Meeting 08 - Abstract Syntax and Parsing

Bor-Yuh Evan Chang

Thursday, September 19, 2024

\(\newcommand{\TirName}[1]{\text{#1}} \newcommand{\inferrule}[3][]{ \let\and\qquad \begin{array}{@{}l@{}} \TirName{#1} \\ \displaystyle \frac{#2}{#3} \end{array} } \newcommand{\infer}[3][]{\inferrule[#1]{#2}{#3}} \)

Meeting 08 - Abstract Syntax and Parsing

What questions does your neighbor have?

In-Class Slides
In-Class Jupyter
Book Chapter

Announcements

  • HW 2 due this Friday Monday 9/23 6pm

Today

  • Revisit last bit of Concrete Syntax
  • Abstract Syntax
  • Triage Your Questions
    • Using VSCode or the terminal to test your code (on coding.csel.io)?
    • Auto-testing with GitHub Actions?
    • Lab 1?
  • Revisit and Go Deeper On:
    • Concrete Syntax (Meeting 07), if time permits

Questions?

  • Review:
    • How do you show that a grammar is ambiguous?

Questions?

One-Slide Review

Concrete syntax is …

Abstract syntax is …

Parsers convert …, which have deal with …

… and … are ways to to describe and deal with a common form of ambiguity.

An Ambiguous Grammar

\[\begin{array}{rrrl} \text{expressions} & e & \mathrel{::=}& n \mid e\;\texttt{/}\;e \mid e\;\texttt{-}\;e \end{array}\]

Abstract Syntax Trees

sealed trait Expr                                  // e ::=
case class N(n: Int) extends Expr                  //   n
case class Divide(e1: Expr, e2: Expr) extends Expr // | e1 / e2
case class Minus(e1: Expr, e2: Expr) extends Expr  // | e1 - e2

Abstract Syntax Trees

Minus(N(10), Divide(N(10), N(10)))

Abstract Syntax Trees versus Parse Trees

Parsing

Take a Theory of Computation course for more language theory. We focus here on the practical aspect of reading and writing BNF grammars.

There are also many advanced parser libraries and generator tools. You might use one in a Compiler Construction course.

An Ambiguous Grammar

\[ \begin{array}{rrrl} \text{expressions} & e & \mathrel{::=}& n \mid e + e \\ \text{numbers} & n \end{array} \]

defined trait Expr
defined class N
defined class Plus

Recursive-Descent Parsing

Automate the top-down, leftmost parsing derivation.

Recursive-Descent Parsing

Two rules:

Combinator Parsing

import $ivy.$                                                       

What’s a combinator?

Restricting the Concrete Syntax

Let’s Implement a Parser!

defined object ExprParser