-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathevaluator.go
More file actions
3795 lines (3407 loc) · 115 KB
/
evaluator.go
File metadata and controls
3795 lines (3407 loc) · 115 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 interpreter
// Copyright (c) 2025-Present Marshall A Burns
// Licensed under the MIT License. See LICENSE for details.
import (
"fmt"
"math"
"math/big"
"strings"
"github.com/marshallburns/ez/pkg/ast"
"github.com/marshallburns/ez/pkg/errors"
)
// Type bounds for integer types
var (
// Signed integer bounds
minInt8 = big.NewInt(math.MinInt8)
maxInt8 = big.NewInt(math.MaxInt8)
minInt16 = big.NewInt(math.MinInt16)
maxInt16 = big.NewInt(math.MaxInt16)
minInt32 = big.NewInt(math.MinInt32)
maxInt32 = big.NewInt(math.MaxInt32)
minInt64 = big.NewInt(math.MinInt64)
maxInt64 = big.NewInt(math.MaxInt64)
minInt128 = new(big.Int)
maxInt128 = new(big.Int)
minInt256 = new(big.Int)
maxInt256 = new(big.Int)
// Unsigned integer bounds
maxUint8 = big.NewInt(math.MaxUint8)
maxUint16 = big.NewInt(math.MaxUint16)
maxUint32 = big.NewInt(math.MaxUint32)
maxUint64 = new(big.Int).SetUint64(math.MaxUint64)
maxUint128 = new(big.Int)
maxUint256 = new(big.Int)
zero = big.NewInt(0)
one = big.NewInt(1)
)
func init() {
// i128: -2^127 to 2^127-1
minInt128.Lsh(big.NewInt(-1), 127)
maxInt128.Lsh(big.NewInt(1), 127)
maxInt128.Sub(maxInt128, one)
// i256: -2^255 to 2^255-1
minInt256.Lsh(big.NewInt(-1), 255)
maxInt256.Lsh(big.NewInt(1), 255)
maxInt256.Sub(maxInt256, one)
// u128: 0 to 2^128-1
maxUint128.Lsh(big.NewInt(1), 128)
maxUint128.Sub(maxUint128, one)
// u256: 0 to 2^256-1
maxUint256.Lsh(big.NewInt(1), 256)
maxUint256.Sub(maxUint256, one)
}
// getTypeBounds returns the min and max values for a given integer type
// Returns nil, nil for arbitrary precision types (int, uint) that have no bounds
func getTypeBounds(typeName string) (min, max *big.Int) {
switch typeName {
case "int", "uint":
// Arbitrary precision - no bounds
return nil, nil
case "i8":
return minInt8, maxInt8
case "i16":
return minInt16, maxInt16
case "i32":
return minInt32, maxInt32
case "i64", "":
return minInt64, maxInt64
case "i128":
return minInt128, maxInt128
case "i256":
return minInt256, maxInt256
case "u8":
return zero, maxUint8
case "u16":
return zero, maxUint16
case "u32":
return zero, maxUint32
case "u64":
return zero, maxUint64
case "u128":
return zero, maxUint128
case "u256":
return zero, maxUint256
default:
// Default to int64 range for unknown types
return minInt64, maxInt64
}
}
// checkOverflow checks if a value is within bounds for a given type
// Returns false for arbitrary precision types (int, uint) that have no bounds
func checkOverflow(result *big.Int, typeName string) bool {
min, max := getTypeBounds(typeName)
if min == nil || max == nil {
// Arbitrary precision type - no overflow possible
return false
}
return result.Cmp(min) < 0 || result.Cmp(max) > 0
}
// getTypeRangeName returns a human-readable name for the type's range
func getTypeRangeName(typeName string) string {
switch typeName {
case "i8", "i16", "i32", "i64", "i128", "i256":
return typeName
case "u8", "u16", "u32", "u64", "u128", "u256":
return typeName
case "int", "":
return "int64"
case "uint":
return "uint64"
default:
return "int64"
}
}
var (
NIL = &Nil{}
TRUE = &Boolean{Value: true}
FALSE = &Boolean{Value: false}
)
// Call stack depth tracking for recursion limit
const MAX_CALL_DEPTH = 10000
var callDepth int
// EvalContext holds context for evaluation including the module loader
type EvalContext struct {
Loader *ModuleLoader
CurrentFile string // Current file being evaluated (for relative imports)
}
// Global eval context (set when running a program)
var globalEvalContext *EvalContext
// validModules lists all available standard library modules
var validModules = map[string]bool{
"std": true, // Standard I/O functions (println, print, read_int)
"math": true, // Math functions
"strings": true, // String utilities
"arrays": true, // Array utilities
"maps": true, // Map utilities
"time": true, // Time functions
"io": true, // File system and I/O operations
"os": true, // Operating system and environment
"bytes": true, // Binary data operations
"random": true, // Random number generation
"json": true, // JSON encoding/decoding
"binary": true, // Binary encoding/decoding for integers and floats
"db": true, // Simple key-value database
"uuid": true, // UUID generation and validation
"encoding": true, // Base64, hex, and URL encoding/decoding
"crypto": true, // Cryptographic hashing and secure random
"http": true, // HTTP client for web requests
}
// isValidModule checks if a module name is valid (either standard library or user-created)
func isValidModule(moduleName string) bool {
// Check standard library modules
if validModules[moduleName] {
return true
}
return false
}
// suggestModule returns a suggestion for a similar module name, or empty string if none found.
func suggestModule(invalidName string) string {
// Check for common typos/variations
suggestions := map[string]string{
"string": "strings",
"array": "arrays",
"map": "maps",
"rand": "random",
"file": "io",
"files": "io",
"fs": "io",
"env": "os",
"system": "os",
"byte": "bytes",
"datetime": "time",
"date": "time",
}
if suggestion, ok := suggestions[invalidName]; ok {
return suggestion
}
// Check for close matches using simple prefix/suffix matching
for validName := range validModules {
// Check if input is a prefix of a valid module (e.g., "str" -> "strings")
if len(invalidName) >= 3 && strings.HasPrefix(validName, invalidName) {
return validName
}
// Check if valid module is a prefix of input (e.g., "stringss" -> "strings")
if len(validName) >= 3 && strings.HasPrefix(invalidName, validName) {
return validName
}
}
return ""
}
// convertVisibility converts AST visibility to object visibility
func convertVisibility(vis ast.Visibility) Visibility {
switch vis {
case ast.VisibilityPrivate:
return VisibilityPrivate
default:
return VisibilityPublic
}
}
// extractModuleName extracts the module name from a file path
// e.g., "./server" -> "server", "../utils" -> "utils", "./src/networking" -> "networking"
func extractModuleName(path string) string {
// Remove leading ./ or ../
for strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../") {
if strings.HasPrefix(path, "./") {
path = path[2:]
} else if strings.HasPrefix(path, "../") {
path = path[3:]
}
}
// Get the last component
parts := strings.Split(path, "/")
if len(parts) > 0 {
return parts[len(parts)-1]
}
return path
}
// SetEvalContext sets the global evaluation context
func SetEvalContext(ctx *EvalContext) {
globalEvalContext = ctx
}
// GetEvalContext returns the global evaluation context
func GetEvalContext() *EvalContext {
return globalEvalContext
}
// EvalWithContext evaluates a program with a given context
func EvalWithContext(node ast.Node, env *Environment, ctx *EvalContext) Object {
oldCtx := globalEvalContext
globalEvalContext = ctx
result := Eval(node, env)
globalEvalContext = oldCtx
return result
}
// loadUserModule loads a user module from a file path and returns a ModuleObject
func loadUserModule(importPath string, line, column int, env *Environment) (*ModuleObject, Object) {
if globalEvalContext == nil || globalEvalContext.Loader == nil {
return nil, newErrorWithLocation("E6001", line, column, "module loader not initialized")
}
// Set the current file for relative path resolution
globalEvalContext.Loader.SetCurrentFile(globalEvalContext.CurrentFile)
// Load the module (this handles parsing and caching)
mod, err := globalEvalContext.Loader.Load(importPath)
if err != nil {
// Check if this is a ModuleError with rich parse errors
if modErr, ok := err.(*ModuleError); ok && modErr.EZErrors != nil && modErr.EZErrors.HasErrors() {
// Return the formatted errors directly without wrapping
return nil, &Error{Message: modErr.Error(), PreFormatted: true}
}
// Return error with location info for proper formatting
if modErr, ok := err.(*ModuleError); ok {
return nil, newErrorWithLocation(modErr.Code, line, column, modErr.Message)
}
return nil, newErrorWithLocation("E6001", line, column, err.Error())
}
// If module is already fully loaded, return cached ModuleObject
if mod.State == ModuleLoaded && mod.ModuleObj != nil {
return mod.ModuleObj, nil
}
// Check for circular import - if module already has a ModuleObj and is loading,
// another call to loadUserModule is already evaluating this module.
// Return the existing ModuleObj which will be populated when that call completes.
if mod.State == ModuleLoading && mod.ModuleObj != nil {
return mod.ModuleObj, nil
}
// We are the first to evaluate this module.
// Create a new environment for the module
moduleEnv := NewEnvironment()
mod.Env = moduleEnv
// Create ModuleObject early so circular imports can reference it
// Since we're about to evaluate, we create the ModuleObj here
mod.ModuleObj = &ModuleObject{
Name: mod.Name,
Exports: make(map[string]Object),
}
// Save the current file and set the module file as current
oldFile := globalEvalContext.CurrentFile
if len(mod.Files) > 0 {
globalEvalContext.CurrentFile = mod.Files[0]
}
// Evaluate the module's AST
result := Eval(mod.AST, moduleEnv)
// Restore the current file
globalEvalContext.CurrentFile = oldFile
if isError(result) {
return nil, result
}
// Export only public symbols from the module environment
for name, obj := range moduleEnv.GetPublicBindings() {
mod.ModuleObj.Exports[name] = obj
}
// Export struct definitions from the module
mod.ModuleObj.StructDefs = moduleEnv.GetPublicStructDefs()
// Mark module as fully loaded
mod.State = ModuleLoaded
return mod.ModuleObj, nil
}
func Eval(node ast.Node, env *Environment) Object {
switch node := node.(type) {
// Program
case *ast.Program:
return evalProgram(node, env)
// Statements
case *ast.ExpressionStatement:
result := Eval(node.Expression, env)
if isError(result) {
return result
}
// Check for uncaptured return values from function calls
if call, ok := node.Expression.(*ast.CallExpression); ok {
if fn, ok := result.(*ReturnValue); ok && len(fn.Values) > 0 {
return newErrorWithLocation("E4009", call.Token.Line, call.Token.Column,
"return value from function not used (use _ to discard)")
}
// Also check if the function has declared return types but result is not NIL
if result != NIL {
// Check if it's a user function with return types
if fnObj := getFunctionObject(call, env); fnObj != nil && len(fnObj.ReturnTypes) > 0 {
return newErrorWithLocation("E4009", call.Token.Line, call.Token.Column,
"return value from function not used (use _ to discard)")
}
}
}
return result
case *ast.VariableDeclaration:
return evalVariableDeclaration(node, env)
case *ast.AssignmentStatement:
return evalAssignment(node, env)
case *ast.ReturnStatement:
return evalReturn(node, env)
case *ast.EnsureStatement:
return evalEnsure(node, env)
case *ast.BlockStatement:
return evalBlockStatement(node, env)
case *ast.IfStatement:
return evalIfStatement(node, env)
case *ast.WhenStatement:
return evalWhenStatement(node, env)
case *ast.WhileStatement:
return evalWhileStatement(node, env)
case *ast.LoopStatement:
return evalLoopStatement(node, env)
case *ast.ForStatement:
return evalForStatement(node, env)
case *ast.ForEachStatement:
return evalForEachStatement(node, env)
case *ast.BreakStatement:
if !env.InLoop() {
return newErrorWithLocation("E5009", node.Token.Line, node.Token.Column,
"break statement outside loop")
}
return &Break{}
case *ast.ContinueStatement:
if !env.InLoop() {
return newErrorWithLocation("E5010", node.Token.Line, node.Token.Column,
"continue statement outside loop")
}
return &Continue{}
case *ast.FunctionDeclaration:
return evalFunctionDeclaration(node, env)
case *ast.StructDeclaration:
// Register the struct type definition with visibility
fields := make(map[string]string)
tags := make(map[string]StructFieldTags)
for _, field := range node.Fields {
fields[field.Name.Value] = field.TypeName
if strings.HasPrefix(field.Tag, "json:\"") {
jsonTag := &JSONTag{Name: field.Name.Value}
optionString, _ := strings.CutPrefix(field.Tag, "json:\"")
optionString, _ = strings.CutSuffix(optionString, "\"")
options := strings.Split(optionString, ",")
switch options[0] {
case "-":
jsonTag.Ignore = true
default:
jsonTag.Name = options[0]
for _, opt := range options[1:] {
switch opt {
case "omitempty":
jsonTag.OmitEmpty = true
case "string":
jsonTag.EncodeAsString = true
}
}
}
tags[field.Name.Value] = jsonTag
} else if field.Tag == "" {
tags[field.Name.Value] = &EmptyTag{}
}
}
vis := convertVisibility(node.Visibility)
env.RegisterStructDefWithVisibility(node.Name.Value, &StructDef{
Name: node.Name.Value,
Fields: fields,
FieldTags: tags,
}, vis)
return NIL
case *ast.EnumDeclaration:
return evalEnumDeclaration(node, env)
case *ast.ImportStatement:
// Register the imported module(s) with their aliases
// The alias is what's used in code (e.g., str.upper())
// The module is the actual library (e.g., strings)
// Handle multiple imports (new comma-separated syntax)
if len(node.Imports) > 0 {
for _, item := range node.Imports {
alias := item.Alias
if alias == "" {
if item.Module != "" {
alias = item.Module
} else {
// Extract from path
alias = extractModuleName(item.Path)
}
}
if item.IsStdlib {
// Standard library import
if !isValidModule(item.Module) {
if suggestion := suggestModule(item.Module); suggestion != "" {
return newErrorWithLocation("E6002", node.Token.Line, node.Token.Column,
"module '%s' not found; did you mean @%s?", item.Module, suggestion)
}
return newErrorWithLocation("E6002", node.Token.Line, node.Token.Column,
"module '%s' not found", item.Module)
}
env.Import(alias, item.Module)
// Dual-name access: also register with original module name if alias differs
if alias != item.Module {
env.Import(item.Module, item.Module)
}
} else if item.Path != "" {
// User module import - load the module
moduleObj, loadErr := loadUserModule(item.Path, node.Token.Line, node.Token.Column, env)
if loadErr != nil {
return loadErr
}
if moduleObj == nil {
return newErrorWithLocation("E6001", node.Token.Line, node.Token.Column,
"failed to load module '%s'", item.Path)
}
// Register the module object so it can be accessed via alias.function()
env.RegisterModule(alias, moduleObj)
// Dual-name access: also register with original module name if alias differs
originalName := extractModuleName(item.Path)
if alias != originalName {
env.RegisterModule(originalName, moduleObj)
}
}
// Handle auto-use (import & use syntax)
if node.AutoUse {
env.Use(alias)
}
}
} else {
// Backward compatibility: handle single import using old fields
if !isValidModule(node.Module) {
if suggestion := suggestModule(node.Module); suggestion != "" {
return newErrorWithLocation("E6002", node.Token.Line, node.Token.Column,
"module '%s' not found; did you mean @%s?", node.Module, suggestion)
}
return newErrorWithLocation("E6002", node.Token.Line, node.Token.Column,
"module '%s' not found", node.Module)
}
alias := node.Alias
if alias == "" {
alias = node.Module
}
env.Import(alias, node.Module)
// Handle auto-use
if node.AutoUse {
env.Use(alias)
}
}
return NIL
case *ast.UsingStatement:
// Bring the module(s) functions into scope (function-scoped using)
for _, module := range node.Modules {
alias := module.Value
// Verify the module was imported (check both stdlib and user modules)
_, isStdlib := env.GetImport(alias)
_, isUserModule := env.GetModule(alias)
if !isStdlib && !isUserModule {
return newErrorWithLocation("E6004", node.Token.Line, node.Token.Column,
"cannot use '%s': module not imported", alias)
}
env.Use(alias)
}
return NIL
// Expressions
case *ast.IntegerValue:
return &Integer{Value: new(big.Int).Set(node.Value)}
case *ast.FloatValue:
return &Float{Value: node.Value}
case *ast.StringValue:
return &String{Value: node.Value, Mutable: true}
case *ast.InterpolatedString:
return evalInterpolatedString(node, env)
case *ast.CharValue:
return &Char{Value: node.Value}
case *ast.BooleanValue:
if node.Value {
return TRUE
}
return FALSE
case *ast.NilValue:
return NIL
case *ast.ArrayValue:
elements := evalExpressions(node.Elements, env)
if len(elements) == 1 && isError(elements[0]) {
return elements[0]
}
return &Array{Elements: elements, Mutable: true}
case *ast.MapValue:
return evalMapLiteral(node, env)
case *ast.StructValue:
return evalStructValue(node, env)
case *ast.Label:
return evalIdentifier(node, env)
case *ast.PrefixExpression:
right := Eval(node.Right, env)
if isError(right) {
return right
}
return evalPrefixExpression(node.Operator, right)
case *ast.InfixExpression:
left := Eval(node.Left, env)
if isError(left) {
return left
}
// Short-circuit evaluation for && and ||
if node.Operator == "&&" {
if !isTruthy(left) {
return FALSE // Left is false, don't evaluate right
}
right := Eval(node.Right, env)
if isError(right) {
return right
}
return nativeBoolToBooleanObject(isTruthy(right))
}
if node.Operator == "||" {
if isTruthy(left) {
return TRUE // Left is true, don't evaluate right
}
right := Eval(node.Right, env)
if isError(right) {
return right
}
return nativeBoolToBooleanObject(isTruthy(right))
}
right := Eval(node.Right, env)
if isError(right) {
return right
}
return evalInfixExpression(node.Operator, left, right, node.Token.Line, node.Token.Column)
case *ast.PostfixExpression:
return evalPostfixExpression(node, env)
case *ast.CallExpression:
return evalCallExpression(node, env)
case *ast.IndexExpression:
left := Eval(node.Left, env)
if isError(left) {
return left
}
index := Eval(node.Index, env)
if isError(index) {
return index
}
// Handle map indexing first (maps can use non-integer keys)
if mapObj, ok := left.(*Map); ok {
// Validate that the key is hashable
if _, hashOk := HashKey(index); !hashOk {
return newErrorWithLocation("E12001", node.Token.Line, node.Token.Column,
"unusable as map key: %s", index.Type())
}
value, exists := mapObj.Get(index)
if !exists {
// Build helpful error message with available keys
availableKeys := make([]string, len(mapObj.Pairs))
for i, pair := range mapObj.Pairs {
availableKeys[i] = pair.Key.Inspect()
}
keyList := ""
if len(availableKeys) > 0 {
keyList = fmt.Sprintf("\n\nAvailable keys: %v", availableKeys)
}
return newErrorWithLocation("E12003", node.Token.Line, node.Token.Column,
"key %s not found in map%s", index.Inspect(), keyList)
}
return value
}
// For arrays and strings, index must be an integer
idx, ok := index.(*Integer)
if !ok {
return newErrorWithLocation("E9003", node.Token.Line, node.Token.Column,
"index must be an integer, got %s", index.Type())
}
switch obj := left.(type) {
case *Array:
arrLen := big.NewInt(int64(len(obj.Elements)))
if idx.Value.Sign() < 0 || idx.Value.Cmp(arrLen) >= 0 {
if arrLen.Sign() == 0 {
return newErrorWithLocation("E9004", node.Token.Line, node.Token.Column,
"index out of bounds: array is empty (length 0)\n\n"+
"Attempted to access index %s, but array has no elements\n"+
"Hint: Use arrays.append() to add elements before accessing by index", idx.Value.String())
}
return newErrorWithLocation("E9001", node.Token.Line, node.Token.Column,
"index out of bounds: attempted to access index %s, but valid range is 0-%d",
idx.Value.String(), arrLen.Int64()-1)
}
return obj.Elements[idx.Value.Int64()]
case *String:
// Convert to runes for proper UTF-8 character indexing
runes := []rune(obj.Value)
strLen := big.NewInt(int64(len(runes)))
if idx.Value.Sign() < 0 || idx.Value.Cmp(strLen) >= 0 {
if strLen.Sign() == 0 {
return newErrorWithLocation("E10004", node.Token.Line, node.Token.Column,
"index out of bounds: string is empty (length 0)\n\n"+
"Attempted to access index %s", idx.Value.String())
}
return newErrorWithLocation("E10003", node.Token.Line, node.Token.Column,
"index out of bounds: attempted to access index %s, but valid range is 0-%d",
idx.Value.String(), strLen.Int64()-1)
}
return &Char{Value: runes[idx.Value.Int64()]}
default:
return newErrorWithLocation("E5015", node.Token.Line, node.Token.Column,
"index operator not supported for %s", left.Type())
}
case *ast.MemberExpression:
return evalMemberExpression(node, env)
case *ast.NewExpression:
return evalNewExpression(node, env)
case *ast.RangeExpression:
return evalRangeExpression(node, env)
case *ast.CastExpression:
return evalCastExpression(node, env)
}
return newError("unknown node type: %T", node)
}
func evalProgram(program *ast.Program, env *Environment) Object {
var result Object
// First, process import statements
for _, stmt := range program.Statements {
if importStmt, ok := stmt.(*ast.ImportStatement); ok {
result = Eval(importStmt, env)
if isError(result) {
return result
}
}
}
// Then, process file-scoped using declarations
for _, usingStmt := range program.FileUsing {
for _, module := range usingStmt.Modules {
alias := module.Value
// Verify the module was imported (check both stdlib and user modules)
_, isStdlib := env.GetImport(alias)
_, isUserModule := env.GetModule(alias)
if !isStdlib && !isUserModule {
return newErrorWithLocation("E6004", usingStmt.Token.Line, usingStmt.Token.Column,
"cannot use '%s': module not imported", alias)
}
env.Use(alias)
}
}
// Finally, process all other statements
for _, stmt := range program.Statements {
// Skip imports (already processed)
if _, ok := stmt.(*ast.ImportStatement); ok {
continue
}
// Update current file context for accurate error reporting in multi-file modules
if globalEvalContext != nil {
if stmtFile := getStatementFile(stmt); stmtFile != "" {
globalEvalContext.CurrentFile = stmtFile
}
}
result = Eval(stmt, env)
switch result := result.(type) {
case *ReturnValue:
if len(result.Values) > 0 {
return result.Values[0]
}
return NIL
case *Error:
return result
}
}
return result
}
func evalBlockStatement(block *ast.BlockStatement, env *Environment) Object {
var result Object
for _, stmt := range block.Statements {
result = Eval(stmt, env)
if result != nil {
rt := result.Type()
if rt == RETURN_VALUE_OBJ || rt == ERROR_OBJ || rt == BREAK_OBJ || rt == CONTINUE_OBJ {
return result
}
}
}
return result
}
func evalVariableDeclaration(node *ast.VariableDeclaration, env *Environment) Object {
var val Object = NIL
if node.Value != nil {
val = Eval(node.Value, env)
if isError(val) {
return val
}
// Copy-by-default for complex types (#661)
// When assigning from another variable, deep copy structs/arrays/maps
// UNLESS the value is a Reference (from ref() builtin)
val = copyByDefault(val)
// Handle multiple assignment FIRST: temp result, err = function()
// This must happen before single-value type validation (#698)
vis := convertVisibility(node.Visibility)
if len(node.Names) > 1 {
// Expect a ReturnValue with multiple values
returnVal, ok := val.(*ReturnValue)
if !ok {
// Single value assigned to multiple variables - error
return newError("expected %d values, got 1", len(node.Names))
}
if len(returnVal.Values) != len(node.Names) {
return newError("expected %d values, got %d", len(node.Names), len(returnVal.Values))
}
// Validate types if TypeNames is provided
for i, name := range node.Names {
// Skip blank identifier (_)
if name.Value == "_" {
continue
}
unpackedVal := returnVal.Values[i]
// Apply type validation if TypeNames is provided
if i < len(node.TypeNames) && node.TypeNames[i] != "" {
typeName := node.TypeNames[i]
// Validate and potentially convert the value based on declared type
validatedVal, err := validateAndConvertType(unpackedVal, typeName, node.Mutable, node.Token.Line, node.Token.Column)
if err != nil {
return err
}
unpackedVal = validatedVal
}
env.SetWithVisibility(name.Value, unpackedVal, node.Mutable, vis)
}
return NIL
}
// Validate type compatibility if a type is declared (single variable case)
if node.TypeName != "" {
// Check if declared type is an array type
if len(node.TypeName) > 0 && node.TypeName[0] == '[' {
// Check if const array has dynamic size (no fixed size specified)
// const arrays must have a fixed size like [int, 3], not [int]
if !node.Mutable && !strings.Contains(node.TypeName, ",") {
// Extract element type from [type] -> type
elemType := node.TypeName[1 : len(node.TypeName)-1]
// Get the array length for the suggested fix
arrayLen := 0
if arr, ok := val.(*Array); ok {
arrayLen = len(arr.Elements)
}
return newErrorWithLocation("E2032", node.Token.Line, node.Token.Column,
"const array must have a fixed size\n\n"+
"Dynamic arrays [%s] can change size, but const prevents modification.\n"+
"Use 'temp' for dynamic arrays, or specify a fixed size for const.\n\n"+
"Example: const arr [%s, %d] = %s",
elemType, elemType, arrayLen, val.Inspect())
}
// Array type declared - value must be an array
arr, ok := val.(*Array)
if !ok {
return newErrorWithLocation("E3018", node.Token.Line, node.Token.Column,
"type mismatch: expected array type '%s', got %s\n\n"+
"Array values must be enclosed in curly braces {}\n"+
"Example: const arr %s = {%s}",
node.TypeName, getEZTypeName(val), node.TypeName, val.Inspect())
}
// Set the element type on the array from the declared type
// Extract element type from type name (e.g., "[int]" -> "int", "[int,5]" -> "int")
elemType := node.TypeName[1:] // Remove leading '['
if commaIdx := strings.Index(elemType, ","); commaIdx != -1 {
elemType = elemType[:commaIdx] // Remove ",size]" part
} else {
elemType = elemType[:len(elemType)-1] // Remove trailing ']'
}
arr.ElementType = elemType
// Set mutability based on temp vs const
arr.Mutable = node.Mutable
// Validate byte array elements are in range 0-255
if elemType == "byte" {
for i, elem := range arr.Elements {
switch e := elem.(type) {
case *Integer:
if e.Value.Sign() < 0 || e.Value.Cmp(big.NewInt(255)) > 0 {
return newErrorWithLocation("E3022", node.Token.Line, node.Token.Column,
"byte array element [%d] value %s out of range: must be between 0 and 255", i, e.Value.String())
}
// Convert integer to byte
arr.Elements[i] = &Byte{Value: uint8(e.Value.Int64())}
case *Byte:
// Already a byte, OK
default:
return newErrorWithLocation("E3022", node.Token.Line, node.Token.Column,
"byte array element [%d] must be an integer value between 0 and 255", i)
}
}
}
}
// Check if declared type is a map type
if strings.HasPrefix(node.TypeName, "map[") {
// Map type declared - value must be a map
mapObj, ok := val.(*Map)
if !ok {
// Special case: empty {} is parsed as empty Array, convert to empty Map
if arr, isArr := val.(*Array); isArr && len(arr.Elements) == 0 {
mapObj = &Map{
Pairs: []*MapPair{},
Index: make(map[string]int),
Mutable: node.Mutable,
KeyType: extractMapKeyType(node.TypeName),
ValueType: extractMapValueType(node.TypeName),
}
val = mapObj
} else {
return newErrorWithLocation("E3019", node.Token.Line, node.Token.Column,
"type mismatch: expected map type '%s', got %s\n\n"+
"Map values must use key: value syntax\n"+
"Example: temp m %s = {\"key\": value}",
node.TypeName, getEZTypeName(val), node.TypeName)
}
} else {
// Set mutability and type info based on declaration
mapObj.Mutable = node.Mutable
mapObj.KeyType = extractMapKeyType(node.TypeName)
mapObj.ValueType = extractMapValueType(node.TypeName)
}
}
// If we have a struct value, set mutability based on temp vs const
if structObj, ok := val.(*Struct); ok {
structObj.Mutable = node.Mutable
}
// If we have an integer value, set the declared type
// and validate signed/unsigned compatibility
if intVal, ok := val.(*Integer); ok {
// Special handling for byte type - convert and validate range
if node.TypeName == "byte" {
if intVal.Value.Sign() < 0 || intVal.Value.Cmp(big.NewInt(255)) > 0 {
return newErrorWithLocation("E3020", node.Token.Line, node.Token.Column,
"cannot assign value %s to byte: value must be between 0 and 255", intVal.Value.String())
}
val = &Byte{Value: uint8(intVal.Value.Int64())}
} else {
// Check for negative value assigned to unsigned type
if isUnsignedIntegerType(node.TypeName) && intVal.Value.Sign() < 0 {
return newErrorWithLocation("E3020", node.Token.Line, node.Token.Column,
"cannot assign negative value %s to unsigned type '%s'", intVal.Value.String(), node.TypeName)
}
// Set the declared type on the integer
intVal.DeclaredType = node.TypeName
}
}
}
} else if node.TypeName != "" {
// Variable declared with type but no value - provide appropriate default
// Check if it's a dynamic array type (starts with '[' but doesn't contain ',')
// Dynamic arrays: [int], [string], etc. - can be declared without values
// Fixed-size arrays: [int,3], [string,5], etc. - MUST be initialized with values
if len(node.TypeName) > 0 && node.TypeName[0] == '[' && !strings.Contains(node.TypeName, ",") {
// Initialize dynamic array to empty array instead of NIL
// Extract element type from type name (e.g., "[int]" -> "int")
elementType := node.TypeName[1 : len(node.TypeName)-1]
val = &Array{Elements: []Object{}, Mutable: node.Mutable, ElementType: elementType}
} else if strings.HasPrefix(node.TypeName, "map[") {
// Initialize map to empty map