Lexical analyzer

79
Compiler Design 40106 1 CS40106 Compiler Design

description

mam gave it.

Transcript of Lexical analyzer

Page 1: Lexical analyzer

Compiler Design 40106 1

CS40106 Compiler Design

Page 2: Lexical analyzer

Compiler Design 40106 2

• Prerequisites:

• Automata Theory: DFAs, NFAs, Regular Expressions

Textbook:Alfred V. Aho, Ravi Sethi, and Jeffrey D. Ullman,

“Compilers: Principles, Techniques, and Tools”

Addison-Wesley, 1986.

K. Cooper, L. Torczon, ‘Engineering a Compiler’, Morgan Kaufmann, 1st Edition, 2003

Page 3: Lexical analyzer

Compiler Design 40106 3

Course Outline• Introduction to Compiling

• Lexical Analysis

• Syntax Analysis– Context Free Grammars

– Top-Down Parsing, LL Parsing

– Bottom-Up Parsing, LR Parsing

• Syntax-Directed Translation– Attribute Definitions

– Evaluation of Attribute Definitions

• Semantic Analysis, Type Checking

• Run-Time Organization

• Intermediate Code Generation

• Code Optimization

Page 4: Lexical analyzer

Compiler Design 40106 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

( Normally a program written in a high-level programming language)

( Normally the equivalent program inmachine code – relocatable object file)

Page 5: Lexical analyzer

Compiler Design 40106 5

Other Applications• In addition to the development of a compiler, the techniques used in

compiler design can be applicable to many problems in computer science.– Techniques used in a lexical analyzer can be used in text editors, information

retrieval system, and pattern recognition programs.

– Techniques used in a parser can be used in a query processing system such as SQL.

– A symbolic equation solver which takes an equation as input. That program should parse the given input equation.

– Most of the techniques used in compiler design can be used in Natural Language Processing (NLP) systems.

Page 6: Lexical analyzer

Compiler Design 40106 6

Major Parts of Compilers

• There are two major parts of a compiler: Analysis and Synthesis

• In analysis phase, an intermediate representation is created from the given source program. – Lexical Analyzer, Syntax Analyzer and Semantic Analyzer are the parts of this

phase.

• In synthesis phase, the equivalent target program is created from this intermediate representation. – Intermediate Code Generator, Code Generator, and Code Optimizer are the parts

of this phase.

Page 7: Lexical analyzer

Compiler Design 40106 7

Phases of A Compiler

Lexical Analyzer

Semantic Analyzer

Syntax Analyzer

IntermediateCode Generator

Code Optimizer

CodeGenerator

TargetProgram

SourceProgram

• Each phase transforms the source program from one representation into another representation.

• They communicate with error handlers.

• They communicate with the symbol table.

Page 8: Lexical analyzer

Compiler Design 40106 8

1. 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 operatoroldval identifier+ add operator12 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.

Page 9: Lexical analyzer

Compiler Design 40106 9

2. Syntax Analyzer

• 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.assgstmt

identifier := expression

newval expression + expression

identifier number

oldval 12

• In a parse tree, all terminals are at leaves.

• All inner nodes are non-terminals in a context free grammar.

Page 10: Lexical analyzer

Compiler Design 40106 10

Syntax Analyzer (CFG)

• The syntax of a language is specified by a context free grammar (CFG).

• The rules in a CFG are mostly recursive.

• A syntax analyzer checks whether a given program satisfies the rules implied by a CFG or not.– If it satisfies, the syntax analyzer creates a parse tree for the given program.

• Ex: We use BNF (Backus Naur Form) to specify a CFG

assgstmt -> identifier := expression

expression -> identifier

expression -> number

expression -> expression + expression

Page 11: Lexical analyzer

Compiler Design 40106 11

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.

Page 12: Lexical analyzer

Compiler Design 40106 12

Parsing Techniques• Depending on how the parse tree is created, there are different parsing

techniques.• These parsing techniques are categorized into two groups:

– Top-Down Parsing, – Bottom-Up Parsing

• Top-Down Parsing:– Construction of the parse tree starts at the root, and proceeds towards the leaves.– Efficient top-down parsers can be easily constructed by hand.– Recursive Predictive Parsing, Non-Recursive Predictive Parsing (LL Parsing).

• Bottom-Up Parsing:– Construction of the parse tree starts at the leaves, and proceeds towards the root.– Normally efficient bottom-up parsers are created with the help of some software

tools.– Bottom-up parsing is also known as shift-reduce parsing.– Operator-Precedence Parsing – simple, restrictive, easy to implement – LR Parsing – much general form of shift-reduce parsing, LR, SLR, LALR

Page 13: Lexical analyzer

Compiler Design 40106 13

3. Semantic Analyzer

• A semantic analyzer checks the source program for semantic errors and collects the type information for the code generation.

• Type-checking is an important part of semantic analyzer.

• Context-free grammars used in the syntax analysis are integrated with attributes (semantic rules) – the result is a syntax-directed translation,

– Attribute grammars

• Ex:newval := oldval + 12

• The type of the identifier newval must match with type of the expression (oldval+12)

Page 14: Lexical analyzer

Compiler Design 40106 14

4. Intermediate Code Generation

• 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.

• Ex:newval := oldval * fact + 1

id1 := id2 * id3 + 1

temp1 := id2 * id3 Intermediates Codes (three address code)

temp2 := temp1 + 1

id1 := temp2

Page 15: Lexical analyzer

Intermediate Code Generation

• Properties of IR-

Easy to produce

Easy to translate into the target program

• IR can be in following forms-

Syntax trees

Postfix notation

Three address statements

• Properties of three address statements-

At most one operator in addition to an assignment operator

Must generate temporary names to hold the value computed at each

instruction

Some instructions have fewer than three operands

Compiler Design 40106 15

Page 16: Lexical analyzer

Compiler Design 40106 16

5. Code Optimizer (for Intermediate Code Generator)

• The code optimizer optimizes the code produced by the intermediate code generator in the terms of time and space.

• Ex:temp1 := id2 * id3

id1 := temp1 + 1

Page 17: Lexical analyzer

Compiler Design 40106 17

6. Code Generator

• Produces the target language in a specific architecture.

• The target program is normally a relocatable object file containing the machine code or assembly code.

• Intermediate instructions are each translated into a sequence of machine instructions that perform the same task.

• Ex:

( assume that we have an architecture with instructions whose at least one of its operands is

a machine register)

MOVE id2,R1

MULT id3,R1

ADD #1,R1

MOVE R1,id1

Page 18: Lexical analyzer

Phases of compiler

Compiler Design 40106 18

Page 19: Lexical analyzer

Compiler Design 40106 19

Page 20: Lexical analyzer

The Structure of a Compiler (8)

20

Scanner [Lexical Analyzer]

Scanner [Lexical Analyzer]

Parser [Syntax Analyzer]

Parser [Syntax Analyzer]

Semantic Process [Semantic analyzer]Semantic Process [Semantic analyzer]

Code Generator[Intermediate Code Generator]

Code Generator[Intermediate Code Generator]

Code OptimizerCode Optimizer

Tokens

Parse tree

Abstract Syntax Tree w/ Attributes

Non-optimized Intermediate Code

Optimized Intermediate Code

Code GenratorCode Genrator

Target machine code

Compiler Design 40106

Page 21: Lexical analyzer

The input program as you see it.

main (){ int i,sum; sum = 0; for (i=1; i<=10; i++); sum = sum + i; printf("%d\n",sum);}

21Compiler Design 40106

Page 22: Lexical analyzer

22Compiler Design 40106

Page 23: Lexical analyzer

Compiler Design 40106 23

Page 24: Lexical analyzer

24Compiler Design 40106

Page 25: Lexical analyzer

25Compiler Design 40106

Page 26: Lexical analyzer

26Compiler Design 40106

Page 27: Lexical analyzer

27Compiler Design 40106

Page 28: Lexical analyzer

28Compiler Design 40106

Page 29: Lexical analyzer

29Compiler Design 40106

Page 30: Lexical analyzer

30Compiler Design 40106

Page 31: Lexical analyzer

31Compiler Design 40106

Page 32: Lexical analyzer

32Compiler Design 40106

Page 33: Lexical analyzer

33Compiler Design 40106

Page 34: Lexical analyzer

Introducing Basic Terminology

• What are Major Terms for Lexical Analysis?– TOKEN

• A classification for a common set of strings

• Examples Include <Identifier>, <number>, etc.

– PATTERN

• The rules which characterize the set of strings for a token

• Recall File and OS Wildcards ([A-Z]*.*)

– LEXEME

• Actual sequence of characters that matches pattern and is classified by a token

• Identifiers: x, count, name, etc…

34Compiler Design 40106

Page 35: Lexical analyzer

Introducing Basic Terminology

Token Sample Lexemes Informal Description of Pattern

const

if

relation

id

num

literal

const

if

<, <=, =, < >, >, >=

pi, count, D2

3.1416, 0, 6.02E23

“core dumped”

const

if

< or <= or = or < > or >= or >

letter followed by letters and digits

any numeric constant

any characters between “ and “ except “

Classifies Pattern

Actual values are critical.

Info is :

1.Stored in symbol table2.Returned to parser

35Compiler Design 40106

Page 36: Lexical analyzer

Attributes for Tokens

Tokens influence parsing decision; the attributes influence the translation of tokens.

Example: E = M * C ** 2

<id, pointer to symbol-table entry for E>

<assign_op, >

<id, pointer to symbol-table entry for M>

<mult_op, >

<id, pointer to symbol-table entry for C>

<exp_op, >

<num, integer value 2>

36Compiler Design 40106

Page 37: Lexical analyzer

Role of the Lexical Analyzer

Compiler Design 40106 37

Page 38: Lexical analyzer

Tasks of Lexical Analyzer

• Reads source text and detects the token

• Stripe outs comments, white spaces, tab, newline characters.

• Correlates error messages from compilers to source program

Approaches to implementation

. Use assembly language- Most efficient but most difficult to implement

. Use high level languages like C- Efficient but difficult to implement

. Use tools like lex, flex- Easy to implement but not as efficient as the first two cases

Compiler Design 40106 38

Page 39: Lexical analyzer

39Compiler Design 40106

Page 40: Lexical analyzer

Handling Lexical ErrorsIn what Situations do Errors Occur?

– Lexical analyzer is unable to proceed because none of the patterns for tokens matches a prefix of remaining input.

For example:

fi ( a == f(x) )….

1) Panic mode recovery - deleting successive characters until a well formed token is formed.

2) Inserting a missing character

3) Replacing a missing character by a correct character

4) Transposing two adjacent characters.

5) Deleting an extraneous character

Compiler Design 40106 40

Page 41: Lexical analyzer

41Compiler Design 40106

Page 42: Lexical analyzer

42Compiler Design 40106

Page 43: Lexical analyzer

43Compiler Design 40106

Page 44: Lexical analyzer

44Compiler Design 40106

Page 45: Lexical analyzer

45Compiler Design 40106

Page 46: Lexical analyzer

46Compiler Design 40106

Page 47: Lexical analyzer

47Compiler Design 40106

Page 48: Lexical analyzer

48Compiler Design 40106

Page 49: Lexical analyzer

49Compiler Design 40106

Page 50: Lexical analyzer

50Compiler Design 40106

Page 51: Lexical analyzer

51Compiler Design 40106

Page 52: Lexical analyzer

52Compiler Design 40106

Page 53: Lexical analyzer

53Compiler Design 40106

Page 54: Lexical analyzer

54Compiler Design 40106

Page 55: Lexical analyzer

55Compiler Design 40106

Page 56: Lexical analyzer

56Compiler Design 40106

Page 57: Lexical analyzer

57Compiler Design 40106

Page 58: Lexical analyzer

58Compiler Design 40106

Page 59: Lexical analyzer

59Compiler Design 40106

Page 60: Lexical analyzer

60Compiler Design 40106

Page 61: Lexical analyzer

61Compiler Design 40106

Page 62: Lexical analyzer

62Compiler Design 40106

Page 63: Lexical analyzer

63Compiler Design 40106

Page 64: Lexical analyzer

64Compiler Design 40106

Page 65: Lexical analyzer

65Compiler Design 40106

Page 66: Lexical analyzer

66Compiler Design 40106

Page 67: Lexical analyzer

67Compiler Design 40106

Page 68: Lexical analyzer

68Compiler Design 40106

Page 69: Lexical analyzer

69Compiler Design 40106

Page 70: Lexical analyzer

70Compiler Design 40106

Page 71: Lexical analyzer

71Compiler Design 40106

Page 72: Lexical analyzer

72Compiler Design 40106

Page 73: Lexical analyzer

73Compiler Design 40106

Page 74: Lexical analyzer

74Compiler Design 40106

Page 75: Lexical analyzer

75Compiler Design 40106

Page 76: Lexical analyzer
Page 77: Lexical analyzer

77Compiler Design 40106

Page 78: Lexical analyzer

78Compiler Design 40106

Page 79: Lexical analyzer

79Compiler Design 40106