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

/jEdit/tags/jedit-4-1-pre5/bsh/Interpreter.java

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