Skip to main content

lisette_syntax/program/
definition.rs

1use rustc_hash::FxHashMap as HashMap;
2
3use ecow::EcoString;
4
5use crate::ast::{
6    Annotation, EnumVariant, Generic, Literal, Span, StructFieldDefinition, StructKind,
7};
8use crate::types::Type;
9
10#[derive(Debug, Clone)]
11pub struct Definition {
12    pub visibility: Visibility,
13    pub ty: Type,
14    pub name: Option<EcoString>,
15    pub name_span: Option<Span>,
16    pub doc: Option<String>,
17    pub body: DefinitionBody,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub enum TypeAttribute {
23    Display,
24    ClosedDomain,
25    AnonStruct,
26    /// Go struct that looks flat but hides an embed bindgen could not emit, so it
27    /// cannot be soundly embedded.
28    HiddenEmbed,
29    Serialized,
30}
31
32pub type Attributes = HashMap<TypeAttribute, ()>;
33
34#[derive(Debug, Clone)]
35pub enum DefinitionBody {
36    TypeAlias {
37        generics: Vec<Generic>,
38        annotation: Annotation,
39        methods: MethodSignatures,
40        attributes: Attributes,
41    },
42    Enum {
43        generics: Vec<Generic>,
44        variants: Vec<EnumVariant>,
45        methods: MethodSignatures,
46        attributes: Attributes,
47    },
48    Struct {
49        generics: Vec<Generic>,
50        fields: Vec<StructFieldDefinition>,
51        kind: StructKind,
52        methods: MethodSignatures,
53        constructor: Option<Type>,
54        attributes: Attributes,
55    },
56    Interface {
57        definition: Interface,
58    },
59    Value {
60        allowed_lints: Vec<String>,
61        go_hints: Vec<String>,
62        go_name: Option<String>,
63        /// Go's full type-parameter list for a `#[go(collapsed_type_params)]`
64        /// function, in declaration order, each entry as a Lisette type (e.g.
65        /// `"Slice<E>, E"`). Lets emit rebuild Go's type arguments when the
66        /// collapsed Lisette list cannot be projected onto Go's positionally.
67        go_type_param_recipe: Option<String>,
68        /// The known literal value when this definition is a case-eligible
69        /// constant (usable as a Go `case` and as a const-pattern target).
70        /// `None` for variables, functions, and non-literal constants.
71        const_value: Option<Literal>,
72    },
73}
74
75impl Definition {
76    pub fn ty(&self) -> &Type {
77        &self.ty
78    }
79
80    pub fn visibility(&self) -> &Visibility {
81        &self.visibility
82    }
83
84    pub fn name_span(&self) -> Option<Span> {
85        self.name_span
86    }
87
88    pub fn doc(&self) -> Option<&String> {
89        self.doc.as_ref()
90    }
91
92    /// A newtype is a single-field, non-generic tuple struct. Relevant
93    /// because Go compiles newtypes to named scalar types, so `.0` is a cast
94    /// rather than a field access — it cannot be assigned to, and taking
95    /// its address is invalid.
96    pub fn is_newtype(&self) -> bool {
97        matches!(
98            &self.body,
99            DefinitionBody::Struct {
100                kind: StructKind::Tuple,
101                fields,
102                generics,
103                ..
104            } if fields.len() == 1 && generics.is_empty()
105        )
106    }
107
108    pub fn is_pointer_backed_newtype<F>(&self, is_alias: F) -> bool
109    where
110        F: Fn(&str) -> bool,
111    {
112        self.is_newtype()
113            && matches!(
114                &self.body,
115                DefinitionBody::Struct { fields, .. }
116                    if crate::types::peel_alias(&fields[0].ty, is_alias).is_ref()
117            )
118    }
119
120    pub fn allowed_lints(&self) -> &[String] {
121        match &self.body {
122            DefinitionBody::Value { allowed_lints, .. } => allowed_lints,
123            _ => &[],
124        }
125    }
126
127    pub fn go_hints(&self) -> &[String] {
128        match &self.body {
129            DefinitionBody::Value { go_hints, .. } => go_hints,
130            _ => &[],
131        }
132    }
133
134    pub fn go_name(&self) -> Option<&str> {
135        match &self.body {
136            DefinitionBody::Value { go_name, .. } => go_name.as_deref(),
137            _ => None,
138        }
139    }
140
141    pub fn go_type_param_recipe(&self) -> Option<&str> {
142        match &self.body {
143            DefinitionBody::Value {
144                go_type_param_recipe,
145                ..
146            } => go_type_param_recipe.as_deref(),
147            _ => None,
148        }
149    }
150
151    pub fn const_value(&self) -> Option<&Literal> {
152        match &self.body {
153            DefinitionBody::Value { const_value, .. } => const_value.as_ref(),
154            _ => None,
155        }
156    }
157
158    pub fn methods_mut(&mut self) -> Option<&mut MethodSignatures> {
159        match &mut self.body {
160            DefinitionBody::Struct { methods, .. } => Some(methods),
161            DefinitionBody::TypeAlias { methods, .. } => Some(methods),
162            DefinitionBody::Enum { methods, .. } => Some(methods),
163            _ => None,
164        }
165    }
166
167    pub fn attributes(&self) -> Option<&Attributes> {
168        match &self.body {
169            DefinitionBody::Struct { attributes, .. }
170            | DefinitionBody::Enum { attributes, .. }
171            | DefinitionBody::TypeAlias { attributes, .. } => Some(attributes),
172            _ => None,
173        }
174    }
175
176    pub fn is_display(&self) -> bool {
177        self.attributes()
178            .is_some_and(|a| a.contains_key(&TypeAttribute::Display))
179    }
180
181    pub fn is_closed_domain(&self) -> bool {
182        self.attributes()
183            .is_some_and(|a| a.contains_key(&TypeAttribute::ClosedDomain))
184    }
185
186    pub fn is_serialized(&self) -> bool {
187        self.attributes()
188            .is_some_and(|a| a.contains_key(&TypeAttribute::Serialized))
189    }
190
191    pub fn is_anon_struct(&self) -> bool {
192        self.attributes()
193            .is_some_and(|a| a.contains_key(&TypeAttribute::AnonStruct))
194    }
195
196    pub fn has_hidden_embed(&self) -> bool {
197        self.attributes()
198            .is_some_and(|a| a.contains_key(&TypeAttribute::HiddenEmbed))
199    }
200
201    pub fn is_type_definition(&self) -> bool {
202        matches!(
203            self.body,
204            DefinitionBody::Struct { .. }
205                | DefinitionBody::Enum { .. }
206                | DefinitionBody::TypeAlias { .. }
207        )
208    }
209
210    pub fn is_type_alias(&self) -> bool {
211        matches!(self.body, DefinitionBody::TypeAlias { .. })
212    }
213
214    pub fn is_value(&self, qualified_name: &str) -> bool {
215        matches!(self.body, DefinitionBody::Value { .. })
216            && self.ty.unwrap_forall().get_qualified_id() != Some(qualified_name)
217    }
218}
219
220pub type MethodSignatures = HashMap<EcoString, Type>;
221
222#[derive(Debug, Clone, PartialEq)]
223pub enum Visibility {
224    Public,
225    Private,
226    Local,
227}
228
229impl Visibility {
230    pub fn is_public(&self) -> bool {
231        matches!(self, Visibility::Public)
232    }
233}
234
235#[derive(Debug, Clone, PartialEq)]
236pub struct Interface {
237    pub name: EcoString,
238    pub generics: Vec<Generic>,
239    pub parents: Vec<Type>,
240    pub methods: HashMap<EcoString, Type>,
241}