Skip to main content

meta_language/translation/surface/
externals.rs

1//! Existing external and import records, re-exported through the surface API.
2use super::{Span, Type};
3use serde::{Deserialize, Serialize};
4
5/// A named import of items of another module of the crate,
6/// `import { a, b as c } from './m.mjs'`.
7#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
8pub struct SImport {
9    /// The imported module's path inside the crate.
10    pub module: Vec<String>,
11    pub names: Vec<SImportName>,
12    #[serde(default, skip_serializing_if = "Option::is_none")]
13    pub span: Option<Span>,
14}
15
16/// An imported item: its name in its module and the name the import binds.
17#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
18pub struct SImportName {
19    pub imported: String,
20    pub local: String,
21}
22
23/// Another item of the module, which a program calls or reads by name
24/// without declaring it.
25///
26/// A function comes with its signature, and a constant with its type and
27/// whether a literal gives its value.
28#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(tag = "k")]
30pub enum External {
31    #[serde(rename = "fn")]
32    Function {
33        name: String,
34        params: Vec<ExternalParam>,
35        ret: Type,
36    },
37    #[serde(rename = "const")]
38    Constant {
39        name: String,
40        #[serde(rename = "type")]
41        ty: Type,
42        literal: bool,
43    },
44}
45
46impl External {
47    /// The name the program calls or reads the item by.
48    #[must_use]
49    pub fn name(&self) -> &str {
50        match self {
51            Self::Function { name, .. } | Self::Constant { name, .. } => name,
52        }
53    }
54
55    /// The types of a function's parameters and its result, or a constant's type.
56    #[must_use]
57    pub fn signature(&self) -> (Vec<&Type>, &Type) {
58        match self {
59            Self::Function { params, ret, .. } => {
60                (params.iter().map(|param| &param.ty).collect(), ret)
61            }
62            Self::Constant { ty, .. } => (Vec::new(), ty),
63        }
64    }
65
66    /// The item under the name `name`.
67    #[must_use]
68    pub fn renamed(&self, name: &str) -> Self {
69        let mut renamed = self.clone();
70        match &mut renamed {
71            Self::Function { name: own, .. } | Self::Constant { name: own, .. } => {
72                name.clone_into(own);
73            }
74        }
75        renamed
76    }
77}
78
79/// A parameter of another item's function.
80#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81pub struct ExternalParam {
82    pub name: String,
83    #[serde(rename = "type")]
84    pub ty: Type,
85}