PageRenderTime 44ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

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

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