PageRenderTime 47ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/jEdit/tags/jedit-4-3-pre5/bsh/ClassGeneratorUtil.java

#
Java | 1137 lines | 704 code | 145 blank | 288 comment | 139 complexity | 8a43f3e3bf9acece67d6438a1b472434 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 org.objectweb.asm.Constants;
  35. import org.objectweb.asm.ClassWriter;
  36. import org.objectweb.asm.Label;
  37. import org.objectweb.asm.CodeVisitor;
  38. import org.objectweb.asm.Type;
  39. import java.lang.reflect.Constructor;
  40. import java.lang.reflect.Method;
  41. import java.lang.reflect.InvocationTargetException;
  42. import java.util.ArrayList;
  43. import java.util.List;
  44. /**
  45. ClassGeneratorUtil utilizes the ASM (www.objectweb.org) bytecode generator
  46. by Eric Bruneton in order to generate class "stubs" for BeanShell at
  47. runtime.
  48. <p>
  49. Stub classes contain all of the fields of a BeanShell scripted class
  50. as well as two "callback" references to BeanShell namespaces: one for
  51. static methods and one for instance methods. Methods of the class are
  52. delegators which invoke corresponding methods on either the static or
  53. instance bsh object and then unpack and return the results. The static
  54. namespace utilizes a static import to delegate variable access to the
  55. class' static fields. The instance namespace utilizes a dynamic import
  56. (i.e. mixin) to delegate variable access to the class' instance variables.
  57. <p>
  58. Constructors for the class delegate to the static initInstance() method of
  59. ClassGeneratorUtil to initialize new instances of the object. initInstance()
  60. invokes the instance intializer code (init vars and instance blocks) and
  61. then delegates to the corresponding scripted constructor method in the
  62. instance namespace. Constructors contain special switch logic which allows
  63. the BeanShell to control the calling of alternate constructors (this() or
  64. super() references) at runtime.
  65. <p>
  66. Specially named superclass delegator methods are also generated in order to
  67. allow BeanShell to access overridden methods of the superclass (which
  68. reflection does not normally allow).
  69. <p>
  70. @author Pat Niemeyer
  71. */
  72. /*
  73. Notes:
  74. It would not be hard to eliminate the use of org.objectweb.asm.Type from
  75. this class, making the distribution a tiny bit smaller.
  76. */
  77. public class ClassGeneratorUtil implements Constants
  78. {
  79. /** The name of the static field holding the reference to the bsh
  80. static This (the callback namespace for static methods) */
  81. static final String BSHSTATIC="_bshStatic";
  82. /** The name of the instance field holding the reference to the bsh
  83. instance This (the callback namespace for instance methods) */
  84. static final String BSHTHIS="_bshThis";
  85. /** The prefix for the name of the super delegate methods. e.g.
  86. _bshSuperfoo() is equivalent to super.foo() */
  87. static final String BSHSUPER="_bshSuper";
  88. /** The bsh static namespace variable name of the instance initializer */
  89. static final String BSHINIT="_bshInstanceInitializer";
  90. /** The bsh static namespace variable that holds the constructor methods */
  91. static final String BSHCONSTRUCTORS="_bshConstructors";
  92. /** The switch branch number for the default constructor.
  93. The value -1 will cause the default branch to be taken. */
  94. static final int DEFAULTCONSTRUCTOR = -1;
  95. static final String OBJECT= "Ljava/lang/Object;";
  96. String className;
  97. /** fully qualified class name (with package) e.g. foo/bar/Blah */
  98. String fqClassName;
  99. Class superClass;
  100. String superClassName;
  101. Class [] interfaces;
  102. Variable [] vars;
  103. Constructor [] superConstructors;
  104. DelayedEvalBshMethod [] constructors;
  105. DelayedEvalBshMethod [] methods;
  106. NameSpace classStaticNameSpace;
  107. Modifiers classModifiers;
  108. boolean isInterface;
  109. /**
  110. @param packageName e.g. "com.foo.bar"
  111. */
  112. public ClassGeneratorUtil(
  113. Modifiers classModifiers, String className, String packageName,
  114. Class superClass, Class [] interfaces, Variable [] vars,
  115. DelayedEvalBshMethod [] bshmethods, NameSpace classStaticNameSpace,
  116. boolean isInterface
  117. )
  118. {
  119. this.classModifiers = classModifiers;
  120. this.className = className;
  121. if ( packageName != null )
  122. this.fqClassName = packageName.replace('.','/') + "/" + className;
  123. else
  124. this.fqClassName = className;
  125. if ( superClass == null )
  126. superClass = Object.class;
  127. this.superClass = superClass;
  128. this.superClassName = Type.getInternalName( superClass );
  129. if ( interfaces == null )
  130. interfaces = new Class[0];
  131. this.interfaces = interfaces;
  132. this.vars = vars;
  133. this.classStaticNameSpace = classStaticNameSpace;
  134. this.superConstructors = superClass.getDeclaredConstructors();
  135. // Split the methods into constructors and regular method lists
  136. List consl = new ArrayList();
  137. List methodsl = new ArrayList();
  138. String classBaseName = getBaseName( className ); // for inner classes
  139. for( int i=0; i< bshmethods.length; i++ )
  140. if ( bshmethods[i].getName().equals( classBaseName ) )
  141. consl.add( bshmethods[i] );
  142. else
  143. methodsl.add( bshmethods[i] );
  144. this.constructors = (DelayedEvalBshMethod [])consl.toArray(
  145. new DelayedEvalBshMethod[0] );
  146. this.methods = (DelayedEvalBshMethod [])methodsl.toArray(
  147. new DelayedEvalBshMethod[0] );
  148. try {
  149. classStaticNameSpace.setLocalVariable(
  150. BSHCONSTRUCTORS, constructors, false/*strict*/ );
  151. } catch ( UtilEvalError e ) {
  152. throw new InterpreterError("can't set cons var");
  153. }
  154. this.isInterface = isInterface;
  155. }
  156. /**
  157. Generate the class bytecode for this class.
  158. @param className should be a path style name, e.g.
  159. "TestClass" or "mypackage/TestClass"
  160. */
  161. public byte [] generateClass()
  162. {
  163. // Force the class public for now...
  164. int classMods = getASMModifiers( classModifiers ) | ACC_PUBLIC;
  165. if ( isInterface )
  166. classMods |= ACC_INTERFACE;
  167. String [] interfaceNames = new String [interfaces.length];
  168. for(int i=0; i<interfaces.length; i++)
  169. interfaceNames[i]=Type.getInternalName( interfaces[i] );
  170. String sourceFile = "BeanShell Generated via ASM (www.objectweb.org)";
  171. ClassWriter cw = new ClassWriter(false);
  172. cw.visit( classMods, fqClassName, superClassName,
  173. interfaceNames, sourceFile );
  174. if ( !isInterface )
  175. {
  176. // Generate the bsh instance 'This' reference holder field
  177. generateField(
  178. BSHTHIS+className, "Lbsh/This;", ACC_PUBLIC, cw);
  179. // Generate the static bsh static reference holder field
  180. generateField(
  181. BSHSTATIC+className, "Lbsh/This;", ACC_PUBLIC+ACC_STATIC, cw);
  182. }
  183. // Generate the fields
  184. for( int i=0; i<vars.length; i++)
  185. {
  186. String type = vars[i].getTypeDescriptor();
  187. // Don't generate private or loosely typed fields
  188. // Note: loose types aren't currently parsed anyway...
  189. if ( vars[i].hasModifier("private") || type == null )
  190. continue;
  191. int modifiers;
  192. if ( isInterface )
  193. modifiers = ACC_PUBLIC | ACC_STATIC | ACC_FINAL;
  194. else
  195. modifiers = getASMModifiers( vars[i].getModifiers() );
  196. generateField( vars[i].getName(), type, modifiers , cw );
  197. }
  198. // Generate the constructors
  199. boolean hasConstructor = false;
  200. for( int i=0; i<constructors.length; i++)
  201. {
  202. // Don't generate private constructors
  203. if ( constructors[i].hasModifier("private") )
  204. continue;
  205. int modifiers = getASMModifiers( constructors[i].getModifiers() );
  206. generateConstructor(
  207. i, constructors[i].getParamTypeDescriptors(), modifiers, cw );
  208. hasConstructor = true;
  209. }
  210. // If no other constructors, generate a default constructor
  211. if ( !isInterface && !hasConstructor )
  212. generateConstructor(
  213. DEFAULTCONSTRUCTOR/*index*/, new String [0], ACC_PUBLIC, cw );
  214. // Generate the delegate methods
  215. for( int i=0; i<methods.length; i++)
  216. {
  217. String returnType = methods[i].getReturnTypeDescriptor();
  218. // Don't generate private /*or loosely return typed */ methods
  219. if ( methods[i].hasModifier("private") /*|| returnType == null*/ )
  220. continue;
  221. int modifiers = getASMModifiers( methods[i].getModifiers() );
  222. if ( isInterface )
  223. modifiers |= ( ACC_PUBLIC | ACC_ABSTRACT );
  224. generateMethod( className, fqClassName,
  225. methods[i].getName(), returnType,
  226. methods[i].getParamTypeDescriptors(), modifiers, cw );
  227. boolean isStatic = (modifiers & ACC_STATIC) > 0 ;
  228. boolean overridden = classContainsMethod(
  229. superClass, methods[i].getName(),
  230. methods[i].getParamTypeDescriptors() ) ;
  231. if ( !isStatic && overridden )
  232. generateSuperDelegateMethod( superClass, superClassName,
  233. methods[i].getName(), returnType,
  234. methods[i].getParamTypeDescriptors(), modifiers, cw );
  235. }
  236. return cw.toByteArray();
  237. }
  238. /**
  239. Translate bsh.Modifiers into ASM modifier bitflags.
  240. */
  241. static int getASMModifiers( Modifiers modifiers )
  242. {
  243. int mods = 0;
  244. if ( modifiers == null )
  245. return mods;
  246. if ( modifiers.hasModifier("public") )
  247. mods += ACC_PUBLIC;
  248. if ( modifiers.hasModifier("protected") )
  249. mods += ACC_PROTECTED;
  250. if ( modifiers.hasModifier("static") )
  251. mods += ACC_STATIC;
  252. if ( modifiers.hasModifier("synchronized") )
  253. mods += ACC_SYNCHRONIZED;
  254. if ( modifiers.hasModifier("abstract") )
  255. mods += ACC_ABSTRACT;
  256. return mods;
  257. }
  258. /**
  259. Generate a field - static or instance.
  260. */
  261. static void generateField(
  262. String fieldName, String type, int modifiers, ClassWriter cw )
  263. {
  264. cw.visitField( modifiers, fieldName, type, null/*value*/ );
  265. }
  266. /**
  267. Generate a delegate method - static or instance.
  268. The generated code packs the method arguments into an object array
  269. (wrapping primitive types in bsh.Primitive), invokes the static or
  270. instance namespace invokeMethod() method, and then unwraps / returns
  271. the result.
  272. */
  273. static void generateMethod(
  274. String className, String fqClassName, String methodName,
  275. String returnType, String[] paramTypes, int modifiers, ClassWriter cw )
  276. {
  277. String [] exceptions = null;
  278. boolean isStatic = (modifiers & ACC_STATIC) != 0 ;
  279. if ( returnType == null ) // map loose return type to Object
  280. returnType = OBJECT;
  281. String methodDescriptor = getMethodDescriptor( returnType, paramTypes );
  282. // Generate method body
  283. CodeVisitor cv = cw.visitMethod(
  284. modifiers, methodName, methodDescriptor, exceptions );
  285. if ( (modifiers & ACC_ABSTRACT) != 0 )
  286. return;
  287. // Generate code to push the BSHTHIS or BSHSTATIC field
  288. if ( isStatic )
  289. {
  290. cv.visitFieldInsn(
  291. GETSTATIC, fqClassName, BSHSTATIC+className, "Lbsh/This;" );
  292. }else
  293. {
  294. // Push 'this'
  295. cv.visitVarInsn( ALOAD, 0 );
  296. // Get the instance field
  297. cv.visitFieldInsn(
  298. GETFIELD, fqClassName, BSHTHIS+className, "Lbsh/This;" );
  299. }
  300. // Push the name of the method as a constant
  301. cv.visitLdcInsn( methodName );
  302. // Generate code to push arguments as an object array
  303. generateParameterReifierCode( paramTypes, isStatic, cv );
  304. // Push nulls for various args of invokeMethod
  305. cv.visitInsn(ACONST_NULL); // interpreter
  306. cv.visitInsn(ACONST_NULL); // callstack
  307. cv.visitInsn(ACONST_NULL); // callerinfo
  308. // Push the boolean constant 'true' (for declaredOnly)
  309. cv.visitInsn(ICONST_1);
  310. // Invoke the method This.invokeMethod( name, Class [] sig, boolean )
  311. cv.visitMethodInsn(
  312. INVOKEVIRTUAL, "bsh/This", "invokeMethod",
  313. Type.getMethodDescriptor(
  314. Type.getType(Object.class),
  315. new Type [] {
  316. Type.getType(String.class),
  317. Type.getType(Object [].class),
  318. Type.getType(Interpreter.class),
  319. Type.getType(CallStack.class),
  320. Type.getType(SimpleNode.class),
  321. Type.getType(Boolean.TYPE)
  322. }
  323. )
  324. );
  325. // Generate code to unwrap bsh Primitive types
  326. cv.visitMethodInsn(
  327. INVOKESTATIC, "bsh/Primitive", "unwrap",
  328. "(Ljava/lang/Object;)Ljava/lang/Object;" );
  329. // Generate code to return the value
  330. generateReturnCode( returnType, cv );
  331. // Need to calculate this... just fudging here for now.
  332. cv.visitMaxs( 20, 20 );
  333. }
  334. /**
  335. Generate a constructor.
  336. */
  337. void generateConstructor(
  338. int index, String [] paramTypes, int modifiers, ClassWriter cw )
  339. {
  340. /** offset after params of the args object [] var */
  341. final int argsVar = paramTypes.length+1;
  342. /** offset after params of the ConstructorArgs var */
  343. final int consArgsVar = paramTypes.length+2;
  344. String [] exceptions = null;
  345. String methodDescriptor = getMethodDescriptor( "V", paramTypes );
  346. // Create this constructor method
  347. CodeVisitor cv =
  348. cw.visitMethod( modifiers, "<init>", methodDescriptor, exceptions );
  349. // Generate code to push arguments as an object array
  350. generateParameterReifierCode( paramTypes, false/*isStatic*/, cv );
  351. cv.visitVarInsn( ASTORE, argsVar );
  352. // Generate the code implementing the alternate constructor switch
  353. generateConstructorSwitch( index, argsVar, consArgsVar, cv );
  354. // Generate code to invoke the ClassGeneratorUtil initInstance() method
  355. // push 'this'
  356. cv.visitVarInsn( ALOAD, 0 );
  357. // Push the class/constructor name as a constant
  358. cv.visitLdcInsn( className );
  359. // Push arguments as an object array
  360. cv.visitVarInsn( ALOAD, argsVar );
  361. // invoke the initInstance() method
  362. cv.visitMethodInsn(
  363. INVOKESTATIC, "bsh/ClassGeneratorUtil", "initInstance",
  364. "(Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/Object;)V");
  365. cv.visitInsn( RETURN );
  366. // Need to calculate this... just fudging here for now.
  367. cv.visitMaxs( 20, 20 );
  368. }
  369. /**
  370. Generate a switch with a branch for each possible alternate
  371. constructor. This includes all superclass constructors and all
  372. constructors of this class. The default branch of this switch is the
  373. default superclass constructor.
  374. <p>
  375. This method also generates the code to call the static
  376. ClassGeneratorUtil
  377. getConstructorArgs() method which inspects the scripted constructor to
  378. find the alternate constructor signature (if any) and evalute the
  379. arguments at runtime. The getConstructorArgs() method returns the
  380. actual arguments as well as the index of the constructor to call.
  381. */
  382. void generateConstructorSwitch(
  383. int consIndex, int argsVar, int consArgsVar, CodeVisitor cv )
  384. {
  385. Label defaultLabel = new Label();
  386. Label endLabel = new Label();
  387. int cases = superConstructors.length + constructors.length ;
  388. Label [] labels = new Label[ cases ];
  389. for(int i=0; i<cases; i++)
  390. labels[i]=new Label();
  391. // Generate code to call ClassGeneratorUtil to get our switch index
  392. // and give us args...
  393. // push super class name
  394. cv.visitLdcInsn( superClass.getName() ); // use superClassName var?
  395. // push class static This object
  396. cv.visitFieldInsn(
  397. GETSTATIC, fqClassName, BSHSTATIC+className, "Lbsh/This;" );
  398. // push args
  399. cv.visitVarInsn( ALOAD, argsVar );
  400. // push this constructor index number onto stack
  401. cv.visitIntInsn( BIPUSH, consIndex );
  402. // invoke the ClassGeneratorUtil getConstructorsArgs() method
  403. cv.visitMethodInsn(
  404. INVOKESTATIC, "bsh/ClassGeneratorUtil", "getConstructorArgs",
  405. "(Ljava/lang/String;Lbsh/This;[Ljava/lang/Object;I)"
  406. +"Lbsh/ClassGeneratorUtil$ConstructorArgs;"
  407. );
  408. // store ConstructorArgs in consArgsVar
  409. cv.visitVarInsn( ASTORE, consArgsVar );
  410. // Get the ConstructorArgs selector field from ConstructorArgs
  411. // push ConstructorArgs
  412. cv.visitVarInsn( ALOAD, consArgsVar );
  413. cv.visitFieldInsn(
  414. GETFIELD, "bsh/ClassGeneratorUtil$ConstructorArgs", "selector", "I" );
  415. // start switch
  416. cv.visitTableSwitchInsn(
  417. 0/*min*/, cases-1/*max*/, defaultLabel, labels );
  418. // generate switch body
  419. int index = 0;
  420. for( int i=0; i< superConstructors.length; i++, index++)
  421. doSwitchBranch( index, superClassName,
  422. getTypeDescriptors( superConstructors[i].getParameterTypes() ),
  423. endLabel, labels, consArgsVar, cv );
  424. for( int i=0; i< constructors.length; i++, index++)
  425. doSwitchBranch( index, fqClassName,
  426. constructors[i].getParamTypeDescriptors(),
  427. endLabel, labels, consArgsVar, cv );
  428. // generate the default branch of switch
  429. cv.visitLabel( defaultLabel );
  430. // default branch always invokes no args super
  431. cv.visitVarInsn( ALOAD, 0 ); // push 'this'
  432. cv.visitMethodInsn( INVOKESPECIAL, superClassName, "<init>", "()V" );
  433. // done with switch
  434. cv.visitLabel( endLabel );
  435. }
  436. /*
  437. Generate a branch of the constructor switch. This method is called by
  438. generateConstructorSwitch.
  439. The code generated by this method assumes that the argument array is
  440. on the stack.
  441. */
  442. static void doSwitchBranch(
  443. int index, String targetClassName, String [] paramTypes,
  444. Label endLabel, Label [] labels, int consArgsVar, CodeVisitor cv
  445. )
  446. {
  447. cv.visitLabel( labels[index] );
  448. //cv.visitLineNumber( index, labels[index] );
  449. cv.visitVarInsn( ALOAD, 0 ); // push this before args
  450. // Unload the arguments from the ConstructorArgs object
  451. for (int i=0; i<paramTypes.length; i++)
  452. {
  453. String type = paramTypes[i];
  454. String method = null;
  455. if ( type.equals("Z") )
  456. method = "getBoolean";
  457. else if ( type.equals("B") )
  458. method = "getByte";
  459. else if ( type.equals("C") )
  460. method = "getChar";
  461. else if ( type.equals("S") )
  462. method = "getShort";
  463. else if ( type.equals("I") )
  464. method = "getInt";
  465. else if ( type.equals("J") )
  466. method = "getLong";
  467. else if ( type.equals("D") )
  468. method = "getDouble";
  469. else if ( type.equals("F") )
  470. method = "getFloat";
  471. else
  472. method = "getObject";
  473. // invoke the iterator method on the ConstructorArgs
  474. cv.visitVarInsn( ALOAD, consArgsVar ); // push the ConstructorArgs
  475. String className = "bsh/ClassGeneratorUtil$ConstructorArgs";
  476. String retType;
  477. if ( method.equals("getObject") )
  478. retType = OBJECT;
  479. else
  480. retType = type;
  481. cv.visitMethodInsn(INVOKEVIRTUAL, className, method, "()"+retType);
  482. // if it's an object type we must do a check cast
  483. if ( method.equals("getObject") )
  484. cv.visitTypeInsn( CHECKCAST, descriptorToClassName(type) );
  485. }
  486. // invoke the constructor for this branch
  487. String descriptor = getMethodDescriptor( "V", paramTypes );
  488. cv.visitMethodInsn(
  489. INVOKESPECIAL, targetClassName, "<init>", descriptor );
  490. cv.visitJumpInsn( GOTO, endLabel );
  491. }
  492. static String getMethodDescriptor( String returnType, String [] paramTypes )
  493. {
  494. StringBuffer sb = new StringBuffer("(");
  495. for(int i=0; i<paramTypes.length; i++)
  496. sb.append(paramTypes[i]);
  497. sb.append(")"+returnType);
  498. return sb.toString();
  499. }
  500. /**
  501. Generate a superclass method delegate accessor method.
  502. These methods are specially named methods which allow access to
  503. overridden methods of the superclass (which the Java reflection API
  504. normally does not allow).
  505. */
  506. // Maybe combine this with generateMethod()
  507. static void generateSuperDelegateMethod(
  508. Class superClass, String superClassName, String methodName,
  509. String returnType, String [] paramTypes, int modifiers, ClassWriter cw)
  510. {
  511. String [] exceptions = null;
  512. if ( returnType == null ) // map loose return to Object
  513. returnType = OBJECT;
  514. String methodDescriptor = getMethodDescriptor( returnType, paramTypes );
  515. // Add method body
  516. CodeVisitor cv = cw.visitMethod(
  517. modifiers, "_bshSuper"+methodName, methodDescriptor, exceptions );
  518. cv.visitVarInsn(ALOAD, 0);
  519. // Push vars
  520. int localVarIndex = 1;
  521. for (int i = 0; i < paramTypes.length; ++i)
  522. {
  523. if ( isPrimitive( paramTypes[i]) )
  524. cv.visitVarInsn(ILOAD, localVarIndex);
  525. else
  526. cv.visitVarInsn(ALOAD, localVarIndex);
  527. localVarIndex +=
  528. ( (paramTypes[i].equals("D") || paramTypes[i].equals("J"))
  529. ? 2 : 1 );
  530. }
  531. cv.visitMethodInsn( INVOKESPECIAL,
  532. superClassName, methodName, methodDescriptor );
  533. generatePlainReturnCode( returnType, cv );
  534. // Need to calculate this... just fudging here for now.
  535. cv.visitMaxs( 20, 20 );
  536. }
  537. boolean classContainsMethod(
  538. Class clas, String methodName, String [] paramTypes )
  539. {
  540. while( clas != null )
  541. {
  542. Method [] methods = clas.getDeclaredMethods();
  543. for( int i =0; i<methods.length; i++ )
  544. {
  545. if ( methods[i].getName().equals(methodName) )
  546. {
  547. String [] methodParamTypes =
  548. getTypeDescriptors( methods[i].getParameterTypes() );
  549. boolean found = true;
  550. for( int j=0; j<methodParamTypes.length; j++)
  551. {
  552. if ( ! paramTypes[j].equals( methodParamTypes[j] ) ) {
  553. found = false;
  554. break;
  555. }
  556. }
  557. if ( found )
  558. return true;
  559. }
  560. }
  561. clas = clas.getSuperclass();
  562. }
  563. return false;
  564. }
  565. /**
  566. Generate return code for a normal bytecode
  567. */
  568. static void generatePlainReturnCode( String returnType, CodeVisitor cv )
  569. {
  570. if ( returnType.equals("V") )
  571. cv.visitInsn( RETURN );
  572. else
  573. if ( isPrimitive( returnType ) )
  574. {
  575. int opcode = IRETURN;
  576. if ( returnType.equals("D") )
  577. opcode = DRETURN;
  578. else if ( returnType.equals("F") )
  579. opcode = FRETURN;
  580. else if ( returnType.equals("J") ) //long
  581. opcode = LRETURN;
  582. cv.visitInsn(opcode);
  583. }
  584. else {
  585. cv.visitTypeInsn( CHECKCAST, descriptorToClassName(returnType) );
  586. cv.visitInsn( ARETURN );
  587. }
  588. }
  589. /**
  590. Generates the code to reify the arguments of the given method.
  591. For a method "int m (int i, String s)", this code is the bytecode
  592. corresponding to the "new Object[] { new bsh.Primitive(i), s }"
  593. expression.
  594. @param cv the code visitor to be used to generate the bytecode.
  595. @param isStatic the enclosing methods is static
  596. @author Eric Bruneton
  597. @author Pat Niemeyer
  598. */
  599. public static void generateParameterReifierCode (
  600. String [] paramTypes, boolean isStatic, final CodeVisitor cv )
  601. {
  602. cv.visitIntInsn(SIPUSH, paramTypes.length);
  603. cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
  604. int localVarIndex = isStatic ? 0 : 1;
  605. for (int i = 0; i < paramTypes.length; ++i)
  606. {
  607. String param = paramTypes[i];
  608. cv.visitInsn(DUP);
  609. cv.visitIntInsn(SIPUSH, i);
  610. if ( isPrimitive( param ) )
  611. {
  612. int opcode = ILOAD;
  613. String type = "bsh/Primitive";
  614. cv.visitTypeInsn( NEW, type );
  615. cv.visitInsn(DUP);
  616. cv.visitVarInsn(opcode, localVarIndex);
  617. String desc = param; // ok?
  618. cv.visitMethodInsn(
  619. INVOKESPECIAL, type, "<init>", "(" + desc + ")V");
  620. } else {
  621. // Technically incorrect here - we need to wrap null values
  622. // as bsh.Primitive.NULL. However the This.invokeMethod()
  623. // will do that much for us.
  624. // We need to generate a conditional here to test for null
  625. // and return Primitive.NULL
  626. cv.visitVarInsn( ALOAD, localVarIndex );
  627. }
  628. cv.visitInsn(AASTORE);
  629. localVarIndex +=
  630. ( (param.equals("D") || param.equals("J")) ? 2 : 1 );
  631. }
  632. }
  633. /**
  634. Generates the code to unreify the result of the given method. For a
  635. method "int m (int i, String s)", this code is the bytecode
  636. corresponding to the "((Integer)...).intValue()" expression.
  637. @param m a method object.
  638. @param cv the code visitor to be used to generate the bytecode.
  639. @author Eric Bruneton
  640. @author Pat Niemeyer
  641. */
  642. public static void generateReturnCode (
  643. String returnType, CodeVisitor cv )
  644. {
  645. if ( returnType.equals("V") )
  646. {
  647. cv.visitInsn(POP);
  648. cv.visitInsn(RETURN);
  649. }
  650. else if ( isPrimitive( returnType ) )
  651. {
  652. int opcode = IRETURN;
  653. String type;
  654. String meth;
  655. if ( returnType.equals("B") ) {
  656. type = "java/lang/Byte";
  657. meth = "byteValue";
  658. } else if (returnType.equals("I") ) {
  659. type = "java/lang/Integer";
  660. meth = "intValue";
  661. } else if (returnType.equals("Z") ) {
  662. type = "java/lang/Boolean";
  663. meth = "booleanValue";
  664. } else if (returnType.equals("D") ) {
  665. opcode = DRETURN;
  666. type = "java/lang/Double";
  667. meth = "doubleValue";
  668. } else if (returnType.equals("F") ) {
  669. opcode = FRETURN;
  670. type = "java/lang/Float";
  671. meth = "floatValue";
  672. } else if (returnType.equals("J") ) {
  673. opcode = LRETURN;
  674. type = "java/lang/Long";
  675. meth = "longValue";
  676. } else if (returnType.equals("C") ) {
  677. type = "java/lang/Character";
  678. meth = "charValue";
  679. } else /*if (returnType.equals("S") )*/ {
  680. type = "java/lang/Short";
  681. meth = "shortValue";
  682. }
  683. String desc = returnType;
  684. cv.visitTypeInsn( CHECKCAST, type ); // type is correct here
  685. cv.visitMethodInsn( INVOKEVIRTUAL, type, meth, "()" + desc );
  686. cv.visitInsn(opcode);
  687. } else
  688. {
  689. cv.visitTypeInsn( CHECKCAST, descriptorToClassName(returnType) );
  690. cv.visitInsn(ARETURN);
  691. }
  692. }
  693. /**
  694. Evaluate the arguments (if any) for the constructor specified by
  695. the constructor index. Return the ConstructorArgs object which
  696. contains the actual arguments to the alternate constructor and also the
  697. index of that constructor for the constructor switch.
  698. @param args the arguments to the constructor. These are necessary in
  699. the evaluation of the alt constructor args. e.g. Foo(a) { super(a); }
  700. @return the ConstructorArgs object containing a constructor selector
  701. and evaluated arguments for the alternate constructor
  702. */
  703. public static ConstructorArgs getConstructorArgs(
  704. String superClassName, This classStaticThis,
  705. Object [] consArgs, int index )
  706. {
  707. DelayedEvalBshMethod [] constructors;
  708. try {
  709. constructors =
  710. (DelayedEvalBshMethod [])classStaticThis.getNameSpace()
  711. .getVariable( BSHCONSTRUCTORS );
  712. } catch ( Exception e ) {
  713. throw new InterpreterError(
  714. "unable to get instance initializer: "+e );
  715. }
  716. if ( index == DEFAULTCONSTRUCTOR ) // auto-gen default constructor
  717. return ConstructorArgs.DEFAULT; // use default super constructor
  718. DelayedEvalBshMethod constructor = constructors[index];
  719. if ( constructor.methodBody.jjtGetNumChildren() == 0 )
  720. return ConstructorArgs.DEFAULT; // use default super constructor
  721. // Determine if the constructor calls this() or super()
  722. String altConstructor = null;
  723. BSHArguments argsNode = null;
  724. SimpleNode firstStatement =
  725. (SimpleNode)constructor.methodBody.jjtGetChild(0);
  726. if ( firstStatement instanceof BSHPrimaryExpression )
  727. firstStatement = (SimpleNode)firstStatement.jjtGetChild(0);
  728. if ( firstStatement instanceof BSHMethodInvocation )
  729. {
  730. BSHMethodInvocation methodNode =
  731. (BSHMethodInvocation)firstStatement;
  732. BSHAmbiguousName methodName = methodNode.getNameNode();
  733. if ( methodName.text.equals("super")
  734. || methodName.text.equals("this")
  735. ) {
  736. altConstructor = methodName.text;
  737. argsNode = methodNode.getArgsNode();
  738. }
  739. }
  740. if ( altConstructor == null )
  741. return ConstructorArgs.DEFAULT; // use default super constructor
  742. // Make a tmp namespace to hold the original constructor args for
  743. // use in eval of the parameters node
  744. NameSpace consArgsNameSpace =
  745. new NameSpace( classStaticThis.getNameSpace(), "consArgs" );
  746. String [] consArgNames = constructor.getParameterNames();
  747. Class [] consArgTypes = constructor.getParameterTypes();
  748. for( int i=0; i<consArgs.length; i++ )
  749. {
  750. try {
  751. consArgsNameSpace.setTypedVariable(
  752. consArgNames[i], consArgTypes[i], consArgs[i],
  753. null/*modifiers*/);
  754. } catch ( UtilEvalError e ) {
  755. throw new InterpreterError("err setting local cons arg:"+e);
  756. }
  757. }
  758. // evaluate the args
  759. CallStack callstack = new CallStack();
  760. callstack.push( consArgsNameSpace);
  761. Object [] args = null;
  762. Interpreter interpreter = classStaticThis.declaringInterpreter;
  763. try {
  764. args = argsNode.getArguments( callstack, interpreter );
  765. } catch ( EvalError e ) {
  766. throw new InterpreterError(
  767. "Error evaluating constructor args: "+e );
  768. }
  769. Class [] argTypes = Types.getTypes( args );
  770. args = Primitive.unwrap( args );
  771. Class superClass =
  772. interpreter.getClassManager().classForName( superClassName );
  773. if ( superClass == null )
  774. throw new InterpreterError(
  775. "can't find superclass: "+superClassName );
  776. Constructor [] superCons = superClass.getDeclaredConstructors();
  777. // find the matching super() constructor for the args
  778. if ( altConstructor.equals("super") )
  779. {
  780. int i = Reflect.findMostSpecificConstructorIndex(
  781. argTypes , superCons );
  782. if ( i == -1 )
  783. throw new InterpreterError("can't find constructor for args!");
  784. return new ConstructorArgs( i, args );
  785. }
  786. // find the matching this() constructor for the args
  787. Class [][] candidates = new Class [ constructors.length ] [];
  788. for(int i=0; i< candidates.length; i++ )
  789. candidates[i] = constructors[i].getParameterTypes();
  790. int i = Reflect.findMostSpecificSignature( argTypes, candidates );
  791. if ( i == -1 )
  792. throw new InterpreterError("can't find constructor for args 2!");
  793. // this() constructors come after super constructors in the table
  794. int selector = i+superCons.length;
  795. int ourSelector = index+superCons.length;
  796. // Are we choosing ourselves recursively through a this() reference?
  797. if ( selector == ourSelector )
  798. throw new InterpreterError( "Recusive constructor call.");
  799. return new ConstructorArgs( selector, args );
  800. }
  801. /**
  802. Initialize an instance of the class.
  803. This method is called from the generated class constructor to evaluate
  804. the instance initializer and scripted constructor in the instance
  805. namespace.
  806. */
  807. public static void initInstance(
  808. Object instance, String className, Object [] args )
  809. {
  810. Class [] sig = Types.getTypes( args );
  811. CallStack callstack = new CallStack();
  812. Interpreter interpreter;
  813. NameSpace instanceNameSpace;
  814. // check to see if the instance has already been initialized
  815. // (the case if using a this() alternate constuctor)
  816. This instanceThis = getClassInstanceThis( instance, className );
  817. // XXX clean up this conditional
  818. if ( instanceThis == null )
  819. {
  820. // Create the instance 'This' namespace, set it on the object
  821. // instance and invoke the instance initializer
  822. // Get the static This reference from the proto-instance
  823. This classStaticThis =
  824. getClassStaticThis( instance.getClass(), className );
  825. interpreter = classStaticThis.declaringInterpreter;
  826. // Get the instance initializer block from the static This
  827. BSHBlock instanceInitBlock;
  828. try {
  829. instanceInitBlock = (BSHBlock)classStaticThis.getNameSpace()
  830. .getVariable( BSHINIT );
  831. } catch ( Exception e ) {
  832. throw new InterpreterError(
  833. "unable to get instance initializer: "+e );
  834. }
  835. // Create the instance namespace
  836. instanceNameSpace =
  837. new NameSpace( classStaticThis.getNameSpace(), className );
  838. instanceNameSpace.isClass = true;
  839. // Set the instance This reference on the instance
  840. instanceThis = instanceNameSpace.getThis( interpreter );
  841. try {
  842. LHS lhs =
  843. Reflect.getLHSObjectField( instance, BSHTHIS+className );
  844. lhs.assign( instanceThis, false/*strict*/ );
  845. } catch ( Exception e ) {
  846. throw new InterpreterError("Error in class gen setup: "+e );
  847. }
  848. // Give the instance space its object import
  849. instanceNameSpace.setClassInstance( instance );
  850. // should use try/finally here to pop ns
  851. callstack.push( instanceNameSpace );
  852. // evaluate the instance portion of the block in it
  853. try { // Evaluate the initializer block
  854. instanceInitBlock.evalBlock(
  855. callstack, interpreter, true/*override*/,
  856. ClassGeneratorImpl.ClassNodeFilter.CLASSINSTANCE );
  857. } catch ( Exception e ) {
  858. throw new InterpreterError("Error in class initialization: "+e);
  859. }
  860. callstack.pop();
  861. } else
  862. {
  863. // The object instance has already been initialzed by another
  864. // constructor. Fall through to invoke the constructor body below.
  865. interpreter = instanceThis.declaringInterpreter;
  866. instanceNameSpace = instanceThis.getNameSpace();
  867. }
  868. // invoke the constructor method from the instanceThis
  869. String constructorName = getBaseName( className );
  870. try {
  871. // Find the constructor (now in the instance namespace)
  872. BshMethod constructor = instanceNameSpace.getMethod(
  873. constructorName, sig, true/*declaredOnly*/ );
  874. // if args, we must have constructor
  875. if ( args.length > 0 && constructor == null )
  876. throw new InterpreterError(
  877. "Can't find constructor: "+ className );
  878. // Evaluate the constructor
  879. if ( constructor != null )
  880. constructor.invoke( args, interpreter, callstack,
  881. null/*callerInfo*/, false/*overrideNameSpace*/ ) ;
  882. } catch ( Exception e ) {
  883. if ( e instanceof TargetError )
  884. e =(Exception)((TargetError)e).getTarget();
  885. if ( e instanceof InvocationTargetException )
  886. e = (Exception)((InvocationTargetException)e)
  887. .getTargetException();
  888. e.printStackTrace( System.err );
  889. throw new InterpreterError("Error in class initialization: "+e );
  890. }
  891. }
  892. /**
  893. Get the static bsh namespace field from the class.
  894. @param className may be the name of clas itself or a superclass of clas.
  895. */
  896. static This getClassStaticThis( Class clas, String className )
  897. {
  898. try {
  899. return (This)Reflect.getStaticField(
  900. clas, BSHSTATIC + className );
  901. } catch ( Exception e ) {
  902. throw new InterpreterError("Unable to get class static space: "+e);
  903. }
  904. }
  905. /**
  906. Get the instance bsh namespace field from the object instance.
  907. @return the class instance This object or null if the object has not
  908. been initialized.
  909. */
  910. static This getClassInstanceThis( Object instance, String className )
  911. {
  912. try {
  913. Object o = Reflect.getObjectField( instance, BSHTHIS+className );
  914. return (This)Primitive.unwrap(o); // unwrap Primitive.Null to null
  915. } catch ( Exception e ) {
  916. throw new InterpreterError(
  917. "Generated class: Error getting This"+e );
  918. }
  919. }
  920. /**
  921. Does the type descriptor string describe a primitive type?
  922. */
  923. private static boolean isPrimitive( String typeDescriptor )
  924. {
  925. return typeDescriptor.length() == 1; // right?
  926. }
  927. static String[] getTypeDescriptors( Class [] cparams )
  928. {
  929. String [] sa = new String [cparams.length];
  930. for(int i=0; i<sa.length; i++)
  931. sa[i] = BSHType.getTypeDescriptor( cparams[i] );
  932. return sa;
  933. }
  934. /**
  935. If a non-array object type, remove the prefix "L" and suffix ";".
  936. */
  937. // Can this be factored out...?
  938. // Should be be adding the L...; here instead?
  939. private static String descriptorToClassName( String s )
  940. {
  941. if ( s.startsWith("[") || !s.startsWith("L") )
  942. return s;
  943. return s.substring( 1, s.length()-1 );
  944. }
  945. private static String getBaseName( String className )
  946. {
  947. int i = className.indexOf("$");
  948. if ( i == -1 )
  949. return className;
  950. return className.substring(i+1);
  951. }
  952. /**
  953. A ConstructorArgs object holds evaluated arguments for a constructor
  954. call as well as the index of a possible alternate selector to invoke.
  955. This object is used by the constructor switch.
  956. @see #generateConstructor( int , String [] , int , ClassWriter )
  957. */
  958. public static class ConstructorArgs
  959. {
  960. /** A ConstructorArgs which calls the default constructor */
  961. public static ConstructorArgs DEFAULT = new ConstructorArgs();
  962. public int selector = DEFAULTCONSTRUCTOR;
  963. Object [] args;
  964. int arg = 0;
  965. /**
  966. The index of the constructor to call.
  967. */
  968. ConstructorArgs() { }
  969. ConstructorArgs( int selector, Object [] args ) {
  970. this.selector = selector;
  971. this.args = args;
  972. }
  973. Object next() { return args[arg++]; }
  974. public boolean getBoolean() { return ((Boolean)next()).booleanValue(); }
  975. public byte getByte() { return ((Byte)next()).byteValue(); }
  976. public char getChar() { return ((Character)next()).charValue(); }
  977. public short getShort() { return ((Short)next()).shortValue(); }
  978. public int getInt() { return ((Integer)next()).intValue(); }
  979. public long getLong() { return ((Long)next()).longValue(); }
  980. public double getDouble() { return ((Double)next()).doubleValue(); }
  981. public float getFloat() { return ((Float)next()).floatValue(); }
  982. public Object getObject() { return next(); }
  983. }
  984. }