-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlower.go
More file actions
5374 lines (5008 loc) · 155 KB
/
lower.go
File metadata and controls
5374 lines (5008 loc) · 155 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
package main
import (
"fmt"
"sort"
"strings"
)
// Lowerer converts an AST Program into an IR Program.
// It resolves names, constructors, builtins, shadowing, and match kinds.
type Lowerer struct {
types map[string]TypeDecl
typeAliases map[string]TypeAliasDecl
traits map[string]TraitDecl
impls map[string][]ImplDecl // keyed by target type name
ctorTypes map[string]string // constructor name → type name
fnNames map[string]string // arca name → Go name for pub functions
functions map[string]FnDecl
moduleNames map[string]bool
goModule string
typeResolver TypeResolver
goPackages map[string]*GoPackage // short name → Go package info (carries Pos/SideEffect/Used)
// Per-function state
currentRetType Type
currentIRRetType IRType // overrides currentRetType when set (for try blocks with type vars)
currentReceiver string
currentTypeName string
matchHint IRType // type hint for match arm bodies
// Collected during lowering
imports []IRImport
builtins map[string]bool
tmpCounter int
errors []CompileError
symbols []SymbolInfo // all symbols (flat, for LSP global list)
rootScope *Scope // root of scope tree (preserved after lowering)
currentScope *Scope // current scope during lowering
// HM type inference — per-function scope
infer *InferScope
}
// --- HM type inference ---
// InferScope holds type inference state for a single function body.
type InferScope struct {
varCounter int
substitution map[int]IRType
typeParamVars map[string]int
}
func NewInferScope() *InferScope {
return &InferScope{
substitution: make(map[int]IRType),
typeParamVars: make(map[string]int),
}
}
func (s *InferScope) freshTypeVar() IRTypeVar {
s.varCounter++
return IRTypeVar{ID: s.varCounter}
}
func (s *InferScope) resolve(t IRType) IRType {
tv, ok := t.(IRTypeVar)
if !ok {
return t
}
if resolved, exists := s.substitution[tv.ID]; exists {
r := s.resolve(resolved)
s.substitution[tv.ID] = r // path compression
return r
}
return t
}
func (s *InferScope) resolveDeep(t IRType) IRType {
if t == nil {
return nil
}
t = s.resolve(t)
switch tt := t.(type) {
case IRResultType:
return IRResultType{Ok: s.resolveDeep(tt.Ok), Err: s.resolveDeep(tt.Err)}
case IROptionType:
return IROptionType{Inner: s.resolveDeep(tt.Inner)}
case IRListType:
return IRListType{Elem: s.resolveDeep(tt.Elem)}
case IRTupleType:
elems := make([]IRType, len(tt.Elements))
for i, e := range tt.Elements {
elems[i] = s.resolveDeep(e)
}
return IRTupleType{Elements: elems}
case IRPointerType:
return IRPointerType{Inner: s.resolveDeep(tt.Inner)}
case IRRefType:
return IRRefType{Inner: s.resolveDeep(tt.Inner)}
case IRNamedType:
if len(tt.Params) == 0 {
return tt
}
params := make([]IRType, len(tt.Params))
for i, p := range tt.Params {
params[i] = s.resolveDeep(p)
}
return IRNamedType{GoName: tt.GoName, Params: params}
default:
return t
}
}
func (s *InferScope) unify(a, b IRType) bool {
a = s.resolve(a)
b = s.resolve(b)
if a == nil || b == nil {
return true
}
if av, ok := a.(IRTypeVar); ok {
s.substitution[av.ID] = b
return true
}
if bv, ok := b.(IRTypeVar); ok {
s.substitution[bv.ID] = a
return true
}
if _, ok := a.(IRInterfaceType); ok {
return true
}
if _, ok := b.(IRInterfaceType); ok {
return true
}
switch at := a.(type) {
case IRNamedType:
if bt, ok := b.(IRNamedType); ok {
if at.GoName != bt.GoName || len(at.Params) != len(bt.Params) {
return false
}
for i := range at.Params {
if !s.unify(at.Params[i], bt.Params[i]) {
return false
}
}
return true
}
// Go stdlib `error` unifies with Arca's Error trait: same runtime
// representation in Go return positions.
if at.GoName == "error" {
if bt, ok := b.(IRTraitType); ok {
return bt.Name == "Error"
}
}
return false
case IRResultType:
bt, ok := b.(IRResultType)
if !ok {
return false
}
return s.unify(at.Ok, bt.Ok) && s.unify(at.Err, bt.Err)
case IROptionType:
bt, ok := b.(IROptionType)
if !ok {
return false
}
return s.unify(at.Inner, bt.Inner)
case IRListType:
bt, ok := b.(IRListType)
if !ok {
return false
}
return s.unify(at.Elem, bt.Elem)
case IRMapType:
bt, ok := b.(IRMapType)
if !ok {
return false
}
return s.unify(at.Key, bt.Key) && s.unify(at.Value, bt.Value)
case IRTupleType:
bt, ok := b.(IRTupleType)
if !ok || len(at.Elements) != len(bt.Elements) {
return false
}
for i := range at.Elements {
if !s.unify(at.Elements[i], bt.Elements[i]) {
return false
}
}
return true
case IRPointerType:
if bt, ok := b.(IRPointerType); ok {
return s.unify(at.Inner, bt.Inner)
}
// Transitional compat: legacy `*T` Arca syntax parses to IRPointerType,
// while FFI-wrapped positions now produce IRRefType. Both emit as Go *T.
// Keep interchangeable until `*T` user syntax is retired.
if rt, ok := b.(IRRefType); ok {
return s.unify(at.Inner, rt.Inner)
}
return false
case IRRefType:
if bt, ok := b.(IRRefType); ok {
return s.unify(at.Inner, bt.Inner)
}
if pt, ok := b.(IRPointerType); ok {
return s.unify(at.Inner, pt.Inner)
}
return false
case IRTraitType:
if bt, ok := b.(IRTraitType); ok {
return at.Name == bt.Name
}
// Arca trait Error and Go stdlib error (IRNamedType{"error"}) are
// interchangeable in IR: both emit as `error` in return positions
// and interop via auto-shim + __goError wrap.
if at.Name == "Error" {
if bt, ok := b.(IRNamedType); ok {
return bt.GoName == "error"
}
}
return false
}
return false
}
func (s *InferScope) typeParamVar(name string) IRTypeVar {
if id, ok := s.typeParamVars[name]; ok {
return IRTypeVar{ID: id}
}
tv := s.freshTypeVar()
s.typeParamVars[name] = tv.ID
return tv
}
// Lowerer convenience methods that delegate to current InferScope.
func (l *Lowerer) freshTypeVar() IRTypeVar { return l.infer.freshTypeVar() }
func (l *Lowerer) resolve(t IRType) IRType { return l.infer.resolve(t) }
func (l *Lowerer) resolveDeep(t IRType) IRType {
// After Lower() finishes l.infer is nil (withInferScope restores the saved
// nil). LSP-driven partial re-lowering calls resolveDeep outside a live
// infer scope; in that case the type is already concrete (nothing to
// substitute) so returning it unchanged is correct.
if l.infer == nil {
return t
}
return l.infer.resolveDeep(t)
}
func (l *Lowerer) typeParamVar(name string) IRTypeVar { return l.infer.typeParamVar(name) }
// unify runs HM unification on two IR types and reports ErrTypeMismatch at
// pos on failure. This is the type-checking entry point — every call site
// that needs error reporting goes through here.
//
// Raw substitution-only unification (fresh-var binding, hint propagation
// that must not report) uses `l.infer.unify(a, b)` directly instead. That
// makes the intent visible in the call: if you see `l.unify(...)` you are
// type-checking, if you see `l.infer.unify(...)` you are rewriting
// substitution for codegen.
//
// Besides structural HM unification, this wrapper accepts
// constraint-compatible type alias pairs (e.g. AdultAge → Age) at the top
// level so hint-based type checks can flow stricter-to-wider alias values.
func (l *Lowerer) unify(a, b IRType, pos Pos) bool {
if l.infer.unify(a, b) {
return true
}
if l.constraintCompatible(a, b) {
return true
}
if l.traitImplCompatible(a, b) {
return true
}
if l.errorTraitCompatible(a, b) {
return true
}
l.addCompileError(ErrTypeMismatch, pos, TypeMismatchData{
Expected: irTypeDisplayStr(l.resolveDeep(b)),
Actual: irTypeDisplayStr(l.resolveDeep(a)),
})
return false
}
// errorTraitCompatible bridges Arca's Error trait and Go's stdlib `error`
// interface at unify time. Both emit as `error` in Go return positions and
// interop via the auto-generated shim plus __goError wrap, so internal IR
// sites that still reference IRNamedType{"error"} (e.g., try hint defaults,
// some ad-hoc result ctor paths) flow into user-declared Result[_, Error]
// without rewriting every site.
func (l *Lowerer) errorTraitCompatible(a, b IRType) bool {
isError := func(t IRType) bool {
switch tt := l.resolveDeep(t).(type) {
case IRNamedType:
return tt.GoName == "error"
case IRTraitType:
return tt.Name == "Error"
}
return false
}
return isError(a) && isError(b)
}
// traitImplCompatible reports whether a concrete type and a trait type pair
// via a registered `impl Type: Trait`. Symmetric — either side may be the
// trait, since unify is order-agnostic at call sites.
func (l *Lowerer) traitImplCompatible(a, b IRType) bool {
an := l.resolveDeep(a)
bn := l.resolveDeep(b)
if tt, ok := an.(IRTraitType); ok {
if nn, ok := bn.(IRNamedType); ok {
return l.typeImplementsTrait(nn.GoName, tt.Name)
}
}
if tt, ok := bn.(IRTraitType); ok {
if nn, ok := an.(IRNamedType); ok {
return l.typeImplementsTrait(nn.GoName, tt.Name)
}
}
return false
}
func (l *Lowerer) typeImplementsTrait(typeName, traitName string) bool {
for _, impl := range l.impls[typeName] {
if impl.TraitName == traitName {
return true
}
}
return false
}
// constraintCompatible reports whether two resolved named types are related
// by constrained alias widening. Used as a last-ditch success path in unify
// so `AdultAge → Age` hint checks still pass.
func (l *Lowerer) constraintCompatible(a, b IRType) bool {
an, ok := l.resolveDeep(a).(IRNamedType)
if !ok {
return false
}
bn, ok := l.resolveDeep(b).(IRNamedType)
if !ok {
return false
}
return l.isConstraintCompatible(an.GoName, bn.GoName)
}
// withInferScope runs fn with a fresh InferScope, restoring the previous scope after.
func (l *Lowerer) withInferScope(fn func()) {
saved := l.infer
l.infer = NewInferScope()
fn()
l.infer = saved
}
// resolveExprTypes walks an IR expression tree and resolves type variables
// to their concrete types after unification.
// resolveResultExprTypeArgs resolves a Result-typed builtin call's TypeArgs string.
func (l *Lowerer) resolveResultExprTypeArgs(t IRType) (IRType, string) {
resolved := l.resolveDeep(t)
if rt, ok := resolved.(IRResultType); ok {
return resolved, "[" + irTypeEmitStr(rt.Ok) + ", " + irTypeEmitStr(rt.Err) + "]"
}
return resolved, ""
}
// resolveExprs applies resolveExprTypes to a slice in place.
func (l *Lowerer) resolveExprs(es []IRExpr) {
for i := range es {
es[i] = l.resolveExprTypes(es[i])
}
}
func (l *Lowerer) resolveExprTypes(e IRExpr) IRExpr {
if e == nil {
return nil
}
switch expr := e.(type) {
case IRNoneExpr:
resolved := l.resolveDeep(expr.Type)
if ot, ok := resolved.(IROptionType); ok {
expr.TypeArg = "[" + irTypeEmitStr(ot.Inner) + "]"
}
expr.Type = resolved
return expr
case IROkCall:
expr.Type, expr.TypeArgs = l.resolveResultExprTypeArgs(expr.Type)
expr.Value = l.resolveExprTypes(expr.Value)
return expr
case IRErrorCall:
expr.Type, expr.TypeArgs = l.resolveResultExprTypeArgs(expr.Type)
expr.Value = l.resolveExprTypes(expr.Value)
return expr
case IRSomeCall:
expr.Type = l.resolveDeep(expr.Type)
expr.Value = l.resolveExprTypes(expr.Value)
return expr
case IRBlock:
for i, stmt := range expr.Stmts {
expr.Stmts[i] = l.resolveStmtTypes(stmt)
}
expr.Expr = l.resolveExprTypes(expr.Expr)
return expr
case IRMatch:
expr.Subject = l.resolveExprTypes(expr.Subject)
for i := range expr.Arms {
expr.Arms[i].Body = l.resolveExprTypes(expr.Arms[i].Body)
}
expr.Type = l.resolveDeep(expr.Type)
return expr
case IRIfExpr:
expr.Cond = l.resolveExprTypes(expr.Cond)
expr.Then = l.resolveExprTypes(expr.Then)
expr.Else = l.resolveExprTypes(expr.Else)
expr.Type = l.resolveDeep(expr.Type)
return expr
case IRListLit:
resolved := l.resolveDeep(expr.Type)
if lt, ok := resolved.(IRListType); ok {
expr.ElemType = irTypeEmitStr(lt.Elem)
}
expr.Type = resolved
l.resolveExprs(expr.Elements)
return expr
case IRFnCall:
l.resolveExprs(expr.Args)
return expr
case IRMethodCall:
expr.Receiver = l.resolveExprTypes(expr.Receiver)
l.resolveExprs(expr.Args)
return expr
case IRBinaryExpr:
expr.Left = l.resolveExprTypes(expr.Left)
expr.Right = l.resolveExprTypes(expr.Right)
expr.Type = l.resolveDeep(expr.Type)
return expr
case IRLambda:
expr.Body = l.resolveExprTypes(expr.Body)
return expr
case IRTryBlock:
for i, stmt := range expr.Stmts {
expr.Stmts[i] = l.resolveStmtTypes(stmt)
}
expr.Expr = l.resolveExprTypes(expr.Expr)
expr.OkType = l.resolveDeep(expr.OkType)
expr.ErrType = l.resolveDeep(expr.ErrType)
return expr
default:
return e
}
}
func (l *Lowerer) resolveStmtTypes(s IRStmt) IRStmt {
switch stmt := s.(type) {
case IRLetStmt:
stmt.Value = l.resolveExprTypes(stmt.Value)
// For empty lists with inferred type, set Type so emit generates `var x []T`
if stmt.Type == nil {
if ll, ok := stmt.Value.(IRListLit); ok && len(ll.Elements) == 0 && ll.Spread == nil {
if lt, ok := ll.Type.(IRListType); ok {
if _, isTV := lt.Elem.(IRTypeVar); !isTV {
stmt.Type = ll.Type
}
}
}
}
// An unresolved HM type variable in a generic-call RHS means the
// type parameter could not be inferred. Report it here instead of
// letting `interface{}` flow to Go, which would surface downstream
// as confusing method or field errors on `interface{}`. Skipped
// when the user provided an explicit annotation or when the RHS is
// a bare collection literal (empty `[]` / `{}` are allowed to
// default to interface element types).
if stmt.GoName != "_" && stmt.Type == nil && isGenericCall(stmt.Value) {
resolved := l.resolveDeep(stmt.Value.irType())
if containsUnresolvedTypeVar(resolved) {
l.addCompileError(ErrCannotInferTypeParam, stmt.Pos, CannotInferTypeParamData{
Binding: stmt.GoName,
Suggestion: callFuncName(stmt.Value),
})
}
}
return stmt
case IRExprStmt:
stmt.Expr = l.resolveExprTypes(stmt.Expr)
return stmt
case IRTryLetStmt:
stmt.CallExpr = l.resolveExprTypes(stmt.CallExpr)
if stmt.ReturnType != nil {
stmt.ReturnType = l.resolveDeep(stmt.ReturnType)
}
// Same unresolved-type-var check as IRLetStmt: `let x = f()?` where
// f's generic T can't be inferred would otherwise hand `x` to the
// rest of the function with an unresolved type. Try always wraps a
// call, so no literal-value exception is needed here.
if stmt.GoName != "_" && isGenericCall(stmt.CallExpr) {
unwrapped := l.resolveDeep(stmt.CallExpr.irType())
if rt, ok := unwrapped.(IRResultType); ok {
unwrapped = rt.Ok
}
if containsUnresolvedTypeVar(unwrapped) {
pos := callExprPos(stmt.CallExpr)
l.addCompileError(ErrCannotInferTypeParam, pos, CannotInferTypeParamData{
Binding: stmt.GoName,
Suggestion: callFuncName(stmt.CallExpr),
})
}
}
return stmt
default:
return s
}
}
// containsUnresolvedTypeVar reports whether an IR type (after resolveDeep)
// still contains an HM type variable anywhere. Used to detect let bindings
// whose generic type parameter was never pinned down.
func containsUnresolvedTypeVar(t IRType) bool {
switch tt := t.(type) {
case IRTypeVar:
return true
case IRPointerType:
return containsUnresolvedTypeVar(tt.Inner)
case IRRefType:
return containsUnresolvedTypeVar(tt.Inner)
case IRListType:
return containsUnresolvedTypeVar(tt.Elem)
case IRMapType:
return containsUnresolvedTypeVar(tt.Key) || containsUnresolvedTypeVar(tt.Value)
case IROptionType:
return containsUnresolvedTypeVar(tt.Inner)
case IRResultType:
return containsUnresolvedTypeVar(tt.Ok) || containsUnresolvedTypeVar(tt.Err)
case IRTupleType:
for _, e := range tt.Elements {
if containsUnresolvedTypeVar(e) {
return true
}
}
return false
case IRNamedType:
for _, p := range tt.Params {
if containsUnresolvedTypeVar(p) {
return true
}
}
return false
}
return false
}
// callFuncName extracts the function name from an IRFnCall (possibly wrapped
// in a block/if/etc.), for use in diagnostic suggestions.
func callFuncName(e IRExpr) string {
switch expr := e.(type) {
case IRFnCall:
return expr.Func
case IRMethodCall:
return expr.Method
}
return "<call>"
}
// isGenericCall reports whether an expression is a direct function or method
// call — the only RHS kinds where an unresolved type variable legitimately
// points to an uninferrable generic type parameter. Literals like empty `[]`
// default to interface element types and must not trigger the check.
func isGenericCall(e IRExpr) bool {
switch e.(type) {
case IRFnCall, IRMethodCall:
return true
}
return false
}
// callExprPos returns the source position of a call expression's origin.
// Falls back to zero Pos when the expression is not a recognized call.
func callExprPos(e IRExpr) Pos {
if call, ok := e.(IRFnCall); ok {
return call.Source.Pos
}
return Pos{}
}
func (l *Lowerer) addError(pos Pos, format string, args ...interface{}) {
l.errors = append(l.errors, CompileError{
Pos: pos,
Phase: "lower",
Data: MessageData{Text: fmt.Sprintf(format, args...)},
})
}
func (l *Lowerer) addCompileError(code ErrorCode, pos Pos, data ErrorData) {
l.errors = append(l.errors, CompileError{Code: code, Pos: pos, Phase: "lower", Data: data})
}
func (l *Lowerer) recordSymbol(name string, t Type, kind string) {
l.symbols = append(l.symbols, SymbolInfo{Name: name, Type: t, Kind: kind})
}
// registerSymbol registers a data symbol (variable, parameter, binding) with both
// AST and IR types. All variable bindings must go through this function.
// Returns the resolved Go name (with shadowing suffix if needed).
func (l *Lowerer) registerSymbol(info SymbolRegInfo) string {
sym := NewSymbolInfo(info.Name, info.Kind)
// Same-scope shadowing: suffix with count
if l.currentScope != nil {
count := l.currentScope.declCount[sym.GoName]
l.currentScope.declCount[sym.GoName] = count + 1
if count > 0 {
sym.GoName = fmt.Sprintf("%s_%d", sym.GoName, count+1)
}
}
if info.ArcaType != nil {
sym.Type = info.ArcaType
}
if info.IRType != nil {
if _, isInterface := info.IRType.(IRInterfaceType); !isInterface {
sym.IRType = info.IRType
}
}
sym.Pos = info.Pos
// Record in lexical scope
if l.currentScope != nil {
l.currentScope.Define(info.Name, &sym)
}
// Record in flat list (for LSP global queries)
l.symbols = append(l.symbols, sym)
return sym.GoName
}
type SymbolRegInfo struct {
Name string
ArcaType Type // nullable
IRType IRType // nullable
Kind string // SymVariable, SymParameter, etc.
Pos Pos // definition position (for LSP go to definition)
}
func (l *Lowerer) withScope(startPos, endPos Pos, symbols []SymbolRegInfo, fn func()) {
l.currentScope = NewScope(l.currentScope)
l.currentScope.StartPos = startPos
l.currentScope.EndPos = endPos
defer func() { l.currentScope = l.currentScope.parent }()
for _, s := range symbols {
l.registerSymbol(s)
}
fn()
}
// LookupSymbol finds a symbol by name in the current lexical scope chain.
// Falls back to flat symbol list if no scope is active.
func (l *Lowerer) LookupSymbol(name string) *SymbolInfo {
if l.currentScope != nil {
return l.currentScope.Lookup(name)
}
// Fallback: flat search
for i := len(l.symbols) - 1; i >= 0; i-- {
if l.symbols[i].Name == name {
return &l.symbols[i]
}
}
return nil
}
// FindSymbolAt finds a symbol by name at a specific source position,
// using the scope tree to resolve lexical scoping.
func (l *Lowerer) FindSymbolAt(name string, pos Pos) *SymbolInfo {
if l.rootScope != nil {
scope := l.rootScope.FindScopeAt(pos)
return scope.Lookup(name)
}
return l.LookupSymbol(name)
}
// Types returns the collected type declarations.
func (l *Lowerer) Types() map[string]TypeDecl { return l.types }
// TypeAliases returns the collected type alias declarations.
func (l *Lowerer) TypeAliases() map[string]TypeAliasDecl { return l.typeAliases }
// Functions returns the collected function declarations.
func (l *Lowerer) Functions() map[string]FnDecl { return l.functions }
// GoPackages returns the collected Go package imports.
func (l *Lowerer) GoPackages() map[string]*GoPackage { return l.goPackages }
// lookupGoPackage returns the Go package for a short name and marks it used.
// Use this instead of direct l.goPackages[name] access at resolution sites so
// unused-import diagnostics work correctly.
func (l *Lowerer) lookupGoPackage(name string) (*GoPackage, bool) {
pkg, ok := l.goPackages[name]
if ok {
pkg.Used = true
}
return pkg, ok
}
// TypeResolver returns the type resolver for Go FFI lookups.
func (l *Lowerer) TypeResolver() TypeResolver { return l.typeResolver }
func (l *Lowerer) Errors() []CompileError {
return l.errors
}
func NewLowerer(prog *Program, goModule string, resolver TypeResolver) *Lowerer {
if resolver == nil {
resolver = NullTypeResolver{}
}
root := NewScope(nil)
l := &Lowerer{
types: make(map[string]TypeDecl),
typeAliases: make(map[string]TypeAliasDecl),
traits: make(map[string]TraitDecl),
impls: make(map[string][]ImplDecl),
ctorTypes: make(map[string]string),
fnNames: make(map[string]string),
functions: make(map[string]FnDecl),
moduleNames: make(map[string]bool),
builtins: make(map[string]bool),
goModule: goModule,
typeResolver: resolver,
rootScope: root,
currentScope: root,
}
registerPreludeTraits(l)
for _, decl := range prog.Decls {
switch d := decl.(type) {
case TypeDecl:
l.types[d.Name] = d
for _, ctor := range d.Constructors {
l.ctorTypes[ctor.Name] = d.Name
}
case TypeAliasDecl:
l.typeAliases[d.Name] = d
case ImportDecl:
if strings.HasPrefix(d.Path, "go/") {
pkg := NewGoPackage(d.Path[3:])
pkg.Pos = d.Pos
pkg.SideEffect = d.SideEffect
if l.goPackages == nil {
l.goPackages = make(map[string]*GoPackage)
}
l.goPackages[pkg.ShortName] = pkg
l.registerSymbol(SymbolRegInfo{Name: pkg.ShortName, Kind: SymPackage, Pos: d.Pos})
l.imports = append(l.imports, IRImport{
Path: pkg.FullPath,
SideEffect: d.SideEffect,
})
if !isStdLib(pkg.FullPath) && !l.typeResolver.CanLoadPackage(pkg.FullPath) {
l.addCompileError(ErrPackageNotFound, d.Pos, PackageNotFoundData{Path: pkg.FullPath})
}
break
}
// Arca built-in package: import stdlib, import stdlib.db, etc.
rootName := strings.Split(d.Path, ".")[0]
if pkg := lookupArcaPackage(rootName); pkg != nil {
if l.goPackages == nil {
l.goPackages = make(map[string]*GoPackage)
}
goPkg := NewGoPackage(pkg.GoModPath)
goPkg.Pos = d.Pos
l.goPackages[pkg.Name] = goPkg
l.registerSymbol(SymbolRegInfo{Name: pkg.Name, Kind: SymPackage, Pos: d.Pos})
l.imports = append(l.imports, IRImport{Path: pkg.GoModPath})
break
}
// Arca module: import user, import user.{find}
parts := strings.Split(d.Path, ".")
l.moduleNames[parts[len(parts)-1]] = true
case FnDecl:
l.functions[d.Name] = d
if d.Public {
l.fnNames[d.Name] = snakeToPascal(d.Name)
}
l.registerSymbol(SymbolRegInfo{Name: d.Name, Kind: SymFunction, Pos: d.NamePos})
case TraitDecl:
l.traits[d.Name] = d
case ImplDecl:
l.impls[d.TypeName] = append(l.impls[d.TypeName], d)
}
}
return l
}
// Lower converts the entire program.
// pkgName is the Go package name ("main" for main files).
// pubOnly limits function output to pub functions only (for same-dir module files).
func (l *Lowerer) Lower(prog *Program, pkgName string, pubOnly bool) IRProgram {
var types []IRTypeDecl
var funcs []IRFuncDecl
for _, decl := range prog.Decls {
switch d := decl.(type) {
case TypeDecl:
types = append(types, l.lowerTypeDecl(d))
for _, method := range d.Methods {
funcs = append(funcs, l.lowerMethod(d, method)...)
}
case TypeAliasDecl:
types = append(types, l.lowerTypeAliasDecl(d))
case FnDecl:
if d.ReceiverType == "" {
if pubOnly && !d.Public {
continue
}
funcs = append(funcs, l.lowerFnDecl(d))
}
case TraitDecl:
types = append(types, l.lowerTraitDecl(d))
case ImplDecl:
funcs = append(funcs, l.lowerImplDecl(d)...)
}
}
// Error is the one trait that maps to Go's stdlib `error` interface
// (see irTypeStr). No ArcaError interface is emitted — user code calls
// trait methods via __goError wrap at match bindings / method-call sites.
// The prelude-registered Error trait exists at the lowerer level only,
// for type checking; it never surfaces as a Go type declaration.
l.checkMethodCollisions()
// Expand sum type methods to per-variant implementations
funcs = l.expandSumTypeMethods(funcs)
// Expand Result/Option in the IR: tail-position Ok/Error/Some/None
// become IRMultiReturn, let bindings of multi-return calls become
// IRMultiLetStmt, and Ok/Error/Some/None in call args are flattened.
// After this pass, emit.go can mechanically output native Go without
// knowing about Result/Option semantics.
for i := range funcs {
ctx := newExpandCtx()
expandFuncParams(&funcs[i], ctx)
funcs[i].Body = expandWithCtx(funcs[i].Body, funcs[i].ReturnType, ctx)
}
// Report unused imports (skip side-effect imports, which are intentional,
// and packages consumed indirectly via auto-detected builtins like string
// interpolation needing fmt). Sort for deterministic diagnostic order.
var unusedNames []string
for name, pkg := range l.goPackages {
if pkg.SideEffect || pkg.Used || l.builtins[name] {
continue
}
unusedNames = append(unusedNames, name)
}
sort.Strings(unusedNames)
for _, name := range unusedNames {
pkg := l.goPackages[name]
l.addCompileError(ErrUnusedPackage, pkg.Pos, UnusedPackageData{Name: name})
}
// Collect builtin names
var builtinNames []string
for name := range l.builtins {
builtinNames = append(builtinNames, name)
}
// Build final imports including auto-detected ones
imports := make([]IRImport, len(l.imports))
copy(imports, l.imports)
if l.builtins["fmt"] && !l.hasImport("fmt") {
imports = append(imports, IRImport{Path: "fmt"})
}
if l.builtins["regexp"] {
imports = append(imports, IRImport{Path: "regexp"})
}
if l.builtins["os"] && !l.hasImport("os") {
imports = append(imports, IRImport{Path: "os"})
}
return IRProgram{
Package: pkgName,
Imports: imports,
Types: types,
Funcs: funcs,
Builtins: builtinNames,
}
}
func (l *Lowerer) hasImport(pkg string) bool {
for _, imp := range l.imports {
if imp.Path == pkg {
return true
}
}
return false
}
// --- Type Declarations ---
func (l *Lowerer) lowerTypeDecl(td TypeDecl) IRTypeDecl {
// Set currentTypeName so isTypeParam resolves generic params (e.g. A, B).
prev := l.currentTypeName
l.currentTypeName = td.Name
defer func() { l.currentTypeName = prev }()
// Check field types exist in all constructors
for _, ctor := range td.Constructors {
for _, f := range ctor.Fields {
l.checkTypeExists(f.Type)
}
}
// Check method signature types
for _, m := range td.Methods {
for _, p := range m.Params {
if p.Type != nil {
l.checkTypeExists(p.Type)
}
}
if m.ReturnType != nil {
l.checkTypeExists(m.ReturnType)
}
}
if isEnum(td) {
return l.lowerEnumDecl(td)
}
if len(td.Constructors) == 1 {
return l.lowerStructDecl(td)
}
return l.lowerSumTypeDecl(td)
}
func (l *Lowerer) lowerEnumDecl(td TypeDecl) IREnumDecl {
variants := make([]string, len(td.Constructors))
for i, c := range td.Constructors {
variants[i] = c.Name
}
return IREnumDecl{
GoName: td.Name,
Variants: variants,
}
}
func (l *Lowerer) lowerStructDecl(td TypeDecl) IRStructDecl {
ctor := td.Constructors[0]
fields := make([]IRFieldDecl, len(ctor.Fields))
for i, f := range ctor.Fields {
tag := l.genStructTagFromRules(f.Name, td.Tags)
fields[i] = IRFieldDecl{
GoName: capitalize(f.Name),
Type: l.lowerType(f.Type),
Tag: tag,
}
}
var validator *IRValidator
if l.hasConstraints(td) {
validator = l.buildStructValidator(td)
}
return IRStructDecl{
GoName: td.Name,
TypeParams: td.Params,
Fields: fields,
Tags: td.Tags,
Validator: validator,
}
}
func (l *Lowerer) lowerSumTypeDecl(td TypeDecl) IRSumTypeDecl {
variants := make([]IRVariantDecl, len(td.Constructors))
for i, c := range td.Constructors {
fields := make([]IRFieldDecl, len(c.Fields))
for j, f := range c.Fields {
fields[j] = IRFieldDecl{
GoName: capitalize(f.Name),
Type: l.lowerType(f.Type),
}
}
variants[i] = IRVariantDecl{
GoName: td.Name + c.Name,
Fields: fields,
}
}
// Collect method signatures for interface definition
var ifaceMethods []IRInterfaceMethod
for _, m := range td.Methods {
if !m.Static {
name := snakeToCamel(m.Name)
if m.Public {
name = snakeToPascal(m.Name)
}
var retType IRType
if m.ReturnType != nil {
retType = l.lowerType(m.ReturnType)
}
ifaceMethods = append(ifaceMethods, IRInterfaceMethod{
Name: name,
Params: l.lowerParams(m.Params),
ReturnType: retType,