Java Code Examples for com.github.javaparser.ast.Node

The following examples show how to use com.github.javaparser.ast.Node. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * Gets the type index.
 *
 * @param <N> the number type
 * @param container the container
 * @param clazz the clazz
 * @return the type index
 */
static <N extends Node> Integer getTypeIndex(Node container, Class<N> clazz) {
    List<Node> children = container.getChildNodes();
    if (CollectionUtil.isNotEmpty(children)) {
        for (int i = 0; i < children.size(); i++) {
            Node child = children.get(i);
            if (clazz.isInstance(child)) {
                return i;
            }
            Integer temIdx = getTypeIndex(child, clazz);
            if (temIdx != null)
                return temIdx;
        }
    }

    return null;
}
 
Example 2
Source Project: impsort-maven-plugin   Source File: ImpSort.java    License: Apache License 2.0 7 votes vote down vote up
private static Set<String> tokensInUse(CompilationUnit unit) {

    // Extract tokens from the java code:
    Stream<Node> packageDecl =
        unit.getPackageDeclaration().isPresent()
            ? Stream.of(unit.getPackageDeclaration().get()).map(PackageDeclaration::getAnnotations)
                .flatMap(NodeList::stream)
            : Stream.empty();
    Stream<String> typesInCode = Stream.concat(packageDecl, unit.getTypes().stream())
        .map(Node::getTokenRange).filter(Optional::isPresent).map(Optional::get)
        .filter(r -> r != TokenRange.INVALID).flatMap(r -> {
          // get all JavaTokens as strings from each range
          return StreamSupport.stream(r.spliterator(), false);
        }).map(JavaToken::asString);

    // Extract referenced class names from parsed javadoc comments:
    Stream<String> typesInJavadocs = unit.getAllComments().stream()
        .filter(c -> c instanceof JavadocComment).map(JavadocComment.class::cast)
        .map(JavadocComment::parse).flatMap(ImpSort::parseJavadoc);

    return Stream.concat(typesInCode, typesInJavadocs)
        .filter(t -> t != null && !t.isEmpty() && Character.isJavaIdentifierStart(t.charAt(0)))
        .collect(Collectors.toSet());
  }
 
Example 3
Source Project: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Gets the field declaration map.
 *
 * @param <T> the generic type
 * @param node the class declaration
 * @param type the type
 * @return the field declaration map
 */
static <T extends BodyDeclaration> Map<String, T> getBodyDeclarationMap(Node node, Class<T> type) {
    List<Node> children = node.getChildNodes();
    if (CollectionUtil.isEmpty(children)) {
        return new HashMap<String, T>(0);
    }

    Map<String, T> bodyMap = new CaseInsensitiveHashMap<T>(children.size());

    List<T> bodyDeclarations = getNodesByType(node, type);

    for (T bodyDeclaration : bodyDeclarations) {
        if (bodyDeclaration instanceof FieldDeclaration) {
            FieldDeclaration fieldDeclaration = (FieldDeclaration) bodyDeclaration;
            VariableDeclarator variableDeclaratorId = getOneNodesByType(fieldDeclaration, VariableDeclarator.class);
            bodyMap.put(variableDeclaratorId.getName().toString(), bodyDeclaration);
        } else if (bodyDeclaration instanceof MethodDeclaration) {
            MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
            bodyMap.put(methodDeclaration.getNameAsString(), bodyDeclaration);
        }
    }
    return bodyMap;
}
 
Example 4
private void printOrphanCommentsEnding(final Node node) {
    List<Node> everything = new LinkedList<>();
    everything.addAll(node.getChildNodes());
    sortByBeginPosition(everything);
    if (everything.isEmpty()) {
        return;
    }

    int commentsAtEnd = 0;
    boolean findingComments = true;
    while (findingComments && commentsAtEnd < everything.size()) {
        Node last = everything.get(everything.size() - 1 - commentsAtEnd);
        findingComments = (last instanceof Comment);
        if (findingComments) {
            commentsAtEnd++;
        }
    }
    for (int i = 0; i < commentsAtEnd; i++) {
        everything.get(everything.size() - commentsAtEnd + i).accept(this, null);
    }
}
 
Example 5
Source Project: apigcc   Source File: RequestMappingHelper.java    License: MIT License 6 votes vote down vote up
/**
 * 判断是否为Rest接口
 * @param n
 * @return
 */
public static boolean isRest(MethodDeclaration n){
    if(n.isAnnotationPresent(ANNOTATION_RESPONSE_BODY)){
        return true;
    }
    Optional<Node> parentOptional = n.getParentNode();
    if(parentOptional.isPresent()){
        Node parentNode = parentOptional.get();
        if(parentNode instanceof ClassOrInterfaceDeclaration){
            if (((ClassOrInterfaceDeclaration) parentNode).isAnnotationPresent(SpringParser.ANNOTATION_REST_CONTROLLER)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 6
Source Project: Recaf   Source File: SourceCode.java    License: MIT License 6 votes vote down vote up
/**
 * Returns the AST node at the given position.
 * The child-most node may not be returned if the parent is better suited for contextual
 * purposes.
 *
 * @param line
 * 		Cursor line.
 * @param column
 * 		Cursor column.
 *
 * @return JavaParser AST node at the given position in the source code.
 */
public Node getNodeAt(int line, int column) {
	return getNodeAt(line, column, unit.findRootNode(), node -> {
		// We want to know more about this type, don't resolve down to the lowest AST
		// type... the parent has more data and is essentially just a wrapper around SimpleName.
		if (node instanceof SimpleName)
			return false;
		// Verify the node range can be accessed
		if (!node.getBegin().isPresent() || !node.getEnd().isPresent())
			return false;
		// Same as above, we want to return the node with actual context.
		if (node instanceof NameExpr)
			return false;
		// Should be fine
		return true;
	});
}
 
Example 7
Source Project: Recaf   Source File: SourceCode.java    License: MIT License 6 votes vote down vote up
private Node getNodeAt(int line, int column, Node root, Predicate<Node> filter) {
	if (!filter.test(root))
		return null;
	// Check cursor is in bounds
	// We won't instantly return null because the root range may be SMALLER than
	// the range of children. This is really stupid IMO but thats how JavaParser is...
	boolean bounds = true;
	Position cursor = Position.pos(line, column);
	if (cursor.isBefore(root.getBegin().get()) || cursor.isAfter(root.getEnd().get()))
		bounds = false;
	// Iterate over children, return non-null child
	for (Node child : root.getChildNodes()) {
		Node ret = getNodeAt(line, column, child, filter);
		if (ret != null)
			return ret;
	}
	// If we're not in bounds and none of our children are THEN we assume this node is bad.
	if (!bounds)
		return null;
	// In bounds so we're good!
	return root;
}
 
Example 8
Source Project: Recaf   Source File: JavaParserUtil.java    License: MIT License 6 votes vote down vote up
/**
 * @param code
 * 		Code wrapper.
 * @param pos
 * 		Position of caret.
 *
 * @return Node of supported type at position.
 */
private static Node getSelectedNode(SourceCode code, TwoDimensional.Position pos) {
	// Abort if no analyzed code to parse
	if (code == null)
		return null;
	// Get node at row/column
	Node node = code.getVerboseNodeAt(pos.getMajor() + 1, pos.getMinor());
	// Go up a level until node type is supported
	while(node != null) {
		if(node instanceof Resolvable || node instanceof InitializerDeclaration)
			break;
		Optional<Node> parent = node.getParentNode();
		if(!parent.isPresent())
			break;
		node = parent.get();
	}
	return node;
}
 
Example 9
Source Project: Recaf   Source File: SourceCodeTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFieldResolve() {
	// Enable advanced resolving
	workspace.analyzeSources();
	// Line 7: Two tabs then this:
	//
	// Scanner scanner = new Scanner(System.in);
	//
	SourceCode code = resource.getClassSource("Start");
	Node node = code.getNodeAt(7, 34);
	assertTrue(node instanceof FieldAccessExpr);
	FieldAccessExpr fieldExpr = (FieldAccessExpr) node;
	ResolvedFieldDeclaration dec = (ResolvedFieldDeclaration) fieldExpr.resolve();
	assertEquals("java/lang/System", getOwner(dec));
	assertEquals("in", dec.getName());
	assertEquals("Ljava/io/InputStream;", getDescriptor(dec));
}
 
Example 10
Source Project: Recaf   Source File: SourceCodeTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testMethodResolve() {
	// Enable advanced resolving
	workspace.analyzeSources();
	// Line 18: Three tabs then this:
	//
	// return new Parenthesis(i).accept(expression);
	//
	SourceCode code = resource.getClassSource("calc/Calculator");
	Node node = code.getNodeAt(18, 33);
	assertTrue(node instanceof MethodCallExpr);
	MethodCallExpr callExpr = (MethodCallExpr) node;
	ResolvedMethodDeclaration dec = callExpr.resolve();
	assertEquals("calc/Parenthesis", getOwner(dec));
	assertEquals("accept", dec.getName());
	assertEquals("(Ljava/lang/String;)D", getDescriptor(dec));
	//
	node = code.getNodeAt(44, 16);
	assertTrue(node instanceof MethodCallExpr);
	callExpr = (MethodCallExpr) node;
	dec = callExpr.resolve();
	assertEquals("java/io/PrintStream", getOwner(dec));
	assertEquals("println", dec.getName());
	assertEquals("(Ljava/lang/String;)V", getDescriptor(dec));
}
 
Example 11
Source Project: Briefness   Source File: FinalRClassBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public static void brewJava(File rFile, File outputDir, String packageName, String className, boolean useLegacyTypes) throws Exception {
  CompilationUnit compilationUnit = JavaParser.parse(rFile);
  TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);

  TypeSpec.Builder result = TypeSpec.classBuilder(className)
      .addModifiers(PUBLIC, FINAL);

  for (Node node : resourceClass.getChildNodes()) {
    if (node instanceof ClassOrInterfaceDeclaration) {
      addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node, useLegacyTypes);
    }
  }

  JavaFile finalR = JavaFile.builder(packageName, result.build())
      .addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!")
      .build();

  finalR.writeTo(outputDir);
}
 
Example 12
Source Project: Briefness   Source File: FinalRClassBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable,
                                     ClassName annotation) {
  String fieldName = variable.getNameAsString();
  String fieldValue = variable.getInitializer()
      .map(Node::toString)
      .orElseThrow(
          () -> new IllegalStateException("Field " + fieldName + " missing initializer"));
  FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName)
      .addModifiers(PUBLIC, STATIC, FINAL)
      .initializer(fieldValue);

  if (annotation != null) {
    fieldSpecBuilder.addAnnotation(annotation);
  }

  resourceType.addField(fieldSpecBuilder.build());
}
 
Example 13
Source Project: jeddict   Source File: MemberExplorer.java    License: Apache License 2.0 6 votes vote down vote up
public String getDefaultValue() {
    String defaultValue = null;
    if (field != null && field.getVariables().get(0).getChildNodes().size() == 3) {
        Node node = field.getVariables().get(0).getChildNodes().get(2);
        if (node instanceof Expression) { //FieldAccessExpr, MethodCallExpr, ObjectCreationExpr
            defaultValue = node.toString();
            Map<String, ImportDeclaration> imports = clazz.getImports();
             String importList = imports.keySet()
                     .stream()
                    .filter(defaultValue::contains)
                    .map(imports::get)
                    .map(ImportDeclaration::getNameAsString)
                    .collect(joining(" ,\n"));
            defaultValue = importList.isEmpty() ? defaultValue : "[\n" + importList + "\n]\n" + defaultValue;
        } else if (node instanceof NodeWithSimpleName) {
            defaultValue = ((NodeWithSimpleName) node).getNameAsString();
        } else if (node instanceof LiteralStringValueExpr) {
            defaultValue = "'" + ((LiteralStringValueExpr) node).getValue() + "'";
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return defaultValue;
}
 
Example 14
Source Project: jeddict   Source File: AnnotatedMember.java    License: Apache License 2.0 6 votes vote down vote up
static List<String> getStringAttributes(AnnotationExpr annotationExpr, String attributeName) {
    List<String> values = new ArrayList<>();
    Optional<Expression> expOptional = getAttribute(annotationExpr, attributeName);
    if (expOptional.isPresent()) {
        Expression expression = expOptional.get();
        if (expression.isStringLiteralExpr()) {
            values.add(expression.asStringLiteralExpr().getValue());
        } else if (expression.isArrayInitializerExpr()) {
            List<Node> nodes = expression.asArrayInitializerExpr().getChildNodes();
            for (Node node : nodes) {
                if (node instanceof StringLiteralExpr) {
                    values.add(((StringLiteralExpr) node).getValue());
                } else {
                    values.add(node.toString());
                }
            }
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return values;
}
 
Example 15
Source Project: jeddict   Source File: AnnotatedMember.java    License: Apache License 2.0 6 votes vote down vote up
static List<String> getClassNameAttributes(AnnotationExpr annotationExpr, String attributeName) {
    List<String> values = new ArrayList<>();
    Optional<Expression> expOptional = getAttribute(annotationExpr, attributeName);
    if (expOptional.isPresent()) {
        Expression expression = expOptional.get();
        if (expression.isClassExpr()) {
            values.add(expression.asClassExpr().getTypeAsString());
        } else if (expression.isArrayInitializerExpr()) {
            for (Node node : expression.asArrayInitializerExpr().getChildNodes()) {
                if (node instanceof ClassExpr) {
                    values.add(((ClassExpr) node).getTypeAsString());
                } else {
                    throw new UnsupportedOperationException();
                }
            }
        } else {
            throw new UnsupportedOperationException();
        }
    }
    return values;
}
 
Example 16
Source Project: scott   Source File: MethodBoundaryExtractor.java    License: MIT License 6 votes vote down vote up
private boolean isInTheCorrectClass(MethodDeclaration methodDeclaration) {
	Node n = methodDeclaration;
	
	String containingClassName = "";
	while (n != null) {
		if (n instanceof ClassOrInterfaceDeclaration) {
			ClassOrInterfaceDeclaration c = (ClassOrInterfaceDeclaration) n;
			containingClassName = c.getName() + "$" + containingClassName;
		}
		Optional<Node> no = n.getParentNode();
		if (no.isEmpty()) {
			n = null;
		} else {
			n = no.get();
		}
	}
	
	containingClassName = containingClassName.substring(0, containingClassName.length() - 1);
	return containingClassName.equals(className);
}
 
Example 17
Source Project: joyqueue   Source File: AutoDoc.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Write the method parameters and it's doc to target api doc
 *
 * @param doc     target doc
 * @param comment parameters and method doc
 **/
private void fillParamDoc(APIDoc doc, JavadocComment comment, StringBuilder methodDesBuilder) {
    Javadoc javadoc = comment.parse();
    toString(javadoc.getDescription(), methodDesBuilder);
    doc.setDesc(methodDesBuilder.toString());
    methodDesBuilder.setLength(0);
    List<JavadocBlockTag> tags = javadoc.getBlockTags();
    if (comment.getCommentedNode().isPresent()) {
        Node node = comment.getCommentedNode().get();
        if (node instanceof MethodDeclaration) {
            MethodDeclaration method = (MethodDeclaration) node;
            for (Parameter p : method.getParameters()) {
                String type = p.getType().asString();
                String name = p.getName().asString();
                List<Param> params = doc.getParams();
                Param param = new Param();
                param.setName(name);
                param.setType(type);
                for (JavadocBlockTag t : tags) {
                    if (t.getName().isPresent()) {
                        if (name.endsWith(t.getName().get())) {
                            toString(t.getContent(), methodDesBuilder);
                            param.setComment(methodDesBuilder.toString());
                            methodDesBuilder.setLength(0);
                        }
                    }
                }
                if (params == null) {
                    params = new ArrayList<>();
                    doc.setParams(params);
                }
                params.add(param);
            }
        }
    }
}
 
Example 18
Source Project: joyqueue   Source File: PackageDocScanParser.java    License: Apache License 2.0 5 votes vote down vote up
private static String describe(Node node) {
    if (node instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) node;
        return "Method " + methodDeclaration.getDeclarationAsString(false, false, true);
    }
    if (node instanceof ConstructorDeclaration) {
        ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) node;
        return "Constructor " + constructorDeclaration.getDeclarationAsString();
    }
    if (node instanceof ClassOrInterfaceDeclaration) {
        ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration) node;
        if (classOrInterfaceDeclaration.isInterface()) {
            return "Interface " + classOrInterfaceDeclaration.getName();
        } else {
            return "Class " + classOrInterfaceDeclaration.getName();
        }
    }
    if (node instanceof EnumDeclaration) {
        EnumDeclaration enumDeclaration = (EnumDeclaration) node;
        return "Enum " + enumDeclaration.getName();
    }
    if (node instanceof FieldDeclaration) {
        FieldDeclaration fieldDeclaration = (FieldDeclaration) node;
        List<String> varNames = fieldDeclaration.getVariables().stream().map(v -> v.getName().getId()).collect(Collectors.toList());
        return "Field " + String.join(", ", varNames);
    }
    return node.toString();
}
 
Example 19
Source Project: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the one nodes by type.
 *
 * @param <N> the number type
 * @param container the container
 * @param clazz the clazz
 * @return the one nodes by type
 */
@SuppressWarnings("unchecked")
static <N extends Node> N getOneNodesByType(Node container, Class<N> clazz) {
    for (Node child : container.getChildNodes()) {
        if (clazz.isInstance(child)) {
            return (N) child;
        }
        Node result = getOneNodesByType(child, clazz);
        if (result != null)
            return (N) result;
    }
    return null;
}
 
Example 20
Source Project: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the nodes by type.
 *
 * @param <N> the number type
 * @param container the container
 * @param clazz the clazz
 * @return the nodes by type
 */
static <N extends Node> List<N> getNodesByType(Node container, Class<N> clazz) {
    List<N> nodes = new ArrayList<N>();
    boolean find = false;
    for (Node child : container.getChildNodes()) {
        if (clazz.isInstance(child)) {
            nodes.add(clazz.cast(child));
            find = true;
        }
        if (!find) {
            nodes.addAll(getNodesByType(child, clazz));
        }
    }
    return nodes;
}
 
Example 21
Source Project: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Prints the self and children.
 *
 * @param container the container
 */
static void printSelfAndChildren(Node container) {
    GLogger.println("当前类为:" + container.getClass() + "...................");
    for (Node child : container.getChildNodes()) {
        GLogger.info("第一级子类为:" + child.getClass() + "..................." + child);
    }
    GLogger.println("打印结束");
    GLogger.println("\n\n\n");
}
 
Example 22
Source Project: stategen   Source File: ASTHelper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the field map.
 *
 * @param node the node
 * @return the field map
 */
static Map<String, String> getFieldMap(Node node) {
    Map<String, String> fieldmap = null;
    Map<String, FieldDeclaration> fieldDeclarationMap = getBodyDeclarationMap(node, FieldDeclaration.class);
    if (fieldDeclarationMap != null) {
        fieldmap = new CaseInsensitiveHashMap<String>(fieldDeclarationMap.size());
        for (String oldFieldName : fieldDeclarationMap.keySet()) {
            fieldmap.put(oldFieldName, oldFieldName);
        }
    }
    return fieldmap;
}
 
Example 23
private void printOrphanCommentsBeforeThisChildNode(final Node node) {
    if (node instanceof Comment) return;

    Node parent = node.getParentNode().orElse(null);
    if (parent == null) return;
    List<Node> everything = new LinkedList<>();
    everything.addAll(parent.getChildNodes());
    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 AssertionError("I am not a child of my parent.");
    }
    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);
    }
}
 
Example 24
Source Project: apigcc   Source File: CompilationUnitHelper.java    License: MIT License 5 votes vote down vote up
public static Optional<CompilationUnit> getCompilationUnit(Node node){
    if(node instanceof CompilationUnit){
        return Optional.of((CompilationUnit) node);
    }
    if (node.getParentNode().isPresent()){
        return getCompilationUnit(node.getParentNode().get());
    }
    return Optional.empty();
}
 
Example 25
Source Project: genDoc   Source File: ParseHelper.java    License: Apache License 2.0 5 votes vote down vote up
static Comment parseComment(Node node) {
    if (node.getComment().isPresent()) {
        Javadoc javadoc = JavaParser.parseJavadoc(node.getComment().get().getContent());
        Comment comment = new Comment();
        comment.setDescription(javadoc.getDescription().toText());

        List<JavadocBlockTag> javadocBlockTags = javadoc.getBlockTags();

        if (javadocBlockTags != null && javadocBlockTags.size() > 0) {
            List<Comment.Tag> tags = new ArrayList<Comment.Tag>();

            for (JavadocBlockTag javadocBlockTag : javadocBlockTags) {
                Comment.Tag tag = new Comment.Tag();
                tag.setTagName(javadocBlockTag.getTagName());
                tag.setName(javadocBlockTag.getName().orElse(null));
                tag.setContent(javadocBlockTag.getContent().toText());
                tags.add(tag);
            }

            comment.setTags(tags);
        }

        return comment;
    }

    return null;
}
 
Example 26
Source Project: genDoc   Source File: ParseHelper.java    License: Apache License 2.0 5 votes vote down vote up
static List<String> parseModifiers(NodeWithModifiers<? extends Node> nodeWithModifiers) {

        EnumSet<Modifier> enumSet = nodeWithModifiers.getModifiers();

        if (enumSet != null && !enumSet.isEmpty()) {
            List<String> modifierList = new ArrayList<String>();
            for (Modifier modifier : enumSet) {
                modifierList.add(modifier.asString());
            }

            return modifierList;
        }

        return null;
    }
 
Example 27
Source Project: Refactoring-Bot   Source File: RefactoringHelper.java    License: MIT License 5 votes vote down vote up
/**
 * @param methodDeclaration
 * @return parent node of the given method declaration as
 *         ClassOrInterfaceDeclaration
 * @throws IllegalStateException
 *             if no parent node is present
 */
public static ClassOrInterfaceDeclaration getClassOrInterfaceOfMethod(MethodDeclaration methodDeclaration) {
	Optional<Node> parentNode = methodDeclaration.getParentNode();
	if (parentNode.isPresent()) {
		return ((ClassOrInterfaceDeclaration) parentNode.get());
	}
	throw new IllegalStateException("MethodDeclaration expected to have a parent node.");
}
 
Example 28
Source Project: Recaf   Source File: JavaParserUtil.java    License: MIT License 5 votes vote down vote up
private static SymbolResolver getSymbolResolver(Node node) {
	if (GET_SOLVER == null)
		return null;
	try {
		return (SymbolResolver) GET_SOLVER.invoke(node);
	} catch(Throwable t) {
		return null;
	}
}
 
Example 29
Source Project: Recaf   Source File: SourceCodeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testNodeAtPos() {
	SourceCode code = resource.getClassSource("Start");
	// Line 7: Two tabs then this:
	//
	// Scanner scanner = new Scanner(System.in);
	//
	// First "Scanner" is an AST Tyoe
	Node node = code.getNodeAt(7, 5); // Scanner
	assertTrue(node instanceof ClassOrInterfaceType);
	assertEquals("Scanner", ((ClassOrInterfaceType)node).asString());
	// "scanner" is just a SimpleName, so we return the parent VariableDeclarator
	node = code.getNodeAt(7, 13); // scanner
	assertTrue(node instanceof VariableDeclarator);
	assertEquals("scanner", ((VariableDeclarator)node).getNameAsString());
	// Second "Scanner" is also an AST Type
	node = code.getNodeAt(7, 27); // Scanner
	assertTrue(node instanceof ClassOrInterfaceType);
	assertEquals("Scanner", ((ClassOrInterfaceType)node).asString());
	// "System.in" is a FieldAccessExpr
	// - "System" is a NameExpr - Field.scope
	// - "in" is a NameExpr - Field.name
	node = code.getNodeAt(7, 34); // System
	assertTrue(node instanceof FieldAccessExpr);
	assertTrue(((FieldAccessExpr)node).getScope() instanceof NameExpr);
	assertEquals("System", ((NameExpr)((FieldAccessExpr)node).getScope()).getNameAsString());
	assertEquals("in", ((FieldAccessExpr)node).getNameAsString());
}
 
Example 30
Source Project: impsort-maven-plugin   Source File: ImpSort.java    License: Apache License 2.0 5 votes vote down vote up
private static Set<Import> convertImportSection(List<Node> importSectionNodes, String eol) {
  List<Comment> recentComments = new ArrayList<>();
  LinkedHashSet<Import> allImports = new LinkedHashSet<>(importSectionNodes.size() / 2);
  for (Node node : importSectionNodes) {
    if (node instanceof Comment) {
      recentComments.add((Comment) node);
    } else if (node instanceof ImportDeclaration) {
      List<Node> thisImport = new ArrayList<>(2);
      ImportDeclaration impDecl = (ImportDeclaration) node;
      thisImport.addAll(recentComments);

      Optional<Comment> impComment = impDecl.getComment();
      if (impComment.isPresent()) {
        Comment c = impComment.get();
        if (c.getBegin().get().isBefore(impDecl.getBegin().get())) {
          thisImport.add(c);
          thisImport.add(impDecl);
        } else {
          thisImport.add(impDecl);
          thisImport.add(c);
        }
      } else {
        thisImport.add(impDecl);
      }

      recentComments.clear();
      convertAndAddImport(allImports, thisImport, eol);
    } else {
      throw new IllegalStateException("Unknown node: " + node);
    }
  }
  if (!recentComments.isEmpty()) {
    throw new IllegalStateException(
        "Unexpectedly found more orphaned comments: " + recentComments);
  }
  return allImports;
}