/jEdit/tags/jedit-3-2-2/bsh/Interpreter.java

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