begin (*statement*) 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); then error (35) end else else getsym if sym=readsym until sym<>comma; then if sym<>rparen (parsing read st.*) then error (33); end 6
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 -functionfunction list s function->FUNC identifier parameter_list statement void ParseFunction ( { MatchToken (T FUNC); ParseIdentifier(); MatchToken (T LPAREN); ParseParameterList () MatchToken (T RPAREN); Parsestatement ()
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(0); else /if match,consume token and move on lookahead yylex(); } 8
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
9 例:递归子程序实现 表达式的语法分析 表达式的EBNF 〈表达式〉∷=[+|-]〈项〉{(+|-)〈项〉} 〈项〉∷=〈因子〉{(*|/)〈因子〉} 〈因子〉∷=ident|number|‘(’〈表达式〉 ‘)’
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; 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;