-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast.rs
More file actions
3287 lines (3091 loc) · 123 KB
/
ast.rs
File metadata and controls
3287 lines (3091 loc) · 123 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Abstract Syntax Tree (AST) for PureScript
//!
//! Similar to the CST but with:
//! - Parentheses removed (replaced by inner value)
//! - Operators desugared to function application
//! - Definition sites on key nodes
use std::collections::{HashMap, HashSet};
use crate::cst::{
self, Associativity, ExportList, FunDep, ImportDecl, ImportList, KindSigSource, ModuleName,
QualifiedIdent, Spanned,
};
use crate::interner::{self, intern, Symbol};
use crate::lexer::token::Ident;
use crate::span::Span;
use crate::typechecker::error::TypeError;
use crate::typechecker::registry::{ModuleExports, ModuleRegistry};
/// Where a name was defined
#[derive(Debug, Clone, PartialEq)]
pub enum DefinitionSite {
Local(Span),
Imported { module: Ident },
}
/// Module
#[derive(Debug, Clone, PartialEq)]
pub struct Module {
pub span: Span,
pub name: Spanned<ModuleName>,
pub exports: Option<Spanned<ExportList>>,
pub imports: Vec<ImportDecl>,
pub decls: Vec<Decl>,
}
/// Top-level declaration
#[derive(Debug, Clone, PartialEq)]
pub enum Decl {
/// Value declaration: foo = bar
Value {
span: Span,
name: Spanned<Ident>,
binders: Vec<Binder>,
guarded: GuardedExpr,
where_clause: Vec<LetBinding>,
},
/// Type signature: foo :: Int -> Int
TypeSignature {
span: Span,
name: Spanned<Ident>,
ty: TypeExpr,
},
/// Data declaration: data Foo a = Bar a | Baz
Data {
span: Span,
name: Spanned<Ident>,
type_vars: Vec<Spanned<Ident>>,
constructors: Vec<DataConstructor>,
kind_sig: KindSigSource,
is_role_decl: bool,
kind_type: Option<Box<TypeExpr>>,
type_var_kind_anns: Vec<Option<Box<TypeExpr>>>,
},
/// Type synonym: type Foo = Bar
TypeAlias {
span: Span,
name: Spanned<Ident>,
type_vars: Vec<Spanned<Ident>>,
ty: TypeExpr,
type_var_kind_anns: Vec<Option<Box<TypeExpr>>>,
},
/// Newtype: newtype Foo = Foo Bar
Newtype {
span: Span,
name: Spanned<Ident>,
type_vars: Vec<Spanned<Ident>>,
constructor: Spanned<Ident>,
ty: TypeExpr,
type_var_kind_anns: Vec<Option<Box<TypeExpr>>>,
},
/// Type class declaration: class Eq a where ...
Class {
span: Span,
constraints: Vec<Constraint>,
name: Spanned<Ident>,
type_vars: Vec<Spanned<Ident>>,
fundeps: Vec<FunDep>,
members: Vec<ClassMember>,
is_kind_sig: bool,
kind_type: Option<Box<TypeExpr>>,
type_var_kind_anns: Vec<Option<Box<TypeExpr>>>,
},
/// Instance declaration: instance Eq Int where ...
Instance {
span: Span,
name: Option<Spanned<Ident>>,
constraints: Vec<Constraint>,
class_name: QualifiedIdent,
class_definition_site: DefinitionSite,
types: Vec<TypeExpr>,
members: Vec<Decl>,
chain: bool,
},
/// Fixity declaration: infixl 6 add as +
Fixity {
span: Span,
associativity: Associativity,
precedence: u8,
target: QualifiedIdent,
target_definition_site: DefinitionSite,
operator: Spanned<Ident>,
is_type: bool,
},
/// Foreign value import: foreign import foo :: Type
Foreign {
span: Span,
name: Spanned<Ident>,
ty: TypeExpr,
},
/// Foreign data import: foreign import data Foo :: Kind
ForeignData {
span: Span,
name: Spanned<Ident>,
kind: TypeExpr,
},
/// Derive instance declaration: derive instance Eq MyType
Derive {
span: Span,
newtype: bool,
name: Option<Spanned<Ident>>,
constraints: Vec<Constraint>,
class_name: QualifiedIdent,
class_definition_site: DefinitionSite,
types: Vec<TypeExpr>,
},
}
/// Data constructor in data declaration
#[derive(Debug, Clone, PartialEq)]
pub struct DataConstructor {
pub span: Span,
pub name: Spanned<Ident>,
pub fields: Vec<TypeExpr>,
}
/// Class member (method signature)
#[derive(Debug, Clone, PartialEq)]
pub struct ClassMember {
pub span: Span,
pub name: Spanned<Ident>,
pub ty: TypeExpr,
}
/// Guarded expression (for pattern matching)
#[derive(Debug, Clone, PartialEq)]
pub enum GuardedExpr {
Unconditional(Box<Expr>),
Guarded(Vec<Guard>),
}
/// Guard in pattern matching
#[derive(Debug, Clone, PartialEq)]
pub struct Guard {
pub span: Span,
pub patterns: Vec<GuardPattern>,
pub expr: Box<Expr>,
}
/// Pattern in guard
#[derive(Debug, Clone, PartialEq)]
pub enum GuardPattern {
Boolean(Box<Expr>),
Pattern(Binder, Box<Expr>),
}
/// Expression
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
/// Variable: x, Data.Array.head
Var {
span: Span,
name: QualifiedIdent,
definition_site: DefinitionSite,
},
/// Constructor: Just, Nothing
Constructor {
span: Span,
name: QualifiedIdent,
definition_site: DefinitionSite,
},
/// Literal value
Literal { span: Span, lit: Literal },
/// Function application: f x
App {
span: Span,
func: Box<Expr>,
arg: Box<Expr>,
},
/// Visible type application: f @Type
VisibleTypeApp {
span: Span,
func: Box<Expr>,
ty: TypeExpr,
},
/// Lambda: \x -> x + 1
Lambda {
span: Span,
binders: Vec<Binder>,
body: Box<Expr>,
},
/// If-then-else
If {
span: Span,
cond: Box<Expr>,
then_expr: Box<Expr>,
else_expr: Box<Expr>,
},
/// Case expression
Case {
span: Span,
exprs: Vec<Expr>,
alts: Vec<CaseAlternative>,
},
/// Let binding
Let {
span: Span,
bindings: Vec<LetBinding>,
body: Box<Expr>,
},
/// Do notation
Do {
span: Span,
module: Option<Ident>,
statements: Vec<DoStatement>,
},
Ado {
span: Span,
module: Option<Ident>,
statements: Vec<DoStatement>,
result: Box<Expr>,
},
/// Record literal: { x: 1, y: 2 }
Record {
span: Span,
fields: Vec<RecordField>,
},
/// Record accessor: rec.field
RecordAccess {
span: Span,
expr: Box<Expr>,
field: Spanned<Ident>,
},
/// Record update: rec { x = 1 }
RecordUpdate {
span: Span,
expr: Box<Expr>,
updates: Vec<RecordUpdate>,
},
/// Type annotation: expr :: Type
TypeAnnotation {
span: Span,
expr: Box<Expr>,
ty: TypeExpr,
},
/// Typed hole: ?hole
Hole { span: Span, name: Ident },
/// Wildcard: _ (anonymous argument, NOT a typed hole)
Wildcard { span: Span },
/// Array literal: [1, 2, 3]
Array { span: Span, elements: Vec<Expr> },
/// Negation: -x
Negate { span: Span, expr: Box<Expr> },
/// As-pattern expression: name@pattern
AsPattern {
span: Span,
name: Box<Expr>,
pattern: Box<Expr>,
},
}
/// Literal values
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
Int(i64),
Float(f64),
String(String),
Char(char),
Boolean(bool),
Array(Vec<Expr>),
}
/// Pattern binder
#[derive(Debug, Clone, PartialEq)]
pub enum Binder {
/// Wildcard: _
Wildcard { span: Span },
/// Variable: x
Var { span: Span, name: Spanned<Ident> },
/// Literal pattern: 42, "foo"
Literal { span: Span, lit: Literal },
/// Constructor pattern: Just x (also used for desugared operator patterns)
Constructor {
span: Span,
name: QualifiedIdent,
args: Vec<Binder>,
definition_site: DefinitionSite,
},
/// Record pattern: { x, y }
Record {
span: Span,
fields: Vec<RecordBinderField>,
},
/// As-pattern: x@(Just y)
As {
span: Span,
name: Spanned<Ident>,
binder: Box<Binder>,
},
/// Array pattern: [a, b, c]
Array { span: Span, elements: Vec<Binder> },
/// Type-annotated pattern: (x :: Type)
Typed {
span: Span,
binder: Box<Binder>,
ty: TypeExpr,
},
}
/// Case alternative
#[derive(Debug, Clone, PartialEq)]
pub struct CaseAlternative {
pub span: Span,
pub binders: Vec<Binder>,
pub result: GuardedExpr,
}
/// Let binding
#[derive(Debug, Clone, PartialEq)]
pub enum LetBinding {
/// Value binding: x = expr
Value {
span: Span,
binder: Binder,
expr: Expr,
},
/// Type signature: x :: Type
Signature {
span: Span,
name: Spanned<Ident>,
ty: TypeExpr,
},
}
/// Do statement
#[derive(Debug, Clone, PartialEq)]
pub enum DoStatement {
/// Bind: x <- action
Bind {
span: Span,
binder: Binder,
expr: Expr,
},
/// Let: let x = expr
Let {
span: Span,
bindings: Vec<LetBinding>,
},
/// Expression statement: action
Discard { span: Span, expr: Expr },
}
/// Record field in literal
#[derive(Debug, Clone, PartialEq)]
pub struct RecordField {
pub span: Span,
pub label: Spanned<Ident>,
pub value: Option<Expr>,
pub type_ann: Option<TypeExpr>,
pub is_update: bool,
}
/// Record update
#[derive(Debug, Clone, PartialEq)]
pub struct RecordUpdate {
pub span: Span,
pub label: Spanned<Ident>,
pub value: Expr,
}
/// Record binder field
#[derive(Debug, Clone, PartialEq)]
pub struct RecordBinderField {
pub span: Span,
pub label: Spanned<Ident>,
pub binder: Option<Binder>,
}
/// Type expression
#[derive(Debug, Clone, PartialEq)]
pub enum TypeExpr {
/// Type variable: a
Var { span: Span, name: Spanned<Ident> },
/// Type constructor: Int, Array
Constructor {
span: Span,
name: QualifiedIdent,
definition_site: DefinitionSite,
},
/// Type application: Array Int
App {
span: Span,
constructor: Box<TypeExpr>,
arg: Box<TypeExpr>,
},
/// Function type: Int -> String
Function {
span: Span,
from: Box<TypeExpr>,
to: Box<TypeExpr>,
},
/// Forall quantification: forall a. a -> a
Forall {
span: Span,
vars: Vec<(Spanned<Ident>, bool, Option<Box<TypeExpr>>)>,
ty: Box<TypeExpr>,
},
/// Constrained type: Show a => a -> String
Constrained {
span: Span,
constraints: Vec<Constraint>,
ty: Box<TypeExpr>,
},
/// Record type: { x :: Int, y :: String }
Record { span: Span, fields: Vec<TypeField> },
/// Row type: (), (a :: String), ( x :: Int | r )
Row {
span: Span,
fields: Vec<TypeField>,
tail: Option<Box<TypeExpr>>,
is_record: bool,
},
/// Type hole: ?hole
Hole { span: Span, name: Ident },
/// Wildcard type: _
Wildcard { span: Span },
/// Kind annotation: Const Void :: Type -> Type
Kinded {
span: Span,
ty: Box<TypeExpr>,
kind: Box<TypeExpr>,
},
/// Type-level string literal: "hello"
StringLiteral { span: Span, value: String },
/// Type-level integer literal: 42
IntLiteral { span: Span, value: i64 },
/// Array pattern parsed in type context (for as-patterns via VTA)
ArrayPattern { span: Span, elements: Vec<TypeExpr> },
/// As-pattern parsed in type context (for nested as-patterns in VTA)
AsPattern { span: Span, name: Spanned<Ident>, ty: Box<TypeExpr> },
}
/// Type constraint (for type classes)
#[derive(Debug, Clone, PartialEq)]
pub struct Constraint {
pub span: Span,
pub class: QualifiedIdent,
pub args: Vec<TypeExpr>,
pub definition_site: DefinitionSite,
}
/// Type field in record/row
#[derive(Debug, Clone, PartialEq)]
pub struct TypeField {
pub span: Span,
pub label: Spanned<Ident>,
pub ty: TypeExpr,
}
// --- span() impls ---
impl Decl {
pub fn span(&self) -> Span {
match self {
Decl::Value { span, .. }
| Decl::TypeSignature { span, .. }
| Decl::Data { span, .. }
| Decl::TypeAlias { span, .. }
| Decl::Newtype { span, .. }
| Decl::Class { span, .. }
| Decl::Instance { span, .. }
| Decl::Fixity { span, .. }
| Decl::Foreign { span, .. }
| Decl::ForeignData { span, .. }
| Decl::Derive { span, .. } => *span,
}
}
pub fn name(&self) -> Option<Symbol> {
match self {
Decl::Value { name, .. }
| Decl::TypeSignature { name, .. }
| Decl::Data { name, .. }
| Decl::TypeAlias { name, .. }
| Decl::Newtype { name, .. }
| Decl::Class { name, .. } => Some(name.value),
Decl::Instance {
name: Some(name), ..
} => Some(name.value),
_ => None,
}
}
}
impl Expr {
pub fn span(&self) -> Span {
match self {
Expr::Var { span, .. }
| Expr::Constructor { span, .. }
| Expr::Literal { span, .. }
| Expr::App { span, .. }
| Expr::Lambda { span, .. }
| Expr::If { span, .. }
| Expr::Case { span, .. }
| Expr::Let { span, .. }
| Expr::Do { span, .. }
| Expr::Ado { span, .. }
| Expr::Record { span, .. }
| Expr::RecordAccess { span, .. }
| Expr::RecordUpdate { span, .. }
| Expr::TypeAnnotation { span, .. }
| Expr::Hole { span, .. }
| Expr::Wildcard { span, .. }
| Expr::Array { span, .. }
| Expr::Negate { span, .. }
| Expr::AsPattern { span, .. }
| Expr::VisibleTypeApp { span, .. } => *span,
}
}
}
impl Binder {
pub fn span(&self) -> Span {
match self {
Binder::Wildcard { span }
| Binder::Var { span, .. }
| Binder::Literal { span, .. }
| Binder::Constructor { span, .. }
| Binder::Record { span, .. }
| Binder::As { span, .. }
| Binder::Array { span, .. }
| Binder::Typed { span, .. } => *span,
}
}
}
impl TypeExpr {
pub fn span(&self) -> Span {
match self {
TypeExpr::Var { span, .. }
| TypeExpr::Constructor { span, .. }
| TypeExpr::App { span, .. }
| TypeExpr::Function { span, .. }
| TypeExpr::Forall { span, .. }
| TypeExpr::Constrained { span, .. }
| TypeExpr::Record { span, .. }
| TypeExpr::Row { span, .. }
| TypeExpr::Hole { span, .. }
| TypeExpr::Wildcard { span, .. }
| TypeExpr::Kinded { span, .. }
| TypeExpr::StringLiteral { span, .. }
| TypeExpr::IntLiteral { span, .. }
| TypeExpr::ArrayPattern { span, .. }
| TypeExpr::AsPattern { span, .. } => *span,
}
}
}
impl DoStatement {
pub fn span(&self) -> Span {
match self {
DoStatement::Bind { span, .. }
| DoStatement::Let { span, .. }
| DoStatement::Discard { span, .. } => *span,
}
}
}
// ===== CST → AST Conversion =====
pub fn convert(module: impl std::borrow::Borrow<cst::Module>, registry: &ModuleRegistry) -> (Module, Vec<TypeError>) {
let module = module.borrow();
let mut conv = Converter::from_module(module, registry);
let decls = module.decls.iter().map(|d| conv.convert_decl(d)).collect();
let ast = Module {
span: module.span,
name: module.name.clone(),
exports: module.exports.clone(),
imports: module.imports.clone(),
decls,
};
(ast, conv.errors)
}
/// Convert a standalone CST expression to an AST expression.
/// Uses a minimal converter with no operator fixity info or definition sites.
/// Suitable for standalone expression inference (e.g. in tests).
pub fn convert_expr(expr: cst::Expr) -> Expr {
let mut conv = Converter::default();
conv.convert_expr(&expr)
}
/// Operator in an infix chain: either a named operator/backtick or a complex backtick expression.
enum ChainOp<'a> {
Named(&'a Spanned<QualifiedIdent>),
Expr(&'a cst::Expr),
}
fn chain_op_span(op: &ChainOp) -> Span {
match op {
ChainOp::Named(named) => named.span,
ChainOp::Expr(expr) => expr.span(),
}
}
struct Converter {
/// Module-level values (vars, constructors, methods) → definition site
values: HashMap<Symbol, DefinitionSite>,
/// Module-level type constructors → definition site
types: HashMap<Symbol, DefinitionSite>,
/// Module-level type class names → definition site
classes: HashMap<Symbol, DefinitionSite>,
/// Type-level operators: op symbol → target type name
type_operators: HashMap<Symbol, Symbol>,
/// Type-level operator fixities
type_fixities: HashMap<Symbol, (Associativity, u8)>,
/// Value-level operator fixities
value_fixities: HashMap<Symbol, (Associativity, u8)>,
/// Value-level operator targets: op symbol → target name (e.g. + → add)
value_operator_targets: HashMap<Symbol, QualifiedIdent>,
/// Operators that alias functions (not constructors)
function_op_aliases: HashSet<Symbol>,
/// Definition sites for operator targets (not user-visible, only for operator desugaring).
/// Maps target names (e.g. `add`) to their definition sites.
operator_target_sites: HashMap<Symbol, DefinitionSite>,
/// Local variable scopes (pushed/popped during walk)
local_scopes: Vec<HashMap<Symbol, Span>>,
/// Whether we're inside a Parens expression (enables post-rebalance section detection)
in_parens: bool,
errors: Vec<TypeError>,
}
impl Default for Converter {
fn default() -> Self {
Converter {
values: HashMap::new(),
types: HashMap::new(),
classes: HashMap::new(),
type_operators: HashMap::new(),
type_fixities: HashMap::new(),
value_fixities: HashMap::new(),
value_operator_targets: HashMap::new(),
function_op_aliases: HashSet::new(),
operator_target_sites: HashMap::new(),
local_scopes: Vec::new(),
in_parens: false,
errors: Vec::new(),
}
}
}
fn module_name_to_symbol(name: &ModuleName) -> Symbol {
interner::intern_module_name(&name.parts)
}
fn is_prim_module(name: &ModuleName) -> bool {
name.parts.len() == 1 && interner::symbol_eq(name.parts[0], "Prim")
}
fn is_prim_submodule(name: &ModuleName) -> bool {
name.parts.len() >= 2 && interner::symbol_eq(name.parts[0], "Prim")
}
fn qualified_symbol(module: Symbol, name: Symbol) -> Symbol {
interner::intern_qualified(module, name)
}
impl Converter {
fn from_module(module: &cst::Module, registry: &ModuleRegistry) -> Self {
let mut conv = Converter {
values: HashMap::new(),
types: HashMap::new(),
classes: HashMap::new(),
type_operators: HashMap::new(),
type_fixities: HashMap::new(),
value_fixities: HashMap::new(),
value_operator_targets: HashMap::new(),
function_op_aliases: HashSet::new(),
operator_target_sites: HashMap::new(),
local_scopes: Vec::new(),
in_parens: false,
errors: Vec::new(),
};
// 1. Register Prim types (unless module has explicit `import Prim (...)`)
let has_explicit_prim_import = module.imports.iter().any(|imp| {
is_prim_module(&imp.module) && imp.imports.is_some() && imp.qualified.is_none()
});
if !has_explicit_prim_import {
conv.register_prim();
}
// 2. Process imports
conv.process_imports(module, registry);
// 3. Register local declarations
conv.register_local_decls(&module.decls);
conv
}
fn register_prim(&mut self) {
let prim = intern("Prim");
let site = DefinitionSite::Imported { module: prim };
for name in &[
"Int",
"Number",
"String",
"Char",
"Boolean",
"Array",
"Record",
"Function",
"Type",
"Constraint",
"Symbol",
"Row",
] {
self.types.insert(intern(name), site.clone());
// Also register with "Prim." qualifier for explicit Prim.Array etc. references
self.types
.insert(qualified_symbol(prim, intern(name)), site.clone());
}
// `(->)` is the function type constructor. When fully applied via `(->) a b`,
// convert_type_expr normalizes to Type::fun(a, b).
self.types.insert(intern("->"), site.clone());
// Partial class
self.classes.insert(intern("Partial"), site.clone());
}
/// Register types and classes from a Prim submodule import.
fn register_prim_submodule(&mut self, import_decl: &cst::ImportDecl) {
let qualifier = import_decl.qualified.as_ref().map(module_name_to_symbol);
let mod_sym = module_name_to_symbol(&import_decl.module);
let site = DefinitionSite::Imported { module: mod_sym };
let sub = if import_decl.module.parts.len() >= 2 {
interner::resolve(import_decl.module.parts[1]).unwrap_or_default()
} else {
return;
};
let (type_names, class_names): (&[&str], &[&str]) = match sub.as_str() {
"Boolean" => (&["True", "False"], &[]),
"Coerce" => (&[], &["Coercible"]),
"Int" => (&[], &["Add", "Compare", "Mul", "ToString"]),
"Ordering" => (&["Ordering", "LT", "EQ", "GT"], &[]),
"Row" => (&[], &["Lacks", "Cons", "Nub", "Union"]),
"RowList" => (&["RowList", "Cons", "Nil"], &["RowToList"]),
"Symbol" => (&[], &["Append", "Compare", "Cons"]),
"TypeError" => (
&["Doc", "Beside", "Above", "Text", "Quote", "QuoteLabel"],
&["Fail", "Warn"],
),
_ => (&[], &[]),
};
// Filter based on import list
let allowed: Option<HashSet<Symbol>> = match &import_decl.imports {
None => None, // import all
Some(ImportList::Explicit(items)) => Some(
items
.iter()
.map(|i| match i {
i => i.name(),
})
.collect(),
),
Some(ImportList::Hiding(items)) => {
let hidden: HashSet<Symbol> = items
.iter()
.map(|i| match i {
i => i.name(),
})
.collect();
// Build allowed = all names minus hidden
let all_names: HashSet<Symbol> = type_names
.iter()
.chain(class_names.iter())
.map(|n| intern(n))
.collect();
Some(all_names.difference(&hidden).cloned().collect())
}
};
for name in type_names {
let sym = intern(name);
if allowed.as_ref().map_or(true, |s| s.contains(&sym)) {
let key = Self::maybe_qualify(sym, qualifier);
self.types.insert(key, site.clone());
}
}
for name in class_names {
let sym = intern(name);
if allowed.as_ref().map_or(true, |s| s.contains(&sym)) {
let key = Self::maybe_qualify(sym, qualifier);
self.classes.insert(key, site.clone());
}
}
}
fn process_imports(&mut self, module: &cst::Module, registry: &ModuleRegistry) {
for import_decl in &module.imports {
let module_exports = if is_prim_module(&import_decl.module) {
let prim_site = DefinitionSite::Imported {
module: intern("Prim"),
};
let prim_sym = intern("Prim");
// Register qualifier if present (e.g. import Prim as P).
if let Some(ref qual) = import_decl.qualified {
let q = module_name_to_symbol(qual);
for name in &[
"Int",
"Number",
"String",
"Char",
"Boolean",
"Array",
"Record",
"Function",
"Type",
"Constraint",
"Symbol",
"Row",
] {
self.types
.insert(qualified_symbol(q, intern(name)), prim_site.clone());
}
self.classes
.insert(qualified_symbol(q, intern("Partial")), prim_site.clone());
}
// If explicit `import Prim (X, Y)`, register only the listed items.
// register_prim() was skipped for this case, so we must add them here.
if let Some(ImportList::Explicit(items)) = &import_decl.imports {
for item in items {
match item {
cst::Import::Type(name, _) => {
let sym = name.value;
self.types.insert(sym, prim_site.clone());
self.types
.insert(qualified_symbol(prim_sym, sym), prim_site.clone());
}
cst::Import::Class(name) => {
let sym = name.value;
self.classes.insert(sym, prim_site.clone());
self.classes
.insert(qualified_symbol(prim_sym, sym), prim_site.clone());
}
cst::Import::Value(name) => {
self.values.insert(name.value, prim_site.clone());
}
cst::Import::TypeOp(name) => {
self.types.insert(name.value, prim_site.clone());
}
}
}
// Always register (->) even for explicit imports
self.types.insert(intern("->"), prim_site.clone());
} else if let Some(ImportList::Hiding(items)) = &import_decl.imports {
// `import Prim hiding (X, Y)` — register all Prim types/classes
// except the hidden ones.
let hidden: HashSet<Symbol> = items
.iter()
.map(|i| match i {
i => i.name(),
})
.collect();
for name in &[
"Int",
"Number",
"String",
"Char",
"Boolean",
"Array",
"Record",
"Function",
"Type",
"Constraint",
"Symbol",
"Row",
] {
let sym = intern(name);
if !hidden.contains(&sym) {
self.types.insert(sym, prim_site.clone());
self.types
.insert(qualified_symbol(prim_sym, sym), prim_site.clone());
}
}
if !hidden.contains(&intern("Partial")) {
self.classes.insert(intern("Partial"), prim_site.clone());
}
self.types.insert(intern("->"), prim_site.clone());
}
continue;
} else if is_prim_submodule(&import_decl.module) {
// Register Prim submodule types/classes so the AST converter knows about them.
self.register_prim_submodule(import_decl);
continue;
} else {
match registry.lookup(&import_decl.module.parts) {
Some(exports) => exports,
None => {
self.errors.push(TypeError::ModuleNotFound {
span: import_decl.span,
name: module_name_to_symbol(&import_decl.module),
});
continue;
}
}
};
let mod_sym = module_name_to_symbol(&import_decl.module);
let qualifier = import_decl.qualified.as_ref().map(module_name_to_symbol);
let site = DefinitionSite::Imported { module: mod_sym };
match &import_decl.imports {
None => {
self.import_all(module_exports, qualifier, &site);
}
Some(ImportList::Explicit(items)) => {
for item in items {
self.import_item(item, module_exports, qualifier, &site);
}