PageRenderTime 39ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/jEdit/tags/jedit-4-2-pre14/bsh/Name.java

#
Java | 1067 lines | 543 code | 142 blank | 382 comment | 179 complexity | 970a4e022a9c830f8385f66a468f6c13 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.Array;
  35. import java.util.Hashtable;
  36. import java.io.*;
  37. import java.lang.reflect.InvocationTargetException;
  38. import java.lang.reflect.Method;
  39. /**
  40. What's in a name? I'll tell you...
  41. Name() is a somewhat ambiguous thing in the grammar and so is this.
  42. <p>
  43. This class is a name resolver. It holds a possibly ambiguous dot
  44. separated name and reference to a namespace in which it allegedly lives.
  45. It provides methods that attempt to resolve the name to various types of
  46. entities: e.g. an Object, a Class, a declared scripted BeanShell method.
  47. <p>
  48. Name objects are created by the factory method NameSpace getNameResolver(),
  49. which caches them subject to a class namespace change. This means that
  50. we can cache information about various types of resolution here.
  51. Currently very little if any information is cached. However with a future
  52. "optimize" setting that defeats certain dynamic behavior we might be able
  53. to cache quite a bit.
  54. */
  55. /*
  56. <strong>Implementation notes</strong>
  57. <pre>
  58. Thread safety: all of the work methods in this class must be synchronized
  59. because they share the internal intermediate evaluation state.
  60. Note about invokeMethod(): We could simply use resolveMethod and return
  61. the MethodInvoker (BshMethod or JavaMethod) however there is no easy way
  62. for the AST (BSHMehodInvocation) to use this as it doesn't have type
  63. information about the target to resolve overloaded methods.
  64. (In Java, overloaded methods are resolved at compile time... here they
  65. are, of necessity, dynamic). So it would have to do what we do here
  66. and cache by signature. We now do that for the client in Reflect.java.
  67. Note on this.caller resolution:
  68. Although references like these do work:
  69. this.caller.caller.caller... // works
  70. the equivalent using successive calls:
  71. // does *not* work
  72. for( caller=this.caller; caller != null; caller = caller.caller );
  73. is prohibited by the restriction that you can only call .caller on a
  74. literal this or caller reference. The effect is that magic caller
  75. reference only works through the current 'this' reference.
  76. The real explanation is that This referernces do not really know anything
  77. about their depth on the call stack. It might even be hard to define
  78. such a thing...
  79. For those purposes we provide :
  80. this.callstack
  81. </pre>
  82. */
  83. class Name implements java.io.Serializable
  84. {
  85. // These do not change during evaluation
  86. public NameSpace namespace;
  87. String value = null;
  88. // ---------------------------------------------------------
  89. // The following instance variables mutate during evaluation and should
  90. // be reset by the reset() method where necessary
  91. // For evaluation
  92. /** Remaining text to evaluate */
  93. private String evalName;
  94. /**
  95. The last part of the name evaluated. This is really only used for
  96. this, caller, and super resolution.
  97. */
  98. private String lastEvalName;
  99. private static String FINISHED = null; // null evalname and we're finished
  100. private Object evalBaseObject; // base object for current eval
  101. private int callstackDepth; // number of times eval hit 'this.caller'
  102. //
  103. // End mutable instance variables.
  104. // ---------------------------------------------------------
  105. // Begin Cached result structures
  106. // These are optimizations
  107. // Note: it's ok to cache class resolution here because when the class
  108. // space changes the namespace will discard cached names.
  109. /**
  110. The result is a class
  111. */
  112. Class asClass;
  113. /**
  114. The result is a static method call on the following class
  115. */
  116. Class classOfStaticMethod;
  117. // End Cached result structures
  118. private void reset() {
  119. evalName = value;
  120. evalBaseObject = null;
  121. callstackDepth = 0;
  122. }
  123. /**
  124. This constructor should *not* be used in general.
  125. Use NameSpace getNameResolver() which supports caching.
  126. @see NameSpace getNameResolver().
  127. */
  128. // I wish I could make this "friendly" to only NameSpace
  129. Name( NameSpace namespace, String s )
  130. {
  131. this.namespace = namespace;
  132. value = s;
  133. }
  134. /**
  135. Resolve possibly complex name to an object value.
  136. Throws EvalError on various failures.
  137. A null object value is indicated by a Primitive.NULL.
  138. A return type of Primitive.VOID comes from attempting to access
  139. an undefined variable.
  140. Some cases:
  141. myVariable
  142. myVariable.foo
  143. myVariable.foo.bar
  144. java.awt.GridBagConstraints.BOTH
  145. my.package.stuff.MyClass.someField.someField...
  146. Interpreter reference is necessary to allow resolution of
  147. "this.interpreter" magic field.
  148. CallStack reference is necessary to allow resolution of
  149. "this.caller" magic field.
  150. "this.callstack" magic field.
  151. */
  152. public Object toObject( CallStack callstack, Interpreter interpreter )
  153. throws UtilEvalError
  154. {
  155. return toObject( callstack, interpreter, false );
  156. }
  157. /**
  158. @see toObject()
  159. @param forceClass if true then resolution will only produce a class.
  160. This is necessary to disambiguate in cases where the grammar knows
  161. that we want a class; where in general the var path may be taken.
  162. */
  163. synchronized public Object toObject(
  164. CallStack callstack, Interpreter interpreter, boolean forceClass )
  165. throws UtilEvalError
  166. {
  167. reset();
  168. Object obj = null;
  169. while( evalName != null )
  170. obj = consumeNextObjectField(
  171. callstack, interpreter, forceClass, false/*autoalloc*/ );
  172. if ( obj == null )
  173. throw new InterpreterError("null value in toObject()");
  174. return obj;
  175. }
  176. private Object completeRound(
  177. String lastEvalName, String nextEvalName, Object returnObject )
  178. {
  179. if ( returnObject == null )
  180. throw new InterpreterError("lastEvalName = "+lastEvalName);
  181. this.lastEvalName = lastEvalName;
  182. this.evalName = nextEvalName;
  183. this.evalBaseObject = returnObject;
  184. return returnObject;
  185. }
  186. /**
  187. Get the next object by consuming one or more components of evalName.
  188. Often this consumes just one component, but if the name is a classname
  189. it will consume all of the components necessary to make the class
  190. identifier.
  191. */
  192. private Object consumeNextObjectField(
  193. CallStack callstack, Interpreter interpreter,
  194. boolean forceClass, boolean autoAllocateThis )
  195. throws UtilEvalError
  196. {
  197. /*
  198. Is it a simple variable name?
  199. Doing this first gives the correct Java precedence for vars
  200. vs. imported class names (at least in the simple case - see
  201. tests/precedence1.bsh). It should also speed things up a bit.
  202. */
  203. if ( (evalBaseObject == null && !isCompound(evalName) )
  204. && !forceClass )
  205. {
  206. Object obj = resolveThisFieldReference(
  207. callstack, namespace, interpreter, evalName, false );
  208. if ( obj != Primitive.VOID )
  209. return completeRound( evalName, FINISHED, obj );
  210. }
  211. /*
  212. Is it a bsh script variable reference?
  213. If we're just starting the eval of name (no base object)
  214. or we're evaluating relative to a This type reference check.
  215. */
  216. String varName = prefix(evalName, 1);
  217. if ( ( evalBaseObject == null || evalBaseObject instanceof This )
  218. && !forceClass )
  219. {
  220. if ( Interpreter.DEBUG )
  221. Interpreter.debug("trying to resolve variable: " + varName);
  222. Object obj;
  223. // switch namespace and special var visibility
  224. if ( evalBaseObject == null ) {
  225. obj = resolveThisFieldReference(
  226. callstack, namespace, interpreter, varName, false );
  227. } else {
  228. obj = resolveThisFieldReference(
  229. callstack, ((This)evalBaseObject).namespace,
  230. interpreter, varName, true );
  231. }
  232. if ( obj != Primitive.VOID )
  233. {
  234. // Resolved the variable
  235. if ( Interpreter.DEBUG )
  236. Interpreter.debug( "resolved variable: " + varName +
  237. " in namespace: "+namespace);
  238. return completeRound( varName, suffix(evalName), obj );
  239. }
  240. }
  241. /*
  242. Is it a class name?
  243. If we're just starting eval of name try to make it, else fail.
  244. */
  245. if ( evalBaseObject == null )
  246. {
  247. if ( Interpreter.DEBUG )
  248. Interpreter.debug( "trying class: " + evalName);
  249. /*
  250. Keep adding parts until we have a class
  251. */
  252. Class clas = null;
  253. int i = 1;
  254. String className = null;
  255. for(; i <= countParts(evalName); i++)
  256. {
  257. className = prefix(evalName, i);
  258. if ( (clas = namespace.getClass(className)) != null )
  259. break;
  260. }
  261. if ( clas != null ) {
  262. return completeRound(
  263. className,
  264. suffix( evalName, countParts(evalName)-i ),
  265. new ClassIdentifier(clas)
  266. );
  267. }
  268. // not a class (or variable per above)
  269. if ( Interpreter.DEBUG )
  270. Interpreter.debug( "not a class, trying var prefix "+evalName );
  271. }
  272. // No variable or class found in 'this' type ref.
  273. // if autoAllocateThis then create one; a child 'this'.
  274. if ( ( evalBaseObject == null || evalBaseObject instanceof This )
  275. && !forceClass && autoAllocateThis )
  276. {
  277. NameSpace targetNameSpace =
  278. ( evalBaseObject == null ) ?
  279. namespace : ((This)evalBaseObject).namespace;
  280. Object obj = new NameSpace(
  281. targetNameSpace, "auto: "+varName ).getThis( interpreter );
  282. targetNameSpace.setVariable( varName, obj, false );
  283. return completeRound( varName, suffix(evalName), obj );
  284. }
  285. /*
  286. If we didn't find a class or variable name (or prefix) above
  287. there are two possibilities:
  288. - If we are a simple name then we can pass as a void variable
  289. reference.
  290. - If we are compound then we must fail at this point.
  291. */
  292. if ( evalBaseObject == null ) {
  293. if ( !isCompound(evalName) ) {
  294. return completeRound( evalName, FINISHED, Primitive.VOID );
  295. } else
  296. throw new UtilEvalError(
  297. "Class or variable not found: " + evalName);
  298. }
  299. /*
  300. --------------------------------------------------------
  301. After this point we're definitely evaluating relative to
  302. a base object.
  303. --------------------------------------------------------
  304. */
  305. /*
  306. Do some basic validity checks.
  307. */
  308. if ( evalBaseObject == Primitive.NULL) // previous round produced null
  309. throw new UtilTargetError( new NullPointerException(
  310. "Null Pointer while evaluating: " +value ) );
  311. if ( evalBaseObject == Primitive.VOID) // previous round produced void
  312. throw new UtilEvalError(
  313. "Undefined variable or class name while evaluating: "+value);
  314. if ( evalBaseObject instanceof Primitive)
  315. throw new UtilEvalError("Can't treat primitive like an object. "+
  316. "Error while evaluating: "+value);
  317. /*
  318. Resolve relative to a class type
  319. static field, inner class, ?
  320. */
  321. if ( evalBaseObject instanceof ClassIdentifier )
  322. {
  323. Class clas = ((ClassIdentifier)evalBaseObject).getTargetClass();
  324. String field = prefix(evalName, 1);
  325. // Class qualified 'this' reference from inner class.
  326. // e.g. 'MyOuterClass.this'
  327. if ( field.equals("this") )
  328. {
  329. // find the enclosing class instance space of the class name
  330. NameSpace ns = namespace;
  331. while ( ns != null )
  332. {
  333. // getClassInstance() throws exception if not there
  334. if ( ns.classInstance != null
  335. && ns.classInstance.getClass() == clas
  336. )
  337. return completeRound(
  338. field, suffix(evalName), ns.classInstance );
  339. ns=ns.getParent();
  340. }
  341. throw new UtilEvalError(
  342. "Can't find enclosing 'this' instance of class: "+clas);
  343. }
  344. Object obj = null;
  345. // static field?
  346. try {
  347. if ( Interpreter.DEBUG )
  348. Interpreter.debug("Name call to getStaticField, class: "
  349. +clas+", field:"+field);
  350. obj = Reflect.getStaticField(clas, field);
  351. } catch( ReflectError e ) {
  352. if ( Interpreter.DEBUG )
  353. Interpreter.debug("field reflect error: "+e);
  354. }
  355. // inner class?
  356. if ( obj == null ) {
  357. String iclass = clas.getName()+"$"+field;
  358. Class c = namespace.getClass( iclass );
  359. if ( c != null )
  360. obj = new ClassIdentifier(c);
  361. }
  362. if ( obj == null )
  363. throw new UtilEvalError(
  364. "No static field or inner class: "
  365. + field + " of " + clas );
  366. return completeRound( field, suffix(evalName), obj );
  367. }
  368. /*
  369. If we've fallen through here we are no longer resolving to
  370. a class type.
  371. */
  372. if ( forceClass )
  373. throw new UtilEvalError(
  374. value +" does not resolve to a class name." );
  375. /*
  376. Some kind of field access?
  377. */
  378. String field = prefix(evalName, 1);
  379. // length access on array?
  380. if ( field.equals("length") && evalBaseObject.getClass().isArray() )
  381. {
  382. Object obj = new Primitive(Array.getLength(evalBaseObject));
  383. return completeRound( field, suffix(evalName), obj );
  384. }
  385. // Check for field on object
  386. // Note: could eliminate throwing the exception somehow
  387. try {
  388. Object obj = Reflect.getObjectField(evalBaseObject, field);
  389. return completeRound( field, suffix(evalName), obj );
  390. } catch(ReflectError e) { /* not a field */ }
  391. // if we get here we have failed
  392. throw new UtilEvalError(
  393. "Cannot access field: " + field + ", on object: " + evalBaseObject);
  394. }
  395. /**
  396. Resolve a variable relative to a This reference.
  397. This is the general variable resolution method, accomodating special
  398. fields from the This context. Together the namespace and interpreter
  399. comprise the This context. The callstack, if available allows for the
  400. this.caller construct.
  401. Optionally interpret special "magic" field names: e.g. interpreter.
  402. <p/>
  403. @param callstack may be null, but this is only legitimate in special
  404. cases where we are sure resolution will not involve this.caller.
  405. @param namespace the namespace of the this reference (should be the
  406. same as the top of the stack?
  407. */
  408. Object resolveThisFieldReference(
  409. CallStack callstack, NameSpace thisNameSpace, Interpreter interpreter,
  410. String varName, boolean specialFieldsVisible )
  411. throws UtilEvalError
  412. {
  413. if ( varName.equals("this") )
  414. {
  415. /*
  416. Somewhat of a hack. If the special fields are visible (we're
  417. operating relative to a 'this' type already) dissallow further
  418. .this references to prevent user from skipping to things like
  419. super.this.caller
  420. */
  421. if ( specialFieldsVisible )
  422. throw new UtilEvalError("Redundant to call .this on This type");
  423. // Allow getThis() to work through BlockNameSpace to the method
  424. // namespace
  425. // XXX re-eval this... do we need it?
  426. This ths = thisNameSpace.getThis( interpreter );
  427. thisNameSpace= ths.getNameSpace();
  428. Object result = ths;
  429. NameSpace classNameSpace = getClassNameSpace( thisNameSpace );
  430. if ( classNameSpace != null )
  431. {
  432. if ( isCompound( evalName ) )
  433. result = classNameSpace.getThis( interpreter );
  434. else
  435. result = classNameSpace.getClassInstance();
  436. }
  437. return result;
  438. }
  439. /*
  440. Some duplication for "super". See notes for "this" above
  441. If we're in an enclsing class instance and have a superclass
  442. instance our super is the superclass instance.
  443. */
  444. if ( varName.equals("super") )
  445. {
  446. //if ( specialFieldsVisible )
  447. //throw new UtilEvalError("Redundant to call .this on This type");
  448. // Allow getSuper() to through BlockNameSpace to the method's super
  449. This ths = thisNameSpace.getSuper( interpreter );
  450. thisNameSpace = ths.getNameSpace();
  451. // super is now the closure's super or class instance
  452. // XXXX re-evaluate this
  453. // can getSuper work by itself now?
  454. // If we're a class instance and the parent is also a class instance
  455. // then super means our parent.
  456. if (
  457. thisNameSpace.getParent() != null
  458. && thisNameSpace.getParent().isClass
  459. )
  460. ths = thisNameSpace.getParent().getThis( interpreter );
  461. return ths;
  462. }
  463. Object obj = null;
  464. if ( varName.equals("global") )
  465. obj = thisNameSpace.getGlobal( interpreter );
  466. if ( obj == null && specialFieldsVisible )
  467. {
  468. if (varName.equals("namespace"))
  469. obj = thisNameSpace;
  470. else if (varName.equals("variables"))
  471. obj = thisNameSpace.getVariableNames();
  472. else if (varName.equals("methods"))
  473. obj = thisNameSpace.getMethodNames();
  474. else if ( varName.equals("interpreter") )
  475. if ( lastEvalName.equals("this") )
  476. obj = interpreter;
  477. else
  478. throw new UtilEvalError(
  479. "Can only call .interpreter on literal 'this'");
  480. }
  481. if ( obj == null && specialFieldsVisible && varName.equals("caller") )
  482. {
  483. if ( lastEvalName.equals("this") || lastEvalName.equals("caller") )
  484. {
  485. // get the previous context (see notes for this class)
  486. if ( callstack == null )
  487. throw new InterpreterError("no callstack");
  488. obj = callstack.get( ++callstackDepth ).getThis(
  489. interpreter );
  490. }
  491. else
  492. throw new UtilEvalError(
  493. "Can only call .caller on literal 'this' or literal '.caller'");
  494. // early return
  495. return obj;
  496. }
  497. if ( obj == null && specialFieldsVisible
  498. && varName.equals("callstack") )
  499. {
  500. if ( lastEvalName.equals("this") )
  501. {
  502. // get the previous context (see notes for this class)
  503. if ( callstack == null )
  504. throw new InterpreterError("no callstack");
  505. obj = callstack;
  506. }
  507. else
  508. throw new UtilEvalError(
  509. "Can only call .callstack on literal 'this'");
  510. }
  511. if ( obj == null )
  512. obj = thisNameSpace.getVariable(varName);
  513. if ( obj == null )
  514. throw new InterpreterError("null this field ref:"+varName);
  515. return obj;
  516. }
  517. /**
  518. @return the enclosing class body namespace or null if not in a class.
  519. */
  520. static NameSpace getClassNameSpace( NameSpace thisNameSpace )
  521. {
  522. NameSpace classNameSpace = null;
  523. // is a class instance
  524. //if ( thisNameSpace.classInstance != null )
  525. if ( thisNameSpace.isClass )
  526. return thisNameSpace;
  527. if ( thisNameSpace.isMethod
  528. && thisNameSpace.getParent() != null
  529. //&& thisNameSpace.getParent().classInstance != null
  530. && thisNameSpace.getParent().isClass
  531. )
  532. return thisNameSpace.getParent();
  533. return null;
  534. }
  535. /**
  536. Check the cache, else use toObject() to try to resolve to a class
  537. identifier.
  538. @throws ClassNotFoundException on class not found.
  539. @throws ClassPathException (type of EvalError) on special case of
  540. ambiguous unqualified name after super import.
  541. */
  542. synchronized public Class toClass()
  543. throws ClassNotFoundException, UtilEvalError
  544. {
  545. if ( asClass != null )
  546. return asClass;
  547. reset();
  548. // "var" means untyped, return null class
  549. if ( evalName.equals("var") )
  550. return asClass = null;
  551. /* Try straightforward class name first */
  552. Class clas = namespace.getClass( evalName );
  553. if ( clas == null )
  554. {
  555. /*
  556. Try toObject() which knows how to work through inner classes
  557. and see what we end up with
  558. */
  559. Object obj = null;
  560. try {
  561. // Null interpreter and callstack references.
  562. // class only resolution should not require them.
  563. obj = toObject( null, null, true );
  564. } catch ( UtilEvalError e ) { }; // couldn't resolve it
  565. if ( obj instanceof ClassIdentifier )
  566. clas = ((ClassIdentifier)obj).getTargetClass();
  567. }
  568. if ( clas == null )
  569. throw new ClassNotFoundException(
  570. "Class: " + value+ " not found in namespace");
  571. asClass = clas;
  572. return asClass;
  573. }
  574. /*
  575. */
  576. synchronized public LHS toLHS(
  577. CallStack callstack, Interpreter interpreter )
  578. throws UtilEvalError
  579. {
  580. // Should clean this up to a single return statement
  581. reset();
  582. LHS lhs;
  583. // Simple (non-compound) variable assignment e.g. x=5;
  584. if ( !isCompound(evalName) )
  585. {
  586. if ( evalName.equals("this") )
  587. throw new UtilEvalError("Can't assign to 'this'." );
  588. // Interpreter.debug("Simple var LHS...");
  589. lhs = new LHS( namespace, evalName, false/*bubble up if allowed*/);
  590. return lhs;
  591. }
  592. // Field e.g. foo.bar=5;
  593. Object obj = null;
  594. try {
  595. while( evalName != null && isCompound( evalName ) )
  596. {
  597. obj = consumeNextObjectField( callstack, interpreter,
  598. false/*forcclass*/, true/*autoallocthis*/ );
  599. }
  600. }
  601. catch( UtilEvalError e ) {
  602. throw new UtilEvalError( "LHS evaluation: " + e.getMessage() );
  603. }
  604. // Finished eval and its a class.
  605. if ( evalName == null && obj instanceof ClassIdentifier )
  606. throw new UtilEvalError("Can't assign to class: " + value );
  607. if ( obj == null )
  608. throw new UtilEvalError("Error in LHS: " + value );
  609. // e.g. this.x=5; or someThisType.x=5;
  610. if ( obj instanceof This )
  611. {
  612. // dissallow assignment to magic fields
  613. if (
  614. evalName.equals("namespace")
  615. || evalName.equals("variables")
  616. || evalName.equals("methods")
  617. || evalName.equals("caller")
  618. )
  619. throw new UtilEvalError(
  620. "Can't assign to special variable: "+evalName );
  621. Interpreter.debug("found This reference evaluating LHS");
  622. /*
  623. If this was a literal "super" reference then we allow recursion
  624. in setting the variable to get the normal effect of finding the
  625. nearest definition starting at the super scope. On any other
  626. resolution qualified by a 'this' type reference we want to set
  627. the variable directly in that scope. e.g. this.x=5; or
  628. someThisType.x=5;
  629. In the old scoping rules super didn't do this.
  630. */
  631. boolean localVar = !lastEvalName.equals("super");
  632. return new LHS( ((This)obj).namespace, evalName, localVar );
  633. }
  634. if ( evalName != null )
  635. {
  636. try {
  637. if ( obj instanceof ClassIdentifier )
  638. {
  639. Class clas = ((ClassIdentifier)obj).getTargetClass();
  640. lhs = Reflect.getLHSStaticField(clas, evalName);
  641. return lhs;
  642. } else {
  643. lhs = Reflect.getLHSObjectField(obj, evalName);
  644. return lhs;
  645. }
  646. } catch(ReflectError e) {
  647. throw new UtilEvalError("Field access: "+e);
  648. }
  649. }
  650. throw new InterpreterError("Internal error in lhs...");
  651. }
  652. /**
  653. Invoke the method identified by this name.
  654. Performs caching of method resolution using SignatureKey.
  655. <p>
  656. Name contains a wholely unqualfied messy name; resolve it to
  657. ( object | static prefix ) + method name and invoke.
  658. <p>
  659. The interpreter is necessary to support 'this.interpreter' references
  660. in the called code. (e.g. debug());
  661. <p>
  662. <pre>
  663. Some cases:
  664. // dynamic
  665. local();
  666. myVariable.foo();
  667. myVariable.bar.blah.foo();
  668. // static
  669. java.lang.Integer.getInteger("foo");
  670. </pre>
  671. */
  672. public Object invokeMethod(
  673. Interpreter interpreter, Object[] args, CallStack callstack,
  674. SimpleNode callerInfo
  675. )
  676. throws UtilEvalError, EvalError, ReflectError, InvocationTargetException
  677. {
  678. String methodName = Name.suffix(value, 1);
  679. BshClassManager bcm = interpreter.getClassManager();
  680. NameSpace namespace = callstack.top();
  681. // Optimization - If classOfStaticMethod is set then we have already
  682. // been here and determined that this is a static method invocation.
  683. // Note: maybe factor this out with path below... clean up.
  684. if ( classOfStaticMethod != null )
  685. {
  686. return Reflect.invokeStaticMethod(
  687. bcm, classOfStaticMethod, methodName, args );
  688. }
  689. if ( !Name.isCompound(value) )
  690. return invokeLocalMethod(
  691. interpreter, args, callstack, callerInfo );
  692. // Note: if we want methods declared inside blocks to be accessible via
  693. // this.methodname() inside the block we could handle it here as a
  694. // special case. See also resolveThisFieldReference() special handling
  695. // for BlockNameSpace case. They currently work via the direct name
  696. // e.g. methodName().
  697. String prefix = Name.prefix(value);
  698. // Superclass method invocation? (e.g. super.foo())
  699. if ( prefix.equals("super") && Name.countParts(value) == 2 )
  700. {
  701. NameSpace classNameSpace = getClassNameSpace( namespace );
  702. if ( classNameSpace != null )
  703. {
  704. Object instance = classNameSpace.getClassInstance();
  705. return ClassGenerator.getClassGenerator()
  706. .invokeSuperclassMethod( bcm, instance, methodName, args );
  707. }
  708. }
  709. // Find target object or class identifier
  710. Name targetName = namespace.getNameResolver( prefix );
  711. Object obj = targetName.toObject( callstack, interpreter );
  712. if ( obj == Primitive.VOID )
  713. throw new UtilEvalError( "Attempt to resolve method: "+methodName
  714. +"() on undefined variable or class name: "+targetName);
  715. // if we've got an object, resolve the method
  716. if ( !(obj instanceof ClassIdentifier) ) {
  717. if (obj instanceof Primitive) {
  718. if (obj == Primitive.NULL)
  719. throw new UtilTargetError( new NullPointerException(
  720. "Null Pointer in Method Invocation" ) );
  721. // some other primitive
  722. // should avoid calling methods on primitive, as we do
  723. // in Name (can't treat primitive like an object message)
  724. // but the hole is useful right now.
  725. if ( Interpreter.DEBUG )
  726. interpreter.debug(
  727. "Attempt to access method on primitive..."
  728. + " allowing bsh.Primitive to peek through for debugging");
  729. }
  730. // found an object and it's not an undefined variable
  731. return Reflect.invokeObjectMethod(
  732. obj, methodName, args, interpreter, callstack, callerInfo );
  733. }
  734. // It's a class
  735. // try static method
  736. if ( Interpreter.DEBUG )
  737. Interpreter.debug("invokeMethod: trying static - " + targetName);
  738. Class clas = ((ClassIdentifier)obj).getTargetClass();
  739. // cache the fact that this is a static method invocation on this class
  740. classOfStaticMethod = clas;
  741. if ( clas != null )
  742. return Reflect.invokeStaticMethod( bcm, clas, methodName, args );
  743. // return null; ???
  744. throw new UtilEvalError("invokeMethod: unknown target: " + targetName);
  745. }
  746. /**
  747. Invoke a locally declared method or a bsh command.
  748. If the method is not already declared in the namespace then try
  749. to load it as a resource from the imported command path (e.g.
  750. /bsh/commands)
  751. */
  752. /*
  753. Note: the bsh command code should probably not be here... we need to
  754. scope it by the namespace that imported the command... so it probably
  755. needs to be integrated into NameSpace.
  756. */
  757. private Object invokeLocalMethod(
  758. Interpreter interpreter, Object[] args, CallStack callstack,
  759. SimpleNode callerInfo
  760. )
  761. throws EvalError/*, ReflectError, InvocationTargetException*/
  762. {
  763. if ( Interpreter.DEBUG )
  764. Interpreter.debug( "invokeLocalMethod: " + value );
  765. if ( interpreter == null )
  766. throw new InterpreterError(
  767. "invokeLocalMethod: interpreter = null");
  768. String commandName = value;
  769. Class [] argTypes = Types.getTypes( args );
  770. // Check for existing method
  771. BshMethod meth = null;
  772. try {
  773. meth = namespace.getMethod( commandName, argTypes );
  774. } catch ( UtilEvalError e ) {
  775. throw e.toEvalError(
  776. "Local method invocation", callerInfo, callstack );
  777. }
  778. // If defined, invoke it
  779. if ( meth != null )
  780. return meth.invoke( args, interpreter, callstack, callerInfo );
  781. BshClassManager bcm = interpreter.getClassManager();
  782. // Look for a BeanShell command
  783. Object commandObject;
  784. try {
  785. commandObject = namespace.getCommand(
  786. commandName, argTypes, interpreter );
  787. } catch ( UtilEvalError e ) {
  788. throw e.toEvalError("Error loading command: ",
  789. callerInfo, callstack );
  790. }
  791. // should try to print usage here if nothing found
  792. if ( commandObject == null )
  793. {
  794. // Look for a default invoke() handler method in the namespace
  795. // Note: this code duplicates that in This.java... should it?
  796. // Call on 'This' can never be a command
  797. BshMethod invokeMethod = null;
  798. try {
  799. invokeMethod = namespace.getMethod(
  800. "invoke", new Class [] { null, null } );
  801. } catch ( UtilEvalError e ) {
  802. throw e.toEvalError(
  803. "Local method invocation", callerInfo, callstack );
  804. }
  805. if ( invokeMethod != null )
  806. return invokeMethod.invoke(
  807. new Object [] { commandName, args },
  808. interpreter, callstack, callerInfo );
  809. throw new EvalError( "Command not found: "
  810. +StringUtil.methodString( commandName, argTypes ),
  811. callerInfo, callstack );
  812. }
  813. if ( commandObject instanceof BshMethod )
  814. return ((BshMethod)commandObject).invoke(
  815. args, interpreter, callstack, callerInfo );
  816. if ( commandObject instanceof Class )
  817. try {
  818. return Reflect.invokeCompiledCommand(
  819. ((Class)commandObject), args, interpreter, callstack );
  820. } catch ( UtilEvalError e ) {
  821. throw e.toEvalError("Error invoking compiled command: ",
  822. callerInfo, callstack );
  823. }
  824. throw new InterpreterError("invalid command type");
  825. }
  826. /*
  827. private String getHelp( String name )
  828. throws UtilEvalError
  829. {
  830. try {
  831. // should check for null namespace here
  832. return get( "bsh.help."+name, null/interpreter/ );
  833. } catch ( Exception e ) {
  834. return "usage: "+name;
  835. }
  836. }
  837. private String getHelp( Class commandClass )
  838. throws UtilEvalError
  839. {
  840. try {
  841. return (String)Reflect.invokeStaticMethod(
  842. null/bcm/, commandClass, "usage", null );
  843. } catch( Exception e )
  844. return "usage: "+name;
  845. }
  846. }
  847. */
  848. // Static methods that operate on compound ('.' separated) names
  849. // I guess we could move these to StringUtil someday
  850. public static boolean isCompound(String value)
  851. {
  852. return value.indexOf('.') != -1 ;
  853. //return countParts(value) > 1;
  854. }
  855. static int countParts(String value)
  856. {
  857. if(value == null)
  858. return 0;
  859. int count = 0;
  860. int index = -1;
  861. while((index = value.indexOf('.', index + 1)) != -1)
  862. count++;
  863. return count + 1;
  864. }
  865. static String prefix(String value)
  866. {
  867. if(!isCompound(value))
  868. return null;
  869. return prefix(value, countParts(value) - 1);
  870. }
  871. static String prefix(String value, int parts)
  872. {
  873. if (parts < 1 )
  874. return null;
  875. int count = 0;
  876. int index = -1;
  877. while( ((index = value.indexOf('.', index + 1)) != -1)
  878. && (++count < parts) )
  879. { ; }
  880. return (index == -1) ? value : value.substring(0, index);
  881. }
  882. static String suffix(String name)
  883. {
  884. if(!isCompound(name))
  885. return null;
  886. return suffix(name, countParts(name) - 1);
  887. }
  888. public static String suffix(String value, int parts)
  889. {
  890. if (parts < 1)
  891. return null;
  892. int count = 0;
  893. int index = value.length() + 1;
  894. while ( ((index = value.lastIndexOf('.', index - 1)) != -1)
  895. && (++count < parts) );
  896. return (index == -1) ? value : value.substring(index + 1);
  897. }
  898. // end compound name routines
  899. public String toString() { return value; }
  900. }