-
Notifications
You must be signed in to change notification settings - Fork 382
/
compiler.go
1481 lines (1351 loc) · 35.3 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 goja
import (
"fmt"
"github.com/dop251/goja/token"
"sort"
"github.com/dop251/goja/ast"
"github.com/dop251/goja/file"
"github.com/dop251/goja/unistring"
)
type blockType int
const (
blockLoop blockType = iota
blockLoopEnum
blockTry
blockLabel
blockSwitch
blockWith
blockScope
blockIterScope
blockOptChain
)
const (
maskConst = 1 << 31
maskVar = 1 << 30
maskDeletable = 1 << 29
maskStrict = maskDeletable
maskTyp = maskConst | maskVar | maskDeletable
)
type varType byte
const (
varTypeVar varType = iota
varTypeLet
varTypeStrictConst
varTypeConst
)
const thisBindingName = " this" // must not be a valid identifier
type CompilerError struct {
Message string
File *file.File
Offset int
}
type CompilerSyntaxError struct {
CompilerError
}
type CompilerReferenceError struct {
CompilerError
}
type srcMapItem struct {
pc int
srcPos int
}
// Program is an internal, compiled representation of code which is produced by the Compile function.
// This representation is not linked to a runtime in any way and can be used concurrently.
// It is always preferable to use a Program over a string when running code as it skips the compilation step.
type Program struct {
code []instruction
funcName unistring.String
src *file.File
srcMap []srcMapItem
}
type compiler struct {
p *Program
scope *scope
block *block
classScope *classScope
enumGetExpr compiledEnumGetExpr
evalVM *vm // VM used to evaluate constant expressions
ctxVM *vm // VM in which an eval() code is compiled
codeScratchpad []instruction
stringCache map[unistring.String]Value
}
type binding struct {
scope *scope
name unistring.String
accessPoints map[*scope]*[]int
isConst bool
isStrict bool
isArg bool
isVar bool
inStash bool
}
func (b *binding) getAccessPointsForScope(s *scope) *[]int {
m := b.accessPoints[s]
if m == nil {
a := make([]int, 0, 1)
m = &a
if b.accessPoints == nil {
b.accessPoints = make(map[*scope]*[]int)
}
b.accessPoints[s] = m
}
return m
}
func (b *binding) markAccessPointAt(pos int) {
scope := b.scope.c.scope
m := b.getAccessPointsForScope(scope)
*m = append(*m, pos-scope.base)
}
func (b *binding) markAccessPointAtScope(scope *scope, pos int) {
m := b.getAccessPointsForScope(scope)
*m = append(*m, pos-scope.base)
}
func (b *binding) markAccessPoint() {
scope := b.scope.c.scope
m := b.getAccessPointsForScope(scope)
*m = append(*m, len(scope.prg.code)-scope.base)
}
func (b *binding) emitGet() {
b.markAccessPoint()
if b.isVar && !b.isArg {
b.scope.c.emit(loadStack(0))
} else {
b.scope.c.emit(loadStackLex(0))
}
}
func (b *binding) emitGetAt(pos int) {
b.markAccessPointAt(pos)
if b.isVar && !b.isArg {
b.scope.c.p.code[pos] = loadStack(0)
} else {
b.scope.c.p.code[pos] = loadStackLex(0)
}
}
func (b *binding) emitGetP() {
if b.isVar && !b.isArg {
// no-op
} else {
// make sure TDZ is checked
b.markAccessPoint()
b.scope.c.emit(loadStackLex(0), pop)
}
}
func (b *binding) emitSet() {
if b.isConst {
if b.isStrict || b.scope.c.scope.strict {
b.scope.c.emit(throwAssignToConst)
}
return
}
b.markAccessPoint()
if b.isVar && !b.isArg {
b.scope.c.emit(storeStack(0))
} else {
b.scope.c.emit(storeStackLex(0))
}
}
func (b *binding) emitSetP() {
if b.isConst {
if b.isStrict || b.scope.c.scope.strict {
b.scope.c.emit(throwAssignToConst)
}
return
}
b.markAccessPoint()
if b.isVar && !b.isArg {
b.scope.c.emit(storeStackP(0))
} else {
b.scope.c.emit(storeStackLexP(0))
}
}
func (b *binding) emitInitP() {
if !b.isVar && b.scope.outer == nil {
b.scope.c.emit(initGlobalP(b.name))
} else {
b.markAccessPoint()
b.scope.c.emit(initStackP(0))
}
}
func (b *binding) emitInit() {
if !b.isVar && b.scope.outer == nil {
b.scope.c.emit(initGlobal(b.name))
} else {
b.markAccessPoint()
b.scope.c.emit(initStack(0))
}
}
func (b *binding) emitInitAt(pos int) {
if !b.isVar && b.scope.outer == nil {
b.scope.c.p.code[pos] = initGlobal(b.name)
} else {
b.markAccessPointAt(pos)
b.scope.c.p.code[pos] = initStack(0)
}
}
func (b *binding) emitInitAtScope(scope *scope, pos int) {
if !b.isVar && scope.outer == nil {
scope.c.p.code[pos] = initGlobal(b.name)
} else {
b.markAccessPointAtScope(scope, pos)
scope.c.p.code[pos] = initStack(0)
}
}
func (b *binding) emitInitPAtScope(scope *scope, pos int) {
if !b.isVar && scope.outer == nil {
scope.c.p.code[pos] = initGlobalP(b.name)
} else {
b.markAccessPointAtScope(scope, pos)
scope.c.p.code[pos] = initStackP(0)
}
}
func (b *binding) emitGetVar(callee bool) {
b.markAccessPoint()
if b.isVar && !b.isArg {
b.scope.c.emit(&loadMixed{name: b.name, callee: callee})
} else {
b.scope.c.emit(&loadMixedLex{name: b.name, callee: callee})
}
}
func (b *binding) emitResolveVar(strict bool) {
b.markAccessPoint()
if b.isVar && !b.isArg {
b.scope.c.emit(&resolveMixed{name: b.name, strict: strict, typ: varTypeVar})
} else {
var typ varType
if b.isConst {
if b.isStrict {
typ = varTypeStrictConst
} else {
typ = varTypeConst
}
} else {
typ = varTypeLet
}
b.scope.c.emit(&resolveMixed{name: b.name, strict: strict, typ: typ})
}
}
func (b *binding) moveToStash() {
if b.isArg && !b.scope.argsInStash {
b.scope.moveArgsToStash()
} else {
b.inStash = true
b.scope.needStash = true
}
}
func (b *binding) useCount() (count int) {
for _, a := range b.accessPoints {
count += len(*a)
}
return
}
type scope struct {
c *compiler
prg *Program
outer *scope
nested []*scope
boundNames map[unistring.String]*binding
bindings []*binding
base int
numArgs int
// function type. If not funcNone, this is a function or a top-level lexical environment
funcType funcType
// in strict mode
strict bool
// eval top-level scope
eval bool
// at least one inner scope has direct eval() which can lookup names dynamically (by name)
dynLookup bool
// at least one binding has been marked for placement in stash
needStash bool
// is a variable environment, i.e. the target for dynamically created var bindings
variable bool
// a function scope that has at least one direct eval() and non-strict, so the variables can be added dynamically
dynamic bool
// arguments have been marked for placement in stash (functions only)
argsInStash bool
// need 'arguments' object (functions only)
argsNeeded bool
}
type block struct {
typ blockType
label unistring.String
cont int
breaks []int
conts []int
outer *block
breaking *block // set when the 'finally' block is an empty break statement sequence
needResult bool
}
func (c *compiler) leaveScopeBlock(enter *enterBlock) {
c.updateEnterBlock(enter)
leave := &leaveBlock{
stackSize: enter.stackSize,
popStash: enter.stashSize > 0,
}
c.emit(leave)
for _, pc := range c.block.breaks {
c.p.code[pc] = leave
}
c.block.breaks = nil
c.leaveBlock()
}
func (c *compiler) leaveBlock() {
lbl := len(c.p.code)
for _, item := range c.block.breaks {
c.p.code[item] = jump(lbl - item)
}
if t := c.block.typ; t == blockLoop || t == blockLoopEnum {
for _, item := range c.block.conts {
c.p.code[item] = jump(c.block.cont - item)
}
}
c.block = c.block.outer
}
func (e *CompilerSyntaxError) Error() string {
if e.File != nil {
return fmt.Sprintf("SyntaxError: %s at %s", e.Message, e.File.Position(e.Offset))
}
return fmt.Sprintf("SyntaxError: %s", e.Message)
}
func (e *CompilerReferenceError) Error() string {
return fmt.Sprintf("ReferenceError: %s", e.Message)
}
func (c *compiler) newScope() {
strict := false
if c.scope != nil {
strict = c.scope.strict
}
c.scope = &scope{
c: c,
prg: c.p,
outer: c.scope,
strict: strict,
}
}
func (c *compiler) newBlockScope() {
c.newScope()
if outer := c.scope.outer; outer != nil {
outer.nested = append(outer.nested, c.scope)
}
c.scope.base = len(c.p.code)
}
func (c *compiler) popScope() {
c.scope = c.scope.outer
}
func (c *compiler) emitLiteralString(s String) {
key := s.string()
if c.stringCache == nil {
c.stringCache = make(map[unistring.String]Value)
}
internVal := c.stringCache[key]
if internVal == nil {
c.stringCache[key] = s
internVal = s
}
c.emit(loadVal{internVal})
}
func (c *compiler) emitLiteralValue(v Value) {
if s, ok := v.(String); ok {
c.emitLiteralString(s)
return
}
c.emit(loadVal{v})
}
func newCompiler() *compiler {
c := &compiler{
p: &Program{},
}
c.enumGetExpr.init(c, file.Idx(0))
return c
}
func (p *Program) dumpCode(logger func(format string, args ...interface{})) {
p._dumpCode("", logger)
}
func (p *Program) _dumpCode(indent string, logger func(format string, args ...interface{})) {
dumpInitFields := func(initFields *Program) {
i := indent + ">"
logger("%s ---- init_fields:", i)
initFields._dumpCode(i, logger)
logger("%s ----", i)
}
for pc, ins := range p.code {
logger("%s %d: %T(%v)", indent, pc, ins, ins)
var prg *Program
switch f := ins.(type) {
case newFuncInstruction:
prg = f.getPrg()
case *newDerivedClass:
if f.initFields != nil {
dumpInitFields(f.initFields)
}
prg = f.ctor
case *newClass:
if f.initFields != nil {
dumpInitFields(f.initFields)
}
prg = f.ctor
case *newStaticFieldInit:
if f.initFields != nil {
dumpInitFields(f.initFields)
}
}
if prg != nil {
prg._dumpCode(indent+">", logger)
}
}
}
func (p *Program) sourceOffset(pc int) int {
i := sort.Search(len(p.srcMap), func(idx int) bool {
return p.srcMap[idx].pc > pc
}) - 1
if i >= 0 {
return p.srcMap[i].srcPos
}
return 0
}
func (p *Program) addSrcMap(srcPos int) {
if len(p.srcMap) > 0 && p.srcMap[len(p.srcMap)-1].srcPos == srcPos {
return
}
p.srcMap = append(p.srcMap, srcMapItem{pc: len(p.code), srcPos: srcPos})
}
func (s *scope) lookupName(name unistring.String) (binding *binding, noDynamics bool) {
noDynamics = true
toStash := false
for curScope := s; ; curScope = curScope.outer {
if curScope.outer != nil {
if b, exists := curScope.boundNames[name]; exists {
if toStash && !b.inStash {
b.moveToStash()
}
binding = b
return
}
} else {
noDynamics = false
return
}
if curScope.dynamic {
noDynamics = false
}
if name == "arguments" && curScope.funcType != funcNone && curScope.funcType != funcArrow {
if curScope.funcType == funcClsInit {
s.c.throwSyntaxError(0, "'arguments' is not allowed in class field initializer or static initialization block")
}
curScope.argsNeeded = true
binding, _ = curScope.bindName(name)
return
}
if curScope.isFunction() {
toStash = true
}
}
}
func (s *scope) lookupThis() (*binding, bool) {
toStash := false
for curScope := s; curScope != nil; curScope = curScope.outer {
if curScope.outer == nil {
if curScope.eval {
return nil, true
}
}
if b, exists := curScope.boundNames[thisBindingName]; exists {
if toStash && !b.inStash {
b.moveToStash()
}
return b, false
}
if curScope.isFunction() {
toStash = true
}
}
return nil, false
}
func (s *scope) ensureBoundNamesCreated() {
if s.boundNames == nil {
s.boundNames = make(map[unistring.String]*binding)
}
}
func (s *scope) addBinding(offset int) *binding {
if len(s.bindings) >= (1<<24)-1 {
s.c.throwSyntaxError(offset, "Too many variables")
}
b := &binding{
scope: s,
}
s.bindings = append(s.bindings, b)
return b
}
func (s *scope) bindNameLexical(name unistring.String, unique bool, offset int) (*binding, bool) {
if b := s.boundNames[name]; b != nil {
if unique {
s.c.throwSyntaxError(offset, "Identifier '%s' has already been declared", name)
}
return b, false
}
b := s.addBinding(offset)
b.name = name
s.ensureBoundNamesCreated()
s.boundNames[name] = b
return b, true
}
func (s *scope) createThisBinding() *binding {
thisBinding, _ := s.bindNameLexical(thisBindingName, false, 0)
thisBinding.isVar = true // don't check on load
return thisBinding
}
func (s *scope) bindName(name unistring.String) (*binding, bool) {
if !s.isFunction() && !s.variable && s.outer != nil {
return s.outer.bindName(name)
}
b, created := s.bindNameLexical(name, false, 0)
if created {
b.isVar = true
}
return b, created
}
func (s *scope) bindNameShadow(name unistring.String) (*binding, bool) {
if !s.isFunction() && s.outer != nil {
return s.outer.bindNameShadow(name)
}
_, exists := s.boundNames[name]
b := &binding{
scope: s,
name: name,
}
s.bindings = append(s.bindings, b)
s.ensureBoundNamesCreated()
s.boundNames[name] = b
return b, !exists
}
func (s *scope) nearestFunction() *scope {
for sc := s; sc != nil; sc = sc.outer {
if sc.isFunction() {
return sc
}
}
return nil
}
func (s *scope) nearestThis() *scope {
for sc := s; sc != nil; sc = sc.outer {
if sc.eval || sc.isFunction() && sc.funcType != funcArrow {
return sc
}
}
return nil
}
func (s *scope) finaliseVarAlloc(stackOffset int) (stashSize, stackSize int) {
argsInStash := false
if f := s.nearestFunction(); f != nil {
argsInStash = f.argsInStash
}
stackIdx, stashIdx := 0, 0
allInStash := s.isDynamic()
var derivedCtor bool
if fs := s.nearestThis(); fs != nil && fs.funcType == funcDerivedCtor {
derivedCtor = true
}
for i, b := range s.bindings {
var this bool
if b.name == thisBindingName {
this = true
}
if allInStash || b.inStash {
for scope, aps := range b.accessPoints {
var level uint32
for sc := scope; sc != nil && sc != s; sc = sc.outer {
if sc.needStash || sc.isDynamic() {
level++
}
}
if level > 255 {
s.c.throwSyntaxError(0, "Maximum nesting level (256) exceeded")
}
idx := (level << 24) | uint32(stashIdx)
base := scope.base
code := scope.prg.code
if this {
if derivedCtor {
for _, pc := range *aps {
ap := &code[base+pc]
switch (*ap).(type) {
case loadStack:
*ap = loadThisStash(idx)
case initStack:
*ap = initStash(idx)
case resolveThisStack:
*ap = resolveThisStash(idx)
case _ret:
*ap = cret(idx)
default:
s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for 'this'")
}
}
} else {
for _, pc := range *aps {
ap := &code[base+pc]
switch (*ap).(type) {
case loadStack:
*ap = loadStash(idx)
case initStack:
*ap = initStash(idx)
default:
s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for 'this'")
}
}
}
} else {
for _, pc := range *aps {
ap := &code[base+pc]
switch i := (*ap).(type) {
case loadStack:
*ap = loadStash(idx)
case storeStack:
*ap = storeStash(idx)
case storeStackP:
*ap = storeStashP(idx)
case loadStackLex:
*ap = loadStashLex(idx)
case storeStackLex:
*ap = storeStashLex(idx)
case storeStackLexP:
*ap = storeStashLexP(idx)
case initStackP:
*ap = initStashP(idx)
case initStack:
*ap = initStash(idx)
case *loadMixed:
i.idx = idx
case *loadMixedLex:
i.idx = idx
case *resolveMixed:
i.idx = idx
default:
s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i)
}
}
}
}
stashIdx++
} else {
var idx int
if !this {
if i < s.numArgs {
idx = -(i + 1)
} else {
stackIdx++
idx = stackIdx + stackOffset
}
}
for scope, aps := range b.accessPoints {
var level int
for sc := scope; sc != nil && sc != s; sc = sc.outer {
if sc.needStash || sc.isDynamic() {
level++
}
}
if level > 255 {
s.c.throwSyntaxError(0, "Maximum nesting level (256) exceeded")
}
code := scope.prg.code
base := scope.base
if this {
if derivedCtor {
for _, pc := range *aps {
ap := &code[base+pc]
switch (*ap).(type) {
case loadStack:
*ap = loadThisStack{}
case initStack:
// no-op
case resolveThisStack:
// no-op
case _ret:
// no-op, already in the right place
default:
s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for 'this'")
}
}
} /*else {
no-op
}*/
} else if argsInStash {
for _, pc := range *aps {
ap := &code[base+pc]
switch i := (*ap).(type) {
case loadStack:
*ap = loadStack1(idx)
case storeStack:
*ap = storeStack1(idx)
case storeStackP:
*ap = storeStack1P(idx)
case loadStackLex:
*ap = loadStack1Lex(idx)
case storeStackLex:
*ap = storeStack1Lex(idx)
case storeStackLexP:
*ap = storeStack1LexP(idx)
case initStackP:
*ap = initStack1P(idx)
case initStack:
*ap = initStack1(idx)
case *loadMixed:
*ap = &loadMixedStack1{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
case *loadMixedLex:
*ap = &loadMixedStack1Lex{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
case *resolveMixed:
*ap = &resolveMixedStack1{typ: i.typ, name: i.name, idx: idx, level: uint8(level), strict: i.strict}
default:
s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i)
}
}
} else {
for _, pc := range *aps {
ap := &code[base+pc]
switch i := (*ap).(type) {
case loadStack:
*ap = loadStack(idx)
case storeStack:
*ap = storeStack(idx)
case storeStackP:
*ap = storeStackP(idx)
case loadStackLex:
*ap = loadStackLex(idx)
case storeStackLex:
*ap = storeStackLex(idx)
case storeStackLexP:
*ap = storeStackLexP(idx)
case initStack:
*ap = initStack(idx)
case initStackP:
*ap = initStackP(idx)
case *loadMixed:
*ap = &loadMixedStack{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
case *loadMixedLex:
*ap = &loadMixedStackLex{name: i.name, idx: idx, level: uint8(level), callee: i.callee}
case *resolveMixed:
*ap = &resolveMixedStack{typ: i.typ, name: i.name, idx: idx, level: uint8(level), strict: i.strict}
default:
s.c.assert(false, s.c.p.sourceOffset(pc), "Unsupported instruction for binding: %T", i)
}
}
}
}
}
}
for _, nested := range s.nested {
nested.finaliseVarAlloc(stackIdx + stackOffset)
}
return stashIdx, stackIdx
}
func (s *scope) moveArgsToStash() {
for _, b := range s.bindings {
if !b.isArg {
break
}
b.inStash = true
}
s.argsInStash = true
s.needStash = true
}
func (c *compiler) trimCode(delta int) {
src := c.p.code[delta:]
newCode := make([]instruction, len(src))
copy(newCode, src)
if cap(c.codeScratchpad) < cap(c.p.code) {
c.codeScratchpad = c.p.code[:0]
}
c.p.code = newCode
}
func (s *scope) trimCode(delta int) {
s.c.trimCode(delta)
if delta != 0 {
srcMap := s.c.p.srcMap
for i := range srcMap {
srcMap[i].pc -= delta
}
s.adjustBase(-delta)
}
}
func (s *scope) adjustBase(delta int) {
s.base += delta
for _, nested := range s.nested {
nested.adjustBase(delta)
}
}
func (s *scope) makeNamesMap() map[unistring.String]uint32 {
l := len(s.bindings)
if l == 0 {
return nil
}
names := make(map[unistring.String]uint32, l)
for i, b := range s.bindings {
idx := uint32(i)
if b.isConst {
idx |= maskConst
if b.isStrict {
idx |= maskStrict
}
}
if b.isVar {
idx |= maskVar
}
names[b.name] = idx
}
return names
}
func (s *scope) isDynamic() bool {
return s.dynLookup || s.dynamic
}
func (s *scope) isFunction() bool {
return s.funcType != funcNone && !s.eval
}
func (s *scope) deleteBinding(b *binding) {
idx := 0
for i, bb := range s.bindings {
if bb == b {
idx = i
goto found
}
}
return
found:
delete(s.boundNames, b.name)
copy(s.bindings[idx:], s.bindings[idx+1:])
l := len(s.bindings) - 1
s.bindings[l] = nil
s.bindings = s.bindings[:l]
}
func (c *compiler) compile(in *ast.Program, strict, inGlobal bool, evalVm *vm) {
c.ctxVM = evalVm
eval := evalVm != nil
c.p.src = in.File
c.newScope()
scope := c.scope
scope.dynamic = true
scope.eval = eval
if !strict && len(in.Body) > 0 {
strict = c.isStrict(in.Body) != nil
}
scope.strict = strict
ownVarScope := eval && strict
ownLexScope := !inGlobal || eval
if ownVarScope {
c.newBlockScope()
scope = c.scope
scope.variable = true
}
if eval && !inGlobal {
for s := evalVm.stash; s != nil; s = s.outer {
if ft := s.funcType; ft != funcNone && ft != funcArrow {
scope.funcType = ft
break
}
}
}
funcs := c.extractFunctions(in.Body)
c.createFunctionBindings(funcs)
numFuncs := len(scope.bindings)
if inGlobal && !ownVarScope {
if numFuncs == len(funcs) {
c.compileFunctionsGlobalAllUnique(funcs)
} else {
c.compileFunctionsGlobal(funcs)
}
}
c.compileDeclList(in.DeclarationList, false)
numVars := len(scope.bindings) - numFuncs
vars := make([]unistring.String, len(scope.bindings))
for i, b := range scope.bindings {
vars[i] = b.name
}
if len(vars) > 0 && !ownVarScope && ownLexScope {
if inGlobal {
c.emit(&bindGlobal{
vars: vars[numFuncs:],
funcs: vars[:numFuncs],
deletable: eval,
})
} else {
c.emit(&bindVars{names: vars, deletable: eval})
}
}
var enter *enterBlock
if c.compileLexicalDeclarations(in.Body, ownVarScope || !ownLexScope) {
if ownLexScope {
c.block = &block{
outer: c.block,
typ: blockScope,
needResult: true,
}
enter = &enterBlock{}
c.emit(enter)
}
}
if len(scope.bindings) > 0 && !ownLexScope {
var lets, consts []unistring.String
for _, b := range c.scope.bindings[numFuncs+numVars:] {
if b.isConst {
consts = append(consts, b.name)
} else {
lets = append(lets, b.name)
}
}
c.emit(&bindGlobal{
vars: vars[numFuncs:],
funcs: vars[:numFuncs],
lets: lets,
consts: consts,
})
}
if !inGlobal || ownVarScope {
c.compileFunctions(funcs)
}
c.compileStatements(in.Body, true)
if enter != nil {
c.leaveScopeBlock(enter)
c.popScope()
}
scope.finaliseVarAlloc(0)
c.stringCache = nil
}
func (c *compiler) compileDeclList(v []*ast.VariableDeclaration, inFunc bool) {