Writing an Interpreter Thoughts on Assignment 6

Size: px
Start display at page:

Download "Writing an Interpreter Thoughts on Assignment 6"

Transcription

1 Writing an Interpreter Thoughts on Assignment 6 CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, March 27, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu 2017 Glenn G. Chappell

2 Review Forth: Details Stacks A Forth implementation adhering to the ANSI standard is actually required to have four stacks. Data stack Holds integer values. These are also used as pointers and booleans. This is the stack we have been dealing with. Floating-point stack Holds floating-point values. Return stack Holds return addresses for words that are called. Locals stack Holds local variables. Why are the return stack & locals stack separate? I do not know. 27 Mar 2017 CS F331 / CSCE A331 Spring

3 Review Forth: Details Floating Point [1/2] Forth includes support for floating-point computations. Floatingpoint values (essentially the same as C/C++ values of type double) are stored on a separate stack: the floating-point stack. Floating-point literals must contain e or E. These push a value on the floating-point stack. -4e 1.2E 1.2e17 See float.fs. 27 Mar 2017 CS F331 / CSCE A331 Spring

4 Review Forth: Details Floating Point [2/2] Words that handle floating-point are often named the same as the corresponding integer-handling words, with an f prepended. f. \ Like. f.s \ Like.s This means that the stack-effect notation refers to the floating-point stack. fdup ( F: x -- x x ) \ Like dup Also fdrop fswap... f+ ( F: x y -- x+y ) \ Like + Also f- f* f/ Here are some other floating-point-handling words. f** ( F: x y -- pow[x,y] ) \ x raised to the y power fsqrt ( F: x -- sqrt[x] ) fexp ( F: x -- exp[x] ) \ Also flog fsin fcos... 1/f ( F: x -- 1/x ) 27 Mar 2017 CS F331 / CSCE A331 Spring

5 Review Forth: Details Other Features Some Forth features that we do not have time to cover: Exceptions Forth has a notion of exception that can be used for error handling. Defining new flow-of-control words Some of the words we have covered are special: if else endif begin while repeat?do loop recurse. These affect the flow of control in ways that we do now know how to duplicate. But Forth does allow us to write such words ourselves. Defining new defining words Some other words are special in another way: variable constant : ;. These allow new words to be defined. Forth allows us to write this kind of word as well. 27 Mar 2017 CS F331 / CSCE A331 Spring

6 Review Forth: Details Specifying Semantics [1/4] Recall: Syntax = structure (of code) Semantics = meaning (of code) Grammatical Notes Semantics is an uncountable noun (like butter ). It is mostly used in the singular (so Semantics is, not Semantics are... ). Semantic is the corresponding adjective. 27 Mar 2017 CS F331 / CSCE A331 Spring

7 Review Forth: Details Specifying Semantics [2/4] How is semantics used? A programmer needs to know the semantics of a PL in order to write correct code. A design of a compiler needs to be based on the semantics of the source PL, so that correct object code can be generated. Similarly, the design of an interpreter needs to be based on the semantics of the source PL, so that correct actions can be performed. Semantics is useful in optimization: altering code so as to improve performance, while keeping semantics the same. Semantics is used in verification: checking that code performs the actions it is supposed to. 27 Mar 2017 CS F331 / CSCE A331 Spring

8 Review Forth: Details Specifying Semantics [3/4] Semantics is generally divided into two kinds: static and dynamic. Static semantics includes the aspects of semantics that can be checked before a program executes. This includes: Typing, in statically typed PLs. Dependencies (what relies on what). Other things like whether all cases in a switch are distinct. Dynamic semantics refers to the semantics of a running program: what statements do, and what expressions compute. In a dynamically typed PL, this also includes typing. 27 Mar 2017 CS F331 / CSCE A331 Spring

9 Review Forth: Details Specifying Semantics [4/4] We have looked at methods for formally specifying syntax in particular, phrase-structure grammars. Formal semantics refers to methods for formally specifying semantics. These generally involve mathematical notations. We looked briefly at four formal-semantics methods. We are not covering notation. Attribute grammars. Specify static semantics via attributes added to AST nodes. Operational semantics. Specify dynamic semantics of a PL in terms of the semantics of some other PL or abstract machine (usually the latter). Axiomatic semantics. Specify dynamic semantics in terms logical statements about program state. Denotational semantics. Specify dynamic semantics by representing state & values with mathematical objects, commands & computations by functions. 27 Mar 2017 CS F331 / CSCE A331 Spring

10 Writing an Interpreter Introduction [1/3] Recall: a compiler takes code in one PL (the source PL) and translates it into code in another PL (the target PL). Source PL Compiler Target PL An interpreter takes code in its source PL and executes it. Source PL Interpreter 27 Mar 2017 CS F331 / CSCE A331 Spring

11 Writing an Interpreter Introduction [2/3] Compilation and interpretation are not mutually exclusive. Many modern interpreters begin by compiling to an intermediate representation (IR) perhaps a byte code which is then interpreted directly. Lua Standard Lua Interpreter Lua Compiler Lua Byte Code Lua Byte Code Interpreter 27 Mar 2017 CS F331 / CSCE A331 Spring

12 Writing an Interpreter Introduction [3/3] Regardless of whether there is a compilation step, virtually all interpreters will use some kind of IR. This might be: An abstract syntax tree (AST). A PL-specific byte code. E.g., Lua byte code, Python byte code. A general-purpose byte code. E.g., LLVM, Java Virtual Machine (JVM) byte code. Some other programming language. JavaScript is used in this way very often. It is possible that more than one IR is used. The source code is translated to the first IR, then the first IR is translated to the second, etc. 27 Mar 2017 CS F331 / CSCE A331 Spring

13 Writing an Interpreter Processing an AST [1/2] The AST produced by the parser will need to be processed, either by interpreting it directly, or generating another IR from it. How is this done? An AST is a rooted tree. Code that deals with a rooted tree usually proceeds as follows. Handle the root node. Make a function call (often a recursive call) on each subtree of the root. (a + 2) * -b + * - a 2 b 27 Mar 2017 CS F331 / CSCE A331 Spring

14 Writing an Interpreter Processing an AST [2/2] Suppose we wish to write a function that evaluates an AST representing a numeric expression, like the pictured tree. Our function will take an AST and return the numeric * value of the expression. It could work something like this: If the root node represents a numeric literal: Convert the literal to a number and return it. Else if the root node represents a numeric variable: Get the variable s current value and return it. Else if the root node represents a binary operator: Get the value of the left subtree (recursive call). Get the value of the right subtree (recursive call). Apply the appropriate operation and return the result. Else if the root node represents a unary operator: Get the value of the subtree (recursive call). Apply the appropriate operation and return the result. + a 2 b - 27 Mar 2017 CS F331 / CSCE A331 Spring

15 Writing an Interpreter Representing State While an interpreter is executing a program, there will need to be some representation of program state: values of variables, the call stack, etc. In a PL with static typing and scope, the compiler/linker can determine the types and scopes of all variables and the types of all unnamed values. These can be laid out in memory (for local values, in a stack frame). Thus, at runtime, a reference to a value will simply be a reference to a particular memory location. In a dynamic PL, it is common to place variables in an associative structure with the variable name as key. Usually a hash table is used, with a separate hash table for each scope. 27 Mar 2017 CS F331 / CSCE A331 Spring

16 Writing an Interpreter Runtime System There will need to be a runtime system (often simply runtime): additional code that programs will need to use at runtime. This might include: Program initialization and shutdown. I/O. Memory management. Interfaces to operating system functionality (e.g., files, threads, interprocess communication). Implementations of PL commands that perform complex operations (e.g., advanced floating-point computations, operations involving multiple data items like sorting or matrix operations). 27 Mar 2017 CS F331 / CSCE A331 Spring

17 Thoughts on Assignment 6 Introduction You have written a lexer and parser for the Kanchil programming language. For Assignment 6 you will complete the trilogy by writing an interpreter that takes an AST and executes it. As with the previous two parts, this will be written in Lua: a module interpit, which exports a single function: interp. A complete specification of the semantics of Kanchil and requirements on your implementation will be given in the Assignment 6 description. These slides contain some relevant ideas & examples. 27 Mar 2017 CS F331 / CSCE A331 Spring

18 Thoughts on Assignment 6 The Goal Once again, here is a sample Kanchil program. # Subroutine &fibo # Given %k, set %fibk to F(%k), # where F(n) = nth Fibonacci no. sub &fibo set %a: 0 # Consecutive Fibos set %b: 1 set %i: 0 # Loop counter while %i < %k set %c: %a+%b # Advance set %a: %b set %b: %c set %i: %i+1 # ++counter end set %fibk: %a # Result end # Get number of Fibos to output print "How many Fibos to print: " input %n cr # Print requested number of Fibos set %j: 0 # Loop counter while %j < %n set %k: %j call &fibo print "F(" print %j print ") = " print %fibk cr set %j: %j + 1 end 27 Mar 2017 CS F331 / CSCE A331 Spring

19 Thoughts on Assignment 6 Function interp [1/2] interpit.interp takes four parameters: ast The AST to execute, in the format returned by parseit.parse. state The current state: values of simple variables, arrays, and subroutines. This is passed so that Kanchil code can be entered interactively, line by line, and handled as a series of separate programs, each getting its state from the earlier code. incall outcall Functions to call to do string input (read line) & output. These are passed so that Kanchil code can interact with files and other programs. In particular, this allows me to test your work. interpit.interp will return the new state. 27 Mar 2017 CS F331 / CSCE A331 Spring

20 Thoughts on Assignment 6 Function interp [2/2] You will need to write a number of helper functions. I suggest that, at the very least, you plan to write: A function that takes the AST for a statement list and executes it, updating the state appropriately. A function that takes the AST for a numeric expression, evaluates it, and returns its value. Both of these will be recursive. The function that executes a statement list will be called to execute a program, or a subroutine, or the body of an if-statement or while-statement. Note that the function that evaluates an expression does not need to be concerned with precedence and associativity; these are already encoded in the AST. The evaluation function may need to read the state, but it will not change it; Kanchil expressions have no side effects. 27 Mar 2017 CS F331 / CSCE A331 Spring

21 Thoughts on Assignment 6 State State will be stored as a Lua table with three members: v, a, s, holding simple variables, arrays, and subroutines, respectively. For example: The value of simple variable %abc will be in state.v["%abc"]. The value of array item %abc[2] will be in state.a["%abc"][2]. The AST for subroutine &abc will be in state.s["&abc"]. All identifiers are global and have dynamic scope. Once a variable/subroutine is given a value, it has that value everywhere in the code. Thus, only one state table is needed. Kanchil has no fatal runtime errors. Thus, undefined variables are treated as if they have a default value. The default value for simple variables and array items is 0. The default AST for a subroutine is { STMT_LIST }. 27 Mar 2017 CS F331 / CSCE A331 Spring

22 Thoughts on Assignment 6 Utilities I provide a runtime system for Kanchil, along with the following utility functions, which should not be modified. numtostr Convert a number to a string. Used in numeric output. strtonum Convert a string to a number. Used in numeric input. numtoint Convert a number to an integer value. Used after every numeric computation. booltoint Convert a Lua boolean to an integer. In addition, the passed incall & outcall should be used to do string I/O. And all of Lua is available to be used. 27 Mar 2017 CS F331 / CSCE A331 Spring

23 Thoughts on Assignment 6 Numeric & Boolean Values Kanchil has no separate boolean type. When a Kanchil number is treated as a boolean, it is true if it is nonzero ( ~= 0) and false otherwise. For the majority of Kanchil operators, the computation performed is that done by the corresponding Lua operator, followed by a call to numtoint or booltoint, as appropriate. Two small exceptions: The Kanchil!= operator corresponds to the Lua ~= operator. Unlike Kanchil, Lua has no unary + operator. The Kanchil unary + operator simply returns its operand unchanged. 27 Mar 2017 CS F331 / CSCE A331 Spring

24 Thoughts on Assignment 6 General Principles Be DRY! If a function is already written, then it can be used. You may assume the AST is formatted correctly. Write all functions local to interpit.interp. Don t pass around state, incall, outcall. Do pass the AST. Pre-declaring local functions: local f function f( ) -- NO "local" L-Values As the argument of input, or the LHS of set, an L-value is something whose value is changed. As part of an argument of print, the RHS of set, or an array index, an L-value is something that is evaluated as part of an expression. 27 Mar 2017 CS F331 / CSCE A331 Spring

25 Thoughts on Assignment 6 How I Did It [1/2] I wrote six new functions, all local to interpit.interp: interp_stmt_list interp_stmt process_lvalue get_lvalue set_lvalue eval_expr Handling L-Values When an L-value is encountered, I call process_lvalue, which returns a description of the L-value (its identifier, whether it is an array reference, and, if so, the index). If I need the value of the L-value, then I pass this description to get_lvalue, which returns the numeric value. If I need to set the L-value, then I pass the description and the new value to set_lvalue. 27 Mar 2017 CS F331 / CSCE A331 Spring

26 Thoughts on Assignment 6 How I Did It [2/2] Writing eval_expr This function takes an AST and returns the value of the expression. It is called for the RHS of a set statement, a non-string argument of print, and an array index. It calls itself recursively. Written in the form of a number of cases: ast[1] is NUMLIT_VAL ast[1] is BOOLLIT_VAL ast[1] is VARID_VAL ast[1] is ARRAY_REF ast[1] is a table, and: ast[1][1] is UN_OP ast[1][1] is BIN_OP 27 Mar 2017 CS F331 / CSCE A331 Spring

27 Thoughts on Assignment 6 Write It TO DO Begin writing module interpit. Implementations were written in class for: Cr statements. Print statements whose argument is a string literal. Sub statements (subroutine definitions). Call statements (subroutine calls). Done. See interpit.lua. 27 Mar 2017 CS F331 / CSCE A331 Spring

Thoughts on Assignment 4 Haskell: Flow of Control

Thoughts on Assignment 4 Haskell: Flow of Control Thoughts on Assignment 4 Haskell: Flow of Control CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, February 27, 2017 Glenn G. Chappell Department of Computer

More information

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G. Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu

More information

Introduction to Syntax Analysis Recursive-Descent Parsing

Introduction to Syntax Analysis Recursive-Descent Parsing Introduction to Syntax Analysis Recursive-Descent Parsing CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 10, 2017 Glenn G. Chappell Department of

More information

Writing a Lexer. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, February 6, Glenn G.

Writing a Lexer. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, February 6, Glenn G. Writing a Lexer CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, February 6, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

More information

Scheme: Expressions & Procedures

Scheme: Expressions & Procedures Scheme: Expressions & Procedures CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, March 31, 2017 Glenn G. Chappell Department of Computer Science University

More information

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking CSE450 Translation of Programming Languages Lecture 11: Semantic Analysis: Types & Type Checking Structure Project 1 - of a Project 2 - Compiler Today! Project 3 - Source Language Lexical Analyzer Syntax

More information

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G. Haskell: Lists CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

More information

Semantics of programming languages

Semantics of programming languages Semantics of programming languages Informatics 2A: Lecture 27 John Longley School of Informatics University of Edinburgh jrl@inf.ed.ac.uk 21 November, 2011 1 / 19 1 2 3 4 2 / 19 Semantics for programming

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

Types and Static Type Checking (Introducing Micro-Haskell)

Types and Static Type Checking (Introducing Micro-Haskell) Types and Static (Introducing Micro-Haskell) Informatics 2A: Lecture 13 Alex Simpson School of Informatics University of Edinburgh als@inf.ed.ac.uk 16 October, 2012 1 / 21 1 Types 2 3 4 2 / 21 Thus far

More information

Semantic actions for expressions

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

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

LECTURE 17. Expressions and Assignment

LECTURE 17. Expressions and Assignment LECTURE 17 Expressions and Assignment EXPRESSION SYNTAX An expression consists of An atomic object, e.g. number or variable. An operator (or function) applied to a collection of operands (or arguments)

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

Type Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules.

Type Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules. Outline Type Checking General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time

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

Outline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference

Outline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference Type Checking Outline General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time

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

Types and Static Type Checking (Introducing Micro-Haskell)

Types and Static Type Checking (Introducing Micro-Haskell) Types and Static (Introducing Micro-Haskell) Informatics 2A: Lecture 14 John Longley School of Informatics University of Edinburgh jrl@inf.ed.ac.uk 17 October 2017 1 / 21 1 Types 2 3 4 2 / 21 So far in

More information

Scheme: Strings Scheme: I/O

Scheme: Strings Scheme: I/O Scheme: Strings Scheme: I/O CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, April 5, 2017 Glenn G. Chappell Department of Computer Science University of

More information

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators)

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators) Name: Email address: Quiz Section: CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators) Instructions: Read the directions for each question carefully before answering. We will

More information

Semantics of programming languages

Semantics of programming languages Semantics of programming languages Informatics 2A: Lecture 28 Mary Cryan School of Informatics University of Edinburgh mcryan@inf.ed.ac.uk 21 November 2018 1 / 18 Two parallel pipelines A large proportion

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

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

Stating the obvious, people and computers do not speak the same language.

Stating the obvious, people and computers do not speak the same language. 3.4 SYSTEM SOFTWARE 3.4.3 TRANSLATION SOFTWARE INTRODUCTION Stating the obvious, people and computers do not speak the same language. People have to write programs in order to instruct a computer what

More information

6.001 Notes: Section 4.1

6.001 Notes: Section 4.1 6.001 Notes: Section 4.1 Slide 4.1.1 In this lecture, we are going to take a careful look at the kinds of procedures we can build. We will first go back to look very carefully at the substitution model,

More information

Symbol Tables Symbol Table: In computer science, a symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is

More information

A language is a subset of the set of all strings over some alphabet. string: a sequence of symbols alphabet: a set of symbols

A language is a subset of the set of all strings over some alphabet. string: a sequence of symbols alphabet: a set of symbols The current topic:! Introduction! Object-oriented programming: Python! Functional programming: Scheme! Python GUI programming (Tkinter)! Types and values! Logic programming: Prolog! Introduction! Rules,

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

PL Categories: Functional PLs Introduction to Haskell Haskell: Functions

PL Categories: Functional PLs Introduction to Haskell Haskell: Functions PL Categories: Functional PLs Introduction to Haskell Haskell: Functions CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, February 22, 2017 Glenn G. Chappell

More information

Intermediate Code Generation

Intermediate Code Generation Intermediate Code Generation In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target

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

CS 6353 Compiler Construction Project Assignments

CS 6353 Compiler Construction Project Assignments CS 6353 Compiler Construction Project Assignments In this project, you need to implement a compiler for a language defined in this handout. The programming language you need to use is C or C++ (and the

More information

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; } Ex: The difference between Compiler and Interpreter The interpreter actually carries out the computations specified in the source program. In other words, the output of a compiler is a program, whereas

More information

CS4215 Programming Language Implementation

CS4215 Programming Language Implementation CS4215 Programming Language Implementation You have 45 minutes to complete the exam. Use a B2 pencil to fill up the provided MCQ form. Leave Section A blank. Fill up Sections B and C. After finishing,

More information

COS 320. Compiling Techniques

COS 320. Compiling Techniques Topic 5: Types COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 Types: potential benefits (I) 2 For programmers: help to eliminate common programming mistakes, particularly

More information

Semantics of programming languages

Semantics of programming languages Semantics of programming languages Informatics 2A: Lecture 27 Alex Simpson School of Informatics University of Edinburgh als@inf.ed.ac.uk 18 November, 2014 1 / 18 Two parallel pipelines A large proportion

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

Where We Are. Lexical Analysis. Syntax Analysis. IR Generation. IR Optimization. Code Generation. Machine Code. Optimization.

Where We Are. Lexical Analysis. Syntax Analysis. IR Generation. IR Optimization. Code Generation. Machine Code. Optimization. Where We Are Source Code Lexical Analysis Syntax Analysis Semantic Analysis IR Generation IR Optimization Code Generation Optimization Machine Code Where We Are Source Code Lexical Analysis Syntax Analysis

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

Modules, Structs, Hashes, and Operational Semantics

Modules, Structs, Hashes, and Operational Semantics CS 152: Programming Language Paradigms Modules, Structs, Hashes, and Operational Semantics Prof. Tom Austin San José State University Lab Review (in-class) Modules Review Modules from HW 1 (in-class) How

More information

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics Recall Architecture of Compilers, Interpreters CMSC 330: Organization of Programming Languages Source Scanner Parser Static Analyzer Operational Semantics Intermediate Representation Front End Back End

More information

ECE251 Midterm practice questions, Fall 2010

ECE251 Midterm practice questions, Fall 2010 ECE251 Midterm practice questions, Fall 2010 Patrick Lam October 20, 2010 Bootstrapping In particular, say you have a compiler from C to Pascal which runs on x86, and you want to write a self-hosting Java

More information

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far

Lecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far Lecture Outline Operational Semantics of Cool Lecture 13 COOL operational semantics Motivation Notation The rules Prof. Aiken CS 143 Lecture 13 1 Prof. Aiken CS 143 Lecture 13 2 Motivation We must specify

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

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

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

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

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

IR Lowering. Notation. Lowering Methodology. Nested Expressions. Nested Statements CS412/CS413. Introduction to Compilers Tim Teitelbaum

IR Lowering. Notation. Lowering Methodology. Nested Expressions. Nested Statements CS412/CS413. Introduction to Compilers Tim Teitelbaum IR Lowering CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 19: Efficient IL Lowering 7 March 07 Use temporary variables for the translation Temporary variables in the Low IR store intermediate

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

7. Introduction to Denotational Semantics. Oscar Nierstrasz

7. Introduction to Denotational Semantics. Oscar Nierstrasz 7. Introduction to Denotational Semantics Oscar Nierstrasz Roadmap > Syntax and Semantics > Semantics of Expressions > Semantics of Assignment > Other Issues References > D. A. Schmidt, Denotational Semantics,

More information

CMSC 330: Organization of Programming Languages. Operational Semantics

CMSC 330: Organization of Programming Languages. Operational Semantics CMSC 330: Organization of Programming Languages Operational Semantics Notes about Project 4, Parts 1 & 2 Still due today (7/2) Will not be graded until 7/11 (along with Part 3) You are strongly encouraged

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

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 2010 P. N. Hilfinger CS 164: Final Examination (revised) Name: Login: You have

More information

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

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) Introduction This semester, through a project split into 3 phases, we are going

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

CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

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

Binary Search Trees Treesort

Binary Search Trees Treesort Treesort CS 311 Data Structures and Algorithms Lecture Slides Friday, November 13, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005 2009

More information

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 19: Efficient IL Lowering 5 March 08

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 19: Efficient IL Lowering 5 March 08 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 19: Efficient IL Lowering 5 March 08 CS 412/413 Spring 2008 Introduction to Compilers 1 IR Lowering Use temporary variables for the translation

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

What is a compiler? var a var b mov 3 a mov 4 r1 cmpi a r1 jge l_e mov 2 b jmp l_d l_e: mov 3 b l_d: ;done

What is a compiler? var a var b mov 3 a mov 4 r1 cmpi a r1 jge l_e mov 2 b jmp l_d l_e: mov 3 b l_d: ;done What is a compiler? What is a compiler? Traditionally: Program that analyzes and translates from a high level language (e.g., C++) to low-level assembly language that can be executed by hardware int a,

More information

LECTURE 18. Control Flow

LECTURE 18. Control Flow LECTURE 18 Control Flow CONTROL FLOW Sequencing: the execution of statements and evaluation of expressions is usually in the order in which they appear in a program text. Selection (or alternation): a

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

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

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; } Ex: The difference between Compiler and Interpreter The interpreter actually carries out the computations specified in the source program. In other words, the output of a compiler is a program, whereas

More information

Crafting a Compiler with C (II) Compiler V. S. Interpreter

Crafting a Compiler with C (II) Compiler V. S. Interpreter Crafting a Compiler with C (II) 資科系 林偉川 Compiler V S Interpreter Compilation - Translate high-level program to machine code Lexical Analyzer, Syntax Analyzer, Intermediate code generator(semantics Analyzer),

More information

CS4215 Programming Language Implementation. Martin Henz

CS4215 Programming Language Implementation. Martin Henz CS4215 Programming Language Implementation Martin Henz Thursday 15 March, 2012 2 Chapter 11 impl: A Simple Imperative Language 11.1 Introduction So far, we considered only languages, in which an identifier

More information

CS 3360 Design and Implementation of Programming Languages. Exam 1

CS 3360 Design and Implementation of Programming Languages. Exam 1 1 Spring 2017 (Thursday, March 9) Name: CS 3360 Design and Implementation of Programming Languages Exam 1 This test has 8 questions and pages numbered 1 through 7. Reminders This test is closed-notes and

More information

Principles of Programming Languages COMP251: Syntax and Grammars

Principles of Programming Languages COMP251: Syntax and Grammars Principles of Programming Languages COMP251: Syntax and Grammars Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology Hong Kong, China Fall 2007

More information

And Parallelism. Parallelism in Prolog. OR Parallelism

And Parallelism. Parallelism in Prolog. OR Parallelism Parallelism in Prolog And Parallelism One reason that Prolog is of interest to computer scientists is that its search mechanism lends itself to parallel evaluation. In fact, it supports two different kinds

More information

CS 351 Design of Large Programs Programming Abstractions

CS 351 Design of Large Programs Programming Abstractions CS 351 Design of Large Programs Programming Abstractions Brooke Chenoweth University of New Mexico Spring 2019 Searching for the Right Abstraction The language we speak relates to the way we think. The

More information

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without previous written authorization. 1 2 The simplest way to create

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

CS /534 Compiler Construction University of Massachusetts Lowell. NOTHING: A Language for Practice Implementation

CS /534 Compiler Construction University of Massachusetts Lowell. NOTHING: A Language for Practice Implementation CS 91.406/534 Compiler Construction University of Massachusetts Lowell Professor Li Xu Fall 2004 NOTHING: A Language for Practice Implementation 1 Introduction NOTHING is a programming language designed

More information

CGS 3066: Spring 2015 JavaScript Reference

CGS 3066: Spring 2015 JavaScript Reference CGS 3066: Spring 2015 JavaScript Reference Can also be used as a study guide. Only covers topics discussed in class. 1 Introduction JavaScript is a scripting language produced by Netscape for use within

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

Chapter 3 (part 3) Describing Syntax and Semantics

Chapter 3 (part 3) Describing Syntax and Semantics Chapter 3 (part 3) Describing Syntax and Semantics Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Attribute Grammars Describing the Meanings

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

Programming Languages and Compilers Qualifying Examination. Answer 4 of 6 questions.

Programming Languages and Compilers Qualifying Examination. Answer 4 of 6 questions. Programming Languages and Compilers Qualifying Examination Fall 2017 Answer 4 of 6 questions. GENERAL INSTRUCTIONS 1. Answer each question in a separate book. 2. Indicate on the cover of each book the

More information

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement Outline Expression Evaluation and Control Flow In Text: Chapter 6 Notation Operator evaluation order Operand evaluation order Overloaded operators Type conversions Short-circuit evaluation of conditions

More information

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 13: Types and Type-Checking 19 Feb 07 Semantic Analysis Last time: Semantic errors related to scopes Symbol tables Name resolution This lecture:

More information

Question Points Score

Question Points Score CS 453 Introduction to Compilers Midterm Examination Spring 2009 March 12, 2009 75 minutes (maximum) Closed Book You may use one side of one sheet (8.5x11) of paper with any notes you like. This exam has

More information

Semantic Analysis and Type Checking

Semantic Analysis and Type Checking Semantic Analysis and Type Checking The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus Types Type checking What is a type? The notion varies from language to language Consensus A set of values A set of operations on those values Classes are one instantiation of the modern notion of type

More information

COMP 410 Lecture 1. Kyle Dewey

COMP 410 Lecture 1. Kyle Dewey COMP 410 Lecture 1 Kyle Dewey About Me I research automated testing techniques and their intersection with CS education My dissertation used logic programming extensively This is my second semester at

More information

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards Language Reference Manual Introduction The purpose of

More information

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis The Compiler So Far Overview of Semantic Analysis Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Lexical analysis Detects inputs with illegal tokens Parsing Detects inputs with ill-formed

More information

Administration CS 412/413. Why build a compiler? Compilers. Architectural independence. Source-to-source translator

Administration CS 412/413. Why build a compiler? Compilers. Architectural independence. Source-to-source translator CS 412/413 Introduction to Compilers and Translators Andrew Myers Cornell University Administration Design reports due Friday Current demo schedule on web page send mail with preferred times if you haven

More information

CS 415 Midterm Exam Spring SOLUTION

CS 415 Midterm Exam Spring SOLUTION CS 415 Midterm Exam Spring 2005 - SOLUTION Name Email Address Student ID # Pledge: This exam is closed note, closed book. Questions will be graded on quality of answer. Please supply the best answer you

More information

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

More information

CS 6353 Compiler Construction Project Assignments

CS 6353 Compiler Construction Project Assignments CS 6353 Compiler Construction Project Assignments In this project, you need to implement a compiler for a language defined in this handout. The programming language you need to use is C or C++ (and the

More information

CS321 Languages and Compiler Design I. Winter 2012 Lecture 1

CS321 Languages and Compiler Design I. Winter 2012 Lecture 1 CS321 Languages and Compiler Design I Winter 2012 Lecture 1 1 COURSE GOALS Improve understanding of languages and machines. Learn practicalities of translation. Learn anatomy of programming languages.

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

In Our Last Exciting Episode

In Our Last Exciting Episode In Our Last Exciting Episode #1 Lessons From Model Checking To find bugs, we need specifications What are some good specifications? To convert a program into a model, we need predicates/invariants and

More information

CIS 341 Midterm March 2, 2017 SOLUTIONS

CIS 341 Midterm March 2, 2017 SOLUTIONS CIS 341 Midterm March 2, 2017 SOLUTIONS 1 1. True or False (14 points) Mark each statement as either true or false. a. T F The typical compiler consists of several phases, including: lexing, parsing, transformation

More information

SaM. 1. Introduction. 2. Stack Machine

SaM. 1. Introduction. 2. Stack Machine SaM 1. Introduction Have you ever heard the Java mantra, write once, run everywhere? So, how does that work? When you compile a Java program, you generate a binary file that contains byte-code. Byte-code

More information

Introduction to Scheme

Introduction to Scheme How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

More information