Skip to main content

lisette_syntax/program/
definition.rs

1use crate::collections::SharedMap;
2use crate::constant;
3use crate::program::PRELUDE_PACKAGE_ID;
4use rustc_hash::{FxHashMap, FxHashSet};
5use std::fmt;
6use std::ops::Deref;
7use std::slice;
8
9use ecow::EcoString;
10
11use crate::ast::{
12    Annotation, EnumVariant, Generic, Literal, Span, StructFieldDefinition, StructFields,
13    Visibility,
14};
15use crate::types::{
16    FunctionParameter, Symbol, Type, TypeKind, TypeList, TypeScheme, build_substitution_map,
17    substitute, type_args_match_params, unqualified_name,
18};
19
20#[derive(Debug, Clone, PartialEq)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub struct Definition {
23    pub visibility: Visibility,
24    pub ty: TypeScheme,
25    pub name_span: Option<Span>,
26    pub doc: Option<String>,
27    pub body: DefinitionBody,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32pub enum TypeAttribute {
33    Display,
34    ClosedDomain,
35    AnonStruct,
36    /// Go struct that looks flat but hides an embed bindgen could not emit, so it
37    /// cannot be soundly embedded.
38    HiddenEmbed,
39    Serialized,
40    ZeroSafe,
41    /// Go type whose zero value is documented broken, so it must come from
42    /// its constructor.
43    ZeroUnsafe,
44    HiddenFields,
45    /// Go type that Go cannot compare for a reason its rendering hides.
46    Incomparable,
47    /// Go interface that Go allows only as a type constraint.
48    Constraint,
49}
50
51impl TypeAttribute {
52    const fn mask(self) -> u16 {
53        match self {
54            Self::Display => 1 << 0,
55            Self::ClosedDomain => 1 << 1,
56            Self::AnonStruct => 1 << 2,
57            Self::HiddenEmbed => 1 << 3,
58            Self::Serialized => 1 << 4,
59            Self::ZeroSafe => 1 << 5,
60            Self::ZeroUnsafe => 1 << 6,
61            Self::HiddenFields => 1 << 7,
62            Self::Incomparable => 1 << 8,
63            Self::Constraint => 1 << 9,
64        }
65    }
66}
67
68#[derive(Debug, Clone, Default, PartialEq, Eq)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
70pub struct Attributes {
71    flags: u16,
72    /// Type parameter positions whose arguments Go needs comparable to compare the type.
73    comparable_arguments: Vec<usize>,
74}
75
76impl Attributes {
77    pub fn insert(&mut self, attribute: TypeAttribute) -> bool {
78        let mask = attribute.mask();
79        let was_absent = self.flags & mask == 0;
80        self.flags |= mask;
81        was_absent
82    }
83
84    pub fn contains(&self, attribute: &TypeAttribute) -> bool {
85        self.flags & attribute.mask() != 0
86    }
87
88    pub fn require_comparable_argument(&mut self, position: usize) {
89        if !self.comparable_arguments.contains(&position) {
90            self.comparable_arguments.push(position);
91        }
92    }
93
94    pub fn requires_comparable_argument(&self, position: usize) -> bool {
95        self.comparable_arguments.contains(&position)
96    }
97}
98
99#[derive(Debug, Clone, PartialEq)]
100#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
101pub enum ValueKind {
102    Runtime,
103    Variable,
104    ConstantDeclaration,
105    Constant(ConstantValue),
106}
107
108#[derive(Debug, Clone, PartialEq)]
109#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
110pub enum ConstantValue {
111    Integer { value: u64, text: Option<String> },
112    Float { value: f64, text: Option<String> },
113    Boolean(bool),
114    String(String),
115    Char(String),
116    Evaluated(constant::Value),
117}
118
119impl ConstantValue {
120    pub fn value(&self) -> Option<constant::Value> {
121        match self {
122            Self::Evaluated(value) => Some(value.clone()),
123            literal => constant::literal_value(&literal.to_literal()?),
124        }
125    }
126
127    pub fn to_literal(&self) -> Option<Literal> {
128        Some(match self {
129            Self::Integer { value, text } => Literal::Integer {
130                value: *value,
131                text: text.clone(),
132            },
133            Self::Float { value, text } => Literal::Float {
134                value: *value,
135                text: text.clone(),
136            },
137            Self::Boolean(value) => Literal::Boolean(*value),
138            Self::String(value) => Literal::String {
139                value: value.clone(),
140                raw: false,
141            },
142            Self::Char(value) => Literal::Char(value.clone()),
143            Self::Evaluated(_) => return None,
144        })
145    }
146}
147
148#[derive(Debug, Clone, PartialEq)]
149#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
150pub enum DefinitionBody {
151    TypeAlias {
152        generics: Vec<Generic>,
153        alias: AliasKind,
154        methods: Methods,
155        attributes: Attributes,
156    },
157    Enum {
158        generics: Vec<Generic>,
159        variants: EnumVariants,
160        methods: Methods,
161        attributes: Attributes,
162        /// Index into `variants`, if the enum marks one.
163        default_variant: Option<usize>,
164    },
165    Struct {
166        generics: Vec<Generic>,
167        fields: StructFields,
168        methods: Methods,
169        attributes: Attributes,
170    },
171    Interface {
172        definition: Interface,
173    },
174    Value {
175        kind: ValueKind,
176        allowed_lints: Vec<String>,
177        go_hints: Vec<super::GoHint>,
178        go_name: Option<String>,
179        /// Go's full type-parameter list for a `#[go(collapsed_type_params)]`
180        /// function, in declaration order, each entry as a Lisette type (e.g.
181        /// `"Slice<E>, E"`). Lets emit rebuild Go's type arguments when the
182        /// collapsed Lisette list cannot be projected onto Go's positionally.
183        go_type_param_recipe: Option<Vec<super::GoTypeRecipe>>,
184        go_type_terms: Vec<super::GoTypeTerms>,
185        superseded_by: Option<String>,
186        /// The impl receiver of a static method in terms of the impl's generics.
187        impl_receiver: Option<Type>,
188    },
189}
190
191#[derive(Debug, Clone, PartialEq)]
192#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
193pub enum AliasKind {
194    Opaque(Annotation),
195    Transparent {
196        annotation: Annotation,
197        target: Type,
198    },
199}
200
201impl AliasKind {
202    pub fn annotation(&self) -> &Annotation {
203        match self {
204            Self::Opaque(annotation) | Self::Transparent { annotation, .. } => annotation,
205        }
206    }
207}
208
209impl DefinitionBody {
210    pub fn value(kind: ValueKind) -> Self {
211        Self::Value {
212            kind,
213            allowed_lints: vec![],
214            go_hints: vec![],
215            go_name: None,
216            go_type_param_recipe: None,
217            go_type_terms: vec![],
218            superseded_by: None,
219            impl_receiver: None,
220        }
221    }
222
223    pub fn generics(&self) -> Option<&[Generic]> {
224        match self {
225            Self::TypeAlias { generics, .. }
226            | Self::Enum { generics, .. }
227            | Self::Struct { generics, .. } => Some(generics),
228            Self::Interface { definition } => Some(&definition.generics),
229            Self::Value { .. } => None,
230        }
231    }
232}
233
234impl Definition {
235    /// A newtype is a single-field, non-generic tuple struct. Relevant
236    /// because Go compiles newtypes to named scalar types, so `.0` is a cast
237    /// rather than a field access, it cannot be assigned to, and taking
238    /// its address is invalid.
239    pub fn is_newtype(&self) -> bool {
240        matches!(
241            &self.body,
242            DefinitionBody::Struct {
243                fields: StructFields::Tuple(fields),
244                generics,
245                ..
246            } if fields.len() == 1 && generics.is_empty()
247        )
248    }
249
250    pub fn newtype_field(&self) -> Option<&Type> {
251        match &self.body {
252            DefinitionBody::Struct {
253                fields: StructFields::Tuple(fields),
254                ..
255            } if self.is_newtype() => Some(&fields[0].ty),
256            _ => None,
257        }
258    }
259
260    pub fn is_pointer_backed_newtype(&self) -> bool {
261        self.is_newtype()
262            && matches!(
263                &self.body,
264                DefinitionBody::Struct {
265                    fields: StructFields::Tuple(fields),
266                    ..
267                } if fields[0].ty.is_ref()
268            )
269    }
270
271    pub fn alias_target(&self) -> Option<&Type> {
272        match &self.body {
273            DefinitionBody::TypeAlias {
274                alias: AliasKind::Transparent { target, .. },
275                ..
276            } => Some(target),
277            _ => None,
278        }
279    }
280
281    pub fn instantiate_alias_target(&self, params: &[Type], writable: bool) -> Option<Type> {
282        let DefinitionBody::TypeAlias {
283            generics,
284            alias: AliasKind::Transparent { target, .. },
285            ..
286        } = &self.body
287        else {
288            return None;
289        };
290        let map = build_substitution_map(generics, params);
291        if writable {
292            Some(substitute(&target.clone().make_writable(), &map))
293        } else {
294            Some(substitute(target, &map))
295        }
296    }
297
298    pub fn newtype_underlying(&self, writable: bool) -> Option<Type> {
299        match &self.body {
300            DefinitionBody::Struct {
301                fields: StructFields::Tuple(fields),
302                ..
303            } if self.is_newtype() => Some(if writable {
304                fields[0].ty.clone()
305            } else {
306                fields[0].ty.demoted()
307            }),
308            _ => None,
309        }
310    }
311
312    /// Returns the callable type of a tuple struct constructor.
313    ///
314    /// The constructor is derived from the struct's resolved fields and type
315    /// rather than stored separately, so it cannot become stale when either
316    /// source changes.
317    pub fn constructor_type(&self) -> Option<TypeScheme> {
318        let DefinitionBody::Struct {
319            fields: StructFields::Tuple(fields),
320            generics,
321            ..
322        } = &self.body
323        else {
324            return None;
325        };
326
327        let function = Type::function(
328            fields
329                .iter()
330                .map(|field| FunctionParameter::new(field.ty.clone()))
331                .collect(),
332            Default::default(),
333            self.ty.body.clone().into(),
334        );
335
336        Some(TypeScheme {
337            vars: generics
338                .iter()
339                .map(|generic| generic.name.clone())
340                .collect(),
341            body: function,
342        })
343    }
344
345    pub fn allowed_lints(&self) -> &[String] {
346        match &self.body {
347            DefinitionBody::Value { allowed_lints, .. } => allowed_lints,
348            _ => &[],
349        }
350    }
351
352    pub fn go_hints(&self) -> &[super::GoHint] {
353        match &self.body {
354            DefinitionBody::Value { go_hints, .. } => go_hints,
355            _ => &[],
356        }
357    }
358
359    pub fn go_name(&self) -> Option<&str> {
360        match &self.body {
361            DefinitionBody::Value { go_name, .. } => go_name.as_deref(),
362            _ => None,
363        }
364    }
365
366    pub fn go_type_param_recipe(&self) -> Option<&[super::GoTypeRecipe]> {
367        match &self.body {
368            DefinitionBody::Value {
369                go_type_param_recipe,
370                ..
371            } => go_type_param_recipe.as_deref(),
372            _ => None,
373        }
374    }
375
376    pub fn go_type_terms(&self) -> &[super::GoTypeTerms] {
377        match &self.body {
378            DefinitionBody::Value { go_type_terms, .. } => go_type_terms,
379            _ => &[],
380        }
381    }
382
383    pub fn impl_receiver(&self) -> Option<&Type> {
384        match &self.body {
385            DefinitionBody::Value { impl_receiver, .. } => impl_receiver.as_ref(),
386            _ => None,
387        }
388    }
389
390    pub fn superseded_by(&self) -> Option<&str> {
391        match &self.body {
392            DefinitionBody::Value { superseded_by, .. } => superseded_by.as_deref(),
393            _ => None,
394        }
395    }
396
397    pub fn const_value(&self) -> Option<&ConstantValue> {
398        match &self.body {
399            DefinitionBody::Value {
400                kind: ValueKind::Constant(value),
401                ..
402            } => Some(value),
403            _ => None,
404        }
405    }
406
407    pub fn is_const(&self) -> bool {
408        matches!(
409            self.body,
410            DefinitionBody::Value {
411                kind: ValueKind::ConstantDeclaration | ValueKind::Constant(_),
412                ..
413            }
414        )
415    }
416
417    /// A Go var that the bindings type wider than Go, so Go rejects writes and `&`.
418    pub fn is_read_only(&self) -> bool {
419        self.is_variable() && self.go_hints().contains(&super::GoHint::ReadOnly)
420    }
421
422    pub fn is_variable(&self) -> bool {
423        matches!(
424            self.body,
425            DefinitionBody::Value {
426                kind: ValueKind::Variable,
427                ..
428            }
429        )
430    }
431
432    pub fn methods_mut(&mut self) -> Option<&mut Methods> {
433        match &mut self.body {
434            DefinitionBody::Struct { methods, .. } => Some(methods),
435            DefinitionBody::TypeAlias { methods, .. } => Some(methods),
436            DefinitionBody::Enum { methods, .. } => Some(methods),
437            DefinitionBody::Interface { definition } => Some(&mut definition.methods),
438            DefinitionBody::Value { .. } => None,
439        }
440    }
441
442    pub fn methods(&self) -> Option<&Methods> {
443        match &self.body {
444            DefinitionBody::Struct { methods, .. }
445            | DefinitionBody::TypeAlias { methods, .. }
446            | DefinitionBody::Enum { methods, .. } => Some(methods),
447            DefinitionBody::Interface { definition } => Some(&definition.methods),
448            DefinitionBody::Value { .. } => None,
449        }
450    }
451
452    pub fn fields(&self) -> Option<&[StructFieldDefinition]> {
453        match &self.body {
454            DefinitionBody::Struct { fields, .. } => Some(fields.as_slice()),
455            _ => None,
456        }
457    }
458
459    pub fn is_interface(&self) -> bool {
460        matches!(self.body, DefinitionBody::Interface { .. })
461    }
462
463    pub fn is_ufcs_method(&self, method: &str) -> bool {
464        let (methods, base_generics_count) = match &self.body {
465            DefinitionBody::Struct {
466                methods, generics, ..
467            }
468            | DefinitionBody::Enum {
469                methods, generics, ..
470            }
471            | DefinitionBody::TypeAlias {
472                methods, generics, ..
473            } => (methods, generics.len()),
474            DefinitionBody::Interface { .. } | DefinitionBody::Value { .. } => return false,
475        };
476        methods
477            .get(method)
478            .is_some_and(|method| is_ufcs_method_type(&method.ty, base_generics_count))
479    }
480
481    fn attributes(&self) -> Option<&Attributes> {
482        match &self.body {
483            DefinitionBody::Struct { attributes, .. }
484            | DefinitionBody::Enum { attributes, .. }
485            | DefinitionBody::TypeAlias { attributes, .. } => Some(attributes),
486            DefinitionBody::Interface { definition } => Some(&definition.attributes),
487            _ => None,
488        }
489    }
490
491    pub fn is_display(&self) -> bool {
492        self.attributes()
493            .is_some_and(|a| a.contains(&TypeAttribute::Display))
494    }
495
496    pub fn is_zero_safe(&self) -> bool {
497        self.attributes()
498            .is_some_and(|a| a.contains(&TypeAttribute::ZeroSafe))
499    }
500
501    pub fn is_zero_unsafe(&self) -> bool {
502        self.attributes()
503            .is_some_and(|a| a.contains(&TypeAttribute::ZeroUnsafe))
504    }
505
506    pub fn has_hidden_fields(&self) -> bool {
507        self.attributes()
508            .is_some_and(|a| a.contains(&TypeAttribute::HiddenFields))
509    }
510
511    pub fn is_closed_domain(&self) -> bool {
512        self.attributes()
513            .is_some_and(|a| a.contains(&TypeAttribute::ClosedDomain))
514    }
515
516    pub fn is_serialized(&self) -> bool {
517        self.attributes()
518            .is_some_and(|a| a.contains(&TypeAttribute::Serialized))
519    }
520
521    pub fn is_anon_struct(&self) -> bool {
522        self.attributes()
523            .is_some_and(|a| a.contains(&TypeAttribute::AnonStruct))
524    }
525
526    pub fn has_hidden_embed(&self) -> bool {
527        self.attributes()
528            .is_some_and(|a| a.contains(&TypeAttribute::HiddenEmbed))
529    }
530
531    pub fn is_incomparable(&self) -> bool {
532        self.attributes()
533            .is_some_and(|a| a.contains(&TypeAttribute::Incomparable))
534    }
535
536    pub fn requires_comparable_argument(&self, position: usize) -> bool {
537        self.attributes()
538            .is_some_and(|a| a.requires_comparable_argument(position))
539    }
540
541    pub fn is_constraint(&self) -> bool {
542        self.attributes()
543            .is_some_and(|a| a.contains(&TypeAttribute::Constraint))
544    }
545
546    pub fn is_type_definition(&self) -> bool {
547        matches!(
548            self.body,
549            DefinitionBody::Struct { .. }
550                | DefinitionBody::Enum { .. }
551                | DefinitionBody::TypeAlias { .. }
552        )
553    }
554
555    pub fn is_type_alias(&self) -> bool {
556        matches!(self.body, DefinitionBody::TypeAlias { .. })
557    }
558
559    pub fn is_value(&self, qualified_name: &str) -> bool {
560        matches!(self.body, DefinitionBody::Value { .. })
561            && self.ty.body.get_qualified_id() != Some(qualified_name)
562    }
563}
564
565fn is_ufcs_method_type(method_ty: &TypeScheme, base_generics_count: usize) -> bool {
566    let TypeScheme { vars, body } = method_ty;
567    if vars.is_empty() {
568        return base_generics_count > 0;
569    }
570
571    if vars.len() > base_generics_count {
572        return true;
573    }
574
575    if let TypeKind::Function(function) = body.kind()
576        && let Some(receiver) = function.params.first()
577        && let TypeKind::Nominal {
578            params: receiver_params,
579            ..
580        } = receiver.ty.strip_refs().kind()
581        && !type_args_match_params(receiver_params, vars.iter())
582    {
583        return true;
584    }
585
586    false
587}
588
589#[derive(Debug, Clone, Copy, PartialEq, Eq)]
590#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
591pub enum MethodOrigin {
592    Declared,
593    Synthesized,
594}
595
596#[derive(Debug, Clone, PartialEq)]
597#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
598pub struct Method {
599    pub source_name: EcoString,
600    pub ty: TypeScheme,
601    pub visibility: Visibility,
602    pub origin: MethodOrigin,
603    pub name_span: Option<Span>,
604    pub doc: Option<String>,
605    pub allowed_lints: Vec<String>,
606    pub go_hints: Vec<super::GoHint>,
607    pub superseded_by: Option<String>,
608}
609
610impl Method {
611    pub fn with_type(&self, ty: TypeScheme) -> Self {
612        Self { ty, ..self.clone() }
613    }
614
615    fn with_receiver_placeholder(mut self) -> Self {
616        self.ty.body = self.ty.body.with_receiver_placeholder();
617        self
618    }
619}
620
621pub type Methods = SharedMap<EcoString, Method>;
622
623#[derive(Clone)]
624pub struct EnumVariants {
625    variants: Vec<EnumVariant>,
626    indices: FxHashMap<EcoString, usize>,
627}
628
629impl EnumVariants {
630    pub fn by_name(&self, name: &str) -> Option<&EnumVariant> {
631        self.indices.get(name).map(|&index| &self.variants[index])
632    }
633
634    pub fn contains_name(&self, name: &str) -> bool {
635        self.indices.contains_key(name)
636    }
637}
638
639impl From<Vec<EnumVariant>> for EnumVariants {
640    fn from(variants: Vec<EnumVariant>) -> Self {
641        let mut indices = FxHashMap::default();
642        for (index, variant) in variants.iter().enumerate() {
643            indices.entry(variant.name.clone()).or_insert(index);
644        }
645        Self { variants, indices }
646    }
647}
648
649impl Deref for EnumVariants {
650    type Target = [EnumVariant];
651
652    fn deref(&self) -> &Self::Target {
653        &self.variants
654    }
655}
656
657impl<'a> IntoIterator for &'a EnumVariants {
658    type Item = &'a EnumVariant;
659    type IntoIter = slice::Iter<'a, EnumVariant>;
660
661    fn into_iter(self) -> Self::IntoIter {
662        self.variants.iter()
663    }
664}
665
666impl<'a> IntoIterator for &'a mut EnumVariants {
667    type Item = &'a mut EnumVariant;
668    type IntoIter = slice::IterMut<'a, EnumVariant>;
669
670    fn into_iter(self) -> Self::IntoIter {
671        self.variants.iter_mut()
672    }
673}
674
675impl PartialEq for EnumVariants {
676    fn eq(&self, other: &Self) -> bool {
677        self.variants == other.variants
678    }
679}
680
681impl fmt::Debug for EnumVariants {
682    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
683        self.variants.fmt(f)
684    }
685}
686
687#[cfg(feature = "serde")]
688impl serde::Serialize for EnumVariants {
689    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
690        self.variants.serialize(serializer)
691    }
692}
693
694#[cfg(feature = "serde")]
695impl<'de> serde::Deserialize<'de> for EnumVariants {
696    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
697        Vec::<EnumVariant>::deserialize(deserializer).map(Self::from)
698    }
699}
700
701#[derive(Debug, Clone, PartialEq)]
702pub struct InterfaceInstance {
703    pub ty: Type,
704    pub parent_of: Option<Symbol>,
705}
706
707/// Instantiate an interface and its complete parent hierarchy exactly once.
708/// Package-qualified structural identity prevents same-named interfaces from
709/// collapsing, while the active path guard terminates malformed cycles.
710pub fn interface_instances<'d, F>(interface_ty: &Type, lookup: F) -> Vec<InterfaceInstance>
711where
712    F: Copy + Fn(&str) -> Option<&'d Definition>,
713{
714    fn collect<'d, F>(
715        interface_ty: &Type,
716        parent_of: Option<&Symbol>,
717        lookup: F,
718        visited: &mut FxHashSet<Type>,
719        visiting: &mut FxHashSet<Symbol>,
720        instances: &mut Vec<InterfaceInstance>,
721    ) where
722        F: Copy + Fn(&str) -> Option<&'d Definition>,
723    {
724        let resolved = interface_ty.without_spelling();
725        let TypeKind::Nominal { id, params, .. } = resolved.kind() else {
726            return;
727        };
728        if !visited.insert(resolved.clone()) || !visiting.insert(id.clone()) {
729            return;
730        }
731        let Some(Definition {
732            body: DefinitionBody::Interface { definition },
733            ..
734        }) = lookup(id)
735        else {
736            visiting.remove(id);
737            return;
738        };
739        let map = build_substitution_map(&definition.generics, params);
740        instances.push(InterfaceInstance {
741            ty: resolved.clone(),
742            parent_of: parent_of.cloned(),
743        });
744        for parent in &definition.parents {
745            collect(
746                &substitute(parent, &map),
747                Some(id),
748                lookup,
749                visited,
750                visiting,
751                instances,
752            );
753        }
754        visiting.remove(id);
755    }
756
757    let mut instances = Vec::new();
758    collect(
759        interface_ty,
760        None,
761        lookup,
762        &mut FxHashSet::default(),
763        &mut FxHashSet::default(),
764        &mut instances,
765    );
766    instances
767}
768
769pub struct ConstructorField<'d> {
770    pub name: &'d EcoString,
771    pub name_span: Span,
772    pub declared_ty: &'d Type,
773    pub ty: Type,
774}
775
776pub struct ConstructorFields<'d> {
777    pub definition: &'d Definition,
778    pub generics: &'d [Generic],
779    pub type_args: Vec<Type>,
780    pub fields: Vec<ConstructorField<'d>>,
781}
782
783pub fn constructor_fields<'d, F>(
784    owner: &str,
785    variant: Option<&str>,
786    ty: &Type,
787    lookup: F,
788) -> Option<ConstructorFields<'d>>
789where
790    F: Fn(&str) -> Option<&'d Definition>,
791{
792    let definition = lookup(owner)?;
793    let type_args = match ty.without_spelling().into_kind() {
794        TypeKind::Nominal { params, .. } => params,
795        _ => TypeList::new(),
796    };
797    let (generics, declared): (&'d [Generic], Vec<(&'d EcoString, Span, &'d Type)>) =
798        match (&definition.body, variant) {
799            (
800                DefinitionBody::Struct {
801                    generics, fields, ..
802                },
803                _,
804            ) => (
805                generics,
806                fields
807                    .iter()
808                    .map(|field| (&field.name, field.name_span, &field.ty))
809                    .collect(),
810            ),
811            (
812                DefinitionBody::Enum {
813                    generics, variants, ..
814                },
815                Some(variant),
816            ) => {
817                let variant = variants.by_name(unqualified_name(variant))?;
818                (
819                    generics,
820                    variant
821                        .fields
822                        .iter()
823                        .map(|field| (&field.name, field.name_span, &field.ty))
824                        .collect(),
825                )
826            }
827            _ => return None,
828        };
829    let map = build_substitution_map(generics, &type_args);
830    let fields = declared
831        .into_iter()
832        .map(|(name, name_span, declared_ty)| ConstructorField {
833            name,
834            name_span,
835            declared_ty,
836            ty: substitute(declared_ty, &map),
837        })
838        .collect();
839    Some(ConstructorFields {
840        definition,
841        generics,
842        type_args: type_args.to_vec(),
843        fields,
844    })
845}
846
847#[derive(Debug, Clone, PartialEq)]
848pub struct InterfaceRequirement {
849    pub declaring_interface: Symbol,
850    pub parent_of: Option<Symbol>,
851    pub name: EcoString,
852    /// The method as declared. Its type determines the generic declaration's
853    /// physical ABI even when substitution reveals a special logical type.
854    pub method: Method,
855    /// The logical signature after applying all interface type arguments.
856    pub ty: Type,
857}
858
859/// Flatten an interface and its instantiated parents into declaration-tagged
860/// method requirements. Cycles and repeated generic instantiations are handled
861/// here so registration, inference, and emission cannot disagree about the
862/// inherited signatures.
863pub fn interface_requirements<'d, F>(interface_ty: &Type, lookup: F) -> Vec<InterfaceRequirement>
864where
865    F: Copy + Fn(&str) -> Option<&'d Definition>,
866{
867    let mut requirements = Vec::new();
868    for instance in interface_instances(interface_ty, lookup) {
869        let TypeKind::Nominal { id, params, .. } = instance.ty.kind() else {
870            continue;
871        };
872        let Some(Definition {
873            body: DefinitionBody::Interface { definition },
874            ..
875        }) = lookup(id)
876        else {
877            continue;
878        };
879        let map = build_substitution_map(&definition.generics, params);
880        requirements.extend(
881            definition
882                .methods
883                .iter()
884                .map(|(name, method)| InterfaceRequirement {
885                    declaring_interface: id.clone(),
886                    parent_of: instance.parent_of.clone(),
887                    name: name.clone(),
888                    method: method.clone(),
889                    ty: substitute(&method.ty.body, &map),
890                }),
891        );
892    }
893    requirements
894}
895
896/// Resolve the complete method set for a type, including inherited and alias methods.
897pub fn methods_for_type<'d, F>(
898    ty: &Type,
899    trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
900    lookup: F,
901) -> Methods
902where
903    F: Copy + Fn(&str) -> Option<&'d Definition>,
904{
905    fn collect<'d, F>(
906        ty: &Type,
907        trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
908        lookup: F,
909        visited: &mut FxHashSet<String>,
910    ) -> Methods
911    where
912        F: Copy + Fn(&str) -> Option<&'d Definition>,
913    {
914        let stripped = ty.strip_refs();
915        let Some(qualified_name) = method_lookup_key(&stripped) else {
916            return Methods::default();
917        };
918
919        if !visited.insert(qualified_name.as_str().to_string()) {
920            return Methods::default();
921        }
922
923        if lookup(&qualified_name)
924            .is_some_and(|definition| matches!(definition.body, DefinitionBody::Interface { .. }))
925        {
926            return interface_requirements(&stripped, lookup)
927                .into_iter()
928                .map(|requirement| {
929                    (
930                        requirement.name,
931                        requirement
932                            .method
933                            .with_type(TypeScheme::mono(requirement.ty))
934                            .with_receiver_placeholder(),
935                    )
936                })
937                .collect();
938        }
939
940        if let Some(bounds) = trait_bounds.get(&qualified_name) {
941            return bounds
942                .iter()
943                .flat_map(|bound| collect(bound, trait_bounds, lookup, visited))
944                .collect();
945        }
946
947        lookup(&qualified_name)
948            .and_then(Definition::methods)
949            .cloned()
950            .unwrap_or_default()
951    }
952
953    collect(ty, trait_bounds, lookup, &mut FxHashSet::default())
954}
955
956/// Whether an interface or any of its parents declares a method.
957pub fn interface_declares_any_method<'d, F>(interface_ty: &Type, lookup: F) -> bool
958where
959    F: Copy + Fn(&str) -> Option<&'d Definition>,
960{
961    interface_instances(interface_ty, lookup)
962        .into_iter()
963        .any(|instance| {
964            let TypeKind::Nominal { id, .. } = instance.ty.kind() else {
965                return false;
966            };
967            matches!(
968                lookup(id),
969                Some(Definition {
970                    body: DefinitionBody::Interface { definition },
971                    ..
972                }) if !definition.methods.is_empty()
973            )
974        })
975}
976
977pub fn method_for_type<'d, F>(
978    ty: &Type,
979    trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
980    lookup: F,
981    wanted: &str,
982) -> Option<Method>
983where
984    F: Copy + Fn(&str) -> Option<&'d Definition>,
985{
986    fn collect<'d, F>(
987        ty: &Type,
988        trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
989        lookup: F,
990        visited: &mut FxHashSet<Symbol>,
991        wanted: &str,
992    ) -> Option<Method>
993    where
994        F: Copy + Fn(&str) -> Option<&'d Definition>,
995    {
996        let stripped = ty.strip_refs();
997        let qualified_name = method_lookup_key(&stripped)?;
998
999        if !visited.insert(qualified_name.clone()) {
1000            return None;
1001        }
1002
1003        if lookup(&qualified_name)
1004            .is_some_and(|definition| matches!(definition.body, DefinitionBody::Interface { .. }))
1005        {
1006            return interface_requirements(&stripped, lookup)
1007                .into_iter()
1008                .rfind(|requirement| requirement.name == wanted)
1009                .map(|requirement| {
1010                    requirement
1011                        .method
1012                        .with_type(TypeScheme::mono(requirement.ty))
1013                        .with_receiver_placeholder()
1014                });
1015        }
1016
1017        // The shared visited set makes bound order matter.
1018        if let Some(bounds) = trait_bounds.get(&qualified_name) {
1019            let mut found = None;
1020            for bound in bounds {
1021                if let Some(method) = collect(bound, trait_bounds, lookup, visited, wanted) {
1022                    found = Some(method);
1023                }
1024            }
1025            return found;
1026        }
1027
1028        lookup(&qualified_name)
1029            .and_then(Definition::methods)
1030            .and_then(|methods| methods.get(wanted))
1031            .cloned()
1032    }
1033
1034    collect(ty, trait_bounds, lookup, &mut FxHashSet::default(), wanted)
1035}
1036
1037pub fn type_has_any_method<'d, F>(ty: &Type, lookup: F) -> bool
1038where
1039    F: Copy + Fn(&str) -> Option<&'d Definition>,
1040{
1041    fn collect<'d, F>(ty: &Type, lookup: F, visited: &mut FxHashSet<Symbol>) -> bool
1042    where
1043        F: Copy + Fn(&str) -> Option<&'d Definition>,
1044    {
1045        let stripped = ty.strip_refs();
1046        let Some(qualified_name) = method_lookup_key(&stripped) else {
1047            return false;
1048        };
1049
1050        if !visited.insert(qualified_name.clone()) {
1051            return false;
1052        }
1053
1054        if lookup(&qualified_name)
1055            .is_some_and(|definition| matches!(definition.body, DefinitionBody::Interface { .. }))
1056        {
1057            return interface_declares_any_method(&stripped, lookup);
1058        }
1059
1060        if lookup(&qualified_name)
1061            .and_then(Definition::methods)
1062            .is_some_and(|methods| !methods.is_empty())
1063        {
1064            return true;
1065        }
1066
1067        false
1068    }
1069
1070    collect(ty, lookup, &mut FxHashSet::default())
1071}
1072
1073pub fn method_lookup_key(ty: &Type) -> Option<Symbol> {
1074    match ty.kind() {
1075        TypeKind::Nominal { id, .. } => Some(id.clone()),
1076        TypeKind::Compound { kind, .. } => {
1077            Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, kind.leaf_name()))
1078        }
1079        TypeKind::Simple(kind) => Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, kind.leaf_name())),
1080        TypeKind::Array { .. } => Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, "Array")),
1081        _ => None,
1082    }
1083}
1084
1085#[derive(Debug, Clone, PartialEq)]
1086#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1087pub struct Interface {
1088    pub generics: Vec<Generic>,
1089    pub parents: Vec<Type>,
1090    pub methods: Methods,
1091    pub attributes: Attributes,
1092}
1093
1094#[cfg(test)]
1095mod tests {
1096    use super::*;
1097    use crate::types::Symbol;
1098
1099    #[test]
1100    fn attributes_track_independent_flags() {
1101        let mut attributes = Attributes::default();
1102
1103        attributes.insert(TypeAttribute::Display);
1104        attributes.insert(TypeAttribute::Serialized);
1105
1106        assert_eq!(
1107            [
1108                attributes.contains(&TypeAttribute::Display),
1109                attributes.contains(&TypeAttribute::Serialized),
1110                attributes.contains(&TypeAttribute::HiddenFields),
1111            ],
1112            [true, true, false]
1113        );
1114    }
1115
1116    #[test]
1117    fn inserting_an_existing_attribute_reports_it_present() {
1118        let mut attributes = Attributes::default();
1119
1120        assert!(attributes.insert(TypeAttribute::Display));
1121        assert!(!attributes.insert(TypeAttribute::Display));
1122    }
1123
1124    fn generic(name: &str) -> Generic {
1125        Generic::new(name, vec![], Span::dummy())
1126    }
1127
1128    fn receiver(params: Vec<Type>) -> Type {
1129        TypeKind::Nominal {
1130            id: Symbol::from_raw("m.Box"),
1131            params: params.into(),
1132            writable: false,
1133        }
1134        .into()
1135    }
1136
1137    fn method(vars: &[&str], receiver: Type) -> TypeScheme {
1138        TypeScheme {
1139            vars: vars.iter().map(|name| EcoString::from(*name)).collect(),
1140            body: Type::function(
1141                vec![FunctionParameter::new(receiver)],
1142                Default::default(),
1143                Box::new(Type::unit()),
1144            ),
1145        }
1146    }
1147
1148    fn definition(method_ty: TypeScheme) -> Definition {
1149        Definition {
1150            visibility: Visibility::Public,
1151            ty: TypeScheme {
1152                vars: vec!["T".into()],
1153                body: receiver(vec![Type::parameter("T".into())]),
1154            },
1155            name_span: None,
1156            doc: None,
1157            body: DefinitionBody::Struct {
1158                generics: vec![generic("T")],
1159                fields: StructFields::Record(vec![]),
1160                methods: Methods::from_iter([(
1161                    "map".into(),
1162                    Method {
1163                        source_name: "map".into(),
1164                        ty: method_ty,
1165                        visibility: Visibility::Public,
1166                        origin: MethodOrigin::Declared,
1167                        name_span: None,
1168                        doc: None,
1169                        allowed_lints: vec![],
1170                        go_hints: vec![],
1171                        superseded_by: None,
1172                    },
1173                )]),
1174                attributes: Attributes::default(),
1175            },
1176        }
1177    }
1178
1179    #[test]
1180    fn full_generic_receiver_is_a_selector_method() {
1181        let definition = definition(method(&["T"], receiver(vec![Type::parameter("T".into())])));
1182
1183        assert!(!definition.is_ufcs_method("map"));
1184    }
1185
1186    #[test]
1187    fn extra_method_generic_requires_ufcs() {
1188        let definition = definition(method(
1189            &["T", "U"],
1190            receiver(vec![Type::parameter("T".into())]),
1191        ));
1192
1193        assert!(definition.is_ufcs_method("map"));
1194    }
1195
1196    #[test]
1197    fn specialized_receiver_requires_ufcs() {
1198        let definition = definition(method(&["T"], receiver(vec![Type::int()])));
1199
1200        assert!(definition.is_ufcs_method("map"));
1201    }
1202
1203    fn nominal(id: &str) -> Type {
1204        TypeKind::Nominal {
1205            id: Symbol::from_raw(id),
1206            params: TypeList::new(),
1207            writable: false,
1208        }
1209        .into()
1210    }
1211
1212    fn named_method(name: &str, return_type: Type) -> (EcoString, Method) {
1213        let ty = Type::function(
1214            vec![FunctionParameter::new(nominal("m.Receiver"))],
1215            Default::default(),
1216            Box::new(return_type),
1217        );
1218        (
1219            name.into(),
1220            Method {
1221                source_name: name.into(),
1222                ty: TypeScheme::mono(ty),
1223                visibility: Visibility::Public,
1224                origin: MethodOrigin::Declared,
1225                name_span: None,
1226                doc: None,
1227                allowed_lints: vec![],
1228                go_hints: vec![],
1229                superseded_by: None,
1230            },
1231        )
1232    }
1233
1234    fn interface_definition(id: &str, parents: Vec<Type>, methods: Methods) -> Definition {
1235        Definition {
1236            visibility: Visibility::Public,
1237            ty: TypeScheme::mono(nominal(id)),
1238            name_span: None,
1239            doc: None,
1240            body: DefinitionBody::Interface {
1241                definition: Interface {
1242                    generics: vec![],
1243                    parents,
1244                    methods,
1245                    attributes: Attributes::default(),
1246                },
1247            },
1248        }
1249    }
1250
1251    fn table(entries: Vec<(&str, Definition)>) -> FxHashMap<String, Definition> {
1252        entries
1253            .into_iter()
1254            .map(|(id, definition)| (id.to_string(), definition))
1255            .collect()
1256    }
1257
1258    /// The narrow lookup must answer exactly what the whole method set holds.
1259    fn assert_narrow_matches_broad(
1260        table: &FxHashMap<String, Definition>,
1261        trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
1262        ty: &Type,
1263        name: &str,
1264    ) {
1265        let lookup = |id: &str| table.get(id);
1266        let broad = methods_for_type(ty, trait_bounds, lookup)
1267            .get(name)
1268            .cloned();
1269        let narrow = method_for_type(ty, trait_bounds, lookup, name);
1270
1271        assert_eq!(narrow, broad);
1272    }
1273
1274    #[test]
1275    fn a_parent_interface_method_shadows_the_child_declaration() {
1276        let table = table(vec![
1277            (
1278                "m.Child",
1279                interface_definition(
1280                    "m.Child",
1281                    vec![nominal("m.Parent")],
1282                    Methods::from_iter([named_method("run", Type::int())]),
1283                ),
1284            ),
1285            (
1286                "m.Parent",
1287                interface_definition(
1288                    "m.Parent",
1289                    vec![],
1290                    Methods::from_iter([named_method("run", Type::string())]),
1291                ),
1292            ),
1293        ]);
1294
1295        assert_narrow_matches_broad(&table, &FxHashMap::default(), &nominal("m.Child"), "run");
1296    }
1297
1298    #[test]
1299    fn the_last_bound_that_declares_a_method_wins() {
1300        let table = table(vec![
1301            (
1302                "m.First",
1303                interface_definition(
1304                    "m.First",
1305                    vec![],
1306                    Methods::from_iter([named_method("run", Type::int())]),
1307                ),
1308            ),
1309            (
1310                "m.Second",
1311                interface_definition(
1312                    "m.Second",
1313                    vec![],
1314                    Methods::from_iter([named_method("run", Type::string())]),
1315                ),
1316            ),
1317        ]);
1318        let trait_bounds = FxHashMap::from_iter([(
1319            Symbol::from_raw("m.T"),
1320            vec![nominal("m.First"), nominal("m.Second")],
1321        )]);
1322
1323        assert_narrow_matches_broad(&table, &trait_bounds, &nominal("m.T"), "run");
1324    }
1325
1326    fn generic_interface_definition(id: &str, methods: Methods) -> Definition {
1327        Definition {
1328            visibility: Visibility::Public,
1329            ty: TypeScheme::mono(nominal(id)),
1330            name_span: None,
1331            doc: None,
1332            body: DefinitionBody::Interface {
1333                definition: Interface {
1334                    generics: vec![generic("T")],
1335                    parents: vec![],
1336                    methods,
1337                    attributes: Attributes::default(),
1338                },
1339            },
1340        }
1341    }
1342
1343    fn instantiated(id: &str, argument: Type) -> Type {
1344        TypeKind::Nominal {
1345            id: Symbol::from_raw(id),
1346            params: vec![argument].into(),
1347            writable: false,
1348        }
1349        .into()
1350    }
1351
1352    #[test]
1353    fn bounds_that_share_a_nominal_key_agree_with_the_whole_method_set() {
1354        let table = table(vec![(
1355            "m.Boxed",
1356            generic_interface_definition(
1357                "m.Boxed",
1358                Methods::from_iter([named_method("run", Type::parameter("T".into()))]),
1359            ),
1360        )]);
1361        let trait_bounds = FxHashMap::from_iter([(
1362            Symbol::from_raw("m.T"),
1363            vec![
1364                instantiated("m.Boxed", Type::int()),
1365                instantiated("m.Boxed", Type::string()),
1366            ],
1367        )]);
1368
1369        assert_narrow_matches_broad(&table, &trait_bounds, &nominal("m.T"), "run");
1370    }
1371
1372    #[test]
1373    fn a_self_referential_bound_terminates() {
1374        let table = table(vec![]);
1375        let trait_bounds = FxHashMap::from_iter([(Symbol::from_raw("m.T"), vec![nominal("m.T")])]);
1376
1377        assert_narrow_matches_broad(&table, &trait_bounds, &nominal("m.T"), "run");
1378    }
1379
1380    #[test]
1381    fn an_interface_declares_a_method_through_its_parent() {
1382        let table = table(vec![
1383            (
1384                "m.Child",
1385                interface_definition("m.Child", vec![nominal("m.Parent")], Methods::default()),
1386            ),
1387            (
1388                "m.Parent",
1389                interface_definition(
1390                    "m.Parent",
1391                    vec![],
1392                    Methods::from_iter([named_method("run", Type::int())]),
1393                ),
1394            ),
1395        ]);
1396        let lookup = |id: &str| table.get(id);
1397
1398        assert!(interface_declares_any_method(&nominal("m.Child"), lookup));
1399        assert!(type_has_any_method(&nominal("m.Child"), lookup));
1400    }
1401
1402    #[test]
1403    fn an_interface_without_any_declared_method_is_reported_empty() {
1404        let table = table(vec![
1405            (
1406                "m.Child",
1407                interface_definition("m.Child", vec![nominal("m.Parent")], Methods::default()),
1408            ),
1409            (
1410                "m.Parent",
1411                interface_definition("m.Parent", vec![], Methods::default()),
1412            ),
1413        ]);
1414        let lookup = |id: &str| table.get(id);
1415
1416        assert!(!interface_declares_any_method(&nominal("m.Child"), lookup));
1417        assert!(!type_has_any_method(&nominal("m.Child"), lookup));
1418    }
1419}