-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathtypechecker.go
More file actions
6810 lines (6148 loc) · 209 KB
/
typechecker.go
File metadata and controls
6810 lines (6148 loc) · 209 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 typechecker
// Copyright (c) 2025-Present Marshall A Burns
// Licensed under the MIT License. See LICENSE for details.
import (
"fmt"
"math/big"
"sort"
"strconv"
"strings"
"github.com/marshallburns/ez/pkg/ast"
"github.com/marshallburns/ez/pkg/errors"
)
// TypeKind represents the category of a type
type TypeKind int
const (
PrimitiveType TypeKind = iota
ArrayType
MapType
StructType
EnumType
FunctionType
VoidType
)
// Scope represents a lexical scope for variable tracking
type Scope struct {
parent *Scope
variables map[string]string // variable name -> type name
mutability map[string]bool // variable name -> is mutable
usingModules map[string]bool // modules imported via 'using'
}
// NewScope creates a new scope with an optional parent
func NewScope(parent *Scope) *Scope {
return &Scope{
parent: parent,
variables: make(map[string]string),
mutability: make(map[string]bool),
usingModules: make(map[string]bool),
}
}
// Define adds a variable to the current scope (defaults to immutable)
func (s *Scope) Define(name, typeName string) {
s.variables[name] = typeName
s.mutability[name] = false
}
// DefineWithMutability adds a variable to the current scope with explicit mutability
func (s *Scope) DefineWithMutability(name, typeName string, mutable bool) {
s.variables[name] = typeName
s.mutability[name] = mutable
}
// IsMutable checks if a variable is mutable in the current scope or any parent scope
func (s *Scope) IsMutable(name string) (bool, bool) {
if mutable, ok := s.mutability[name]; ok {
return mutable, true
}
if s.parent != nil {
return s.parent.IsMutable(name)
}
return false, false
}
// Lookup finds a variable in the current scope or any parent scope
func (s *Scope) Lookup(name string) (string, bool) {
if typeName, ok := s.variables[name]; ok {
return typeName, true
}
if s.parent != nil {
return s.parent.Lookup(name)
}
return "", false
}
// AddUsingModule adds a module to the current scope's using list
func (s *Scope) AddUsingModule(moduleName string) {
s.usingModules[moduleName] = true
}
// HasUsingModule checks if a module is in scope via 'using'
func (s *Scope) HasUsingModule(moduleName string) bool {
if s.usingModules[moduleName] {
return true
}
if s.parent != nil {
return s.parent.HasUsingModule(moduleName)
}
return false
}
// GetAllUsingModules returns all modules imported via 'using' in the current scope and parent scopes
func (s *Scope) GetAllUsingModules() []string {
result := make([]string, 0)
seen := make(map[string]bool)
// Collect from current scope
for moduleName := range s.usingModules {
if !seen[moduleName] {
result = append(result, moduleName)
seen[moduleName] = true
}
}
// Collect from parent scopes
if s.parent != nil {
for _, moduleName := range s.parent.GetAllUsingModules() {
if !seen[moduleName] {
result = append(result, moduleName)
seen[moduleName] = true
}
}
}
return result
}
// Type represents a type in the EZ type system
type Type struct {
Name string
Kind TypeKind
ElementType *Type // For arrays
KeyType *Type // For maps
ValueType *Type // For maps
Fields map[string]*Type // For structs
Size int // For fixed-size arrays, -1 for dynamic
EnumBaseType string // For enums: "int", "string", or "float"
EnumMembers map[string]bool // For enums: set of valid member names (#607)
}
// FunctionSignature represents a function's type signature
type FunctionSignature struct {
Name string
Parameters []*Parameter
ReturnTypes []string
}
// Parameter represents a function parameter with type
type Parameter struct {
Name string
Type string
Mutable bool // true if declared with & prefix
HasDefault bool // true if parameter has a default value
}
// TypeChecker validates types in an EZ program
type TypeChecker struct {
types map[string]*Type // All known types
functions map[string]*FunctionSignature // All function signatures
variables map[string]string // Variable name -> type name (global scope)
modules map[string]bool // Imported module names
fileUsingModules map[string]bool // File-level using modules
moduleFunctions map[string]map[string]*FunctionSignature // Module name -> function name -> signature
moduleTypes map[string]map[string]*Type // Module name -> type name -> type
moduleVariables map[string]map[string]string // Module name -> variable name -> type (#677)
currentScope *Scope // Current scope for local variable tracking
errors *errors.EZErrorList
source string
filename string
skipMainCheck bool // Skip main() function requirement (for module files)
loopDepth int // Track nesting depth of loops for break/continue validation (#603)
currentFuncAttrs []*ast.Attribute // Current function's attributes for #suppress checking
fileSuppressWarnings []string // File-level suppressed warnings (from #suppress at file scope)
currentModuleName string // Current module name for same-module symbol lookup
}
// NewTypeChecker creates a new type checker
func NewTypeChecker(source, filename string) *TypeChecker {
tc := &TypeChecker{
types: make(map[string]*Type),
functions: make(map[string]*FunctionSignature),
variables: make(map[string]string),
modules: make(map[string]bool),
fileUsingModules: make(map[string]bool),
moduleFunctions: make(map[string]map[string]*FunctionSignature),
moduleTypes: make(map[string]map[string]*Type),
moduleVariables: make(map[string]map[string]string),
errors: errors.NewErrorList(),
source: source,
filename: filename,
}
// Register built-in primitive types
tc.registerBuiltinTypes()
return tc
}
// SetSkipMainCheck sets whether to skip the main() function requirement
// Use this for module files that don't need a main() function
func (tc *TypeChecker) SetSkipMainCheck(skip bool) {
tc.skipMainCheck = skip
}
// SetCurrentModule sets the current module name for same-module symbol lookup
// This allows files in the same module to access each other's symbols without qualification
func (tc *TypeChecker) SetCurrentModule(moduleName string) {
tc.currentModuleName = moduleName
}
// RegisterModuleFunction registers a function signature from an imported module
func (tc *TypeChecker) RegisterModuleFunction(moduleName, funcName string, sig *FunctionSignature) {
if tc.moduleFunctions[moduleName] == nil {
tc.moduleFunctions[moduleName] = make(map[string]*FunctionSignature)
}
tc.moduleFunctions[moduleName][funcName] = sig
}
// RegisterModuleType registers a type from an imported module
func (tc *TypeChecker) RegisterModuleType(moduleName, typeName string, t *Type) {
if tc.moduleTypes[moduleName] == nil {
tc.moduleTypes[moduleName] = make(map[string]*Type)
}
tc.moduleTypes[moduleName][typeName] = t
}
// RegisterModuleVariable registers a variable/constant from an imported module (#677)
func (tc *TypeChecker) RegisterModuleVariable(moduleName, varName, typeName string) {
if tc.moduleVariables[moduleName] == nil {
tc.moduleVariables[moduleName] = make(map[string]string)
}
tc.moduleVariables[moduleName][varName] = typeName
}
// GetModuleFunction retrieves a function signature from a module
func (tc *TypeChecker) GetModuleFunction(moduleName, funcName string) (*FunctionSignature, bool) {
if funcs, ok := tc.moduleFunctions[moduleName]; ok {
sig, exists := funcs[funcName]
return sig, exists
}
return nil, false
}
// GetModuleVariable retrieves a variable type from a module (#677)
func (tc *TypeChecker) GetModuleVariable(moduleName, varName string) (string, bool) {
if vars, ok := tc.moduleVariables[moduleName]; ok {
typeName, exists := vars[varName]
return typeName, exists
}
return "", false
}
// GetFunctions returns the functions map (for extracting signatures from module typechecker)
func (tc *TypeChecker) GetFunctions() map[string]*FunctionSignature {
return tc.functions
}
// GetTypes returns the types map (for extracting types from module typechecker)
func (tc *TypeChecker) GetTypes() map[string]*Type {
return tc.types
}
// GetVariables returns the variables map (for extracting constants from module typechecker) (#677)
func (tc *TypeChecker) GetVariables() map[string]string {
return tc.variables
}
// registerBuiltinTypes adds all built-in types to the registry
func (tc *TypeChecker) registerBuiltinTypes() {
primitives := []string{
// Signed integers
"i8", "i16", "i32", "i64", "i128", "i256", "int",
// Unsigned integers
"u8", "u16", "u32", "u64", "u128", "u256", "uint",
// Floats
"f32", "f64", "float",
// Other primitives
"bool", "char", "string", "byte",
// Special
"void", "nil",
// Internal types (not for user code - will be rejected by E3034)
"any",
}
for _, name := range primitives {
tc.types[name] = &Type{
Name: name,
Kind: PrimitiveType,
}
}
// Register built-in Error struct (both "Error" and "error" alias)
errorType := &Type{
Name: "Error",
Kind: StructType,
Fields: map[string]*Type{
"message": {Name: "string", Kind: PrimitiveType},
"code": {Name: "int", Kind: PrimitiveType},
},
}
tc.types["Error"] = errorType
tc.types["error"] = errorType // Alias for convenience
}
// TypeExists checks if a type name is registered
func (tc *TypeChecker) TypeExists(typeName string) bool {
// Check for array types: [type] or [type, size]
if len(typeName) > 2 && typeName[0] == '[' {
// For now, just check if it's an array syntax
// Full validation will happen in CheckArrayType
return true
}
// Check for map types: map[keyType:valueType]
if strings.HasPrefix(typeName, "map[") && strings.HasSuffix(typeName, "]") {
// Validate the map type has proper format
inner := typeName[4 : len(typeName)-1] // Extract keyType:valueType
parts := strings.Split(inner, ":")
if len(parts) == 2 {
keyType := parts[0]
valueType := parts[1]
// Both key and value types must exist
return tc.TypeExists(keyType) && tc.TypeExists(valueType)
}
return false
}
// Check for qualified type names (module.TypeName)
// These are validated at runtime when the module is loaded
if strings.Contains(typeName, ".") {
parts := strings.SplitN(typeName, ".", 2)
if len(parts) == 2 {
moduleName := parts[0]
typeNamePart := parts[1]
// Check if the module has been imported
if tc.modules[moduleName] {
return true
}
// Also check registered module types (#722 - self-referencing types)
if modTypes, ok := tc.moduleTypes[moduleName]; ok {
if _, exists := modTypes[typeNamePart]; exists {
return true
}
}
}
}
// Check local types first
if _, exists := tc.types[typeName]; exists {
return true
}
// Check if the type might be available via file-level 'using' directive
// For unqualified type names, if a module is imported via 'using',
// the type will be validated at runtime when the module is loaded
for moduleName := range tc.fileUsingModules {
// If the module has been imported and is in file-level 'using', the type is considered valid
// Actual type existence is validated at runtime
if tc.modules[moduleName] {
return true
}
}
// Also check scope-level 'using' modules
if tc.currentScope != nil {
for _, moduleName := range tc.currentScope.GetAllUsingModules() {
// If the module has been imported and is in 'using', the type is considered valid
// Actual type existence is validated at runtime
if tc.modules[moduleName] {
return true
}
}
}
return false
}
// RegisterType adds a user-defined type to the registry
func (tc *TypeChecker) RegisterType(name string, t *Type) {
tc.types[name] = t
}
// RegisterFunction adds a function signature to the registry
func (tc *TypeChecker) RegisterFunction(name string, sig *FunctionSignature) {
tc.functions[name] = sig
}
// RegisterVariable adds a variable/constant to the global scope (#722)
func (tc *TypeChecker) RegisterVariable(name, typeName string) {
tc.variables[name] = typeName
}
// GetType retrieves a type by name
func (tc *TypeChecker) GetType(name string) (*Type, bool) {
t, ok := tc.types[name]
return t, ok
}
// getStructTypeIncludingModules looks up a struct type by name, checking both local
// and module types. For qualified names like "lib.Hero", it looks up in moduleTypes.
// For unqualified names like "Item", it also searches through all registered modules.
func (tc *TypeChecker) getStructTypeIncludingModules(typeName string) (*Type, bool) {
// First check local types
if t, exists := tc.types[typeName]; exists && t.Kind == StructType {
return t, true
}
// Check if it's a qualified type (e.g., "lib.Hero")
if strings.Contains(typeName, ".") {
parts := strings.SplitN(typeName, ".", 2)
if len(parts) == 2 {
moduleName := parts[0]
baseTypeName := parts[1]
if moduleTypes, hasModule := tc.moduleTypes[moduleName]; hasModule {
if t, exists := moduleTypes[baseTypeName]; exists && t.Kind == StructType {
return t, true
}
}
}
}
// For unqualified names, search through all registered modules
// This handles cases where a struct field type like "[Item]" references
// a type from the same module without qualification
for _, moduleTypes := range tc.moduleTypes {
if t, exists := moduleTypes[typeName]; exists && t.Kind == StructType {
return t, true
}
}
return nil, false
}
// Errors returns the error list
func (tc *TypeChecker) Errors() *errors.EZErrorList {
return tc.errors
}
// addError adds a type error
func (tc *TypeChecker) addError(code errors.ErrorCode, message string, line, column int) {
sourceLine := ""
if tc.source != "" {
sourceLine = errors.GetSourceLine(tc.source, line)
}
err := errors.NewErrorWithSource(
code,
message,
tc.filename,
line,
column,
sourceLine,
)
tc.errors.AddError(err)
}
// addWarning adds a type warning
func (tc *TypeChecker) addWarning(code errors.ErrorCode, message string, line, column int) {
sourceLine := ""
if tc.source != "" {
sourceLine = errors.GetSourceLine(tc.source, line)
}
warn := errors.NewErrorWithSource(
code,
message,
tc.filename,
line,
column,
sourceLine,
)
tc.errors.AddWarning(warn)
}
// CheckProgram performs type checking on the entire program
func (tc *TypeChecker) CheckProgram(program *ast.Program) bool {
// Store file-level suppressions
tc.fileSuppressWarnings = program.FileSuppressWarnings
// Phase 0: Register all imported modules
for _, stmt := range program.Statements {
if importStmt, ok := stmt.(*ast.ImportStatement); ok {
for _, item := range importStmt.Imports {
// Register the module (use alias if provided, otherwise module name)
moduleName := item.Alias
if moduleName == "" {
moduleName = item.Module
}
tc.modules[moduleName] = true
// If this is an "import & use" statement, also register for file-level using
// This allows unqualified access to types from the module
if importStmt.AutoUse {
tc.fileUsingModules[moduleName] = true
}
}
}
}
// Phase 0.5: Register file-level using modules
for _, usingStmt := range program.FileUsing {
for _, mod := range usingStmt.Modules {
tc.fileUsingModules[mod.Value] = true
}
}
// Phase 1: Register all user-defined types (structs, enums)
for _, stmt := range program.Statements {
switch node := stmt.(type) {
case *ast.StructDeclaration:
tc.registerStructType(node)
case *ast.EnumDeclaration:
tc.registerEnumType(node)
}
}
// Phase 2: Validate all global declarations
for _, stmt := range program.Statements {
switch node := stmt.(type) {
case *ast.StructDeclaration:
tc.checkStructDeclaration(node)
case *ast.EnumDeclaration:
tc.checkEnumDeclaration(node)
case *ast.VariableDeclaration:
tc.checkGlobalVariableDeclaration(node)
case *ast.FunctionDeclaration:
tc.checkFunctionDeclaration(node)
}
}
// Phase 3: Check for invalid file-scope statements (#662)
tc.checkFileScopeStatements(program.Statements)
// Phase 4: Type check function bodies
for _, stmt := range program.Statements {
if fn, ok := stmt.(*ast.FunctionDeclaration); ok {
tc.checkFunctionBody(fn)
}
}
// Phase 5: Validate that a main() function exists (unless skipped for module files)
if !tc.skipMainCheck {
tc.checkMainFunction()
}
errCount, _ := tc.errors.Count()
return errCount == 0
}
// RegisterDeclarations performs a lightweight pass to register type and function
// declarations without full type checking. Used for multi-file modules to make
// types available before checking files that depend on them (#709).
func (tc *TypeChecker) RegisterDeclarations(program *ast.Program) {
// Phase 0: Register all imported modules
for _, stmt := range program.Statements {
if importStmt, ok := stmt.(*ast.ImportStatement); ok {
for _, item := range importStmt.Imports {
moduleName := item.Alias
if moduleName == "" {
moduleName = item.Module
}
tc.modules[moduleName] = true
if importStmt.AutoUse {
tc.fileUsingModules[moduleName] = true
}
}
}
}
// Phase 0.5: Register file-level using modules
for _, usingStmt := range program.FileUsing {
for _, mod := range usingStmt.Modules {
tc.fileUsingModules[mod.Value] = true
}
}
// Phase 1: Register all user-defined types (structs, enums)
for _, stmt := range program.Statements {
switch node := stmt.(type) {
case *ast.StructDeclaration:
tc.registerStructType(node)
case *ast.EnumDeclaration:
tc.registerEnumType(node)
}
}
// Phase 1.5: Populate struct fields (without validation errors)
for _, stmt := range program.Statements {
if node, ok := stmt.(*ast.StructDeclaration); ok {
tc.populateStructFields(node)
}
}
// Phase 2: Register function signatures
for _, stmt := range program.Statements {
switch node := stmt.(type) {
case *ast.FunctionDeclaration:
sig := &FunctionSignature{
Name: node.Name.Value,
Parameters: []*Parameter{},
ReturnTypes: node.ReturnTypes,
}
for _, param := range node.Parameters {
sig.Parameters = append(sig.Parameters, &Parameter{
Name: param.Name.Value,
Type: param.TypeName,
Mutable: param.Mutable,
HasDefault: param.DefaultValue != nil,
})
}
tc.RegisterFunction(node.Name.Value, sig)
case *ast.VariableDeclaration:
// Register global constants/variables
varType := node.TypeName
if varType == "" {
if inferred, ok := tc.inferExpressionType(node.Value); ok {
varType = inferred
}
}
tc.variables[node.Name.Value] = varType
}
}
}
// populateStructFields adds field types to a struct without validation errors
func (tc *TypeChecker) populateStructFields(node *ast.StructDeclaration) {
structType, ok := tc.GetType(node.Name.Value)
if !ok {
return
}
for _, field := range node.Fields {
// Create type for the field (skip validation - will be done in full check)
var fieldType *Type
if tc.isArrayType(field.TypeName) {
fieldType = &Type{Name: field.TypeName, Kind: ArrayType}
} else if tc.isMapType(field.TypeName) {
fieldType = &Type{Name: field.TypeName, Kind: MapType}
} else if existingType, exists := tc.GetType(field.TypeName); exists {
fieldType = existingType
} else {
// Type doesn't exist yet - create placeholder
fieldType = &Type{Name: field.TypeName, Kind: StructType}
}
structType.Fields[field.Name.Value] = fieldType
}
}
// registerStructType registers a struct type name (without validating fields yet)
func (tc *TypeChecker) registerStructType(node *ast.StructDeclaration) {
structType := &Type{
Name: node.Name.Value,
Kind: StructType,
Fields: make(map[string]*Type),
}
tc.RegisterType(node.Name.Value, structType)
}
// registerEnumType registers an enum type name
func (tc *TypeChecker) registerEnumType(node *ast.EnumDeclaration) {
// Determine base type from attributes, default to "int"
baseType := "int"
if node.Attributes != nil && node.Attributes.TypeName != "" {
baseType = node.Attributes.TypeName
} else {
// Infer base type from first value if no explicit attribute
for _, member := range node.Values {
if member.Value != nil {
baseType = tc.getEnumValueType(member.Value)
if baseType == "" {
baseType = "int" // fallback
}
break
}
}
}
// Collect enum member names (#607)
enumMembers := make(map[string]bool)
for _, member := range node.Values {
enumMembers[member.Name.Value] = true
}
enumType := &Type{
Name: node.Name.Value,
Kind: EnumType,
EnumBaseType: baseType,
EnumMembers: enumMembers,
}
tc.RegisterType(node.Name.Value, enumType)
}
// checkStructDeclaration validates a struct's field types
func (tc *TypeChecker) checkStructDeclaration(node *ast.StructDeclaration) {
structType, ok := tc.GetType(node.Name.Value)
if !ok {
return
}
for _, field := range node.Fields {
// Check if field type exists
if !tc.TypeExists(field.TypeName) {
tc.addError(
errors.E3009,
fmt.Sprintf("undefined type '%s' in struct '%s'", field.TypeName, node.Name.Value),
field.Name.Token.Line,
field.Name.Token.Column,
)
continue
}
// Add field to struct type
fieldType, ok := tc.GetType(field.TypeName)
if !ok {
// For array/map types, create a Type on-the-fly since they're not in the registry
if tc.isArrayType(field.TypeName) {
fieldType = &Type{Name: field.TypeName, Kind: ArrayType}
} else if tc.isMapType(field.TypeName) {
fieldType = &Type{Name: field.TypeName, Kind: MapType}
} else {
// This shouldn't happen since TypeExists passed, but be safe
continue
}
}
structType.Fields[field.Name.Value] = fieldType
}
}
// checkStructLiteral validates a struct literal's field values against the type definition
func (tc *TypeChecker) checkStructLiteral(structVal *ast.StructValue) {
if structVal.Name == nil {
return
}
structName := structVal.Name.Value
// Use getStructTypeIncludingModules to handle both local types and
// qualified imported types like "lib.Item"
structType, exists := tc.getStructTypeIncludingModules(structName)
if !exists {
// Struct type doesn't exist - will be caught elsewhere
return
}
// Check each field in the literal
for fieldName, fieldValue := range structVal.Fields {
// Check for type/function used as field value
tc.checkValueExpression(fieldValue)
tc.checkExpression(fieldValue)
// Get the expected type for this field
expectedType, fieldExists := structType.Fields[fieldName]
if !fieldExists {
// Field doesn't exist on struct - report error
line, column := tc.getExpressionPosition(fieldValue)
tc.addError(
errors.E4003,
fmt.Sprintf("struct '%s' has no field '%s'", structName, fieldName),
line,
column,
)
continue
}
// Infer the actual type of the field value
actualType, ok := tc.inferExpressionType(fieldValue)
if !ok {
continue
}
// Check type compatibility
if !tc.typesCompatible(expectedType.Name, actualType) {
line, column := tc.getExpressionPosition(fieldValue)
tc.addError(
errors.E3001,
fmt.Sprintf("struct field '%s' expects %s, got %s",
fieldName, expectedType.Name, actualType),
line,
column,
)
}
}
}
// checkArrayLiteral validates array literal elements have consistent types
func (tc *TypeChecker) checkArrayLiteral(arr *ast.ArrayValue) {
if len(arr.Elements) == 0 {
return // Empty array is OK
}
// Check each element for type/function used as value
for _, elem := range arr.Elements {
tc.checkValueExpression(elem)
tc.checkExpression(elem)
}
// Get the type of the first element
firstType, ok := tc.inferExpressionType(arr.Elements[0])
if !ok {
return // Can't determine type
}
// All other elements must have the same type
for i := 1; i < len(arr.Elements); i++ {
elemType, ok := tc.inferExpressionType(arr.Elements[i])
if !ok {
continue
}
if !tc.typesCompatible(firstType, elemType) {
line, column := tc.getExpressionPosition(arr.Elements[i])
tc.addError(
errors.E3001,
fmt.Sprintf("array element type mismatch: expected %s (from first element), got %s",
firstType, elemType),
line,
column,
)
}
}
}
// checkEnumDeclaration validates an enum declaration
func (tc *TypeChecker) checkEnumDeclaration(node *ast.EnumDeclaration) {
// All enum members must have the same type
// Determine the type from explicit values, or default to int for auto-assigned
var firstType string
var firstMemberName string
// Track seen values to detect duplicates (#577)
seenValues := make(map[string]string) // value string -> member name
for _, member := range node.Values {
if member.Value == nil {
// No explicit value - will be auto-assigned as int
if firstType == "" {
firstType = "int"
firstMemberName = member.Name.Value
} else if firstType != "int" {
tc.addError(
errors.E3028,
fmt.Sprintf("enum '%s' has mixed types: member '%s' is %s, but '%s' has no value (defaults to int)",
node.Name.Value, firstMemberName, firstType, member.Name.Value),
member.Name.Token.Line,
member.Name.Token.Column,
)
}
continue
}
// Determine the type of this member's value
memberType := tc.getEnumValueType(member.Value)
if memberType == "" {
// Could not determine type - skip (parser should have caught invalid values)
continue
}
if firstType == "" {
// This is the first member with a determinable type
firstType = memberType
firstMemberName = member.Name.Value
} else if memberType != firstType {
// Type mismatch!
tc.addError(
errors.E3028,
fmt.Sprintf("enum '%s' has mixed types: member '%s' is %s, but '%s' is %s",
node.Name.Value, firstMemberName, firstType, member.Name.Value, memberType),
member.Name.Token.Line,
member.Name.Token.Column,
)
}
// Check for duplicate values (#577)
valueStr := tc.getEnumValueString(member.Value)
if existingMember, exists := seenValues[valueStr]; exists {
tc.addError(
errors.E3033,
fmt.Sprintf("enum '%s' has duplicate value: '%s' and '%s' both have value %s",
node.Name.Value, existingMember, member.Name.Value, valueStr),
member.Name.Token.Line,
member.Name.Token.Column,
)
} else {
seenValues[valueStr] = member.Name.Value
}
}
}
// getEnumValueType returns the type of an enum value expression
func (tc *TypeChecker) getEnumValueType(expr ast.Expression) string {
switch expr.(type) {
case *ast.IntegerValue:
return "int"
case *ast.FloatValue:
return "float"
case *ast.StringValue:
return "string"
case *ast.BooleanValue:
return "bool"
case *ast.CharValue:
return "char"
default:
// For more complex expressions, we can't easily determine the type
// This covers cases like enum values referencing other enums, etc.
return ""
}
}
// getEnumValueString returns a string representation of an enum value for duplicate detection
func (tc *TypeChecker) getEnumValueString(expr ast.Expression) string {
switch e := expr.(type) {
case *ast.IntegerValue:
return fmt.Sprintf("%d", e.Value)
case *ast.FloatValue:
return fmt.Sprintf("%v", e.Value)
case *ast.StringValue:
return fmt.Sprintf("\"%s\"", e.Value)
case *ast.BooleanValue:
return fmt.Sprintf("%v", e.Value)
case *ast.CharValue:
return fmt.Sprintf("'%c'", e.Value)
default:
return ""
}
}
// checkGlobalVariableDeclaration validates a global variable declaration
func (tc *TypeChecker) checkGlobalVariableDeclaration(node *ast.VariableDeclaration) {
// Check each variable in the declaration
for _, name := range node.Names {
varName := name.Value
// Determine the type
var typeName string
if node.TypeName != "" {
typeName = node.TypeName
} else if node.Value != nil {
// Type inference from value
if inferredType, ok := tc.inferExpressionType(node.Value); ok {
typeName = inferredType
} else {
continue
}
} else {
continue
}
// Check if type exists (skip for inferred types that might be complex)
if typeName != "" && !tc.TypeExists(typeName) && !strings.HasPrefix(typeName, "[") && !strings.HasPrefix(typeName, "map[") {
tc.addError(
errors.E3002,
fmt.Sprintf("undefined type '%s'", typeName),
name.Token.Line,
name.Token.Column,
)
continue
}
// Check if 'any' type is used (not allowed for user code)
if typeName != "" && tc.containsAnyType(typeName) {
tc.addError(
errors.E3034,
"'any' type cannot be used in variable declarations",
name.Token.Line,
name.Token.Column,
)
continue
}
// Register variable
tc.variables[varName] = typeName
}
}
// checkFunctionDeclaration validates a function's signature
func (tc *TypeChecker) checkFunctionDeclaration(node *ast.FunctionDeclaration) {
sig := &FunctionSignature{
Name: node.Name.Value,
Parameters: []*Parameter{},
ReturnTypes: node.ReturnTypes,
}
// Check parameter types and names
for _, param := range node.Parameters {
paramName := param.Name.Value
// Check if parameter name shadows a user-defined type (struct/enum)
if _, exists := tc.types[paramName]; exists {
tc.addError(
errors.E2033,
fmt.Sprintf("'%s' is a type name and cannot be used as a parameter name", paramName),
param.Name.Token.Line,
param.Name.Token.Column,
)
}
// Check if parameter name shadows a user-defined function
if _, exists := tc.functions[paramName]; exists {
tc.addError(
errors.E2033,
fmt.Sprintf("'%s' is a function name and cannot be used as a parameter name", paramName),
param.Name.Token.Line,
param.Name.Token.Column,