forked from dop251/goja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime.go
1470 lines (1294 loc) · 33.1 KB
/
runtime.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 goja
import (
"bytes"
"errors"
"fmt"
"go/ast"
"math"
"math/rand"
"reflect"
"strconv"
js_ast "github.com/dop251/goja/ast"
"github.com/dop251/goja/parser"
)
const (
sqrt1_2 float64 = math.Sqrt2 / 2
)
var (
typeCallable = reflect.TypeOf(Callable(nil))
typeValue = reflect.TypeOf((*Value)(nil)).Elem()
)
type global struct {
Object *Object
Array *Object
Function *Object
String *Object
Number *Object
Boolean *Object
RegExp *Object
Date *Object
ArrayBuffer *Object
Error *Object
TypeError *Object
ReferenceError *Object
SyntaxError *Object
RangeError *Object
EvalError *Object
URIError *Object
GoError *Object
ObjectPrototype *Object
ArrayPrototype *Object
NumberPrototype *Object
StringPrototype *Object
BooleanPrototype *Object
FunctionPrototype *Object
RegExpPrototype *Object
DatePrototype *Object
ArrayBufferPrototype *Object
ErrorPrototype *Object
TypeErrorPrototype *Object
SyntaxErrorPrototype *Object
RangeErrorPrototype *Object
ReferenceErrorPrototype *Object
EvalErrorPrototype *Object
URIErrorPrototype *Object
GoErrorPrototype *Object
Eval *Object
thrower *Object
throwerProperty Value
}
type Flag int
const (
FLAG_NOT_SET Flag = iota
FLAG_FALSE
FLAG_TRUE
)
func (f Flag) Bool() bool {
return f == FLAG_TRUE
}
func ToFlag(b bool) Flag {
if b {
return FLAG_TRUE
}
return FLAG_FALSE
}
type RandSource func() float64
type Runtime struct {
global global
globalObject *Object
stringSingleton *stringObject
rand RandSource
typeInfoCache map[reflect.Type]*reflectTypeInfo
fieldNameMapper FieldNameMapper
vm *vm
}
type stackFrame struct {
prg *Program
funcName string
pc int
}
func (f *stackFrame) position() Position {
return f.prg.src.Position(f.prg.sourceOffset(f.pc))
}
func (f *stackFrame) write(b *bytes.Buffer) {
if f.prg != nil {
if n := f.prg.funcName; n != "" {
b.WriteString(n)
b.WriteString(" (")
}
if n := f.prg.src.name; n != "" {
b.WriteString(n)
} else {
b.WriteString("<eval>")
}
b.WriteByte(':')
b.WriteString(f.position().String())
b.WriteByte('(')
b.WriteString(strconv.Itoa(f.pc))
b.WriteByte(')')
if f.prg.funcName != "" {
b.WriteByte(')')
}
} else {
if f.funcName != "" {
b.WriteString(f.funcName)
b.WriteString(" (")
}
b.WriteString("native")
if f.funcName != "" {
b.WriteByte(')')
}
}
}
type Exception struct {
val Value
stack []stackFrame
}
type InterruptedError struct {
Exception
iface interface{}
}
func (e *InterruptedError) Value() interface{} {
return e.iface
}
func (e *InterruptedError) String() string {
if e == nil {
return "<nil>"
}
var b bytes.Buffer
if e.iface != nil {
b.WriteString(fmt.Sprint(e.iface))
b.WriteByte('\n')
}
e.writeFullStack(&b)
return b.String()
}
func (e *InterruptedError) Error() string {
if e == nil || e.iface == nil {
return "<nil>"
}
var b bytes.Buffer
b.WriteString(fmt.Sprint(e.iface))
e.writeShortStack(&b)
return b.String()
}
func (e *Exception) writeFullStack(b *bytes.Buffer) {
for _, frame := range e.stack {
b.WriteString("\tat ")
frame.write(b)
b.WriteByte('\n')
}
}
func (e *Exception) writeShortStack(b *bytes.Buffer) {
if len(e.stack) > 0 && (e.stack[0].prg != nil || e.stack[0].funcName != "") {
b.WriteString(" at ")
e.stack[0].write(b)
}
}
func (e *Exception) String() string {
if e == nil {
return "<nil>"
}
var b bytes.Buffer
if e.val != nil {
b.WriteString(e.val.String())
b.WriteByte('\n')
}
e.writeFullStack(&b)
return b.String()
}
func (e *Exception) Error() string {
if e == nil || e.val == nil {
return "<nil>"
}
var b bytes.Buffer
b.WriteString(e.val.String())
e.writeShortStack(&b)
return b.String()
}
func (e *Exception) Value() Value {
return e.val
}
func (r *Runtime) addToGlobal(name string, value Value) {
r.globalObject.self._putProp(name, value, true, false, true)
}
func (r *Runtime) init() {
r.rand = rand.Float64
r.global.ObjectPrototype = r.newBaseObject(nil, classObject).val
r.globalObject = r.NewObject()
r.vm = &vm{
r: r,
}
r.vm.init()
r.global.FunctionPrototype = r.newNativeFunc(nil, nil, "Empty", nil, 0)
r.initObject()
r.initFunction()
r.initArray()
r.initString()
r.initNumber()
r.initRegExp()
r.initDate()
r.initBoolean()
r.initErrors()
r.global.Eval = r.newNativeFunc(r.builtin_eval, nil, "eval", nil, 1)
r.addToGlobal("eval", r.global.Eval)
r.initGlobalObject()
r.initMath()
r.initJSON()
//r.initTypedArrays()
r.global.thrower = r.newNativeFunc(r.builtin_thrower, nil, "thrower", nil, 0)
r.global.throwerProperty = &valueProperty{
getterFunc: r.global.thrower,
setterFunc: r.global.thrower,
accessor: true,
}
}
func (r *Runtime) typeErrorResult(throw bool, args ...interface{}) {
if throw {
panic(r.NewTypeError(args...))
}
}
func (r *Runtime) newError(typ *Object, format string, args ...interface{}) Value {
msg := fmt.Sprintf(format, args...)
return r.builtin_new(typ, []Value{newStringValue(msg)})
}
func (r *Runtime) throwReferenceError(name string) {
panic(r.newError(r.global.ReferenceError, "%s is not defined", name))
}
func (r *Runtime) newSyntaxError(msg string, offset int) Value {
return r.builtin_new((r.global.SyntaxError), []Value{newStringValue(msg)})
}
func (r *Runtime) newArray(prototype *Object) (a *arrayObject) {
v := &Object{runtime: r}
a = &arrayObject{}
a.class = classArray
a.val = v
a.extensible = true
v.self = a
a.prototype = prototype
a.init()
return
}
func (r *Runtime) newArrayObject() *arrayObject {
return r.newArray(r.global.ArrayPrototype)
}
func (r *Runtime) newArrayValues(values []Value) *Object {
v := &Object{runtime: r}
a := &arrayObject{}
a.class = classArray
a.val = v
a.extensible = true
v.self = a
a.prototype = r.global.ArrayPrototype
a.init()
a.values = values
a.length = int64(len(values))
a.objCount = a.length
return v
}
func (r *Runtime) newArrayLength(l int64) *Object {
a := r.newArrayValues(nil)
a.self.putStr("length", intToValue(l), true)
return a
}
func (r *Runtime) newBaseObject(proto *Object, class string) (o *baseObject) {
v := &Object{runtime: r}
o = &baseObject{}
o.class = class
o.val = v
o.extensible = true
v.self = o
o.prototype = proto
o.init()
return
}
func (r *Runtime) NewObject() (v *Object) {
return r.newBaseObject(r.global.ObjectPrototype, classObject).val
}
// CreateObject creates an object with given prototype. Equivalent of Object.create(proto).
func (r *Runtime) CreateObject(proto *Object) *Object {
return r.newBaseObject(proto, classObject).val
}
func (r *Runtime) NewTypeError(args ...interface{}) *Object {
msg := ""
if len(args) > 0 {
f, _ := args[0].(string)
msg = fmt.Sprintf(f, args[1:]...)
}
return r.builtin_new(r.global.TypeError, []Value{newStringValue(msg)})
}
func (r *Runtime) NewGoError(err error) *Object {
e := r.newError(r.global.GoError, err.Error()).(*Object)
e.Set("value", err)
return e
}
func (r *Runtime) newFunc(name string, len int, strict bool) (f *funcObject) {
v := &Object{runtime: r}
f = &funcObject{}
f.class = classFunction
f.val = v
f.extensible = true
v.self = f
f.prototype = r.global.FunctionPrototype
f.init(name, len)
if strict {
f._put("caller", r.global.throwerProperty)
f._put("arguments", r.global.throwerProperty)
}
return
}
func (r *Runtime) newNativeFuncObj(v *Object, call func(FunctionCall) Value, construct func(args []Value) *Object, name string, proto *Object, length int) *nativeFuncObject {
f := &nativeFuncObject{
baseFuncObject: baseFuncObject{
baseObject: baseObject{
class: classFunction,
val: v,
extensible: true,
prototype: r.global.FunctionPrototype,
},
},
f: call,
construct: construct,
}
v.self = f
f.init(name, length)
if proto != nil {
f._putProp("prototype", proto, false, false, false)
}
return f
}
func (r *Runtime) newNativeConstructor(call func(ConstructorCall) *Object, name string, length int) *Object {
v := &Object{runtime: r}
f := &nativeFuncObject{
baseFuncObject: baseFuncObject{
baseObject: baseObject{
class: classFunction,
val: v,
extensible: true,
prototype: r.global.FunctionPrototype,
},
},
}
f.f = func(c FunctionCall) Value {
return f.defaultConstruct(call, c.Arguments)
}
f.construct = func(args []Value) *Object {
return f.defaultConstruct(call, args)
}
v.self = f
f.init(name, length)
proto := r.NewObject()
proto.self._putProp("constructor", v, true, false, true)
f._putProp("prototype", proto, true, false, false)
return v
}
func (r *Runtime) newNativeFunc(call func(FunctionCall) Value, construct func(args []Value) *Object, name string, proto *Object, length int) *Object {
v := &Object{runtime: r}
f := &nativeFuncObject{
baseFuncObject: baseFuncObject{
baseObject: baseObject{
class: classFunction,
val: v,
extensible: true,
prototype: r.global.FunctionPrototype,
},
},
f: call,
construct: construct,
}
v.self = f
f.init(name, length)
if proto != nil {
f._putProp("prototype", proto, false, false, false)
proto.self._putProp("constructor", v, true, false, true)
}
return v
}
func (r *Runtime) newNativeFuncConstructObj(v *Object, construct func(args []Value, proto *Object) *Object, name string, proto *Object, length int) *nativeFuncObject {
f := &nativeFuncObject{
baseFuncObject: baseFuncObject{
baseObject: baseObject{
class: classFunction,
val: v,
extensible: true,
prototype: r.global.FunctionPrototype,
},
},
f: r.constructWrap(construct, proto),
construct: func(args []Value) *Object {
return construct(args, proto)
},
}
f.init(name, length)
if proto != nil {
f._putProp("prototype", proto, false, false, false)
}
return f
}
func (r *Runtime) newNativeFuncConstruct(construct func(args []Value, proto *Object) *Object, name string, prototype *Object, length int) *Object {
return r.newNativeFuncConstructProto(construct, name, prototype, r.global.FunctionPrototype, length)
}
func (r *Runtime) newNativeFuncConstructProto(construct func(args []Value, proto *Object) *Object, name string, prototype, proto *Object, length int) *Object {
v := &Object{runtime: r}
f := &nativeFuncObject{}
f.class = classFunction
f.val = v
f.extensible = true
v.self = f
f.prototype = proto
f.f = r.constructWrap(construct, prototype)
f.construct = func(args []Value) *Object {
return construct(args, prototype)
}
f.init(name, length)
if prototype != nil {
f._putProp("prototype", prototype, false, false, false)
prototype.self._putProp("constructor", v, true, false, true)
}
return v
}
func (r *Runtime) newPrimitiveObject(value Value, proto *Object, class string) *Object {
v := &Object{runtime: r}
o := &primitiveValueObject{}
o.class = class
o.val = v
o.extensible = true
v.self = o
o.prototype = proto
o.pValue = value
o.init()
return v
}
func (r *Runtime) builtin_Number(call FunctionCall) Value {
if len(call.Arguments) > 0 {
return call.Arguments[0].ToNumber()
} else {
return intToValue(0)
}
}
func (r *Runtime) builtin_newNumber(args []Value) *Object {
var v Value
if len(args) > 0 {
v = args[0].ToNumber()
} else {
v = intToValue(0)
}
return r.newPrimitiveObject(v, r.global.NumberPrototype, classNumber)
}
func (r *Runtime) builtin_Boolean(call FunctionCall) Value {
if len(call.Arguments) > 0 {
if call.Arguments[0].ToBoolean() {
return valueTrue
} else {
return valueFalse
}
} else {
return valueFalse
}
}
func (r *Runtime) builtin_newBoolean(args []Value) *Object {
var v Value
if len(args) > 0 {
if args[0].ToBoolean() {
v = valueTrue
} else {
v = valueFalse
}
} else {
v = valueFalse
}
return r.newPrimitiveObject(v, r.global.BooleanPrototype, classBoolean)
}
func (r *Runtime) error_toString(call FunctionCall) Value {
obj := call.This.ToObject(r).self
msg := obj.getStr("message")
name := obj.getStr("name")
var nameStr, msgStr string
if name != nil && name != _undefined {
nameStr = name.String()
}
if msg != nil && msg != _undefined {
msgStr = msg.String()
}
if nameStr != "" && msgStr != "" {
return newStringValue(fmt.Sprintf("%s: %s", name.String(), msgStr))
} else {
if nameStr != "" {
return name.ToString()
} else {
return msg.ToString()
}
}
}
func (r *Runtime) builtin_Error(args []Value, proto *Object) *Object {
obj := r.newBaseObject(proto, classError)
if len(args) > 0 && args[0] != _undefined {
obj._putProp("message", args[0], true, false, true)
}
return obj.val
}
func (r *Runtime) builtin_new(construct *Object, args []Value) *Object {
repeat:
switch f := construct.self.(type) {
case *nativeFuncObject:
if f.construct != nil {
return f.construct(args)
} else {
panic("Not a constructor")
}
case *boundFuncObject:
if f.construct != nil {
return f.construct(args)
} else {
panic("Not a constructor")
}
case *funcObject:
// TODO: implement
panic("Not implemented")
case *lazyObject:
construct.self = f.create(construct)
goto repeat
default:
panic("Not a constructor")
}
}
func (r *Runtime) throw(e Value) {
panic(e)
}
func (r *Runtime) builtin_thrower(call FunctionCall) Value {
r.typeErrorResult(true, "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them")
return nil
}
func (r *Runtime) eval(src string, direct, strict bool, this Value) Value {
p, err := r.compile("<eval>", src, strict, true)
if err != nil {
panic(err)
}
vm := r.vm
vm.pushCtx()
vm.prg = p
vm.pc = 0
if !direct {
vm.stash = nil
}
vm.sb = vm.sp
vm.push(this)
if strict {
vm.push(valueTrue)
} else {
vm.push(valueFalse)
}
vm.run()
vm.popCtx()
vm.halt = false
retval := vm.stack[vm.sp-1]
vm.sp -= 2
return retval
}
func (r *Runtime) builtin_eval(call FunctionCall) Value {
if len(call.Arguments) == 0 {
return _undefined
}
if str, ok := call.Arguments[0].assertString(); ok {
return r.eval(str.String(), false, false, r.globalObject)
}
return call.Arguments[0]
}
func (r *Runtime) constructWrap(construct func(args []Value, proto *Object) *Object, proto *Object) func(call FunctionCall) Value {
return func(call FunctionCall) Value {
return construct(call.Arguments, proto)
}
}
func (r *Runtime) toCallable(v Value) func(FunctionCall) Value {
if call, ok := r.toObject(v).self.assertCallable(); ok {
return call
}
r.typeErrorResult(true, "Value is not callable: %s", v.ToString())
return nil
}
func (r *Runtime) checkObjectCoercible(v Value) {
switch v.(type) {
case valueUndefined, valueNull:
r.typeErrorResult(true, "Value is not object coercible")
}
}
func toUInt32(v Value) uint32 {
v = v.ToNumber()
if i, ok := v.assertInt(); ok {
return uint32(i)
}
if f, ok := v.assertFloat(); ok {
if !math.IsNaN(f) && !math.IsInf(f, 0) {
return uint32(int64(f))
}
}
return 0
}
func toUInt16(v Value) uint16 {
v = v.ToNumber()
if i, ok := v.assertInt(); ok {
return uint16(i)
}
if f, ok := v.assertFloat(); ok {
if !math.IsNaN(f) && !math.IsInf(f, 0) {
return uint16(int64(f))
}
}
return 0
}
func toLength(v Value) int64 {
if v == nil {
return 0
}
i := v.ToInteger()
if i < 0 {
return 0
}
if i >= maxInt {
return maxInt - 1
}
return i
}
func toInt32(v Value) int32 {
v = v.ToNumber()
if i, ok := v.assertInt(); ok {
return int32(i)
}
if f, ok := v.assertFloat(); ok {
if !math.IsNaN(f) && !math.IsInf(f, 0) {
return int32(int64(f))
}
}
return 0
}
func (r *Runtime) toBoolean(b bool) Value {
if b {
return valueTrue
} else {
return valueFalse
}
}
// New creates an instance of a Javascript runtime that can be used to run code. Multiple instances may be created and
// used simultaneously, however it is not possible to pass JS values across runtimes.
func New() *Runtime {
r := &Runtime{}
r.init()
return r
}
// Compile creates an internal representation of the JavaScript code that can be later run using the Runtime.RunProgram()
// method. This representation is not linked to a runtime in any way and can be run in multiple runtimes (possibly
// at the same time).
func Compile(name, src string, strict bool) (*Program, error) {
return compile(name, src, strict, false)
}
// CompileAST creates an internal representation of the JavaScript code that can be later run using the Runtime.RunProgram()
// method. This representation is not linked to a runtime in any way and can be run in multiple runtimes (possibly
// at the same time).
func CompileAST(prg *js_ast.Program, strict bool) (*Program, error) {
return compileAST(prg, strict, false)
}
// MustCompile is like Compile but panics if the code cannot be compiled.
// It simplifies safe initialization of global variables holding compiled JavaScript code.
func MustCompile(name, src string, strict bool) *Program {
prg, err := Compile(name, src, strict)
if err != nil {
panic(err)
}
return prg
}
func compile(name, src string, strict, eval bool) (p *Program, err error) {
prg, err1 := parser.ParseFile(nil, name, src, 0)
if err1 != nil {
switch err1 := err1.(type) {
case parser.ErrorList:
if len(err1) > 0 && err1[0].Message == "Invalid left-hand side in assignment" {
err = &CompilerReferenceError{
CompilerError: CompilerError{
Message: err1.Error(),
},
}
return
}
}
// FIXME offset
err = &CompilerSyntaxError{
CompilerError: CompilerError{
Message: err1.Error(),
},
}
return
}
p, err = compileAST(prg, strict, eval)
return
}
func compileAST(prg *js_ast.Program, strict, eval bool) (p *Program, err error) {
c := newCompiler()
c.scope.strict = strict
c.scope.eval = eval
defer func() {
if x := recover(); x != nil {
p = nil
switch x1 := x.(type) {
case *CompilerSyntaxError:
err = x1
default:
panic(x)
}
}
}()
c.compile(prg)
p = c.p
return
}
func (r *Runtime) compile(name, src string, strict, eval bool) (p *Program, err error) {
p, err = compile(name, src, strict, eval)
if err != nil {
switch x1 := err.(type) {
case *CompilerSyntaxError:
err = &Exception{
val: r.builtin_new(r.global.SyntaxError, []Value{newStringValue(x1.Error())}),
}
case *CompilerReferenceError:
err = &Exception{
val: r.newError(r.global.ReferenceError, x1.Message),
} // TODO proper message
}
}
return
}
// RunString executes the given string in the global context.
func (r *Runtime) RunString(str string) (Value, error) {
return r.RunScript("", str)
}
// RunScript executes the given string in the global context.
func (r *Runtime) RunScript(name, src string) (Value, error) {
p, err := Compile(name, src, false)
if err != nil {
return nil, err
}
return r.RunProgram(p)
}
// RunProgram executes a pre-compiled (see Compile()) code in the global context.
func (r *Runtime) RunProgram(p *Program) (result Value, err error) {
defer func() {
if x := recover(); x != nil {
if intr, ok := x.(*InterruptedError); ok {
err = intr
} else {
panic(x)
}
}
}()
recursive := false
if len(r.vm.callStack) > 0 {
recursive = true
r.vm.pushCtx()
}
r.vm.prg = p
r.vm.pc = 0
ex := r.vm.runTry()
if ex == nil {
result = r.vm.pop()
} else {
err = ex
}
if recursive {
r.vm.popCtx()
r.vm.halt = false
r.vm.clearStack()
} else {
r.vm.stack = nil
}
return
}
// Interrupt a running JavaScript. The corresponding Go call will return an *InterruptedError containing v.
// Note, it only works while in JavaScript code, it does not interrupt native Go functions (which includes all built-ins).
func (r *Runtime) Interrupt(v interface{}) {
r.vm.Interrupt(v)
}
/*
ToValue converts a Go value into JavaScript value.
Primitive types (ints and uints, floats, string, bool) are converted to the corresponding JavaScript primitives.
func(FunctionCall) Value is treated as a native JavaScript function.
map[string]interface{} is converted into a host object that largely behaves like a JavaScript Object.
[]interface{} is converted into a host object that behaves largely like a JavaScript Array, however it's not extensible
because extending it can change the pointer so it becomes detached from the original.
*[]interface{} same as above, but the array becomes extensible.
A function is wrapped within a native JavaScript function. When called the arguments are automatically converted to
the appropriate Go types. If conversion is not possible, a TypeError is thrown.
A slice type is converted into a generic reflect based host object that behaves similar to an unexpandable Array.
Any other type is converted to a generic reflect based host object. Depending on the underlying type it behaves similar
to a Number, String, Boolean or Object.
Note that the underlying type is not lost, calling Export() returns the original Go value. This applies to all
reflect based types.
*/
func (r *Runtime) ToValue(i interface{}) Value {
switch i := i.(type) {
case nil:
return _null
case Value:
// TODO: prevent importing Objects from a different runtime
return i
case string:
return newStringValue(i)
case bool:
if i {
return valueTrue
} else {
return valueFalse
}
case func(FunctionCall) Value:
return r.newNativeFunc(i, nil, "", nil, 0)
case func(ConstructorCall) *Object:
return r.newNativeConstructor(i, "", 0)
case int:
return intToValue(int64(i))
case int8:
return intToValue(int64(i))
case int16:
return intToValue(int64(i))
case int32:
return intToValue(int64(i))
case int64:
return intToValue(i)
case uint:
if int64(i) <= math.MaxInt64 {
return intToValue(int64(i))
} else {
return floatToValue(float64(i))
}
case uint8:
return intToValue(int64(i))
case uint16:
return intToValue(int64(i))
case uint32:
return intToValue(int64(i))
case uint64:
if i <= math.MaxInt64 {
return intToValue(int64(i))
}
return floatToValue(float64(i))
case float32:
return floatToValue(float64(i))
case float64:
return floatToValue(i)
case map[string]interface{}:
obj := &Object{runtime: r}
m := &objectGoMapSimple{
baseObject: baseObject{
val: obj,
extensible: true,
},
data: i,
}
obj.self = m
m.init()
return obj
case []interface{}: