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