/jEdit/branches/4.4.x-merge-request-for-r18847-r18954-r19206-r19210/org/gjt/sp/jedit/bsh/Interpreter.java

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