SlideShare a Scribd company logo
1 of 21
Guide to Yacc and Lex
Introduction
• Yacc: a parser generator
– Describing the input to a computer program.
– Take action when a rule matched.
• Lex: a lexical analyser generator
– Recognise regular expression
– Take action when one word matched
Example
• Configuration file
– e.g. config.ini
ID = 42
Name = EvanJiang
.
.
.
Parsing. v1
• scan file rigidly
better choice ?
if (fscanf(parfile, "ID = %sn", seed) != 1) {
fprintf(stderr, "Error reading 'Seed:'n");
exit(0);
}
Parsing. better choice
• parsing tools accept the format like :
LIST '=' VALUE {
$$ = $3; /*$$ is result, $3 is the value of "VALUE"*/
}
YACC and LEX do this work well!
Yacc Overview
Purpose: automatically write a parser program
for a grammar written in BNF.
Usage: you write a yacc source file containing
rules that look like BNF.
Yacc creates a C program that parses
according to the rules
term : term '*' factor { $$ = $1 * $3; }
| term '/' factor { $$ = $1 / $3; }
| factor { $$ = $1; }
;
factor : ID { $$ = valueof($1); }
| NUMBER { $$ = $1; }
;
Yacc Overview(2)
> yacc myparser.y
myparser.tab.c
parser source code
myparser.y
BNF rules and actions for
your grammar.
yylex.c
tokenizer function in C
> gcc -o myprog myparser.tab.c yylex.c
myprog
executable program
The programmer puts BNF rules and
token rules for the parser he wants in
a bison source file myparser.y
run yacc to create a C program
(*.tab.c) containing a parser function.
The programmer must also supply a
tokenizer named yylex( )
Yacc Overview(3)
input file to be
parsed.
yyparse( )
parser created by bison
In operation:
your main program calls yyparse( ).
yyparse( ) calls yylex() when it
wants a token.
yylex returns the type of the token.
yylex puts the value of the token in
a global variable named yylval
yyparse() call action when one rule
matched
yylex( )
tokenizer returns the type
of the next token
yylval
call action when rule
matched
Yacc source file
/* declarations go here */
%%
/* grammar rules go here */
%%
/* additional C code goes here */
The file has 3 sections, separated by "%%" lines.
Note: format for "yacc" is the same as for bison.
Yacc source file example
%{
/* C declarations and #DEFINE statements go here */
#include <stdio.h>
#define YYSTYPE double
%}
/* Bison/Yacc declarations go here */
%token NUMBER /* define token type NUMBER */
%%
/* grammar rules go here */
%%
/* additional C code goes here */
Structure of Bison or Yacc input:
Provide by yylex(), which
abstracts detail to a token
Yacc source file example(2)
%% /* Bison grammar rules */
input : /* empty production to allow an empty input */
| input line
;
line : term 'n' { printf("Result is %fn", $1); }
;
term : term '*' factor { $$ = $1 * $3; }
| term '/' factor { $$ = $1 / $3; }
| factor { $$ = $1; }
;
factor : NUMBER { $$ = $1; }
;
Yacc source file example(3)
• $1, $2, ... represent the actual values of tokens or non-
terminals (rules) that match the production.
• $$ is the result.
term : term '*' factor { $$ = $1 * $3; }
| term '/' factor { $$ = $1 / $3; }
| factor { $$ = $1; }
;
Example:
if the input matches term / factor then set the result
($$) equal to the value of term divided factor ($1 / $3).
pattern to match actionrule
Further studying
• Yacc with ambiguous grammar
Precedence / Association
• Conflicts
– shift/reduce conflict
– reduce/reduce Conflicts
• Debug
Introduction to Lex
/* Bison/Yacc declarations go here */
%token NUMBER /* define token type NUMBER */
factor : NUMBER { $$ = $1; }
;
• NUMBER,is given by Lex.
• Yacc calls yylex() to get the token and vale.
Introduction to Lex. cont.
• Lex is a program that automatically creates a
scanner in C, using rules for tokens as regular
expressions.
• Format of the input file is like Yacc.
%{
/* C definitions for scanner */
%}
flex definitions
%%
rules
%%
user code (extra C code)
Regular Expression example
Regular Expression Strings in L(R)
digit = [0-9] “0” “1” “2” “3” …
posint = digit+ “8” “412” …
int = -? posint “-42” “1024” …
[a-zA-Z_][a-zA-Z0-9_]* C identifiers
Lex example
• Read input and describes each token
read.
/* flex definitions */
DIGIT [0-9]
%%
[ tn]+ {}
-?{DIGIT}+ { printf("Number: %sn", yytext);
yylval=atoi(yytext); return NUMBER; }
n printf("End of linen"); return 0;
%%
/* all code is copied to the generated .c file*/
Example explanation
/* flex definitions */
DIGIT [0-9]
%%
[ tn]+ {}
-?{DIGIT}+ { printf("Number: %sn", yytext);
yylval=atoi(yytext); return NUMBER; }
n printf("End of linen"); return 0;
%%
/* all code is copied to the generated .c file*/
Yacc get the value Yacc get the token
Further studying
• Regular expression
• Debug
Review
> yacc –d mygrammar.y
mygrammar.tab.c
yy.tab.h
mygrammer.y
BNF rules for your
grammar.
lex.yy,c
tokenizer function in C
> gcc -o myprog mygrammar.tab.c lex.yy.c
myprog
executable program
mylex.fl
Regular expressions that
match and return tokens
> lex mylex.fl
Thanks

More Related Content

What's hot (20)

Lexical analysis
Lexical analysisLexical analysis
Lexical analysis
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
02. chapter 3 lexical analysis
02. chapter 3   lexical analysis02. chapter 3   lexical analysis
02. chapter 3 lexical analysis
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Yacc
YaccYacc
Yacc
 
Algorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms IAlgorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms I
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Chap 6(decision making-looping)
Chap 6(decision making-looping)Chap 6(decision making-looping)
Chap 6(decision making-looping)
 
Strings in c
Strings in cStrings in c
Strings in c
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Primality
PrimalityPrimality
Primality
 
LEX & YACC
LEX & YACCLEX & YACC
LEX & YACC
 
DATA REPRESENTATION
DATA  REPRESENTATIONDATA  REPRESENTATION
DATA REPRESENTATION
 
SINGLE SOURCE SHORTEST PATH.ppt
SINGLE SOURCE SHORTEST PATH.pptSINGLE SOURCE SHORTEST PATH.ppt
SINGLE SOURCE SHORTEST PATH.ppt
 
Implementation of lexical analyser
Implementation of lexical analyserImplementation of lexical analyser
Implementation of lexical analyser
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
String in programming language in c or c++
 String in programming language  in c or c++  String in programming language  in c or c++
String in programming language in c or c++
 
C if else
C if elseC if else
C if else
 

Viewers also liked (20)

Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)
 
Lexyacc
LexyaccLexyacc
Lexyacc
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Lex yacc
Lex yaccLex yacc
Lex yacc
 
Cimplementation
CimplementationCimplementation
Cimplementation
 
Ch4c
Ch4cCh4c
Ch4c
 
Flex y Bison
Flex y BisonFlex y Bison
Flex y Bison
 
Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabus
 
Chapter Five(2)
Chapter Five(2)Chapter Five(2)
Chapter Five(2)
 
Meta Languages Bnf Ebnf Student Version
Meta Languages Bnf Ebnf Student VersionMeta Languages Bnf Ebnf Student Version
Meta Languages Bnf Ebnf Student Version
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
Lex
LexLex
Lex
 
System Programming Unit IV
System Programming Unit IVSystem Programming Unit IV
System Programming Unit IV
 
Parsing example
Parsing exampleParsing example
Parsing example
 
Software tools
Software toolsSoftware tools
Software tools
 
Dhtml
DhtmlDhtml
Dhtml
 
Type checking
Type checkingType checking
Type checking
 
Compiler Design Tutorial
Compiler Design Tutorial Compiler Design Tutorial
Compiler Design Tutorial
 
Compiler design lab programs
Compiler design lab programs Compiler design lab programs
Compiler design lab programs
 
Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2
 

Similar to Yacc lex

Lex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.pptLex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.pptMohitJain296729
 
yacc installation & sample program exe.ppt
yacc installation & sample program exe.pptyacc installation & sample program exe.ppt
yacc installation & sample program exe.pptKoppala Guravaiah
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flexvip_du
 
Compiler Engineering Lab#5 : Symbol Table, Flex Tool
Compiler Engineering Lab#5 : Symbol Table, Flex ToolCompiler Engineering Lab#5 : Symbol Table, Flex Tool
Compiler Engineering Lab#5 : Symbol Table, Flex ToolMashaelQ
 
module 4_ Lex_new.ppt
module 4_ Lex_new.pptmodule 4_ Lex_new.ppt
module 4_ Lex_new.pptleyobi6147
 
Generating parsers using Ragel and Lemon
Generating parsers using Ragel and LemonGenerating parsers using Ragel and Lemon
Generating parsers using Ragel and LemonTristan Penman
 
Compiler design and lexical analyser
Compiler design and lexical analyserCompiler design and lexical analyser
Compiler design and lexical analyserabhishek gupta
 
system software
system software system software
system software randhirlpu
 
Lex and Yacc.pdf
Lex and Yacc.pdfLex and Yacc.pdf
Lex and Yacc.pdfAKASHPAL102
 
Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsAbed Bukhari
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginnersAbishek Purushothaman
 

Similar to Yacc lex (20)

Assignment2
Assignment2Assignment2
Assignment2
 
Lexyacc
LexyaccLexyacc
Lexyacc
 
Module4 lex and yacc.ppt
Module4 lex and yacc.pptModule4 lex and yacc.ppt
Module4 lex and yacc.ppt
 
Lex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.pptLex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.ppt
 
yacc installation & sample program exe.ppt
yacc installation & sample program exe.pptyacc installation & sample program exe.ppt
yacc installation & sample program exe.ppt
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flex
 
module 4.pptx
module 4.pptxmodule 4.pptx
module 4.pptx
 
Compiler Engineering Lab#5 : Symbol Table, Flex Tool
Compiler Engineering Lab#5 : Symbol Table, Flex ToolCompiler Engineering Lab#5 : Symbol Table, Flex Tool
Compiler Engineering Lab#5 : Symbol Table, Flex Tool
 
module 4_ Lex_new.ppt
module 4_ Lex_new.pptmodule 4_ Lex_new.ppt
module 4_ Lex_new.ppt
 
Handout#03
Handout#03Handout#03
Handout#03
 
Generating parsers using Ragel and Lemon
Generating parsers using Ragel and LemonGenerating parsers using Ragel and Lemon
Generating parsers using Ragel and Lemon
 
Lex programming
Lex programmingLex programming
Lex programming
 
Compiler design and lexical analyser
Compiler design and lexical analyserCompiler design and lexical analyser
Compiler design and lexical analyser
 
system software
system software system software
system software
 
Lex and Yacc.pdf
Lex and Yacc.pdfLex and Yacc.pdf
Lex and Yacc.pdf
 
Lexyacc
LexyaccLexyacc
Lexyacc
 
Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressions
 
Plc part 2
Plc  part 2Plc  part 2
Plc part 2
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
 

Recently uploaded

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Yacc lex

  • 1. Guide to Yacc and Lex
  • 2. Introduction • Yacc: a parser generator – Describing the input to a computer program. – Take action when a rule matched. • Lex: a lexical analyser generator – Recognise regular expression – Take action when one word matched
  • 3. Example • Configuration file – e.g. config.ini ID = 42 Name = EvanJiang . . .
  • 4. Parsing. v1 • scan file rigidly better choice ? if (fscanf(parfile, "ID = %sn", seed) != 1) { fprintf(stderr, "Error reading 'Seed:'n"); exit(0); }
  • 5. Parsing. better choice • parsing tools accept the format like : LIST '=' VALUE { $$ = $3; /*$$ is result, $3 is the value of "VALUE"*/ } YACC and LEX do this work well!
  • 6. Yacc Overview Purpose: automatically write a parser program for a grammar written in BNF. Usage: you write a yacc source file containing rules that look like BNF. Yacc creates a C program that parses according to the rules term : term '*' factor { $$ = $1 * $3; } | term '/' factor { $$ = $1 / $3; } | factor { $$ = $1; } ; factor : ID { $$ = valueof($1); } | NUMBER { $$ = $1; } ;
  • 7. Yacc Overview(2) > yacc myparser.y myparser.tab.c parser source code myparser.y BNF rules and actions for your grammar. yylex.c tokenizer function in C > gcc -o myprog myparser.tab.c yylex.c myprog executable program The programmer puts BNF rules and token rules for the parser he wants in a bison source file myparser.y run yacc to create a C program (*.tab.c) containing a parser function. The programmer must also supply a tokenizer named yylex( )
  • 8. Yacc Overview(3) input file to be parsed. yyparse( ) parser created by bison In operation: your main program calls yyparse( ). yyparse( ) calls yylex() when it wants a token. yylex returns the type of the token. yylex puts the value of the token in a global variable named yylval yyparse() call action when one rule matched yylex( ) tokenizer returns the type of the next token yylval call action when rule matched
  • 9. Yacc source file /* declarations go here */ %% /* grammar rules go here */ %% /* additional C code goes here */ The file has 3 sections, separated by "%%" lines. Note: format for "yacc" is the same as for bison.
  • 10. Yacc source file example %{ /* C declarations and #DEFINE statements go here */ #include <stdio.h> #define YYSTYPE double %} /* Bison/Yacc declarations go here */ %token NUMBER /* define token type NUMBER */ %% /* grammar rules go here */ %% /* additional C code goes here */ Structure of Bison or Yacc input: Provide by yylex(), which abstracts detail to a token
  • 11. Yacc source file example(2) %% /* Bison grammar rules */ input : /* empty production to allow an empty input */ | input line ; line : term 'n' { printf("Result is %fn", $1); } ; term : term '*' factor { $$ = $1 * $3; } | term '/' factor { $$ = $1 / $3; } | factor { $$ = $1; } ; factor : NUMBER { $$ = $1; } ;
  • 12. Yacc source file example(3) • $1, $2, ... represent the actual values of tokens or non- terminals (rules) that match the production. • $$ is the result. term : term '*' factor { $$ = $1 * $3; } | term '/' factor { $$ = $1 / $3; } | factor { $$ = $1; } ; Example: if the input matches term / factor then set the result ($$) equal to the value of term divided factor ($1 / $3). pattern to match actionrule
  • 13. Further studying • Yacc with ambiguous grammar Precedence / Association • Conflicts – shift/reduce conflict – reduce/reduce Conflicts • Debug
  • 14. Introduction to Lex /* Bison/Yacc declarations go here */ %token NUMBER /* define token type NUMBER */ factor : NUMBER { $$ = $1; } ; • NUMBER,is given by Lex. • Yacc calls yylex() to get the token and vale.
  • 15. Introduction to Lex. cont. • Lex is a program that automatically creates a scanner in C, using rules for tokens as regular expressions. • Format of the input file is like Yacc. %{ /* C definitions for scanner */ %} flex definitions %% rules %% user code (extra C code)
  • 16. Regular Expression example Regular Expression Strings in L(R) digit = [0-9] “0” “1” “2” “3” … posint = digit+ “8” “412” … int = -? posint “-42” “1024” … [a-zA-Z_][a-zA-Z0-9_]* C identifiers
  • 17. Lex example • Read input and describes each token read. /* flex definitions */ DIGIT [0-9] %% [ tn]+ {} -?{DIGIT}+ { printf("Number: %sn", yytext); yylval=atoi(yytext); return NUMBER; } n printf("End of linen"); return 0; %% /* all code is copied to the generated .c file*/
  • 18. Example explanation /* flex definitions */ DIGIT [0-9] %% [ tn]+ {} -?{DIGIT}+ { printf("Number: %sn", yytext); yylval=atoi(yytext); return NUMBER; } n printf("End of linen"); return 0; %% /* all code is copied to the generated .c file*/ Yacc get the value Yacc get the token
  • 19. Further studying • Regular expression • Debug
  • 20. Review > yacc –d mygrammar.y mygrammar.tab.c yy.tab.h mygrammer.y BNF rules for your grammar. lex.yy,c tokenizer function in C > gcc -o myprog mygrammar.tab.c lex.yy.c myprog executable program mylex.fl Regular expressions that match and return tokens > lex mylex.fl