Skip to content

Commit

Permalink
Prefer ParseResult<CompilationUnit> over just CompilationUnit
Browse files Browse the repository at this point in the history
  • Loading branch information
Danny van Bruggen committed Feb 8, 2017
1 parent 855ca2a commit b6b07ac
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 35 deletions.
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ protected NodeGenerator(JavaParser javaParser, SourceRoot sourceRoot) {
public final void generate() throws Exception { public final void generate() throws Exception {
log.info(f("Running %s", getClass().getSimpleName())); log.info(f("Running %s", getClass().getSimpleName()));
for (BaseNodeMetaModel nodeMetaModel : JavaParserMetaModel.getNodeMetaModels()) { for (BaseNodeMetaModel nodeMetaModel : JavaParserMetaModel.getNodeMetaModels()) {
CompilationUnit nodeCu = sourceRoot.parse(nodeMetaModel.getPackageName(), nodeMetaModel.getTypeName() + ".java", javaParser).orElseThrow(() -> new IOException(f("java file for %s not found", nodeMetaModel.getTypeName()))); CompilationUnit nodeCu = sourceRoot.parse(nodeMetaModel.getPackageName(), nodeMetaModel.getTypeName() + ".java", javaParser);
ClassOrInterfaceDeclaration nodeCoid = nodeCu.getClassByName(nodeMetaModel.getTypeName()).orElseThrow(() -> new IOException("Can't find class")); ClassOrInterfaceDeclaration nodeCoid = nodeCu.getClassByName(nodeMetaModel.getTypeName()).orElseThrow(() -> new IOException("Can't find class"));
generateNode(nodeMetaModel, nodeCu, nodeCoid); generateNode(nodeMetaModel, nodeCu, nodeCoid);
} }
Expand Down
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ protected VisitorGenerator(JavaParser javaParser, SourceRoot sourceRoot, String
public final void generate() throws Exception { public final void generate() throws Exception {
log.info(f("Running %s", getClass().getSimpleName())); log.info(f("Running %s", getClass().getSimpleName()));


final CompilationUnit compilationUnit = sourceRoot.parse(pkg, visitorClassName + ".java", javaParser).get(); final CompilationUnit compilationUnit = sourceRoot.tryToParse(pkg, visitorClassName + ".java", javaParser).getResult().get();


Optional<ClassOrInterfaceDeclaration> visitorClassOptional = compilationUnit.getClassByName(visitorClassName); Optional<ClassOrInterfaceDeclaration> visitorClassOptional = compilationUnit.getClassByName(visitorClassName);
if (!visitorClassOptional.isPresent()) { if (!visitorClassOptional.isPresent()) {
Expand Down
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ private void generateGetter(BaseNodeMetaModel nodeMetaModel, ClassOrInterfaceDec


@Override @Override
protected void after() throws Exception { protected void after() throws Exception {
CompilationUnit observablePropertyCu = sourceRoot.parse("com.github.javaparser.ast.observer", "ObservableProperty.java", javaParser).get(); CompilationUnit observablePropertyCu = sourceRoot.tryToParse("com.github.javaparser.ast.observer", "ObservableProperty.java", javaParser).getResult().get();
EnumDeclaration observablePropertyEnum = observablePropertyCu.getEnumByName("ObservableProperty").get(); EnumDeclaration observablePropertyEnum = observablePropertyCu.getEnumByName("ObservableProperty").get();
observablePropertyEnum.getEntries().clear(); observablePropertyEnum.getEntries().clear();
for (String prop : observablePropertyNames) { for (String prop : observablePropertyNames) {
Expand Down
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ public class ParseProblemException extends RuntimeException {
*/ */
private final List<Problem> problems; private final List<Problem> problems;


ParseProblemException(List<Problem> problems) { public ParseProblemException(List<Problem> problems) {
super(createMessage(assertNotNull(problems))); super(createMessage(assertNotNull(problems)));
this.problems = problems; this.problems = problems;
} }


ParseProblemException(Throwable throwable) { public ParseProblemException(Throwable throwable) {
this(singletonList(new Problem(throwable.getMessage(), null, throwable))); this(singletonList(new Problem(throwable.getMessage(), null, throwable)));
} }


Expand Down
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public class ParseResult<T> {
* @param problems a list of encountered parsing problems. * @param problems a list of encountered parsing problems.
* @param tokens the complete list of tokens that were parsed, or empty if parsing failed completely. * @param tokens the complete list of tokens that were parsed, or empty if parsing failed completely.
*/ */
ParseResult(T result, List<Problem> problems, List<JavaToken> tokens, CommentsCollection commentsCollection) { public ParseResult(T result, List<Problem> problems, List<JavaToken> tokens, CommentsCollection commentsCollection) {
this.commentsCollection = commentsCollection; this.commentsCollection = commentsCollection;
this.result = result; this.result = result;
this.problems = problems; this.problems = problems;
Expand Down
Original file line number Original file line Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.github.javaparser.generator.utils; package com.github.javaparser.generator.utils;


import com.github.javaparser.JavaParser; import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseProblemException;
import com.github.javaparser.ParseResult; import com.github.javaparser.ParseResult;
import com.github.javaparser.Problem; import com.github.javaparser.Problem;
import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.CompilationUnit;
Expand All @@ -18,6 +19,7 @@
import java.nio.file.SimpleFileVisitor; import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;


import static com.github.javaparser.ParseStart.COMPILATION_UNIT; import static com.github.javaparser.ParseStart.COMPILATION_UNIT;
import static com.github.javaparser.Providers.UTF8; import static com.github.javaparser.Providers.UTF8;
Expand All @@ -31,26 +33,24 @@
public class SourceRoot { public class SourceRoot {
private final Logger log = LoggerFactory.getLogger(SourceRoot.class); private final Logger log = LoggerFactory.getLogger(SourceRoot.class);
private final Path root; private final Path root;
private final Map<Path, CompilationUnit> content = new HashMap<>(); private final Map<Path, ParseResult<CompilationUnit>> content = new HashMap<>();
private final List<Problem> problems = new ArrayList<>();


public SourceRoot(Path root) { public SourceRoot(Path root) {
this.root = root.normalize(); this.root = root.normalize();
log.info(f("New source root at \"%s\"", this.root)); log.info(f("New source root at \"%s\"", this.root));
} }


/** /**
* Parses a package recursively. * Parses all .java files in a package recursively.
*/ */
public Map<Path, CompilationUnit> parse(String startPackage, JavaParser parser) throws IOException { public Map<Path, ParseResult<CompilationUnit>> tryToParse(String startPackage, JavaParser parser) throws IOException {
log.info(f("Parsing package \"%s\"", startPackage)); log.info(f("Parsing package \"%s\"", startPackage));
final Path path = packageAbsolutePath(root, startPackage); final Path path = packageAbsolutePath(root, startPackage);
content.clear();
Files.walkFileTree(path, new SimpleFileVisitor<Path>() { Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!attrs.isDirectory() && file.toString().endsWith(".java")) { if (!attrs.isDirectory() && file.toString().endsWith(".java")) {
parse(startPackage, file.getFileName().toString(), parser); tryToParse(startPackage, file.getFileName().toString(), parser);
} }
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
Expand All @@ -59,10 +59,10 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
} }


/** /**
* Parse every Java file in this source root. * Parse every .java file in this source root.
*/ */
public Map<Path, CompilationUnit> parse(JavaParser parser) throws IOException { public Map<Path, ParseResult<CompilationUnit>> tryToParse(JavaParser parser) throws IOException {
return parse("", parser); return tryToParse("", parser);
} }


/** /**
Expand All @@ -77,52 +77,67 @@ public void saveAll() throws FileNotFoundException, UnsupportedEncodingException
*/ */
public void saveAll(Path root) throws FileNotFoundException, UnsupportedEncodingException { public void saveAll(Path root) throws FileNotFoundException, UnsupportedEncodingException {
log.info(f("Saving all files (%s) to %s", content.size(), root)); log.info(f("Saving all files (%s) to %s", content.size(), root));
for (Map.Entry<Path, CompilationUnit> cu : content.entrySet()) { for (Map.Entry<Path, ParseResult<CompilationUnit>> cu : content.entrySet()) {
final Path path = root.resolve(cu.getKey()); final Path path = root.resolve(cu.getKey());
log.debug(f("Saving %s", path)); log.debug(f("Saving %s", path));
path.getParent().toFile().mkdirs(); path.getParent().toFile().mkdirs();


final String code = new PrettyPrinter().print(cu.getValue()); final String code = new PrettyPrinter().print(cu.getValue().getResult().get());
try (PrintWriter out = new PrintWriter(path.toFile(), UTF8.toString())) { try (PrintWriter out = new PrintWriter(path.toFile(), UTF8.toString())) {
out.println(code); out.println(code);
} }
} }
} }


/** /**
* A complete list of encountered problems while parsing. * The Java files that have been parsed by this source root object,
* or have been added manually.
*/ */
public List<Problem> getProblems() { public Map<Path, ParseResult<CompilationUnit>> getContent() {
return problems; return content;
} }


/** /**
* The Java files that have been parsed by this source root object. * The CompilationUnits of the Java files that have been parsed succesfully by this source root object,
* or have been added manually.
*/ */
public Map<Path, CompilationUnit> getContent() { public List<CompilationUnit> getCompilationUnits() {
return content; return content.values().stream()
.filter(ParseResult::isSuccessful)
.map(p -> p.getResult().get())
.collect(Collectors.toList());
} }


/** /**
* Parse a single Java file and return it. * Try to parse a single Java file and return the result of parsing.
*/ */
public Optional<CompilationUnit> parse(String packag, String filename, JavaParser javaParser) throws IOException { public ParseResult<CompilationUnit> tryToParse(String packag, String filename, JavaParser javaParser) throws IOException {
final Path relativePath = fileInPackageRelativePath(packag, filename); final Path relativePath = fileInPackageRelativePath(packag, filename);
if (content.containsKey(relativePath)) { if (content.containsKey(relativePath)) {
log.debug(f("Retrieving cached %s", relativePath)); log.debug(f("Retrieving cached %s", relativePath));
return Optional.of(content.get(relativePath)); return content.get(relativePath);
} }
final Path path = root.resolve(relativePath); final Path path = root.resolve(relativePath);
log.debug(f("Parsing %s", path)); log.debug(f("Parsing %s", path));
final ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(path)); final ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(path));
if (result.isSuccessful()) { content.put(relativePath, result);
final CompilationUnit cu = result.getResult().get(); return result;
content.put(relativePath, cu); }
} else {
log.error(f("Problems occurred parsing %s.", relativePath)); /**
problems.addAll(result.getProblems()); * Try to parse a single Java file and return it.
* @throws ParseProblemException when something went wrong.
*/
public CompilationUnit parse(String packag, String filename, JavaParser javaParser) {
try {
ParseResult<CompilationUnit> result = tryToParse(packag, filename, javaParser);
if (result.isSuccessful()) {
return result.getResult().get();
}
throw new ParseProblemException(result.getProblems());
} catch (IOException e) {
throw new ParseProblemException(e);
} }
return result.getResult();
} }


/** /**
Expand All @@ -131,6 +146,7 @@ public Optional<CompilationUnit> parse(String packag, String filename, JavaParse
public void add(String pkg, String filename, CompilationUnit compilationUnit) { public void add(String pkg, String filename, CompilationUnit compilationUnit) {
log.debug(f("Adding new file %s.%s", pkg, filename)); log.debug(f("Adding new file %s.%s", pkg, filename));
final Path path = fileInPackageRelativePath(pkg, filename); final Path path = fileInPackageRelativePath(pkg, filename);
content.put(path, compilationUnit); final ParseResult<CompilationUnit> parseResult = new ParseResult<>(compilationUnit, new ArrayList<>(), null, null);
content.put(path, parseResult);
} }
} }
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ private void run() throws IOException, NoSuchMethodException {


SourceRoot sourceRoot = new SourceRoot(root); SourceRoot sourceRoot = new SourceRoot(root);


CompilationUnit javaParserMetaModel = sourceRoot.parse(METAMODEL_PACKAGE, "JavaParserMetaModel.java", javaParser).get(); CompilationUnit javaParserMetaModel = sourceRoot.tryToParse(METAMODEL_PACKAGE, "JavaParserMetaModel.java", javaParser).getResult().get();


generateNodeMetaModels(javaParserMetaModel, sourceRoot); generateNodeMetaModels(javaParserMetaModel, sourceRoot);


Expand Down

0 comments on commit b6b07ac

Please sign in to comment.