SlideShare a Scribd company logo
Syntax Analysis
Or
Parsing
Parsing
• A.K.A. Syntax Analysis
– Recognize sentences in a language.
– Discover the structure of a document/program.
– Construct (implicitly or explicitly) a tree (called as a
parse tree) to represent the structure.
– The above tree is used later to guide translation.
Parsing During Compilation
intermediate
representation
errors
lexical
analyzer
parser
rest of
front end
symbol
table
source
program
parse
treeget next
token
token
regular
expressions
• Collecting token
information
• Perform type checking
• Intermediate code
generation
• uses a grammar to check structure of tokens
• produces a parse tree
• syntactic errors and recovery
• recognize correct syntax
• report errors
Parsing Responsibilities
Syntax Error Identification / Handling
Recall typical error types:
1. Lexical : Misspellings
2. Syntactic : Omission, wrong order of tokens
3. Semantic : Incompatible types, undefined IDs
4. Logical : Infinite loop / recursive call
Majority of error processing occurs during syntax analysis
NOTE: Not all errors are identifiable !!
if x<1 thenn y = 5:
if ((x<1) & (y>5)))
if (x+5) then
if (i<9) then ...
Should be <= not <
Error Detection
• Much responsibility on Parser
– Many errors are syntactic in nature
– Modern parsing method can detect the presence of syntactic errors in
programs very efficiently
– Detecting semantic or logical error is difficult
• Challenges for error handler in Parser
– It should report error clearly and accurately
– It should recover from error and continue..
– It should not significantly slow down the processing of correct programs
• Good news is
– Common errors are simple and relatively easy to catch.
• Errors don’t occur that frequently!!
• 60% programs are syntactically and semantically correct
• 80% erroneous statements have only 1 error, 13% have 2
• Most error are trivial : 90% single token error
• 60% punctuation, 20% operator, 15% keyword, 5% other error
• Difficult to generate clear and accurate error messages.
Example
function foo () {
...
if (...) {
...
} else {
...
...
}
<eof>
Example
int myVarr;
...
x = myVar;
...
Adequate Error Reporting is Not a Trivial
Task
Missing } here
Not detected until here
Misspelled ID here
Not detected until here
Error Recovery
• After first error recovered
– Compiler must go on!
• Restore to some state and process the rest of the input
• Error-Correcting Compilers
– Issue an error message
– Fix the problem
– Produce an executable
Example
Error on line 23: “myVarr” undefined.
“myVar” was used.
May not be a good Idea!!
– Guessing the programmers intention is not easy!
Error Recovery May Trigger More Errors!
• Inadequate recovery may introduce more errors
– Those were not programmers errors
• Example:
int myVar flag ;
...
x := flag;
...
...
while (flag==0)
...
Too many Error message may be obscuring
– May bury the real message
– Remedy:
• allow 1 message per token or per statement
• Quit after a maximum (e.g. 100) number of errors
Declaration of flag is discarded
Variable flag is undefined
Variable flag is undefined
Error Recovery Approaches: Panic Mode
• Discard tokens until we see a “synchronizing” token.
• The key...
– Good set of synchronizing tokens
– Knowing what to do then
• Advantage
– Simple to implement
– Does not go into infinite loop
– Commonly used
• Disadvantage
– May skip over large sections of source with some errors
Example
Skip to next occurrence of
} end ;
Resume by parsing the next statement
Error Recovery Approaches: Phrase-Level
Recovery
• Compiler corrects the program
by deleting or inserting tokens
...so it can proceed to parse from where it was.
• The key...
Don’t get into an infinite loop
Example
while (x==4) y:= a + b
Insert do to fix the statement
Context Free Grammars (CFG)
• A context free grammar is a formal model that consists of:
• Terminals
Keywords
Token Classes
Punctuation
• Non-terminals
Any symbol appearing on the lefthand side of any rule
• Start Symbol
Usually the non-terminal on the lefthand side of the first rule
• Rules (or “Productions”)
BNF: Backus-Naur Form / Backus-Normal Form
Stmt ::= if Expr then Stmt else Stmt
Rule Alternative Notations
Context Free Grammars : A First Look
assign_stmt → id := expr ;
expr → expr operator term
expr → term
term → id
term → real
term → integer
operator → +
operator → -
Derivation: A sequence of grammar rule applications and
substitutions that transform a starting non-term into a sequence
of terminals / tokens.
Derivation
Let’s derive: id := id + real – integer ;
assign_stmt assign_stmt → id := expr ;
→ id := expr ; expr → expr operator term
→id := expr operator term; expr → expr operator term
→id := expr operator term operator term; expr → term
→ id := term operator term operator term; term → id
→ id := id operator term operator term; operator → +
→ id := id + term operator term; term → real
→ id := id + real operator term; operator → -
→ id := id + real - term; term → integer
→ id := id + real - integer;
using production:
Example Grammar: Simple Arithmetic
Expressions
expr → expr op expr
expr → ( expr )
expr → - expr
expr → id
op → +
op → -
op → *
op → /
op → ↑
9 Production rules
Terminals: id + - * / ↑ ( )
Nonterminals: expr, op
Start symbol: expr
Notational Conventions
• Terminals
– Lower-case letters early in the alphabet: a, b, c
– Operator symbols: +, -
– Punctuations symbols: parentheses, comma
– Boldface strings: id or if
• Nonterminals:
– Upper-case letters early in the alphabet: A, B, C
– The letter S (start symbol)
– Lower-case italic names: expr or stmt
• Upper-case letters late in the alphabet, such as X, Y, Z,
represent either nonterminals or terminals.
• Lower-case letters late in the alphabet, such as u, v, …, z,
represent strings of terminals.
Notational Conventions
• Lower-case Greek letters, such as α, β, γ, represent strings of
grammar symbols. Thus A→ α indicates that there is a single
nonterminal A on the left side of the production and a string of
grammar symbols α to the right of the arrow.
• If A→ α1, A→ α2, …., A→ αk are all productions with A on the
left, we may write A→ α1 | α2 | …. | αk
• Unless otherwise started, the left side of the first production is
the start symbol.
E → E A E | ( E ) | -E | id
A → + | - | * | / | ↑
Derivations
Doesn’t contain nonterminals
Derivation
Leftmost Derivation
Rightmost Derivation
Parse Tree
Parse Tree
Parse Tree
Parse Tree
Ambiguous Grammar
Ambiguous Grammar
• More than one Parse Tree for some sentence.
– The grammar for a programming language may be
ambiguous
– Need to modify it for parsing.
• Also: Grammar may be left recursive.
• Need to modify it for parsing.
Elimination of Ambiguity
• Ambiguous
• A Grammar is ambiguous if there are multiple parse
trees for the same sentence.
• Disambiguation
• Express Preference for one parse tree over others
– Add disambiguating rule into the grammar
Resolving Problems: Ambiguous Grammars
Consider the following grammar segment:
stmt → if expr then stmt
| if expr then stmt else stmt
| other (any other statement)
If E1 then S1 else if E2 then S2 else S3
simple parse tree:
stmt
stmt
stmtexpr
exprE1
E2
S3
S1
S2
then
then
else
else
if
if
stmt stmt
Example : What Happens with this string?
If E1 then if E2 then S1 else S2
How is this parsed ?
if E1 then
if E2 then
S1
else
S2
if E1 then
if E2 then
S1
else
S2
vs.
Parse Trees: If E1 then if E2 then S1 else S2
Form 1:
stmt
stmt
stmtexpr
E1 S2
then elseif
expr
E2
S1
thenif
stmt
stmt
expr
E1
thenif
stmt
expr
E2
S2S1
then else
if
stmt stmt
Form 2:
Removing Ambiguity
Take Original Grammar:
stmt → if expr then stmt
| if expr then stmt else stmt
| other (any other statement)
Revise to remove ambiguity:
stmt → matched_stmt | unmatched_stmt
matched_stmt → if expr then matched_stmt else matched_stmt |
other
unmatched_stmt → if expr then stmt
| if expr then matched_stmt else unmatched_stmt
Rule: Match each else with the closest previous
unmatched then.
Any Question?

More Related Content

What's hot

Bottom - Up Parsing
Bottom - Up ParsingBottom - Up Parsing
Bottom - Up Parsing
kunj desai
 
Yacc
YaccYacc
Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
Akshaya Arunan
 
LL(1) Parsers
LL(1) ParsersLL(1) Parsers
Top down parsing
Top down parsingTop down parsing
Top down parsing
ASHOK KUMAR REDDY
 
Chapter 5 Syntax Directed Translation
Chapter 5   Syntax Directed TranslationChapter 5   Syntax Directed Translation
Chapter 5 Syntax Directed Translation
Radhakrishnan Chinnusamy
 
Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler Design
Akhil Kaushik
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
Muhammed Afsal Villan
 
Intermediate code generator
Intermediate code generatorIntermediate code generator
Intermediate code generator
sanchi29
 
Lecture: Context-Free Grammars
Lecture: Context-Free GrammarsLecture: Context-Free Grammars
Lecture: Context-Free Grammars
Marina Santini
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
Radhakrishnan Chinnusamy
 
Back patching
Back patchingBack patching
Back patching
santhiya thavanthi
 
Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Lexical Analysis - Compiler design
Lexical Analysis - Compiler design
Aman Sharma
 
Shift reduce parser
Shift reduce parserShift reduce parser
Shift reduce parser
TEJVEER SINGH
 
Parsing
ParsingParsing
Parsing
khush_boo31
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
Dr. C.V. Suresh Babu
 
Compiler Design Lecture Notes
Compiler Design Lecture NotesCompiler Design Lecture Notes
Compiler Design Lecture Notes
FellowBuddy.com
 
COMPILER DESIGN
COMPILER DESIGNCOMPILER DESIGN
COMPILER DESIGN
Vetukurivenkatashiva
 
Parse Tree
Parse TreeParse Tree
Parse Tree
A. S. M. Shafi
 
Lexical Analysis - Compiler Design
Lexical Analysis - Compiler DesignLexical Analysis - Compiler Design
Lexical Analysis - Compiler Design
Akhil Kaushik
 

What's hot (20)

Bottom - Up Parsing
Bottom - Up ParsingBottom - Up Parsing
Bottom - Up Parsing
 
Yacc
YaccYacc
Yacc
 
Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
 
LL(1) Parsers
LL(1) ParsersLL(1) Parsers
LL(1) Parsers
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Chapter 5 Syntax Directed Translation
Chapter 5   Syntax Directed TranslationChapter 5   Syntax Directed Translation
Chapter 5 Syntax Directed Translation
 
Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler Design
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
 
Intermediate code generator
Intermediate code generatorIntermediate code generator
Intermediate code generator
 
Lecture: Context-Free Grammars
Lecture: Context-Free GrammarsLecture: Context-Free Grammars
Lecture: Context-Free Grammars
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
 
Back patching
Back patchingBack patching
Back patching
 
Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Lexical Analysis - Compiler design
Lexical Analysis - Compiler design
 
Shift reduce parser
Shift reduce parserShift reduce parser
Shift reduce parser
 
Parsing
ParsingParsing
Parsing
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
Compiler Design Lecture Notes
Compiler Design Lecture NotesCompiler Design Lecture Notes
Compiler Design Lecture Notes
 
COMPILER DESIGN
COMPILER DESIGNCOMPILER DESIGN
COMPILER DESIGN
 
Parse Tree
Parse TreeParse Tree
Parse Tree
 
Lexical Analysis - Compiler Design
Lexical Analysis - Compiler DesignLexical Analysis - Compiler Design
Lexical Analysis - Compiler Design
 

Viewers also liked

Lecture 06 syntax analysis 3
Lecture 06 syntax analysis 3Lecture 06 syntax analysis 3
Lecture 06 syntax analysis 3
Iffat Anjum
 
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
Chetan Mahawar
 
Parsing
ParsingParsing
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
Binsent Ribera
 
Lexical analysis
Lexical analysisLexical analysis
Lexical analysis
Richa Sharma
 
Lecture 3 basic syntax and semantics
Lecture 3  basic syntax and semanticsLecture 3  basic syntax and semantics
Lecture 3 basic syntax and semanticsalvin567
 
Compiler Design Introduction
Compiler Design IntroductionCompiler Design Introduction
Compiler Design Introduction
Richa Sharma
 
Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2
Iffat Anjum
 
Compiler Design - Introduction to Compiler
Compiler Design - Introduction to CompilerCompiler Design - Introduction to Compiler
Compiler Design - Introduction to Compiler
Iffat Anjum
 
Syntax and semantics
Syntax and semanticsSyntax and semantics
Syntax and semanticsRushdi Shams
 
Fog computing ( foggy cloud)
Fog computing  ( foggy cloud)Fog computing  ( foggy cloud)
Fog computing ( foggy cloud)
Iffat Anjum
 
Error detection recovery
Error detection recoveryError detection recovery
Error detection recoveryTech_MX
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up Parsing
Gerwin Ocsena
 
Types of errors
Types of errorsTypes of errors
Types of errors
Rima fathi
 
Compiler Design
Compiler DesignCompiler Design
Compiler DesignMir Majid
 

Viewers also liked (20)

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
 
Parsing
ParsingParsing
Parsing
 
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
 
Syntax analysis
Syntax analysisSyntax analysis
Syntax analysis
 
Syntactic analysis.pptx
Syntactic analysis.pptxSyntactic analysis.pptx
Syntactic analysis.pptx
 
Lexical analysis
Lexical analysisLexical analysis
Lexical analysis
 
Lecture 3 basic syntax and semantics
Lecture 3  basic syntax and semanticsLecture 3  basic syntax and semantics
Lecture 3 basic syntax and semantics
 
Cs419 lec10 left recursion and left factoring
Cs419 lec10   left recursion and left factoringCs419 lec10   left recursion and left factoring
Cs419 lec10 left recursion and left factoring
 
Compiler Design Introduction
Compiler Design IntroductionCompiler Design Introduction
Compiler Design Introduction
 
Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2
 
Compiler Design - Introduction to Compiler
Compiler Design - Introduction to CompilerCompiler Design - Introduction to Compiler
Compiler Design - Introduction to Compiler
 
Syntax and semantics
Syntax and semanticsSyntax and semantics
Syntax and semantics
 
Fog computing ( foggy cloud)
Fog computing  ( foggy cloud)Fog computing  ( foggy cloud)
Fog computing ( foggy cloud)
 
Parsing
ParsingParsing
Parsing
 
Error detection recovery
Error detection recoveryError detection recovery
Error detection recovery
 
Syntax
SyntaxSyntax
Syntax
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up Parsing
 
Types of errors
Types of errorsTypes of errors
Types of errors
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 

Similar to Lecture 04 syntax analysis

3a. Context Free Grammar.pdf
3a. Context Free Grammar.pdf3a. Context Free Grammar.pdf
3a. Context Free Grammar.pdf
TANZINTANZINA
 
3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx
Mattupallipardhu
 
8-Practice problems on operator precedence parser-24-05-2023.docx
8-Practice problems on operator precedence parser-24-05-2023.docx8-Practice problems on operator precedence parser-24-05-2023.docx
8-Practice problems on operator precedence parser-24-05-2023.docx
venkatapranaykumarGa
 
Programming_Language_Syntax.ppt
Programming_Language_Syntax.pptProgramming_Language_Syntax.ppt
Programming_Language_Syntax.ppt
Amrita Sharma
 
Module 11
Module 11Module 11
Module 11
bittudavis
 
Ch3_Syntax Analysis.pptx
Ch3_Syntax Analysis.pptxCh3_Syntax Analysis.pptx
Ch3_Syntax Analysis.pptx
TameneTamire
 
Syntax part1
Syntax part1Syntax part1
Syntax part1
Yophi Gimbal
 
Syntax
SyntaxSyntax
New compiler design 101 April 13 2024.pdf
New compiler design 101 April 13 2024.pdfNew compiler design 101 April 13 2024.pdf
New compiler design 101 April 13 2024.pdf
eliasabdi2024
 
Lecture 02 lexical analysis
Lecture 02 lexical analysisLecture 02 lexical analysis
Lecture 02 lexical analysis
Iffat Anjum
 
Chapter-3 compiler.pptx course materials
Chapter-3 compiler.pptx course materialsChapter-3 compiler.pptx course materials
Chapter-3 compiler.pptx course materials
gadisaAdamu
 
Lexical analysis, syntax analysis, semantic analysis. Ppt
Lexical analysis, syntax analysis, semantic analysis. PptLexical analysis, syntax analysis, semantic analysis. Ppt
Lexical analysis, syntax analysis, semantic analysis. Ppt
ovidlivi91
 
A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of C
jeremyrand
 
LVEE 2014: Text parsing with Python and PLY
LVEE 2014: Text parsing with Python and PLYLVEE 2014: Text parsing with Python and PLY
LVEE 2014: Text parsing with Python and PLY
dmbaturin
 
Uni texus austin
Uni texus austinUni texus austin
Uni texus austin
N/A
 
Control structure
Control structureControl structure
Control structure
baran19901990
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
 
Computational model language and grammar bnf
Computational model language and grammar bnfComputational model language and grammar bnf
Computational model language and grammar bnf
Taha Shakeel
 
match the following attributes to the parts of a compilerstrips ou.pdf
match the following attributes to the parts of a compilerstrips ou.pdfmatch the following attributes to the parts of a compilerstrips ou.pdf
match the following attributes to the parts of a compilerstrips ou.pdf
arpitaeron555
 

Similar to Lecture 04 syntax analysis (20)

3a. Context Free Grammar.pdf
3a. Context Free Grammar.pdf3a. Context Free Grammar.pdf
3a. Context Free Grammar.pdf
 
3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx3. Syntax Analyzer.pptx
3. Syntax Analyzer.pptx
 
8-Practice problems on operator precedence parser-24-05-2023.docx
8-Practice problems on operator precedence parser-24-05-2023.docx8-Practice problems on operator precedence parser-24-05-2023.docx
8-Practice problems on operator precedence parser-24-05-2023.docx
 
Programming_Language_Syntax.ppt
Programming_Language_Syntax.pptProgramming_Language_Syntax.ppt
Programming_Language_Syntax.ppt
 
Module 11
Module 11Module 11
Module 11
 
Ch3_Syntax Analysis.pptx
Ch3_Syntax Analysis.pptxCh3_Syntax Analysis.pptx
Ch3_Syntax Analysis.pptx
 
Syntax part1
Syntax part1Syntax part1
Syntax part1
 
Syntax
SyntaxSyntax
Syntax
 
New compiler design 101 April 13 2024.pdf
New compiler design 101 April 13 2024.pdfNew compiler design 101 April 13 2024.pdf
New compiler design 101 April 13 2024.pdf
 
Lecture 02 lexical analysis
Lecture 02 lexical analysisLecture 02 lexical analysis
Lecture 02 lexical analysis
 
Chapter-3 compiler.pptx course materials
Chapter-3 compiler.pptx course materialsChapter-3 compiler.pptx course materials
Chapter-3 compiler.pptx course materials
 
Lexical analysis, syntax analysis, semantic analysis. Ppt
Lexical analysis, syntax analysis, semantic analysis. PptLexical analysis, syntax analysis, semantic analysis. Ppt
Lexical analysis, syntax analysis, semantic analysis. Ppt
 
A Quick Taste of C
A Quick Taste of CA Quick Taste of C
A Quick Taste of C
 
LVEE 2014: Text parsing with Python and PLY
LVEE 2014: Text parsing with Python and PLYLVEE 2014: Text parsing with Python and PLY
LVEE 2014: Text parsing with Python and PLY
 
Uni texus austin
Uni texus austinUni texus austin
Uni texus austin
 
Control structure
Control structureControl structure
Control structure
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Computational model language and grammar bnf
Computational model language and grammar bnfComputational model language and grammar bnf
Computational model language and grammar bnf
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
match the following attributes to the parts of a compilerstrips ou.pdf
match the following attributes to the parts of a compilerstrips ou.pdfmatch the following attributes to the parts of a compilerstrips ou.pdf
match the following attributes to the parts of a compilerstrips ou.pdf
 

More from Iffat Anjum

Cognitive radio network_MS_defense_presentation
Cognitive radio network_MS_defense_presentationCognitive radio network_MS_defense_presentation
Cognitive radio network_MS_defense_presentation
Iffat Anjum
 
Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2
Iffat Anjum
 
Lecture 16 17 code-generation
Lecture 16 17 code-generationLecture 16 17 code-generation
Lecture 16 17 code-generation
Iffat Anjum
 
Lecture 14 run time environment
Lecture 14 run time environmentLecture 14 run time environment
Lecture 14 run time environment
Iffat Anjum
 
Lecture 12 intermediate code generation
Lecture 12 intermediate code generationLecture 12 intermediate code generation
Lecture 12 intermediate code generation
Iffat Anjum
 
Lecture 13 intermediate code generation 2.pptx
Lecture 13 intermediate code generation 2.pptxLecture 13 intermediate code generation 2.pptx
Lecture 13 intermediate code generation 2.pptx
Iffat Anjum
 
Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2
Iffat Anjum
 
Lecture 09 syntax analysis 05
Lecture 09 syntax analysis 05Lecture 09 syntax analysis 05
Lecture 09 syntax analysis 05
Iffat Anjum
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01
Iffat Anjum
 
Lecture 07 08 syntax analysis-4
Lecture 07 08 syntax analysis-4Lecture 07 08 syntax analysis-4
Lecture 07 08 syntax analysis-4
Iffat Anjum
 
Lecture 03 lexical analysis
Lecture 03 lexical analysisLecture 03 lexical analysis
Lecture 03 lexical analysis
Iffat Anjum
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compiler
Iffat Anjum
 
Distributed contention based mac protocol for cognitive radio
Distributed contention based mac protocol for cognitive radioDistributed contention based mac protocol for cognitive radio
Distributed contention based mac protocol for cognitive radio
Iffat Anjum
 
On qo s provisioning in context aware wireless sensor networks for healthcare
On qo s provisioning in context aware wireless sensor networks for healthcareOn qo s provisioning in context aware wireless sensor networks for healthcare
On qo s provisioning in context aware wireless sensor networks for healthcare
Iffat Anjum
 
Data link control
Data link controlData link control
Data link control
Iffat Anjum
 
Pnp mac preemptive slot allocation and non preemptive transmission for provid...
Pnp mac preemptive slot allocation and non preemptive transmission for provid...Pnp mac preemptive slot allocation and non preemptive transmission for provid...
Pnp mac preemptive slot allocation and non preemptive transmission for provid...
Iffat Anjum
 
Qo s based mac protocol for medical wireless body area sensor networks
Qo s based mac protocol for medical wireless body area sensor networksQo s based mac protocol for medical wireless body area sensor networks
Qo s based mac protocol for medical wireless body area sensor networksIffat Anjum
 
A reinforcement learning based routing protocol with qo s support for biomedi...
A reinforcement learning based routing protocol with qo s support for biomedi...A reinforcement learning based routing protocol with qo s support for biomedi...
A reinforcement learning based routing protocol with qo s support for biomedi...
Iffat Anjum
 
Data centric multiobjective qo s-aware routing protocol (dm-qos) for body are...
Data centric multiobjective qo s-aware routing protocol (dm-qos) for body are...Data centric multiobjective qo s-aware routing protocol (dm-qos) for body are...
Data centric multiobjective qo s-aware routing protocol (dm-qos) for body are...
Iffat Anjum
 
Quality of service aware mac protocol for body sensor networks
Quality of service aware mac protocol for body sensor networksQuality of service aware mac protocol for body sensor networks
Quality of service aware mac protocol for body sensor networks
Iffat Anjum
 

More from Iffat Anjum (20)

Cognitive radio network_MS_defense_presentation
Cognitive radio network_MS_defense_presentationCognitive radio network_MS_defense_presentation
Cognitive radio network_MS_defense_presentation
 
Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2Lecture 15 run timeenvironment_2
Lecture 15 run timeenvironment_2
 
Lecture 16 17 code-generation
Lecture 16 17 code-generationLecture 16 17 code-generation
Lecture 16 17 code-generation
 
Lecture 14 run time environment
Lecture 14 run time environmentLecture 14 run time environment
Lecture 14 run time environment
 
Lecture 12 intermediate code generation
Lecture 12 intermediate code generationLecture 12 intermediate code generation
Lecture 12 intermediate code generation
 
Lecture 13 intermediate code generation 2.pptx
Lecture 13 intermediate code generation 2.pptxLecture 13 intermediate code generation 2.pptx
Lecture 13 intermediate code generation 2.pptx
 
Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2Lecture 11 semantic analysis 2
Lecture 11 semantic analysis 2
 
Lecture 09 syntax analysis 05
Lecture 09 syntax analysis 05Lecture 09 syntax analysis 05
Lecture 09 syntax analysis 05
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01
 
Lecture 07 08 syntax analysis-4
Lecture 07 08 syntax analysis-4Lecture 07 08 syntax analysis-4
Lecture 07 08 syntax analysis-4
 
Lecture 03 lexical analysis
Lecture 03 lexical analysisLecture 03 lexical analysis
Lecture 03 lexical analysis
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compiler
 
Distributed contention based mac protocol for cognitive radio
Distributed contention based mac protocol for cognitive radioDistributed contention based mac protocol for cognitive radio
Distributed contention based mac protocol for cognitive radio
 
On qo s provisioning in context aware wireless sensor networks for healthcare
On qo s provisioning in context aware wireless sensor networks for healthcareOn qo s provisioning in context aware wireless sensor networks for healthcare
On qo s provisioning in context aware wireless sensor networks for healthcare
 
Data link control
Data link controlData link control
Data link control
 
Pnp mac preemptive slot allocation and non preemptive transmission for provid...
Pnp mac preemptive slot allocation and non preemptive transmission for provid...Pnp mac preemptive slot allocation and non preemptive transmission for provid...
Pnp mac preemptive slot allocation and non preemptive transmission for provid...
 
Qo s based mac protocol for medical wireless body area sensor networks
Qo s based mac protocol for medical wireless body area sensor networksQo s based mac protocol for medical wireless body area sensor networks
Qo s based mac protocol for medical wireless body area sensor networks
 
A reinforcement learning based routing protocol with qo s support for biomedi...
A reinforcement learning based routing protocol with qo s support for biomedi...A reinforcement learning based routing protocol with qo s support for biomedi...
A reinforcement learning based routing protocol with qo s support for biomedi...
 
Data centric multiobjective qo s-aware routing protocol (dm-qos) for body are...
Data centric multiobjective qo s-aware routing protocol (dm-qos) for body are...Data centric multiobjective qo s-aware routing protocol (dm-qos) for body are...
Data centric multiobjective qo s-aware routing protocol (dm-qos) for body are...
 
Quality of service aware mac protocol for body sensor networks
Quality of service aware mac protocol for body sensor networksQuality of service aware mac protocol for body sensor networks
Quality of service aware mac protocol for body sensor networks
 

Recently uploaded

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 

Recently uploaded (20)

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 

Lecture 04 syntax analysis

  • 2. Parsing • A.K.A. Syntax Analysis – Recognize sentences in a language. – Discover the structure of a document/program. – Construct (implicitly or explicitly) a tree (called as a parse tree) to represent the structure. – The above tree is used later to guide translation.
  • 3. Parsing During Compilation intermediate representation errors lexical analyzer parser rest of front end symbol table source program parse treeget next token token regular expressions • Collecting token information • Perform type checking • Intermediate code generation • uses a grammar to check structure of tokens • produces a parse tree • syntactic errors and recovery • recognize correct syntax • report errors
  • 4. Parsing Responsibilities Syntax Error Identification / Handling Recall typical error types: 1. Lexical : Misspellings 2. Syntactic : Omission, wrong order of tokens 3. Semantic : Incompatible types, undefined IDs 4. Logical : Infinite loop / recursive call Majority of error processing occurs during syntax analysis NOTE: Not all errors are identifiable !! if x<1 thenn y = 5: if ((x<1) & (y>5))) if (x+5) then if (i<9) then ... Should be <= not <
  • 5. Error Detection • Much responsibility on Parser – Many errors are syntactic in nature – Modern parsing method can detect the presence of syntactic errors in programs very efficiently – Detecting semantic or logical error is difficult • Challenges for error handler in Parser – It should report error clearly and accurately – It should recover from error and continue.. – It should not significantly slow down the processing of correct programs • Good news is – Common errors are simple and relatively easy to catch. • Errors don’t occur that frequently!! • 60% programs are syntactically and semantically correct • 80% erroneous statements have only 1 error, 13% have 2 • Most error are trivial : 90% single token error • 60% punctuation, 20% operator, 15% keyword, 5% other error
  • 6. • Difficult to generate clear and accurate error messages. Example function foo () { ... if (...) { ... } else { ... ... } <eof> Example int myVarr; ... x = myVar; ... Adequate Error Reporting is Not a Trivial Task Missing } here Not detected until here Misspelled ID here Not detected until here
  • 7. Error Recovery • After first error recovered – Compiler must go on! • Restore to some state and process the rest of the input • Error-Correcting Compilers – Issue an error message – Fix the problem – Produce an executable Example Error on line 23: “myVarr” undefined. “myVar” was used. May not be a good Idea!! – Guessing the programmers intention is not easy!
  • 8. Error Recovery May Trigger More Errors! • Inadequate recovery may introduce more errors – Those were not programmers errors • Example: int myVar flag ; ... x := flag; ... ... while (flag==0) ... Too many Error message may be obscuring – May bury the real message – Remedy: • allow 1 message per token or per statement • Quit after a maximum (e.g. 100) number of errors Declaration of flag is discarded Variable flag is undefined Variable flag is undefined
  • 9. Error Recovery Approaches: Panic Mode • Discard tokens until we see a “synchronizing” token. • The key... – Good set of synchronizing tokens – Knowing what to do then • Advantage – Simple to implement – Does not go into infinite loop – Commonly used • Disadvantage – May skip over large sections of source with some errors Example Skip to next occurrence of } end ; Resume by parsing the next statement
  • 10. Error Recovery Approaches: Phrase-Level Recovery • Compiler corrects the program by deleting or inserting tokens ...so it can proceed to parse from where it was. • The key... Don’t get into an infinite loop Example while (x==4) y:= a + b Insert do to fix the statement
  • 11. Context Free Grammars (CFG) • A context free grammar is a formal model that consists of: • Terminals Keywords Token Classes Punctuation • Non-terminals Any symbol appearing on the lefthand side of any rule • Start Symbol Usually the non-terminal on the lefthand side of the first rule • Rules (or “Productions”) BNF: Backus-Naur Form / Backus-Normal Form Stmt ::= if Expr then Stmt else Stmt
  • 13. Context Free Grammars : A First Look assign_stmt → id := expr ; expr → expr operator term expr → term term → id term → real term → integer operator → + operator → - Derivation: A sequence of grammar rule applications and substitutions that transform a starting non-term into a sequence of terminals / tokens.
  • 14. Derivation Let’s derive: id := id + real – integer ; assign_stmt assign_stmt → id := expr ; → id := expr ; expr → expr operator term →id := expr operator term; expr → expr operator term →id := expr operator term operator term; expr → term → id := term operator term operator term; term → id → id := id operator term operator term; operator → + → id := id + term operator term; term → real → id := id + real operator term; operator → - → id := id + real - term; term → integer → id := id + real - integer; using production:
  • 15. Example Grammar: Simple Arithmetic Expressions expr → expr op expr expr → ( expr ) expr → - expr expr → id op → + op → - op → * op → / op → ↑ 9 Production rules Terminals: id + - * / ↑ ( ) Nonterminals: expr, op Start symbol: expr
  • 16. Notational Conventions • Terminals – Lower-case letters early in the alphabet: a, b, c – Operator symbols: +, - – Punctuations symbols: parentheses, comma – Boldface strings: id or if • Nonterminals: – Upper-case letters early in the alphabet: A, B, C – The letter S (start symbol) – Lower-case italic names: expr or stmt • Upper-case letters late in the alphabet, such as X, Y, Z, represent either nonterminals or terminals. • Lower-case letters late in the alphabet, such as u, v, …, z, represent strings of terminals.
  • 17. Notational Conventions • Lower-case Greek letters, such as α, β, γ, represent strings of grammar symbols. Thus A→ α indicates that there is a single nonterminal A on the left side of the production and a string of grammar symbols α to the right of the arrow. • If A→ α1, A→ α2, …., A→ αk are all productions with A on the left, we may write A→ α1 | α2 | …. | αk • Unless otherwise started, the left side of the first production is the start symbol. E → E A E | ( E ) | -E | id A → + | - | * | / | ↑
  • 20.
  • 28. Ambiguous Grammar • More than one Parse Tree for some sentence. – The grammar for a programming language may be ambiguous – Need to modify it for parsing. • Also: Grammar may be left recursive. • Need to modify it for parsing.
  • 29. Elimination of Ambiguity • Ambiguous • A Grammar is ambiguous if there are multiple parse trees for the same sentence. • Disambiguation • Express Preference for one parse tree over others – Add disambiguating rule into the grammar
  • 30. Resolving Problems: Ambiguous Grammars Consider the following grammar segment: stmt → if expr then stmt | if expr then stmt else stmt | other (any other statement) If E1 then S1 else if E2 then S2 else S3 simple parse tree: stmt stmt stmtexpr exprE1 E2 S3 S1 S2 then then else else if if stmt stmt
  • 31. Example : What Happens with this string? If E1 then if E2 then S1 else S2 How is this parsed ? if E1 then if E2 then S1 else S2 if E1 then if E2 then S1 else S2 vs.
  • 32. Parse Trees: If E1 then if E2 then S1 else S2 Form 1: stmt stmt stmtexpr E1 S2 then elseif expr E2 S1 thenif stmt stmt expr E1 thenif stmt expr E2 S2S1 then else if stmt stmt Form 2:
  • 33. Removing Ambiguity Take Original Grammar: stmt → if expr then stmt | if expr then stmt else stmt | other (any other statement) Revise to remove ambiguity: stmt → matched_stmt | unmatched_stmt matched_stmt → if expr then matched_stmt else matched_stmt | other unmatched_stmt → if expr then stmt | if expr then matched_stmt else unmatched_stmt Rule: Match each else with the closest previous unmatched then.