begin(* statemen t米) begin if sym=ident getsym then(parsing ass st *) if sym>lparen begin then error (34) getsym; else if sym=becomes repeat then getsym getsym else error(13) if sym ident expression (fsys) end then error(35) else else getsym if sym=readsym until sym>comma then if sym>paren (* parsing read st.米) then error(33) end
6 begin(*statement*) if sym=ident then (*parsing ass.st.*) begin getsym; if sym=becomes then getsym else error(13); expression(fsys); end else if sym=readsym then (* parsing read st.*) begin getsym; if sym<>lparen then error(34) else repeat getsym; if sym <> ident then error(35) else getsym until sym<>comma; if sym<>rparen then error(33); end
递归下降子程序 program - function list function list→> function function listε function - FUNC identifier( parameter list statement void Parsefunction( MatchToken(T func)i Parseldentifier(i MatchToken (T LPARen) Parseparameterlistoi MatchToken(T paren; Parsestatement oi
7 递归下降子程序 program –> function_list function_list –> function function_list | function –> FUNC identifier ( parameter_list ) statement void ParseFunction() { MatchToken(T_FUNC); ParseIdentifier(); MatchToken(T_LPAREN); ParseParameterList(); MatchToken(T_RPAREN); ParseStatement(); }
void matchToken(int expected) if (lookahead ! expected)( printf("syntax error n") exit(o)i g else / if match, consume token and move on lookahead yylex ()i
8 void MatchToken(int expected) { if (lookahead != expected) { printf("syntax error \n"); exit(0); } else // if match, consume token and move on lookahead = yylex(); }
例:递归子程序实现 表达式的语法分析 表达式的EBNF 〈表达式〉∷=[+|-]〈项〉{(+|-)〈项〉} 项〉∷=〈因子〉{(*/)〈因子〉} 〈因子〉∷= ident number`(〈表达式〉
9 例:递归子程序实现 表达式的语法分析 表达式的EBNF 〈表达式〉∷=[+|-]〈项〉{(+|-)〈项〉} 〈项〉∷=〈因子〉{(*|/)〈因子〉} 〈因子〉∷=ident|number|‘(’〈表达式〉 ‘)’
procedure expr egin if sym in[ plus, minus]then egin getsym; term; end else term while sym in [plus, minus] do begin getsym; term; en d end 10
10 procedure expr; begin if sym in [ plus, minus ] then begin getsym; term; end else term; while sym in [plus, minus] do begin getsym; term; end end;