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