Grammar

To specify the syntax of a language, we define a grammar:

  • an alphabet, (terminals and non-terminals)
  • rules
  • initial symbol
Link to original

A context-free grammar (CFG) is a formal grammar whose rules can be applied to a non-terminal symbol regardless of context.

Example: a grammar for palindromes over the alphabet

Example derivation:

Example: an (ambiguous) grammar for arithmetic expressions

Example: another ambiguous grammar with a 'dangling' else

The compiler will get confused trying to parse if a then if x then y else c.

A CFG Derivation

  1. Begin with a string containing only the start symbol
  2. Replace any non-terminal in the string by the right-hand side of some production
  3. Repeat until there are no non-terminals left:

A CFG is left-recursive if it has a non-terminal such that

Parse Trees

For a given grammar:

We can actual create a tree which represents the parsing of, for example, :

graph TB;
	1[E]-->2[T];
	1-->3[+];
	1-->4[E];
	
	2-->5[F];
	5-->6[1];
	
	4-->7[T];
	4-->8[+];
	4-->9[E];
	
	7-->10[F];
	7-->11[*];
	7-->12[T];
	
	10-->13[2];
	12-->14[F];
	14-->15[3];
	
	9-->16[T];
	16-->17[F];
	17-->18[4];

CYK Parsing Algorithm

Example

We use this triangle and move upwards, merging items below and to the right.

It is the fastest possible algorithm for recognition problem, the runtime is . However, grammars must be transformed into CNF.

Chomsky Normal Form

In the Chomsky Normal Form, we:

  • remove any

    ), , we find:

    Given the grammar for palindromes (over

Context Sensitive Grammars

A context-sensitive grammar (CSG) is a formal grammar in which the left-hand and right-hand sides of rules may be surrounded by a context of terminal and non-terminal symbols.

It is much harder to find out whether a string is parsed by a CSG.

0 items under this folder.