SlideShare a Scribd company logo
1 of 28
L A B # 5 : S Y M B O L TA B L E , F L E X
COMPILER
ENGINEERING
WHY DO I NEED A SYMBOL TABLE?
• Symbol Table answers the following questions:
1. For a certain declaration of an Identifier name , does it have
multiple declarations in different scopes?
• If YES, keep track of these different cases
2. For a USE of an Identifier name, to which scope does it
correspond? (using the "most closely nested" rule)
3. How can various language logical structures be presented?
• One of the Main Purposes of Symbol Table is: to keep
track of IDENTIFIERS recognized in the input stream.
• All subsequent references to identifiers refer to the
appropriate symbol table index.
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
2
WHY DO I NEED A SYMBOL TABLE?
• So, Symbol Table is a group of linked hash tables that
manages either:
• IDENTIFIERS attributes,
• or convey the structure of a statementexpression that they
reflect.
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
3
BUILDING COMPILER WITH
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
4
Lexical Analysis
(Lex  Flex)
Syntax-Semantic
Analysis
(Yacc Bison)
Assembly
(LLVM)
Linking
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
5
TOKENS ARE NUMERICAL
REPRESENTATIONS OF STRINGS,
AND SIMPLIFY PROCESSING
First: Lexical Analysis with Flex
Reminder:
What is the goal of Lexical Analysis phase?
In other words, why do I use TOKENS?
BUILDING A COMPILER WITH
FLEX(LEX) & BISON(YACC)
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
6
FLEX & BISON INPUT-OUTPUT
INTERACTION
• Bas.y (Parser Input):
• Y.tab.h (Parser Output):
• is a header file that contains, among other things,
• the definitions of the token names NUM, OPA, etc.,
• and the variable yylval that we use to pass the bison code the semantic values of
tokens
• Y.tab.c (Parser Output):
• contains the CC++ code for the parser (which is a function called
yyparse())
• Bas.l (Lexica Analyzer Input):
• needs those definitions in (Y.tab.h) so that the yylex() function it defines for
bison can pass back the information it needs to pass back.
• Lex.yy.c(Lexica Analyzer Output): generated by FLEX that
contains, among other things, the definition of the yylex() function
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
7
FLEX
• Flex is an open-source tool for Fast lexical Analyzer can
be downloaded from Flex Download Webpage
• Flex reads user-specified input files
• If no input file is given, Flex will read its standard file
• Flex INPUT file:
• is a description of a scanner to generate
• The description is Pairs of Regular Expressions and C Code
called RULES
Source: Flex Website
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
8
FLEX
• When the executable runs it analyzes its input for
occurrences of text matching the Regular Expressions
(RegExp) for each rule.
• Whenever it finds a match  it executes the corresponding C
code
• Flex generates a C source file named “lex.yy.c” which
defines the function yylex()
• The file “lex.yy.c” can be compiled and linked to produce
an executable
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
9
BISON(1)
• Bison is a general-purpose parser generator that
converts an annotated context-free grammar into a
deterministic [LR or generalized LR (GLR)] parser.
• Bison, you can use it to develop a wide range of
language parsers.
• Bison is compatible with YACC
• Based on CC++ and works with Java.
(1) Source: Bison Webpage
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
10
1-4/4/12 11
Department of Computer Science -
Compiler Engineering Lab
FLEX TOOL
FIRST : LEXICAL ANALYSIS
BISONYACC & PARSING
• The grammar in the previous diagram (FlexBison
Interaction Model Diagram) is a text file you create with a
text editor
• Yacc will read your grammar and generate C code for a
syntax analyzer or parser
• The syntax analyzer uses grammar rules that allow it to
analyze tokens from the lexical analyzer and create a
syntax tree
• The syntax tree imposes a hierarchical structure on the
tokens
• e.g. operator precedence and associativity are apparent in the
syntax tree
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
12
LEXICAL ANALYSIS: FLEX IN DETAIL
• The flex generated scanner code tries to match
characters from the current input stream to these regular
expressions, and when a match is found, it executes the
associtated action code.
• The variable yytext contains the string (in the C sense,
i.e. '0' terminated char*.) of characters that were
matched.
• When more than one match is possible it breaks ties by
going with the longest match then first listed
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
13
FLEX FILES FORMAT
The general format of Lex source is:
{definitions}
%%
{rules}
%%
{user subroutines}
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
14
FLEX FILES FORMAT
• Any line which is not part of a Lex rule or action which begins
with a blank or tab is copied into the Lex generated program.
(used for Comments)
• source input prior to the first %% delimiter will be external to
any function in the code; if it appears immediately after the
first %%, it appears in an appropriate place for declarations in
the function written by
• Anything included between lines containing only %{ and %} is
copied out as above. The delimiters are discarded. This
format permits entering text like preprocessor statements that
must begin in column 1.
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
15
FLEX FILES FORMAT
• Any line which is not part of a Lex rule or action which begins
with a blank or tab is copied into the Lex generated program.
(used for Comments)
• This means each code-line must start from column one.
• source input prior to the first %% delimiter will be external to
any function in the code; if it appears immediately after the
first %%, it appears in an appropriate place for declarations in
the function written by
• Anything included between lines contain- ing only %{ and %}
is copied out as above. The delimiters are discarded. This
format permits entering text like preprocessor statements that
must begin in column 1.
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
16
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
17
EXAMPLE # 1 : CALCULATOR FLEX FILE
Write a Flex file for a calculator that is able
to recognize the following:
• numbers,
• (+,-,*,/) operators,
• and parantheses
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
18
EXAMPLE # 1 : CALCULATOR (.L)
%{
#include "ex1.tab.hpp"
#include <iostream>
using namespace std;
%}
%option noyywrap
%%
[0-9]+ { yylval.val = atoi(yytext); return NUM; }
[+|-] { yylval.sym = yytext[0]; return OPA; }
[*|/] { yylval.sym = yytext[0]; return OPM; }
"(" { return LP; }
")" { return RP; }
";" { return STOP; }
<<EOF>> { return 0; }
[ tn]+ { } . { cerr << "Unrecognized token!" << endl; exit(1); }
%%
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
19
EXAMPLE # 2 : “BASIC LANGUAGE” FILE
Write a Flex file for ”Basic Language” that is
able to recognize the following:
• Numbers,
• Identifiers,
• Keywords,
• Relation Operations
• Arthimitic operators,
• and Delimiters
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
20
EXAMPLE # 2 : (BAS.L) FILE FOR BASIC
LANGAUGE
%{
#include "y.tab.h”
%}
digit [0-9]
letter [a-zA-Z]
%%
"+" { return PLUS; }
"-" { return MINUS; }
"*" { return TIMES; }
"/" { return SLASH; }
"(" { return LPAREN; }
")" { return RPAREN; }
";" { return SEMICOLON; }
"," { return COMMA; }
"." { return PERIOD; }
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
21
EXAMPLE # 2 : (BAS.L) FILE FOR BASIC
LANGAUGE
":=" { return BECOMES; }
"=" { return EQL; }
"<>" { return NEQ; }
"<" { return LSS; }
">" { return GTR; }
"<=" { return LEQ; }
">=" { return GEQ; }
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
22
EXAMPLE # 2 : (BAS.L) FILE FOR BASIC
LANGAUGE
"begin" { return BEGINSYM; }
"call" { return CALLSYM; }
"const" { return CONSTSYM; }
"do" { return DOSYM; }
"end" { return ENDSYM; }
"if" { return IFSYM; }
"odd" { return ODDSYM; }
"procedure" { return PROCSYM; }
"then" { return THENSYM; }
"var" { return VARSYM; }
"while" { return WHILESYM; }
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
23
EXAMPLE # 2 : (BAS.L) FILE FOR BASIC
LANGAUGE
{letter}({letter}|{digit})*
{ yylval.id = (char *)strdup(yytext);
return IDENT; }
{digit}+
{ yylval.num = atoi(yytext);
return NUMBER; }
[ tnr] /* skip whitespace */
. { printf("Unknown character [%c]n",yytext[0]);
return UNKNOWN; }
%% int yywrap(void) {return 1;}
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
24
INSTALLING FLEX & BISON
• Flex & Bison are Unix-based Tools that can be installed
directly under UnixLinux environment.
• Unser Windows Environment: Flex & Bison can be
installed under Cygwin ( Linux Terminal).
• Cygwin can be downloaded from here.
• Cygwin is a Linux API layer providing substantial Linux
API functionality.
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
25
INSTALLING FLEX & BISON
• Steps to download Cygwin:
1. Click the following link for Setup
2. Click Run  Next  Choose the option “Install from Internet”
 Next  Make sure the correct installation directory then
Next
3. Choose “Direct Connection” then Next
4. Choose any of the available HTTP download sites and click
Next
5. In the “Select Packages” page: search for both “Flex” and
“Bison” packages through the search textbox  then ensure
the “install” option is selected
6. Finish the installation process by clicking Next to the end.
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
26
OVERVIEW OF ANTLR(1)
• ANTLR, ANother Tool for Language Recognition, is a
language tool that provides a framework for constructing
recognizers, interpreters, compilers, and translators from
grammatical descriptions containing actions in a variety
of target languages.
• ANTLR provides excellent support for tree construction,
tree walking, translation, error recovery, and error
reporting
• ANTLR can be downloaded from the following link
ANTLR (.jar) file download link
(1) Source: ANTLR Webpage
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
27
QUESTIONS?
Thank you for listening 
1-4/4/12
Department of Computer Science -
Compiler Engineering Lab
28

More Related Content

What's hot

Fundamentals of data structures ellis horowitz & sartaj sahni
Fundamentals of data structures   ellis horowitz & sartaj sahniFundamentals of data structures   ellis horowitz & sartaj sahni
Fundamentals of data structures ellis horowitz & sartaj sahniHitesh Wagle
 
Compiler construction tools
Compiler construction toolsCompiler construction tools
Compiler construction toolsAkhil Kaushik
 
compiler ppt on symbol table
 compiler ppt on symbol table compiler ppt on symbol table
compiler ppt on symbol tablenadarmispapaulraj
 
Feature driven development (FDD)
Feature driven development (FDD)Feature driven development (FDD)
Feature driven development (FDD)LennonDukeDuero
 
Computer Organization and Assembly Language
Computer Organization and Assembly LanguageComputer Organization and Assembly Language
Computer Organization and Assembly Languagefasihuddin90
 
Implementation issues software engineering
Implementation issues software engineeringImplementation issues software engineering
Implementation issues software engineeringrishi ram khanal
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)Sami Said
 
Type checking in compiler design
Type checking in compiler designType checking in compiler design
Type checking in compiler designSudip Singh
 
Software Engineering (Introduction to Software Engineering)
Software Engineering (Introduction to Software Engineering)Software Engineering (Introduction to Software Engineering)
Software Engineering (Introduction to Software Engineering)ShudipPal
 
Meta-modeling: concepts, tools and applications
Meta-modeling: concepts, tools and applicationsMeta-modeling: concepts, tools and applications
Meta-modeling: concepts, tools and applicationsSaïd Assar
 
Compiler Design
Compiler DesignCompiler Design
Compiler DesignMir Majid
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursionAbdullah Al-hazmy
 
2_2Specification of Tokens.ppt
2_2Specification of Tokens.ppt2_2Specification of Tokens.ppt
2_2Specification of Tokens.pptRatnakar Mikkili
 

What's hot (20)

Phases of Compiler
Phases of CompilerPhases of Compiler
Phases of Compiler
 
Fundamentals of data structures ellis horowitz & sartaj sahni
Fundamentals of data structures   ellis horowitz & sartaj sahniFundamentals of data structures   ellis horowitz & sartaj sahni
Fundamentals of data structures ellis horowitz & sartaj sahni
 
Compiler construction tools
Compiler construction toolsCompiler construction tools
Compiler construction tools
 
compiler ppt on symbol table
 compiler ppt on symbol table compiler ppt on symbol table
compiler ppt on symbol table
 
Feature driven development (FDD)
Feature driven development (FDD)Feature driven development (FDD)
Feature driven development (FDD)
 
Computer Organization and Assembly Language
Computer Organization and Assembly LanguageComputer Organization and Assembly Language
Computer Organization and Assembly Language
 
Implementation issues software engineering
Implementation issues software engineeringImplementation issues software engineering
Implementation issues software engineering
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
Type checking in compiler design
Type checking in compiler designType checking in compiler design
Type checking in compiler design
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
Software Engineering (Introduction to Software Engineering)
Software Engineering (Introduction to Software Engineering)Software Engineering (Introduction to Software Engineering)
Software Engineering (Introduction to Software Engineering)
 
Meta-modeling: concepts, tools and applications
Meta-modeling: concepts, tools and applicationsMeta-modeling: concepts, tools and applications
Meta-modeling: concepts, tools and applications
 
COMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed TranslationCOMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed Translation
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Direct linking loaders
Direct linking loadersDirect linking loaders
Direct linking loaders
 
Design notation
Design notationDesign notation
Design notation
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Compiler design
Compiler designCompiler design
Compiler design
 
2_2Specification of Tokens.ppt
2_2Specification of Tokens.ppt2_2Specification of Tokens.ppt
2_2Specification of Tokens.ppt
 

Similar to Compiler Engineering Lab#5 : Symbol Table, Flex Tool

6 compiler lab - Flex
6 compiler lab - Flex6 compiler lab - Flex
6 compiler lab - FlexMashaelQ
 
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...Prof Chethan Raj C
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manualSami Said
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc pptpssraikar
 
7 compiler lab
7 compiler lab 7 compiler lab
7 compiler lab MashaelQ
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxfaithxdunce63732
 
Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Wei Sun
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_netNico Ludwig
 
Unix system programming
Unix system programmingUnix system programming
Unix system programmingSyed Mustafa
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flexvip_du
 
Runtime Environment Of .Net Divya Rathore
Runtime Environment Of .Net Divya RathoreRuntime Environment Of .Net Divya Rathore
Runtime Environment Of .Net Divya RathoreEsha Yadav
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxVigneshkumar Ponnusamy
 

Similar to Compiler Engineering Lab#5 : Symbol Table, Flex Tool (20)

6 compiler lab - Flex
6 compiler lab - Flex6 compiler lab - Flex
6 compiler lab - Flex
 
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
Lecture 01 2017
Lecture 01 2017Lecture 01 2017
Lecture 01 2017
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
Lex
LexLex
Lex
 
LEX & YACC
LEX & YACCLEX & YACC
LEX & YACC
 
7 compiler lab
7 compiler lab 7 compiler lab
7 compiler lab
 
Flex
FlexFlex
Flex
 
11700220036.pdf
11700220036.pdf11700220036.pdf
11700220036.pdf
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
 
Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02Dotnetintroduce 100324201546-phpapp02
Dotnetintroduce 100324201546-phpapp02
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net
 
Unix system programming
Unix system programmingUnix system programming
Unix system programming
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flex
 
Module4 lex and yacc.ppt
Module4 lex and yacc.pptModule4 lex and yacc.ppt
Module4 lex and yacc.ppt
 
Runtime Environment Of .Net Divya Rathore
Runtime Environment Of .Net Divya RathoreRuntime Environment Of .Net Divya Rathore
Runtime Environment Of .Net Divya Rathore
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptx
 
7986-lect 7.pdf
7986-lect 7.pdf7986-lect 7.pdf
7986-lect 7.pdf
 

Recently uploaded

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 

Compiler Engineering Lab#5 : Symbol Table, Flex Tool

  • 1. L A B # 5 : S Y M B O L TA B L E , F L E X COMPILER ENGINEERING
  • 2. WHY DO I NEED A SYMBOL TABLE? • Symbol Table answers the following questions: 1. For a certain declaration of an Identifier name , does it have multiple declarations in different scopes? • If YES, keep track of these different cases 2. For a USE of an Identifier name, to which scope does it correspond? (using the "most closely nested" rule) 3. How can various language logical structures be presented? • One of the Main Purposes of Symbol Table is: to keep track of IDENTIFIERS recognized in the input stream. • All subsequent references to identifiers refer to the appropriate symbol table index. 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 2
  • 3. WHY DO I NEED A SYMBOL TABLE? • So, Symbol Table is a group of linked hash tables that manages either: • IDENTIFIERS attributes, • or convey the structure of a statementexpression that they reflect. 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 3
  • 4. BUILDING COMPILER WITH 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 4 Lexical Analysis (Lex Flex) Syntax-Semantic Analysis (Yacc Bison) Assembly (LLVM) Linking
  • 5. 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 5 TOKENS ARE NUMERICAL REPRESENTATIONS OF STRINGS, AND SIMPLIFY PROCESSING First: Lexical Analysis with Flex Reminder: What is the goal of Lexical Analysis phase? In other words, why do I use TOKENS?
  • 6. BUILDING A COMPILER WITH FLEX(LEX) & BISON(YACC) 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 6
  • 7. FLEX & BISON INPUT-OUTPUT INTERACTION • Bas.y (Parser Input): • Y.tab.h (Parser Output): • is a header file that contains, among other things, • the definitions of the token names NUM, OPA, etc., • and the variable yylval that we use to pass the bison code the semantic values of tokens • Y.tab.c (Parser Output): • contains the CC++ code for the parser (which is a function called yyparse()) • Bas.l (Lexica Analyzer Input): • needs those definitions in (Y.tab.h) so that the yylex() function it defines for bison can pass back the information it needs to pass back. • Lex.yy.c(Lexica Analyzer Output): generated by FLEX that contains, among other things, the definition of the yylex() function 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 7
  • 8. FLEX • Flex is an open-source tool for Fast lexical Analyzer can be downloaded from Flex Download Webpage • Flex reads user-specified input files • If no input file is given, Flex will read its standard file • Flex INPUT file: • is a description of a scanner to generate • The description is Pairs of Regular Expressions and C Code called RULES Source: Flex Website 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 8
  • 9. FLEX • When the executable runs it analyzes its input for occurrences of text matching the Regular Expressions (RegExp) for each rule. • Whenever it finds a match  it executes the corresponding C code • Flex generates a C source file named “lex.yy.c” which defines the function yylex() • The file “lex.yy.c” can be compiled and linked to produce an executable 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 9
  • 10. BISON(1) • Bison is a general-purpose parser generator that converts an annotated context-free grammar into a deterministic [LR or generalized LR (GLR)] parser. • Bison, you can use it to develop a wide range of language parsers. • Bison is compatible with YACC • Based on CC++ and works with Java. (1) Source: Bison Webpage 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 10
  • 11. 1-4/4/12 11 Department of Computer Science - Compiler Engineering Lab FLEX TOOL FIRST : LEXICAL ANALYSIS
  • 12. BISONYACC & PARSING • The grammar in the previous diagram (FlexBison Interaction Model Diagram) is a text file you create with a text editor • Yacc will read your grammar and generate C code for a syntax analyzer or parser • The syntax analyzer uses grammar rules that allow it to analyze tokens from the lexical analyzer and create a syntax tree • The syntax tree imposes a hierarchical structure on the tokens • e.g. operator precedence and associativity are apparent in the syntax tree 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 12
  • 13. LEXICAL ANALYSIS: FLEX IN DETAIL • The flex generated scanner code tries to match characters from the current input stream to these regular expressions, and when a match is found, it executes the associtated action code. • The variable yytext contains the string (in the C sense, i.e. '0' terminated char*.) of characters that were matched. • When more than one match is possible it breaks ties by going with the longest match then first listed 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 13
  • 14. FLEX FILES FORMAT The general format of Lex source is: {definitions} %% {rules} %% {user subroutines} 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 14
  • 15. FLEX FILES FORMAT • Any line which is not part of a Lex rule or action which begins with a blank or tab is copied into the Lex generated program. (used for Comments) • source input prior to the first %% delimiter will be external to any function in the code; if it appears immediately after the first %%, it appears in an appropriate place for declarations in the function written by • Anything included between lines containing only %{ and %} is copied out as above. The delimiters are discarded. This format permits entering text like preprocessor statements that must begin in column 1. 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 15
  • 16. FLEX FILES FORMAT • Any line which is not part of a Lex rule or action which begins with a blank or tab is copied into the Lex generated program. (used for Comments) • This means each code-line must start from column one. • source input prior to the first %% delimiter will be external to any function in the code; if it appears immediately after the first %%, it appears in an appropriate place for declarations in the function written by • Anything included between lines contain- ing only %{ and %} is copied out as above. The delimiters are discarded. This format permits entering text like preprocessor statements that must begin in column 1. 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 16
  • 17. 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 17
  • 18. EXAMPLE # 1 : CALCULATOR FLEX FILE Write a Flex file for a calculator that is able to recognize the following: • numbers, • (+,-,*,/) operators, • and parantheses 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 18
  • 19. EXAMPLE # 1 : CALCULATOR (.L) %{ #include "ex1.tab.hpp" #include <iostream> using namespace std; %} %option noyywrap %% [0-9]+ { yylval.val = atoi(yytext); return NUM; } [+|-] { yylval.sym = yytext[0]; return OPA; } [*|/] { yylval.sym = yytext[0]; return OPM; } "(" { return LP; } ")" { return RP; } ";" { return STOP; } <<EOF>> { return 0; } [ tn]+ { } . { cerr << "Unrecognized token!" << endl; exit(1); } %% 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 19
  • 20. EXAMPLE # 2 : “BASIC LANGUAGE” FILE Write a Flex file for ”Basic Language” that is able to recognize the following: • Numbers, • Identifiers, • Keywords, • Relation Operations • Arthimitic operators, • and Delimiters 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 20
  • 21. EXAMPLE # 2 : (BAS.L) FILE FOR BASIC LANGAUGE %{ #include "y.tab.h” %} digit [0-9] letter [a-zA-Z] %% "+" { return PLUS; } "-" { return MINUS; } "*" { return TIMES; } "/" { return SLASH; } "(" { return LPAREN; } ")" { return RPAREN; } ";" { return SEMICOLON; } "," { return COMMA; } "." { return PERIOD; } 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 21
  • 22. EXAMPLE # 2 : (BAS.L) FILE FOR BASIC LANGAUGE ":=" { return BECOMES; } "=" { return EQL; } "<>" { return NEQ; } "<" { return LSS; } ">" { return GTR; } "<=" { return LEQ; } ">=" { return GEQ; } 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 22
  • 23. EXAMPLE # 2 : (BAS.L) FILE FOR BASIC LANGAUGE "begin" { return BEGINSYM; } "call" { return CALLSYM; } "const" { return CONSTSYM; } "do" { return DOSYM; } "end" { return ENDSYM; } "if" { return IFSYM; } "odd" { return ODDSYM; } "procedure" { return PROCSYM; } "then" { return THENSYM; } "var" { return VARSYM; } "while" { return WHILESYM; } 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 23
  • 24. EXAMPLE # 2 : (BAS.L) FILE FOR BASIC LANGAUGE {letter}({letter}|{digit})* { yylval.id = (char *)strdup(yytext); return IDENT; } {digit}+ { yylval.num = atoi(yytext); return NUMBER; } [ tnr] /* skip whitespace */ . { printf("Unknown character [%c]n",yytext[0]); return UNKNOWN; } %% int yywrap(void) {return 1;} 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 24
  • 25. INSTALLING FLEX & BISON • Flex & Bison are Unix-based Tools that can be installed directly under UnixLinux environment. • Unser Windows Environment: Flex & Bison can be installed under Cygwin ( Linux Terminal). • Cygwin can be downloaded from here. • Cygwin is a Linux API layer providing substantial Linux API functionality. 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 25
  • 26. INSTALLING FLEX & BISON • Steps to download Cygwin: 1. Click the following link for Setup 2. Click Run  Next  Choose the option “Install from Internet”  Next  Make sure the correct installation directory then Next 3. Choose “Direct Connection” then Next 4. Choose any of the available HTTP download sites and click Next 5. In the “Select Packages” page: search for both “Flex” and “Bison” packages through the search textbox  then ensure the “install” option is selected 6. Finish the installation process by clicking Next to the end. 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 26
  • 27. OVERVIEW OF ANTLR(1) • ANTLR, ANother Tool for Language Recognition, is a language tool that provides a framework for constructing recognizers, interpreters, compilers, and translators from grammatical descriptions containing actions in a variety of target languages. • ANTLR provides excellent support for tree construction, tree walking, translation, error recovery, and error reporting • ANTLR can be downloaded from the following link ANTLR (.jar) file download link (1) Source: ANTLR Webpage 1-4/4/12 Department of Computer Science - Compiler Engineering Lab 27
  • 28. QUESTIONS? Thank you for listening  1-4/4/12 Department of Computer Science - Compiler Engineering Lab 28