The document discusses the phases of a compiler:
1) Lexical analysis scans the source code and converts it to tokens which are passed to the syntax analyzer.
2) Syntax analysis/parsing checks the token arrangements against the language grammar and generates a parse tree.
3) Semantic analysis checks that the parse tree follows the language rules by using the syntax tree and symbol table, performing type checking.
4) Intermediate code generation represents the program for an abstract machine in a machine-independent form like 3-address code.
This document provides an overview of a compiler design course, including prerequisites, textbook, course outline, and introductions to key compiler concepts. The course outline covers topics such as lexical analysis, syntax analysis, parsing techniques, semantic analysis, intermediate code generation, code optimization, and code generation. Compiler design involves translating a program from a source language to a target language. Key phases of compilation include lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation. Parsing techniques can be top-down or bottom-up.
This document provides an overview of the key concepts and phases in compiler design, including lexical analysis, syntax analysis using context-free grammars and parsing techniques, semantic analysis using attribute grammars, intermediate code generation, code optimization, and code generation. The major parts of a compiler are the analysis phase, which creates an intermediate representation from the source program using lexical analysis, syntax analysis, and semantic analysis, and the synthesis phase, which generates the target program from the intermediate representation using intermediate code generation, code optimization, and code generation.
The document provides an overview of compilers and interpreters. It discusses that a compiler translates source code into machine code that can be executed, while an interpreter executes source code directly without compilation. The document then covers the typical phases of a compiler in more detail, including the front-end (lexical analysis, syntax analysis, semantic analysis), middle-end/optimizer, and back-end (code generation). It also discusses interpreters, intermediate code representation, symbol tables, and compiler construction tools.
This document provides an introduction to compilers and their construction. It defines a compiler as a program that translates a source program into target machine code. The compilation process involves several phases including lexical analysis, syntax analysis, semantic analysis, code optimization, and code generation. An interpreter directly executes source code without compilation. The document also discusses compiler tools and intermediate representations used in the compilation process.
We have learnt that any computer system is made of hardware and software.
The hardware understands a language, which humans cannot understand. So we write programs in high-level language, which is easier for us to understand and remember.
These programs are then fed into a series of tools and OS components to get the desired code that can be used by the machine.
This is known as Language Processing System.
The document summarizes the key phases of a compiler:
1. The compiler takes source code as input and goes through several phases including lexical analysis, syntax analysis, semantic analysis, code optimization, and code generation to produce machine code as output.
2. Lexical analysis converts the source code into tokens, syntax analysis checks the grammar and produces a parse tree, and semantic analysis validates meanings.
3. Code optimization improves the intermediate code before code generation translates it into machine instructions.
System software module 4 presentation filejithujithin657
The document discusses the various phases of a compiler:
1. Lexical analysis scans source code and transforms it into tokens.
2. Syntax analysis validates the structure and checks for syntax errors.
3. Semantic analysis ensures declarations and statements follow language guidelines.
4. Intermediate code generation develops three-address codes as an intermediate representation.
5. Code generation translates the optimized intermediate code into machine code.
This document provides an overview of a compiler design course, including prerequisites, textbook, course outline, and introductions to key compiler concepts. The course outline covers topics such as lexical analysis, syntax analysis, parsing techniques, semantic analysis, intermediate code generation, code optimization, and code generation. Compiler design involves translating a program from a source language to a target language. Key phases of compilation include lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation. Parsing techniques can be top-down or bottom-up.
This document provides an overview of the key concepts and phases in compiler design, including lexical analysis, syntax analysis using context-free grammars and parsing techniques, semantic analysis using attribute grammars, intermediate code generation, code optimization, and code generation. The major parts of a compiler are the analysis phase, which creates an intermediate representation from the source program using lexical analysis, syntax analysis, and semantic analysis, and the synthesis phase, which generates the target program from the intermediate representation using intermediate code generation, code optimization, and code generation.
The document provides an overview of compilers and interpreters. It discusses that a compiler translates source code into machine code that can be executed, while an interpreter executes source code directly without compilation. The document then covers the typical phases of a compiler in more detail, including the front-end (lexical analysis, syntax analysis, semantic analysis), middle-end/optimizer, and back-end (code generation). It also discusses interpreters, intermediate code representation, symbol tables, and compiler construction tools.
This document provides an introduction to compilers and their construction. It defines a compiler as a program that translates a source program into target machine code. The compilation process involves several phases including lexical analysis, syntax analysis, semantic analysis, code optimization, and code generation. An interpreter directly executes source code without compilation. The document also discusses compiler tools and intermediate representations used in the compilation process.
We have learnt that any computer system is made of hardware and software.
The hardware understands a language, which humans cannot understand. So we write programs in high-level language, which is easier for us to understand and remember.
These programs are then fed into a series of tools and OS components to get the desired code that can be used by the machine.
This is known as Language Processing System.
The document summarizes the key phases of a compiler:
1. The compiler takes source code as input and goes through several phases including lexical analysis, syntax analysis, semantic analysis, code optimization, and code generation to produce machine code as output.
2. Lexical analysis converts the source code into tokens, syntax analysis checks the grammar and produces a parse tree, and semantic analysis validates meanings.
3. Code optimization improves the intermediate code before code generation translates it into machine instructions.
System software module 4 presentation filejithujithin657
The document discusses the various phases of a compiler:
1. Lexical analysis scans source code and transforms it into tokens.
2. Syntax analysis validates the structure and checks for syntax errors.
3. Semantic analysis ensures declarations and statements follow language guidelines.
4. Intermediate code generation develops three-address codes as an intermediate representation.
5. Code generation translates the optimized intermediate code into machine code.
The document provides an introduction to compiler design, including:
- A compiler converts a program written in a high-level language into machine code. It can run on a different machine than the target.
- Language processing systems like compilers transform high-level code into a form usable by machines through a series of translations.
- A compiler analyzes source code in two main phases - analysis and synthesis. The analysis phase creates an intermediate representation, and the synthesis phase generates target code from that.
The compiler is software that converts source code written in a high-level language into machine code. It works in two major phases - analysis and synthesis. The analysis phase performs lexical analysis, syntax analysis, and semantic analysis to generate an intermediate representation from the source code. The synthesis phase performs code optimization and code generation to create the target machine code from the intermediate representation. The compiler uses various components like a symbol table, parser, and code generator to perform this translation.
The document provides an introduction to compilers. It discusses that compilers are language translators that take source code as input and convert it to another language as output. The compilation process involves multiple phases including lexical analysis, syntax analysis, semantic analysis, code generation, and code optimization. It describes the different phases of compilation in detail and explains concepts like intermediate code representation, symbol tables, and grammars.
This document provides an overview of the principles of compiler design. It discusses the main phases of compilation, including lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation. For each phase, it describes the key techniques and concepts used, such as lexical analysis using regular expressions and finite automata, syntax analysis using parsing techniques, semantic analysis using symbol tables and type checking, and code optimization methods like dead code elimination and loop optimization. The document emphasizes that compilers are essential tools that translate high-level programming languages into executable machine code.
This document provides an introduction to compilers. It discusses how compilers bridge the gap between high-level programming languages that are easier for humans to write in and machine languages that computers can actually execute. It describes the various phases of compilation like lexical analysis, syntax analysis, semantic analysis, code generation, and optimization. It also compares compilers to interpreters and discusses different types of translators like compilers, interpreters, and assemblers.
1. The document describes the 6 main phases of a compiler: lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation.
2. Each phase transforms the source program into different representations, with the lexical analyzer identifying tokens, the syntax analyzer constructing a parse tree, and the semantic analyzer performing type checking.
3. The intermediate code generator produces machine-independent code, the code optimizer improves performance, and the code generator outputs machine-specific object code.
This document provides information about the CS416 Compiler Design course, including the instructor details, prerequisites, textbook, grading breakdown, course outline, and an overview of the major parts and phases of a compiler. The course will cover topics such as lexical analysis, syntax analysis using top-down and bottom-up parsing, semantic analysis using attribute grammars, intermediate code generation, code optimization, and code generation.
- The document outlines the goals, outcomes, prerequisites, topics covered, and grading for a compiler design course.
- The major goals are to provide an understanding of compiler phases like scanning, parsing, semantic analysis and code generation, and have students implement parts of a compiler for a small language.
- By the end of the course students will be familiar with compiler phases and be able to define the semantic rules of a programming language.
- Prerequisites include knowledge of programming languages, algorithms, and grammar theories.
- The course covers topics like scanning, parsing, semantic analysis, code generation and optimization.
The document summarizes the six main phases of a compiler:
1. The lexical analyzer identifies tokens from the source code and removes whitespace and comments.
2. The syntax analyzer checks that the code follows grammar rules of the language and constructs a parse tree.
3. The semantic analyzer verifies type consistency and checks for semantic errors using the symbol table and parse tree.
4. The intermediate code generator produces machine-independent code in a form that can be optimized and executed.
5. The code optimizer improves performance by removing unused code and variables without altering meaning.
6. The code generator produces machine-specific object code by selecting instructions and registers for the target platform.
The document outlines the major phases of a compiler: lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation. It describes the purpose and techniques used in each phase, including how lexical analyzers produce tokens, parsers use context-free grammars to build parse trees, and semantic analyzers perform type checking using attribute grammars. The intermediate code generation phase produces machine-independent codes that are later optimized and translated to machine-specific target codes.
A compiler is a program that translates a program written in a source language into an equivalent program in a target language. It has two major phases: analysis and synthesis. The analysis phase creates an intermediate representation using tools like a lexical analyzer, syntax analyzer, and semantic analyzer. The synthesis phase creates the target program from this representation using tools like an intermediate code generator, code optimizer, and code generator. Techniques used in compiler design like lexical analysis, parsing, and code generation have applications in other areas like text editors, databases, and natural language processing.
The document provides an overview of the compilation process and the different phases involved in compiler construction. It can be summarized as follows:
1. A compiler translates a program written in a source language into an equivalent program in a target language. It performs analysis, synthesis and error checking during this translation process.
2. The major phases of a compiler include lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, code generation and linking. Tools like Lex and Yacc are commonly used to generate lexical and syntax analyzers.
3. Regular expressions are used to specify patterns for tokens during lexical analysis. A lexical analyzer reads the source program and generates a sequence of tokens by matching character sequences to patterns
The document provides an overview of compiler design and the different phases involved in compiling a program. It discusses:
1) What compilers do by translating source code into machine code while hiding machine-dependent details. Compilers may generate pure machine code, augmented machine code, or virtual machine code.
2) The typical structure of a compiler which includes lexical analysis, syntactic analysis, semantic analysis, code generation, and optimization phases.
3) Lexical analysis involves scanning the source code and grouping characters into tokens. Regular expressions are used to specify patterns for tokens. Scanner generators like Lex and Flex can generate scanners from regular expression definitions.
The document provides an introduction to compilers, describing compilers as programs that translate source code written in a high-level language into an equivalent program in a lower-level language. It discusses the various phases of compilation including lexical analysis, syntax analysis, semantic analysis, code optimization, and code generation. It also describes different compiler components such as preprocessors, compilers, assemblers, and linkers, and distinguishes between compiler front ends and back ends.
The document discusses the different phases of a compiler:
1. Lexical analysis scans source code and converts it to tokens.
2. Syntax analysis checks token arrangements against the grammar to validate syntax.
3. Semantic analysis checks that rules like type compatibility are followed.
4. Intermediate code is generated for an abstract machine.
5. Code is optimized in the intermediate representation.
6. Code generation produces machine code from the optimized intermediate code.
This document outlines the course structure and content for UCS 802 Compiler Construction. It discusses the key components of a compiler including lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation. Parsing techniques like top-down and bottom-up are also covered. The major parts of a compiler including analysis and synthesis phases are defined.
Translation of a program written in a source language into a semantically equivalent program written in a target language
It also reports to its users the presence of errors in the source program
This document provides information about the CS213 Programming Languages Concepts course taught by Prof. Taymoor Mohamed Nazmy in the computer science department at Ain Shams University in Cairo, Egypt. It describes the syntax and semantics of programming languages, discusses different programming language paradigms like imperative, functional, and object-oriented, and explains concepts like lexical analysis, parsing, semantic analysis, symbol tables, intermediate code generation, optimization, and code generation which are parts of the compiler design process.
The document provides an introduction to compiler design, including:
- A compiler converts a program written in a high-level language into machine code. It can run on a different machine than the target.
- Language processing systems like compilers transform high-level code into a form usable by machines through a series of translations.
- A compiler analyzes source code in two main phases - analysis and synthesis. The analysis phase creates an intermediate representation, and the synthesis phase generates target code from that.
The compiler is software that converts source code written in a high-level language into machine code. It works in two major phases - analysis and synthesis. The analysis phase performs lexical analysis, syntax analysis, and semantic analysis to generate an intermediate representation from the source code. The synthesis phase performs code optimization and code generation to create the target machine code from the intermediate representation. The compiler uses various components like a symbol table, parser, and code generator to perform this translation.
The document provides an introduction to compilers. It discusses that compilers are language translators that take source code as input and convert it to another language as output. The compilation process involves multiple phases including lexical analysis, syntax analysis, semantic analysis, code generation, and code optimization. It describes the different phases of compilation in detail and explains concepts like intermediate code representation, symbol tables, and grammars.
This document provides an overview of the principles of compiler design. It discusses the main phases of compilation, including lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation. For each phase, it describes the key techniques and concepts used, such as lexical analysis using regular expressions and finite automata, syntax analysis using parsing techniques, semantic analysis using symbol tables and type checking, and code optimization methods like dead code elimination and loop optimization. The document emphasizes that compilers are essential tools that translate high-level programming languages into executable machine code.
This document provides an introduction to compilers. It discusses how compilers bridge the gap between high-level programming languages that are easier for humans to write in and machine languages that computers can actually execute. It describes the various phases of compilation like lexical analysis, syntax analysis, semantic analysis, code generation, and optimization. It also compares compilers to interpreters and discusses different types of translators like compilers, interpreters, and assemblers.
1. The document describes the 6 main phases of a compiler: lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation.
2. Each phase transforms the source program into different representations, with the lexical analyzer identifying tokens, the syntax analyzer constructing a parse tree, and the semantic analyzer performing type checking.
3. The intermediate code generator produces machine-independent code, the code optimizer improves performance, and the code generator outputs machine-specific object code.
This document provides information about the CS416 Compiler Design course, including the instructor details, prerequisites, textbook, grading breakdown, course outline, and an overview of the major parts and phases of a compiler. The course will cover topics such as lexical analysis, syntax analysis using top-down and bottom-up parsing, semantic analysis using attribute grammars, intermediate code generation, code optimization, and code generation.
- The document outlines the goals, outcomes, prerequisites, topics covered, and grading for a compiler design course.
- The major goals are to provide an understanding of compiler phases like scanning, parsing, semantic analysis and code generation, and have students implement parts of a compiler for a small language.
- By the end of the course students will be familiar with compiler phases and be able to define the semantic rules of a programming language.
- Prerequisites include knowledge of programming languages, algorithms, and grammar theories.
- The course covers topics like scanning, parsing, semantic analysis, code generation and optimization.
The document summarizes the six main phases of a compiler:
1. The lexical analyzer identifies tokens from the source code and removes whitespace and comments.
2. The syntax analyzer checks that the code follows grammar rules of the language and constructs a parse tree.
3. The semantic analyzer verifies type consistency and checks for semantic errors using the symbol table and parse tree.
4. The intermediate code generator produces machine-independent code in a form that can be optimized and executed.
5. The code optimizer improves performance by removing unused code and variables without altering meaning.
6. The code generator produces machine-specific object code by selecting instructions and registers for the target platform.
The document outlines the major phases of a compiler: lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation. It describes the purpose and techniques used in each phase, including how lexical analyzers produce tokens, parsers use context-free grammars to build parse trees, and semantic analyzers perform type checking using attribute grammars. The intermediate code generation phase produces machine-independent codes that are later optimized and translated to machine-specific target codes.
A compiler is a program that translates a program written in a source language into an equivalent program in a target language. It has two major phases: analysis and synthesis. The analysis phase creates an intermediate representation using tools like a lexical analyzer, syntax analyzer, and semantic analyzer. The synthesis phase creates the target program from this representation using tools like an intermediate code generator, code optimizer, and code generator. Techniques used in compiler design like lexical analysis, parsing, and code generation have applications in other areas like text editors, databases, and natural language processing.
The document provides an overview of the compilation process and the different phases involved in compiler construction. It can be summarized as follows:
1. A compiler translates a program written in a source language into an equivalent program in a target language. It performs analysis, synthesis and error checking during this translation process.
2. The major phases of a compiler include lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, code generation and linking. Tools like Lex and Yacc are commonly used to generate lexical and syntax analyzers.
3. Regular expressions are used to specify patterns for tokens during lexical analysis. A lexical analyzer reads the source program and generates a sequence of tokens by matching character sequences to patterns
The document provides an overview of compiler design and the different phases involved in compiling a program. It discusses:
1) What compilers do by translating source code into machine code while hiding machine-dependent details. Compilers may generate pure machine code, augmented machine code, or virtual machine code.
2) The typical structure of a compiler which includes lexical analysis, syntactic analysis, semantic analysis, code generation, and optimization phases.
3) Lexical analysis involves scanning the source code and grouping characters into tokens. Regular expressions are used to specify patterns for tokens. Scanner generators like Lex and Flex can generate scanners from regular expression definitions.
The document provides an introduction to compilers, describing compilers as programs that translate source code written in a high-level language into an equivalent program in a lower-level language. It discusses the various phases of compilation including lexical analysis, syntax analysis, semantic analysis, code optimization, and code generation. It also describes different compiler components such as preprocessors, compilers, assemblers, and linkers, and distinguishes between compiler front ends and back ends.
The document discusses the different phases of a compiler:
1. Lexical analysis scans source code and converts it to tokens.
2. Syntax analysis checks token arrangements against the grammar to validate syntax.
3. Semantic analysis checks that rules like type compatibility are followed.
4. Intermediate code is generated for an abstract machine.
5. Code is optimized in the intermediate representation.
6. Code generation produces machine code from the optimized intermediate code.
This document outlines the course structure and content for UCS 802 Compiler Construction. It discusses the key components of a compiler including lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization, and code generation. Parsing techniques like top-down and bottom-up are also covered. The major parts of a compiler including analysis and synthesis phases are defined.
Translation of a program written in a source language into a semantically equivalent program written in a target language
It also reports to its users the presence of errors in the source program
This document provides information about the CS213 Programming Languages Concepts course taught by Prof. Taymoor Mohamed Nazmy in the computer science department at Ain Shams University in Cairo, Egypt. It describes the syntax and semantics of programming languages, discusses different programming language paradigms like imperative, functional, and object-oriented, and explains concepts like lexical analysis, parsing, semantic analysis, symbol tables, intermediate code generation, optimization, and code generation which are parts of the compiler design process.
Post init hook in the odoo 17 ERP ModuleCeline George
In Odoo, hooks are functions that are presented as a string in the __init__ file of a module. They are the functions that can execute before and after the existing code.
Creativity for Innovation and SpeechmakingMattVassar1
Tapping into the creative side of your brain to come up with truly innovative approaches. These strategies are based on original research from Stanford University lecturer Matt Vassar, where he discusses how you can use them to come up with truly innovative solutions, regardless of whether you're using to come up with a creative and memorable angle for a business pitch--or if you're coming up with business or technical innovations.
Information and Communication Technology in EducationMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 2)-𝐏𝐫𝐞𝐥𝐢𝐦𝐬
𝐄𝐱𝐩𝐥𝐚𝐢𝐧 𝐭𝐡𝐞 𝐈𝐂𝐓 𝐢𝐧 𝐞𝐝𝐮𝐜𝐚𝐭𝐢𝐨𝐧:
Students will be able to explain the role and impact of Information and Communication Technology (ICT) in education. They will understand how ICT tools, such as computers, the internet, and educational software, enhance learning and teaching processes. By exploring various ICT applications, students will recognize how these technologies facilitate access to information, improve communication, support collaboration, and enable personalized learning experiences.
𝐃𝐢𝐬𝐜𝐮𝐬𝐬 𝐭𝐡𝐞 𝐫𝐞𝐥𝐢𝐚𝐛𝐥𝐞 𝐬𝐨𝐮𝐫𝐜𝐞𝐬 𝐨𝐧 𝐭𝐡𝐞 𝐢𝐧𝐭𝐞𝐫𝐧𝐞𝐭:
-Students will be able to discuss what constitutes reliable sources on the internet. They will learn to identify key characteristics of trustworthy information, such as credibility, accuracy, and authority. By examining different types of online sources, students will develop skills to evaluate the reliability of websites and content, ensuring they can distinguish between reputable information and misinformation.
How to Create User Notification in Odoo 17Celine George
This slide will represent how to create user notification in Odoo 17. Odoo allows us to create and send custom notifications on some events or actions. We have different types of notification such as sticky notification, rainbow man effect, alert and raise exception warning or validation.
How to Download & Install Module From the Odoo App Store in Odoo 17Celine George
Custom modules offer the flexibility to extend Odoo's capabilities, address unique requirements, and optimize workflows to align seamlessly with your organization's processes. By leveraging custom modules, businesses can unlock greater efficiency, productivity, and innovation, empowering them to stay competitive in today's dynamic market landscape. In this tutorial, we'll guide you step by step on how to easily download and install modules from the Odoo App Store.
Brand Guideline of Bashundhara A4 Paper - 2024khabri85
It outlines the basic identity elements such as symbol, logotype, colors, and typefaces. It provides examples of applying the identity to materials like letterhead, business cards, reports, folders, and websites.
Cross-Cultural Leadership and CommunicationMattVassar1
Business is done in many different ways across the world. How you connect with colleagues and communicate feedback constructively differs tremendously depending on where a person comes from. Drawing on the culture map from the cultural anthropologist, Erin Meyer, this class discusses how best to manage effectively across the invisible lines of culture.
bryophytes.pptx bsc botany honours second semester
Compier Design_Unit I.ppt
1. Compiler Design
Textbook:
Alfred V. Aho, Ravi Sethi, and Jeffrey D. Ullman,
“Compilers: Principles, Techniques, and Tools”
Addison-Wesley, 1986.
2. Unit – I Syllabus
2
Compilers – Analysis of the source program-Phases of a compiler –
Cousins of the Compiler-Grouping of Phases – Compiler construction
tools- Lexical Analysis – Role of Lexical Analyzer-Input Buffering-
Specification of Tokens--Finite automation – deterministic Finite
automation - non deterministic-Transition Tables- Acceptance of Input
Strings by Automata-State Diagrams and Regular Expressions- Conversion
of regular expression to NFA - Thompson’s method-Conversion of NFA to
DFA- Simulation of an NFA-Converting Regular expression directly to DFA-
Minimization of DFA-Minimization of NFA- Design of lexical analysis (LEX)
3. Compiler - Introduction
• A compiler is a program that can read a program in one language - the
source language - and translate it into an equivalent program in another
language - the target language.
• A compiler acts as a translator, transforming human-oriented
programming languages into computer-oriented machine languages.
• Ignore machine-dependent details for programmer
Jeya R 3
4. COMPILERS
• A compiler is a program takes a program written in a
source language and translates it into an equivalent program
in a target language.
source program COMPILER target program
error messages
Jeya R 4
( Normally a program written in
a high-level programming language)
( Normally the equivalent program in
machine code – relocatable object file)
5. CompilervsInterpreter
• An interpreter is another common kind of language
processor. Instead of producing a target program as a
translation, an interpreter appears to directly execute
the operations specified in the source program on
inputs supplied by the user
• The machine-language target program produced by a
compiler is usually much faster than an interpreter at
mapping inputs to outputs .
• An interpreter, however, can usually give better error
diagnostics than a compiler, because it executes the source
program statement by statement
Jeya R 5
6. Compiler Applications
• Machine Code Generation
– Convert source language program to machine understandable one
– Takes care of semantics of varied constructs of source language
– Considers limitations and specific features of target machine
– Automata theory helps in syntactic checks
– valid and invalid programs
– Compilation also generate code for syntactically correct programs
Jeya R 6
7. Structureof aCompiler
• Breaks the source program into pieces
and fit into a
grammatical structure
• If this part detect any syntactically ill
formed or semantically unsound error it
is report to the user
• It collect the information about the
source program and stored in a data
structure – Symbol Table
• Construct the target program from
the available symbol table and
intermediate representation
Analysis
Synthesis
Jeya R 7
9. Phases of A Compiler
Jeya R 9
Lexical
Analyzer
Semantic
Analyzer
Syntax
Analyzer
Intermediate
Code Generator
Code
Optimizer
Code
Generator
Target
Program
Source
Program
• Each phase transforms the source program from one representation
into another representation.
• They communicate with error handlers.
• They communicate with the symbol table.
10. Lexical Analyzer
• Lexical Analyzer reads the source program character by character and returns
the tokens of the source program.
• A token describes a pattern of characters having same meaning in the source
program. (such as identifiers, operators, keywords, numbers, delimeters and so
on)
Ex: newval := oldval + 12 => tokens: newval identifier
:= assignment
operator
oldval identifier
+ add operator
12 a number
• Puts information about identifiers into the symbol table.
• Regular expressions are used to describe tokens (lexical constructs).
• A (Deterministic) Finite State Automaton can be used in the implementation of a
lexical analyzer.
Jeya R 10
11. Phasesof Compiler-LexicalAnalysis
• It is also called as scanning
• This phase scans the source code as a stream of characters and converts it
into meaningful lexemes.
• For each lexeme, the lexical analyzer produces as output a token of
the form
• It passes on to the subsequent phase, syntax analysis.
<token-name,
attribute-value>
It is an abstract
symbol that is
used during
syntax
analysis
This points to an entry in
the symbol table for this
token.
Information from the
symbol-table
entry 'is needed for
semantic analysis and
code generation
Jeya R 11
12. Token , Pattern and Lexeme
• Token: Token is a sequence of characters that
can be treated as a single logical entity. Typical
tokens are, 1) Identifiers 2) keywords 3) operators 4)
special symbols 5)constants
• Pattern: A set of strings in the input for which the
same token is produced as output. This set of strings
is described by a rule called a pattern associated
with the token.
• Lexeme: A lexeme is a sequence of characters in
the source program that is matched by the pattern
for a token.
Jeya R 12
13. Phasesof Compiler-SymbolTable
Management
• Symbol table is a data structure holding information about all symbols defined in
the source program
• Not part of the final code, however used as reference by all phases of a
compiler
• Typical information stored there include name, type, size, relative offset of
variables
• Generally created by lexical analyzer and syntax analyzer
• Good data structures needed to minimize searching time
• The data structure may be flat or hierarchical
14. Syntax
Analysis
A Syntax Analyzer creates the syntactic
structure (generally a parse tree) of the
given program.
A syntax analyzer is also called as a parser.
A parse tree describes a syntactic structure
•In a parse tree, all terminals are at leaves.
• All inner nodes are non-terminals in
a context free grammar
15. Phasesof Compiler-SyntaxAnalysis
• This is the second phase, it is also called as parsing
• It takes the token produced by lexical analysis as input and generates a parse
tree (or syntax tree).
• In this phase, token arrangements are checked against the source code
grammar, i.e. the parser checks if the expression made by the tokens is
syntactically correct.
16. Syntax Analyzer versus Lexical Analyzer
• Which constructs of a program should be recognized by the
lexical analyzer, and which ones by the syntax analyzer?
• Both of them do similar things; But the lexical analyzer deals with simple non-
recursive constructs of the language.
• The syntax analyzer deals with recursive constructs of the language.
• The lexical analyzer simplifies the job of the syntax analyzer.
• The lexical analyzer recognizes the smallest meaningful units (tokens) in a
source program.
• The syntax analyzer works on the smallest meaningful units (tokens) in a
source program to recognize meaningful structures in our programming
language.
Jeya R 16
18. Phasesof Compiler-SemanticAnalysis
• Semantic analysis checks whether the parse tree constructed follows the
rules of language.
• The semantic analyzer uses the syntax tree and the information in the
symbol table to check the source program for semantic consistency with
the language definition.
• It also gathers type information and saves it in either the syntax
tree or the symbol table, for subsequent use during intermediate-code
generation.
• An important part of semantic analysis is type checking
19. Phasesof Compiler-SemanticAnalysis
• Suppose that position, initial, and rate have been declared to be
floating-point numbers and that the lexeme 60 by itself forms an integer.
• The type checker in the semantic analyzer discovers that the operator
* is applied to a floating-point number rate and an integer 60.
• In this case, the integer may be converted into a floating-point number.
21. Phasesof Compiler-IntermediateCode
Generation
• After semantic analysis the compiler generates an intermediate code of
the source code for the target machine.
• It represents a program for some abstract machine.
• It is in between the high-level language and the machine language.
• This intermediate code should be generated in such a way that it makes
it easier to be translated into the target machine code.
• A compiler may produce an explicit intermediate codes representing the
source program.
• These intermediate codes are generally machine (architecture
independent). But the level of intermediate codes is close to the level of
machine codes
22. Phasesof Compiler-IntermediateCode
Generation
• An intermediate form called three-address code were used
• It consists of a sequence of assembly-like instructions with three
operands per instruction. Each operand can act like a register.
24. Phasesof Compiler-CodeOptimization
• The next phase does code optimization of the intermediate code.
• Optimization can be assumed as something that removes unnecessary
code lines, and arranges the sequence of statements in order to speed up
the program execution without wasting resources (CPU, memory).
26. Phasesof Compiler-CodeGeneration
• In this phase, the code generator takes the optimized representation of the
intermediate code and maps it to the target machine language.
• If the target language is machine code, registers or memory locations are
selected for each of the variables used by the program.
• Then, the intermediate instructions are translated into sequences of
machine instructions that perform the same task.
• Produces the target language in a specific architecture.
• The target program is normally is a relocatable object file containing the
machine codes
27. Phasesof Compiler-CodeGeneration
• For example, using registers R1 and R2, the intermediate code
might get translated into the machine code
• The first operand of each instruction specifies a destination. The F
in each instruction tells us that it deals with floating-point
numbers.
31. Role of a Lexical Analyzer
• Role of lexical analyzer
• Specification of tokens
• Recognition of tokens
• Lexical analyzer generator
• Finite automata
• Design of lexical analyzer generator
Jeya R 31
32. Why to separateLexicalanalysisand parsing
1. Simplicity of design
2. Improving compiler efficiency
3. Enhancing compiler portability
By Nagadevi
33. The role of lexical analyzer
Lexical Analyzer Parser
Source
program
token
getNextToken
Symbol
table
To semantic
analysis
By Nagadevi
34. CS416 Compiler Design 34
Lexical Analyzer
• Lexical Analyzer reads the source program character by character to
produce tokens.
• Normally a lexical analyzer doesn’t return a list of tokens at one shot, it
returns a token when the parser asks a token from it.
Lexical
Analyze
r
Parser
source
program
token
get next token
35. Lexical errors
• Some errors are out of power of lexical analyzer to
recognize:
• fi (a == f(x)) …
• However it may be able to recognize errors like:
• d = 2r
• Such errors are recognized when no pattern for tokens
matches a character sequence
By Nagadevi
36. Error recovery
• Panic mode: successive characters are ignored until we
reach to a well formed token
• Delete one character from the remaining input
• Insert a missing character into the remaining input
• Replace a character by another character
• Transpose two adjacent characters
By Nagadevi
37. CS416 Compiler Design 37
Token
• Token represents a set of strings described by a pattern.
• Identifier represents a set of strings which start with a letter continues with letters and
digits
• The actual string (newval) is called as lexeme.
• Tokens: identifier, number, addop, delimeter, …
• Since a token can represent more than one lexeme, additional information should be held
for that specific lexeme. This additional information is called as the attribute of the token.
• For simplicity, a token may have a single attribute which holds the required information for
that token.
• For identifiers, this attribute a pointer to the symbol table, and the symbol table holds
the actual attributes for that token.
38. Token
• Some attributes:
• <id,attr> where attr is pointer to the symbol table
• <assgop,_> no attribute is needed (if there is only one assignment operator)
• <num,val> where val is the actual value of the number.
• Token type and its attribute uniquely identifies a lexeme.
• Regular expressions are widely used to specify patterns.
Jeya R 38
39. Tokens, Patterns and Lexemes
• A token is a pair a token name and an optional token value
• A pattern is a description of the form that the lexemes of a
token may take
• A lexeme is a sequence of characters in the source program
that matches the pattern for a token
By Nagadevi
40. Example
Token Informal description Sample lexemes
if
else
comparison
id
number
literal
Characters i, f
Characters e, l, s, e
< or > or <= or >= or == or !=
Letter followed by letter and digits
Any numeric constant
Anything but “ sorrounded by “
if
else
<=, !=
pi, score, D2
3.14159, 0, 6.02e23
“core dumped”
printf(“total = %dn”, score);
By Nagadevi
41. CS416 Compiler Design 41
Terminology of Languages
• Alphabet : a finite set of symbols (ASCII characters)
• String :
• Finite sequence of symbols on an alphabet
• Sentence and word are also used in terms of string
• is the empty string
• |s| is the length of string s.
• Language: sets of strings over some fixed alphabet
• the empty set is a language.
• {} the set containing empty string is a language
• The set of well-formed C programs is a language
• The set of all possible identifiers is a language.
42. Terminology of Languages
• Operators on Strings:
• Concatenation: xy represents the concatenation of strings
x and y. s = s s = s
• sn
= s s s .. s ( n times) s0
=
Jeya R 42
43. Input buffering
• Sometimes lexical analyzer needs to look ahead some symbols to decide
about the token to return
• In C language: we need to look after -, = or < to decide what token to
return
• In Fortran: DO 5 I = 1.25
• We need to introduce a two buffer scheme to handle large look-aheads
safely
E = M * C * * 2 eof
43
47. Sentinels
Switch (*forward++) {
case eof:
if (forward is at end of first buffer) {
reload second buffer;
forward = beginning of second buffer;
}
else if {forward is at end of second buffer) {
reload first buffer;
forward = beginning of first buffer;
}
else /* eof within a buffer marks the end of input */
terminate lexical analysis;
E = M eof * C * * 2 eof eof
47
48. Specification of tokens
• In theory of compilation regular expressions are used to
formalize the specification of tokens
• Regular expressions are means for specifying regular
languages
• Example:
• Letter_(letter_ | digit)*
• Each regular expression is a pattern specifying the form of
strings
48
49. Regular expressions
• Ɛ is a regular expression, L(Ɛ) = {Ɛ}
• If a is a symbol in ∑then a is a regular expression, L(a) = {a}
• (r) | (s) is a regular expression denoting the language L(r) ∪
L(s)
• (r)(s) is a regular expression denoting the language L(r)L(s)
• (r)* is a regular expression denoting (L(r))*
• (r) is a regular expression denting L(r)
49
50. Regular definitions
d1 -> r1
d2 -> r2
…
dn -> rn
• Example:
letter_ -> A | B | … | Z | a | b | … | Z | _
digit -> 0 | 1 | … | 9
id -> letter_ (letter_ | digit)*
50
51. Extensions
• One or more instances: (r)+
• Zero or one instances: r?
• Character classes: [abc]
• Example:
• letter_ -> [A-Za-z_]
• digit -> [0-9]
• id -> letter_(letter|digit)*
51
52. Recognition of tokens
• Starting point is the language grammar to understand the
tokens:
stmt -> if expr then stmt
| if expr then stmt else stmt
| Ɛ
expr -> term relop term
| term
term -> id
| number
52
53. Recognition of tokens (cont.)
• The next step is to formalize the patterns:
digit -> [0-9]
Digits -> digit+
number -> digit(.digits)? (E[+-]? Digit)?
letter -> [A-Za-z_]
id -> letter (letter|digit)*
If -> if
Then -> then
Else -> else
Relop -> < | > | <= | >= | = | <>
• We also need to handle whitespaces:
ws -> (blank | tab | newline)+
53
54. CS416 Compiler Design 54
Operations on Languages
• Concatenation:
• L1L2 = { s1s2 | s1 L1 and s2 L2 }
• Union
• L1 L2 = { s| s L1 or s L2 }
• Exponentiation:
• L0 = {} L1 = L L2 = LL
• Kleene Closure
• L* =
• Positive Closure
• L+ =
0
i
i
L
1
i
i
L
55. CS416 Compiler Design 55
Example
• L1 = {a,b,c,d} L2 = {1,2}
• L1L2 = {a1,a2,b1,b2,c1,c2,d1,d2}
• L1 L2 = {a,b,c,d,1,2}
• L1
3 = all strings with length three (using a,b,c,d}
• L1
* = all strings using letters a,b,c,d and empty string
56. CS416 Compiler Design 56
Regular Definitions
• To write regular expression for some languages can be difficult, because their regular expressions can
be quite complex. In those cases, we may use regular definitions.
• We can give names to regular expressions, and we can use these names as symbols to define other
regular expressions.
• A regular definition is a sequence of the definitions of the form:
d1 r1 where di is a distinct name and
d2 r2 ri is a regular expression over symbols in
. {d1,d2,...,di-1}
dn rn
basic symbols previously defined names
57. CS416 Compiler Design 57
Regular Definitions (cont.)
• Ex: Identifiers in Pascal
letter A | B | ... | Z | a | b | ... | z
digit 0 | 1 | ... | 9
id letter (letter | digit ) *
• If we try to write the regular expression representing identifiers without using regular
definitions, that regular expression will be complex.
(A|...|Z|a|...|z) ( (A|...|Z|a|...|z) | (0|...|9) ) *
• Ex: Unsigned numbers in Pascal
digit 0 | 1 | ... | 9
digits digit +
opt-fraction ( . digits ) ?
opt-exponent ( E (+|-)? digits ) ?
unsigned-num digits opt-fraction opt-exponent
58. Regular expressions
• Ɛ is a regular expression, L(Ɛ) = {Ɛ}
• If a is a symbol in ∑then a is a regular expression, L(a) = {a}
• (r) | (s) is a regular expression denoting the language L(r) ∪
L(s)
• (r)(s) is a regular expression denoting the language L(r)L(s)
• (r)* is a regular expression denoting (L(r))*
• (r) is a regular expression denting L(r)
By Nagadevi
59. Regular definitions
d1 -> r1
d2 -> r2
…
dn -> rn
• Example:
letter_ -> A | B | … | Z | a | b | … | Z | _
digit -> 0 | 1 | … | 9
id -> letter_ (letter_ | digit)*
By Nagadevi
60. Extensions
• One or more instances: (r)+
• Zero or one instances: r?
• Character classes: [abc]
• Example:
• letter_ -> [A-Za-z_]
• digit -> [0-9]
• id -> letter_(letter|digit)*
By Nagadevi
61. Recognition of tokens
• Starting point is the language grammar to understand the
tokens:
stmt -> if expr then stmt
| if expr then stmt else stmt
| Ɛ
expr -> term relop term
| term
term -> id
| number
By Nagadevi
62. Recognition of tokens (cont.)
• The next step is to formalize the patterns:
digit -> [0-9]
Digits -> digit+
number -> digit(.digits)? (E[+-]? Digit)?
letter -> [A-Za-z_]
id -> letter (letter|digit)*
If -> if
Then -> then
Else -> else
Relop -> < | > | <= | >= | = | <>
• We also need to handle whitespaces:
ws -> (blank | tab | newline)+
By Nagadevi
64. Design of a Lexical
Analyzer
6
4
• LEX is a software tool that automatically construct a lexical
analyzer from a program
• The Lexical analyzer will be of the form
P1 {action 1}
P2 {action 2}
--
--
• Each pattern pi is a regular expression and action i is a program
fragment that is to be executed whenever a lexeme matched
by pi is found in the input
• If two or more patterns that match the longest lexeme, the first
listed matching pattern is chosen
65. Design of a Lexical Analyzer
6
5
• Here the Lex compiler
constructs a transition table
for a finite automaton from
the regular expression pattern
in the Lex specification
• The lexical analyzer itself
consists of a finite automaton
simulator that uses this
transition table to look for the
regular expression patterns in
the input buffer
66. General
format
6
6
• The declarations section includes declarations
of variables, manifest constants (identifiers
declared to stand for a constant, e.g., the
name of a token)
• The translation rules each have the form
Pattern { Action )
• Each pattern is a regular expression, which
may use the regular definitions of the
declaration section.
• The actions are fragments of code, typically
written in C, although many variants of Lex
using other languages have been created.
• The third section holds whatever additional
functions are used in the actions.
67. Lexical Analyzer Generator - Lex
67
Lexical Compiler
Lex Source
program
lex.l
lex.yy.c
C
compiler
lex.yy.c a.out
a.out
Input
stream
Sequenc
e of
tokens
68. Finite Automata
• Regular expressions = specification
• Finite automata = implementation
• Recognizer ---A recognizer for a language is a program that takes as input
a string x answers ‘yes’ if x is a sentence of the language and ‘no’ otherwise.
• A better way to convert a regular expression to a recognizer is to construct
a generalized transition diagram from the expression. This diagram is
called a finite automaton.
• Finite Automaton can be
• Deterministic
• Non-deterministic
68
69. Finite Automata
• A finite automaton consists of
• An input alphabet
• A set of states S
• A start state n
• A set of accepting states F S
• A set of transitions state input state
6
9
70. Finite Automata
• Transition
s1 a s2
• Is read
In state s1 on input “a” go to state s2
• If end of input
• If in accepting state => accept, otherwise => reject
• If no transition possible => reject
70
71. Finite Automata State Graphs
• A state
71
• The start state
• An accepting state
• A transition
a
72. CS416 Compiler Design 72
FiniteAutomata
• A recognizer for a language is a program that takes a string x, and answers “yes” if x is a sentence of that
language, and “no” otherwise.
• We call the recognizer of the tokens as a finite automaton.
• A finite automaton can be: deterministic(DFA) or non-deterministic (NFA)
• This means that we may use a deterministic or non-deterministic automaton as a lexical analyzer.
• Both deterministic and non-deterministic finite automaton recognize regular sets.
• Which one?
• deterministic – faster recognizer, but it may take more space
• non-deterministic – slower, but it may take less space
• Deterministic automatons are widely used lexical analyzers.
• First, we define regular expressions for tokens; Then we convert them into a DFA to get a lexical
analyzer for our tokens.
• Algorithm1: Regular Expression NFA DFA (two steps: first to NFA, then to DFA)
• Algorithm2: Regular Expression DFA (directly convert a regular expression into a DFA)
73. Non-Deterministic Finite Automaton (NFA)
• A non-deterministic finite automaton (NFA) is a mathematical model that consists of:
• S - a set of states
• - a set of input symbols (alphabet)
• move – a transition function move to map state-symbol pairs to sets of states.
• s0 - a start (initial) state
• F – a set of accepting states (final states)
• - transitions are allowed in NFAs. In other words, we can move from one state to
another one without consuming any symbol.
• A NFA accepts a string x, if and only if there is a path from the starting state to one of
accepting states such that edge labels along this path spell out x.
73
74. Deterministicand NondeterministicAutomata
• Deterministic Finite Automata (DFA)
• One transition per input per state
• No -moves
• Nondeterministic Finite Automata (NFA)
• Can have multiple transitions for one input in a given state
• Can have -moves
• Finite automata have finite memory
• Need only to encode the current state
74
75. A Simple Example
• A finite automaton that accepts only “1”
• A finite automaton accepts a string if we can follow transitions labeled
with the characters in the string from the start to some accepting state
75
1
76. Another Simple Example
• A finite automaton accepting any number of 1’s followed by a single 0
• Alphabet: {0,1}
• Check that “1110” is accepted.
76
0
1
80. CS416 Compiler Design 80
ConvertingA Regular Expressioninto A NFA
(Thomson’sConstruction)
• This is one way to convert a regular expression into a NFA.
• There can be other ways (much efficient) for the conversion.
• Thomson’s Construction is simple and systematic method.
It guarantees that the resulting NFA will have exactly one
final state, and one start state.
• Construction starts from simplest parts (alphabet symbols).
• To create a NFA for a complex regular expression, NFAs of
its sub-expressions are combined to create its NFA,
81. CS416 Compiler Design 81
• To recognize an empty string
• To recognize a symbol a in the alphabet
• If N(r1) and N(r2) are NFAs for regular expressions r1 and r2
• For regular expression r1 | r2
a
f
i
f
i
N(r2)
N(r1)
f
i
NFA for r1 | r2
Thomson’s Construction (cont.)
82. CS416 Compiler Design 82
Thomson’s Construction (cont.)
• For regular expression r1 r2
i f
N(r2)
N(r1)
NFA for r1 r2
Final state of N(r2) become
final state of N(r1r2)
• For regular expression r*
N(r)
i f
NFA for r*
83. CS416 Compiler Design 83
Thomson’sConstruction(Example- (a|b) * a )
a:
a
b
b:
(a | b)
a
b
b
a
(a|b) *
b
a
a
(a|b) * a
85. CS416 Compiler Design 85
Convertinga NFAinto a DFA (subset
construction)
put -closure({s0}) as an unmarked
state into the set of DFA (DS)
while (there is one unmarked S1 in
DS) do
begin
mark S1
for each input symbol a do
begin
S2 -closure(move(S1,a))
if (S2 is not in DS) then
add S2 into DS as an
unmarked state
transfunc[S1,a] S2
end
end
• a state S in DS is an accepting state of DFA if a state
in S is an accepting state of NFA
• the start state of DFA is -closure({s0})
set of states to which there is a transition on
a from a state s in S1
-closure({s0}) is the set of all states can b
accessible
from s0 by -transition.
86. CS416 Compiler Design 86
Converting a NFA into a DFA (Example)
b
a
a
0 1
3
4 5
2
7 8
6
S0 = -closure({0}) = {0,1,2,4,7} S0 into DS as an unmarked state
mark S0
-closure(move(S0,a)) = -closure({3,8}) = {1,2,3,4,6,7,8} = S1 S1 into DS
-closure(move(S0,b)) = -closure({5}) = {1,2,4,5,6,7} = S2 S2 into DS
transfunc[S0,a] S1 transfunc[S0,b] S2
mark S1
-closure(move(S1,a)) = -closure({3,8}) = {1,2,3,4,6,7,8} = S1
-closure(move(S1,b)) = -closure({5}) = {1,2,4,5,6,7} = S2
transfunc[S1,a] S1 transfunc[S1,b] S2
mark S2
-closure(move(S2,a)) = -closure({3,8}) = {1,2,3,4,6,7,8} = S1
-closure(move(S2,b)) = -closure({5}) = {1,2,4,5,6,7} = S2
transfunc[S2,a] S1 transfunc[S2,b] S2
87. CS416 Compiler Design 87
Convertinga NFAinto a DFA (Example – cont.)
S0 is the start state of DFA since 0 is a member of S0={0,1,2,4,7}
S1 is an accepting state of DFA since 8 is a member of S1 = {1,2,3,4,6,7,8}
b
a
a
b
b
a
S1
S2
S0