forked from ezdapps/backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile.go
More file actions
1172 lines (1110 loc) · 35.1 KB
/
compile.go
File metadata and controls
1172 lines (1110 loc) · 35.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The go-daylight Authors
// This file is part of the go-daylight library.
//
// The go-daylight library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-daylight library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-daylight library. If not, see <http://www.gnu.org/licenses/>.
package script
import (
"fmt"
"reflect"
"strconv"
"github.com/GenesisKernel/go-genesis/packages/consts"
log "github.com/sirupsen/logrus"
)
// operPrior contains command and its priority
type operPrior struct {
Cmd uint16 // identifier of the command
Priority uint16 // priority of the command
}
// State contains a new state and a handle function
type compileState struct {
NewState int // a new state
Func int // a handle function
}
type stateLine map[int]compileState
// The list of compile states
type compileStates []stateLine
type compileFunc func(*[]*Block, int, *Lexem) error
// The compiler converts the sequence of lexemes into the bytecodes using a finite state machine the same as
// it was implemented in lexical analysis. The difference lays in that we do not convert the list of
// states and transitions to the intermediate array.
/* Byte code could be described as a tree where functions and contracts are on the top level and
nesting goes further according to nesting of bracketed brackets. Tree nodes are structures of
'Block' type. For instance,
func a {
if b {
while d {
}
}
if c {
}
}
will be compiled into Block(a) which will have two child blocks Block (b) and Block (c) that
are responsible for executing bytecode inside if. Block (b) will have a child Block (d) with
a cycle.
*/
const (
// The list of state types
stateRoot = iota
stateBody
stateBlock
stateContract
stateFunc
stateFParams
stateFParam
stateFParamTYPE
stateFTail
stateFResult
stateFDot
stateVar
stateVarType
stateAssignEval
stateAssign
stateTX
stateSettings
stateConsts
stateConstsAssign
stateConstsValue
stateFields
stateEval
// The list of state flags
statePush = 0x0100
statePop = 0x0200
stateStay = 0x0400
stateToBlock = 0x0800
stateToBody = 0x1000
stateFork = 0x2000
stateToFork = 0x4000
stateLabel = 0x8000
stateMustEval = 0x010000
flushMark = 0x100000
)
const (
// Errors of compilation
// errNoError = iota
errUnknownCmd = iota + 1 // unknown command
errMustName // must be the name
errMustLCurly // must be '{'
errMustRCurly // must be '}'
errParams // wrong parameters
errVars // wrong variables
errVarType // must be type
errAssign // must be '='
errStrNum // must be number or string
)
const (
// This is a list of identifiers for functions that will generate a bytecode for
// the corresponding cases
// Indexes of handle functions funcs = CompileFunc[]
// cfNothing = iota
cfError = iota + 1
cfNameBlock
cfFResult
cfReturn
cfIf
cfElse
cfFParam
cfFType
cfFTail
cfFNameParam
cfAssignVar
cfAssign
cfTX
cfSettings
cfConstName
cfConstValue
cfField
cfFieldType
cfFieldTag
cfWhile
cfContinue
cfBreak
cfCmdError
// cfEval
)
var (
// Array of operations and their priority
opers = map[uint32]operPrior{
isOr: {cmdOr, 10}, isAnd: {cmdAnd, 15}, isEqEq: {cmdEqual, 20}, isNotEq: {cmdNotEq, 20},
isLess: {cmdLess, 22}, isGrEq: {cmdNotLess, 22}, isGreat: {cmdGreat, 22}, isLessEq: {cmdNotGreat, 22},
isPlus: {cmdAdd, 25}, isMinus: {cmdSub, 25}, isAsterisk: {cmdMul, 30},
isSolidus: {cmdDiv, 30}, isSign: {cmdSign, cmdUnary}, isNot: {cmdNot, cmdUnary}, isLPar: {cmdSys, 0xff}, isRPar: {cmdSys, 0},
}
// The array of functions corresponding to the constants cf...
funcs = []compileFunc{nil,
fError,
fNameBlock,
fFuncResult,
fReturn,
fIf,
fElse,
fFparam,
fFtype,
fFtail,
fFNameParam,
fAssignVar,
fAssign,
fTx,
fSettings,
fConstName,
fConstValue,
fField,
fFieldType,
fFieldTag,
fWhile,
fContinue,
fBreak,
fCmdError,
}
// 'states' describes a finite machine with states on the base of which a bytecode will be generated
states = compileStates{
{ // stateRoot
lexNewLine: {stateRoot, 0},
lexKeyword | (keyContract << 8): {stateContract | statePush, 0},
lexKeyword | (keyFunc << 8): {stateFunc | statePush, 0},
0: {errUnknownCmd, cfError},
},
{ // stateBody
lexNewLine: {stateBody, 0},
lexKeyword | (keyFunc << 8): {stateFunc | statePush, 0},
lexKeyword | (keyReturn << 8): {stateEval, cfReturn},
lexKeyword | (keyContinue << 8): {stateBody, cfContinue},
lexKeyword | (keyBreak << 8): {stateBody, cfBreak},
lexKeyword | (keyIf << 8): {stateEval | statePush | stateToBlock | stateMustEval, cfIf},
lexKeyword | (keyWhile << 8): {stateEval | statePush | stateToBlock | stateLabel | stateMustEval, cfWhile},
lexKeyword | (keyElse << 8): {stateBlock | statePush, cfElse},
lexKeyword | (keyVar << 8): {stateVar, 0},
lexKeyword | (keyTX << 8): {stateTX, cfTX},
lexKeyword | (keySettings << 8): {stateSettings, cfSettings},
lexKeyword | (keyError << 8): {stateEval, cfCmdError},
lexKeyword | (keyWarning << 8): {stateEval, cfCmdError},
lexKeyword | (keyInfo << 8): {stateEval, cfCmdError},
lexIdent: {stateAssignEval | stateFork, 0},
lexExtend: {stateAssignEval | stateFork, 0},
isRCurly: {statePop, 0},
0: {errMustRCurly, cfError},
},
{ // stateBlock
lexNewLine: {stateBlock, 0},
isLCurly: {stateBody, 0},
0: {errMustLCurly, cfError},
},
{ // stateContract
lexNewLine: {stateContract, 0},
lexIdent: {stateBlock, cfNameBlock},
0: {errMustName, cfError},
},
{ // stateFunc
lexNewLine: {stateFunc, 0},
lexIdent: {stateFParams, cfNameBlock},
0: {errMustName, cfError},
},
{ // stateFParams
lexNewLine: {stateFParams, 0},
isLPar: {stateFParam, 0},
0: {stateFResult | stateStay, 0},
},
{ // stateFParam
lexNewLine: {stateFParam, 0},
lexIdent: {stateFParamTYPE, cfFParam},
// lexType: {stateFParam, cfFType},
isComma: {stateFParam, 0},
isRPar: {stateFResult, 0},
0: {errParams, cfError},
},
{ // stateFParamTYPE
lexIdent: {stateFParamTYPE, cfFParam},
lexType: {stateFParam, cfFType},
lexKeyword | (keyTail << 8): {stateFTail, cfFTail},
isComma: {stateFParamTYPE, 0},
// isRPar: {stateFResult, 0},
0: {errVarType, cfError},
},
{ // stateFTail
lexNewLine: {stateFTail, 0},
isRPar: {stateFResult, 0},
0: {errParams, cfError},
},
{ // stateFResult
lexNewLine: {stateFResult, 0},
isDot: {stateFDot, 0},
lexType: {stateFResult, cfFResult},
isComma: {stateFResult, 0},
0: {stateBlock | stateStay, 0},
},
{ // stateFDot
lexNewLine: {stateFDot, 0},
lexIdent: {stateFParams, cfFNameParam},
0: {errMustName, cfError},
},
{ // stateVar
lexNewLine: {stateBody, 0},
lexIdent: {stateVarType, cfFParam},
isRCurly: {stateBody | stateStay, 0},
isComma: {stateVar, 0},
0: {errVars, cfError},
},
{ // stateVarType
lexIdent: {stateVarType, cfFParam},
lexType: {stateVar, cfFType},
isComma: {stateVarType, 0},
0: {errVarType, cfError},
},
{ // stateAssignEval
isLPar: {stateEval | stateToFork | stateToBody, 0},
isLBrack: {stateEval | stateToFork | stateToBody, 0},
0: {stateAssign | stateToFork | stateStay, 0},
},
{ // stateAssign
isComma: {stateAssign, 0},
lexIdent: {stateAssign, cfAssignVar},
lexExtend: {stateAssign, cfAssignVar},
isEq: {stateEval | stateToBody, cfAssign},
0: {errAssign, cfError},
},
{ // stateTX
lexNewLine: {stateTX, 0},
isLCurly: {stateFields, 0},
0: {errMustLCurly, cfError},
},
{ // stateSettings
lexNewLine: {stateSettings, 0},
isLCurly: {stateConsts, 0},
0: {errMustLCurly, cfError},
},
{ // stateConsts
lexNewLine: {stateConsts, 0},
isComma: {stateConsts, 0},
lexIdent: {stateConstsAssign, cfConstName},
isRCurly: {stateToBody, 0},
0: {errMustRCurly, cfError},
},
{ // stateConstsAssign
isEq: {stateConstsValue, 0},
0: {errAssign, cfError},
},
{ // stateConstsValue
lexString: {stateConsts, cfConstValue},
lexNumber: {stateConsts, cfConstValue},
0: {errStrNum, cfError},
},
{ // stateFields
lexNewLine: {stateFields, 0},
isComma: {stateFields, 0},
lexIdent: {stateFields, cfField},
lexType: {stateFields, cfFieldType},
lexString: {stateFields, cfFieldTag},
isRCurly: {stateToBody, 0},
0: {errMustRCurly, cfError},
},
}
)
func fError(buf *[]*Block, state int, lexem *Lexem) error {
errors := []string{`no error`,
`unknown command`, // errUnknownCmd
`must be the name`, // errMustName
`must be '{'`, // errMustLCurly
`must be '}'`, // errMustRCurly
`wrong parameters`, // errParams
`wrong variables`, // errVars
`must be type`, // errVarType
`must be '='`, // errAssign
`must be number or string`, // errStrNum
}
fmt.Printf("%s %x %v [Ln:%d Col:%d]\r\n", errors[state], lexem.Type, lexem.Value, lexem.Line, lexem.Column)
logger := lexem.GetLogger()
if lexem.Type == lexNewLine {
logger.WithFields(log.Fields{"error": errors[state], "lex_value": lexem.Value, "type": consts.ParseError}).Error("unexpected new line")
return fmt.Errorf(`%s (unexpected new line) [Ln:%d]`, errors[state], lexem.Line-1)
}
logger.WithFields(log.Fields{"error": errors[state], "lex_value": lexem.Value, "type": consts.ParseError}).Error("parsing error")
return fmt.Errorf(`%s %x %v [Ln:%d Col:%d]`, errors[state], lexem.Type, lexem.Value, lexem.Line, lexem.Column)
}
func fFuncResult(buf *[]*Block, state int, lexem *Lexem) error {
fblock := (*buf)[len(*buf)-1].Info.(*FuncInfo)
(*fblock).Results = append((*fblock).Results, lexem.Value.(reflect.Type))
return nil
}
func fReturn(buf *[]*Block, state int, lexem *Lexem) error {
(*(*buf)[len(*buf)-1]).Code = append((*(*buf)[len(*buf)-1]).Code, &ByteCode{cmdReturn, 0})
return nil
}
func fCmdError(buf *[]*Block, state int, lexem *Lexem) error {
(*(*buf)[len(*buf)-1]).Code = append((*(*buf)[len(*buf)-1]).Code, &ByteCode{cmdError, lexem.Value})
return nil
}
func fFparam(buf *[]*Block, state int, lexem *Lexem) error {
block := (*buf)[len(*buf)-1]
if block.Type == ObjFunc && (state == stateFParam || state == stateFParamTYPE) {
fblock := block.Info.(*FuncInfo)
if fblock.Names == nil {
fblock.Params = append(fblock.Params, reflect.TypeOf(nil))
} else {
for key := range *fblock.Names {
if key[0] == '_' {
name := key[1:]
params := append((*fblock.Names)[name].Params, reflect.TypeOf(nil))
offset := append((*fblock.Names)[name].Offset, len(block.Vars))
(*fblock.Names)[name] = FuncName{Params: params, Offset: offset}
break
}
}
}
}
if block.Objects == nil {
block.Objects = make(map[string]*ObjInfo)
}
block.Objects[lexem.Value.(string)] = &ObjInfo{Type: ObjVar, Value: len(block.Vars)}
block.Vars = append(block.Vars, reflect.TypeOf(nil))
return nil
}
func fFtype(buf *[]*Block, state int, lexem *Lexem) error {
block := (*buf)[len(*buf)-1]
if block.Type == ObjFunc && state == stateFParam {
fblock := block.Info.(*FuncInfo)
if fblock.Names == nil {
for pkey, param := range fblock.Params {
if param == reflect.TypeOf(nil) {
fblock.Params[pkey] = lexem.Value.(reflect.Type)
}
}
} else {
for key := range *fblock.Names {
if key[0] == '_' {
for pkey, param := range (*fblock.Names)[key[1:]].Params {
if param == reflect.TypeOf(nil) {
(*fblock.Names)[key[1:]].Params[pkey] = lexem.Value.(reflect.Type)
}
}
break
}
}
}
}
for vkey, ivar := range block.Vars {
if ivar == reflect.TypeOf(nil) {
block.Vars[vkey] = lexem.Value.(reflect.Type)
}
}
return nil
}
func fFtail(buf *[]*Block, state int, lexem *Lexem) error {
var used bool
block := (*buf)[len(*buf)-1]
fblock := block.Info.(*FuncInfo)
if fblock.Names == nil {
for pkey, param := range fblock.Params {
if param == reflect.TypeOf(nil) {
if used {
return fmt.Errorf(`... parameter must be one`)
}
fblock.Params[pkey] = reflect.TypeOf([]interface{}{})
used = true
}
}
block.Info.(*FuncInfo).Variadic = true
} else {
for key := range *fblock.Names {
if key[0] == '_' {
name := key[1:]
for pkey, param := range (*fblock.Names)[name].Params {
if param == reflect.TypeOf(nil) {
if used {
return fmt.Errorf(`... parameter must be one`)
}
(*fblock.Names)[name].Params[pkey] = reflect.TypeOf([]interface{}{})
used = true
}
}
offset := append((*fblock.Names)[name].Offset, len(block.Vars))
(*fblock.Names)[name] = FuncName{Params: (*fblock.Names)[name].Params,
Offset: offset, Variadic: true}
break
}
}
}
for vkey, ivar := range block.Vars {
if ivar == reflect.TypeOf(nil) {
block.Vars[vkey] = reflect.TypeOf([]interface{}{})
}
}
return nil
}
func fFNameParam(buf *[]*Block, state int, lexem *Lexem) error {
block := (*buf)[len(*buf)-1]
fblock := block.Info.(*FuncInfo)
if fblock.Names == nil {
names := make(map[string]FuncName)
fblock.Names = &names
}
for key := range *fblock.Names {
if key[0] == '_' {
delete(*fblock.Names, key)
}
}
(*fblock.Names)[`_`+lexem.Value.(string)] = FuncName{}
return nil
}
func fIf(buf *[]*Block, state int, lexem *Lexem) error {
(*(*buf)[len(*buf)-2]).Code = append((*(*buf)[len(*buf)-2]).Code, &ByteCode{cmdIf, (*buf)[len(*buf)-1]})
return nil
}
func fWhile(buf *[]*Block, state int, lexem *Lexem) error {
(*(*buf)[len(*buf)-2]).Code = append((*(*buf)[len(*buf)-2]).Code, &ByteCode{cmdWhile, (*buf)[len(*buf)-1]})
(*(*buf)[len(*buf)-2]).Code = append((*(*buf)[len(*buf)-2]).Code, &ByteCode{cmdContinue, 0})
return nil
}
func fContinue(buf *[]*Block, state int, lexem *Lexem) error {
(*(*buf)[len(*buf)-1]).Code = append((*(*buf)[len(*buf)-1]).Code, &ByteCode{cmdContinue, 0})
return nil
}
func fBreak(buf *[]*Block, state int, lexem *Lexem) error {
(*(*buf)[len(*buf)-1]).Code = append((*(*buf)[len(*buf)-1]).Code, &ByteCode{cmdBreak, 0})
return nil
}
func fAssignVar(buf *[]*Block, state int, lexem *Lexem) error {
block := (*buf)[len(*buf)-1]
var (
prev []*VarInfo
ivar VarInfo
)
if lexem.Type == lexExtend {
ivar = VarInfo{&ObjInfo{ObjExtend, lexem.Value.(string)}, nil}
} else {
objInfo, tobj := findVar(lexem.Value.(string), buf)
if objInfo == nil || objInfo.Type != ObjVar {
logger := lexem.GetLogger()
logger.WithFields(log.Fields{"type": consts.ParseError, "lex_value": lexem.Value.(string)}).Error("unknown variable")
return fmt.Errorf(`unknown variable %s`, lexem.Value.(string))
}
ivar = VarInfo{objInfo, tobj}
}
if len(block.Code) > 0 {
if block.Code[len(block.Code)-1].Cmd == cmdAssignVar {
prev = block.Code[len(block.Code)-1].Value.([]*VarInfo)
}
}
prev = append(prev, &ivar)
if len(prev) == 1 {
(*(*buf)[len(*buf)-1]).Code = append((*block).Code, &ByteCode{cmdAssignVar, prev})
} else {
(*(*buf)[len(*buf)-1]).Code[len(block.Code)-1] = &ByteCode{cmdAssignVar, prev}
}
return nil
}
func fAssign(buf *[]*Block, state int, lexem *Lexem) error {
(*(*buf)[len(*buf)-1]).Code = append((*(*buf)[len(*buf)-1]).Code, &ByteCode{cmdAssign, 0})
return nil
}
func fTx(buf *[]*Block, state int, lexem *Lexem) error {
contract := (*buf)[len(*buf)-1]
logger := lexem.GetLogger()
if contract.Type != ObjContract {
logger.WithFields(log.Fields{"type": consts.ParseError, "contract_type": contract.Type, "lex_value": lexem.Value}).Error("data can only be in contract")
return fmt.Errorf(`data can only be in contract`)
}
(*contract).Info.(*ContractInfo).Tx = new([]*FieldInfo)
return nil
}
func fSettings(buf *[]*Block, state int, lexem *Lexem) error {
contract := (*buf)[len(*buf)-1]
if contract.Type != ObjContract {
logger := lexem.GetLogger()
logger.WithFields(log.Fields{"type": consts.ParseError, "contract_type": contract.Type, "lex_value": lexem.Value}).Error("data can only be in contract")
return fmt.Errorf(`data can only be in contract`)
}
(*contract).Info.(*ContractInfo).Settings = make(map[string]interface{})
return nil
}
func fConstName(buf *[]*Block, state int, lexem *Lexem) error {
sets := (*(*buf)[len(*buf)-1]).Info.(*ContractInfo).Settings
sets[lexem.Value.(string)] = nil
return nil
}
func fConstValue(buf *[]*Block, state int, lexem *Lexem) error {
sets := (*(*buf)[len(*buf)-1]).Info.(*ContractInfo).Settings
for key, val := range sets {
if val == nil {
sets[key] = lexem.Value
break
}
}
return nil
}
func fField(buf *[]*Block, state int, lexem *Lexem) error {
tx := (*(*buf)[len(*buf)-1]).Info.(*ContractInfo).Tx
*tx = append(*tx, &FieldInfo{Name: lexem.Value.(string), Type: reflect.TypeOf(nil)})
return nil
}
func fFieldType(buf *[]*Block, state int, lexem *Lexem) error {
tx := (*(*buf)[len(*buf)-1]).Info.(*ContractInfo).Tx
for i, field := range *tx {
if field.Type == reflect.TypeOf(nil) {
(*tx)[i].Type = lexem.Value.(reflect.Type)
}
}
return nil
}
func fFieldTag(buf *[]*Block, state int, lexem *Lexem) error {
tx := (*(*buf)[len(*buf)-1]).Info.(*ContractInfo).Tx
for i := len(*tx) - 1; i >= 0; i-- {
if len((*tx)[i].Tags) == 0 {
(*tx)[i].Tags = lexem.Value.(string)
break
}
}
return nil
}
func fElse(buf *[]*Block, state int, lexem *Lexem) error {
code := (*(*buf)[len(*buf)-2]).Code
if code[len(code)-1].Cmd != cmdIf {
logger := lexem.GetLogger()
logger.WithFields(log.Fields{"type": consts.ParseError}).Error("there is not if before")
return fmt.Errorf(`there is not if before %v [Ln:%d Col:%d]`, lexem.Type, lexem.Line, lexem.Column)
}
(*(*buf)[len(*buf)-2]).Code = append(code, &ByteCode{cmdElse, (*buf)[len(*buf)-1]})
return nil
}
// StateName checks the name of the contract and modifies it to @[state]name if it is necessary.
func StateName(state uint32, name string) string {
if len(name) < 3 {
return name
}
if name[0] != '@' {
return fmt.Sprintf(`@%d%s`, state, name)
} else if name[1] < '0' || name[1] > '9' {
name = `@0` + name[1:]
}
return name
}
func fNameBlock(buf *[]*Block, state int, lexem *Lexem) error {
var itype int
prev := (*buf)[len(*buf)-2]
fblock := (*buf)[len(*buf)-1]
name := lexem.Value.(string)
switch state {
case stateBlock:
itype = ObjContract
name = StateName((*buf)[0].Info.(uint32), name)
fblock.Info = &ContractInfo{ID: uint32(len(prev.Children) - 1), Name: name,
Owner: (*buf)[0].Owner}
default:
itype = ObjFunc
fblock.Info = &FuncInfo{}
}
fblock.Type = itype
prev.Objects[name] = &ObjInfo{Type: itype, Value: fblock}
return nil
}
// CompileBlock compile the source code into the Block structure with a byte-code
func (vm *VM) CompileBlock(input []rune, owner *OwnerInfo) (*Block, error) {
root := &Block{Info: owner.StateID, Owner: owner}
lexems, err := lexParser(input)
if err != nil {
return nil, err
}
if len(lexems) == 0 {
return root, nil
}
curState := 0
stack := make([]int, 0, 64)
blockstack := make([]*Block, 1, 64)
blockstack[0] = root
fork := 0
for i := 0; i < len(lexems); i++ {
var (
newState compileState
ok bool
)
lexem := lexems[i]
if newState, ok = states[curState][int(lexem.Type)]; !ok {
newState = states[curState][0]
}
nextState := newState.NewState & 0xff
if (newState.NewState & stateFork) > 0 {
fork = i
}
if (newState.NewState & stateToFork) > 0 {
i = fork
fork = 0
lexem = lexems[i]
}
if (newState.NewState & stateStay) > 0 {
curState = nextState
i--
continue
}
if nextState == stateEval {
if newState.NewState&stateLabel > 0 {
(*blockstack[len(blockstack)-1]).Code = append((*blockstack[len(blockstack)-1]).Code, &ByteCode{cmdLabel, 0})
}
curlen := len((*blockstack[len(blockstack)-1]).Code)
if err := vm.compileEval(&lexems, &i, &blockstack); err != nil {
return nil, err
}
if (newState.NewState&stateMustEval) > 0 && curlen == len((*blockstack[len(blockstack)-1]).Code) {
log.WithFields(log.Fields{"type": consts.ParseError}).Error("there is not eval expression")
return nil, fmt.Errorf("there is not eval expression")
}
nextState = curState
}
if (newState.NewState & statePush) > 0 {
stack = append(stack, curState)
top := blockstack[len(blockstack)-1]
if top.Objects == nil {
top.Objects = make(map[string]*ObjInfo)
}
block := &Block{Parent: top}
top.Children = append(top.Children, block)
blockstack = append(blockstack, block)
}
if (newState.NewState & statePop) > 0 {
if len(stack) == 0 {
return nil, fError(&blockstack, errMustLCurly, lexem)
}
nextState = stack[len(stack)-1]
stack = stack[:len(stack)-1]
if len(blockstack) >= 2 {
prev := blockstack[len(blockstack)-2]
if len(prev.Code) > 0 && (*prev).Code[len((*prev).Code)-1].Cmd == cmdContinue {
(*prev).Code = (*prev).Code[:len((*prev).Code)-1]
prev = blockstack[len(blockstack)-1]
(*prev).Code = append((*prev).Code, &ByteCode{cmdContinue, 0})
}
}
blockstack = blockstack[:len(blockstack)-1]
}
if (newState.NewState & stateToBlock) > 0 {
nextState = stateBlock
}
if (newState.NewState & stateToBody) > 0 {
nextState = stateBody
}
if newState.Func > 0 {
if err := funcs[newState.Func](&blockstack, nextState, lexem); err != nil {
return nil, err
}
}
curState = nextState
}
if len(stack) > 0 {
return nil, fError(&blockstack, errMustRCurly, lexems[len(lexems)-1])
}
return root, nil
}
// FlushBlock loads the compiled Block into the virtual machine
func (vm *VM) FlushBlock(root *Block) {
shift := len(vm.Children)
for key, item := range root.Objects {
if cur, ok := vm.Objects[key]; ok {
switch item.Type {
case ObjContract:
root.Objects[key].Value.(*Block).Info.(*ContractInfo).ID = cur.Value.(*Block).Info.(*ContractInfo).ID + flushMark
case ObjFunc:
root.Objects[key].Value.(*Block).Info.(*FuncInfo).ID = cur.Value.(*Block).Info.(*FuncInfo).ID + flushMark
vm.Objects[key].Value = root.Objects[key].Value
}
}
vm.Objects[key] = item
}
for _, item := range root.Children {
switch item.Type {
case ObjContract:
if item.Info.(*ContractInfo).ID > flushMark {
item.Info.(*ContractInfo).ID -= flushMark
vm.Children[item.Info.(*ContractInfo).ID] = item
shift--
continue
}
item.Parent = &vm.Block
item.Info.(*ContractInfo).ID += uint32(shift)
case ObjFunc:
if item.Info.(*FuncInfo).ID > flushMark {
item.Info.(*FuncInfo).ID -= flushMark
vm.Children[item.Info.(*FuncInfo).ID] = item
shift--
continue
}
item.Parent = &vm.Block
item.Info.(*FuncInfo).ID += uint32(shift)
}
vm.Children = append(vm.Children, item)
}
}
// FlushExtern switches off the extern mode of the compilation
func (vm *VM) FlushExtern() {
vm.Extern = false
return
}
// Compile compiles a source code and loads the byte-code into the virtual machine
func (vm *VM) Compile(input []rune, owner *OwnerInfo) error {
root, err := vm.CompileBlock(input, owner)
if err == nil {
vm.FlushBlock(root)
}
return err
}
func findVar(name string, block *[]*Block) (ret *ObjInfo, owner *Block) {
var ok bool
i := len(*block) - 1
for ; i >= 0; i-- {
ret, ok = (*block)[i].Objects[name]
if ok {
return ret, (*block)[i]
}
}
return nil, nil
}
func (vm *VM) findObj(name string, block *[]*Block) (ret *ObjInfo, owner *Block) {
sname := StateName((*block)[0].Info.(uint32), name)
ret, owner = findVar(name, block)
if ret != nil {
return
} else if len(sname) > 0 {
if ret, owner = findVar(sname, block); ret != nil {
return
}
}
if ret = vm.getObjByName(name); ret == nil && len(sname) > 0 {
ret = vm.getObjByName(sname)
}
return
}
// This function is responsible for the compilation of expressions
func (vm *VM) compileEval(lexems *Lexems, ind *int, block *[]*Block) error {
var indexInfo *IndexInfo
i := *ind
curBlock := (*block)[len(*block)-1]
buffer := make(ByteCodes, 0, 20)
bytecode := make(ByteCodes, 0, 100)
parcount := make([]int, 0, 20)
setIndex := false
main:
for ; i < len(*lexems); i++ {
var cmd *ByteCode
var call bool
lexem := (*lexems)[i]
logger := lexem.GetLogger()
switch lexem.Type {
case isRCurly, isLCurly:
i--
break main
case lexNewLine:
if i > 0 && ((*lexems)[i-1].Type == isComma || (*lexems)[i-1].Type == lexOper) {
continue main
}
for k := len(buffer) - 1; k >= 0; k-- {
if buffer[k].Cmd == cmdSys {
continue main
}
}
break main
case isLPar:
buffer = append(buffer, &ByteCode{cmdSys, uint16(0xff)})
case isLBrack:
buffer = append(buffer, &ByteCode{cmdSys, uint16(0xff)})
case isComma:
if len(parcount) > 0 {
parcount[len(parcount)-1]++
}
for len(buffer) > 0 {
prev := buffer[len(buffer)-1]
if prev.Cmd == cmdSys && prev.Value.(uint16) == 0xff {
break
} else {
bytecode = append(bytecode, prev)
buffer = buffer[:len(buffer)-1]
}
}
case isRPar:
for {
if len(buffer) == 0 {
logger.WithFields(log.Fields{"lex_value": lexem.Value.(string), "type": consts.ParseError}).Error("there is not pair")
return fmt.Errorf(`there is not pair`)
}
prev := buffer[len(buffer)-1]
buffer = buffer[:len(buffer)-1]
if prev.Value.(uint16) == 0xff {
break
} else {
bytecode = append(bytecode, prev)
}
}
if len(buffer) > 0 {
if prev := buffer[len(buffer)-1]; prev.Cmd == cmdFuncName {
buffer = buffer[:len(buffer)-1]
(*prev).Value = FuncNameCmd{Name: prev.Value.(FuncNameCmd).Name,
Count: parcount[len(parcount)-1]}
parcount = parcount[:len(parcount)-1]
bytecode = append(bytecode, prev)
}
var tail *ByteCode
if prev := buffer[len(buffer)-1]; prev.Cmd == cmdCall || prev.Cmd == cmdCallVari {
if prev.Value.(*ObjInfo).Type == ObjFunc && prev.Value.(*ObjInfo).Value.(*Block).Info.(*FuncInfo).Names != nil {
if len(bytecode) == 0 || bytecode[len(bytecode)-1].Cmd != cmdFuncName {
bytecode = append(bytecode, &ByteCode{cmdPush, nil})
}
if i < len(*lexems)-4 && (*lexems)[i+1].Type == isDot {
if (*lexems)[i+2].Type != lexIdent {
log.WithFields(log.Fields{"type": consts.ParseError}).Error("must be the name of the tail")
return fmt.Errorf(`must be the name of the tail`)
}
names := prev.Value.(*ObjInfo).Value.(*Block).Info.(*FuncInfo).Names
if _, ok := (*names)[(*lexems)[i+2].Value.(string)]; !ok {
if i < len(*lexems)-5 && (*lexems)[i+3].Type == isLPar {
objInfo, _ := vm.findObj((*lexems)[i+2].Value.(string), block)
if objInfo != nil && objInfo.Type == ObjFunc || objInfo.Type == ObjExtFunc {
tail = &ByteCode{uint16(cmdCall), objInfo}
}
}
if tail == nil {
log.WithFields(log.Fields{"type": consts.ParseError, "tail": (*lexems)[i+2].Value.(string)}).Error("unknown function tail")
return fmt.Errorf(`unknown function tail %s`, (*lexems)[i+2].Value.(string))
}
}
if tail == nil {
buffer = append(buffer, &ByteCode{cmdFuncName, FuncNameCmd{Name: (*lexems)[i+2].Value.(string)}})
count := 0
if (*lexems)[i+3].Type != isRPar {
count++
}
parcount = append(parcount, count)
i += 2
break
}
}
}
count := parcount[len(parcount)-1]
parcount = parcount[:len(parcount)-1]
if prev.Value.(*ObjInfo).Type == ObjExtFunc {
var errtext string
extinfo := prev.Value.(*ObjInfo).Value.(ExtFuncInfo)
wantlen := len(extinfo.Params)
for _, v := range extinfo.Auto {
if len(v) > 0 {
wantlen--
}
}
if count != wantlen && (!extinfo.Variadic || count < wantlen) {
errtext = fmt.Sprintf(eWrongParams, extinfo.Name, wantlen)
logger.WithFields(log.Fields{"error": errtext, "type": consts.ParseError}).Error(errtext)
return fmt.Errorf(errtext)
}
}
if prev.Cmd == cmdCallVari {
bytecode = append(bytecode, &ByteCode{cmdPush, count})
}
buffer = buffer[:len(buffer)-1]
bytecode = append(bytecode, prev)
if tail != nil {
buffer = append(buffer, tail)
parcount = append(parcount, 1)
i += 2
}
}
}
case isRBrack:
for {
if len(buffer) == 0 {
logger.WithFields(log.Fields{"lex_value": lexem.Value.(string), "type": consts.ParseError}).Error("there is not pair")
return fmt.Errorf(`there is not pair`)
}
prev := buffer[len(buffer)-1]
buffer = buffer[:len(buffer)-1]
if prev.Value.(uint16) == 0xff {
break
} else {
bytecode = append(bytecode, prev)
}
}
if len(buffer) > 0 {
if prev := buffer[len(buffer)-1]; prev.Cmd == cmdIndex {
buffer = buffer[:len(buffer)-1]
if i < len(*lexems)-1 && (*lexems)[i+1].Type == isEq {
i++
setIndex = true
indexInfo = prev.Value.(*IndexInfo)
continue
}
bytecode = append(bytecode, prev)