List of usage examples for org.eclipse.jdt.core.dom ASTNode getAST
public final AST getAST()
From source file:at.bestsolution.fxide.jdt.corext.dom.ASTFlattener.java
License:Open Source License
public static String asString(ASTNode node) { Assert.isTrue(node.getAST().apiLevel() == ASTProvider.SHARED_AST_LEVEL); ASTFlattener flattener = new ASTFlattener(); node.accept(flattener);/*from w w w .j ava2 s . c o m*/ return flattener.getResult(); }
From source file:ch.acanda.eclipse.pmd.java.resolution.SuppressWarningsQuickFix.java
License:Open Source License
@Override protected boolean apply(final ASTNode node) { final ASTNode annotatableNode = findAnnotatableASTNode(node); if (annotatableNode != null) { final AST ast = node.getAST(); final List<IExtendedModifier> modifiers = getModifiers(annotatableNode); final Annotation existingAnnotation = findExistingSuppressWarningsAnnotation(modifiers); final Annotation annotation = createReplacementSuppressWarningsAnnotation(existingAnnotation, ast); if (existingAnnotation == null) { final int position = findPosition(modifiers); modifiers.add(position, annotation); } else {/*from w w w . j av a 2 s . c om*/ ASTUtil.replace(existingAnnotation, annotation); } return !annotation.equals(existingAnnotation); } return false; }
From source file:ch.acanda.eclipse.pmd.java.resolution.TextEditQuickFixTestCase.java
License:Open Source License
@Test public void apply() throws MalformedTreeException, BadLocationException, JavaModelException { final ASTRewriteQuickFix<ASTNode> quickFix = getQuickFix(); final org.eclipse.jface.text.Document document = new org.eclipse.jface.text.Document(params.source); final CompilationUnit ast = createAST(document); final ASTNode node = findNode(params, ast, quickFix); final ASTRewrite rewrite = ASTRewrite.create(node.getAST()); final boolean isSuccessful = quickFix.rewrite(node, rewrite); assertTrue("The quick fix should be able to successfully rewrite", isSuccessful); rewrite.rewriteAST(document, getOptions()).apply(document); final String actual = document.get(); assertEquals("Result of applying the quick fix " + quickFix.getClass().getSimpleName() + " to the test " + params.name, params.expectedSource, actual); }
From source file:com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring.java
License:Open Source License
/** * Computes the changes to be made to Java file(s) and returns a list of {@link Change}. * <p/>/*from w w w . jav a2s . c o m*/ * This function scans a Java compilation unit using {@link ReplaceStringsVisitor}, looking * for a string literal equals to <code>tokenString</code>. * If found, a change is made to replace each occurrence of <code>tokenString</code> by * a piece of Java code that somehow accesses R.string.<code>xmlStringId</code>. * * @param unit The compilated unit to process. Must not be null. * @param tokenString The string to find. Must not be null or empty. * @param status Status used to report fatal errors. * @param monitor Used to log progress. */ private List<Change> computeJavaChanges(ICompilationUnit unit, String xmlStringId, String tokenString, RefactoringStatus status, SubMonitor monitor) { // We shouldn't be trying to replace a null or empty string. assert tokenString != null && tokenString.length() > 0; if (tokenString == null || tokenString.length() == 0) { return null; } // Get the Android package name from the Android Manifest. We need it to create // the FQCN of the R class. String packageName = null; String error = null; IResource manifestFile = mProject.findMember(SdkConstants.FN_ANDROID_MANIFEST_XML); if (manifestFile == null || manifestFile.getType() != IResource.FILE) { error = "File not found"; } else { ManifestData manifestData = AndroidManifestHelper.parseForData((IFile) manifestFile); if (manifestData == null) { error = "Invalid content"; } else { packageName = manifestData.getPackage(); if (packageName == null) { error = "Missing package definition"; } } } if (error != null) { status.addFatalError(String.format("Failed to parse file %1$s: %2$s.", manifestFile == null ? "" : manifestFile.getFullPath(), //$NON-NLS-1$ error)); return null; } // Right now the changes array will contain one TextFileChange at most. ArrayList<Change> changes = new ArrayList<Change>(); // This is the unit that will be modified. TextFileChange change = new TextFileChange(getName(), (IFile) unit.getResource()); change.setTextType("java"); //$NON-NLS-1$ // Create an AST for this compilation unit ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(unit.getJavaProject()); parser.setSource(unit); parser.setResolveBindings(true); ASTNode node = parser.createAST(monitor.newChild(1)); // The ASTNode must be a CompilationUnit, by design if (!(node instanceof CompilationUnit)) { status.addFatalError(String.format("Internal error: ASTNode class %s", //$NON-NLS-1$ node.getClass())); return null; } // ImportRewrite will allow us to add the new type to the imports and will resolve // what the Java source must reference, e.g. the FQCN or just the simple name. ImportRewrite importRewrite = ImportRewrite.create((CompilationUnit) node, true); String Rqualifier = packageName + ".R"; //$NON-NLS-1$ Rqualifier = importRewrite.addImport(Rqualifier); // Rewrite the AST itself via an ASTVisitor AST ast = node.getAST(); ASTRewrite astRewrite = ASTRewrite.create(ast); ArrayList<TextEditGroup> astEditGroups = new ArrayList<TextEditGroup>(); ReplaceStringsVisitor visitor = new ReplaceStringsVisitor(ast, astRewrite, astEditGroups, tokenString, Rqualifier, xmlStringId); node.accept(visitor); // Finally prepare the change set try { MultiTextEdit edit = new MultiTextEdit(); // Create the edit to change the imports, only if anything changed TextEdit subEdit = importRewrite.rewriteImports(monitor.newChild(1)); if (subEdit.hasChildren()) { edit.addChild(subEdit); } // Create the edit to change the Java source, only if anything changed subEdit = astRewrite.rewriteAST(); if (subEdit.hasChildren()) { edit.addChild(subEdit); } // Only create a change set if any edit was collected if (edit.hasChildren()) { change.setEdit(edit); // Create TextEditChangeGroups which let the user turn changes on or off // individually. This must be done after the change.setEdit() call above. for (TextEditGroup editGroup : astEditGroups) { TextEditChangeGroup group = new TextEditChangeGroup(change, editGroup); if (editGroup instanceof EnabledTextEditGroup) { group.setEnabled(((EnabledTextEditGroup) editGroup).isEnabled()); } change.addTextEditChangeGroup(group); } changes.add(change); } monitor.worked(1); if (changes.size() > 0) { return changes; } } catch (CoreException e) { // ImportRewrite.rewriteImports failed. status.addFatalError(e.getMessage()); } return null; }
From source file:com.android.ide.eclipse.adt.refactorings.extractstring.ExtractStringRefactoring.java
License:Open Source License
/** * Computes the changes to be made to Java file(s) and returns a list of {@link Change}. */// w w w . ja v a 2 s.c om private List<Change> computeJavaChanges(ICompilationUnit unit, String xmlStringId, String tokenString, RefactoringStatus status, SubMonitor subMonitor) { // Get the Android package name from the Android Manifest. We need it to create // the FQCN of the R class. String packageName = null; String error = null; IResource manifestFile = mProject.findMember(AndroidConstants.FN_ANDROID_MANIFEST); if (manifestFile == null || manifestFile.getType() != IResource.FILE) { error = "File not found"; } else { try { AndroidManifestParser manifest = AndroidManifestParser.parseForData((IFile) manifestFile); if (manifest == null) { error = "Invalid content"; } else { packageName = manifest.getPackage(); if (packageName == null) { error = "Missing package definition"; } } } catch (CoreException e) { error = e.getLocalizedMessage(); } } if (error != null) { status.addFatalError( String.format("Failed to parse file %1$s: %2$s.", manifestFile.getFullPath(), error)); return null; } // TODO in a future version we might want to collect various Java files that // need to be updated in the same project and process them all together. // To do that we need to use an ASTRequestor and parser.createASTs, kind of // like this: // // ASTRequestor requestor = new ASTRequestor() { // @Override // public void acceptAST(ICompilationUnit sourceUnit, CompilationUnit astNode) { // super.acceptAST(sourceUnit, astNode); // // TODO process astNode // } // }; // ... // parser.createASTs(compilationUnits, bindingKeys, requestor, monitor) // // and then add multiple TextFileChange to the changes arraylist. // Right now the changes array will contain one TextFileChange at most. ArrayList<Change> changes = new ArrayList<Change>(); // This is the unit that will be modified. TextFileChange change = new TextFileChange(getName(), (IFile) unit.getResource()); change.setTextType("java"); //$NON-NLS-1$ // Create an AST for this compilation unit ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setProject(unit.getJavaProject()); parser.setSource(unit); parser.setResolveBindings(true); ASTNode node = parser.createAST(subMonitor.newChild(1)); // The ASTNode must be a CompilationUnit, by design if (!(node instanceof CompilationUnit)) { status.addFatalError(String.format("Internal error: ASTNode class %s", //$NON-NLS-1$ node.getClass())); return null; } // ImportRewrite will allow us to add the new type to the imports and will resolve // what the Java source must reference, e.g. the FQCN or just the simple name. ImportRewrite importRewrite = ImportRewrite.create((CompilationUnit) node, true); String Rqualifier = packageName + ".R"; //$NON-NLS-1$ Rqualifier = importRewrite.addImport(Rqualifier); // Rewrite the AST itself via an ASTVisitor AST ast = node.getAST(); ASTRewrite astRewrite = ASTRewrite.create(ast); ArrayList<TextEditGroup> astEditGroups = new ArrayList<TextEditGroup>(); ReplaceStringsVisitor visitor = new ReplaceStringsVisitor(ast, astRewrite, astEditGroups, tokenString, Rqualifier, xmlStringId); node.accept(visitor); // Finally prepare the change set try { MultiTextEdit edit = new MultiTextEdit(); // Create the edit to change the imports, only if anything changed TextEdit subEdit = importRewrite.rewriteImports(subMonitor.newChild(1)); if (subEdit.hasChildren()) { edit.addChild(subEdit); } // Create the edit to change the Java source, only if anything changed subEdit = astRewrite.rewriteAST(); if (subEdit.hasChildren()) { edit.addChild(subEdit); } // Only create a change set if any edit was collected if (edit.hasChildren()) { change.setEdit(edit); // Create TextEditChangeGroups which let the user turn changes on or off // individually. This must be done after the change.setEdit() call above. for (TextEditGroup editGroup : astEditGroups) { change.addTextEditChangeGroup(new TextEditChangeGroup(change, editGroup)); } changes.add(change); } // TODO to modify another Java source, loop back to the creation of the // TextFileChange and accumulate in changes. Right now only one source is // modified. if (changes.size() > 0) { return changes; } subMonitor.worked(1); } catch (CoreException e) { // ImportRewrite.rewriteImports failed. status.addFatalError(e.getMessage()); } return null; }
From source file:com.codenvy.ide.ext.java.server.dom.ASTFlattener.java
License:Open Source License
public static String asString(ASTNode node) { Assert.isTrue(node.getAST().apiLevel() == AST.JLS8); ASTFlattener flattener = new ASTFlattener(); node.accept(flattener);/*from w ww . j a v a2 s.c om*/ return flattener.getResult(); }
From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaAbstractAstNodeModelAdapter.java
License:Open Source License
@Override public Object createChildOnContainmentFeature(Object element, Object feature, Object correspondingChild) { if (AstCacheCodePackage.eINSTANCE.getModifiableElement_Modifiers().equals(feature)) { if (!(element instanceof BodyDeclaration || element instanceof SingleVariableDeclaration)) { return null; } else {/*from w w w .j a v a 2s. co m*/ IExtendedModifier extendedModifier = null; if (correspondingChild instanceof com.crispico.flower.mp.model.astcache.code.Modifier) { ASTNode parent = (ASTNode) element; AST ast = parent.getAST(); com.crispico.flower.mp.model.astcache.code.Modifier modifier = (com.crispico.flower.mp.model.astcache.code.Modifier) correspondingChild; extendedModifier = ast.newModifier(Modifier.ModifierKeyword.fromFlagValue(modifier.getType())); if (parent instanceof BodyDeclaration) { ((BodyDeclaration) parent).modifiers().add(extendedModifier); } else { ((SingleVariableDeclaration) parent).modifiers().add(extendedModifier); } } if (correspondingChild instanceof com.crispico.flower.mp.model.astcache.code.Annotation) { ASTNode parent = (ASTNode) element; AST ast = parent.getAST(); com.crispico.flower.mp.model.astcache.code.Annotation annotation = (com.crispico.flower.mp.model.astcache.code.Annotation) correspondingChild; if (annotation.getValues().size() == 0) { MarkerAnnotation markerAnnotation = ast.newMarkerAnnotation(); extendedModifier = markerAnnotation; } if (annotation.getValues().size() == 1) { SingleMemberAnnotation singleMemberAnnotation = ast.newSingleMemberAnnotation(); extendedModifier = singleMemberAnnotation; } else { NormalAnnotation normalAnnotation = ast.newNormalAnnotation(); extendedModifier = normalAnnotation; } if (parent instanceof BodyDeclaration) { ((BodyDeclaration) parent).modifiers().add(extendedModifier); } else { ((SingleVariableDeclaration) parent).modifiers().add(extendedModifier); } } return extendedModifier; } } return null; }
From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaAnnotationModelAdapter.java
License:Open Source License
@Override public Object createChildOnContainmentFeature(Object element, Object feature, Object correspondingChild) { if (AstCacheCodePackage.eINSTANCE.getAnnotation_Values().equals(feature)) { ASTNode child = null;/*from ww w . j a va2s .co m*/ ASTNode parent = (ASTNode) element; AST ast = parent.getAST(); // for an existing NormalAnnotation, just add the new value if (parent instanceof NormalAnnotation) { MemberValuePair pair = ast.newMemberValuePair(); ((NormalAnnotation) parent).values().add(pair); child = pair; } else { AnnotationValue value = (AnnotationValue) correspondingChild; // if the existing annotation is a SingleMemberAnnotation, then set its value if (parent instanceof SingleMemberAnnotation) { ASTNode expression = getExpressionFromString(parent.getAST(), value.getValue()); ((SingleMemberAnnotation) parent).setValue((Expression) expression); child = ast.newMemberValuePair(); // avoid NPE later } } return child; } return super.createChildOnContainmentFeature(element, feature, correspondingChild); }
From source file:com.google.devtools.j2cpp.translate.Rewriter.java
License:Open Source License
/** * Given a AST node, return the appropriate printf() format specifier. *//* w ww. ja v a 2 s . c om*/ private String getFormatArgument(ASTNode node) { ITypeBinding type = Types.getTypeBinding(node); AST ast = node.getAST(); if (node instanceof CharacterLiteral || type.isEqualTo(ast.resolveWellKnownType("char"))) { return "%C"; } if (node instanceof BooleanLiteral || type.isEqualTo(ast.resolveWellKnownType("boolean"))) { return "%d"; } if (type.isEqualTo(ast.resolveWellKnownType("byte")) || type.isEqualTo(ast.resolveWellKnownType("int")) || type.isEqualTo(ast.resolveWellKnownType("short"))) { return "%d"; } if (type.isEqualTo(ast.resolveWellKnownType("long"))) { return "%lld"; } if (type.isEqualTo(ast.resolveWellKnownType("float")) || type.isEqualTo(ast.resolveWellKnownType("double"))) { return "%f"; } if (node instanceof NumberLiteral) { String token = ((NumberLiteral) node).getToken(); try { Integer.parseInt(token); return "%d"; } catch (NumberFormatException e) { try { Long.parseLong(token); return "%lld"; } catch (NumberFormatException e2) { try { Double.parseDouble(token); return "%f"; } catch (NumberFormatException e3) { throw new AssertionError("unknown number literal format: \"" + token + "\""); } } } } return "%@"; // object, including string }
From source file:com.halware.nakedide.eclipse.ext.annot.utils.AstUtils.java
License:Open Source License
/** * Provided as a slight performance optimization when an ASTParser is already available * to do the refactoring./*from w ww. j av a2s. c o m*/ * * @param parser - must have the compilationUnit as its source, per {@link ASTParser#setSource(ICompilationUnit)}. * @param compilationUnit * @param originals - to be replaced with the (single) replacement node. * @param replacement - the (single) replacement node; may be null meaning the originals are simply removed completely. * * @throws JavaModelException * @throws MalformedTreeException * @throws BadLocationException */ public static void rewriteReplace(ASTParser parser, ICompilationUnit compilationUnit, List<ASTNode> originals, ASTNode replacement) throws JavaModelException, MalformedTreeException, BadLocationException { String source = compilationUnit.getBuffer().getContents(); Document document = new Document(source); ASTNode firstOriginal = originals.get(0); ASTRewrite rewrite = ASTRewrite.create(firstOriginal.getAST()); TextEditGroup editGroup = new TextEditGroup("Replacing nodes"); for (ASTNode original : originals) { if (original == firstOriginal) { rewrite.replace(original, replacement, editGroup); } else { rewrite.replace(original, null, editGroup); } } TextEdit edits = rewrite.rewriteAST(document, compilationUnit.getJavaProject().getOptions(true)); // computation of the new source code edits.apply(document); String newSource = document.get(); // update of the compilation unit compilationUnit.getBuffer().setContents(newSource); }