PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

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