Compilation 2013 Semantic Analysis
|
|
- Cecilia Young
- 5 years ago
- Views:
Transcription
1 Compilation 2013 Semantic Analysis Erik Ernst Aarhus University
2 Semantic Analysis The meaning of a program: Above the contextfree level Use general programming to compute well-formedness representation resource management Types may represent several of these aspects exceptions exist, e.g., correct placement of break 2
3 Symbol Tables Re: A symbol table maps names to meanings in some context (e.g., the type) Names are declarations or applications, exting sym.tabs resp. looking up the meaning Static, lexical scoping stack discipline Need undo to recover sym.tab. after scope s 3
4 An Imperative Symbol Table Note that binding needs to vary with the purpose Note that arrays are mutable (no ref needed!) val SIZE = 109 type binding =... type bucket = (string * binding) list type table = bucket Array.array val t: table = Array.array (SIZE, nil) fun hash (s: string): int = CharVector.foldl (fn (c,n) => (n*256+ord(c)) mod SIZE) 0 s fun insert (s: string, b: binding) = let val i = hash s in Array.update (t, i, (s,b)::array.sub(t,i))... Semantic Analysis 4
5 Note that hash is called all the time Note: insert/pop calls must correspond exactly!... exception NotFound An Imperative Symbol Table fun lookup (s: string) = let val i = hash s fun search ((s,b)::rest) = if s=s' then b else search rest search nil = raise NotFound in search (Array.sub (t,i)) fun pop (s: string) = let val i = hash s val (s,b)::rest = Array.sub (t,i) in assert (s=s ); Array.update (t,i,rest) Semantic Analysis 5
6 Example: Symbol Table Stack Discipline Starting from σ 0 the environment changes at name declarations, σ 0 σ 1 σ 2 σ 3 σ 1 σ 0 Transitions like σ 0 σ 1 require adding: override Transitions like σ 1 σ 0 require undo (pop + ) {g string, a int} = σ 0 function f(a:int, b:int, c:int) = σ 0 + {a int, b int, c int} = σ 1 ( print_int(a+c) σ 1 ; let var j := a+b σ 1 + {j int} = σ 2 var a := "hello" σ 2 + {a string} = σ 3 in print(a); print_int(j) σ 3 σ 1 ; print_int(b)) σ 0 σ 0 6
7 Symbol Table Stack Discipline Using a functional approach: Transition σ 0 σ 1, adding: build new, use sharing Transition σ 1 σ 0, undo : simply use older table again Safe, simple, used for Tiger but do use the right one! {g string, a int} = σ 0 function f(a:int, b:int, c:int) = σ 0 + {a int, b int, c int} = σ 1 ( print_int(a+c) σ 1 ; let var j := a+b σ 1 + {j int} = σ 2 var a := "hello" σ 2 + {a string} = σ 3 in print(a); print_int(j) σ 3 σ 1 ; print_int(b)) σ 0 σ 0 7
8 Tiger Compiler Symbol Table Signature SYMBOL NB: table polymorphic, symbol eqtype signature SYMBOL = sig eqtype symbol val symbol: string -> symbol val name: symbol -> string type 'a table val empty: 'a table val enter: 'a table * symbol * 'a -> 'a table val look: 'a table * symbol -> 'a option Semantic Analysis 8
9 Tiger Compiler Symbol Table structure Symbol :> SYMBOL = struct structure HT = HashTable structure HS = HashString type symbol = string * int exception Symbol val nextsym = ref 0 val hashtable: (string, int) HT.hash_table = HT.mkTable (HS.hashString, op= ) (128, Symbol) fun symbol name = case HT.find hashtable name of SOME i => (name, i) NONE => let val i =!nextsym in nextsym := i+1; HT.insert hashtable (name, i); (name, i) fun name (s, n) = s type 'a table = 'a IntBinaryMap.map val empty = IntBinaryMap.empty fun enter (t, (s,n), a) = IntBinaryMap.insert (t, n, a) fun look (t, (s,n)) = IntBinaryMap.look (t, n) structures types, exc state functions symbol tables! Semantic Analysis 9
10 Tiger Compiler Symbol Table structure Symbol :> SYMBOL = struct structure HT = HashTable structure HS = HashString type symbol = string * int exception Symbol val nextsym = ref 0 val hashtable: (string, int) HT.hash_table = HT.mkTable (HS.hashString, op= ) (128, Symbol) fun symbol name = case HT.find hashtable name of SOME i => (name, i) NONE => let val i =!nextsym in nextsym := i+1; HT.insert hashtable (name, i); (name, i) fun name (s, n) = s type 'a table = 'a IntBinaryMap.map val empty = IntBinaryMap.empty fun enter (t, (s,n), a) = IntBinaryMap.insert (t, n, a) fun look (t, (s,n)) = IntBinaryMap.look (t, n) Semantic Analysis structures types, exc state functions symbol tables! NB: The symbol is the int 9
11 Representation of Types Almost enough to mimic the syntax but note uniqueness and error structure Types : TYPES = struct type unique = unit ref datatype ty = INT STRING RECORD of (Symbol.symbol * ty) list * unique ARRAY of ty * unique NIL UNIT NAME of Symbol.symbol * ty option ref ERROR (* ambiguity exists due to type error *) 10
12 Unique : Nominal Type Equivalence Nominal type equivalence known from Java etc.: class C1 {.. /* some declarations */..} class C2 {.. /* identical to C1, rename as needed */..} Even though declarations are identical, these classes are not the same type Tiger uses nominal type eq. for records and arrays: unit ref is always a unique value structure Types : TYPES = struct type unique = unit ref datatype ty =... RECORD of (Symbol.symbol * ty) list * unique ARRAY of ty * unique... 11
13 Representation of Environments Note incompleteness (formals: only types) Will return to access later signature ENV = sig type access type ty = Types.ty datatype enventry = VarEntry of {ty: ty} FunEntry of {formals: ty list, result: ty} val base_tenv: ty Symbol.table val base_venv: enventry Symbol.table 12
14 Top-down & bottom-up Type-checking Basics type of name application from environment, top-down type of composite (e.g., expression) built inductively Basic definitions for Tiger (Re: namespaces): type tenv = Types.ty Symbol.table type venv = Env.enventry Symbol.table type expty = {exp: Translate.exp, ty: Types.ty} transty: tenv * Absyn.ty -> Types.ty transvar: venv * tenv * Absyn.var -> expty transexp: venv * tenv * Absyn.exp -> expty transdec: venv * tenv * Absyn.dec -> {venv: venv, tenv: tenv} structure Translate = struct type exp = unit /* dummy, will be elaborated later */ 13
15 Type-checking Expressions: Bottom-up Bottom-up analysis ~ proof by induction Pattern matching ( left vs. oper=.., using _) fun transexp ( venv, tenv, Absyn.OpExp {left,oper=absyn.plusop,right,pos}) = let val {exp=_, ty=tyleft} = transexp (venv, tenv, left) val {exp=_, ty=tyright} = transexp (venv, tenv, right) in case tyleft of Types.INT => () _ => error pos "integer required"; case tyright of Types.INT => () _ => error pos "integer required" {exp=(), ty=types.int} Semantic Analysis 14
16 Reorganizing transexp structure A = Absyn fun checkint ({exp,ty},pos) = (...) fun transexp (venv, tenv) = let fun trexp (A.OpExp {left,oper=absyn.plusop,right,pos}) = ( checkint (trexp left, pos) ; checkint (trexp right, pos) ; {exp=(), ty=types.int}) fun trexp (A.RecordExp...) = and fun trvar (A.SimpleVar (id, pos)) = (case Symbol.look (venv, id) of SOME (E.VarEntry {ty}) => {exp=(), ty = actualty ty} NONE => (error pos "Undefined variable " ^ S.name id; {exp=(), ty=types.error}) trvar (A.FieldVar (v, id, pos)) =... in trexp Semantic Analysis NB: transexp now curried => missing 3rd argument 15
17 Type-checking Declarations General Tiger declarations are in let Below: Simple general treatment, complexity in cases Variable declarations: Easy Type declarations: Consider an easy case Function declarations: Consider an even easier case ;-) fun transexp (venv, tenv) =... trexp (A.LetExp {decs,body,pos}) = let val {venv=venv', tenv=tenv'} = transdecs (venv, tenv, decs) in transexp (venv', tenv') body... Semantic Analysis 16
18 Type-checking Variable Declarations Variable declaration: Easy! Basic idea: Declaration = environment transformer Consider treatment of var x := e fun transdec ( venv, tenv, A.VarDec {name, typ=none, init,...}) = let val {exp,ty} = transexp (venv, tenv) init in { tenv = tenv, venv = S.enter ( venv, name, E.VarEntry {ty=ty})} NB: We need another pattern typ=.. to handle var x: T := e Semantic Analysis 17
19 Type-checking Type Declarations Focus on easy case! just one type Idea: Transform syntax to meaning transdec (venv, tenv, A.TypeDec [{name,ty}]) = { venv = venv, tenv = S.enter ( tenv, name, transty (tenv, ty))} Note lack of generality Recursion: Later structure Types : TYPES = struct type unique = unit ref datatype ty = INT STRING RECORD of (Symbol.symbol * ty) list * unique ARRAY of ty * unique NIL UNIT NAME of Symbol.symbol * ty option ref ERROR Semantic Analysis 18
20 Translating Type Expressions Mainly a cleanup job just construct the obvious Types.ty from the given Absyn.TypeDec NB: Just a skeleton several times more code with error checking fun transty (tenv, t) = let fun getfieldty {name, typ,...} = (name, S.look tenv (#1 typ)) fun getfieldtys fields = map getfieldty fields in case t of A.NameTy (sym, pos) => S.look tenv sym A.RecordTy fields => Ty.RECORD (getfieldtys fields, ref ()) A.ArrayTy (sym, pos) => Ty.ARRAY (S.look tenv sym, ref ()) Semantic Analysis 19
21 Type-checking a Function Declaration Lots of stuff to consider! Simple case here. Basic idea: Deal with all syntactic elements transdec (venv, tenv, A.FunctionDec [{ name, params, body, pos,, result = SOME (rt,pos)}]) = let val SOME resultty = S.look (tenv, rt) fun transparam {name, typ, pos} = case S.look (tenv, typ) of SOME t => {name = name, ty = t} val params' = map transparam params val venv' = S.enter ( venv, name, E.FunEntry { formals = maps #ty params', result = resultty}) fun enterparam ({name,ty}, venv) = S.enter (venv, name, E.VarEntry {access = (), ty = ty}) val venv'' = foldl enterparam params' venv' in transexp (venv'', tenv) body; {venv = venv', tenv = tenv} Semantic Analysis 20
22 Type-checking a Function Declaration Incompleteness of this solution: Only one function (singleton list) No recursion (self or mutual) No error handling (check SOME t ) No type check on returned value Complete solution systematically built from this Semantic Analysis 21
23 Supporting Recursion Crucial feature with recursive data types ( anything having unbounded size ) Two-phase approach: Visit all mutually recursive declarations, add header Revisit declarations, check body Requires circular data ( enable unlimited walk ) Cannot be built bottom-up, only trees can: Need mutable state! 22
24 Recursion Enabler: Types.NAME NAME types forward to other types Note option: May be unresolved type list = {first: int, rest: list} Initial tenv entry: type list =?, i.e.: tenv' = S.enter( tenv, name, NAME (name, ref NONE)) Call transty on {first: int, rest: list} with tenv' as type environment After both phases: cyclic structure in place structure Types : TYPES = struct type unique = unit ref datatype ty = INT STRING RECORD of (Symbol.symbol * ty) list * unique ARRAY of ty * unique NIL UNIT NAME of Symbol.symbol * ty option ref ERROR 23
25 Type Checking as Inference Rules Idea: Premises (top) imply conclusion (bottom) If e 1 has type INT and e 2 has type INT, then e 1 + e 2 has type INT The system is not complete, e.g., we do not handle declarations Δ;Γ e 1 :INT Δ;Γ e 2 :INT Δ;Γ e 1 + e 2 :INT 24
26 Inference Rules vs Implementation Each premise and conclusion is a judgment Environments given to the left of each judgment Syntax corresponds to Absyn values Types correspond to Types values Δ;Γ e 1 :INT Δ;Γ e 2 :INT Δ;Γ e 1 + e 2 :INT tenv venv Absyn.OpExp {..PlusOp..} Types.ty 25
27 Inference Rules vs Implementation Environment lookup corresponds to simple rules Note use of actualty to eliminate NAME types val (SOME Env.VarEntry {ty}) = Symbol.look (venv, sym) val ty = actualty ty sym venv Γ(x) = T Δ;Γ x:t ty 26
28 Inference Rule: If-then Illustrating valueless expression, multiple types Δ;Γ e 1 :INT Δ;Γ e 2 :UNIT Δ;Γ if e 1 then e 2 : UNIT 27
29 Inference Rule: If-then-else Illustrating the use of a type variable: T can be any well-formed type Δ;Γ e 1 :INT Δ;Γ e 2 :T Δ;Γ e 3 :T Δ;Γ if e 1 then e 2 else e 3 : T 28
30 Inference Rule: If-then-else Illustrating the use of a type variable: T can be any well-formed type Δ;Γ e 1 :INT Δ;Γ e 2 :T Δ;Γ e 3 :T Δ;Γ if e 1 then e 2 else e 3 : T (NB: Subsumed by later rules!) 28
31 Inference Rule: Wrong addition Illustrating simple error handling: Report error because addition is incorrect, but use type INT in conclusion because no other type is possible in corrected program Δ;Γ e 1 :S Δ;Γ e 2 :T S INT T INT Δ;Γ e 1 + e 2 :INT 29
32 Checking Type-correct Equality Δ;Γ e 1 :S Δ;Γ e 2 :T eqok(s,t ) Δ;Γ e 1 = e 2 : INT fun eqok (INT,INT) = true... (* + other simple cases, except (NIL,NIL) *) eqok (RECORD (_,u1), RECORD (_,u2)) = (u1=u2) eqok (RECORD _, NIL) = true eqok (NIL, RECORD _) = true... eqok (ERROR,_) = true (* no error message: has *) eqok (_,ERROR) = true (* been reported already *) eqok _ = false eqok as premise: Rule only applicable when eqok true 30
33 Checking Type-incorrect Equality Δ;Γ e 1 :S Δ;Γ e 2 :T eqok(s,t ) Δ;Γ e 1 = e 2 : INT fun eqok (INT,INT) = true... (* + other simple cases, except (NIL,NIL) *) eqok (RECORD (_,u1), RECORD (_,u2)) = (u1=u2) eqok (RECORD _, NIL) = true eqok (NIL, RECORD _) = true... eqok (ERROR,_) = true (* no error message: has *) eqok (_,ERROR) = true (* been reported already *) eqok _ = false Report error: Error always introduced when eqok 31
34 Checking if-then-else with OK Guard Improving on earlier rule Δ;Γ e 1 :INT Δ;Γ e 2 :S Δ;Γ e 3 :T U = ifcomb(s,t ) Δ;Γ if e 1 then e 2 else e 3 : U fun ifcomb (ERROR,_) = ERROR ifcomb (_,ERROR) = ERROR ifcomb (S as RECORD _, NIL) = S ifcomb (NIL, T as RECORD _) = T... ifcomb (S,T) = if S=T then S else ERROR Report error if introduced 32
35 Checking If-then-else with Wrong Guard Δ;Γ e 1 :T Δ;Γ e 2 :S Δ;Γ e 3 :T T INT U = ifcombw(s,t ) Δ;Γ if e 1 then e 2 else e 3 : U fun ifcombw (S,T) = if S=T then S else ERROR Report error that guard is not INT unless ERROR already Possibly report error for differently typed if-branches 33
36 Inference Rule: Function Call Illustrating a variable number of premises Note that we check both the number of arguments and the type of each of them Note that we can add f to the environment Γ when checking the body of f itself: Two phases.. Γ(f)= S 1 S k T Δ;Γ e i :S i for i=1 k Δ;Γ f(e 1 e k ): T 34
37 Summary Semantic analysis: Above CFG, general Major element: Type-checking: well-formedness, representation, choice of variant,... Tool: Symbol table (imp./func.), stack discipline Representation of types, environments Bottom-up type-checking: Expressions Top-down: Environments, name applications Type-checking declarations Recursion: Header phase + Body phase + NAME Inference rules: Concise and useful notation 35
Connecting Definition and Use? Tiger Semantic Analysis. Symbol Tables. Symbol Tables (cont d)
Tiger source program Tiger Semantic Analysis lexical analyzer report all lexical errors token get next token parser construct variable deinitions to their uses report all syntactic errors absyn checks
More informationThe 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 informationTopic 7: Intermediate Representations
Topic 7: Intermediate Representations COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 2 Intermediate Representations 3 Intermediate Representations 4 Intermediate Representations
More informationAgenda. CS301 Session 9. Abstract syntax: top level. Abstract syntax: expressions. The uscheme interpreter. Approaches to solving the homework problem
CS301 Session 9 The uscheme interpreter Agenda Approaches to solving the homework problem 1 2 Abstract syntax: top level datatype toplevel = EXP of exp DEFINE of name * lambda VAL of name * exp USE of
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Operational Semantics CMSC 330 Summer 2018 1 Formal Semantics of a Prog. Lang. Mathematical description of the meaning of programs written in that language
More informationCMSC 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 informationCSE 341 Section 5. Winter 2018
CSE 341 Section 5 Winter 2018 Midterm Review! Variable Bindings, Shadowing, Let Expressions Boolean, Comparison and Arithmetic Operations Equality Types Types, Datatypes, Type synonyms Tuples, Records
More informationDefining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona
Defining Functions CSc 372 Comparative Programming Languages 5 : Haskell Function Definitions Department of Computer Science University of Arizona collberg@gmail.com When programming in a functional language
More informationCS1622. 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 informationLecture 15 CIS 341: COMPILERS
Lecture 15 CIS 341: COMPILERS Announcements HW4: OAT v. 1.0 Parsing & basic code generation Due: March 28 th No lecture on Thursday, March 22 Dr. Z will be away Zdancewic CIS 341: Compilers 2 Adding Integers
More informationCOS 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 informationProgramming Languages Assignment #7
Programming Languages Assignment #7 December 2, 2007 1 Introduction This assignment has 20 points total. In this assignment, you will write a type-checker for the PolyMinML language (a language that is
More information6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson
6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator
More informationCompilation 2014 Activation Records
Compilation 2014 Activation Records Aslan Askarov aslan@cs.au.dk Revised from slides by E. Ernst (Abstract) computer organization Program memory code segment contains program text data segment contains
More informationA Functional Evaluation Model
A Functional Evaluation Model COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel A Functional Evaluation Model In order to be able to write a program,
More informationHandout 2 August 25, 2008
CS 502: Compiling and Programming Systems Handout 2 August 25, 2008 Project The project you will implement will be a subset of Standard ML called Mini-ML. While Mini- ML shares strong syntactic and semantic
More informationClosures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming
Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming Summary 1. Predictive Parsing 2. Large Step Operational Semantics (Natural) 3. Small Step Operational Semantics
More informationMid-Term 2 Grades
Mid-Term 2 Grades 100 46 1 HW 9 Homework 9, in untyped class interpreter: Add instanceof Restrict field access to local class Implement overloading (based on argument count) Due date is the same as for
More informationLists. Michael P. Fourman. February 2, 2010
Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce
More informationMeanings of syntax. Norman Ramsey Geoffrey Mainland. COMP 105 Programming Languages Tufts University. January 26, 2015
Meanings of syntax Norman Ramsey Geoffrey Mainland COMP 105 Programming Languages Tufts University January 26, 2015 (COMP 105) Meanings of syntax January 26, 2015 1 / 33 What is the meaning of a while
More informationType Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413
Type Inference Systems CS412/CS413 Introduction to Compilers Tim Teitelbaum Type inference systems define types for all legal programs in a language Type inference systems are to type-checking: As regular
More informationIntroduction to OCaml
Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional
More informationCompilation 2013 Translation to IR
Compilation 2013 Erik Ernst Aarhus University Intermediate Representation Translation source/target uses IR as a bridge Simplification: n+m combinations, not n m Java SML Pascal C C++ SPARC MIPS Pentium
More informationCSE-321 Programming Languages 2010 Midterm
Name: Hemos ID: CSE-321 Programming Languages 2010 Midterm Score Prob 1 Prob 2 Prob 3 Prob 4 Total Max 15 30 35 20 100 1 1 SML Programming [15 pts] Question 1. [5 pts] Give a tail recursive implementation
More informationOCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java
OCaml Data : Organization of Programming Languages OCaml 4 Data Types & Modules So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure
More informationCMSC 330: Organization of Programming Languages. OCaml Imperative Programming
CMSC 330: Organization of Programming Languages OCaml Imperative Programming CMSC330 Fall 2017 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory All
More informationPierce Ch. 3, 8, 11, 15. Type Systems
Pierce Ch. 3, 8, 11, 15 Type Systems Goals Define the simple language of expressions A small subset of Lisp, with minor modifications Define the type system of this language Mathematical definition using
More informationCompiler 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 informationCMSC 330: Organization of Programming Languages. Functional Programming with Lists
CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as
More informationDatatype declarations
Datatype declarations datatype suit = HEARTS DIAMONDS CLUBS SPADES datatype a list = nil (* copy me NOT! *) op :: of a * a list datatype a heap = EHEAP HEAP of a * a heap * a heap type suit val HEARTS
More informationClosures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming
Closures Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming t ::= x x. t t t Call-by-value big-step Operational Semantics terms variable v ::= values abstraction x.
More informationFunctional Programming. Pure Functional Programming
Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).
More informationThe 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 informationCMSC 330, Fall 2013, Practice Problem 3 Solutions
CMSC 330, Fall 2013, Practice Problem 3 Solutions 1. OCaml and Functional Programming a. Define functional programming Programs are expression evaluations b. Define imperative programming Programs change
More informationA Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1
A Third Look At ML Chapter Nine Modern Programming Languages, 2nd ed. 1 Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order
More informationLecture #23: Conversion and Type Inference
Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:
More informationCS4215 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 informationCSE-321 Programming Languages 2012 Midterm
Name: Hemos ID: CSE-321 Programming Languages 2012 Midterm Prob 1 Prob 2 Prob 3 Prob 4 Prob 5 Prob 6 Total Score Max 14 15 29 20 7 15 100 There are six problems on 24 pages in this exam. The maximum score
More informationTopics Covered Thus Far CMSC 330: Organization of Programming Languages
Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free
More informationConversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";
Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";
More informationCS4215 Programming Language Implementation. Martin Henz
CS4215 Programming Language Implementation Martin Henz Thursday 26 January, 2012 2 Chapter 4 The Language simpl In this chapter, we are exting the language epl in order to provide a more powerful programming
More informationCSE 130 [Winter 2014] Programming Languages
CSE 130 [Winter 2014] Programming Languages Introduction to OCaml (Continued) Ravi Chugh! Jan 14 Announcements HW #1 due Mon Jan 20 Post questions/discussion to Piazza Check Piazza for TA/Tutor lab hours
More informationFlang typechecker Due: February 27, 2015
CMSC 22610 Winter 2015 Implementation of Computer Languages I Flang typechecker Due: February 27, 2015 Project 3 February 9, 2015 1 Introduction The third project is to implement a type checker for Flang,
More informationCompiler construction
Compiler construction Martin Steffen March 13, 2017 Contents 1 Abstract 1 1.1 Symbol tables. 1 1.1.1 Introduction 1 1.1.2 Symbol table design and interface.. 2 1.1.3 Implementing symbol tables 3 1.1.4
More informationFunctional Languages. CSE 307 Principles of Programming Languages Stony Brook University
Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work
More informationThe PCAT Programming Language Reference Manual
The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language
More informationOCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.
OCaml The PL for the discerning hacker. ML Flow Expressions (Syntax) Compile-time Static 1. Enter expression 2. ML infers a type Exec-time Dynamic Types 3. ML crunches expression down to a value 4. Value
More informationStandard ML. Data types. ML Datatypes.1
Standard ML Data types ML Datatypes.1 Concrete Datatypes The datatype declaration creates new types These are concrete data types, not abstract Concrete datatypes can be inspected - constructed and taken
More informationBindex: Naming, Free Variables, and Environments SOLUTIONS
Review: Scope and Lexical Contours Bindex: Naming, Free Variables, and Environments CS251 Programming Languages Fall 2018, Lyn Turbak Department of Computer Science Wellesley College scope = area of program
More informationFunctional programming Primer I
Functional programming Primer I COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 Characteristics of functional programming Primary notions: functions and expressions (not
More informationCS558 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 informationPrinciples of Programming Languages
Principles of Programming Languages Lesson 14 Type Checking Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172 1 Type Checking We return to the issue of type safety we discussed informally,
More informationCS 11 Haskell track: lecture 1
CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of
More informationLecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.
Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)
More informationHOT Compilation: Elaboration
HOT Compilation: Elaboration TA: Akiva Leffert - aleffert@andrew.cmu.edu Out: Wednesday, October 25, 2005 Due: Wednesday, November 8, 2005 (before midnight) 1 Introduction Elaboration is the first phase
More informationInduction and Semantics in Dafny
15-414 Lecture 11 1 Instructor: Matt Fredrikson Induction and Semantics in Dafny TA: Ryan Wagner Encoding the syntax of Imp Recall the abstract syntax of Imp: a AExp ::= n Z x Var a 1 + a 2 b BExp ::=
More informationCS558 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 informationCMSC 330: Organization of Programming Languages. OCaml Imperative Programming
CMSC 330: Organization of Programming Languages OCaml Imperative Programming CMSC330 Spring 2018 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory
More informationSemantic 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 informationCVO103: Programming Languages. Lecture 5 Design and Implementation of PLs (1) Expressions
CVO103: Programming Languages Lecture 5 Design and Implementation of PLs (1) Expressions Hakjoo Oh 2018 Spring Hakjoo Oh CVO103 2018 Spring, Lecture 5 April 3, 2018 1 / 23 Plan Part 1 (Preliminaries):
More informationCS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011
CS152: Programming Languages Lecture 11 STLC Extensions and Related Topics Dan Grossman Spring 2011 Review e ::= λx. e x e e c v ::= λx. e c τ ::= int τ τ Γ ::= Γ, x : τ (λx. e) v e[v/x] e 1 e 1 e 1 e
More informationSemantic 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 informationCS4120/4121/5120/5121 Spring 2018 Xi Type System Specification Cornell University Version of February 18, 2018
CS4120/4121/5120/5121 Spring 2018 Xi Type System Specification Cornell University Version of February 18, 2018 0 Changes 2/16: Added typing rule for empty blocks 1 Types The Xi type system uses a somewhat
More informationCA 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 informationProgramming Language Concepts, cs2104 Lecture 04 ( )
Programming Language Concepts, cs2104 Lecture 04 (2003-08-29) Seif Haridi Department of Computer Science, NUS haridi@comp.nus.edu.sg 2003-09-05 S. Haridi, CS2104, L04 (slides: C. Schulte, S. Haridi) 1
More informationCSCI-GA Scripting Languages
CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation
More informationCMSC 330: Organization of Programming Languages. Functional Programming with Lists
CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure
More informationUNIVERSITY 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 informationChapter 11 :: Functional Languages
Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative
More informationScope. Chapter Ten Modern Programming Languages 1
Scope Chapter Ten Modern Programming Languages 1 Reusing Names Scope is trivial if you have a unique name for everything: fun square a = a * a; fun double b = b + b; But in modern languages, we often use
More informationTwo approaches to writing interfaces
Two approaches to writing interfaces Interface projected from implementation: No separate interface Compiler extracts from implementation (CLU, Java class, Haskell) When code changes, must extract again
More informationOutline. What is semantics? Denotational semantics. Semantics of naming. What is semantics? 2 / 21
Semantics 1 / 21 Outline What is semantics? Denotational semantics Semantics of naming What is semantics? 2 / 21 What is the meaning of a program? Recall: aspects of a language syntax: the structure of
More informationPattern Matching and Abstract Data Types
Pattern Matching and Abstract Data Types Tom Murphy VII 3 Dec 2002 0-0 Outline Problem Setup Views ( Views: A Way For Pattern Matching To Cohabit With Data Abstraction, Wadler, 1986) Active Patterns (
More informationCSE-321: Assignment 8 (100 points)
CSE-321: Assignment 8 (100 points) gla@postech.ac.kr Welcome to the final assignment of CSE-321! In this assignment, you will implement a type reconstruction algorithm (the algorithm W discussed in class)
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 10 Thomas Wies New York University Review Last class ML Outline Modules Sources: PLP, 3.3.4, 3.3.5, 3.8 McConnell, Steve. Code Complete, Second Edition,
More informationCS558 Programming Languages. Winter 2013 Lecture 3
CS558 Programming Languages Winter 2013 Lecture 3 1 NAMES AND BINDING One essential part of being a high-level language is having convenient names for things: variables constants types functions etc. classes
More informationIntroduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming
Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming Typed Lambda Calculus Chapter 9 Benjamin Pierce Types and Programming Languages Call-by-value Operational Semantics
More informationDenotational Semantics. Domain Theory
Denotational Semantics and Domain Theory 1 / 51 Outline Denotational Semantics Basic Domain Theory Introduction and history Primitive and lifted domains Sum and product domains Function domains Meaning
More informationPrograms as data first-order functional language type checking
Programs as data first-order functional language type checking Copyright 2013-18, Peter Sestoft and Cesare Tinelli. Created by Cesare Tinelli at the University of Iowa from notes originally developed by
More informationCompilers and computer architecture: Semantic analysis
1 / 1 Compilers and computer architecture: Semantic analysis Martin Berger Alex Jeffery October 2018 Recall the function of compilers 2 / 1 3 / 1 Recall the structure of compilers Source program Lexical
More informationTopics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited
CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation
More informationSemantic 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 informationProgramming Paradigms
PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE
More informationBindex: Naming, Free Variables, and Environments
Review: Scope and Lexical Contours Bindex: Naming, Free Variables, and Environments scope = area of program where declared name can be used. Show scope in Racket via lexical contours in scope diagrams.
More informationHomework 3 COSE212, Fall 2018
Homework 3 COSE212, Fall 2018 Hakjoo Oh Due: 10/28, 24:00 Problem 1 (100pts) Let us design and implement a programming language called ML. ML is a small yet Turing-complete functional language that supports
More informationSemantic Analysis Type Checking
Semantic Analysis Type Checking Maryam Siahbani CMPT 379 * Slides are modified version of Schwarz s compiler course at Stanford 4/8/2016 1 Type Checking Type errors arise when operations are performed
More informationCMSC 430 Introduction to Compilers. Fall Everything (else) you always wanted to know about OCaml (but were afraid to ask)
CMSC 430 Introduction to Compilers Fall 2015 Everything (else) you always wanted to know about OCaml (but were afraid to ask) OCaml You know it well from CMSC 330 All programming projects will be in OCaml
More informationCSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)
CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent
More informationComputer Science Department Carlos III University of Madrid Leganés (Spain) David Griol Barres
Computer Science Department Carlos III University of Madrid Leganés (Spain) David Griol Barres dgriol@inf.uc3m.es Introduction He am a driver might be syntactically correct but semantically wrong. Semantic
More informationCornell University 12 Oct Solutions. (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below.
Cornell University 12 Oct 2006 Solutions 1. Types, Polymorphism [14 pts] (parts a b) (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below. i. fun f x y = (y,
More informationCSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013
CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging
More informationBegin at the beginning
Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of
More informationDecaf Language Reference
Decaf Language Reference Mike Lam, James Madison University Fall 2016 1 Introduction Decaf is an imperative language similar to Java or C, but is greatly simplified compared to those languages. It will
More informationCSCC24 Functional Programming Typing, Scope, Exceptions ML
CSCC24 Functional Programming Typing, Scope, Exceptions ML Carolyn MacLeod 1 winter 2012 1 Based on slides by Anya Tafliovich, with many thanks to Gerald Penn and Sheila McIlraith. motivation Consider
More informationPart VI. Imperative Functional Programming
Part VI Imperative Functional Programming Chapter 14 Mutable Storage MinML is said to be a pure language because the execution model consists entirely of evaluating an expression for its value. ML is
More informationInformal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility
Informal Semantics of Data semantic specification names (identifiers) attributes binding declarations scope rules visibility 1 Ways to Specify Semantics Standards Documents (Language Definition) Language
More informationLecture 11: Subprograms & their implementation. Subprograms. Parameters
Lecture 11: Subprograms & their implementation Subprograms Parameter passing Activation records The run-time stack Implementation of static and dynamic scope rules Subprograms A subprogram is a piece of
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions
More informationType 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 informationFOFL and FOBS: First-Order Functions
CS251 Programming Languages Handout # 35 Prof. Lyn Turbak April 14, 2005 Wellesley College Revised April 24, 2005 FOFL and FOBS: First-Order Functions Revisions: Apr 24 : In the interpreters for Fofl and
More information