forked from robertkrimen/otto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuiltin.go
1302 lines (1141 loc) · 34 KB
/
builtin.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 otto
import (
"strings"
"fmt"
"strconv"
"math"
"bytes"
"regexp"
"math/rand"
time_ "time"
"net/url"
)
// Global
func builtinGlobal_eval(call FunctionCall) Value {
source := call.Argument(0)
if !source.IsString() {
return source
}
program, err := parse(toString(source))
if err != nil {
//panic(call.runtime.newError("SyntaxError", UndefinedValue()))
panic(&_syntaxError{Message: fmt.Sprintf("%v", err)})
}
runtime := call.runtime
runtime.EnterEvalExecutionContext(call)
defer runtime.LeaveExecutionContext()
returnValue := runtime.evaluate(program)
if returnValue.isEmpty() {
return UndefinedValue()
}
return returnValue
}
func builtinGlobal_isNaN(call FunctionCall) Value {
value := toFloat(call.Argument(0))
return toValue(math.IsNaN(value))
}
func builtinGlobal_isFinite(call FunctionCall) Value {
value := toFloat(call.Argument(0))
return toValue(!math.IsNaN(value) && !math.IsInf(value, 0))
}
func builtinGlobal_parseInt(call FunctionCall) Value {
// Caveat emptor: This implementation does NOT match the specification
string_ := strings.TrimSpace(toString(call.Argument(0)))
radix := call.Argument(1)
radixValue := 0
if radix.IsDefined() {
radixValue = int(toInteger(radix))
}
value, err := strconv.ParseInt(string_, radixValue, 64)
if err != nil {
return NaNValue()
}
return toValue(value)
}
func builtinGlobal_parseFloat(call FunctionCall) Value {
// Caveat emptor: This implementation does NOT match the specification
string_ := strings.TrimSpace(toString(call.Argument(0)))
value, err := strconv.ParseFloat(string_, 64)
if err != nil {
return NaNValue()
}
return toValue(value)
}
func _builtinGlobal_encodeURI(call FunctionCall, characterRegexp *regexp.Regexp) Value {
value := []byte(toString(call.Argument(0)))
value = characterRegexp.ReplaceAllFunc(value, func(target []byte) []byte {
// Probably a better way of doing this
if target[0] == ' ' {
return []byte("%20")
}
return []byte(url.QueryEscape(string(target)))
})
return toValue(string(value))
}
var encodeURI_Regexp *regexp.Regexp = regexp.MustCompile(`([^~!@#$&*()=:/,;?+'])`)
func builtinGlobal_encodeURI(call FunctionCall) Value {
return _builtinGlobal_encodeURI(call, encodeURI_Regexp)
}
var encodeURIComponent_Regexp *regexp.Regexp = regexp.MustCompile(`([^~!*()'])`)
func builtinGlobal_encodeURIComponent(call FunctionCall) Value {
return _builtinGlobal_encodeURI(call, encodeURIComponent_Regexp)
}
func builtinGlobal_decodeURI_decodeURIComponent(call FunctionCall) Value {
value, err := url.QueryUnescape(toString(call.Argument(0)))
if err != nil {
panic(newURIError("URI malformed"))
}
return toValue(value)
}
// Object
func builtinObject(call FunctionCall) Value {
value := call.Argument(0)
switch value._valueType {
case valueUndefined, valueNull:
return toValue(call.runtime.newObject())
}
return toValue(call.runtime.toObject(value))
}
func builtinNewObject(self *_object, _ Value, _ []Value) Value {
return toValue(self.runtime.newObject())
}
func builtinObject_toString(call FunctionCall) Value {
result := ""
if call.This.IsUndefined() {
result = "[object Undefined]"
} else if call.This.IsNull() {
result = "[object Null]"
} else {
result = fmt.Sprintf("[object %s]", call.thisObject().Class)
}
return toValue(result)
}
// Function
func builtinFunction(call FunctionCall) Value {
return toValue(builtinNewFunctionNative(call.runtime, call.ArgumentList))
}
func builtinNewFunction(self *_object, _ Value, argumentList []Value) Value {
return toValue(builtinNewFunctionNative(self.runtime, argumentList))
}
func builtinNewFunctionNative(runtime *_runtime, argumentList []Value) *_object {
parameterList := []string{}
bodySource := ""
argumentCount := len(argumentList)
if argumentCount > 0 {
bodySource = toString(argumentList[argumentCount-1])
argumentList = argumentList[0:argumentCount-1]
for _, value := range argumentList {
parameterList = append(parameterList, toString(value))
}
}
parser := newParser()
parser.lexer.Source = bodySource
_programNode := parser.ParseAsFunction()
return runtime.newNodeFunction(_programNode.toFunction(parameterList), runtime.GlobalEnvironment)
}
func builtinFunction_apply(call FunctionCall) Value {
if !call.This.isCallable() {
panic(newTypeError())
}
this := call.Argument(0)
if this.IsUndefined() {
// FIXME Not ECMA5
this = toValue(call.runtime.GlobalObject)
}
argumentList := call.Argument(1)
switch argumentList._valueType {
case valueUndefined, valueNull:
return call.thisObject().Call(this, []Value{})
case valueObject:
default:
panic(newTypeError())
}
arrayObject := argumentList._object()
thisObject := call.thisObject()
length := uint(toUI32(arrayObject.Get("length")))
valueArray := make([]Value, length)
for index := uint(0); index < length; index++ {
valueArray[index] = arrayObject.Get(arrayIndexToString(index))
}
return thisObject.Call(this, valueArray)
}
func builtinFunction_call(call FunctionCall) Value {
if !call.This.isCallable() {
panic(newTypeError())
}
thisObject := call.thisObject()
this := call.Argument(0)
if this.IsUndefined() {
// FIXME Not ECMA5
this = toValue(call.runtime.GlobalObject)
}
if len(call.ArgumentList) >= 1 {
return thisObject.Call(this, call.ArgumentList[1:])
}
return thisObject.Call(this, []Value{})
}
// Boolean
func builtinBoolean(call FunctionCall) Value {
return toValue(toBoolean(call.Argument(0)))
}
func builtinNewBoolean(self *_object, _ Value, argumentList []Value) Value {
return toValue(self.runtime.newBoolean(valueOfArrayIndex(argumentList, 0)))
}
// String
func stringValueFromStringArgumentList(argumentList []Value) Value {
if len(argumentList) > 0 {
return toValue(toString(argumentList[0]))
}
return toValue("")
}
func builtinString(call FunctionCall) Value {
return stringValueFromStringArgumentList(call.ArgumentList)
}
func builtinNewString(self *_object, _ Value, argumentList []Value) Value {
return toValue(self.runtime.newString(stringValueFromStringArgumentList(argumentList)))
}
func builtinString_charAt(call FunctionCall) Value {
checkObjectCoercible(call.This)
value := toString(call.This)
index := toInteger(call.Argument(0))
if 0 > index || index >= int64(len(value)) {
return toValue("")
}
return toValue(string(value[index]))
}
func builtinString_charCodeAt(call FunctionCall) Value {
checkObjectCoercible(call.This)
value := toString(call.This)
index := toInteger(call.Argument(0))
if 0 > index || index >= int64(len(value)) {
return NaNValue()
}
return toValue(value[index])
}
func builtinString_concat(call FunctionCall) Value {
checkObjectCoercible(call.This)
var value bytes.Buffer
value.WriteString(toString(call.This))
for _, item := range call.ArgumentList {
value.WriteString(toString(item))
}
return toValue(value.String())
}
func builtinString_indexOf(call FunctionCall) Value {
checkObjectCoercible(call.This)
value := toString(call.This)
target := toString(call.Argument(0))
if 2 > len(call.ArgumentList) {
return toValue(strings.Index(value, target))
}
start := toInteger(call.Argument(1))
if 0 > start {
start = 0
} else if start >= int64(len(value)) {
if target == "" {
return toValue(len(value))
}
return toValue(-1)
}
return toValue(strings.Index(value[start:], target))
}
func builtinString_lastIndexOf(call FunctionCall) Value {
checkObjectCoercible(call.This)
value := toString(call.This)
target := toString(call.Argument(0))
if 2 > len(call.ArgumentList) || call.ArgumentList[1].IsUndefined() {
return toValue(strings.LastIndex(value, target))
}
length := len(value)
if length == 0 {
return toValue(strings.LastIndex(value, target))
}
startNumber := toFloat(call.ArgumentList[1])
start := int64(0)
if math.IsNaN(startNumber) || math.IsInf(startNumber, 0) {
// startNumber is infinity, so start is the end of string (start = length)
return toValue(strings.LastIndex(value, target))
} else {
start = toInteger(call.ArgumentList[1])
}
if 0 > start {
start = 0
} else if start >= int64(length) {
return toValue(strings.LastIndex(value, target))
}
return toValue(strings.LastIndex(value[:start], target))
}
func builtinString_match(call FunctionCall) Value {
checkObjectCoercible(call.This)
target := toString(call.This)
matcherValue := call.Argument(0)
matcher := matcherValue._object()
if !matcherValue.IsObject() || matcher.Class != "RegExp" {
matcher = call.runtime.newRegExp(matcherValue, UndefinedValue())
}
global := toBoolean(matcher.Get("global"))
if !global {
match, result := execRegExp(matcher, target)
if !match {
return NullValue()
}
return toValue(execResultToArray(call.runtime, target, result))
}
{
result := matcher.RegExp.RegularExpression.FindAllStringIndex(target, -1)
matchCount := len(result)
if result == nil {
matcher.WriteValue("lastIndex", toValue(0), true)
return UndefinedValue() // !match
}
matchCount = len(result)
valueArray := make([]Value, matchCount)
for index := 0; index < matchCount; index++ {
valueArray[index] = toValue(target[result[index][0]:result[index][1]])
}
matcher.WriteValue("lastIndex", toValue(result[matchCount-1][1]), true)
return toValue(call.runtime.newArray(valueArray))
}
}
var builtinString_replace_Regexp *regexp.Regexp = regexp.MustCompile("\\$(?:[\\$\\&\\'\\`1-9]|0[1-9]|[1-9][0-9])")
func builtinString_findAndReplaceString(input []byte, lastIndex int, match []int, target []byte, replaceValue []byte) (output []byte) {
matchCount := len(match) / 2
output = input
if match[0] != lastIndex {
output = append(output, target[lastIndex:match[0]]...)
}
replacement := builtinString_replace_Regexp.ReplaceAllFunc(replaceValue, func(part []byte) []byte{
// TODO Check if match[0] or match[1] can be -1 in this scenario
switch part[1] {
case '$':
return []byte{'$'}
case '&':
return target[match[0]:match[1]]
case '`':
return target[:match[0]]
case '\'':
return target[match[1]:len(target)-1]
}
matchNumberParse, error := strconv.ParseInt(string(part[1:]), 10, 64)
matchNumber := int(matchNumberParse)
if error != nil || matchNumber >= matchCount {
return []byte{}
}
offset := 2 * matchNumber
if match[offset] != -1 {
return target[match[offset]:match[offset+1]]
}
return []byte{} // The empty string
})
output = append(output, replacement...)
return output
}
func builtinString_replace(call FunctionCall) Value {
checkObjectCoercible(call.This)
target := []byte(toString(call.This))
searchValue := call.Argument(0)
searchObject := searchValue._object()
// TODO If a capture is -1?
var search *regexp.Regexp
global := false
find := 1
if searchValue.IsObject() && searchObject.Class == "RegExp" {
search = searchObject.RegExp.RegularExpression
global = toBoolean(searchObject.Get("global"))
if global {
find = -1
}
} else {
search = regexp.MustCompile(regexp.QuoteMeta(toString(searchValue)))
}
found := search.FindAllSubmatchIndex(target, find)
if found == nil {
return toValue(string(target)) // !match
}
{
lastIndex := 0
result := []byte{}
replaceValue := call.Argument(1)
if replaceValue.isCallable() {
target := string(target)
replace := replaceValue._object()
for _, match := range found {
if match[0] != lastIndex {
result = append(result, target[lastIndex:match[0]]...)
}
matchCount := len(match) / 2
argumentList := make([]Value, matchCount + 2)
for index := 0; index < matchCount; index++ {
offset := 2 * index
if match[offset] != -1 {
argumentList[index] = toValue(target[match[offset]:match[offset+1]])
} else {
argumentList[index] = UndefinedValue()
}
}
argumentList[matchCount + 0] = toValue(match[0])
argumentList[matchCount + 1] = toValue(target)
replacement := toString(replace.Call(UndefinedValue(), argumentList))
result = append(result, []byte(replacement)...)
lastIndex = match[1]
}
} else {
replace := []byte(toString(replaceValue))
for _, match := range found {
result = builtinString_findAndReplaceString(result, lastIndex, match, target, replace)
lastIndex = match[1]
}
}
if lastIndex != len(target) {
result = append(result, target[lastIndex:]...)
}
if global && searchObject != nil {
searchObject.Put("lastIndex", toValue(lastIndex), true)
}
return toValue(string(result))
}
return UndefinedValue()
}
func builtinString_search(call FunctionCall) Value {
checkObjectCoercible(call.This)
target := toString(call.This)
searchValue := call.Argument(0)
search := searchValue._object()
if !searchValue.IsObject() || search.Class != "RegExp" {
search = call.runtime.newRegExp(searchValue, UndefinedValue())
}
result := search.RegExp.RegularExpression.FindStringIndex(target)
if result == nil {
return toValue(-1)
}
return toValue(result[0])
}
func stringSplitMatch(target string, targetLength int64, index uint, search string, searchLength int64) (bool, uint) {
if int64(index) + searchLength > searchLength {
return false, 0
}
found := strings.Index(target[index:], search)
if 0 > found {
return false, 0
}
return true, uint(found)
}
func builtinString_split(call FunctionCall) Value {
checkObjectCoercible(call.This)
target := toString(call.This)
separatorValue := call.Argument(0)
limitValue := call.Argument(1)
limit := -1
if limitValue.IsDefined() {
limit = int(toUI32(limitValue))
}
if limit == 0 {
return toValue(call.runtime.newArray([]Value{}))
}
if separatorValue.IsUndefined() {
return toValue(call.runtime.newArray([]Value{toValue(target)}))
}
if separatorValue.isRegExp() {
targetLength := len(target)
search := separatorValue._object().RegExp.RegularExpression
valueArray := []Value{}
result := search.FindAllStringSubmatchIndex(target, -1)
lastIndex := 0
found := 0
for _, match := range result {
if match[0] == match[1] {
// An "empty" match
continue
}
if lastIndex != match[0] {
valueArray = append(valueArray, toValue(target[lastIndex:match[0]]))
found++
} else if lastIndex == match[0] {
if lastIndex != -1 {
valueArray = append(valueArray, toValue(""))
found++
}
}
lastIndex = match[1]
if found == limit {
goto RETURN
}
captureCount := len(match) / 2
for index := 1; index < captureCount; index++ {
offset := index * 2
value := UndefinedValue()
if match[offset] != -1 {
value = toValue(target[match[offset]:match[offset+1]])
}
valueArray = append(valueArray, value)
found++
if found == limit {
goto RETURN
}
}
}
if found != limit {
if lastIndex != targetLength {
valueArray = append(valueArray, toValue(target[lastIndex:targetLength]))
} else {
valueArray = append(valueArray, toValue(""))
}
}
RETURN:
return toValue(call.runtime.newArray(valueArray))
} else {
separator := toString(separatorValue)
splitLimit := limit
excess := false
if limit > 0 {
splitLimit = limit + 1
excess = true
}
split := strings.SplitN(target, separator, splitLimit)
if excess && len(split) > limit {
split = split[:limit]
}
valueArray := make([]Value, len(split))
for index, value := range split {
valueArray[index] = toValue(value)
}
return toValue(call.runtime.newArray(valueArray))
}
return UndefinedValue()
}
func builtinString_slice(call FunctionCall) Value {
checkObjectCoercible(call.This)
target := toString(call.This)
length := uint(len(target))
start, end := sliceStartEnd(call.ArgumentList, length)
if 0 >= end - start {
return toValue("")
}
return toValue(target[start:end])
}
func builtinString_substring(call FunctionCall) Value {
checkObjectCoercible(call.This)
target := toString(call.This)
length := uint(len(target))
start := valueToArrayIndex(call.Argument(0), length, false)
end := valueToArrayIndex(call.Argument(1), length, false)
if start > end {
start, end = end, start
}
return toValue(target[start:end])
}
func builtinString_toLowerCase(call FunctionCall) Value {
checkObjectCoercible(call.This)
return toValue(strings.ToLower(toString(call.This)))
}
func builtinString_toUpperCase(call FunctionCall) Value {
checkObjectCoercible(call.This)
return toValue(strings.ToUpper(toString(call.This)))
}
// Number
func numberValueFromNumberArgumentList(argumentList []Value) Value {
if len(argumentList) > 0 {
return toValue(toNumber(argumentList[0]))
}
return toValue(0)
}
func builtinNumber(call FunctionCall) Value {
return numberValueFromNumberArgumentList(call.ArgumentList)
}
func builtinNewNumber(self *_object, _ Value, argumentList []Value) Value {
return toValue(self.runtime.newNumber(numberValueFromNumberArgumentList(argumentList)))
}
// Array
func builtinArray(call FunctionCall) Value {
return toValue(builtinNewArrayNative(call.runtime, call.ArgumentList))
}
func builtinNewArray(self *_object, _ Value, argumentList []Value) Value {
return toValue(builtinNewArrayNative(self.runtime, argumentList))
}
func builtinNewArrayNative(runtime *_runtime, argumentList []Value) *_object {
valueArray := argumentList
if len(argumentList) == 1 {
value := argumentList[0]
if value.IsNumber() {
numberValue := uint(toUI32(value))
if float64(numberValue) == toFloat(value) {
valueArray = make([]Value, numberValue)
} else {
panic(newRangeError())
}
}
}
return runtime.newArray(valueArray)
}
func builtinArray_concat(call FunctionCall) Value {
thisObject := call.thisObject()
valueArray := []Value{}
itemList := append([]Value{toValue(thisObject)}, call.ArgumentList...)
for len(itemList) > 0 {
item := itemList[0]
itemList = itemList[1:]
switch item._valueType {
case valueObject:
value := item._object()
if value.Class == "Array" {
itemValueArray := value._propertyStash.(*_arrayStash).valueArray
for _, item := range itemValueArray {
if item._valueType == valueEmpty {
continue
}
valueArray = append(valueArray, item)
}
continue
}
fallthrough
default:
valueArray = append(valueArray, item)
}
}
return toValue(call.runtime.newArray(valueArray))
}
func builtinArray_shift(call FunctionCall) Value {
thisObject := call.thisObject()
length := uint(toUI32(thisObject.Get("length")))
if 0 == length {
thisObject.Put("length", toValue(length), true)
return UndefinedValue()
}
first := thisObject.Get("0")
for index := uint(1); index < length; index++ {
from := arrayIndexToString(index)
to := arrayIndexToString(index - 1)
if thisObject.HasProperty(from) {
thisObject.Put(to, thisObject.Get(from), true)
} else {
thisObject.Delete(to, true)
}
}
thisObject.Delete(arrayIndexToString(length - 1), true)
thisObject.Put("length", toValue(length - 1), true)
return first
}
func builtinArray_push(call FunctionCall) Value {
thisObject := call.thisObject()
itemList := call.ArgumentList
index := uint(toUI32(thisObject.Get("length")))
for len(itemList) > 0 {
thisObject.Put(arrayIndexToString(index), itemList[0], true)
itemList = itemList[1:]
index += 1
}
length := toValue(index)
thisObject.Put("length", length, true)
return length
}
func builtinArray_pop(call FunctionCall) Value {
thisObject := call.thisObject()
length := uint(toUI32(thisObject.Get("length")))
if 0 == length {
thisObject.Put("length", toValue(length), true)
return UndefinedValue()
}
last := thisObject.Get(arrayIndexToString(length - 1))
thisObject.Delete(arrayIndexToString(length - 1), true)
thisObject.Put("length", toValue(length - 1), true)
return last
}
func builtinArray_join(call FunctionCall) Value {
separator := ","
{
argument := call.Argument(0)
if argument.IsDefined() {
separator = toString(argument)
}
}
thisObject := call.thisObject()
if stash, isArray := thisObject._propertyStash.(*_arrayStash); isArray {
return toValue(builtinArray_joinNative(stash.valueArray, separator))
}
// Generic .join
length := uint(toUI32(thisObject.Get("length")))
if length == 0 {
return toValue("")
}
stringList := make([]string, 0, length)
for index := uint(0); index < length; index += 1 {
value := thisObject.Get(arrayIndexToString(index))
stringValue := ""
switch value._valueType {
case valueEmpty, valueUndefined, valueNull:
default:
stringValue = toString(value)
}
stringList = append(stringList, stringValue)
}
return toValue(strings.Join(stringList, ","))
}
func builtinArray_joinNative(valueArray []Value, separator string) string {
length := len(valueArray)
if length == 0 {
return ""
}
stringList := make([]string, 0, length)
for index := 0; index < length; index++ {
value := valueArray[index]
stringValue := ""
switch value._valueType {
case valueEmpty, valueUndefined, valueNull:
default:
stringValue = toString(value)
}
stringList = append(stringList, stringValue)
}
return strings.Join(stringList, separator)
}
func sliceStartEnd(source []Value, length uint) (start, end uint) {
start = valueToArrayIndex(valueOfArrayIndex(source, 0), length, true)
if len(source) == 1 {
end = length
return
}
end = length
endValue := valueOfArrayIndex(source, 1)
if !endValue.IsUndefined() {
end = valueToArrayIndex(endValue, length, true)
}
return
}
func builtinArray_splice(call FunctionCall) Value {
thisObject := call.thisObject()
length := uint(toUI32(thisObject.Get("length")))
start := valueToArrayIndex(call.Argument(0), length, true)
deleteCount := valueToArrayIndex(call.Argument(1), length - start, false)
valueArray := make([]Value, deleteCount)
for index := uint(0); index < deleteCount; index++ {
indexString := arrayIndexToString(start + index)
if thisObject.HasProperty(indexString) {
valueArray[index] = thisObject.Get(indexString)
}
}
// 0, <1, 2, 3, 4>, 5, 6, 7
// a, b
// length 8 - delete 4 @ start 1
itemList := []Value{}
itemCount := uint(len(call.ArgumentList))
if itemCount > 2 {
itemCount -= 2 // Less the first two arguments
itemList = call.ArgumentList[2:]
} else {
itemCount = 0
}
if itemCount < deleteCount {
// The Object/Array is shrinking
stop := length - deleteCount // The new length of the Object/Array before
// appending the itemList remainder
// Stopping at the lower bound of the insertion:
// Move an item from the after the deleted portion
// to a position after the inserted portion
for index := start; index < stop; index++ {
from := arrayIndexToString(index + deleteCount) // Position just after deletion
to := arrayIndexToString(index + itemCount) // Position just after splice (insertion)
if thisObject.HasProperty(from) {
thisObject.Put(to, thisObject.Get(from), true)
} else {
thisObject.Delete(to, true)
}
}
// Delete off the end
// We don't bother to delete below <stop + itemCount> (if any) since those
// will be overwritten anyway
for index := length; index > (stop + itemCount); index-- {
thisObject.Delete(arrayIndexToString(index - 1), true)
}
} else if itemCount > deleteCount {
// The Object/Array is growing
// The itemCount is greater than the deleteCount, so we do
// not have to worry about overwriting what we should be moving
// ---
// Starting from the upper bound of the deletion:
// Move an item from the after the deleted portion
// to a position after the inserted portion
for index := length - deleteCount; index > start; index-- {
from := arrayIndexToString(index + deleteCount - 1)
to := arrayIndexToString(index + itemCount - 1)
if thisObject.HasProperty(from) {
thisObject.Put(to, thisObject.Get(from), true)
} else {
thisObject.Delete(to, true)
}
}
}
for index := uint(0); index < itemCount; index++ {
thisObject.Put(arrayIndexToString(index + start), itemList[index], true)
}
thisObject.Put("length", toValue(length + itemCount - deleteCount), true)
return toValue(call.runtime.newArray(valueArray))
}
func builtinArray_slice(call FunctionCall) Value {
thisObject := call.thisObject()
length := uint(toUI32(thisObject.Get("length")))
start, end := sliceStartEnd(call.ArgumentList, length)
if start >= end {
// Always an empty array
return toValue(call.runtime.newArray([]Value{}))
}
sliceLength := end - start
sliceValueArray := make([]Value, sliceLength)
// Native slicing if a "real" array
if _arrayStash, ok := thisObject._propertyStash.(*_arrayStash); ok {
copy(sliceValueArray, _arrayStash.valueArray[start:start+sliceLength])
} else {
for index := uint(0); index < sliceLength; index++ {
from := arrayIndexToString(index + start)
if thisObject.HasProperty(from) {
sliceValueArray[index] = thisObject.Get(from)
}
}
}
return toValue(call.runtime.newArray(sliceValueArray))
}
func builtinArray_unshift(call FunctionCall) Value {
thisObject := call.thisObject()
length := uint(toUI32(thisObject.Get("length")))
itemList := call.ArgumentList
itemCount := uint(len(itemList))
for index := length; index > 0; index-- {
from := arrayIndexToString(index - 1)
to := arrayIndexToString(index + itemCount - 1)
if thisObject.HasProperty(from) {
thisObject.Put(to, thisObject.Get(from), true)
} else {
thisObject.Delete(to, true)
}
}
for index := uint(0); index < itemCount; index++ {
thisObject.Put(arrayIndexToString(index), itemList[index], true)
}
newLength := toValue(length + itemCount)
thisObject.Put("length", newLength, true)
return newLength
}
func builtinArray_reverse(call FunctionCall) Value {
thisObject := call.thisObject()
length := uint(toUI32(thisObject.Get("length")))
lower := struct {
name string
index uint
exists bool
}{}
upper := lower
lower.index = 0
middle := length / 2 // Division will floor
for lower.index != middle {
lower.name = arrayIndexToString(lower.index)
upper.index = length - lower.index - 1
upper.name = arrayIndexToString(upper.index)
lower.exists = thisObject.HasProperty(lower.name)
upper.exists = thisObject.HasProperty(upper.name)
if lower.exists && upper.exists {
lowerValue := thisObject.Get(lower.name)
upperValue := thisObject.Get(upper.name)
thisObject.Put(lower.name, upperValue, true)
thisObject.Put(upper.name, lowerValue, true)
} else if !lower.exists && upper.exists {
value := thisObject.Get(upper.name)
thisObject.Delete(upper.name, true)
thisObject.Put(lower.name, value, true)
} else if lower.exists && !upper.exists {
value := thisObject.Get(lower.name)
thisObject.Delete(lower.name, true)
thisObject.Put(upper.name, value, true)
} else {
// Nothing happens.
}
lower.index += 1
}
return call.This
}
func sortCompare(thisObject *_object, index0, index1 uint, compare *_object) int {
j := struct {
name string
exists bool
defined bool
value string
}{}
k := j
j.name = arrayIndexToString(index0)
j.exists = thisObject.HasProperty(j.name)
k.name = arrayIndexToString(index1)
k.exists = thisObject.HasProperty(k.name)
if !j.exists && !k.exists {
return 0
} else if !j.exists {
return 1
} else if !k.exists {
return -1
}
x := thisObject.Get(j.name)
y := thisObject.Get(k.name)
j.defined = x.IsDefined()
k.defined = y.IsDefined()
if !j.defined && !k.defined {
return 0
} else if !j.defined {