Skip to main content

lisette_syntax/program/
definition.rs

1use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
2
3use ecow::EcoString;
4
5use crate::ast::{Annotation, EnumVariant, Generic, Literal, Span, StructFields};
6use crate::types::{
7    FunctionParameter, Type, build_substitution_map, substitute, type_args_match_params,
8};
9
10#[derive(Debug, Clone)]
11pub struct Definition {
12    pub visibility: Visibility,
13    pub ty: Type,
14    pub name_span: Option<Span>,
15    pub doc: Option<String>,
16    pub body: DefinitionBody,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub enum TypeAttribute {
22    Display,
23    ClosedDomain,
24    AnonStruct,
25    /// Go struct that looks flat but hides an embed bindgen could not emit, so it
26    /// cannot be soundly embedded.
27    HiddenEmbed,
28    Serialized,
29    ZeroSafe,
30    HiddenFields,
31}
32
33pub type Attributes = HashSet<TypeAttribute>;
34
35#[derive(Debug, Clone)]
36pub enum ValueKind {
37    Runtime,
38    ConstantDeclaration,
39    Constant(Literal),
40}
41
42#[derive(Debug, Clone)]
43pub enum DefinitionBody {
44    TypeAlias {
45        generics: Vec<Generic>,
46        alias: AliasKind,
47        methods: MethodSignatures,
48        attributes: Attributes,
49    },
50    Enum {
51        generics: Vec<Generic>,
52        variants: Vec<EnumVariant>,
53        methods: MethodSignatures,
54        attributes: Attributes,
55    },
56    Struct {
57        generics: Vec<Generic>,
58        fields: StructFields,
59        methods: MethodSignatures,
60        attributes: Attributes,
61    },
62    Interface {
63        definition: Interface,
64    },
65    Value {
66        kind: ValueKind,
67        allowed_lints: Vec<String>,
68        go_hints: Vec<String>,
69        go_name: Option<String>,
70        /// Go's full type-parameter list for a `#[go(collapsed_type_params)]`
71        /// function, in declaration order, each entry as a Lisette type (e.g.
72        /// `"Slice<E>, E"`). Lets emit rebuild Go's type arguments when the
73        /// collapsed Lisette list cannot be projected onto Go's positionally.
74        go_type_param_recipe: Option<String>,
75    },
76}
77
78#[derive(Debug, Clone)]
79pub enum AliasKind {
80    Opaque(Annotation),
81    Transparent {
82        annotation: Annotation,
83        target: Type,
84    },
85}
86
87impl AliasKind {
88    pub fn annotation(&self) -> &Annotation {
89        match self {
90            Self::Opaque(annotation) | Self::Transparent { annotation, .. } => annotation,
91        }
92    }
93}
94
95impl DefinitionBody {
96    pub fn generics(&self) -> Option<&[Generic]> {
97        match self {
98            Self::TypeAlias { generics, .. }
99            | Self::Enum { generics, .. }
100            | Self::Struct { generics, .. } => Some(generics),
101            Self::Interface { definition } => Some(&definition.generics),
102            Self::Value { .. } => None,
103        }
104    }
105
106    pub fn generics_mut(&mut self) -> Option<&mut [Generic]> {
107        match self {
108            Self::TypeAlias { generics, .. }
109            | Self::Enum { generics, .. }
110            | Self::Struct { generics, .. } => Some(generics),
111            Self::Interface { definition } => Some(&mut definition.generics),
112            Self::Value { .. } => None,
113        }
114    }
115}
116
117impl Definition {
118    /// A newtype is a single-field, non-generic tuple struct. Relevant
119    /// because Go compiles newtypes to named scalar types, so `.0` is a cast
120    /// rather than a field access, it cannot be assigned to, and taking
121    /// its address is invalid.
122    pub fn is_newtype(&self) -> bool {
123        matches!(
124            &self.body,
125            DefinitionBody::Struct {
126                fields: StructFields::Tuple(fields),
127                generics,
128                ..
129            } if fields.len() == 1 && generics.is_empty()
130        )
131    }
132
133    pub fn is_pointer_backed_newtype<'d, F>(&self, lookup: F) -> bool
134    where
135        F: Fn(&str) -> Option<&'d Definition>,
136    {
137        self.is_newtype()
138            && matches!(
139                &self.body,
140                DefinitionBody::Struct {
141                    fields: StructFields::Tuple(fields),
142                    ..
143                } if crate::types::peel_alias(&fields[0].ty, lookup).is_ref()
144            )
145    }
146
147    pub fn instantiate_alias_target(&self, params: &[Type]) -> Option<Type> {
148        let DefinitionBody::TypeAlias {
149            generics,
150            alias: AliasKind::Transparent { target, .. },
151            ..
152        } = &self.body
153        else {
154            return None;
155        };
156        Some(substitute(
157            target,
158            &build_substitution_map(generics, params),
159        ))
160    }
161
162    pub fn instantiate_underlying(&self, params: &[Type]) -> Option<Type> {
163        if let Some(target) = self.instantiate_alias_target(params) {
164            return Some(target);
165        }
166        match &self.body {
167            DefinitionBody::Struct {
168                fields: StructFields::Tuple(fields),
169                ..
170            } if self.is_newtype() => Some(fields[0].ty.clone()),
171            _ => None,
172        }
173    }
174
175    /// Returns the callable type of a tuple struct constructor.
176    ///
177    /// The constructor is derived from the struct's resolved fields and type
178    /// rather than stored separately, so it cannot become stale when either
179    /// source changes.
180    pub fn constructor_type(&self) -> Option<Type> {
181        let DefinitionBody::Struct {
182            fields: StructFields::Tuple(fields),
183            generics,
184            ..
185        } = &self.body
186        else {
187            return None;
188        };
189
190        let return_type = self.ty.unwrap_forall().clone();
191        let function = Type::function(
192            fields
193                .iter()
194                .map(|field| FunctionParameter::new(field.ty.clone(), false))
195                .collect(),
196            Default::default(),
197            return_type.into(),
198        );
199
200        Some(if generics.is_empty() {
201            function
202        } else {
203            Type::Forall {
204                vars: generics
205                    .iter()
206                    .map(|generic| generic.name.clone())
207                    .collect(),
208                body: Box::new(function),
209            }
210        })
211    }
212
213    pub fn is_transparent_type_alias(&self) -> bool {
214        matches!(
215            self.body,
216            DefinitionBody::TypeAlias {
217                alias: AliasKind::Transparent { .. },
218                ..
219            }
220        )
221    }
222
223    pub fn allowed_lints(&self) -> &[String] {
224        match &self.body {
225            DefinitionBody::Value { allowed_lints, .. } => allowed_lints,
226            _ => &[],
227        }
228    }
229
230    pub fn go_hints(&self) -> &[String] {
231        match &self.body {
232            DefinitionBody::Value { go_hints, .. } => go_hints,
233            _ => &[],
234        }
235    }
236
237    pub fn go_name(&self) -> Option<&str> {
238        match &self.body {
239            DefinitionBody::Value { go_name, .. } => go_name.as_deref(),
240            _ => None,
241        }
242    }
243
244    pub fn go_type_param_recipe(&self) -> Option<&str> {
245        match &self.body {
246            DefinitionBody::Value {
247                go_type_param_recipe,
248                ..
249            } => go_type_param_recipe.as_deref(),
250            _ => None,
251        }
252    }
253
254    pub fn const_value(&self) -> Option<&Literal> {
255        match &self.body {
256            DefinitionBody::Value {
257                kind: ValueKind::Constant(value),
258                ..
259            } => Some(value),
260            _ => None,
261        }
262    }
263
264    pub fn is_const(&self) -> bool {
265        matches!(
266            self.body,
267            DefinitionBody::Value {
268                kind: ValueKind::ConstantDeclaration | ValueKind::Constant(_),
269                ..
270            }
271        )
272    }
273
274    pub fn methods_mut(&mut self) -> Option<&mut MethodSignatures> {
275        match &mut self.body {
276            DefinitionBody::Struct { methods, .. } => Some(methods),
277            DefinitionBody::TypeAlias { methods, .. } => Some(methods),
278            DefinitionBody::Enum { methods, .. } => Some(methods),
279            _ => None,
280        }
281    }
282
283    pub fn methods(&self) -> Option<&MethodSignatures> {
284        match &self.body {
285            DefinitionBody::Struct { methods, .. }
286            | DefinitionBody::TypeAlias { methods, .. }
287            | DefinitionBody::Enum { methods, .. } => Some(methods),
288            DefinitionBody::Interface { .. } | DefinitionBody::Value { .. } => None,
289        }
290    }
291
292    pub fn is_ufcs_method(&self, method: &str) -> bool {
293        let (methods, base_generics_count) = match &self.body {
294            DefinitionBody::Struct {
295                methods, generics, ..
296            }
297            | DefinitionBody::Enum {
298                methods, generics, ..
299            }
300            | DefinitionBody::TypeAlias {
301                methods, generics, ..
302            } => (methods, generics.len()),
303            DefinitionBody::Interface { .. } | DefinitionBody::Value { .. } => return false,
304        };
305        methods
306            .get(method)
307            .is_some_and(|method_ty| is_ufcs_method_type(method_ty, base_generics_count))
308    }
309
310    fn attributes(&self) -> Option<&Attributes> {
311        match &self.body {
312            DefinitionBody::Struct { attributes, .. }
313            | DefinitionBody::Enum { attributes, .. }
314            | DefinitionBody::TypeAlias { attributes, .. } => Some(attributes),
315            _ => None,
316        }
317    }
318
319    pub fn is_display(&self) -> bool {
320        self.attributes()
321            .is_some_and(|a| a.contains(&TypeAttribute::Display))
322    }
323
324    pub fn is_zero_safe(&self) -> bool {
325        self.attributes()
326            .is_some_and(|a| a.contains(&TypeAttribute::ZeroSafe))
327    }
328
329    pub fn has_hidden_fields(&self) -> bool {
330        self.attributes()
331            .is_some_and(|a| a.contains(&TypeAttribute::HiddenFields))
332    }
333
334    pub fn is_closed_domain(&self) -> bool {
335        self.attributes()
336            .is_some_and(|a| a.contains(&TypeAttribute::ClosedDomain))
337    }
338
339    pub fn is_serialized(&self) -> bool {
340        self.attributes()
341            .is_some_and(|a| a.contains(&TypeAttribute::Serialized))
342    }
343
344    pub fn is_anon_struct(&self) -> bool {
345        self.attributes()
346            .is_some_and(|a| a.contains(&TypeAttribute::AnonStruct))
347    }
348
349    pub fn has_hidden_embed(&self) -> bool {
350        self.attributes()
351            .is_some_and(|a| a.contains(&TypeAttribute::HiddenEmbed))
352    }
353
354    pub fn is_type_definition(&self) -> bool {
355        matches!(
356            self.body,
357            DefinitionBody::Struct { .. }
358                | DefinitionBody::Enum { .. }
359                | DefinitionBody::TypeAlias { .. }
360        )
361    }
362
363    pub fn is_type_alias(&self) -> bool {
364        matches!(self.body, DefinitionBody::TypeAlias { .. })
365    }
366
367    pub fn is_value(&self, qualified_name: &str) -> bool {
368        matches!(self.body, DefinitionBody::Value { .. })
369            && self.ty.unwrap_forall().get_qualified_id() != Some(qualified_name)
370    }
371}
372
373fn is_ufcs_method_type(method_ty: &Type, base_generics_count: usize) -> bool {
374    let Type::Forall { vars, body } = method_ty else {
375        return base_generics_count > 0;
376    };
377
378    if vars.len() > base_generics_count {
379        return true;
380    }
381
382    if let Type::Function(function) = body.as_ref()
383        && let Some(receiver) = function.params.first()
384        && let Type::Nominal {
385            params: receiver_params,
386            ..
387        } = receiver.ty.strip_refs()
388        && !type_args_match_params(&receiver_params, vars.iter())
389    {
390        return true;
391    }
392
393    false
394}
395
396pub type MethodSignatures = HashMap<EcoString, Type>;
397
398#[derive(Debug, Clone, PartialEq)]
399#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
400pub enum Visibility {
401    Public,
402    Private,
403    Local,
404}
405
406impl Visibility {
407    pub fn is_public(&self) -> bool {
408        matches!(self, Visibility::Public)
409    }
410}
411
412#[derive(Debug, Clone, PartialEq)]
413pub struct Interface {
414    pub generics: Vec<Generic>,
415    pub parents: Vec<Type>,
416    pub methods: HashMap<EcoString, Type>,
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422    use crate::types::Symbol;
423
424    fn generic(name: &str) -> Generic {
425        Generic::new(name, vec![], Span::dummy())
426    }
427
428    fn receiver(params: Vec<Type>) -> Type {
429        Type::Nominal {
430            id: Symbol::from_raw("m.Box"),
431            params,
432        }
433    }
434
435    fn method(vars: &[&str], receiver: Type) -> Type {
436        let function = Type::function(
437            vec![FunctionParameter::new(receiver, false)],
438            Default::default(),
439            Box::new(Type::unit()),
440        );
441        Type::Forall {
442            vars: vars.iter().map(|name| EcoString::from(*name)).collect(),
443            body: Box::new(function),
444        }
445    }
446
447    fn definition(method_ty: Type) -> Definition {
448        Definition {
449            visibility: Visibility::Public,
450            ty: receiver(vec![Type::Parameter("T".into())]),
451            name_span: None,
452            doc: None,
453            body: DefinitionBody::Struct {
454                generics: vec![generic("T")],
455                fields: StructFields::Record(vec![]),
456                methods: HashMap::from_iter([("map".into(), method_ty)]),
457                attributes: Attributes::default(),
458            },
459        }
460    }
461
462    #[test]
463    fn full_generic_receiver_is_a_selector_method() {
464        let definition = definition(method(&["T"], receiver(vec![Type::Parameter("T".into())])));
465
466        assert!(!definition.is_ufcs_method("map"));
467    }
468
469    #[test]
470    fn extra_method_generic_requires_ufcs() {
471        let definition = definition(method(
472            &["T", "U"],
473            receiver(vec![Type::Parameter("T".into())]),
474        ));
475
476        assert!(definition.is_ufcs_method("map"));
477    }
478
479    #[test]
480    fn specialized_receiver_requires_ufcs() {
481        let definition = definition(method(&["T"], receiver(vec![Type::int()])));
482
483        assert!(definition.is_ufcs_method("map"));
484    }
485}