下面列出了怎么用org.eclipse.jdt.core.dom.ASTVisitor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* {@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;
}
};
}
/**
* {@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;
}
};
}
/**
* {@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;
}
};
}
/**
* {@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
}
};
}
/**
* {@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;
}
};
}
/**
* {@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;
}
};
}
/**
* {@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;
}
};
}
/**
* createMarkerVisitor Creates the Visitor that goes through the unit and sets the Marker based on a case, which is currently hard coded as cypher.getinstance('AES').
*
* @param unit Unit from getUnitForParser
* @param cu same as unit but different type
* @return visitor for the unit
*/
private ASTVisitor createMarkerVisitor(final ICompilationUnit unit, final CompilationUnit cu) {
final ASTVisitor visitor = new ASTVisitor() {
@Override
public boolean visit(final MethodInvocation node) {
final int lineNumber = cu.getLineNumber(node.getStartPosition()) - 1;
if ("getInstance".equals(node.getName().toString()) && "Cipher".equals(node.getExpression().toString())) {
final List<Expression> l = node.arguments();
if (!l.isEmpty()) {
if ("AES".equals(l.get(0).resolveConstantExpressionValue()) && l.size() == 1) {
addMarker(unit.getResource(), "Error found", lineNumber, node.getStartPosition(), node.getStartPosition() + node.getLength());
}
}
}
return true;
}
};
return visitor;
}
@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;
}
};
}
@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
}
};
}
@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;
}
};
}
@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;
}
};
}
@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;
}
};
}
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;
}
});
}
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;
}
@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;
}
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;
}
/**
* 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];
}
/**
* @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);
}
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;
}
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];
}
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];
}
}
/**
* 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;
}
@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);
}
}
@Override
public void apply(int kind, TokenManager tokenManager, ASTNode astRoot) {
if ((kind & CodeFormatter.F_INCLUDE_COMMENTS) != 0) {
ASTVisitor visitor = new Vistor(tokenManager);
for (Comment comment : getComments(astRoot)) {
comment.accept(visitor);
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
final 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
int pos = node.getStartPosition() + (node.getJavadoc() != null
? node.getJavadoc().getLength() + JAVADOC_COMMENT_LENGTH
: 0);
if (containsPosition(lineInfo, pos)) {
if (!Modifier.isFinal(node.getModifiers())) {
Modifier finalModifier = node.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD);
node.modifiers().add(finalModifier);
// reorder modifiers into their correct order
List<ASTNode> reorderedModifiers = ModifierOrderQuickfix.reOrderModifiers(node.modifiers());
node.modifiers().clear();
node.modifiers().addAll(reorderedModifiers);
}
}
return true;
}
};
}
/**
* {@inheritDoc}
*/
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo,
final int markerStartOffset) {
return new ASTVisitor() {
@SuppressWarnings("unchecked")
@Override
public boolean visit(TypeDeclaration 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)) {
if (!Modifier.isFinal(node.getModifiers())) {
Modifier finalModifier = node.getAST().newModifier(ModifierKeyword.FINAL_KEYWORD);
node.modifiers().add(finalModifier);
// reorder modifiers into their correct order
List<?> reorderedModifiers = ModifierOrderQuickfix.reOrderModifiers(node.modifiers());
node.modifiers().clear();
node.modifiers().addAll(reorderedModifiers);
}
}
return true;
}
};
}
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
return new ASTVisitor() {
@Override
public boolean visit(final VariableDeclarationFragment node) {
if (containsPosition(node, markerStartOffset)) {
node.getInitializer().delete();
}
return false;
}
};
}
@Override
public ASTVisitor getCorrectingASTVisitor(IRegion lineInfo, int markerStartOffset) {
return new ASTVisitor() {
@SuppressWarnings("unchecked")
@Override
public boolean visit(TypeDeclaration 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<?> reorderedModifiers = ModifierOrderQuickFix.reorderModifiers(node.modifiers());
node.modifiers().clear();
node.modifiers().addAll(reorderedModifiers);
}
}
return true;
}
};
}
@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;
}
};
}