Skip to main content

nash_can/
interface.rs

1use bumpalo::Bump;
2use nash_ast::{
3    Alias as CanAlias, Annotation, Associativity, Binop as CanBinop, Ctor as CanCtor, CtorOpts,
4    Decls, Def, Export, Exports, Module as CanModule, ModuleName, Precedence, Type as CanType,
5    Union as CanUnion,
6};
7use nash_region::Located;
8
9/// An exported value with its type, mirroring Elm's `I.Interface` values
10/// map (`Map Name Can.Annotation`). Every entry comes from the type
11/// solver, so interfaces can only be produced for solved modules.
12#[derive(Clone, Copy, Debug)]
13pub struct InterfaceValue<'a> {
14    pub name: &'a str,
15    pub annotation: &'a Annotation<'a>,
16}
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum UnionVisibility {
20    Open,
21    Closed,
22    Private,
23}
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum AliasVisibility {
27    Public,
28    Private,
29}
30
31#[derive(Clone, Copy, Debug)]
32pub struct Interface<'a> {
33    pub impls: &'a [crate::environment::ImplInfo<'a>],
34    pub traits: &'a [InterfaceTrait<'a>],
35    pub home: ModuleName<'a>,
36    pub values: &'a [InterfaceValue<'a>],
37    pub aliases: &'a [InterfaceAlias<'a>],
38    pub unions: &'a [InterfaceUnion<'a>],
39    pub binops: &'a [InterfaceBinop<'a>],
40}
41
42#[derive(Clone, Copy, Debug)]
43pub struct InterfaceTrait<'a> {
44    pub name: &'a str,
45    pub parameters: &'a [&'a str],
46    pub kinds: &'a [&'a nash_ast::Kind<'a>],
47    pub supers: &'a [nash_ast::Pred<'a>],
48    pub methods: &'a [InterfaceMethod<'a>],
49    /// Private metadata remains available to check exported schemes.
50    pub exported: bool,
51}
52
53#[derive(Clone, Copy, Debug)]
54pub struct InterfaceMethod<'a> {
55    pub name: &'a str,
56    pub annotation: &'a Annotation<'a>,
57    pub has_default: bool,
58}
59
60#[derive(Clone, Copy, Debug)]
61pub struct InterfaceUnion<'a> {
62    pub kind: &'a nash_ast::Kind<'a>,
63    pub context: &'a [nash_ast::Pred<'a>],
64    pub name: &'a str,
65    pub parameters: &'a [&'a str],
66    pub ctors: &'a [&'a CanCtor<'a>],
67    pub alternatives: u16,
68    pub options: CtorOpts,
69    pub visibility: UnionVisibility,
70}
71
72#[derive(Clone, Copy, Debug)]
73pub struct InterfaceAlias<'a> {
74    pub kind: &'a nash_ast::Kind<'a>,
75    pub context: &'a [nash_ast::Pred<'a>],
76    pub name: &'a str,
77    pub parameters: &'a [&'a str],
78    pub typ: &'a Located<CanType<'a>>,
79    pub visibility: AliasVisibility,
80}
81
82/// Mirrors Elm's `I.Binop op annotation associativity precedence`: the
83/// annotation is the underlying function's solved scheme or the trait
84/// method's checked scheme. The function retains its defining module even
85/// when another module declares the operator.
86#[derive(Clone, Copy, Debug)]
87pub struct InterfaceBinop<'a> {
88    pub symbol: &'a str,
89    pub annotation: &'a Annotation<'a>,
90    pub associativity: Associativity,
91    pub precedence: Precedence,
92    pub function: nash_ast::QualifiedName<'a>,
93}
94
95/// Type annotations for every top-level value of a module, as produced by
96/// the type solver (Elm's `Map Name Can.Annotation`).
97pub type Annotations<'a> = std::collections::BTreeMap<&'a str, &'a Annotation<'a>>;
98
99/// Mirrors Elm's `I.fromModule home canModule annotations`. Like Elm's
100/// partial `annotations ! name` lookup, a top-level value or operator
101/// function missing from `annotations` is a bug in the caller: interfaces
102/// exist only for fully solved modules.
103pub fn from_module<'a>(
104    bump: &'a Bump,
105    module: &CanModule<'a>,
106    annotations: &Annotations<'a>,
107) -> Interface<'a> {
108    Interface {
109        impls: bump.alloc_slice_fill_iter(
110            module
111                .impls
112                .iter()
113                .map(|i| crate::impls::info(bump, module.name, i)),
114        ),
115        traits: bump.alloc_slice_fill_iter(module.traits.iter().map(|t| InterfaceTrait {
116            name: t.value.name.value,
117            parameters: t.value.parameters,
118            kinds: t.value.kinds,
119            supers: t.value.supers,
120            methods: bump.alloc_slice_fill_iter(t.value.methods.iter().map(|m| InterfaceMethod {
121                name: m.name.value,
122                annotation: m.annotation,
123                has_default: m.default.is_some(),
124            })),
125            exported: match module.exports {
126                Exports::Everything(_) => true,
127                Exports::Explicit(exports) => {
128                    exports.iter().any(
129                        |e| matches!(e.value, Export::Trait(name) if name == t.value.name.value),
130                    )
131                }
132            },
133        })),
134        home: module.name,
135        values: extract_values(bump, &module.exports, module.decls, annotations),
136        unions: extract_unions(bump, &module.exports, module.unions),
137        aliases: extract_aliases(bump, &module.exports, module.aliases),
138        binops: extract_binops(bump, &module.exports, module.binops, annotations),
139    }
140}
141
142impl<'a> InterfaceUnion<'a> {
143    pub fn to_public(&self) -> Option<InterfaceUnion<'a>> {
144        match self.visibility {
145            UnionVisibility::Open => Some(*self),
146            UnionVisibility::Closed => Some(InterfaceUnion {
147                ctors: &[],
148                alternatives: 0,
149                ..*self
150            }),
151            UnionVisibility::Private => None,
152        }
153    }
154}
155
156impl<'a> InterfaceAlias<'a> {
157    pub fn to_public(&self) -> Option<InterfaceAlias<'a>> {
158        match self.visibility {
159            AliasVisibility::Public => Some(*self),
160            AliasVisibility::Private => None,
161        }
162    }
163}
164
165/// Mirrors Elm's `restrict exports annotations`: every top-level value's
166/// annotation, filtered by the export list.
167fn extract_values<'a>(
168    bump: &'a Bump,
169    exports: &Exports<'a>,
170    decls: &Decls<'a>,
171    annotations: &Annotations<'a>,
172) -> &'a [InterfaceValue<'a>] {
173    let mut names = Vec::new();
174    collect_decl_names(decls, &mut names);
175
176    let to_value = |name: &'a str| InterfaceValue {
177        name,
178        annotation: annotations
179            .get(name)
180            .copied()
181            .expect("solver annotations cover every top-level value"),
182    };
183
184    match exports {
185        Exports::Everything(_) => bump.alloc_slice_fill_iter(names.into_iter().map(to_value)),
186        Exports::Explicit(exports) => bump.alloc_slice_fill_iter(
187            names
188                .into_iter()
189                .filter(|name| is_exported_value(exports, name))
190                .map(to_value)
191                .collect::<Vec<_>>(),
192        ),
193    }
194}
195
196fn collect_decl_names<'a>(decls: &Decls<'a>, names: &mut Vec<&'a str>) {
197    match decls {
198        Decls::Declare { definition, next } => {
199            names.push(def_name(definition));
200            collect_decl_names(next, names);
201        }
202        Decls::DeclareRec {
203            definition,
204            following,
205            next,
206        } => {
207            names.push(def_name(definition));
208            for def in *following {
209                names.push(def_name(def));
210            }
211            collect_decl_names(next, names);
212        }
213        Decls::Empty => {}
214    }
215}
216
217fn def_name<'a>(def: &Def<'a>) -> &'a str {
218    match def {
219        Def::Def { name, .. } | Def::TypedDef { name, .. } => name.value,
220    }
221}
222
223fn is_exported_value(exports: &[&Located<Export<'_>>], name: &str) -> bool {
224    exports
225        .iter()
226        .any(|export| matches!(&export.value, Export::Value(n) if *n == name))
227}
228
229fn extract_unions<'a>(
230    bump: &'a Bump,
231    exports: &Exports<'a>,
232    unions: &'a [&'a Located<CanUnion<'a>>],
233) -> &'a [InterfaceUnion<'a>] {
234    bump.alloc_slice_fill_iter(unions.iter().map(|union| {
235        let name = union.value.name.value;
236        InterfaceUnion {
237            name,
238            kind: union.value.kind,
239            context: union.value.context,
240            parameters: union.value.parameters,
241            ctors: union.value.ctors,
242            alternatives: union.value.alternatives,
243            options: union.value.options,
244            visibility: union_visibility(exports, name),
245        }
246    }))
247}
248
249fn extract_aliases<'a>(
250    bump: &'a Bump,
251    exports: &Exports<'a>,
252    aliases: &'a [&'a Located<CanAlias<'a>>],
253) -> &'a [InterfaceAlias<'a>] {
254    bump.alloc_slice_fill_iter(aliases.iter().map(|alias| {
255        let name = alias.value.name.value;
256        InterfaceAlias {
257            name,
258            kind: alias.value.kind,
259            context: alias.value.context,
260            parameters: alias.value.parameters,
261            typ: alias.value.typ,
262            visibility: alias_visibility(exports, name),
263        }
264    }))
265}
266
267fn extract_binops<'a>(
268    bump: &'a Bump,
269    exports: &Exports<'a>,
270    binops: &'a [&'a Located<CanBinop<'a>>],
271    annotations: &Annotations<'a>,
272) -> &'a [InterfaceBinop<'a>] {
273    bump.alloc_slice_fill_iter(
274        binops
275            .iter()
276            .filter_map(|binop| {
277                if is_exported_binop(exports, binop.value.symbol) {
278                    let annotation = binop.value.annotation.unwrap_or_else(|| {
279                        annotations
280                            .get(binop.value.function.name)
281                            .copied()
282                            .expect("solver annotations cover every local operator function")
283                    });
284                    Some(InterfaceBinop {
285                        symbol: binop.value.symbol,
286                        annotation,
287                        associativity: binop.value.associativity,
288                        precedence: binop.value.precedence,
289                        function: binop.value.function,
290                    })
291                } else {
292                    None
293                }
294            })
295            .collect::<Vec<_>>(),
296    )
297}
298
299fn union_visibility(exports: &Exports<'_>, name: &str) -> UnionVisibility {
300    match exports {
301        Exports::Everything(_) => UnionVisibility::Open,
302        Exports::Explicit(exports) => {
303            for export in exports.iter() {
304                match &export.value {
305                    Export::UnionOpen(n) if *n == name => return UnionVisibility::Open,
306                    Export::UnionClosed(n) if *n == name => return UnionVisibility::Closed,
307                    _ => {}
308                }
309            }
310            UnionVisibility::Private
311        }
312    }
313}
314
315fn alias_visibility(exports: &Exports<'_>, name: &str) -> AliasVisibility {
316    match exports {
317        Exports::Everything(_) => AliasVisibility::Public,
318        Exports::Explicit(exports) => {
319            if exports
320                .iter()
321                .any(|e| matches!(&e.value, Export::Alias(n) if *n == name))
322            {
323                AliasVisibility::Public
324            } else {
325                AliasVisibility::Private
326            }
327        }
328    }
329}
330
331fn is_exported_binop(exports: &Exports<'_>, symbol: &str) -> bool {
332    match exports {
333        Exports::Everything(_) => true,
334        Exports::Explicit(exports) => exports
335            .iter()
336            .any(|export| matches!(&export.value, Export::Binop(s) if *s == symbol)),
337    }
338}