Class ASTRewrite
The following code snippet illustrated usage of this class:
Document document = new Document("import java.util.List;\nclass X {}\n"); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(document.get().toCharArray()); CompilationUnit cu = (CompilationUnit) parser.createAST(null); AST ast = cu.getAST(); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName(new String[] {"java", "util", "Set"})); ASTRewrite rewriter = ASTRewrite.create(ast); TypeDeclaration td = (TypeDeclaration) cu.types().get(0); ITrackedNodePosition tdLocation = rewriter.track(td); ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY); lrw.insertLast(id, null); TextEdit edits = rewriter.rewriteAST(document, null); UndoEdit undo = null; try { undo = edits.apply(document); } catch(MalformedTreeException e) { e.printStackTrace(); } catch(BadLocationException e) { e.printStackTrace(); } assert "import java.util.List;\nimport java.util.Set;\nclass X {}\n".equals(document.get()); // tdLocation.getStartPosition() and tdLocation.getLength() // are new source range for "class X {}" in document.get()
If you are sure you never have to explore multiple alternate changes and you never need
to create copies
or string placeholders
,
then you can also try CompilationUnit.recordModifications()
instead.
ASTRewrite
cannot rewrite (non-Javadoc) comments from
CompilationUnit.getCommentList()
, since those comment nodes
are not part of the normal node hierarchy.
This class is not intended to be subclassed.
- Since:
- 3.0
- Restriction:
- This class is not intended to be subclassed by clients.
- Restriction:
- This class is not intended to be instantiated by clients.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic ASTRewrite
Creates a new instance for describing manipulations of the given AST.final ASTNode
createCopyTarget
(ASTNode node) Creates and returns a placeholder node for a true copy of the given node.final ASTNode
createGroupNode
(ASTNode[] targetNodes) Creates and returns a node that represents a sequence of nodes.final ASTNode
createMoveTarget
(ASTNode node) Creates and returns a placeholder node for the new locations of the given node.final ASTNode
createStringPlaceholder
(String code, int nodeType) Creates and returns a placeholder node for a source string that is to be inserted into the output document at the position corresponding to the placeholder.get
(ASTNode node, StructuralPropertyDescriptor property) Returns the value of the given property as managed by this rewriter.final AST
getAST()
Returns the AST the rewrite was set up on.Returns the extended source range computer for this AST rewriter.final ListRewrite
getListRewrite
(ASTNode node, ChildListPropertyDescriptor property) Creates and returns a new rewriter for describing modifications to the given list property of the given node.protected final org.eclipse.jdt.internal.core.dom.rewrite.NodeInfoStore
Internal method.final Object
getProperty
(String propertyName) Returns the value of the named property of this rewrite, ornull
if none.protected final org.eclipse.jdt.internal.core.dom.rewrite.RewriteEventStore
Internal method.final void
Removes the given node from its parent in this rewriter.final void
Replaces the given node in this rewriter.org.eclipse.text.edits.TextEdit
Converts all modifications recorded by this rewriter into an object representing the the corresponding text edits to the source of aITypeRoot
from which the AST was created from.org.eclipse.text.edits.TextEdit
rewriteAST
(org.eclipse.jface.text.IDocument document, Map options) Converts all modifications recorded by this rewriter into an object representing the corresponding text edits to the given document containing the original source code.final void
set
(ASTNode node, StructuralPropertyDescriptor property, Object value, org.eclipse.text.edits.TextEditGroup editGroup) Sets the given property of the given node.final void
setProperty
(String propertyName, Object data) Sets the named property of this rewrite to the given value, or tonull
to clear it.final void
Sets a custom target source range computer for this AST rewriter.toString()
Returns a string suitable for debugging purposes (only).final ITrackedNodePosition
Returns an object that tracks the source range of the given node across the rewrite to its AST.
-
Constructor Details
-
ASTRewrite
Internal constructor. Creates a new instance for the given AST. Clients should usecreate(AST)
to create instances.- Parameters:
ast
- the AST being rewritten
-
-
Method Details
-
create
Creates a new instance for describing manipulations of the given AST.- Parameters:
ast
- the AST whose nodes will be rewritten- Returns:
- the new rewriter instance
-
getAST
Returns the AST the rewrite was set up on.- Returns:
- the AST the rewrite was set up on
-
getRewriteEventStore
protected final org.eclipse.jdt.internal.core.dom.rewrite.RewriteEventStore getRewriteEventStore()Internal method. Returns the internal event store. Clients should not use.- Returns:
- Returns the internal event store. Clients should not use.
-
getNodeStore
protected final org.eclipse.jdt.internal.core.dom.rewrite.NodeInfoStore getNodeStore()Internal method. Returns the internal node info store. Clients should not use.- Returns:
- Returns the internal info store. Clients should not use.
-
rewriteAST
public org.eclipse.text.edits.TextEdit rewriteAST(org.eclipse.jface.text.IDocument document, Map options) throws IllegalArgumentException Converts all modifications recorded by this rewriter into an object representing the corresponding text edits to the given document containing the original source code. The document itself is not modified.For nodes in the original that are being replaced or deleted, this rewriter computes the adjusted source ranges by calling
getExtendedSourceRangeComputer().computeSourceRange(node)
.Calling this methods does not discard the modifications on record. Subsequence modifications are added to the ones already on record. If this method is called again later, the resulting text edit object will accurately reflect the net cumulative effect of all those changes.
- Parameters:
document
- original document containing source codeoptions
- the table of formatter options (key type:String
; value type:String
); ornull
to use the standard global optionsJavaCore.getOptions()
- Returns:
- text edit object describing the changes to the document corresponding to the changes recorded by this rewriter
- Throws:
IllegalArgumentException
- AnIllegalArgumentException
is thrown if the document passed does not correspond to the AST that is rewritten.
-
rewriteAST
public org.eclipse.text.edits.TextEdit rewriteAST() throws JavaModelException, IllegalArgumentExceptionConverts all modifications recorded by this rewriter into an object representing the the corresponding text edits to the source of aITypeRoot
from which the AST was created from. The type root's source itself is not modified by this method call.Important: This API can only be used if the modified AST has been created from a
ITypeRoot
with source. That meansASTParser.setSource(ICompilationUnit)
,ASTParser.setSource(IClassFile)
orASTParser.setSource(ITypeRoot)
has been used when initializing theASTParser
. AIllegalArgumentException
is thrown otherwise. AnIllegalArgumentException
is also thrown when the type roots buffer does not correspond anymore to the AST. UserewriteAST(IDocument, Map)
for all ASTs created from other content.For nodes in the original that are being replaced or deleted, this rewriter computes the adjusted source ranges by calling
getExtendedSourceRangeComputer().computeSourceRange(node)
.Calling this methods does not discard the modifications on record. Subsequence modifications are added to the ones already on record. If this method is called again later, the resulting text edit object will accurately reflect the net cumulative effect of all those changes.
- Returns:
- text edit object describing the changes to the document corresponding to the changes recorded by this rewriter
- Throws:
JavaModelException
- AJavaModelException
is thrown when the underlying compilation units buffer could not be accessed.IllegalArgumentException
- AnIllegalArgumentException
is thrown if the document passed does not correspond to the AST that is rewritten.- Since:
- 3.2
-
remove
Removes the given node from its parent in this rewriter. The AST itself is not actually modified in any way; rather, the rewriter just records a note that this node should not be there.- Parameters:
node
- the node being removed. The node can either be an original node in the AST or (since 3.4) a new node already inserted or used as replacement in this AST rewriter.editGroup
- the edit group in which to collect the corresponding text edits, ornull
if ungrouped- Throws:
IllegalArgumentException
- if the node is null, or if the node is not part of this rewriter's AST, or if the described modification is invalid (such as removing a required node)
-
replace
public final void replace(ASTNode node, ASTNode replacement, org.eclipse.text.edits.TextEditGroup editGroup) Replaces the given node in this rewriter. The replacement node must either be brand new (not part of the original AST) or a placeholder node (for example, one created bycreateCopyTarget(ASTNode)
orcreateStringPlaceholder(String, int)
). The AST itself is not actually modified in any way; rather, the rewriter just records a note that this node has been replaced.- Parameters:
node
- the node being replaced. The node can either be an original node in the AST or (since 3.4) a new node already inserted or used as replacement in this AST rewriter.replacement
- the replacement node, ornull
if no replacementeditGroup
- the edit group in which to collect the corresponding text edits, ornull
if ungrouped- Throws:
IllegalArgumentException
- if the node is null, or if the node is not part of this rewriter's AST, or if the replacement node is not a new node (or placeholder), or if the described modification is otherwise invalid
-
set
public final void set(ASTNode node, StructuralPropertyDescriptor property, Object value, org.eclipse.text.edits.TextEditGroup editGroup) Sets the given property of the given node. If the given property is a child property, the value must be a replacement node that is either be brand new (not part of the original AST) or a placeholder node (for example, one created bycreateCopyTarget(ASTNode)
orcreateStringPlaceholder(String, int)
); or it must benull
, indicating that the child should be deleted. If the given property is a simple property, the value must be the new value (primitive types must be boxed) ornull
. The AST itself is not actually modified in any way; rather, the rewriter just records a note that this node has been changed in the specified way.- Parameters:
node
- the nodeproperty
- the node's property; either a simple property or a child propertyvalue
- the replacement child or new value, ornull
if noneeditGroup
- the edit group in which to collect the corresponding text edits, ornull
if ungrouped- Throws:
IllegalArgumentException
- if the node or property is null, or if the node is not part of this rewriter's AST, or if the property is not a node property, or if the described modification is invalid
-
get
Returns the value of the given property as managed by this rewriter. If the property has been removed,null
is returned. If it has been replaced, the replacing value is returned. If the property has not been changed yet, the original value is returned.For child list properties use
ListRewrite.getRewrittenList()
to get access to the rewritten nodes in a list.- Parameters:
node
- the nodeproperty
- the node's property- Returns:
- the value of the given property as managed by this rewriter
- Since:
- 3.2
-
getListRewrite
Creates and returns a new rewriter for describing modifications to the given list property of the given node.- Parameters:
node
- the nodeproperty
- the node's property; the child list property- Returns:
- a new list rewriter object
- Throws:
IllegalArgumentException
- if the node or property is null, or if the node is not part of this rewriter's AST, or if the property is not a node property, or if the described modification is invalid
-
getProperty
Returns the value of the named property of this rewrite, ornull
if none.- Parameters:
propertyName
- the property name- Returns:
- the property value, or
null
if none - Throws:
IllegalArgumentException
- if the given property name isnull
- Since:
- 3.7
- See Also:
-
track
Returns an object that tracks the source range of the given node across the rewrite to its AST. Upon return, the result object reflects the given node's current source range in the AST. Afterrewrite
is called, the result object is updated to reflect the given node's source range in the rewritten AST.- Parameters:
node
- the node to track- Returns:
- an object that tracks the source range of
node
- Throws:
IllegalArgumentException
- if the node is null, or if the node is not part of this rewriter's AST, or if the node is already being tracked
-
createStringPlaceholder
Creates and returns a placeholder node for a source string that is to be inserted into the output document at the position corresponding to the placeholder. The string will be inserted without being reformatted beyond correcting the indentation level. The placeholder node can either be inserted as new or used to replace an existing node.- Parameters:
code
- the string to be inserted; lines should should not have extra indentationnodeType
- the ASTNode type that corresponds to the passed code.- Returns:
- the new placeholder node
- Throws:
IllegalArgumentException
- if the code is null, or if the node type is invalid
-
createGroupNode
Creates and returns a node that represents a sequence of nodes. Each of the given nodes must be either be brand new (not part of the original AST), or a placeholder node (for example, one created bycreateCopyTarget(ASTNode)
orcreateStringPlaceholder(String, int)
), or another group node. The type of the returned node is unspecified. The returned node can be used to replace an existing node (or as an element of another group node). When the document is rewritten, the source code for each of the given nodes is inserted, in order, into the output document at the position corresponding to the group (indentation is adjusted).- Parameters:
targetNodes
- the nodes to go in the group- Returns:
- the new group node
- Throws:
IllegalArgumentException
- if the targetNodes isnull
or empty- Since:
- 3.1
-
createCopyTarget
Creates and returns a placeholder node for a true copy of the given node. The placeholder node can either be inserted as new or used to replace an existing node. When the document is rewritten, a copy of the source code for the given node is inserted into the output document at the position corresponding to the placeholder (indentation is adjusted).- Parameters:
node
- the node to create a copy placeholder for- Returns:
- the new placeholder node
- Throws:
IllegalArgumentException
- if the node is null, or if the node is not part of this rewriter's AST
-
createMoveTarget
Creates and returns a placeholder node for the new locations of the given node. After obtaining a placeholder, the node must be removed or replaced. The placeholder node can either be inserted as new or used to replace an existing node. The placeholder must be used somewhere in the AST and must not be dropped by subsequent modifications. When the document is rewritten, the source code for the given node is inserted into the output document at the position corresponding to the placeholder (indentation is adjusted).- Parameters:
node
- the node to create a move placeholder for- Returns:
- the new placeholder node
- Throws:
IllegalArgumentException
- if the node is null, or if the node is not part of this rewriter's AST
-
getExtendedSourceRangeComputer
Returns the extended source range computer for this AST rewriter. The default value is anew TargetSourceRangeComputer()
.- Returns:
- an extended source range computer
- Since:
- 3.1
- See Also:
-
setProperty
Sets the named property of this rewrite to the given value, or tonull
to clear it.Clients should employ property names that are sufficiently unique to avoid inadvertent conflicts with other clients that might also be setting properties on the same rewrite.
Note that modifying a property is not considered a modification to the AST itself. This is to allow clients to decorate existing rewrites with their own properties without jeopardizing certain things (like the validity of bindings), which rely on the underlying tree remaining static.
- Parameters:
propertyName
- the property namedata
- the new property value, ornull
if none- Throws:
IllegalArgumentException
- if the given property name isnull
- Since:
- 3.7
- See Also:
-
setTargetSourceRangeComputer
Sets a custom target source range computer for this AST rewriter. This is advanced feature to modify how comments are associated with nodes, which should be done only in special cases.- Parameters:
computer
- a target source range computer, ornull
to restore the default value ofnew TargetSourceRangeComputer()
- Since:
- 3.1
- See Also:
-
toString
Returns a string suitable for debugging purposes (only).
-