Syntax and Type Analysis

Similar documents
2. Syntax and Type Analysis

Compiler phases. Non-tokens

Introduction to Lexical Analysis

Lexical Analysis. Chapter 2

Lexical Analysis. Introduction

Lexical Analysis - 2

Lexical Analysis. Lecture 2-4

Implementation of Lexical Analysis

Implementation of Lexical Analysis

The Front End. The purpose of the front end is to deal with the input language. Perform a membership test: code source language?

Announcements! P1 part 1 due next Tuesday P1 part 2 due next Friday

2010: Compilers REVIEW: REGULAR EXPRESSIONS HOW TO USE REGULAR EXPRESSIONS

Lexical Analysis. Lexical analysis is the first phase of compilation: The file is converted from ASCII to tokens. It must be fast!

Compiler Construction

Outline. 1 Scanning Tokens. 2 Regular Expresssions. 3 Finite State Automata

Lexical Analysis 1 / 52

Lexical Analysis. Lecture 3-4

CSEP 501 Compilers. Languages, Automata, Regular Expressions & Scanners Hal Perkins Winter /8/ Hal Perkins & UW CSE B-1

CSc 453 Lexical Analysis (Scanning)

Chapter 3 Lexical Analysis

EDAN65: Compilers, Lecture 02 Regular expressions and scanning. Görel Hedin Revised:

Regular Expressions. Agenda for Today. Grammar for a Tiny Language. Programming Language Specifications

Compiler course. Chapter 3 Lexical Analysis

UNIT -2 LEXICAL ANALYSIS

CS412/413. Introduction to Compilers Tim Teitelbaum. Lecture 2: Lexical Analysis 23 Jan 08

Lexical Analysis. Dragon Book Chapter 3 Formal Languages Regular Expressions Finite Automata Theory Lexical Analysis using Automata

Compiler Construction

Lexical Analysis. Chapter 1, Section Chapter 3, Section 3.1, 3.3, 3.4, 3.5 JFlex Manual

Lexical Analysis. Implementation: Finite Automata

Implementation of Lexical Analysis

5. Garbage Collection

Figure 2.1: Role of Lexical Analyzer

CSE 413 Programming Languages & Implementation. Hal Perkins Autumn 2012 Grammars, Scanners & Regular Expressions

David Griol Barres Computer Science Department Carlos III University of Madrid Leganés (Spain)

Formal Languages and Compilers Lecture IV: Regular Languages and Finite. Finite Automata

Compiler Construction I

Outline CS4120/4121. Compilation in a Nutshell 1. Administration. Introduction to Compilers Andrew Myers. HW1 out later today due next Monday.

Computer Science Department Carlos III University of Madrid Leganés (Spain) David Griol Barres

CSE302: Compiler Design

CSE 413 Programming Languages & Implementation. Hal Perkins Winter 2019 Grammars, Scanners & Regular Expressions

Administrivia. Lexical Analysis. Lecture 2-4. Outline. The Structure of a Compiler. Informal sketch of lexical analysis. Issues in lexical analysis

Compiler Construction I

CS321 Languages and Compiler Design I. Winter 2012 Lecture 4

Compiler Construction

Implementation of Lexical Analysis

Formal Languages and Compilers Lecture VI: Lexical Analysis

Concepts. Lexical scanning Regular expressions DFAs and FSAs Lex. Lexical analysis in perspective

Lexical Analysis - An Introduction. Lecture 4 Spring 2005 Department of Computer Science University of Alabama Joel Jones

CS 310: State Transition Diagrams

Chapter 4. Lexical analysis. Concepts. Lexical scanning Regular expressions DFAs and FSAs Lex. Lexical analysis in perspective

Lexical Analysis. Lecture 3. January 10, 2018

Finite automata. We have looked at using Lex to build a scanner on the basis of regular expressions.

Writing a Lexical Analyzer in Haskell (part II)

Introduction to Lexical Analysis

Compiler Construction


Lecture 4: Syntax Specification

CS Lecture 2. The Front End. Lecture 2 Lexical Analysis

Zhizheng Zhang. Southeast University

CMSC 350: COMPILER DESIGN

MIT Specifying Languages with Regular Expressions and Context-Free Grammars

Concepts Introduced in Chapter 3. Lexical Analysis. Lexical Analysis Terms. Attributes for Tokens

CSE Lecture 4: Scanning and parsing 28 Jan Nate Nystrom University of Texas at Arlington

Theoretical Part. Chapter one:- - What are the Phases of compiler? Answer:

Formal Languages and Grammars. Chapter 2: Sections 2.1 and 2.2

CS 403: Scanning and Parsing

Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan

Lecture 3: Lexical Analysis

CS308 Compiler Principles Lexical Analyzer Li Jiang

CS 314 Principles of Programming Languages. Lecture 3

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

[Lexical Analysis] Bikash Balami

MIT Specifying Languages with Regular Expressions and Context-Free Grammars. Martin Rinard Massachusetts Institute of Technology

CS415 Compilers. Lexical Analysis

Languages, Automata, Regular Expressions & Scanners. Winter /8/ Hal Perkins & UW CSE B-1

Lexical Analyzer Scanner

THE COMPILATION PROCESS EXAMPLE OF TOKENS AND ATTRIBUTES

1. INTRODUCTION TO LANGUAGE PROCESSING The Language Processing System can be represented as shown figure below.

Lexical Analyzer Scanner

Regular Languages. MACM 300 Formal Languages and Automata. Formal Languages: Recap. Regular Languages

2. Lexical Analysis! Prof. O. Nierstrasz!

CPSC 434 Lecture 3, Page 1

Lexical Analysis. COMP 524, Spring 2014 Bryan Ward

Part 5 Program Analysis Principles and Techniques

CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 5

Compiler Construction LECTURE # 3

Non-deterministic Finite Automata (NFA)

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design

Lexical Analysis. Finite Automata

Interpreter. Scanner. Parser. Tree Walker. read. request token. send token. send AST I/O. Console

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

Garbage Collection. Lecture Compilers SS Dr.-Ing. Ina Schaefer. Software Technology Group TU Kaiserslautern. Ina Schaefer Garbage Collection 1

Cunning Plan. Informal Sketch of Lexical Analysis. Issues in Lexical Analysis. Specifying Lexers

PRINCIPLES OF COMPILER DESIGN UNIT II LEXICAL ANALYSIS 2.1 Lexical Analysis - The Role of the Lexical Analyzer

COMPILER DESIGN UNIT I LEXICAL ANALYSIS. Translator: It is a program that translates one language to another Language.

Compiler Construction D7011E

CSCI312 Principles of Programming Languages!

Dr. D.M. Akbar Hussain

Scanners. Xiaokang Qiu Purdue University. August 24, ECE 468 Adapted from Kulkarni 2012

COP4020 Programming Languages. Syntax Prof. Robert van Engelen

Transcription:

Syntax and Type Analysis Lecture Compilers Summer Term 2011 Prof. Dr. Arnd Poetzsch-Heffter Software Technology Group TU Kaiserslautern Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 1 Content of Lecture 1. Introduction: Overview and Motivation 2. Syntax- and Type Analysis 2.1 2.2 Context-Free Syntax Analysis 2.3 Context-Dependent Syntax Analysis 3. Translation to Target Language 3.1 Translation of Imperative Language Constructs 3.2 Translation of Object-Oriented Language Constructs 4. Selected Aspects of Compilers 4.1 Intermediate Languages 4.2 Optimization 4.3 Data Flow Analysis 4.4 Register Allocation 4.5 Code Generation 5. Garbage Collection 6. XML Processing (DOM, SAX, XSLT) Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 2

2. Syntax and Type Analysis Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 3 Educational Objectives Tasks of different syntax analysis phases Interaction of syntax analysis phases Specification techniques for syntax analysis Generation techniques Usage of tools Lexical analysis Context-free analysis (parsing) Context-sensitive analysis Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 4

Syntax Analysis Introduction to Syntax and Type Analysis Tasks of Syntax Analysis Check if input is syntactically correct Dependent on result: Error message Generation of appropriate data structure for subsequent processing Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 5 Introduction to Syntax and Type Analysis Syntax and Type Analysis Phases Source Code Lexical analysis: Character stream token stream (or symbol stream) Context-free analysis: Token stream syntax tree Context-sensitive analysis: Syntax tree syntax tree with cross references Syntax and Type Analysis Character Stream Scanner Token Stream Parser Syntax Tree Name and Type Analysis Attributed Syntax Tree Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 6

Introduction to Syntax and Type Analysis Reasons for Separation of Phases Lexical and context-free analysis Reduced load for context-free analysis, e.g., whitespaces are not required for context-free analysis Context-free and context-sensitive analysis Context-sensitive analysis uses tree structure instead of token stream Advantages for construction of target data structure For both cases Increased efficiency Natural process (cmp. natural language) More appropriate tool support Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 7 2.1. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 8

Tasks Break input character stream into a token stream wrt. language definition Classify tokens into token classes Representation of tokens Hashing of identifiers Conversion of constants Elimination of whitespaces (spaces, comments...) external constructs (compiler directives...) Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 9 (2) Terminology Token/symbol: a word over an alphabet of characters (often with additional information, e.g. token class, encoding, position..) Token class: a set of tokens (identifier, constants,...); correspond to terminal symbols of a context-free grammar Remark: the terms token and symbol refer to the same concept. The term token is in general used when talking about parsing technology, whereas the term symbol is used when talking about formal languages. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 10

: Example Input Line 23: if ( A <= 3.14 ) B = B Token Class String Token Information Col:Row IF if 23:3 OPAR ( 23:5 ID A 72 (Hash) 23:7 RELOP <= 4 (Encoding) 23:9 FLOATCONST 3.14 3,14 (Constant Value) 23:12 CPAR ) 23:16 ID B 84 (Hash) 23:20... Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 11 Specification Specification of Scanners The specification of the lexical analysis is a part of the language specification. The two parts of lexical analysis specification: Scanning algorithm (often only implicit) Specification of tokens and token classes Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 12

Examples: Scanning Specification of Scanners 1. Statement in C B = B --- A; Problem: Separation ( - - and - are tokens) Solution: Longest token is chosen, i.e, B = B -- - A; 2. Java Fragment class public { public m() {...} } Problem: Ambiguity (keyword, identifier) Solution: Precedence rules Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 13 Specification of Scanners Standard Scan Algorithm (Concept) Scanning is often implemented as a procedure: Procedure returns next token State is remainder of input In error cases, returns the UNDEF token and updates the input Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 14

Specification of Scanners Standard Scan Algorithm (Pseudo Code) CharStream inputrest := input; Token nexttoken() { Token curtoken := longesttokenprefix(inputrest); inputrest:= cut(curtoken, inputrest); return curtoken; } where cut is defined as if curtoken UNDEF, curtoken is removed from inputrest else inputrest remains unchanged. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 15 Specification of Scanners Standard Scan Algorithm (2) Token longesttokenprefix(charstream ir) { require availablechar(ir) > 0 int curlength = 1; String curprefix := prefix(curlength,ir); Token longesttoken := UNDEF; } while( curlength <= availablechar(ir) && istokenprefix(curprefix) ) { if (istoken(curprefix) { longesttoken := curprefix; } curlength++; curprefix := prefix(curlength,ir); } return longesttoken; Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 16

Standard Scan Algorithm (3) Specification of Scanners Predicates to be defined: istokenprefix: String boolean istoken: String boolean Remarks: Standard scan algorithm is used in many modern languages, but not, e.g., in FORTRAN because blanks are not special, except in literal tokens, e.g. DO 7 I = 1.25 DO 7 I is an identifier. DO 7 I = 1,25 DO is a keyword. Error cases are not handled Complete realization of longesttokenprefix is discussed later. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 17 Specification of Scanners Specification of Token Classes Token classes are defined by regular expressions (REs). REs specify the set of strings, which belong to a certain token class. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 18

Regular Expressions Specification of Scanners Let Σ be an alphabet, i.e. an non-empty set of characters. Σ is the set of all words over Σ, ɛ is the empty word. Definition (Regular expressions, regular languages) ε is a RE and specifies the language L = {ɛ}. Each a Σ is a RE and specifies the language L = {a}. Let r and s be two RE specifying the languages R and S, resp. Then the following are RE and specify the language L: (r s) with L = R S (union) rs with L = {vw v R, w S} (concatenation) r with {v 1... v n v i R, 0 i n} (Kleene star) The language L Σ is called regular if there exists RE r defining L. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 19 Regular Expressions (2) Specification of Scanners Remarks: L = is not regular according to the definition, but is often considered regular. Other Operators, e.g. +,?,., [] can be defined using the basic operators, e.g. r + (r r ) r \ {ɛ} [abd] a B d [a g] a b c d e f g Caution: Regular expressions only define valid tokens and do not specify the program or translation units of a programming language. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 20

sequence of regular expressions and actions (input language of scanner generator) Scanner Generator scanner program (usually in a programming language) Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 21 Scanner Generator: JFlex Typical use of JFlex: java -jar JFlex.jar Example.jflex javac Yylex.java Actions are written in Java Examples : 1. Regular expression in JFlex [a-za-z_0-9] [a-za-z_0-9] * 2. JFlex input with abbreviations ZI = [0-9] BU = [a-za-z_] BUZI = [a-za-z_0-9] %% {BU}{BUZI}* { anaction(); } Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 22

A Complete JFlex Example enum Token { DO, DOUBLE, IDENT, FLOATCONST, STRING;} %% %line %column %debug %type Token // declare token type ZI = [0-9] BU = [a-za-z_] BUZI = [a-za-z_0-9] ZE = [a-za-z_0-9?\]\[\. \t...] WhiteSpace = [ \t\n] %% {WhiteSpace} { } "double" { return Token.DOUBLE; } "do" { return Token.DO; } {BU}{BUZI}* { return Token.IDENT; } {ZI}+\.{ZI}+ { return Token.FLOATCONST; } \"({ZE} \\\")*\" { return Token.STRING; } <<EOF>> { System.out.println("FINISHED"); return null; } Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 23 Scanner Generators Scanner generation uses the equivalence between Regular expressions Non-deterministic finite automata (NFA) Deterministic finite automata (DFA) Construction methods is based in two steps: Regular expressions NFA NFA DFA Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 24

Definition of NFA Definition (Non-deterministic Finite Automaton) A non-deterministic finite automaton is defined as a 5-tuple where Σ is the input alphabet Q is the set of states q 0 Q is the initial state F Q is the set of final states M = (Σ, Q,, q 0, F) Q Σ {ɛ} Q is the transition relation. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 25 1. Schritt: Reguläre Implementation of Ausdrücke Scanners NEA Regular Expressions NFA Übersetzungsschema: Prinzip: Konstruiere für jeden regulären Teilausdruck NEA mit genau einem Start- und Endzustand der die gleiche Sprache akzeptiert. Principle: For each regular sub-expression, construct NFA with one start and end state that accepts the same language. s 0 a s a 0 f 0 (r s) s 1 R f 1 s 0 f 0 s 2 S f 2 Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 26

a a Regular Expressions a NFA (2) (r s) (r s) a (r s) der 0 die gleiche Sprache akzeptiert. s a 0 s 0 s a f 0 0 f 0 s 0 f 0 s 1 R f s 1 1 R f 1 s 0 f s 0 0 s 1 R f 1 s 0 s f 2 s S f 0 2 S 2 f s 2 2 f 2 (rs) (rs) (rs) s s 1 R f 1 s 1 2 S f 1 RR f 1 f 2 1 s 2 S f 2 r* r* r* s 0 s s 0 0 s 1 R f 1 s 1 s 1 R f 1 f f 0 f 0 25.04.2007 25.04.2007 25.04.2007 A. Poetzsch-Heffter, TU Kaiserslautern A. Poetzsch-Heffter, TU Kaiserslautern A. Poetzsch-Heffter, TU Kaiserslautern 43 43 43 Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 27 Example: Construction of NFA LZ, TAB Übersetzung am Beispiel von Folie 41: s 1 s d 2 s o 3 s 4 s 0 s d 5 s o 6 s u 7 s b 8 s l 9 s e 10 s 11 s 12 BU s 13 BUZI ZI ZI s ZI. 14 s 15 s ZI 16 s 17 s 18 s 19 ZE s 20 s 21 \ s 22 s 23 s 24 s 25 s 26 Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 28

ɛ-closure Function closure computes the ɛ-closure of a set of states s 1,..., s n. Definition (ɛ-closure) For an NFA M = (Σ, Q,, q 0, F) and a state q Q, the ɛ-closure of q is defined by ɛ-closure(q) = {p Q p reachable from q via ɛ-transitions} For S Q, the ɛ-closure of S is defined by ɛ-closure(s) = s S ɛ-closure(s) Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 29 Longest Token Prefix with NFA Token longesttokenprefix(char[] ir) { // length(ir) > 0 StateSet curstate := closure( {s0} ); int curlength := 0; int tokenlength := undef; } while (curlength <= length(ir) && isemptyset(curstate) ) { if (contains(curstate,finalstate)) { tokenlength := curlength; } curlength++; curstate := closure(successor(curstate,ir[curlength])); } return token(prefix(ir,tokenlength)); Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 30

Longest Token Prefix with NFA (2) Remark: Problem of ambiguity: If there are more than one token matching the longest input prefix, procedure token nondeterministically returns one of them. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 31 NFA DFA Principle: For each NFA, a DFA can be constructed that accepts the same language. (In general, this does not hold for NFA with output.) Properties of DFA: No ɛ-transitions Transitions are deterministic given the input char Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 32

NFA DFA (2) Definition (Deterministic Finite State Automaton) A deterministic finite automaton is defined as a 5-tuple where Σ is the input alphabet Q is the set of states q 0 Q is the initial state F Q is the set of final states M = (Σ, Q,, q 0, F) : Q Σ Q is the transition function. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 33 NFA DFA (3) Construction: (according to John Myhill) The States of the DFA are subsets of NFA states (powerset construction). Subsets of finite sets are also finite. The start state of the DFA is the ɛ-closure of the NFA start state The final states of the DFA are the sets of states that contain an NFA final state. The successor state of a state S in the DFA under input a is obtained by computing all successors p of q S under a in the NFA and adding the ɛ-closure of p Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 34

NFA DFA (4) If working with character classes (e.g. [a-f]), characters and character classes at outgoing transitions must be disjoint. Completion of automaton for error handling: Insert additional (final) state (nt) For each state, add a transition for each character for which no outgoing transition exists to the nontoken state. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 35 NFA DFA (5) Definition (DFA for NFA) Let M = (Σ, Q,, q 0, F) be a NFA. Then, the DFA M corresponding to the NFA M is defined as M = (Σ, Q,, q 0, F ) where the set of states is Q P(Q), power set of Q the initial state q 0 is the ɛ-closure of q 0 the final states are F = {S Q S F } (S, a) = ɛ-closure({p (q, a, p), q S}) for all a Σ. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 36

Example: DFA s 11,13 e Wg. Übersichtlichkeit Kanten zu ks nur angedeutet. s 10,13 Transitions to nt sketched. nt ks l LZ, TAB s 1 BUZI\{e} s 9,13 b BUZI BUZI\{l} s 8,13 u BUZI\{b} s 4,7,13 o LZ, TAB s 13 BUZI\{u} s3,6,13 BUZI BUZI\{o} BU\{d} d ZI ZI s 0,1,2,5,12,14,18 s 17 s 26 ZI. ZI s 16 s 15 ZE s 19,20,21,22,25 s ZE 19,20,22,25 \ ZE \ ZE s19,20,21,22,23,25 s 19,20,22,24,25,26 \ \ Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 37 Longest Token Prefix with DFA Token longesttokenprefix(char[] ir) { // length(ir) > 0 State curstate : = StartState; int curlength := 0; int tokenlength := undef; } while (curlength <= length(ir) && curstate = nt) if (curstate is FinalState) { tokenlength := curlength; } curlength++; curstate := successor(curstate,ir[curlength])); } return token(prefix(ir,tokenlength)); Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 38

Longest Token Prefix with DFA (2) Remarks: Computation of closure at construction time, not at runtime. (Principle: Do as much statically as you can) Problem of ambiguity still not solved. However, many scanner generators allows the user to control which token is returned. For example, JFlex returns the token of the first rule in the JFlex file that matches the longest input prefix. Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 39 Longest Token Prefix with DFA (3) Implementation Aspects: Constructed DFA can be minimized. Input buffering is important: often use of cyclic arrays (caution with maximal token length, e.g. in case of comments) Encode DFA in table Choose suitable partitioning of alphabet in order to reduce number of transitions (i.e. size of table) Interface with parser: usually parser asks proactively for next token Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 40

Recommended Reading Wilhelm, Maurer: Chap. 7, pp. 239-269 (More theoretical) Appel: Chap 2, pp. 16-37 (More practical) Additional Reading: Aho, Sethi, Ullman: Chap. 3 (very detailed) Prof. Dr. Arnd Poetzsch-Heffter Syntax and Type Analysis 41