Search in sources :

Example 1 with ParseResult

use of com.github.javaparser.ParseResult in project javaparser by javaparser.

the class SourceRoot method add.

/**
 * Add a newly created Java file to the cache of this source root. It will be saved when saveAll is called. It needs
 * to have its path set.
 */
public SourceRoot add(CompilationUnit compilationUnit) {
    assertNotNull(compilationUnit);
    if (compilationUnit.getStorage().isPresent()) {
        final Path path = compilationUnit.getStorage().get().getPath();
        Log.trace("Adding new file %s", path);
        final ParseResult<CompilationUnit> parseResult = new ParseResult<>(compilationUnit, new ArrayList<>(), null, null);
        cache.put(path, parseResult);
    } else {
        throw new AssertionError("Files added with this method should have their path set.");
    }
    return this;
}
Also used : CodeGenerationUtils.fileInPackageRelativePath(com.github.javaparser.utils.CodeGenerationUtils.fileInPackageRelativePath) Path(java.nio.file.Path) CodeGenerationUtils.packageAbsolutePath(com.github.javaparser.utils.CodeGenerationUtils.packageAbsolutePath) CompilationUnit(com.github.javaparser.ast.CompilationUnit) ParseResult(com.github.javaparser.ParseResult)

Example 2 with ParseResult

use of com.github.javaparser.ParseResult in project javaparser by javaparser.

the class SourceRoot method add.

/**
 * Add a newly created Java file to the cache of this source root. It will be saved when saveAll is called.
 *
 * @param startPackage files in this package and deeper are parsed. Pass "" to parse all files.
 */
public SourceRoot add(String startPackage, String filename, CompilationUnit compilationUnit) {
    assertNotNull(startPackage);
    assertNotNull(filename);
    assertNotNull(compilationUnit);
    Log.trace("Adding new file %s.%s", startPackage, filename);
    final Path path = fileInPackageRelativePath(startPackage, filename);
    final ParseResult<CompilationUnit> parseResult = new ParseResult<>(compilationUnit, new ArrayList<>(), null, null);
    cache.put(path, parseResult);
    return this;
}
Also used : CodeGenerationUtils.fileInPackageRelativePath(com.github.javaparser.utils.CodeGenerationUtils.fileInPackageRelativePath) Path(java.nio.file.Path) CodeGenerationUtils.packageAbsolutePath(com.github.javaparser.utils.CodeGenerationUtils.packageAbsolutePath) CompilationUnit(com.github.javaparser.ast.CompilationUnit) ParseResult(com.github.javaparser.ParseResult)

Example 3 with ParseResult

use of com.github.javaparser.ParseResult in project drools by kiegroup.

the class MvelParser method parse.

/**
 * Parses source code.
 * It takes the source code from a Provider.
 * The start indicates what can be found in the source code (compilation unit, block, import...)
 *
 * @param start refer to the constants in ParseStart to see what can be parsed.
 * @param provider refer to Providers to see how you can read source. The provider will be closed after parsing.
 * @param <N> the subclass of Node that is the result of parsing in the start.
 * @return the parse result, a collection of encountered problems, and some extra data.
 */
public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) {
    assertNotNull(start);
    assertNotNull(provider);
    final GeneratedMvelParser parser = getParserForProvider(provider);
    try {
        N resultNode = start.parse(parser);
        ParseResult<N> result = new ParseResult<>(resultNode, parser.problems, parser.getCommentsCollection());
        configuration.getPostProcessors().forEach(postProcessor -> postProcessor.process(result, configuration));
        result.getProblems().sort(PROBLEM_BY_BEGIN_POSITION);
        return result;
    } catch (Exception e) {
        final String message = e.getMessage() == null ? "Unknown error" : e.getMessage();
        parser.problems.add(new Problem(message, null, e));
        return new ParseResult<>(null, parser.problems, parser.getCommentsCollection());
    } finally {
        try {
            provider.close();
        } catch (IOException e) {
        // Since we're done parsing and have our result, we don't care about any errors.
        }
    }
}
Also used : ParseResult(com.github.javaparser.ParseResult) Problem(com.github.javaparser.Problem) IOException(java.io.IOException) EXPRESSION(org.drools.mvel.parser.ParseStart.EXPRESSION) PROBLEM_BY_BEGIN_POSITION(com.github.javaparser.Problem.PROBLEM_BY_BEGIN_POSITION) IOException(java.io.IOException) ParseProblemException(com.github.javaparser.ParseProblemException)

Example 4 with ParseResult

use of com.github.javaparser.ParseResult in project scheduler by btrplace.

the class DSN method testSloc.

// @Test
// Extract the number of line of codes of tests
public void testSloc() throws Exception {
    // Parse the legacy unit tests
    List<Integer> unitTests = new ArrayList<>();
    List<Path> paths = Files.list(Paths.get("choco/src/test/java/org/btrplace/scheduler/choco/constraint/")).filter(Files::isRegularFile).collect(Collectors.toList());
    for (Path p : paths) {
        try (InputStream in = Files.newInputStream(p)) {
            ParseResult<CompilationUnit> cu = new JavaParser().parse(in);
            new UnitTestsVisitor(unitTests).visit(cu.getResult().get(), null);
        }
    }
    // Parse the new unit tests
    List<Integer> safeTests = new ArrayList<>();
    try (InputStream in = Files.newInputStream(Paths.get("safeplace/src/test/java/org/btrplace/safeplace/testing/TestSafePlace.java"))) {
        ParseResult<CompilationUnit> cu = new JavaParser().parse(in);
        new SafeplaceTestsVisitor(safeTests).visit(cu.getResult().get(), null);
    }
    String sb = "testing;sloc\n" + unitTests.stream().map(i -> "btrPlace;" + i).collect(Collectors.joining("\n", "", "\n")) + safeTests.stream().map(i -> "safePlace;" + i).collect(Collectors.joining("\n", "", "\n"));
    Path path = Paths.get(root, "sloc.csv");
    Files.write(path, sb.getBytes());
}
Also used : Path(java.nio.file.Path) CompilationUnit(com.github.javaparser.ast.CompilationUnit) CSVReport(org.btrplace.safeplace.testing.reporting.CSVReport) PrettyPrinterConfiguration(com.github.javaparser.printer.configuration.PrettyPrinterConfiguration) ParseResult(com.github.javaparser.ParseResult) VoidVisitorAdapter(com.github.javaparser.ast.visitor.VoidVisitorAdapter) AnnotationExpr(com.github.javaparser.ast.expr.AnnotationExpr) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Restriction(org.btrplace.safeplace.testing.fuzzer.Restriction) Constraint(org.btrplace.safeplace.spec.Constraint) Matcher(java.util.regex.Matcher) Assert(org.testng.Assert) Map(java.util.Map) CompilationUnit(com.github.javaparser.ast.CompilationUnit) SpecScanner(org.btrplace.safeplace.spec.SpecScanner) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) SpecVerifier(org.btrplace.safeplace.testing.verification.spec.SpecVerifier) TestScanner(org.btrplace.safeplace.testing.TestScanner) Files(java.nio.file.Files) Verifier(org.btrplace.safeplace.testing.verification.Verifier) Collectors(java.util.stream.Collectors) Bench(org.btrplace.safeplace.testing.Bench) List(java.util.List) StoredReport(org.btrplace.safeplace.testing.reporting.StoredReport) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Paths(java.nio.file.Paths) Result(org.btrplace.safeplace.testing.Result) TestCampaign(org.btrplace.safeplace.testing.TestCampaign) Pattern(java.util.regex.Pattern) CheckerVerifier(org.btrplace.safeplace.testing.verification.btrplace.CheckerVerifier) JavaParser(com.github.javaparser.JavaParser) InputStream(java.io.InputStream) JavaParser(com.github.javaparser.JavaParser) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList)

Example 5 with ParseResult

use of com.github.javaparser.ParseResult in project javaparser by javaparser.

the class SourceRoot method parse.

/**
 * Tries to parse all .java files in a package recursively and passes them one by one to the callback. In comparison
 * to the other parse methods, this is much more memory efficient, but saveAll() won't work.
 *
 * @param startPackage files in this package and deeper are parsed. Pass "" to parse all files.
 */
public SourceRoot parse(String startPackage, ParserConfiguration configuration, Callback callback) throws IOException {
    assertNotNull(startPackage);
    assertNotNull(configuration);
    assertNotNull(callback);
    logPackage(startPackage);
    final JavaParser javaParser = new JavaParser(configuration);
    final Path path = packageAbsolutePath(root, startPackage);
    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult visitFile(Path absolutePath, BasicFileAttributes attrs) throws IOException {
            if (!attrs.isDirectory() && absolutePath.toString().endsWith(".java")) {
                Path localPath = root.relativize(absolutePath);
                Log.trace("Parsing %s", localPath);
                final ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(absolutePath));
                result.getResult().ifPresent(cu -> cu.setStorage(absolutePath));
                if (callback.process(localPath, absolutePath, result) == SAVE) {
                    if (result.getResult().isPresent()) {
                        save(result.getResult().get(), path);
                    }
                }
            }
            return CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return isSensibleDirectoryToEnter(dir) ? CONTINUE : SKIP_SUBTREE;
        }
    });
    return this;
}
Also used : CodeGenerationUtils.fileInPackageRelativePath(com.github.javaparser.utils.CodeGenerationUtils.fileInPackageRelativePath) Path(java.nio.file.Path) CodeGenerationUtils.packageAbsolutePath(com.github.javaparser.utils.CodeGenerationUtils.packageAbsolutePath) Providers.provider(com.github.javaparser.Providers.provider) SAVE(com.github.javaparser.utils.SourceRoot.Callback.Result.SAVE) ParseResult(com.github.javaparser.ParseResult) COMPILATION_UNIT(com.github.javaparser.ParseStart.COMPILATION_UNIT) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Utils.assertNotNull(com.github.javaparser.utils.Utils.assertNotNull) CodeGenerationUtils.fileInPackageRelativePath(com.github.javaparser.utils.CodeGenerationUtils.fileInPackageRelativePath) Map(java.util.Map) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) PrettyPrinter(com.github.javaparser.printer.PrettyPrinter) Files(java.nio.file.Files) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ParserConfiguration(com.github.javaparser.ParserConfiguration) IOException(java.io.IOException) RecursiveAction(java.util.concurrent.RecursiveAction) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) CONTINUE(java.nio.file.FileVisitResult.CONTINUE) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) ParseProblemException(com.github.javaparser.ParseProblemException) SKIP_SUBTREE(java.nio.file.FileVisitResult.SKIP_SUBTREE) ForkJoinPool(java.util.concurrent.ForkJoinPool) Pattern(java.util.regex.Pattern) JavaParser(com.github.javaparser.JavaParser) CodeGenerationUtils.packageAbsolutePath(com.github.javaparser.utils.CodeGenerationUtils.packageAbsolutePath) JavaParser(com.github.javaparser.JavaParser) ParseResult(com.github.javaparser.ParseResult) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

ParseResult (com.github.javaparser.ParseResult)7 Path (java.nio.file.Path)6 CompilationUnit (com.github.javaparser.ast.CompilationUnit)5 CodeGenerationUtils.fileInPackageRelativePath (com.github.javaparser.utils.CodeGenerationUtils.fileInPackageRelativePath)4 CodeGenerationUtils.packageAbsolutePath (com.github.javaparser.utils.CodeGenerationUtils.packageAbsolutePath)4 Map (java.util.Map)4 JavaParser (com.github.javaparser.JavaParser)3 Files (java.nio.file.Files)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Pattern (java.util.regex.Pattern)3 Collectors (java.util.stream.Collectors)3 ParseProblemException (com.github.javaparser.ParseProblemException)2 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)2 AnnotationExpr (com.github.javaparser.ast.expr.AnnotationExpr)2 VoidVisitorAdapter (com.github.javaparser.ast.visitor.VoidVisitorAdapter)2 PrettyPrinterConfiguration (com.github.javaparser.printer.configuration.PrettyPrinterConfiguration)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 Paths (java.nio.file.Paths)2