PageRenderTime 295ms CodeModel.GetById 35ms RepoModel.GetById 1ms app.codeStats 0ms

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

#
Java | 428 lines | 222 code | 43 blank | 163 comment | 44 complexity | 09b7209ae06575a680ee725e8d7e355c 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.Method;
  35. import java.lang.reflect.InvocationTargetException;
  36. /**
  37. This represents an instance of a bsh method declaration in a particular
  38. namespace. This is a thin wrapper around the BSHMethodDeclaration
  39. with a pointer to the declaring namespace.
  40. <p>
  41. When a method is located in a subordinate namespace or invoked from an
  42. arbitrary namespace it must nontheless execute with its 'super' as the
  43. context in which it was declared.
  44. <p/>
  45. */
  46. /*
  47. Note: this method incorrectly caches the method structure. It needs to
  48. be cleared when the classloader changes.
  49. */
  50. public class BshMethod
  51. implements java.io.Serializable
  52. {
  53. /*
  54. This is the namespace in which the method is set.
  55. It is a back-reference for the node, which needs to execute under this
  56. namespace. It is not necessary to declare this transient, because
  57. we can only be saved as part of our namespace anyway... (currently).
  58. */
  59. NameSpace declaringNameSpace;
  60. // Begin Method components
  61. Modifiers modifiers;
  62. private String name;
  63. private Class creturnType;
  64. // Arguments
  65. private String [] paramNames;
  66. private int numArgs;
  67. private Class [] cparamTypes;
  68. // Scripted method body
  69. BSHBlock methodBody;
  70. // Java Method, for a BshObject that delegates to a real Java method
  71. private Method javaMethod;
  72. private Object javaObject;
  73. // End method components
  74. BshMethod(
  75. BSHMethodDeclaration method,
  76. NameSpace declaringNameSpace, Modifiers modifiers )
  77. {
  78. this( method.name, method.returnType, method.paramsNode.getParamNames(),
  79. method.paramsNode.paramTypes, method.blockNode, declaringNameSpace,
  80. modifiers );
  81. }
  82. BshMethod(
  83. String name, Class returnType, String [] paramNames,
  84. Class [] paramTypes, BSHBlock methodBody,
  85. NameSpace declaringNameSpace, Modifiers modifiers
  86. ) {
  87. this.name = name;
  88. this.creturnType = returnType;
  89. this.paramNames = paramNames;
  90. if ( paramNames != null )
  91. this.numArgs = paramNames.length;
  92. this.cparamTypes = paramTypes;
  93. this.methodBody = methodBody;
  94. this.declaringNameSpace = declaringNameSpace;
  95. this.modifiers = modifiers;
  96. }
  97. /*
  98. Create a BshMethod that delegates to a real Java method upon invocation.
  99. This is used to represent imported object methods.
  100. */
  101. BshMethod( Method method, Object object )
  102. {
  103. this( method.getName(), method.getReturnType(), null/*paramNames*/,
  104. method.getParameterTypes(), null/*method.block*/,
  105. null/*declaringNameSpace*/, null/*modifiers*/ );
  106. this.javaMethod = method;
  107. this.javaObject = object;
  108. }
  109. /**
  110. Get the argument types of this method.
  111. loosely typed (untyped) arguments will be represented by null argument
  112. types.
  113. */
  114. /*
  115. Note: bshmethod needs to re-evaluate arg types here
  116. This is broken.
  117. */
  118. public Class [] getParameterTypes() { return cparamTypes; }
  119. public String [] getParameterNames() { return paramNames; }
  120. /**
  121. Get the return type of the method.
  122. @return Returns null for a loosely typed return value,
  123. Void.TYPE for a void return type, or the Class of the type.
  124. */
  125. /*
  126. Note: bshmethod needs to re-evaluate the method return type here.
  127. This is broken.
  128. */
  129. public Class getReturnType() { return creturnType; }
  130. public Modifiers getModifiers() { return modifiers; }
  131. public String getName() { return name; }
  132. /**
  133. Invoke the declared method with the specified arguments and interpreter
  134. reference. This is the simplest form of invoke() for BshMethod
  135. intended to be used in reflective style access to bsh scripts.
  136. */
  137. public Object invoke(
  138. Object[] argValues, Interpreter interpreter )
  139. throws EvalError
  140. {
  141. return invoke( argValues, interpreter, null, null, false );
  142. }
  143. /**
  144. Invoke the bsh method with the specified args, interpreter ref,
  145. and callstack.
  146. callerInfo is the node representing the method invocation
  147. It is used primarily for debugging in order to provide access to the
  148. text of the construct that invoked the method through the namespace.
  149. @param callerInfo is the BeanShell AST node representing the method
  150. invocation. It is used to print the line number and text of
  151. errors in EvalError exceptions. If the node is null here error
  152. messages may not be able to point to the precise location and text
  153. of the error.
  154. @param callstack is the callstack. If callstack is null a new one
  155. will be created with the declaring namespace of the method on top
  156. of the stack (i.e. it will look for purposes of the method
  157. invocation like the method call occurred in the declaring
  158. (enclosing) namespace in which the method is defined).
  159. */
  160. public Object invoke(
  161. Object[] argValues, Interpreter interpreter, CallStack callstack,
  162. SimpleNode callerInfo )
  163. throws EvalError
  164. {
  165. return invoke( argValues, interpreter, callstack, callerInfo, false );
  166. }
  167. /**
  168. Invoke the bsh method with the specified args, interpreter ref,
  169. and callstack.
  170. callerInfo is the node representing the method invocation
  171. It is used primarily for debugging in order to provide access to the
  172. text of the construct that invoked the method through the namespace.
  173. @param callerInfo is the BeanShell AST node representing the method
  174. invocation. It is used to print the line number and text of
  175. errors in EvalError exceptions. If the node is null here error
  176. messages may not be able to point to the precise location and text
  177. of the error.
  178. @param callstack is the callstack. If callstack is null a new one
  179. will be created with the declaring namespace of the method on top
  180. of the stack (i.e. it will look for purposes of the method
  181. invocation like the method call occurred in the declaring
  182. (enclosing) namespace in which the method is defined).
  183. @param overrideNameSpace
  184. When true the method is executed in the namespace on the top of the
  185. stack instead of creating its own local namespace. This allows it
  186. to be used in constructors.
  187. */
  188. Object invoke(
  189. Object[] argValues, Interpreter interpreter, CallStack callstack,
  190. SimpleNode callerInfo, boolean overrideNameSpace )
  191. throws EvalError
  192. {
  193. if ( argValues != null )
  194. for (int i=0; i<argValues.length; i++)
  195. if ( argValues[i] == null )
  196. throw new Error("HERE!");
  197. if ( javaMethod != null )
  198. try {
  199. return Reflect.invokeMethod(
  200. javaMethod, javaObject, argValues );
  201. } catch ( ReflectError e ) {
  202. throw new EvalError(
  203. "Error invoking Java method: "+e, callerInfo, callstack );
  204. } catch ( InvocationTargetException e2 ) {
  205. throw new TargetError(
  206. "Exception invoking imported object method.",
  207. e2, callerInfo, callstack, true/*isNative*/ );
  208. }
  209. // is this a syncrhonized method?
  210. if ( modifiers != null && modifiers.hasModifier("synchronized") )
  211. {
  212. // The lock is our declaring namespace's This reference
  213. // (the method's 'super'). Or in the case of a class it's the
  214. // class instance.
  215. Object lock;
  216. if ( declaringNameSpace.isClass )
  217. {
  218. try {
  219. lock = declaringNameSpace.getClassInstance();
  220. } catch ( UtilEvalError e ) {
  221. throw new InterpreterError(
  222. "Can't get class instance for synchronized method.");
  223. }
  224. } else
  225. lock = declaringNameSpace.getThis(interpreter); // ???
  226. synchronized( lock )
  227. {
  228. return invokeImpl(
  229. argValues, interpreter, callstack,
  230. callerInfo, overrideNameSpace );
  231. }
  232. } else
  233. return invokeImpl( argValues, interpreter, callstack, callerInfo,
  234. overrideNameSpace );
  235. }
  236. private Object invokeImpl(
  237. Object[] argValues, Interpreter interpreter, CallStack callstack,
  238. SimpleNode callerInfo, boolean overrideNameSpace )
  239. throws EvalError
  240. {
  241. Class returnType = getReturnType();
  242. Class [] paramTypes = getParameterTypes();
  243. // If null callstack
  244. if ( callstack == null )
  245. callstack = new CallStack( declaringNameSpace );
  246. if ( argValues == null )
  247. argValues = new Object [] { };
  248. // Cardinality (number of args) mismatch
  249. if ( argValues.length != numArgs )
  250. {
  251. /*
  252. // look for help string
  253. try {
  254. // should check for null namespace here
  255. String help =
  256. (String)declaringNameSpace.get(
  257. "bsh.help."+name, interpreter );
  258. interpreter.println(help);
  259. return Primitive.VOID;
  260. } catch ( Exception e ) {
  261. throw eval error
  262. }
  263. */
  264. throw new EvalError(
  265. "Wrong number of arguments for local method: "
  266. + name, callerInfo, callstack );
  267. }
  268. // Make the local namespace for the method invocation
  269. NameSpace localNameSpace;
  270. if ( overrideNameSpace )
  271. localNameSpace = callstack.top();
  272. else
  273. {
  274. localNameSpace = new NameSpace( declaringNameSpace, name );
  275. localNameSpace.isMethod = true;
  276. }
  277. // should we do this for both cases above?
  278. localNameSpace.setNode( callerInfo );
  279. // set the method parameters in the local namespace
  280. for(int i=0; i<numArgs; i++)
  281. {
  282. // Set typed variable
  283. if ( paramTypes[i] != null )
  284. {
  285. try {
  286. argValues[i] =
  287. //Types.getAssignableForm( argValues[i], paramTypes[i] );
  288. Types.castObject( argValues[i], paramTypes[i], Types.ASSIGNMENT );
  289. }
  290. catch( UtilEvalError e) {
  291. throw new EvalError(
  292. "Invalid argument: "
  293. + "`"+paramNames[i]+"'" + " for method: "
  294. + name + " : " +
  295. e.getMessage(), callerInfo, callstack );
  296. }
  297. try {
  298. localNameSpace.setTypedVariable( paramNames[i],
  299. paramTypes[i], argValues[i], null/*modifiers*/);
  300. } catch ( UtilEvalError e2 ) {
  301. throw e2.toEvalError( "Typed method parameter assignment",
  302. callerInfo, callstack );
  303. }
  304. }
  305. // Set untyped variable
  306. else // untyped param
  307. {
  308. // getAssignable would catch this for typed param
  309. if ( argValues[i] == Primitive.VOID)
  310. throw new EvalError(
  311. "Undefined variable or class name, parameter: " +
  312. paramNames[i] + " to method: "
  313. + name, callerInfo, callstack );
  314. else
  315. try {
  316. localNameSpace.setLocalVariable(
  317. paramNames[i], argValues[i],
  318. interpreter.getStrictJava() );
  319. } catch ( UtilEvalError e3 ) {
  320. throw e3.toEvalError( callerInfo, callstack );
  321. }
  322. }
  323. }
  324. // Push the new namespace on the call stack
  325. if ( !overrideNameSpace )
  326. callstack.push( localNameSpace );
  327. // Invoke the block, overriding namespace with localNameSpace
  328. Object ret = methodBody.eval(
  329. callstack, interpreter, true/*override*/ );
  330. // save the callstack including the called method, just for error mess
  331. CallStack returnStack = callstack.copy();
  332. // Get back to caller namespace
  333. if ( !overrideNameSpace )
  334. callstack.pop();
  335. ReturnControl retControl = null;
  336. if ( ret instanceof ReturnControl )
  337. {
  338. retControl = (ReturnControl)ret;
  339. // Method body can only use 'return' statment type return control.
  340. if ( retControl.kind == retControl.RETURN )
  341. ret = ((ReturnControl)ret).value;
  342. else
  343. // retControl.returnPoint is the Node of the return statement
  344. throw new EvalError("'continue' or 'break' in method body",
  345. retControl.returnPoint, returnStack );
  346. // Check for explicit return of value from void method type.
  347. // retControl.returnPoint is the Node of the return statement
  348. if ( returnType == Void.TYPE && ret != Primitive.VOID )
  349. throw new EvalError( "Cannot return value from void method",
  350. retControl.returnPoint, returnStack);
  351. }
  352. if ( returnType != null )
  353. {
  354. // If return type void, return void as the value.
  355. if ( returnType == Void.TYPE )
  356. return Primitive.VOID;
  357. // return type is a class
  358. try {
  359. ret =
  360. // Types.getAssignableForm( ret, (Class)returnType );
  361. Types.castObject( ret, returnType, Types.ASSIGNMENT );
  362. } catch( UtilEvalError e )
  363. {
  364. // Point to return statement point if we had one.
  365. // (else it was implicit return? What's the case here?)
  366. SimpleNode node = callerInfo;
  367. if ( retControl != null )
  368. node = retControl.returnPoint;
  369. throw e.toEvalError(
  370. "Incorrect type returned from method: "
  371. + name + e.getMessage(), node, callstack );
  372. }
  373. }
  374. return ret;
  375. }
  376. public boolean hasModifier( String name ) {
  377. return modifiers != null && modifiers.hasModifier(name);
  378. }
  379. public String toString() {
  380. return "Scripted Method: "
  381. + StringUtil.methodString( name, getParameterTypes() );
  382. }
  383. }