草稿-不会写
paser规则内不要用fragmentgrammar AHK;@header {import java.io.*;}@members {String s = "";String newLine = "<br/>";String head = "<html><body>";String foot = "</body></html>";String begin01 = "<span style=\"color:";String begin02 = "\">";String end = "</span>";String bBegin = "<strong>";String bEnd = "</strong>";String comment = "#008000";String function = "#004080";String var = "#0000ff";String ref = "#7f200f";void fillFile(String s){File dest = new File("dest.html");try {FileWriter fw = new FileWriter(dest);s = head + s + foot;fw.write(s);fw.flush();} catch (IOException e) {e.printStackTrace();}}/*** color the value*/String c(String value, String color){return begin01 + color + begin02 + value + " " + end;}/** * bold and color the value*/String bc(String value, String color){return bBegin + c(value, color) + bEnd;}}prog:stat{System.out.println(s);fillFile(s);} ; stat: (line{s+=$line.v + newLine;})+;line returns : ( function {v+=bc($function.text,function);} ( vars{v+=c($vars.text,var);} |guiSet{v+=c($guiSet.text, var);} |ref{v+=c($ref.text,ref);})* |expr {v += $expr.v;} )* ( e=NewLine{v+=$e.text;} |LINE_COMMENT{v+=c($LINE_COMMENT.text,comment);} ) ;guiSet:(ADD|SUB Identifier)+;vars:Identifier (COMMA Identifier)*;ref:'%'Identifier'%';function:Identifier COMMA*;exprreturns :e=Identifier{$v += $e.text;} EQ {$v += $EQ.text;}e=Identifier{$v += $e.text;};WS:( '\t'|' '|'\u000C' )+ { $channel = HIDDEN; } ;fragmentLetter:'A'..'Z';NewLine:'\r'? '\n' ;LINE_COMMENT : ';' ~('\n'|'\r')* '\r'? '\n' ;LPAREN: '(' ; RPAREN: ')' ; LBRACK: '[' ; RBRACK: ']' ; LBRACE: '{' ; RBRACE: '}' ; COMMA : ',' ; SEMICOLON : ';' ; ADD : '+' ; SUB : '-' ; MUL : '*' ; DIV : '/' ; EQEQ : '==' ; NE: '!=' ; LT: '<' ; LE: '<=' ; GT: '>' ; GE: '>=' ; BANG : '!' ; ANDAND: '&&' ; OROR : '||' ; EQ: '='|':=' ; IF: 'if' ; ELSE : 'else' ; WHILE : 'while' ; BREAK : 'break' ; READ : 'read' ; WRITE : 'write' ; INT : 'int' ; REAL : 'real' ; Identifier : LetterOrUnderscore ( LetterOrUnderscore | Digit )* ; Integer : Digit+ ; RealNumber : Digit+ '.' Digit+ ; fragmentDigit : '0'..'9' ; fragmentLetterOrUnderscore : Letter | '_' ;
测试代码:
import org.antlr.runtime.*;public class TestAHK { public static void main(String[] args) throws Exception { ANTLRNoCaseFileStream input = new ANTLRNoCaseFileStream("clock.ahk"); AHKLexer lexer = new AHKLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); AHKParser parser = new AHKParser(tokens);try{ parser.prog();}catch(Exception e){e.printStackTrace();} }}
页:
[1]