# Parse Trees ## How do I get the input text for a parse-tree subtree? In ParseTree, you have this method: ```java /** Return the combined text of all leaf nodes. Does not get any * off-channel tokens (if any) so won't return whitespace and * comments if they are sent to parser on hidden channel. */ String getText(); ``` But, you probably want this method from TokenStream: ```java /** * Return the text of all tokens in the source interval of the specified * context. This method behaves like the following code, including potential * exceptions from the call to {@link #getText(Interval)}, but may be * optimized by the specific implementation. * *
If {@code ctx.getSourceInterval()} does not return a valid interval of * tokens provided by this stream, the behavior is unspecified.
* ** TokenStream stream = ...; * String text = stream.getText(ctx.getSourceInterval()); ** * @param ctx The context providing the source interval of tokens to get * text for. * @return The text of all tokens within the source interval of {@code ctx}. */ public String getText(RuleContext ctx); ``` That is, do this: ``` mytokens.getText(mySubTree); ``` ## What if I need ASTs not parse trees for a compiler, for example? For writing a compiler, either generate [LLVM-type static-single-assignment](http://llvm.org/docs/LangRef.html) form or construct an AST from the parse tree using a listener or visitor. Or, use actions in grammar, turning off auto-parse-tree construction. ## When do I use listener/visitor vs XPath vs Tree pattern matching? ### XPath XPath works great when you need to find specific nodes, possibly in certain contexts. The context is limited to the parents on the way to the root of the tree. For example, if you want to find all ID nodes, use path `//ID`. If you want all variable declarations, you might use path `//vardecl`. If you only want fields declarations, then you can use some context information via path `/classdef/vardecl`, which would only find vardecls that our children of class definitions. You can merge the results of multiple XPath `findAll()`s simulating a set union for XPath. The only caveat is that the order from the original tree is not preserved when you union multiple `findAll()` sets. ### Tree pattern matching Use tree pattern matching when you want to find specific subtree structures such as all assignments to 0 using pattern `x = 0;`. (Recall that these are very convenient because you specify the tree structure in the concrete syntax of the language described by the grammar.) If you want to find all assignments of any kind, you can use pattern `x =