Docsity

Understanding Parsers: Top-Down vs. Bottom-Up, YACC and its Use, Study notes of Programming Languages

Toggle sidebar
bg1
1
Goals of the parser, given an input program:
– Find all syntax errors; for each, produce an
appropriate diagnostic message, and recover
quickly
– Produce the parse tree, or at least a trace of
the parse tree, for the program
The Parsing Problem (cont.)
• Two categories of parsers
– Top down - produce the parse tree, beginning at the
root
• Order is that of a leftmost derivation
• Traces or builds the parse tree in preorder
– Bottom up - produce the parse tree, beginning at the
leaves
• Order is that of the reverse of a rightmost derivation
• Parsers look only one token ahead in the input
The Parsing Problem (cont.)
• Top-down Parsers
– Given a sentential form, xAα, the parser must
choose the correct A-rule to get the next sentential
form in the leftmost derivation, using only the first
token produced by A
• The most common top-down parsing
algorithms:
– Recursive descent - a coded implementation
– LL parsers - table driven implementation
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Understanding Parsers: Top-Down vs. Bottom-Up, YACC and its Use and more Study notes Programming Languages in PDF only on Docsity!

Goals of the parser, given an input program:

– Find all syntax errors; for each, produce an

appropriate diagnostic message, and recover

quickly

– Produce the parse tree, or at least a trace of

the parse tree, for the program

The Parsing Problem (cont.)

• Two categories of parsers

  • Top down - produce the parse tree, beginning at the

root

  • Order is that of a leftmost derivation
  • Traces or builds the parse tree in preorder
  • Bottom up - produce the parse tree, beginning at the

leaves

  • Order is that of the reverse of a rightmost derivation

• Parsers look only one token ahead in the input

The Parsing Problem (cont.)

• Top-down Parsers

  • Given a sentential form, xAα , the parser must

choose the correct A-rule to get the next sentential

form in the leftmost derivation, using only the first

token produced by A

• The most common top-down parsing

algorithms:

  • Recursive descent - a coded implementation
  • LL parsers - table driven implementation

The Parsing Problem (cont.)

• Bottom-up parsers

  • Given a right sentential form, α, determine what

substring of α is the right-hand side of the rule in

the grammar that must be reduced to produce the

previous sentential form in the right derivation

  • The most common bottom-up parsing algorithms

are in the LR family

  • YACC is in the LR family…

YACC Introduction

• What is YACC?

  • Tool which will produce a parser for a given

grammar.

  • YACC (Yet Another Compiler Compiler) is a

program designed to compile a LALR(1)

grammar and to produce the source code of the

syntactic analyzer of a language produced by this

grammar.

History

  • Yacc original written by

Stephen C. Johnson , 1975.

  • Variants:
    • lex, yacc (AT&T)
    • bison: a yacc replacement (GNU)
    • flex: f ast lex ical analyzer (GNU)
    • BSD yacc
    • PCLEX, PCYACC (Abraxas Software)

Definitions Section

%{

#include <stdio.h>

#include <stdlib.h>

%}

%token ID NUM

%start expr

It is a terminal

start from expr

Start Symbol

  • The first non-terminal specified in the grammar

specification section.

  • To overwrite it use %start declaration.

%start non-terminal

Rules Section

  • Is a grammar
  • Example

expr : expr '+' term | term; term : term '*' factor | factor; factor : '(' expr ')' | ID | NUM;

Rules Section

  • Normally written like this
  • Example: expr : expr '+' term | term ; term : term '*' factor | factor ; factor : '(' expr ')' | ID | NUM ;

The Position of Rules

expr : expr '+' term { $$ = $1 + $3; } | term { $$ = $1; } ; term : term '*' factor { $$ = $1 * $3; } | factor { $$ = $1; } ; factor : '(' expr ')' { $$ = $2; } | ID | NUM ;

Works with LEX

call yylex() [0-9]+

next token is NUM

NUM ‘+’ NUM

LEX and YACC need a way to identify tokens

Passing value of token

  • Every terminal-token (symbol) may represent a value

or data type

  • May be a numeric quantity in case of a number (42)
  • May be a pointer to a string ("Hello, World!")
  • When using lex, we put the value into yylval
  • In complex situations yylval is a union
  • Typical lex code: [0-9]+ {yylval = atoi(yytext); return NUM}

Passing value of token

  • Yacc allows symbols to have multiple types of value symbols

%union { double dval; int vblno; char* strval; }

Passing value of token

%union { double dval; int vblno; char strval; }*

yacc -d y.tab.h … extern YYSTYPE yylval;

[0-9]+ { yylval.vblno = atoi(yytext); return NUM;} [A-z]+ { yylval.strval = strdup(yytext); return STRING;} (^) Lex file include “y.tab.h”

Yacc Example

  • Taken from Lex & Yacc
  • Example: Simple calculator a = 4 + 6 a a= b = 7 c = a + b c c = 17 $

Grammar

expression ::= expression '+' term | expression '-' term | term

term ::= term '*' factor | term '/' factor | factor

factor ::= '(' expression ')' | '-' factor | NUMBER | NAME

#define NSYMS 20 /* maximum number of symbols */

struct symtab { char *name; double value; } symtab[NSYMS];

struct symtab *symlook();

parser.h

(^0) name value 1 name value 2 name value 3 name value (^4) name value (^5) name value 6 name value 7 name value 8 name value 9 name value (^10) name value

Symbol Table

%{ #include "y.tab.h" #include "parser.h" #include <math.h> %} %% ([0-9]+|([0-9]*.[0-9]+)([eE][-+]?[0-9]+)?) { yylval.dval = atof(yytext); return NUMBER; }

[ \t] ; /* ignore white space */

Scanner

scanner.l

[A-Za-z][A-Za-z0-9]* { /* return symbol pointer */ yylval.symp = symlook(yytext); return NAME; }

"$" { return 0; /* end of input */ }

\n |”=“|”+”|”-”|”*”|”/” return yytext[0]; %%

Scanner (cont’d)

scanner.l

Precedence / Association

1. 1-2-3 = (1-2)-3? or 1-(2-3)?

2. 1-23 = 1-(23) or (1-2)*3?

Yacc: Shift/Reduce conflicts. Default is to shift.

Precedence / Association

%right ‘=‘

%left '<' '>' NE LE GE

%left '+' '-‘

%left '*' '/'

highest precedence

Precedence / Association

expr : expr ‘+’ expr { $$ = $1 + $3; } | expr ‘-’ expr { $$ = $1 - $3; } | expr ‘*’ expr { $$ = $1 * $3; } | expr ‘/’ expr { if($3==0) yyerror(“divide 0”); else $$ = $1 / $3; } | ‘-’ expr %prec UMINUS {$$ = -$2; }

%left '+' '-' %left '*' '/' %noassoc UMINUS

IF-ELSE Ambiguity

Consider the following rule:

How about the following statement?

IF expr IF expr stmt ELSE stmt

stmt : IF expr stmt | IF expr stmt ELSE stmt ……

Error Messages

  • Bad error message:
    • Syntax error.
    • Compiler needs to give programmer a good

advice.

  • It is better to track the line number in lex:

void yyerror(char *s) { fprintf(stderr, "line %d: %s\n:", yylineno, s); }

Debug Your Parser

  1. Use –t option or define YYDEBUG to 1.
  2. Set variable yydebug to 1 when you want to

trace parsing status.

  1. If you want to trace the semantic values

z Define your YYPRINT function

Shift and Reducing: Example

stmt: stmt ‘;’ stmt

| NAME ‘=‘ exp

exp: exp ‘+’ exp

| exp ‘-’ exp | NAME | NUMBER

input: a = 7; b = 3 + a + 2

stack:

Recursive Grammar

  • Left recursion
  • Right recursion
  • LR parser (e.g. yacc) prefers left recursion.
  • LL parser prefers right recursion.

list: item | list ',' item ;

list: item | item ',' list ;

YACC Declaration Summary

`%start' Specify the grammar's start symbol

`%union' Declare the collection of data types that semantic values may have

`%token' Declare a terminal symbol (token type name) with no precedence or associativity specified

`%type' Declare the type of semantic values for a nonterminal symbol

YACC Declaration Summary

`%right' Declare a terminal symbol (token type name) that is right-associative

`%left' Declare a terminal symbol (token type name) that is left-associative

`%nonassoc' Declare a terminal symbol (token type name) that is nonassociative (using it in a way that would be associative is a syntax error, ex: x op. y op. z is syntax error)