Presentation is loading. Please wait.

Presentation is loading. Please wait.

Context-free Languages

Similar presentations


Presentation on theme: "Context-free Languages"— Presentation transcript:

1 Context-free Languages

2 Context-free Grammar Context-free Grammars have following restrictions placed on production rules: A single nonterminal element allowed on the left side On the right side a rule is allowed to have nothing any number of terminal and/or nonterminal elements

3 Context-free Language
Language generated by context-free grammar Language parser can be implemented using pushdown (stack) machine Slower parsing than regular languages Rules allow construction of complex enough structures for any programming language Rules are still too simplistic for describing natural languages Can be used as a parser for programming languages

4 Parse Tree Tree structure to represent syntax of a given sentence
Starting symbol as root element Intermediary non-terminals as branches Terminal elements as leaves Every required syntax element is present as a node in the tree Parser may omit generating a parse tree

5 Postfix, infix, prefix calculator
"fix" refers to the position of the operator Postfix: 2 2 + Infix: 2 + 2 Prefix: + 2 2 Infix requires operator precedence and parentheses to overrule precedence Postfix and prefix don’t and can be parsed without look-ahead

6 Parser Several types of parsers Bottom-up Top-down Shift-reduce
LR - left to right scan, rightmost derivation LALR - look-ahead LR LALR(1) 1 token look-ahead LALR(k) k token look-ahead Top-down LL - left to right scan/generation, leftmost derivation LL(k) k token look-ahead

7 Bison Open source version of classic AT&T tool yacc (yet another compiler compiler) Generates a LALR(1) parser based on rules section Uses Backus-Naur form for pattern matching Allows to be interfaced with flex or can be used on its own (but then you need to write your own scanner) Provides C functions and global variables for operating the parser Manual at:

8 Bison Source File Structure
4 sections top definitions / priority rules %% rules / actions code Some sections may be empty

9 Bison source file example (calc.y)
%{ #include <stdio.h> extern int yylex(void); void yyerror(const char *s); %} %error-verbose %token NUM %% root : expr '\n' { printf("%d\n", $1); } ; expr : NUM { $$ = $1; } | expr expr '+' { $$ = $1 + $2; } void yyerror(const char *s) { printf("ERROR: %s\n", s); } int main(void) { return yyparse(); }

10 Flex source file example (calc.l)
%top{ #include "calc.tab.h" } %option noyywrap %% [0-9]+ { yylval = atoi(yytext); return NUM; } [\+\n] { return *yytext; } . ;


Download ppt "Context-free Languages"

Similar presentations


Ads by Google