Example #1
0
 /** Returns the contents of the next text field. */
 public String getNextString() {
   String theText;
   if (stringField == null) return "";
   TextField tf = (TextField) (stringField.elementAt(sfIndex));
   theText = tf.getText();
   if (macro) {
     String label = (String) labels.get((Object) tf);
     theText = Macro.getValue(macroOptions, label, theText);
     if (theText != null
         && (theText.startsWith("&") || label.toLowerCase(Locale.US).startsWith(theText))) {
       // Is the value a macro variable?
       if (theText.startsWith("&")) theText = theText.substring(1);
       Interpreter interp = Interpreter.getInstance();
       String s = interp != null ? interp.getVariableAsString(theText) : null;
       if (s != null) theText = s;
     }
   }
   if (recorderOn) {
     String s = theText;
     if (s != null
         && s.length() >= 3
         && Character.isLetter(s.charAt(0))
         && s.charAt(1) == ':'
         && s.charAt(2) == '\\')
       s = s.replaceAll("\\\\", "\\\\\\\\"); // replace "\" with "\\" in Windows file paths
     if (!smartRecording || !s.equals((String) defaultStrings.elementAt(sfIndex)))
       recordOption(tf, s);
     else if (Recorder.getCommandOptions() == null) Recorder.recordOption(" ");
   }
   sfIndex++;
   return theText;
 }
Example #2
0
 private static void endInterpreter(String contextId) throws EvalError {
   Interpreter i = interpreters.get(contextId);
   if (i == null) return;
   i.eval("clear();"); // can't hurt to tell bsh to clean up internally
   interpreters.remove(contextId); // now wait for GC
   Log.log("Destroyed context: " + contextId + " (" + i + ")");
 }
 private void populateResponses() throws SurveyException {
   Interpreter interpreter = new Interpreter(survey);
   do {
     Question q = interpreter.getNextQuestion();
     SurveyDatum[] c = q.getOptListByIndex();
     List<SurveyDatum> answers = new ArrayList<>();
     // calculate our answer
     if (q.freetext) {
       answers.add(new StringDatum(generateStringComponent(q), -1, -1));
     } else {
       int denom = getDenominator(q);
       double prob = rng.nextDouble();
       double cumulativeProb = 0.0;
       for (int j = 0; j < denom; j++) {
         assert posPref.get(q).length == denom
             : String.format(
                 "Expected position preference question options and denom to be equal (%d = %d)",
                 posPref.get(q).length, denom);
         cumulativeProb += posPref.get(q)[j];
         if (prob < cumulativeProb) {
           answers.addAll(selectOptions(j, c));
           break;
         }
       }
     }
     interpreter.answer(q, answers);
   } while (!interpreter.terminated());
   this.response = interpreter.getResponse();
   this.response.setKnownValidityStatus(KnownValidityStatus.NO);
 }
Example #4
0
  /**
   * Runs a BeanShell script. Errors are passed to the caller.
   *
   * <p>If the <code>in</code> parameter is non-null, the script is read from that stream; otherwise
   * it is read from the file identified by <code>path</code> .
   *
   * <p>The <code>scriptPath</code> BeanShell variable is set to the path name of the script.
   *
   * @param path The script file's VFS path.
   * @param in The reader to read the script from, or <code>null</code> .
   * @param namespace The namespace to run the script in.
   * @exception Exception instances are thrown when various BeanShell errors occur
   * @since jEdit 4.2pre5
   */
  public void _runScript(String path, Reader in, NameSpace namespace) throws Exception {
    log.info("Running script " + path);

    Interpreter interp = createInterpreter(namespace);

    try {
      if (in == null) {
        in = res.getResourceAsReader(path);
      }

      setupDefaultVariables(namespace);
      interp.set("scriptPath", path);

      running = true;

      interp.eval(in, namespace, path);
    } catch (Exception e) {
      unwrapException(e);
    } finally {
      running = false;

      try {
        // no need to do this for macros!
        if (namespace == global) {
          resetDefaultVariables(namespace);
          interp.unset("scriptPath");
        }
      } catch (EvalError e) {
        // do nothing
      }
    }
  } // }}}
  @Override
  protected Object jobRun() throws Throwable {
    String replName = getRequiredReplName();
    Interpreter repl = getRepl(replName);
    logger().info("run paragraph {} using {} " + repl, getId(), replName);
    if (repl == null) {
      logger().error("Can not find interpreter name " + repl);
      throw new RuntimeException("Can not find interpreter for " + getRequiredReplName());
    }

    String script = getScriptBody();
    // inject form
    if (repl.getFormType() == FormType.NATIVE) {
      settings.clear();
    } else if (repl.getFormType() == FormType.SIMPLE) {
      String scriptBody = getScriptBody();
      Map<String, Input> inputs = Input.extractSimpleQueryParam(scriptBody); // inputs will be built
      // from script body
      settings.setForms(inputs);
      script = Input.getSimpleQuery(settings.getParams(), scriptBody);
    }
    logger().info("RUN : " + script);
    InterpreterResult ret = repl.interpret(script, getInterpreterContext());
    return ret;
  }
Example #6
0
 /**
  * Execute Script Loads environment and saves result
  *
  * @return null or Exception
  */
 public Exception execute() {
   m_result = null;
   if (m_variable == null
       || m_variable.length() == 0
       || m_script == null
       || m_script.length() == 0) {
     IllegalArgumentException e = new IllegalArgumentException("No variable/script");
     log.config(e.toString());
     return e;
   }
   Interpreter i = new Interpreter();
   loadEnvironment(i);
   try {
     log.config(m_script);
     i.eval(m_script);
   } catch (Exception e) {
     log.config(e.toString());
     return e;
   }
   try {
     m_result = i.get(m_variable);
     log.config("Result (" + m_result.getClass().getName() + ") " + m_result);
   } catch (Exception e) {
     log.config("Result - " + e);
     if (e instanceof NullPointerException)
       e = new IllegalArgumentException("Result Variable not found - " + m_variable);
     return e;
   }
   return null;
 } //  execute
Example #7
0
 /** Returns the index of the selected item in the next popup menu. */
 public int getNextChoiceIndex() {
   if (choice == null) return -1;
   Choice thisChoice = (Choice) (choice.elementAt(choiceIndex));
   int index = thisChoice.getSelectedIndex();
   if (macro) {
     String label = (String) labels.get((Object) thisChoice);
     String oldItem = thisChoice.getSelectedItem();
     int oldIndex = thisChoice.getSelectedIndex();
     String item = Macro.getValue(macroOptions, label, oldItem);
     if (item != null && item.startsWith("&")) // value is macro variable
     item = getChoiceVariable(item);
     thisChoice.select(item);
     index = thisChoice.getSelectedIndex();
     if (index == oldIndex && !item.equals(oldItem)) {
       // is value a macro variable?
       Interpreter interp = Interpreter.getInstance();
       String s = interp != null ? interp.getStringVariable(item) : null;
       if (s == null)
         IJ.error(getTitle(), "\"" + item + "\" is not a valid choice for \"" + label + "\"");
       else item = s;
     }
   }
   if (recorderOn) {
     int defaultIndex = ((Integer) (defaultChoiceIndexes.elementAt(choiceIndex))).intValue();
     if (!(smartRecording && index == defaultIndex)) {
       String item = thisChoice.getSelectedItem();
       if (!(item.equals("*None*") && getTitle().equals("Merge Channels")))
         recordOption(thisChoice, thisChoice.getSelectedItem());
     }
   }
   choiceIndex++;
   return index;
 }
  @Override
  protected Object jobRun() throws Throwable {
    String replName = getRequiredReplName();
    Interpreter repl = getRepl(replName);
    logger().info("run paragraph {} using {} " + repl, getId(), replName);
    if (repl == null) {
      logger().error("Can not find interpreter name " + repl);
      throw new RuntimeException("Can not find interpreter for " + getRequiredReplName());
    }

    String script = getScriptBody();
    // inject form
    if (repl.getFormType() == FormType.NATIVE) {
      settings.clear();
    } else if (repl.getFormType() == FormType.SIMPLE) {
      String scriptBody = getScriptBody();
      Map<String, Input> inputs = Input.extractSimpleQueryParam(scriptBody); // inputs will be built
      // from script body
      settings.setForms(inputs);
      script = Input.getSimpleQuery(settings.getParams(), scriptBody);
    }
    logger().debug("RUN : " + script);
    try {
      InterpreterContext context = getInterpreterContext();
      InterpreterContext.set(context);
      InterpreterResult ret = repl.interpret(script, context);

      if (Code.KEEP_PREVIOUS_RESULT == ret.code()) {
        return getReturn();
      }

      String message = "";

      context.out.flush();
      InterpreterResult.Type outputType = context.out.getType();
      byte[] interpreterOutput = context.out.toByteArray();
      context.out.clear();

      if (interpreterOutput != null && interpreterOutput.length > 0) {
        message = new String(interpreterOutput);
      }

      if (message.isEmpty()) {
        return ret;
      } else {
        String interpreterResultMessage = ret.message();
        if (interpreterResultMessage != null && !interpreterResultMessage.isEmpty()) {
          message += interpreterResultMessage;
          return new InterpreterResult(ret.code(), ret.type(), message);
        } else {
          return new InterpreterResult(ret.code(), outputType, message);
        }
      }
    } finally {
      InterpreterContext.remove();
    }
  }
Example #9
0
 public double parseDouble(String s) {
   if (s == null) return Double.NaN;
   double value = Tools.parseDouble(s);
   if (Double.isNaN(value)) {
     if (s.startsWith("&")) s = s.substring(1);
     Interpreter interp = Interpreter.getInstance();
     value = interp != null ? interp.getVariable2(s) : Double.NaN;
   }
   return value;
 }
Example #10
0
 @Override
 public int progress() {
   String replName = getRequiredReplName();
   Interpreter repl = getRepl(replName);
   if (repl != null) {
     return repl.getProgress(getInterpreterContext());
   } else {
     return 0;
   }
 }
Example #11
0
 private String backgroundColour(String type) {
   LispExpr e = interpreter.getGlobalExpr(type);
   if (!(e instanceof LispString)) {
     e = interpreter.getGlobalExpr("text-background-colour");
     if (!(e instanceof LispString)) {
       return "white";
     }
   }
   return ((LispString) e).toString();
 }
Example #12
0
 @Override
 protected boolean jobAbort() {
   Interpreter repl = getRepl(getRequiredReplName());
   Job job = repl.getScheduler().removeFromWaitingQueue(getId());
   if (job != null) {
     job.setStatus(Status.ABORT);
   } else {
     repl.cancel(getInterpreterContext());
   }
   return true;
 }
Example #13
0
  /**
   * Get combined property of all interpreters in this group
   *
   * @return
   */
  public Properties getProperty() {
    Properties p = new Properties();

    for (List<Interpreter> intpGroupForASession : this.values()) {
      for (Interpreter intp : intpGroupForASession) {
        p.putAll(intp.getProperty());
      }
      // it's okay to break here while every List<Interpreters> will have the same property set
      break;
    }
    return p;
  }
Example #14
0
 /**
  * Returns the contents of the next numeric field, or NaN if the field does not contain a number.
  */
 public double getNextNumber() {
   if (numberField == null) return -1.0;
   TextField tf = (TextField) numberField.elementAt(nfIndex);
   String theText = tf.getText();
   String label = null;
   if (macro) {
     label = (String) labels.get((Object) tf);
     theText = Macro.getValue(macroOptions, label, theText);
     // IJ.write("getNextNumber: "+label+"  "+theText);
   }
   String originalText = (String) defaultText.elementAt(nfIndex);
   double defaultValue = ((Double) (defaultValues.elementAt(nfIndex))).doubleValue();
   double value;
   boolean skipRecording = false;
   if (theText.equals(originalText)) {
     value = defaultValue;
     if (smartRecording) skipRecording = true;
   } else {
     Double d = getValue(theText);
     if (d != null) value = d.doubleValue();
     else {
       // Is the value a macro variable?
       if (theText.startsWith("&")) theText = theText.substring(1);
       Interpreter interp = Interpreter.getInstance();
       value = interp != null ? interp.getVariable2(theText) : Double.NaN;
       if (Double.isNaN(value)) {
         invalidNumber = true;
         errorMessage = "\"" + theText + "\" is an invalid number";
         value = Double.NaN;
         if (macro) {
           IJ.error(
               "Macro Error",
               "Numeric value expected in run() function\n \n"
                   + "   Dialog box title: \""
                   + getTitle()
                   + "\"\n"
                   + "   Key: \""
                   + label.toLowerCase(Locale.US)
                   + "\"\n"
                   + "   Value or variable name: \""
                   + theText
                   + "\"");
         }
       }
     }
   }
   if (recorderOn && !skipRecording) {
     recordOption(tf, trim(theText));
   }
   nfIndex++;
   return value;
 }
Example #15
0
  public List<String> completion(String buffer, int cursor) {
    String replName = getRequiredReplName(buffer);
    if (replName != null) {
      cursor -= replName.length() + 1;
    }
    String body = getScriptBody(buffer);
    Interpreter repl = getRepl(replName);
    if (repl == null) {
      return null;
    }

    return repl.completion(body, cursor);
  }
Example #16
0
 private String getChoiceVariable(String item) {
   item = item.substring(1);
   Interpreter interp = Interpreter.getInstance();
   String s = interp != null ? interp.getStringVariable(item) : null;
   if (s == null) {
     double value = interp != null ? interp.getVariable2(item) : Double.NaN;
     if (!Double.isNaN(value)) {
       if ((int) value == value) s = "" + (int) value;
       else s = "" + value;
     }
   }
   if (s != null) item = s;
   return item;
 }
Example #17
0
  public static void main(String argv[]) {
    // basically, if a command-line parameter is supplied
    // then assume it is a file name and execute it as
    // a simpular program without using the GUI at all.
    if (argv.length == 0) {
      // no command-line parameters, so use GUI.
      InterpreterFrame f = new InterpreterFrame();
    } else if (argv[0].equals("-no-gui")) {
      // run interpreter without GUI!

      // setup new argument list for original
      // Main method
      String[] newargv = new String[argv.length - 1];
      for (int i = 1; i != argv.length; ++i) {
        newargv[i - 1] = argv[i];
      }
      Interpreter.main(newargv);
    } else {
      // run interpreter with GUI, but
      // load requested file.

      InterpreterFrame f = new InterpreterFrame();
      // load file into text view
      f.textView.setText(f.physReadTextFile(new File(argv[0])));
      // update status
      f.statusView.setText(" Loaded file \"" + argv[0] + "\".");
      // reset dirty bit
      f.dirty = false;
    }
  }
Example #18
0
 /**
  * Set Environment for Interpreter
  *
  * @param i Interpreter
  */
 private void loadEnvironment(Interpreter i) {
   if (m_ctx == null) return;
   Iterator<String> it = m_ctx.keySet().iterator();
   while (it.hasNext()) {
     String key = it.next();
     Object value = m_ctx.get(key);
     try {
       if (value instanceof Boolean) i.set(key, ((Boolean) value).booleanValue());
       else if (value instanceof Integer) i.set(key, ((Integer) value).intValue());
       else if (value instanceof Double) i.set(key, ((Double) value).doubleValue());
       else i.set(key, value);
     } catch (EvalError ee) {
       log.log(Level.SEVERE, "", ee);
     }
   }
 } //  setEnvironment
  public String[][] exec(String[] befehle) {
    String[][] antworten = new String[befehle.length][1];
    Object aktObj;
    for (int i = 0; i < befehle.length; i++) {
      try {
        aktObj = interpreter.eval(befehle[i]);
        if (aktObj != null) antworten[i][0] = aktObj.toString();
        else antworten[i][0] = "null";
      } catch (EvalError e) {
        System.err.println(e.getMessage());
        antworten[i][0] = "ERROR";
      }
      if (verbose) {
        assert !quiet;
        System.out.println("# " + i + ":  " + befehle[i]);
        for (int j = 0; j < antworten[i].length; j++) {
          System.out.println("@ " + antworten[i][j]);
        }
      } else if (!quiet)
        for (int j = 0; j < antworten[i].length; j++) {
          System.out.print("#");
        }
    }

    return antworten;
  }
Example #20
0
 void drawAllROIs(Graphics g) {
   RoiManager rm = RoiManager.getInstance();
   if (rm == null) {
     rm = Interpreter.getBatchModeRoiManager();
     if (rm != null && rm.getList().getItemCount() == 0) rm = null;
   }
   if (rm == null) {
     // if (showAllList!=null)
     //	overlay = showAllList;
     showAllROIs = false;
     repaint();
     return;
   }
   initGraphics(g, null, showAllColor);
   Hashtable rois = rm.getROIs();
   java.awt.List list = rm.getList();
   boolean drawLabels = rm.getDrawLabels();
   currentRoi = null;
   int n = list.getItemCount();
   if (IJ.debugMode) IJ.log("paint: drawing " + n + " \"Show All\" ROIs");
   if (labelRects == null || labelRects.length != n) labelRects = new Rectangle[n];
   if (!drawLabels) showAllList = new Overlay();
   else showAllList = null;
   if (imp == null) return;
   int currentImage = imp.getCurrentSlice();
   int channel = 0, slice = 0, frame = 0;
   boolean hyperstack = imp.isHyperStack();
   if (hyperstack) {
     channel = imp.getChannel();
     slice = imp.getSlice();
     frame = imp.getFrame();
   }
   drawNames = Prefs.useNamesAsLabels;
   for (int i = 0; i < n; i++) {
     String label = list.getItem(i);
     Roi roi = (Roi) rois.get(label);
     if (roi == null) continue;
     if (showAllList != null) showAllList.add(roi);
     if (i < 200 && drawLabels && roi == imp.getRoi()) currentRoi = roi;
     if (Prefs.showAllSliceOnly && imp.getStackSize() > 1) {
       if (hyperstack && roi.getPosition() == 0) {
         int c = roi.getCPosition();
         int z = roi.getZPosition();
         int t = roi.getTPosition();
         if ((c == 0 || c == channel) && (z == 0 || z == slice) && (t == 0 || t == frame))
           drawRoi(g, roi, drawLabels ? i : -1);
       } else {
         int position = roi.getPosition();
         if (position == 0) position = getSliceNumber(roi.getName());
         if (position == 0 || position == currentImage) drawRoi(g, roi, drawLabels ? i : -1);
       }
     } else drawRoi(g, roi, drawLabels ? i : -1);
   }
   ((Graphics2D) g).setStroke(Roi.onePixelWide);
   drawNames = false;
 }
  @Override
  protected boolean jobAbort() {
    Interpreter repl = getRepl(getRequiredReplName());
    if (repl == null) {
      // when interpreters are already destroyed
      return true;
    }

    Scheduler scheduler = repl.getScheduler();
    if (scheduler == null) {
      return true;
    }

    Job job = scheduler.removeFromWaitingQueue(getId());
    if (job != null) {
      job.setStatus(Status.ABORT);
    } else {
      repl.cancel(getInterpreterContext());
    }
    return true;
  }
Example #22
0
  /**
   * Evaluates the specified BeanShell expression. Unlike <code>eval()</code> , this method passes
   * any exceptions to the caller.
   *
   * @param namespace The namespace
   * @param command The expression
   * @return Description of the Return Value
   * @exception Exception instances are thrown when various BeanShell errors occur
   * @since jEdit 3.2pre7
   */
  public Object _eval(NameSpace namespace, String command) throws Exception {
    Interpreter interp = createInterpreter(namespace);

    try {
      setupDefaultVariables(namespace);
      if (log.isDebugEnabled()) {
        log.debug("Running script: " + command);
      }
      return interp.eval(command);
    } catch (Exception e) {
      unwrapException(e);
      // never called
      return null;
    } finally {
      // try {
      resetDefaultVariables(namespace);
      // }
      // catch (UtilEvalError e) {
      // do nothing
      // }
    }
  } // }}}
Example #23
0
  public Interpreter clone() {
    Interpreter clone = new Interpreter();

    clone._useFrames = _useFrames;

    Program instructionList = new Program();
    _inInstructionList.CopyTo(instructionList);
    clone.SetInstructions(instructionList);
    clone.SetRandomParameters(
        _minRandomInt,
        _maxRandomInt,
        _randomIntResolution,
        _minRandomFloat,
        _maxRandomFloat,
        _randomFloatResolution,
        _maxRandomCodeSize,
        _maxPointsInProgram);

    clone._useFrames = _useFrames;

    return clone;
  }
 public void run(String path) {
   if (path == null || path.equals("")) path = showDialog();
   if (path == null) return;
   openingStartupMacrosInEditor = path.indexOf("StartupMacros") != -1;
   String text = open(path);
   if (text != null) {
     String functions = Interpreter.getAdditionalFunctions();
     if (functions != null) {
       if (!(text.endsWith("\n") || functions.startsWith("\n"))) text = text + "\n" + functions;
       else text = text + functions;
     }
     install(text);
   }
 }
  public List<InterpreterCompletion> completion(String buffer, int cursor) {
    String lines[] = buffer.split(System.getProperty("line.separator"));
    if (lines.length > 0 && lines[0].startsWith("%") && cursor <= lines[0].trim().length()) {

      int idx = lines[0].indexOf(' ');
      if (idx < 0 || (idx > 0 && cursor <= idx)) {
        return getInterpreterCompletion();
      }
    }

    String replName = getRequiredReplName(buffer);
    if (replName != null && cursor > replName.length()) {
      cursor -= replName.length() + 1;
    }

    String body = getScriptBody(buffer);
    Interpreter repl = getRepl(replName);
    if (repl == null) {
      return null;
    }

    List completion = repl.completion(body, cursor);
    return completion;
  }
  public String[] exec(String befehl) {
    String[] antwort = new String[1];
    Object aktObj;
    try {
      aktObj = interpreter.eval(befehl);
      if (aktObj != null) antwort[0] = aktObj.toString();
      else antwort[0] = "null";
    } catch (EvalError e) {
      System.err.println(e.getMessage());
      antwort[0] = "ERROR";
    }

    if (!quiet) System.out.print("#");
    if (verbose) {
      assert !quiet;
      System.out.println(" " + befehl);
      System.out.println("@ " + antwort[0]);
    }

    return antwort;
  }
Example #27
0
  public InterpreterFrame() {
    super("Simple Lisp Interpreter");

    // Create the menu
    menubar = buildMenuBar();
    setJMenuBar(menubar);
    // Create the toolbar
    toolbar = buildToolBar();
    // disable cut and copy actions
    cutAction.setEnabled(false);
    copyAction.setEnabled(false);
    // Setup text area for editing source code
    // and setup document listener so interpreter
    // is notified when current file modified and
    // when the cursor is moved.
    textView = buildEditor();
    textView.getDocument().addDocumentListener(this);
    textView.addCaretListener(this);

    // set default key bindings
    bindKeyToCommand("ctrl C", "(buffer-copy)");
    bindKeyToCommand("ctrl X", "(buffer-cut)");
    bindKeyToCommand("ctrl V", "(buffer-paste)");
    bindKeyToCommand("ctrl E", "(buffer-eval)");
    bindKeyToCommand("ctrl O", "(file-open)");
    bindKeyToCommand("ctrl S", "(file-save)");
    bindKeyToCommand("ctrl Q", "(exit)");

    // Give text view scrolling capability
    Border border =
        BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(3, 3, 3, 3),
            BorderFactory.createLineBorder(Color.gray));
    JScrollPane topSplit = addScrollers(textView);
    topSplit.setBorder(border);

    // Create tabbed pane for console/problems
    consoleView = makeConsoleArea(10, 50, true);
    problemsView = makeConsoleArea(10, 50, false);
    tabbedPane = buildProblemsConsole();

    // Plug the editor and problems/console together
    // using a split pane. This allows one to change
    // their relative size using the split-bar in
    // between them.
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topSplit, tabbedPane);

    // Create status bar
    statusView = new JLabel(" Status");
    lineNumberView = new JLabel("0:0");
    statusbar = buildStatusBar();

    // Now, create the outer panel which holds
    // everything together
    outerpanel = new JPanel();
    outerpanel.setLayout(new BorderLayout());
    outerpanel.add(toolbar, BorderLayout.PAGE_START);
    outerpanel.add(splitPane, BorderLayout.CENTER);
    outerpanel.add(statusbar, BorderLayout.SOUTH);
    getContentPane().add(outerpanel);

    // tell frame to fire a WindowsListener event
    // but not to close when "x" button clicked.
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(this);
    // set minimised icon to use
    setIconImage(makeImageIcon("spi.png").getImage());

    // setup additional internal functions
    InternalFunctions.setup_internals(interpreter, this);

    // set default window size
    Component top = splitPane.getTopComponent();
    Component bottom = splitPane.getBottomComponent();
    top.setPreferredSize(new Dimension(100, 400));
    bottom.setPreferredSize(new Dimension(100, 200));
    pack();

    // load + run user configuration file (if there is one)
    String homedir = System.getProperty("user.home");
    try {
      interpreter.load(homedir + "/.simplelisp");
    } catch (FileNotFoundException e) {
      // do nothing if file does not exist!
      System.out.println("Didn't find \"" + homedir + "/.simplelisp\"");
    }

    textView.grabFocus();
    setVisible(true);

    // redirect all I/O to problems/console
    redirectIO();

    // start highlighter thread
    highlighter = new DisplayThread(250);
    highlighter.setDaemon(true);
    highlighter.start();
  }
  /**
   * Parse the BSHBlock for for the class definition and generate the class using ClassGenerator.
   */
  public static Class generateClassImpl(
      String name,
      Modifiers modifiers,
      Class[] interfaces,
      Class superClass,
      BSHBlock block,
      boolean isInterface,
      CallStack callstack,
      Interpreter interpreter)
      throws EvalError {
    // Scripting classes currently requires accessibility
    // This can be eliminated with a bit more work.
    try {
      Capabilities.setAccessibility(true);
    } catch (Capabilities.Unavailable e) {
      throw new EvalError(
          "Defining classes currently requires reflective Accessibility.", block, callstack);
    }

    NameSpace enclosingNameSpace = callstack.top();
    String packageName = enclosingNameSpace.getPackage();
    String className =
        enclosingNameSpace.isClass ? (enclosingNameSpace.getName() + "$" + name) : name;
    String fqClassName = packageName == null ? className : packageName + "." + className;

    BshClassManager bcm = interpreter.getClassManager();
    // Race condition here...
    bcm.definingClass(fqClassName);

    // Create the class static namespace
    NameSpace classStaticNameSpace = new NameSpace(enclosingNameSpace, className);
    classStaticNameSpace.isClass = true;

    callstack.push(classStaticNameSpace);

    // Evaluate any inner class class definitions in the block
    // effectively recursively call this method for contained classes first
    block.evalBlock(callstack, interpreter, true /*override*/, ClassNodeFilter.CLASSCLASSES);

    // Generate the type for our class
    Variable[] variables = getDeclaredVariables(block, callstack, interpreter, packageName);
    DelayedEvalBshMethod[] methods = getDeclaredMethods(block, callstack, interpreter, packageName);

    ClassGeneratorUtil classGenerator =
        new ClassGeneratorUtil(
            modifiers,
            className,
            packageName,
            superClass,
            interfaces,
            variables,
            methods,
            classStaticNameSpace,
            isInterface);
    byte[] code = classGenerator.generateClass();

    // if debug, write out the class file to debugClasses directory
    if (DEBUG_DIR != null)
      try {
        FileOutputStream out = new FileOutputStream(DEBUG_DIR + '/' + className + ".class");
        out.write(code);
        out.close();
      } catch (IOException e) {
        throw new IllegalStateException(
            "cannot create file " + DEBUG_DIR + '/' + className + ".class", e);
      }

    // Define the new class in the classloader
    Class genClass = bcm.defineClass(fqClassName, code);

    // import the unq name into parent
    enclosingNameSpace.importClass(fqClassName.replace('$', '.'));

    try {
      classStaticNameSpace.setLocalVariable(
          ClassGeneratorUtil.BSHINIT, block, false /*strictJava*/);
    } catch (UtilEvalError e) {
      throw new InterpreterError("unable to init static: " + e);
    }

    // Give the static space its class static import
    // important to do this after all classes are defined
    classStaticNameSpace.setClassStatic(genClass);

    // evaluate the static portion of the block in the static space
    block.evalBlock(callstack, interpreter, true /*override*/, ClassNodeFilter.CLASSSTATIC);

    callstack.pop();

    if (!genClass.isInterface()) {
      // Set the static bsh This callback
      String bshStaticFieldName = ClassGeneratorUtil.BSHSTATIC + className;
      try {
        LHS lhs = Reflect.getLHSStaticField(genClass, bshStaticFieldName);
        lhs.assign(classStaticNameSpace.getThis(interpreter), false /*strict*/);
      } catch (Exception e) {
        throw new InterpreterError("Error in class gen setup: " + e);
      }
    }

    bcm.doneDefiningClass(fqClassName);
    return genClass;
  }
Example #29
0
 @Override
 protected boolean jobAbort() {
   Interpreter repl = getRepl(getRequiredReplName());
   repl.cancel(getInterpreterContext());
   return true;
 }
Example #30
0
 public static void main(String args[]) {
   Interpreter test = new Interpreter(new File(args[0]));
   test.run();
 }