PageRenderTime 53ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/jEdit/tags/jedit-4-2-pre14/bsh/Primitive.java

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