org.eclipse.jdt.core.dom.ASTVisitor Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.ASTVisitor. 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 File: JunkVariableRenamer.java    From naturalize with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @param vars
 * @param entry
 * @return
 */
private Set<Integer> getCurrentlyUsedNames(
		final Multimap<ASTNode, Variable> vars,
		final Entry<ASTNode, Variable> entry) {
	// Create a list of all the names that are used in that scope
	final Set<Variable> scopeUsedNames = Sets.newHashSet();
	// Check all the parents & self
	ASTNode currentNode = entry.getKey();
	while (currentNode != null) {
		scopeUsedNames.addAll(vars.get(currentNode));
		currentNode = currentNode.getParent();
	}
	// and now add all children
	final ASTVisitor v = new ASTVisitor() {
		@Override
		public void preVisit(final ASTNode node) {
			scopeUsedNames.addAll(vars.get(node));
		}
	};
	entry.getKey().accept(v);
	// and we're done
	return getUsedIds(scopeUsedNames);
}
 
Example #2
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void updateLocalVariableDeclarations(final ASTRewrite rewrite, final Set<String> variables, Block block) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(block);
    Assert.isNotNull(variables);

    final AST ast = rewrite.getAST();
    block.accept(new ASTVisitor() {

        @Override
        public boolean visit(VariableDeclarationFragment fragment) {
            if (variables.contains(fragment.getName().getFullyQualifiedName())) {
                ASTNode parent = fragment.getParent();
                if (parent instanceof VariableDeclarationStatement) {
                    ListRewrite listRewrite = rewrite
                            .getListRewrite(parent, VariableDeclarationStatement.MODIFIERS2_PROPERTY);
                    listRewrite.insertLast(ast.newModifier(ModifierKeyword.FINAL_KEYWORD), null);
                }
            }
            return true;
        }

    });

}
 
Example #3
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Set<String> findVariableReferences(List<?> arguments) {
    final Set<String> refs = new HashSet<>();
    for (Object argumentObj : arguments) {
        Expression argument = (Expression) argumentObj;
        argument.accept(new ASTVisitor() {

            @Override
            public boolean visit(SimpleName node) {
                if (!(node.getParent() instanceof Type)) {
                    refs.add(node.getFullyQualifiedName());
                }
                return true;
            }

        });
    }
    return refs;
}
 
Example #4
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Nonnull
private String findLabelReplacement(ASTVisitor labelFixingVisitor) {
    IMarker marker = getMarker();
    try {
        ASTNode node = getNodeForMarker(marker);
        if (node != null) {
            node.accept(labelFixingVisitor);
            String retVal = ((CustomLabelVisitor) labelFixingVisitor).getLabelReplacement();
            return retVal == null ? DEFAULT_REPLACEMENT : retVal;
        }
        // Catch all exceptions (explicit) so that the label creation won't fail
        // FindBugs prefers this being explicit instead of just catching Exception
    } catch (JavaModelException | ASTNodeNotFoundException | RuntimeException e) {
        FindbugsPlugin.getDefault().logException(e, e.getLocalizedMessage());
        return DEFAULT_REPLACEMENT;
    }
    return DEFAULT_REPLACEMENT;
}
 
Example #5
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean findApplicability(ASTVisitor prescanVisitor, IMarker marker) {
    try {
        ASTNode node = getNodeForMarker(marker);
        if (node != null) {
            node.accept(prescanVisitor);
            //this cast is safe because isApplicable checks the type before calling
            return ((ApplicabilityVisitor) prescanVisitor).isApplicable();
        }
        // Catch all exceptions (explicit) so that applicability check won't fail
        // FindBugs prefers this being explicit instead of just catching Exception
    } catch (JavaModelException | ASTNodeNotFoundException | RuntimeException e) {
        FindbugsPlugin.getDefault().logException(e, e.getLocalizedMessage());
        return true;
    }
    return true;
}
 
Example #6
Source File: UncommentedMainQuickFix.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
    return new ASTVisitor() {

        @Override
        public boolean visit(MethodDeclaration node) {
            // recalculate start position because optional javadoc is mixed
            // into the original start position
            final int pos = node.getStartPosition() +
                    (node.getJavadoc() != null ? node.getJavadoc().getLength() + JAVADOC_COMMENT_LENGTH : 0);
            if (containsPosition(lineInfo, pos) && node.getName().getFullyQualifiedName().equals("main")) {
                node.delete();
            }
            return true;
        }
    };
}
 
Example #7
Source File: UpperEllQuickFix.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
    return new ASTVisitor() {

        @Override
        public boolean visit(NumberLiteral node) {
            if (containsPosition(node, markerStartOffset)) {

                String token = node.getToken();
                if (token.endsWith("l")) { //$NON-NLS-1$
                    token = token.replace('l', 'L');
                    node.setToken(token);
                }
            }
            return true;
        }
    };
}
 
Example #8
Source File: FinalParametersQuickFix.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
    return new ASTVisitor() {

        @SuppressWarnings("unchecked")
        @Override
        public boolean visit(SingleVariableDeclaration node) {
            if (containsPosition(node, markerStartOffset) && !Modifier.isFinal(node.getModifiers())) {
                if (!Modifier.isFinal(node.getModifiers())) {
                    final Modifier finalModifier = node.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD);
                    node.modifiers().add(finalModifier);
                }
            }
            return true;
        }
    };
}
 
Example #9
Source File: MissingSwitchDefaultQuickFix.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
    return new ASTVisitor() {

        @SuppressWarnings("unchecked")
        @Override
        public boolean visit(SwitchStatement node) {
            if (containsPosition(lineInfo, node.getStartPosition())) {
                final SwitchCase defNode = node.getAST().newSwitchCase();
                defNode.setExpression(null);
                node.statements().add(defNode);
                node.statements().add(node.getAST().newBreakStatement());
            }
            return true; // also visit children
        }
    };
}
 
Example #10
Source File: EmptyStatementQuickFix.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
    return new ASTVisitor() {
        @Override
        public boolean visit(EmptyStatement node) {
            if (containsPosition(lineInfo, node.getStartPosition())) {

                // early exit if the statement is mandatory, e.g. only
                // statement in a for-statement without block
                final StructuralPropertyDescriptor p = node.getLocationInParent();
                if (p.isChildProperty() && ((ChildPropertyDescriptor) p).isMandatory()) {
                    return false;
                }

                node.delete();
            }
            return false;
        }
    };
}
 
Example #11
Source File: EquivalentNodeFinder.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds the equivalent AST node, or null if one could not be found.
 */
public ASTNode find() {
  final ASTNode foundNode[] = new ASTNode[1];
  newAncestorNode.accept(new ASTVisitor(true) {
    @Override
    public void preVisit(ASTNode visitedNode) {
      if (foundNode[0] != null) {
        // Already found a result, do not search further
        return;
      }

      if (!treesMatch(originalNode, visitedNode, ancestorNode,
          newAncestorNode, matcher)) {
        // Keep searching
        return;
      }

      foundNode[0] = visitedNode;

      // We are done
    }
  });

  return foundNode[0];
}
 
Example #12
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean replaceMarker(final ASTRewrite rewrite, final Expression qualifier, Expression assignedValue, final NullLiteral marker) {
	class MarkerReplacer extends ASTVisitor {

		private boolean fReplaced= false;

		@Override
		public boolean visit(NullLiteral node) {
			if (node == marker) {
				rewrite.replace(node, rewrite.createCopyTarget(qualifier), null);
				fReplaced= true;
				return false;
			}
			return true;
		}
	}
	if (assignedValue != null && qualifier != null) {
		MarkerReplacer visitor= new MarkerReplacer();
		assignedValue.accept(visitor);
		return visitor.fReplaced;
	}
	return false;
}
 
Example #13
Source File: UncommentedMainQuickfix.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
        final int markerStartOffset) {
  return new ASTVisitor() {

    @Override
    public boolean visit(MethodDeclaration node) {
      // recalculate start position because optional javadoc is mixed
      // into the original start position
      int pos = node.getStartPosition() + (node.getJavadoc() != null
              ? node.getJavadoc().getLength() + JAVADOC_COMMENT_LENGTH
              : 0);
      if (containsPosition(lineInfo, pos)
              && node.getName().getFullyQualifiedName().equals("main")) {
        node.delete();
      }
      return true;
    }
  };
}
 
Example #14
Source File: FinalParametersQuickfix.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
        final int markerStartOffset) {
  return new ASTVisitor() {

    @SuppressWarnings("unchecked")
    @Override
    public boolean visit(SingleVariableDeclaration node) {
      if (containsPosition(node, markerStartOffset) && !Modifier.isFinal(node.getModifiers())) {
        if (!Modifier.isFinal(node.getModifiers())) {
          Modifier finalModifier = node.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD);
          node.modifiers().add(finalModifier);
        }
      }
      return true;
    }
  };
}
 
Example #15
Source File: UpperEllQuickfix.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
        final int markerStartOffset) {
  return new ASTVisitor() {

    @Override
    public boolean visit(NumberLiteral node) {
      if (containsPosition(node, markerStartOffset)) {

        String token = node.getToken();
        if (token.endsWith("l")) { //$NON-NLS-1$
          token = token.replace('l', 'L');
          node.setToken(token);
        }
      }
      return true;
    }
  };
}
 
Example #16
Source File: MissingSwitchDefaultQuickfix.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
        final int markerStartOffset) {

  return new ASTVisitor() {

    @SuppressWarnings("unchecked")
    @Override
    public boolean visit(SwitchStatement node) {
      if (containsPosition(lineInfo, node.getStartPosition())) {
        SwitchCase defNode = node.getAST().newSwitchCase();
        defNode.setExpression(null);
        node.statements().add(defNode);
        node.statements().add(node.getAST().newBreakStatement());
      }
      return true; // also visit children
    }
  };
}
 
Example #17
Source File: EmptyStatementQuickfix.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
        final int markerStartPosition) {

  return new ASTVisitor() {
    @Override
    public boolean visit(EmptyStatement node) {
      if (containsPosition(lineInfo, node.getStartPosition())) {

        // early exit if the statement is mandatory, e.g. only
        // statement in a for-statement without block
        StructuralPropertyDescriptor p = node.getLocationInParent();
        if (p.isChildProperty() && ((ChildPropertyDescriptor) p).isMandatory()) {
          return false;
        }

        node.delete();
      }
      return false;
    }
  };
}
 
Example #18
Source File: ExplicitInitializationQuickfix.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
        final int markerStartOffset) {
  return new ASTVisitor() {

    @Override
    public boolean visit(final VariableDeclarationFragment node) {
      if (containsPosition(node, markerStartOffset)) {
        node.getInitializer().delete();
      }
      return false;
    }

  };
}
 
Example #19
Source File: MethodLimitQuickfix.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
    final int markerStartOffset) {

  return new ASTVisitor() {

    @SuppressWarnings("unchecked")
    public boolean visit(MethodDeclaration node) {

      Javadoc doc = node.getJavadoc();

      if (doc == null) {
        doc = node.getAST().newJavadoc();
        node.setJavadoc(doc);
      }

      TagElement newTag = node.getAST().newTagElement();
      newTag.setTagName("TODO Added by MethodLimit Sample quickfix");

      doc.tags().add(0, newTag);

      return true;
    }
  };
}
 
Example #20
Source File: AccessorClassModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ASTNode findField(ASTNode astRoot, final String name) {

		class STOP_VISITING extends RuntimeException {
			private static final long serialVersionUID= 1L;
		}

		final ASTNode[] result= new ASTNode[1];

		try {
			astRoot.accept(new ASTVisitor() {

				@Override
				public boolean visit(VariableDeclarationFragment node) {
					if (name.equals(node.getName().getFullyQualifiedName())) {
						result[0]= node.getParent();
						throw new STOP_VISITING();
					}
					return true;
				}
			});
		} catch (STOP_VISITING ex) {
			// stop visiting AST
		}

		return result[0];
	}
 
Example #21
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static SimpleName getLeftMostSimpleName(Name name) {
	if (name instanceof SimpleName) {
		return (SimpleName)name;
	} else {
		final SimpleName[] result= new SimpleName[1];
		ASTVisitor visitor= new ASTVisitor() {
			@Override
			public boolean visit(QualifiedName qualifiedName) {
				Name left= qualifiedName.getQualifier();
				if (left instanceof SimpleName)
					result[0]= (SimpleName)left;
				else
					left.accept(this);
				return false;
			}
		};
		name.accept(visitor);
		return result[0];
	}
}
 
Example #22
Source File: IntroduceParameterObjectProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void updateBody(MethodDeclaration methodDeclaration, final CompilationUnitRewrite cuRewrite, RefactoringStatus result) throws CoreException {
	// ensure that the parameterObject is imported
	fParameterObjectFactory.createType(fCreateAsTopLevel, cuRewrite, methodDeclaration.getStartPosition());
	if (cuRewrite.getCu().equals(getCompilationUnit()) && !fParameterClassCreated) {
		createParameterClass(methodDeclaration, cuRewrite);
		fParameterClassCreated= true;
	}
	Block body= methodDeclaration.getBody();
	final List<SingleVariableDeclaration> parameters= methodDeclaration.parameters();
	if (body != null) { // abstract methods don't have bodies
		final ASTRewrite rewriter= cuRewrite.getASTRewrite();
		ListRewrite bodyStatements= rewriter.getListRewrite(body, Block.STATEMENTS_PROPERTY);
		List<ParameterInfo> managedParams= getParameterInfos();
		for (Iterator<ParameterInfo> iter= managedParams.iterator(); iter.hasNext();) {
			final ParameterInfo pi= iter.next();
			if (isValidField(pi)) {
				if (isReadOnly(pi, body, parameters, null)) {
					body.accept(new ASTVisitor(false) {

						@Override
						public boolean visit(SimpleName node) {
							updateSimpleName(rewriter, pi, node, parameters, cuRewrite.getCu().getJavaProject());
							return false;
						}

					});
					pi.setInlined(true);
				} else {
					ExpressionStatement initializer= fParameterObjectFactory.createInitializer(pi, getParameterName(), cuRewrite);
					bodyStatements.insertFirst(initializer, null);
				}
			}
		}
	}


}
 
Example #23
Source File: CodeLineBreakPreparator.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(int kind, TokenManager tokenManager, ASTNode astRoot) {
	if ((kind & CodeFormatter.K_COMPILATION_UNIT) != 0) {
		ASTVisitor visitor = new Vistor(tokenManager);
		astRoot.accept(visitor);
	}
}
 
Example #24
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void collectRefrencedVariables(ASTNode root, final Set<IBinding> result) {
 	root.accept(new ASTVisitor() {
         @Override
public boolean visit(SimpleName node) {
             IBinding binding= node.resolveBinding();
             if (binding instanceof IVariableBinding)
             	result.add(binding);
             return true;
         }
     });
 }
 
Example #25
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static TypeDeclaration findTypeDeclaration(CompilationUnit unit,
    String qualifiedTypeName) {
  final List<TypeDeclaration> typeDeclarations = new ArrayList<TypeDeclaration>();
  unit.accept(new ASTVisitor() {
    @Override
    public boolean visit(TypeDeclaration node) {
      typeDeclarations.add(node);
      return true;
    }
  });

  return findTypeDeclaration(typeDeclarations, qualifiedTypeName);
}
 
Example #26
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * If getApplicabilityVisitor() is overwritten, this checks
 * to see if this resolution applies to the code at the given marker.
 *
 * @param marker
 * @return true if this resolution should be visible to the user at the given marker
 */
public boolean isApplicable(IMarker marker) {
    ASTVisitor prescanVisitor = getApplicabilityVisitor();
    if (prescanVisitor instanceof ApplicabilityVisitor) { //this has an implicit null check
        return findApplicability(prescanVisitor, marker);
    }
    return true;
}
 
Example #27
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the short label that briefly describes the change that will be made.
 *
 * Typically, labels are static and defined in <code>plugin.xml</code>.
 * For runtime-computed labels, define a base label in plugin.xml using the
 * <code>PLACEHOLDER_STRING</code> "YYY" where any custom text should go.  Then,
 * override getLabelFixingVisitor() to scan the code and find the text to replace
 * the placeholder.
 *
 * The visitor is only used to scan once, the result being cached on subsequent visits.
 */
@Override
@Nonnull
public String getLabel() {
    ASTVisitor labelFixingVisitor = getCustomLabelVisitor();
    if (labelFixingVisitor instanceof CustomLabelVisitor) {
        if (customizedLabel == null) {
            String labelReplacement = findLabelReplacement(labelFixingVisitor);
            customizedLabel = label.replace(BugResolution.PLACEHOLDER_STRING, labelReplacement);
        }
        return customizedLabel;
    }
    return label;
}
 
Example #28
Source File: CallerFinder.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a collection of return statements withing @param methodDeclaration.
 * */
public static Collection<ReturnStatement> findReturns(IProgressMonitor progressMonitor, MethodDeclaration methodDeclaration, JavaProject project) {
	progressMonitor.setTaskName("Looking for returns in " + methodDeclaration.getName());
	final Collection<ReturnStatement> returns = new ArrayList<ReturnStatement>();
	ASTVisitor finder = new ASTVisitor() {			
		public boolean visit(ReturnStatement node) {
			return returns.add(node);
		}
	};
	
	methodDeclaration.accept(finder);
	return returns;
}
 
Example #29
Source File: Instrument.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public static boolean execute(String path, ASTVisitor visitor) {
	if (path == null || path.length() <= 1) {
		LevelLogger.error(__name__ + "#execute illegal input file : " + path);
		return false;
	}
	File file = new File(path);
	if (!file.exists()) {
		LevelLogger.error(__name__ + "#execute input file not exist : " + path);
		return false;
	}
	List<File> fileList = new ArrayList<>();
	if (file.isDirectory()) {
		fileList = JavaFile.ergodic(file, fileList);
	} else if (file.isFile()) {
		fileList.add(file);
	} else {
		LevelLogger.error(
				__name__ + "#execute input file is neither a file nor directory : " + file.getAbsolutePath());
		return false;
	}

	for (File f : fileList) {
		CompilationUnit unit = JavaFile.genASTFromFile(f);
		if (unit == null || unit.toString().trim().length() < 1) {
			continue;
		}
		unit.accept(visitor);
		JavaFile.writeStringToFile(f, unit.toString());
	}
	return true;
}
 
Example #30
Source File: DesignForExtensionQuickFix.java    From vscode-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
    return new ASTVisitor() {

        @SuppressWarnings("unchecked")
        @Override
        public boolean visit(MethodDeclaration node) {
            // recalculate start position because optional javadoc is mixed
            // into the original start position
            final int pos = node.getStartPosition() +
                    (node.getJavadoc() != null ? node.getJavadoc().getLength() + JAVADOC_COMMENT_LENGTH : 0);
            if (containsPosition(lineInfo, pos)) {

                if (!Modifier.isFinal(node.getModifiers())) {

                    final Modifier finalModifier = node.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD);
                    node.modifiers().add(finalModifier);

                    // reorder modifiers into their correct order
                    final List<ASTNode> reorderedModifiers = ModifierOrderQuickFix
                            .reorderModifiers(node.modifiers());
                    node.modifiers().clear();
                    node.modifiers().addAll(reorderedModifiers);
                }
            }
            return true;
        }
    };
}