自顶向下语法分析器 (java实现)

这里只给出语法分析器的关键代码

 

/** * 自顶向下(递归下降方法)的语法分析器 * AUTHOR:方剑冰 * DATE:2009.12.7 * * 语法规则: * stmt → BEGIN sentences end # * sentences → sent ; sentences * | ε * sent → evaluate * evalute → ID := expr * expr → item + item * | item - item * | item * item → gene * gene * | gene / gene * | gene * gene → ID * | NUM * | ( expr ) */ package parser; import lexer.Token; import lexer.Tag; import lexer.main; public class Parser { private static Token lookahead; //记录向前看的第一个Token private static int index; //标识现在所取的Token编号 private static int num; //code中总共的Token数目 public Parser(){ index = 0; num = main.tokens.size(); if(index < num) lookahead = (Token)main.tokens.get(index++); else return; } public boolean stmt(){ return( match(Tag.BEGIN) && sentences() && match(Tag.END) && match(Tag.FINAL) ); } public boolean sentences(){ if(lookahead.tag == Tag.END){ return true; }else{ return( sent() && match(Tag.SEMICOLON) && sentences() ); } } public boolean sent(){ return( match(Tag.ID) && match(Tag.EVALUEATE) && expr() ); } public boolean expr(){ if(item()){ if(lookahead.tag == Tag.PLUS){ return( match(Tag.PLUS) && item() ); }else if(lookahead.tag == Tag.SUB){ return( match(Tag.SUB) && item() ); }else{ return true; } }else{ System.out.println("ERROR:/""+lookahead.content+"/"(in line:"+lookahead.pos+")"); return false; } } public boolean item(){ if(gene()){ if(lookahead.tag == Tag.MULT){ return( match(Tag.MULT) && gene() ); }else if(lookahead.tag == Tag.DIVI){ return( match(Tag.DIVI) && gene() ); }else{ return true; } }else{ System.out.println("ERROR:/""+lookahead.content+"/"(in line:"+lookahead.pos+")"); return false; } } public boolean gene(){ if(lookahead.tag == Tag.ID){ return match(Tag.ID); }else if(lookahead.tag == Tag.NUM){ return match(Tag.NUM); }else if(lookahead.tag == Tag.LEFTP){ return ( match(Tag.LEFTP) && expr() && match(Tag.RIGHTP) ); }else{ System.out.println("ERROR:/""+lookahead.content+"/"(in line:"+lookahead.pos+")"); return false; } } public boolean match(int tag){ if(lookahead.tag == tag){ if(index < num) lookahead = (Token)main.tokens.get(index++); return true; }else{ System.out.println("ERROR:/""+lookahead.content+"/"(in line:"+lookahead.pos+")"); return false; } } }

你可能感兴趣的:(自顶向下语法分析器 (java实现))