PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

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

#
Java | 1578 lines | 773 code | 179 blank | 626 comment | 212 complexity | a1083c282c5f9784f7d0575143e31e1b 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.util.*;
  35. import java.io.InputStream;
  36. import java.io.BufferedReader;
  37. import java.io.InputStreamReader;
  38. import java.io.IOException;
  39. import java.lang.reflect.Method;
  40. import java.lang.reflect.Field;
  41. /**
  42. A namespace in which methods, variables, and imports (class names) live.
  43. This is package public because it is used in the implementation of some
  44. bsh commands. However for normal use you should be using methods on
  45. bsh.Interpreter to interact with your scripts.
  46. <p>
  47. A bsh.This object is a thin layer over a NameSpace that associates it with
  48. an Interpreter instance. Together they comprise a Bsh scripted object
  49. context.
  50. <p>
  51. Note: I'd really like to use collections here, but we have to keep this
  52. compatible with JDK1.1
  53. */
  54. /*
  55. Thanks to Slava Pestov (of jEdit fame) for import caching enhancements.
  56. Note: This class has gotten too big. It should be broken down a bit.
  57. */
  58. public class NameSpace
  59. implements java.io.Serializable, BshClassManager.Listener,
  60. NameSource
  61. {
  62. public static final NameSpace JAVACODE =
  63. new NameSpace((BshClassManager)null, "Called from compiled Java code.");
  64. static {
  65. JAVACODE.isMethod = true;
  66. }
  67. // Begin instance data
  68. // Note: if we add something here we should reset it in the clear() method.
  69. /**
  70. The name of this namespace. If the namespace is a method body
  71. namespace then this is the name of the method. If it's a class or
  72. class instance then it's the name of the class.
  73. */
  74. private String nsName;
  75. private NameSpace parent;
  76. private Hashtable variables;
  77. private Hashtable methods;
  78. protected Hashtable importedClasses;
  79. private Vector importedPackages;
  80. private Vector importedObjects;
  81. private Vector importedStatic;
  82. private Vector importedCommands;
  83. private String packageName;
  84. transient private BshClassManager classManager;
  85. // See notes in getThis()
  86. private This thisReference;
  87. /** Name resolver objects */
  88. private Hashtable names;
  89. /** The node associated with the creation of this namespace.
  90. This is used support getInvocationLine() and getInvocationText(). */
  91. SimpleNode callerInfoNode;
  92. /**
  93. Note that the namespace is a method body namespace. This is used for
  94. printing stack traces in exceptions.
  95. */
  96. boolean isMethod;
  97. /**
  98. Note that the namespace is a class body or class instance namespace.
  99. This is used for controlling static/object import precedence, etc.
  100. */
  101. /*
  102. Note: We will ll move this behavior out to a subclass of
  103. NameSpace, but we'll start here.
  104. */
  105. boolean isClass;
  106. Class classStatic;
  107. Object classInstance;
  108. void setClassStatic( Class clas ) {
  109. this.classStatic = clas;
  110. importStatic( clas );
  111. }
  112. void setClassInstance( Object instance ) {
  113. this.classInstance = instance;
  114. importObject( instance );
  115. }
  116. Object getClassInstance()
  117. throws UtilEvalError
  118. {
  119. if ( classInstance != null )
  120. return classInstance;
  121. if ( classStatic != null
  122. //|| ( getParent()!=null && getParent().classStatic != null )
  123. )
  124. throw new UtilEvalError(
  125. "Can't refer to class instance from static context.");
  126. else
  127. throw new InterpreterError(
  128. "Can't resolve class instance 'this' in: "+this);
  129. }
  130. /**
  131. Local class cache for classes resolved through this namespace using
  132. getClass() (taking into account imports). Only unqualified class names
  133. are cached here (those which might be imported). Qualified names are
  134. always absolute and are cached by BshClassManager.
  135. */
  136. transient private Hashtable classCache;
  137. // End instance data
  138. // Begin constructors
  139. /**
  140. @parent the parent namespace of this namespace. Child namespaces
  141. inherit all variables and methods of their parent and can (of course)
  142. override / shadow them.
  143. */
  144. public NameSpace( NameSpace parent, String name )
  145. {
  146. // Note: in this case parent must have a class manager.
  147. this( parent, null, name );
  148. }
  149. public NameSpace( BshClassManager classManager, String name )
  150. {
  151. this( null, classManager, name );
  152. }
  153. public NameSpace(
  154. NameSpace parent, BshClassManager classManager, String name )
  155. {
  156. // We might want to do this here rather than explicitly in Interpreter
  157. // for global (see also prune())
  158. //if ( classManager == null && (parent == null ) )
  159. // create our own class manager?
  160. setName(name);
  161. setParent(parent);
  162. setClassManager( classManager );
  163. // Register for notification of classloader change
  164. if ( classManager != null )
  165. classManager.addListener(this);
  166. }
  167. // End constructors
  168. public void setName( String name ) {
  169. this.nsName = name;
  170. }
  171. /**
  172. The name of this namespace. If the namespace is a method body
  173. namespace then this is the name of the method. If it's a class or
  174. class instance then it's the name of the class.
  175. */
  176. public String getName() {
  177. return this.nsName;
  178. }
  179. /**
  180. Set the node associated with the creation of this namespace.
  181. This is used in debugging and to support the getInvocationLine()
  182. and getInvocationText() methods.
  183. */
  184. void setNode( SimpleNode node ) {
  185. callerInfoNode = node;
  186. }
  187. /**
  188. */
  189. SimpleNode getNode()
  190. {
  191. if ( callerInfoNode != null )
  192. return callerInfoNode;
  193. if ( parent != null )
  194. return parent.getNode();
  195. else
  196. return null;
  197. }
  198. /**
  199. Resolve name to an object through this namespace.
  200. */
  201. public Object get( String name, Interpreter interpreter )
  202. throws UtilEvalError
  203. {
  204. CallStack callstack = new CallStack( this );
  205. return getNameResolver( name ).toObject( callstack, interpreter );
  206. }
  207. public void setVariable(String name, Object value) throws UtilEvalError
  208. {
  209. setVariable(name,value,false);
  210. }
  211. /**
  212. Set the variable through this namespace.
  213. This method obeys the LOCALSCOPING property to determine how variables
  214. are set.
  215. <p>
  216. Note: this method is primarily intended for use internally. If you use
  217. this method outside of the bsh package and wish to set variables with
  218. primitive values you will have to wrap them using bsh.Primitive.
  219. @see bsh.Primitive
  220. <p>
  221. Setting a new variable (which didn't exist before) or removing
  222. a variable causes a namespace change.
  223. @param strictJava specifies whether strict java rules are applied.
  224. */
  225. public void setVariable( String name, Object value, boolean strictJava )
  226. throws UtilEvalError
  227. {
  228. // if localscoping switch follow strictJava, else recurse
  229. boolean recurse = Interpreter.LOCALSCOPING ? strictJava : true;
  230. setVariable( name, value, strictJava, recurse );
  231. }
  232. /**
  233. Set a variable explicitly in the local scope.
  234. */
  235. void setLocalVariable(
  236. String name, Object value, boolean strictJava )
  237. throws UtilEvalError
  238. {
  239. setVariable( name, value, strictJava, false/*recurse*/ );
  240. }
  241. /**
  242. Set the value of a the variable 'name' through this namespace.
  243. The variable may be an existing or non-existing variable.
  244. It may live in this namespace or in a parent namespace if recurse is
  245. true.
  246. <p>
  247. Note: This method is not public and does *not* know about LOCALSCOPING.
  248. Its caller methods must set recurse intelligently in all situations
  249. (perhaps based on LOCALSCOPING).
  250. <p>
  251. Note: this method is primarily intended for use internally. If you use
  252. this method outside of the bsh package and wish to set variables with
  253. primitive values you will have to wrap them using bsh.Primitive.
  254. @see bsh.Primitive
  255. <p>
  256. Setting a new variable (which didn't exist before) or removing
  257. a variable causes a namespace change.
  258. @param strictJava specifies whether strict java rules are applied.
  259. @param recurse determines whether we will search for the variable in
  260. our parent's scope before assigning locally.
  261. */
  262. void setVariable(
  263. String name, Object value, boolean strictJava, boolean recurse )
  264. throws UtilEvalError
  265. {
  266. if ( variables == null )
  267. variables = new Hashtable();
  268. // primitives should have been wrapped
  269. if ( value == null ) {
  270. // don't break jEdit core and plugins!
  271. //throw new InterpreterError("null variable value");
  272. unsetVariable(name);
  273. return;
  274. }
  275. // Locate the variable definition if it exists.
  276. Variable existing = getVariableImpl( name, recurse );
  277. // Found an existing variable here (or above if recurse allowed)
  278. if ( existing != null )
  279. {
  280. try {
  281. existing.setValue( value, Variable.ASSIGNMENT );
  282. } catch ( UtilEvalError e ) {
  283. throw new UtilEvalError(
  284. "Variable assignment: " + name + ": " + e.getMessage());
  285. }
  286. } else
  287. // No previous variable definition found here (or above if recurse)
  288. {
  289. if ( strictJava )
  290. throw new UtilEvalError(
  291. "(Strict Java mode) Assignment to undeclared variable: "
  292. +name );
  293. // If recurse, set global untyped var, else set it here.
  294. //NameSpace varScope = recurse ? getGlobal() : this;
  295. // This modification makes default allocation local
  296. NameSpace varScope = this;
  297. varScope.variables.put(
  298. name, new Variable( name, value, null/*modifiers*/ ) );
  299. // nameSpaceChanged() on new variable addition
  300. nameSpaceChanged();
  301. }
  302. }
  303. /**
  304. Remove the variable from the namespace.
  305. */
  306. public void unsetVariable( String name )
  307. {
  308. variables.remove( name );
  309. nameSpaceChanged();
  310. }
  311. /**
  312. Get the names of variables defined in this namespace.
  313. (This does not show variables in parent namespaces).
  314. */
  315. public String [] getVariableNames() {
  316. if ( variables == null )
  317. return new String [0];
  318. else
  319. return enumerationToStringArray( variables.keys() );
  320. }
  321. /**
  322. Get the names of methods declared in this namespace.
  323. (This does not include methods in parent namespaces).
  324. */
  325. public String [] getMethodNames()
  326. {
  327. if ( methods == null )
  328. return new String [0];
  329. else
  330. return enumerationToStringArray( methods.keys() );
  331. }
  332. /**
  333. Get the methods defined in this namespace.
  334. (This does not show methods in parent namespaces).
  335. Note: This will probably be renamed getDeclaredMethods()
  336. */
  337. public BshMethod [] getMethods()
  338. {
  339. if ( methods == null )
  340. return new BshMethod [0];
  341. else
  342. return flattenMethodCollection( methods.elements() );
  343. }
  344. private String [] enumerationToStringArray( Enumeration e ) {
  345. Vector v = new Vector();
  346. while ( e.hasMoreElements() )
  347. v.addElement( e.nextElement() );
  348. String [] sa = new String [ v.size() ];
  349. v.copyInto( sa );
  350. return sa;
  351. }
  352. /**
  353. Flatten the vectors of overloaded methods to a single array.
  354. @see #getMethods()
  355. */
  356. private BshMethod [] flattenMethodCollection( Enumeration e ) {
  357. Vector v = new Vector();
  358. while ( e.hasMoreElements() ) {
  359. Object o = e.nextElement();
  360. if ( o instanceof BshMethod )
  361. v.addElement( o );
  362. else {
  363. Vector ov = (Vector)o;
  364. for(int i=0; i<ov.size(); i++)
  365. v.addElement( ov.elementAt( i ) );
  366. }
  367. }
  368. BshMethod [] bma = new BshMethod [ v.size() ];
  369. v.copyInto( bma );
  370. return bma;
  371. }
  372. /**
  373. Get the parent namespace.
  374. Note: this isn't quite the same as getSuper().
  375. getSuper() returns 'this' if we are at the root namespace.
  376. */
  377. public NameSpace getParent() {
  378. return parent;
  379. }
  380. /**
  381. Get the parent namespace' This reference or this namespace' This
  382. reference if we are the top.
  383. */
  384. public This getSuper( Interpreter declaringInterpreter )
  385. {
  386. if ( parent != null )
  387. return parent.getThis( declaringInterpreter );
  388. else
  389. return getThis( declaringInterpreter );
  390. }
  391. /**
  392. Get the top level namespace or this namespace if we are the top.
  393. Note: this method should probably return type bsh.This to be consistent
  394. with getThis();
  395. */
  396. public This getGlobal( Interpreter declaringInterpreter )
  397. {
  398. if ( parent != null )
  399. return parent.getGlobal( declaringInterpreter );
  400. else
  401. return getThis( declaringInterpreter );
  402. }
  403. /**
  404. A This object is a thin layer over a namespace, comprising a bsh object
  405. context. It handles things like the interface types the bsh object
  406. supports and aspects of method invocation on it.
  407. <p>
  408. The declaringInterpreter is here to support callbacks from Java through
  409. generated proxies. The scripted object "remembers" who created it for
  410. things like printing messages and other per-interpreter phenomenon
  411. when called externally from Java.
  412. */
  413. /*
  414. Note: we need a singleton here so that things like 'this == this' work
  415. (and probably a good idea for speed).
  416. Caching a single instance here seems technically incorrect,
  417. considering the declaringInterpreter could be different under some
  418. circumstances. (Case: a child interpreter running a source() / eval()
  419. command ). However the effect is just that the main interpreter that
  420. executes your script should be the one involved in call-backs from Java.
  421. I do not know if there are corner cases where a child interpreter would
  422. be the first to use a This reference in a namespace or if that would
  423. even cause any problems if it did... We could do some experiments
  424. to find out... and if necessary we could cache on a per interpreter
  425. basis if we had weak references... We might also look at skipping
  426. over child interpreters and going to the parent for the declaring
  427. interpreter, so we'd be sure to get the top interpreter.
  428. */
  429. This getThis( Interpreter declaringInterpreter )
  430. {
  431. if ( thisReference == null )
  432. thisReference = This.getThis( this, declaringInterpreter );
  433. return thisReference;
  434. }
  435. public BshClassManager getClassManager()
  436. {
  437. if ( classManager != null )
  438. return classManager;
  439. if ( parent != null && parent != JAVACODE )
  440. return parent.getClassManager();
  441. System.out.println("experiment: creating class manager");
  442. classManager = BshClassManager.createClassManager( null/*interp*/ );
  443. //Interpreter.debug("No class manager namespace:" +this);
  444. return classManager;
  445. }
  446. void setClassManager( BshClassManager classManager ) {
  447. this.classManager = classManager;
  448. }
  449. /**
  450. Used for serialization
  451. */
  452. public void prune()
  453. {
  454. // Cut off from parent, we must have our own class manager.
  455. // Can't do this in the run() command (needs to resolve stuff)
  456. // Should we do it by default when we create a namespace will no
  457. // parent of class manager?
  458. if ( this.classManager == null )
  459. // XXX if we keep the createClassManager in getClassManager then we can axe
  460. // this?
  461. setClassManager(
  462. BshClassManager.createClassManager( null/*interp*/ ) );
  463. setParent( null );
  464. }
  465. public void setParent( NameSpace parent )
  466. {
  467. this.parent = parent;
  468. // If we are disconnected from root we need to handle the def imports
  469. if ( parent == null )
  470. loadDefaultImports();
  471. }
  472. /**
  473. Get the specified variable in this namespace or a parent namespace.
  474. <p>
  475. Note: this method is primarily intended for use internally. If you use
  476. this method outside of the bsh package you will have to use
  477. Primitive.unwrap() to get primitive values.
  478. @see Primitive#unwrap( Object )
  479. @return The variable value or Primitive.VOID if it is not defined.
  480. */
  481. public Object getVariable( String name )
  482. throws UtilEvalError
  483. {
  484. return getVariable( name, true );
  485. }
  486. /**
  487. Get the specified variable in this namespace.
  488. @param recurse If recurse is true then we recursively search through
  489. parent namespaces for the variable.
  490. <p>
  491. Note: this method is primarily intended for use internally. If you use
  492. this method outside of the bsh package you will have to use
  493. Primitive.unwrap() to get primitive values.
  494. @see Primitive#unwrap( Object )
  495. @return The variable value or Primitive.VOID if it is not defined.
  496. */
  497. public Object getVariable( String name, boolean recurse )
  498. throws UtilEvalError
  499. {
  500. Variable var = getVariableImpl( name, recurse );
  501. return unwrapVariable( var );
  502. }
  503. /**
  504. Locate a variable and return the Variable object with optional
  505. recursion through parent name spaces.
  506. <p/>
  507. If this namespace is static, return only static variables.
  508. @return the Variable value or null if it is not defined
  509. */
  510. protected Variable getVariableImpl( String name, boolean recurse )
  511. throws UtilEvalError
  512. {
  513. Variable var = null;
  514. // Change import precedence if we are a class body/instance
  515. // Get imported first.
  516. if ( var == null && isClass )
  517. var = getImportedVar( name );
  518. if ( var == null && variables != null )
  519. var = (Variable)variables.get(name);
  520. // Change import precedence if we are a class body/instance
  521. if ( var == null && !isClass )
  522. var = getImportedVar( name );
  523. // try parent
  524. if ( recurse && (var == null) && (parent != null) )
  525. var = parent.getVariableImpl( name, recurse );
  526. return var;
  527. }
  528. /*
  529. Get variables declared in this namespace.
  530. */
  531. public Variable [] getDeclaredVariables()
  532. {
  533. if ( variables == null )
  534. return new Variable[0];
  535. Variable [] vars = new Variable [ variables.size() ];
  536. int i=0;
  537. for( Enumeration e = variables.elements(); e.hasMoreElements(); )
  538. vars[i++] = (Variable)e.nextElement();
  539. return vars;
  540. }
  541. /**
  542. Unwrap a variable to its value.
  543. @return return the variable value. A null var is mapped to
  544. Primitive.VOID
  545. */
  546. protected Object unwrapVariable( Variable var )
  547. throws UtilEvalError
  548. {
  549. return (var == null) ? Primitive.VOID : var.getValue();
  550. }
  551. /**
  552. @deprecated See #setTypedVariable( String, Class, Object, Modifiers )
  553. */
  554. public void setTypedVariable(
  555. String name, Class type, Object value, boolean isFinal )
  556. throws UtilEvalError
  557. {
  558. Modifiers modifiers = new Modifiers();
  559. if ( isFinal )
  560. modifiers.addModifier( Modifiers.FIELD, "final" );
  561. setTypedVariable( name, type, value, modifiers );
  562. }
  563. /**
  564. Declare a variable in the local scope and set its initial value.
  565. Value may be null to indicate that we would like the default value
  566. for the variable type. (e.g. 0 for integer types, null for object
  567. types). An existing typed variable may only be set to the same type.
  568. If an untyped variable of the same name exists it will be overridden
  569. with the new typed var.
  570. The set will perform a Types.getAssignableForm() on the value if
  571. necessary.
  572. <p>
  573. Note: this method is primarily intended for use internally. If you use
  574. this method outside of the bsh package and wish to set variables with
  575. primitive values you will have to wrap them using bsh.Primitive.
  576. @see bsh.Primitive
  577. @param value If value is null, you'll get the default value for the type
  578. @param modifiers may be null
  579. */
  580. public void setTypedVariable(
  581. String name, Class type, Object value, Modifiers modifiers )
  582. throws UtilEvalError
  583. {
  584. //checkVariableModifiers( name, modifiers );
  585. if ( variables == null )
  586. variables = new Hashtable();
  587. // Setting a typed variable is always a local operation.
  588. Variable existing = getVariableImpl( name, false/*recurse*/ );
  589. // Null value is just a declaration
  590. // Note: we might want to keep any existing value here instead of reset
  591. /*
  592. // Moved to Variable
  593. if ( value == null )
  594. value = Primitive.getDefaultValue( type );
  595. */
  596. // does the variable already exist?
  597. if ( existing != null )
  598. {
  599. // Is it typed?
  600. if ( existing.getType() != null )
  601. {
  602. // If it had a different type throw error.
  603. // This allows declaring the same var again, but not with
  604. // a different (even if assignable) type.
  605. if ( existing.getType() != type )
  606. {
  607. throw new UtilEvalError( "Typed variable: "+name
  608. +" was previously declared with type: "
  609. + existing.getType() );
  610. } else
  611. {
  612. // else set it and return
  613. existing.setValue( value, Variable.DECLARATION );
  614. return;
  615. }
  616. }
  617. // Careful here:
  618. // else fall through to override and install the new typed version
  619. }
  620. // Add the new typed var
  621. variables.put( name, new Variable( name, type, value, modifiers ) );
  622. }
  623. /**
  624. Dissallow static vars outside of a class
  625. @param name is here just to allow the error message to use it
  626. protected void checkVariableModifiers( String name, Modifiers modifiers )
  627. throws UtilEvalError
  628. {
  629. if ( modifiers!=null && modifiers.hasModifier("static") )
  630. throw new UtilEvalError(
  631. "Can't declare static variable outside of class: "+name );
  632. }
  633. */
  634. /**
  635. Note: this is primarily for internal use.
  636. @see Interpreter#source( String )
  637. @see Interpreter#eval( String )
  638. */
  639. public void setMethod( String name, BshMethod method )
  640. throws UtilEvalError
  641. {
  642. //checkMethodModifiers( method );
  643. if ( methods == null )
  644. methods = new Hashtable();
  645. Object m = methods.get(name);
  646. if ( m == null )
  647. methods.put(name, method);
  648. else
  649. if ( m instanceof BshMethod ) {
  650. Vector v = new Vector();
  651. v.addElement( m );
  652. v.addElement( method );
  653. methods.put( name, v );
  654. } else // Vector
  655. ((Vector)m).addElement( method );
  656. }
  657. /**
  658. @see #getMethod( String, Class [], boolean )
  659. @see #getMethod( String, Class [] )
  660. */
  661. public BshMethod getMethod( String name, Class [] sig )
  662. throws UtilEvalError
  663. {
  664. return getMethod( name, sig, false/*declaredOnly*/ );
  665. }
  666. /**
  667. Get the bsh method matching the specified signature declared in
  668. this name space or a parent.
  669. <p>
  670. Note: this method is primarily intended for use internally. If you use
  671. this method outside of the bsh package you will have to be familiar
  672. with BeanShell's use of the Primitive wrapper class.
  673. @see bsh.Primitive
  674. @return the BshMethod or null if not found
  675. @param declaredOnly if true then only methods declared directly in this
  676. namespace will be found and no inherited or imported methods will
  677. be visible.
  678. */
  679. public BshMethod getMethod(
  680. String name, Class [] sig, boolean declaredOnly )
  681. throws UtilEvalError
  682. {
  683. BshMethod method = null;
  684. // Change import precedence if we are a class body/instance
  685. // Get import first.
  686. if ( method == null && isClass && !declaredOnly )
  687. method = getImportedMethod( name, sig );
  688. Object m = null;
  689. if ( method == null && methods != null )
  690. {
  691. m = methods.get(name);
  692. // m contains either BshMethod or Vector of BshMethod
  693. if ( m != null )
  694. {
  695. // unwrap
  696. BshMethod [] ma;
  697. if ( m instanceof Vector )
  698. {
  699. Vector vm = (Vector)m;
  700. ma = new BshMethod[ vm.size() ];
  701. vm.copyInto( ma );
  702. } else
  703. ma = new BshMethod[] { (BshMethod)m };
  704. // Apply most specific signature matching
  705. Class [][] candidates = new Class[ ma.length ][];
  706. for( int i=0; i< ma.length; i++ )
  707. candidates[i] = ma[i].getParameterTypes();
  708. int match =
  709. Reflect.findMostSpecificSignature( sig, candidates );
  710. if ( match != -1 )
  711. method = ma[match];
  712. }
  713. }
  714. if ( method == null && !isClass && !declaredOnly )
  715. method = getImportedMethod( name, sig );
  716. // try parent
  717. if ( !declaredOnly && (method == null) && (parent != null) )
  718. return parent.getMethod( name, sig );
  719. return method;
  720. }
  721. /**
  722. Import a class name.
  723. Subsequent imports override earlier ones
  724. */
  725. public void importClass(String name)
  726. {
  727. if ( importedClasses == null )
  728. importedClasses = new Hashtable();
  729. importedClasses.put( Name.suffix(name, 1), name );
  730. nameSpaceChanged();
  731. }
  732. /**
  733. subsequent imports override earlier ones
  734. */
  735. public void importPackage(String name)
  736. {
  737. if(importedPackages == null)
  738. importedPackages = new Vector();
  739. // If it exists, remove it and add it at the end (avoid memory leak)
  740. if ( importedPackages.contains( name ) )
  741. importedPackages.remove( name );
  742. importedPackages.addElement(name);
  743. nameSpaceChanged();
  744. }
  745. static class CommandPathEntry
  746. {
  747. String path;
  748. Class clas;
  749. CommandPathEntry(String path, Class clas)
  750. {
  751. this.path = path;
  752. this.clas = clas;
  753. }
  754. }
  755. /**
  756. Adds a URL to the command path.
  757. */
  758. public void addCommandPath(String path, Class clas)
  759. {
  760. if(importedCommands == null)
  761. importedCommands = new Vector();
  762. if(!path.endsWith("/"))
  763. path = path + "/";
  764. importedCommands.addElement(new CommandPathEntry(path,clas));
  765. }
  766. /**
  767. Remove a URLfrom the command path.
  768. */
  769. public void removeCommandPath(String path, Class clas)
  770. {
  771. if(importedCommands == null)
  772. return;
  773. for(int i = 0; i < importedCommands.size(); i++)
  774. {
  775. CommandPathEntry entry = (CommandPathEntry)importedCommands
  776. .elementAt(i);
  777. if(entry.path.equals(path) && entry.clas == clas)
  778. {
  779. importedCommands.removeElementAt(i);
  780. return;
  781. }
  782. }
  783. }
  784. /**
  785. Looks up a command.
  786. */
  787. public InputStream getCommand(String name)
  788. {
  789. if(importedCommands != null)
  790. {
  791. String extName = name + ".bsh";
  792. for(int i = importedCommands.size() - 1; i >= 0; i--)
  793. {
  794. CommandPathEntry entry = (CommandPathEntry)importedCommands
  795. .elementAt(i);
  796. InputStream in = entry.clas.getResourceAsStream(entry.path + extName);
  797. if(in != null)
  798. return in;
  799. }
  800. }
  801. if(parent == null)
  802. return null;
  803. else
  804. return parent.getCommand(name);
  805. }
  806. /**
  807. A command is a scripted method or compiled command class implementing a
  808. specified method signature. Commands are loaded from the classpath
  809. and may be imported using the importCommands() method.
  810. <p/>
  811. This method searches the imported commands packages for a script or
  812. command object corresponding to the name of the method. If it is a
  813. script the script is sourced into this namespace and the BshMethod for
  814. the requested signature is returned. If it is a compiled class the
  815. class is returned. (Compiled command classes implement static invoke()
  816. methods).
  817. <p/>
  818. The imported packages are searched in reverse order, so that later
  819. imports take priority.
  820. Currently only the first object (script or class) with the appropriate
  821. name is checked. If another, overloaded form, is located in another
  822. package it will not currently be found. This could be fixed.
  823. <p/>
  824. @return a BshMethod, Class, or null if no such command is found.
  825. @param name is the name of the desired command method
  826. @param argTypes is the signature of the desired command method.
  827. @throws UtilEvalError if loadScriptedCommand throws UtilEvalError
  828. i.e. on errors loading a script that was found
  829. */
  830. public Object getCommand(
  831. String name, Class [] argTypes, Interpreter interpreter )
  832. throws UtilEvalError
  833. {
  834. if (Interpreter.DEBUG) Interpreter.debug("getCommand: "+name);
  835. BshClassManager bcm = interpreter.getClassManager();
  836. InputStream in = getCommand( name );
  837. if ( in != null )
  838. return loadScriptedCommand(
  839. in, name, argTypes, name, interpreter );
  840. /* // Chop leading "/" and change "/" to "."
  841. String className;
  842. if ( path.equals("/") )
  843. className = name;
  844. else
  845. className = path.substring(1).replace('/','.') +"."+name;
  846. Class clas = bcm.classForName( className );
  847. if ( clas != null )
  848. return clas; */
  849. if ( parent != null )
  850. return parent.getCommand( name, argTypes, interpreter );
  851. else
  852. return null;
  853. }
  854. protected BshMethod getImportedMethod( String name, Class [] sig )
  855. throws UtilEvalError
  856. {
  857. // Try object imports
  858. if ( importedObjects != null )
  859. for(int i=0; i<importedObjects.size(); i++)
  860. {
  861. Object object = importedObjects.elementAt(i);
  862. Class clas = object.getClass();
  863. Method method = Reflect.resolveJavaMethod(
  864. getClassManager(), clas, name, sig, false/*onlyStatic*/ );
  865. if ( method != null )
  866. return new BshMethod( method, object );
  867. }
  868. // Try static imports
  869. if ( importedStatic!= null )
  870. for(int i=0; i<importedStatic.size(); i++)
  871. {
  872. Class clas = (Class)importedStatic.elementAt(i);
  873. Method method = Reflect.resolveJavaMethod(
  874. getClassManager(), clas, name, sig, true/*onlyStatic*/ );
  875. if ( method != null )
  876. return new BshMethod( method, null/*object*/ );
  877. }
  878. return null;
  879. }
  880. protected Variable getImportedVar( String name )
  881. throws UtilEvalError
  882. {
  883. // Try object imports
  884. if ( importedObjects != null )
  885. for(int i=0; i<importedObjects.size(); i++)
  886. {
  887. Object object = importedObjects.elementAt(i);
  888. Class clas = object.getClass();
  889. Field field = Reflect.resolveJavaField(
  890. clas, name, false/*onlyStatic*/ );
  891. if ( field != null )
  892. return new Variable(
  893. name, field.getType(), new LHS( object, field ) );
  894. }
  895. // Try static imports
  896. if ( importedStatic!= null )
  897. for(int i=0; i<importedStatic.size(); i++)
  898. {
  899. Class clas = (Class)importedStatic.elementAt(i);
  900. Field field = Reflect.resolveJavaField(
  901. clas, name, true/*onlyStatic*/ );
  902. if ( field != null )
  903. return new Variable( name, field.getType(), new LHS( field ) );
  904. }
  905. return null;
  906. }
  907. /**
  908. Load a command script from the input stream and find the BshMethod in
  909. the target namespace.
  910. @throws UtilEvalError on error in parsing the script or if the the
  911. method is not found after parsing the script.
  912. */
  913. /*
  914. If we want to support multiple commands in the command path we need to
  915. change this to not throw the exception.
  916. */
  917. private BshMethod loadScriptedCommand(
  918. InputStream in, String name, Class [] argTypes, String resourcePath,
  919. Interpreter interpreter )
  920. throws UtilEvalError
  921. {
  922. try {
  923. interpreter.eval(
  924. new InputStreamReader(in), this, resourcePath );
  925. } catch ( EvalError e ) {
  926. /*
  927. Here we catch any EvalError from the interpreter because we are
  928. using it as a tool to load the command, not as part of the
  929. execution path.
  930. */
  931. Interpreter.debug( e.toString() );
  932. throw new UtilEvalError(
  933. "Error loading script: "+ e.getMessage());
  934. }
  935. // Look for the loaded command
  936. BshMethod meth = getMethod( name, argTypes );
  937. /*
  938. if ( meth == null )
  939. throw new UtilEvalError("Loaded resource: " + resourcePath +
  940. "had an error or did not contain the correct method" );
  941. */
  942. return meth;
  943. }
  944. /**
  945. Helper that caches class.
  946. */
  947. void cacheClass( String name, Class c ) {
  948. if ( classCache == null ) {
  949. classCache = new Hashtable();
  950. //cacheCount++; // debug
  951. }
  952. classCache.put(name, c);
  953. }
  954. /**
  955. Load a class through this namespace taking into account imports.
  956. The class search will proceed through the parent namespaces if
  957. necessary.
  958. @return null if not found.
  959. */
  960. public Class getClass( String name )
  961. throws UtilEvalError
  962. {
  963. Class c = getClassImpl(name);
  964. if ( c != null )
  965. return c;
  966. else
  967. // implement the recursion for getClassImpl()
  968. if ( parent != null )
  969. return parent.getClass( name );
  970. else
  971. return null;
  972. }
  973. /**
  974. Implementation of getClass()
  975. Load a class through this namespace taking into account imports.
  976. <p>
  977. Check the cache first. If an unqualified name look for imported
  978. class or package. Else try to load absolute name.
  979. <p>
  980. This method implements caching of unqualified names (normally imports).
  981. Qualified names are cached by the BshClassManager.
  982. Unqualified absolute class names (e.g. unpackaged Foo) are cached too
  983. so that we don't go searching through the imports for them each time.
  984. @return null if not found.
  985. */
  986. private Class getClassImpl( String name )
  987. throws UtilEvalError
  988. {
  989. Class c = null;
  990. // Check the cache
  991. if (classCache != null) {
  992. c = (Class)classCache.get(name);
  993. if ( c != null )
  994. return c;
  995. }
  996. // Unqualified (simple, non-compound) name
  997. boolean unqualifiedName = !Name.isCompound(name);
  998. // Unqualified name check imported
  999. if ( unqualifiedName )
  1000. {
  1001. // Try imported class
  1002. if ( c == null )
  1003. c = getImportedClassImpl( name );
  1004. // if found as imported also cache it
  1005. if ( c != null ) {
  1006. cacheClass( name, c );
  1007. return c;
  1008. }
  1009. }
  1010. // Try absolute
  1011. c = classForName( name );
  1012. if ( c != null ) {
  1013. // Cache unqualified names to prevent import check again
  1014. if ( unqualifiedName )
  1015. cacheClass( name, c );
  1016. return c;
  1017. }
  1018. // Not found
  1019. if ( Interpreter.DEBUG )
  1020. Interpreter.debug("getClass(): " + name + " not found in "+this);
  1021. return null;
  1022. }
  1023. /**
  1024. Try to make the name into an imported class.
  1025. This method takes into account only imports (class or package)
  1026. found directly in this NameSpace (no parent chain).
  1027. */
  1028. private Class getImportedClassImpl( String name )
  1029. throws UtilEvalError
  1030. {
  1031. // Try explicitly imported class, e.g. import foo.Bar;
  1032. String fullname = null;
  1033. if ( importedClasses != null )
  1034. fullname = (String)importedClasses.get(name);
  1035. // not sure if we should really recurse here for explicitly imported
  1036. // class in parent...
  1037. if ( fullname != null )
  1038. {
  1039. /*
  1040. Found the full name in imported classes.
  1041. */
  1042. // Try to make the full imported name
  1043. Class clas=classForName(fullname);
  1044. // Handle imported inner class case
  1045. if ( clas == null )
  1046. {
  1047. // Imported full name wasn't found as an absolute class
  1048. // If it is compound, try to resolve to an inner class.
  1049. // (maybe this should happen in the BshClassManager?)
  1050. if ( Name.isCompound( fullname ) )
  1051. try {
  1052. clas = getNameResolver( fullname ).toClass();
  1053. } catch ( ClassNotFoundException e ) { /* not a class */ }
  1054. else
  1055. if ( Interpreter.DEBUG ) Interpreter.debug(
  1056. "imported unpackaged name not found:" +fullname);
  1057. // If found cache the full name in the BshClassManager
  1058. if ( clas != null ) {
  1059. // (should we cache info in not a class case too?)
  1060. getClassManager().cacheClassInfo( fullname, clas );
  1061. return clas;
  1062. }
  1063. } else
  1064. return clas;
  1065. // It was explicitly imported, but we don't know what it is.
  1066. // should we throw an error here??
  1067. return null;
  1068. }
  1069. /*
  1070. Try imported packages, e.g. "import foo.bar.*;"
  1071. in reverse order of import...
  1072. (give later imports precedence...)
  1073. */
  1074. if ( importedPackages != null )
  1075. for(int i=importedPackages.size()-1; i>=0; i--)
  1076. {
  1077. String s = ((String)importedPackages.elementAt(i)) + "." + name;
  1078. Class c=classForName(s);
  1079. if ( c != null )
  1080. return c;
  1081. }
  1082. BshClassManager bcm = getClassManager();
  1083. /*
  1084. Try super import if available
  1085. Note: we do this last to allow explicitly imported classes
  1086. and packages to take priority. This method will also throw an
  1087. error indicating ambiguity if it exists...
  1088. */
  1089. if ( bcm.hasSuperImport() )
  1090. {
  1091. String s = bcm.getClassNameByUnqName( name );
  1092. if ( s != null )
  1093. return classForName( s );
  1094. }
  1095. return null;
  1096. }
  1097. private Class classForName( String name )
  1098. {
  1099. return getClassManager().classForName( name );
  1100. }
  1101. /**
  1102. Implements NameSource
  1103. @return all variable and method names in this and all parent
  1104. namespaces
  1105. */
  1106. public String [] getAllNames()
  1107. {
  1108. Vector vec = new Vector();
  1109. getAllNamesAux( vec );
  1110. String [] names = new String [ vec.size() ];
  1111. vec.copyInto( names );
  1112. return names;
  1113. }
  1114. /**
  1115. Helper for implementing NameSource
  1116. */
  1117. protected void getAllNamesAux( Vector vec )
  1118. {
  1119. Enumeration varNames = variables.keys();
  1120. while( varNames.hasMoreElements() )
  1121. vec.addElement( varNames.nextElement() );
  1122. Enumeration methodNames = methods.keys();
  1123. while( methodNames.hasMoreElements() )
  1124. vec.addElement( methodNames.nextElement() );
  1125. if ( parent != null )
  1126. parent.getAllNamesAux( vec );
  1127. }
  1128. Vector nameSourceListeners;
  1129. /**
  1130. Implements NameSource
  1131. Add a listener who is notified upon changes to names in this space.
  1132. */
  1133. public void addNameSourceListener( NameSource.Listener listener ) {
  1134. if ( nameSourceListeners == null )
  1135. nameSourceListeners = new Vector();
  1136. nameSourceListeners.addElement( listener );
  1137. }
  1138. /**
  1139. Perform "import *;" causing the entire classpath to be mapped.
  1140. This can take a while.
  1141. */
  1142. public void doSuperImport()
  1143. throws UtilEvalError
  1144. {
  1145. getClassManager().doSuperImport();
  1146. }
  1147. public String toString() {
  1148. return "NameSpace: "
  1149. + ( nsName==null
  1150. ? super.toString()
  1151. : nsName + " (" + super.toString() +")" )
  1152. + ( isClass ? " (isClass) " : "" )
  1153. + ( isMethod ? " (method) " : "" )
  1154. + ( classStatic != null ? " (class static) " : "" )
  1155. + ( classInstance != null ? " (class instance) " : "" );
  1156. }
  1157. /*
  1158. For serialization.
  1159. Don't serialize non-serializable objects.
  1160. */
  1161. private synchronized void writeObject(java.io.ObjectOutputStream s)
  1162. throws IOException
  1163. {
  1164. // clear name resolvers... don't know if this is necessary.
  1165. names = null;
  1166. s.defaultWriteObject();
  1167. }
  1168. /**
  1169. Invoke a method in this namespace with the specified args and
  1170. interpreter reference. No caller information or call stack is
  1171. required. The method will appear as if called externally from Java.
  1172. <p>
  1173. @see bsh.This.invokeMethod(
  1174. String methodName, Object [] args, Interpreter interpreter,
  1175. CallStack callstack, SimpleNode callerInfo, boolean )
  1176. */
  1177. public Object invokeMethod(
  1178. String methodName, Object [] args, Interpreter interpreter )
  1179. throws EvalError
  1180. {
  1181. return invokeMethod(
  1182. methodName, args, interpreter, null, null );
  1183. }
  1184. /**
  1185. This method simply delegates to This.invokeMethod();
  1186. <p>
  1187. @see bsh.This.invokeMethod(
  1188. String methodName, Object [] args, Interpreter interpreter,
  1189. CallStack callstack, SimpleNode callerInfo )
  1190. */
  1191. public Object invokeMethod(
  1192. String methodName, Object [] args, Interpreter interpreter,
  1193. CallStack callstack, SimpleNode callerInfo )
  1194. throws EvalError
  1195. {
  1196. return getThis( interpreter ).invokeMethod(
  1197. methodName, args, interpreter, callstack, callerInfo,
  1198. false/*declaredOnly*/ );
  1199. }
  1200. /**
  1201. Clear all cached classes and names
  1202. */
  1203. public void classLoaderChanged() {
  1204. nameSpaceChanged();
  1205. }
  1206. /**
  1207. Clear all cached classes and names
  1208. */
  1209. public void nameSpaceChanged() {
  1210. classCache = null;
  1211. names = null;
  1212. }
  1213. /**
  1214. Import standard packages. Currently:
  1215. <pre>
  1216. importClass("bsh.EvalError");
  1217. importClass("bsh.Interpreter");
  1218. importPackage("javax.swing.event");
  1219. importPackage("javax.swing");
  1220. importPackage("java.awt.event");
  1221. importPackage("java.awt");
  1222. importPackage("java.net");
  1223. importPackage("java.util");
  1224. importPackage("java.io");
  1225. importPackage("java.lang");
  1226. addCommandPath("/bsh/commands",getClass());
  1227. </pre>
  1228. */
  1229. public void loadDefaultImports()
  1230. {
  1231. /**
  1232. Note: the resolver looks through these in reverse order, per
  1233. precedence rules... so for max efficiency put the most common
  1234. ones later.
  1235. */
  1236. importClass("bsh.EvalError");
  1237. importClass("bsh.Interpreter");
  1238. importPackage("javax.swing.event");
  1239. importPackage("javax.swing");
  1240. importPackage("java.awt.event");
  1241. importPackage("java.awt");
  1242. importPackage("java.net");
  1243. importPackage("java.util");
  1244. importPackage("java.io");
  1245. importPackage("java.lang");
  1246. addCommandPath("/bsh/commands",getClass());
  1247. }
  1248. /**
  1249. This is the factory for Name objects which resolve names within
  1250. this namespace (e.g. toObject(), toClass(), toLHS()).
  1251. <p>
  1252. This was intended to support name resolver caching, allowing
  1253. Name objects to cache info about the resolution of names for
  1254. performance reasons. However this not proven useful yet.
  1255. <p>
  1256. We'll leave the caching as it will at least minimize Name object
  1257. creation.
  1258. <p>
  1259. (This method would be called getName() if it weren't already used for
  1260. the simple name of the NameSpace)
  1261. <p>
  1262. This method was public for a time, which was a mistake.
  1263. Use get() instead.
  1264. */
  1265. Name getNameResolver( String ambigname )
  1266. {
  1267. if ( names == null )
  1268. names = new Hashtable();
  1269. Name name = (Name)names.get( ambigname );
  1270. if ( name == null ) {
  1271. name = new Name( this, ambigname );
  1272. names.put( ambigname, name );
  1273. }
  1274. return name;
  1275. }
  1276. public int getInvocationLine() {
  1277. SimpleNode node = getNode();
  1278. if ( node != null )
  1279. return node.getLineNumber();
  1280. else
  1281. return -1;
  1282. }
  1283. public String getInvocationText() {
  1284. SimpleNode node = getNode();
  1285. if ( node != null )
  1286. return node.getText();
  1287. else
  1288. return "<invoked from Java code>";
  1289. }
  1290. /**
  1291. This is a helper method for working inside of bsh scripts and commands.
  1292. In that context it is impossible to see a ClassIdentifier object
  1293. for what it is. Attempting to access a method on a ClassIdentifier
  1294. will look like a static method invocation.
  1295. This method is in NameSpace for convenience (you don't have to import
  1296. bsh.ClassIdentifier to use it );
  1297. */
  1298. public static Class identifierToClass( ClassIdentifier ci )
  1299. {
  1300. return ci.getTargetClass();
  1301. }
  1302. /**
  1303. Clear all variables, methods, and imports from this namespace.
  1304. If this namespace is the root, it will be reset to the default
  1305. imports.
  1306. @see #loadDefaultImports()
  1307. */
  1308. public void clear()
  1309. {
  1310. variables = null;
  1311. methods = null;
  1312. importedClasses = null;
  1313. importedPackages = null;
  1314. importedCommands = null;
  1315. importedObjects = null;
  1316. if ( parent == null )
  1317. loadDefaultImports();
  1318. classCache = null;
  1319. names = null;
  1320. }
  1321. /**
  1322. Import a compiled Java object's methods and variables into this
  1323. namespace. When no scripted method / command or variable is found
  1324. locally in this namespace method / fields of the object will be
  1325. checked. Objects are checked in the order of import with later imports
  1326. taking precedence.
  1327. <p/>
  1328. */
  1329. /*
  1330. Note: this impor pattern is becoming common... could factor it out into
  1331. an importedObject Vector class.
  1332. */
  1333. public void importObject( Object obj )
  1334. {
  1335. if ( importedObjects == null )
  1336. importedObjects = new Vector();
  1337. // If it exists, remove it and add it at the end (avoid memory leak)
  1338. if ( importedObjects.contains( obj ) )
  1339. importedObjects.remove( obj );
  1340. importedObjects.addElement( obj );
  1341. nameSpaceChanged();
  1342. }
  1343. /**
  1344. */
  1345. public void importStatic( Class clas )
  1346. {
  1347. if ( importedStatic == null )
  1348. importedStatic = new Vector();
  1349. // If it exists, remove it and add it at the end (avoid memory leak)
  1350. if ( importedStatic.contains( clas ) )
  1351. importedStatic.remove( clas );
  1352. importedStatic.addElement( clas );
  1353. nameSpaceChanged();
  1354. }
  1355. /**
  1356. Set the package name for classes defined in this namespace.
  1357. Subsequent sets override the package.
  1358. */
  1359. void setPackage( String packageName )
  1360. {
  1361. this.packageName = packageName;
  1362. }
  1363. String getPackage()
  1364. {
  1365. if ( packageName != null )
  1366. return packageName;
  1367. if ( parent != null )
  1368. return parent.getPackage();
  1369. return null;
  1370. }
  1371. }