ContextFree Languages 1 Regular Languages 2 ContextFree Languages Slides: 48 Download presentation Context-Free Languages 1 Regular Languages 2 Context-Free Languages Regular Languages 3 Context-Free Languages Context-Free Grammars Pushdown Automata stack automaton 4 Context-Free Grammars 5 Example A context-free grammar : A derivation: 6 A context-free grammar : Another derivation: 7 Example A context-free grammar : A derivation: 9 A context-free grammar : Another derivation: 10 11 Example A context-free grammar : A derivation: 12 A context-free grammar : A derivation: 13 Definition: Context-Free Grammars Grammar Variables Terminal symbols Start variables Productions of the form: is string of variables and terminals 15 Definition: Context-Free Languages A language is context-free if and only if there is a grammar with 16 Derivation Order Leftmost derivation: Rightmost derivation: 17 Leftmost derivation: Rightmost derivation: 18 Derivation Trees 19 20 21 22 23 Derivation Tree 24 Derivation Tree yield 25 Partial Derivation Trees Partial derivation tree 26 Partial derivation tree 27 sentential form Partial derivation tree yield 28 Sometimes, derivation order doesn’t matter Leftmost: Rightmost: Same derivation tree 29 Ambiguity 30 leftmost derivation 31 leftmost derivation 32 Two derivation trees 33 The grammar is ambiguous: string has two derivation trees 34 The grammar is ambiguous: string has two leftmost derivations 35 Definition: A context-free grammar if some string is ambiguous has: two or more derivation trees 36 In other words: A context-free grammar if some string is ambiguous has: two or more leftmost derivations (or rightmost) 37 Why do we care about ambiguity? take 38 39 40 Correct result: 41 • Ambiguity is bad for programming languages • We want to remove ambiguity 42 We fix the ambiguous grammar: New non-ambiguous grammar: 43 44 Unique derivation tree 45 The grammar : is non-ambiguous: Every string has a unique derivation tree 46 Inherent Ambiguity Some context free languages have only ambiguous grammars Example: 47 The string has two derivation trees 48