Docsity

Context-Free Grammars and Parsing in Programming Languages - Prof. John D. Gannon, Assignments of Programming Languages

Toggle sidebar
bg1
1
CMSC 330: Organization of
Programming Languages
Context Free Grammars
CMSC 330 2
Where We Are
Programming languages
•
Ruby
•
OCaml
Implementing programming languages
•
Scanner
Uses regular expressions
Finite automata
•
Parser
Uses context free grammars
Pushdown automata
CMSC 330 3
This Lecture
Program syntax
•
Regular expressions & grammars
Context free grammars (CFGs )
•
Definition
•
Derivations (leftmost)
•
Parse tree
•
Ambiguity
•
Associativity & precedence
CMSC 330 4
Programming Languages
Syntax
•
What a program looks like
•
Needs to be very precise
Semantics
•
What a program means
•
How different parts of a program behave
CMSC 330 5
Motivation for Grammars
Programs are just strings of text
•
But they’re strings that have a certain structure
Informal description of structure of a C program
•
A C program is a list of declarations and definitions
•
A function definition contains parameters and a body
•
A function body is a sequence of statements
•
A statement is either an expression, a while loop, etc…
•
An expression may be assignment, addition, etc…
CMSC 330 6
Motivation for Grammars (cont.)
We want to describe program structure precisely
Regular expressions are not enough
•
No regular expression for balanced pairs of ( )’s
{ “( )”, “(( ))”, “((( )))”, “(((( ))))”, … } is not a regular language
Need to use context free gram mar (CFG)
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Context-Free Grammars and Parsing in Programming Languages - Prof. John D. Gannon and more Assignments Programming Languages in PDF only on Docsity!

CMSC 330: Organization of

Programming Languages

Context Free Grammars

CMSC 330 2

Where We Are

Programming languages

  • Ruby
  • OCaml

Implementing programming languages

  • Scanner  Uses regular expressions  Finite automata
  • Parser  Uses context free grammars  Pushdown automata

CMSC 330 3

This Lecture

Program syntax

  • Regular expressions & grammars

Context free grammars (CFGs)

  • Definition
  • Derivations (leftmost)
  • Parse tree
  • Ambiguity
  • Associativity & precedence

CMSC 330 4

Programming Languages

Syntax

  • What a program looks like
  • Needs to be very precise

Semantics

  • What a program means
  • How different parts of a program behave

CMSC 330 5

Motivation for Grammars

Programs are just strings of text

  • But they’re strings that have a certain structure

Informal description of structure of a C program

  • A C program is a list of declarations and definitions
  • A function definition contains parameters and a body
  • A function body is a sequence of statements
  • A statement is either an expression, a while loop, etc…
  • An expression may be assignment, addition, etc…

CMSC 330 6

Motivation for Grammars (cont.)

We want to describe program structure precisely

Regular expressions are not enough

  • No regular expression for balanced pairs of ( )’s  { “( )”, “(( ))”, “((( )))”, “(((( ))))”, … } is not a regular language

Need to use context free grammar (CFG)

CMSC 330 7

Context Free Grammar (CFG)

A way of generating sets of strings or languages

Grammar: S → 0S | 1S | ε

  • Means every S may be replaced by 0S, 1S, or ε
  • Example

 S 0S // using S → 0S

01S // using S → 1S

011S // using S → 1S

011 // using S → ε

Grammar is same as regular expression (0|1)*

  • Generates / accepts the same set of strings

CMSC 330 8

Context-Free Grammars (CFGs)

But CFGs can do a lot more!

  • S → ( S ) | ε // generates balanced pairs of ( )’s

In fact, CFGs subsume REs, DFAs, NFAs

  • There is a CFG that generates any regular language
  • But REs are a better notation for regular languages

CFGs can specify programming language syntax

  • CFGs (mostly) describe the parsing process

CMSC 330 9

Formal Definition

A context-free grammar G is a 4-tuple

  •  – a finite set of terminal (alphabet) symbols  Often written in lowercase
  • N – a finite, nonempty set of nonterminal symbols  Often written in uppercase

 It must be that N  = 

  • P – a set of productions of the form N  (
|N)*

 Informally this means that the nonterminal can be replaced by the string of zero or more terminals or nonterminals to the

right of the 

 Can think of productions as rewriting rules

  • S  N – the start symbol

CMSC 330 10

Backus-Naur Form

Context-free grammar production rules are also

called Backus-Naur Form or BNF

brackets and ::= instead of )

  • Often used to describe language syntax

BNF was designed by

  • John Backus  Chair of the Algol committee in the early 1960s
  • Peter Naur  Secretary of the committee, who used this notation to describe Algol in 1962

CMSC 330 11

Informal Definition of Acceptance

A string is accepted by a CFG if there is

  • Some sequence of applying productions (rewrites) starting at the start symbol that generates the string

Example

  • Grammar: S → 0S | 1S | ε
  • Sequence generating the string 010

 S 0S 01S 010S 010

Terminology

  • Such a sequence of rewrites is a derivation or parse
  • Discovering the derivation is called parsing

CMSC 330 12

Derivations

Notation

indicates a derivation of one step

  • indicates a derivation of one or more steps
  • indicates a derivation of zero or more steps

Example

  • S → 0S | 1S | ε

For the string 010

• S 0S 01S 010S 010
• S + 010
• S * S

CMSC 330 19

Sentential Forms Example

Given grammar

  • S → 0S | 1S | ε

Possible derivations

• S 0S 01S 010S 010

 S, 0S, 01S, 010S, 010 are sentential forms

  • S 1S 11S 111S 111  S, 1S, 11S, 111S, 111 are sentential forms
  • S ε  S, ε are sentential forms

In other words

  • If S * , then  is a sentential form CMSC 330 20

Language Generated by Grammar

A slightly more formal definition…

  • The language defined by a CFG is the set of all sentential forms made up of only terminals

Example

  • S → 0S | 1S | ε
  • In language Not in language 01, 000, 11, ε … 0S, a, 11S, …

CMSC 330 21

Language Generated by Grammar (cont.)

L(G), the language generated by grammar G is

L(G) = {  | 

* and S +^  }

  • S is the start symbol of the grammar
  •  is the alphabet for that grammar

In other words

  • All sentential forms with only terminals
  • All strings over

that can be derived from the start symbol via one or more productions CMSC 330 22

Practice

Given the grammar

S  aS | T

T  bT | U

U  cU |

  • Provide derivations for the following strings  b  ac  bbc
  • Does the grammar generate the following?

 S +^ ccc S +^ bS

 S +^ bab S +^ Ta

S T bT bU b

S aS aT aU acU ac

S T bT bbT bbU bbcU bbc

Yes No

No No

CMSC 330 23

Practice

Given the grammar

S  aS | T

T  bT | U

U  cU |

  • Name language accepted by grammar  abc*
  • Give a different grammar accepting language

S  ABC

A  aA | // a*

B  bB | // b*

C  cC | // c*

CMSC 330 24

Parse Trees

Parse tree shows how a string is produced by a

grammar

  • Root node is the start symbol
  • Every internal node is a nonterminal
  • Children of an internal node  Are symbols on RHS of production applied to nonterminal
  • Every leaf node is a terminal (including )

Reading the leaves left to right

  • Shows the string corresponding to the tree

CMSC 330 25

Parse Tree Example

S  aS | T

T  bT | U

U  cU |

S aS aT aU acU ac

CMSC 330 26

Parse Trees for Expressions

A parse tree shows the structure of an

expression as it corresponds to a grammar

E a | b | c | d | E+E | E-E | E*E | (E)

a ac c(b+d)

CMSC 330 27

Practice

E a | b | c | d | E+E | E-E | E*E | (E)

Make a parse tree for…

  • a*b
  • a+(b-c)
  • d*(d+b)-a
  • (a+b)*(c-d)
  • a+(b-c)*d

CMSC 330 28

Review

Why should we study CFGs?

  • Precisely describe syntax of programming languages

What are the four parts of a CFG?

  • Terminals, nonterminals, productions, start symbol

How do we tell if a string is accepted by a CFG?

  • Find a derivation from start symbol to string  By applying productions to nonterminals at each step

What’s a parse tree?

  • Representation of derivation of string

CMSC 330 29

REs and CFGs in Practice

REs turn raw text into a stream of tokens

  • E.g., “if”, “then”, “identifier”, etc.
  • This process is calling scanning or lexing
  • Whitespace and comments are simply skipped
  • These tokens become the input for the parser

CFGs turn tokens into parse trees

  • This process is called parsing
  • Parse trees become the input for the code generator

CMSC 330 30

Steps of Compilation

CMSC 330 37

CFGs for Languages

Recall that our goal is to describe programming

languages with CFGs

We had the following example which describes

limited arithmetic expressions

E  a | b | c | E+E | E-E | E*E | (E)

What’s wrong with using this grammar?

  • It’s ambiguous!

CMSC 330 38

Example: a-b-c

E E-E a-E a-E-E a-

b-E a-b-c

E E-E E-E-E

a-E-E a-b-E a-b-c

Corresponds to a-(b-c) (^) Corresponds to (a-b)-c

CMSC 330 39

Example: a-b*c

E E-E a-E a-E*E a-

bE a-bc

E E-E E-E*E

a-EE a-bE a-b*c

Corresponds to a-(bc) (^) Corresponds to (a-b)c

CMSC 330 40

Another Example: If-Then-Else

 | <if-stmt> | ...

<if-stmt>  if () |

if () else (Note < >’s are used to denote nonterminals)

Consider the following program fragment

if (x > y) if (x < z) a = 1; else a = 2; (Note: Ignore newlines)

CMSC 330 41

Parse Tree

Else belongs to inner if

CMSC 330 42

Parse Tree

Else belongs to outer if

CMSC 330 43

Dealing With Ambiguous Grammars

Ambiguity is bad

  • Syntax is correct
  • But semantics differ depending on choice  Different associativity (a-b)-c vs. a-(b-c)  Different precedence (a-b)c vs. a-(bc)  Different control flow if (if else) vs. if (if) else

Two approaches

  • Rewrite grammar
  • Use special parsing rules  Depending on parsing method (learn in CMSC 430) CMSC 330 44

Fixing the Expression Grammar

Require right operand to not be bare expression

E  E+T | E-T | E*T | T

T  a | b | c | (E)

Corresponds to left-associativity

Now only one parse tree for a-b-c

  • Find derivation

CMSC 330 45

What if We Wanted Right-Associativity?

Left-recursive productions

  • Used for left-associative operators
  • Example

E  E+T | E-T | E*T | T

T  a | b | c | (E)

Right-recursive productions

  • Used for right-associative operators
  • Example

E  T+E | T-E | T*E | T

T  a | b | c | (E)

CMSC 330 46

Parse Tree Shape

The kind of recursion determines the shape of

the parse tree

left recursion (^) right recursion

CMSC 330 47

A Different Problem

How about the string a+b*c?

E  E+T | E-T | E*T | T

T  a | b | c | (E)

Doesn’t have correct

precedence for *

  • When a nonterminal has productions for several operators, they effectively have the same precedence

CMSC 330 48

Final Expression Grammar

E  E+T | E-T | T lowest precedence operators

T  T*P | P higher precedence

P  a | b | c | (E) highest precedence (parentheses)

Practice

  • Construct tree and left and and right derivations for  a+bc a(b+c) a*b+c a-b-c
  • See what happens if you change the last set of

productions to P  a | b | c | E | (E)

  • See what happens if you change the first set of

productions to E  E +T | E-T | T | P