Syntactic Analysis Tools - PowerPoint PPT Presentation

About This Presentation
Title:

Syntactic Analysis Tools

Description:

Syntactic Analysis Tools. Natawut Nupairoj, Ph.D. Department of ... Compile Yacc and Lex. byacc d calc.y. flex calc.l. gcc o calc y.tab.c lex.yy.c -lfl ... – PowerPoint PPT presentation

Number of Views:85
Avg rating:3.0/5.0
Slides: 12
Provided by: chulalongk
Category:

less

Transcript and Presenter's Notes

Title: Syntactic Analysis Tools


1
Syntactic Analysis Tools
  • Natawut Nupairoj, Ph.D.
  • Department of Computer Engineering
  • Chulalongkorn University

2
Outline
  • Overview.
  • Yacc Specification Format.
  • Examples.

3
Parser Generator
4
Yacc Specification
  • A Yacc source program has three parts
  • declarations
  • translation rules
  • supporting C-routines

5
Example Calculator Program
  • include ltstdio.hgt
  • token DIGIT
  • line expr '\n' printf("d\n", 1)
  • expr expr '' term 1 3
  • term
  • term term '' factor 1 3
  • factor
  • factor '(' expr ')' 2
  • DIGIT

6
Example Calculator Program
  • yylex()
  • int c
  • c getchar()
  • if(c gt '0' c lt '9')
  • yylval c - '0'
  • return DIGIT
  • return c
  • yyerror(char errmsg)
  • fprintf(stderr, "s\n", errmsg)
  • main(int argc, char argv)

7
How to use Yacc with Lex
  • yyparse calls yylex to get the next token
    automatically.
  • yylex returns
  • token type or 0 (EOF).
  • yylval - token attribute.
  • Tokens are defined in yacc definition
  • Lex definition can get them through y.tab.h.

8
Example Yacc with Lex (Yacc)
  • include ltstdio.hgt
  • token EOL NUMBER
  • line expr EOL printf("d\n", 1)
  • expr expr '' term 1 3
  • term
  • term term '' factor 1 3
  • factor
  • factor '(' expr ')' 2
  • NUMBER

9
Example Yacc with Lex (Yacc)
  • yyerror(char errmsg)
  • fprintf(stderr, "s\n", errmsg)
  • main(int argc, char argv)
  • yyparse()
  • return 0

10
Example Yacc with Lex (Lex)
  • / define constants for C program here /
  • include ltstdlib.hgt
  • include "y.tab.h"
  • extern int yylval
  • / regular definitions /
  • delim \t
  • ws delim
  • eol \n
  • number 0-9
  • symbol \\\(\)
  • ws / no action and no return /
  • eol return EOL
  • number yylval atoi(yytext)
    return(NUMBER)

11
Compile Yacc and Lex
  • byacc d calc.y
  • flex calc.l
  • gcc o calc y.tab.c lex.yy.c -lfl
Write a Comment
User Comments (0)
About PowerShow.com