forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
machine.go
1949 lines (1842 loc) · 47.7 KB
/
machine.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 gno
// XXX rename file to machine.go.
import (
"fmt"
"io"
"os"
"reflect"
"strings"
"testing"
"github.com/gnolang/gno/pkgs/errors"
"github.com/gnolang/gno/pkgs/std"
)
//----------------------------------------
// Machine
type Machine struct {
// State
Ops []Op // main operations
NumOps int
Values []TypedValue // buffer of values to be operated on
NumValues int // number of values
Exprs []Expr // pending expressions
Stmts []Stmt // pending statements
Blocks []*Block // block (scope) stack
Frames []Frame // func call stack
Package *PackageValue // active package
Realm *Realm // active realm
Alloc *Allocator // memory allocations
Exception *TypedValue // if panic'd unless recovered
NumResults int // number of results returned
Cycles int64 // number of "cpu" cycles
// Configuration
CheckTypes bool // not yet used
ReadOnly bool
MaxCycles int64
Output io.Writer
Store Store
Context interface{}
}
// Machine with new package of given path.
// Creates a new MemRealmer for any new realms.
// Looks in store for package of pkgPath; if not found,
// creates new instances as necessary.
// If pkgPath is zero, the machine has no active package
// and one must be set prior to usage.
func NewMachine(pkgPath string, store Store) *Machine {
return NewMachineWithOptions(
MachineOptions{
PkgPath: pkgPath,
Store: store,
})
}
type MachineOptions struct {
PkgPath string
CheckTypes bool // not yet used
ReadOnly bool
Output io.Writer
Store Store
Context interface{}
Alloc *Allocator // or see MaxAllocBytes.
MaxAllocBytes int64 // or 0 for no limit.
MaxCycles int64 // or 0 for no limit.
}
func NewMachineWithOptions(opts MachineOptions) *Machine {
checkTypes := opts.CheckTypes
readOnly := opts.ReadOnly
maxCycles := opts.MaxCycles
output := opts.Output
if output == nil {
output = os.Stdout
}
alloc := opts.Alloc
if alloc == nil {
alloc = NewAllocator(opts.MaxAllocBytes)
}
store := opts.Store
if store == nil {
// bare store, no stdlibs.
store = NewStore(alloc, nil, nil)
}
pv := (*PackageValue)(nil)
if opts.PkgPath != "" {
pv = store.GetPackage(opts.PkgPath, false)
if pv == nil {
pkgName := defaultPkgName(opts.PkgPath)
pn := NewPackageNode(pkgName, opts.PkgPath, &FileSet{})
pv = pn.NewPackage()
store.SetBlockNode(pn)
store.SetCachePackage(pv)
}
}
context := opts.Context
mm := &Machine{
Ops: make([]Op, 1024),
NumOps: 0,
Values: make([]TypedValue, 1024),
NumValues: 0,
Package: pv,
Alloc: alloc,
CheckTypes: checkTypes,
ReadOnly: readOnly,
MaxCycles: maxCycles,
Output: output,
Store: store,
Context: context,
}
if pv != nil {
mm.SetActivePackage(pv)
}
return mm
}
func (m *Machine) SetActivePackage(pv *PackageValue) {
if err := m.CheckEmpty(); err != nil {
panic(errors.Wrap(err, "set package when machine not empty"))
}
m.Package = pv
m.Realm = pv.GetRealm()
m.Blocks = []*Block{
pv.GetBlock(m.Store),
}
}
//----------------------------------------
// top level Run* methods.
// Upon restart, preprocess all MemPackage and save blocknodes.
// This is a temporary measure until we optimize/make-lazy.
func (m *Machine) PreprocessAllFilesAndSaveBlockNodes() {
ch := m.Store.IterMemPackage()
for memPkg := range ch {
fset := ParseMemPackage(memPkg)
pn := NewPackageNode(Name(memPkg.Name), memPkg.Path, fset)
m.Store.SetBlockNode(pn)
PredefineFileSet(m.Store, pn, fset)
for _, fn := range fset.Files {
// Save Types to m.Store (while preprocessing).
fn = Preprocess(m.Store, pn, fn).(*FileNode)
// Save BlockNodes to m.Store.
SaveBlockNodes(m.Store, fn)
}
// Normally, the fileset would be added onto the
// package node only after runFiles(), but we cannot
// run files upon restart (only preprocess them).
// So, add them here instead.
// TODO: is this right?
if pn.FileSet == nil {
pn.FileSet = fset
} else {
// This happens for non-realm file tests.
// TODO ensure the files are the same.
}
}
}
//----------------------------------------
// top level Run* methods.
// Parses files, sets the package if doesn't exist, runs files, saves mempkg
// and corresponding package node, package value, and types to store. Save
// is set to false for tests where package values may be native.
func (m *Machine) RunMemPackage(memPkg *std.MemPackage, save bool) (*PackageNode, *PackageValue) {
// parse files.
files := ParseMemPackage(memPkg)
// make and set package if doesn't exist.
pn := (*PackageNode)(nil)
pv := (*PackageValue)(nil)
if m.Package != nil && m.Package.PkgPath == memPkg.Path {
pv = m.Package
loc := PackageNodeLocation(memPkg.Path)
pn = m.Store.GetBlockNode(loc).(*PackageNode)
} else {
pn = NewPackageNode(Name(memPkg.Name), memPkg.Path, &FileSet{})
pv = pn.NewPackage()
m.Store.SetBlockNode(pn)
m.Store.SetCachePackage(pv)
}
m.SetActivePackage(pv)
// run files.
m.RunFiles(files.Files...)
// maybe save package value and mempackage.
if save {
// store package values and types
m.savePackageValuesAndTypes()
// store mempackage
m.Store.AddMemPackage(memPkg)
}
return pn, pv
}
// Tests all test files in a mempackage.
// Assumes that the importing of packages is handled elsewhere.
// The resulting package value and node become injected with TestMethods and
// other declarations, so it is expected that non-test code will not be run
// afterwards from the same store.
func (m *Machine) TestMemPackage(t *testing.T, memPkg *std.MemPackage) {
defer m.injectLocOnPanic()
DisableDebug()
fmt.Println("DEBUG DISABLED (FOR TEST DEPENDENCIES INIT)")
// prefetch the testing package.
testingpv := m.Store.GetPackage("testing", false)
testingtv := TypedValue{T: gPackageType, V: testingpv}
testingcx := &ConstExpr{TypedValue: testingtv}
// parse test files.
tfiles, itfiles := ParseMemPackageTests(memPkg)
{ // first, tfiles which run in the same package.
pv := m.Store.GetPackage(memPkg.Path, false)
pvBlock := pv.GetBlock(m.Store)
pvSize := len(pvBlock.Values)
m.SetActivePackage(pv)
// run test files.
m.RunFiles(tfiles.Files...)
// run all tests in test files.
for i := pvSize; i < len(pvBlock.Values); i++ {
tv := &pvBlock.Values[i]
if !(tv.T.Kind() == FuncKind &&
strings.HasPrefix(
string(tv.V.(*FuncValue).Name),
"Test")) {
continue // not a test function.
}
// XXX ensure correct func type.
name := tv.V.(*FuncValue).Name
t.Run(string(name), func(t *testing.T) {
defer m.injectLocOnPanic()
x := Call(name, Call(Sel(testingcx, "NewT"), Str(string(name))))
res := m.Eval(x)
if len(res) != 0 {
panic(fmt.Sprintf(
"expected no results but got %d",
len(res)))
}
})
}
}
{ // run all (import) tests in test files.
pn := NewPackageNode(Name(memPkg.Name+"_test"), memPkg.Path+"_test", itfiles)
pv := pn.NewPackage()
m.Store.SetBlockNode(pn)
m.Store.SetCachePackage(pv)
pvBlock := pv.GetBlock(m.Store)
m.SetActivePackage(pv)
m.RunFiles(itfiles.Files...)
pn.PrepareNewValues(pv)
EnableDebug()
fmt.Println("DEBUG ENABLED")
for i := 0; i < len(pvBlock.Values); i++ {
tv := &pvBlock.Values[i]
if !(tv.T.Kind() == FuncKind &&
strings.HasPrefix(
string(tv.V.(*FuncValue).Name),
"Test")) {
continue // not a test function.
}
// XXX ensure correct func type.
name := tv.V.(*FuncValue).Name
t.Run(string(name), func(t *testing.T) {
defer m.injectLocOnPanic()
x := Call(name, Call(Sel(testingcx, "NewT"), Str(string(name))))
res := m.Eval(x)
if len(res) != 0 {
fmt.Println("ERROR")
panic(fmt.Sprintf(
"expected no results but got %d",
len(res)))
}
})
}
}
}
// in case of panic, inject location information to exception.
func (m *Machine) injectLocOnPanic() {
if r := recover(); r != nil {
// Show last location information.
// First, determine the line number of expression or statement if any.
lastLine := 0
if len(m.Exprs) > 0 {
for i := len(m.Exprs) - 1; i >= 0; i-- {
expr := m.Exprs[i]
if expr.GetLine() > 0 {
lastLine = expr.GetLine()
break
}
}
}
if lastLine == 0 && len(m.Stmts) > 0 {
for i := len(m.Stmts) - 1; i >= 0; i-- {
stmt := m.Stmts[i]
if stmt.GetLine() > 0 {
lastLine = stmt.GetLine()
break
}
}
}
// Append line number to block location.
lastLoc := Location{}
for i := len(m.Blocks) - 1; i >= 0; i-- {
block := m.Blocks[i]
src := block.GetSource(m.Store)
loc := src.GetLocation()
if !loc.IsZero() {
lastLoc = loc
if lastLine > 0 {
lastLoc.Line = lastLine
}
break
}
}
// wrap panic with location information.
if !lastLoc.IsZero() {
fmt.Printf("%s: %v\n", lastLoc.String(), r)
panic(errors.Wrap(r, fmt.Sprintf("location: %s", lastLoc.String())))
} else {
panic(r)
}
}
}
// Add files to the package's *FileSet and run them.
// This will also run each init function encountered.
func (m *Machine) RunFiles(fns ...*FileNode) {
m.runFiles(fns...)
}
func (m *Machine) runFiles(fns ...*FileNode) {
// Files' package names must match the machine's active one.
// if there is one.
for _, fn := range fns {
if fn.PkgName != "" && fn.PkgName != m.Package.PkgName {
panic(fmt.Sprintf("expected package name [%s] but got [%s]",
m.Package.PkgName, fn.PkgName))
}
}
// Add files to *PackageNode.FileSet.
pv := m.Package
pb := pv.GetBlock(m.Store)
pn := pb.GetSource(m.Store).(*PackageNode)
fs := &FileSet{Files: fns}
fdeclared := map[Name]struct{}{}
if pn.FileSet == nil {
pn.FileSet = fs
} else {
// collect pre-existing declared names
for _, fn := range pn.FileSet.Files {
for _, decl := range fn.Decls {
for _, name := range decl.GetDeclNames() {
fdeclared[name] = struct{}{}
}
}
}
// add fns to pre-existing fileset.
pn.FileSet.AddFiles(fns...)
}
// Predefine declarations across all files.
PredefineFileSet(m.Store, pn, fs)
// Preprocess each new file.
for _, fn := range fns {
// Preprocess file.
// NOTE: Most of the declaration is handled by
// Preprocess and any constant values set on
// pn.StaticBlock, and those values are copied to the
// runtime package value via PrepareNewValues. Then,
// non-constant var declarations and file-level imports
// are re-set in runDeclaration(,true).
fn = Preprocess(m.Store, pn, fn).(*FileNode)
if debug {
debug.Printf("PREPROCESSED FILE: %v\n", fn)
}
// After preprocessing, save blocknodes to store.
SaveBlockNodes(m.Store, fn)
// Make block for fn.
// Each file for each *PackageValue gets its own file *Block,
// with values copied over from each file's
// *FileNode.StaticBlock.
fb := m.Alloc.NewBlock(fn, pb)
fb.Values = make([]TypedValue, len(fn.StaticBlock.Values))
copy(fb.Values, fn.StaticBlock.Values)
pv.AddFileBlock(fn.Name, fb)
}
// Get new values across all files in package.
updates := pn.PrepareNewValues(pv)
// to detect loops in var declarations.
var loopfindr = []Name{}
// recursive function for var declarations.
var runDeclarationFor func(fn *FileNode, decl Decl)
runDeclarationFor = func(fn *FileNode, decl Decl) {
// get fileblock of fn.
// fb := pv.GetFileBlock(nil, fn.Name)
// get dependencies of decl.
deps := make(map[Name]struct{})
findDependentNames(decl, deps)
for dep, _ := range deps {
// if dep already defined as import, skip.
if _, ok := fn.GetLocalIndex(dep); ok {
continue
}
// if dep already in fdeclared, skip.
if _, ok := fdeclared[dep]; ok {
continue
}
fn, depdecl, exists := pn.FileSet.GetDeclForSafe(dep)
// special case: if doesn't exist:
if !exists {
if isUverseName(dep) { // then is reserved keyword in uverse.
continue
} else { // is an undefined dependency.
panic(fmt.Sprintf(
"dependency %s not defined in fileset with files %v",
dep, fs.FileNames()))
}
}
// if dep already in loopfindr, abort.
if hasName(dep, loopfindr) {
if _, ok := (*depdecl).(*FuncDecl); ok {
// recursive function dependencies
// are OK with func decls.
continue
} else {
panic(fmt.Sprintf(
"loop in variable initialization: dependency trail %v circularly depends on %s", loopfindr, dep))
}
}
// run dependecy declaration
loopfindr = append(loopfindr, dep)
runDeclarationFor(fn, *depdecl)
loopfindr = loopfindr[:len(loopfindr)-1]
}
// run declaration
fb := pv.GetFileBlock(m.Store, fn.Name)
m.PushBlock(fb)
m.runDeclaration(decl)
m.PopBlock()
for _, n := range decl.GetDeclNames() {
fdeclared[n] = struct{}{}
}
}
// Declarations (and variable initializations). This must happen
// after all files are preprocessed, because value decl may be out of
// order and depend on other files.
// Run declarations.
for _, fn := range fns {
for _, decl := range fn.Decls {
runDeclarationFor(fn, decl)
}
}
// Run new init functions.
// Go spec: "To ensure reproducible initialization
// behavior, build systems are encouraged to present
// multiple files belonging to the same package in
// lexical file name order to a compiler."
for _, tv := range updates {
if tv.IsDefined() && tv.T.Kind() == FuncKind && tv.V != nil {
fv, ok := tv.V.(*FuncValue)
if !ok {
continue // skip native functions.
}
if strings.HasPrefix(string(fv.Name), "init.") {
fb := pv.GetFileBlock(m.Store, fv.FileName)
m.PushBlock(fb)
m.RunFunc(fv.Name)
m.PopBlock()
}
}
}
}
// Save the machine's package using realm finalization deep crawl.
// Also saves declared types.
func (m *Machine) savePackageValuesAndTypes() {
// save package value and dependencies.
pv := m.Package
if pv.IsRealm() {
rlm := pv.Realm
rlm.MarkNewReal(pv)
rlm.FinalizeRealmTransaction(m.ReadOnly, m.Store)
// save package realm info.
m.Store.SetPackageRealm(rlm)
} else { // use a throwaway realm.
rlm := NewRealm(pv.PkgPath)
rlm.MarkNewReal(pv)
rlm.FinalizeRealmTransaction(m.ReadOnly, m.Store)
}
// save declared types.
if bv, ok := pv.Block.(*Block); ok {
for _, tv := range bv.Values {
if tvv, ok := tv.V.(TypeValue); ok {
if dt, ok := tvv.Type.(*DeclaredType); ok {
m.Store.SetType(dt)
}
}
}
}
}
func (m *Machine) RunFunc(fn Name) {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Machine.RunFunc(%q) panic: %v\n%s\n",
fn, r, m.String())
panic(r)
}
}()
m.RunStatement(S(Call(Nx(fn))))
}
func (m *Machine) RunMain() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Machine.RunMain() panic: %v\n%s\n",
r, m.String())
panic(r)
}
}()
m.RunStatement(S(Call(X("main"))))
}
// Evaluate throwaway expression in new block scope.
// If x is a function call, it may return any number of
// results including 0. Otherwise it returns 1.
// Input must not have been preprocessed, that is,
// it should not be the child of any parent.
func (m *Machine) Eval(x Expr) []TypedValue {
if debug {
m.Printf("Machine.Eval(%v)\n", x)
}
// X must not have been preprocessed.
if x.GetAttribute(ATTR_PREPROCESSED) != nil {
panic(fmt.Sprintf(
"Machine.Eval(x) expression already preprocessed: %s",
x.String()))
}
// Preprocess input using last block context.
last := m.LastBlock().GetSource(m.Store)
// Transform expression to ensure isolation.
// This is to ensure that the parent context
// doesn't get modified.
// XXX Just use a BlockStmt?
if _, ok := x.(*CallExpr); !ok {
x = Call(Fn(nil, Flds("x", InterfaceT(nil)),
Ss(
Return(x),
)))
} else {
// x already creates its own scope.
}
// Preprocess x.
x = Preprocess(m.Store, last, x).(Expr)
// Evaluate x.
start := m.NumValues
m.PushOp(OpHalt)
m.PushExpr(x)
m.PushOp(OpEval)
m.Run()
res := m.ReapValues(start)
return res
}
// Evaluate any preprocessed expression statically.
// This is primiarily used by the preprocessor to evaluate
// static types and values.
func (m *Machine) EvalStatic(last BlockNode, x Expr) TypedValue {
if debug {
m.Printf("Machine.EvalStatic(%v, %v)\n", last, x)
}
// X must have been preprocessed.
if x.GetAttribute(ATTR_PREPROCESSED) == nil {
panic(fmt.Sprintf(
"Machine.EvalStatic(x) expression not yet preprocessed: %s",
x.String()))
}
// Temporarily push last to m.Blocks.
m.PushBlock(last.GetStaticBlock().GetBlock())
// Evaluate x.
start := m.NumValues
m.PushOp(OpHalt)
m.PushOp(OpPopBlock)
m.PushExpr(x)
m.PushOp(OpEval)
m.Run()
res := m.ReapValues(start)
if len(res) != 1 {
panic("should not happen")
}
return res[0]
}
// Evaluate the type of any preprocessed expression statically.
// This is primiarily used by the preprocessor to evaluate
// static types of nodes.
func (m *Machine) EvalStaticTypeOf(last BlockNode, x Expr) Type {
if debug {
m.Printf("Machine.EvalStaticTypeOf(%v, %v)\n", last, x)
}
// X must have been preprocessed.
if x.GetAttribute(ATTR_PREPROCESSED) == nil {
panic(fmt.Sprintf(
"Machine.EvalStaticTypeOf(x) expression not yet preprocessed: %s",
x.String()))
}
// Temporarily push last to m.Blocks.
m.PushBlock(last.GetStaticBlock().GetBlock())
// Evaluate x.
start := m.NumValues
m.PushOp(OpHalt)
m.PushOp(OpPopBlock)
m.PushExpr(x)
m.PushOp(OpStaticTypeOf)
m.Run()
res := m.ReapValues(start)
if len(res) != 1 {
panic("should not happen")
}
tv := res[0].V.(TypeValue)
return tv.Type
}
func (m *Machine) RunStatement(s Stmt) {
sn := m.LastBlock().GetSource(m.Store)
s = Preprocess(m.Store, sn, s).(Stmt)
m.PushOp(OpHalt)
m.PushStmt(s)
m.PushOp(OpExec)
m.Run()
}
// Runs a declaration after preprocessing d. If d was already
// preprocessed, call runDeclaration() instead.
// This function is primarily for testing, so no blocknodes are
// saved to store, and declarations are not realm compatible.
// NOTE: to support realm persistence of types, must
// first require the validation of blocknode locations.
func (m *Machine) RunDeclaration(d Decl) {
// Preprocess input using package block. There should only
// be one block right now, and it's a *PackageNode.
pn := m.LastBlock().GetSource(m.Store).(*PackageNode)
d = Preprocess(m.Store, pn, d).(Decl)
// do not SaveBlockNodes(m.Store, d).
pn.PrepareNewValues(m.Package)
m.runDeclaration(d)
if debug {
if pn != m.Package.GetBlock(m.Store).GetSource(m.Store) {
panic("package mismatch")
}
}
}
// Declarations to be run within a body (not at the file or
// package level, for which evaluations happen during
// preprocessing).
func (m *Machine) runDeclaration(d Decl) {
switch d := d.(type) {
case *FuncDecl:
// nothing to do.
// closure and package already set
// during PackageNode.NewPackage().
case *ValueDecl:
m.PushOp(OpHalt)
m.PushStmt(d)
m.PushOp(OpExec)
m.Run()
case *TypeDecl:
m.PushOp(OpHalt)
m.PushStmt(d)
m.PushOp(OpExec)
m.Run()
default:
// Do nothing for package constants.
}
}
//----------------------------------------
// Op
type Op uint8
const (
/* Control operators */
OpInvalid Op = 0x00 // invalid
OpHalt Op = 0x01 // halt (e.g. last statement)
OpNoop Op = 0x02 // no-op
OpExec Op = 0x03 // exec next statement
OpPrecall Op = 0x04 // sets X (func) to frame
OpCall Op = 0x05 // call(Frame.Func, [...])
OpCallNativeBody Op = 0x06 // call body is native
OpReturn Op = 0x07 // return ...
OpReturnFromBlock Op = 0x08 // return results (after defers)
OpReturnToBlock Op = 0x09 // copy results to block (before defer)
OpDefer Op = 0x0A // defer call(X, [...])
OpCallDeferNativeBody Op = 0x0B // call body is native
OpGo Op = 0x0C // go call(X, [...])
OpSelect Op = 0x0D // exec next select case
OpSwitchClause Op = 0x0E // exec next switch clause
OpSwitchClauseCase Op = 0x0F // exec next switch clause case
OpTypeSwitch Op = 0x10 // exec type switch clauses (all)
OpIfCond Op = 0x11 // eval cond
OpPopValue Op = 0x12 // pop X
OpPopResults Op = 0x13 // pop n call results
OpPopBlock Op = 0x14 // pop block NOTE breaks certain invariants.
OpPopFrameAndReset Op = 0x15 // pop frame and reset.
OpPanic1 Op = 0x16 // pop exception and pop call frames.
OpPanic2 Op = 0x17 // pop call frames.
/* Unary & binary operators */
OpUpos Op = 0x20 // + (unary)
OpUneg Op = 0x21 // - (unary)
OpUnot Op = 0x22 // ! (unary)
OpUxor Op = 0x23 // ^ (unary)
OpUrecv Op = 0x25 // <- (unary) // TODO make expr
OpLor Op = 0x26 // ||
OpLand Op = 0x27 // &&
OpEql Op = 0x28 // ==
OpNeq Op = 0x29 // !=
OpLss Op = 0x2A // <
OpLeq Op = 0x2B // <=
OpGtr Op = 0x2C // >
OpGeq Op = 0x2D // >=
OpAdd Op = 0x2E // +
OpSub Op = 0x2F // -
OpBor Op = 0x30 // |
OpXor Op = 0x31 // ^
OpMul Op = 0x32 // *
OpQuo Op = 0x33 // /
OpRem Op = 0x34 // %
OpShl Op = 0x35 // <<
OpShr Op = 0x36 // >>
OpBand Op = 0x37 // &
OpBandn Op = 0x38 // &^
/* Other expression operators */
OpEval Op = 0x40 // eval next expression
OpBinary1 Op = 0x41 // X op ?
OpIndex1 Op = 0x42 // X[Y]
OpIndex2 Op = 0x43 // (_, ok :=) X[Y]
OpSelector Op = 0x44 // X.Y
OpSlice Op = 0x45 // X[Low:High:Max]
OpStar Op = 0x46 // *X (deref or pointer-to)
OpRef Op = 0x47 // &X
OpTypeAssert1 Op = 0x48 // X.(Type)
OpTypeAssert2 Op = 0x49 // (_, ok :=) X.(Type)
OpStaticTypeOf Op = 0x4A // static type of X
OpCompositeLit Op = 0x4B // X{???}
OpArrayLit Op = 0x4C // [Len]{...}
OpSliceLit Op = 0x4D // []{value,...}
OpSliceLit2 Op = 0x4E // []{key:value,...}
OpMapLit Op = 0x4F // X{...}
OpStructLit Op = 0x50 // X{...}
OpFuncLit Op = 0x51 // func(T){Body}
OpConvert Op = 0x52 // Y(X)
/* Native operators */
OpArrayLitGoNative Op = 0x60
OpSliceLitGoNative Op = 0x61
OpStructLitGoNative Op = 0x62
OpCallGoNative Op = 0x63
/* Type operators */
OpFieldType Op = 0x70 // Name: X `tag`
OpArrayType Op = 0x71 // [X]Y{}
OpSliceType Op = 0x72 // []X{}
OpPointerType Op = 0x73 // *X
OpInterfaceType Op = 0x74 // interface{...}
OpChanType Op = 0x75 // [<-]chan[<-]X
OpFuncType Op = 0x76 // func(params...)results...
OpMapType Op = 0x77 // map[X]Y
OpStructType Op = 0x78 // struct{...}
OpMaybeNativeType Op = 0x79 // maybenative{X}
/* Statement operators */
OpAssign Op = 0x80 // Lhs = Rhs
OpAddAssign Op = 0x81 // Lhs += Rhs
OpSubAssign Op = 0x82 // Lhs -= Rhs
OpMulAssign Op = 0x83 // Lhs *= Rhs
OpQuoAssign Op = 0x84 // Lhs /= Rhs
OpRemAssign Op = 0x85 // Lhs %= Rhs
OpBandAssign Op = 0x86 // Lhs &= Rhs
OpBandnAssign Op = 0x87 // Lhs &^= Rhs
OpBorAssign Op = 0x88 // Lhs |= Rhs
OpXorAssign Op = 0x89 // Lhs ^= Rhs
OpShlAssign Op = 0x8A // Lhs <<= Rhs
OpShrAssign Op = 0x8B // Lhs >>= Rhs
OpDefine Op = 0x8C // X... := Y...
OpInc Op = 0x8D // X++
OpDec Op = 0x8E // X--
/* Decl operators */
OpValueDecl Op = 0x90 // var/const ...
OpTypeDecl Op = 0x91 // type ...
/* Loop (sticky) operators (>= 0xD0) */
OpSticky Op = 0xD0 // not a real op.
OpBody Op = 0xD1 // if/block/switch/select.
OpForLoop Op = 0xD2
OpRangeIter Op = 0xD3
OpRangeIterString Op = 0xD4
OpRangeIterMap Op = 0xD5
OpRangeIterArrayPtr Op = 0xD6
OpReturnCallDefers Op = 0xD7 // TODO rename?
)
//----------------------------------------
// "CPU" steps.
func (m *Machine) incrCPU(cycles int64) {
m.Cycles += cycles
if m.MaxCycles != 0 && m.Cycles > m.MaxCycles {
panic("CPU cycle overrun")
}
}
const (
/* Control operators */
OpCPUInvalid = 1
OpCPUHalt = 1
OpCPUNoop = 1
OpCPUExec = 1
OpCPUPrecall = 1
OpCPUCall = 1
OpCPUCallNativeBody = 1
OpCPUReturn = 1
OpCPUReturnFromBlock = 1
OpCPUReturnToBlock = 1
OpCPUDefer = 1
OpCPUCallDeferNativeBody = 1
OpCPUGo = 1
OpCPUSelect = 1
OpCPUSwitchClause = 1
OpCPUSwitchClauseCase = 1
OpCPUTypeSwitch = 1
OpCPUIfCond = 1
OpCPUPopValue = 1
OpCPUPopResults = 1
OpCPUPopBlock = 1
OpCPUPopFrameAndReset = 1
OpCPUPanic1 = 1
OpCPUPanic2 = 1
/* Unary & binary operators */
OpCPUUpos = 1
OpCPUUneg = 1
OpCPUUnot = 1
OpCPUUxor = 1
OpCPUUrecv = 1
OpCPULor = 1
OpCPULand = 1
OpCPUEql = 1
OpCPUNeq = 1
OpCPULss = 1
OpCPULeq = 1
OpCPUGtr = 1
OpCPUGeq = 1
OpCPUAdd = 1
OpCPUSub = 1
OpCPUBor = 1
OpCPUXor = 1
OpCPUMul = 1
OpCPUQuo = 1
OpCPURem = 1
OpCPUShl = 1
OpCPUShr = 1
OpCPUBand = 1
OpCPUBandn = 1
/* Other expression operators */
OpCPUEval = 1
OpCPUBinary1 = 1
OpCPUIndex1 = 1
OpCPUIndex2 = 1
OpCPUSelector = 1
OpCPUSlice = 1
OpCPUStar = 1
OpCPURef = 1
OpCPUTypeAssert1 = 1
OpCPUTypeAssert2 = 1
OpCPUStaticTypeOf = 1
OpCPUCompositeLit = 1
OpCPUArrayLit = 1
OpCPUSliceLit = 1
OpCPUSliceLit2 = 1
OpCPUMapLit = 1
OpCPUStructLit = 1
OpCPUFuncLit = 1
OpCPUConvert = 1
/* Native operators */
OpCPUArrayLitGoNative = 1
OpCPUSliceLitGoNative = 1
OpCPUStructLitGoNative = 1
OpCPUCallGoNative = 1
/* Type operators */
OpCPUFieldType = 1
OpCPUArrayType = 1
OpCPUSliceType = 1
OpCPUPointerType = 1
OpCPUInterfaceType = 1
OpCPUChanType = 1
OpCPUFuncType = 1
OpCPUMapType = 1
OpCPUStructType = 1
OpCPUMaybeNativeType = 1
/* Statement operators */
OpCPUAssign = 1
OpCPUAddAssign = 1
OpCPUSubAssign = 1
OpCPUMulAssign = 1
OpCPUQuoAssign = 1
OpCPURemAssign = 1
OpCPUBandAssign = 1
OpCPUBandnAssign = 1
OpCPUBorAssign = 1
OpCPUXorAssign = 1
OpCPUShlAssign = 1
OpCPUShrAssign = 1
OpCPUDefine = 1
OpCPUInc = 1
OpCPUDec = 1
/* Decl operators */
OpCPUValueDecl = 1
OpCPUTypeDecl = 1
/* Loop (sticky) operators (>= 0xD0) */
OpCPUSticky = 1
OpCPUBody = 1
OpCPUForLoop = 1
OpCPURangeIter = 1
OpCPURangeIterString = 1
OpCPURangeIterMap = 1
OpCPURangeIterArrayPtr = 1
OpCPUReturnCallDefers = 1
)
//----------------------------------------
// main run loop.
func (m *Machine) Run() {
for {
op := m.PopOp()
// TODO: this can be optimized manually, even into tiers.
switch op {
/* Control operators */
case OpHalt:
m.incrCPU(OpCPUHalt)
return
case OpNoop:
m.incrCPU(OpCPUNoop)
continue
case OpExec:
m.incrCPU(OpCPUExec)
m.doOpExec(op)
case OpPrecall:
m.incrCPU(OpCPUPrecall)
m.doOpPrecall()
case OpCall:
m.incrCPU(OpCPUCall)
m.doOpCall()
case OpCallNativeBody:
m.incrCPU(OpCPUCallNativeBody)
m.doOpCallNativeBody()
case OpReturn:
m.incrCPU(OpCPUReturn)
m.doOpReturn()
case OpReturnFromBlock:
m.incrCPU(OpCPUReturnFromBlock)
m.doOpReturnFromBlock()
case OpReturnToBlock:
m.incrCPU(OpCPUReturnToBlock)
m.doOpReturnToBlock()
case OpDefer:
m.incrCPU(OpCPUDefer)
m.doOpDefer()
case OpPanic1:
m.incrCPU(OpCPUPanic1)
m.doOpPanic1()
case OpPanic2:
m.incrCPU(OpCPUPanic2)
m.doOpPanic2()
case OpCallDeferNativeBody: