/* If we want to support multiple commands in the command path we need to change this to not throw the exception. */ private BshMethod loadScriptedCommand( InputStream in, String name, Class[] argTypes, String resourcePath, Interpreter interpreter) throws UtilEvalError { try { interpreter.eval(new InputStreamReader(in), this, resourcePath); } catch (EvalError e) { /* Here we catch any EvalError from the interpreter because we are using it as a tool to load the command, not as part of the execution path. */ Interpreter.debug(e.toString()); throw new UtilEvalError("Error loading script: " + e.getMessage(), e); } // Look for the loaded command BshMethod meth = getMethod(name, argTypes); /* if ( meth == null ) throw new UtilEvalError("Loaded resource: " + resourcePath + "had an error or did not contain the correct method" ); */ return meth; }
/** 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; }
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); }
/** * A command is a scripted method or compiled command class implementing a specified method * signature. Commands are loaded from the classpath and may be imported using the * importCommands() method. * * <p>This method searches the imported commands packages for a script or command object * corresponding to the name of the method. If it is a script the script is sourced into this * namespace and the BshMethod for the requested signature is returned. If it is a compiled class * the class is returned. (Compiled command classes implement static invoke() methods). * * <p>The imported packages are searched in reverse order, so that later imports take priority. * Currently only the first object (script or class) with the appropriate name is checked. If * another, overloaded form, is located in another package it will not currently be found. This * could be fixed. * * <p> * * @return a BshMethod, Class, or null if no such command is found. * @param name is the name of the desired command method * @param argTypes is the signature of the desired command method. * @throws UtilEvalError if loadScriptedCommand throws UtilEvalError i.e. on errors loading a * script that was found */ public Object getCommand(String name, Class[] argTypes, Interpreter interpreter) throws UtilEvalError { if (Interpreter.DEBUG) Interpreter.debug("getCommand: " + name); BshClassManager bcm = interpreter.getClassManager(); if (importedCommands != null) { // loop backwards for precedence for (int i = importedCommands.size() - 1; i >= 0; i--) { String path = importedCommands.get(i); String scriptPath; if (path.equals("/")) scriptPath = path + name + ".bsh"; else scriptPath = path + "/" + name + ".bsh"; Interpreter.debug("searching for script: " + scriptPath); InputStream in = bcm.getResourceAsStream(scriptPath); if (in != null) return loadScriptedCommand(in, name, argTypes, scriptPath, interpreter); // Chop leading "/" and change "/" to "." String className; if (path.equals("/")) className = name; else className = path.substring(1).replace('/', '.') + "." + name; Interpreter.debug("searching for class: " + className); Class clas = bcm.classForName(className); if (clas != null) return clas; } } if (parent != null) return parent.getCommand(name, argTypes, interpreter); else return null; }
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 + ")"); }
/** * 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 } } } // }}}
/** 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; }
/** * 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
/** * Takes an input string purporting to represent a program in L(G), where G is the context-free * grammar defined above, and prints the sequence of tokens of the program, terminated by a dummy * token. If an illegal token is present, it prints an error message to that effect. * * @param expr the string, represented as a string of tokens separated by whitespace characters as * recognized by the <code>Character.isWhitespace</code> predicate. */ private static void test(String program) { try { Interpreter interpreter = new Interpreter(); System.out.println(interpreter.interpret(program)); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } }
public ProjectNode(Interpreter interpreter, Project rel) { ImmutableList.Builder<Scalar> builder = ImmutableList.builder(); for (RexNode node : rel.getProjects()) { builder.add(interpreter.compile(node)); } this.projects = builder.build(); this.source = interpreter.source(rel, 0); this.sink = interpreter.sink(rel); this.context = interpreter.createContext(); }
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; }
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(); }
/** * 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; }
private void doTest(String input, String expectedOutput, boolean isQuestion) { interpreter.question = isQuestion; ArrayList<CNF> cnfInput = interpreter.getCNFInput(input); ArrayList<String> kifClauses = interpreter.interpretCNF(cnfInput); String actual = interpreter.fromKIFClauses(kifClauses); Formula actualFormula = new Formula(actual); assertEquals( expectedOutput.replaceAll("\\s+", " ").trim(), actual.replaceAll("\\s+", " ").trim()); assertTrue(actualFormula.logicallyEquals(expectedOutput)); }
@Override public Result attempt( final List<AvailObject> args, final Interpreter interpreter, final boolean skipReturnCheck) { assert args.size() == 2; final A_Atom propertyKey = args.get(0); final A_Atom atom = args.get(1); if (atom.isAtomSpecial()) { return interpreter.primitiveFailure(E_SPECIAL_ATOM); } final A_BasicObject propertyValue = atom.getAtomProperty(propertyKey); return interpreter.primitiveSuccess( AtomDescriptor.objectFromBoolean(!propertyValue.equalsNil())); }
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; }
@Override public Result attempt( final List<AvailObject> args, final Interpreter interpreter, final boolean skipReturnCheck) { assert args.size() == 1; final A_BasicObject value = args.get(0); final ByteArrayOutputStream out = new ByteArrayOutputStream(100); final Serializer serializer = new Serializer(out); try { serializer.serialize(value); } catch (final Exception e) { return interpreter.primitiveFailure(E_SERIALIZATION_FAILED); } return interpreter.primitiveSuccess(ByteArrayTupleDescriptor.forByteArray(out.toByteArray())); }
private void parseAndLoadInputs(String inputs) throws Exception { String inputTokens[] = inputs.split("\\s+"); for (int i = 0; i < inputTokens.length; i++) { String token = inputTokens[i]; if (token.equals("")) { continue; } else if (token.equals("true")) { _interpreter.boolStack().push(true); _interpreter.inputStack().push(true); } else if (token.equals("false")) { _interpreter.boolStack().push(false); _interpreter.inputStack().push(false); } else if (token.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")) { if (token.indexOf('.') != -1) { _interpreter.floatStack().push(Float.parseFloat(token)); _interpreter.inputStack().push(Float.parseFloat(token)); } else { _interpreter.intStack().push(Integer.parseInt(token)); _interpreter.inputStack().push(Integer.parseInt(token)); } } else { throw new Exception( "Inputs must be of type int, float, or boolean. \"" + token + "\" is none of these."); } } }
/** * ************************************************************** Mary, my sister, arrived. * appos(?X,?Y) ==> (equals(?X,?Y)). */ @Test public void testAppos() { String input = "sumo(Woman,Mary-1), number(SINGULAR,London-1), tense(PRESENT,smells-2), number(SINGULAR,Sam-1), number(SINGULAR,brother-3), tense(PAST,arrived-4), number(SINGULAR,Mary-1), appos(Mary-1,sister-4), poss(sister-4,my-2), sumo(sister,sister-4), number(SINGULAR,sister-4), root(ROOT-0,arrive-6), nsubj(arrive-6,Mary-1), sumo(Arriving,arrive-6), tense(PAST,arrive-6)"; ArrayList<CNF> cnfInput = interpreter.getCNFInput(input); String[] expected = {"(equals Mary-1 sister-4)"}; ArrayList<String> kifClauses = interpreter.interpretCNF(cnfInput); Set<String> actual = Sets.newHashSet(kifClauses); Set<String> cleanedActual = actual.stream().map(str -> str.replaceAll("\\s+", " ")).collect(Collectors.toSet()); assertThat(cleanedActual, hasItems(expected)); }
/** * 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
@Override public Result attempt( final List<AvailObject> args, final Interpreter interpreter, final boolean skipReturnCheck) { assert args.size() == 1; final AvailObject map = args.get(0); return interpreter.primitiveSuccess(ObjectTypeDescriptor.objectTypeFromMap(map)); }
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; }
@Override Value execute(Interpreter machine) { String a = _myOperands.get(0).getString(); Value b = _myOperands.get(1).execute(machine); Interpreter.getTable().put(a, b); return null; }
/** * ************************************************************** The meat smells sweet. * acomp(?V,?A), sumo(?AC,?A), nsubj(?V,?O), sumo(?C,?O), isSubclass(?C,Object) ==> * (attribute(?O,?AC)). */ @Test public void testAcomp2() { String input = "det(meat-2,the-1), det(meat-2,The-1), sumo(Meat,meat-2), number(SINGULAR,meat-2), root(ROOT-0,smell-3), nsubj(smell-3,meat-2), acomp(smell-3,sweet-4), sumo(Smelling,smell-3), tense(PRESENT,smell-3), acomp(smells-3,sweet-4), sumo(Sweetness,sweet-4)"; ArrayList<CNF> cnfInput = interpreter.getCNFInput(input); String[] expected = {"(attribute meat-2 Sweetness)"}; ArrayList<String> kifClauses = interpreter.interpretCNF(cnfInput); Set<String> actual = Sets.newHashSet(kifClauses); Set<String> cleanedActual = actual.stream().map(str -> str.replaceAll("\\s+", " ")).collect(Collectors.toSet()); assertThat(cleanedActual, hasItems(expected)); }
@Override public Result attempt( final List<AvailObject> args, final Interpreter interpreter, final boolean skipReturnCheck) { assert args.size() == 1; final A_Token token = args.get(0); return interpreter.primitiveSuccess(LiteralNodeDescriptor.fromToken(token)); }
@Test public void shouldInterpretOperation() throws Exception { assertThat( interpreter.interpret( new OperationSyntaxNode(new IntegerSyntaxNode(1), new IntegerSyntaxNode(2), "+")), is(3)); }
/** * ************************************************************** Yesterday, Mary ran. tmod(?V,?T) * ==> (during(?V,?T)). */ @Test public void testTmod() { String input = "names(Mary-3,\"Mary\"), attribute(Mary-3,Female), sumo(Human,Mary-3), number(SINGULAR,Mary-3), tmod(ran-4,yesterday-1), sumo(Day,yesterday-1), number(SINGULAR,yesterday-1), root(ROOT-0,run-4), tmod(run-4,Yesterday-1), nsubj(run-4,Mary-3), sumo(Running,run-4), tense(PAST,run-4)"; ArrayList<CNF> cnfInput = interpreter.getCNFInput(input); String[] expected = {"(during run-4 Yesterday-1)"}; ArrayList<String> kifClauses = interpreter.interpretCNF(cnfInput); Set<String> actual = Sets.newHashSet(kifClauses); Set<String> cleanedActual = actual.stream().map(str -> str.replaceAll("\\s+", " ")).collect(Collectors.toSet()); assertThat(cleanedActual, hasItems(expected)); }
/** * ************************************************************** John has a red car. amod(?X,?Y), * sumo(?C,?Y) ==> (attribute(?X,?C)). */ @Test public void testAMod() { String input = "root(ROOT-0,have-2), nsubj(have-2,John-1), det(car-5,a-3), amod(car-5,red-4), dobj(have-2,car-5), names(John-1,\"John\"), sumo(Automobile,car-5), attribute(John-1,Male), sumo(Human,John-1), sumo(Red,red-4), number(SINGULAR,John-1), tense(PRESENT,have-2), number(SINGULAR,car-5)"; ArrayList<CNF> cnfInput = interpreter.getCNFInput(input); String[] expected = {"(attribute car-5 Red)"}; ArrayList<String> kifClauses = interpreter.interpretCNF(cnfInput); Set<String> actual = Sets.newHashSet(kifClauses); Set<String> cleanedActual = actual.stream().map(str -> str.replaceAll("\\s+", " ")).collect(Collectors.toSet()); assertThat(cleanedActual, hasItems(expected)); }
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; } }
protected void LOAD_ADDRESS(String arg) { int addr = in.getLineNumber(arg); push(addr); if (addr < 0) { ERROR("Invalid Address: " + arg); } }