CS 152 - Lecture 11

Cover page image

Cay S. Horstmann

Parsing 5

Reminder: Context-Free Grammar

Repetition

Operator Precedence

Operator Associativity

LL(1) Grammars

Avoiding Left Recursion

Left Factoring

Ambiguity

Reading Grammars

Lab

???

Step 1

  1. Look at the Annotated XML Specification Section 3.1. Can you have spaces before an element name in a start tag?
    < name>

    Which grammar rule did you use to answer this question?

  2. Before the /> in an empty-element tag?
    <name />

    Which grammar rule did you use to answer this question?

  3. Around the = in an attribute?
    <name attr = "value">

    Which grammar rule did you use to answer this question?

Step 2

  1. Write a Scala parser for the grammar
    expr ::= "if" "(" number ")" expr ("else" expr)? | number

    What is your program? What do you get when you parse

    if (1) if (2) 3 else 4
  2. Ok, it's probably too tedious to figure out whether the else associates with the first or second if. Enhance your program to yield a IfExpr. Use the following outline:
    class Expr
    case class IfExpr(cond : Number, pos : Expr, neg : Expr) extends Expr
    case class Number(value : String) extends Expr
    
    class SimpleLanguageParser extends JavaTokenParsers {    
      def expr: Parser[Expr] = ... 
      def number: Parser[Number] = wholeNumber ^^ { Number(_) }
    }

    Transform cond ~ expr ~ None into IfExpr(cond, expr, null).

    Now what do you get for

    if (1) if (2) 3 else 4
  3. Does the Scala parser resolve the if/if/else ambiguity in the same way as C++, or the other way?