Создание парсеров на основе GPLEX+GPPG
Материал из Вики ИТ мехмата ЮФУ
Комплект разработчика парсеров
SimpleLex.lex
%namespace LexScanner Alpha [a-zA-Z_] INTNUM [0-9]+ REALNUM {INTNUM}\.{INTNUM} ID [a-zA-Z_][a-zA-Z0-9_]* %% ":=" { return (int)Tokens.ASSIGN; } ";" { return (int)Tokens.SEMICOLON; } {ID} { int res = ScannerHelper.GetIDToken(yytext); if (res == (int)Tokens.ID) yylval.sVal = yytext; return res; } {INTNUM} { yylval.iVal = int.Parse(yytext); return (int)Tokens.INTNUM; } %% class ScannerHelper { private static Dictionary<string,int> keywords; static ScannerHelper() { keywords = new Dictionary<string,int>(); keywords.Add("begin",(int)Tokens.BEGIN); keywords.Add("end",(int)Tokens.END); keywords.Add("cycle",(int)Tokens.CYCLE); } public static int GetIDToken(string s) { if (keywords.ContainsKey(s.ToLower())) return keywords[s]; else return (int)Tokens.ID; } }
SimpleYacc.yacc
%{ Dictionary<string,double> vars = new Dictionary<string,double>(); %} %output = SimpleYacc.cs %union { public double dVal; public int iVal; public string sVal; public Node nVal; public StatementList stlistVal ; } %using System.IO %namespace LexScanner %start progr %token BEGIN END CYCLE ASSIGN SEMICOLON %token <iVal> INTNUM %token <sVal> ID %type <nVal> expr assign st comp cycl %type <stlistVal> stlist %% progr : stlist {} ; stlist : st { $$ = new StatementList($1);} | stlist SEMICOLON st {$1.Add($3); $$=$1;} ; st : assign {$$=$1;} | comp {$$=$1;} | cycl {$$=$1;} ; assign : ID ASSIGN expr {$$ = new AssignNode($1 as IDNode,$3 as ExprNode,AssignOpType.lexAssign);} ; expr : ID {$$ = new IDNode($1);} | INTNUM {$$ = new NumNode($1);} ; comp : BEGIN stlist END {} ; cycl : CYCLE expr st {} ; %%