PageRenderTime 23ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/jEdit/tags/jedit-4-5-pre1/org/gjt/sp/jedit/bsh/Primitive.java

#
Java | 1098 lines | 716 code | 160 blank | 222 comment | 190 complexity | 93cbe78fc07039f71515a62198c32bac MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  1. /*****************************************************************************
  2. * *
  3. * This file is part of the BeanShell Java Scripting distribution. *
  4. * Documentation and updates may be found at http://www.beanshell.org/ *
  5. * *
  6. * Sun Public License Notice: *
  7. * *
  8. * The contents of this file are subject to the Sun Public License Version *
  9. * 1.0 (the "License"); you may not use this file except in compliance with *
  10. * the License. A copy of the License is available at http://www.sun.com *
  11. * *
  12. * The Original Code is BeanShell. The Initial Developer of the Original *
  13. * Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
  14. * (C) 2000. All Rights Reserved. *
  15. * *
  16. * GNU Public License Notice: *
  17. * *
  18. * Alternatively, the contents of this file may be used under the terms of *
  19. * the GNU Lesser General Public License (the "LGPL"), in which case the *
  20. * provisions of LGPL are applicable instead of those above. If you wish to *
  21. * allow use of your version of this file only under the terms of the LGPL *
  22. * and not to allow others to use your version of this file under the SPL, *
  23. * indicate your decision by deleting the provisions above and replace *
  24. * them with the notice and other provisions required by the LGPL. If you *
  25. * do not delete the provisions above, a recipient may use your version of *
  26. * this file under either the SPL or the LGPL. *
  27. * *
  28. * Patrick Niemeyer (pat@pat.net) *
  29. * Author of Learning Java, O'Reilly & Associates *
  30. * http://www.pat.net/~pat/ *
  31. * *
  32. *****************************************************************************/
  33. package org.gjt.sp.jedit.bsh;
  34. import java.util.Hashtable;
  35. /**
  36. Wrapper for primitive types in Bsh. This is package public because it
  37. is used in the implementation of some bsh commands.
  38. See the note in LHS.java about wrapping objects.
  39. */
  40. /*
  41. Note: this class is final because we may test == Primitive.class in places.
  42. If we need to change that search for those tests.
  43. */
  44. public final class Primitive implements ParserConstants, java.io.Serializable
  45. {
  46. /*
  47. static Hashtable primitiveToWrapper = new Hashtable();
  48. static Hashtable wrapperToPrimitive = new Hashtable();
  49. static {
  50. primitiveToWrapper.put( Boolean.TYPE, Boolean.class );
  51. primitiveToWrapper.put( Byte.TYPE, Byte.class );
  52. primitiveToWrapper.put( Short.TYPE, Short.class );
  53. primitiveToWrapper.put( Character.TYPE, Character.class );
  54. primitiveToWrapper.put( Integer.TYPE, Integer.class );
  55. primitiveToWrapper.put( Long.TYPE, Long.class );
  56. primitiveToWrapper.put( Float.TYPE, Float.class );
  57. primitiveToWrapper.put( Double.TYPE, Double.class );
  58. wrapperToPrimitive.put( Boolean.class, Boolean.TYPE );
  59. wrapperToPrimitive.put( Byte.class, Byte.TYPE );
  60. wrapperToPrimitive.put( Short.class, Short.TYPE );
  61. wrapperToPrimitive.put( Character.class, Character.TYPE );
  62. wrapperToPrimitive.put( Integer.class, Integer.TYPE );
  63. wrapperToPrimitive.put( Long.class, Long.TYPE );
  64. wrapperToPrimitive.put( Float.class, Float.TYPE );
  65. wrapperToPrimitive.put( Double.class, Double.TYPE );
  66. }
  67. */
  68. static Hashtable wrapperMap = new Hashtable();
  69. static {
  70. wrapperMap.put( Boolean.TYPE, Boolean.class );
  71. wrapperMap.put( Byte.TYPE, Byte.class );
  72. wrapperMap.put( Short.TYPE, Short.class );
  73. wrapperMap.put( Character.TYPE, Character.class );
  74. wrapperMap.put( Integer.TYPE, Integer.class );
  75. wrapperMap.put( Long.TYPE, Long.class );
  76. wrapperMap.put( Float.TYPE, Float.class );
  77. wrapperMap.put( Double.TYPE, Double.class );
  78. wrapperMap.put( Boolean.class, Boolean.TYPE );
  79. wrapperMap.put( Byte.class, Byte.TYPE );
  80. wrapperMap.put( Short.class, Short.TYPE );
  81. wrapperMap.put( Character.class, Character.TYPE );
  82. wrapperMap.put( Integer.class, Integer.TYPE );
  83. wrapperMap.put( Long.class, Long.TYPE );
  84. wrapperMap.put( Float.class, Float.TYPE );
  85. wrapperMap.put( Double.class, Double.TYPE );
  86. }
  87. /** The primitive value stored in its java.lang wrapper class */
  88. private Object value;
  89. private static class Special implements java.io.Serializable
  90. {
  91. private Special() { }
  92. public static final Special NULL_VALUE = new Special();
  93. public static final Special VOID_TYPE = new Special();
  94. }
  95. /*
  96. NULL means "no value".
  97. This ia a placeholder for primitive null value.
  98. */
  99. public static final Primitive NULL = new Primitive(Special.NULL_VALUE);
  100. /**
  101. VOID means "no type".
  102. Strictly speaking, this makes no sense here. But for practical
  103. reasons we'll consider the lack of a type to be a special value.
  104. */
  105. public static final Primitive VOID = new Primitive(Special.VOID_TYPE);
  106. // private to prevent invocation with param that isn't a primitive-wrapper
  107. public Primitive( Object value )
  108. {
  109. if ( value == null )
  110. throw new InterpreterError(
  111. "Use Primitve.NULL instead of Primitive(null)");
  112. if ( value != Special.NULL_VALUE
  113. && value != Special.VOID_TYPE &&
  114. !isWrapperType( value.getClass() )
  115. )
  116. throw new InterpreterError( "Not a wrapper type: "+value);
  117. this.value = value;
  118. }
  119. public Primitive(boolean value) { this(new Boolean(value)); }
  120. public Primitive(byte value) { this(new Byte(value)); }
  121. public Primitive(short value) { this(new Short(value)); }
  122. public Primitive(char value) { this(new Character(value)); }
  123. public Primitive(int value) { this(new Integer(value)); }
  124. public Primitive(long value) { this(new Long(value)); }
  125. public Primitive(float value) { this(new Float(value)); }
  126. public Primitive(double value) { this(new Double(value)); }
  127. /**
  128. Return the primitive value stored in its java.lang wrapper class
  129. */
  130. public Object getValue()
  131. {
  132. if ( value == Special.NULL_VALUE )
  133. return null;
  134. else
  135. if ( value == Special.VOID_TYPE )
  136. throw new InterpreterError("attempt to unwrap void type");
  137. else
  138. return value;
  139. }
  140. public String toString()
  141. {
  142. if(value == Special.NULL_VALUE)
  143. return "null";
  144. else if(value == Special.VOID_TYPE)
  145. return "void";
  146. else
  147. return value.toString();
  148. }
  149. /**
  150. Get the corresponding Java primitive TYPE class for this Primitive.
  151. @return the primitive TYPE class type of the value or Void.TYPE for
  152. Primitive.VOID or null value for type of Primitive.NULL
  153. */
  154. public Class getType()
  155. {
  156. if ( this == Primitive.VOID )
  157. return Void.TYPE;
  158. // NULL return null as type... we currently use null type to indicate
  159. // loose typing throughout bsh.
  160. if ( this == Primitive.NULL )
  161. return null;
  162. return unboxType( value.getClass() );
  163. }
  164. /**
  165. Perform a binary operation on two Primitives or wrapper types.
  166. If both original args were Primitives return a Primitive result
  167. else it was mixed (wrapper/primitive) return the wrapper type.
  168. The exception is for boolean operations where we will return the
  169. primitive type either way.
  170. */
  171. public static Object binaryOperation(
  172. Object obj1, Object obj2, int kind)
  173. throws UtilEvalError
  174. {
  175. // special primitive types
  176. if ( obj1 == NULL || obj2 == NULL )
  177. throw new UtilEvalError(
  178. "Null value or 'null' literal in binary operation");
  179. if ( obj1 == VOID || obj2 == VOID )
  180. throw new UtilEvalError(
  181. "Undefined variable, class, or 'void' literal in binary operation");
  182. // keep track of the original types
  183. Class lhsOrgType = obj1.getClass();
  184. Class rhsOrgType = obj2.getClass();
  185. // Unwrap primitives
  186. if ( obj1 instanceof Primitive )
  187. obj1 = ((Primitive)obj1).getValue();
  188. if ( obj2 instanceof Primitive )
  189. obj2 = ((Primitive)obj2).getValue();
  190. Object[] operands = promotePrimitives(obj1, obj2);
  191. Object lhs = operands[0];
  192. Object rhs = operands[1];
  193. if(lhs.getClass() != rhs.getClass())
  194. throw new UtilEvalError("Type mismatch in operator. "
  195. + lhs.getClass() + " cannot be used with " + rhs.getClass() );
  196. Object result;
  197. try {
  198. result = binaryOperationImpl( lhs, rhs, kind );
  199. } catch ( ArithmeticException e ) {
  200. throw new UtilTargetError( "Arithemetic Exception in binary op", e);
  201. }
  202. // If both original args were Primitives return a Primitive result
  203. // else it was mixed (wrapper/primitive) return the wrapper type
  204. // Exception is for boolean result, return the primitive
  205. if ( (lhsOrgType == Primitive.class && rhsOrgType == Primitive.class)
  206. || result instanceof Boolean
  207. )
  208. return new Primitive( result );
  209. else
  210. return result;
  211. }
  212. static Object binaryOperationImpl( Object lhs, Object rhs, int kind )
  213. throws UtilEvalError
  214. {
  215. if(lhs instanceof Boolean)
  216. return booleanBinaryOperation((Boolean)lhs, (Boolean)rhs, kind);
  217. else if(lhs instanceof Integer)
  218. return intBinaryOperation( (Integer)lhs, (Integer)rhs, kind );
  219. else if(lhs instanceof Long)
  220. return longBinaryOperation((Long)lhs, (Long)rhs, kind);
  221. else if(lhs instanceof Float)
  222. return floatBinaryOperation((Float)lhs, (Float)rhs, kind);
  223. else if(lhs instanceof Double)
  224. return doubleBinaryOperation( (Double)lhs, (Double)rhs, kind);
  225. else
  226. throw new UtilEvalError("Invalid types in binary operator" );
  227. }
  228. static Boolean booleanBinaryOperation(Boolean B1, Boolean B2, int kind)
  229. {
  230. boolean lhs = B1.booleanValue();
  231. boolean rhs = B2.booleanValue();
  232. switch(kind)
  233. {
  234. case EQ:
  235. return new Boolean(lhs == rhs);
  236. case NE:
  237. return new Boolean(lhs != rhs);
  238. case BOOL_OR:
  239. case BOOL_ORX:
  240. return new Boolean( lhs || rhs );
  241. case BOOL_AND:
  242. case BOOL_ANDX:
  243. return new Boolean( lhs && rhs );
  244. default:
  245. throw new InterpreterError("unimplemented binary operator");
  246. }
  247. }
  248. // returns Object covering both Long and Boolean return types
  249. static Object longBinaryOperation(Long L1, Long L2, int kind)
  250. {
  251. long lhs = L1.longValue();
  252. long rhs = L2.longValue();
  253. switch(kind)
  254. {
  255. // boolean
  256. case LT:
  257. case LTX:
  258. return new Boolean(lhs < rhs);
  259. case GT:
  260. case GTX:
  261. return new Boolean(lhs > rhs);
  262. case EQ:
  263. return new Boolean(lhs == rhs);
  264. case LE:
  265. case LEX:
  266. return new Boolean(lhs <= rhs);
  267. case GE:
  268. case GEX:
  269. return new Boolean(lhs >= rhs);
  270. case NE:
  271. return new Boolean(lhs != rhs);
  272. // arithmetic
  273. case PLUS:
  274. return new Long(lhs + rhs);
  275. case MINUS:
  276. return new Long(lhs - rhs);
  277. case STAR:
  278. return new Long(lhs * rhs);
  279. case SLASH:
  280. return new Long(lhs / rhs);
  281. case MOD:
  282. return new Long(lhs % rhs);
  283. // bitwise
  284. case LSHIFT:
  285. case LSHIFTX:
  286. return new Long(lhs << rhs);
  287. case RSIGNEDSHIFT:
  288. case RSIGNEDSHIFTX:
  289. return new Long(lhs >> rhs);
  290. case RUNSIGNEDSHIFT:
  291. case RUNSIGNEDSHIFTX:
  292. return new Long(lhs >>> rhs);
  293. case BIT_AND:
  294. case BIT_ANDX:
  295. return new Long(lhs & rhs);
  296. case BIT_OR:
  297. case BIT_ORX:
  298. return new Long(lhs | rhs);
  299. case XOR:
  300. return new Long(lhs ^ rhs);
  301. default:
  302. throw new InterpreterError(
  303. "Unimplemented binary long operator");
  304. }
  305. }
  306. // returns Object covering both Integer and Boolean return types
  307. static Object intBinaryOperation(Integer I1, Integer I2, int kind)
  308. {
  309. int lhs = I1.intValue();
  310. int rhs = I2.intValue();
  311. switch(kind)
  312. {
  313. // boolean
  314. case LT:
  315. case LTX:
  316. return new Boolean(lhs < rhs);
  317. case GT:
  318. case GTX:
  319. return new Boolean(lhs > rhs);
  320. case EQ:
  321. return new Boolean(lhs == rhs);
  322. case LE:
  323. case LEX:
  324. return new Boolean(lhs <= rhs);
  325. case GE:
  326. case GEX:
  327. return new Boolean(lhs >= rhs);
  328. case NE:
  329. return new Boolean(lhs != rhs);
  330. // arithmetic
  331. case PLUS:
  332. return new Integer(lhs + rhs);
  333. case MINUS:
  334. return new Integer(lhs - rhs);
  335. case STAR:
  336. return new Integer(lhs * rhs);
  337. case SLASH:
  338. return new Integer(lhs / rhs);
  339. case MOD:
  340. return new Integer(lhs % rhs);
  341. // bitwise
  342. case LSHIFT:
  343. case LSHIFTX:
  344. return new Integer(lhs << rhs);
  345. case RSIGNEDSHIFT:
  346. case RSIGNEDSHIFTX:
  347. return new Integer(lhs >> rhs);
  348. case RUNSIGNEDSHIFT:
  349. case RUNSIGNEDSHIFTX:
  350. return new Integer(lhs >>> rhs);
  351. case BIT_AND:
  352. case BIT_ANDX:
  353. return new Integer(lhs & rhs);
  354. case BIT_OR:
  355. case BIT_ORX:
  356. return new Integer(lhs | rhs);
  357. case XOR:
  358. return new Integer(lhs ^ rhs);
  359. default:
  360. throw new InterpreterError(
  361. "Unimplemented binary integer operator");
  362. }
  363. }
  364. // returns Object covering both Double and Boolean return types
  365. static Object doubleBinaryOperation(Double D1, Double D2, int kind)
  366. throws UtilEvalError
  367. {
  368. double lhs = D1.doubleValue();
  369. double rhs = D2.doubleValue();
  370. switch(kind)
  371. {
  372. // boolean
  373. case LT:
  374. case LTX:
  375. return new Boolean(lhs < rhs);
  376. case GT:
  377. case GTX:
  378. return new Boolean(lhs > rhs);
  379. case EQ:
  380. return new Boolean(lhs == rhs);
  381. case LE:
  382. case LEX:
  383. return new Boolean(lhs <= rhs);
  384. case GE:
  385. case GEX:
  386. return new Boolean(lhs >= rhs);
  387. case NE:
  388. return new Boolean(lhs != rhs);
  389. // arithmetic
  390. case PLUS:
  391. return new Double(lhs + rhs);
  392. case MINUS:
  393. return new Double(lhs - rhs);
  394. case STAR:
  395. return new Double(lhs * rhs);
  396. case SLASH:
  397. return new Double(lhs / rhs);
  398. case MOD:
  399. return new Double(lhs % rhs);
  400. // can't shift floating-point values
  401. case LSHIFT:
  402. case LSHIFTX:
  403. case RSIGNEDSHIFT:
  404. case RSIGNEDSHIFTX:
  405. case RUNSIGNEDSHIFT:
  406. case RUNSIGNEDSHIFTX:
  407. throw new UtilEvalError("Can't shift doubles");
  408. default:
  409. throw new InterpreterError(
  410. "Unimplemented binary double operator");
  411. }
  412. }
  413. // returns Object covering both Long and Boolean return types
  414. static Object floatBinaryOperation(Float F1, Float F2, int kind)
  415. throws UtilEvalError
  416. {
  417. float lhs = F1.floatValue();
  418. float rhs = F2.floatValue();
  419. switch(kind)
  420. {
  421. // boolean
  422. case LT:
  423. case LTX:
  424. return new Boolean(lhs < rhs);
  425. case GT:
  426. case GTX:
  427. return new Boolean(lhs > rhs);
  428. case EQ:
  429. return new Boolean(lhs == rhs);
  430. case LE:
  431. case LEX:
  432. return new Boolean(lhs <= rhs);
  433. case GE:
  434. case GEX:
  435. return new Boolean(lhs >= rhs);
  436. case NE:
  437. return new Boolean(lhs != rhs);
  438. // arithmetic
  439. case PLUS:
  440. return new Float(lhs + rhs);
  441. case MINUS:
  442. return new Float(lhs - rhs);
  443. case STAR:
  444. return new Float(lhs * rhs);
  445. case SLASH:
  446. return new Float(lhs / rhs);
  447. case MOD:
  448. return new Float(lhs % rhs);
  449. // can't shift floats
  450. case LSHIFT:
  451. case LSHIFTX:
  452. case RSIGNEDSHIFT:
  453. case RSIGNEDSHIFTX:
  454. case RUNSIGNEDSHIFT:
  455. case RUNSIGNEDSHIFTX:
  456. throw new UtilEvalError("Can't shift floats ");
  457. default:
  458. throw new InterpreterError(
  459. "Unimplemented binary float operator");
  460. }
  461. }
  462. /**
  463. Promote primitive wrapper type to to Integer wrapper type
  464. */
  465. static Object promoteToInteger(Object wrapper )
  466. {
  467. if(wrapper instanceof Character)
  468. return new Integer(((Character)wrapper).charValue());
  469. else if((wrapper instanceof Byte) || (wrapper instanceof Short))
  470. return new Integer(((Number)wrapper).intValue());
  471. return wrapper;
  472. }
  473. /**
  474. Promote the pair of primitives to the maximum type of the two.
  475. e.g. [int,long]->[long,long]
  476. */
  477. static Object[] promotePrimitives(Object lhs, Object rhs)
  478. {
  479. lhs = promoteToInteger(lhs);
  480. rhs = promoteToInteger(rhs);
  481. if((lhs instanceof Number) && (rhs instanceof Number))
  482. {
  483. Number lnum = (Number)lhs;
  484. Number rnum = (Number)rhs;
  485. boolean b;
  486. if((b = (lnum instanceof Double)) || (rnum instanceof Double))
  487. {
  488. if(b)
  489. rhs = new Double(rnum.doubleValue());
  490. else
  491. lhs = new Double(lnum.doubleValue());
  492. }
  493. else if((b = (lnum instanceof Float)) || (rnum instanceof Float))
  494. {
  495. if(b)
  496. rhs = new Float(rnum.floatValue());
  497. else
  498. lhs = new Float(lnum.floatValue());
  499. }
  500. else if((b = (lnum instanceof Long)) || (rnum instanceof Long))
  501. {
  502. if(b)
  503. rhs = new Long(rnum.longValue());
  504. else
  505. lhs = new Long(lnum.longValue());
  506. }
  507. }
  508. return new Object[] { lhs, rhs };
  509. }
  510. public static Primitive unaryOperation(Primitive val, int kind)
  511. throws UtilEvalError
  512. {
  513. if (val == NULL)
  514. throw new UtilEvalError(
  515. "illegal use of null object or 'null' literal");
  516. if (val == VOID)
  517. throw new UtilEvalError(
  518. "illegal use of undefined object or 'void' literal");
  519. Class operandType = val.getType();
  520. Object operand = promoteToInteger(val.getValue());
  521. if ( operand instanceof Boolean )
  522. return new Primitive(booleanUnaryOperation((Boolean)operand, kind));
  523. else if(operand instanceof Integer)
  524. {
  525. int result = intUnaryOperation((Integer)operand, kind);
  526. // ++ and -- must be cast back the original type
  527. if(kind == INCR || kind == DECR)
  528. {
  529. if(operandType == Byte.TYPE)
  530. return new Primitive((byte)result);
  531. if(operandType == Short.TYPE)
  532. return new Primitive((short)result);
  533. if(operandType == Character.TYPE)
  534. return new Primitive((char)result);
  535. }
  536. return new Primitive(result);
  537. }
  538. else if(operand instanceof Long)
  539. return new Primitive(longUnaryOperation((Long)operand, kind));
  540. else if(operand instanceof Float)
  541. return new Primitive(floatUnaryOperation((Float)operand, kind));
  542. else if(operand instanceof Double)
  543. return new Primitive(doubleUnaryOperation((Double)operand, kind));
  544. else
  545. throw new InterpreterError(
  546. "An error occurred. Please call technical support.");
  547. }
  548. static boolean booleanUnaryOperation(Boolean B, int kind)
  549. throws UtilEvalError
  550. {
  551. boolean operand = B.booleanValue();
  552. switch(kind)
  553. {
  554. case BANG:
  555. return !operand;
  556. default:
  557. throw new UtilEvalError("Operator inappropriate for boolean");
  558. }
  559. }
  560. static int intUnaryOperation(Integer I, int kind)
  561. {
  562. int operand = I.intValue();
  563. switch(kind)
  564. {
  565. case PLUS:
  566. return operand;
  567. case MINUS:
  568. return -operand;
  569. case TILDE:
  570. return ~operand;
  571. case INCR:
  572. return operand + 1;
  573. case DECR:
  574. return operand - 1;
  575. default:
  576. throw new InterpreterError("bad integer unaryOperation");
  577. }
  578. }
  579. static long longUnaryOperation(Long L, int kind)
  580. {
  581. long operand = L.longValue();
  582. switch(kind)
  583. {
  584. case PLUS:
  585. return operand;
  586. case MINUS:
  587. return -operand;
  588. case TILDE:
  589. return ~operand;
  590. case INCR:
  591. return operand + 1;
  592. case DECR:
  593. return operand - 1;
  594. default:
  595. throw new InterpreterError("bad long unaryOperation");
  596. }
  597. }
  598. static float floatUnaryOperation(Float F, int kind)
  599. {
  600. float operand = F.floatValue();
  601. switch(kind)
  602. {
  603. case PLUS:
  604. return operand;
  605. case MINUS:
  606. return -operand;
  607. default:
  608. throw new InterpreterError("bad float unaryOperation");
  609. }
  610. }
  611. static double doubleUnaryOperation(Double D, int kind)
  612. {
  613. double operand = D.doubleValue();
  614. switch(kind)
  615. {
  616. case PLUS:
  617. return operand;
  618. case MINUS:
  619. return -operand;
  620. default:
  621. throw new InterpreterError("bad double unaryOperation");
  622. }
  623. }
  624. public int intValue() throws UtilEvalError
  625. {
  626. if(value instanceof Number)
  627. return((Number)value).intValue();
  628. else
  629. throw new UtilEvalError("Primitive not a number");
  630. }
  631. public boolean booleanValue() throws UtilEvalError
  632. {
  633. if(value instanceof Boolean)
  634. return((Boolean)value).booleanValue();
  635. else
  636. throw new UtilEvalError("Primitive not a boolean");
  637. }
  638. /**
  639. Determine if this primitive is a numeric type.
  640. i.e. not boolean, null, or void (but including char)
  641. */
  642. public boolean isNumber() {
  643. return ( !(value instanceof Boolean)
  644. && !(this == NULL) && !(this == VOID) );
  645. }
  646. public Number numberValue() throws UtilEvalError
  647. {
  648. Object value = this.value;
  649. // Promote character to Number type for these purposes
  650. if (value instanceof Character)
  651. value = new Integer(((Character)value).charValue());
  652. if (value instanceof Number)
  653. return (Number)value;
  654. else
  655. throw new UtilEvalError("Primitive not a number");
  656. }
  657. /**
  658. Primitives compare equal with other Primitives containing an equal
  659. wrapped value.
  660. */
  661. public boolean equals( Object obj )
  662. {
  663. if ( obj instanceof Primitive )
  664. return ((Primitive)obj).value.equals( this.value );
  665. else
  666. return false;
  667. }
  668. /**
  669. The hash of the Primitive is tied to the hash of the wrapped value but
  670. shifted so that they are not the same.
  671. */
  672. public int hashCode()
  673. {
  674. return this.value.hashCode() * 21; // arbitrary
  675. }
  676. /**
  677. Unwrap primitive values and map voids to nulls.
  678. Non Primitive types remain unchanged.
  679. @param obj object type which may be bsh.Primitive
  680. @return corresponding "normal" Java type, "unwrapping"
  681. any bsh.Primitive types to their wrapper types.
  682. */
  683. public static Object unwrap( Object obj )
  684. {
  685. // map voids to nulls for the outside world
  686. if (obj == Primitive.VOID)
  687. return null;
  688. // unwrap primitives
  689. if (obj instanceof Primitive)
  690. return((Primitive)obj).getValue();
  691. else
  692. return obj;
  693. }
  694. /*
  695. Unwrap Primitive wrappers to their java.lang wrapper values.
  696. e.g. Primitive(42) becomes Integer(42)
  697. @see #unwrap( Object )
  698. */
  699. public static Object [] unwrap( Object[] args )
  700. {
  701. Object [] oa = new Object[ args.length ];
  702. for(int i=0; i<args.length; i++)
  703. oa[i] = unwrap( args[i] );
  704. return oa;
  705. }
  706. /*
  707. */
  708. public static Object [] wrap( Object[] args, Class [] paramTypes )
  709. {
  710. if ( args == null )
  711. return null;
  712. Object [] oa = new Object[ args.length ];
  713. for(int i=0; i<args.length; i++)
  714. oa[i] = wrap( args[i], paramTypes[i] );
  715. return oa;
  716. }
  717. /**
  718. Wrap primitive values (as indicated by type param) and nulls in the
  719. Primitive class. Values not primitive or null are left unchanged.
  720. Primitive values are represented by their wrapped values in param value.
  721. <p/>
  722. The value null is mapped to Primitive.NULL.
  723. Any value specified with type Void.TYPE is mapped to Primitive.VOID.
  724. */
  725. public static Object wrap(
  726. Object value, Class type )
  727. {
  728. if ( type == Void.TYPE )
  729. return Primitive.VOID;
  730. if ( value == null )
  731. return Primitive.NULL;
  732. if ( type.isPrimitive() )
  733. return new Primitive( value );
  734. return value;
  735. }
  736. /**
  737. Get the appropriate default value per JLS 4.5.4
  738. */
  739. public static Primitive getDefaultValue( Class type )
  740. {
  741. if ( type == null || !type.isPrimitive() )
  742. return Primitive.NULL;
  743. if ( type == Boolean.TYPE )
  744. return new Primitive( false );
  745. // non boolean primitive, get appropriate flavor of zero
  746. try {
  747. return new Primitive((int)0).castToType( type, Types.CAST );
  748. } catch ( UtilEvalError e ) {
  749. throw new InterpreterError( "bad cast" );
  750. }
  751. }
  752. /**
  753. Get the corresponding java.lang wrapper class for the primitive TYPE
  754. class.
  755. e.g. Integer.TYPE -> Integer.class
  756. */
  757. public static Class boxType( Class primitiveType )
  758. {
  759. Class c = (Class)wrapperMap.get( primitiveType );
  760. if ( c != null )
  761. return c;
  762. throw new InterpreterError(
  763. "Not a primitive type: "+ primitiveType );
  764. }
  765. /**
  766. Get the corresponding primitive TYPE class for the java.lang wrapper
  767. class type.
  768. e.g. Integer.class -> Integer.TYPE
  769. */
  770. public static Class unboxType( Class wrapperType )
  771. {
  772. Class c = (Class)wrapperMap.get( wrapperType );
  773. if ( c != null )
  774. return c;
  775. throw new InterpreterError(
  776. "Not a primitive wrapper type: "+wrapperType );
  777. }
  778. /**
  779. Cast this bsh.Primitive value to a new bsh.Primitive value
  780. This is usually a numeric type cast. Other cases include:
  781. A boolean can be cast to boolen
  782. null can be cast to any object type and remains null
  783. Attempting to cast a void causes an exception
  784. @param toType is the java object or primitive TYPE class
  785. */
  786. public Primitive castToType( Class toType, int operation )
  787. throws UtilEvalError
  788. {
  789. return castPrimitive(
  790. toType, getType()/*fromType*/, this/*fromValue*/,
  791. false/*checkOnly*/, operation );
  792. }
  793. /*
  794. Cast or check a cast of a primitive type to another type.
  795. Normally both types are primitive (e.g. numeric), but a null value
  796. (no type) may be cast to any type.
  797. <p/>
  798. @param toType is the target type of the cast. It is normally a
  799. java primitive TYPE, but in the case of a null cast can be any object
  800. type.
  801. @param fromType is the java primitive TYPE type of the primitive to be
  802. cast or null, to indicate that the fromValue was null or void.
  803. @param fromValue is, optionally, the value to be converted. If
  804. checkOnly is true fromValue must be null. If checkOnly is false,
  805. fromValue must be non-null (Primitive.NULL is of course valid).
  806. */
  807. static Primitive castPrimitive(
  808. Class toType, Class fromType, Primitive fromValue,
  809. boolean checkOnly, int operation )
  810. throws UtilEvalError
  811. {
  812. /*
  813. Lots of preconditions checked here...
  814. Once things are running smoothly we might comment these out
  815. (That's what assertions are for).
  816. */
  817. if ( checkOnly && fromValue != null )
  818. throw new InterpreterError("bad cast param 1");
  819. if ( !checkOnly && fromValue == null )
  820. throw new InterpreterError("bad cast param 2");
  821. if ( fromType != null && !fromType.isPrimitive() )
  822. throw new InterpreterError("bad fromType:" +fromType);
  823. if ( fromValue == Primitive.NULL && fromType != null )
  824. throw new InterpreterError("inconsistent args 1");
  825. if ( fromValue == Primitive.VOID && fromType != Void.TYPE )
  826. throw new InterpreterError("inconsistent args 2");
  827. // can't cast void to anything
  828. if ( fromType == Void.TYPE )
  829. if ( checkOnly )
  830. return Types.INVALID_CAST;
  831. else
  832. throw Types.castError( Reflect.normalizeClassName(toType),
  833. "void value", operation );
  834. // unwrap Primitive fromValue to its wrapper value, etc.
  835. Object value = null;
  836. if ( fromValue != null )
  837. value = fromValue.getValue();
  838. if ( toType.isPrimitive() )
  839. {
  840. // Trying to cast null to primitive type?
  841. if ( fromType == null )
  842. if ( checkOnly )
  843. return Types.INVALID_CAST;
  844. else
  845. throw Types.castError(
  846. "primitive type:" + toType, "Null value", operation );
  847. // fall through
  848. } else
  849. {
  850. // Trying to cast primitive to an object type
  851. // Primitive.NULL can be cast to any object type
  852. if ( fromType == null )
  853. return checkOnly ? Types.VALID_CAST :
  854. Primitive.NULL;
  855. if ( checkOnly )
  856. return Types.INVALID_CAST;
  857. else
  858. throw Types.castError(
  859. "object type:" + toType, "primitive value", operation);
  860. }
  861. // can only cast boolean to boolean
  862. if ( fromType == Boolean.TYPE )
  863. {
  864. if ( toType != Boolean.TYPE )
  865. if ( checkOnly )
  866. return Types.INVALID_CAST;
  867. else
  868. throw Types.castError( toType, fromType, operation );
  869. return checkOnly ? Types.VALID_CAST :
  870. fromValue;
  871. }
  872. // Do numeric cast
  873. // Only allow legal Java assignment unless we're a CAST operation
  874. if ( operation == Types.ASSIGNMENT
  875. && !Types.isJavaAssignable( toType, fromType )
  876. ) {
  877. if ( checkOnly )
  878. return Types.INVALID_CAST;
  879. else
  880. throw Types.castError( toType, fromType, operation );
  881. }
  882. return checkOnly ? Types.VALID_CAST :
  883. new Primitive( castWrapper(toType, value) );
  884. }
  885. public static boolean isWrapperType( Class type )
  886. {
  887. return wrapperMap.get( type ) != null && !type.isPrimitive();
  888. }
  889. /**
  890. Cast a primitive value represented by its java.lang wrapper type to the
  891. specified java.lang wrapper type. e.g. Byte(5) to Integer(5) or
  892. Integer(5) to Byte(5)
  893. @param toType is the java TYPE type
  894. @param value is the value in java.lang wrapper.
  895. value may not be null.
  896. */
  897. static Object castWrapper(
  898. Class toType, Object value )
  899. {
  900. if ( !toType.isPrimitive() )
  901. throw new InterpreterError("invalid type in castWrapper: "+toType);
  902. if ( value == null )
  903. throw new InterpreterError("null value in castWrapper, guard");
  904. if ( value instanceof Boolean )
  905. {
  906. if ( toType != Boolean.TYPE )
  907. throw new InterpreterError("bad wrapper cast of boolean");
  908. else
  909. return value;
  910. }
  911. // first promote char to Number type to avoid duplicating code
  912. if ( value instanceof Character )
  913. value = new Integer(((Character)value).charValue());
  914. if ( !(value instanceof Number) )
  915. throw new InterpreterError("bad type in cast");
  916. Number number = (Number)value;
  917. if (toType == Byte.TYPE)
  918. return new Byte(number.byteValue());
  919. if (toType == Short.TYPE)
  920. return new Short(number.shortValue());
  921. if (toType == Character.TYPE)
  922. return new Character((char)number.intValue());
  923. if (toType == Integer.TYPE)
  924. return new Integer(number.intValue());
  925. if (toType == Long.TYPE)
  926. return new Long(number.longValue());
  927. if (toType == Float.TYPE)
  928. return new Float(number.floatValue());
  929. if (toType == Double.TYPE)
  930. return new Double(number.doubleValue());
  931. throw new InterpreterError("error in wrapper cast");
  932. }
  933. }