PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

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

#
Java | 312 lines | 193 code | 31 blank | 88 comment | 18 complexity | e0bb508175bd2127e065f15112f1cb47 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.lang.reflect.Array;
  35. import java.lang.reflect.InvocationTargetException;
  36. /**
  37. New object, new array, or inner class style allocation with body.
  38. */
  39. class BSHAllocationExpression extends SimpleNode
  40. {
  41. BSHAllocationExpression(int id) { super(id); }
  42. private static int innerClassCount = 0;
  43. public Object eval( CallStack callstack, Interpreter interpreter)
  44. throws EvalError
  45. {
  46. // type is either a class name or a primitive type
  47. SimpleNode type = (SimpleNode)jjtGetChild(0);
  48. // args is either constructor arguments or array dimensions
  49. SimpleNode args = (SimpleNode)jjtGetChild(1);
  50. if ( type instanceof BSHAmbiguousName )
  51. {
  52. BSHAmbiguousName name = (BSHAmbiguousName)type;
  53. if (args instanceof BSHArguments)
  54. return objectAllocation(name, (BSHArguments)args,
  55. callstack, interpreter );
  56. else
  57. return objectArrayAllocation(name, (BSHArrayDimensions)args,
  58. callstack, interpreter );
  59. }
  60. else
  61. return primitiveArrayAllocation((BSHPrimitiveType)type,
  62. (BSHArrayDimensions)args, callstack, interpreter );
  63. }
  64. private Object objectAllocation(
  65. BSHAmbiguousName nameNode, BSHArguments argumentsNode,
  66. CallStack callstack, Interpreter interpreter
  67. )
  68. throws EvalError
  69. {
  70. NameSpace namespace = callstack.top();
  71. Object[] args = argumentsNode.getArguments( callstack, interpreter );
  72. if ( args == null)
  73. throw new EvalError( "Null args in new.", this, callstack );
  74. // Look for scripted class object
  75. Object obj = nameNode.toObject(
  76. callstack, interpreter, false/* force class*/ );
  77. // Try regular class
  78. obj = nameNode.toObject(
  79. callstack, interpreter, true/*force class*/ );
  80. Class type = null;
  81. if ( obj instanceof ClassIdentifier )
  82. type = ((ClassIdentifier)obj).getTargetClass();
  83. else
  84. throw new EvalError(
  85. "Unknown class: "+nameNode.text, this, callstack );
  86. // Is an inner class style object allocation
  87. boolean hasBody = jjtGetNumChildren() > 2;
  88. if ( hasBody )
  89. {
  90. BSHBlock body = (BSHBlock)jjtGetChild(2);
  91. if ( type.isInterface() )
  92. return constructWithInterfaceBody(
  93. type, args, body, callstack, interpreter );
  94. else
  95. return constructWithClassBody(
  96. type, args, body, callstack, interpreter );
  97. } else
  98. return constructObject( type, args, callstack );
  99. }
  100. private Object constructObject(
  101. Class type, Object[] args, CallStack callstack )
  102. throws EvalError
  103. {
  104. Object obj;
  105. try {
  106. obj = Reflect.constructObject( type, args );
  107. } catch ( ReflectError e) {
  108. throw new EvalError(
  109. "Constructor error: " + e.getMessage(), this, callstack );
  110. } catch(InvocationTargetException e) {
  111. // No need to wrap this debug
  112. Interpreter.debug("The constructor threw an exception:\n\t" +
  113. e.getTargetException());
  114. throw new TargetError(
  115. "Object constructor", e.getTargetException(),
  116. this, callstack, true);
  117. }
  118. String className = type.getName();
  119. // Is it an inner class?
  120. if ( className.indexOf("$") == -1 )
  121. return obj;
  122. // Temporary hack to support inner classes
  123. // If the obj is a non-static inner class then import the context...
  124. // This is not a sufficient emulation of inner classes.
  125. // Replace this later...
  126. // work through to class 'this'
  127. This ths = callstack.top().getThis( null );
  128. NameSpace instanceNameSpace =
  129. Name.getClassNameSpace( ths.getNameSpace() );
  130. // Change the parent (which was the class static) to the class instance
  131. // We really need to check if we're a static inner class here first...
  132. // but for some reason Java won't show the static modifier on our
  133. // fake inner classes... could generate a flag field.
  134. if ( instanceNameSpace != null
  135. && className.startsWith( instanceNameSpace.getName() +"$")
  136. )
  137. {
  138. try {
  139. ClassGenerator.getClassGenerator().setInstanceNameSpaceParent(
  140. obj, className, instanceNameSpace );
  141. } catch ( UtilEvalError e ) {
  142. throw e.toEvalError( this, callstack );
  143. }
  144. }
  145. return obj;
  146. }
  147. private Object constructWithClassBody(
  148. Class type, Object[] args, BSHBlock block,
  149. CallStack callstack, Interpreter interpreter )
  150. throws EvalError
  151. {
  152. String name = callstack.top().getName() + "$" + (++innerClassCount);
  153. Modifiers modifiers = new Modifiers();
  154. modifiers.addModifier( Modifiers.CLASS, "public" );
  155. Class clas;
  156. try {
  157. clas = ClassGenerator.getClassGenerator() .generateClass(
  158. name, modifiers, null/*interfaces*/, type/*superClass*/,
  159. block, false/*isInterface*/, callstack, interpreter );
  160. } catch ( UtilEvalError e ) {
  161. throw e.toEvalError( this, callstack );
  162. }
  163. try {
  164. return Reflect.constructObject( clas, args );
  165. } catch ( Exception e ) {
  166. if ( e instanceof InvocationTargetException )
  167. e = (Exception)((InvocationTargetException)e)
  168. .getTargetException();
  169. throw new EvalError(
  170. "Error constructing inner class instance: "+e, this, callstack
  171. );
  172. }
  173. }
  174. private Object constructWithInterfaceBody(
  175. Class type, Object[] args, BSHBlock body,
  176. CallStack callstack, Interpreter interpreter )
  177. throws EvalError
  178. {
  179. NameSpace namespace = callstack.top();
  180. NameSpace local = new NameSpace(namespace, "AnonymousBlock");
  181. callstack.push(local);
  182. body.eval( callstack, interpreter, true/*overrideNamespace*/ );
  183. callstack.pop();
  184. // statical import fields from the interface so that code inside
  185. // can refer to the fields directly (e.g. HEIGHT)
  186. local.importStatic( type );
  187. try {
  188. return local.getThis(interpreter).getInterface( type );
  189. } catch ( UtilEvalError e ) {
  190. throw e.toEvalError( this, callstack );
  191. }
  192. }
  193. private Object objectArrayAllocation(
  194. BSHAmbiguousName nameNode, BSHArrayDimensions dimensionsNode,
  195. CallStack callstack, Interpreter interpreter
  196. )
  197. throws EvalError
  198. {
  199. NameSpace namespace = callstack.top();
  200. Class type = nameNode.toClass( callstack, interpreter );
  201. if ( type == null )
  202. throw new EvalError( "Class " + nameNode.getName(namespace)
  203. + " not found.", this, callstack );
  204. return arrayAllocation( dimensionsNode, type, callstack, interpreter );
  205. }
  206. private Object primitiveArrayAllocation(
  207. BSHPrimitiveType typeNode, BSHArrayDimensions dimensionsNode,
  208. CallStack callstack, Interpreter interpreter
  209. )
  210. throws EvalError
  211. {
  212. Class type = typeNode.getType();
  213. return arrayAllocation( dimensionsNode, type, callstack, interpreter );
  214. }
  215. private Object arrayAllocation(
  216. BSHArrayDimensions dimensionsNode, Class type,
  217. CallStack callstack, Interpreter interpreter )
  218. throws EvalError
  219. {
  220. /*
  221. dimensionsNode can return either a fully intialized array or VOID.
  222. when VOID the prescribed array dimensions (defined and undefined)
  223. are contained in the node.
  224. */
  225. Object result = dimensionsNode.eval( type, callstack, interpreter );
  226. if ( result != Primitive.VOID )
  227. return result;
  228. else
  229. return arrayNewInstance( type, dimensionsNode, callstack );
  230. }
  231. /**
  232. Create an array of the dimensions specified in dimensionsNode.
  233. dimensionsNode may contain a number of "undefined" as well as "defined"
  234. dimensions.
  235. <p>
  236. Background: in Java arrays are implemented in arrays-of-arrays style
  237. where, for example, a two dimensional array is a an array of arrays of
  238. some base type. Each dimension-type has a Java class type associated
  239. with it... so if foo = new int[5][5] then the type of foo is
  240. int [][] and the type of foo[0] is int[], etc. Arrays may also be
  241. specified with undefined trailing dimensions - meaning that the lower
  242. order arrays are not allocated as objects. e.g.
  243. if foo = new int [5][]; then foo[0] == null //true; and can later be
  244. assigned with the appropriate type, e.g. foo[0] = new int[5];
  245. (See Learning Java, O'Reilly & Associates more background).
  246. <p>
  247. To create an array with undefined trailing dimensions using the
  248. reflection API we must use an array type to represent the lower order
  249. (undefined) dimensions as the "base" type for the array creation...
  250. Java will then create the correct type by adding the dimensions of the
  251. base type to specified allocated dimensions yielding an array of
  252. dimensionality base + specified with the base dimensons unallocated.
  253. To create the "base" array type we simply create a prototype, zero
  254. length in each dimension, array and use it to get its class
  255. (Actually, I think there is a way we could do it with Class.forName()
  256. but I don't trust this). The code is simpler than the explanation...
  257. see below.
  258. */
  259. private Object arrayNewInstance(
  260. Class type, BSHArrayDimensions dimensionsNode, CallStack callstack )
  261. throws EvalError
  262. {
  263. if ( dimensionsNode.numUndefinedDims > 0 )
  264. {
  265. Object proto = Array.newInstance(
  266. type, new int [dimensionsNode.numUndefinedDims] ); // zeros
  267. type = proto.getClass();
  268. }
  269. try {
  270. return Array.newInstance(
  271. type, dimensionsNode.definedDimensions);
  272. } catch( NegativeArraySizeException e1 ) {
  273. throw new TargetError( e1, this, callstack );
  274. } catch( Exception e ) {
  275. throw new EvalError("Can't construct primitive array: " +
  276. e.getMessage(), this, callstack);
  277. }
  278. }
  279. }