1use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
2
3use ecow::EcoString;
4
5use crate::ast::{Annotation, EnumVariant, Generic, Literal, Span, StructFields};
6use crate::types;
7use crate::types::{
8 FunctionParameter, Symbol, Type, build_substitution_map, substitute, type_args_match_params,
9};
10
11#[derive(Debug, Clone)]
12pub struct Definition {
13 pub visibility: Visibility,
14 pub ty: Type,
15 pub name_span: Option<Span>,
16 pub doc: Option<String>,
17 pub body: DefinitionBody,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub enum TypeAttribute {
23 Display,
24 ClosedDomain,
25 AnonStruct,
26 HiddenEmbed,
29 Serialized,
30 ZeroSafe,
31 ZeroUnsafe,
34 HiddenFields,
35}
36
37pub type Attributes = HashSet<TypeAttribute>;
38
39#[derive(Debug, Clone)]
40pub enum ValueKind {
41 Runtime,
42 ConstantDeclaration,
43 Constant(Literal),
44}
45
46#[derive(Debug, Clone)]
47pub enum DefinitionBody {
48 TypeAlias {
49 generics: Vec<Generic>,
50 alias: AliasKind,
51 methods: Methods,
52 attributes: Attributes,
53 },
54 Enum {
55 generics: Vec<Generic>,
56 variants: Vec<EnumVariant>,
57 methods: Methods,
58 attributes: Attributes,
59 },
60 Struct {
61 generics: Vec<Generic>,
62 fields: StructFields,
63 methods: Methods,
64 attributes: Attributes,
65 },
66 Interface {
67 definition: Interface,
68 },
69 Value {
70 kind: ValueKind,
71 allowed_lints: Vec<String>,
72 go_hints: Vec<String>,
73 go_name: Option<String>,
74 go_type_param_recipe: Option<String>,
79 },
80}
81
82#[derive(Debug, Clone)]
83pub enum AliasKind {
84 Opaque(Annotation),
85 Transparent {
86 annotation: Annotation,
87 target: Type,
88 },
89}
90
91impl AliasKind {
92 pub fn annotation(&self) -> &Annotation {
93 match self {
94 Self::Opaque(annotation) | Self::Transparent { annotation, .. } => annotation,
95 }
96 }
97}
98
99impl DefinitionBody {
100 pub fn generics(&self) -> Option<&[Generic]> {
101 match self {
102 Self::TypeAlias { generics, .. }
103 | Self::Enum { generics, .. }
104 | Self::Struct { generics, .. } => Some(generics),
105 Self::Interface { definition } => Some(&definition.generics),
106 Self::Value { .. } => None,
107 }
108 }
109
110 pub fn generics_mut(&mut self) -> Option<&mut [Generic]> {
111 match self {
112 Self::TypeAlias { generics, .. }
113 | Self::Enum { generics, .. }
114 | Self::Struct { generics, .. } => Some(generics),
115 Self::Interface { definition } => Some(&mut definition.generics),
116 Self::Value { .. } => None,
117 }
118 }
119}
120
121impl Definition {
122 pub fn is_newtype(&self) -> bool {
127 matches!(
128 &self.body,
129 DefinitionBody::Struct {
130 fields: StructFields::Tuple(fields),
131 generics,
132 ..
133 } if fields.len() == 1 && generics.is_empty()
134 )
135 }
136
137 pub fn is_pointer_backed_newtype<'d, F>(&self, lookup: F) -> bool
138 where
139 F: Fn(&str) -> Option<&'d Definition>,
140 {
141 self.is_newtype()
142 && matches!(
143 &self.body,
144 DefinitionBody::Struct {
145 fields: StructFields::Tuple(fields),
146 ..
147 } if types::peel_alias(&fields[0].ty, lookup).is_ref()
148 )
149 }
150
151 pub fn instantiate_alias_target(&self, params: &[Type], writable: bool) -> Option<Type> {
152 let DefinitionBody::TypeAlias {
153 generics,
154 alias: AliasKind::Transparent { target, .. },
155 ..
156 } = &self.body
157 else {
158 return None;
159 };
160 let map = build_substitution_map(generics, params);
161 if writable {
162 Some(substitute(&target.clone().make_writable(), &map))
163 } else {
164 Some(substitute(target, &map))
165 }
166 }
167
168 pub fn instantiate_underlying(&self, params: &[Type], writable: bool) -> Option<Type> {
169 if let Some(target) = self.instantiate_alias_target(params, writable) {
170 return Some(target);
171 }
172 match &self.body {
173 DefinitionBody::Struct {
174 fields: StructFields::Tuple(fields),
175 ..
176 } if self.is_newtype() => Some(if writable {
177 fields[0].ty.clone()
178 } else {
179 fields[0].ty.demoted()
180 }),
181 _ => None,
182 }
183 }
184
185 pub fn constructor_type(&self) -> Option<Type> {
191 let DefinitionBody::Struct {
192 fields: StructFields::Tuple(fields),
193 generics,
194 ..
195 } = &self.body
196 else {
197 return None;
198 };
199
200 let return_type = self.ty.unwrap_forall().clone();
201 let function = Type::function(
202 fields
203 .iter()
204 .map(|field| FunctionParameter::new(field.ty.clone(), false))
205 .collect(),
206 Default::default(),
207 return_type.into(),
208 );
209
210 Some(if generics.is_empty() {
211 function
212 } else {
213 Type::Forall {
214 vars: generics
215 .iter()
216 .map(|generic| generic.name.clone())
217 .collect(),
218 body: Box::new(function),
219 }
220 })
221 }
222
223 pub fn is_transparent_type_alias(&self) -> bool {
224 matches!(
225 self.body,
226 DefinitionBody::TypeAlias {
227 alias: AliasKind::Transparent { .. },
228 ..
229 }
230 )
231 }
232
233 pub fn allowed_lints(&self) -> &[String] {
234 match &self.body {
235 DefinitionBody::Value { allowed_lints, .. } => allowed_lints,
236 _ => &[],
237 }
238 }
239
240 pub fn go_hints(&self) -> &[String] {
241 match &self.body {
242 DefinitionBody::Value { go_hints, .. } => go_hints,
243 _ => &[],
244 }
245 }
246
247 pub fn go_name(&self) -> Option<&str> {
248 match &self.body {
249 DefinitionBody::Value { go_name, .. } => go_name.as_deref(),
250 _ => None,
251 }
252 }
253
254 pub fn go_type_param_recipe(&self) -> Option<&str> {
255 match &self.body {
256 DefinitionBody::Value {
257 go_type_param_recipe,
258 ..
259 } => go_type_param_recipe.as_deref(),
260 _ => None,
261 }
262 }
263
264 pub fn const_value(&self) -> Option<&Literal> {
265 match &self.body {
266 DefinitionBody::Value {
267 kind: ValueKind::Constant(value),
268 ..
269 } => Some(value),
270 _ => None,
271 }
272 }
273
274 pub fn is_const(&self) -> bool {
275 matches!(
276 self.body,
277 DefinitionBody::Value {
278 kind: ValueKind::ConstantDeclaration | ValueKind::Constant(_),
279 ..
280 }
281 )
282 }
283
284 pub fn methods_mut(&mut self) -> Option<&mut Methods> {
285 match &mut self.body {
286 DefinitionBody::Struct { methods, .. } => Some(methods),
287 DefinitionBody::TypeAlias { methods, .. } => Some(methods),
288 DefinitionBody::Enum { methods, .. } => Some(methods),
289 DefinitionBody::Interface { definition } => Some(&mut definition.methods),
290 DefinitionBody::Value { .. } => None,
291 }
292 }
293
294 pub fn methods(&self) -> Option<&Methods> {
295 match &self.body {
296 DefinitionBody::Struct { methods, .. }
297 | DefinitionBody::TypeAlias { methods, .. }
298 | DefinitionBody::Enum { methods, .. } => Some(methods),
299 DefinitionBody::Interface { definition } => Some(&definition.methods),
300 DefinitionBody::Value { .. } => None,
301 }
302 }
303
304 pub fn is_ufcs_method(&self, method: &str) -> bool {
305 let (methods, base_generics_count) = match &self.body {
306 DefinitionBody::Struct {
307 methods, generics, ..
308 }
309 | DefinitionBody::Enum {
310 methods, generics, ..
311 }
312 | DefinitionBody::TypeAlias {
313 methods, generics, ..
314 } => (methods, generics.len()),
315 DefinitionBody::Interface { .. } | DefinitionBody::Value { .. } => return false,
316 };
317 methods
318 .get(method)
319 .is_some_and(|method| is_ufcs_method_type(&method.ty, base_generics_count))
320 }
321
322 fn attributes(&self) -> Option<&Attributes> {
323 match &self.body {
324 DefinitionBody::Struct { attributes, .. }
325 | DefinitionBody::Enum { attributes, .. }
326 | DefinitionBody::TypeAlias { attributes, .. } => Some(attributes),
327 _ => None,
328 }
329 }
330
331 pub fn is_display(&self) -> bool {
332 self.attributes()
333 .is_some_and(|a| a.contains(&TypeAttribute::Display))
334 }
335
336 pub fn is_zero_safe(&self) -> bool {
337 self.attributes()
338 .is_some_and(|a| a.contains(&TypeAttribute::ZeroSafe))
339 }
340
341 pub fn is_zero_unsafe(&self) -> bool {
342 self.attributes()
343 .is_some_and(|a| a.contains(&TypeAttribute::ZeroUnsafe))
344 }
345
346 pub fn has_hidden_fields(&self) -> bool {
347 self.attributes()
348 .is_some_and(|a| a.contains(&TypeAttribute::HiddenFields))
349 }
350
351 pub fn is_closed_domain(&self) -> bool {
352 self.attributes()
353 .is_some_and(|a| a.contains(&TypeAttribute::ClosedDomain))
354 }
355
356 pub fn is_serialized(&self) -> bool {
357 self.attributes()
358 .is_some_and(|a| a.contains(&TypeAttribute::Serialized))
359 }
360
361 pub fn is_anon_struct(&self) -> bool {
362 self.attributes()
363 .is_some_and(|a| a.contains(&TypeAttribute::AnonStruct))
364 }
365
366 pub fn has_hidden_embed(&self) -> bool {
367 self.attributes()
368 .is_some_and(|a| a.contains(&TypeAttribute::HiddenEmbed))
369 }
370
371 pub fn is_type_definition(&self) -> bool {
372 matches!(
373 self.body,
374 DefinitionBody::Struct { .. }
375 | DefinitionBody::Enum { .. }
376 | DefinitionBody::TypeAlias { .. }
377 )
378 }
379
380 pub fn is_type_alias(&self) -> bool {
381 matches!(self.body, DefinitionBody::TypeAlias { .. })
382 }
383
384 pub fn is_value(&self, qualified_name: &str) -> bool {
385 matches!(self.body, DefinitionBody::Value { .. })
386 && self.ty.unwrap_forall().get_qualified_id() != Some(qualified_name)
387 }
388}
389
390fn is_ufcs_method_type(method_ty: &Type, base_generics_count: usize) -> bool {
391 let Type::Forall { vars, body } = method_ty else {
392 return base_generics_count > 0;
393 };
394
395 if vars.len() > base_generics_count {
396 return true;
397 }
398
399 if let Type::Function(function) = body.as_ref()
400 && let Some(receiver) = function.params.first()
401 && let Type::Nominal {
402 params: receiver_params,
403 ..
404 } = receiver.ty.strip_refs()
405 && !type_args_match_params(&receiver_params, vars.iter())
406 {
407 return true;
408 }
409
410 false
411}
412
413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
414#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
415pub enum MethodOrigin {
416 Declared,
417 Synthesized,
418}
419
420#[derive(Debug, Clone, PartialEq)]
421#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
422pub struct Method {
423 pub source_name: EcoString,
424 pub ty: Type,
425 pub visibility: Visibility,
426 pub origin: MethodOrigin,
427 pub name_span: Option<Span>,
428 pub doc: Option<String>,
429 pub allowed_lints: Vec<String>,
430 pub go_hints: Vec<String>,
431}
432
433impl Method {
434 pub fn with_type(&self, ty: Type) -> Self {
435 Self { ty, ..self.clone() }
436 }
437
438 fn with_receiver_placeholder(self) -> Self {
439 let Self {
440 source_name,
441 ty,
442 visibility,
443 origin,
444 name_span,
445 doc,
446 allowed_lints,
447 go_hints,
448 } = self;
449 Self {
450 source_name,
451 ty: ty.with_receiver_placeholder(),
452 visibility,
453 origin,
454 name_span,
455 doc,
456 allowed_lints,
457 go_hints,
458 }
459 }
460}
461
462pub type Methods = HashMap<EcoString, Method>;
463
464#[derive(Debug, Clone, PartialEq)]
465pub struct InterfaceInstance {
466 pub ty: Type,
467 pub parent_of: Option<Symbol>,
468}
469
470pub fn interface_instances<'d, F>(interface_ty: &Type, lookup: F) -> Vec<InterfaceInstance>
474where
475 F: Copy + Fn(&str) -> Option<&'d Definition>,
476{
477 fn collect<'d, F>(
478 interface_ty: &Type,
479 parent_of: Option<&Symbol>,
480 lookup: F,
481 visited: &mut HashSet<String>,
482 visiting: &mut HashSet<Symbol>,
483 instances: &mut Vec<InterfaceInstance>,
484 ) where
485 F: Copy + Fn(&str) -> Option<&'d Definition>,
486 {
487 let resolved = types::peel_alias(interface_ty, lookup);
488 let Type::Nominal { id, params, .. } = &resolved else {
489 return;
490 };
491 if !visited.insert(format!("{resolved:?}")) || !visiting.insert(id.clone()) {
494 return;
495 }
496 let Some(Definition {
497 body: DefinitionBody::Interface { definition },
498 ..
499 }) = lookup(id)
500 else {
501 visiting.remove(id);
502 return;
503 };
504 let map = build_substitution_map(&definition.generics, params);
505 instances.push(InterfaceInstance {
506 ty: resolved.clone(),
507 parent_of: parent_of.cloned(),
508 });
509 for parent in &definition.parents {
510 collect(
511 &substitute(parent, &map),
512 Some(id),
513 lookup,
514 visited,
515 visiting,
516 instances,
517 );
518 }
519 visiting.remove(id);
520 }
521
522 let mut instances = Vec::new();
523 collect(
524 interface_ty,
525 None,
526 lookup,
527 &mut HashSet::default(),
528 &mut HashSet::default(),
529 &mut instances,
530 );
531 instances
532}
533
534#[derive(Debug, Clone, PartialEq)]
535pub struct InterfaceRequirement {
536 pub declaring_interface: Symbol,
537 pub parent_of: Option<Symbol>,
538 pub name: EcoString,
539 pub method: Method,
542 pub ty: Type,
544}
545
546pub fn interface_requirements<'d, F>(interface_ty: &Type, lookup: F) -> Vec<InterfaceRequirement>
551where
552 F: Copy + Fn(&str) -> Option<&'d Definition>,
553{
554 let mut requirements = Vec::new();
555 for instance in interface_instances(interface_ty, lookup) {
556 let Type::Nominal { id, params, .. } = instance.ty else {
557 continue;
558 };
559 let Some(Definition {
560 body: DefinitionBody::Interface { definition },
561 ..
562 }) = lookup(&id)
563 else {
564 continue;
565 };
566 let map = build_substitution_map(&definition.generics, ¶ms);
567 requirements.extend(
568 definition
569 .methods
570 .iter()
571 .map(|(name, method)| InterfaceRequirement {
572 declaring_interface: id.clone(),
573 parent_of: instance.parent_of.clone(),
574 name: name.clone(),
575 method: method.clone(),
576 ty: substitute(&method.ty, &map),
577 }),
578 );
579 }
580 requirements
581}
582
583pub fn methods_for_type<'d, F>(
585 ty: &Type,
586 trait_bounds: &HashMap<Symbol, Vec<Type>>,
587 lookup: F,
588) -> Methods
589where
590 F: Copy + Fn(&str) -> Option<&'d Definition>,
591{
592 fn collect<'d, F>(
593 ty: &Type,
594 trait_bounds: &HashMap<Symbol, Vec<Type>>,
595 lookup: F,
596 visited: &mut HashSet<String>,
597 ) -> Methods
598 where
599 F: Copy + Fn(&str) -> Option<&'d Definition>,
600 {
601 let stripped = ty.strip_refs();
602 let Some(qualified_name) = method_lookup_key(&stripped) else {
603 return Methods::default();
604 };
605
606 if !visited.insert(qualified_name.as_str().to_string()) {
607 return Methods::default();
608 }
609
610 if lookup(&qualified_name)
611 .is_some_and(|definition| matches!(definition.body, DefinitionBody::Interface { .. }))
612 {
613 return interface_requirements(&stripped, lookup)
614 .into_iter()
615 .map(|requirement| {
616 (
617 requirement.name,
618 requirement
619 .method
620 .with_type(requirement.ty)
621 .with_receiver_placeholder(),
622 )
623 })
624 .collect();
625 }
626
627 if let Some(bounds) = trait_bounds.get(&qualified_name) {
628 return bounds
629 .iter()
630 .flat_map(|bound| collect(bound, trait_bounds, lookup, visited))
631 .collect();
632 }
633
634 let mut methods = lookup(&qualified_name)
635 .and_then(Definition::methods)
636 .cloned()
637 .unwrap_or_default();
638
639 if lookup(&qualified_name).is_some_and(Definition::is_transparent_type_alias) {
640 let underlying = types::peel_alias(&stripped, lookup);
641 if underlying != stripped {
642 for (name, method) in collect(&underlying, trait_bounds, lookup, visited) {
643 methods.entry(name).or_insert(method);
644 }
645 }
646 }
647
648 methods
649 }
650
651 collect(ty, trait_bounds, lookup, &mut HashSet::default())
652}
653
654fn method_lookup_key(ty: &Type) -> Option<Symbol> {
655 match ty {
656 Type::Nominal { id, .. } => Some(id.clone()),
657 Type::Compound { kind, .. } => Some(Symbol::from_parts("prelude", kind.leaf_name())),
658 Type::Simple(kind) => Some(Symbol::from_parts("prelude", kind.leaf_name())),
659 Type::Array { .. } => Some(Symbol::from_parts("prelude", "Array")),
660 _ => None,
661 }
662}
663
664#[derive(Debug, Clone, PartialEq)]
665#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
666pub enum Visibility {
667 Public,
668 Private,
669 Local,
670}
671
672impl Visibility {
673 pub fn is_public(&self) -> bool {
674 matches!(self, Visibility::Public)
675 }
676}
677
678#[derive(Debug, Clone, PartialEq)]
679pub struct Interface {
680 pub generics: Vec<Generic>,
681 pub parents: Vec<Type>,
682 pub methods: Methods,
683}
684
685#[cfg(test)]
686mod tests {
687 use super::*;
688 use crate::types::Symbol;
689
690 fn generic(name: &str) -> Generic {
691 Generic::new(name, vec![], Span::dummy())
692 }
693
694 fn receiver(params: Vec<Type>) -> Type {
695 Type::Nominal {
696 id: Symbol::from_raw("m.Box"),
697 params,
698 writable: false,
699 }
700 }
701
702 fn method(vars: &[&str], receiver: Type) -> Type {
703 let function = Type::function(
704 vec![FunctionParameter::new(receiver, false)],
705 Default::default(),
706 Box::new(Type::unit()),
707 );
708 Type::Forall {
709 vars: vars.iter().map(|name| EcoString::from(*name)).collect(),
710 body: Box::new(function),
711 }
712 }
713
714 fn definition(method_ty: Type) -> Definition {
715 Definition {
716 visibility: Visibility::Public,
717 ty: receiver(vec![Type::Parameter("T".into())]),
718 name_span: None,
719 doc: None,
720 body: DefinitionBody::Struct {
721 generics: vec![generic("T")],
722 fields: StructFields::Record(vec![]),
723 methods: HashMap::from_iter([(
724 "map".into(),
725 Method {
726 source_name: "map".into(),
727 ty: method_ty,
728 visibility: Visibility::Public,
729 origin: MethodOrigin::Declared,
730 name_span: None,
731 doc: None,
732 allowed_lints: vec![],
733 go_hints: vec![],
734 },
735 )]),
736 attributes: Attributes::default(),
737 },
738 }
739 }
740
741 #[test]
742 fn full_generic_receiver_is_a_selector_method() {
743 let definition = definition(method(&["T"], receiver(vec![Type::Parameter("T".into())])));
744
745 assert!(!definition.is_ufcs_method("map"));
746 }
747
748 #[test]
749 fn extra_method_generic_requires_ufcs() {
750 let definition = definition(method(
751 &["T", "U"],
752 receiver(vec![Type::Parameter("T".into())]),
753 ));
754
755 assert!(definition.is_ufcs_method("map"));
756 }
757
758 #[test]
759 fn specialized_receiver_requires_ufcs() {
760 let definition = definition(method(&["T"], receiver(vec![Type::int()])));
761
762 assert!(definition.is_ufcs_method("map"));
763 }
764}