Skip to content

Commit

Permalink
Spring cleaning
Browse files Browse the repository at this point in the history
  • Loading branch information
matozoid committed Feb 1, 2019
1 parent a896097 commit b9caf94
Show file tree
Hide file tree
Showing 24 changed files with 185 additions and 173 deletions.
Expand Up @@ -72,7 +72,7 @@ public static Javadoc parse(String commentContent) {
//then needs to be added again so that the block parsers handles everything correctly. //then needs to be added again so that the block parsers handles everything correctly.
blockLines = BLOCK_PATTERN blockLines = BLOCK_PATTERN
.splitAsStream(tagBlock) .splitAsStream(tagBlock)
.filter(STRING_NOT_EMPTY) .filter(s1 -> !s1.isEmpty())
.map(s -> BLOCK_TAG_PREFIX + s) .map(s -> BLOCK_TAG_PREFIX + s)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
Expand Down
Expand Up @@ -6,7 +6,7 @@
* An implementation of interface CharStream, where the stream is assumed to * An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (with java-like unicode escape processing). * contain only ASCII characters (with java-like unicode escape processing).
*/ */
public class UnicodeEscapeProcessingProvider implements Provider { class UnicodeEscapeProcessingProvider implements Provider {
private static int hexval(char c) throws java.io.IOException { private static int hexval(char c) throws java.io.IOException {
switch (c) { switch (c) {
case '0': case '0':
Expand Down
Expand Up @@ -8,6 +8,9 @@
import static com.github.javaparser.utils.Utils.capitalize; import static com.github.javaparser.utils.Utils.capitalize;
import static com.github.javaparser.utils.Utils.decapitalize; import static com.github.javaparser.utils.Utils.decapitalize;


/**
* Utilities that can be useful when generating code.
*/
public final class CodeGenerationUtils { public final class CodeGenerationUtils {
private CodeGenerationUtils() { private CodeGenerationUtils() {
} }
Expand Down
Expand Up @@ -8,6 +8,8 @@


/** /**
* To avoid dependencies on logging frameworks, we have invented yet another logging framework :-) * To avoid dependencies on logging frameworks, we have invented yet another logging framework :-)
* <p>
* See <a href="http://javaparser.org/javaparsers-logging-framework-in-one-file/">a blog about this</a>
*/ */
public class Log { public class Log {
/** /**
Expand Down
Expand Up @@ -21,6 +21,8 @@


package com.github.javaparser.utils; package com.github.javaparser.utils;


import java.util.Objects;

import static com.github.javaparser.utils.CodeGenerationUtils.f; import static com.github.javaparser.utils.CodeGenerationUtils.f;


/** /**
Expand All @@ -45,8 +47,8 @@ public boolean equals(Object o) {


Pair<?, ?> pair = (Pair<?, ?>) o; Pair<?, ?> pair = (Pair<?, ?>) o;


if (a != null ? !a.equals(pair.a) : pair.a != null) return false; if (!Objects.equals(a, pair.a)) return false;
if (b != null ? !b.equals(pair.b) : pair.b != null) return false; if (!Objects.equals(b, pair.b)) return false;


return true; return true;
} }
Expand Down
Expand Up @@ -23,6 +23,7 @@


import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.nio.file.Files;
import java.util.*; import java.util.*;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.function.Function; import java.util.function.Function;
Expand All @@ -37,11 +38,10 @@
public class Utils { public class Utils {
public static final String EOL = System.getProperty("line.separator"); public static final String EOL = System.getProperty("line.separator");


public static final Predicate<String> STRING_NOT_EMPTY = s -> !s.isEmpty();

/** /**
* @deprecated This is no longer in use by JavaParser, please write your own replacement. * @deprecated This is no longer in use by JavaParser, please write your own replacement.
*/ */
@Deprecated
public static <T> List<T> ensureNotNull(List<T> list) { public static <T> List<T> ensureNotNull(List<T> list) {
return list == null ? new ArrayList<>() : list; return list == null ? new ArrayList<>() : list;
} }
Expand Down
Expand Up @@ -36,47 +36,49 @@
import com.github.javaparser.symbolsolver.model.resolution.SymbolReference; import com.github.javaparser.symbolsolver.model.resolution.SymbolReference;
import com.github.javaparser.symbolsolver.model.resolution.TypeSolver; import com.github.javaparser.symbolsolver.model.resolution.TypeSolver;


import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.LinkedList; import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List; import java.util.List;


import static com.github.javaparser.symbolsolver.javaparser.Navigator.requireParentNode; import static com.github.javaparser.symbolsolver.javaparser.Navigator.requireParentNode;
import static java.util.Comparator.comparing;


/** /**
* It prints information extracted from a source file. It is mainly intended as an example usage of JavaSymbolSolver. * Resolves resolvable nodes from one or more source files, and reports the results.
* It is mainly intended as an example usage of JavaSymbolSolver.
* *
* @author Federico Tomassetti * @author Federico Tomassetti
*/ */
public class SourceFileInfoExtractor { public class SourceFileInfoExtractor {


private TypeSolver typeSolver; private final TypeSolver typeSolver;


private int ok = 0; private int successes = 0;
private int ko = 0; private int failures = 0;
private int unsupported = 0; private int unsupported = 0;
private boolean printFileName = true; private boolean printFileName = true;
private PrintStream out = System.out; private PrintStream out = System.out;
private PrintStream err = System.err; private PrintStream err = System.err;
private boolean verbose = false;

public SourceFileInfoExtractor(TypeSolver typeSolver) {
this.typeSolver = typeSolver;
}


public void setVerbose(boolean verbose) { public void setVerbose(boolean verbose) {
this.verbose = verbose; this.verbose = verbose;
} }


private boolean verbose = false;

public void setPrintFileName(boolean printFileName) { public void setPrintFileName(boolean printFileName) {
this.printFileName = printFileName; this.printFileName = printFileName;
} }


public void clear() {
ok = 0;
ko = 0;
unsupported = 0;
}

public void setOut(PrintStream out) { public void setOut(PrintStream out) {
this.out = out; this.out = out;
} }
Expand All @@ -85,17 +87,16 @@ public void setErr(PrintStream err) {
this.err = err; this.err = err;
} }


public int getOk() { public int getSuccesses() {
return ok; return successes;

} }


public int getUnsupported() { public int getUnsupported() {
return unsupported; return unsupported;
} }


public int getKo() { public int getFailures() {
return ko; return failures;
} }


private void solveTypeDecl(ClassOrInterfaceDeclaration node) { private void solveTypeDecl(ClassOrInterfaceDeclaration node) {
Expand All @@ -115,23 +116,27 @@ private void solve(Node node) {
if (node instanceof ClassOrInterfaceDeclaration) { if (node instanceof ClassOrInterfaceDeclaration) {
solveTypeDecl((ClassOrInterfaceDeclaration) node); solveTypeDecl((ClassOrInterfaceDeclaration) node);
} else if (node instanceof Expression) { } else if (node instanceof Expression) {
if ((requireParentNode(node) instanceof ImportDeclaration) || (requireParentNode(node) instanceof Expression) Node parentNode = requireParentNode(node);
|| (requireParentNode(node) instanceof MethodDeclaration) if (parentNode instanceof ImportDeclaration ||
|| (requireParentNode(node) instanceof PackageDeclaration)) { parentNode instanceof Expression ||
parentNode instanceof MethodDeclaration ||
parentNode instanceof PackageDeclaration) {
// skip // skip
} else if ((requireParentNode(node) instanceof Statement) || return;
(requireParentNode(node) instanceof VariableDeclarator) || }
(requireParentNode(node) instanceof SwitchEntry)) { if (parentNode instanceof Statement ||
parentNode instanceof VariableDeclarator ||
parentNode instanceof SwitchEntry) {
try { try {
ResolvedType ref = JavaParserFacade.get(typeSolver).getType(node); ResolvedType ref = JavaParserFacade.get(typeSolver).getType(node);
out.println(" Line " + node.getRange().get().begin.line + ") " + node + " ==> " + ref.describe()); out.println(" Line " + lineNr(node) + ") " + node + " ==> " + ref.describe());
ok++; successes++;
} catch (UnsupportedOperationException upe) { } catch (UnsupportedOperationException upe) {
unsupported++; unsupported++;
err.println(upe.getMessage()); err.println(upe.getMessage());
throw upe; throw upe;
} catch (RuntimeException re) { } catch (RuntimeException re) {
ko++; failures++;
err.println(re.getMessage()); err.println(re.getMessage());
throw re; throw re;
} }
Expand All @@ -141,7 +146,7 @@ private void solve(Node node) {


private void solveMethodCalls(Node node) { private void solveMethodCalls(Node node) {
if (node instanceof MethodCallExpr) { if (node instanceof MethodCallExpr) {
out.println(" Line " + node.getBegin().get().line + ") " + node + " ==> " + toString((MethodCallExpr) node)); out.println(" Line " + lineNr(node) + ") " + node + " ==> " + toString((MethodCallExpr) node));
} }
for (Node child : node.getChildNodes()) { for (Node child : node.getChildNodes()) {
solveMethodCalls(child); solveMethodCalls(child);
Expand All @@ -153,7 +158,7 @@ private String toString(MethodCallExpr node) {
return toString(JavaParserFacade.get(typeSolver).solve(node)); return toString(JavaParserFacade.get(typeSolver).solve(node));
} catch (Exception e) { } catch (Exception e) {
if (verbose) { if (verbose) {
System.err.println("Error resolving call at L" + node.getBegin().get().line + ": " + node); System.err.println("Error resolving call at L" + lineNr(node) + ": " + node);
e.printStackTrace(); e.printStackTrace();
} }
return "ERROR"; return "ERROR";
Expand All @@ -169,54 +174,46 @@ private String toString(SymbolReference<ResolvedMethodDeclaration> methodDeclara
} }


private List<Node> collectAllNodes(Node node) { private List<Node> collectAllNodes(Node node) {
List<Node> nodes = new LinkedList<>(); List<Node> nodes = new ArrayList<>();
collectAllNodes(node, nodes); node.walk(nodes::add);
nodes.sort((n1, n2) -> n1.getBegin().get().compareTo(n2.getBegin().get())); nodes.sort(comparing(n -> n.getBegin().get()));
return nodes; return nodes;
} }


private void collectAllNodes(Node node, List<Node> nodes) {
nodes.add(node);
node.getChildNodes().forEach(c -> collectAllNodes(c, nodes));
}

public void solve(Path path) throws IOException { public void solve(Path path) throws IOException {
File file = path.toFile(); Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
if (file.isDirectory()) { @Override
for (File f : file.listFiles()) { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
solve(f.toPath()); if (file.toString().endsWith(".java")) {
} if (printFileName) {
} else { out.println("- parsing " + file.toAbsolutePath());
if (file.getName().endsWith(".java")) { }
if (printFileName) { CompilationUnit cu = JavaParser.parse(file);
out.println("- parsing " + file.getAbsolutePath()); List<Node> nodes = collectAllNodes(cu);
nodes.forEach(n -> solve(n));
} }
CompilationUnit cu = JavaParser.parse(file); return FileVisitResult.CONTINUE;
List<Node> nodes = collectAllNodes(cu);
nodes.forEach(n -> solve(n));
} }
} });
} }


public void solveMethodCalls(Path path) throws IOException { public void solveMethodCalls(Path path) throws IOException {
File file = path.toFile(); Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
if (file.isDirectory()) { @Override
for (File f : file.listFiles()) { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
solveMethodCalls(f.toPath()); if (file.toString().endsWith(".java")) {
} if (printFileName) {
} else { out.println("- parsing " + file.toAbsolutePath());
if (file.getName().endsWith(".java")) { }
if (printFileName) { CompilationUnit cu = JavaParser.parse(file);
out.println("- parsing " + file.getAbsolutePath()); solveMethodCalls(cu);
} }
CompilationUnit cu = JavaParser.parse(file); return FileVisitResult.CONTINUE;
solveMethodCalls(cu);
} }
} });
} }


public void setTypeSolver(TypeSolver typeSolver) { private int lineNr(Node node) {
this.typeSolver = typeSolver; return node.getRange().map(range -> range.begin.line).orElseThrow(IllegalStateException::new);
} }

} }
Expand Up @@ -51,7 +51,7 @@ public int getNumberOfParams() {


@Override @Override
public ResolvedParameterDeclaration getParam(int i) { public ResolvedParameterDeclaration getParam(int i) {
throw new UnsupportedOperationException("The default constructor has not parameters"); throw new UnsupportedOperationException("The default constructor has no parameters");
} }


@Override @Override
Expand Down
Expand Up @@ -110,7 +110,7 @@ public String getPackageName() {
public String getClassName() { public String getClassName() {
String className = ctClass.getName().replace('$', '.'); String className = ctClass.getName().replace('$', '.');
if (getPackageName() != null) { if (getPackageName() != null) {
return className.substring(getPackageName().length() + 1, className.length()); return className.substring(getPackageName().length() + 1);
} }
return className; return className;
} }
Expand All @@ -120,6 +120,7 @@ public String getQualifiedName() {
return ctClass.getName().replace('$', '.'); return ctClass.getName().replace('$', '.');
} }


@Deprecated
public Optional<MethodUsage> solveMethodAsUsage(String name, List<ResolvedType> argumentsTypes, public Optional<MethodUsage> solveMethodAsUsage(String name, List<ResolvedType> argumentsTypes,
Context invokationContext, List<ResolvedType> typeParameterValues) { Context invokationContext, List<ResolvedType> typeParameterValues) {
return JavassistUtils.getMethodUsage(ctClass, name, argumentsTypes, typeSolver, invokationContext); return JavassistUtils.getMethodUsage(ctClass, name, argumentsTypes, typeSolver, invokationContext);
Expand Down
Expand Up @@ -35,8 +35,8 @@
* @author Fred Lefévère-Laoide * @author Fred Lefévère-Laoide
*/ */
public class JavassistConstructorDeclaration implements ResolvedConstructorDeclaration { public class JavassistConstructorDeclaration implements ResolvedConstructorDeclaration {
private CtConstructor ctConstructor; private final CtConstructor ctConstructor;
private TypeSolver typeSolver; private final TypeSolver typeSolver;


public JavassistConstructorDeclaration(CtConstructor ctConstructor, TypeSolver typeSolver) { public JavassistConstructorDeclaration(CtConstructor ctConstructor, TypeSolver typeSolver) {
this.ctConstructor = ctConstructor; this.ctConstructor = ctConstructor;
Expand All @@ -45,8 +45,9 @@ public JavassistConstructorDeclaration(CtConstructor ctConstructor, TypeSolver t


@Override @Override
public String toString() { public String toString() {
return "JavassistMethodDeclaration{" + return getClass().getSimpleName() + "{" +
"CtConstructor=" + ctConstructor + "ctConstructor=" + ctConstructor.getName() +
", typeSolver=" + typeSolver +
'}'; '}';
} }


Expand Down
Expand Up @@ -59,4 +59,13 @@ public ResolvedType getType() {
} }
return type; return type;
} }

@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"ctField=" + ctField.getName() +
", typeSolver=" + typeSolver +
'}';
}

} }
Expand Up @@ -282,4 +282,12 @@ public List<ResolvedEnumConstantDeclaration> getEnumConstants() {
public List<ResolvedConstructorDeclaration> getConstructors() { public List<ResolvedConstructorDeclaration> getConstructors() {
return javassistTypeDeclarationAdapter.getConstructors(); return javassistTypeDeclarationAdapter.getConstructors();
} }

@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"ctClass=" + ctClass.getName() +
", typeSolver=" + typeSolver +
'}';
}
} }
Expand Up @@ -49,9 +49,7 @@ public ResolvedType getType() {
} else { } else {
return JavassistFactory.typeUsageFor(ctField.getType(), typeSolver); return JavassistFactory.typeUsageFor(ctField.getType(), typeSolver);
} }
} catch (NotFoundException e) { } catch (NotFoundException | BadBytecode e) {
throw new RuntimeException(e);
} catch (BadBytecode e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
Expand Down

0 comments on commit b9caf94

Please sign in to comment.