Parsing Techniques




CS152

Chris Pollett

Feb. 23, 2009

Outline

Introduction

Top-down versus Bottom-up Parsing

There are two approaches to parsing:

Both methods can be automated. Yacc/Bison is a shift/reduce parser.

Recursive Descent Parsing

Example

Consider:

sentence → nounPhrase verbPhrase
nounPhrase → article noun
article → a | the

This might yield procedures such as:

void sentence (void) {nounPhrase();verbPhrase;}
void nounPhrase(void) {article(); noun();}
void article(void) {if (token=="a") match("a");
   else if (token == "the") match("the");
   else error(); }

Comments on Example

Quiz

Which of the following grammars is ambiguous:

  1. <A> → < A >b | b
  2. <A> → <A> <A> | <B>
    <B> → b
  3. <A> → <A> | <B>
    <B> → b

Left Recursion Removal

Fixing Associativity

Left Factoring

A right recursive rule like:

<expr> → <term> @ <expr> | <term>

Can also be rewritten in EBNF as:

<expr> → <term> [@ <expr> ]

This is called left factoring.

Consider:

<if-statement> → if(<expr>) <statement> |
		 if(<expr>) <statement> else <statement>

This cannot be directly translated into code as both rules begin with the same prefix, but we can "factor out" the prefix:

<if-statement> → if(<expr>) <statement> [else <statement>]

This can be code viewing the [ ] as an if clause:

void ifStatement() {
   match("if"); match("("); expression(); match(")"); statement(); 
   if(token=="else"){match("else"); statement();}
}	

Predictive Parsing

More on Predictive Parsing

Second Criteria for Predictive Parsing