summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/d5/tengo/compiler/bytecode_decode.go
blob: b3b32a64269746780c4572d4e72fe8ee519ae8de (plain) (blame)
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
package compiler

import (
	"encoding/gob"
	"fmt"
	"io"

	"github.com/d5/tengo/objects"
)

// Decode reads Bytecode data from the reader.
func (b *Bytecode) Decode(r io.Reader, modules *objects.ModuleMap) error {
	if modules == nil {
		modules = objects.NewModuleMap()
	}

	dec := gob.NewDecoder(r)

	if err := dec.Decode(&b.FileSet); err != nil {
		return err
	}
	// TODO: files in b.FileSet.File does not have their 'set' field properly set to b.FileSet
	// as it's private field and not serialized by gob encoder/decoder.

	if err := dec.Decode(&b.MainFunction); err != nil {
		return err
	}

	if err := dec.Decode(&b.Constants); err != nil {
		return err
	}
	for i, v := range b.Constants {
		fv, err := fixDecoded(v, modules)
		if err != nil {
			return err
		}
		b.Constants[i] = fv
	}

	return nil
}

func fixDecoded(o objects.Object, modules *objects.ModuleMap) (objects.Object, error) {
	switch o := o.(type) {
	case *objects.Bool:
		if o.IsFalsy() {
			return objects.FalseValue, nil
		}
		return objects.TrueValue, nil
	case *objects.Undefined:
		return objects.UndefinedValue, nil
	case *objects.Array:
		for i, v := range o.Value {
			fv, err := fixDecoded(v, modules)
			if err != nil {
				return nil, err
			}
			o.Value[i] = fv
		}
	case *objects.ImmutableArray:
		for i, v := range o.Value {
			fv, err := fixDecoded(v, modules)
			if err != nil {
				return nil, err
			}
			o.Value[i] = fv
		}
	case *objects.Map:
		for k, v := range o.Value {
			fv, err := fixDecoded(v, modules)
			if err != nil {
				return nil, err
			}
			o.Value[k] = fv
		}
	case *objects.ImmutableMap:
		modName := moduleName(o)
		if mod := modules.GetBuiltinModule(modName); mod != nil {
			return mod.AsImmutableMap(modName), nil
		}

		for k, v := range o.Value {
			// encoding of user function not supported
			if _, isUserFunction := v.(*objects.UserFunction); isUserFunction {
				return nil, fmt.Errorf("user function not decodable")
			}

			fv, err := fixDecoded(v, modules)
			if err != nil {
				return nil, err
			}
			o.Value[k] = fv
		}
	}

	return o, nil
}