use of org.eclipse.jdt.core.dom.ASTVisitor in project flux by eclipse.
the class ASTNodes method getQualifiedTypeName.
/**
* Returns the (potentially qualified) name of a type, followed by array dimensions.
* Skips type arguments and type annotations.
*
* @param type a type that has a name
* @return the name, followed by array dimensions
* @since 3.10
*/
public static String getQualifiedTypeName(Type type) {
final StringBuffer buffer = new StringBuffer();
ASTVisitor visitor = new ASTVisitor() {
@Override
public boolean visit(SimpleType node) {
buffer.append(node.getName().getFullyQualifiedName());
return false;
}
@Override
public boolean visit(QualifiedType node) {
node.getQualifier().accept(this);
buffer.append('.');
buffer.append(node.getName().getIdentifier());
return false;
}
@Override
public boolean visit(NameQualifiedType node) {
buffer.append(node.getQualifier().getFullyQualifiedName());
buffer.append('.');
buffer.append(node.getName().getIdentifier());
return false;
}
@Override
public boolean visit(ParameterizedType node) {
node.getType().accept(this);
return false;
}
@Override
public void endVisit(ArrayType node) {
for (int i = 0; i < node.dimensions().size(); i++) {
// $NON-NLS-1$
buffer.append("[]");
}
}
};
type.accept(visitor);
return buffer.toString();
}
use of org.eclipse.jdt.core.dom.ASTVisitor in project eclipse-pmd by acanda.
the class SuppressWarningsQuickFix method findBodyDeclaration.
private BodyDeclaration findBodyDeclaration(final ASTNode node) {
final BodyDeclaration[] bodyDeclaration = new BodyDeclaration[1];
node.accept(new ASTVisitor() {
@Override
public boolean visit(final EnumDeclaration node) {
bodyDeclaration[0] = node;
return false;
}
@Override
public boolean visit(final TypeDeclaration node) {
bodyDeclaration[0] = node;
return false;
}
@Override
public boolean visit(final AnnotationTypeDeclaration node) {
bodyDeclaration[0] = node;
return false;
}
});
return bodyDeclaration[0];
}
use of org.eclipse.jdt.core.dom.ASTVisitor in project AutoRefactor by JnRouvignac.
the class ApplyRefactoringsJob method applyRefactoring.
/**
* Applies the cleanups provided inside the {@link AggregateASTVisitor} to
* the provided {@link ICompilationUnit}.
*
* @param document the document where the compilation unit comes from
* @param compilationUnit the compilation unit to refactor
* @param refactoring the {@link AggregateASTVisitor} to apply to the
* compilation unit
* @param options the Java project options used to compile the project
* @param monitor the progress monitor of the current job
* @param hasToSave hasToSave
* @return TextEdit
* @throws Exception if any problem occurs
*
* @see <a href=
* "http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Fguide%2Fjdt_api_manip.htm"
* >Eclipse JDT core - Manipulating Java code</a>
* @see <a href=
* "http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/workbench_cmd_menus.htm"
* > Eclipse Platform Plug-in Developer Guide > Plugging into the workbench
* > Basic workbench extension points using commands >
* org.eclipse.ui.menus</a>
* @see <a href=
* "http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html"
* >Abstract Syntax Tree > Write it down</a>
*/
public List<TextEdit> applyRefactoring(final IDocument document, final ICompilationUnit compilationUnit, final AggregateASTVisitor refactoring, final JavaProjectOptions options, final SubMonitor monitor, final boolean hasToSave) throws Exception {
// Creation of DOM/AST from a ICompilationUnit
@SuppressWarnings("deprecation") ASTParser parser = ASTParser.newParser(AST.JLS8);
int maxIterations = 100;
int iterationCount = 0;
Set<ASTVisitor> lastLoopVisitors = Collections.emptySet();
int nbLoopsWithSameVisitors = 0;
List<TextEdit> textEdits = new ArrayList<>();
monitor.setWorkRemaining(maxIterations);
CompilationUnit astRoot;
do {
// I did not find any other way to directly modify the AST
// while still keeping the resolved type bindings working.
// Using astRoot.recordModifications() did not work:
// type bindings were lost. Is there a way to recover them?
// FIXME we should find a way to apply all the changes at
// the AST level and refresh the bindings
resetParser(compilationUnit, parser, options);
astRoot = (CompilationUnit) parser.createAST(null);
if (iterationCount > maxIterations) {
// Oops! Something went wrong.
String errorMsg = // $NON-NLS-1$ //$NON-NLS-2$
"An infinite loop has been detected for file " + ASTNodes.getFileName(astRoot) + "." + // $NON-NLS-1$
" A possible cause is that code is being incorrectly" + " refactored one way then refactored back to what it was." + // $NON-NLS-1$ //$NON-NLS-2$
" Fix the code before pursuing." + getPossibleCulprits(nbLoopsWithSameVisitors, lastLoopVisitors);
environment.getLogger().error(errorMsg, new IllegalStateException(astRoot, errorMsg));
break;
}
CompilationUnitRewrite cuRewrite = new CompilationUnitRewrite(compilationUnit, astRoot, options, monitor, environment);
refactoring.setRefactoringContext(cuRewrite);
ASTRewrite refactorings = refactoring.getRefactorings(astRoot);
if (!refactorings.hasRefactorings()) {
// We are done with applying the cleanups.
break;
}
// Apply the cleanups and save the compilation unit
refactorings.applyTo(document, hasToSave);
textEdits.add(refactorings.getEdits());
if (!hasToSave) {
return textEdits;
}
boolean hadUnsavedChanges = compilationUnit.hasUnsavedChanges();
compilationUnit.getBuffer().setContents(document.get());
// , null, null);
if (!hadUnsavedChanges && hasToSave) {
compilationUnit.save(null, true);
}
iterationCount++;
Set<ASTVisitor> thisLoopVisitors = refactoring.getVisitorsContributingRefactoring();
if (thisLoopVisitors.equals(lastLoopVisitors)) {
nbLoopsWithSameVisitors++;
} else {
lastLoopVisitors = new HashSet<>(thisLoopVisitors);
nbLoopsWithSameVisitors = 0;
}
} while (true);
return textEdits;
}
use of org.eclipse.jdt.core.dom.ASTVisitor in project xtext-xtend by eclipse.
the class ASTFlattenerUtils method findDeclaredType.
private Type findDeclaredType(final ASTNode scope, final SimpleName simpleName) {
final ArrayList<Type> matchesFound = CollectionLiterals.<Type>newArrayList();
scope.accept(new ASTVisitor() {
@Override
public boolean visit(final VariableDeclarationFragment node) {
boolean _equals = node.getName().getIdentifier().equals(simpleName.getIdentifier());
if (_equals) {
final ASTNode parentNode = node.getParent();
boolean _matched = false;
if (parentNode instanceof VariableDeclarationStatement) {
_matched = true;
matchesFound.add(((VariableDeclarationStatement) parentNode).getType());
}
if (!_matched) {
if (parentNode instanceof FieldDeclaration) {
_matched = true;
matchesFound.add(((FieldDeclaration) parentNode).getType());
}
}
if (!_matched) {
if (parentNode instanceof VariableDeclarationExpression) {
_matched = true;
matchesFound.add(((VariableDeclarationExpression) parentNode).getType());
}
}
}
return false;
}
@Override
public boolean preVisit2(final ASTNode node) {
return matchesFound.isEmpty();
}
@Override
public boolean visit(final SingleVariableDeclaration node) {
boolean _equals = node.getName().getIdentifier().equals(simpleName.getIdentifier());
if (_equals) {
matchesFound.add(node.getType());
}
return false;
}
});
return IterableExtensions.<Type>head(matchesFound);
}
use of org.eclipse.jdt.core.dom.ASTVisitor in project flow by vaadin.
the class CodeTest method gwtGenerics.
private static void gwtGenerics(File file) throws IOException {
ASTParser parser = ASTParser.newParser(AST.JLS8);
String value = FileUtils.readFileToString(file, UTF_8);
parser.setSource(value.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.accept(new ASTVisitor() {
Set<String> imports = new HashSet<>();
String packageName;
@Override
public boolean visit(PackageDeclaration node) {
packageName = node.getName().toString();
return false;
}
@Override
public boolean visit(ImportDeclaration node) {
imports.add(node.getName().toString());
return false;
}
@Override
public boolean visit(VariableDeclarationStatement node) {
for (Object frament : node.fragments()) {
if (frament instanceof VariableDeclarationFragment) {
VariableDeclarationFragment variableDeclaration = (VariableDeclarationFragment) frament;
Expression expression = variableDeclaration.getInitializer();
if (expression instanceof ClassInstanceCreation) {
ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression;
Class<?> typeClass = getClass(node.getType());
Class<?> instanceClass = getClass(classInstanceCreation.getType());
if (typeClass != instanceClass && typeClass.isAssignableFrom(instanceClass)) {
fail("Variable type must be the specific implementation in " + node + " in " + file.getName());
}
}
}
}
return false;
}
private Class<?> getClass(Type type) {
if (type instanceof ArrayType) {
type = ((ArrayType) type).getElementType();
}
if (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getType();
}
String className = type.toString();
if (className.indexOf('.') == -1) {
String dotPrefix = '.' + className;
for (String i : imports) {
if (i.endsWith(dotPrefix)) {
className = i;
break;
}
}
}
Class<?> clas = getClass(className);
if (clas != null) {
return clas;
}
clas = getClass("java.lang." + className);
if (clas != null) {
return clas;
}
try {
String fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
if (fileName.equals(className)) {
return Class.forName(packageName + '.' + fileName);
}
clas = getClass(packageName + '.' + className);
if (clas != null) {
return clas;
}
return Class.forName(packageName + '.' + fileName + '$' + className);
} catch (ClassNotFoundException e) {
fail("Could not load class " + e);
return null;
}
}
private Class<?> getClass(String className) {
try {
return ClassUtils.getClass(className);
} catch (ClassNotFoundException e) {
return null;
}
}
});
}
Aggregations