Skip to main content

lisette_syntax/program/
resolution.rs

1use crate::ast::Expression;
2use crate::types::Symbol;
3use crate::types::Type;
4
5pub fn resolved_definition(expression: &Expression) -> Option<&str> {
6    match expression.unwrap_parens() {
7        Expression::Identifier { resolution, .. } => resolution.definition(),
8        Expression::DotAccess { resolution, .. } => resolution.definition(),
9        _ => None,
10    }
11}
12
13#[derive(Debug, Clone, Copy)]
14pub enum ChannelOperation<'a> {
15    Receive {
16        channel: &'a Expression,
17    },
18    Send {
19        channel: &'a Expression,
20        value: &'a Expression,
21    },
22}
23
24impl<'a> ChannelOperation<'a> {
25    pub fn channel(self) -> &'a Expression {
26        match self {
27            Self::Receive { channel } | Self::Send { channel, .. } => channel,
28        }
29    }
30
31    pub fn value(self) -> Option<&'a Expression> {
32        match self {
33            Self::Receive { .. } => None,
34            Self::Send { value, .. } => Some(value),
35        }
36    }
37}
38
39pub fn channel_operation(expression: &Expression) -> Option<ChannelOperation<'_>> {
40    let Expression::Call {
41        expression: callee,
42        args,
43        ..
44    } = expression
45    else {
46        return None;
47    };
48
49    let (channel, method, operands): (&Expression, &str, &[Expression]) = match callee.as_ref() {
50        Expression::DotAccess {
51            expression: channel,
52            member,
53            ..
54        } => (channel, member, args),
55        Expression::Identifier { value, .. } if has_channel_ufcs_prefix(value) => {
56            let (channel, operands) = args.split_first()?;
57            (channel, value.rsplit('.').next()?, operands)
58        }
59        _ => return None,
60    };
61
62    match (method, operands) {
63        ("receive", []) => Some(ChannelOperation::Receive { channel }),
64        ("send", [value]) => Some(ChannelOperation::Send { channel, value }),
65        _ => None,
66    }
67}
68
69fn has_channel_ufcs_prefix(identifier: &str) -> bool {
70    let Some((prefix, _)) = identifier.rsplit_once('.') else {
71        return false;
72    };
73    matches!(
74        prefix.rsplit('.').next(),
75        Some("Channel" | "Sender" | "Receiver")
76    )
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum ReceiverCoercion {
81    /// Insert `&` to convert `T` to `Ref<T>`
82    AutoAddress,
83    /// Insert `*` to convert `Ref<T>` to `T`
84    AutoDeref,
85}
86
87/// What a dot access resolved to during type checking.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum DotAccessKind {
90    /// Named struct field access
91    StructField { is_exported: bool },
92    /// Tuple struct field access (e.g., `point.0` on `struct Point(int, int)`).
93    /// `is_newtype` is true when the struct has exactly 1 field and no generics,
94    /// meaning access should emit a type cast rather than `.F0`.
95    TupleStructField { is_newtype: bool },
96    /// Tuple element access (e.g., `t.0`, `t.1`)
97    TupleElement,
98    /// Module member access (e.g., `mod.func`)
99    ModuleMember,
100    /// ADT enum variant constructor (e.g., `makeColorRed[T]()`)
101    EnumVariant,
102    /// Instance method (has `self` receiver)
103    InstanceMethod { is_exported: bool },
104    /// Instance method used as a first-class value (not called).
105    /// E.g., `Point.area` used as a callback. The emitter needs to know
106    /// whether the receiver is a pointer to emit Go method expression syntax.
107    InstanceMethodValue {
108        is_exported: bool,
109        is_pointer_receiver: bool,
110    },
111    /// Static method (no `self` receiver)
112    StaticMethod { is_exported: bool },
113}
114
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub enum DotAccessResolution {
117    Unresolved,
118    StructField {
119        is_exported: bool,
120    },
121    TupleStructField {
122        is_newtype: bool,
123    },
124    TupleElement,
125    ModuleMember {
126        definition: Option<Symbol>,
127    },
128    EnumVariant {
129        definition: Symbol,
130    },
131    InstanceMethod {
132        is_exported: bool,
133        receiver_coercion: Option<ReceiverCoercion>,
134        definition: Option<Symbol>,
135    },
136    InstanceMethodValue {
137        is_exported: bool,
138        is_pointer_receiver: bool,
139        definition: Option<Symbol>,
140    },
141    StaticMethod {
142        is_exported: bool,
143        definition: Symbol,
144    },
145}
146
147impl DotAccessResolution {
148    pub fn kind(&self) -> Option<DotAccessKind> {
149        Some(match self {
150            Self::Unresolved => return None,
151            Self::StructField { is_exported } => DotAccessKind::StructField {
152                is_exported: *is_exported,
153            },
154            Self::TupleStructField { is_newtype } => DotAccessKind::TupleStructField {
155                is_newtype: *is_newtype,
156            },
157            Self::TupleElement => DotAccessKind::TupleElement,
158            Self::ModuleMember { .. } => DotAccessKind::ModuleMember,
159            Self::EnumVariant { .. } => DotAccessKind::EnumVariant,
160            Self::InstanceMethod { is_exported, .. } => DotAccessKind::InstanceMethod {
161                is_exported: *is_exported,
162            },
163            Self::InstanceMethodValue {
164                is_exported,
165                is_pointer_receiver,
166                ..
167            } => DotAccessKind::InstanceMethodValue {
168                is_exported: *is_exported,
169                is_pointer_receiver: *is_pointer_receiver,
170            },
171            Self::StaticMethod { is_exported, .. } => DotAccessKind::StaticMethod {
172                is_exported: *is_exported,
173            },
174        })
175    }
176
177    pub fn receiver_coercion(&self) -> Option<ReceiverCoercion> {
178        match self {
179            Self::InstanceMethod {
180                receiver_coercion, ..
181            } => *receiver_coercion,
182            _ => None,
183        }
184    }
185
186    pub fn definition(&self) -> Option<&str> {
187        match self {
188            Self::ModuleMember { definition }
189            | Self::InstanceMethod { definition, .. }
190            | Self::InstanceMethodValue { definition, .. } => {
191                definition.as_ref().map(Symbol::as_str)
192            }
193            Self::EnumVariant { definition } | Self::StaticMethod { definition, .. } => {
194                Some(definition)
195            }
196            Self::Unresolved
197            | Self::StructField { .. }
198            | Self::TupleStructField { .. }
199            | Self::TupleElement => None,
200        }
201    }
202}
203
204/// What kind of native built-in type (Slice, Map, Channel, etc.) a call targets.
205/// Defined here so semantics can classify calls without depending on
206/// emit-specific types. The emitter maps this to its internal `NativeGoType`.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum NativeTypeKind {
209    Slice,
210    EnumeratedSlice,
211    Map,
212    Channel,
213    Sender,
214    Receiver,
215    String,
216    Array,
217}
218
219impl NativeTypeKind {
220    pub fn from_type(ty: &Type) -> Option<Self> {
221        let resolved = ty.strip_refs();
222        // Skip module namespaces and Go-imported types: their leaf name can
223        // collide with a native type (e.g. `Slice`), but they are not native.
224        if resolved.as_import_namespace().is_some() {
225            return None;
226        }
227        if let Type::Nominal { ref id, .. } = resolved
228            && id.as_str().starts_with("go:")
229        {
230            return None;
231        }
232        let name = resolved.get_name()?;
233        Self::from_name(name)
234    }
235
236    pub fn from_constructor_path(path: &str) -> Option<Self> {
237        match path {
238            "Channel.new" | "Channel.buffered" => Some(Self::Channel),
239            "Map.new" => Some(Self::Map),
240            "Slice.new" | "Slice.make" => Some(Self::Slice),
241            _ => None,
242        }
243    }
244
245    pub fn is_constructor_method(name: &str) -> bool {
246        matches!(name, "new" | "buffered" | "make")
247    }
248
249    pub fn from_name(name: &str) -> Option<Self> {
250        match name {
251            "Slice" => Some(Self::Slice),
252            "EnumeratedSlice" => Some(Self::EnumeratedSlice),
253            "Map" => Some(Self::Map),
254            "Channel" => Some(Self::Channel),
255            "Sender" => Some(Self::Sender),
256            "Receiver" => Some(Self::Receiver),
257            "string" => Some(Self::String),
258            "Array" => Some(Self::Array),
259            _ => None,
260        }
261    }
262}
263
264/// What a call expression resolved to during type checking.
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub enum CallKind {
267    /// The call has not reached semantic classification yet.
268    Unresolved,
269    /// Regular function or method call
270    Regular,
271    /// Tuple struct constructor (e.g., `Point(1, 2)`)
272    TupleStructConstructor,
273    /// Type assertion (`assert_type`)
274    AssertType,
275    /// UFCS method call: `receiver.method()` where method is a free function
276    UfcsMethod,
277    /// Native type constructor (e.g., `Channel.new`, `Map.new`, `Slice.new`)
278    NativeConstructor(NativeTypeKind),
279    /// Native type instance method via dot access (e.g., `slice.append(x)`)
280    NativeMethod(NativeTypeKind),
281    /// Native type method via identifier (e.g., `Slice.contains(s, x)`)
282    NativeMethodIdentifier(NativeTypeKind),
283    /// Receiver method in UFCS syntax: `Type.method(receiver, args)`
284    ReceiverMethodUfcs { is_public: bool },
285}