Languages and Compilers (SProg og Oversættere) Lecture 15 (2) Bent Thomsen Department of Computer Science Aalborg University

Size: px
Start display at page:

Download "Languages and Compilers (SProg og Oversættere) Lecture 15 (2) Bent Thomsen Department of Computer Science Aalborg University"

Transcription

1 Languages and Compilers (SProg og Oversættere) Lecture 15 (2) Bent Thomsen Department of Computer Science Aalborg University With acknowledgement to Norm Hutchinson whose slides this lecture is based on. 1

2 Curricula (Studieordning) The purpose of the course is for the student to gain knowledge of important principles in programming languages and for the student to gain an understanding of techniques for describing and compiling programming languages. 2

3 What was this course about? Programming Language Design Concepts and Paradigms Ideas and philosophy Syntax and Semantics Compiler Construction Tools and Techniques Implementations The nuts and bolts 3

4 The principal paradigms Imperative Programming (C) Object-Oriented Programming (C++) Logic/Declarative Programming (Prolog) Functional/Applicative Programming (Lisp) New paradigms? Agent Oriented Programming Business Process Oriented (Web computing) Grid Oriented Aspect Oriented Programming 4

5 Criteria in a good language design Readability understand and comprehend a computation easily and accurately Write-ability express a computation clearly, correctly, concisely, and quickly Reliability assures a program will not behave in unexpected or disastrous ways Orthogonality A relatively small set of primitive constructs can be combined in a relatively small number of ways Every possible combination is legal Lack of orthogonality leads to exceptions to rules 5

6 Criteria (Continued) Uniformity similar features should look similar and behave similar Maintainability errors can be found and corrected and new features added easily Generality avoid special cases in the availability or use of constructs and by combining closely related constructs into a single more general one Extensibility provide some general mechanism for the user to add new constructs to a language Standardability allow programs to be transported from one computer to another without significant change in language structure Implementability ensure a translator or interpreter can be written 6

7 Tennent s Language Design principles 7

8 Important! Syntax is the visible part of a programming language Programming Language designers can waste a lot of time discussing unimportant details of syntax The language paradigm is the next most visible part The choice of paradigm, and therefore language, depends on how humans best think about the problem There are no right models of computations just different models of computations, some more suited for certain classes of problems than others The most invisible part is the language semantics Clear semantics usually leads to simple and efficient implementations 8

9 Levels of Programming Languages High-level program class Triangle {... float surface() return b*h/2; } Low-level program LOAD r1,b LOAD r2,h MUL r1,r2 DIV r1,#2 RET Executable Machine code

10 Terminology Q: Which programming languages play a role in this picture? input source program Translator output object program is expressed in the source language is expressed in the implementation language is expressed in the target language A: All of them! 10

11 Tombstone Diagrams What are they? diagrams consisting out of a set of puzzle pieces we can use to reason about language processors and programs different kinds of pieces combination rules (not all diagrams are well formed ) Program P implemented in L Translator implemented in L P L S -> T L Machine implemented in hardware M Language interpreter in L M L 11

12 Syntax Specification Syntax is specified using Context Free Grammars : A finite set of terminal symbols A finite set of non-terminal symbols A start symbol A finite set of production rules A CFG defines a set of strings This is called the language of the CFG. 12

13 Backus-Naur Form Usually CFG are written in BNF notation. A production rule in BNF notation is written as: N ::= α where N is a non terminal and α a sequence of terminals and non-terminals N ::= α β... is an abbreviation for several rules with N as left-hand side. 13

14 Concrete and Abstract Syntax The previous grammar specified the concrete syntax of Mini Mriangle. The concrete syntax is important for the programmer who needs to know exactly how to write syntactically wellformed programs. The abstract syntax omits irrelevant syntactic details and only specifies the essential structure of programs. Example: different concrete syntaxes for an assignment v := e (set! v e) e -> v v = e 14

15 Abstract Syntax Trees Abstract Syntax Tree for: d:=d+10*n AssignmentCmd BinaryExpression BinaryExpression VName VNameExp IntegerExp SimpleVName SimpleVName VNameExp SimpleVName Ident Ident Op Int-Lit Op Ident d d + 10 * n 15

16 Contextual Constraints Syntax rules alone are not enough to specify the format of well-formed programs. Example 1: let const m~2 in m + x Undefined! Scope Rules Example 2: let const m~2 ; var n:boolean in begin n := m<4; n := n+1 Type error! end Type Rules 16

17 Semantics Specification of semantics is concerned with specifying the meaning of well-formed programs. Terminology: Expressions are evaluated and yield values (and may or may not perform side effects) Commands are executed and perform side effects. Declarations are elaborated to produce bindings Side effects: change the values of variables perform input/output 17

18 Phases of a Compiler A compiler s phases are steps in transforming source code into object code. The different phases correspond roughly to the different parts of the language specification: Syntax analysis <-> Syntax Contextual analysis <-> Contextual constraints Code generation <-> Semantics 18

19 The Phases of a Compiler Source Program Syntax Analysis Error Reports Contextual Analysis Abstract Syntax Tree Error Reports Code Generation Decorated Abstract Syntax Tree Object Code 19

20 Compiler Passes A pass is a complete traversal of the source program, or a complete traversal of some internal representation of the source program. A pass can correspond to a phase but it does not have to! Sometimes a single pass corresponds to several phases that are interleaved in time. What and how many passes a compiler does over the source program is an important design decision. 20

21 Single Pass Compiler A single pass compiler makes a single pass over the source text, parsing, analyzing and generating code all at once. Dependency diagram of a typical Single Pass Compiler: Compiler Driver calls Syntactic Analyzer calls Contextual Analyzer calls Code Generator 21

22 Multi Pass Compiler A multi pass compiler makes several passes over the program. The output of a preceding phase is stored in a data structure and used by subsequent phases. Dependency diagram of a typical Multi Pass Compiler: calls Compiler Driver calls calls Syntactic Analyzer input output Contextual Analyzer input output Code Generator input output Source Text AST Decorated AST Object Code 22

23 Syntax Analysis Dataflow chart Source Program Stream of Characters Scanner Error Reports Stream of Tokens Parser Error Reports Abstract Syntax Tree 23

24 Regular Expressions RE are a notation for expressing a set of strings of terminal symbols. Different kinds of RE: ε The empty string t Generates only the string t X Y Generates any string xy such that x is generated by x and y is generated by Y X Y Generates any string which generated either by X or by Y X* The concatenation of zero or more strings generated by X (X) For grouping, 24

25 FA and the implementation of Scanners Regular expressions, (N)DFA-ε and NDFA and DFA s are all equivalent formalisms in terms of what languages can be defined with them. Regular expressions are a convenient notation for describing the tokens of programming languages. Regular expressions can be converted into FA s (the algorithm for conversion into NDFA-ε is straightforward) DFA s can be easily implemented as computer programs. 25

26 Parsing Parsing == Recognition + determining phrase structure (for example by generating AST) Different types of parsing strategies bottom up top down 26

27 Top-Down vs Bottom-Up parsing LL-Analyse (Top-Down) LR-Analyse (Bottom-Up) Reduction Derivation Look-Ahead Look-Ahead 27

28 Development of Recursive Descent Parser (1) Express grammar in EBNF (2) Grammar Transformations: Left factorization and Left recursion elimination (3) Create a parser class with private variable currenttoken methods to call the scanner: accept and acceptit (4) Implement private parsing methods: add private parsen method for each non terminal N public parse method that gets the first token form the scanner calls parses (S is the start symbol of the grammar) 28

29 LL(1) Grammars The presented algorithm to convert EBNF into a parser does not work for all possible grammars. It only works for so called LL(1) grammars. Basically, an LL(1) grammar is a grammar which can be parsed with a top-down parser with a lookahead (in the input stream of tokens) of one token. What grammars are LL(1)? How can we recognize that a grammar is (or is not) LL(1)? We can deduce the necessary conditions from the parser generation algorithm. We can use a formal definition 29

30 Converting EBNF into RD parsers The conversion of an EBNF specification into a Java implementation for a recursive descent parser is so mechanical that it can easily be automated! => JavaCC Java Compiler Compiler 30

31 JavaCC and JJTree 31

32 LR parsing The algorithm makes use of a stack. The first item on the stack is the initial state of a DFA A state of the automaton is a set of LR(0)/LR(1) items. The initial state is constructed from productions of the form S:= α [, $] (where S is the start symbol of the CFG) The stack contains (in alternating) order: A DFA state A terminal symbol or part (subtree) of the parse tree being constructed The items on the stack are related by transitions of the DFA There are two basic actions in the algorithm: shift: get next input token reduce: build a new node (remove children from stack) 32

33 Bottom Up Parsers: Overview of Algorithms LR(0) : The simplest algorithm, theoretically important but rather weak (not practical) SLR : An improved version of LR(0) more practical but still rather weak. LR(1) : LR(0) algorithm with extra lookahead token. very powerful algorithm. Not often used because of large memory requirements (very big parsing tables) LALR : Watered down version of LR(1) still very powerful, but has much smaller parsing tables most commonly used algorithm today 33

34 JavaCUP: A LALR generator for Java Definition of tokens Regular Expressions Grammar BNF-like Specification JFlex JavaCUP Java File: Scanner Class Recognizes Tokens Java File: Parser Class Uses Scanner to get Tokens Parses Stream of Tokens Syntactic Analyzer 34

35 Steps to build a compiler with SableCC 1. Create a SableCC specification file 2. Call SableCC 3. Create one or more working classes, possibly inherited from classes generated by SableCC 4. Create a Main class activating lexer, parser and working classes 5. Compile with Javac 35

36 Contextual Analysis Phase Purposes: Finish syntax analysis by deriving context-sensitive information Associate semantic routines with individual productions of the context free grammar or subtrees of the AST Start to interpret meaning of program based on its syntactic structure Prepare for the final stage of compilation: Code generation 36

37 Contextual Analysis -> Decorated AST Program LetCommand Annotations: result of identification :type result of type checking SequentialCommand SequentialDeclaration AssignCommand AssignCommand BinaryExpr :int VarDecl VarDecl SimpleT SimpleT Ident Ident Ident Ident SimpleV Char.Expr :char :char VNameExp :int :int SimpleV :int Ident Char.Lit Ident Ident Op Int.Expr :int Int.Lit n Integer c Char c & n n

38 Nested Block Structure Nested A language exhibits nested block structure if if blocks may be be nested one within another (typically with no no upper bound on on the the level of of nesting that is is allowed). There can be any number of scope levels (depending on the level of nesting of blocks): Typical scope rules: no identifier may be declared more than once within the same block (at the same level). for any applied occurrence there must be a corresponding declaration, either within the same block or in a block in which it is nested. 38

39 Type Checking For most statically typed programming languages, type checking is a bottom up algorithm over the AST: Types of expression AST leaves are known immediately: literals => obvious variables => from the ID table named constants => from the ID table Types of internal nodes are inferred from the type of the children and the type rule for that kind of expression 39

40 Contextual Analysis Identification and type checking are combined into a depth-first traversal of the abstract syntax tree. Program LetCommand SequentialDeclaration SequentialCommand AssignCommand AssignCommand BinaryExpression VarDec VarDec CharExpr VnameExpr IntExpr SimpleT SimpleT SimpleV SimpleV SimpleV Ident Ident Ident Ident Ident CharLit Ident Ident Op IntLit n Integer c Char c & n n

41 Visitor Solution Nodes accept visitors and call appropriate method of the visitor Visitors implement the operations and have one method for each type of node they visit VariableRefNode Node Accept(NodeVisitor v) {v->visitvariableref(this)} Accept( NodeVisitor v ) AssignmentNode Accept(NodeVisitor v) {v->visitassignment(this)} NodeVisitor VisitAssignment( AssignmentNode ) VisitVariableRef( VariableRefNode ) TypeCheckingVisitor VisitAssignment( AssignmentNode ) VisitVariableRef( VariableRefNode ) CodeGeneratingVisitor VisitAssignment( AssignmentNode ) VisitVariableRef( VariableRefNode ) 41

42 Runtime organization Data Representation: how to represent values of the source language on the target machine. Primitives, arrays, structures, unions, pointers Expression Evaluation: How to organize computing the values of expressions (taking care of intermediate results) Register vs. stack machine Storage Allocation: How to organize storage for variables (considering different lifetimes of global, local and heap variables) Activation records, static links Routines: How to implement procedures, functions (and how to pass their parameters and return values) Value vs. reference, closures, recursion Object Orientation: Runtime organization for OO languages Method tables 42

43 RECAP: TAM Frame Layout Summary LB ST arguments dynamic link static link return address local variables and intermediate results Arguments for current procedure they were put here by the caller. Link data Local data, grows and shrinks during execution. 43

44 Garbage Collection: Conclusions Relieves the burden of explicit memory allocation and deallocation. Software module coupling related to memory management issues is eliminated. An extremely dangerous class of bugs is eliminated. The compiler generates code for allocating objects The compiler must also generate code to support GC The GC must be able to recognize root pointers from the stack The GC must know about data-layout and objects descriptors 44

45 Code Generation Source Program let var n: n: integer; var c: c: char in in begin c := := & ; n := := n+1 end Source and target program must be semantically equivalent ~ Target program PUSH 2 LOADL STORE 1[SB] LOAD 0 LOADL 1 CALL add STORE 0[SB] POP 2 HALT Semantic specification of the source language is structured in terms of phrases in the SL: expressions, commands, etc. => Code generation follows the same inductive structure. 45

46 Specifying Code Generation with Code Templates The code generation functions for Mini Triangle Phrase Class Function Effect of the generated code Program run P Command Expression V-name V-name Declaration execute C evaluate E fetch V assign V elaborate D Run program P then halt. Starting and finishing with empty stack Execute Command C. May update variables but does not shrink or grow the stack! Evaluate E, net result is pushing the value of E on the stack. Push value of constant or variable on the stack. Pop value from stack and store in variable V Elaborate declaration, make space on the stack for constants and variables in the decl. 46

47 Code Generation with Code Templates While command execute [while E do C] = JUMP h g: execute [C] h: evaluate[e] JUMPIF(1) g C E 47

48 Developing a Code Generator Visitor execute [C1 ; C2] = execute[c1] execute[c2] public Object visitsequentialcommand( SequentialCommand com,object arg) { com.c1.visit(this,arg); com.c2.visit(this,arg); return null; } LetCommand, IfCommand, WhileCommand => later. - LetCommand is more complex: memory allocation and addresses - IfCommand and WhileCommand: complications with jumps 48

49 Code improvement (optimization) The code generated by our compiler is not efficient: It computes values at runtime that could be known at compile time It computes values more times than necessary We can do better! Constant folding Common sub-expression elimination Code motion Dead code elimination 49

50 Optimization implementation Is the optimization correct or safe? Is the optimization an improvement? What sort of analyses do we need to perform to get the required information? Local Global 50

51 Concurrency, distributed computing, the Internet Traditional view: Let the OS deal with this => It is not a programming language issue! End of Lecture Wait-a-minute Maybe the traditional view is getting out of date? 51

52 Languages with concurrency constructs Maybe the traditional view was always out of date? Simula Modula3 Occam Concurrent Pascal ADA Linda CML Facile Jo-Caml Java C# Fortress 52

53 What could languages provide? Abstract model of system abstract machine => abstract system Example high-level constructs Process as the value of an expression Pass processes to functions Create processes at the result of function call Communication abstractions Synchronous communication Buffered asynchronous channels that preserve msg order Mutual exclusion, atomicity primitives Most concurrent languages provide some form of locking Atomicity is more complicated, less commonly provided 53

54 Programming Language Life cycle The requirements for the new language are identified The language syntax and semantics is designed BNF or EBNF, experiments with front-end tools Informal or formal Semantic An informal or formal specification is developed Initial implementation Prototype via interpreter or interpretive compiler Language tested by designers, implementers and a few friends Feedback on the design and possible reconsiderations Improved implementation 54

55 Programming Language Life cycle Design Specification Prototype Manuals, Textbooks Compiler 55

56 Programming Language Life cycle Lots of research papers Conferences session dedicated to new language Text books and manuals Used in large applications Huge international user community Dedicated conference International standardisation efforts Industry de facto standard Programs written in the languages becomes legacy code Language enters hall-of-fame and features are taught in CS course on Programming Language Design and Implementation 56

57 The Most Important Open Problem in Computing Increasing Programmer Productivity Write programs correctly Write programs quickly Write programs easily Why? Decreases support cost Decreases development cost Decreases time to market Increases satisfaction 57

58 Why Programming Languages? 3 ways of increasing programmer productivity: 1. Process (software engineering) Controlling programmers 2. Tools (verification, static analysis, program generation) Important, but generally of narrow applicability 3. Language design --- the center of the universe! Core abstractions, mechanisms, services, guarantees Affect how programmers approach a task (C vs. SML) Multi-paradigm integration 58

59 Programming Languages and Compilers are at the core of Computing All software is written in a programming language Learning about compilers will teach you a lot about the programming languages you already know. Compilers are big therefore you need to apply all you knowledge of software engineering. The compiler is the program from which all other programs arise. 59

60 How to recognize a problem that can be solved with programming language techniques when you see one? Problem - a Scrabble game to be distributed as an applet. Create a dictionary of 50,000 words. Two options Program 1: create an external file words.txt and read it into an array when program starts while ((word = f.readline())!= null {words.addelement(word);} Program 2: create a element table in the program and initialize it to the words String [] words = { hill, fetch, pail, water,..}; Advantages/disadvantages of each approach? performance flexibility correctness. Example from J. Craig Cleaveland. Program Generators with XML and Java, chapter 1 60

61 A program generator approach import java.io.*; import java.util.*; class Dictionary1Generator { static Vector words = new Vector(); static void loadwords() { // read the words in file words.txt // into the Vector words } } static public void main(string[] args) { loadwords(); // Generate Dictionary1 program System.out.println("class Dictionary1{\n"); System.out.println(" String words = {"); for (int j=0; j<words.size(); ++j) { System.out.println("\""+words.elementAt(j)+"\","); }; System.out.println( } \n } ); 61

62 Typical program generator Dictionary example The data simply a list of words Analyzing/transforming data duplicate word removal sorting Generate program simply use print statements to write program text General picture The data some more complex representation of data formal specs, grammar, spreadsheet, XML, etc. Analyzing/transforming data parse, check for inconsistencies, transform to other data structures Generate program generate syntax tree, use templates, 62

63 The next wave of Program Generators: Model-Driven Development Requirements Analysis & Design Implementation Testing 63

64 New Programming Language! Why Should I Care? The problem is not designing a new language It s easy! Thousands of languages have been developed The problem is how to get wide adoption of the new language It s hard! Challenges include Competition Usefulness Interoperability Fear It s a good idea, but it s a new idea; therefore, I fear it and must reject it. --- Homer Simpson The financial rewards are low, but 64

65 Famous Danish Computer Scientists Peter Nauer BNF and Algol Per Brinck Hansen Monitors and Concurrent Pascal Dines Bjørner VDM and ADA Bjarne Straustrup C++ MadsTofte SML Rasmus Lerdorf PhP Anders Hejlsberg Turbo Pascal and C# Jacob Nielsen 65

66 66

67 67

68 Fancy joining this crowd? Join the Programming Language Technology Research Group when you get to DAT5/DAT6 or SW8/SW9 Research Programme underway How would you like to programme in 20 years? OO and Functional Programming Lots of MSc projects Languages for testability, verifiability, specifiability Java vs..net Aspect Oriented Programming on.net Business Process Management Language Multiple dispatch in C# XML as program representation Java on Mobile Phones OO and DB OO and Concurrency 68

69 Finally Keep in mind, the compiler is the program from which all other programs arise. If your compiler is under par, all programs created by the compiler will also be under par. No matter the purpose or use -- your own enlightenment about compilers or commercial applications -- you want to be patient and do a good job with this program; in other words, don't try to throw this together on a weekend. Asking a computer programmer to tell you how to write a compiler is like saying to Picasso, "Teach me to paint like you." *Sigh* Well, Picasso tried. 69

70 What I promised you at the start of the course Ideas, principles and techniques to help you Design your own programming language or design your own extensions to an existing language Tools and techniques to implement a compiler or an interpreter Lots of knowledge about programming I hope you feel you got what I promised 70

71 Top 10 reasons COMPILERS must be female 10. Picky, picky, picky. 9. They hear what you say, but not what you mean. 8. Beauty is only shell deep. 7. When you ask what's wrong, they say "nothing". 6. Can produce incorrect results with alarming speed. 5. Always turning simple statements into big productions. 4. Small talk is important. 3. You do the same thing for years, and suddenly it's wrong. 2. They make you take the garbage out. 1. Miss a period and they go wild. 71

Course Overview. Levels of Programming Languages. Compilers and other translators. Tombstone Diagrams. Syntax Specification

Course Overview. Levels of Programming Languages. Compilers and other translators. Tombstone Diagrams. Syntax Specification Course Overview Levels of Programming Languages PART I: overview material 1 Introduction 2 Language processors (tombstone diagrams, bootstrapping) 3 Architecture of a compiler PART II: inse a compiler

More information

Course Overview. Introduction (Chapter 1) Compiler Frontend: Today. Compiler Backend:

Course Overview. Introduction (Chapter 1) Compiler Frontend: Today. Compiler Backend: Course Overview Introduction (Chapter 1) Compiler Frontend: Today Lexical Analysis & Parsing (Chapter 2,3,4) Semantic Analysis (Chapter 5) Activation Records (Chapter 6) Translation to Intermediate Code

More information

Semantic Analysis. Lecture 9. February 7, 2018

Semantic Analysis. Lecture 9. February 7, 2018 Semantic Analysis Lecture 9 February 7, 2018 Midterm 1 Compiler Stages 12 / 14 COOL Programming 10 / 12 Regular Languages 26 / 30 Context-free Languages 17 / 21 Parsing 20 / 23 Extra Credit 4 / 6 Average

More information

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

Theoretical Part. Chapter one:- - What are the Phases of compiler? Answer: Theoretical Part Chapter one:- - What are the Phases of compiler? Six phases Scanner Parser Semantic Analyzer Source code optimizer Code generator Target Code Optimizer Three auxiliary components Literal

More information

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology exam Compiler Construction in4020 July 5, 2007 14.00-15.30 This exam (8 pages) consists of 60 True/False

More information

EDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised:

EDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised: EDAN65: Compilers, Lecture 06 A LR parsing Görel Hedin Revised: 2017-09-11 This lecture Regular expressions Context-free grammar Attribute grammar Lexical analyzer (scanner) Syntactic analyzer (parser)

More information

The Structure of a Syntax-Directed Compiler

The Structure of a Syntax-Directed Compiler Source Program (Character Stream) Scanner Tokens Parser Abstract Syntax Tree Type Checker (AST) Decorated AST Translator Intermediate Representation Symbol Tables Optimizer (IR) IR Code Generator Target

More information

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

SEMANTIC ANALYSIS TYPES AND DECLARATIONS SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether

More information

Languages and Compilers (SProg og Oversættere)

Languages and Compilers (SProg og Oversættere) Languages and Compilers (SProg og Oversættere) Bent Thomsen Department of Computer Science Aalborg University With acknowledgement to Norm Hutchinson whose slides this lecture is based on. 1 Syntax Analysis

More information

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology exam Compiler Construction in4303 April 9, 2010 14.00-15.30 This exam (6 pages) consists of 52 True/False

More information

11. a b c d e. 12. a b c d e. 13. a b c d e. 14. a b c d e. 15. a b c d e

11. a b c d e. 12. a b c d e. 13. a b c d e. 14. a b c d e. 15. a b c d e CS-3160 Concepts of Programming Languages Spring 2015 EXAM #1 (Chapters 1-6) Name: SCORES MC: /75 PROB #1: /15 PROB #2: /10 TOTAL: /100 Multiple Choice Responses Each multiple choice question in the separate

More information

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis? Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator

More information

Working of the Compilers

Working of the Compilers Working of the Compilers Manisha Yadav Nisha Thakran IT DEPARTMENT IT DEPARTMENT DCE,GURGAON DCE,GURGAON Abstract- The objective of the paper is to depict the working of the compilers that were designed

More information

CSE 12 Abstract Syntax Trees

CSE 12 Abstract Syntax Trees CSE 12 Abstract Syntax Trees Compilers and Interpreters Parse Trees and Abstract Syntax Trees (AST's) Creating and Evaluating AST's The Table ADT and Symbol Tables 16 Using Algorithms and Data Structures

More information

Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition. Chapter 7 Basic Semantics Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

More information

When do We Run a Compiler?

When do We Run a Compiler? When do We Run a Compiler? Prior to execution This is standard. We compile a program once, then use it repeatedly. At the start of each execution We can incorporate values known at the start of the run

More information

St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad

St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad-00 014 Subject: PPL Class : CSE III 1 P a g e DEPARTMENT COMPUTER SCIENCE AND ENGINEERING S No QUESTION Blooms Course taxonomy level Outcomes UNIT-I

More information

CS152 Programming Language Paradigms Prof. Tom Austin, Fall Syntax & Semantics, and Language Design Criteria

CS152 Programming Language Paradigms Prof. Tom Austin, Fall Syntax & Semantics, and Language Design Criteria CS152 Programming Language Paradigms Prof. Tom Austin, Fall 2014 Syntax & Semantics, and Language Design Criteria Lab 1 solution (in class) Formally defining a language When we define a language, we need

More information

Lecture 4: Syntax Specification

Lecture 4: Syntax Specification The University of North Carolina at Chapel Hill Spring 2002 Lecture 4: Syntax Specification Jan 16 1 Phases of Compilation 2 1 Syntax Analysis Syntax: Webster s definition: 1 a : the way in which linguistic

More information

Parsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones

Parsing III. CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Parsing III (Top-down parsing: recursive descent & LL(1) ) (Bottom-up parsing) CS434 Lecture 8 Spring 2005 Department of Computer Science University of Alabama Joel Jones Copyright 2003, Keith D. Cooper,

More information

Syntax Errors; Static Semantics

Syntax Errors; Static Semantics Dealing with Syntax Errors Syntax Errors; Static Semantics Lecture 14 (from notes by R. Bodik) One purpose of the parser is to filter out errors that show up in parsing Later stages should not have to

More information

CST-402(T): Language Processors

CST-402(T): Language Processors CST-402(T): Language Processors Course Outcomes: On successful completion of the course, students will be able to: 1. Exhibit role of various phases of compilation, with understanding of types of grammars

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

Code Generation. Overview of Lecture 6. Code Generation. Compiler Phases. Ch 7 Code Generation

Code Generation. Overview of Lecture 6. Code Generation. Compiler Phases. Ch 7 Code Generation Overview of Lecture 6 Code Generation Vertalerbouw HC6 Ch 7 Code Generation 7.1 Code selection 7.2 A code generation algorithm 7.3 Constants and variables HC7 7.4 Procedures and functions 7.5 Case study

More information

CS 406/534 Compiler Construction Putting It All Together

CS 406/534 Compiler Construction Putting It All Together CS 406/534 Compiler Construction Putting It All Together Prof. Li Xu Dept. of Computer Science UMass Lowell Fall 2004 Part of the course lecture notes are based on Prof. Keith Cooper, Prof. Ken Kennedy

More information

Chapter 2 :: Programming Language Syntax

Chapter 2 :: Programming Language Syntax Chapter 2 :: Programming Language Syntax Michael L. Scott kkman@sangji.ac.kr, 2015 1 Regular Expressions A regular expression is one of the following: A character The empty string, denoted by Two regular

More information

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University Semantic Analysis CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Role of Semantic Analysis Syntax vs. Semantics: syntax concerns the form of a

More information

CS 2210 Sample Midterm. 1. Determine if each of the following claims is true (T) or false (F).

CS 2210 Sample Midterm. 1. Determine if each of the following claims is true (T) or false (F). CS 2210 Sample Midterm 1. Determine if each of the following claims is true (T) or false (F). F A language consists of a set of strings, its grammar structure, and a set of operations. (Note: a language

More information

The Phases of a Compiler. Course Overview. In Chapter 4. Syntax Analysis. Syntax Analysis. Multi Pass Compiler. PART I: overview material

The Phases of a Compiler. Course Overview. In Chapter 4. Syntax Analysis. Syntax Analysis. Multi Pass Compiler. PART I: overview material Course Overview The Phases of a Compiler PART I: overview material Introduction 2 Language processors (tombstone diagrams, bootstrappg) 3 Architecture of a compiler PART II: side a compiler 4 Sntax analsis

More information

Informatica 3 Syntax and Semantics

Informatica 3 Syntax and Semantics Informatica 3 Syntax and Semantics Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Introduction Introduction to the concepts of syntax and semantics Binding Variables Routines

More information

Parsing. Roadmap. > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing

Parsing. Roadmap. > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing Roadmap > Context-free grammars > Derivations and precedence > Top-down parsing > Left-recursion > Look-ahead > Table-driven parsing The role of the parser > performs context-free syntax analysis > guides

More information

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

Regular Expressions. Agenda for Today. Grammar for a Tiny Language. Programming Language Specifications Agenda for Today Regular Expressions CSE 413, Autumn 2005 Programming Languages Basic concepts of formal grammars Regular expressions Lexical specification of programming languages Using finite automata

More information

programming languages need to be precise a regular expression is one of the following: tokens are the building blocks of programs

programming languages need to be precise a regular expression is one of the following: tokens are the building blocks of programs Chapter 2 :: Programming Language Syntax Programming Language Pragmatics Michael L. Scott Introduction programming languages need to be precise natural languages less so both form (syntax) and meaning

More information

Syntax Analysis. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill

Syntax Analysis. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill Syntax Analysis Björn B. Brandenburg The University of North Carolina at Chapel Hill Based on slides and notes by S. Olivier, A. Block, N. Fisher, F. Hernandez-Campos, and D. Stotts. The Big Picture Character

More information

About the Authors... iii Introduction... xvii. Chapter 1: System Software... 1

About the Authors... iii Introduction... xvii. Chapter 1: System Software... 1 Table of Contents About the Authors... iii Introduction... xvii Chapter 1: System Software... 1 1.1 Concept of System Software... 2 Types of Software Programs... 2 Software Programs and the Computing Machine...

More information

Wednesday, September 9, 15. Parsers

Wednesday, September 9, 15. Parsers Parsers What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda

More information

Parsers. What is a parser. Languages. Agenda. Terminology. Languages. A parser has two jobs:

Parsers. What is a parser. Languages. Agenda. Terminology. Languages. A parser has two jobs: What is a parser Parsers A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda

More information

Bottom-Up Parsing. Lecture 11-12

Bottom-Up Parsing. Lecture 11-12 Bottom-Up Parsing Lecture 11-12 (From slides by G. Necula & R. Bodik) 9/22/06 Prof. Hilfinger CS164 Lecture 11 1 Bottom-Up Parsing Bottom-up parsing is more general than topdown parsing And just as efficient

More information

The role of semantic analysis in a compiler

The role of semantic analysis in a compiler Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad -500 043 INFORMATION TECHNOLOGY TUTORIAL QUESTION BANK Name : PRINCIPLES OF PROGRAMMING LANGUAGES Code : A40511 Class : II B. Tech

More information

Operational Semantics. One-Slide Summary. Lecture Outline

Operational Semantics. One-Slide Summary. Lecture Outline Operational Semantics #1 One-Slide Summary Operational semantics are a precise way of specifying how to evaluate a program. A formal semantics tells you what each expression means. Meaning depends on context:

More information

Programming Languages, Summary CSC419; Odelia Schwartz

Programming Languages, Summary CSC419; Odelia Schwartz Programming Languages, Summary CSC419; Odelia Schwartz Chapter 1 Topics Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation Criteria Influences on Language Design

More information

CS 415 Midterm Exam Spring 2002

CS 415 Midterm Exam Spring 2002 CS 415 Midterm Exam Spring 2002 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Good Luck! Score Fortran Algol 60 Compilation Names, Bindings, Scope Functional Programming

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

CA Compiler Construction

CA Compiler Construction CA4003 - Compiler Construction Semantic Analysis David Sinclair Semantic Actions A compiler has to do more than just recognise if a sequence of characters forms a valid sentence in the language. It must

More information

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

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design i About the Tutorial A compiler translates the codes written in one language to some other language without changing the meaning of the program. It is also expected that a compiler should make the target

More information

Syntax Analysis/Parsing. Context-free grammars (CFG s) Context-free grammars vs. Regular Expressions. BNF description of PL/0 syntax

Syntax Analysis/Parsing. Context-free grammars (CFG s) Context-free grammars vs. Regular Expressions. BNF description of PL/0 syntax Susan Eggers 1 CSE 401 Syntax Analysis/Parsing Context-free grammars (CFG s) Purpose: determine if tokens have the right form for the language (right syntactic structure) stream of tokens abstract syntax

More information

CS606- compiler instruction Solved MCQS From Midterm Papers

CS606- compiler instruction Solved MCQS From Midterm Papers CS606- compiler instruction Solved MCQS From Midterm Papers March 06,2014 MC100401285 Moaaz.pk@gmail.com Mc100401285@gmail.com PSMD01 Final Term MCQ s and Quizzes CS606- compiler instruction If X is a

More information

CSCI312 Principles of Programming Languages!

CSCI312 Principles of Programming Languages! CSCI312 Principles of Programming Languages!! Chapter 3 Regular Expression and Lexer Xu Liu Recap! Copyright 2006 The McGraw-Hill Companies, Inc. Clite: Lexical Syntax! Input: a stream of characters from

More information

What do Compilers Produce?

What do Compilers Produce? What do Compilers Produce? Pure Machine Code Compilers may generate code for a particular machine, not assuming any operating system or library routines. This is pure code because it includes nothing beyond

More information

Question Bank. 10CS63:Compiler Design

Question Bank. 10CS63:Compiler Design Question Bank 10CS63:Compiler Design 1.Determine whether the following regular expressions define the same language? (ab)* and a*b* 2.List the properties of an operator grammar 3. Is macro processing a

More information

shift-reduce parsing

shift-reduce parsing Parsing #2 Bottom-up Parsing Rightmost derivations; use of rules from right to left Uses a stack to push symbols the concatenation of the stack symbols with the rest of the input forms a valid bottom-up

More information

CSCE 314 Programming Languages. Type System

CSCE 314 Programming Languages. Type System CSCE 314 Programming Languages Type System Dr. Hyunyoung Lee 1 Names Names refer to different kinds of entities in programs, such as variables, functions, classes, templates, modules,.... Names can be

More information

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer. The Compiler So Far CSC 4181 Compiler Construction Scanner - Lexical analysis Detects inputs with illegal tokens e.g.: main 5 (); Parser - Syntactic analysis Detects inputs with ill-formed parse trees

More information

Compilers. Type checking. Yannis Smaragdakis, U. Athens (original slides by Sam

Compilers. Type checking. Yannis Smaragdakis, U. Athens (original slides by Sam Compilers Type checking Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Summary of parsing Parsing A solid foundation: context-free grammars A simple parser: LL(1) A more powerful parser:

More information

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 2. true / false ML can be compiled. 3. true / false FORTRAN can reasonably be considered

More information

EI326 ENGINEERING PRACTICE & TECHNICAL INNOVATION (III-G) Kenny Q. Zhu Dept. of Computer Science Shanghai Jiao Tong University

EI326 ENGINEERING PRACTICE & TECHNICAL INNOVATION (III-G) Kenny Q. Zhu Dept. of Computer Science Shanghai Jiao Tong University EI326 ENGINEERING PRACTICE & TECHNICAL INNOVATION (III-G) Kenny Q. Zhu Dept. of Computer Science Shanghai Jiao Tong University KENNY ZHU Research Interests: Programming Languages Data processing Coordination

More information

SYED AMMAL ENGINEERING COLLEGE (An ISO 9001:2008 Certified Institution) Dr. E.M. Abdullah Campus, Ramanathapuram

SYED AMMAL ENGINEERING COLLEGE (An ISO 9001:2008 Certified Institution) Dr. E.M. Abdullah Campus, Ramanathapuram CS6660 COMPILER DESIGN Question Bank UNIT I-INTRODUCTION TO COMPILERS 1. Define compiler. 2. Differentiate compiler and interpreter. 3. What is a language processing system? 4. List four software tools

More information

PRINCIPLES OF COMPILER DESIGN UNIT I INTRODUCTION TO COMPILERS

PRINCIPLES OF COMPILER DESIGN UNIT I INTRODUCTION TO COMPILERS Objective PRINCIPLES OF COMPILER DESIGN UNIT I INTRODUCTION TO COMPILERS Explain what is meant by compiler. Explain how the compiler works. Describe various analysis of the source program. Describe the

More information

Week 2: Syntax Specification, Grammars

Week 2: Syntax Specification, Grammars CS320 Principles of Programming Languages Week 2: Syntax Specification, Grammars Jingke Li Portland State University Fall 2017 PSU CS320 Fall 17 Week 2: Syntax Specification, Grammars 1/ 62 Words and Sentences

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Statically vs. Dynamically typed languages

More information

CMSC 330: Organization of Programming Languages. Context Free Grammars

CMSC 330: Organization of Programming Languages. Context Free Grammars CMSC 330: Organization of Programming Languages Context Free Grammars 1 Architecture of Compilers, Interpreters Source Analyzer Optimizer Code Generator Abstract Syntax Tree Front End Back End Compiler

More information

Chapter 4. Abstract Syntax

Chapter 4. Abstract Syntax Chapter 4 Abstract Syntax Outline compiler must do more than recognize whether a sentence belongs to the language of a grammar it must do something useful with that sentence. The semantic actions of a

More information

Principles of Programming Languages [PLP-2015] Detailed Syllabus

Principles of Programming Languages [PLP-2015] Detailed Syllabus Principles of Programming Languages [PLP-2015] Detailed Syllabus This document lists the topics presented along the course. The PDF slides published on the course web page (http://www.di.unipi.it/~andrea/didattica/plp-15/)

More information

Syntax Analysis. The Big Picture. The Big Picture. COMP 524: Programming Languages Srinivas Krishnan January 25, 2011

Syntax Analysis. The Big Picture. The Big Picture. COMP 524: Programming Languages Srinivas Krishnan January 25, 2011 Syntax Analysis COMP 524: Programming Languages Srinivas Krishnan January 25, 2011 Based in part on slides and notes by Bjoern Brandenburg, S. Olivier and A. Block. 1 The Big Picture Character Stream Token

More information

List of Figures. About the Authors. Acknowledgments

List of Figures. About the Authors. Acknowledgments List of Figures Preface About the Authors Acknowledgments xiii xvii xxiii xxv 1 Compilation 1 1.1 Compilers..................................... 1 1.1.1 Programming Languages......................... 1

More information

Project Compiler. CS031 TA Help Session November 28, 2011

Project Compiler. CS031 TA Help Session November 28, 2011 Project Compiler CS031 TA Help Session November 28, 2011 Motivation Generally, it s easier to program in higher-level languages than in assembly. Our goal is to automate the conversion from a higher-level

More information

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2009 P. N. Hilfinger CS 164: Final Examination (corrected) Name: Login: You have

More information

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division Fall, 2001 Prof. R. Fateman SUGGESTED S CS 164 Final Examination: December 18, 2001, 8-11AM

More information

Semantic actions for declarations and expressions

Semantic actions for declarations and expressions Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

flex is not a bad tool to use for doing modest text transformations and for programs that collect statistics on input.

flex is not a bad tool to use for doing modest text transformations and for programs that collect statistics on input. flex is not a bad tool to use for doing modest text transformations and for programs that collect statistics on input. More often than not, though, you ll want to use flex to generate a scanner that divides

More information

Midterm 2 Solutions Many acceptable answers; one was the following: (defparameter g1

Midterm 2 Solutions Many acceptable answers; one was the following: (defparameter g1 Midterm 2 Solutions 1. [20 points] Consider the language that consist of possibly empty lists of the identifier x enclosed by parentheses and separated by commas. The language includes { () (x) (x,x) (x,x,x)

More information

The Structure of a Syntax-Directed Compiler

The Structure of a Syntax-Directed Compiler Source Program (Character Stream) Scanner Tokens Parser Abstract Syntax Tree (AST) Type Checker Decorated AST Translator Intermediate Representation Symbol Tables Optimizer (IR) IR Code Generator Target

More information

COP 3402 Systems Software Top Down Parsing (Recursive Descent)

COP 3402 Systems Software Top Down Parsing (Recursive Descent) COP 3402 Systems Software Top Down Parsing (Recursive Descent) Top Down Parsing 1 Outline 1. Top down parsing and LL(k) parsing 2. Recursive descent parsing 3. Example of recursive descent parsing of arithmetic

More information

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given MUHAMMAD FAISAL MIT 4 th Semester Al-Barq Campus (VGJW01) Gujranwala faisalgrw123@gmail.com MEGA File Solved MCQ s For Final TERM EXAMS CS508- Modern Programming Languages Question No: 1 ( Marks: 1 ) -

More information

Semantic actions for declarations and expressions. Monday, September 28, 15

Semantic actions for declarations and expressions. Monday, September 28, 15 Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

CSE 130 Programming Language Principles & Paradigms Lecture # 5. Chapter 4 Lexical and Syntax Analysis

CSE 130 Programming Language Principles & Paradigms Lecture # 5. Chapter 4 Lexical and Syntax Analysis Chapter 4 Lexical and Syntax Analysis Introduction - Language implementation systems must analyze source code, regardless of the specific implementation approach - Nearly all syntax analysis is based on

More information

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Static Semantics Lecture 15 (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Current Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing

More information

Parsing II Top-down parsing. Comp 412

Parsing II Top-down parsing. Comp 412 COMP 412 FALL 2018 Parsing II Top-down parsing Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled

More information

Compiler Theory. (Semantic Analysis and Run-Time Environments)

Compiler Theory. (Semantic Analysis and Run-Time Environments) Compiler Theory (Semantic Analysis and Run-Time Environments) 005 Semantic Actions A compiler must do more than recognise whether a sentence belongs to the language of a grammar it must do something useful

More information

CS143 Handout 20 Summer 2011 July 15 th, 2011 CS143 Practice Midterm and Solution

CS143 Handout 20 Summer 2011 July 15 th, 2011 CS143 Practice Midterm and Solution CS143 Handout 20 Summer 2011 July 15 th, 2011 CS143 Practice Midterm and Solution Exam Facts Format Wednesday, July 20 th from 11:00 a.m. 1:00 p.m. in Gates B01 The exam is designed to take roughly 90

More information

Answer: Early binding generally leads to greater efficiency (compilation approach) Late binding general leads to greater flexibility

Answer: Early binding generally leads to greater efficiency (compilation approach) Late binding general leads to greater flexibility Quiz Review Q1. What is the advantage of binding things as early as possible? Is there any advantage to delaying binding? Answer: Early binding generally leads to greater efficiency (compilation approach)

More information

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

CSEP 501 Compilers. Languages, Automata, Regular Expressions & Scanners Hal Perkins Winter /8/ Hal Perkins & UW CSE B-1 CSEP 501 Compilers Languages, Automata, Regular Expressions & Scanners Hal Perkins Winter 2008 1/8/2008 2002-08 Hal Perkins & UW CSE B-1 Agenda Basic concepts of formal grammars (review) Regular expressions

More information

Operational Semantics of Cool

Operational Semantics of Cool Operational Semantics of Cool Lecture 23 Dr. Sean Peisert ECS 142 Spring 2009 1 Status Project 3 due on Friday Project 4 assigned on Friday. Due June 5, 11:55pm Office Hours this week Fri at 11am No Class

More information

5. Semantic Analysis!

5. Semantic Analysis! 5. Semantic Analysis! Prof. O. Nierstrasz! Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes.! http://www.cs.ucla.edu/~palsberg/! http://www.cs.purdue.edu/homes/hosking/!

More information

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

Lexical Analysis. Lexical analysis is the first phase of compilation: The file is converted from ASCII to tokens. It must be fast! Lexical Analysis Lexical analysis is the first phase of compilation: The file is converted from ASCII to tokens. It must be fast! Compiler Passes Analysis of input program (front-end) character stream

More information

Bottom-Up Parsing. Lecture 11-12

Bottom-Up Parsing. Lecture 11-12 Bottom-Up Parsing Lecture 11-12 (From slides by G. Necula & R. Bodik) 2/20/08 Prof. Hilfinger CS164 Lecture 11 1 Administrivia Test I during class on 10 March. 2/20/08 Prof. Hilfinger CS164 Lecture 11

More information

CSE 5317 Midterm Examination 4 March Solutions

CSE 5317 Midterm Examination 4 March Solutions CSE 5317 Midterm Examination 4 March 2010 1. / [20 pts] Solutions (parts a j; -1 point for each wrong answer, 0 points for each blank answer, 2 point for each correct answer. Therefore, the score for this

More information

Introduction to Lexing and Parsing

Introduction to Lexing and Parsing Introduction to Lexing and Parsing ECE 351: Compilers Jon Eyolfson University of Waterloo June 18, 2012 1 Riddle Me This, Riddle Me That What is a compiler? 1 Riddle Me This, Riddle Me That What is a compiler?

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.

More information

Compilers. Yannis Smaragdakis, U. Athens (original slides by Sam

Compilers. Yannis Smaragdakis, U. Athens (original slides by Sam Compilers Parsing Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Next step text chars Lexical analyzer tokens Parser IR Errors Parsing: Organize tokens into sentences Do tokens conform

More information

CSE 401 Midterm Exam Sample Solution 2/11/15

CSE 401 Midterm Exam Sample Solution 2/11/15 Question 1. (10 points) Regular expression warmup. For regular expression questions, you must restrict yourself to the basic regular expression operations covered in class and on homework assignments:

More information

Building Compilers with Phoenix

Building Compilers with Phoenix Building Compilers with Phoenix Parser Generators: ANTLR History of ANTLR ANother Tool for Language Recognition Terence Parr's dissertation: Obtaining Practical Variants of LL(k) and LR(k) for k > 1 PCCTS:

More information

NOTE: Answer ANY FOUR of the following 6 sections:

NOTE: Answer ANY FOUR of the following 6 sections: A-PDF MERGER DEMO Philadelphia University Lecturer: Dr. Nadia Y. Yousif Coordinator: Dr. Nadia Y. Yousif Internal Examiner: Dr. Raad Fadhel Examination Paper... Programming Languages Paradigms (750321)

More information

Last time. What are compilers? Phases of a compiler. Scanner. Parser. Semantic Routines. Optimizer. Code Generation. Sunday, August 29, 2010

Last time. What are compilers? Phases of a compiler. Scanner. Parser. Semantic Routines. Optimizer. Code Generation. Sunday, August 29, 2010 Last time Source code Scanner Tokens Parser What are compilers? Phases of a compiler Syntax tree Semantic Routines IR Optimizer IR Code Generation Executable Extra: Front-end vs. Back-end Scanner + Parser

More information

MIDTERM EXAM (Solutions)

MIDTERM EXAM (Solutions) MIDTERM EXAM (Solutions) Total Score: 100, Max. Score: 83, Min. Score: 26, Avg. Score: 57.3 1. (10 pts.) List all major categories of programming languages, outline their definitive characteristics and

More information

Context-free grammars (CFG s)

Context-free grammars (CFG s) Syntax Analysis/Parsing Purpose: determine if tokens have the right form for the language (right syntactic structure) stream of tokens abstract syntax tree (AST) AST: captures hierarchical structure of

More information

Time : 1 Hour Max Marks : 30

Time : 1 Hour Max Marks : 30 Total No. of Questions : 6 P4890 B.E/ Insem.- 74 B.E ( Computer Engg) PRINCIPLES OF MODERN COMPILER DESIGN (2012 Pattern) (Semester I) Time : 1 Hour Max Marks : 30 Q.1 a) Explain need of symbol table with

More information

The Substitution Model

The Substitution Model The Substitution Model Prof. Clarkson Fall 2017 Today s music: Substitute by The Who Review Previously in 3110: simple interpreter for expression language abstract syntax tree (AST) evaluation based on

More information

Abstract Syntax Trees and Contextual Analysis. Roland Backhouse March 8, 2001

Abstract Syntax Trees and Contextual Analysis. Roland Backhouse March 8, 2001 1 Abstract Syntax Trees and Contextual Analysis Roland Backhouse March 8, 2001 Phases of a Compiler 2 sequence of characters sequence of tokens Lexical analysis Syntax Analysis AST representation of program

More information