Grammar Tutorial

Robert B. Heckendorn
University of Idaho

A grammar is used to specify the syntax of a language. It answers the question: What sentences are in the language and what are not? A sentence is a finite sequence of symbols from the vocabulary of the language. The grammar we discuss here is for a context free languages. The grammar is a context free grammar or CFG.

Some Definitions

A grammar has:

Backus-Naur Form (BNF) is a notation for expressing a CFG. The notation:

Here is an example grammar for simple English sentences:

<sentence> ::= <subject> <predicate>
<subject> ::= <article> <noun>
<predicate> ::= <verb> <direct-object>
<direct-object> ::= <article> <noun>
<article> ::= THE | A
<noun> ::= MAN | DOG
<verb> ::= BITES | PETS

Is the sentence "THE DOG BITES A MAN" in the language? That is does

<sentence> -> THE DOG BITES A MAN

MAN BITES DOG is not in the grammar.

Parse tree is a tree based notation for describing the way a sentence could be built from a grammar. There might be more than one parse tree for a given sentence in a language (see ambiguity).

Derivation is the list of steps used in construction of a specific parse tree for a sentence from a grammar.

Left Most Derivation is a derivation in which the left most nonterminal is always replaced first.

Parse is to show how a sentence could be built from a grammar.

Metasymbols are symbols outside the language to prevent circularity in talking about the grammar.

Some Examples

Many of the linguistic structures in a computer language come from a small set of basic idioms. Here are some basic forms for some common things you might want in your language:

Associativity and Precedence

Getting the parse tree to represent proper grouping when grouping delimiters like parentheses are missing requires that we understand associativity and precedence.

Ambiguity

The processing of sentences in a language to get their meaning usually uses the parse trees. The parse tree is a way to understand the structure of what was said in the sentence. If for a given grammar G there exists a sentence in the language for which there is more than one parse tree then G is said to be ambiguous. You only need one example sentence to make G ambiguous! Note that the language is not ambiguous, the grammar is. Also note that it is OK for there to be more than one derivation for a sentence using an unambiguous grammar. Derivation doesn't make the grammar ambiguous, parse trees do.

<sentence> ::= X | <sentence> X | X <sentence>

This grammar is ambiguous because there exists a sentence that has more than one parse tree. For example XX has two parse trees. Here is another way to get ambiguity for that language:

<sentence> ::= X | <sentence> <sentence>

Try the sentence XXX on above grammar. Can you can find two parse trees? The fix is just to do:

<sentence> ::= X | <sentence> X

Here is another very similar ambiguous grammar:

<binary-string> ::= 0 | 1 | <binary-string> <binary-string>

Here is a fix:

<binary-string> ::= 0 <binary-string> | 1 <binary-string> | 0 | 1

Ambiguity effects meaning:

        <sentence> ::= <expression>

<expression> ::= <expression> + <expression> | <expression> * <expression> | <identifier> <identifier> ::= X | Y | Z

These are in the language:

        X
        X + Y
        X + Y * Z
While the first two expressions are fine, X + Y * Z has a multiple parse trees. We want the multiply to be done first when we do a depth first traversal of the parse tree to extract the structure. How do we do this? We need to control operator precedence. Here we have added to the ambiguous grammar above to make multiply done before addition (BUT IT IS STILL AMBIGUOUS)
        <sentence> ::= <expression>
        <expression> ::= <term> | <expression> + <expression>
        <term> ::= <identifier> | <term> * <term>
        <identifier> ::= X | Y | Z

Operator Associativity determines the order of execution of homogeneous operators. Essentially is it left to right or right to left. Here we have modified the grammar to be left to to right for both + and *.

        <sentence> ::= <expression>
        <expression> ::= <term> | <expression> + <term>
        <term> ::= <identifier> | <term> * <identifier>
        <identifier> ::= X | Y | Z
Suppose we want to have both + and - be of equal precedence? We can do that here:
        <sentence> ::= <expression>
        <expression> ::= <term> | <expression> + <term> | <expression> - <term>
        <term> ::= <identifier> | <term> * <identifier>
        <identifier> ::= X | Y | Z
Note: we cannot have two operators of the same precedence in which one is left to right associative and the other is right to left associative. For example:
        <sentence> ::= <expression>
        <expression> ::= <term> | <expression> + <term> | <term> - <expression>
        <identifier> ::= X | Y | Z
If we did then the grammar would be ambiguous To see this assume for a moment that + and left to right as normal but - is right to left. How do we parse: X+Y-Z? Is it evaluated as if it is (X+Y)-Z or is it evaluated as X+(Y-Z)? Our grammar doesn't tell us.

Another way to get ambiguity

Why just adding stuff can be a bad idea: (infinite loop). We added a reference "up the grammar" to an earlier nonterminal. The result in a loop of <expression> -> <term> -> <expression> -> <term> -> ... that can go on any number of times. Therefore there is more than one parse tree since you can pick to go through the loop say 12 times or 317 times giving two different trees.

        <sentence> ::= <expression>
        <expression> ::= <term> | <expression> + <term>
        <term> ::= <identifier> | <term> * <identifier> | <expression>
        <identifier> ::= X | Y | Z

The fix is to mark each time through the loop by forcing something to be "removed" from the sentence each time. In this case we have parentheses:

        <sentence> ::= <expression>
        <expression> ::= <term> | <expression> + <term>
        <term> ::= <identifier> | <term> * <identifier> | ( <expression> )
        <identifier> ::= X | Y | Z
Now if you go through the loop 12 times you are nested 12 deep in parens but if you go through it 317 times then you are nested 317 deep.

Yet Another way to get ambiguity

A grammar is ambiguous if you have two or more paths through the grammar to a symbol. For example starting with <aardvark>:

<aardvark> :: = <cat> | <dog>
<cat> ::= <zebra>
<dog> ::= <zebra>
then you get at least two parse trees for <zebra> starting with <aardvark>. So this grammar is ambiguous. Note that
<aardvark> :: = ( <cat> ) | <dog>
<cat> ::= <zebra>
<dog> ::= <zebra>
is NOT ambiguous since <zebra> must go through <dog> or it will pickup a set of parentheses "marking" that it went via <cat>.

In this next grammar just adding on stuff to a working grammar has created two ways to get from expression to X making the grammar ambiguous.

        <expression> ::= <term> | <expression> + <term> | <identifier>
        <term> ::= <identifier> | <term> * <identifier>
        <identifier> ::= X | Y | Z | <expression>
The first parse tree is:
<expression> -> <term> -> <identifier> -> X
The second is:
<expression> -> <identifier> -> X

In summary there are 3 ways to get ambiguity.

  1. associativity:
    <sentence> ::= X | <sentence> <sentence>
    

  2. infinite loop:
            <expression> ::= <term> | <expression> + <term>
            <term> ::= <identifier> | <term> * <identifier>
            <identifier> ::= X | Y | Z | <expression>
    
  3. alternate routes:
            <expression> ::= <term> | <expression> + <term> | <identifier>
            <term> ::= <identifier> | <term> * <identifier>
            <identifier> ::= X | Y | Z | <expression>
    

The Dangling Else

  • Here is the grammar for the dangling else problem. In this problem we want to make sure that we always associate an else with last if. This prevents the ambiguity of not knowing which if an else associates with. Let's work through this. First note the ambiguity with the statement:
    if ( exp ) if ( exp ) stmt else stmt
    
    if you have the grammar:
    stmt      : IF '(' exp ')' stmt ELSE stmt
              | IF '(' exp ')' stmt
    

    Let's now solve this my creating separate nonterminals for if-statements with a paired else and without. Let a "matched if" be one in which an else is matched with the the most recent unmatched if. Let an "unmatched if" be an if with no matching else. This gives us 6 possible cases for an if-statement whose then-part or else-part may also be an if-statement. They are:

    IF '(' <exp> ')' <matched>                       // 1
    IF '(' <exp> ')' <unmatched>                     // 2
    IF '(' <exp> ')' <matched> ELSE <matched>     // 3
    IF '(' <exp> ')' <matched> ELSE <unmatched>   // 4
    IF '(' <exp> ')' <unmatched> ELSE <matched>   // 5
    IF '(' <exp> ')' <unmatched> ELSE <unmatched> // 6
    
    To have our rule of most recent unmatched if matches the else we must discard rules 5 and 6. This gives us a grammar like:
    <stmts>   ::=  <stmts> <stmt> | <stmt>
    
    <stmt>    ::= <matched> | <unmatched>
    
    <matched> ::= IF '(' <exp> ')' <matched> ELSE <matched>
                 | <other-stmts>
    
    <unmatched> ::= IF '(' <exp> ')' <matched>
                  | IF '(' <exp> ')' <unmatched>
                  | IF '(' <exp> ')' <matched> ELSE <unmatched>
    
    Here is a common mistake with the famous dangling else grammar:
    <stmts>   ::=  <stmts> <stmt> | <stmt>
    
    <stmt>    ::= <matched> | <unmatched> | <other-stmts>
    
    <matched> ::= IF '(' <exp> ')' <matched> ELSE <matched>
                 | <other-stmts>
    
    <unmatched> ::= IF '(' <exp> ')' <matched>
                  | IF '(' <exp> ')' <unmatched>
                  | IF '(' <exp> ')' <matched> ELSE <unmatched>
    
    In this case there is more than one way to get to <other-stmts>

    Here is another common mistake with the dangling else grammar:

    <stmts>   ::=  <stmts> <stmt> | <stmt>
    
    <stmt>    ::= <matched> | <unmatched> | <other-stmts>
    
    <matched> ::= IF '(' <exp> ')' <matched> ELSE <matched>
    
    <unmatched> ::= IF '(' <exp> ')' <matched>
                  | IF '(' <exp> ')' <unmatched>
                  | IF '(' <exp> ')' <matched> ELSE <unmatched>
    
    Not only is this grammar incomplete it has a trap in it. Suppose you get to <matched> or <unmatched> then you can never escape those two states.

    The power of context free and incomplete grammars

    Another problem with grammars is they do not describe all the sentences of language you had in mind. Let's look at that along with the idea that a CFG is context free.

    In a context free language you can make any substitution for a left-hand-side nonterminal suggested by any production without regard to the context in which the nonterminal occurs. For example

    <dogs> ::= corgi | other
    
    means that anywhere a dog nonterminal occurs you can replace it with a corgi or an other. Let's use this mathematical property of grammars to see if there is a difference between two languages specified by these two grammars.

    What is the difference between L_a and L_b?

    L_a:
            <sentence> ::= <exp>
            <exp> ::= <term> | <exp> + <term>
            <term> ::= <id> | <term> * <id>
            <id> ::= X | Y | Z | ( <exp> )
    

    L_b: <sentence> ::= <exp> <exp> ::= <term> | <exp> + <term> <term> ::= <id> | <term> * <id> | ( <exp> ) <id> ::= X | Y | Z

    Note that by using the rule of context freeness we can transform the grammar of L_a to:

            <sentence> ::= <exp>
            <exp> ::= <term> | <exp> + <term>
            <term> ::= <id> | <term> * <id> |  (<exp>) | <term> * (<exp>)
            <id> ::= X | Y | Z
    

    so this adds * () that wasn't in L_b. What is an example of this:

    X*(Y)
    
    Therefore X*(Y) is in L_a but not in L_b!!!

    Here is another common mistake with the dangling else grammar:

    <stmts>   ::=  <stmts> <stmt> | <stmt>
    
    <stmt>    ::= <matched> | <unmatched> | <other-stmts>
    
    <matched> ::= IF '(' <exp> ')' <matched> ELSE <matched>
    
    <unmatched> ::= IF '(' <exp> ')' <matched>
                  | IF '(' <exp> ')' <unmatched>
                  | IF '(' <exp> ')' <matched> ELSE <unmatched>
    
    Not only is this grammar incomplete it has a trap in it. Suppose you get to <matched> or <unmatched> then you can never escape those two states.

    Tips for grammar writing

    Extended BNF

    Extended BNF tries to make lists and optional arguments easy. Extended BNF uses metachars [], {}, (), *, + Note: sometimes (as in our book) {} means {}*. EBNF often says nothing about precedence or associativity and this is often defined with text about the operators. Here are a bunch of examples:


    Robert Heckendorn Up One Level Last updated: May 12, 2009 17:53