Skip to main content

lisette_syntax/program/
resolution.rs

1use crate::ast::Expression;
2use crate::types::Symbol;
3use crate::types::{CompoundKind, SimpleKind, 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    /// Package member access (e.g., `mod.func`)
99    PackageMember,
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        declaring_type: Option<Symbol>,
121    },
122    TupleStructField {
123        is_newtype: bool,
124    },
125    TupleElement,
126    PackageMember {
127        definition: Option<Symbol>,
128    },
129    EnumVariant {
130        definition: Symbol,
131    },
132    InstanceMethod {
133        is_exported: bool,
134        receiver_coercion: Option<ReceiverCoercion>,
135        definition: Option<Symbol>,
136    },
137    InstanceMethodValue {
138        is_exported: bool,
139        is_pointer_receiver: bool,
140        definition: Option<Symbol>,
141    },
142    StaticMethod {
143        is_exported: bool,
144        definition: Symbol,
145    },
146}
147
148impl DotAccessResolution {
149    pub fn kind(&self) -> Option<DotAccessKind> {
150        Some(match self {
151            Self::Unresolved => return None,
152            Self::StructField { is_exported, .. } => DotAccessKind::StructField {
153                is_exported: *is_exported,
154            },
155            Self::TupleStructField { is_newtype } => DotAccessKind::TupleStructField {
156                is_newtype: *is_newtype,
157            },
158            Self::TupleElement => DotAccessKind::TupleElement,
159            Self::PackageMember { .. } => DotAccessKind::PackageMember,
160            Self::EnumVariant { .. } => DotAccessKind::EnumVariant,
161            Self::InstanceMethod { is_exported, .. } => DotAccessKind::InstanceMethod {
162                is_exported: *is_exported,
163            },
164            Self::InstanceMethodValue {
165                is_exported,
166                is_pointer_receiver,
167                ..
168            } => DotAccessKind::InstanceMethodValue {
169                is_exported: *is_exported,
170                is_pointer_receiver: *is_pointer_receiver,
171            },
172            Self::StaticMethod { is_exported, .. } => DotAccessKind::StaticMethod {
173                is_exported: *is_exported,
174            },
175        })
176    }
177
178    pub fn declaring_type(&self) -> Option<&Symbol> {
179        match self {
180            Self::StructField { declaring_type, .. } => declaring_type.as_ref(),
181            _ => None,
182        }
183    }
184
185    pub fn receiver_coercion(&self) -> Option<ReceiverCoercion> {
186        match self {
187            Self::InstanceMethod {
188                receiver_coercion, ..
189            } => *receiver_coercion,
190            _ => None,
191        }
192    }
193
194    pub fn definition(&self) -> Option<&str> {
195        match self {
196            Self::PackageMember { definition }
197            | Self::InstanceMethod { definition, .. }
198            | Self::InstanceMethodValue { definition, .. } => {
199                definition.as_ref().map(Symbol::as_str)
200            }
201            Self::EnumVariant { definition } | Self::StaticMethod { definition, .. } => {
202                Some(definition)
203            }
204            Self::Unresolved
205            | Self::StructField { .. }
206            | Self::TupleStructField { .. }
207            | Self::TupleElement => None,
208        }
209    }
210}
211
212/// What kind of native built-in type (Slice, Map, Channel, etc.) a call targets.
213/// Defined here so semantics can classify calls without depending on
214/// emit-specific types. The emitter maps this to its internal `NativeGoType`.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub enum NativeTypeKind {
217    Slice,
218    EnumeratedSlice,
219    Map,
220    Channel,
221    Sender,
222    Receiver,
223    String,
224    Array,
225}
226
227impl NativeTypeKind {
228    pub fn from_type(ty: &Type) -> Option<Self> {
229        Some(match ty.strip_refs() {
230            Type::Compound { kind, .. } => match kind {
231                CompoundKind::Slice => Self::Slice,
232                CompoundKind::EnumeratedSlice => Self::EnumeratedSlice,
233                CompoundKind::Map => Self::Map,
234                CompoundKind::Channel => Self::Channel,
235                CompoundKind::Sender => Self::Sender,
236                CompoundKind::Receiver => Self::Receiver,
237                CompoundKind::Ref | CompoundKind::VarArgs => return None,
238            },
239            Type::Simple(SimpleKind::String) => Self::String,
240            Type::Array { .. } => Self::Array,
241            _ => return None,
242        })
243    }
244
245    pub fn from_constructor_path(path: &str) -> Option<Self> {
246        match path {
247            "Channel.new" | "Channel.buffered" => Some(Self::Channel),
248            "Map.new" => Some(Self::Map),
249            "Slice.new" | "Slice.make" => Some(Self::Slice),
250            "Array.new" | "Array.from" => Some(Self::Array),
251            _ => None,
252        }
253    }
254
255    pub fn is_constructor_method(name: &str) -> bool {
256        matches!(name, "new" | "buffered" | "make")
257    }
258
259    pub fn from_name(name: &str) -> Option<Self> {
260        match name {
261            "Slice" => Some(Self::Slice),
262            "EnumeratedSlice" => Some(Self::EnumeratedSlice),
263            "Map" => Some(Self::Map),
264            "Channel" => Some(Self::Channel),
265            "Sender" => Some(Self::Sender),
266            "Receiver" => Some(Self::Receiver),
267            "string" => Some(Self::String),
268            "Array" => Some(Self::Array),
269            _ => None,
270        }
271    }
272}
273
274/// What a call expression resolved to during type checking.
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276pub enum CallKind {
277    /// The call has not reached semantic classification yet.
278    Unresolved,
279    /// Regular function or method call
280    Regular,
281    /// Tuple struct constructor (e.g., `Point(1, 2)`)
282    TupleStructConstructor,
283    /// Type assertion (`assert_type`)
284    AssertType,
285    /// Zero value of a type (`zero`)
286    Zero,
287    /// UFCS method call: `receiver.method()` where method is a free function
288    UfcsMethod,
289    /// Native type constructor (e.g., `Channel.new`, `Map.new`, `Slice.new`)
290    NativeConstructor(NativeTypeKind),
291    /// Native type instance method via dot access (e.g., `slice.append(x)`)
292    NativeMethod(NativeTypeKind),
293    /// Native type method via identifier (e.g., `Slice.contains(s, x)`)
294    NativeMethodIdentifier(NativeTypeKind),
295    /// Receiver method in UFCS syntax: `Type.method(receiver, args)`
296    ReceiverMethodUfcs { is_public: bool },
297}