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