EclipseJDT Source Viewer

Home|eclipse_jdt/src/org/eclipse/jdt/core/dom/rewrite/ASTRewrite.java
1/*******************************************************************************
2 * Copyright (c) 2004, 2021 IBM Corporation and others.
3 *
4 * This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License 2.0
6 * which accompanies this distribution, and is available at
7 * https://www.eclipse.org/legal/epl-2.0/
8 *
9 * SPDX-License-Identifier: EPL-2.0
10 *
11 * Contributors:
12 *     IBM Corporation - initial API and implementation
13 *     Microsoft Corporation - read formatting options from the compilation unit
14 *******************************************************************************/
15package org.eclipse.jdt.core.dom.rewrite;
16
17import java.util.HashMap;
18import java.util.Iterator;
19import java.util.List;
20import java.util.Map;
21
22import org.eclipse.jdt.core.IClassFile;
23import org.eclipse.jdt.core.ICompilationUnit;
24import org.eclipse.jdt.core.ITypeRoot;
25import org.eclipse.jdt.core.JavaCore;
26import org.eclipse.jdt.core.JavaModelException;
27import org.eclipse.jdt.core.dom.AST;
28import org.eclipse.jdt.core.dom.ASTNode;
29import org.eclipse.jdt.core.dom.ASTParser;
30import org.eclipse.jdt.core.dom.Block;
31import org.eclipse.jdt.core.dom.ChildListPropertyDescriptor;
32import org.eclipse.jdt.core.dom.ChildPropertyDescriptor;
33import org.eclipse.jdt.core.dom.CompilationUnit;
34import org.eclipse.jdt.core.dom.SimplePropertyDescriptor;
35import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
36import org.eclipse.jdt.internal.compiler.parser.RecoveryScannerData;
37import org.eclipse.jdt.internal.core.dom.rewrite.ASTRewriteAnalyzer;
38import org.eclipse.jdt.internal.core.dom.rewrite.LineInformation;
39import org.eclipse.jdt.internal.core.dom.rewrite.NodeInfoStore;
40import org.eclipse.jdt.internal.core.dom.rewrite.NodeRewriteEvent;
41import org.eclipse.jdt.internal.core.dom.rewrite.RewriteEventStore;
42import org.eclipse.jdt.internal.core.dom.rewrite.TrackedNodePosition;
43import org.eclipse.jdt.internal.core.dom.rewrite.RewriteEventStore.CopySourceInfo;
44import org.eclipse.jdt.internal.core.dom.rewrite.RewriteEventStore.PropertyLocation;
45import org.eclipse.jface.text.IDocument;
46import org.eclipse.jface.text.TextUtilities;
47import org.eclipse.text.edits.MultiTextEdit;
48import org.eclipse.text.edits.TextEdit;
49import org.eclipse.text.edits.TextEditGroup;
50
51/**
52 * Infrastructure for modifying code by describing changes to AST nodes.
53 * The AST rewriter collects descriptions of modifications to nodes and
54 * translates these descriptions into text edits that can then be applied to
55 * the original source. The key thing is that this is all done without actually
56 * modifying the original AST, which has the virtue of allowing one to entertain
57 * several alternate sets of changes on the same AST (e.g., for calculating multiple
58 * quick fix proposals). The rewrite infrastructure tries to generate minimal
59 * text changes, preserve existing comments and indentation, and follow code
60 * formatter settings.
61 * <p>
62 * The following code snippet illustrated usage of this class:
63 * </p>
64 * <pre>
65 * Document document = new Document("import java.util.List;\nclass X {}\n");
66 * ASTParser parser = ASTParser.newParser(AST.JLS3);
67 * parser.setSource(document.get().toCharArray());
68 * CompilationUnit cu = (CompilationUnit) parser.createAST(null);
69 * AST ast = cu.getAST();
70 * ImportDeclaration id = ast.newImportDeclaration();
71 * id.setName(ast.newName(new String[] {"java", "util", "Set"}));
72 * ASTRewrite rewriter = ASTRewrite.create(ast);
73 * TypeDeclaration td = (TypeDeclaration) cu.types().get(0);
74 * ITrackedNodePosition tdLocation = rewriter.track(td);
75 * ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY);
76 * lrw.insertLast(id, null);
77 * TextEdit edits = rewriter.rewriteAST(document, null);
78 * UndoEdit undo = null;
79 * try {
80 *     undo = edits.apply(document);
81 * } catch(MalformedTreeException e) {
82 *     e.printStackTrace();
83 * } catch(BadLocationException e) {
84 *     e.printStackTrace();
85 * }
86 * assert "import java.util.List;\nimport java.util.Set;\nclass X {}\n".equals(document.get());
87 * // tdLocation.getStartPosition() and tdLocation.getLength()
88 * // are new source range for "class X {}" in document.get()
89 * </pre>
90 * <p>
91 * If you are sure you never have to explore multiple alternate changes and you never need
92 * to create {@link #createCopyTarget(ASTNode) copies} or {@link #createStringPlaceholder(String, int) string placeholders},
93 * then you can also try {@link CompilationUnit#recordModifications()} instead.
94 * </p>
95 * <p>
96 * <code>ASTRewrite</code> cannot rewrite (non-Javadoc) comments from
97 * {@link CompilationUnit#getCommentList()}, since those comment nodes
98 * are not part of the normal node hierarchy.
99 * </p>
100 * <p>
101 * This class is not intended to be subclassed.
102 * </p>
103 * @since 3.0
104 * @noinstantiate This class is not intended to be instantiated by clients.
105 * @noextend This class is not intended to be subclassed by clients.
106 */
107@SuppressWarnings({ "rawtypes""unchecked" })
108public class ASTRewrite {
109    /** root node for the rewrite: Only nodes under this root are accepted */
110    private final AST ast;
111
112    private final RewriteEventStore eventStore;
113    private final NodeInfoStore nodeStore;
114
115    /**
116     * Target source range computer; null means uninitialized;
117     * lazy initialized to <code>new TargetSourceRangeComputer()</code>.
118     * @since 3.1
119     */
120    private TargetSourceRangeComputer targetSourceRangeComputer = null;
121
122    /**
123     * Primary field used in representing rewrite properties efficiently.
124     * If <code>null</code>, this rewrite has no properties.
125     * If a {@link String}, this is the name of this rewrite's sole property,
126     * and <code>property2</code> contains its value.
127     * If a {@link Map}, this is the table of property name-value
128     * mappings.
129     * Initially <code>null</code>.
130     *
131     * @see #property2
132     */
133    private Object property1 = null;
134
135    /**
136     * Auxiliary field used in representing rewrite properties efficiently.
137     *
138     * @see #property1
139     */
140    private Object property2 = null;
141
142    /**
143     * Creates a new instance for describing manipulations of
144     * the given AST.
145     *
146     * @param ast the AST whose nodes will be rewritten
147     * @return the new rewriter instance
148     */
149    public static ASTRewrite create(AST ast) {
150        return new ASTRewrite(ast);
151    }
152
153    /**
154     * Internal constructor. Creates a new instance for the given AST.
155     * Clients should use {@link #create(AST)} to create instances.
156     *
157     * @param ast the AST being rewritten
158     */
159    protected ASTRewrite(AST ast) {
160        this.astast;
161        this.eventStore= new RewriteEventStore();
162        this.nodeStore= new NodeInfoStore(ast);
163    }
164
165    /**
166     * Returns the AST the rewrite was set up on.
167     *
168     * @return the AST the rewrite was set up on
169     */
170    public final AST getAST() {
171        return this.ast;
172    }
173
174    /**
175     * Internal method. Returns the internal event store.
176     * Clients should not use.
177     * @return Returns the internal event store. Clients should not use.
178     */
179    protected final RewriteEventStore getRewriteEventStore() {
180        return this.eventStore;
181    }
182
183    /**
184     * Internal method. Returns the internal node info store.
185     * Clients should not use.
186     * @return Returns the internal info store. Clients should not use.
187     */
188    protected final NodeInfoStore getNodeStore() {
189        return this.nodeStore;
190    }
191
192    /**
193     * Converts all modifications recorded by this rewriter
194     * into an object representing the corresponding text
195     * edits to the given document containing the original source
196     * code. The document itself is not modified.
197     * <p>
198     * For nodes in the original that are being replaced or deleted,
199     * this rewriter computes the adjusted source ranges
200     * by calling {@link TargetSourceRangeComputer#computeSourceRange(ASTNode) getExtendedSourceRangeComputer().computeSourceRange(node)}.
201     * </p>
202     * <p>
203     * Calling this methods does not discard the modifications
204     * on record. Subsequence modifications are added to the ones
205     * already on record. If this method is called again later,
206     * the resulting text edit object will accurately reflect
207     * the net cumulative effect of all those changes.
208     * </p>
209     *
210     * @param document original document containing source code
211     * @param options the table of formatter options
212     * (key type: <code>String</code>; value type: <code>String</code>);
213     * or <code>null</code> to use the standard global options
214     * {@link JavaCore#getOptions() JavaCore.getOptions()}
215     * @return text edit object describing the changes to the
216     * document corresponding to the changes recorded by this rewriter
217     * @throws IllegalArgumentException An <code>IllegalArgumentException</code>
218     * is thrown if the document passed does not correspond to the AST that is rewritten.
219     */
220    public TextEdit rewriteAST(IDocument documentMap options) throws IllegalArgumentException {
221        if (document == null) {
222            throw new IllegalArgumentException();
223        }
224
225        ASTNode rootNodegetRootNode();
226        if (rootNode == null) {
227            return new MultiTextEdit(); // no changes
228        }
229
230        char[] contentdocument.get().toCharArray();
231        LineInformation lineInfoLineInformation.create(document);
232        String lineDelimTextUtilities.getDefaultLineDelimiter(document);
233
234        ASTNode astRootrootNode.getRoot();
235        List commentNodesastRoot instanceof CompilationUnit ? ((CompilationUnitastRoot).getCommentList() : null;
236        Map currentOptions = options == null ? JavaCore.getOptions() : options;
237        return internalRewriteAST(contentlineInfolineDelimcommentNodescurrentOptionsrootNode, (RecoveryScannerData)((CompilationUnitastRoot).getStatementsRecoveryData());
238    }
239
240    /**
241     * Converts all modifications recorded by this rewriter into an object representing the the corresponding text
242     * edits to the source of a {@link ITypeRoot} from which the AST was created from.
243     * The type root's source itself is not modified by this method call.
244     * <p>
245     * Important: This API can only be used if the modified AST has been created from a
246     * {@link ITypeRoot} with source. That means {@link ASTParser#setSource(ICompilationUnit)},
247     * {@link ASTParser#setSource(IClassFile)} or {@link ASTParser#setSource(ITypeRoot)}
248     * has been used when initializing the {@link ASTParser}. A {@link IllegalArgumentException} is thrown
249     * otherwise. An {@link IllegalArgumentException} is also thrown when the type roots buffer does not correspond
250     * anymore to the AST. Use {@link #rewriteAST(IDocument, Map)} for all ASTs created from other content.
251     * </p>
252     * <p>
253     * For nodes in the original that are being replaced or deleted,
254     * this rewriter computes the adjusted source ranges
255     * by calling {@link TargetSourceRangeComputer#computeSourceRange(ASTNode) getExtendedSourceRangeComputer().computeSourceRange(node)}.
256     * </p>
257     * <p>
258     * Calling this methods does not discard the modifications
259     * on record. Subsequence modifications are added to the ones
260     * already on record. If this method is called again later,
261     * the resulting text edit object will accurately reflect
262     * the net cumulative effect of all those changes.
263     * </p>
264     *
265     * @return text edit object describing the changes to the
266     * document corresponding to the changes recorded by this rewriter
267     * @throws JavaModelException A {@link JavaModelException} is thrown when
268     * the underlying compilation units buffer could not be accessed.
269     * @throws IllegalArgumentException An {@link IllegalArgumentException}
270     * is thrown if the document passed does not correspond to the AST that is rewritten.
271     *
272     * @since 3.2
273     */
274    public TextEdit rewriteAST() throws JavaModelExceptionIllegalArgumentException {
275        ASTNode rootNodegetRootNode();
276        if (rootNode == null) {
277            return new MultiTextEdit(); // no changes
278        }
279
280        ASTNode rootrootNode.getRoot();
281        if (!(root instanceof CompilationUnit)) {
282            throw new IllegalArgumentException("This API can only be used if the AST is created from a compilation unit or class file"); //$NON-NLS-1$
283        }
284        CompilationUnit astRoot= (CompilationUnitroot;
285        ITypeRoot typeRoot = astRoot.getTypeRoot();
286        if (typeRoot == null || typeRoot.getBuffer() == null) {
287            throw new IllegalArgumentException("This API can only be used if the AST is created from a compilation unit or class file"); //$NON-NLS-1$
288        }
289
290        char[] contenttypeRoot.getBuffer().getCharacters();
291        LineInformation lineInfoLineInformation.create(astRoot);
292        String lineDelimtypeRoot.findRecommendedLineSeparator();
293        Map optionstypeRoot instanceof ICompilationUnit ? ((ICompilationUnittypeRoot).getOptions(true) :
294            typeRoot.getJavaProject().getOptions(true);
295
296        return internalRewriteAST(contentlineInfolineDelimastRoot.getCommentList(), optionsrootNode, (RecoveryScannerData)astRoot.getStatementsRecoveryData());
297    }
298
299    private TextEdit internalRewriteAST(char[] contentLineInformation lineInfoString lineDelimList commentNodesMap optionsASTNode rootNodeRecoveryScannerData recoveryScannerData) {
300        TextEdit result= new MultiTextEdit();
301        //validateASTNotModified(rootNode);
302
303        TargetSourceRangeComputer sourceRangeComputergetExtendedSourceRangeComputer();
304        this.eventStore.prepareMovedNodes(sourceRangeComputer);
305
306        ASTRewriteAnalyzer visitor= new ASTRewriteAnalyzer(contentlineInfolineDelimresult, this.eventStore, this.nodeStorecommentNodesoptionssourceRangeComputerrecoveryScannerData);
307        rootNode.accept(visitor); // throws IllegalArgumentException
308
309        this.eventStore.revertMovedNodes();
310        return result;
311    }
312
313    private ASTNode getRootNode() {
314        ASTNode nodenull;
315        int start= -1;
316        int end= -1;
317
318        for (Iterator itergetRewriteEventStore().getChangeRootIterator(); iter.hasNext();) {
319            ASTNode curr= (ASTNodeiter.next();
320            if (!RewriteEventStore.isNewNode(curr)) {
321                int currStartcurr.getStartPosition();
322                int currEndcurrStart + curr.getLength();
323                if (node == null || currStart < start && currEnd > end) {
324                    startcurrStart;
325                    endcurrEnd;
326                    nodecurr;
327                } else if (currStart < start) {
328                    startcurrStart;
329                } else if (currEnd > end) {
330                    endcurrEnd;
331                }
332            }
333        }
334        if (node != null) {
335            int currStartnode.getStartPosition();
336            int currEndcurrStart + node.getLength();
337            while (start < currStart || end > currEnd) { // go up until a node covers all
338                nodenode.getParent();
339                currStartnode.getStartPosition();
340                currEndcurrStart + node.getLength();
341            }
342            ASTNode parentnode.getParent(); // go up until a parent has different range
343            while (parent != null && parent.getStartPosition() == node.getStartPosition() && parent.getLength() == node.getLength()) {
344                nodeparent;
345                parentnode.getParent();
346            }
347        }
348        return node;
349    }
350
351    /*
352    private void validateASTNotModified(ASTNode root) throws IllegalArgumentException {
353        GenericVisitor isModifiedVisitor= new GenericVisitor() {
354            protected boolean visitNode(ASTNode node) {
355                if ((node.getFlags() & ASTNode.ORIGINAL) == 0) {
356                    throw new IllegalArgumentException("The AST that is rewritten must not be modified."); //$NON-NLS-1$
357                }
358                return true;
359            }
360        };
361        root.accept(isModifiedVisitor);
362    }
363    */
364
365    /**
366     * Removes the given node from its parent in this rewriter. The AST itself
367     * is not actually modified in any way; rather, the rewriter just records
368     * a note that this node should not be there.
369     *
370     * @param node the node being removed. The node can either be an original node in the AST
371     * or (since 3.4) a new node already inserted or used as replacement in this AST rewriter.
372     * @param editGroup the edit group in which to collect the corresponding
373     * text edits, or <code>null</code> if ungrouped
374     * @throws IllegalArgumentException if the node is null, or if the node is not
375     * part of this rewriter's AST, or if the described modification is invalid
376     * (such as removing a required node)
377     */
378    public final void remove(ASTNode nodeTextEditGroup editGroup) {
379        if (node == null) {
380            throw new IllegalArgumentException();
381        }
382
383        StructuralPropertyDescriptor property;
384        ASTNode parent;
385        if (RewriteEventStore.isNewNode(node)) { // remove a new node, bug 164862
386            PropertyLocation location= this.eventStore.getPropertyLocation(nodeRewriteEventStore.NEW);
387            if (location != null) {
388                propertylocation.getProperty();
389                parentlocation.getParent();
390            } else {
391                throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$
392            }
393        } else {
394            propertynode.getLocationInParent();
395            parentnode.getParent();
396        }
397
398        if (property.isChildListProperty()) {
399            getListRewrite(parent, (ChildListPropertyDescriptorproperty).remove(nodeeditGroup);
400        } else {
401            set(parentpropertynulleditGroup);
402        }
403    }
404
405    /**
406     * Replaces the given node in this rewriter. The replacement node
407     * must either be brand new (not part of the original AST) or a placeholder
408     * node (for example, one created by {@link #createCopyTarget(ASTNode)}
409     * or {@link #createStringPlaceholder(String, int)}). The AST itself
410     * is not actually modified in any way; rather, the rewriter just records
411     * a note that this node has been replaced.
412     *
413     * @param node the node being replaced. The node can either be an original node in the AST
414     * or (since 3.4) a new node already inserted or used as replacement in this AST rewriter.
415     * @param replacement the replacement node, or <code>null</code> if no
416     * replacement
417     * @param editGroup the edit group in which to collect the corresponding
418     * text edits, or <code>null</code> if ungrouped
419     * @throws IllegalArgumentException if the node is null, or if the node is not part
420     * of this rewriter's AST, or if the replacement node is not a new node (or
421     * placeholder), or if the described modification is otherwise invalid
422     */
423    public final void replace(ASTNode nodeASTNode replacementTextEditGroup editGroup) {
424        if (node == null) {
425            throw new IllegalArgumentException();
426        }
427
428        StructuralPropertyDescriptor property;
429        ASTNode parent;
430        if (RewriteEventStore.isNewNode(node)) { // replace a new node, bug 164862
431            PropertyLocation location= this.eventStore.getPropertyLocation(nodeRewriteEventStore.NEW);
432            if (location != null) {
433                propertylocation.getProperty();
434                parentlocation.getParent();
435            } else {
436                throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$
437            }
438        } else {
439            propertynode.getLocationInParent();
440            parentnode.getParent();
441        }
442
443        if (property.isChildListProperty()) {
444            getListRewrite(parent, (ChildListPropertyDescriptorproperty).replace(nodereplacementeditGroup);
445        } else {
446            set(parentpropertyreplacementeditGroup);
447        }
448    }
449
450    /**
451     * Sets the given property of the given node. If the given property is a child
452     * property, the value must be a replacement node that is either be brand new
453     * (not part of the original AST) or a placeholder node (for example, one
454     * created by {@link #createCopyTarget(ASTNode)}
455     * or {@link #createStringPlaceholder(String, int)}); or it must be
456     * <code>null</code>, indicating that the child should be deleted.
457     * If the given property is a simple property, the value must be the new
458     * value (primitive types must be boxed) or <code>null</code>.
459     * The AST itself is not actually modified in any way; rather, the rewriter
460     * just records a note that this node has been changed in the specified way.
461     *
462     * @param node the node
463     * @param property the node's property; either a simple property or a child property
464     * @param value the replacement child or new value, or <code>null</code> if none
465     * @param editGroup the edit group in which to collect the corresponding
466     * text edits, or <code>null</code> if ungrouped
467     * @throws IllegalArgumentException if the node or property is null, or if the node
468     * is not part of this rewriter's AST, or if the property is not a node property,
469     * or if the described modification is invalid
470     */
471    public final void set(ASTNode nodeStructuralPropertyDescriptor propertyObject valueTextEditGroup editGroup) {
472        if (node == null || property == null) {
473            throw new IllegalArgumentException();
474        }
475        validateIsCorrectAST(node);
476        validatePropertyType(propertyvalue);
477        validateIsPropertyOfNode(propertynode);
478
479        NodeRewriteEvent nodeEvent= this.eventStore.getNodeEvent(nodepropertytrue);
480        nodeEvent.setNewValue(value);
481        if (editGroup != null) {
482            this.eventStore.setEventEditGroup(nodeEventeditGroup);
483        }
484    }
485
486    /**
487     * Returns the value of the given property as managed by this rewriter. If the property
488     * has been removed, <code>null</code> is returned. If it has been replaced, the replacing value
489     * is returned. If the property has not been changed yet, the original value is returned.
490     * <p>
491     * For child list properties use {@link ListRewrite#getRewrittenList()} to get access to the
492     * rewritten nodes in a list. </p>
493     *
494     * @param node the node
495     * @param property the node's property
496     * @return the value of the given property as managed by this rewriter
497     *
498     * @since 3.2
499     */
500    public Object get(ASTNode nodeStructuralPropertyDescriptor property) {
501        if (node == null || property == null) {
502            throw new IllegalArgumentException();
503        }
504        if (property.isChildListProperty()) {
505            throw new IllegalArgumentException("Use the list rewriter to access nodes in a list"); //$NON-NLS-1$
506        }
507        return this.eventStore.getNewValue(nodeproperty);
508    }
509
510    /**
511     * Creates and returns a new rewriter for describing modifications to the
512     * given list property of the given node.
513     *
514     * @param node the node
515     * @param property the node's property; the child list property
516     * @return a new list rewriter object
517     * @throws IllegalArgumentException if the node or property is null, or if the node
518     * is not part of this rewriter's AST, or if the property is not a node property,
519     * or if the described modification is invalid
520     */
521    public final ListRewrite getListRewrite(ASTNode nodeChildListPropertyDescriptor property) {
522        if (node == null || property == null) {
523            throw new IllegalArgumentException();
524        }
525
526        validateIsCorrectAST(node);
527        validateIsListProperty(property);
528        validateIsPropertyOfNode(propertynode);
529
530        return new ListRewrite(this, nodeproperty);
531    }
532
533    /**
534     * Returns the value of the named property of this rewrite, or <code>null</code> if none.
535     *
536     * @param propertyName the property name
537     * @return the property value, or <code>null</code> if none
538     * @see #setProperty(String,Object)
539     * @throws IllegalArgumentException if the given property name is <code>null</code>
540     * @since 3.7
541     */
542    public final Object getProperty(String propertyName) {
543        if (propertyName == null) {
544            throw new IllegalArgumentException();
545        }
546        if (this.property1 == null) {
547            // rewrite has no properties at all
548            return null;
549        }
550        if (this.property1 instanceof String) {
551            // rewrite has only a single property
552            if (propertyName.equals(this.property1)) {
553                return this.property2;
554            } else {
555                return null;
556            }
557        }
558        // otherwise rewrite has table of properties
559        Map m = (Map) this.property1;
560        return m.get(propertyName);
561    }
562
563    /**
564     * Returns an object that tracks the source range of the given node
565     * across the rewrite to its AST. Upon return, the result object reflects
566     * the given node's current source range in the AST. After
567     * <code>rewrite</code> is called, the result object is updated to
568     * reflect the given node's source range in the rewritten AST.
569     *
570     * @param node the node to track
571     * @return an object that tracks the source range of <code>node</code>
572     * @throws IllegalArgumentException if the node is null, or if the node
573     * is not part of this rewriter's AST, or if the node is already being
574     * tracked
575     */
576    public final ITrackedNodePosition track(ASTNode node) {
577        if (node == null) {
578            throw new IllegalArgumentException();
579        }
580        TextEditGroup group= this.eventStore.getTrackedNodeData(node);
581        if (group == null) {
582            group= new TextEditGroup("internal"); //$NON-NLS-1$
583            this.eventStore.setTrackedNodeData(nodegroup);
584        }
585        return new TrackedNodePosition(groupnode);
586    }
587
588    private void validateIsExistingNode(ASTNode node) {
589        if (node.getStartPosition() == -1) {
590            throw new IllegalArgumentException("Node is not an existing node"); //$NON-NLS-1$
591        }
592    }
593
594    private void validateIsCorrectAST(ASTNode node) {
595        if (node.getAST() != getAST()) {
596            throw new IllegalArgumentException("Node is not inside the AST"); //$NON-NLS-1$
597        }
598    }
599
600    private void validateIsListProperty(StructuralPropertyDescriptor property) {
601        if (!property.isChildListProperty()) {
602            String messageproperty.getId() + " is not a list property"//$NON-NLS-1$
603            throw new IllegalArgumentException(message);
604        }
605    }
606
607    private void validateIsPropertyOfNode(StructuralPropertyDescriptor propertyASTNode node) {
608        if (!property.getNodeClass().isInstance(node)) {
609            String messageproperty.getId() + " is not a property of type " + node.getClass().getName(); //$NON-NLS-1$
610            throw new IllegalArgumentException(message);
611        }
612    }
613
614    private void validatePropertyType(StructuralPropertyDescriptor propObject value) {
615        if (prop.isChildListProperty()) {
616            String message = "Can not modify a list property, use getListRewrite()"//$NON-NLS-1$
617            throw new IllegalArgumentException(message);
618        }
619        if (!RewriteEventStore.DEBUG) {
620            return;
621        }
622
623        if (value == null) {
624            if (prop.isSimpleProperty() && ((SimplePropertyDescriptorprop).isMandatory()
625                    || prop.isChildProperty() && ((ChildPropertyDescriptorprop).isMandatory()) {
626                String message = "Can not remove property " + prop.getId(); //$NON-NLS-1$
627                throw new IllegalArgumentException(message);
628            }
629
630        } else {
631            Class valueType;
632            if (prop.isSimpleProperty()) {
633                SimplePropertyDescriptor p = (SimplePropertyDescriptorprop;
634                valueType = p.getValueType();
635                if (valueType == int.class) {
636                    valueType = Integer.class;
637                } else if (valueType == boolean.class) {
638                    valueType = Boolean.class;
639                }
640            } else {
641                ChildPropertyDescriptor p = (ChildPropertyDescriptorprop;
642                valueType = p.getChildType();
643            }
644            if (!valueType.isAssignableFrom(value.getClass())) {
645                String message = value.getClass().getName() + " is not a valid type for " + prop.getNodeClass().getName() //$NON-NLS-1$
646                        + " property '" + prop.getId() + '\''//$NON-NLS-1$
647                throw new IllegalArgumentException(message);
648            }
649        }
650    }
651
652    /**
653     * Creates and returns a placeholder node for a source string that is to be inserted into
654     * the output document at the position corresponding to the placeholder.
655     * The string will be inserted without being reformatted beyond correcting
656     * the indentation level. The placeholder node can either be inserted as new or
657     * used to replace an existing node.
658     *
659     * @param code the string to be inserted; lines should should not have extra indentation
660     * @param nodeType the ASTNode type that corresponds to the passed code.
661     * @return the new placeholder node
662     * @throws IllegalArgumentException if the code is null, or if the node
663     * type is invalid
664     */
665    public final ASTNode createStringPlaceholder(String codeint nodeType) {
666        if (code == null) {
667            throw new IllegalArgumentException();
668        }
669        ASTNode placeholdergetNodeStore().newPlaceholderNode(nodeType);
670        if (placeholder == null) {
671            throw new IllegalArgumentException("String placeholder is not supported for type" + nodeType); //$NON-NLS-1$
672        }
673
674        getNodeStore().markAsStringPlaceholder(placeholdercode);
675        return placeholder;
676    }
677
678    /**
679     * Creates and returns a node that represents a sequence of nodes.
680     * Each of the given nodes must be either be brand new (not part of the original AST), or
681     * a placeholder node (for example, one created by {@link #createCopyTarget(ASTNode)}
682     * or {@link #createStringPlaceholder(String, int)}), or another group node.
683     * The type of the returned node is unspecified. The returned node can be used
684     * to replace an existing node (or as an element of another group node).
685     * When the document is rewritten, the source code for each of the given nodes is
686     * inserted, in order, into the output document at the position corresponding to the
687     * group (indentation is adjusted).
688     *
689     * @param targetNodes the nodes to go in the group
690     * @return the new group node
691     * @throws IllegalArgumentException if the targetNodes is <code>null</code> or empty
692     * @since 3.1
693     */
694    public final ASTNode createGroupNode(ASTNode[] targetNodes) {
695        if (targetNodes == null || targetNodes.length == 0) {
696            throw new IllegalArgumentException();
697        }
698        Block resgetNodeStore().createCollapsePlaceholder();
699        ListRewrite listRewritegetListRewrite(resBlock.STATEMENTS_PROPERTY);
700        for (int i0i < targetNodes.lengthi++) {
701            listRewrite.insertLast(targetNodes[i], null);
702        }
703        return res;
704    }
705
706
707    private ASTNode createTargetNode(ASTNode nodeboolean isMove) {
708        if (node == null) {
709            throw new IllegalArgumentException();
710        }
711        validateIsExistingNode(node);
712        validateIsCorrectAST(node);
713        CopySourceInfo infogetRewriteEventStore().markAsCopySource(node.getParent(), node.getLocationInParent(), nodeisMove);
714
715        ASTNode placeholdergetNodeStore().newPlaceholderNode(node.getNodeType());
716        if (placeholder == null) {
717            throw new IllegalArgumentException("Creating a target node is not supported for nodes of type" + node.getClass().getName()); //$NON-NLS-1$
718        }
719        getNodeStore().markAsCopyTarget(placeholderinfo);
720
721        return placeholder;
722    }
723
724    /**
725     * Creates and returns a placeholder node for a true copy of the given node.
726     * The placeholder node can either be inserted as new or used to replace an
727     * existing node. When the document is rewritten, a copy of the source code
728     * for the given node is inserted into the output document at the position
729     * corresponding to the placeholder (indentation is adjusted).
730     *
731     * @param node the node to create a copy placeholder for
732     * @return the new placeholder node
733     * @throws IllegalArgumentException if the node is null, or if the node
734     * is not part of this rewriter's AST
735     */
736    public final ASTNode createCopyTarget(ASTNode node) {
737        return createTargetNode(nodefalse);
738    }
739
740    /**
741     * Creates and returns a placeholder node for the new locations of the given node.
742     * After obtaining a placeholder, the node must be removed or replaced.
743     * The placeholder node can either be inserted as new or used to replace an
744     * existing node. The placeholder must be used somewhere in the AST and must not be dropped
745     * by subsequent modifications. When the document is rewritten, the source code for the given
746     * node is inserted into the output document at the position corresponding to the
747     * placeholder (indentation is adjusted).
748     *
749     * @param node the node to create a move placeholder for
750     * @return the new placeholder node
751     * @throws IllegalArgumentException if the node is null, or if the node
752     * is not part of this rewriter's AST
753     */
754    public final ASTNode createMoveTarget(ASTNode node) {
755        return createTargetNode(nodetrue);
756    }
757
758    /**
759     * Returns the extended source range computer for this AST rewriter.
760     * The default value is a <code>new TargetSourceRangeComputer()</code>.
761     *
762     * @return an extended source range computer
763     * @since 3.1
764     * @see #setTargetSourceRangeComputer(TargetSourceRangeComputer)
765     */
766    public final TargetSourceRangeComputer getExtendedSourceRangeComputer() {
767        if (this.targetSourceRangeComputer == null) {
768            // lazy initialize
769            this.targetSourceRangeComputer = new TargetSourceRangeComputer();
770        }
771        return this.targetSourceRangeComputer;
772    }
773
774    /**
775     * Sets the named property of this rewrite to the given value,
776     * or to <code>null</code> to clear it.
777     * <p>
778     * Clients should employ property names that are sufficiently unique
779     * to avoid inadvertent conflicts with other clients that might also be
780     * setting properties on the same rewrite.
781     * </p>
782     * <p>
783     * Note that modifying a property is not considered a modification to the
784     * AST itself. This is to allow clients to decorate existing rewrites with
785     * their own properties without jeopardizing certain things (like the
786     * validity of bindings), which rely on the underlying tree remaining static.
787     * </p>
788     *
789     * @param propertyName the property name
790     * @param data the new property value, or <code>null</code> if none
791     * @see #getProperty(String)
792     * @throws IllegalArgumentException if the given property name is <code>null</code>
793     * @since 3.7
794     */
795    public final void setProperty(String propertyNameObject data) {
796        if (propertyName == null) {
797            throw new IllegalArgumentException();
798        }
799        if (this.property1 == null) {
800            // rewrite has no properties at all
801            if (data == null) {
802                // rewrite already knows this
803                return;
804            }
805            // rewrite gets its fist property
806            this.property1 = propertyName;
807            this.property2 = data;
808            return;
809        }
810        if (this.property1 instanceof String) {
811            // rewrite has only a single property
812            if (propertyName.equals(this.property1)) {
813                // we're in luck
814                if (data == null) {
815                    // just delete last property
816                    this.property1 = null;
817                    this.property2 = null;
818                } else {
819                    this.property2 = data;
820                }
821                return;
822            }
823            if (data == null) {
824                // we already know this
825                return;
826            }
827            // rewrite already has one property - getting its second
828            // convert to more flexible representation
829            Map m = new HashMap(3);
830            m.put(this.property1, this.property2);
831            m.put(propertyNamedata);
832            this.property1 = m;
833            this.property2 = null;
834            return;
835        }
836        // rewrite has two or more properties
837        Map m = (Map) this.property1;
838        if (data == null) {
839            m.remove(propertyName);
840            // check for just one property left
841            if (m.size() == 1) {
842                // convert to more efficient representation
843                Map.Entry[] entries = (Map.Entry[]) m.entrySet().toArray(new Map.Entry[1]);
844                this.property1 = entries[0].getKey();
845                this.property2 = entries[0].getValue();
846            }
847            return;
848        } else {
849            m.put(propertyNamedata);
850            // still has two or more properties
851            return;
852        }
853    }
854
855    /**
856     * Sets a custom target source range computer for this AST rewriter. This is advanced feature to modify how
857     * comments are associated with nodes, which should be done only in special cases.
858     *
859     * @param computer a target source range computer,
860     * or <code>null</code> to restore the default value of
861     * <code>new TargetSourceRangeComputer()</code>
862     * @since 3.1
863     * @see #getExtendedSourceRangeComputer()
864     */
865    public final void setTargetSourceRangeComputer(TargetSourceRangeComputer computer) {
866        // if computer==null, rely on lazy init code in getExtendedSourceRangeComputer()
867        this.targetSourceRangeComputer = computer;
868    }
869
870    /**
871     * Returns a string suitable for debugging purposes (only).
872     *
873     * @return a debug string
874     */
875    @Override
876    public String toString() {
877        StringBuilder buf= new StringBuilder();
878        buf.append("Events:\n"); //$NON-NLS-1$
879        // be extra careful of uninitialized or mangled instances
880        if (this.eventStore != null) {
881            buf.append(this.eventStore.toString());
882        }
883        return buf.toString();
884    }
885}
886
MembersX
ASTRewrite:rewriteAST:Block:commentNodes
ASTRewrite:ast
ASTRewrite:targetSourceRangeComputer
ASTRewrite:create
ASTRewrite:set:Block:nodeEvent
ASTRewrite:rewriteAST:Block:currentOptions
ASTRewrite:rewriteAST:Block:options
ASTRewrite:rewriteAST:Block:lineInfo
ASTRewrite:track:Block:group
ASTRewrite:remove
ASTRewrite:getProperty:Block:m
ASTRewrite:setProperty:Block:Block:m
ASTRewrite:getListRewrite
ASTRewrite:rewriteAST:Block:rootNode
ASTRewrite:createGroupNode:Block:res
ASTRewrite:getExtendedSourceRangeComputer
ASTRewrite:getRootNode:Block:Block:currEnd
ASTRewrite:createStringPlaceholder
ASTRewrite:rewriteAST:Block:content
ASTRewrite:remove:Block:property
ASTRewrite:toString:Block:buf
ASTRewrite:internalRewriteAST:Block:sourceRangeComputer
ASTRewrite:validatePropertyType:Block:Block:message
ASTRewrite:getNodeStore
ASTRewrite:replace
ASTRewrite:validateIsCorrectAST
ASTRewrite:property2
ASTRewrite:property1
ASTRewrite:remove:Block:Block:location
ASTRewrite:setProperty
ASTRewrite:setProperty:Block:Block:Block:entries
ASTRewrite:internalRewriteAST
ASTRewrite:internalRewriteAST:Block:result
ASTRewrite:replace:Block:Block:location
ASTRewrite:getRootNode:Block:Block:curr
ASTRewrite:getRootNode:Block:Block:Block:currEnd
ASTRewrite:getRootNode:Block:end
ASTRewrite:validatePropertyType:Block:Block:Block:p
ASTRewrite:rewriteAST
ASTRewrite:rewriteAST:Block:root
ASTRewrite:replace:Block:parent
ASTRewrite:remove:Block:parent
ASTRewrite:getProperty
ASTRewrite:nodeStore
ASTRewrite:get
ASTRewrite:getRootNode
ASTRewrite:getRootNode:Block:start
ASTRewrite:createTargetNode:Block:info
ASTRewrite:validateIsExistingNode
ASTRewrite:setProperty:Block:m
ASTRewrite:rewriteAST:Block:lineDelim
ASTRewrite:validateIsPropertyOfNode
ASTRewrite:createTargetNode:Block:placeholder
ASTRewrite:getAST
ASTRewrite:replace:Block:property
ASTRewrite:getRootNode:Block:Block:parent
ASTRewrite:setTargetSourceRangeComputer
ASTRewrite:internalRewriteAST:Block:visitor
ASTRewrite:createMoveTarget
ASTRewrite:getRootNode:Block:node
ASTRewrite:validateIsPropertyOfNode:Block:Block:message
ASTRewrite:validateIsListProperty:Block:Block:message
ASTRewrite:getRewriteEventStore
ASTRewrite:rewriteAST:Block:astRoot
ASTRewrite:set
ASTRewrite:createGroupNode:Block:listRewrite
ASTRewrite:toString
ASTRewrite:getRootNode:Block:Block:currStart
ASTRewrite:track
ASTRewrite:validatePropertyType
ASTRewrite:createStringPlaceholder:Block:placeholder
ASTRewrite:rewriteAST:Block:typeRoot
ASTRewrite:createCopyTarget
ASTRewrite:getRootNode:Block:Block:Block:currStart
ASTRewrite:eventStore
ASTRewrite:createGroupNode
ASTRewrite:createTargetNode
ASTRewrite:ASTRewrite
ASTRewrite:validatePropertyType:Block:Block:Block:message
ASTRewrite:validatePropertyType:Block:Block:valueType
ASTRewrite:validateIsListProperty
Members
X