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