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. 4 */ 5 6 #pragma once 7 8 #include "tree/TerminalNode.h" 9 #include "ParserRuleContext.h" 10 #include "Recognizer.h" 11 12 namespace antlr4 { 13 namespace tree { 14 15 /// A set of utility routines useful for all kinds of ANTLR trees. 16 class ANTLR4CPP_PUBLIC Trees { 17 public: 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); 22 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); 27 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); 34 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); 38 39 /** Return true if t is u's parent or a node on path to root from u. 40 * Use == not equals(). 41 * 42 * @since 4.5.1 43 */ 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); 48 49 /** Get all descendents; includes t itself. 50 * 51 * @since 4.5.1 52 */ 53 static std::vector<ParseTree *> getDescendants(ParseTree *t); 54 55 /** @deprecated */ 56 static std::vector<ParseTree *> descendants(ParseTree *t); 57 58 /** Find smallest subtree of t enclosing range startTokenIndex..stopTokenIndex 59 * inclusively using postorder traversal. Recursive depth-first-search. 60 * 61 * @since 4.5.1 62 */ 63 static ParserRuleContext* getRootOfSubtreeEnclosingRegion(ParseTree *t, 64 size_t startTokenIndex, // inclusive 65 size_t stopTokenIndex); // inclusive 66 67 /** Return first node satisfying the pred 68 * 69 * @since 4.5.1 70 */ 71 static ParseTree* findNodeSuchThat(ParseTree *t, Ref<misc::Predicate> const& pred); 72 73 private: 74 Trees(); 75 }; 76 77 } // namespace tree 78 } // namespace antlr4 79