1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
|
options
{
language = "CSharp";
}
class InstrParser extends Parser;
options {
buildAST = true;
k=2;
}
tokens {
CALL; // define imaginary token CALL
}
slist
: ( stat )+
;
stat: LBRACE^ (stat)+ RBRACE
| "if"^ expr "then" stat ("else" stat)?
| ID ASSIGN^ expr SEMI
| call
;
expr
: mexpr (PLUS^ mexpr)*
;
mexpr
: atom (STAR^ atom)*
;
atom: INT
| ID
;
call: ID LPAREN (expr)? RPAREN SEMI
{#call = #(#[CALL,"CALL"], #call);}
;
class InstrLexer extends Lexer;
options {
charVocabulary = '\3'..'\377';
}
WS : (' '
| '\t'
| ('\n'|'\r'('\n')?) {newline();}
)+
;
// Single-line comments
SL_COMMENT
: "//"
(~('\n'|'\r'))* ('\n'|'\r'('\n')?)
{newline();}
;
LBRACE: '{'
;
RBRACE: '}'
;
LPAREN: '('
;
RPAREN: ')'
;
STAR: '*'
;
PLUS: '+'
;
SEMI: ';'
;
ASSIGN
: '='
;
protected
DIGIT
: '0'..'9'
;
INT : (DIGIT)+
;
ID : ('a'..'z')+
;
class InstrTreeWalker extends TreeParser;
{
/** walk list of hidden tokens in order, printing them out */
public static void dumpHidden(antlr.IHiddenStreamToken t) {
for ( ; t!=null ; t=InstrMain.filter.getHiddenAfter(t) ) {
Console.Error.Write(t.getText());
}
}
private void pr(AST p) {
Console.Out.Write(p.getText());
dumpHidden(
((antlr.CommonASTWithHiddenTokens)p).getHiddenAfter()
);
}
}
slist
: {dumpHidden(InstrMain.filter.getInitialHiddenToken());}
(stat)+
;
stat: #(LBRACE {pr(#LBRACE);} (stat)+ RBRACE {pr(#RBRACE);})
| #(i:"if" {pr(i);} expr t:"then" {pr(t);} stat (e:"else" {pr(e);} stat)?)
| #(ASSIGN ID {pr(#ID); pr(#ASSIGN);} expr SEMI {pr(#SEMI);} )
| call
;
expr
: #(PLUS expr {pr(#PLUS);} expr)
| #(STAR expr {pr(#STAR);} expr)
| INT {pr(#INT);}
| ID {pr(#ID);}
;
call: {
// add instrumentation about call; manually call rule
callDumpInstrumentation(#call);
}
#(CALL ID {pr(#ID);}
LPAREN {pr(#LPAREN);} (expr)? RPAREN {pr(#RPAREN);}
SEMI
{
// print SEMI manually; need '}' between it and whitespace
Console.Error.Write(#SEMI.getText());
Console.Error.Write("}"); // close {...} of instrumentation
dumpHidden(
((antlr.CommonASTWithHiddenTokens)#SEMI).getHiddenAfter()
);
}
)
;
/** Dump instrumentation for a call statement.
* The reference to rule expr prints out the arg
* and then at the end of this rule, we close the
* generated called to dbg.invoke().
*/
callDumpInstrumentation
: #(CALL id:ID
{Console.Error.Write("{dbg.invoke(\""+id.getText()+"\", \"");}
LPAREN (e:expr)? RPAREN SEMI
{Console.Error.Write("\"); ");}
)
;
|