forked from robertkrimen/otto
/
evaluate_expression.go
573 lines (496 loc) · 15.1 KB
/
evaluate_expression.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
package otto
import (
"math"
"strings"
)
func (self *_runtime) evaluateConditional(node *_conditionalNode) Value {
test := self.evaluate(node.Test)
testValue := self.GetValue(test)
if toBoolean(testValue) {
return self.evaluate(node.Consequent)
}
return self.evaluate(node.Alternate)
}
func (self *_runtime) evaluateNew(node *_newNode) Value {
callee := self.evaluate(node.Callee)
calleeValue := self.GetValue(callee)
argumentList := []Value{}
for _, argumentNode := range node.ArgumentList {
argumentList = append(argumentList, self.GetValue(self.evaluate(argumentNode)))
}
this := UndefinedValue()
if !calleeValue.IsFunction() {
panic(newTypeError("%v is not a function", calleeValue))
}
return calleeValue._object().Construct(this, argumentList)
}
func (self *_runtime) evaluateArray(node *_arrayNode) Value {
valueArray := []Value{}
for _, node := range node.nodeList {
valueArray = append(valueArray, self.GetValue(self.evaluate(node)))
}
result := self.newArrayOf(valueArray)
return toValue_object(result)
}
func (self *_runtime) evaluateObject(node *_objectNode) Value {
result := self.newObject()
for _, property := range node.propertyList {
result.defineProperty(property.Key, self.GetValue(self.evaluate(property.Value)), 0111, false)
}
return toValue_object(result)
}
func (self *_runtime) evaluateRegExp(node *_regExpNode) Value {
return toValue_object(self._newRegExp(node.Pattern, node.Flags))
}
func (self *_runtime) evaluateUnaryOperation(node *_unaryOperationNode) Value {
target := self.evaluate(node.Target)
switch node.Operator {
case "typeof", "delete":
if target._valueType == valueReference && target.reference().IsUnresolvable() {
if node.Operator == "typeof" {
return toValue_string("undefined")
}
return TrueValue()
}
}
targetValue := self.GetValue(target)
switch node.Operator {
case "!":
if targetValue.toBoolean() {
return FalseValue()
}
return TrueValue()
case "~":
integerValue := toInt32(targetValue)
return toValue_int32(^integerValue)
case "+":
return toValue_float64(targetValue.toFloat())
case "-":
value := targetValue.toFloat()
// TODO Test this
sign := float64(-1)
if math.Signbit(value) {
sign = 1
}
return toValue_float64(math.Copysign(value, sign))
case "++=": // Prefix ++
newValue := toValue_float64(+1 + targetValue.toFloat())
self.PutValue(target.reference(), newValue)
return newValue
case "--=": // Prefix --
newValue := toValue_float64(-1 + targetValue.toFloat())
self.PutValue(target.reference(), newValue)
return newValue
case "=++": // Postfix ++
oldValue := targetValue.toFloat()
newValue := toValue_float64(+1 + oldValue)
self.PutValue(target.reference(), newValue)
return toValue_float64(oldValue)
case "=--": // Postfix --
oldValue := targetValue.toFloat()
newValue := toValue_float64(-1 + oldValue)
self.PutValue(target.reference(), newValue)
return toValue_float64(oldValue)
case "void":
return UndefinedValue()
case "delete":
reference := target.reference()
if reference == nil {
return TrueValue()
}
return toValue_bool(target.reference().Delete())
case "typeof":
switch targetValue._valueType {
case valueUndefined:
return toValue_string("undefined")
case valueNull:
return toValue_string("object")
case valueBoolean:
return toValue_string("boolean")
case valueNumber:
return toValue_string("number")
case valueString:
return toValue_string("string")
case valueObject:
if targetValue._object().functionValue().call != nil {
return toValue_string("function")
}
return toValue_string("object")
default:
// ?
}
}
panic(hereBeDragons())
}
func (self *_runtime) evaluateMultiply(left float64, right float64) Value {
// TODO 11.5.1
return UndefinedValue()
}
func (self *_runtime) evaluateDivide(left float64, right float64) Value {
if math.IsNaN(left) || math.IsNaN(right) {
return NaNValue()
}
if math.IsInf(left, 0) && math.IsInf(right, 0) {
return NaNValue()
}
if left == 0 && right == 0 {
return NaNValue()
}
if math.IsInf(left, 0) {
if math.Signbit(left) == math.Signbit(right) {
return positiveInfinityValue()
} else {
return negativeInfinityValue()
}
}
if math.IsInf(right, 0) {
if math.Signbit(left) == math.Signbit(right) {
return positiveZeroValue()
} else {
return negativeZeroValue()
}
}
if right == 0 {
if math.Signbit(left) == math.Signbit(right) {
return positiveInfinityValue()
} else {
return negativeInfinityValue()
}
}
return toValue_float64(left / right)
}
func (self *_runtime) evaluateModulo(left float64, right float64) Value {
// TODO 11.5.3
return UndefinedValue()
}
func (self *_runtime) calculateBinaryOperation(operator string, left Value, right Value) Value {
leftValue := self.GetValue(left)
switch operator {
// Additive
case "+":
leftValue = toPrimitive(leftValue)
rightValue := self.GetValue(right)
rightValue = toPrimitive(rightValue)
if leftValue.IsString() || rightValue.IsString() {
return toValue_string(strings.Join([]string{leftValue.toString(), rightValue.toString()}, ""))
} else {
return toValue_float64(leftValue.toFloat() + rightValue.toFloat())
}
case "-":
rightValue := self.GetValue(right)
return toValue_float64(leftValue.toFloat() - rightValue.toFloat())
// Multiplicative
case "*":
rightValue := self.GetValue(right)
return toValue_float64(leftValue.toFloat() * rightValue.toFloat())
case "/":
rightValue := self.GetValue(right)
return self.evaluateDivide(leftValue.toFloat(), rightValue.toFloat())
case "%":
rightValue := self.GetValue(right)
return toValue_float64(math.Mod(leftValue.toFloat(), rightValue.toFloat()))
// Logical
case "&&":
left := toBoolean(leftValue)
if !left {
return FalseValue()
}
return toValue_bool(toBoolean(self.GetValue(right)))
case "||":
left := toBoolean(leftValue)
if left {
return TrueValue()
}
return toValue_bool(toBoolean(self.GetValue(right)))
// Bitwise
case "&":
rightValue := self.GetValue(right)
return toValue_int32(toInt32(leftValue) & toInt32(rightValue))
case "|":
rightValue := self.GetValue(right)
return toValue_int32(toInt32(leftValue) | toInt32(rightValue))
case "^":
rightValue := self.GetValue(right)
return toValue_int32(toInt32(leftValue) ^ toInt32(rightValue))
// Shift
// (Masking of 0x1f is to restrict the shift to a maximum of 31 places)
case "<<":
rightValue := self.GetValue(right)
return toValue_int32(toInt32(leftValue) << (toUint32(rightValue) & 0x1f))
case ">>":
rightValue := self.GetValue(right)
return toValue_int32(toInt32(leftValue) >> (toUint32(rightValue) & 0x1f))
case ">>>":
rightValue := self.GetValue(right)
// Shifting an unsigned integer is a logical shift
return toValue_uint32(toUint32(leftValue) >> (toUint32(rightValue) & 0x1f))
case "instanceof":
rightValue := self.GetValue(right)
if !rightValue.IsObject() {
panic(newTypeError("Expecting a function in instanceof check, but got: %v", rightValue))
}
return toValue_bool(rightValue._object().HasInstance(leftValue))
case "in":
rightValue := self.GetValue(right)
if !rightValue.IsObject() {
panic(newTypeError())
}
return toValue_bool(rightValue._object().hasProperty(toString(leftValue)))
}
panic(hereBeDragons(operator))
}
func (self *_runtime) evaluateAssignment(node *_assignmentNode) Value {
left := self.evaluate(node.Left)
right := self.evaluate(node.Right)
rightValue := self.GetValue(right)
result := rightValue
if node.Operator != "" {
result = self.calculateBinaryOperation(node.Operator, left, rightValue)
}
self.PutValue(left.reference(), result)
return result
}
func valueKindDispatchKey(left _valueType, right _valueType) int {
return (int(left) << 2) + int(right)
}
var equalDispatch map[int](func(Value, Value) bool) = makeEqualDispatch()
func makeEqualDispatch() map[int](func(Value, Value) bool) {
key := valueKindDispatchKey
return map[int](func(Value, Value) bool){
key(valueNumber, valueObject): func(x Value, y Value) bool { return x.toFloat() == y.toFloat() },
key(valueString, valueObject): func(x Value, y Value) bool { return x.toFloat() == y.toFloat() },
key(valueObject, valueNumber): func(x Value, y Value) bool { return x.toFloat() == y.toFloat() },
key(valueObject, valueString): func(x Value, y Value) bool { return x.toFloat() == y.toFloat() },
}
}
type _lessThanResult int
const (
lessThanFalse _lessThanResult = iota
lessThanTrue
lessThanUndefined
)
func calculateLessThan(left Value, right Value, leftFirst bool) _lessThanResult {
x := UndefinedValue()
y := x
if leftFirst {
x = toNumberPrimitive(left)
y = toNumberPrimitive(right)
} else {
y = toNumberPrimitive(right)
x = toNumberPrimitive(left)
}
result := false
if x._valueType != valueString || y._valueType != valueString {
x, y := x.toFloat(), y.toFloat()
if math.IsNaN(x) || math.IsNaN(y) {
return lessThanUndefined
}
result = x < y
} else {
x, y := x.toString(), y.toString()
result = x < y
}
if result {
return lessThanTrue
}
return lessThanFalse
}
var lessThanTable [4](map[_lessThanResult]bool) = [4](map[_lessThanResult]bool){
// <
map[_lessThanResult]bool{
lessThanFalse: false,
lessThanTrue: true,
lessThanUndefined: false,
},
// >
map[_lessThanResult]bool{
lessThanFalse: false,
lessThanTrue: true,
lessThanUndefined: false,
},
// <=
map[_lessThanResult]bool{
lessThanFalse: true,
lessThanTrue: false,
lessThanUndefined: false,
},
// >=
map[_lessThanResult]bool{
lessThanFalse: true,
lessThanTrue: false,
lessThanUndefined: false,
},
}
func (self *_runtime) calculateComparison(comparator string, left Value, right Value) bool {
// TODO This might be redundant now (with regards to evaluateComparison)
x := self.GetValue(left)
y := self.GetValue(right)
kindEqualKind := false
result := true
negate := false
switch comparator {
case "<":
result = lessThanTable[0][calculateLessThan(x, y, true)]
case ">":
result = lessThanTable[1][calculateLessThan(y, x, false)]
case "<=":
result = lessThanTable[2][calculateLessThan(y, x, false)]
case ">=":
result = lessThanTable[3][calculateLessThan(x, y, true)]
case "!==":
negate = true
fallthrough
case "===":
if x._valueType != y._valueType {
result = false
} else {
kindEqualKind = true
}
case "!=":
negate = true
fallthrough
case "==":
if x._valueType == y._valueType {
kindEqualKind = true
} else if x._valueType <= valueUndefined && y._valueType <= valueUndefined {
result = true
} else if x._valueType <= valueUndefined || y._valueType <= valueUndefined {
result = false
} else if x._valueType <= valueString && y._valueType <= valueString {
result = x.toFloat() == y.toFloat()
} else if x._valueType == valueBoolean {
result = self.calculateComparison("==", toValue_float64(x.toFloat()), y)
} else if y._valueType == valueBoolean {
result = self.calculateComparison("==", x, toValue_float64(y.toFloat()))
} else if x._valueType == valueObject {
result = self.calculateComparison("==", toPrimitive(x), y)
} else if y._valueType == valueObject {
result = self.calculateComparison("==", x, toPrimitive(y))
} else {
panic(hereBeDragons("Unable to test for equality: %v ==? %v", x, y))
}
}
if kindEqualKind {
switch x._valueType {
case valueUndefined, valueNull:
result = true
case valueNumber:
x := x.toFloat()
y := y.toFloat()
if math.IsNaN(x) || math.IsNaN(y) {
result = false
} else {
result = x == y
}
case valueString:
result = x.toString() == y.toString()
case valueBoolean:
result = x.toBoolean() == y.toBoolean()
case valueObject:
result = x._object() == y._object()
default:
goto ERROR
}
}
if negate {
result = !result
}
return result
ERROR:
panic(hereBeDragons("%v (%v) %s %v (%v)", x, x._valueType, comparator, y, y._valueType))
}
func (self *_runtime) evaluateComparison(node *_comparisonNode) Value {
left := self.GetValue(self.evaluate(node.Left))
right := self.GetValue(self.evaluate(node.Right))
return toValue_bool(self.calculateComparison(node.Comparator, left, right))
}
func (self *_runtime) evaluateBinaryOperation(node *_binaryOperationNode) Value {
left := self.evaluate(node.Left)
leftValue := self.GetValue(left)
switch node.Operator {
// Logical
case "&&":
if !toBoolean(leftValue) {
return leftValue
}
right := self.evaluate(node.Right)
return self.GetValue(right)
case "||":
if toBoolean(leftValue) {
return leftValue
}
right := self.evaluate(node.Right)
return self.GetValue(right)
}
return self.calculateBinaryOperation(node.Operator, leftValue, self.evaluate(node.Right))
}
func (self *_runtime) evaluateCall(node *_callNode, withArgumentList []interface{}) Value {
callee := self.evaluate(node.Callee)
calleeValue := self.GetValue(callee)
argumentList := []Value{}
if withArgumentList != nil {
argumentList = self.toValueArray(withArgumentList...)
} else {
for _, argumentNode := range node.ArgumentList {
argumentList = append(argumentList, self.GetValue(self.evaluate(argumentNode)))
}
}
this := UndefinedValue()
calleeReference := callee.reference()
evalHint := false
if calleeReference != nil {
if calleeReference.IsPropertyReference() {
calleeObject := calleeReference.GetBase().(*_object)
this = toValue_object(calleeObject)
} else {
// TODO ImplictThisValue
}
if calleeReference.GetName() == "eval" {
evalHint = true // Possible direct eval
}
}
if !calleeValue.IsFunction() {
panic(newTypeError("%v is not a function", calleeValue))
}
return self.Call(calleeValue._object(), this, argumentList, evalHint)
}
func (self *_runtime) evaluateFunction(node *_functionNode) Value {
return toValue_object(self.newNodeFunction(node, self.LexicalEnvironment()))
}
func (self *_runtime) evaluateDotMember(node *_dotMemberNode) Value {
target := self.evaluate(node.Target)
targetValue := self.GetValue(target)
// TODO Pass in base value as-is, and defer toObject till later?
return toValue(newPropertyReference(self.toObject(targetValue), node.Member, false, node))
}
func (self *_runtime) evaluateBracketMember(node *_bracketMemberNode) Value {
target := self.evaluate(node.Target)
targetValue := self.GetValue(target)
member := self.evaluate(node.Member)
memberValue := self.GetValue(member)
// TODO Pass in base value as-is, and defer toObject till later?
return toValue(newPropertyReference(self.toObject(targetValue), toString(memberValue), false, node))
}
func (self *_runtime) evaluateIdentifier(node *_identifierNode) Value {
name := node.Value
// TODO Should be true or false (strictness) depending on context
// getIdentifierReference should not return nil, but we check anyway and panic
// so as not to propagate the nil into something else
reference := getIdentifierReference(self.LexicalEnvironment(), name, false, node)
if reference == nil {
// Should never get here!
panic(hereBeDragons("referenceError == nil: " + name))
}
return toValue(reference)
}
func (self *_runtime) evaluateValue(node *_valueNode) Value {
return node.Value
}
func (self *_runtime) evaluateComma(node *_commaNode) Value {
var result Value
for _, node := range node.Sequence {
result = self.evaluate(node)
result = self.GetValue(result)
}
return result
}