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

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

#
Java | 530 lines | 253 code | 49 blank | 228 comment | 140 complexity | d5fff6aeecf4d871faab6bf214461a0b 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. /**
  35. Static routines supporing type comparison and conversion in BeanShell.
  36. The following are notes on type comparison and conversion in BeanShell.
  37. */
  38. class Types
  39. {
  40. /*
  41. Type conversion identifiers. An ASSIGNMENT allows conversions that would
  42. normally happen on assignment. A CAST performs numeric conversions to smaller
  43. types (as in an explicit Java cast) and things allowed only in variable and array
  44. declarations (e.g. byte b = 42;)
  45. */
  46. static final int CAST=0, ASSIGNMENT=1;
  47. static final int
  48. JAVA_BASE_ASSIGNABLE = 1,
  49. JAVA_BOX_TYPES_ASSIGABLE = 2,
  50. JAVA_VARARGS_ASSIGNABLE = 3,
  51. BSH_ASSIGNABLE = 4;
  52. static final int
  53. FIRST_ROUND_ASSIGNABLE = JAVA_BASE_ASSIGNABLE,
  54. LAST_ROUND_ASSIGNABLE = BSH_ASSIGNABLE;
  55. /**
  56. Special value that indicates by identity that the result of a cast
  57. operation was a valid cast. This is used by castObject() and
  58. castPrimitive() in the checkOnly mode of operation. This value is a
  59. Primitive type so that it can be returned by castPrimitive.
  60. */
  61. static Primitive VALID_CAST = new Primitive(1);
  62. static Primitive INVALID_CAST = new Primitive(-1);
  63. /**
  64. Get the Java types of the arguments.
  65. */
  66. public static Class[] getTypes( Object[] args )
  67. {
  68. if ( args == null )
  69. return new Class[0];
  70. Class[] types = new Class[ args.length ];
  71. for( int i=0; i<args.length; i++ )
  72. {
  73. if ( args[i] == null )
  74. types[i] = null;
  75. else
  76. if ( args[i] instanceof Primitive )
  77. types[i] = ((Primitive)args[i]).getType();
  78. else
  79. types[i] = args[i].getClass();
  80. }
  81. return types;
  82. }
  83. /**
  84. Is the 'from' signature (argument types) assignable to the 'to'
  85. signature (candidate method types)
  86. This method handles the special case of null values in 'to' types
  87. indicating a loose type and matching anything.
  88. */
  89. /* Should check for strict java here and limit to isJavaAssignable() */
  90. static boolean isSignatureAssignable( Class[] from, Class[] to, int round )
  91. {
  92. if ( round != JAVA_VARARGS_ASSIGNABLE && from.length != to.length )
  93. return false;
  94. switch ( round )
  95. {
  96. case JAVA_BASE_ASSIGNABLE:
  97. for( int i=0; i<from.length; i++ )
  98. if ( !isJavaBaseAssignable( to[i], from[i] ) )
  99. return false;
  100. return true;
  101. case JAVA_BOX_TYPES_ASSIGABLE:
  102. for( int i=0; i<from.length; i++ )
  103. if ( !isJavaBoxTypesAssignable( to[i], from[i] ) )
  104. return false;
  105. return true;
  106. case JAVA_VARARGS_ASSIGNABLE:
  107. return isSignatureVarargsAssignable( from, to );
  108. case BSH_ASSIGNABLE:
  109. for( int i=0; i<from.length; i++ )
  110. if ( !isBshAssignable( to[i], from[i] ) )
  111. return false;
  112. return true;
  113. default:
  114. throw new InterpreterError("bad case");
  115. }
  116. }
  117. private static boolean isSignatureVarargsAssignable(
  118. Class[] from, Class[] to )
  119. {
  120. return false;
  121. }
  122. /**
  123. Test if a conversion of the rhsType type to the lhsType type is legal via
  124. standard Java assignment conversion rules (i.e. without a cast).
  125. The rules include Java 5 autoboxing/unboxing.
  126. <p/>
  127. For Java primitive TYPE classes this method takes primitive promotion
  128. into account. The ordinary Class.isAssignableFrom() does not take
  129. primitive promotion conversions into account. Note that Java allows
  130. additional assignments without a cast in combination with variable
  131. declarations and array allocations. Those are handled elsewhere
  132. (maybe should be here with a flag?)
  133. <p/>
  134. This class accepts a null rhsType type indicating that the rhsType was the
  135. value Primitive.NULL and allows it to be assigned to any reference lhsType
  136. type (non primitive).
  137. <p/>
  138. Note that the getAssignableForm() method is the primary bsh method for
  139. checking assignability. It adds additional bsh conversions, etc.
  140. @see #isBshAssignable( Class, Class )
  141. @param lhsType assigning from rhsType to lhsType
  142. @param rhsType assigning from rhsType to lhsType
  143. */
  144. static boolean isJavaAssignable( Class lhsType, Class rhsType ) {
  145. return isJavaBaseAssignable( lhsType, rhsType )
  146. || isJavaBoxTypesAssignable( lhsType, rhsType );
  147. }
  148. /**
  149. Is the assignment legal via original Java (up to version 1.4)
  150. assignment rules, not including auto-boxing/unboxing.
  151. @param rhsType may be null to indicate primitive null value
  152. */
  153. static boolean isJavaBaseAssignable( Class lhsType, Class rhsType )
  154. {
  155. /*
  156. Assignment to loose type, defer to bsh extensions
  157. Note: we could shortcut this here:
  158. if ( lhsType == null ) return true;
  159. rather than forcing another round. It's not strictly a Java issue,
  160. so does it belong here?
  161. */
  162. if ( lhsType == null )
  163. return false;
  164. // null rhs type corresponds to type of Primitive.NULL
  165. // assignable to any object type
  166. if ( rhsType == null )
  167. return !lhsType.isPrimitive();
  168. if ( lhsType.isPrimitive() && rhsType.isPrimitive() )
  169. {
  170. if ( lhsType == rhsType )
  171. return true;
  172. // handle primitive widening conversions - JLS 5.1.2
  173. if ( (rhsType == Byte.TYPE) &&
  174. (lhsType == Short.TYPE || lhsType == Integer.TYPE
  175. || lhsType == Long.TYPE || lhsType == Float.TYPE
  176. || lhsType == Double.TYPE))
  177. return true;
  178. if ( (rhsType == Short.TYPE) &&
  179. (lhsType == Integer.TYPE || lhsType == Long.TYPE ||
  180. lhsType == Float.TYPE || lhsType == Double.TYPE))
  181. return true;
  182. if ((rhsType == Character.TYPE) &&
  183. (lhsType == Integer.TYPE || lhsType == Long.TYPE ||
  184. lhsType == Float.TYPE || lhsType == Double.TYPE))
  185. return true;
  186. if ((rhsType == Integer.TYPE) &&
  187. (lhsType == Long.TYPE || lhsType == Float.TYPE ||
  188. lhsType == Double.TYPE))
  189. return true;
  190. if ((rhsType == Long.TYPE) &&
  191. (lhsType == Float.TYPE || lhsType == Double.TYPE))
  192. return true;
  193. if ((rhsType == Float.TYPE) && (lhsType == Double.TYPE))
  194. return true;
  195. }
  196. else
  197. if ( lhsType.isAssignableFrom(rhsType) )
  198. return true;
  199. return false;
  200. }
  201. /**
  202. Determine if the type is assignable via Java boxing/unboxing rules.
  203. */
  204. static boolean isJavaBoxTypesAssignable(
  205. Class lhsType, Class rhsType )
  206. {
  207. // Assignment to loose type... defer to bsh extensions
  208. if ( lhsType == null )
  209. return false;
  210. // prim can be boxed and assigned to Object
  211. if ( lhsType == Object.class )
  212. return true;
  213. // prim numeric type can be boxed and assigned to number
  214. if ( lhsType == Number.class
  215. && rhsType != Character.TYPE
  216. && rhsType != Boolean.TYPE
  217. )
  218. return true;
  219. // General case prim type to wrapper or vice versa.
  220. // I don't know if this is faster than a flat list of 'if's like above.
  221. // wrapperMap maps both prim to wrapper and wrapper to prim types,
  222. // so this test is symmetric
  223. if ( Primitive.wrapperMap.get( lhsType ) == rhsType )
  224. return true;
  225. return false;
  226. }
  227. /**
  228. Test if a type can be converted to another type via BeanShell
  229. extended syntax rules (a superset of Java conversion rules).
  230. */
  231. static boolean isBshAssignable( Class toType, Class fromType )
  232. {
  233. try {
  234. return castObject(
  235. toType, fromType, null/*fromValue*/,
  236. ASSIGNMENT, true/*checkOnly*/
  237. ) == VALID_CAST;
  238. } catch ( UtilEvalError e ) {
  239. // This should not happen with checkOnly true
  240. throw new InterpreterError("err in cast check: "+e);
  241. }
  242. }
  243. /**
  244. Attempt to cast an object instance to a new type if possible via
  245. BeanShell extended syntax rules. These rules are always a superset of
  246. Java conversion rules. If you wish to impose context sensitive
  247. conversion rules then you must test before calling this method.
  248. <p/>
  249. This method can handle fromValue Primitive types (representing
  250. primitive casts) as well as fromValue object casts requiring interface
  251. generation, etc.
  252. @param toType the class type of the cast result, which may include
  253. primitive types, e.g. Byte.TYPE
  254. @param fromValue an Object or bsh.Primitive primitive value (including
  255. Primitive.NULL or Primitive.VOID )
  256. @see #isBshAssignable( Class, Class )
  257. */
  258. public static Object castObject(
  259. Object fromValue, Class toType, int operation )
  260. throws UtilEvalError
  261. {
  262. if ( fromValue == null )
  263. throw new InterpreterError("null fromValue");
  264. Class fromType =
  265. fromValue instanceof Primitive ?
  266. ((Primitive)fromValue).getType()
  267. : fromValue.getClass();
  268. return castObject(
  269. toType, fromType, fromValue, operation, false/*checkonly*/ );
  270. }
  271. /**
  272. Perform a type conversion or test if a type conversion is possible with
  273. respect to BeanShell extended rules. These rules are always a superset of
  274. the Java language rules, so this method can also perform (but not test)
  275. any Java language assignment or cast conversion.
  276. <p/>
  277. This method can perform the functionality of testing if an assignment
  278. or cast is ultimately possible (with respect to BeanShell) as well as the
  279. functionality of performing the necessary conversion of a value based
  280. on the specified target type. This combined functionality is done for
  281. expediency and could be separated later.
  282. <p/>
  283. Other methods such as isJavaAssignable() should be used to determine the
  284. suitability of an assignment in a fine grained or restrictive way based
  285. on context before calling this method
  286. <p/>
  287. A CAST is stronger than an ASSIGNMENT operation in that it will attempt to
  288. perform primtive operations that cast to a smaller type. e.g. (byte)myLong;
  289. These are used in explicit primitive casts, primitive delclarations and
  290. array declarations. I don't believe there are any object conversions which are
  291. different between ASSIGNMENT and CAST (e.g. scripted object to interface proxy
  292. in bsh is done on assignment as well as cast).
  293. <p/>
  294. This method does not obey strictJava(), you must test first before
  295. using this method if you care. (See #isJavaAssignable()).
  296. <p/>
  297. @param toType the class type of the cast result, which may include
  298. primitive types, e.g. Byte.TYPE. toType may be null to indicate a
  299. loose type assignment (which matches any fromType).
  300. @param fromType is the class type of the value to be cast including
  301. java primitive TYPE classes for primitives.
  302. If fromValue is (or would be) Primitive.NULL then fromType should be null.
  303. @param fromValue an Object or bsh.Primitive primitive value (including
  304. Primitive.NULL or Primitive.VOID )
  305. @param checkOnly If checkOnly is true then fromValue must be null.
  306. FromType is checked for the cast to toType...
  307. If checkOnly is false then fromValue must be non-null
  308. (Primitive.NULL is ok) and the actual cast is performed.
  309. @throws UtilEvalError on invalid assignment (when operation is
  310. assignment ).
  311. @throws UtilTargetError wrapping ClassCastException on cast error
  312. (when operation is cast)
  313. @param operation is Types.CAST or Types.ASSIGNMENT
  314. @see org.gjt.sp.jedit.bsh.Primitive.getType()
  315. */
  316. /*
  317. Notes: This method is currently responsible for auto-boxing/unboxing
  318. conversions... Where does that need to go?
  319. */
  320. private static Object castObject(
  321. Class toType, Class fromType, Object fromValue,
  322. int operation, boolean checkOnly )
  323. throws UtilEvalError
  324. {
  325. /*
  326. Lots of preconditions checked here...
  327. Once things are running smoothly we might comment these out
  328. (That's what assertions are for).
  329. */
  330. if ( checkOnly && fromValue != null )
  331. throw new InterpreterError("bad cast params 1");
  332. if ( !checkOnly && fromValue == null )
  333. throw new InterpreterError("bad cast params 2");
  334. if ( fromType == Primitive.class )
  335. throw new InterpreterError("bad from Type, need to unwrap");
  336. if ( fromValue == Primitive.NULL && fromType != null )
  337. throw new InterpreterError("inconsistent args 1");
  338. if ( fromValue == Primitive.VOID && fromType != Void.TYPE )
  339. throw new InterpreterError("inconsistent args 2");
  340. if ( toType == Void.TYPE )
  341. throw new InterpreterError("loose toType should be null");
  342. // assignment to loose type, void type, or exactly same type
  343. if ( toType == null || toType == fromType )
  344. return checkOnly ? VALID_CAST :
  345. fromValue;
  346. // Casting to primitive type
  347. if ( toType.isPrimitive() )
  348. {
  349. if ( fromType == Void.TYPE || fromType == null
  350. || fromType.isPrimitive() )
  351. {
  352. // Both primitives, do primitive cast
  353. return Primitive.castPrimitive(
  354. toType, fromType, (Primitive)fromValue,
  355. checkOnly, operation );
  356. } else
  357. {
  358. if ( Primitive.isWrapperType( fromType ) )
  359. {
  360. // wrapper to primitive
  361. // Convert value to Primitive and check/cast it.
  362. //Object r = checkOnly ? VALID_CAST :
  363. Class unboxedFromType = Primitive.unboxType( fromType );
  364. Primitive primFromValue;
  365. if ( checkOnly )
  366. primFromValue = null; // must be null in checkOnly
  367. else
  368. primFromValue = (Primitive)Primitive.wrap(
  369. fromValue, unboxedFromType );
  370. return Primitive.castPrimitive(
  371. toType, unboxedFromType, primFromValue,
  372. checkOnly, operation );
  373. } else
  374. {
  375. // Cannot cast from arbitrary object to primitive
  376. if ( checkOnly )
  377. return INVALID_CAST;
  378. else
  379. throw castError( toType, fromType, operation );
  380. }
  381. }
  382. }
  383. // Else, casting to reference type
  384. // Casting from primitive or void (to reference type)
  385. if ( fromType == Void.TYPE || fromType == null
  386. || fromType.isPrimitive() )
  387. {
  388. // cast from primitive to wrapper type
  389. if ( Primitive.isWrapperType( toType )
  390. && fromType != Void.TYPE && fromType != null )
  391. {
  392. // primitive to wrapper type
  393. return checkOnly ? VALID_CAST :
  394. Primitive.castWrapper(
  395. Primitive.unboxType(toType),
  396. ((Primitive)fromValue).getValue() );
  397. }
  398. // Primitive (not null or void) to Object.class type
  399. if ( toType == Object.class
  400. && fromType != Void.TYPE && fromType != null )
  401. {
  402. // box it
  403. return checkOnly ? VALID_CAST :
  404. ((Primitive)fromValue).getValue();
  405. }
  406. // Primitive to arbitrary object type.
  407. // Allow Primitive.castToType() to handle it as well as cases of
  408. // Primitive.NULL and Primitive.VOID
  409. return Primitive.castPrimitive(
  410. toType, fromType, (Primitive)fromValue, checkOnly, operation );
  411. }
  412. // If type already assignable no cast necessary
  413. // We do this last to allow various errors above to be caught.
  414. // e.g cast Primitive.Void to Object would pass this
  415. if ( toType.isAssignableFrom( fromType ) )
  416. return checkOnly ? VALID_CAST :
  417. fromValue;
  418. // Can we use the proxy mechanism to cast a bsh.This to
  419. // the correct interface?
  420. if ( toType.isInterface()
  421. && org.gjt.sp.jedit.bsh.This.class.isAssignableFrom( fromType )
  422. && Capabilities.canGenerateInterfaces()
  423. )
  424. return checkOnly ? VALID_CAST :
  425. ((org.gjt.sp.jedit.bsh.This)fromValue).getInterface( toType );
  426. // Both numeric wrapper types?
  427. // Try numeric style promotion wrapper cast
  428. if ( Primitive.isWrapperType( toType )
  429. && Primitive.isWrapperType( fromType )
  430. )
  431. return checkOnly ? VALID_CAST :
  432. Primitive.castWrapper( toType, fromValue );
  433. if ( checkOnly )
  434. return INVALID_CAST;
  435. else
  436. throw castError( toType, fromType , operation );
  437. }
  438. /**
  439. Return a UtilEvalError or UtilTargetError wrapping a ClassCastException
  440. describing an illegal assignment or illegal cast, respectively.
  441. */
  442. static UtilEvalError castError(
  443. Class lhsType, Class rhsType, int operation )
  444. {
  445. return castError(
  446. Reflect.normalizeClassName(lhsType),
  447. Reflect.normalizeClassName(rhsType), operation );
  448. }
  449. static UtilEvalError castError(
  450. String lhs, String rhs, int operation )
  451. {
  452. if ( operation == ASSIGNMENT )
  453. return new UtilEvalError (
  454. "Can't assign " + rhs + " to "+ lhs );
  455. Exception cce = new ClassCastException(
  456. "Cannot cast " + rhs + " to " + lhs );
  457. return new UtilTargetError( cce );
  458. }
  459. }