forked from google/starlark-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile.go
1927 lines (1712 loc) · 48.1 KB
/
compile.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 compile defines the Starlark bytecode compiler.
// It is an internal package of the Starlark interpreter and is not directly accessible to clients.
//
// The compiler generates byte code with optional uint32 operands for a
// virtual machine with the following components:
// - a program counter, which is an index into the byte code array.
// - an operand stack, whose maximum size is computed for each function by the compiler.
// - an stack of active iterators.
// - an array of local variables.
// The number of local variables and their indices are computed by the resolver.
// Locals (possibly including parameters) that are shared with nested functions
// are 'cells': their locals array slot will contain a value of type 'cell',
// an indirect value in a box that is explicitly read/updated by instructions.
// - an array of free variables, for nested functions.
// Free variables are a subset of the ancestors' cell variables.
// As with locals and cells, these are computed by the resolver.
// - an array of global variables, shared among all functions in the same module.
// All elements are initially nil.
// - two maps of predeclared and universal identifiers.
//
// Each function has a line number table that maps each program counter
// offset to a source position, including the column number.
//
// Operands, logically uint32s, are encoded using little-endian 7-bit
// varints, the top bit indicating that more bytes follow.
package compile // import "go.starlark.net/internal/compile"
import (
"bytes"
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"go.starlark.net/resolve"
"go.starlark.net/syntax"
)
// Disassemble causes the assembly code for each function
// to be printed to stderr as it is generated.
var Disassemble = false
const debug = false // make code generation verbose, for debugging the compiler
// Increment this to force recompilation of saved bytecode files.
const Version = 14
type Opcode uint8
// "x DUP x x" is a "stack picture" that describes the state of the
// stack before and after execution of the instruction.
//
// OP<index> indicates an immediate operand that is an index into the
// specified table: locals, names, freevars, constants.
const (
NOP Opcode = iota // - NOP -
// stack operations
DUP // x DUP x x
DUP2 // x y DUP2 x y x y
POP // x POP -
EXCH // x y EXCH y x
// binary comparisons
// (order must match Token)
LT
GT
GE
LE
EQL
NEQ
// binary arithmetic
// (order must match Token)
PLUS
MINUS
STAR
SLASH
SLASHSLASH
PERCENT
AMP
PIPE
CIRCUMFLEX
LTLT
GTGT
IN
// unary operators
UPLUS // x UPLUS x
UMINUS // x UMINUS -x
TILDE // x TILDE ~x
NONE // - NONE None
TRUE // - TRUE True
FALSE // - FALSE False
MANDATORY // - MANDATORY Mandatory [sentinel value for required kwonly args]
ITERPUSH // iterable ITERPUSH - [pushes the iterator stack]
ITERPOP // - ITERPOP - [pops the iterator stack]
NOT // value NOT bool
RETURN // value RETURN -
SETINDEX // a i new SETINDEX -
INDEX // a i INDEX elem
SETDICT // dict key value SETDICT -
SETDICTUNIQ // dict key value SETDICTUNIQ -
APPEND // list elem APPEND -
SLICE // x lo hi step SLICE slice
INPLACE_ADD // x y INPLACE_ADD z where z is x+y or x.extend(y)
INPLACE_PIPE // x y INPLACE_PIPE z where z is x|y
MAKEDICT // - MAKEDICT dict
// --- opcodes with an argument must go below this line ---
// control flow
JMP // - JMP<addr> -
CJMP // cond CJMP<addr> -
ITERJMP // - ITERJMP<addr> elem (and fall through) [acts on topmost iterator]
// or: - ITERJMP<addr> - (and jump)
CONSTANT // - CONSTANT<constant> value
MAKETUPLE // x1 ... xn MAKETUPLE<n> tuple
MAKELIST // x1 ... xn MAKELIST<n> list
MAKEFUNC // defaults+freevars MAKEFUNC<func> fn
LOAD // from1 ... fromN module LOAD<n> v1 ... vN
SETLOCAL // value SETLOCAL<local> -
SETGLOBAL // value SETGLOBAL<global> -
LOCAL // - LOCAL<local> value
FREE // - FREE<freevar> cell
FREECELL // - FREECELL<freevar> value (content of FREE cell)
LOCALCELL // - LOCALCELL<local> value (content of LOCAL cell)
SETLOCALCELL // value SETLOCALCELL<local> - (set content of LOCAL cell)
GLOBAL // - GLOBAL<global> value
PREDECLARED // - PREDECLARED<name> value
UNIVERSAL // - UNIVERSAL<name> value
ATTR // x ATTR<name> y y = x.name
SETFIELD // x y SETFIELD<name> - x.name = y
UNPACK // iterable UNPACK<n> vn ... v1
// n>>8 is #positional args and n&0xff is #named args (pairs).
CALL // fn positional named CALL<n> result
CALL_VAR // fn positional named *args CALL_VAR<n> result
CALL_KW // fn positional named **kwargs CALL_KW<n> result
CALL_VAR_KW // fn positional named *args **kwargs CALL_VAR_KW<n> result
OpcodeArgMin = JMP
OpcodeMax = CALL_VAR_KW
)
// TODO(adonovan): add dynamic checks for missing opcodes in the tables below.
var opcodeNames = [...]string{
AMP: "amp",
APPEND: "append",
ATTR: "attr",
CALL: "call",
CALL_KW: "call_kw ",
CALL_VAR: "call_var",
CALL_VAR_KW: "call_var_kw",
CIRCUMFLEX: "circumflex",
CJMP: "cjmp",
CONSTANT: "constant",
DUP2: "dup2",
DUP: "dup",
EQL: "eql",
EXCH: "exch",
FALSE: "false",
FREE: "free",
FREECELL: "freecell",
GE: "ge",
GLOBAL: "global",
GT: "gt",
GTGT: "gtgt",
IN: "in",
INDEX: "index",
INPLACE_ADD: "inplace_add",
INPLACE_PIPE: "inplace_pipe",
ITERJMP: "iterjmp",
ITERPOP: "iterpop",
ITERPUSH: "iterpush",
JMP: "jmp",
LE: "le",
LOAD: "load",
LOCAL: "local",
LOCALCELL: "localcell",
LT: "lt",
LTLT: "ltlt",
MAKEDICT: "makedict",
MAKEFUNC: "makefunc",
MAKELIST: "makelist",
MAKETUPLE: "maketuple",
MANDATORY: "mandatory",
MINUS: "minus",
NEQ: "neq",
NONE: "none",
NOP: "nop",
NOT: "not",
PERCENT: "percent",
PIPE: "pipe",
PLUS: "plus",
POP: "pop",
PREDECLARED: "predeclared",
RETURN: "return",
SETDICT: "setdict",
SETDICTUNIQ: "setdictuniq",
SETFIELD: "setfield",
SETGLOBAL: "setglobal",
SETINDEX: "setindex",
SETLOCAL: "setlocal",
SETLOCALCELL: "setlocalcell",
SLASH: "slash",
SLASHSLASH: "slashslash",
SLICE: "slice",
STAR: "star",
TILDE: "tilde",
TRUE: "true",
UMINUS: "uminus",
UNIVERSAL: "universal",
UNPACK: "unpack",
UPLUS: "uplus",
}
const variableStackEffect = 0x7f
// stackEffect records the effect on the size of the operand stack of
// each kind of instruction. For some instructions this requires computation.
var stackEffect = [...]int8{
AMP: -1,
APPEND: -2,
ATTR: 0,
CALL: variableStackEffect,
CALL_KW: variableStackEffect,
CALL_VAR: variableStackEffect,
CALL_VAR_KW: variableStackEffect,
CIRCUMFLEX: -1,
CJMP: -1,
CONSTANT: +1,
DUP2: +2,
DUP: +1,
EQL: -1,
FALSE: +1,
FREE: +1,
FREECELL: +1,
GE: -1,
GLOBAL: +1,
GT: -1,
GTGT: -1,
IN: -1,
INDEX: -1,
INPLACE_ADD: -1,
INPLACE_PIPE: -1,
ITERJMP: variableStackEffect,
ITERPOP: 0,
ITERPUSH: -1,
JMP: 0,
LE: -1,
LOAD: -1,
LOCAL: +1,
LOCALCELL: +1,
LT: -1,
LTLT: -1,
MAKEDICT: +1,
MAKEFUNC: 0,
MAKELIST: variableStackEffect,
MAKETUPLE: variableStackEffect,
MANDATORY: +1,
MINUS: -1,
NEQ: -1,
NONE: +1,
NOP: 0,
NOT: 0,
PERCENT: -1,
PIPE: -1,
PLUS: -1,
POP: -1,
PREDECLARED: +1,
RETURN: -1,
SETLOCALCELL: -1,
SETDICT: -3,
SETDICTUNIQ: -3,
SETFIELD: -2,
SETGLOBAL: -1,
SETINDEX: -3,
SETLOCAL: -1,
SLASH: -1,
SLASHSLASH: -1,
SLICE: -3,
STAR: -1,
TRUE: +1,
UMINUS: 0,
UNIVERSAL: +1,
UNPACK: variableStackEffect,
UPLUS: 0,
}
func (op Opcode) String() string {
if op < OpcodeMax {
if name := opcodeNames[op]; name != "" {
return name
}
}
return fmt.Sprintf("illegal op (%d)", op)
}
// A Program is a Starlark file in executable form.
//
// Programs are serialized by the Program.Encode method,
// which must be updated whenever this declaration is changed.
type Program struct {
Loads []Binding // name (really, string) and position of each load stmt
Names []string // names of attributes and predeclared variables
Constants []interface{} // = string | int64 | float64 | *big.Int | Bytes
Functions []*Funcode
Globals []Binding // for error messages and tracing
Toplevel *Funcode // module initialization function
Recursion bool // disable recursion check for functions in this file
}
// The type of a bytes literal value, to distinguish from text string.
type Bytes string
// A Funcode is the code of a compiled Starlark function.
//
// Funcodes are serialized by the encoder.function method,
// which must be updated whenever this declaration is changed.
type Funcode struct {
Prog *Program
Pos syntax.Position // position of def or lambda token
Name string // name of this function
Doc string // docstring of this function
Code []byte // the byte code
pclinetab []uint16 // mapping from pc to linenum
Locals []Binding // locals, parameters first
Cells []int // indices of Locals that require cells
Freevars []Binding // for tracing
MaxStack int
NumParams int
NumKwonlyParams int
HasVarargs, HasKwargs bool
// -- transient state --
lntOnce sync.Once
lnt []pclinecol // decoded line number table
}
type pclinecol struct {
pc uint32
line, col int32
}
// A Binding is the name and position of a binding identifier.
type Binding struct {
Name string
Pos syntax.Position
}
// A pcomp holds the compiler state for a Program.
type pcomp struct {
prog *Program // what we're building
names map[string]uint32
constants map[interface{}]uint32
functions map[*Funcode]uint32
}
// An fcomp holds the compiler state for a Funcode.
type fcomp struct {
fn *Funcode // what we're building
pcomp *pcomp
pos syntax.Position // current position of generated code
loops []loop
block *block
}
type loop struct {
break_, continue_ *block
}
type block struct {
insns []insn
// If the last insn is a RETURN, jmp and cjmp are nil.
// If the last insn is a CJMP or ITERJMP,
// cjmp and jmp are the "true" and "false" successors.
// Otherwise, jmp is the sole successor.
jmp, cjmp *block
initialstack int // for stack depth computation
// Used during encoding
index int // -1 => not encoded yet
addr uint32
}
type insn struct {
op Opcode
arg uint32
line, col int32
}
// Position returns the source position for program counter pc.
func (fn *Funcode) Position(pc uint32) syntax.Position {
fn.lntOnce.Do(fn.decodeLNT)
// Binary search to find last LNT entry not greater than pc.
// To avoid dynamic dispatch, this is a specialization of
// sort.Search using this predicate:
// !(i < len(fn.lnt)-1 && fn.lnt[i+1].pc <= pc)
n := len(fn.lnt)
i, j := 0, n
for i < j {
h := int(uint(i+j) >> 1)
if !(h >= n-1 || fn.lnt[h+1].pc > pc) {
i = h + 1
} else {
j = h
}
}
var line, col int32
if i < n {
line = fn.lnt[i].line
col = fn.lnt[i].col
}
pos := fn.Pos // copy the (annoyingly inaccessible) filename
pos.Col = col
pos.Line = line
return pos
}
// decodeLNT decodes the line number table and populates fn.lnt.
// It is called at most once.
func (fn *Funcode) decodeLNT() {
// Conceptually the table contains rows of the form
// (pc uint32, line int32, col int32), sorted by pc.
// We use a delta encoding, since the differences
// between successive pc, line, and column values
// are typically small and positive (though line and
// especially column differences may be negative).
// The delta encoding starts from
// {pc: 0, line: fn.Pos.Line, col: fn.Pos.Col}.
//
// Each entry is packed into one or more 16-bit values:
// Δpc uint4
// Δline int5
// Δcol int6
// incomplete uint1
// The top 4 bits are the unsigned delta pc.
// The next 5 bits are the signed line number delta.
// The next 6 bits are the signed column number delta.
// The bottom bit indicates that more rows follow because
// one of the deltas was maxed out.
// These field widths were chosen from a sample of real programs,
// and allow >97% of rows to be encoded in a single uint16.
fn.lnt = make([]pclinecol, 0, len(fn.pclinetab)) // a minor overapproximation
entry := pclinecol{
pc: 0,
line: fn.Pos.Line,
col: fn.Pos.Col,
}
for _, x := range fn.pclinetab {
entry.pc += uint32(x) >> 12
entry.line += int32((int16(x) << 4) >> (16 - 5)) // sign extend Δline
entry.col += int32((int16(x) << 9) >> (16 - 6)) // sign extend Δcol
if (x & 1) == 0 {
fn.lnt = append(fn.lnt, entry)
}
}
}
// bindings converts resolve.Bindings to compiled form.
func bindings(bindings []*resolve.Binding) []Binding {
res := make([]Binding, len(bindings))
for i, bind := range bindings {
res[i].Name = bind.First.Name
res[i].Pos = bind.First.NamePos
}
return res
}
// Expr compiles an expression to a program whose toplevel function evaluates it.
// The options must be consistent with those used when parsing expr.
func Expr(opts *syntax.FileOptions, expr syntax.Expr, name string, locals []*resolve.Binding) *Program {
pos := syntax.Start(expr)
stmts := []syntax.Stmt{&syntax.ReturnStmt{Result: expr}}
return File(opts, stmts, pos, name, locals, nil)
}
// File compiles the statements of a file into a program.
// The options must be consistent with those used when parsing stmts.
func File(opts *syntax.FileOptions, stmts []syntax.Stmt, pos syntax.Position, name string, locals, globals []*resolve.Binding) *Program {
pcomp := &pcomp{
prog: &Program{
Globals: bindings(globals),
Recursion: opts.Recursion,
},
names: make(map[string]uint32),
constants: make(map[interface{}]uint32),
functions: make(map[*Funcode]uint32),
}
pcomp.prog.Toplevel = pcomp.function(name, pos, stmts, locals, nil)
return pcomp.prog
}
func (pcomp *pcomp) function(name string, pos syntax.Position, stmts []syntax.Stmt, locals, freevars []*resolve.Binding) *Funcode {
fcomp := &fcomp{
pcomp: pcomp,
pos: pos,
fn: &Funcode{
Prog: pcomp.prog,
Pos: pos,
Name: name,
Doc: docStringFromBody(stmts),
Locals: bindings(locals),
Freevars: bindings(freevars),
},
}
// Record indices of locals that require cells.
for i, local := range locals {
if local.Scope == resolve.Cell {
fcomp.fn.Cells = append(fcomp.fn.Cells, i)
}
}
if debug {
fmt.Fprintf(os.Stderr, "start function(%s @ %s)\n", name, pos)
}
// Convert AST to a CFG of instructions.
entry := fcomp.newBlock()
fcomp.block = entry
fcomp.stmts(stmts)
if fcomp.block != nil {
fcomp.emit(NONE)
fcomp.emit(RETURN)
}
var oops bool // something bad happened
setinitialstack := func(b *block, depth int) {
if b.initialstack == -1 {
b.initialstack = depth
} else if b.initialstack != depth {
fmt.Fprintf(os.Stderr, "%d: setinitialstack: depth mismatch: %d vs %d\n",
b.index, b.initialstack, depth)
oops = true
}
}
// Linearize the CFG:
// compute order, address, and initial
// stack depth of each reachable block.
var pc uint32
var blocks []*block
var maxstack int
var visit func(b *block)
visit = func(b *block) {
if b.index >= 0 {
return // already visited
}
b.index = len(blocks)
b.addr = pc
blocks = append(blocks, b)
stack := b.initialstack
if debug {
fmt.Fprintf(os.Stderr, "%s block %d: (stack = %d)\n", name, b.index, stack)
}
var cjmpAddr *uint32
var isiterjmp int
for i, insn := range b.insns {
pc++
// Compute size of argument.
if insn.op >= OpcodeArgMin {
switch insn.op {
case ITERJMP:
isiterjmp = 1
fallthrough
case CJMP:
cjmpAddr = &b.insns[i].arg
pc += 4
default:
pc += uint32(argLen(insn.arg))
}
}
// Compute effect on stack.
se := insn.stackeffect()
if debug {
fmt.Fprintln(os.Stderr, "\t", insn.op, stack, stack+se)
}
stack += se
if stack < 0 {
fmt.Fprintf(os.Stderr, "After pc=%d: stack underflow\n", pc)
oops = true
}
if stack+isiterjmp > maxstack {
maxstack = stack + isiterjmp
}
}
if debug {
fmt.Fprintf(os.Stderr, "successors of block %d (start=%d):\n",
b.addr, b.index)
if b.jmp != nil {
fmt.Fprintf(os.Stderr, "jmp to %d\n", b.jmp.index)
}
if b.cjmp != nil {
fmt.Fprintf(os.Stderr, "cjmp to %d\n", b.cjmp.index)
}
}
// Place the jmp block next.
if b.jmp != nil {
// jump threading (empty cycles are impossible)
for b.jmp.insns == nil {
b.jmp = b.jmp.jmp
}
setinitialstack(b.jmp, stack+isiterjmp)
if b.jmp.index < 0 {
// Successor is not yet visited:
// place it next and fall through.
visit(b.jmp)
} else {
// Successor already visited;
// explicit backward jump required.
pc += 5
}
}
// Then the cjmp block.
if b.cjmp != nil {
// jump threading (empty cycles are impossible)
for b.cjmp.insns == nil {
b.cjmp = b.cjmp.jmp
}
setinitialstack(b.cjmp, stack)
visit(b.cjmp)
// Patch the CJMP/ITERJMP, if present.
if cjmpAddr != nil {
*cjmpAddr = b.cjmp.addr
}
}
}
setinitialstack(entry, 0)
visit(entry)
fn := fcomp.fn
fn.MaxStack = maxstack
// Emit bytecode (and position table).
if Disassemble {
fmt.Fprintf(os.Stderr, "Function %s: (%d blocks, %d bytes)\n", name, len(blocks), pc)
}
fcomp.generate(blocks, pc)
if debug {
fmt.Fprintf(os.Stderr, "code=%d maxstack=%d\n", fn.Code, fn.MaxStack)
}
// Don't panic until we've completed printing of the function.
if oops {
panic("internal error")
}
if debug {
fmt.Fprintf(os.Stderr, "end function(%s @ %s)\n", name, pos)
}
return fn
}
func docStringFromBody(body []syntax.Stmt) string {
if len(body) == 0 {
return ""
}
expr, ok := body[0].(*syntax.ExprStmt)
if !ok {
return ""
}
lit, ok := expr.X.(*syntax.Literal)
if !ok {
return ""
}
if lit.Token != syntax.STRING {
return ""
}
return lit.Value.(string)
}
func (insn *insn) stackeffect() int {
se := int(stackEffect[insn.op])
if se == variableStackEffect {
arg := int(insn.arg)
switch insn.op {
case CALL, CALL_KW, CALL_VAR, CALL_VAR_KW:
se = -int(2*(insn.arg&0xff) + insn.arg>>8)
if insn.op != CALL {
se--
}
if insn.op == CALL_VAR_KW {
se--
}
case ITERJMP:
// Stack effect differs by successor:
// +1 for jmp/false/ok
// 0 for cjmp/true/exhausted
// Handled specially in caller.
se = 0
case MAKELIST, MAKETUPLE:
se = 1 - arg
case UNPACK:
se = arg - 1
default:
panic(insn.op)
}
}
return se
}
// generate emits the linear instruction stream from the CFG,
// and builds the PC-to-line number table.
func (fcomp *fcomp) generate(blocks []*block, codelen uint32) {
code := make([]byte, 0, codelen)
var pclinetab []uint16
prev := pclinecol{
pc: 0,
line: fcomp.fn.Pos.Line,
col: fcomp.fn.Pos.Col,
}
for _, b := range blocks {
if Disassemble {
fmt.Fprintf(os.Stderr, "%d:\n", b.index)
}
pc := b.addr
for _, insn := range b.insns {
if insn.line != 0 {
// Instruction has a source position. Delta-encode it.
// See Funcode.Position for the encoding.
for {
var incomplete uint16
// Δpc, uint4
deltapc := pc - prev.pc
if deltapc > 0x0f {
deltapc = 0x0f
incomplete = 1
}
prev.pc += deltapc
// Δline, int5
deltaline, ok := clip(insn.line-prev.line, -0x10, 0x0f)
if !ok {
incomplete = 1
}
prev.line += deltaline
// Δcol, int6
deltacol, ok := clip(insn.col-prev.col, -0x20, 0x1f)
if !ok {
incomplete = 1
}
prev.col += deltacol
entry := uint16(deltapc<<12) | uint16(deltaline&0x1f)<<7 | uint16(deltacol&0x3f)<<1 | incomplete
pclinetab = append(pclinetab, entry)
if incomplete == 0 {
break
}
}
if Disassemble {
fmt.Fprintf(os.Stderr, "\t\t\t\t\t; %s:%d:%d\n",
filepath.Base(fcomp.fn.Pos.Filename()), insn.line, insn.col)
}
}
if Disassemble {
PrintOp(fcomp.fn, pc, insn.op, insn.arg)
}
code = append(code, byte(insn.op))
pc++
if insn.op >= OpcodeArgMin {
if insn.op == CJMP || insn.op == ITERJMP {
code = addUint32(code, insn.arg, 4) // pad arg to 4 bytes
} else {
code = addUint32(code, insn.arg, 0)
}
pc = uint32(len(code))
}
}
if b.jmp != nil && b.jmp.index != b.index+1 {
addr := b.jmp.addr
if Disassemble {
fmt.Fprintf(os.Stderr, "\t%d\tjmp\t\t%d\t; block %d\n",
pc, addr, b.jmp.index)
}
code = append(code, byte(JMP))
code = addUint32(code, addr, 4)
}
}
if len(code) != int(codelen) {
panic("internal error: wrong code length")
}
fcomp.fn.pclinetab = pclinetab
fcomp.fn.Code = code
}
// clip returns the value nearest x in the range [min...max],
// and whether it equals x.
func clip(x, min, max int32) (int32, bool) {
if x > max {
return max, false
} else if x < min {
return min, false
} else {
return x, true
}
}
// addUint32 encodes x as 7-bit little-endian varint.
// TODO(adonovan): opt: steal top two bits of opcode
// to encode the number of complete bytes that follow.
func addUint32(code []byte, x uint32, min int) []byte {
end := len(code) + min
for x >= 0x80 {
code = append(code, byte(x)|0x80)
x >>= 7
}
code = append(code, byte(x))
// Pad the operand with NOPs to exactly min bytes.
for len(code) < end {
code = append(code, byte(NOP))
}
return code
}
func argLen(x uint32) int {
n := 0
for x >= 0x80 {
n++
x >>= 7
}
return n + 1
}
// PrintOp prints an instruction.
// It is provided for debugging.
func PrintOp(fn *Funcode, pc uint32, op Opcode, arg uint32) {
if op < OpcodeArgMin {
fmt.Fprintf(os.Stderr, "\t%d\t%s\n", pc, op)
return
}
var comment string
switch op {
case CONSTANT:
switch x := fn.Prog.Constants[arg].(type) {
case string:
comment = strconv.Quote(x)
case Bytes:
comment = "b" + strconv.Quote(string(x))
default:
comment = fmt.Sprint(x)
}
case MAKEFUNC:
comment = fn.Prog.Functions[arg].Name
case SETLOCAL, LOCAL:
comment = fn.Locals[arg].Name
case SETGLOBAL, GLOBAL:
comment = fn.Prog.Globals[arg].Name
case ATTR, SETFIELD, PREDECLARED, UNIVERSAL:
comment = fn.Prog.Names[arg]
case FREE:
comment = fn.Freevars[arg].Name
case CALL, CALL_VAR, CALL_KW, CALL_VAR_KW:
comment = fmt.Sprintf("%d pos, %d named", arg>>8, arg&0xff)
default:
// JMP, CJMP, ITERJMP, MAKETUPLE, MAKELIST, LOAD, UNPACK:
// arg is just a number
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "\t%d\t%-10s\t%d", pc, op, arg)
if comment != "" {
fmt.Fprint(&buf, "\t; ", comment)
}
fmt.Fprintln(&buf)
os.Stderr.Write(buf.Bytes())
}
// newBlock returns a new block.
func (fcomp) newBlock() *block {
return &block{index: -1, initialstack: -1}
}
// emit emits an instruction to the current block.
func (fcomp *fcomp) emit(op Opcode) {
if op >= OpcodeArgMin {
panic("missing arg: " + op.String())
}
insn := insn{op: op, line: fcomp.pos.Line, col: fcomp.pos.Col}
fcomp.block.insns = append(fcomp.block.insns, insn)
fcomp.pos.Line = 0
fcomp.pos.Col = 0
}
// emit1 emits an instruction with an immediate operand.
func (fcomp *fcomp) emit1(op Opcode, arg uint32) {
if op < OpcodeArgMin {
panic("unwanted arg: " + op.String())
}
insn := insn{op: op, arg: arg, line: fcomp.pos.Line, col: fcomp.pos.Col}
fcomp.block.insns = append(fcomp.block.insns, insn)
fcomp.pos.Line = 0
fcomp.pos.Col = 0
}
// jump emits a jump to the specified block.
// On return, the current block is unset.
func (fcomp *fcomp) jump(b *block) {
if b == fcomp.block {
panic("self-jump") // unreachable: Starlark has no arbitrary looping constructs
}
fcomp.block.jmp = b
fcomp.block = nil
}
// condjump emits a conditional jump (CJMP or ITERJMP)
// to the specified true/false blocks.
// (For ITERJMP, the cases are jmp/f/ok and cjmp/t/exhausted.)
// On return, the current block is unset.
func (fcomp *fcomp) condjump(op Opcode, t, f *block) {
if !(op == CJMP || op == ITERJMP) {
panic("not a conditional jump: " + op.String())
}
fcomp.emit1(op, 0) // fill in address later
fcomp.block.cjmp = t
fcomp.jump(f)
}
// nameIndex returns the index of the specified name
// within the name pool, adding it if necessary.
func (pcomp *pcomp) nameIndex(name string) uint32 {
index, ok := pcomp.names[name]
if !ok {
index = uint32(len(pcomp.prog.Names))
pcomp.names[name] = index
pcomp.prog.Names = append(pcomp.prog.Names, name)
}
return index
}
// constantIndex returns the index of the specified constant
// within the constant pool, adding it if necessary.
func (pcomp *pcomp) constantIndex(v interface{}) uint32 {
index, ok := pcomp.constants[v]
if !ok {
index = uint32(len(pcomp.prog.Constants))
pcomp.constants[v] = index
pcomp.prog.Constants = append(pcomp.prog.Constants, v)
}
return index
}
// functionIndex returns the index of the specified function
// AST the nestedfun pool, adding it if necessary.
func (pcomp *pcomp) functionIndex(fn *Funcode) uint32 {
index, ok := pcomp.functions[fn]
if !ok {
index = uint32(len(pcomp.prog.Functions))
pcomp.functions[fn] = index
pcomp.prog.Functions = append(pcomp.prog.Functions, fn)
}
return index
}
// string emits code to push the specified string.
func (fcomp *fcomp) string(s string) {
fcomp.emit1(CONSTANT, fcomp.pcomp.constantIndex(s))
}
// setPos sets the current source position.
// It should be called prior to any operation that can fail dynamically.
// All positions are assumed to belong to the same file.
func (fcomp *fcomp) setPos(pos syntax.Position) {