• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
3  * Copyright (C) 2011, 2013-2016 The JavaParser Team.
4  *
5  * This file is part of JavaParser.
6  *
7  * JavaParser can be used either under the terms of
8  * a) the GNU Lesser General Public License as published by
9  *     the Free Software Foundation, either version 3 of the License, or
10  *     (at your option) any later version.
11  * b) the terms of the Apache License
12  *
13  * You should have received a copy of both licenses in LICENCE.LGPL and
14  * LICENCE.APACHE. Please refer to those files for details.
15  *
16  * JavaParser is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU Lesser General Public License for more details.
20  */
21 package com.github.javaparser.ast;
22 
23 import com.github.javaparser.HasParentNode;
24 import com.github.javaparser.Range;
25 import com.github.javaparser.TokenRange;
26 import com.github.javaparser.ast.comments.BlockComment;
27 import com.github.javaparser.ast.comments.Comment;
28 import com.github.javaparser.ast.comments.LineComment;
29 import com.github.javaparser.ast.nodeTypes.NodeWithRange;
30 import com.github.javaparser.ast.nodeTypes.NodeWithTokenRange;
31 import com.github.javaparser.ast.observer.AstObserver;
32 import com.github.javaparser.ast.observer.ObservableProperty;
33 import com.github.javaparser.ast.observer.PropagatingAstObserver;
34 import com.github.javaparser.ast.visitor.CloneVisitor;
35 import com.github.javaparser.ast.visitor.EqualsVisitor;
36 import com.github.javaparser.ast.visitor.HashCodeVisitor;
37 import com.github.javaparser.ast.visitor.Visitable;
38 import com.github.javaparser.metamodel.*;
39 import com.github.javaparser.printer.PrettyPrinter;
40 import com.github.javaparser.printer.PrettyPrinterConfiguration;
41 import com.github.javaparser.resolution.SymbolResolver;
42 import com.github.javaparser.resolution.types.ResolvedType;
43 
44 import java.util.*;
45 import java.util.function.Consumer;
46 import java.util.function.Function;
47 import java.util.function.Predicate;
48 import java.util.stream.Stream;
49 import java.util.stream.StreamSupport;
50 
51 import static com.github.javaparser.ast.Node.Parsedness.PARSED;
52 import static com.github.javaparser.ast.Node.TreeTraversal.PREORDER;
53 import static java.util.Collections.emptySet;
54 import static java.util.Collections.unmodifiableList;
55 import static java.util.Spliterator.DISTINCT;
56 import static java.util.Spliterator.NONNULL;
57 
58 /**
59  * Base class for all nodes of the abstract syntax tree.
60  * <h2>Construction</h2>
61  * <p>The tree is built by instantiating the required nodes, then adding them to other nodes.
62  * If it is the parser who is building the tree, it will use the largest constructor,
63  * the one with "range" as the first parameter.
64  * If you want to manually instantiate nodes, we suggest to...
65  * <ul>
66  * <li>use a convenience method, like "addStatement(...)", or if none are available...</li>
67  * <li>use a convenient constructor, like ClassOrInterfaceType(String name), or if none are available...</li>
68  * <li>use the default constructor.</li>
69  * <li>Alternatively, use one of the JavaParser.parse(snippet) methods.</li>
70  * </ul>
71  * ... and use the various methods on the node to initialize it further, if needed.
72  * <h2>Parent/child</h2>
73  * <p>The parent node field is managed automatically and can be seen as read only.
74  * Note that there is only one parent,
75  * and trying to use the same node in two places will lead to unexpected behaviour.
76  * It is advised to clone() a node before moving it around.
77  * <h2>Comments</h2>
78  * <p>Each Node can have one associated comment which describes it and
79  * a number of "orphan comments" which it contains but are not specifically
80  * associated to any child.
81  * <h2>Positions</h2>
82  * <p>When the parser creates nodes, it sets their source code position in the "range" field.
83  * When you manually instantiate nodes, their range is not set.
84  * The top left character is position 1, 1.
85  * Note that since this is an <i>abstract</i> syntax tree,
86  * it leaves out a lot of text from the original source file,
87  * like where braces or comma's are exactly.
88  * Therefore there is no position information on everything in the original source file.
89  * <h2>Observers</h2>
90  * <p>It is possible to add observers to the the tree.
91  * Any change in the tree is sent as an event to any observers watching.
92  * <h2>Visitors</h2>
93  * <p>The most comfortable way of working with an abstract syntax tree is using visitors.
94  * You can use one of the visitors in the visitor package, or extend one of them.
95  * A visitor can be "run" by calling accept on a node:
96  * <pre>node.accept(visitor, argument);</pre>
97  * where argument is an object of your choice (often simply null.)
98  *
99  * @author Julio Vilmar Gesser
100  */
101 public abstract class Node implements Cloneable, HasParentNode<Node>, Visitable, NodeWithRange<Node>, NodeWithTokenRange<Node> {
102 
103     /**
104      * Different registration mode for observers on nodes.
105      */
106     public enum ObserverRegistrationMode {
107 
108         /**
109          * Notify exclusively for changes happening on this node alone.
110          */
111         JUST_THIS_NODE,
112         /**
113          * Notify for changes happening on this node and all its descendants existing at the moment in
114          * which the observer was registered. Nodes attached later will not be observed.
115          */
116         THIS_NODE_AND_EXISTING_DESCENDANTS,
117         /**
118          * Notify for changes happening on this node and all its descendants. The descendants existing at the moment in
119          * which the observer was registered will be observed immediately. As new nodes are attached later they are
120          * automatically registered to be observed.
121          */
122         SELF_PROPAGATING
123     }
124 
125     public enum Parsedness {
126 
127         PARSED, UNPARSABLE
128     }
129 
130     /**
131      * This can be used to sort nodes on position.
132      */
133     public static Comparator<NodeWithRange<?>> NODE_BY_BEGIN_POSITION = (a, b) -> {
134         if (a.getRange().isPresent() && b.getRange().isPresent()) {
135             return a.getRange().get().begin.compareTo(b.getRange().get().begin);
136         }
137         if (a.getRange().isPresent() || b.getRange().isPresent()) {
138             if (a.getRange().isPresent()) {
139                 return 1;
140             }
141             return -1;
142         }
143         return 0;
144     };
145 
146     private static PrettyPrinterConfiguration toStringPrettyPrinterConfiguration = new PrettyPrinterConfiguration();
147 
148     protected static final PrettyPrinterConfiguration prettyPrinterNoCommentsConfiguration = new PrettyPrinterConfiguration().setPrintComments(false);
149 
150     @InternalProperty
151     private Range range;
152 
153     @InternalProperty
154     private TokenRange tokenRange;
155 
156     @InternalProperty
157     private Node parentNode;
158 
159     @InternalProperty
160     private List<Node> childNodes = new LinkedList<>();
161 
162     @InternalProperty
163     private List<Comment> orphanComments = new LinkedList<>();
164 
165     @InternalProperty
166     private IdentityHashMap<DataKey<?>, Object> data = null;
167 
168     @OptionalProperty
169     private Comment comment;
170 
171     @InternalProperty
172     private List<AstObserver> observers = new ArrayList<>();
173 
174     @InternalProperty
175     private Parsedness parsed = PARSED;
176 
Node(TokenRange tokenRange)177     protected Node(TokenRange tokenRange) {
178         setTokenRange(tokenRange);
179     }
180 
181     /**
182      * Called in every constructor for node specific code.
183      * It can't be written in the constructor itself because it will
184      * be overwritten during code generation.
185      */
customInitialization()186     protected void customInitialization() {
187     }
188 
189     /**
190      * This is a comment associated with this node.
191      *
192      * @return comment property
193      */
194     @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
getComment()195     public Optional<Comment> getComment() {
196         return Optional.ofNullable(comment);
197     }
198 
199     /**
200      * @return the range of characters in the source code that this node covers.
201      */
getRange()202     public Optional<Range> getRange() {
203         return Optional.ofNullable(range);
204     }
205 
206     /**
207      * @return the range of tokens that this node covers.
208      */
getTokenRange()209     public Optional<TokenRange> getTokenRange() {
210         return Optional.ofNullable(tokenRange);
211     }
212 
setTokenRange(TokenRange tokenRange)213     public Node setTokenRange(TokenRange tokenRange) {
214         this.tokenRange = tokenRange;
215         if (tokenRange == null || !(tokenRange.getBegin().getRange().isPresent() && tokenRange.getBegin().getRange().isPresent())) {
216             range = null;
217         } else {
218             range = new Range(tokenRange.getBegin().getRange().get().begin, tokenRange.getEnd().getRange().get().end);
219         }
220         return this;
221     }
222 
223     /**
224      * @param range the range of characters in the source code that this node covers. null can be used to indicate that
225      *              no range information is known, or that it is not of interest.
226      */
setRange(Range range)227     public Node setRange(Range range) {
228         if (this.range == range) {
229             return this;
230         }
231         notifyPropertyChange(ObservableProperty.RANGE, this.range, range);
232         this.range = range;
233         return this;
234     }
235 
236     /**
237      * Use this to store additional information to this node.
238      *
239      * @param comment to be set
240      */
setComment(final Comment comment)241     public Node setComment(final Comment comment) {
242         if (this.comment == comment) {
243             return this;
244         }
245         notifyPropertyChange(ObservableProperty.COMMENT, this.comment, comment);
246         if (this.comment != null) {
247             this.comment.setCommentedNode(null);
248         }
249         this.comment = comment;
250         if (comment != null) {
251             this.comment.setCommentedNode(this);
252         }
253         return this;
254     }
255 
256     /**
257      * Use this to store additional information to this node.
258      *
259      * @param comment to be set
260      */
setLineComment(String comment)261     public final Node setLineComment(String comment) {
262         return setComment(new LineComment(comment));
263     }
264 
265     /**
266      * Use this to store additional information to this node.
267      *
268      * @param comment to be set
269      */
setBlockComment(String comment)270     public final Node setBlockComment(String comment) {
271         return setComment(new BlockComment(comment));
272     }
273 
274     /**
275      * @return pretty printed source code for this node and its children.
276      * Formatting can be configured with Node.setToStringPrettyPrinterConfiguration.
277      */
278     @Override
toString()279     public final String toString() {
280         return new PrettyPrinter(toStringPrettyPrinterConfiguration).print(this);
281     }
282 
283     /**
284      * @return pretty printed source code for this node and its children.
285      * Formatting can be configured with parameter prettyPrinterConfiguration.
286      */
toString(PrettyPrinterConfiguration prettyPrinterConfiguration)287     public final String toString(PrettyPrinterConfiguration prettyPrinterConfiguration) {
288         return new PrettyPrinter(prettyPrinterConfiguration).print(this);
289     }
290 
291     @Override
hashCode()292     public final int hashCode() {
293         return HashCodeVisitor.hashCode(this);
294     }
295 
296     @Override
equals(final Object obj)297     public boolean equals(final Object obj) {
298         if (obj == null || !(obj instanceof Node)) {
299             return false;
300         }
301         return EqualsVisitor.equals(this, (Node) obj);
302     }
303 
304     @Override
getParentNode()305     public Optional<Node> getParentNode() {
306         return Optional.ofNullable(parentNode);
307     }
308 
309     /**
310      * Contains all nodes that have this node set as their parent.
311      * You can add and remove nodes from this list by adding or removing nodes from the fields of this node.
312      *
313      * @return all nodes that have this node as their parent.
314      */
getChildNodes()315     public List<Node> getChildNodes() {
316         return unmodifiableList(childNodes);
317     }
318 
addOrphanComment(Comment comment)319     public void addOrphanComment(Comment comment) {
320         orphanComments.add(comment);
321         comment.setParentNode(this);
322     }
323 
removeOrphanComment(Comment comment)324     public boolean removeOrphanComment(Comment comment) {
325         boolean removed = orphanComments.remove(comment);
326         if (removed) {
327             notifyPropertyChange(ObservableProperty.COMMENT, comment, null);
328             comment.setParentNode(null);
329         }
330         return removed;
331     }
332 
333     /**
334      * This is a list of Comment which are inside the node and are not associated
335      * with any meaningful AST Node.
336      * <p>
337      * For example, comments at the end of methods (immediately before the parenthesis)
338      * or at the end of CompilationUnit are orphan comments.
339      * <p>
340      * When more than one comment preceeds a statement, the one immediately preceding it
341      * it is associated with the statements, while the others are orphans.
342      * <p>
343      * Changes to this list are not persisted.
344      *
345      * @return all comments that cannot be attributed to a concept
346      */
getOrphanComments()347     public List<Comment> getOrphanComments() {
348         return new LinkedList<>(orphanComments);
349     }
350 
351     /**
352      * This is the list of Comment which are contained in the Node either because
353      * they are properly associated to one of its children or because they are floating
354      * around inside the Node
355      *
356      * @return all Comments within the node as a list
357      */
getAllContainedComments()358     public List<Comment> getAllContainedComments() {
359         List<Comment> comments = new LinkedList<>();
360         comments.addAll(getOrphanComments());
361         for (Node child : getChildNodes()) {
362             child.getComment().ifPresent(comments::add);
363             comments.addAll(child.getAllContainedComments());
364         }
365         return comments;
366     }
367 
368     /**
369      * Assign a new parent to this node, removing it
370      * from the list of children of the previous parent, if any.
371      *
372      * @param newParentNode node to be set as parent
373      */
374     @Override
setParentNode(Node newParentNode)375     public Node setParentNode(Node newParentNode) {
376         if (newParentNode == parentNode) {
377             return this;
378         }
379         observers.forEach(o -> o.parentChange(this, parentNode, newParentNode));
380         // remove from old parent, if any
381         if (parentNode != null) {
382             final List<Node> parentChildNodes = parentNode.childNodes;
383             for (int i = 0; i < parentChildNodes.size(); i++) {
384                 if (parentChildNodes.get(i) == this) {
385                     parentChildNodes.remove(i);
386                 }
387             }
388         }
389         parentNode = newParentNode;
390         // add to new parent, if any
391         if (parentNode != null) {
392             parentNode.childNodes.add(this);
393         }
394         return this;
395     }
396 
setAsParentNodeOf(Node childNode)397     protected void setAsParentNodeOf(Node childNode) {
398         if (childNode != null) {
399             childNode.setParentNode(getParentNodeForChildren());
400         }
401     }
402 
403     public static final int ABSOLUTE_BEGIN_LINE = -1;
404 
405     public static final int ABSOLUTE_END_LINE = -2;
406 
tryAddImportToParentCompilationUnit(Class<?> clazz)407     public void tryAddImportToParentCompilationUnit(Class<?> clazz) {
408         findAncestor(CompilationUnit.class).ifPresent(p -> p.addImport(clazz));
409     }
410 
411     /**
412      * Recursively finds all nodes of a certain type.
413      *
414      * @param clazz the type of node to find.
415      * @deprecated use {@link Node#findAll(Class)} but be aware that findAll also considers the initial node.
416      */
417     @Deprecated
getChildNodesByType(Class<N> clazz)418     public <N extends Node> List<N> getChildNodesByType(Class<N> clazz) {
419         List<N> nodes = new ArrayList<>();
420         for (Node child : getChildNodes()) {
421             if (clazz.isInstance(child)) {
422                 nodes.add(clazz.cast(child));
423             }
424             nodes.addAll(child.getChildNodesByType(clazz));
425         }
426         return nodes;
427     }
428 
429     /**
430      * @deprecated use {@link Node#findAll(Class)} but be aware that findAll also considers the initial node.
431      */
432     @Deprecated
getNodesByType(Class<N> clazz)433     public <N extends Node> List<N> getNodesByType(Class<N> clazz) {
434         return getChildNodesByType(clazz);
435     }
436 
437     /**
438      * Gets data for this node using the given key.
439      *
440      * @param <M> The type of the data.
441      * @param key The key for the data
442      * @return The data.
443      * @throws IllegalStateException if the key was not set in this node.
444      * @see Node#containsData(DataKey)
445      * @see DataKey
446      */
447     @SuppressWarnings("unchecked")
getData(final DataKey<M> key)448     public <M> M getData(final DataKey<M> key) {
449         if (data == null) {
450             throw new IllegalStateException("No data of this type found. Use containsData to check for this first.");
451         }
452         M value = (M) data.get(key);
453         if (value == null) {
454             throw new IllegalStateException("No data of this type found. Use containsData to check for this first.");
455         }
456         return value;
457     }
458 
459     /**
460      * This method was added to support the clone method.
461      *
462      * @return all known data keys.
463      */
getDataKeys()464     public Set<DataKey<?>> getDataKeys() {
465         if (data == null) {
466             return emptySet();
467         }
468         return data.keySet();
469     }
470 
471     /**
472      * Sets data for this node using the given key.
473      * For information on creating DataKey, see {@link DataKey}.
474      *
475      * @param <M>    The type of data
476      * @param key    The singleton key for the data
477      * @param object The data object
478      * @see DataKey
479      */
setData(DataKey<M> key, M object)480     public <M> void setData(DataKey<M> key, M object) {
481         if (data == null) {
482             data = new IdentityHashMap<>();
483         }
484         data.put(key, object);
485     }
486 
487     /**
488      * @return does this node have data for this key?
489      * @see DataKey
490      */
containsData(DataKey<?> key)491     public boolean containsData(DataKey<?> key) {
492         if (data == null) {
493             return false;
494         }
495         return data.containsKey(key);
496     }
497 
498     /**
499      * Remove data by key.
500      *
501      * @see DataKey
502      */
removeData(DataKey<ResolvedType> key)503     public void removeData(DataKey<ResolvedType> key) {
504         if (data != null) {
505             data.remove(key);
506         }
507     }
508 
509     /**
510      * Try to remove this node from the parent
511      *
512      * @return true if removed, false if it is a required property of the parent, or if the parent isn't set.
513      * @throws RuntimeException if it fails in an unexpected way
514      */
remove()515     public boolean remove() {
516         if (parentNode == null) {
517             return false;
518         }
519         return parentNode.remove(this);
520     }
521 
522     /**
523      * Try to replace this node in the parent with the supplied node.
524      *
525      * @return true if removed, or if the parent isn't set.
526      * @throws RuntimeException if it fails in an unexpected way
527      */
replace(Node node)528     public boolean replace(Node node) {
529         if (parentNode == null) {
530             return false;
531         }
532         return parentNode.replace(this, node);
533     }
534 
535     /**
536      * Forcibly removes this node from the AST.
537      * If it cannot be removed from the parent with remove(),
538      * it will try to remove its parent instead,
539      * until it finds a node that can be removed,
540      * or no parent can be found.
541      * <p>
542      * Since everything at CompilationUnit level is removable,
543      * this method will only (silently) fail when the node is in a detached AST fragment.
544      */
removeForced()545     public void removeForced() {
546         if (!remove()) {
547             getParentNode().ifPresent(Node::remove);
548         }
549     }
550 
551     @Override
getParentNodeForChildren()552     public Node getParentNodeForChildren() {
553         return this;
554     }
555 
setAsParentNodeOf(NodeList<? extends Node> list)556     protected void setAsParentNodeOf(NodeList<? extends Node> list) {
557         if (list != null) {
558             list.setParentNode(getParentNodeForChildren());
559         }
560     }
561 
notifyPropertyChange(ObservableProperty property, P oldValue, P newValue)562     public <P> void notifyPropertyChange(ObservableProperty property, P oldValue, P newValue) {
563         this.observers.forEach(o -> o.propertyChange(this, property, oldValue, newValue));
564     }
565 
566     @Override
unregister(AstObserver observer)567     public void unregister(AstObserver observer) {
568         this.observers.remove(observer);
569     }
570 
571     @Override
register(AstObserver observer)572     public void register(AstObserver observer) {
573         this.observers.add(observer);
574     }
575 
576     /**
577      * Register a new observer for the given node. Depending on the mode specified also descendants, existing
578      * and new, could be observed. For more details see <i>ObserverRegistrationMode</i>.
579      */
register(AstObserver observer, ObserverRegistrationMode mode)580     public void register(AstObserver observer, ObserverRegistrationMode mode) {
581         if (mode == null) {
582             throw new IllegalArgumentException("Mode should be not null");
583         }
584         switch (mode) {
585             case JUST_THIS_NODE:
586                 register(observer);
587                 break;
588             case THIS_NODE_AND_EXISTING_DESCENDANTS:
589                 registerForSubtree(observer);
590                 break;
591             case SELF_PROPAGATING:
592                 registerForSubtree(PropagatingAstObserver.transformInPropagatingObserver(observer));
593                 break;
594             default:
595                 throw new UnsupportedOperationException("This mode is not supported: " + mode);
596         }
597     }
598 
599     /**
600      * Register the observer for the current node and all the contained node and nodelists, recursively.
601      */
registerForSubtree(AstObserver observer)602     public void registerForSubtree(AstObserver observer) {
603         register(observer);
604         this.getChildNodes().forEach(c -> c.registerForSubtree(observer));
605         for (PropertyMetaModel property : getMetaModel().getAllPropertyMetaModels()) {
606             if (property.isNodeList()) {
607                 NodeList<?> nodeList = (NodeList<?>) property.getValue(this);
608                 if (nodeList != null)
609                     nodeList.register(observer);
610             }
611         }
612     }
613 
614     @Override
isRegistered(AstObserver observer)615     public boolean isRegistered(AstObserver observer) {
616         return this.observers.contains(observer);
617     }
618 
619     @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
remove(Node node)620     public boolean remove(Node node) {
621         if (node == null)
622             return false;
623         if (comment != null) {
624             if (node == comment) {
625                 removeComment();
626                 return true;
627             }
628         }
629         return false;
630     }
631 
632     @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
removeComment()633     public Node removeComment() {
634         return setComment((Comment) null);
635     }
636 
637     @Override
638     @Generated("com.github.javaparser.generator.core.node.CloneGenerator")
clone()639     public Node clone() {
640         return (Node) accept(new CloneVisitor(), null);
641     }
642 
643     /**
644      * @return get JavaParser specific node introspection information.
645      */
646     @Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
getMetaModel()647     public NodeMetaModel getMetaModel() {
648         return JavaParserMetaModel.nodeMetaModel;
649     }
650 
651     /**
652      * @return whether this node was successfully parsed or not.
653      * If it was not, only the range and tokenRange fields will be valid.
654      */
getParsed()655     public Parsedness getParsed() {
656         return parsed;
657     }
658 
659     /**
660      * Used by the parser to flag unparsable nodes.
661      */
setParsed(Parsedness parsed)662     public Node setParsed(Parsedness parsed) {
663         this.parsed = parsed;
664         return this;
665     }
666 
getToStringPrettyPrinterConfiguration()667     public static PrettyPrinterConfiguration getToStringPrettyPrinterConfiguration() {
668         return toStringPrettyPrinterConfiguration;
669     }
670 
setToStringPrettyPrinterConfiguration(PrettyPrinterConfiguration toStringPrettyPrinterConfiguration)671     public static void setToStringPrettyPrinterConfiguration(PrettyPrinterConfiguration toStringPrettyPrinterConfiguration) {
672         Node.toStringPrettyPrinterConfiguration = toStringPrettyPrinterConfiguration;
673     }
674 
675     @Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
replace(Node node, Node replacementNode)676     public boolean replace(Node node, Node replacementNode) {
677         if (node == null)
678             return false;
679         if (comment != null) {
680             if (node == comment) {
681                 setComment((Comment) replacementNode);
682                 return true;
683             }
684         }
685         return false;
686     }
687 
688     /**
689      * Finds the root node of this AST by finding the topmost parent.
690      */
findRootNode()691     public Node findRootNode() {
692         Node n = this;
693         while (n.getParentNode().isPresent()) {
694             n = n.getParentNode().get();
695         }
696         return n;
697     }
698 
699     /**
700      * @return the containing CompilationUnit, or empty if this node is not inside a compilation unit.
701      */
findCompilationUnit()702     public Optional<CompilationUnit> findCompilationUnit() {
703         Node rootNode = findRootNode();
704         if (rootNode instanceof CompilationUnit) {
705             return Optional.of((CompilationUnit) rootNode);
706         }
707         return Optional.empty();
708     }
709 
getSymbolResolver()710     protected SymbolResolver getSymbolResolver() {
711         return findCompilationUnit().map(cu -> {
712             SymbolResolver symbolResolver = cu.getData(SYMBOL_RESOLVER_KEY);
713             if (symbolResolver == null) {
714                 throw new IllegalStateException("Symbol resolution not configured: to configure consider setting a SymbolResolver in the ParserConfiguration");
715             }
716             return symbolResolver;
717         }).orElseThrow(() -> new IllegalStateException("The node is not inserted in a CompilationUnit"));
718     }
719 
720     // We need to expose it because we will need to use it to inject the SymbolSolver
721     public static final DataKey<SymbolResolver> SYMBOL_RESOLVER_KEY = new DataKey<SymbolResolver>() {
722     };
723 
724     public enum TreeTraversal {
725 
726         PREORDER, BREADTHFIRST, POSTORDER, PARENTS, DIRECT_CHILDREN
727     }
728 
treeIterator(TreeTraversal traversal)729     private Iterator<Node> treeIterator(TreeTraversal traversal) {
730         switch (traversal) {
731             case BREADTHFIRST:
732                 return new BreadthFirstIterator(this);
733             case POSTORDER:
734                 return new PostOrderIterator(this);
735             case PREORDER:
736                 return new PreOrderIterator(this);
737             case DIRECT_CHILDREN:
738                 return new DirectChildrenIterator(this);
739             case PARENTS:
740                 return new ParentsVisitor(this);
741             default:
742                 throw new IllegalArgumentException("Unknown traversal choice.");
743         }
744     }
745 
treeIterable(TreeTraversal traversal)746     private Iterable<Node> treeIterable(TreeTraversal traversal) {
747         return () -> treeIterator(traversal);
748     }
749 
750     /**
751      * Make a stream of nodes using traversal algorithm "traversal".
752      */
stream(TreeTraversal traversal)753     public Stream<Node> stream(TreeTraversal traversal) {
754         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(treeIterator(traversal), NONNULL | DISTINCT), false);
755     }
756 
757     /**
758      * Make a stream of nodes using pre-order traversal.
759      */
stream()760     public Stream<Node> stream() {
761         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(treeIterator(PREORDER), NONNULL | DISTINCT), false);
762     }
763 
764     /**
765      * Walks the AST, calling the consumer for every node, with traversal algorithm "traversal".
766      * <br/>This is the most general walk method. All other walk and findAll methods are based on this.
767      */
walk(TreeTraversal traversal, Consumer<Node> consumer)768     public void walk(TreeTraversal traversal, Consumer<Node> consumer) {
769         // Could be implemented as a call to the above walk method, but this is a little more efficient.
770         for (Node node : treeIterable(traversal)) {
771             consumer.accept(node);
772         }
773     }
774 
775     /**
776      * Walks the AST, calling the consumer for every node with pre-order traversal.
777      */
walk(Consumer<Node> consumer)778     public void walk(Consumer<Node> consumer) {
779         walk(PREORDER, consumer);
780     }
781 
782     /**
783      * Walks the AST with pre-order traversal, calling the consumer for every node of type "nodeType".
784      */
walk(Class<T> nodeType, Consumer<T> consumer)785     public <T extends Node> void walk(Class<T> nodeType, Consumer<T> consumer) {
786         walk(TreeTraversal.PREORDER, node -> {
787             if (nodeType.isAssignableFrom(node.getClass())) {
788                 consumer.accept(nodeType.cast(node));
789             }
790         });
791     }
792 
793     /**
794      * Walks the AST with pre-order traversal, returning all nodes of type "nodeType".
795      */
findAll(Class<T> nodeType)796     public <T extends Node> List<T> findAll(Class<T> nodeType) {
797         final List<T> found = new ArrayList<>();
798         walk(nodeType, found::add);
799         return found;
800     }
801 
802     /**
803      * Walks the AST with pre-order traversal, returning all nodes of type "nodeType" that match the predicate.
804      */
findAll(Class<T> nodeType, Predicate<T> predicate)805     public <T extends Node> List<T> findAll(Class<T> nodeType, Predicate<T> predicate) {
806         final List<T> found = new ArrayList<>();
807         walk(nodeType, n -> {
808             if (predicate.test(n))
809                 found.add(n);
810         });
811         return found;
812     }
813 
814     /**
815      * Walks the AST, applying the function for every node, with traversal algorithm "traversal". If the function
816      * returns something else than null, the traversal is stopped and the function result is returned. <br/>This is the
817      * most general findFirst method. All other findFirst methods are based on this.
818      */
findFirst(TreeTraversal traversal, Function<Node, Optional<T>> consumer)819     public <T> Optional<T> findFirst(TreeTraversal traversal, Function<Node, Optional<T>> consumer) {
820         for (Node node : treeIterable(traversal)) {
821             final Optional<T> result = consumer.apply(node);
822             if (result.isPresent()) {
823                 return result;
824             }
825         }
826         return Optional.empty();
827     }
828 
829     /**
830      * Walks the AST with pre-order traversal, returning the first node of type "nodeType" or empty() if none is found.
831      */
findFirst(Class<N> nodeType)832     public <N extends Node> Optional<N> findFirst(Class<N> nodeType) {
833         return findFirst(TreeTraversal.PREORDER, node -> {
834             if (nodeType.isAssignableFrom(node.getClass())) {
835                 return Optional.of(nodeType.cast(node));
836             }
837             return Optional.empty();
838         });
839     }
840 
841     /**
842      * Walks the AST with pre-order traversal, returning the first node of type "nodeType" that matches "predicate" or empty() if none is
843      * found.
844      */
845     public <N extends Node> Optional<N> findFirst(Class<N> nodeType, Predicate<N> predicate) {
846         return findFirst(TreeTraversal.PREORDER, node -> {
847             if (nodeType.isAssignableFrom(node.getClass())) {
848                 final N castNode = nodeType.cast(node);
849                 if (predicate.test(castNode)) {
850                     return Optional.of(castNode);
851                 }
852             }
853             return Optional.empty();
854         });
855     }
856 
857     /**
858      * Determines whether this node is an ancestor of the given node. A node is <i>not</i> an ancestor of itself.
859      *
860      * @param descendant the node for which to determine whether it has this node as an ancestor.
861      * @return {@code true} if this node is an ancestor of the given node, and {@code false} otherwise.
862      * @see HasParentNode#isDescendantOf(Node)
863      */
864     public boolean isAncestorOf(Node descendant) {
865         return this != descendant && findFirst(Node.class, n -> n == descendant).isPresent();
866     }
867 
868     /**
869      * Performs a breadth-first node traversal starting with a given node.
870      *
871      * @see <a href="https://en.wikipedia.org/wiki/Breadth-first_search">Breadth-first traversal</a>
872      */
873     public static class BreadthFirstIterator implements Iterator<Node> {
874 
875         private final Queue<Node> queue = new LinkedList<>();
876 
877         public BreadthFirstIterator(Node node) {
878             queue.add(node);
879         }
880 
881         @Override
882         public boolean hasNext() {
883             return !queue.isEmpty();
884         }
885 
886         @Override
887         public Node next() {
888             Node next = queue.remove();
889             queue.addAll(next.getChildNodes());
890             return next;
891         }
892     }
893 
894     /**
895      * Performs a simple traversal over all nodes that have the passed node as their parent.
896      */
897     public static class DirectChildrenIterator implements Iterator<Node> {
898 
899         private final Iterator<Node> childrenIterator;
900 
901         public DirectChildrenIterator(Node node) {
902             childrenIterator = new ArrayList<>(node.getChildNodes()).iterator();
903         }
904 
905         @Override
906         public boolean hasNext() {
907             return childrenIterator.hasNext();
908         }
909 
910         @Override
911         public Node next() {
912             return childrenIterator.next();
913         }
914     }
915 
916     /**
917      * Iterates over the parent of the node, then the parent's parent, then the parent's parent's parent, until running
918      * out of parents.
919      */
920     public static class ParentsVisitor implements Iterator<Node> {
921 
922         private Node node;
923 
924         public ParentsVisitor(Node node) {
925             this.node = node;
926         }
927 
928         @Override
929         public boolean hasNext() {
930             return node.getParentNode().isPresent();
931         }
932 
933         @Override
934         public Node next() {
935             node = node.getParentNode().orElse(null);
936             return node;
937         }
938     }
939 
940     /**
941      * Performs a pre-order (or depth-first) node traversal starting with a given node.
942      *
943      * @see <a href="https://en.wikipedia.org/wiki/Pre-order">Pre-order traversal</a>
944      */
945     public static class PreOrderIterator implements Iterator<Node> {
946 
947         private final Stack<Node> stack = new Stack<>();
948 
949         public PreOrderIterator(Node node) {
950             stack.add(node);
951         }
952 
953         @Override
954         public boolean hasNext() {
955             return !stack.isEmpty();
956         }
957 
958         @Override
959         public Node next() {
960             Node next = stack.pop();
961             List<Node> children = next.getChildNodes();
962             for (int i = children.size() - 1; i >= 0; i--) {
963                 stack.add(children.get(i));
964             }
965             return next;
966         }
967     }
968 
969     /**
970      * Performs a post-order (or leaves-first) node traversal starting with a given node.
971      *
972      * @see <a href="https://en.wikipedia.org/wiki/Post-order">Post-order traversal</a>
973      */
974     public static class PostOrderIterator implements Iterator<Node> {
975 
976         private final Stack<List<Node>> nodesStack = new Stack<>();
977 
978         private final Stack<Integer> cursorStack = new Stack<>();
979 
980         private final Node root;
981 
982         private boolean hasNext = true;
983 
984         public PostOrderIterator(Node root) {
985             this.root = root;
986             fillStackToLeaf(root);
987         }
988 
989         private void fillStackToLeaf(Node node) {
990             while (true) {
991                 List<Node> childNodes = new ArrayList<>(node.getChildNodes());
992                 if (childNodes.isEmpty()) {
993                     break;
994                 }
995                 nodesStack.push(childNodes);
996                 cursorStack.push(0);
997                 node = childNodes.get(0);
998             }
999         }
1000 
1001         @Override
1002         public boolean hasNext() {
1003             return hasNext;
1004         }
1005 
1006         @Override
1007         public Node next() {
1008             final List<Node> nodes = nodesStack.peek();
1009             final int cursor = cursorStack.peek();
1010             final boolean levelHasNext = cursor < nodes.size();
1011             if (levelHasNext) {
1012                 Node node = nodes.get(cursor);
1013                 fillStackToLeaf(node);
1014                 return nextFromLevel();
1015             } else {
1016                 nodesStack.pop();
1017                 cursorStack.pop();
1018                 hasNext = !nodesStack.empty();
1019                 if (hasNext) {
1020                     return nextFromLevel();
1021                 }
1022                 return root;
1023             }
1024         }
1025 
1026         private Node nextFromLevel() {
1027             final List<Node> nodes = nodesStack.peek();
1028             final int cursor = cursorStack.pop();
1029             cursorStack.push(cursor + 1);
1030             return nodes.get(cursor);
1031         }
1032     }
1033 }
1034