| 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 | *******************************************************************************/ |
| 15 | package org.eclipse.jdt.core.dom.rewrite; |
| 16 | |
| 17 | import java.util.HashMap; |
| 18 | import java.util.Iterator; |
| 19 | import java.util.List; |
| 20 | import java.util.Map; |
| 21 | |
| 22 | import org.eclipse.jdt.core.IClassFile; |
| 23 | import org.eclipse.jdt.core.ICompilationUnit; |
| 24 | import org.eclipse.jdt.core.ITypeRoot; |
| 25 | import org.eclipse.jdt.core.JavaCore; |
| 26 | import org.eclipse.jdt.core.JavaModelException; |
| 27 | import org.eclipse.jdt.core.dom.AST; |
| 28 | import org.eclipse.jdt.core.dom.ASTNode; |
| 29 | import org.eclipse.jdt.core.dom.ASTParser; |
| 30 | import org.eclipse.jdt.core.dom.Block; |
| 31 | import org.eclipse.jdt.core.dom.ChildListPropertyDescriptor; |
| 32 | import org.eclipse.jdt.core.dom.ChildPropertyDescriptor; |
| 33 | import org.eclipse.jdt.core.dom.CompilationUnit; |
| 34 | import org.eclipse.jdt.core.dom.SimplePropertyDescriptor; |
| 35 | import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; |
| 36 | import org.eclipse.jdt.internal.compiler.parser.RecoveryScannerData; |
| 37 | import org.eclipse.jdt.internal.core.dom.rewrite.ASTRewriteAnalyzer; |
| 38 | import org.eclipse.jdt.internal.core.dom.rewrite.LineInformation; |
| 39 | import org.eclipse.jdt.internal.core.dom.rewrite.NodeInfoStore; |
| 40 | import org.eclipse.jdt.internal.core.dom.rewrite.NodeRewriteEvent; |
| 41 | import org.eclipse.jdt.internal.core.dom.rewrite.RewriteEventStore; |
| 42 | import org.eclipse.jdt.internal.core.dom.rewrite.TrackedNodePosition; |
| 43 | import org.eclipse.jdt.internal.core.dom.rewrite.RewriteEventStore.CopySourceInfo; |
| 44 | import org.eclipse.jdt.internal.core.dom.rewrite.RewriteEventStore.PropertyLocation; |
| 45 | import org.eclipse.jface.text.IDocument; |
| 46 | import org.eclipse.jface.text.TextUtilities; |
| 47 | import org.eclipse.text.edits.MultiTextEdit; |
| 48 | import org.eclipse.text.edits.TextEdit; |
| 49 | import 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" }) |
| 108 | public 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.ast= ast; |
| 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 document, Map options) throws IllegalArgumentException { |
| 221 | if (document == null) { |
| 222 | throw new IllegalArgumentException(); |
| 223 | } |
| 224 | |
| 225 | ASTNode rootNode= getRootNode(); |
| 226 | if (rootNode == null) { |
| 227 | return new MultiTextEdit(); // no changes |
| 228 | } |
| 229 | |
| 230 | char[] content= document.get().toCharArray(); |
| 231 | LineInformation lineInfo= LineInformation.create(document); |
| 232 | String lineDelim= TextUtilities.getDefaultLineDelimiter(document); |
| 233 | |
| 234 | ASTNode astRoot= rootNode.getRoot(); |
| 235 | List commentNodes= astRoot instanceof CompilationUnit ? ((CompilationUnit) astRoot).getCommentList() : null; |
| 236 | Map currentOptions = options == null ? JavaCore.getOptions() : options; |
| 237 | return internalRewriteAST(content, lineInfo, lineDelim, commentNodes, currentOptions, rootNode, (RecoveryScannerData)((CompilationUnit) astRoot).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 JavaModelException, IllegalArgumentException { |
| 275 | ASTNode rootNode= getRootNode(); |
| 276 | if (rootNode == null) { |
| 277 | return new MultiTextEdit(); // no changes |
| 278 | } |
| 279 | |
| 280 | ASTNode root= rootNode.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= (CompilationUnit) root; |
| 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[] content= typeRoot.getBuffer().getCharacters(); |
| 291 | LineInformation lineInfo= LineInformation.create(astRoot); |
| 292 | String lineDelim= typeRoot.findRecommendedLineSeparator(); |
| 293 | Map options= typeRoot instanceof ICompilationUnit ? ((ICompilationUnit) typeRoot).getOptions(true) : |
| 294 | typeRoot.getJavaProject().getOptions(true); |
| 295 | |
| 296 | return internalRewriteAST(content, lineInfo, lineDelim, astRoot.getCommentList(), options, rootNode, (RecoveryScannerData)astRoot.getStatementsRecoveryData()); |
| 297 | } |
| 298 | |
| 299 | private TextEdit internalRewriteAST(char[] content, LineInformation lineInfo, String lineDelim, List commentNodes, Map options, ASTNode rootNode, RecoveryScannerData recoveryScannerData) { |
| 300 | TextEdit result= new MultiTextEdit(); |
| 301 | //validateASTNotModified(rootNode); |
| 302 | |
| 303 | TargetSourceRangeComputer sourceRangeComputer= getExtendedSourceRangeComputer(); |
| 304 | this.eventStore.prepareMovedNodes(sourceRangeComputer); |
| 305 | |
| 306 | ASTRewriteAnalyzer visitor= new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result, this.eventStore, this.nodeStore, commentNodes, options, sourceRangeComputer, recoveryScannerData); |
| 307 | rootNode.accept(visitor); // throws IllegalArgumentException |
| 308 | |
| 309 | this.eventStore.revertMovedNodes(); |
| 310 | return result; |
| 311 | } |
| 312 | |
| 313 | private ASTNode getRootNode() { |
| 314 | ASTNode node= null; |
| 315 | int start= -1; |
| 316 | int end= -1; |
| 317 | |
| 318 | for (Iterator iter= getRewriteEventStore().getChangeRootIterator(); iter.hasNext();) { |
| 319 | ASTNode curr= (ASTNode) iter.next(); |
| 320 | if (!RewriteEventStore.isNewNode(curr)) { |
| 321 | int currStart= curr.getStartPosition(); |
| 322 | int currEnd= currStart + curr.getLength(); |
| 323 | if (node == null || currStart < start && currEnd > end) { |
| 324 | start= currStart; |
| 325 | end= currEnd; |
| 326 | node= curr; |
| 327 | } else if (currStart < start) { |
| 328 | start= currStart; |
| 329 | } else if (currEnd > end) { |
| 330 | end= currEnd; |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | if (node != null) { |
| 335 | int currStart= node.getStartPosition(); |
| 336 | int currEnd= currStart + node.getLength(); |
| 337 | while (start < currStart || end > currEnd) { // go up until a node covers all |
| 338 | node= node.getParent(); |
| 339 | currStart= node.getStartPosition(); |
| 340 | currEnd= currStart + node.getLength(); |
| 341 | } |
| 342 | ASTNode parent= node.getParent(); // go up until a parent has different range |
| 343 | while (parent != null && parent.getStartPosition() == node.getStartPosition() && parent.getLength() == node.getLength()) { |
| 344 | node= parent; |
| 345 | parent= node.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 node, TextEditGroup 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(node, RewriteEventStore.NEW); |
| 387 | if (location != null) { |
| 388 | property= location.getProperty(); |
| 389 | parent= location.getParent(); |
| 390 | } else { |
| 391 | throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$ |
| 392 | } |
| 393 | } else { |
| 394 | property= node.getLocationInParent(); |
| 395 | parent= node.getParent(); |
| 396 | } |
| 397 | |
| 398 | if (property.isChildListProperty()) { |
| 399 | getListRewrite(parent, (ChildListPropertyDescriptor) property).remove(node, editGroup); |
| 400 | } else { |
| 401 | set(parent, property, null, editGroup); |
| 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 node, ASTNode replacement, TextEditGroup 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(node, RewriteEventStore.NEW); |
| 432 | if (location != null) { |
| 433 | property= location.getProperty(); |
| 434 | parent= location.getParent(); |
| 435 | } else { |
| 436 | throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$ |
| 437 | } |
| 438 | } else { |
| 439 | property= node.getLocationInParent(); |
| 440 | parent= node.getParent(); |
| 441 | } |
| 442 | |
| 443 | if (property.isChildListProperty()) { |
| 444 | getListRewrite(parent, (ChildListPropertyDescriptor) property).replace(node, replacement, editGroup); |
| 445 | } else { |
| 446 | set(parent, property, replacement, editGroup); |
| 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 node, StructuralPropertyDescriptor property, Object value, TextEditGroup editGroup) { |
| 472 | if (node == null || property == null) { |
| 473 | throw new IllegalArgumentException(); |
| 474 | } |
| 475 | validateIsCorrectAST(node); |
| 476 | validatePropertyType(property, value); |
| 477 | validateIsPropertyOfNode(property, node); |
| 478 | |
| 479 | NodeRewriteEvent nodeEvent= this.eventStore.getNodeEvent(node, property, true); |
| 480 | nodeEvent.setNewValue(value); |
| 481 | if (editGroup != null) { |
| 482 | this.eventStore.setEventEditGroup(nodeEvent, editGroup); |
| 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 node, StructuralPropertyDescriptor 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(node, property); |
| 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 node, ChildListPropertyDescriptor property) { |
| 522 | if (node == null || property == null) { |
| 523 | throw new IllegalArgumentException(); |
| 524 | } |
| 525 | |
| 526 | validateIsCorrectAST(node); |
| 527 | validateIsListProperty(property); |
| 528 | validateIsPropertyOfNode(property, node); |
| 529 | |
| 530 | return new ListRewrite(this, node, property); |
| 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(node, group); |
| 584 | } |
| 585 | return new TrackedNodePosition(group, node); |
| 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 message= property.getId() + " is not a list property"; //$NON-NLS-1$ |
| 603 | throw new IllegalArgumentException(message); |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | private void validateIsPropertyOfNode(StructuralPropertyDescriptor property, ASTNode node) { |
| 608 | if (!property.getNodeClass().isInstance(node)) { |
| 609 | String message= property.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 prop, Object 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() && ((SimplePropertyDescriptor) prop).isMandatory() |
| 625 | || prop.isChildProperty() && ((ChildPropertyDescriptor) prop).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 = (SimplePropertyDescriptor) prop; |
| 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 = (ChildPropertyDescriptor) prop; |
| 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 code, int nodeType) { |
| 666 | if (code == null) { |
| 667 | throw new IllegalArgumentException(); |
| 668 | } |
| 669 | ASTNode placeholder= getNodeStore().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(placeholder, code); |
| 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 res= getNodeStore().createCollapsePlaceholder(); |
| 699 | ListRewrite listRewrite= getListRewrite(res, Block.STATEMENTS_PROPERTY); |
| 700 | for (int i= 0; i < targetNodes.length; i++) { |
| 701 | listRewrite.insertLast(targetNodes[i], null); |
| 702 | } |
| 703 | return res; |
| 704 | } |
| 705 | |
| 706 | |
| 707 | private ASTNode createTargetNode(ASTNode node, boolean isMove) { |
| 708 | if (node == null) { |
| 709 | throw new IllegalArgumentException(); |
| 710 | } |
| 711 | validateIsExistingNode(node); |
| 712 | validateIsCorrectAST(node); |
| 713 | CopySourceInfo info= getRewriteEventStore().markAsCopySource(node.getParent(), node.getLocationInParent(), node, isMove); |
| 714 | |
| 715 | ASTNode placeholder= getNodeStore().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(placeholder, info); |
| 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(node, false); |
| 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(node, true); |
| 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 propertyName, Object 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(propertyName, data); |
| 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(propertyName, data); |
| 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 |
Members