forked from ezdapps/backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval.go
More file actions
75 lines (67 loc) · 2.41 KB
/
eval.go
File metadata and controls
75 lines (67 loc) · 2.41 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
// 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 (
log "github.com/sirupsen/logrus"
"github.com/GenesisKernel/go-genesis/packages/consts"
"github.com/GenesisKernel/go-genesis/packages/crypto"
)
type evalCode struct {
Source string
Code *Block
}
var (
evals = make(map[uint64]*evalCode)
)
// CompileEval compiles conditional exppression
func (vm *VM) CompileEval(input string, state uint32) error {
source := `func eval bool { return ` + input + `}`
block, err := vm.CompileBlock([]rune(source), &OwnerInfo{StateID: state})
if err == nil {
crc, err := crypto.CalcChecksum([]byte(input))
if err != nil {
log.WithFields(log.Fields{"type": consts.CryptoError, "error": err}).Fatal("calculating compile eval input checksum")
}
evals[crc] = &evalCode{Source: input, Code: block}
return nil
}
return err
}
// EvalIf runs the conditional expression. It compiles the source code before that if that's necessary.
func (vm *VM) EvalIf(input string, state uint32, vars *map[string]interface{}) (bool, error) {
if len(input) == 0 {
return true, nil
}
crc, err := crypto.CalcChecksum([]byte(input))
if err != nil {
log.WithFields(log.Fields{"type": consts.CryptoError, "error": err}).Fatal("calculating compile eval checksum")
}
if eval, ok := evals[crc]; !ok || eval.Source != input {
if err := vm.CompileEval(input, state); err != nil {
log.WithFields(log.Fields{"type": consts.EvalError, "error": err}).Error("compiling eval")
return false, err
}
}
rt := vm.RunInit(CostDefault)
ret, err := rt.Run(evals[crc].Code.Children[0], nil, vars)
if err == nil {
if len(ret) == 0 {
return false, nil
}
return valueToBool(ret[0]), nil
}
return false, err
}