Created
April 1, 2014 11:24
-
-
Save sharwell/9912132 to your computer and use it in GitHub Desktop.
TreePatternTest in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace TreePatternTest | |
{ | |
using System; | |
using System.Collections.Generic; | |
using Antlr4.Runtime; | |
using Antlr4.Runtime.Tree; | |
using Antlr4.Runtime.Tree.Pattern; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string input = "3*4*5;"; | |
var charStream = new AntlrInputStream(input); | |
var lexer = new X6Lexer(charStream); | |
var tokenStream = new CommonTokenStream(lexer); | |
var parser = new X6Parser(tokenStream); | |
X6Parser.SContext compileUnit = parser.s(); | |
string pattern = "<expr> * <expr> * <expr>"; | |
var parseTreePattern = parser.CompileParseTreePattern(pattern, X6Parser.RULE_expr); | |
IList<ParseTreeMatch> matches = parseTreePattern.FindAll(compileUnit, "//expr"); | |
foreach (var match in matches) | |
{ | |
Console.WriteLine("Match: {0}", match.GetTree().GetText()); | |
foreach (KeyValuePair<string, IList<IParseTree>> pair in match.GetLabels()) | |
{ | |
Console.WriteLine(" Label: {0}", pair.Key); | |
foreach (IParseTree parseTree in pair.Value) | |
{ | |
Console.WriteLine(" {0}", parseTree.GetText()); | |
} | |
} | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
grammar X6; | |
/* | |
* Parser Rules | |
*/ | |
s | |
: expr ';' EOF | |
; | |
expr | |
: expr '*' expr | |
| expr '=' expr | |
| ID | |
| INT | |
; | |
/* | |
* Lexer Rules | |
*/ | |
ID | |
: [a-z]+ | |
; | |
INT | |
: [0-9]+ | |
; | |
WS | |
: ' ' -> channel(HIDDEN) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed for Antlr 4.9.2