PageRenderTime 47ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

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

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