public Expr dropNoncompArgs(Context ctxt) { if (ctxt.getFlag("debug_drop_noncomp")) { ctxt.w.println("Dropping non-comp arguments from term-app " + toString(ctxt)); ctxt.w.flush(); } ArrayList nX = new ArrayList(); ArrayList no = new ArrayList(); boolean changed = false; Boolean b = new Boolean(false); for (int i = 0, iend = X.length; i < iend; i++) { if (X[i].isProof(ctxt) || specarg[i]) changed = true; else { nX.add(X[i]); no.add(b); } } Expr ret = this; if (changed) { if (nX.size() == 0) ret = head; else ret = new TermApp(head, Parser.toExprArray(nX), Parser.toBooleanArray(no)); } if (ctxt.getFlag("debug_drop_noncomp")) { ctxt.w.println("Returning " + ret.toString(ctxt)); ctxt.w.flush(); } return ret; }
public void parseStyleDeclaration(CSSStyleDeclaration sd, InputSource source) throws IOException { Stack nodeStack = new Stack(); nodeStack.push(sd); CSSOMHandler handler = new CSSOMHandler(nodeStack); _parser.setDocumentHandler(handler); _parser.parseStyleDeclaration(source); }
public static void main(String[] args) { Parser parser = new Parser(); Label labels = new Label(); String asmbly; int pc = 100; try { BufferedReader br = new BufferedReader(new FileReader(args[0])); String line; while ((line = br.readLine()) != null) { if (line.contains(":")) labels.fillLabels(line, pc); pc++; } } catch (Exception e) { System.out.println("Failed first"); } try { BufferedReader br = new BufferedReader(new FileReader(args[0])); PrintWriter writer = new PrintWriter("output", "UTF-8"); String line; while ((line = br.readLine()) != null) { asmbly = parser.parseLine(line, labels); writer.println(asmbly); } writer.close(); } catch (Exception e) { System.out.println("Failed second"); } }
public void WriteHeader(){ out.println("\t\t"+Parser.StartingTag("ValidichroHeader")); out.println("\t\t\t"+Parser.Tag("Date",experiment_date)); out.println("\t\t\t"+Parser.Tag("Generic",generic)); //... out.println("\t\t"+Parser.EndingTag("ValidichroHeader")); }
public void WriteExported(){ out.println(Parser.getFileHeader()); out.println("\t"+Parser.StartingTag("ValidichroData")); WriteHeader(); WriteBody(); WriteUnparsed(); out.println("\t"+Parser.EndingTag("ValidichroData")); }
public static AST_Imports MakeAST(String in) { try { Parser parser = Parser.getInstance(new StringReader(in)); return (AST_Imports) parser.parse("AST_Imports"); } catch (ParseException pe) { AstNode.fatalError("string-to-ast parse error: " + in); return null; } }
public void WriteBody(){ //@ToDo : Make this proper java! //@ToDo Important: Add missing elements and check existing ones // - Update:, now refers to values as Unknown1,Uknown2... It's just unknown to me, can't remember what these values represent! out.println("\t\t"+Parser.StartingTag("ValidichroBody")); for(String line :spectral_table){ out.println("\t\t\t"+Parser.Tag("SpectralEntry",line)); } out.println("\t\t"+Parser.EndingTag("ValidichroBody")); }
public static String parse(File f, BlobStore blobStore, HashStore hashStore) throws FileNotFoundException, IOException { Parser parser = new Parser(); FileInputStream fin = null; BufferedInputStream bufIn = null; try { fin = new FileInputStream(f); bufIn = new BufferedInputStream(fin); return parser.parse(bufIn, hashStore, blobStore); } finally { IOUtils.closeQuietly(bufIn); IOUtils.closeQuietly(fin); } }
/** * Takes in a file name and outputs a Piece represending the song. * * @param abcFileName */ public Piece buildSong(String abcFileName) { // Open up the File String fileContent = getFile(abcFileName); // Create Lexer, pass string into lexer Lexer lexer = new Lexer(fileContent); // Pass lexer into Parser to get Piece Parser parser = new Parser(lexer); Piece toReturn = parser.parse(); return toReturn; }
/** * Parses an expression. Returns a object of type Node, does not catch errors. Does not set the * topNode variable of the JEP instance. This method should generally be used with the {@link * #evaluate evaluate} method rather than getValueAsObject. * * @param expression represented as a string. * @return The top node of a tree representing the parsed expression. * @throws ParseException * @since 2.3.0 alpha * @since 2.3.0 beta - will raise exception if errorList non empty */ public Node parse(String expression) throws ParseException { java.io.StringReader sr = new java.io.StringReader(expression); errorList.removeAllElements(); Node node = parser.parseStream(sr, this); if (this.hasError()) throw new ParseException(getErrorInfo()); return node; }
public static void work(BufferedReader ir) { TestParser testParser = new TestParser(); try { PushbackReader r = new PushbackReader(ir, 1024); Parser parser = new Parser(new Lexer(r)); Node syntaxTree = parser.parse(); syntaxTree.apply(testParser); } catch (LexerException e) { System.out.println(e.getMessage() + "."); } catch (ParserException e) { System.out.println(e.getMessage() + "."); } catch (IOException e) { System.out.println(e.getMessage() + "."); System.exit(1); } }
public void evaluate() { try { // clear problems and console messages problemsView.setText(""); consoleView.setText(""); // update status view statusView.setText(" Parsing ..."); tabbedPane.setSelectedIndex(0); LispExpr root = Parser.parse(textView.getText()); statusView.setText(" Running ..."); tabbedPane.setSelectedIndex(1); // update run button runButton.setIcon(stopImage); runButton.setActionCommand("Stop"); // start run thread runThread = new RunThread(root); runThread.start(); } catch (SyntaxError e) { tabbedPane.setSelectedIndex(0); System.err.println( "Syntax Error at " + e.getLine() + ", " + e.getColumn() + " : " + e.getMessage()); } catch (Error e) { // parsing error System.err.println(e.getMessage()); statusView.setText(" Errors."); } }
public void ParseSpectralEntry(String line){ //@ToDo, take all values (there are 7) // Update - now takes all values, but calls them Unknown1,2,3,4 I need to find out what these values represent! //Not production safe! String table_ent=Parser.getTableRow(line,new String[]{"WaveLength","Smooth","Unsmooth","Unknown1","Unknown2","Uknown3","Unknown4"}); spectral_table.add(table_ent); }
/*.................................................................................................................*/ public Object doCommand(String commandName, String arguments, CommandChecker checker) { if (checker.compare( this.getClass(), "Sets the username", "[username]", commandName, "setUsername")) { username = parser.getFirstToken(arguments); } return null; }
/** * Static service to get a term from its string representation, providing a specific operator * manager */ public static Term parseSingleTerm(String st, OperatorManager op) throws InvalidTermException { try { Parser p = new Parser(op, st); Token t = p.tokenizer.readToken(); if (t.isEOF()) throw new InvalidTermException("Term starts with EOF"); p.tokenizer.unreadToken(t); Term term = p.expr(false); if (term == null) throw new InvalidTermException("Term is null"); if (!p.tokenizer.readToken().isEOF()) throw new InvalidTermException("The entire string could not be read as one term"); term.resolveTerm(); return term; } catch (IOException ex) { throw new InvalidTermException("An I/O error occured"); } }
public static HashMap<String, Test> processScriptFile(File file) { HashMap<String, Test> tests = new HashMap<String, Test>(); try { Parser parser = new Parser(new Lexer(new PushbackReader(new FileReader(file)))); Start root = parser.parse(); AScript a1 = (AScript) root.getPScript(); for (PScriptTail tail : a1.getScriptTail()) { AScriptTail a2 = (AScriptTail) tail; Test test = TestBuilder.buildTest(a2.getTest()); tests.put(test.getName(), test); } System.out.println("SUCESSFULLY PARSED!"); } catch (Exception e) { System.err.println(e.getMessage()); } return tests; }
/** * Parses and returns a valid 'leftside' of an expression. If the left side starts with a prefix, * it consumes other expressions with a lower priority than itself. If the left side does not have * a prefix it must be an expr0. * * @param commaIsEndMarker used when the leftside is part of and argument list of expressions * @param maxPriority operators with a higher priority than this will effectivly end the * expression * @return a wrapper of: 1. term correctly structured and 2. the priority of its root operator * @throws InvalidTermException */ private IdentifiedTerm parseLeftSide(boolean commaIsEndMarker, int maxPriority) throws InvalidTermException, IOException { // 1. prefix expression Token f = tokenizer.readToken(); if (f.isOperator(commaIsEndMarker)) { int FX = opManager.opPrio(f.seq, "fx"); int FY = opManager.opPrio(f.seq, "fy"); if (f.seq.equals("-")) { Token t = tokenizer.readToken(); if (t.isNumber()) /*Michele Castagna 06/2011*/ // return new IdentifiedTerm(0, Parser.createNumber("-" + t.seq)); return identifyTerm(0, Parser.createNumber("-" + t.seq), tokenStart); /**/ else tokenizer.unreadToken(t); } // check that no operator has a priority higher than permitted if (FY > maxPriority) FY = -1; if (FX > maxPriority) FX = -1; // FX has priority over FY boolean haveAttemptedFX = false; if (FX >= FY && FX >= OperatorManager.OP_LOW) { IdentifiedTerm found = exprA(FX - 1, commaIsEndMarker); // op(fx, n) exprA(n - 1) if (found != null) /*Castagna 06/2011*/ // return new IdentifiedTerm(FX, new Struct(f.seq, found.result)); return identifyTerm(FX, new Struct(f.seq, found.result), tokenStart); /**/ else haveAttemptedFX = true; } // FY has priority over FX, or FX has failed if (FY >= OperatorManager.OP_LOW) { IdentifiedTerm found = exprA(FY, commaIsEndMarker); // op(fy,n) exprA(1200) or op(fy,n) exprA(n) if (found != null) /*Castagna 06/2011*/ // return new IdentifiedTerm(FY, new Struct(f.seq, found.result)); return identifyTerm(FY, new Struct(f.seq, found.result), tokenStart); /**/ } // FY has priority over FX, but FY failed if (!haveAttemptedFX && FX >= OperatorManager.OP_LOW) { IdentifiedTerm found = exprA(FX - 1, commaIsEndMarker); // op(fx, n) exprA(n - 1) if (found != null) /*Castagna 06/2011*/ // return new IdentifiedTerm(FX, new Struct(f.seq, found.result)); return identifyTerm(FX, new Struct(f.seq, found.result), tokenStart); /**/ } } tokenizer.unreadToken(f); // 2. expr0 return new IdentifiedTerm(0, expr0()); }
public void reset() { this.lookupEnvironment.reset(); // GROOVY start: give the parser a chance to reset as well parser.reset(); // GROOVY end this.parser.scanner.source = null; this.unitsToProcess = null; if (DebugRequestor != null) DebugRequestor.reset(); this.problemReporter.reset(); }
/*.................................................................................................................*/ public Object doCommand(String commandName, String arguments, CommandChecker checker) { if (checker.compare( this.getClass(), "Sets the running file path", "[file path]", commandName, "setRunningFilePath")) { runningFilePath = parser.getFirstToken(arguments); } else if (checker.compare( this.getClass(), "Sets the output file paths", "[file paths]", commandName, "setOutputFilePaths")) { int num = parser.getNumberOfTokens(arguments); outputFilePaths = new String[num]; if (num > 0) outputFilePaths[0] = parser.getFirstToken(); for (int i = 1; i < num; i++) outputFilePaths[i] = parser.getNextToken(); } return null; }
public static void parse(File sourceFile) throws Exception { if (ByteCodeTranslator.verbose) { System.out.println("Parsing: " + sourceFile.getAbsolutePath()); } ClassReader r = new ClassReader(new FileInputStream(sourceFile)); /*if(ByteCodeTranslator.verbose) { System.out.println("Class: " + r.getClassName() + " derives from: " + r.getSuperName() + " interfaces: " + Arrays.asList(r.getInterfaces())); }*/ Parser p = new Parser(); p.clsName = r.getClassName().replace('/', '_').replace('$', '_'); if (p.clsName.startsWith("java_lang_annotation") || p.clsName.startsWith("java_lang_Deprecated") || p.clsName.startsWith("java_lang_Override") || p.clsName.startsWith("java_lang_SuppressWarnings")) { return; } p.cls = new ByteCodeClass(p.clsName); r.accept(p, ClassReader.EXPAND_FRAMES); classes.add(p.cls); }
private void parseMapsXml() { try { String fileName = LocationLoader.getLocationDir(NavigineApp.AppContext, null) + "/maps.xml"; List<LocationInfo> infoList = Parser.parseMapsXml(NavigineApp.AppContext, fileName); mInfoList = new ArrayList<LocationInfo>(); if (infoList != null) mInfoList = infoList; mAdapter.updateList(); new File(fileName).delete(); } catch (Throwable e) { Log.e(TAG, Log.getStackTraceString(e)); } }
public JavaProgram createJavaProgram( List sourceFiles, String libraryPath, String mainClassname, String projectType, String policyType) throws Exception { // Debug.setOn(true); long l = Debug.getTime(); LibraryData libraryData = new LibraryData(new File(libraryPath), projectType, language, false); Library library = new Library(libraryData); Parser parser = Parser.createParser(this.language, sourceFiles, library, new TranslationPolicy(policyType)); long lll = Debug.getTime(); System.out.println("Library Loaded in " + (lll - l) + "ms"); ParseTree tree = parser.parse(); TranslationReport report = tree.getTranslationReport(); long ll = Debug.getTime(); System.out.println("Code parsed in " + (ll - lll) + "ms"); Debug.setOn(true); Translator tt = new Translator(this.language); JavaProgram jp = tt.createJavaProgram(tree, mainClassname, projectType); if (report.hasTypeResolveErrors() || report.hasTranslationWarnings()) { List errors = new ArrayList(); errors.addAll(report.getTypeResolveExceptions()); report.doReport(errors, report.getTranslationWarnings()); } l = Debug.getTime(); System.out.println("Translated in " + (l - ll) + "ms"); jp.setTypeResolved(!report.hasTypeResolveErrors()); // resolved if no errors return jp; }
public static void main(String args[]) { try { System.out.println("Type in a tiny exp folowed by one or two Ctrl-d's:"); Parser p = new Parser(new Lexer(new PushbackReader(new InputStreamReader(System.in), 1024))); Start tree = p.parse(); NewEval.replaceUminus(tree); /* pretty-print */ System.out.println("\nThe result of evaluating:"); PrettyPrinter.print(tree); /* pre-eval to replace uminus */ /* evaluate */ System.out.print("\nis: "); PrettyPrinter.print(Evaluator.eval(tree)); System.out.println("\n"); } catch (Exception e) { System.out.println(e); } }
public static void main(String[] args) throws IOException { String filename = "z.xml"; // NOT LOCALIZABLE, main try { String uri = "file:" + new File(filename).getAbsolutePath(); // NOT LOCALIZABLE, main // // turn it into an in-memory object. // Parser parser = getParser(); parser.setDocumentHandler(new XmlParser()); parser.setErrorHandler(new MyErrorHandler()); parser.parse(uri); } catch (SAXParseException err) { Debug.trace( "** Parsing error" // NOT LOCALIZABLE, main + ", line " + err.getLineNumber() // NOT LOCALIZABLE + ", uri " + err.getSystemId()); // NOT LOCALIZABLE Debug.trace(" " + err.getMessage()); } catch (SAXException e) { Exception x = e; if (e.getException() != null) x = e.getException(); x.printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } byte[] buf = new byte[256]; Debug.trace("Press ENTER to exit."); // NOT LOCALIZABLE System.in.read(buf, 0, 256); System.exit(0); }
public void prettyPrint() { try { // clear old problem messages problemsView.setText(""); // update status view statusView.setText(" Parsing ..."); LispExpr root = Parser.parse(textView.getText()); statusView.setText(" Pretty Printing ..."); String newText = PrettyPrinter.prettyPrint(root); textView.setText(newText); statusView.setText(" Done."); } catch (Error e) { System.err.println(e.getMessage()); statusView.setText(" Errors."); } }
public static void test1() { Sequence[] seqs = Parser.test1(); double[][] distances = (new GappedHammingDistance()).getDistanceMatrix(seqs); DecimalFormat f = new DecimalFormat("0000.000"); System.out.println(" " + seqs.length); for (int i = 0; i < seqs.length; i++) { System.out.print(seqs[i].name); for (int k = 0; k < 10 - seqs[i].name.length(); k++) { System.out.print(" "); } System.out.print(" "); int cols = 1; for (int j = 0; j < seqs.length; j++) { if (i != j) { int di = i; int dj = j; // force symmetric matrix - arg - what the??? // testing!!! if (j > i) { di = j; dj = i; } double d = distances[di][dj]; // testing if (d > 2000) { System.err.println("ARGH"); } System.out.print(f.format(d)); } else { System.out.print(f.format(0)); } System.out.print(" "); cols++; if (cols >= 7) { System.out.println(); System.out.print(" "); cols = 0; } } if (cols != 7) { System.out.println(); } } }
/** * Parses the expression. If there are errors in the expression, they are added to the <code> * errorList</code> member. Errors can be obtained through <code>getErrorInfo()</code>. * * @param expression_in The input expression string * @return the top node of the expression tree if the parse was successful, <code>null</code> * otherwise */ public Node parseExpression(String expression_in) { Reader reader = new StringReader(expression_in); try { // try parsing errorList.removeAllElements(); topNode = parser.parseStream(reader, this); // if there is an error in the list, the parse failed // so set topNode to null if (hasError()) topNode = null; } catch (Throwable e) { // an exception was thrown, so there is no parse tree topNode = null; // check the type of error if (e instanceof ParseException) { // the ParseException object contains additional error // information errorList.addElement(((ParseException) e).getMessage()); // getErrorInfo()); } else { // if the exception was not a ParseException, it was most // likely a syntax error if (debug) { System.out.println(e.getMessage()); e.printStackTrace(); } errorList.addElement("Syntax error"); } } // If traversing is enabled, print a dump of the tree to // standard output if (traverse && !hasError()) { ParserVisitor v = new ParserDumpVisitor(); try { topNode.jjtAccept(v, null); } catch (ParseException e) { errorList.addElement(e.getMessage()); } } return topNode; }
@SuppressWarnings("deprecation") public static void main(String[] args) throws java.lang.Exception { try { String zipCode = ReadInput(); WeatherProxy proxy = new WeatherProxy(); String weatherData = proxy.getWeatherForZip(zipCode); String cityStateTemp = Parser.GetCityStateTemperature(weatherData); System.out.println(cityStateTemp); } catch (NumberFormatException e) { System.out.println("invalid zip code format"); } catch (Exception e) { System.out.println(e); } }
private void test(Parser p, DataSet d) { int dsize = d.size(); testSize = dsize; for (int i = 0; i < dsize; i++) { String words = d.sent(i); Exp sem = d.sem(i); if (verbose) { System.out.println( i + ": ==================(" + correctParses + " -- " + wrongParses + ")"); System.out.println(words); System.out.println(sem); } String mes = null; if (verbose) mes = "Test"; p.parseTimed(words, null, mes); isCorrect(words, sem, p); } }
// bindKeyToCommand binds a given key sequence to a Lisp command // so that pressing the key sequence executes the command. public void bindKeyToCommand(String keySequence, String cmd) { bindKeyToCommand(keySequence, Parser.parse(cmd)); }