-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathOperators.java
More file actions
715 lines (613 loc) · 23.8 KB
/
Operators.java
File metadata and controls
715 lines (613 loc) · 23.8 KB
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
/** Copyright 2018 Nick nickl- Lombard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
package bsh;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class Operators implements ParserConstants {
private static final List<Integer> OVERFLOW_OPS
= Arrays.asList(PLUS, MINUS, STAR, POWER);
private static final List<Integer> COMPARABLE_OPS
= Arrays.asList(LT, LTX, GT, GTX, EQ, LE, LEX, GE, GEX, NE);
/** Constructor private no instance required. */
private Operators() {}
/** Binary operations on arbitrary objects.
* @param lhs left hand side value
* @param rhs right hand side value
* @param kind operator type
* @return operator applied value
* @throws UtilEvalError evaluation error */
@SuppressWarnings("unchecked")
public static Object arbitraryObjectsBinaryOperation(Object lhs, Object rhs, int kind)
throws UtilEvalError {
if ( kind == EQ )
return (lhs == rhs) ? Primitive.TRUE : Primitive.FALSE;
if ( kind == NE )
return (lhs != rhs) ? Primitive.TRUE : Primitive.FALSE;
if ( lhs == Primitive.VOID || rhs == Primitive.VOID )
throw new UtilEvalError(
"illegal use of undefined variable, class, or"
+ " 'void' literal");
if (kind == SPACESHIP) {
int comp = 0; // used to ensure only -1, 0, and 1 is returned.
if (lhs instanceof Comparable || rhs instanceof Comparable)
comp = Comparator.nullsFirst( // nullsFirst Comparable Comparator
Comparator.<Comparable<Object>>naturalOrder())
.compare((Comparable<Object>)Primitive.unwrap(lhs),
(Comparable<Object>)Primitive.unwrap(rhs));
else
comp = Comparator.nullsFirst( // nullsFirst toString Comparator
Comparator.comparing(Object::toString))
.compare(Primitive.unwrap(lhs), Primitive.unwrap(rhs));
return Primitive.wrap(comp < 0 ? -1 : comp > 0 ? 1 : 0, Integer.TYPE);
}
if ( kind == PLUS ) {
// String concatenation operation
if ( lhs instanceof String || rhs instanceof String )
return BSHLiteral.internStrings
? (String.valueOf(lhs) + String.valueOf(rhs)).intern()
: String.valueOf(lhs) + String.valueOf(rhs);
// array concatenation operation
if ( lhs.getClass().isArray() && rhs instanceof List )
rhs = ((List<?>) rhs).toArray();
if ( lhs.getClass().isArray()
&& rhs.getClass().isArray() )
return BshArray.concat(lhs, rhs);
// list concatenation operation
if ( lhs instanceof List && rhs.getClass().isArray() )
rhs = Types.castObject(rhs, List.class, Types.CAST);
if ( lhs instanceof List && rhs instanceof List )
return BshArray.concat(
(List<?>) lhs, (List<?>) rhs);
}
if ( kind == STAR ) {
// array repeat operation
if ( lhs.getClass().isArray() )
return BshArray.repeat(lhs,
(int) Primitive.castWrapper(Integer.TYPE, rhs));
if ( rhs.getClass().isArray() )
return BshArray.repeat(rhs,
(int) Primitive.castWrapper(Integer.TYPE, lhs));
// List repeat operation
if ( lhs instanceof List )
return BshArray.repeat((List<Object>) lhs,
(int) Primitive.castWrapper(Integer.TYPE, rhs));
if ( rhs instanceof List )
return BshArray.repeat((List<Object>) rhs,
(int) Primitive.castWrapper(Integer.TYPE, lhs));
try {
// String repeat operation
if ( lhs instanceof String )
return BSHLiteral.internStrings
? new String(new char[(int) Primitive.castWrapper(Integer.TYPE, rhs)])
.replace("\0", String.valueOf(lhs)).intern()
: new String(new char[(int) Primitive.castWrapper(Integer.TYPE, rhs)])
.replace("\0", String.valueOf(lhs));
if ( rhs instanceof String )
return BSHLiteral.internStrings
? new String(new char[(int) Primitive.castWrapper(Integer.TYPE, lhs)])
.replace("\0", String.valueOf(rhs)).intern()
: new String(new char[(int) Primitive.castWrapper(Integer.TYPE, lhs)])
.replace("\0", String.valueOf(rhs));
} catch (NegativeArraySizeException e) {
throw new UtilEvalError("Negative repeat operand: "+e.getMessage(), e);
}
}
if ( lhs instanceof String || rhs instanceof String )
throw new UtilEvalError(
"Use of non + operator with String" );
if ( lhs.getClass().isArray() || rhs.getClass().isArray()
|| lhs instanceof List || rhs instanceof List)
throw new UtilEvalError(
"Use of invalid operator " + tokenImage[kind]
+ " with array or List type" );
if ( lhs == Primitive.NULL || rhs == Primitive.NULL )
throw new UtilEvalError(
"illegal use of null value or 'null' literal");
throw new UtilEvalError("Operator: " + tokenImage[kind]
+ " inappropriate for objects");
}
/**
Perform a binary operation on two Primitives or wrapper types.
If both original args were Primitives return a Primitive result
else it was mixed (wrapper/primitive) return the wrapper type.
The exception is for boolean operations where we will return the
primitive type either way.
*/
public static Object binaryOperation(Object obj1, Object obj2, int kind)
throws UtilEvalError {
// Unwrap primitives
Object lhs = Primitive.unwrap(obj1);
Object rhs = Primitive.unwrap(obj2);
if ( Types.isNumeric(lhs) && Types.isNumeric(rhs) ) {
Object[] operands = promotePrimitives(lhs, rhs);
lhs = operands[0];
rhs = operands[1];
}
if ( lhs.getClass() != rhs.getClass() )
throw new UtilEvalError("Type mismatch in operator. "
+ lhs.getClass() + " cannot be used with " + rhs.getClass());
Object result;
try {
result = binaryOperationImpl( lhs, rhs, kind );
} catch (ArithmeticException e) {
throw new UtilTargetError("Arithemetic Exception in binary op", e);
}
if ( result instanceof Boolean )
return ((Boolean) result).booleanValue() ? Primitive.TRUE : Primitive.FALSE;
// If both original args were Primitives return a Primitive result
// else it was mixed (wrapper/primitive) return the wrapper type
// Exception is for boolean result, return the primitive
if ( obj1 instanceof Primitive && obj2 instanceof Primitive )
if ( Types.isFloatingpoint(result) && lhs.getClass() == BigDecimal.class )
return Primitive.wrap(result, result.getClass());
else
return Primitive.shrinkWrap(result);
return Primitive.shrinkWrap(result).getValue();
}
@SuppressWarnings("unchecked")
static <T> Object binaryOperationImpl( T lhs, T rhs, int kind )
throws UtilEvalError
{
if (kind == SPACESHIP) // compares two non null numbers
return ((Comparable<T>)lhs).compareTo(rhs);
if (lhs instanceof Boolean)
return booleanBinaryOperation( (Boolean) lhs, (Boolean) rhs, kind );
if (COMPARABLE_OPS.contains(kind))
return comparableBinaryBooleanOperations((Comparable<T>) lhs, rhs, kind);
if (lhs instanceof BigInteger)
return bigIntegerBinaryOperation( (BigInteger) lhs, (BigInteger) rhs, kind );
if (lhs instanceof BigDecimal)
return bigDecimalBinaryOperation( (BigDecimal) lhs, (BigDecimal) rhs, kind );
if (Types.isFloatingpoint(lhs))
return doubleBinaryOperation( (Double) lhs, (Double) rhs, kind );
if (lhs instanceof Number)
return longBinaryOperation( (Long) lhs, (Long) rhs, kind );
throw new UtilEvalError("Invalid types in binary operator" );
}
static Boolean booleanBinaryOperation(Boolean B1, Boolean B2, int kind)
{
boolean lhs = B1.booleanValue();
boolean rhs = B2.booleanValue();
switch(kind)
{
case EQ:
return lhs == rhs;
case NE:
return lhs != rhs;
case BOOL_OR:
case BOOL_ORX:
// already evaluated lhs TRUE
// see BSHBinaryExpression
return false || rhs;
case BOOL_AND:
case BOOL_ANDX:
// already evaluated lhs FALSE
// see BSHBinaryExpression
return true && rhs;
case BIT_AND:
case BIT_ANDX:
return lhs & rhs;
case BIT_OR:
case BIT_ORX:
return lhs | rhs;
case XOR:
case XORX:
return lhs ^ rhs;
}
throw new InterpreterError("unimplemented binary operator");
}
static <T> Boolean comparableBinaryBooleanOperations(Comparable<T> lhs, T rhs, int kind) {
switch(kind)
{
// boolean
case LT:
case LTX:
return lhs.compareTo(rhs) < 0;
case GT:
case GTX:
return lhs.compareTo(rhs) > 0;
case LE:
case LEX:
return lhs.compareTo(rhs) <= 0;
case GE:
case GEX:
return lhs.compareTo(rhs) >= 0;
case NE:
return lhs.compareTo(rhs) != 0;
case EQ:
default:
return lhs.compareTo(rhs) == 0;
}
}
// returns Object covering both Long and Boolean return types
static Object longBinaryOperation(long lhs, long rhs, int kind)
{
switch(kind)
{
// arithmetic
case PLUS:
if ( lhs > 0 && (Long.MAX_VALUE - lhs) < rhs )
break;
return lhs + rhs;
case MINUS:
if ( lhs < 0 && (Long.MIN_VALUE - lhs) > -rhs )
break;
return lhs - rhs;
case STAR:
if ( lhs != 0 && Long.MAX_VALUE / lhs < rhs )
break;
return lhs * rhs;
case SLASH:
return lhs / rhs;
case MOD:
case MODX:
return lhs % rhs;
case POWER:
case POWERX:
double check = Math.pow(lhs, rhs);
BigInteger bi = BigDecimal.valueOf(check).toBigInteger();
if ( bi.compareTo(Primitive.LONG_MIN) >= 0 && bi.compareTo(Primitive.LONG_MAX) <= 0 )
return (long) check;
break;
// bitwise
case LSHIFT:
case LSHIFTX:
return lhs << rhs;
case RSIGNEDSHIFT:
case RSIGNEDSHIFTX:
return lhs >> rhs;
case RUNSIGNEDSHIFT:
case RUNSIGNEDSHIFTX:
return lhs >>> rhs;
case BIT_AND:
case BIT_ANDX:
return lhs & rhs;
case BIT_OR:
case BIT_ORX:
return lhs | rhs;
case XOR:
case XORX:
return lhs ^ rhs;
}
if ( OVERFLOW_OPS.contains(kind) )
return bigIntegerBinaryOperation(BigInteger.valueOf(lhs), BigInteger.valueOf(rhs), kind);
throw new InterpreterError(
"Unimplemented binary long operator");
}
// returns Object covering both Integer and Boolean return types
static Object bigIntegerBinaryOperation(BigInteger lhs, BigInteger rhs, int kind)
{
switch(kind)
{
// arithmetic
case PLUS:
return lhs.add(rhs);
case MINUS:
return lhs.subtract(rhs);
case STAR:
return lhs.multiply(rhs);
case SLASH:
return lhs.divide(rhs);
case MOD:
case MODX:
return lhs.mod(rhs);
case POWER:
case POWERX:
return lhs.pow(rhs.intValue());
// bitwise
case LSHIFT:
case LSHIFTX:
return lhs.shiftLeft(rhs.intValue());
case RSIGNEDSHIFT:
case RSIGNEDSHIFTX:
return lhs.shiftRight(rhs.intValue());
case RUNSIGNEDSHIFT:
case RUNSIGNEDSHIFTX:
if ( lhs.signum() >= 0 )
return lhs.shiftRight(rhs.intValue());
BigInteger opener = BigInteger.ONE.shiftLeft(lhs.toString(2).length() + 1);
BigInteger opened = lhs.subtract(opener);
BigInteger mask = opener.subtract(BigInteger.ONE).shiftRight(rhs.intValue() + 1);
return opened.shiftRight(rhs.intValue()).and(mask);
case BIT_AND:
case BIT_ANDX:
return lhs.and(rhs);
case BIT_OR:
case BIT_ORX:
return lhs.or(rhs);
case XOR:
case XORX:
return lhs.xor(rhs);
}
throw new InterpreterError(
"Unimplemented binary integer operator");
}
// returns Object covering both Double and Boolean return types
static Object doubleBinaryOperation(double lhs, double rhs, int kind)
throws UtilEvalError
{
switch(kind)
{
// arithmetic
case PLUS:
if ( lhs > 0d && (Double.MAX_VALUE - lhs) < rhs )
break;
return lhs + rhs;
case MINUS:
if ( lhs < 0d && (-Double.MAX_VALUE - lhs) > -rhs )
break;
return lhs - rhs;
case STAR:
if ( lhs != 0 && Double.MAX_VALUE / lhs < rhs )
break;
return lhs * rhs;
case SLASH:
return lhs / rhs;
case MOD:
case MODX:
return lhs % rhs;
case POWER:
case POWERX:
double check = Math.pow(lhs, rhs);
if ( Double.isInfinite(check) )
break;
return check;
// can't shift floating-point values
case LSHIFT:
case LSHIFTX:
case RSIGNEDSHIFT:
case RSIGNEDSHIFTX:
case RUNSIGNEDSHIFT:
case RUNSIGNEDSHIFTX:
throw new UtilEvalError("Can't shift floatingpoint values");
}
if ( OVERFLOW_OPS.contains(kind) )
return bigDecimalBinaryOperation(BigDecimal.valueOf(lhs), BigDecimal.valueOf(rhs), kind);
throw new InterpreterError(
"Unimplemented binary double operator");
}
// returns Object covering both Long and Boolean return types
static Object bigDecimalBinaryOperation(BigDecimal lhs, BigDecimal rhs, int kind)
throws UtilEvalError
{
switch(kind)
{
// arithmetic
case PLUS:
return lhs.add(rhs);
case MINUS:
return lhs.subtract(rhs);
case STAR:
return lhs.multiply(rhs);
case SLASH:
return lhs.divide(rhs);
case MOD:
case MODX:
return lhs.remainder(rhs);
case POWER:
case POWERX:
return lhs.pow(rhs.intValue());
// can't shift floats
case LSHIFT:
case LSHIFTX:
case RSIGNEDSHIFT:
case RSIGNEDSHIFTX:
case RUNSIGNEDSHIFT:
case RUNSIGNEDSHIFTX:
throw new UtilEvalError("Can't shift floatingpoint values");
}
throw new InterpreterError(
"Unimplemented binary float operator");
}
/**
Promote primitive wrapper type to Integer wrapper type
*/
static Number promoteToInteger(Object wrapper )
{
if ( wrapper instanceof Character )
return Integer.valueOf(((Character) wrapper).charValue());
if ( wrapper instanceof Byte || wrapper instanceof Short )
return Integer.valueOf(((Number) wrapper).intValue());
return (Number) wrapper;
}
/**
Promote the pair of primitives to the maximum type of the two.
e.g. [int,long]->[long,long]
*/
static Object[] promotePrimitives(Object lhs, Object rhs)
{
Number lnum = promoteToInteger(lhs);
Number rnum = promoteToInteger(rhs);
if ( lhs instanceof BigDecimal ) {
if ( !(rhs instanceof BigDecimal) )
rhs = Primitive.castNumber(BigDecimal.class, rnum);
} else if ( rhs instanceof BigDecimal ) {
lhs = Primitive.castNumber(BigDecimal.class, lnum);
} else if ( Types.isFloatingpoint(lhs) || Types.isFloatingpoint(rhs)) {
if ( !(lhs instanceof Double) )
lhs = Double.valueOf(lnum.doubleValue());
if ( !(rhs instanceof Double) )
rhs = Double.valueOf(rnum.doubleValue());
} else if ( lhs instanceof BigInteger ) {
if ( !(rhs instanceof BigInteger) )
rhs = Primitive.castNumber(BigInteger.class, rnum);
} else if ( rhs instanceof BigInteger ) {
lhs = Primitive.castNumber(BigInteger.class, lnum);
} else {
if ( !(lhs instanceof Long) )
lhs = Long.valueOf(lnum.longValue());
if ( !(rhs instanceof Long) )
rhs = Long.valueOf(rnum.longValue());
}
return new Object[] { lhs, rhs };
}
public static Primitive unaryOperation(Primitive val, int kind)
throws UtilEvalError
{
if (val == Primitive.NULL)
throw new UtilEvalError(
"illegal use of null object or 'null' literal");
if (val == Primitive.VOID)
throw new UtilEvalError(
"illegal use of undefined object or 'void' literal");
Class<?> operandType = val.getType();
if ( operandType == Boolean.TYPE )
return booleanUnaryOperation((Boolean) val.getValue(), kind)
? Primitive.TRUE : Primitive.FALSE;
Number operand = promoteToInteger(val.getValue());
if(operand instanceof Integer)
{
int result = intUnaryOperation((Integer) operand, kind);
// ++ and -- must be cast back the original type
if(kind == INCR || kind == DECR)
{
if(operandType == Byte.TYPE)
return new Primitive((byte) result);
if(operandType == Short.TYPE)
return new Primitive((short) result);
if(operandType == Character.TYPE)
return new Primitive((char) result);
}
return new Primitive(result);
}
if(operand instanceof Long)
return new Primitive(longUnaryOperation(operand.longValue(), kind));
if(operand instanceof Float)
return new Primitive(floatUnaryOperation(operand.floatValue(), kind));
if(operand instanceof Double)
return new Primitive(doubleUnaryOperation(operand.doubleValue(), kind));
if(operand instanceof BigInteger)
return new Primitive(bigIntegerUnaryOperation((BigInteger) operand, kind));
if(operand instanceof BigDecimal)
return new Primitive(bigDecimalUnaryOperation((BigDecimal) operand, kind));
throw new InterpreterError(
"An error occurred. Please call technical support.");
}
static boolean booleanUnaryOperation(Boolean B, int kind)
throws UtilEvalError
{
boolean operand = B.booleanValue();
switch(kind)
{
case BANG:
return !operand;
}
throw new UtilEvalError("Operator inappropriate for boolean");
}
static int intUnaryOperation(Integer I, int kind)
{
int operand = I.intValue();
switch(kind)
{
case PLUS:
return operand;
case MINUS:
return -operand;
case TILDE:
return ~operand;
case INCR:
return operand + 1;
case DECR:
return operand - 1;
}
throw new InterpreterError("bad integer unaryOperation");
}
static BigInteger bigIntegerUnaryOperation(BigInteger operand, int kind)
{
switch(kind)
{
case PLUS:
return operand;
case MINUS:
return operand.negate();
case TILDE:
return operand.not();
case INCR:
return operand.add(BigInteger.ONE);
case DECR:
return operand.subtract(BigInteger.ONE);
}
throw new InterpreterError("bad big integer unaryOperation");
}
static BigDecimal bigDecimalUnaryOperation(BigDecimal operand, int kind)
{
switch(kind)
{
case PLUS:
return operand;
case MINUS:
return operand.negate();
case TILDE:
return operand.signum() == 1 ? operand.negate() : operand;
case INCR:
return operand.add(BigDecimal.ONE);
case DECR:
return operand.subtract(BigDecimal.ONE);
}
throw new InterpreterError("bad big decimal unaryOperation");
}
static long longUnaryOperation(Long L, int kind)
{
long operand = L.longValue();
switch(kind)
{
case PLUS:
return operand;
case MINUS:
return -operand;
case TILDE:
return ~operand;
case INCR:
return operand + 1;
case DECR:
return operand - 1;
}
throw new InterpreterError("bad long unaryOperation");
}
static float floatUnaryOperation(Float F, int kind)
{
float operand = F.floatValue();
switch(kind)
{
case PLUS:
return operand;
case MINUS:
return -operand;
case INCR:
return operand + 1;
case DECR:
return operand - 1;
}
throw new InterpreterError("bad float unaryOperation");
}
static double doubleUnaryOperation(Double D, int kind)
{
double operand = D.doubleValue();
switch(kind)
{
case PLUS:
return operand;
case MINUS:
return -operand;
case INCR:
return operand + 1;
case DECR:
return operand - 1;
}
throw new InterpreterError("bad double unaryOperation");
}
}