Search in sources :

Example 61 with Node

use of com.github.javaparser.ast.Node in project javaparser by javaparser.

the class DumpVisitor method printOrphanCommentsBeforeThisChildNode.

private void printOrphanCommentsBeforeThisChildNode(final Node node) {
    if (node instanceof Comment)
        return;
    Node parent = node.getParentNode();
    if (parent == null)
        return;
    List<Node> everything = new LinkedList<Node>();
    everything.addAll(parent.getChildrenNodes());
    sortByBeginPosition(everything);
    int positionOfTheChild = -1;
    for (int i = 0; i < everything.size(); i++) {
        if (everything.get(i) == node)
            positionOfTheChild = i;
    }
    if (positionOfTheChild == -1)
        throw new RuntimeException("My index not found!!! " + node);
    int positionOfPreviousChild = -1;
    for (int i = positionOfTheChild - 1; i >= 0 && positionOfPreviousChild == -1; i--) {
        if (!(everything.get(i) instanceof Comment))
            positionOfPreviousChild = i;
    }
    for (int i = positionOfPreviousChild + 1; i < positionOfTheChild; i++) {
        Node nodeToPrint = everything.get(i);
        if (!(nodeToPrint instanceof Comment))
            throw new RuntimeException("Expected comment, instead " + nodeToPrint.getClass() + ". Position of previous child: " + positionOfPreviousChild + ", position of child " + positionOfTheChild);
        nodeToPrint.accept(this, null);
    }
}
Also used : Comment(com.github.javaparser.ast.comments.Comment) JavadocComment(com.github.javaparser.ast.comments.JavadocComment) BlockComment(com.github.javaparser.ast.comments.BlockComment) LineComment(com.github.javaparser.ast.comments.LineComment) Node(com.github.javaparser.ast.Node) LinkedList(java.util.LinkedList)

Example 62 with Node

use of com.github.javaparser.ast.Node in project javaparser by javaparser.

the class JavaParser method insertCommentsInNode.

/**
 * This method try to attributes the nodes received to child of the node.
 * It returns the node that were not attributed.
 */
private static void insertCommentsInNode(Node node, List<Comment> commentsToAttribute) {
    if (commentsToAttribute.size() == 0)
        return;
    // the comments can:
    // 1) Inside one of the child, then it is the child that have to associate them
    // 2) If they are not inside a child they could be preceeding nothing, a comment or a child
    // if they preceed a child they are assigned to it, otherweise they remain "orphans"
    List<Node> children = node.getChildrenNodes();
    PositionUtils.sortByBeginPosition(children);
    for (Node child : children) {
        List<Comment> commentsInsideChild = new LinkedList<Comment>();
        for (Comment c : commentsToAttribute) {
            if (PositionUtils.nodeContains(child, c, _doNotConsiderAnnotationsAsNodeStartForCodeAttribution)) {
                commentsInsideChild.add(c);
            }
        }
        commentsToAttribute.removeAll(commentsInsideChild);
        insertCommentsInNode(child, commentsInsideChild);
    }
    // I can attribute in line comments to elements preceeding them, if there
    // is something contained in their line
    List<Comment> attributedComments = new LinkedList<Comment>();
    for (Comment comment : commentsToAttribute) {
        if (comment.isLineComment()) {
            for (Node child : children) {
                if (child.getEndLine() == comment.getBeginLine()) {
                    if (attributeLineCommentToNodeOrChild(child, comment.asLineComment())) {
                        attributedComments.add(comment);
                    }
                }
            }
        }
    }
    // at this point I create an ordered list of all remaining comments and children
    Comment previousComment = null;
    attributedComments = new LinkedList<Comment>();
    List<Node> childrenAndComments = new LinkedList<Node>();
    childrenAndComments.addAll(children);
    childrenAndComments.addAll(commentsToAttribute);
    PositionUtils.sortByBeginPosition(childrenAndComments, _doNotConsiderAnnotationsAsNodeStartForCodeAttribution);
    for (Node thing : childrenAndComments) {
        if (thing instanceof Comment) {
            previousComment = (Comment) thing;
            if (!previousComment.isOrphan()) {
                previousComment = null;
            }
        } else {
            if (previousComment != null && !thing.hasComment()) {
                if (!_doNotAssignCommentsPreceedingEmptyLines || !thereAreLinesBetween(previousComment, thing)) {
                    thing.setComment(previousComment);
                    attributedComments.add(previousComment);
                    previousComment = null;
                }
            }
        }
    }
    commentsToAttribute.removeAll(attributedComments);
    // all the remaining are orphan nodes
    for (Comment c : commentsToAttribute) {
        if (c.isOrphan()) {
            node.addOrphanComment(c);
        }
    }
}
Also used : LineComment(com.github.javaparser.ast.comments.LineComment) Comment(com.github.javaparser.ast.comments.Comment) Node(com.github.javaparser.ast.Node) LinkedList(java.util.LinkedList)

Example 63 with Node

use of com.github.javaparser.ast.Node in project javaparser by javaparser.

the class AbstractJavaParserContext method getParent.

@Override
public final Context getParent() {
    Node parent = wrappedNode.getParentNode().orElse(null);
    if (parent instanceof MethodCallExpr) {
        MethodCallExpr parentCall = (MethodCallExpr) parent;
        boolean found = false;
        if (parentCall.getArguments() != null) {
            for (Expression expression : parentCall.getArguments()) {
                if (expression == wrappedNode) {
                    found = true;
                }
            }
        }
        if (found) {
            Node notMethod = parent;
            while (notMethod instanceof MethodCallExpr) {
                notMethod = requireParentNode(notMethod);
            }
            return JavaParserFactory.getContext(notMethod, typeSolver);
        }
    }
    Node notMethod = parent;
    while (notMethod instanceof MethodCallExpr || notMethod instanceof FieldAccessExpr) {
        notMethod = notMethod.getParentNode().orElse(null);
    }
    if (notMethod == null) {
        return null;
    }
    return JavaParserFactory.getContext(notMethod, typeSolver);
}
Also used : Expression(com.github.javaparser.ast.expr.Expression) Navigator.getParentNode(com.github.javaparser.symbolsolver.javaparser.Navigator.getParentNode) Navigator.requireParentNode(com.github.javaparser.symbolsolver.javaparser.Navigator.requireParentNode) Node(com.github.javaparser.ast.Node) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 64 with Node

use of com.github.javaparser.ast.Node in project javaparser by javaparser.

the class JavaParserFacade method getType.

public ResolvedType getType(Node node, boolean solveLambdas) {
    if (solveLambdas) {
        if (!cacheWithLambdasSolved.containsKey(node)) {
            ResolvedType res = getTypeConcrete(node, solveLambdas);
            cacheWithLambdasSolved.put(node, res);
            boolean secondPassNecessary = false;
            if (node instanceof MethodCallExpr) {
                MethodCallExpr methodCallExpr = (MethodCallExpr) node;
                for (Node arg : methodCallExpr.getArguments()) {
                    if (!cacheWithLambdasSolved.containsKey(arg)) {
                        getType(arg, true);
                        secondPassNecessary = true;
                    }
                }
            }
            if (secondPassNecessary) {
                cacheWithLambdasSolved.remove(node);
                cacheWithLambdasSolved.put(node, getType(node, true));
            }
            logger.finer("getType on " + node + " -> " + res);
        }
        return cacheWithLambdasSolved.get(node);
    } else {
        Optional<ResolvedType> res = find(cacheWithLambdasSolved, node);
        if (res.isPresent()) {
            return res.get();
        }
        res = find(cacheWithoutLambdasSolved, node);
        if (!res.isPresent()) {
            ResolvedType resType = getTypeConcrete(node, solveLambdas);
            cacheWithoutLambdasSolved.put(node, resType);
            logger.finer("getType on " + node + " (no solveLambdas) -> " + res);
            return resType;
        }
        return res.get();
    }
}
Also used : Navigator.requireParentNode(com.github.javaparser.symbolsolver.javaparser.Navigator.requireParentNode) Node(com.github.javaparser.ast.Node)

Example 65 with Node

use of com.github.javaparser.ast.Node in project javaparser by javaparser.

the class JavaParserFacade method convertToUsage.

protected ResolvedType convertToUsage(com.github.javaparser.ast.type.Type type, Context context) {
    if (context == null) {
        throw new NullPointerException("Context should not be null");
    }
    if (type instanceof ClassOrInterfaceType) {
        ClassOrInterfaceType classOrInterfaceType = (ClassOrInterfaceType) type;
        String name = qName(classOrInterfaceType);
        SymbolReference<ResolvedTypeDeclaration> ref = context.solveType(name, typeSolver);
        if (!ref.isSolved()) {
            throw new UnsolvedSymbolException(name);
        }
        ResolvedTypeDeclaration typeDeclaration = ref.getCorrespondingDeclaration();
        List<ResolvedType> typeParameters = Collections.emptyList();
        if (classOrInterfaceType.getTypeArguments().isPresent()) {
            typeParameters = classOrInterfaceType.getTypeArguments().get().stream().map((pt) -> convertToUsage(pt, context)).collect(Collectors.toList());
        }
        if (typeDeclaration.isTypeParameter()) {
            if (typeDeclaration instanceof ResolvedTypeParameterDeclaration) {
                return new ResolvedTypeVariable((ResolvedTypeParameterDeclaration) typeDeclaration);
            } else {
                JavaParserTypeVariableDeclaration javaParserTypeVariableDeclaration = (JavaParserTypeVariableDeclaration) typeDeclaration;
                return new ResolvedTypeVariable(javaParserTypeVariableDeclaration.asTypeParameter());
            }
        } else {
            return new ReferenceTypeImpl((ResolvedReferenceTypeDeclaration) typeDeclaration, typeParameters, typeSolver);
        }
    } else if (type instanceof com.github.javaparser.ast.type.PrimitiveType) {
        return ResolvedPrimitiveType.byName(((com.github.javaparser.ast.type.PrimitiveType) type).getType().name());
    } else if (type instanceof WildcardType) {
        WildcardType wildcardType = (WildcardType) type;
        if (wildcardType.getExtendedType().isPresent() && !wildcardType.getSuperType().isPresent()) {
            // removed (ReferenceTypeImpl)
            return ResolvedWildcard.extendsBound(convertToUsage(wildcardType.getExtendedType().get(), context));
        } else if (!wildcardType.getExtendedType().isPresent() && wildcardType.getSuperType().isPresent()) {
            // removed (ReferenceTypeImpl)
            return ResolvedWildcard.superBound(convertToUsage(wildcardType.getSuperType().get(), context));
        } else if (!wildcardType.getExtendedType().isPresent() && !wildcardType.getSuperType().isPresent()) {
            return ResolvedWildcard.UNBOUNDED;
        } else {
            throw new UnsupportedOperationException(wildcardType.toString());
        }
    } else if (type instanceof com.github.javaparser.ast.type.VoidType) {
        return ResolvedVoidType.INSTANCE;
    } else if (type instanceof com.github.javaparser.ast.type.ArrayType) {
        com.github.javaparser.ast.type.ArrayType jpArrayType = (com.github.javaparser.ast.type.ArrayType) type;
        return new ResolvedArrayType(convertToUsage(jpArrayType.getComponentType(), context));
    } else if (type instanceof UnionType) {
        UnionType unionType = (UnionType) type;
        return new ResolvedUnionType(unionType.getElements().stream().map(el -> convertToUsage(el, context)).collect(Collectors.toList()));
    } else if (type instanceof VarType) {
        Node parent = type.getParentNode().get();
        if (!(parent instanceof VariableDeclarator)) {
            throw new IllegalStateException("Trying to resolve a `var` which is not in a variable declaration.");
        }
        final VariableDeclarator variableDeclarator = (VariableDeclarator) parent;
        return variableDeclarator.getInitializer().map(Expression::calculateResolvedType).orElseThrow(() -> new IllegalStateException("Cannot resolve `var` which has no initializer."));
    } else {
        throw new UnsupportedOperationException(type.getClass().getCanonicalName());
    }
}
Also used : FieldAccessContext(com.github.javaparser.symbolsolver.javaparsermodel.contexts.FieldAccessContext) java.util(java.util) Navigator.requireParentNode(com.github.javaparser.symbolsolver.javaparser.Navigator.requireParentNode) MethodUsage(com.github.javaparser.resolution.MethodUsage) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration) Level(java.util.logging.Level) com.github.javaparser.ast.body(com.github.javaparser.ast.body) Context(com.github.javaparser.symbolsolver.core.resolution.Context) ConstructorResolutionLogic(com.github.javaparser.symbolsolver.resolution.ConstructorResolutionLogic) CompilationUnit(com.github.javaparser.ast.CompilationUnit) Node(com.github.javaparser.ast.Node) NodeList(com.github.javaparser.ast.NodeList) com.github.javaparser.ast.type(com.github.javaparser.ast.type) UnsolvedSymbolException(com.github.javaparser.resolution.UnsolvedSymbolException) TypeSolver(com.github.javaparser.symbolsolver.model.resolution.TypeSolver) com.github.javaparser.symbolsolver.model.typesystem(com.github.javaparser.symbolsolver.model.typesystem) ReflectionClassDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration) Logger(java.util.logging.Logger) com.github.javaparser.resolution.declarations(com.github.javaparser.resolution.declarations) Collectors(java.util.stream.Collectors) ExplicitConstructorInvocationStmt(com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt) com.github.javaparser.symbolsolver.javaparsermodel.declarations(com.github.javaparser.symbolsolver.javaparsermodel.declarations) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) com.github.javaparser.resolution.types(com.github.javaparser.resolution.types) ConsoleHandler(java.util.logging.ConsoleHandler) SymbolSolver(com.github.javaparser.symbolsolver.resolution.SymbolSolver) com.github.javaparser.ast.expr(com.github.javaparser.ast.expr) Navigator.requireParentNode(com.github.javaparser.symbolsolver.javaparser.Navigator.requireParentNode) Node(com.github.javaparser.ast.Node) com.github.javaparser.ast.type(com.github.javaparser.ast.type) UnsolvedSymbolException(com.github.javaparser.resolution.UnsolvedSymbolException)

Aggregations

Node (com.github.javaparser.ast.Node)95 Test (org.junit.Test)24 Expression (com.github.javaparser.ast.expr.Expression)22 NodeList (com.github.javaparser.ast.NodeList)18 Comment (com.github.javaparser.ast.comments.Comment)13 CompilationUnit (com.github.javaparser.ast.CompilationUnit)12 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)12 NameExpr (com.github.javaparser.ast.expr.NameExpr)12 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)12 ArrayList (java.util.ArrayList)11 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)8 Collectors (java.util.stream.Collectors)8 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)7 LineComment (com.github.javaparser.ast.comments.LineComment)7 BinaryExpr (com.github.javaparser.ast.expr.BinaryExpr)7 EnclosedExpr (com.github.javaparser.ast.expr.EnclosedExpr)7 SimpleName (com.github.javaparser.ast.expr.SimpleName)7 HalfBinaryExpr (org.drools.mvel.parser.ast.expr.HalfBinaryExpr)7 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)6 AssignExpr (com.github.javaparser.ast.expr.AssignExpr)6