forked from dop251/goja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime.go
3141 lines (2782 loc) · 77.8 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"
"hash/maphash"
"math"
"math/bits"
"math/rand"
"reflect"
"runtime"
"strconv"
"time"
"golang.org/x/text/collate"
js_ast "github.com/dop251/goja/ast"
"github.com/dop251/goja/file"
"github.com/dop251/goja/parser"
"github.com/dop251/goja/unistring"
)
const (
sqrt1_2 float64 = math.Sqrt2 / 2
deoptimiseRegexp = false
)
var (
typeCallable = reflect.TypeOf(Callable(nil))
typeValue = reflect.TypeOf((*Value)(nil)).Elem()
typeObject = reflect.TypeOf((*Object)(nil))
typeTime = reflect.TypeOf(time.Time{})
typeBytes = reflect.TypeOf(([]byte)(nil))
)
type iterationKind int
const (
iterationKindKey iterationKind = iota
iterationKindValue
iterationKindKeyValue
)
type global struct {
stash stash
varNames map[unistring.String]struct{}
Object *Object
Array *Object
Function *Object
String *Object
Number *Object
Boolean *Object
RegExp *Object
Date *Object
Symbol *Object
Proxy *Object
Reflect *Object
Promise *Object
Math *Object
JSON *Object
AsyncFunction *Object
ArrayBuffer *Object
DataView *Object
TypedArray *Object
Uint8Array *Object
Uint8ClampedArray *Object
Int8Array *Object
Uint16Array *Object
Int16Array *Object
Uint32Array *Object
Int32Array *Object
Float32Array *Object
Float64Array *Object
WeakSet *Object
WeakMap *Object
Map *Object
Set *Object
Error *Object
AggregateError *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
SymbolPrototype *Object
ArrayBufferPrototype *Object
DataViewPrototype *Object
TypedArrayPrototype *Object
WeakSetPrototype *Object
WeakMapPrototype *Object
MapPrototype *Object
SetPrototype *Object
PromisePrototype *Object
GeneratorFunctionPrototype *Object
GeneratorFunction *Object
GeneratorPrototype *Object
AsyncFunctionPrototype *Object
IteratorPrototype *Object
ArrayIteratorPrototype *Object
MapIteratorPrototype *Object
SetIteratorPrototype *Object
StringIteratorPrototype *Object
RegExpStringIteratorPrototype *Object
ErrorPrototype *Object
Eval *Object
thrower *Object
stdRegexpProto *guardedObject
weakSetAdder *Object
weakMapAdder *Object
mapAdder *Object
setAdder *Object
arrayValues *Object
arrayToString *Object
stringproto_trimEnd *Object
stringproto_trimStart *Object
parseFloat, parseInt *Object
typedArrayValues *Object
}
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 Now func() time.Time
type Runtime struct {
global global
globalObject *Object
stringSingleton *stringObject
rand RandSource
now Now
_collator *collate.Collator
parserOptions []parser.Option
symbolRegistry map[unistring.String]*Symbol
fieldsInfoCache map[reflect.Type]*reflectFieldsInfo
methodsInfoCache map[reflect.Type]*reflectMethodsInfo
fieldNameMapper FieldNameMapper
vm *vm
hash *maphash.Hash
idSeq uint64
jobQueue []func()
promiseRejectionTracker PromiseRejectionTracker
asyncContextTracker AsyncContextTracker
}
type StackFrame struct {
prg *Program
funcName unistring.String
pc int
}
func (f *StackFrame) SrcName() string {
if f.prg == nil {
return "<native>"
}
return f.prg.src.Name()
}
func (f *StackFrame) FuncName() string {
if f.funcName == "" && f.prg == nil {
return "<native>"
}
if f.funcName == "" {
return "<anonymous>"
}
return f.funcName.String()
}
func (f *StackFrame) Position() file.Position {
if f.prg == nil || f.prg.src == nil {
return file.Position{}
}
return f.prg.src.Position(f.prg.sourceOffset(f.pc))
}
func (f *StackFrame) WriteToValueBuilder(b *StringBuilder) {
if f.prg != nil {
if n := f.prg.funcName; n != "" {
b.WriteString(stringValueFromRaw(n))
b.writeASCII(" (")
}
p := f.Position()
if p.Filename != "" {
b.WriteUTF8String(p.Filename)
} else {
b.writeASCII("<eval>")
}
b.WriteRune(':')
b.writeASCII(strconv.Itoa(p.Line))
b.WriteRune(':')
b.writeASCII(strconv.Itoa(p.Column))
b.WriteRune('(')
b.writeASCII(strconv.Itoa(f.pc))
b.WriteRune(')')
if f.prg.funcName != "" {
b.WriteRune(')')
}
} else {
if f.funcName != "" {
b.WriteString(stringValueFromRaw(f.funcName))
b.writeASCII(" (")
}
b.writeASCII("native")
if f.funcName != "" {
b.WriteRune(')')
}
}
}
func (f *StackFrame) Write(b *bytes.Buffer) {
if f.prg != nil {
if n := f.prg.funcName; n != "" {
b.WriteString(n.String())
b.WriteString(" (")
}
p := f.Position()
if p.Filename != "" {
b.WriteString(p.Filename)
} else {
b.WriteString("<eval>")
}
b.WriteByte(':')
b.WriteString(strconv.Itoa(p.Line))
b.WriteByte(':')
b.WriteString(strconv.Itoa(p.Column))
b.WriteByte('(')
b.WriteString(strconv.Itoa(f.pc))
b.WriteByte(')')
if f.prg.funcName != "" {
b.WriteByte(')')
}
} else {
if f.funcName != "" {
b.WriteString(f.funcName.String())
b.WriteString(" (")
}
b.WriteString("native")
if f.funcName != "" {
b.WriteByte(')')
}
}
}
// An un-catchable exception is not catchable by try/catch statements (finally is not executed either),
// but it is returned as an error to a Go caller rather than causing a panic.
type uncatchableException interface {
error
_uncatchableException()
}
type Exception struct {
val Value
stack []StackFrame
}
type baseUncatchableException struct {
Exception
}
func (e *baseUncatchableException) _uncatchableException() {}
type InterruptedError struct {
baseUncatchableException
iface interface{}
}
func (e *InterruptedError) Unwrap() error {
if err, ok := e.iface.(error); ok {
return err
}
return nil
}
type StackOverflowError struct {
baseUncatchableException
}
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 (e *Exception) Unwrap() error {
if obj, ok := e.val.(*Object); ok {
if obj.runtime.getGoError().self.hasInstance(obj) {
if val := obj.Get("value"); val != nil {
e1, _ := val.Export().(error)
return e1
}
}
}
return nil
}
func (r *Runtime) createIterProto(val *Object) objectImpl {
o := newBaseObjectObj(val, r.global.ObjectPrototype, classObject)
o._putSym(SymIterator, valueProp(r.newNativeFunc(r.returnThis, "[Symbol.iterator]", 0), true, false, true))
return o
}
func (r *Runtime) getIteratorPrototype() *Object {
var o *Object
if o = r.global.IteratorPrototype; o == nil {
o = &Object{runtime: r}
r.global.IteratorPrototype = o
o.self = r.createIterProto(o)
}
return o
}
func (r *Runtime) init() {
r.rand = rand.Float64
r.now = time.Now
r.global.ObjectPrototype = &Object{runtime: r}
r.newTemplatedObject(getObjectProtoTemplate(), r.global.ObjectPrototype)
r.globalObject = &Object{runtime: r}
r.newTemplatedObject(getGlobalObjectTemplate(), r.globalObject)
r.vm = &vm{
r: r,
}
r.vm.init()
}
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 {
var msg string
if len(args) > 0 {
msg = fmt.Sprintf(format, args...)
} else {
msg = format
}
return r.builtin_new(typ, []Value{newStringValue(msg)})
}
func (r *Runtime) throwReferenceError(name unistring.String) {
panic(r.newReferenceError(name))
}
func (r *Runtime) newReferenceError(name unistring.String) Value {
return r.newError(r.getReferenceError(), "%s is not defined", name)
}
func (r *Runtime) newSyntaxError(msg string, offset int) Value {
return r.builtin_new(r.getSyntaxError(), []Value{newStringValue(msg)})
}
func newBaseObjectObj(obj, proto *Object, class string) *baseObject {
o := &baseObject{
class: class,
val: obj,
extensible: true,
prototype: proto,
}
obj.self = o
o.init()
return o
}
func newGuardedObj(proto *Object, class string) *guardedObject {
return &guardedObject{
baseObject: baseObject{
class: class,
extensible: true,
prototype: proto,
},
}
}
func (r *Runtime) newBaseObject(proto *Object, class string) (o *baseObject) {
v := &Object{runtime: r}
return newBaseObjectObj(v, proto, class)
}
func (r *Runtime) newGuardedObject(proto *Object, class string) (o *guardedObject) {
v := &Object{runtime: r}
o = newGuardedObj(proto, class)
v.self = o
o.val = v
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) NewArray(items ...interface{}) *Object {
values := make([]Value, len(items))
for i, item := range items {
values[i] = r.ToValue(item)
}
return r.newArrayValues(values)
}
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.getTypeError(), []Value{newStringValue(msg)})
}
func (r *Runtime) NewGoError(err error) *Object {
e := r.newError(r.getGoError(), err.Error()).(*Object)
e.Set("value", err)
return e
}
func (r *Runtime) newFunc(name unistring.String, length int, strict bool) (f *funcObject) {
f = &funcObject{}
r.initBaseJsFunction(&f.baseJsFuncObject, strict)
f.val.self = f
f.init(name, intToValue(int64(length)))
return
}
func (r *Runtime) newAsyncFunc(name unistring.String, length int, strict bool) (f *asyncFuncObject) {
f = &asyncFuncObject{}
r.initBaseJsFunction(&f.baseJsFuncObject, strict)
f.class = classFunction
f.prototype = r.getAsyncFunctionPrototype()
f.val.self = f
f.init(name, intToValue(int64(length)))
return
}
func (r *Runtime) newGeneratorFunc(name unistring.String, length int, strict bool) (f *generatorFuncObject) {
f = &generatorFuncObject{}
r.initBaseJsFunction(&f.baseJsFuncObject, strict)
f.class = classFunction
f.prototype = r.getGeneratorFunctionPrototype()
f.val.self = f
f.init(name, intToValue(int64(length)))
f._putProp("prototype", r.newBaseObject(r.getGeneratorPrototype(), classObject).val, true, false, false)
return
}
func (r *Runtime) newClassFunc(name unistring.String, length int, proto *Object, derived bool) (f *classFuncObject) {
v := &Object{runtime: r}
f = &classFuncObject{}
f.class = classFunction
f.val = v
f.extensible = true
f.strict = true
f.derived = derived
v.self = f
f.prototype = proto
f.init(name, intToValue(int64(length)))
return
}
func (r *Runtime) initBaseJsFunction(f *baseJsFuncObject, strict bool) {
v := &Object{runtime: r}
f.class = classFunction
f.val = v
f.extensible = true
f.strict = strict
f.prototype = r.getFunctionPrototype()
}
func (r *Runtime) newMethod(name unistring.String, length int, strict bool) (f *methodFuncObject) {
f = &methodFuncObject{}
r.initBaseJsFunction(&f.baseJsFuncObject, strict)
f.val.self = f
f.init(name, intToValue(int64(length)))
return
}
func (r *Runtime) newGeneratorMethod(name unistring.String, length int, strict bool) (f *generatorMethodFuncObject) {
f = &generatorMethodFuncObject{}
r.initBaseJsFunction(&f.baseJsFuncObject, strict)
f.prototype = r.getGeneratorFunctionPrototype()
f.val.self = f
f.init(name, intToValue(int64(length)))
f._putProp("prototype", r.newBaseObject(r.getGeneratorPrototype(), classObject).val, true, false, false)
return
}
func (r *Runtime) newAsyncMethod(name unistring.String, length int, strict bool) (f *asyncMethodFuncObject) {
f = &asyncMethodFuncObject{}
r.initBaseJsFunction(&f.baseJsFuncObject, strict)
f.val.self = f
f.init(name, intToValue(int64(length)))
return
}
func (r *Runtime) initArrowFunc(f *arrowFuncObject, strict bool) {
r.initBaseJsFunction(&f.baseJsFuncObject, strict)
f.newTarget = r.vm.newTarget
}
func (r *Runtime) newArrowFunc(name unistring.String, length int, strict bool) (f *arrowFuncObject) {
f = &arrowFuncObject{}
r.initArrowFunc(f, strict)
f.val.self = f
f.init(name, intToValue(int64(length)))
return
}
func (r *Runtime) newAsyncArrowFunc(name unistring.String, length int, strict bool) (f *asyncArrowFuncObject) {
f = &asyncArrowFuncObject{}
r.initArrowFunc(&f.arrowFuncObject, strict)
f.class = classObject
f.prototype = r.getAsyncFunctionPrototype()
f.val.self = f
f.init(name, intToValue(int64(length)))
return
}
func (r *Runtime) newNativeConstructor(call func(ConstructorCall) *Object, name unistring.String, length int64) *Object {
v := &Object{runtime: r}
f := &nativeFuncObject{
baseFuncObject: baseFuncObject{
baseObject: baseObject{
class: classFunction,
val: v,
extensible: true,
prototype: r.getFunctionPrototype(),
},
},
}
f.f = func(c FunctionCall) Value {
thisObj, _ := c.This.(*Object)
if thisObj != nil {
res := call(ConstructorCall{
This: thisObj,
Arguments: c.Arguments,
})
if res == nil {
return _undefined
}
return res
}
return f.defaultConstruct(call, c.Arguments, nil)
}
f.construct = func(args []Value, newTarget *Object) *Object {
return f.defaultConstruct(call, args, newTarget)
}
v.self = f
f.init(name, intToValue(length))
proto := r.NewObject()
proto.self._putProp("constructor", v, true, false, true)
f._putProp("prototype", proto, true, false, false)
return v
}
func (r *Runtime) newNativeConstructOnly(v *Object, ctor func(args []Value, newTarget *Object) *Object, defaultProto *Object, name unistring.String, length int64) *nativeFuncObject {
return r.newNativeFuncAndConstruct(v, func(call FunctionCall) Value {
return ctor(call.Arguments, nil)
},
func(args []Value, newTarget *Object) *Object {
if newTarget == nil {
newTarget = v
}
return ctor(args, newTarget)
}, defaultProto, name, intToValue(length))
}
func (r *Runtime) newNativeFuncAndConstruct(v *Object, call func(call FunctionCall) Value, ctor func(args []Value, newTarget *Object) *Object, defaultProto *Object, name unistring.String, l Value) *nativeFuncObject {
if v == nil {
v = &Object{runtime: r}
}
f := &nativeFuncObject{
baseFuncObject: baseFuncObject{
baseObject: baseObject{
class: classFunction,
val: v,
extensible: true,
prototype: r.getFunctionPrototype(),
},
},
f: call,
construct: ctor,
}
v.self = f
f.init(name, l)
if defaultProto != nil {
f._putProp("prototype", defaultProto, false, false, false)
}
return f
}
func (r *Runtime) newNativeFunc(call func(FunctionCall) Value, name unistring.String, length int) *Object {
v := &Object{runtime: r}
f := &nativeFuncObject{
baseFuncObject: baseFuncObject{
baseObject: baseObject{
class: classFunction,
val: v,
extensible: true,
prototype: r.getFunctionPrototype(),
},
},
f: call,
}
v.self = f
f.init(name, intToValue(int64(length)))
return v
}
func (r *Runtime) newWrappedFunc(value reflect.Value) *Object {
v := &Object{runtime: r}
f := &wrappedFuncObject{
nativeFuncObject: nativeFuncObject{
baseFuncObject: baseFuncObject{
baseObject: baseObject{
class: classFunction,
val: v,
extensible: true,
prototype: r.getFunctionPrototype(),
},
},
f: r.wrapReflectFunc(value),
},
wrapped: value,
}
v.self = f
name := unistring.NewFromString(runtime.FuncForPC(value.Pointer()).Name())
f.init(name, intToValue(int64(value.Type().NumIn())))
return v
}
func (r *Runtime) newNativeFuncConstructObj(v *Object, construct func(args []Value, proto *Object) *Object, name unistring.String, proto *Object, length int) *nativeFuncObject {
f := &nativeFuncObject{
baseFuncObject: baseFuncObject{
baseObject: baseObject{
class: classFunction,
val: v,
extensible: true,
prototype: r.getFunctionPrototype(),
},
},
f: r.constructToCall(construct, proto),
construct: r.wrapNativeConstruct(construct, v, proto),
}
f.init(name, intToValue(int64(length)))
if proto != nil {
f._putProp("prototype", proto, false, false, false)
}
return f
}
func (r *Runtime) newNativeFuncConstruct(v *Object, construct func(args []Value, proto *Object) *Object, name unistring.String, prototype *Object, length int64) *Object {
return r.newNativeFuncConstructProto(v, construct, name, prototype, r.getFunctionPrototype(), length)
}
func (r *Runtime) newNativeFuncConstructProto(v *Object, construct func(args []Value, proto *Object) *Object, name unistring.String, prototype, proto *Object, length int64) *Object {
f := &nativeFuncObject{}
f.class = classFunction
f.val = v
f.extensible = true
v.self = f
f.prototype = proto
f.f = r.constructToCall(construct, prototype)
f.construct = r.wrapNativeConstruct(construct, v, prototype)
f.init(name, intToValue(length))
if prototype != nil {
f._putProp("prototype", prototype, false, false, false)
}
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 valueInt(0)
}
}
func (r *Runtime) builtin_newNumber(args []Value, proto *Object) *Object {
var v Value
if len(args) > 0 {
v = args[0].ToNumber()
} else {
v = intToValue(0)
}
return r.newPrimitiveObject(v, proto, 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, proto *Object) *Object {
var v Value
if len(args) > 0 {
if args[0].ToBoolean() {
v = valueTrue
} else {
v = valueFalse
}
} else {
v = valueFalse
}
return r.newPrimitiveObject(v, proto, classBoolean)
}
func (r *Runtime) builtin_new(construct *Object, args []Value) *Object {
return r.toConstructor(construct)(args, construct)
}
func (r *Runtime) builtin_thrower(call FunctionCall) Value {
obj := r.toObject(call.This)
strict := true
switch fn := obj.self.(type) {
case *funcObject:
strict = fn.strict
}
r.typeErrorResult(strict, "'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(srcVal String, direct, strict bool) Value {
src := escapeInvalidUtf16(srcVal)
vm := r.vm
inGlobal := true
if direct {
for s := vm.stash; s != nil; s = s.outer {
if s.isVariable() {
inGlobal = false
break
}
}
}
vm.pushCtx()
funcObj := _undefined
if !direct {
vm.stash = &r.global.stash
vm.privEnv = nil
} else {
if sb := vm.sb; sb > 0 {
funcObj = vm.stack[sb-1]
}
}
p, err := r.compile("<eval>", src, strict, inGlobal, r.vm)
if err != nil {
panic(err)
}
vm.prg = p
vm.pc = 0
vm.args = 0
vm.result = _undefined
vm.push(funcObj)
vm.sb = vm.sp
vm.push(nil) // this
ex := vm.runTry()
retval := vm.result
vm.popCtx()
if ex != nil {
panic(ex)
}
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].(String); ok {
return r.eval(str, false, false)
}
return call.Arguments[0]
}
func (r *Runtime) constructToCall(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) wrapNativeConstruct(c func(args []Value, proto *Object) *Object, ctorObj, defProto *Object) func(args []Value, newTarget *Object) *Object {
if c == nil {
return nil
}
return func(args []Value, newTarget *Object) *Object {
var proto *Object
if newTarget != nil {
proto = r.getPrototypeFromCtor(newTarget, ctorObj, defProto)
} else {
proto = defProto
}
return c(args, 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 toInt8(v Value) int8 {
v = v.ToNumber()
if i, ok := v.(valueInt); ok {
return int8(i)
}
if f, ok := v.(valueFloat); ok {
f := float64(f)
if !math.IsNaN(f) && !math.IsInf(f, 0) {
return int8(int64(f))
}
}
return 0
}
func toUint8(v Value) uint8 {
v = v.ToNumber()
if i, ok := v.(valueInt); ok {
return uint8(i)
}
if f, ok := v.(valueFloat); ok {
f := float64(f)
if !math.IsNaN(f) && !math.IsInf(f, 0) {
return uint8(int64(f))
}
}