SlideShare una empresa de Scribd logo
1 de 24
COMPILER DESIGN
SYNTAX ANALYSIS
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 1
Ms. RICHA SHARMA
Assistant Professor
richa.18364@lpu.co.in
Lovely Professional
University
SYNTAX ANALYSIS INTRODUCTION
• LEXICAL PHASE IS IMPLEMENTED ON FINITE AUTOMATA & FINITE AUTOMATA CAN REALLY
ONLY EXPRESS THINGS WHERE YOU CAN COUNT MODULUS ON K.
• REGULAR LANGUAGES – THE WEAKEST FORMAL LANGUAGES WIDELY USED
– MANY APPLICATIONS
– CAN’T HANDLE ITERATION & NESTED LOOPS(NESTED IF ELSE ).
TO SUMMARIZE, THE LEXER TAKES A STRING OF CHARACTER AS INPUT AND PRODUCES A STRING
OF TOKENS AS OUTPUT.
THAT STRING OF TOKENS IS THE INPUT TO THE PARSER WHICH TAKES A STRING OF TOKENS AND
PRODUCES A PARSE TREE OF THE PROGRAM.
SOMETIMES THE PARSE TREE IS ONLY IMPLICIT. SO THE, A COMPILER MAY NEVER ACTUALLY
BUILD THE FULL PARSE
TREE.
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 2
Lexical
Analyzer
Parser
Source
program
token
getNext
Token
Symbol
table
Parse tree Rest of
Front End
Intermediate
representation
ROLE OF SYNTAX ANALYSIS/PARSER
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 3
CONTEXT FREE GRAMMARS
expression -> expression + term
expression -> expression – term
expression -> term
term -> term * factor
term -> term / factor
term -> factor
factor -> (expression)
factor -> id
S - IS A FINITE SET OF TERMINALS
N - IS A FINITE SET OF NON-TERMINALS
P - IS A FINITE SUBSET OF PRODUCTION
RULES
S - IS THE START SYMBOL
G=(S ,N,P,S)
• A GRAMMAR DERIVES STRINGS BY BEGINNING WITH START SYMBOL AND
REPEATEDLY REPLACING A NON TERMINAL BY THE RIGHT HAND SIDE OF A
PRODUCTION FOR THAT NON TERMINAL.
• FROM THE START SYMBOL OF A GRAMMAR G FORM THE LANGUAGE L(G)
DEFINED BY THE GRAMMAR THE STRINGS THAT CAN BE DERIVED .
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 4
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 5
• PROGRAMMING LANGUAGES HAVE RECURSIVE STRUCTURE
• CONTEXT-FREE GRAMMARS ARE A NATURAL NOTATION FOR THIS
RECURSIVE STRUCTURE .
NOT ALL STRINGS OF TOKENS ARE PROGRAMS . . .
. . . PARSER MUST DISTINGUISH BETWEEN VALID AND INVALID
STRINGS OF TOKENS
WE NEED :
– A LANGUAGE :FOR DESCRIBING VALID STRINGS OF TOKENS
– A METHOD: FOR DISTINGUISHING VALID FROM INVALID STRINGS OF
TOKENS
CONTEXT FREE GRAMMARS
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY)
E ::= T | E + T | E - T
T ::= F | T * F |T / F
F ::= id | (E)
• ARITHMETIC EXPRESSIONS
• STATEMENTS
If Statement ::= if E then Statement else Statement
CONTEXT FREE GRAMMAR EXAMPLES
Steps:
1. Begin with a string with only the start
symbol S
2. Replace any non-terminal X in the
string by the right-hand side of some
production
X -> Y1…Yn
3. Repeat (2) until there are no non-
terminals
6
DERIVATIONS
• DERIVATION IS A SEQUENCE OF PRODUCTIONS SO BEGINNING WITH THE START SYMBOL.
• WE CAN APPLY PRODUCTIONS ONE AT A TIME IN SEQUENCE & THAT WILL PRODUCES A
DERIVATION.
• A DERIVATION IS A SEQUENCE OF PRODUCTIONS
A -> … -> … ->… -> … -> …
• A DERIVATION CAN BE DRAWN AS A TREE
– START SYMBOL IS THE TREE’S ROOT
– FOR A PRODUCTION X -> Y1…Yn ADD CHILDREN Y1…Yn TO NODE X
• GRAMMAR
E -> E + E | E * E | (E) | ID
• STRING
ID *ID + ID
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 7
DERIVATIONS
DERIVATIONS ARE OF TWO TYPES:
• RIGHTMOST AND LEFTMOST DERIVATIONS
• LETS DISCUSS WITH EXAMPLE
GRAMMAR: E -> E + E | E * E | -E | (E) | ID
STRING :(ID+ID)
LEFT MOST DERIVATION RIGHT MOST DERIVATION
E E
= (E) = (E)
= (E+E) = (E+E)
= (ID+E) = (E+ID)
=(ID+ID) =(ID+ID)
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 8
DERIVATIONS
• NOW WE'RE GOING TO PARSE THIS STRING AND WE'RE GOING TO SHOW HOW TO
PRODUCE A DERIVATION FOR THE STRING AND ALSO AT THE SAME TIME BUILD
THE TREE.
• PARSE TREES HAVE TERMINALS AT THE LEAVES AND NONTERMINALS AT THE
INTERIOR NODES AND FURTHERMORE, IN-ORDER TRAVERSAL OF THE LEAVES IS
THE ORIGINAL INPUT.
• GRAMMAR
E -> E + E | E * E | (E) | ID
• STRING
ID * ID + ID
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 9
LEFT MOST DERIVATION AND PARSE TREE
E
E
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 10
LEFT MOST DERIVATION AND PARSE TREE
E
E+E E
E + E
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 11
LEFT MOST DERIVATION AND PARSE TREE
E
E+E E
E*E+E E + E
E * E
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 12
LEFT MOST DERIVATION AND PARSE TREE
E
E+E E
E*E+E E + E
id*E+E E * E
id
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 13
LEFT MOST DERIVATION AND PARSE TREE
E
E+E E
E*E+E E + E
id*E+E E * E
id*id+E id id
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 14
LEFT MOST DERIVATION AND PARSE TREE
E
E+E E
E*E+E E + E
id*E+E E * E id
id*id+id id id
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 15
DERIVATIONS
• A PARSE TREE HAS
– TERMINALS AT THE LEAVES
– NON-TERMINALS AT THE INTERIOR NODES
• AN IN-ORDER TRAVERSAL OF THE LEAVES IS THE ORIGINAL INPUT
• THE PARSE TREE SHOWS THE ASSOCIATION OF OPERATIONS, THE INPUT STRING
DOES NOT .
NOTE: THAT RIGHT-MOST AND LEFT-MOST DERIVATIONS HAVE THE SAME PARSE
TREE IF NOT THEN THE GRAMMAR IS AMBIGUOUS GRAMMAR.
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 16
AMBIGUITY
• IF STRING HAS TWO OR MORE RIGHT MOST DERIVATIONS OR TWO OR MORE
LEFT DERIVATIONS THEN THAT STRING WILL HAVE TWO DISTINCT PARSE TREES
AND HENCE GRAMMAR WILL BE AMBIGUOUS.
• AMBIGUITY IS BAD: LEAVES MEANING OF SOME PROGRAMS ILL-DEFINED
• MULTIPLE PARSE TREES FOR SOME PROGRAM THEN THAT ESSENTIALLY MEANS
THAT YOU'RE LEAVING IT UP TO THE COMPILER TO PICK WHICH OF THOSE TWO
POSSIBLE INTERPRETATIONS OF THE PROGRAM YOU WANT IT TO GENERATE
CODE FOR AND THAT'S NOT A GOOD IDEA.
• TO REMOVE AMBIGUITY WE NEED TO REWRITE THE RULES CHECKING OVER
PRECEDENCE AND ASSOCIATIVITY .
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 17
AMBIGUITY
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 18
Eg: The string id +id* id produces two parse tree hence the grammar is ambiguous.
One can remove the ambiguity by rewriting the grammar as introducing new non-terminal instead of r
non-terminal , but it can result in left or right recursion .Hence we have to remove left recursion.
AMBIGUITY
• IF WE HAVE AN AMBIGUOUS GRAMMAR:
E →E * E
E →NUM
• AS THIS DEPENDS ON THE ASSOCIATIVITY OF *,WE USE DIFFERENT REWRITE
RULES FOR DIFFERENT ASSOCIATIVITY .
• IF * IS LEFT-ASSOCIATIVE, WE MAKE THE GRAMMAR LEFT-RECURSIVE BY HAVING
A RECURSIVE REFERENCE TO THE LEFT ONLY OF THE OPERATOR SYMBOL.
UNAMBIGUOUS GRAMMAR: E →E * E’
E →E’
E’→NUM
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 19
LEFT RECURSION
• UNAMBIGUOUS GRAMMAR : E →E * E’
E →E’
E’→NUM
• THIS GRAMMAR IS NOW LEFT RECURSIVE. LEFT RECURSIVE GRAMMAR IS ANY
GRAMMAR THAT HAS A NON-TERMINAL WHERE IF YOU START WITH THAT NON-
TERMINAL AND YOU DO SOME NON-EMPTY SEQUENCE OF RE-WRITES.
• CONSIDER THE LEFT-RECURSIVE GRAMMAR S -> S a | b
• S GENERATES ALL STRINGS STARTING WITH “a” AND FOLLOWED BY ANY
NUMBER OF “b’S”
• CAN REWRITE USING RIGHT-RECURSION
• S ->bS’
S’ ->aS’ |€
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY)
20
EXAMPLES OF LEFT RECURSION
1. E -> E + T | T T -> ID | (E)
2. S ->(L)|X L ->L,S|S
3. S ->S0S1S|01
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY)
21
LEFT FACTORING
• LEFT FACTORING IS A GRAMMAR TRANSFORMATION THAT IS USEFUL
FOR PRODUCING A DETERMINISTIC GRAMMAR FROM NON-
DETERMINISTIC GRAMMAR SUITABLE FOR PREDICTIVE OR TOP-DOWN
PARSING.
• CONSIDER FOLLOWING GRAMMAR:
• STMT -> IF EXPR THEN STMT ELSE STMT
• | IF EXPR THEN STMT
• ON SEEING INPUT IF IT IS NOT CLEAR FOR THE PARSER WHICH
PRODUCTION TO USE
• WE CAN EASILY PERFORM LEFT FACTORING:
• IF WE HAVE A->ΑΒ1 | ΑΒ2 THEN WE REPLACE IT WITH
• A -> ΑA’
• A’ -> Β1 | Β2
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY)
22
EXAMPLES OF LEFT FACTORING
1. S -> iEtS|iEtSES|a E ->b
2. S-> aSSbS|aSaSb|abb|b
3. S-> bSSaaS|bSSaSb|bSb|a
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY)
23
RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 24

Más contenido relacionado

La actualidad más candente

Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design) Tasif Tanzim
 
Regular expressions-Theory of computation
Regular expressions-Theory of computationRegular expressions-Theory of computation
Regular expressions-Theory of computationBipul Roy Bpl
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translationAkshaya Arunan
 
NFA or Non deterministic finite automata
NFA or Non deterministic finite automataNFA or Non deterministic finite automata
NFA or Non deterministic finite automatadeepinderbedi
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)swapnac12
 
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)Mohammad Ilyas Malik
 
Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler DesignAkhil Kaushik
 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTanzeela_Hussain
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generationrawan_z
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notationsEhtisham Ali
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generationAkshaya Arunan
 

La actualidad más candente (20)

Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)
 
First and follow set
First and follow setFirst and follow set
First and follow set
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
 
Regular expressions-Theory of computation
Regular expressions-Theory of computationRegular expressions-Theory of computation
Regular expressions-Theory of computation
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
 
NFA or Non deterministic finite automata
NFA or Non deterministic finite automataNFA or Non deterministic finite automata
NFA or Non deterministic finite automata
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
 
Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler Design
 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive Parsing
 
Daa unit 1
Daa unit 1Daa unit 1
Daa unit 1
 
Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generation
 
Context free grammar
Context free grammar Context free grammar
Context free grammar
 
Specification-of-tokens
Specification-of-tokensSpecification-of-tokens
Specification-of-tokens
 
Parsing
ParsingParsing
Parsing
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
 

Destacado (20)

Lexical analysis
Lexical analysisLexical analysis
Lexical analysis
 
Compiler Design Introduction
Compiler Design IntroductionCompiler Design Introduction
Compiler Design Introduction
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Lecture 04 syntax analysis
Lecture 04 syntax analysisLecture 04 syntax analysis
Lecture 04 syntax analysis
 
Lecture 06 syntax analysis 3
Lecture 06 syntax analysis 3Lecture 06 syntax analysis 3
Lecture 06 syntax analysis 3
 
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Syntactic Analysis
Syntactic AnalysisSyntactic Analysis
Syntactic Analysis
 
Role-of-lexical-analysis
Role-of-lexical-analysisRole-of-lexical-analysis
Role-of-lexical-analysis
 
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
 
Parsing
ParsingParsing
Parsing
 
Compiler design
Compiler designCompiler design
Compiler design
 
Data Locality
Data LocalityData Locality
Data Locality
 
Unit 1 cd
Unit 1 cdUnit 1 cd
Unit 1 cd
 
Compiler Design - Introduction to Compiler
Compiler Design - Introduction to CompilerCompiler Design - Introduction to Compiler
Compiler Design - Introduction to Compiler
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up Parsing
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 

Similar a Compiler design syntax analysis

5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptxvenkatapranaykumarGa
 
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...movocode
 
Fuzzy Matching with Apache Spark
Fuzzy Matching with Apache SparkFuzzy Matching with Apache Spark
Fuzzy Matching with Apache SparkDataWorks Summit
 
Syntactic analysis in NLP
Syntactic analysis in NLPSyntactic analysis in NLP
Syntactic analysis in NLPkartikaVashisht
 
Parsing (Automata)
Parsing (Automata)Parsing (Automata)
Parsing (Automata)ROOP SAGAR
 
Bioinformatics p2-p3-perl-regexes v2013-wim_vancriekinge
Bioinformatics p2-p3-perl-regexes v2013-wim_vancriekingeBioinformatics p2-p3-perl-regexes v2013-wim_vancriekinge
Bioinformatics p2-p3-perl-regexes v2013-wim_vancriekingeProf. Wim Van Criekinge
 
Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014Sandy Smith
 
Unitiv 111206005201-phpapp01
Unitiv 111206005201-phpapp01Unitiv 111206005201-phpapp01
Unitiv 111206005201-phpapp01riddhi viradiya
 
RECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSINGRECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSINGJothi Lakshmi
 

Similar a Compiler design syntax analysis (13)

5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
5-Introduction to Parsing and Context Free Grammar-09-05-2023.pptx
 
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
6-Role of Parser, Construction of Parse Tree and Elimination of Ambiguity-06-...
 
3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx
 
Fuzzy Matching with Apache Spark
Fuzzy Matching with Apache SparkFuzzy Matching with Apache Spark
Fuzzy Matching with Apache Spark
 
Lexical 2
Lexical 2Lexical 2
Lexical 2
 
Syntactic analysis in NLP
Syntactic analysis in NLPSyntactic analysis in NLP
Syntactic analysis in NLP
 
Parsing (Automata)
Parsing (Automata)Parsing (Automata)
Parsing (Automata)
 
Module 11
Module 11Module 11
Module 11
 
Bioinformatics p2-p3-perl-regexes v2013-wim_vancriekinge
Bioinformatics p2-p3-perl-regexes v2013-wim_vancriekingeBioinformatics p2-p3-perl-regexes v2013-wim_vancriekinge
Bioinformatics p2-p3-perl-regexes v2013-wim_vancriekinge
 
Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014Don't Fear the Regex - CapitalCamp/GovDays 2014
Don't Fear the Regex - CapitalCamp/GovDays 2014
 
Unitiv 111206005201-phpapp01
Unitiv 111206005201-phpapp01Unitiv 111206005201-phpapp01
Unitiv 111206005201-phpapp01
 
Witchcraft
WitchcraftWitchcraft
Witchcraft
 
RECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSINGRECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSING
 

Último

Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...HenryBriggs2
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projectssmsksolar
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stageAbc194748
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 

Último (20)

Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 

Compiler design syntax analysis

  • 1. COMPILER DESIGN SYNTAX ANALYSIS RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 1 Ms. RICHA SHARMA Assistant Professor richa.18364@lpu.co.in Lovely Professional University
  • 2. SYNTAX ANALYSIS INTRODUCTION • LEXICAL PHASE IS IMPLEMENTED ON FINITE AUTOMATA & FINITE AUTOMATA CAN REALLY ONLY EXPRESS THINGS WHERE YOU CAN COUNT MODULUS ON K. • REGULAR LANGUAGES – THE WEAKEST FORMAL LANGUAGES WIDELY USED – MANY APPLICATIONS – CAN’T HANDLE ITERATION & NESTED LOOPS(NESTED IF ELSE ). TO SUMMARIZE, THE LEXER TAKES A STRING OF CHARACTER AS INPUT AND PRODUCES A STRING OF TOKENS AS OUTPUT. THAT STRING OF TOKENS IS THE INPUT TO THE PARSER WHICH TAKES A STRING OF TOKENS AND PRODUCES A PARSE TREE OF THE PROGRAM. SOMETIMES THE PARSE TREE IS ONLY IMPLICIT. SO THE, A COMPILER MAY NEVER ACTUALLY BUILD THE FULL PARSE TREE. RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 2
  • 3. Lexical Analyzer Parser Source program token getNext Token Symbol table Parse tree Rest of Front End Intermediate representation ROLE OF SYNTAX ANALYSIS/PARSER RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 3
  • 4. CONTEXT FREE GRAMMARS expression -> expression + term expression -> expression – term expression -> term term -> term * factor term -> term / factor term -> factor factor -> (expression) factor -> id S - IS A FINITE SET OF TERMINALS N - IS A FINITE SET OF NON-TERMINALS P - IS A FINITE SUBSET OF PRODUCTION RULES S - IS THE START SYMBOL G=(S ,N,P,S) • A GRAMMAR DERIVES STRINGS BY BEGINNING WITH START SYMBOL AND REPEATEDLY REPLACING A NON TERMINAL BY THE RIGHT HAND SIDE OF A PRODUCTION FOR THAT NON TERMINAL. • FROM THE START SYMBOL OF A GRAMMAR G FORM THE LANGUAGE L(G) DEFINED BY THE GRAMMAR THE STRINGS THAT CAN BE DERIVED . RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 4
  • 5. RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 5 • PROGRAMMING LANGUAGES HAVE RECURSIVE STRUCTURE • CONTEXT-FREE GRAMMARS ARE A NATURAL NOTATION FOR THIS RECURSIVE STRUCTURE . NOT ALL STRINGS OF TOKENS ARE PROGRAMS . . . . . . PARSER MUST DISTINGUISH BETWEEN VALID AND INVALID STRINGS OF TOKENS WE NEED : – A LANGUAGE :FOR DESCRIBING VALID STRINGS OF TOKENS – A METHOD: FOR DISTINGUISHING VALID FROM INVALID STRINGS OF TOKENS CONTEXT FREE GRAMMARS
  • 6. RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) E ::= T | E + T | E - T T ::= F | T * F |T / F F ::= id | (E) • ARITHMETIC EXPRESSIONS • STATEMENTS If Statement ::= if E then Statement else Statement CONTEXT FREE GRAMMAR EXAMPLES Steps: 1. Begin with a string with only the start symbol S 2. Replace any non-terminal X in the string by the right-hand side of some production X -> Y1…Yn 3. Repeat (2) until there are no non- terminals 6
  • 7. DERIVATIONS • DERIVATION IS A SEQUENCE OF PRODUCTIONS SO BEGINNING WITH THE START SYMBOL. • WE CAN APPLY PRODUCTIONS ONE AT A TIME IN SEQUENCE & THAT WILL PRODUCES A DERIVATION. • A DERIVATION IS A SEQUENCE OF PRODUCTIONS A -> … -> … ->… -> … -> … • A DERIVATION CAN BE DRAWN AS A TREE – START SYMBOL IS THE TREE’S ROOT – FOR A PRODUCTION X -> Y1…Yn ADD CHILDREN Y1…Yn TO NODE X • GRAMMAR E -> E + E | E * E | (E) | ID • STRING ID *ID + ID RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 7
  • 8. DERIVATIONS DERIVATIONS ARE OF TWO TYPES: • RIGHTMOST AND LEFTMOST DERIVATIONS • LETS DISCUSS WITH EXAMPLE GRAMMAR: E -> E + E | E * E | -E | (E) | ID STRING :(ID+ID) LEFT MOST DERIVATION RIGHT MOST DERIVATION E E = (E) = (E) = (E+E) = (E+E) = (ID+E) = (E+ID) =(ID+ID) =(ID+ID) RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 8
  • 9. DERIVATIONS • NOW WE'RE GOING TO PARSE THIS STRING AND WE'RE GOING TO SHOW HOW TO PRODUCE A DERIVATION FOR THE STRING AND ALSO AT THE SAME TIME BUILD THE TREE. • PARSE TREES HAVE TERMINALS AT THE LEAVES AND NONTERMINALS AT THE INTERIOR NODES AND FURTHERMORE, IN-ORDER TRAVERSAL OF THE LEAVES IS THE ORIGINAL INPUT. • GRAMMAR E -> E + E | E * E | (E) | ID • STRING ID * ID + ID RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 9
  • 10. LEFT MOST DERIVATION AND PARSE TREE E E RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 10
  • 11. LEFT MOST DERIVATION AND PARSE TREE E E+E E E + E RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 11
  • 12. LEFT MOST DERIVATION AND PARSE TREE E E+E E E*E+E E + E E * E RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 12
  • 13. LEFT MOST DERIVATION AND PARSE TREE E E+E E E*E+E E + E id*E+E E * E id RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 13
  • 14. LEFT MOST DERIVATION AND PARSE TREE E E+E E E*E+E E + E id*E+E E * E id*id+E id id RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 14
  • 15. LEFT MOST DERIVATION AND PARSE TREE E E+E E E*E+E E + E id*E+E E * E id id*id+id id id RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 15
  • 16. DERIVATIONS • A PARSE TREE HAS – TERMINALS AT THE LEAVES – NON-TERMINALS AT THE INTERIOR NODES • AN IN-ORDER TRAVERSAL OF THE LEAVES IS THE ORIGINAL INPUT • THE PARSE TREE SHOWS THE ASSOCIATION OF OPERATIONS, THE INPUT STRING DOES NOT . NOTE: THAT RIGHT-MOST AND LEFT-MOST DERIVATIONS HAVE THE SAME PARSE TREE IF NOT THEN THE GRAMMAR IS AMBIGUOUS GRAMMAR. RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 16
  • 17. AMBIGUITY • IF STRING HAS TWO OR MORE RIGHT MOST DERIVATIONS OR TWO OR MORE LEFT DERIVATIONS THEN THAT STRING WILL HAVE TWO DISTINCT PARSE TREES AND HENCE GRAMMAR WILL BE AMBIGUOUS. • AMBIGUITY IS BAD: LEAVES MEANING OF SOME PROGRAMS ILL-DEFINED • MULTIPLE PARSE TREES FOR SOME PROGRAM THEN THAT ESSENTIALLY MEANS THAT YOU'RE LEAVING IT UP TO THE COMPILER TO PICK WHICH OF THOSE TWO POSSIBLE INTERPRETATIONS OF THE PROGRAM YOU WANT IT TO GENERATE CODE FOR AND THAT'S NOT A GOOD IDEA. • TO REMOVE AMBIGUITY WE NEED TO REWRITE THE RULES CHECKING OVER PRECEDENCE AND ASSOCIATIVITY . RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 17
  • 18. AMBIGUITY RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 18 Eg: The string id +id* id produces two parse tree hence the grammar is ambiguous. One can remove the ambiguity by rewriting the grammar as introducing new non-terminal instead of r non-terminal , but it can result in left or right recursion .Hence we have to remove left recursion.
  • 19. AMBIGUITY • IF WE HAVE AN AMBIGUOUS GRAMMAR: E →E * E E →NUM • AS THIS DEPENDS ON THE ASSOCIATIVITY OF *,WE USE DIFFERENT REWRITE RULES FOR DIFFERENT ASSOCIATIVITY . • IF * IS LEFT-ASSOCIATIVE, WE MAKE THE GRAMMAR LEFT-RECURSIVE BY HAVING A RECURSIVE REFERENCE TO THE LEFT ONLY OF THE OPERATOR SYMBOL. UNAMBIGUOUS GRAMMAR: E →E * E’ E →E’ E’→NUM RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 19
  • 20. LEFT RECURSION • UNAMBIGUOUS GRAMMAR : E →E * E’ E →E’ E’→NUM • THIS GRAMMAR IS NOW LEFT RECURSIVE. LEFT RECURSIVE GRAMMAR IS ANY GRAMMAR THAT HAS A NON-TERMINAL WHERE IF YOU START WITH THAT NON- TERMINAL AND YOU DO SOME NON-EMPTY SEQUENCE OF RE-WRITES. • CONSIDER THE LEFT-RECURSIVE GRAMMAR S -> S a | b • S GENERATES ALL STRINGS STARTING WITH “a” AND FOLLOWED BY ANY NUMBER OF “b’S” • CAN REWRITE USING RIGHT-RECURSION • S ->bS’ S’ ->aS’ |€ RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 20
  • 21. EXAMPLES OF LEFT RECURSION 1. E -> E + T | T T -> ID | (E) 2. S ->(L)|X L ->L,S|S 3. S ->S0S1S|01 RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 21
  • 22. LEFT FACTORING • LEFT FACTORING IS A GRAMMAR TRANSFORMATION THAT IS USEFUL FOR PRODUCING A DETERMINISTIC GRAMMAR FROM NON- DETERMINISTIC GRAMMAR SUITABLE FOR PREDICTIVE OR TOP-DOWN PARSING. • CONSIDER FOLLOWING GRAMMAR: • STMT -> IF EXPR THEN STMT ELSE STMT • | IF EXPR THEN STMT • ON SEEING INPUT IF IT IS NOT CLEAR FOR THE PARSER WHICH PRODUCTION TO USE • WE CAN EASILY PERFORM LEFT FACTORING: • IF WE HAVE A->ΑΒ1 | ΑΒ2 THEN WE REPLACE IT WITH • A -> ΑA’ • A’ -> Β1 | Β2 RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 22
  • 23. EXAMPLES OF LEFT FACTORING 1. S -> iEtS|iEtSES|a E ->b 2. S-> aSSbS|aSaSb|abb|b 3. S-> bSSaaS|bSSaSb|bSb|a RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 23
  • 24. RICHA SHARMA (LOVELY PROFESSIONAL UNIVERSITY) 24