1use std::path::PathBuf;
2use std::sync::atomic::{AtomicU32, Ordering};
3
4use ecow::EcoString;
5use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
6
7use syntax::ast::{EnumVariant, Expression, Literal, StructFieldDefinition};
8use syntax::program::{
9 Definition, DefinitionBody, File, Interface, MethodSignatures, Module, ModuleId,
10};
11use syntax::types::{SimpleKind, SubstitutionMap, Symbol, Type, substitute};
12
13pub const ENTRY_MODULE_ID: &str = "_entry_";
14pub const ENTRY_FILE_ID: u32 = 0;
15
16#[derive(Debug, Clone)]
17pub struct ClosedMember {
18 pub display_name: EcoString,
20 pub literal: Literal,
22 pub value: DomainValue,
24}
25
26#[derive(Debug, Clone)]
28pub struct ClosedDomain {
29 pub base: SimpleKind,
30 pub type_display: EcoString,
31 pub members: Vec<ClosedMember>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
37pub enum DomainValue {
38 Int(i128),
39 Str(String),
40}
41
42impl DomainValue {
43 pub fn from_literal(literal: &Literal, base: SimpleKind) -> Option<DomainValue> {
44 match base {
48 SimpleKind::Rune => match literal {
49 Literal::Char(text) => char_codepoint(text).map(|cp| DomainValue::Int(cp as i128)),
50 Literal::Integer { value, .. } => Some(DomainValue::Int(*value as i64 as i128)),
51 _ => None,
52 },
53 SimpleKind::String => match literal {
54 Literal::String { value, .. } => Some(DomainValue::Str(value.clone())),
55 _ => None,
56 },
57 _ if is_unsigned_base(base) => match literal {
58 Literal::Integer { value, .. } => Some(DomainValue::Int(*value as i128)),
59 _ => None,
60 },
61 _ if base.is_signed_int() => match literal {
62 Literal::Integer { value, .. } => Some(DomainValue::Int(*value as i64 as i128)),
63 _ => None,
64 },
65 _ => None,
66 }
67 }
68}
69
70pub fn is_unsigned_base(base: SimpleKind) -> bool {
73 base.is_unsigned_int() || base == SimpleKind::Uintptr
74}
75
76fn char_codepoint(text: &str) -> Option<u64> {
79 let Some(rest) = text.strip_prefix('\\') else {
80 return text.chars().next().map(|c| c as u64);
81 };
82 match rest.as_bytes().first()? {
83 b'a' => Some(7),
84 b'b' => Some(8),
85 b'f' => Some(12),
86 b'n' => Some(10),
87 b'r' => Some(13),
88 b't' => Some(9),
89 b'v' => Some(11),
90 b'\\' => Some(92),
91 b'\'' => Some(39),
92 b'x' => u64::from_str_radix(&rest[1..], 16).ok(),
93 b'0'..=b'7' => u64::from_str_radix(rest, 8).ok(),
94 _ => None,
95 }
96}
97
98pub struct Store {
99 pub modules: HashMap<String, Module>,
100 pub module_ids: Vec<ModuleId>,
101 pub files: HashMap<u32, String>,
103 pub go_package_names: HashMap<String, String>,
106 pub typedef_paths: HashMap<u32, PathBuf>,
109 visited_modules: HashSet<String>,
110 next_file_id: AtomicU32,
112 pub closed_domains: HashMap<Symbol, ClosedDomain>,
115}
116
117impl Default for Store {
118 fn default() -> Self {
119 Self::new()
120 }
121}
122
123impl Store {
124 pub fn new() -> Self {
125 let prelude_module = Module::new("prelude");
126 let nominal_module = Module::nominal();
127
128 let modules = vec![
129 (prelude_module.id.clone(), prelude_module),
130 (nominal_module.id.clone(), nominal_module),
131 ]
132 .into_iter()
133 .collect();
134
135 let module_ids = vec!["prelude".to_string()];
136
137 Self {
138 files: Default::default(),
139 modules,
140 module_ids,
141 go_package_names: Default::default(),
142 typedef_paths: Default::default(),
143 visited_modules: Default::default(),
144 next_file_id: AtomicU32::new(2), closed_domains: Default::default(),
146 }
147 }
148
149 pub fn new_file_id(&self) -> u32 {
150 self.next_file_id.fetch_add(1, Ordering::Relaxed)
151 }
152
153 pub fn register_file(&mut self, file_id: u32, module_id: &str) {
154 self.files.insert(file_id, module_id.to_string());
155 }
156
157 pub fn entry_module_id(&self) -> &'static str {
158 ENTRY_MODULE_ID
159 }
160
161 pub fn init_entry_module(&mut self) {
163 self.add_module(ENTRY_MODULE_ID);
164 self.register_file(ENTRY_FILE_ID, ENTRY_MODULE_ID);
165 }
166
167 pub fn store_entry_file(
168 &mut self,
169 filename: &str,
170 display_path: &str,
171 source: &str,
172 ast: Vec<Expression>,
173 ) {
174 self.store_file(
175 ENTRY_MODULE_ID,
176 File {
177 id: ENTRY_FILE_ID,
178 module_id: ENTRY_MODULE_ID.to_string(),
179 name: filename.to_string(),
180 display_path: display_path.to_string(),
181 source: source.to_string(),
182 items: ast,
183 },
184 );
185 }
186
187 pub fn store_module(&mut self, module_id: &str, files: Vec<File>) {
188 self.mark_visited(module_id);
189 self.add_module(module_id);
190
191 for file in files {
192 self.store_file(module_id, file);
193 }
194 }
195
196 pub fn store_file(&mut self, module_id: &str, file: File) {
199 self.files.insert(file.id, module_id.to_string());
200
201 let module = self
202 .get_module_mut(module_id)
203 .expect("module must exist to store file");
204
205 if file.is_d_lis() {
206 module.typedefs.insert(file.id, file);
207 } else {
208 module.files.insert(file.id, file);
209 }
210 }
211
212 pub fn get_file(&self, file_id: u32) -> Option<&File> {
213 let module_id = self.files.get(&file_id)?;
214 let module = self.get_module(module_id)?;
215 module
216 .get_file(file_id)
217 .or_else(|| module.get_typedef_by_id(file_id))
218 }
219
220 pub fn get_file_mut(&mut self, file_id: u32) -> Option<&mut File> {
221 let module_id = self.files.get(&file_id)?.clone();
222 let module = self.modules.get_mut(&module_id)?;
223 module
224 .files
225 .get_mut(&file_id)
226 .or_else(|| module.typedefs.get_mut(&file_id))
227 }
228
229 pub fn get_module(&self, module_id: &str) -> Option<&Module> {
230 self.modules.get(module_id)
231 }
232
233 pub fn has(&self, module_id: &str) -> bool {
234 self.modules.contains_key(module_id)
235 }
236
237 pub fn add_module(&mut self, module_id: &str) {
238 if self.modules.contains_key(module_id) {
239 return;
240 }
241
242 self.modules
243 .insert(module_id.to_string(), Module::new(module_id));
244 self.module_ids.push(module_id.to_string());
245 }
246
247 pub fn get_module_mut(&mut self, module_id: &str) -> Option<&mut Module> {
248 self.modules.get_mut(module_id)
249 }
250
251 pub fn is_visited(&self, module_id: &str) -> bool {
252 self.visited_modules.contains(module_id)
253 }
254
255 pub fn mark_visited(&mut self, module_id: &str) {
256 self.visited_modules.insert(module_id.to_string());
257 }
258
259 pub fn get_definition(&self, qualified_name: &str) -> Option<&Definition> {
260 let module_name = self.module_for_qualified_name(qualified_name)?;
261
262 self.get_module(module_name)?
263 .definitions
264 .get(qualified_name)
265 }
266
267 pub fn module_for_qualified_name<'a>(&'a self, qualified_name: &'a str) -> Option<&'a str> {
268 syntax::types::module_for_qualified_name(
269 qualified_name,
270 self.modules.keys().map(String::as_str),
271 )
272 }
273
274 pub fn variants_of(&self, qualified_name: &str) -> Option<&[EnumVariant]> {
275 match &self.get_definition(qualified_name)?.body {
276 DefinitionBody::Enum { variants, .. } => Some(variants),
277 _ => None,
278 }
279 }
280
281 pub fn variant_of(&self, enum_qualified: &str, variant_name: &str) -> Option<&EnumVariant> {
282 self.variants_of(enum_qualified)?
283 .iter()
284 .find(|v| v.name == variant_name)
285 }
286
287 pub fn is_nominal_defined_type(&self, qualified_name: &str) -> bool {
288 match self.get_definition(qualified_name) {
289 Some(def) => def.is_newtype(),
290 None => false,
291 }
292 }
293
294 pub fn build_closed_domains(&mut self) {
295 let mut bases: HashMap<Symbol, (SimpleKind, String)> = HashMap::default();
297 for module in self.modules.values() {
298 for (qualified_name, definition) in &module.definitions {
299 if definition.is_closed_domain()
302 && let Some(base) = definition.ty().underlying_simple_kind()
303 && !base.is_float()
304 {
305 bases.insert(qualified_name.clone(), (base, module.id.clone()));
306 }
307 }
308 }
309
310 if bases.is_empty() {
311 return;
312 }
313
314 let mut members: HashMap<Symbol, Vec<ClosedMember>> = HashMap::default();
315 for module in self.modules.values() {
316 for (qualified_name, definition) in &module.definitions {
317 let Some(const_literal) = definition.const_value() else {
318 continue;
319 };
320 let Type::Nominal { id, .. } = definition.ty() else {
321 continue;
322 };
323 let Some((base, declaring_module)) = bases.get(id) else {
324 continue;
325 };
326 if module.id != *declaring_module {
329 continue;
330 }
331 let Some(value) = DomainValue::from_literal(const_literal, *base) else {
332 continue;
333 };
334 members.entry(id.clone()).or_default().push(ClosedMember {
335 display_name: domain_display_name(qualified_name.as_str()).into(),
336 literal: const_literal.clone(),
337 value,
338 });
339 }
340 }
341
342 let mut domains: HashMap<Symbol, ClosedDomain> = HashMap::default();
343 for (type_id, (base, _)) in bases {
344 let Some(mut domain_members) = members.remove(&type_id) else {
345 continue;
346 };
347 domain_members.sort_by(|a, b| a.value.cmp(&b.value));
348 domains.insert(
349 type_id.clone(),
350 ClosedDomain {
351 base,
352 type_display: domain_display_name(type_id.as_str()).into(),
353 members: domain_members,
354 },
355 );
356 }
357
358 self.closed_domains = domains;
359 }
360
361 pub fn fields_of(&self, qualified_name: &str) -> Option<&[StructFieldDefinition]> {
362 match &self.get_definition(qualified_name)?.body {
363 DefinitionBody::Struct { fields, .. } => Some(fields),
364 _ => None,
365 }
366 }
367
368 pub fn struct_kind(&self, qualified_name: &str) -> Option<syntax::ast::StructKind> {
369 match &self.get_definition(qualified_name)?.body {
370 DefinitionBody::Struct { kind, .. } => Some(*kind),
371 _ => None,
372 }
373 }
374
375 pub fn struct_constructor(&self, qualified_name: &str) -> Option<&Type> {
376 match &self.get_definition(qualified_name)?.body {
377 DefinitionBody::Struct { constructor, .. } => constructor.as_ref(),
378 _ => None,
379 }
380 }
381
382 pub fn parent_interfaces_of(&self, qualified_name: &str) -> Option<&[Type]> {
383 match &self.get_definition(qualified_name)?.body {
384 DefinitionBody::Interface { definition, .. } => Some(&definition.parents),
385 _ => None,
386 }
387 }
388
389 pub fn get_type(&self, qualified_name: &str) -> Option<&Type> {
390 self.get_definition(qualified_name)
391 .map(|definition| definition.ty())
392 }
393
394 pub fn get_interface(&self, qualified_name: &str) -> Option<&Interface> {
395 match &self.get_definition(qualified_name)?.body {
396 DefinitionBody::Interface { definition, .. } => Some(definition),
397 _ => None,
398 }
399 }
400
401 pub fn is_nilable_go_type(&self, ty: &Type) -> bool {
402 if ty.is_ref() || matches!(ty, Type::Function(_)) {
403 return true;
404 }
405 let Type::Nominal { id, .. } = ty else {
406 return false;
407 };
408 if self.get_definition(id.as_str()).is_none() {
409 return false;
410 }
411 if self.get_interface(id.as_str()).is_some() {
412 return true;
413 }
414 match ty.get_underlying() {
415 Some(Type::Function(_)) => true,
416 Some(u) if u.is_ref() => true,
417 _ => false,
418 }
419 }
420
421 pub fn peel_alias(&self, ty: &Type) -> Type {
422 syntax::types::peel_alias(ty, |id| {
423 self.get_definition(id)
424 .is_some_and(Definition::is_type_alias)
425 })
426 }
427
428 pub fn deep_resolve_alias(&self, ty: &Type) -> Type {
429 let mut current = ty.clone();
430 let mut seen: HashSet<Symbol> = HashSet::default();
431 loop {
432 let Type::Nominal { id, params, .. } = ¤t else {
433 return current;
434 };
435 if !seen.insert(id.clone()) {
436 return current;
437 }
438 let Some(def) = self.get_definition(id.as_str()) else {
439 return current;
440 };
441 if !matches!(def.body, DefinitionBody::TypeAlias { .. }) {
442 return current;
443 }
444 let def_ty = &def.ty;
445 let (vars, body) = match def_ty {
446 Type::Forall { vars, body } => (vars.clone(), body.as_ref().clone()),
447 other => (vec![], other.clone()),
448 };
449 let map: SubstitutionMap = vars.iter().cloned().zip(params.iter().cloned()).collect();
450 current = substitute(&body, &map);
451 }
452 }
453
454 pub fn peel_alias_deep(&self, ty: &Type) -> Type {
455 match self.peel_alias(ty) {
456 Type::Compound { kind, args } => Type::Compound {
457 kind,
458 args: args.iter().map(|a| self.peel_alias_deep(a)).collect(),
459 },
460 Type::Tuple(elements) => {
461 Type::Tuple(elements.iter().map(|e| self.peel_alias_deep(e)).collect())
462 }
463 Type::Nominal {
464 id,
465 params,
466 underlying_ty,
467 } => Type::Nominal {
468 id,
469 params: params.iter().map(|p| self.peel_alias_deep(p)).collect(),
470 underlying_ty,
471 },
472 Type::Function(f) => {
473 let f = std::sync::Arc::try_unwrap(f).unwrap_or_else(|arc| (*arc).clone());
474 Type::function(
475 f.params.iter().map(|p| self.peel_alias_deep(p)).collect(),
476 f.param_mutability,
477 f.bounds,
478 Box::new(self.peel_alias_deep(&f.return_type)),
479 )
480 }
481 other => other,
482 }
483 }
484
485 pub fn get_own_methods(&self, qualified_name: &str) -> Option<&MethodSignatures> {
486 match &self.get_definition(qualified_name)?.body {
487 DefinitionBody::Struct { methods, .. } => Some(methods),
488 DefinitionBody::TypeAlias { methods, .. } => Some(methods),
489 DefinitionBody::Enum { methods, .. } => Some(methods),
490 _ => None,
491 }
492 }
493
494 pub fn get_all_methods(
495 &self,
496 ty: &Type,
497 trait_bounds: &HashMap<Symbol, Vec<Type>>,
498 ) -> MethodSignatures {
499 let mut visited = HashSet::default();
500 self.get_all_methods_recursive(ty, trait_bounds, &mut visited)
501 }
502
503 fn get_all_methods_recursive(
504 &self,
505 ty: &Type,
506 trait_bounds: &HashMap<Symbol, Vec<Type>>,
507 visited: &mut HashSet<String>,
508 ) -> MethodSignatures {
509 let stripped = ty.strip_refs();
510 let Some(qualified_name) = method_lookup_key(&stripped) else {
511 return MethodSignatures::default();
512 };
513
514 if !visited.insert(qualified_name.as_str().to_string()) {
516 return MethodSignatures::default();
517 }
518
519 if let Some(interface) = self.get_interface(&qualified_name) {
520 let mut all_interface_methods = MethodSignatures::default();
521
522 let type_args = ty.get_type_params().unwrap_or_default();
523 let map: SubstitutionMap = interface
524 .generics
525 .iter()
526 .map(|g| g.name.clone())
527 .zip(type_args.iter().cloned())
528 .collect();
529
530 for (name, method_ty) in &interface.methods {
531 let substituted = substitute(method_ty, &map);
532 all_interface_methods.insert(name.clone(), substituted.with_receiver_placeholder());
533 }
534
535 for parent in &interface.parents {
536 for (name, method_ty) in
537 self.get_all_methods_recursive(parent, trait_bounds, visited)
538 {
539 all_interface_methods.insert(name, method_ty);
540 }
541 }
542
543 return all_interface_methods;
544 }
545
546 if let Some(bound_types) = trait_bounds.get(&qualified_name) {
547 return bound_types
548 .iter()
549 .flat_map(|interface_ty| {
550 self.get_all_methods_recursive(interface_ty, trait_bounds, visited)
551 })
552 .collect();
553 }
554
555 let mut methods = self
556 .get_own_methods(&qualified_name)
557 .cloned()
558 .unwrap_or_default();
559
560 if let Some(definition) = self.get_definition(&qualified_name)
562 && matches!(definition.body, DefinitionBody::TypeAlias { .. })
563 {
564 let alias_ty = &definition.ty;
565 let underlying = match alias_ty {
566 Type::Forall { body, .. } => body.as_ref(),
567 other => other,
568 };
569 let underlying_key = match underlying {
570 Type::Nominal { id, .. } => Some(id.as_str().to_string()),
571 Type::Simple(kind) => Some(format!("prelude.{}", kind.leaf_name())),
572 Type::Compound { kind, .. } => Some(format!("prelude.{}", kind.leaf_name())),
573 _ => None,
574 };
575 if let Some(k) = underlying_key
579 && k != qualified_name.as_str()
580 {
581 let alias_ty = alias_ty.clone();
582 for (name, method_ty) in
583 self.get_all_methods_recursive(&alias_ty, trait_bounds, visited)
584 {
585 methods.entry(name).or_insert(method_ty);
586 }
587 }
588 }
589
590 methods
591 }
592
593 pub fn get_methods_from_bounds(
594 &self,
595 qualified_name: &str,
596 trait_bounds: &HashMap<Symbol, Vec<Type>>,
597 ) -> MethodSignatures {
598 if let Some(bound_types) = trait_bounds.get(qualified_name) {
599 return bound_types
600 .iter()
601 .flat_map(|interface_ty| self.get_all_methods(interface_ty, trait_bounds))
602 .collect();
603 }
604 MethodSignatures::default()
605 }
606}
607
608fn domain_display_name(qualified: &str) -> String {
609 let Some((module, name)) = qualified.rsplit_once('.') else {
610 return qualified.to_string();
611 };
612 match module.strip_prefix("go:") {
613 Some(go_module) => {
614 let package = go_module.rsplit('/').next().unwrap_or(go_module);
615 format!("{package}.{name}")
616 }
617 None => name.to_string(),
618 }
619}
620
621fn method_lookup_key(ty: &Type) -> Option<Symbol> {
625 match ty {
626 Type::Nominal { id, .. } => Some(id.clone()),
627 Type::Compound { kind, .. } => Some(Symbol::from_parts("prelude", kind.leaf_name())),
628 Type::Simple(kind) => Some(Symbol::from_parts("prelude", kind.leaf_name())),
629 _ => None,
630 }
631}
632
633#[cfg(test)]
634mod closed_domain_tests {
635 use super::*;
636 use syntax::ast::StructKind;
637 use syntax::program::Visibility;
638
639 fn nominal_int(id: &str) -> Type {
640 Type::Nominal {
641 id: Symbol::from_raw(id),
642 params: vec![],
643 underlying_ty: Some(Box::new(Type::Simple(SimpleKind::Int))),
644 }
645 }
646
647 fn struct_def(ty: Type, closed_domain: bool) -> Definition {
648 Definition {
649 visibility: Visibility::Public,
650 ty,
651 name: None,
652 name_span: None,
653 doc: None,
654 body: DefinitionBody::Struct {
655 generics: vec![],
656 fields: vec![],
657 kind: StructKind::Tuple,
658 methods: Default::default(),
659 constructor: None,
660 display: false,
661 closed_domain,
662 },
663 }
664 }
665
666 fn int_const(ty: Type, value: u64) -> Definition {
667 Definition {
668 visibility: Visibility::Public,
669 ty,
670 name: None,
671 name_span: None,
672 doc: None,
673 body: DefinitionBody::Value {
674 allowed_lints: vec![],
675 go_hints: vec![],
676 go_name: None,
677 const_value: Some(Literal::Integer { value, text: None }),
678 },
679 }
680 }
681
682 fn insert(store: &mut Store, module: &str, name: &str, def: Definition) {
683 store.add_module(module);
684 store
685 .get_module_mut(module)
686 .unwrap()
687 .definitions
688 .insert(Symbol::from_raw(name), def);
689 }
690
691 #[test]
692 fn tagged_type_with_members_is_indexed_and_sorted() {
693 let mut store = Store::new();
694 let ty = nominal_int("m.Weekday");
695 insert(&mut store, "m", "m.Weekday", struct_def(ty.clone(), true));
696 insert(&mut store, "m", "m.Saturday", int_const(ty.clone(), 6));
697 insert(&mut store, "m", "m.Sunday", int_const(ty.clone(), 0));
698
699 store.build_closed_domains();
700
701 let domain = store
702 .closed_domains
703 .get("m.Weekday")
704 .expect("tagged type with members should be indexed");
705 assert_eq!(domain.base, SimpleKind::Int);
706 assert_eq!(domain.type_display.as_str(), "Weekday");
707 let names: Vec<&str> = domain
708 .members
709 .iter()
710 .map(|m| m.display_name.as_str())
711 .collect();
712 assert_eq!(names, vec!["Sunday", "Saturday"]);
713 }
714
715 #[test]
716 fn untagged_type_is_absent() {
717 let mut store = Store::new();
718 let ty = nominal_int("m.Plain");
719 insert(&mut store, "m", "m.Plain", struct_def(ty.clone(), false));
720 insert(&mut store, "m", "m.One", int_const(ty, 1));
721
722 store.build_closed_domains();
723
724 assert!(store.closed_domains.is_empty());
725 }
726
727 #[test]
728 fn tagged_type_without_members_records_no_domain() {
729 let mut store = Store::new();
730 insert(
731 &mut store,
732 "m",
733 "m.Empty",
734 struct_def(nominal_int("m.Empty"), true),
735 );
736
737 store.build_closed_domains();
738
739 assert!(!store.closed_domains.contains_key("m.Empty"));
740 }
741
742 #[test]
743 fn const_in_other_module_does_not_widen_domain() {
744 let mut store = Store::new();
745 let ty = nominal_int("lib.Weekday");
746 insert(
747 &mut store,
748 "lib",
749 "lib.Weekday",
750 struct_def(ty.clone(), true),
751 );
752 insert(&mut store, "lib", "lib.Sunday", int_const(ty.clone(), 0));
753 insert(&mut store, "user", "user.Bad", int_const(ty, 99));
754
755 store.build_closed_domains();
756
757 let domain = store.closed_domains.get("lib.Weekday").unwrap();
758 let names: Vec<&str> = domain
759 .members
760 .iter()
761 .map(|m| m.display_name.as_str())
762 .collect();
763 assert_eq!(names, vec!["Sunday"]);
764 }
765}