-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.go
1380 lines (1242 loc) · 33.4 KB
/
compiler.go
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 tengo
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/d5/tengo/v2/parser"
"github.com/d5/tengo/v2/token"
)
// compilationScope represents a compiled instructions and the last two
// instructions that were emitted.
type compilationScope struct {
Instructions []byte
SymbolInit map[string]bool
SourceMap map[int]parser.Pos
}
// loop represents a loop construct that the compiler uses to track the current
// loop.
type loop struct {
Continues []int
Breaks []int
}
// CompilerError represents a compiler error.
type CompilerError struct {
FileSet *parser.SourceFileSet
Node parser.Node
Err error
}
func (e *CompilerError) Error() string {
filePos := e.FileSet.Position(e.Node.Pos())
return fmt.Sprintf("Compile Error: %s\n\tat %s", e.Err.Error(), filePos)
}
// Compiler compiles the AST into a bytecode.
type Compiler struct {
file *parser.SourceFile
parent *Compiler
modulePath string
importDir string
importFileExt []string
constants []Object
symbolTable *SymbolTable
scopes []compilationScope
scopeIndex int
modules ModuleGetter
compiledModules map[string]*CompiledFunction
allowFileImport bool
loops []*loop
loopIndex int
trace io.Writer
indent int
}
// NewCompiler creates a Compiler.
func NewCompiler(
file *parser.SourceFile,
symbolTable *SymbolTable,
constants []Object,
modules ModuleGetter,
trace io.Writer,
) *Compiler {
mainScope := compilationScope{
SymbolInit: make(map[string]bool),
SourceMap: make(map[int]parser.Pos),
}
// symbol table
if symbolTable == nil {
symbolTable = NewSymbolTable()
}
// add builtin functions to the symbol table
for idx, fn := range builtinFuncs {
symbolTable.DefineBuiltin(idx, fn.Name)
}
// builtin modules
if modules == nil {
modules = NewModuleMap()
}
return &Compiler{
file: file,
symbolTable: symbolTable,
constants: constants,
scopes: []compilationScope{mainScope},
scopeIndex: 0,
loopIndex: -1,
trace: trace,
modules: modules,
compiledModules: make(map[string]*CompiledFunction),
importFileExt: []string{SourceFileExtDefault},
}
}
// Compile compiles the AST node.
func (c *Compiler) Compile(node parser.Node) error {
if c.trace != nil {
if node != nil {
defer untracec(tracec(c, fmt.Sprintf("%s (%s)",
node.String(), reflect.TypeOf(node).Elem().Name())))
} else {
defer untracec(tracec(c, "<nil>"))
}
}
switch node := node.(type) {
case *parser.File:
for _, stmt := range node.Stmts {
if err := c.Compile(stmt); err != nil {
return err
}
}
case *parser.ExprStmt:
if err := c.Compile(node.Expr); err != nil {
return err
}
c.emit(node, parser.OpPop)
case *parser.IncDecStmt:
op := token.AddAssign
if node.Token == token.Dec {
op = token.SubAssign
}
return c.compileAssign(node, []parser.Expr{node.Expr},
[]parser.Expr{&parser.IntLit{Value: 1}}, op)
case *parser.ParenExpr:
if err := c.Compile(node.Expr); err != nil {
return err
}
case *parser.BinaryExpr:
if node.Token == token.LAnd || node.Token == token.LOr {
return c.compileLogical(node)
}
if err := c.Compile(node.LHS); err != nil {
return err
}
if err := c.Compile(node.RHS); err != nil {
return err
}
switch node.Token {
case token.Add:
c.emit(node, parser.OpBinaryOp, int(token.Add))
case token.Sub:
c.emit(node, parser.OpBinaryOp, int(token.Sub))
case token.Mul:
c.emit(node, parser.OpBinaryOp, int(token.Mul))
case token.Quo:
c.emit(node, parser.OpBinaryOp, int(token.Quo))
case token.Rem:
c.emit(node, parser.OpBinaryOp, int(token.Rem))
case token.Greater:
c.emit(node, parser.OpBinaryOp, int(token.Greater))
case token.GreaterEq:
c.emit(node, parser.OpBinaryOp, int(token.GreaterEq))
case token.Less:
c.emit(node, parser.OpBinaryOp, int(token.Less))
case token.LessEq:
c.emit(node, parser.OpBinaryOp, int(token.LessEq))
case token.Equal:
c.emit(node, parser.OpEqual)
case token.NotEqual:
c.emit(node, parser.OpNotEqual)
case token.And:
c.emit(node, parser.OpBinaryOp, int(token.And))
case token.Or:
c.emit(node, parser.OpBinaryOp, int(token.Or))
case token.Xor:
c.emit(node, parser.OpBinaryOp, int(token.Xor))
case token.AndNot:
c.emit(node, parser.OpBinaryOp, int(token.AndNot))
case token.Shl:
c.emit(node, parser.OpBinaryOp, int(token.Shl))
case token.Shr:
c.emit(node, parser.OpBinaryOp, int(token.Shr))
default:
return c.errorf(node, "invalid binary operator: %s",
node.Token.String())
}
case *parser.IntLit:
c.emit(node, parser.OpConstant,
c.addConstant(&Int{Value: node.Value}))
case *parser.FloatLit:
c.emit(node, parser.OpConstant,
c.addConstant(&Float{Value: node.Value}))
case *parser.BoolLit:
if node.Value {
c.emit(node, parser.OpTrue)
} else {
c.emit(node, parser.OpFalse)
}
case *parser.StringLit:
if len(node.Value) > MaxStringLen {
return c.error(node, ErrStringLimit)
}
c.emit(node, parser.OpConstant,
c.addConstant(&String{Value: node.Value}))
case *parser.CharLit:
c.emit(node, parser.OpConstant,
c.addConstant(&Char{Value: node.Value}))
case *parser.UndefinedLit:
c.emit(node, parser.OpNull)
case *parser.UnaryExpr:
if err := c.Compile(node.Expr); err != nil {
return err
}
switch node.Token {
case token.Not:
c.emit(node, parser.OpLNot)
case token.Sub:
c.emit(node, parser.OpMinus)
case token.Xor:
c.emit(node, parser.OpBComplement)
case token.Add:
// do nothing?
default:
return c.errorf(node,
"invalid unary operator: %s", node.Token.String())
}
case *parser.IfStmt:
// open new symbol table for the statement
c.symbolTable = c.symbolTable.Fork(true)
defer func() {
c.symbolTable = c.symbolTable.Parent(false)
}()
if node.Init != nil {
if err := c.Compile(node.Init); err != nil {
return err
}
}
if err := c.Compile(node.Cond); err != nil {
return err
}
// first jump placeholder
jumpPos1 := c.emit(node, parser.OpJumpFalsy, 0)
if err := c.Compile(node.Body); err != nil {
return err
}
if node.Else != nil {
// second jump placeholder
jumpPos2 := c.emit(node, parser.OpJump, 0)
// update first jump offset
curPos := len(c.currentInstructions())
c.changeOperand(jumpPos1, curPos)
if err := c.Compile(node.Else); err != nil {
return err
}
// update second jump offset
curPos = len(c.currentInstructions())
c.changeOperand(jumpPos2, curPos)
} else {
// update first jump offset
curPos := len(c.currentInstructions())
c.changeOperand(jumpPos1, curPos)
}
case *parser.ForStmt:
return c.compileForStmt(node)
case *parser.ForInStmt:
return c.compileForInStmt(node)
case *parser.BranchStmt:
if node.Token == token.Break {
curLoop := c.currentLoop()
if curLoop == nil {
return c.errorf(node, "break not allowed outside loop")
}
pos := c.emit(node, parser.OpJump, 0)
curLoop.Breaks = append(curLoop.Breaks, pos)
} else if node.Token == token.Continue {
curLoop := c.currentLoop()
if curLoop == nil {
return c.errorf(node, "continue not allowed outside loop")
}
pos := c.emit(node, parser.OpJump, 0)
curLoop.Continues = append(curLoop.Continues, pos)
} else {
panic(fmt.Errorf("invalid branch statement: %s",
node.Token.String()))
}
case *parser.BlockStmt:
if len(node.Stmts) == 0 {
return nil
}
c.symbolTable = c.symbolTable.Fork(true)
defer func() {
c.symbolTable = c.symbolTable.Parent(false)
}()
for _, stmt := range node.Stmts {
if err := c.Compile(stmt); err != nil {
return err
}
}
case *parser.AssignStmt:
err := c.compileAssign(node, node.LHS, node.RHS, node.Token)
if err != nil {
return err
}
case *parser.Ident:
symbol, _, ok := c.symbolTable.Resolve(node.Name, false)
if !ok {
return c.errorf(node, "unresolved reference '%s'", node.Name)
}
switch symbol.Scope {
case ScopeGlobal:
c.emit(node, parser.OpGetGlobal, symbol.Index)
case ScopeLocal:
c.emit(node, parser.OpGetLocal, symbol.Index)
case ScopeBuiltin:
c.emit(node, parser.OpGetBuiltin, symbol.Index)
case ScopeFree:
c.emit(node, parser.OpGetFree, symbol.Index)
}
case *parser.ArrayLit:
for _, elem := range node.Elements {
if err := c.Compile(elem); err != nil {
return err
}
}
c.emit(node, parser.OpArray, len(node.Elements))
case *parser.MapLit:
for _, elt := range node.Elements {
// key
if len(elt.Key) > MaxStringLen {
return c.error(node, ErrStringLimit)
}
c.emit(node, parser.OpConstant,
c.addConstant(&String{Value: elt.Key}))
// value
if err := c.Compile(elt.Value); err != nil {
return err
}
}
c.emit(node, parser.OpMap, len(node.Elements)*2)
case *parser.SelectorExpr: // selector on RHS side
if err := c.Compile(node.Expr); err != nil {
return err
}
if err := c.Compile(node.Sel); err != nil {
return err
}
c.emit(node, parser.OpIndex)
case *parser.IndexExpr:
if err := c.Compile(node.Expr); err != nil {
return err
}
if err := c.Compile(node.Index); err != nil {
return err
}
c.emit(node, parser.OpIndex)
case *parser.SliceExpr:
if err := c.Compile(node.Expr); err != nil {
return err
}
if node.Low != nil {
if err := c.Compile(node.Low); err != nil {
return err
}
} else {
c.emit(node, parser.OpNull)
}
if node.High != nil {
if err := c.Compile(node.High); err != nil {
return err
}
} else {
c.emit(node, parser.OpNull)
}
c.emit(node, parser.OpSliceIndex)
case *parser.FuncLit:
c.enterScope()
for _, p := range node.Type.Params.List {
s := c.symbolTable.Define(p.Name)
// function arguments is not assigned directly.
s.LocalAssigned = true
}
if err := c.Compile(node.Body); err != nil {
return err
}
// code optimization
c.optimizeFunc(node)
freeSymbols := c.symbolTable.FreeSymbols()
numLocals := c.symbolTable.MaxSymbols()
instructions, sourceMap := c.leaveScope()
for _, s := range freeSymbols {
switch s.Scope {
case ScopeLocal:
if !s.LocalAssigned {
// Here, the closure is capturing a local variable that's
// not yet assigned its value. One example is a local
// recursive function:
//
// func() {
// foo := func(x) {
// // ..
// return foo(x-1)
// }
// }
//
// which translate into
//
// 0000 GETL 0
// 0002 CLOSURE ? 1
// 0006 DEFL 0
//
// . So the local variable (0) is being captured before
// it's assigned the value.
//
// Solution is to transform the code into something like
// this:
//
// func() {
// foo := undefined
// foo = func(x) {
// // ..
// return foo(x-1)
// }
// }
//
// that is equivalent to
//
// 0000 NULL
// 0001 DEFL 0
// 0003 GETL 0
// 0005 CLOSURE ? 1
// 0009 SETL 0
//
c.emit(node, parser.OpNull)
c.emit(node, parser.OpDefineLocal, s.Index)
s.LocalAssigned = true
}
c.emit(node, parser.OpGetLocalPtr, s.Index)
case ScopeFree:
c.emit(node, parser.OpGetFreePtr, s.Index)
}
}
compiledFunction := &CompiledFunction{
Instructions: instructions,
NumLocals: numLocals,
NumParameters: len(node.Type.Params.List),
VarArgs: node.Type.Params.VarArgs,
SourceMap: sourceMap,
}
if len(freeSymbols) > 0 {
c.emit(node, parser.OpClosure,
c.addConstant(compiledFunction), len(freeSymbols))
} else {
c.emit(node, parser.OpConstant, c.addConstant(compiledFunction))
}
case *parser.ReturnStmt:
if c.symbolTable.Parent(true) == nil {
// outside the function
return c.errorf(node, "return not allowed outside function")
}
if node.Result == nil {
c.emit(node, parser.OpReturn, 0)
} else {
if err := c.Compile(node.Result); err != nil {
return err
}
c.emit(node, parser.OpReturn, 1)
}
case *parser.CallExpr:
if err := c.Compile(node.Func); err != nil {
return err
}
for _, arg := range node.Args {
if err := c.Compile(arg); err != nil {
return err
}
}
ellipsis := 0
if node.Ellipsis.IsValid() {
ellipsis = 1
}
c.emit(node, parser.OpCall, len(node.Args), ellipsis)
case *parser.ImportExpr:
if node.ModuleName == "" {
return c.errorf(node, "empty module name")
}
if mod := c.modules.Get(node.ModuleName); mod != nil {
v, err := mod.Import(node.ModuleName)
if err != nil {
return err
}
switch v := v.(type) {
case []byte: // module written in Tengo
compiled, err := c.compileModule(node,
node.ModuleName, v, false)
if err != nil {
return err
}
c.emit(node, parser.OpConstant, c.addConstant(compiled))
c.emit(node, parser.OpCall, 0, 0)
case Object: // builtin module
c.emit(node, parser.OpConstant, c.addConstant(v))
default:
panic(fmt.Errorf("invalid import value type: %T", v))
}
} else if c.allowFileImport {
moduleName := node.ModuleName
modulePath, err := c.getPathModule(moduleName)
if err != nil {
return c.errorf(node, "module file path error: %s",
err.Error())
}
moduleSrc, err := ioutil.ReadFile(modulePath)
if err != nil {
return c.errorf(node, "module file read error: %s",
err.Error())
}
compiled, err := c.compileModule(node, modulePath, moduleSrc, true)
if err != nil {
return err
}
c.emit(node, parser.OpConstant, c.addConstant(compiled))
c.emit(node, parser.OpCall, 0, 0)
} else {
return c.errorf(node, "module '%s' not found", node.ModuleName)
}
case *parser.ExportStmt:
// export statement must be in top-level scope
if c.scopeIndex != 0 {
return c.errorf(node, "export not allowed inside function")
}
// export statement is simply ignore when compiling non-module code
if c.parent == nil {
break
}
if err := c.Compile(node.Result); err != nil {
return err
}
c.emit(node, parser.OpImmutable)
c.emit(node, parser.OpReturn, 1)
case *parser.ErrorExpr:
if err := c.Compile(node.Expr); err != nil {
return err
}
c.emit(node, parser.OpError)
case *parser.ImmutableExpr:
if err := c.Compile(node.Expr); err != nil {
return err
}
c.emit(node, parser.OpImmutable)
case *parser.CondExpr:
if err := c.Compile(node.Cond); err != nil {
return err
}
// first jump placeholder
jumpPos1 := c.emit(node, parser.OpJumpFalsy, 0)
if err := c.Compile(node.True); err != nil {
return err
}
// second jump placeholder
jumpPos2 := c.emit(node, parser.OpJump, 0)
// update first jump offset
curPos := len(c.currentInstructions())
c.changeOperand(jumpPos1, curPos)
if err := c.Compile(node.False); err != nil {
return err
}
// update second jump offset
curPos = len(c.currentInstructions())
c.changeOperand(jumpPos2, curPos)
}
return nil
}
// Bytecode returns a compiled bytecode.
func (c *Compiler) Bytecode() *Bytecode {
return &Bytecode{
FileSet: c.file.Set(),
MainFunction: &CompiledFunction{
Instructions: append(c.currentInstructions(), parser.OpSuspend),
SourceMap: c.currentSourceMap(),
},
Constants: c.constants,
}
}
// EnableFileImport enables or disables module loading from local files.
// Local file modules are disabled by default.
func (c *Compiler) EnableFileImport(enable bool) {
c.allowFileImport = enable
}
// SetImportDir sets the initial import directory path for file imports.
func (c *Compiler) SetImportDir(dir string) {
c.importDir = dir
}
// SetImportFileExt sets the extension name of the source file for loading
// local module files.
//
// Use this method if you want other source file extension than ".tengo".
//
// // this will search for *.tengo, *.foo, *.bar
// err := c.SetImportFileExt(".tengo", ".foo", ".bar")
//
// This function requires at least one argument, since it will replace the
// current list of extension name.
func (c *Compiler) SetImportFileExt(exts ...string) error {
if len(exts) == 0 {
return fmt.Errorf("missing arg: at least one argument is required")
}
for _, ext := range exts {
if ext != filepath.Ext(ext) || ext == "" {
return fmt.Errorf("invalid file extension: %s", ext)
}
}
c.importFileExt = exts // Replace the hole current extension list
return nil
}
// GetImportFileExt returns the current list of extension name.
// Thease are the complementary suffix of the source file to search and load
// local module files.
func (c *Compiler) GetImportFileExt() []string {
return c.importFileExt
}
func (c *Compiler) compileAssign(
node parser.Node,
lhs, rhs []parser.Expr,
op token.Token,
) error {
numLHS, numRHS := len(lhs), len(rhs)
if numLHS > 1 || numRHS > 1 {
return c.errorf(node, "tuple assignment not allowed")
}
// resolve and compile left-hand side
ident, selectors := resolveAssignLHS(lhs[0])
numSel := len(selectors)
if op == token.Define && numSel > 0 {
// using selector on new variable does not make sense
return c.errorf(node, "operator ':=' not allowed with selector")
}
_, isFunc := rhs[0].(*parser.FuncLit)
symbol, depth, exists := c.symbolTable.Resolve(ident, false)
if op == token.Define {
if depth == 0 && exists {
return c.errorf(node, "'%s' redeclared in this block", ident)
}
if isFunc {
symbol = c.symbolTable.Define(ident)
}
} else {
if !exists {
return c.errorf(node, "unresolved reference '%s'", ident)
}
}
// +=, -=, *=, /=
if op != token.Assign && op != token.Define {
if err := c.Compile(lhs[0]); err != nil {
return err
}
}
// compile RHSs
for _, expr := range rhs {
if err := c.Compile(expr); err != nil {
return err
}
}
if op == token.Define && !isFunc {
symbol = c.symbolTable.Define(ident)
}
switch op {
case token.AddAssign:
c.emit(node, parser.OpBinaryOp, int(token.Add))
case token.SubAssign:
c.emit(node, parser.OpBinaryOp, int(token.Sub))
case token.MulAssign:
c.emit(node, parser.OpBinaryOp, int(token.Mul))
case token.QuoAssign:
c.emit(node, parser.OpBinaryOp, int(token.Quo))
case token.RemAssign:
c.emit(node, parser.OpBinaryOp, int(token.Rem))
case token.AndAssign:
c.emit(node, parser.OpBinaryOp, int(token.And))
case token.OrAssign:
c.emit(node, parser.OpBinaryOp, int(token.Or))
case token.AndNotAssign:
c.emit(node, parser.OpBinaryOp, int(token.AndNot))
case token.XorAssign:
c.emit(node, parser.OpBinaryOp, int(token.Xor))
case token.ShlAssign:
c.emit(node, parser.OpBinaryOp, int(token.Shl))
case token.ShrAssign:
c.emit(node, parser.OpBinaryOp, int(token.Shr))
}
// compile selector expressions (right to left)
for i := numSel - 1; i >= 0; i-- {
if err := c.Compile(selectors[i]); err != nil {
return err
}
}
switch symbol.Scope {
case ScopeGlobal:
if numSel > 0 {
c.emit(node, parser.OpSetSelGlobal, symbol.Index, numSel)
} else {
c.emit(node, parser.OpSetGlobal, symbol.Index)
}
case ScopeLocal:
if numSel > 0 {
c.emit(node, parser.OpSetSelLocal, symbol.Index, numSel)
} else {
if op == token.Define && !symbol.LocalAssigned {
c.emit(node, parser.OpDefineLocal, symbol.Index)
} else {
c.emit(node, parser.OpSetLocal, symbol.Index)
}
}
// mark the symbol as local-assigned
symbol.LocalAssigned = true
case ScopeFree:
if numSel > 0 {
c.emit(node, parser.OpSetSelFree, symbol.Index, numSel)
} else {
c.emit(node, parser.OpSetFree, symbol.Index)
}
default:
panic(fmt.Errorf("invalid assignment variable scope: %s",
symbol.Scope))
}
return nil
}
func (c *Compiler) compileLogical(node *parser.BinaryExpr) error {
// left side term
if err := c.Compile(node.LHS); err != nil {
return err
}
// jump position
var jumpPos int
if node.Token == token.LAnd {
jumpPos = c.emit(node, parser.OpAndJump, 0)
} else {
jumpPos = c.emit(node, parser.OpOrJump, 0)
}
// right side term
if err := c.Compile(node.RHS); err != nil {
return err
}
c.changeOperand(jumpPos, len(c.currentInstructions()))
return nil
}
func (c *Compiler) compileForStmt(stmt *parser.ForStmt) error {
c.symbolTable = c.symbolTable.Fork(true)
defer func() {
c.symbolTable = c.symbolTable.Parent(false)
}()
// init statement
if stmt.Init != nil {
if err := c.Compile(stmt.Init); err != nil {
return err
}
}
// pre-condition position
preCondPos := len(c.currentInstructions())
// condition expression
postCondPos := -1
if stmt.Cond != nil {
if err := c.Compile(stmt.Cond); err != nil {
return err
}
// condition jump position
postCondPos = c.emit(stmt, parser.OpJumpFalsy, 0)
}
// enter loop
loop := c.enterLoop()
// body statement
if err := c.Compile(stmt.Body); err != nil {
c.leaveLoop()
return err
}
c.leaveLoop()
// post-body position
postBodyPos := len(c.currentInstructions())
// post statement
if stmt.Post != nil {
if err := c.Compile(stmt.Post); err != nil {
return err
}
}
// back to condition
c.emit(stmt, parser.OpJump, preCondPos)
// post-statement position
postStmtPos := len(c.currentInstructions())
if postCondPos >= 0 {
c.changeOperand(postCondPos, postStmtPos)
}
// update all break/continue jump positions
for _, pos := range loop.Breaks {
c.changeOperand(pos, postStmtPos)
}
for _, pos := range loop.Continues {
c.changeOperand(pos, postBodyPos)
}
return nil
}
func (c *Compiler) compileForInStmt(stmt *parser.ForInStmt) error {
c.symbolTable = c.symbolTable.Fork(true)
defer func() {
c.symbolTable = c.symbolTable.Parent(false)
}()
// for-in statement is compiled like following:
//
// for :it := iterator(iterable); :it.next(); {
// k, v := :it.get() // DEFINE operator
//
// ... body ...
// }
//
// ":it" is a local variable but it will not conflict with other user variables
// because character ":" is not allowed in the variable names.
// init
// :it = iterator(iterable)
itSymbol := c.symbolTable.Define(":it")
if err := c.Compile(stmt.Iterable); err != nil {
return err
}
c.emit(stmt, parser.OpIteratorInit)
if itSymbol.Scope == ScopeGlobal {
c.emit(stmt, parser.OpSetGlobal, itSymbol.Index)
} else {
c.emit(stmt, parser.OpDefineLocal, itSymbol.Index)
}
// pre-condition position
preCondPos := len(c.currentInstructions())
// condition
// :it.HasMore()
if itSymbol.Scope == ScopeGlobal {
c.emit(stmt, parser.OpGetGlobal, itSymbol.Index)
} else {
c.emit(stmt, parser.OpGetLocal, itSymbol.Index)
}
c.emit(stmt, parser.OpIteratorNext)
// condition jump position
postCondPos := c.emit(stmt, parser.OpJumpFalsy, 0)
// enter loop
loop := c.enterLoop()
// assign key variable
if stmt.Key.Name != "_" {
keySymbol := c.symbolTable.Define(stmt.Key.Name)
if itSymbol.Scope == ScopeGlobal {
c.emit(stmt, parser.OpGetGlobal, itSymbol.Index)
} else {
c.emit(stmt, parser.OpGetLocal, itSymbol.Index)
}
c.emit(stmt, parser.OpIteratorKey)
if keySymbol.Scope == ScopeGlobal {
c.emit(stmt, parser.OpSetGlobal, keySymbol.Index)
} else {
keySymbol.LocalAssigned = true
c.emit(stmt, parser.OpDefineLocal, keySymbol.Index)
}
}
// assign value variable
if stmt.Value.Name != "_" {
valueSymbol := c.symbolTable.Define(stmt.Value.Name)
if itSymbol.Scope == ScopeGlobal {
c.emit(stmt, parser.OpGetGlobal, itSymbol.Index)
} else {
c.emit(stmt, parser.OpGetLocal, itSymbol.Index)
}
c.emit(stmt, parser.OpIteratorValue)
if valueSymbol.Scope == ScopeGlobal {
c.emit(stmt, parser.OpSetGlobal, valueSymbol.Index)
} else {
valueSymbol.LocalAssigned = true
c.emit(stmt, parser.OpDefineLocal, valueSymbol.Index)
}
}
// body statement
if err := c.Compile(stmt.Body); err != nil {
c.leaveLoop()
return err
}
c.leaveLoop()
// post-body position
postBodyPos := len(c.currentInstructions())
// back to condition
c.emit(stmt, parser.OpJump, preCondPos)
// post-statement position
postStmtPos := len(c.currentInstructions())
c.changeOperand(postCondPos, postStmtPos)
// update all break/continue jump positions
for _, pos := range loop.Breaks {
c.changeOperand(pos, postStmtPos)
}
for _, pos := range loop.Continues {
c.changeOperand(pos, postBodyPos)
}
return nil
}
func (c *Compiler) checkCyclicImports(
node parser.Node,
modulePath string,
) error {
if c.modulePath == modulePath {
return c.errorf(node, "cyclic module import: %s", modulePath)
} else if c.parent != nil {
return c.parent.checkCyclicImports(node, modulePath)
}
return nil
}
func (c *Compiler) compileModule(
node parser.Node,
modulePath string,
src []byte,
isFile bool,
) (*CompiledFunction, error) {
if err := c.checkCyclicImports(node, modulePath); err != nil {
return nil, err
}
compiledModule, exists := c.loadCompiledModule(modulePath)