/jEdit/tags/jedit-4-2-pre7/bsh/Interpreter.java

# · Java · 1145 lines · 596 code · 125 blank · 424 comment · 76 complexity · a8135867023ea1bb7bd516acfe5291a8 MD5 · raw file

  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.Vector;
  35. import java.io.*;
  36. /**
  37. The BeanShell script interpreter.
  38. An instance of Interpreter can be used to source scripts and evaluate
  39. statements or expressions.
  40. <p>
  41. See the BeanShell User's Manual for more information.
  42. */
  43. public class Interpreter
  44. implements Runnable, ConsoleInterface,Serializable
  45. {
  46. /* --- Begin static members --- */
  47. public static final String VERSION = "1.3.0-jedit1";
  48. /*
  49. Debug utils are static so that they are reachable by code that doesn't
  50. necessarily have an interpreter reference (e.g. tracing in utils).
  51. In the future we may want to allow debug/trace to be turned on on
  52. a per interpreter basis, in which case we'll need to use the parent
  53. reference in some way to determine the scope of the command that
  54. turns it on or off.
  55. */
  56. public static boolean DEBUG, TRACE, LOCALSCOPING;
  57. // This should be per instance
  58. transient static PrintStream debug;
  59. static String systemLineSeparator = "\n"; // default
  60. static {
  61. staticInit();
  62. }
  63. /** Shared system object visible under bsh.system */
  64. static This sharedObject;
  65. /**
  66. Strict Java mode
  67. @see setStrictJava( boolean )
  68. */
  69. private boolean strictJava = false;
  70. /* --- End static members --- */
  71. /* --- Instance data --- */
  72. transient Parser parser;
  73. NameSpace globalNameSpace;
  74. transient Reader in;
  75. transient PrintStream out;
  76. transient PrintStream err;
  77. ConsoleInterface console;
  78. /** If this interpeter is a child of another, the parent */
  79. Interpreter parent;
  80. /** The name of the file or other source that this interpreter is reading */
  81. String sourceFileInfo;
  82. /** by default in interactive mode System.exit() on EOF */
  83. private boolean exitOnEOF = true;
  84. protected boolean
  85. evalOnly, // Interpreter has no input stream, use eval() only
  86. interactive; // Interpreter has a user, print prompts, etc.
  87. /* --- End instance data --- */
  88. /**
  89. The main constructor.
  90. All constructors should now pass through here.
  91. @param namespace If namespace is non-null then this interpreter's
  92. root namespace will be set to the one provided. If it is null a new
  93. one will be created for it.
  94. @param parent The parent interpreter if this interpreter is a child
  95. of another. May be null. Children share a BshClassManager with
  96. their parent instance.
  97. @param sourceFileInfo An informative string holding the filename
  98. or other description of the source from which this interpreter is
  99. reading... used for debugging. May be null.
  100. */
  101. public Interpreter(
  102. Reader in, PrintStream out, PrintStream err,
  103. boolean interactive, NameSpace namespace,
  104. Interpreter parent, String sourceFileInfo )
  105. {
  106. parser = new Parser( in );
  107. long t1=System.currentTimeMillis();
  108. this.in = in;
  109. this.out = out;
  110. this.err = err;
  111. this.interactive = interactive;
  112. debug = err;
  113. this.parent = parent;
  114. if ( parent != null )
  115. setStrictJava( parent.getStrictJava() );
  116. this.sourceFileInfo = sourceFileInfo;
  117. if ( namespace == null )
  118. this.globalNameSpace = new NameSpace(
  119. BshClassManager.createClassManager(), "global");
  120. else
  121. this.globalNameSpace = namespace;
  122. // now done in NameSpace automatically when root
  123. // The classes which are imported by default
  124. //globalNameSpace.loadDefaultImports();
  125. /*
  126. Create the root "bsh" system object if it doesn't exist.
  127. */
  128. if ( ! ( getu("bsh") instanceof bsh.This ) )
  129. initRootSystemObject();
  130. if ( interactive )
  131. loadRCFiles();
  132. long t2=System.currentTimeMillis();
  133. if ( Interpreter.DEBUG )
  134. Interpreter.debug("Time to initialize interpreter: "+(t2-t1));
  135. }
  136. public Interpreter(
  137. Reader in, PrintStream out, PrintStream err,
  138. boolean interactive, NameSpace namespace)
  139. {
  140. this( in, out, err, interactive, namespace, null, null );
  141. }
  142. public Interpreter(
  143. Reader in, PrintStream out, PrintStream err, boolean interactive)
  144. {
  145. this(in, out, err, interactive, null);
  146. }
  147. /**
  148. Construct a new interactive interpreter attached to the specified
  149. console using the specified parent namespace.
  150. */
  151. public Interpreter(ConsoleInterface console, NameSpace globalNameSpace) {
  152. this( console.getIn(), console.getOut(), console.getErr(),
  153. true, globalNameSpace );
  154. setConsole( console );
  155. }
  156. /**
  157. Construct a new interactive interpreter attached to the specified
  158. console.
  159. */
  160. public Interpreter(ConsoleInterface console) {
  161. this(console, null);
  162. }
  163. /**
  164. Create an interpreter for evaluation only.
  165. */
  166. public Interpreter()
  167. {
  168. this( new StringReader(""),
  169. System.out, System.err, false, null );
  170. evalOnly = true;
  171. setu( "bsh.evalOnly", new Primitive(true) );
  172. }
  173. // End constructors
  174. /**
  175. Attach a console
  176. Note: this method is incomplete.
  177. */
  178. public void setConsole( ConsoleInterface console ) {
  179. this.console = console;
  180. setu( "bsh.console", console );
  181. // redundant with constructor
  182. setOut( console.getOut() );
  183. setErr( console.getErr() );
  184. // need to set the input stream - reinit the parser?
  185. }
  186. private void initRootSystemObject()
  187. {
  188. BshClassManager bcm = getClassManager();
  189. //System.out.println("init root bcm ="+bcm);
  190. // bsh
  191. setu("bsh", new NameSpace( bcm, "Bsh Object" ).getThis( this ) );
  192. // init the static shared sharedObject if it's not there yet
  193. if ( sharedObject == null )
  194. sharedObject = new NameSpace(
  195. bcm, "Bsh Shared System Object" ).getThis( this );
  196. // bsh.system
  197. setu( "bsh.system", sharedObject );
  198. setu( "bsh.shared", sharedObject ); // alias
  199. // bsh.help
  200. This helpText = new NameSpace(
  201. bcm, "Bsh Command Help Text" ).getThis( this );
  202. setu( "bsh.help", helpText );
  203. // bsh.cwd
  204. try {
  205. setu( "bsh.cwd", System.getProperty("user.dir") );
  206. } catch ( SecurityException e ) {
  207. // applets can't see sys props
  208. setu( "bsh.cwd", "." );
  209. }
  210. // bsh.interactive
  211. setu( "bsh.interactive", new Primitive(interactive) );
  212. // bsh.evalOnly
  213. setu( "bsh.evalOnly", new Primitive(evalOnly) );
  214. }
  215. /**
  216. Set the global namespace for this interpreter.
  217. <p>
  218. Note: This is here for completeness. If you're using this a lot
  219. it may be an indication that you are doing more work than you have
  220. to. For example, caching the interpreter instance rather than the
  221. namespace should not add a significant overhead. No state other
  222. than the debug status is stored in the interpreter.
  223. <p>
  224. All features of the namespace can also be accessed using the
  225. interpreter via eval() and the script variable 'this.namespace'
  226. (or global.namespace as necessary).
  227. */
  228. public void setNameSpace( NameSpace globalNameSpace ) {
  229. this.globalNameSpace = globalNameSpace;
  230. }
  231. /**
  232. Get the global namespace of this interpreter.
  233. <p>
  234. Note: This is here for completeness. If you're using this a lot
  235. it may be an indication that you are doing more work than you have
  236. to. For example, caching the interpreter instance rather than the
  237. namespace should not add a significant overhead. No state other than
  238. the debug status is stored in the interpreter.
  239. <p>
  240. All features of the namespace can also be accessed using the
  241. interpreter via eval() and the script variable 'this.namespace'
  242. (or global.namespace as necessary).
  243. */
  244. public NameSpace getNameSpace() {
  245. return globalNameSpace;
  246. }
  247. /**
  248. Run the text only interpreter on the command line or specify a file.
  249. */
  250. public static void main( String [] args )
  251. {
  252. if ( args.length > 0 ) {
  253. String filename = args[0];
  254. String [] bshArgs;
  255. if ( args.length > 1 ) {
  256. bshArgs = new String [ args.length -1 ];
  257. System.arraycopy( args, 1, bshArgs, 0, args.length-1 );
  258. } else
  259. bshArgs = new String [0];
  260. Interpreter interpreter = new Interpreter();
  261. interpreter.setu( "bsh.args", bshArgs );
  262. try {
  263. interpreter.source( filename, interpreter.globalNameSpace );
  264. } catch ( FileNotFoundException e ) {
  265. System.out.println("File not found: "+e);
  266. } catch ( TargetError e ) {
  267. System.out.println("Script threw exception: "+e);
  268. if ( e.inNativeCode() )
  269. e.printStackTrace( DEBUG, System.err );
  270. } catch ( EvalError e ) {
  271. System.out.println("Evaluation Error: "+e);
  272. } catch ( IOException e ) {
  273. System.out.println("I/O Error: "+e);
  274. }
  275. } else {
  276. // Workaround for JDK bug 4071281, where system.in.available()
  277. // returns too large a value. This bug has been fixed in JDK 1.2.
  278. InputStream src;
  279. if ( System.getProperty("os.name").startsWith("Windows")
  280. && System.getProperty("java.version").startsWith("1.1."))
  281. {
  282. src = new FilterInputStream(System.in) {
  283. public int available() throws IOException {
  284. return 0;
  285. }
  286. };
  287. }
  288. else
  289. src = System.in;
  290. Reader in = new CommandLineReader( new InputStreamReader(src));
  291. Interpreter interpreter =
  292. new Interpreter( in, System.out, System.err, true );
  293. interpreter.run();
  294. }
  295. }
  296. /**
  297. Run interactively. (printing prompts, etc.)
  298. */
  299. public void run()
  300. {
  301. if(evalOnly)
  302. throw new RuntimeException("bsh Interpreter: No stream");
  303. /*
  304. We'll print our banner using eval(String) in order to
  305. exercise the parser and get the basic expression classes loaded...
  306. This ameliorates the delay after typing the first statement.
  307. */
  308. if ( interactive )
  309. try {
  310. eval("printBanner();");
  311. } catch ( EvalError e ) {
  312. println(
  313. "BeanShell "+VERSION+" - by Pat Niemeyer (pat@pat.net)");
  314. }
  315. // init the callstack.
  316. CallStack callstack = new CallStack( globalNameSpace );
  317. boolean eof = false;
  318. while( !eof )
  319. {
  320. try
  321. {
  322. // try to sync up the console
  323. System.out.flush();
  324. System.err.flush();
  325. Thread.yield(); // this helps a little
  326. if ( interactive )
  327. print( getBshPrompt() );
  328. eof = Line();
  329. if( get_jjtree().nodeArity() > 0 ) // number of child nodes
  330. {
  331. SimpleNode node = (SimpleNode)(get_jjtree().rootNode());
  332. if(DEBUG)
  333. node.dump(">");
  334. Object ret = node.eval( callstack, this );
  335. // sanity check during development
  336. if ( callstack.depth() > 1 )
  337. throw new InterpreterError(
  338. "Callstack growing: "+callstack);
  339. if(ret instanceof ReturnControl)
  340. ret = ((ReturnControl)ret).value;
  341. if(ret != Primitive.VOID)
  342. {
  343. setu("$_", ret);
  344. Object show = getu("bsh.show");
  345. if(show instanceof Boolean &&
  346. ((Boolean)show).booleanValue() == true)
  347. println("<" + ret + ">");
  348. }
  349. }
  350. }
  351. catch(ParseException e)
  352. {
  353. error("Parser Error: " + e.getMessage(DEBUG));
  354. if ( DEBUG )
  355. e.printStackTrace();
  356. if(!interactive)
  357. eof = true;
  358. parser.reInitInput(in);
  359. }
  360. catch(InterpreterError e)
  361. {
  362. error("Internal Error: " + e.getMessage());
  363. e.printStackTrace();
  364. if(!interactive)
  365. eof = true;
  366. }
  367. catch(TargetError e)
  368. {
  369. error("// Uncaught Exception: " + e );
  370. if ( e.inNativeCode() )
  371. e.printStackTrace( DEBUG, err );
  372. if(!interactive)
  373. eof = true;
  374. setu("$_e", e.getTarget());
  375. }
  376. catch (EvalError e)
  377. {
  378. if ( interactive )
  379. error( "EvalError: "+e.toString() );
  380. else
  381. error( "EvalError: "+e.getMessage() );
  382. if(DEBUG)
  383. e.printStackTrace();
  384. if(!interactive)
  385. eof = true;
  386. }
  387. catch(Exception e)
  388. {
  389. error("Unknown error: " + e);
  390. if ( DEBUG )
  391. e.printStackTrace();
  392. if(!interactive)
  393. eof = true;
  394. }
  395. catch(TokenMgrError e)
  396. {
  397. error("Error parsing input: " + e);
  398. /*
  399. We get stuck in infinite loops here when unicode escapes
  400. fail. Must re-init the char stream reader
  401. (ASCII_UCodeESC_CharStream.java)
  402. */
  403. parser.reInitTokenInput( in );
  404. if(!interactive)
  405. eof = true;
  406. }
  407. finally
  408. {
  409. get_jjtree().reset();
  410. // reinit the callstack
  411. if ( callstack.depth() > 1 ) {
  412. callstack.clear();
  413. callstack.push( globalNameSpace );
  414. }
  415. }
  416. }
  417. if ( interactive && exitOnEOF )
  418. System.exit(0);
  419. }
  420. // begin source and eval
  421. /**
  422. Read text from fileName and eval it.
  423. */
  424. public Object source( String filename, NameSpace nameSpace )
  425. throws FileNotFoundException, IOException, EvalError
  426. {
  427. File file = pathToFile( filename );
  428. if ( Interpreter.DEBUG ) debug("Sourcing file: "+file);
  429. Reader sourceIn = new BufferedReader( new FileReader(file) );
  430. try {
  431. return eval( sourceIn, nameSpace, filename );
  432. } finally {
  433. sourceIn.close();
  434. }
  435. }
  436. /**
  437. Read text from fileName and eval it.
  438. Convenience method. Use the global namespace.
  439. */
  440. public Object source( String filename )
  441. throws FileNotFoundException, IOException, EvalError
  442. {
  443. return source( filename, globalNameSpace );
  444. }
  445. /**
  446. Spawn a non-interactive local interpreter to evaluate text in the
  447. specified namespace.
  448. Return value is the evaluated object (or corresponding primitive
  449. wrapper).
  450. @param sourceFileInfo is for information purposes only. It is used to
  451. display error messages (and in the future may be made available to
  452. the script).
  453. @throws EvalError on script problems
  454. @throws TargetError on unhandled exceptions from the script
  455. */
  456. /*
  457. Note: we need a form of eval that passes the callstack through...
  458. */
  459. /*
  460. Can't this be combined with run() ?
  461. run seems to have stuff in it for interactive vs. non-interactive...
  462. compare them side by side and see what they do differently, aside from the
  463. exception handling.
  464. */
  465. public Object eval(
  466. Reader in, NameSpace nameSpace, String sourceFileInfo
  467. /*, CallStack callstack */ )
  468. throws EvalError
  469. {
  470. Object retVal = null;
  471. if ( Interpreter.DEBUG ) debug("eval: nameSpace = "+nameSpace);
  472. /*
  473. Create non-interactive local interpreter for this namespace
  474. with source from the input stream and out/err same as
  475. this interpreter.
  476. */
  477. Interpreter localInterpreter =
  478. new Interpreter(
  479. in, out, err, false, nameSpace, this, sourceFileInfo );
  480. CallStack callstack = new CallStack( nameSpace );
  481. boolean eof = false;
  482. while(!eof)
  483. {
  484. SimpleNode node = null;
  485. try
  486. {
  487. eof = localInterpreter.Line();
  488. if (localInterpreter.get_jjtree().nodeArity() > 0)
  489. {
  490. node = (SimpleNode)localInterpreter.get_jjtree().rootNode();
  491. // nodes remember from where they were sourced
  492. node.setSourceFile( sourceFileInfo );
  493. if ( TRACE )
  494. println( "// " +node.getText() );
  495. retVal = node.eval( callstack, localInterpreter );
  496. // sanity check during development
  497. if ( callstack.depth() > 1 )
  498. throw new InterpreterError(
  499. "Callstack growing: "+callstack);
  500. if ( retVal instanceof ReturnControl ) {
  501. retVal = ((ReturnControl)retVal).value;
  502. break; // non-interactive, return control now
  503. }
  504. }
  505. } catch(ParseException e) {
  506. /*
  507. throw new EvalError(
  508. "Sourced file: "+sourceFileInfo+" parser Error: "
  509. + e.getMessage( DEBUG ), node, callstack );
  510. */
  511. if ( DEBUG )
  512. // show extra "expecting..." info
  513. error( e.getMessage(DEBUG) );
  514. // add the source file info and throw again
  515. e.setErrorSourceFile( sourceFileInfo );
  516. throw e;
  517. } catch ( InterpreterError e ) {
  518. e.printStackTrace();
  519. throw new EvalError(
  520. "Sourced file: "+sourceFileInfo+" internal Error: "
  521. + e.getMessage(), node, callstack);
  522. } catch ( TargetError e ) {
  523. // failsafe, set the Line as the origin of the error.
  524. if ( e.getNode()==null )
  525. e.setNode( node );
  526. e.reThrow("Sourced file: "+sourceFileInfo);
  527. } catch ( EvalError e) {
  528. if ( DEBUG)
  529. e.printStackTrace();
  530. // failsafe, set the Line as the origin of the error.
  531. if ( e.getNode()==null )
  532. e.setNode( node );
  533. e.reThrow( "Sourced file: "+sourceFileInfo );
  534. } catch ( Exception e) {
  535. if ( DEBUG)
  536. e.printStackTrace();
  537. throw new EvalError(
  538. "Sourced file: "+sourceFileInfo+" unknown error: "
  539. + e.getMessage(), node, callstack);
  540. } catch(TokenMgrError e) {
  541. throw new EvalError(
  542. "Sourced file: "+sourceFileInfo+" Token Parsing Error: "
  543. + e.getMessage(), node, callstack );
  544. } finally {
  545. localInterpreter.get_jjtree().reset();
  546. // reinit the callstack
  547. if ( callstack.depth() > 1 ) {
  548. callstack.clear();
  549. callstack.push( nameSpace );
  550. }
  551. }
  552. }
  553. return Primitive.unwrap( retVal );
  554. }
  555. /**
  556. Evaluate the inputstream in this interpreter's global namespace.
  557. */
  558. public Object eval( Reader in ) throws EvalError
  559. {
  560. return eval( in, globalNameSpace, "eval stream" );
  561. }
  562. /**
  563. Evaluate the string in this interpreter's global namespace.
  564. */
  565. public Object eval( String statements ) throws EvalError {
  566. if ( Interpreter.DEBUG ) debug("eval(String): "+statements);
  567. return eval(statements, globalNameSpace);
  568. }
  569. /**
  570. Evaluate the string in the specified namespace.
  571. */
  572. public Object eval( String statements, NameSpace nameSpace )
  573. throws EvalError
  574. {
  575. String s = ( statements.endsWith(";") ? statements : statements+";" );
  576. return eval(
  577. new StringReader(s), nameSpace,
  578. "inline evaluation of: ``"+ showEvalString(s)+"''" );
  579. }
  580. private String showEvalString( String s ) {
  581. s = s.replace('\n', ' ');
  582. s = s.replace('\r', ' ');
  583. if ( s.length() > 80 )
  584. s = s.substring( 0, 80 ) + " . . . ";
  585. return s;
  586. }
  587. // end source and eval
  588. /**
  589. Print an error message in a standard format on the output stream
  590. associated with this interpreter. On the GUI console this will appear
  591. in red, etc.
  592. */
  593. public final void error(String s) {
  594. if ( console != null )
  595. console.error( "// Error: " + s +"\n" );
  596. else {
  597. err.println("// Error: " + s);
  598. err.flush();
  599. }
  600. }
  601. // ConsoleInterface
  602. // The interpreter reflexively implements the console interface that it
  603. // uses. Should clean this up by using an inner class to implement the
  604. // console for us.
  605. /**
  606. Get the input stream associated with this interpreter.
  607. This may be be stdin or the GUI console.
  608. */
  609. public Reader getIn() { return in; }
  610. /**
  611. Get the outptut stream associated with this interpreter.
  612. This may be be stdout or the GUI console.
  613. */
  614. public PrintStream getOut() { return out; }
  615. /**
  616. Get the error output stream associated with this interpreter.
  617. This may be be stderr or the GUI console.
  618. */
  619. public PrintStream getErr() { return err; }
  620. public final void println(String s)
  621. {
  622. //print(s + "\n");
  623. print( s + systemLineSeparator );
  624. }
  625. public final void print(String s)
  626. {
  627. if (console != null) {
  628. console.print(s);
  629. } else {
  630. out.print(s);
  631. out.flush();
  632. }
  633. }
  634. // End ConsoleInterface
  635. /**
  636. Print a debug message on debug stream associated with this interpreter
  637. only if debugging is turned on.
  638. */
  639. public final static void debug(String s)
  640. {
  641. if ( DEBUG )
  642. debug.println("// Debug: " + s);
  643. }
  644. /*
  645. Primary interpreter set and get variable methods
  646. Note: These are squeltching errors... should they?
  647. */
  648. /**
  649. Get the value of the name.
  650. name may be any value. e.g. a variable or field
  651. */
  652. public Object get( String name ) throws EvalError {
  653. try {
  654. Object ret = globalNameSpace.get( name, this );
  655. return Primitive.unwrap( ret );
  656. } catch ( UtilEvalError e ) {
  657. throw e.toEvalError( SimpleNode.JAVACODE, new CallStack() );
  658. }
  659. }
  660. /**
  661. Unchecked get for internal use
  662. */
  663. Object getu( String name ) {
  664. try {
  665. return get( name );
  666. } catch ( EvalError e ) {
  667. throw new InterpreterError("set: "+e);
  668. }
  669. }
  670. /**
  671. Assign the value to the name.
  672. name may evaluate to anything assignable. e.g. a variable or field.
  673. */
  674. public void set( String name, Object value )
  675. throws EvalError
  676. {
  677. // map null to Primtive.NULL coming in...
  678. if ( value == null )
  679. value = Primitive.NULL;
  680. CallStack callstack = new CallStack();
  681. try {
  682. if ( Name.isCompound( name ) )
  683. {
  684. LHS lhs = globalNameSpace.getNameResolver( name ).toLHS(
  685. callstack, this );
  686. lhs.assign( value, false );
  687. } else // optimization for common case
  688. globalNameSpace.setVariable( name, value, false );
  689. } catch ( UtilEvalError e ) {
  690. throw e.toEvalError( SimpleNode.JAVACODE, callstack );
  691. }
  692. }
  693. /**
  694. Unchecked set for internal use
  695. */
  696. void setu(String name, Object value) {
  697. try {
  698. set(name, value);
  699. } catch ( EvalError e ) {
  700. throw new InterpreterError("set: "+e);
  701. }
  702. }
  703. public void set(String name, long value) throws EvalError {
  704. set(name, new Primitive(value));
  705. }
  706. public void set(String name, int value) throws EvalError {
  707. set(name, new Primitive(value));
  708. }
  709. public void set(String name, double value) throws EvalError {
  710. set(name, new Primitive(value));
  711. }
  712. public void set(String name, float value) throws EvalError {
  713. set(name, new Primitive(value));
  714. }
  715. public void set(String name, boolean value) throws EvalError {
  716. set(name, new Primitive(value));
  717. }
  718. /**
  719. Unassign the variable name.
  720. Name should evaluate to a variable.
  721. */
  722. public void unset( String name )
  723. throws EvalError
  724. {
  725. /*
  726. We jump through some hoops here to handle arbitrary cases like
  727. unset("bsh.foo");
  728. */
  729. CallStack callstack = new CallStack();
  730. try {
  731. LHS lhs = globalNameSpace.getNameResolver( name ).toLHS(
  732. callstack, this );
  733. if ( lhs.type != LHS.VARIABLE )
  734. throw new EvalError("Can't unset, not a variable: "+name,
  735. SimpleNode.JAVACODE, new CallStack() );
  736. //lhs.assign( null, false );
  737. lhs.nameSpace.unsetVariable( name );
  738. } catch ( UtilEvalError e ) {
  739. throw new EvalError( e.getMessage(),
  740. SimpleNode.JAVACODE, new CallStack() );
  741. }
  742. }
  743. // end primary set and get methods
  744. /**
  745. Get a reference to the interpreter (global namespace), cast
  746. to the specified interface type. Assuming the appropriate
  747. methods of the interface are defined in the interpreter, then you may
  748. use this interface from Java, just like any other Java object.
  749. <p>
  750. For example:
  751. <pre>
  752. Interpreter interpreter = new Interpreter();
  753. // define a method called run()
  754. interpreter.eval("run() { ... }");
  755. // Fetch a reference to the interpreter as a Runnable
  756. Runnable runnable =
  757. (Runnable)interpreter.getInterface( Runnable.class );
  758. </pre>
  759. <p>
  760. Note that the interpreter does *not* require that any or all of the
  761. methods of the interface be defined at the time the interface is
  762. generated. However if you attempt to invoke one that is not defined
  763. you will get a runtime exception.
  764. <p>
  765. Note also that this convenience method has exactly the same effect as
  766. evaluating the script:
  767. <pre>
  768. (Type)this;
  769. </pre>
  770. <p>
  771. For example, the following is identical to the previous example:
  772. <p>
  773. <pre>
  774. // Fetch a reference to the interpreter as a Runnable
  775. Runnable runnable =
  776. (Runnable)interpreter.eval( "(Runnable)this" );
  777. </pre>
  778. <p>
  779. <em>Version requirement</em> Although standard Java interface types
  780. are always available, to be used with arbitrary interfaces this
  781. feature requires that you are using Java 1.3 or greater.
  782. <p>
  783. @throws EvalError if the interface cannot be generated because the
  784. version of Java does not support the proxy mechanism.
  785. */
  786. public Object getInterface( Class interf ) throws EvalError
  787. {
  788. try {
  789. return globalNameSpace.getThis( this ).getInterface( interf );
  790. } catch ( UtilEvalError e ) {
  791. throw e.toEvalError( SimpleNode.JAVACODE, new CallStack() );
  792. }
  793. }
  794. /* Methods for interacting with Parser */
  795. private JJTParserState get_jjtree() {
  796. return parser.jjtree;
  797. }
  798. private JavaCharStream get_jj_input_stream() {
  799. return parser.jj_input_stream;
  800. }
  801. private boolean Line() throws ParseException {
  802. return parser.Line();
  803. }
  804. /* End methods for interacting with Parser */
  805. void loadRCFiles() {
  806. try {
  807. String rcfile =
  808. // Default is c:\windows under win98, $HOME under Unix
  809. System.getProperty("user.home") + File.separator + ".bshrc";
  810. source( rcfile, globalNameSpace );
  811. } catch ( Exception e ) {
  812. // squeltch security exception, filenotfoundexception
  813. if ( Interpreter.DEBUG ) debug("Could not find rc file: "+e);
  814. }
  815. }
  816. /**
  817. Localize a path to the file name based on the bsh.cwd interpreter
  818. working directory.
  819. */
  820. public File pathToFile( String fileName )
  821. throws IOException
  822. {
  823. File file = new File( fileName );
  824. // if relative, fix up to bsh.cwd
  825. if ( !file.isAbsolute() ) {
  826. String cwd = (String)getu("bsh.cwd");
  827. file = new File( cwd + File.separator + fileName );
  828. }
  829. // The canonical file name is also absolute.
  830. // No need for getAbsolutePath() here...
  831. return new File( file.getCanonicalPath() );
  832. }
  833. public static void redirectOutputToFile( String filename )
  834. {
  835. try {
  836. PrintStream pout = new PrintStream(
  837. new FileOutputStream( filename ) );
  838. System.setOut( pout );
  839. System.setErr( pout );
  840. } catch ( IOException e ) {
  841. System.err.println("Can't redirect output to file: "+filename );
  842. }
  843. }
  844. /**
  845. Set an external class loader to be used for all basic class loading
  846. in BeanShell.
  847. <p>
  848. BeanShell will use this at the same point it would otherwise use the
  849. plain Class.forName().
  850. i.e. if no explicit classpath management is done from the script
  851. (addClassPath(), setClassPath(), reloadClasses()) then BeanShell will
  852. only use the supplied classloader. If additional classpath management
  853. is done then BeanShell will perform that in addition to the supplied
  854. external classloader.
  855. However BeanShell is not currently able to reload
  856. classes supplied through the external classloader.
  857. <p>
  858. @see BshClassManager#setClassLoader( ClassLoader )
  859. */
  860. public void setClassLoader( ClassLoader externalCL ) {
  861. getClassManager().setClassLoader( externalCL );
  862. }
  863. /**
  864. Get the class manager associated with this interpreter
  865. (the BshClassManager of this interpreter's global namespace).
  866. This is primarily a convenience method.
  867. */
  868. public BshClassManager getClassManager()
  869. {
  870. return getNameSpace().getClassManager();
  871. }
  872. /**
  873. Set the class manager.
  874. public setClassManager( BshClassManager manager )
  875. {
  876. this.classManager = manager;
  877. }
  878. */
  879. /**
  880. Set strict Java mode on or off.
  881. This mode attempts to make BeanShell syntax behave as Java
  882. syntax, eliminating conveniences like loose variables, etc.
  883. When enabled, variables are required to be declared or initialized
  884. before use and method arguments are reqired to have types.
  885. <p>
  886. This mode will become more strict in a future release when
  887. classes are interpreted and there is an alternative to scripting
  888. objects as method closures.
  889. */
  890. public void setStrictJava( boolean b ) {
  891. this.strictJava = b;
  892. }
  893. /**
  894. @see #setStrictJava( boolean )
  895. */
  896. public boolean getStrictJava() {
  897. return this.strictJava;
  898. }
  899. static void staticInit()
  900. {
  901. /*
  902. Apparently in some environments you can't catch the security exception
  903. at all... e.g. as an applet in IE ... will probably have to work
  904. around
  905. */
  906. try {
  907. systemLineSeparator = System.getProperty("line.separator");
  908. debug = System.err;
  909. DEBUG = Boolean.getBoolean("debug");
  910. TRACE = Boolean.getBoolean("trace");
  911. LOCALSCOPING = Boolean.getBoolean("localscoping");
  912. String outfilename = System.getProperty("outfile");
  913. if ( outfilename != null )
  914. redirectOutputToFile( outfilename );
  915. } catch ( SecurityException e ) {
  916. System.err.println("Could not init static:"+e);
  917. } catch ( Exception e ) {
  918. System.err.println("Could not init static(2):"+e);
  919. } catch ( Throwable e ) {
  920. System.err.println("Could not init static(3):"+e);
  921. }
  922. }
  923. /**
  924. Specify the source of the text from which this interpreter is reading.
  925. Note: there is a difference between what file the interrpeter is
  926. sourcing and from what file a method was originally parsed. One
  927. file may call a method sourced from another file. See SimpleNode
  928. for origination file info.
  929. @see bsh.SimpleNode#getSourceFile()
  930. */
  931. public String getSourceFileInfo() {
  932. if ( sourceFileInfo != null )
  933. return sourceFileInfo;
  934. else
  935. return "<unknown source>";
  936. }
  937. /**
  938. Get the parent Interpreter of this interpreter, if any.
  939. Currently this relationship implies the following:
  940. 1) Parent and child share a BshClassManager
  941. 2) Children indicate the parent's source file information in error
  942. reporting.
  943. When created as part of a source() / eval() the child also shares
  944. the parent's namespace. But that is not necessary in general.
  945. */
  946. public Interpreter getParent() {
  947. return parent;
  948. }
  949. public void setOut( PrintStream out ) {
  950. this.out = out;
  951. }
  952. public void setErr( PrintStream err ) {
  953. this.err = err;
  954. }
  955. /**
  956. De-serialization setup.
  957. Default out and err streams to stdout, stderr if they are null.
  958. */
  959. private void readObject(ObjectInputStream stream)
  960. throws java.io.IOException, ClassNotFoundException
  961. {
  962. stream.defaultReadObject();
  963. // set transient fields
  964. if ( console != null ) {
  965. setOut( console.getOut() );
  966. setErr( console.getErr() );
  967. } else {
  968. setOut( System.out );
  969. setErr( System.err );
  970. }
  971. }
  972. /**
  973. Get the prompt string defined by the getBshPrompt() method in the
  974. global namespace. This may be from the getBshPrompt() command or may
  975. be defined by the user as with any other method.
  976. Defaults to "bsh % " if the method is not defined or there is an error.
  977. */
  978. private String getBshPrompt()
  979. {
  980. try {
  981. return (String)eval("getBshPrompt()");
  982. } catch ( Exception e ) {
  983. return "bsh % ";
  984. }
  985. }
  986. /**
  987. Specify whether, in interactive mode, the interpreter exits Java upon
  988. end of input. If true, when in interactive mode the interpreter will
  989. issue a System.exit(0) upon eof. If false the interpreter no
  990. System.exit() will be done.
  991. <p/>
  992. Note: if you wish to cause an EOF externally you can try closing the
  993. input stream. This is not guaranteed to work in older versions of Java
  994. due to Java limitations, but should work in newer JDK/JREs. (That was
  995. the motivation for the Java NIO package).
  996. */
  997. public void setExitOnEOF( boolean value ) {
  998. exitOnEOF = value; // ug
  999. }
  1000. }