1 /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
2 * Use of this file is governed by the BSD 3-clause license that
3 * can be found in the LICENSE.txt file in the project root.
8 #include "tree/TerminalNode.h"
9 #include "ParserRuleContext.h"
10 #include "Recognizer.h"
15 /// A set of utility routines useful for all kinds of ANTLR trees.
16 class ANTLR4CPP_PUBLIC Trees {
18 /// Print out a whole tree in LISP form. getNodeText is used on the
19 /// node payloads to get the text for the nodes. Detect
20 /// parse trees and extract data appropriately.
21 static std::string toStringTree(ParseTree *t, bool pretty = false);
23 /// Print out a whole tree in LISP form. getNodeText is used on the
24 /// node payloads to get the text for the nodes. Detect
25 /// parse trees and extract data appropriately.
26 static std::string toStringTree(ParseTree *t, Parser *recog, bool pretty = false);
28 /// Print out a whole tree in LISP form. getNodeText is used on the
29 /// node payloads to get the text for the nodes. Detect
30 /// parse trees and extract data appropriately.
31 static std::string toStringTree(ParseTree *t, const std::vector<std::string> &ruleNames, bool pretty = false);
32 static std::string getNodeText(ParseTree *t, Parser *recog);
33 static std::string getNodeText(ParseTree *t, const std::vector<std::string> &ruleNames);
35 /// Return a list of all ancestors of this node. The first node of
36 /// list is the root and the last is the parent of this node.
37 static std::vector<ParseTree *> getAncestors(ParseTree *t);
39 /** Return true if t is u's parent or a node on path to root from u.
40 * Use == not equals().
44 static bool isAncestorOf(ParseTree *t, ParseTree *u);
45 static std::vector<ParseTree *> findAllTokenNodes(ParseTree *t, size_t ttype);
46 static std::vector<ParseTree *> findAllRuleNodes(ParseTree *t, size_t ruleIndex);
47 static std::vector<ParseTree *> findAllNodes(ParseTree *t, size_t index, bool findTokens);
49 /** Get all descendents; includes t itself.
53 static std::vector<ParseTree *> getDescendants(ParseTree *t);
56 static std::vector<ParseTree *> descendants(ParseTree *t);
58 /** Find smallest subtree of t enclosing range startTokenIndex..stopTokenIndex
59 * inclusively using postorder traversal. Recursive depth-first-search.
63 static ParserRuleContext* getRootOfSubtreeEnclosingRegion(ParseTree *t,
64 size_t startTokenIndex, // inclusive
65 size_t stopTokenIndex); // inclusive
67 /** Return first node satisfying the pred
71 static ParseTree* findNodeSuchThat(ParseTree *t, Ref<misc::Predicate> const& pred);