Docsity

Compiler Design (3170701), Study notes of Compiler Design

Toggle sidebar
bg1
CD 3170701 - Unit 1 - 1
Compiler Design (3170701): Unit 1 Notes
Overview of the Compiler and its Structure (3 hours)
Syllabus coverage
Official syllabus item Section Asked in papers
Language processor 1.1 W21, W25 (definitions)
Applications of language processors 1.2 S24
Definition, structure and working of compiler 1.3, 1.4 W22, S22, S23, W23, W24, S25, W25, S26
The science of building compilers 1.5 Not asked in these 10 papers
Basic understanding of interpreter and assembler 1.6, 1.7 W21, W25
Difference between interpreter and compiler 1.8 W24, S25, W25
Compilation of source code into target language 1.9 W22, W23, W25 and phase questions
Cousins of compiler 1.10 S22, W23, S24, W24, S26
Types of compiler 1.11 S24, W25, S26
Exam focus: phases of compiler, cousins of compiler and compiler vs interpreter. Papers are
written as S = Summer and W = Winter.
1.1 Language Processor
Definition: A language processor is system software that reads a program written in one language and
either translates it into another form or executes it. It is needed because a computer directly executes
only machine language, while programmers prefer high-level languages.
Language
processor
Input Output / action
Compiler High-level source program Equivalent target program (assembly or machine
code); reports errors
Interpreter Source program and its input data Executes the program and produces output directly
Assembler Assembly language program Machine code (object code)
Preprocessor Source with macros and file
inclusions
Expanded (pure) source program
Levels of language:
•Machine language: binary instructions; fast but hard to write and machine dependent.
•Assembly language: mnemonics such as LOAD and ADD; machine dependent.
•High-level language: C, C++, Java, Python; readable and largely machine independent.
Advantages: programmer productivity, portability, early error detection. Limitations: translation takes
time and memory, and generated code may be less efficient than expert hand-written code.
1.2 Applications of Language Processors and Compiler
Technology
Application Explanation Example
Implementation of
high-level languages
Translates abstract features (classes, dynamic
dispatch, garbage collection) into efficient low-level
code.
C, C++, Java compilers
Optimization for parallelism Finds operations that can run together on multiple
issue units or processors.
Instruction scheduling,
auto-parallelization
Optimization for memory
hierarchy
Arranges code and data to use registers and cache
well.
Register allocation, loop
blocking
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28

Partial preview of the text

Download Compiler Design (3170701) and more Study notes Compiler Design in PDF only on Docsity!

Compiler Design (3170701): Unit 1 Notes

Overview of the Compiler and its Structure (3 hours)

Syllabus coverage

Official syllabus item Section Asked in papers

Language processor 1.1 W21, W25 (definitions)

Applications of language processors 1.2 S

Definition, structure and working of compiler 1.3, 1.4 W22, S22, S23, W23, W24, S25, W25, S

The science of building compilers 1.5 Not asked in these 10 papers

Basic understanding of interpreter and assembler 1.6, 1.7 W21, W

Difference between interpreter and compiler 1.8 W24, S25, W

Compilation of source code into target language 1.9 W22, W23, W25 and phase questions

Cousins of compiler 1.10 S22, W23, S24, W24, S

Types of compiler 1.11 S24, W25, S

Exam focus: phases of compiler , cousins of compiler and compiler vs interpreter. Papers are written as S = Summer and W = Winter.

1.1 Language Processor

Definition: A language processor is system software that reads a program written in one language and either translates it into another form or executes it. It is needed because a computer directly executes only machine language, while programmers prefer high-level languages.

Language processor

Input Output / action

Compiler High-level source program Equivalent target program (assembly or machine code); reports errors

Interpreter Source program and its input data Executes the program and produces output directly

Assembler Assembly language program Machine code (object code)

Preprocessor Source with macros and file inclusions

Expanded (pure) source program

Levels of language:

  • Machine language: binary instructions; fast but hard to write and machine dependent.
  • Assembly language: mnemonics such as LOAD and ADD; machine dependent.
  • High-level language: C, C++, Java, Python; readable and largely machine independent. Advantages: programmer productivity, portability, early error detection. Limitations: translation takes time and memory, and generated code may be less efficient than expert hand-written code.

1.2 Applications of Language Processors and Compiler

Technology

Application Explanation Example

Implementation of high-level languages

Translates abstract features (classes, dynamic dispatch, garbage collection) into efficient low-level code.

C, C++, Java compilers

Optimization for parallelism Finds operations that can run together on multiple issue units or processors.

Instruction scheduling, auto-parallelization

Optimization for memory hierarchy

Arranges code and data to use registers and cache well.

Register allocation, loop blocking

Application Explanation Example

Design of new computer architectures

Hardware and compilers are designed and evaluated together.

RISC, vector and VLIW machines

Program translation Translates between different representations. Binary translation, query compilation, hardware synthesis from Verilog

Compiled simulation Compiles a design into code that simulates it, which is faster than interpreting it.

Circuit simulation

Software productivity tools Uses program analysis to find defects. Type checking, bounds checking, memory-leak detection

Editors and text processing Uses scanning and parsing. Syntax highlighting, code formatters, HTML/XML processing

1.3 Compiler: Definition and Working

Definition: A compiler is a program that reads a program written in one language (the source language ) and translates it into an equivalent program in another language (the target language ). During translation it reports errors found in the source program.

(a) Compiler

Source program Compiler Target program

Error messages

Output

run

Input

(b) Interpreter

Source program

Input

Interpreter Output

Fig. 1: Working of a compiler and an interpreter

Analysis-synthesis model

  • Analysis part (front end): breaks the source program into pieces, checks its grammatical and semantic correctness, collects information in the symbol table and creates an intermediate representation.
  • Synthesis part (back end): builds the target program from the intermediate representation and the symbol table.

Properties of a good compiler

  • Preserves the meaning of the source program (correctness).
  • Generates fast and small target code.
  • Compiles in reasonable time.
  • Gives clear error messages and recovers to find further errors.
  • Is portable and easy to maintain.

Advantages: fast execution of the compiled program; translation done once and reused; whole-program optimization; source code need not be distributed. Limitations: compilation delay after every change; target code is machine dependent; extra memory for object code; debugging is less direct.

4. Intermediate code generation

Produces a machine-independent representation that is easy to generate and easy to translate. A common form is three-address code , in which each instruction has at most one operator on the right side. Input: annotated tree. Output: intermediate code.

5. Code optimization (machine independent)

Transforms intermediate code so that it runs faster or uses less space, without changing its meaning. Examples: constant folding, common sub-expression elimination, copy propagation, dead code elimination. Input: intermediate code. Output: improved intermediate code. This phase is optional.

6. Code generation

Maps intermediate code to the target language. It performs instruction selection, register allocation and instruction ordering. Input: optimized intermediate code. Output: target assembly or machine code. Machine-dependent optimization may follow.

Symbol table manager

The symbol table is a data structure containing a record for each identifier, with fields such as name, type, scope, memory location and, for procedures, number and types of parameters and return type. It must support fast insertion and lookup.

Phase Role of symbol table

Lexical analysis Enters identifier names when first seen (in many designs).

Syntax analysis Helps record declarations and scope structure.

Semantic analysis Stores and checks type and scope information.

Intermediate code generation Uses types to choose operations and conversions; records temporaries.

Code optimization Uses information about variables, such as scope and use.

Code generation Uses and assigns storage addresses and registers.

Error handler

Each phase can detect errors. The error handler reports the error with its location and recovers so that compilation can continue and find more errors. Common strategies (detailed in Unit 4) are panic mode, phrase level, error productions and global correction.

Pseudocode: working of the compiler

COMPILE(source): table <- empty symbol table tokens <- LEXICAL_ANALYSIS(source, table) tree <- PARSE(tokens) tree <- SEMANTIC_CHECK(tree, table) if errors were reported: stop, no target code ir <- GENERATE_IR(tree, table) ir <- OPTIMIZE(ir) return GENERATE_CODE(ir, table)

Solved example 1: a = b + c * 60 (a, b, c are float) [W25, 7 marks]

Step 1: Lexical analysis

Lexeme a = b + c * 60

Token <=> <+> <*>

Entry Name Type

1 a float

2 b float

Entry Name Type

3 c float

Steps 2 and 3: Syntax and semantic analysis. * has higher precedence than +. Since c is float and 60 is integer, inttofloat is inserted.

id

id

id3 60

+

=

id

id

id

60

inttofloat

+

=

(a) Syntax tree (b) Tree after semantic analysis Fig. 3: Syntax analysis and semantic analysis output

Step 4: Intermediate code

t1 = inttofloat(60) t2 = id3 * t t3 = id2 + t id1 = t

Step 5: Code optimization. The conversion is done at compile time and the extra copy through t3 is removed.

t1 = id3 * 60. id1 = id2 + t

Step 6: Code generation (F means floating point, # means constant)

LDF R2, id MULF R2, R2, #60. LDF R1, id ADDF R1, R1, R STF id1, R

Solved example 2 (practice): x = (a + b) * (a + b), all integers

Phase Output

Lexical id1 = ( id2 + id3 ) * ( id2 + id3 ), where x, a, b are entries 1, 2, 3

Syntax Root =, left child id1, right child *, whose two children are + (id2, id3)

Semantic All operands are int; no conversion needed

Intermediate code t1 = id2 + id3; t2 = id2 + id3; t3 = t1 * t2; id1 = t

Optimization t1 = id2 + id3; id1 = t1 * t1 (common sub-expression removed)

Code generation LD R1, id2; LD R2, id3; ADD R1, R1, R2; MUL R1, R1, R1; ST id1, R

Front end and back end

Point Front end Back end

Phases Lexical, syntax, semantic analysis, intermediate code generation

Code optimization and code generation

Depends on Source language Target machine

1.6 Interpreter

Definition: An interpreter is a language processor that directly executes the operations of the source program on the supplied input, usually one statement at a time, without producing a separate target program (Fig. 1b).

INTERPRET(program): while statements remain: s <- next statement analyze s if s has an error: report it and stop execute s

Example: in a statement-by-statement interpreter, if line 3 of a script divides by zero, lines 1 and 2 have already executed and execution stops at line 3. Examples of interpreted environments: Unix shell, classic BASIC. CPython first compiles to bytecode and then interprets the bytecode.

Applications: scripting, command shells, teaching, rapid testing. Advantages: easy debugging, no separate target file, portable where an interpreter exists. Limitations: slower execution, statements in loops are analyzed repeatedly (in a pure interpreter), interpreter must be present at run time.

Hybrid compiler

Java combines both methods. javac compiles source into bytecode ; the Java Virtual Machine interprets it. A just-in-time (JIT) compiler translates frequently used bytecode into machine code during execution.

Source (.java) --javac--> Bytecode (.class) --JVM (interpret / JIT) + input--> Output

1.7 Assembler

Definition: An assembler translates an assembly language program into relocatable machine code. It replaces mnemonic opcodes with operation codes and symbolic names with addresses.

Types: a one-pass assembler reads the source once and later fills in forward references (backpatching). A two-pass assembler collects symbols in pass 1 and generates code in pass 2.

PASS 1: LC <- start address for each line: if line has a label: add (label, LC) to SYMTAB LC <- LC + size of the instruction or data PASS 2: for each line: find opcode in the opcode table find operand address in SYMTAB write object code (report undefined symbols)

Solved numerical: two-pass assembly

Assume a hypothetical machine: start address 100, each instruction and data word takes 4 bytes; opcodes LOAD=01, ADD=02, STORE=03, JNZ=04, HLT=05.

Address (LC) Source statement Pass 2 output (opcode, address)

100 LOOP: LOAD R1, X 01, R1, 120

104 ADD R1, Y 02, R1, 124

108 STORE R1, Z 03, R1, 128

112 JNZ LOOP 04, 100

116 HLT 05

120 X: DW 5 5

124 Y: DW 7 7

128 Z: RESW 1 (space reserved)

Symbol table after pass 1: LOOP = 100, X = 120, Y = 124, Z = 128. X, Y and Z are forward references , which is why a second pass is convenient.

Advantages: readable compared with binary, precise hardware control. Limitations: machine dependent, long programs, less productive than high-level languages.

1.8 Difference between Compiler and Interpreter

Basis Compiler Interpreter

Translation Whole program is translated Executes statement by statement

Target program Generated No separate target program

Execution speed Faster Slower

Analysis time Done before execution Done during execution

Error reporting Errors reported after analyzing the program Stops at the point where an error is met

Debugging Comparatively harder Easier

Memory Needs space for object code; compiler not needed at run time

No object code; interpreter needed at run time

Repeated runs No retranslation if source is unchanged Translation work repeated on each run

Examples C, C++ compilers Shell, BASIC interpreters

Compiler vs Assembler

Basis Compiler Assembler

Input High-level language Assembly language

Output Assembly or machine code Relocatable machine code

Mapping One statement may give many instructions Mostly one instruction to one machine instruction

Complexity High; many phases Lower; usually one or two passes

1.9 Compilation of Source Code into Target Language

A compiler alone may not produce an executable program. The complete language processing system performs the following steps.

(b) Assembler

Translates assembly code to relocatable machine code, usually in two passes (Section 1.7).

(c) Linker (link editor)

Combines separately compiled object modules and library routines into one executable. Its tasks are symbol resolution (matching an external reference such as a call to printf with its definition) and relocation (adjusting addresses). Linking is static (library code copied into the executable) or dynamic (library linked at load or run time).

(d) Loader

An operating-system program that brings the executable into main memory and starts it. Basic functions: allocation of memory, linking , relocation and loading. Types include compile-and-go, absolute, relocating and dynamic loaders. (In a linking loader, linking is also done by the loader.)

LOAD(executable): read header to find the required size base <- allocate memory copy code and data to memory for each relocatable address A: A <- A + base (if needed) set up stack; jump to entry point

Formula and solved numerical: relocation

Absolute address = Load (base) address + Relative address

Module A (300 bytes) and module B (200 bytes) are placed one after another from address 1000. A symbol is at relative address 40 in B. Find its absolute address.

  1. Base of A = 1000.
  2. Base of B = 1000 + 300 = 1300.
  3. Address of symbol = 1300 + 40 = 1340.
  4. Total occupied range = 1000 to 1499 (500 bytes).

Cousin Input Output Main job

Preprocessor Source program Modified source Macros, file inclusion

Assembler Assembly code Object code Mnemonics to machine code

Linker Object files, libraries Executable Resolve references, relocate

Loader Executable Program in memory Allocate, load, start

Linker Loader

Creates the executable Loads the executable into memory

Resolves external symbols Allocates memory and performs load-time relocation

Works after assembly Works at the time of execution

1.11 Types of Compiler

One-pass and two-pass (multi-pass) compilers

A one-pass compiler processes the source once, performing all required phases together. A two-pass compiler divides the work: pass 1 (analysis/front end) produces intermediate code and the symbol table; pass 2 (synthesis/back end) produces target code. A multi-pass compiler makes several passes.

One pass: Source -> [analysis + code generation] -> Target Two pass: Source -> [Pass 1: front end] -> IR -> [Pass 2: back end] -> Target

Basis One-pass Two-pass / multi-pass

Reading of program Once Two or more times (source or IR)

Compilation speed Usually faster Usually slower

Basis One-pass Two-pass / multi-pass

Intermediate memory Less storage for program representations

Stores intermediate representation

Optimization Limited Better

Forward references Need declarations first or backpatching

Handled easily

Portability Lower Higher (replace back end)

Example Classic Pascal compilers Modern optimizing C/C++ compilers

Cross compiler

A cross compiler runs on one machine (the host) and produces code for a different machine (the target). Example: using an ARM GCC toolchain on an x86 PC to build a program for an ARM board.

Source S Target T

Runs on H

Native compiler: H = T Cross compiler: H ≠ T

Fig. 5: T-diagram of a compiler (source S, target T, running on host H)

Uses: embedded systems, microcontrollers, mobile devices, bringing up a new machine. Advantages: target need not have enough resources to run a compiler. Limitation: testing needs the target device or an emulator.

Other types

Type Description Example / use

Native compiler Generates code for the machine it runs on GCC on a PC building for that PC

Source-to-source (transpiler) Translates one high-level language to another TypeScript to JavaScript

Just-in-time compiler Compiles during program execution JVM HotSpot

Ahead-of-time compiler Compiles before execution C compiler

Optimizing compiler Spends effort to improve speed or size GCC with -O

Incremental compiler Recompiles only changed parts IDE build systems

Load-and-go compiler Puts code in memory and runs it immediately Early student compilers

Bootstrapping (self-hosting) compiler

Written in the language it compiles C compiler written in C

Decompiler Reverse: low-level to higher-level form Program analysis

Q6. What is a compiler? What are the front end and back end of a compiler? [W22 Q1(a)]

A compiler translates a program in a source language into an equivalent program in a target language and reports errors. Front end: lexical, syntax, semantic analysis and intermediate code generation; depends mainly on the source language. Back end: code optimization and code generation; depends mainly on the target machine.

Q7. State the applications of language processors. [S24 Q1(a)]

  1. Translating high-level languages into machine code (compilers, assemblers).
  2. Executing scripts and commands (interpreters).
  3. Optimizing programs for parallel processors and memory hierarchies.
  4. Designing and evaluating new computer architectures.
  5. Program translation: binary translation, database queries, hardware synthesis.
  6. Software productivity tools: type checking, bounds checking, error detection.

Q8. Enlist types of compiler. Explain any two in brief. [S24 Q2(a)]

Types: one-pass, multi-pass, native, cross, source-to-source, just-in-time, optimizing, incremental. One-pass compiler: reads the source once and generates code in the same pass; fast, but allows limited optimization. Cross compiler: runs on one machine and generates code for another; used for embedded systems.

4-mark answer

Q9. Discuss one-pass and two-pass compilers. [W25 Q1(b)]

A pass is one complete reading of the source program or its intermediate form. One-pass compiler: all required work is done in a single reading. It is fast and simple in input/output, but has limited optimization and needs special handling of forward references. Example: classic Pascal compilers. Two-pass compiler: pass 1 performs analysis and creates intermediate code and symbol table; pass 2 optimizes and generates target code. It handles forward references, optimizes better and is portable, but usually takes more time and memory.

One pass: Source -> Compiler -> Target Two pass: Source -> Front end -> IR -> Back end -> Target

Basis One-pass Two-pass

Speed Faster Slower

Optimization Limited Better

Portability Low High

7-mark answers

Q10. Explain the phases of a compiler with a suitable example. [S23, W23, W24 Q1(c); variants W22, W25, S25 Q1(c)]

Definition: A compiler translates a source program into an equivalent target program. It works in six phases; each takes one representation as input and gives another as output. Draw Fig. 2.

Phase Input Action Output for a = b + c * 60

Lexical analysis Characters Forms tokens; removes blanks and comments

id1 = id2 + id3 * 60

Syntax analysis Tokens Checks grammar; builds tree =(id1, +(id2, *(id3, 60)))

Phase Input Action Output for a = b + c * 60

Semantic analysis Syntax tree Type checking and coercion 60 becomes inttofloat(60)

Intermediate code Checked tree Generates three-address code t1=inttofloat(60); t2=id3*t1; t3=id2+t2; id1=t

Optimization Intermediate code

Removes unnecessary operations

t1=id3*60.0; id1=id2+t

Code generation Optimized code Selects instructions and registers

LDF R2,id3; MULF R2,R2,#60.0; LDF R1,id2; ADDF R1,R1,R2; STF id1,R

Symbol table manager: stores name, type, scope and address of identifiers (here a, b, c: float) and serves all phases. Error handler: detects, reports and recovers from errors in each phase.

Variant guide: W22 (input, output, action): write the table. W25 (output of all phases): also draw both trees of Fig. 3. S25: add Q12.

Q11. Explain the language dependent and machine independent phases of a compiler. Also list major functions done by a compiler. [S22 Q1(c)]

Compiler phases are grouped into a front end and a back end. Language-dependent phases (front end): they depend on the source language and are largely independent of the target machine.

  • Lexical analysis: forms tokens.
  • Syntax analysis: checks grammatical structure.
  • Semantic analysis: checks types and declarations.
  • Intermediate code generation: produces machine-independent code.

Machine-independent part: the front end and intermediate code optimization do not depend on the target machine. The optimizer applies constant folding, common sub-expression and dead code elimination. In contrast, code generation and machine-dependent optimization depend on the machine.

Source -> [Lexical, Syntax, Semantic, ICG] -> IR -> [Optimizer] -> [Code generator] -> Target language dependent machine independent machine dependent

Major functions of a compiler:

  1. Recognize tokens.
  2. Check syntax.
  3. Check semantics and types.
  4. Maintain the symbol table.
  5. Detect, report and recover from errors.
  6. Generate intermediate code.
  7. Optimize code.
  8. Allocate registers and storage and generate target code.

Advantage of grouping: a new back end retargets the compiler; different front ends can share one back end.

Q12. Explain phases of compiler in context of front end and back end with example. Give the significance of both. [S25 Q1(c)]

Draw Fig. 2 and mark the front end and back end. Example: a = b + c * 60 (float variables).

Front end (analysis):

  1. Lexical analysis: id1 = id2 + id3 * 60
  2. Syntax analysis: tree with * below +, below =
  3. Semantic analysis: inttofloat(60)
  4. Intermediate code: t1=inttofloat(60); t2=id3*t1; t3=id2+t2; id1=t

Practice questions (not from these papers)

P1 (4 marks). Explain the science of building a compiler. [Practice]

Compiler design models translation problems mathematically and solves them with algorithms. Finite automata and regular expressions model tokens; context-free grammars model syntax; trees model structure; graphs support data-flow analysis and register allocation. An optimization must be correct, improve performance, keep compile time reasonable and need manageable engineering effort. Optimal code cannot be guaranteed, so heuristics are used.

P2 (4 marks). Explain interpreter with advantages and limitations. [Practice]

An interpreter directly executes the source program on its input without producing a separate target program. It analyzes a statement, executes it and moves to the next. Draw Fig. 1(b). Advantages: easy debugging, quick testing, portability. Limitations: slower execution, repeated analysis, interpreter needed at run time. Example: Unix shell.

Part C: Important Formulas and Definitions

Unit 1 is theoretical. The relations below are the only calculations used in these notes.

Relation Meaning

Absolute address = Base address + Relative address Relocation

Base of next module = Base of current module + its length Modules placed one after another

Next LC = LC + instruction or data size Assembler pass 1

Separate compilers = m × n; shared IR components = m + n m languages, n target machines

Term Definition

Language processor Software that translates or executes programs

Compiler Translates source program to equivalent target program and reports errors

Interpreter Directly executes source program

Assembler Assembly language to machine code

Preprocessor Prepares source before compilation

Linker Combines object files and resolves references

Loader Places program in memory for execution

Phase Logical unit converting one representation to another

Pass One complete reading of source or intermediate form

Token Token name with optional attribute value

Lexeme Character sequence matching a token pattern

Symbol table Record of identifiers and attributes

Intermediate code Representation between source and target

Coercion Automatic type conversion

Front end Source-dependent analysis part

Back end Target-dependent synthesis part

Cross compiler Runs on host, generates code for a different target

Bootstrapping Building a compiler using its own source language

Part D: Diagram Revision Sheet

Figure Draw it for Must label

Fig. 1 Compiler, interpreter Source, target, input, output, errors

Fig. 2 Phases, front/back end, symbol table Six phases, intermediate outputs, two side modules

Fig. 3 Output of all phases Operator precedence, inttofloat

Fig. 4 Cousins, compilation process Four programs and the file between each pair

Fig. 5 Cross compiler Source, target, host; H ≠ T

Quick-draw chains

Phases : Lex -> Syn -> Sem -> ICG -> Opt -> CodeGen System : Preprocessor -> Compiler -> Assembler -> Linker -> Loader Files : .c -> .i -> .s -> .o -> executable

Redraw Fig. 2 and Fig. 4 from memory first; they carry the most marks. The full figures are in Sections 1.3, 1.4, 1.9 and 1.11.

Memory aid for phases: L et S mart S tudents I mprove O wn C ode (Lexical, Syntax, Semantic, Intermediate, Optimization, Code generation).

Lexical analyzer Parser (syntax analyzer)

Detects malformed tokens Detects grammatical errors

Lexical errors and recovery

A lexical error occurs when no token pattern matches a prefix of the remaining input, for example an illegal character such as @ in C code, or an unterminated string or comment. A misspelling such as fi for if is not detected here, because fi is a valid identifier.

  • Panic mode: delete successive characters until a well-formed token can be found.
  • Delete one extraneous character.
  • Insert a missing character.
  • Replace one character by another.
  • Transpose two adjacent characters.

2.2 Token, Lexeme and Pattern

  • Token: a pair of token name and optional attribute value. The token name is an abstract symbol for a kind of lexical unit (id, number, if, relop).
  • Pattern: the rule describing the form that lexemes of a token may take.
  • Lexeme: the sequence of characters in the source program that matches the pattern of a token.

Token Sample lexemes Informal pattern

if if characters i, f

relop <, <=, =, <>, >, >= a comparison operator

id total, x2 letter followed by letters or digits

number 10, 3.14, 6.02E23 numeric constant

literal "hello" characters between double quotes

punctuation ( ) ; , the symbol itself

Attributes: when several lexemes match one token, the attribute identifies which one. For E = M * C :

2.3 Specification of Tokens

Alphabet, string and language

  • Alphabet (Σ): a finite set of symbols, e.g. {0,1}.
  • String: a finite sequence of symbols from Σ. |s| is its length; ε is the empty string.
  • Language: any set of strings over Σ.
  • Prefix / suffix / substring: obtained by removing trailing symbols / leading symbols / both. For banana: ban is a prefix, ana a suffix, nan a substring.
  • Subsequence: obtained by deleting zero or more symbols, not necessarily adjacent, e.g. baan.
  • Concatenation: xy; εx = xε = x.

Operations on languages

Operation Definition For L = {a, b}, D = {0, 1}

Union L ∪ D strings in L or D {a, b, 0, 1}

Concatenation LD st with s in L, t in D {a0, a1, b0, b1}

Kleene closure L* zero or more concatenations: ∪ Li, i ≥ 0 {ε, a, b, aa, ab, ...}

Positive closure L+ one or more: ∪ Li, i ≥ 1 {a, b, aa, ab, ...}

Regular expressions: recursive rules

  1. ε is a regular expression and L(ε) = {ε}.
  1. Each symbol a in Σ is a regular expression and L(a) = {a}.
  2. If r and s are regular expressions, then (r)|(s), (r)(s), (r)* and (r) are regular expressions denoting L(r) ∪ L(s), L(r)L(s), (L(r))* and L(r). Precedence (highest first): *, concatenation, |. All are left associative. A language denoted by a regular expression is a regular set.

Law Description

r | s = s | r Union is commutative

r | (s | t) = (r | s) | t Union is associative

r(st) = (rs)t Concatenation is associative

r(s | t) = rs | rt; (s | t)r = sr | tr Concatenation distributes over union

εr = rε = r ε is identity for concatenation

r* = (r | ε)* ε is guaranteed in a closure

r** = r* * is idempotent

Regular definitions

A regular definition gives names to regular expressions: d1 → r1, d2 → r2, ..., where each ri uses only symbols of Σ and earlier names.

letter -> A | B | ... | Z | a | b | ... | z | _ digit -> 0 | 1 | ... | 9 id -> letter (letter | digit)*

digits -> digit digit* fraction ->. digits | ε exponent -> E (+ | - | ε) digits | ε number -> digits fraction exponent

Shorthand Meaning Example

r+ one or more digit+

r? zero or one (r | ε) (+|-)?

[abc] a | b | c [+-]

[a-z] character range [A-Za-z]

Limitation: regular expressions cannot describe nested or balanced structures such as matching parentheses; context-free grammars are needed.

How to write a regular expression

  1. Write a few strings that belong to the language and a few that do not.
  2. Fix the compulsory parts.
  3. Fill the free parts with closures such as (a|b)*.
  4. Check ε and the shortest strings. The solved regular-expression questions are Q8 to Q12 in Part B.

2.4 Recognition of Tokens

Specification says what tokens look like; recognition finds them in the input. Consider:

stmt -> if expr then stmt | if expr then stmt else stmt | ε expr -> term relop term | term term -> id | number ws -> (blank | tab | newline)+ (recognized and discarded)

Lexeme Token Attribute

any ws - -