PageRenderTime 45ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

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

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