PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

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

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