@Override public ArrayList<JavaSegment> parse(String classFile) throws Exception { CompilationUnit unit = JavaParser.parse(new ByteArrayInputStream(classFile.getBytes())); ArrayList<JavaMethod> methods = new ArrayList<JavaMethod>(); getJavaMethods(methods, getOuterClass(unit)); ArrayList<JniSection> methodBodies = getNativeCodeBodies(classFile); ArrayList<JniSection> sections = getJniSections(classFile); alignMethodBodies(methods, methodBodies); ArrayList<JavaSegment> segments = sortMethodsAndSections(methods, sections); return segments; }
// This parses the action as a list of statements and replaces variables by equivalent getters // called on a "machine" variable private static List<Statement> actionAsStatements(String action) { if (action.isEmpty()) { return Collections.emptyList(); } try { final BlockStmt block = JavaParser.parseBlock('{' + action + '}'); // Replace fields by getters block.accept(VariableToGetter.INSTANCE, null); return block.getStmts(); } catch (ParseException exception) { throw new RuntimeException(exception); } }
// This parses the condition to an expression and replaces variables by equivalent getters called // on a "machine" variable // Returns null if the condition is an empty string private static Expression conditionAsExpression(String condition) { if (condition.isEmpty()) { return null; } try { final Expression expression = JavaParser.parseExpression(condition); // Replace fields by getters expression.accept(VariableToGetter.INSTANCE, null); return expression; } catch (ParseException exception) { throw new RuntimeException(exception); } }
public static void processFileList( String fileListFile, String appSourceDir, CompUnitProcessable cup) throws Exception { BufferedReader br = new BufferedReader(new FileReader(fileListFile)); String line; while ((line = br.readLine()) != null) { String fileName = line.substring(2); File file = new File(appSourceDir, fileName); if (!file.exists()) { throw new RuntimeException("CANT FIND FILE: " + appSourceDir + fileName); } // creates an input stream for the file to be parse FileInputStream in = new FileInputStream(file); CompilationUnit cu = JavaParser.parse(in); if (cu != null) { cup.process(fileName, cu); } in.close(); } br.close(); }
@Nullable private static String extractClassName(String code, PrintStream err) { InputStream inputStream = new ByteArrayInputStream(code.getBytes(StandardCharsets.UTF_8)); try { CompilationUnit compilationUnit = JavaParser.parse(inputStream); List<TypeDeclaration> types = compilationUnit.getTypes(); if (types.size() == 1) { String simpleType = types.get(0).getName(); return Optional.ofNullable(compilationUnit.getPackage()) .map(PackageDeclaration::getPackageName) .map(it -> it + "." + simpleType) .orElse(simpleType); } else if (types.size() == 0) { err.println("No class definition found"); } else { err.println("Too many class definitions found. Only one class can be defined at a time."); } } catch (ParseException e) { // ignore error, let the compiler provide an error message return "Err"; } return null; }
private static void openAnnotatedJava() { // Create list with source code names @SuppressWarnings("unchecked") Vector<String> myfilelist = new Vector<String>(cmd.getArgList()); // Table that stores parsed compilation units Hashtable<String, CompilationUnit> myjpunitlist = new Hashtable<String, CompilationUnit>(); // Declare outside, so filename can be used in case of exception. // Generate AST with JavaParser for (Enumeration<String> e = myfilelist.elements(); e.hasMoreElements(); ) { String mysource = ""; CompilationUnit mycunit = null; try { // read filename mysource = e.nextElement(); // Compile it with java parser. mycunit = JavaParser.parse(new FileInputStream(mysource)); // Then fix the AST following the JC requirements ComplyToJCVisitor myfixervisitor = new ComplyToJCVisitor(); mycunit = (CompilationUnit) myfixervisitor.visit(mycunit, new Integer(0)); // creates an input stream and parse it using Java Parser myjpunitlist.put(mysource, mycunit); if (cmd.hasOption("d")) { // ASTDumpVisitor myjpvisitor = new ASTDumpVisitor(); DumpVisitor myjpvisitor = new DumpVisitor(); myjpvisitor.visit(myjpunitlist.get(mysource), null); System.out.print(myjpvisitor.getSource()); } } catch (com.github.javaparser.ParseException ex) { System.out.println("Error: Parsing of Java file failed: " + mysource + ". Exiting..."); System.exit(1); } catch (FileNotFoundException ex) { System.out.println("Error: File not found: " + mysource + ". Exiting..."); System.exit(1); } } // Building internals from Java Compiler Context mycontext = new Context(); JavaCompiler myjcompiler = new JavaCompiler(mycontext); JavaFileManager myfilemanager = mycontext.get(JavaFileManager.class); // Phase that Javac may go to: Setting code generation myjcompiler.shouldStopPolicyIfNoError = CompileState.GENERATE; // Table that stores the Java Compiler's ASTs List<JCCompilationUnit> ljctreelist = List.<JCCompilationUnit>nil(); // Convert to Java Parser AST to JCTree AST's for (Enumeration<String> e = myjpunitlist.keys(); e.hasMoreElements(); ) { // read filename String mysource = e.nextElement(); CompilationUnit myjpunit = myjpunitlist.get(mysource); JavaParser2JCTree translator = new JavaParser2JCTree(mycontext); AJCCompilationUnit myjctreeunit = (AJCCompilationUnit) translator.visit(myjpunit, myjpunit); // Setting additional information for Javac: // - Source file. Otherwise it throws a NullPointerException myjctreeunit.sourcefile = ((JavacFileManager) myfilemanager).getFileForInput(mysource); // Storing in the list ljctreelist = ljctreelist.append(myjctreeunit); // Debug: Shows how the JCTree AST was generated. Output node types. if (cmd.hasOption("d")) { try { Writer mystdout = new OutputStreamWriter(System.out); (new PrintAstVisitor(mystdout, true)).visitTopLevel(myjctreeunit); mystdout.flush(); } catch (Exception z) { } } } // Enter (phase I): starting to build symtable Enter myenter = Enter.instance(mycontext); myenter.main(ljctreelist); // Enter (phase II): Finishing to build symtable /* MemberEnter mymemberenter = MemberEnter.instance(mycontext); mymemberenter.visitTopLevel(myjctreeunit); */ // Get the todo list generated by Enter phase // From now on, the output of a phase is the input of the other. Todo mytodo = Todo.instance(mycontext); // atrribute: type-checking, name resolution, constant folding // flow: deadcode elimination // desugar: removes synctactic sugar: inner classes, class literals, assertions, foreachs myjcompiler.desugar(myjcompiler.flow(myjcompiler.attribute(mytodo))); // generate: produce bytecode or source code. Erases the whole AST // myjcompiler.generate(myjcompiler.desugar(myjcompiler.flow(myjcompiler.attribute( mytodo)))); // Prints the Java program to output files and leave for (ListIterator<JCCompilationUnit> i = ljctreelist.listIterator(); i.hasNext(); ) { JCCompilationUnit myjctreeunit = i.next(); try { Writer myoutputfile; if (cmd.getOptionValue("o") == null) { myoutputfile = new FileWriter(FileDescriptor.out); } else { myoutputfile = new FileWriter(myjctreeunit.sourcefile + ".new"); } (new APretty(myoutputfile, true)).visitTopLevel(myjctreeunit); myoutputfile.flush(); } catch (Exception e) { // TODO - Check what to report in case of error. } } }