Skip to main content

lisette_syntax/program/
definition.rs

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