Class Node
- java.lang.Object
-
- com.github.javaparser.ast.Node
-
- All Implemented Interfaces:
NodeWithRange<Node>
,NodeWithTokenRange<Node>
,Observable
,Visitable
,HasParentNode<Node>
,Cloneable
- Direct Known Subclasses:
ArrayCreationLevel
,BodyDeclaration
,CatchClause
,Comment
,CompilationUnit
,Expression
,ImportDeclaration
,MemberValuePair
,Modifier
,ModuleDeclaration
,ModuleDirective
,Name
,PackageDeclaration
,Parameter
,ReceiverParameter
,SimpleName
,Statement
,SwitchEntry
,Type
,VariableDeclarator
public abstract class Node extends Object implements Cloneable, HasParentNode<Node>, Visitable, NodeWithRange<Node>, NodeWithTokenRange<Node>
Base class for all nodes of the abstract syntax tree.Construction
The tree is built by instantiating the required nodes, then adding them to other nodes. If it is the parser who is building the tree, it will use the largest constructor, the one with "range" as the first parameter. If you want to manually instantiate nodes, we suggest to...
- use a convenience method, like "addStatement(...)", or if none are available...
- use a convenient constructor, like ClassOrInterfaceType(String name), or if none are available...
- use the default constructor.
- Alternatively, use one of the JavaParser.parse(snippet) methods.
Parent/child
The parent node field is managed automatically and can be seen as read only. Note that there is only one parent, and trying to use the same node in two places will lead to unexpected behaviour. It is advised to clone() a node before moving it around.
Comments
Each Node can have one associated comment which describes it and a number of "orphan comments" which it contains but are not specifically associated to any child.
Positions
When the parser creates nodes, it sets their source code position in the "range" field. When you manually instantiate nodes, their range is not set. The top left character is position 1, 1. Note that since this is an abstract syntax tree, it leaves out a lot of text from the original source file, like where braces or comma's are exactly. Therefore there is no position information on everything in the original source file.
Observers
It is possible to add observers to the tree. Any change in the tree is sent as an event to any observers watching.
Visitors
The most comfortable way of working with an abstract syntax tree is using visitors. You can use one of the visitors in the visitor package, or extend one of them. A visitor can be "run" by calling accept on a node:
node.accept(visitor, argument);
where argument is an object of your choice (often simply null.)- Author:
- Julio Vilmar Gesser
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
Node.BreadthFirstIterator
Performs a breadth-first node traversal starting with a given node.static class
Node.DirectChildrenIterator
Performs a simple traversal over all nodes that have the passed node as their parent.static class
Node.ObserverRegistrationMode
Different registration mode for observers on nodes.static class
Node.ParentsVisitor
Iterates over the parent of the node, then the parent's parent, then the parent's parent's parent, until running out of parents.static class
Node.Parsedness
static class
Node.PostOrderIterator
Performs a post-order (or leaves-first) node traversal starting with a given node.static class
Node.PreOrderIterator
Performs a pre-order (or depth-first) node traversal starting with a given node.static class
Node.TreeTraversal
-
Field Summary
Fields Modifier and Type Field Description static int
ABSOLUTE_BEGIN_LINE
Deprecated.static int
ABSOLUTE_END_LINE
Deprecated.static DataKey<LineSeparator>
LINE_SEPARATOR_KEY
static Comparator<NodeWithRange<?>>
NODE_BY_BEGIN_POSITION
This can be used to sort nodes on position.protected static DataKey<Boolean>
PHANTOM_KEY
protected static PrinterConfiguration
prettyPrinterNoCommentsConfiguration
protected static DataKey<Printer>
PRINTER_KEY
static DataKey<SymbolResolver>
SYMBOL_RESOLVER_KEY
-
Constructor Summary
Constructors Modifier Constructor Description protected
Node(TokenRange tokenRange)
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
addOrphanComment(Comment comment)
Node
clone()
boolean
containsData(DataKey<?> key)
protected Printer
createDefaultPrinter()
protected Printer
createDefaultPrinter(PrinterConfiguration configuration)
protected void
customInitialization()
Called in every constructor for node specific code.boolean
equals(Object obj)
<T extends Node>
List<T>findAll(Class<T> nodeType)
Walks the AST with pre-order traversal, returning all nodes of type "nodeType".<T extends Node>
List<T>findAll(Class<T> nodeType, Node.TreeTraversal traversal)
Walks the AST with specified traversal order, returning all nodes of type "nodeType".<T extends Node>
List<T>findAll(Class<T> nodeType, Predicate<T> predicate)
Walks the AST with pre-order traversal, returning all nodes of type "nodeType" that match the predicate.Optional<Node>
findByRange(Range range)
Optional<CompilationUnit>
findCompilationUnit()
<M> Optional<M>
findData(DataKey<M> key)
Gets data for this node using the given key or returns anOptional.empty()
.<T> Optional<T>
findFirst(Node.TreeTraversal traversal, Function<Node,Optional<T>> consumer)
Walks the AST, applying the function for every node, with traversal algorithm "traversal".<N extends Node>
Optional<N>findFirst(Class<N> nodeType)
Walks the AST with pre-order traversal, returning the first node of type "nodeType" or empty() if none is found.<N extends Node>
Optional<N>findFirst(Class<N> nodeType, Predicate<N> predicate)
Walks the AST with pre-order traversal, returning the first node of type "nodeType" that matches "predicate" or empty() if none is found.Node
findRootNode()
Finds the root node of this AST by finding the topmost parent.List<Comment>
getAllContainedComments()
This is the list of Comment which are contained in the Node either because they are properly associated to one of its children or because they are floating around inside the NodeList<Node>
getChildNodes()
Contains all nodes that have this node set as their parent.<N extends Node>
List<N>getChildNodesByType(Class<N> clazz)
Deprecated.usefindAll(Class)
but be aware that findAll also considers the initial node.Optional<Comment>
getComment()
This is a comment associated with this node.<M> M
getData(DataKey<M> key)
Gets data for this node using the given key.Set<DataKey<?>>
getDataKeys()
This method was added to support the clone method.protected PrinterConfiguration
getDefaultPrinterConfiguration()
LineSeparator
getLineEndingStyle()
LineSeparator
getLineEndingStyleOrDefault(LineSeparator defaultLineSeparator)
NodeMetaModel
getMetaModel()
<N extends Node>
List<N>getNodesByType(Class<N> clazz)
Deprecated.usefindAll(Class)
but be aware that findAll also considers the initial node.List<Comment>
getOrphanComments()
This is a list of Comment which are inside the node and are not associated with any meaningful AST Node.Optional<Node>
getParentNode()
Returns the parent node, orOptional.empty
if no parent is set.Node
getParentNodeForChildren()
Returns the parent node from the perspective of the children of this node.Node.Parsedness
getParsed()
protected Printer
getPrinter()
protected Printer
getPrinter(PrinterConfiguration configuration)
Optional<Range>
getRange()
SymbolResolver
getSymbolResolver()
Optional<TokenRange>
getTokenRange()
int
hashCode()
boolean
hasScope()
boolean
isAncestorOf(Node descendant)
Determines whether this node is an ancestor of the given node.boolean
isPhantom()
boolean
isRegistered(AstObserver observer)
Was this observer registered?<P> void
notifyPropertyChange(ObservableProperty property, P oldValue, P newValue)
void
register(AstObserver observer)
Register an observer.void
register(AstObserver observer, Node.ObserverRegistrationMode mode)
Register a new observer for the given node.void
registerForSubtree(AstObserver observer)
Register the observer for the current node and all the contained node and nodelists, recursively.boolean
remove()
Try to remove this node from the parentboolean
remove(Node node)
Node
removeComment()
void
removeData(DataKey<?> key)
Remove data by key.void
removeForced()
Forcibly removes this node from the AST.boolean
removeOrphanComment(Comment comment)
boolean
replace(Node node)
Try to replace this node in the parent with the supplied node.boolean
replace(Node node, Node replacementNode)
protected void
setAsParentNodeOf(Node childNode)
protected void
setAsParentNodeOf(NodeList<? extends Node> list)
Node
setBlockComment(String comment)
Use this to store additional information to this node.Node
setComment(Comment comment)
Use this to store additional information to this node.<M> void
setData(DataKey<M> key, M object)
Sets data for this node using the given key.Node
setLineComment(String comment)
Use this to store additional information to this node.Node
setParentNode(Node newParentNode)
Assign a new parent to this node, removing it from the list of children of the previous parent, if any.Node
setParsed(Node.Parsedness parsed)
Used by the parser to flag unparsable nodes.Node
setRange(Range range)
Node
setTokenRange(TokenRange tokenRange)
Stream<Node>
stream()
Make a stream of nodes using pre-order traversal.Stream<Node>
stream(Node.TreeTraversal traversal)
Make a stream of nodes using traversal algorithm "traversal".String
toString()
String
toString(PrinterConfiguration configuration)
void
tryAddImportToParentCompilationUnit(Class<?> clazz)
void
unregister(AstObserver observer)
Unregister an observer.void
walk(Node.TreeTraversal traversal, Consumer<Node> consumer)
Walks the AST, calling the consumer for every node, with traversal algorithm "traversal".<T extends Node>
voidwalk(Class<T> nodeType, Consumer<T> consumer)
Walks the AST with pre-order traversal, calling the consumer for every node of type "nodeType".void
walk(Consumer<Node> consumer)
Walks the AST, calling the consumer for every node with pre-order traversal.-
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface com.github.javaparser.HasParentNode
findAncestor, findAncestor, findAncestor, hasParentNode, isDescendantOf
-
Methods inherited from interface com.github.javaparser.ast.nodeTypes.NodeWithRange
containsWithin, containsWithinRange, getBegin, getEnd, hasRange
-
-
-
-
Field Detail
-
NODE_BY_BEGIN_POSITION
public static Comparator<NodeWithRange<?>> NODE_BY_BEGIN_POSITION
This can be used to sort nodes on position.
-
prettyPrinterNoCommentsConfiguration
protected static final PrinterConfiguration prettyPrinterNoCommentsConfiguration
-
ABSOLUTE_BEGIN_LINE
@Deprecated public static final int ABSOLUTE_BEGIN_LINE
Deprecated.- See Also:
- Constant Field Values
-
ABSOLUTE_END_LINE
@Deprecated public static final int ABSOLUTE_END_LINE
Deprecated.- See Also:
- Constant Field Values
-
SYMBOL_RESOLVER_KEY
public static final DataKey<SymbolResolver> SYMBOL_RESOLVER_KEY
-
LINE_SEPARATOR_KEY
public static final DataKey<LineSeparator> LINE_SEPARATOR_KEY
-
-
Constructor Detail
-
Node
protected Node(TokenRange tokenRange)
-
-
Method Detail
-
customInitialization
protected void customInitialization()
Called in every constructor for node specific code. It can't be written in the constructor itself because it will be overwritten during code generation.
-
getPrinter
protected Printer getPrinter()
-
getPrinter
protected Printer getPrinter(PrinterConfiguration configuration)
-
createDefaultPrinter
protected Printer createDefaultPrinter()
-
createDefaultPrinter
protected Printer createDefaultPrinter(PrinterConfiguration configuration)
-
getDefaultPrinterConfiguration
protected PrinterConfiguration getDefaultPrinterConfiguration()
-
getComment
public Optional<Comment> getComment()
This is a comment associated with this node.- Returns:
- comment property
-
getRange
public Optional<Range> getRange()
- Specified by:
getRange
in interfaceNodeWithRange<Node>
- Returns:
- the range of characters in the source code that this node covers.
-
getTokenRange
public Optional<TokenRange> getTokenRange()
- Specified by:
getTokenRange
in interfaceNodeWithTokenRange<Node>
- Returns:
- the range of tokens that this node covers.
-
setTokenRange
public Node setTokenRange(TokenRange tokenRange)
- Specified by:
setTokenRange
in interfaceNodeWithTokenRange<Node>
-
setRange
public Node setRange(Range range)
- Specified by:
setRange
in interfaceNodeWithRange<Node>
- Parameters:
range
- the range of characters in the source code that this node covers. null can be used to indicate that no range information is known, or that it is not of interest.
-
setComment
public Node setComment(Comment comment)
Use this to store additional information to this node.- Parameters:
comment
- to be set
-
setLineComment
public final Node setLineComment(String comment)
Use this to store additional information to this node.- Parameters:
comment
- to be set
-
setBlockComment
public final Node setBlockComment(String comment)
Use this to store additional information to this node.- Parameters:
comment
- to be set
-
toString
public final String toString()
-
toString
public final String toString(PrinterConfiguration configuration)
- Returns:
- pretty printed source code for this node and its children. Formatting can be configured with parameter PrinterConfiguration.
-
getParentNode
public Optional<Node> getParentNode()
Description copied from interface:HasParentNode
Returns the parent node, orOptional.empty
if no parent is set.- Specified by:
getParentNode
in interfaceHasParentNode<Node>
-
getChildNodes
public List<Node> getChildNodes()
Contains all nodes that have this node set as their parent. You can add and remove nodes from this list by adding or removing nodes from the fields of this node.- Returns:
- all nodes that have this node as their parent.
-
addOrphanComment
public void addOrphanComment(Comment comment)
-
removeOrphanComment
public boolean removeOrphanComment(Comment comment)
-
getOrphanComments
public List<Comment> getOrphanComments()
This is a list of Comment which are inside the node and are not associated with any meaningful AST Node.For example, comments at the end of methods (immediately before the parenthesis) or at the end of CompilationUnit are orphan comments.
When more than one comment preceeds a statement, the one immediately preceding it it is associated with the statements, while the others are orphans.
Changes to this list are not persisted.
- Returns:
- all comments that cannot be attributed to a concept
-
getAllContainedComments
public List<Comment> getAllContainedComments()
This is the list of Comment which are contained in the Node either because they are properly associated to one of its children or because they are floating around inside the Node- Returns:
- all Comments within the node as a list
-
setParentNode
public Node setParentNode(Node newParentNode)
Assign a new parent to this node, removing it from the list of children of the previous parent, if any.- Specified by:
setParentNode
in interfaceHasParentNode<Node>
- Parameters:
newParentNode
- node to be set as parent- Returns:
this
-
setAsParentNodeOf
protected void setAsParentNodeOf(Node childNode)
-
tryAddImportToParentCompilationUnit
public void tryAddImportToParentCompilationUnit(Class<?> clazz)
-
getChildNodesByType
@Deprecated public <N extends Node> List<N> getChildNodesByType(Class<N> clazz)
Deprecated.usefindAll(Class)
but be aware that findAll also considers the initial node.Recursively finds all nodes of a certain type.- Parameters:
clazz
- the type of node to find.
-
getNodesByType
@Deprecated public <N extends Node> List<N> getNodesByType(Class<N> clazz)
Deprecated.usefindAll(Class)
but be aware that findAll also considers the initial node.
-
getData
public <M> M getData(DataKey<M> key)
Gets data for this node using the given key.- Type Parameters:
M
- The type of the data.- Parameters:
key
- The key for the data- Returns:
- The data.
- Throws:
IllegalStateException
- if the key was not set in this node.- See Also:
containsData(DataKey)
,DataKey
-
findData
public <M> Optional<M> findData(DataKey<M> key)
Gets data for this node using the given key or returns anOptional.empty()
.- Type Parameters:
M
- The type of the data.- Parameters:
key
- The key for the data- Returns:
- The data.
- See Also:
DataKey
-
getDataKeys
public Set<DataKey<?>> getDataKeys()
This method was added to support the clone method.- Returns:
- all known data keys.
-
setData
public <M> void setData(DataKey<M> key, M object)
Sets data for this node using the given key. For information on creating DataKey, seeDataKey
.- Type Parameters:
M
- The type of data- Parameters:
key
- The singleton key for the dataobject
- The data object- See Also:
DataKey
-
containsData
public boolean containsData(DataKey<?> key)
- Returns:
- does this node have data for this key?
- See Also:
DataKey
-
remove
public boolean remove()
Try to remove this node from the parent- Returns:
- true if removed, false if it is a required property of the parent, or if the parent isn't set.
- Throws:
RuntimeException
- if it fails in an unexpected way
-
replace
public boolean replace(Node node)
Try to replace this node in the parent with the supplied node.- Returns:
- true if removed, or if the parent isn't set.
- Throws:
RuntimeException
- if it fails in an unexpected way
-
removeForced
public void removeForced()
Forcibly removes this node from the AST. If it cannot be removed from the parent with remove(), it will try to remove its parent instead, until it finds a node that can be removed, or no parent can be found.Since everything at CompilationUnit level is removable, this method will only (silently) fail when the node is in a detached AST fragment.
-
getParentNodeForChildren
public Node getParentNodeForChildren()
Description copied from interface:HasParentNode
Returns the parent node from the perspective of the children of this node.That is, this method returns
this
for everything exceptNodeList
. ANodeList
returns its parent node instead. This is because aNodeList
sets the parent of all its children to its own parent node (seeNodeList
for details).- Specified by:
getParentNodeForChildren
in interfaceHasParentNode<Node>
-
notifyPropertyChange
public <P> void notifyPropertyChange(ObservableProperty property, P oldValue, P newValue)
-
unregister
public void unregister(AstObserver observer)
Description copied from interface:Observable
Unregister an observer. If the given observer was not registered there are no effects.- Specified by:
unregister
in interfaceObservable
-
register
public void register(AstObserver observer)
Description copied from interface:Observable
Register an observer.- Specified by:
register
in interfaceObservable
-
register
public void register(AstObserver observer, Node.ObserverRegistrationMode mode)
Register a new observer for the given node. Depending on the mode specified also descendants, existing and new, could be observed. For more details see ObserverRegistrationMode.
-
registerForSubtree
public void registerForSubtree(AstObserver observer)
Register the observer for the current node and all the contained node and nodelists, recursively.
-
isRegistered
public boolean isRegistered(AstObserver observer)
Description copied from interface:Observable
Was this observer registered? Note that equals is used to determine if the given observer was registered.- Specified by:
isRegistered
in interfaceObservable
-
remove
public boolean remove(Node node)
-
removeComment
public Node removeComment()
-
getMetaModel
public NodeMetaModel getMetaModel()
- Returns:
- get JavaParser specific node introspection information.
-
getParsed
public Node.Parsedness getParsed()
- Returns:
- whether this node was successfully parsed or not. If it was not, only the range and tokenRange fields will be valid.
-
setParsed
public Node setParsed(Node.Parsedness parsed)
Used by the parser to flag unparsable nodes.
-
findRootNode
public Node findRootNode()
Finds the root node of this AST by finding the topmost parent.
-
findCompilationUnit
public Optional<CompilationUnit> findCompilationUnit()
- Returns:
- the containing CompilationUnit, or empty if this node is not inside a compilation unit.
-
getLineEndingStyleOrDefault
public LineSeparator getLineEndingStyleOrDefault(LineSeparator defaultLineSeparator)
-
getLineEndingStyle
public LineSeparator getLineEndingStyle()
-
getSymbolResolver
public SymbolResolver getSymbolResolver()
-
stream
public Stream<Node> stream(Node.TreeTraversal traversal)
Make a stream of nodes using traversal algorithm "traversal".
-
walk
public void walk(Node.TreeTraversal traversal, Consumer<Node> consumer)
Walks the AST, calling the consumer for every node, with traversal algorithm "traversal".
This is the most general walk method. All other walk and findAll methods are based on this.
-
walk
public void walk(Consumer<Node> consumer)
Walks the AST, calling the consumer for every node with pre-order traversal.
-
walk
public <T extends Node> void walk(Class<T> nodeType, Consumer<T> consumer)
Walks the AST with pre-order traversal, calling the consumer for every node of type "nodeType".
-
findAll
public <T extends Node> List<T> findAll(Class<T> nodeType)
Walks the AST with pre-order traversal, returning all nodes of type "nodeType".
-
findAll
public <T extends Node> List<T> findAll(Class<T> nodeType, Node.TreeTraversal traversal)
Walks the AST with specified traversal order, returning all nodes of type "nodeType".
-
findAll
public <T extends Node> List<T> findAll(Class<T> nodeType, Predicate<T> predicate)
Walks the AST with pre-order traversal, returning all nodes of type "nodeType" that match the predicate.
-
findFirst
public <T> Optional<T> findFirst(Node.TreeTraversal traversal, Function<Node,Optional<T>> consumer)
Walks the AST, applying the function for every node, with traversal algorithm "traversal". If the function returns something else than null, the traversal is stopped and the function result is returned.
This is the most general findFirst method. All other findFirst methods are based on this.
-
findFirst
public <N extends Node> Optional<N> findFirst(Class<N> nodeType)
Walks the AST with pre-order traversal, returning the first node of type "nodeType" or empty() if none is found.
-
findFirst
public <N extends Node> Optional<N> findFirst(Class<N> nodeType, Predicate<N> predicate)
Walks the AST with pre-order traversal, returning the first node of type "nodeType" that matches "predicate" or empty() if none is found.
-
isAncestorOf
public boolean isAncestorOf(Node descendant)
Determines whether this node is an ancestor of the given node. A node is not an ancestor of itself.- Parameters:
descendant
- the node for which to determine whether it has this node as an ancestor.- Returns:
true
if this node is an ancestor of the given node, andfalse
otherwise.- See Also:
HasParentNode.isDescendantOf(Node)
-
hasScope
public boolean hasScope()
-
isPhantom
public boolean isPhantom()
-
-