Where we are SEMANTIC ANALYSIS. ! Program is lexically well- formed: ! Program is syntac,cally well- formed:

Size: px
Start display at page:

Download "Where we are SEMANTIC ANALYSIS. ! Program is lexically well- formed: ! Program is syntac,cally well- formed:"

Transcription

1 SEMANTIC ANALYSIS Where we are! Program is lexically well- formed: o Iden:fiers have valid names. o Strings are properly terminated.! Program is syntac,cally well- formed: o Class declara:ons have the correct structure.! Expressions are syntac:cally valid.! Does this mean that the program is legal? 1

2 2

3 Seman:c Analysis! Seman:c Analysis Ensure that the program has a well- defined meaning. o Verify proper:es of the program that aren't caught during the earlier phases: o Variables are declared before they're used. o Expressions have the right types. o Arrays can only be instan:ated with NewArray. o Classes don't inherit from nonexistent base classes! Once we finish seman:c analysis, we know that the user's input program is legal. Challenge! Reject the largest number of incorrect programs.! Accept the largest number of correct programs. 3

4 Validity vs Correctness 4

5 Seman:c Analysis! Gather useful informa:on about program for later phases: o Determine what variables are meant by each iden:fier. o Build an internal representa:on of inheritance hierarchies. o Count how many variables are in scope at each point. 5

6 ! Using CFGs: Limits of CFG o How would you prevent duplicate class defini:ons? o How would you differen:ate variables of one type from variables of another type? o How would you ensure classes implement all interface methods?! For most programming languages, these are provably impossible. o Use the pumping lemma for context- free languages CFGs do not suffice! Let y: String abc in y + 3! Let y: Int in x + 3! An example property that is not context free. 6

7 Implemen:ng Seman:c Analysis! A6ribute Grammars o Approach suggested in the Compilers book.! Recursive AST Walk o Construct the AST, then use recursion to explore the tree. SCOPE, AGAIN 7

8 ! The same name in a program may refer to fundamentally different things:! This is perfectly legal Java code: 8

9 Symbol Table! A symbol table is a mapping from a name to the thing that name refers to.! As we run our seman:c analysis, con:nuously update the symbol table with informa:on about what is in scope.! Ques:ons: o What does this look like in prac:ce? o What opera:ons need to be defined on it? o How do we implement it? 9

10 10

11 11

12 12

13 Symbol Table! Typically implemented as a stack of maps. o Each map corresponds to a par:cular scope.! Stack allows for easy enter and exit opera:ons.! Symbol table opera:ons are! Push scope: Enter a new scope. Pop scope: Leave a scope, discarding all declara:ons in it.! Insert symbol: Add a new entry to the current scope.! Lookup symbol: Find what a name corresponds to. Using Symbol Table! To process a por:on of the program that creates a scope (block statements, func:on calls, classes, etc.)! Enter a new scope.! Add all variable declara:ons to the symbol table. Process the body of the block/func:on/class.! Exit the scope. 13

14 14

15 Spagheh Stack! Treat the symbol table as a linked structure of scopes.! Each scope stores a pointer to its parents, but not vice- versa.! From any point in the program, symbol table appears to be a stack.! This is called a spaghej stack. 15

16 16

17 TYPES What is a type! What is a type? The no:on varies from language to language! Consensus A set of values A set of opera:ons on those values! Classes are one instan:a:on of the modern no:on of type 17

18 Types! Certain opera:ons are legal for values of each type o It doesn t make sense to add a func:on pointer and an integer in C o It does make sense to add two integers! But both have the same assembly language implementa:on! Type Systems! A language s type system specifies which opera:ons are valid for which types! The goal of type checking is to ensure that opera:ons are used with the correct types! Enforces intended interpreta:on of values, because nothing else will! 18

19 Type Checking! Sta:cally typed: All or almost all checking of types is done as part of compila:on (C, Java, C#)! Dynamically typed: Almost all checking of types is done as part of program execu:on (LISP)! Untyped: No type checking (machine code) The type war! Sta:c typing proponents say: o Sta:c checking catches many programming errors at compile :me o Avoids overhead of run:me typechecks! Dynamic typing proponents say: o Sta:c type systems are restric:ve o Rapid prototyping difficult within a sta:c type system 19

20 Type Checking vs Type Inference! Type Checking is the process of verifying fully typed programs! Type Inference is the process of filling in missing type informa:on! The two are different, but the terms are onen used interchangeably Sta:cs! Aner parsing, we have an AST.! Cri:cal issue: o not all opera:ons are defined on all values. o e.g., (3 / 0), sub("foo",5), 42(x)! Op:ons 1. don't worry about it (C, C++, etc.) 2. force all opera:ons to be total (Scheme) e.g., (3 / 0) - > 0, 42(x) - > try to rule out ill- formed expressions (ML) 20

21 Type Soundness! Construct a model of the source language o i.e., interpreter o This tells us where opera:ons are par:al. o And par:ality is different for different languages (e.g., "foo" + "bar" may be meaningful in some languages, but not others.)! Construct a func:on TC: AST - > bool o when true, should ensure interpre:ng the AST does not result in an undefined opera:on.! Prove that TC is correct. 21

22 22

23 23

24 Simple Language: type tipe = Int_t Fn_t of tipe*tipe Pair_t of tipe*tipe type exp = Var of var Int of int Plus_i of exp*exp Lambda of var * tipe * exp App of exp*exp Pair of exp * exp Fst of exp Snd of exp Interpreter: let rec interp (env:var->value)(e:exp) = match e with Var x -> env x Int I -> Int_v i Plus_i(e1,e2) -> (match interp env e1, interp env e2 of Int i, Int j -> Int_v(i+j) _,_ => error()) Lambda(x,t,e) => Closure_v{env=env,code=(x,e)} App(e1,e2) => (match interp env e1, interp env e2 of Closure_v{env=cenv,code=(x,e)},v -> interp (extend cenv x v) e _,_ -> error() 24

25 Type Checker: let rec tc (env:var->tipe) (e:exp) = match e with Var x -> env x Int _ -> Int_t Plus_i(e1,e2) -> (match tc env e1, tc env e with Int_t, Int_t -> Int_t _,_ => error()) Lambda(x,t,e) -> Fn_t(t,tc (extend env x t) e) App(e1,e2) -> (match (tc env e1, tc env e2) with Arrow_t(t1,t2), t -> if (t1!= t) then error() else t2 _,_ -> error()) Growing the language type tipe =... Bool_t type exp =... True False If of exp*exp*exp let rec interp env e =... True -> True_v False -> False_v If(e1,e2,e3) -> (match interp env e1 with True_v -> interp env e2 False_v -> interp env e3 _ => error()) 25

26 Type- Checking let rec tc (env:var->tipe) (e:exp) = match e with... True -> Bool_t False -> Bool_t If(e1,e2,e3) -> (let (t1,t2,t3) = (tc env e1,tc env e2,tc env e3) in match t1 with Bool_t -> if (t2!= t3) then error() else t2 _ => error()) Refining Types We can easily add new types that dis:nguish different subsets of values. type tipe =... True_t False_t Bool_t Pos_t Neg_t Zero_t Int_t Any_t 26

27 Modified Type- Checker let rec tc (env:var->tipe) (e:exp) =... True -> True_t False -> False_t If(e1,e2,e3) -> (match tc env e1 with True_t -> tc env e2 False_t -> tc env e3 Bool_t -> (let (t2,t3) = (tc env e2, tc env e3) in lub t2 t3) _ => error()) Least Upper Bound let lub t1 t2 = match t1, t2 with True_t (Bool_t False_t) -> Bool_t False_t,(Bool_t True_t) -> Bool_t Zero_t, (Neg_t Pos_t Int_t) -> Int_t Neg_t, (Zero_t Pos_t Int_t) -> Int_t Pos_t, (Zero_t Pos_t Int_t) -> Int_t _,_ -> if (t1 = t2) then t1 else Any_t 27

28 Refining Integers into Zero,Neg,Pos let rec tc (env:var->tipe) (e:exp) =... Int 0 -> Zero_t Int I -> if i < 0 then Neg_t else Pos_t Plus(e1,e2) -> (match tc env e1, tc env e2 with Zero_t,t2 -> t2 t1,zero_t -> t1 Pos_t,Pos_t -> Pos_t Neg_t,Neg_t -> Neg_t (Neg_t Pos_t Int_t),Int_t -> Int_t Int_t,(Neg_t Pos_t) -> Int_t _,_ -> error()) Subtyping as Subsets! If we think of types as sets of values, then a subtype corresponds to a subset and lub corresponds to union.! e.g., Pos_t <= Int_t since every posi:ve integer is also an integer.! For condi:onals, we want to find the least type of the types the two branches might return. o Adding "Any_t" ensures there is a type. o (Not always a good thing to have ) o Need NonPos_t, NonNeg_t and NonZero_t to get least upper bounds. 28

29 Extending Subtyping:! What about pairs? o (T 1 * T 2 ) <= (U 1 * U 2 ) when T 1 <= U 1 and T 2 <= U 2 o But only when immutable! o Why?! What about func:ons? o (T 1 - > T 2 ) <= (U 1 - > U 2 ) when U 1 <= T 1 and T 2 <= U 2. o Why? Problems with Mutability: let f(p :ref(pos_t)) = let q :ref(int_t) = p in q := 0; 42 div (!p) 29

30 Another Way to See it:! Any shared, mutable data structure can be thought of as an immutable record of pairs of methods (with hidden state): o p : ref(pos_t) => o p : { get: unit -> Pos_t, set: Pos_t -> unit }! When is ref(t) <= ref(u)? When: o unit->t <= unit->u or T <= U and o T->unit <= U->unit or U <= T. o Thus, only when T = U! N- Tuples and Simple Records:! (T 1 * * T n * T n+1 ) <= (U 1 * * U n ) when T i <= U i. o Why?! Non- Permutable Records: {l 1 :T 1,,l n :T n,l n+1 :T n+1 } <= {l 1 :U 1,, l n :U n } when T i <= U i. o Assumes {x:int,y:int}!= {y:int,x:int} o That is, the posi:on of a label is independent of the rest of the labels in the type. o In SML (or for Java interfaces) this is not the case. 30

31 SML- Style Records:! Compiler sorts by label.! So if you write {y:int,z:int,x:int}, the compiler immediately rewrites it to {x:int,y:int,z:int}.! So you need to know all of the labels to determine their posi:ons.! Consider: {y:int,z:int,x:int} <= {y:int,z:int} but {y,z,x} == {x,y,z} <= {y,z} If you want both:! If you want permutability & dropping, you need to either copy or use a dic:onary: x y z p = {x=42,y=55,z=66}:{x:int,y:int,z:int} y z q : {y:int,z:int} = p 31

32 Type Inference let rec tc (env:(var*tipe) list) (e:exp) = match e with Var x -> lookup env x Lambda(x,e) -> (let t = guess() in Fn_t(t,tc (extend env x t) e)) App(e1,e2) -> (match tc env e1, tc env e2 with Fn_t(t1,t2), t -> if t1!= t then error() else t2 _,_ => error()) Extend Types with Guesses: type tipe = Int_t Fn_t of tipe*tipe Guess of (tipe option ref) fun guess() = Guess(ref None) 32

33 Must Handle Guesses Lambda(x,e) -> let t = guess() in Fn_t(t,tc (extend env x t) e) App(e1,e2) -> (match tc env e1, tc env e2 with Fn_t(t1,t2), t -> if t1!= t then error() else t2 Guess (r as ref None), t -> let t2 = guess() in r := Some(Fn_t(t,t2)); t2 Guess (ref Some (Fn_t(t1,t2))), t -> if t1!= t then error() else t2 Cleaner: let rec tc (env: (var*tipe) list) (e:exp) = match e with Var x -> lookup env x Lambda(x,e) -> let t = guess() in Fn_t(t,tc (extend env x t) e) App(e1,e2) -> let (t1,t2) = (tc env e1, tc env e2) in let t = guess() in if unify t1 (Fn_t(t2,t)) then t else error() 33

34 Where: let rec unify (t1:tipe) (t2:tipe):bool = if (t1 = t2) then true else match t1,t2 with Guess(ref(Some t1')), _ -> unify t1 t2 Guess(r as (ref None)), t2 -> (r := t2; true) _, Guess(_) -> unify t2 t1 Int_t, Int_t -> true Fn_t(t1a,t1b), Fn_t(t2a,t2b)) -> unify t1a t2a && unify t1b t2b Subtlety! Consider: fun x => x x! We guess g1 for x o We see App(x,x) o recursive calls say we have t1=g1 and t2=g1. o We guess g2 for the result. o And unify(g1,fn_t(g1,g2)) o So we set g1 := Some(Fn_t(g1,g2)) o What happens if we print the type? 34

35 Fixes:! Do an "occurs" check in unify: let rec unify (t1:tipe) )t2:tipe):bool = if (t1 = t2) then true else case (t1,t2) of (Guess(r as ref None),_) => if occurs r t2 then error() else (r := Some t2; true)! Alterna:vely, be careful not to loop anywhere. o In par:cular, when comparing t1 = t2, we must code up a graph equality, not a tree equality. Polymorphism:! Consider: fun x => x! We guess g1 for x o We see x. o So g1 is the result. o We return Fn_t(g1,g1) o g1 is unconstrained. o We could constraint it to Int_t or Fn_t(Int_t,Int_t) or any type. o In fact, we could re- use this code at any type. 35

36 type exp = ML Expressions: Var of var Int of int Lambda of var * exp App of exp*exp Let of var * exp * exp Naïve ML Type Inference: let rec tc (env: (var*tipe) list) (e:exp) = match e with Var x -> lookup env x Lambda(x,e) -> let t = guess() in Fn_t(t,tc (extend env x t) e) end App(e1,e2) -> let (t1,t2) = (tc env e1, tc env e2) in let t = guess() in if unify t1 (Fn_t(t2,t)) then t else error() Let(x,e1,e2) => (tc env e1; tc env (substitute(e1,x,e2)) 36

37 Example: let id = fn x => x in (id 3, id "fred") end ====> ((fun x => x) 3, (fun x => x) "fred") Be~er Approach (DM): type tvar = string type tipe = Int_t Fn_t of tipe*tipe Guess of (tipe option ref) Var_t of tvar type tipe_scheme = Forall of (tvar list * tipe) 37

38 ML Type Inference let rec tc (env:(var*tipe_scheme) list) (e:exp) = match e with Var x -> instantiate(lookup env x) Int _ -> Int_t Lambda(x,e) -> let g = guess() in Fn_t(g,tc (extend env x (Forall([],t)) e) App(e1,e2) -> let (t1,t2,t) = (tc env e1,tc env e2,guess()) in if unify(t1,fn_t(t2,t)) then t else error() Let(x,e1,e2) -> let s = generalize(env,tc env e1) in tc (extend env x s) e2 end Instan:a:on let instantiate(s:tipe_scheme):tipe = let val Forall(vs,t) = s val vs_and_ts : (var*tipe) list = map (fn a => (a,guess()) vs in end substitute(vs_and_ts,t) 38

39 Generaliza:on: let generalize(e:env,t:tipe):tipe_scheme = let t_gs = guesses_of_tipe t in let env_list_gs = map (fun (x,s) -> guesses_of s) e in let env_gs = foldl union empty env_list_gs let diff = minus t_gs env_gs in let gs_vs = map (fun g -> (g,freshvar())) diff in let tc = subst_guess(gs_vs,t) in Forall(map snd gs_vs, tc) end Explana:on:! Each let- bound value is generalized. o e.g., g- >g generalizes to Forall a.a - > a.! Each use of a let- bound variable is instan:ated with fresh guesses: o e.g., if f:forall a.a- >a, then in f e, then the type we assign to f is g- >g for some fresh guess g.! But we can't generalize guesses that might later become constrained. o Sufficient to filter out guesses that occur elsewhere in the environment. o e.g., if the expression has type g1- >g2 and y:g1, then we might later use y in a context that demands it has type int, such as y+1. 39

40 Effects:! The algorithm given is equivalent to subs:tu:ng the let- bound expression.! But in ML, we evaluate CBV, not CBN! let id = (print "Hello"; fn x => x) in (id 42, id "fred )!= ((print "Hello";fn x=>x) 42, (print "Hello";fn x=>x) "fred") Problem: let r = ref (fn x=>x) in (* r : Forall 'a.ref('a->'a) *) r := (fn x => x+1); (* r:ref(int->int) *) (!r)("fred") (* r:ref(string->string) *) 40

41 "Value Restric:on"! When is let x=e1 in e2 equivalent to subst(e1,x,e2)?! If e1 has no side effects. o reads/writes/alloca:on of refs/arrays. o input, output. o non- termina:on.! So only generalize when e1 is a value. o or something easy to prove equivalent to a value. Real Algorithm: let rec tc (env:var->tipe_scheme) (e:exp) = match e with... Let(x,e1,e2) -> let s = if may_have_effects e1 then Forall([],tc env e1) else generalize(env,tc env e1) in tc (extend env x s) e2 end 41

42 Checking Effects: let rec may_have_effects e = match e with Int _ -> false Var _ -> false Lambda _ -> false Pair(e1,e2) -> may_have_effects e1 may_have_effects e2 App _ -> true 42

CS153: Compilers Lecture 14: Type Checking

CS153: Compilers Lecture 14: Type Checking CS153: Compilers Lecture 14: Type Checking Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 4 out Due Thursday Oct 25 (7 days) Project 5 out Due Tuesday Nov 13 (26 days) Project

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

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

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

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

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

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

More information

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

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

Ways to implement a language

Ways to implement a language Interpreters Implemen+ng PLs Most of the course is learning fundamental concepts for using PLs Syntax vs. seman+cs vs. idioms Powerful constructs like closures, first- class objects, iterators (streams),

More information

Closures & Environments. CS4410: Spring 2013

Closures & Environments. CS4410: Spring 2013 Closures & Environments CS4410: Spring 2013 "Functional" Languages: Lisp, Scheme, Miranda, Hope, ML, OCaml, Haskell, Functions are first-class not just for calling can pass to other functions (map), return

More information

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016 CSE341: Programming Languages Lecture 11 Type Inference Dan Grossman Spring 2016 Type-checking (Static) type-checking can reject a program before it runs to prevent the possibility of some errors A feature

More information

Instructor: Randy H. Katz hap://inst.eecs.berkeley.edu/~cs61c/fa13. Fall Lecture #7. Warehouse Scale Computer

Instructor: Randy H. Katz hap://inst.eecs.berkeley.edu/~cs61c/fa13. Fall Lecture #7. Warehouse Scale Computer CS 61C: Great Ideas in Computer Architecture Everything is a Number Instructor: Randy H. Katz hap://inst.eecs.berkeley.edu/~cs61c/fa13 9/19/13 Fall 2013 - - Lecture #7 1 New- School Machine Structures

More information

Type Declarations. Γ <num> : num [... <id> τ... ] <id> : τ Γ true : bool Γ false : bool Γ e 1 : num Γ e 2 : num Γ. {+ e 1 e 2 } : num

Type Declarations. Γ <num> : num [... <id> τ... ] <id> : τ Γ true : bool Γ false : bool Γ e 1 : num Γ e 2 : num Γ. {+ e 1 e 2 } : num Type Declarations Γ : num [... τ... ] : τ Γ true : bool Γ false : bool Γ e 1 : num Γ e 2 : num Γ {+ e 1 e 2 } : num Γ e 1 : bool Γ e 2 : τ 0 Γ e 3 : τ 0 Γ {if e 1 e 2 e 3 } : τ 0 Γ[

More information

Overview of Semantic Analysis. Lecture 9

Overview of Semantic Analysis. Lecture 9 Overview of Semantic Analysis Lecture 9 1 Midterm Thursday In class SCPD students come to campus for the exam Material through lecture 8 Open note Laptops OK, but no internet or computation 2 Outline The

More information

Type Soundness. Type soundness is a theorem of the form If e : τ, then running e never produces an error

Type Soundness. Type soundness is a theorem of the form If e : τ, then running e never produces an error Type Soundness Type soundness is a theorem of the form If e : τ, then running e never produces an error 1 Type Soundness Type soundness is a theorem of the form If e : τ, then running e never produces

More information

CSCI-GA Scripting Languages

CSCI-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 information

Variables and Bindings

Variables and Bindings Net: Variables Variables and Bindings Q: How to use variables in ML? Q: How to assign to a variable? # let = 2+2;; val : int = 4 let = e;; Bind the value of epression e to the variable Variables and Bindings

More information

CS153: Compilers Lecture 16: Local Optimization II

CS153: Compilers Lecture 16: Local Optimization II CS153: Compilers Lecture 16: Local Optimization II Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 4 out Due today! Project 5 out Due Tuesday Nov 13 (19 days) Project 6 out

More information

CSCE 314 Programming Languages. Type System

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

More information

A Func'onal Introduc'on. COS 326 David Walker Princeton University

A Func'onal Introduc'on. COS 326 David Walker Princeton University A Func'onal Introduc'on COS 326 David Walker Princeton University Thinking Func'onally In Java or C, you get (most) work done by changing something temp = pair.x; pair.x = pair.y; pair.y = temp; commands

More information

CSE Compilers. Reminders/ Announcements. Lecture 15: Seman9c Analysis, Part III Michael Ringenburg Winter 2013

CSE Compilers. Reminders/ Announcements. Lecture 15: Seman9c Analysis, Part III Michael Ringenburg Winter 2013 CSE 401 - Compilers Lecture 15: Seman9c Analysis, Part III Michael Ringenburg Winter 2013 Winter 2013 UW CSE 401 (Michael Ringenburg) Reminders/ Announcements Project Part 2 due Wednesday Midterm Friday

More information

Type checking. Jianguo Lu. November 27, slides adapted from Sean Treichler and Alex Aiken s. Jianguo Lu November 27, / 39

Type checking. Jianguo Lu. November 27, slides adapted from Sean Treichler and Alex Aiken s. Jianguo Lu November 27, / 39 Type checking Jianguo Lu November 27, 2014 slides adapted from Sean Treichler and Alex Aiken s Jianguo Lu November 27, 2014 1 / 39 Outline 1 Language translation 2 Type checking 3 optimization Jianguo

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

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

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

Implemen'ng OCaml in OCaml

Implemen'ng OCaml in OCaml 1 An OCaml defini'on of OCaml evalua'on, or, Implemen'ng OCaml in OCaml COS 326 David Walker Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel permission granted to reuse

More information

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Topics 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 information

CSE341, Spring 2013, Final Examination June 13, 2013

CSE341, Spring 2013, Final Examination June 13, 2013 CSE341, Spring 2013, Final Examination June 13, 2013 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, except for both sides of one 8.5x11in piece of paper. Please stop

More information

Compila(on /15a Lecture 6. Seman(c Analysis Noam Rinetzky

Compila(on /15a Lecture 6. Seman(c Analysis Noam Rinetzky Compila(on 0368-3133 2014/15a Lecture 6 Seman(c Analysis Noam Rinetzky 1 You are here Source text txt Process text input characters Lexical Analysis tokens Annotated AST Syntax Analysis AST Seman(c Analysis

More information

Lecture 15 CIS 341: COMPILERS

Lecture 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 information

Recap: Functions as first-class values

Recap: Functions as first-class values Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Lesson 18! Bootstrapping Names in programming languages Binding

More information

CMSC 330: Organization of Programming Languages

CMSC 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 information

Closures. 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 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 information

Typed Recursion {with {mk-rec : (((num -> num) -> (num -> num)) -> (num -> num)) {fun {body : ((num -> num) -> (num -> num))} {{fun {fx :

Typed Recursion {with {mk-rec : (((num -> num) -> (num -> num)) -> (num -> num)) {fun {body : ((num -> num) -> (num -> num))} {{fun {fx : Recursion {with {mk-rec {fun {body} {{fun {fx} {fx fx}} {fun {fx} {{fun {f} {body f}} {fun {x} {{fx fx} x}}}}}}} {with {fib {mk-rec {fun {fib} {fun {n} {if0 n 1 {if0 {- n 1} 1 {+ {fib {- n 1}} {fib {-

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Lesson 11! Syntax- Directed Transla>on The Structure of the

More information

Closures. 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 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 information

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d) CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)

More information

NAMES, SCOPES AND BINDING A REVIEW OF THE CONCEPTS

NAMES, SCOPES AND BINDING A REVIEW OF THE CONCEPTS NAMES, SCOPES AND BINDING A REVIEW OF THE CONCEPTS Name Binding and Binding Time Name binding is the associa1on of objects (data and/or code) with names (iden1fiers) Shape S = new Shape(); The binding

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

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 15/ Prof. Andrea Corradini Department of Computer Science, Pisa Lesson 13! Scoping rules and their implementa;on 1 Summary

More information

CS 61C: Great Ideas in Computer Architecture Func%ons and Numbers

CS 61C: Great Ideas in Computer Architecture Func%ons and Numbers CS 61C: Great Ideas in Computer Architecture Func%ons and Numbers 9/11/12 Instructor: Krste Asanovic, Randy H. Katz hcp://inst.eecs.berkeley.edu/~cs61c/sp12 Fall 2012 - - Lecture #8 1 New- School Machine

More information

Programming Language Features. CMSC 330: Organization of Programming Languages. Turing Completeness. Turing Machine.

Programming Language Features. CMSC 330: Organization of Programming Languages. Turing Completeness. Turing Machine. CMSC 330: Organization of Programming Languages Lambda Calculus Programming Language Features Many features exist simply for convenience Multi-argument functions foo ( a, b, c ) Ø Use currying or tuples

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Lambda Calculus CMSC 330 1 Programming Language Features Many features exist simply for convenience Multi-argument functions foo ( a, b, c ) Ø Use currying

More information

Announcements. Working in pairs is only allowed for programming assignments and not for homework problems. H3 has been posted

Announcements. Working in pairs is only allowed for programming assignments and not for homework problems. H3 has been posted Announcements Working in pairs is only allowed for programming assignments and not for homework problems H3 has been posted 1 Syntax Directed Transla@on 2 CFGs so Far CFGs for Language Defini&on The CFGs

More information

Context Analysis. Mooly Sagiv. html://www.cs.tau.ac.il/~msagiv/courses/wcc11-12.html

Context Analysis. Mooly Sagiv. html://www.cs.tau.ac.il/~msagiv/courses/wcc11-12.html Context Analysis Mooly Sagiv html://www.cs.tau.ac.il/~msagiv/courses/wcc11-12.html 1 Short Decaf Program Interface not declared class MyClass implements MyInterface { string myinteger; void dosomething()

More information

Announcements. Working on requirements this week Work on design, implementation. Types. Lecture 17 CS 169. Outline. Java Types

Announcements. Working on requirements this week Work on design, implementation. Types. Lecture 17 CS 169. Outline. Java Types Announcements Types Working on requirements this week Work on design, implementation Lecture 17 CS 169 Prof. Brewer CS 169 Lecture 16 1 Prof. Brewer CS 169 Lecture 16 2 Outline Type concepts Where do types

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

LECTURE 3. Compiler Phases

LECTURE 3. Compiler Phases LECTURE 3 Compiler Phases COMPILER PHASES Compilation of a program proceeds through a fixed series of phases. Each phase uses an (intermediate) form of the program produced by an earlier phase. Subsequent

More information

Type Systems, Type Inference, and Polymorphism

Type Systems, Type Inference, and Polymorphism 6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

More information

LISP: LISt Processing

LISP: LISt Processing Introduc)on to Racket, a dialect of LISP: Expressions and Declara)ons LISP: designed by John McCarthy, 1958 published 1960 CS251 Programming Languages Spring 2017, Lyn Turbak Department of Computer Science

More information

CMSC 330: Organization of Programming Languages

CMSC 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 information

Thinking Induc,vely. COS 326 David Walker Princeton University

Thinking Induc,vely. COS 326 David Walker Princeton University Thinking Induc,vely COS 326 David Walker Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel permission granted to reuse these slides for non-commercial educa,onal purposes

More information

Thinking Induc,vely. COS 326 David Walker Princeton University

Thinking Induc,vely. COS 326 David Walker Princeton University Thinking Induc,vely COS 326 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa,onal purposes Administra,on 2 Assignment

More information

Notes on specifying user defined types

Notes on specifying user defined types Notes on specifying user defined types data Exp = While Exp Exp Bool Bool If Exp Exp Exp Int Int Add Exp Exp Sub Exp Exp Mul Exp Exp Div Exp Exp Leq Exp Exp Char Char Ceq Exp Exp Pair Exp Exp Fst Exp Snd

More information

Begin at the beginning

Begin 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 information

Formal Semantics. Chapter Twenty-Three Modern Programming Languages, 2nd ed. 1

Formal Semantics. Chapter Twenty-Three Modern Programming Languages, 2nd ed. 1 Formal Semantics Chapter Twenty-Three Modern Programming Languages, 2nd ed. 1 Formal Semantics At the beginning of the book we saw formal definitions of syntax with BNF And how to make a BNF that generates

More information

Types and Type Inference

Types and Type Inference Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

More information

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University CS558 Programming Languages Winter 2018 Lecture 4a Andrew Tolmach Portland State University 1994-2018 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information

Project Compiler. CS031 TA Help Session November 28, 2011

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

More information

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

Research opportuni/es with me

Research opportuni/es with me Research opportuni/es with me Independent study for credit - Build PL tools (parsers, editors) e.g., JDial - Build educa/on tools (e.g., Automata Tutor) - Automata theory problems e.g., AutomatArk - Research

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics 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 information

Lecture 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 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 information

Programming Languages

Programming Languages CSE 130 : Spring 2011 Programming Languages Lecture 3: Crash Course Ctd, Expressions and Types Ranjit Jhala UC San Diego A shorthand for function binding # let neg = fun f -> fun x -> not (f x); # let

More information

Compilers and computer architecture: Semantic analysis

Compilers 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 information

Type Declarations. [... <id> τ... ] <id> : τ. Γ <num> : number. Γ true : boolean. Γ false : boolean. Γ e 1 : number.

Type Declarations. [... <id> τ... ] <id> : τ. Γ <num> : number. Γ true : boolean. Γ false : boolean. Γ e 1 : number. Type Inference 1 Type Declarations Γ : number Γ true : boolean Γ e 1 : number [... τ... ] : τ Γ false : boolean Γ e 2 : number Γ {+ e 1 e 2 } : number Γ e 1 : boolean Γ e 2 : τ 0 Γ e 3

More information

EDAN65: Compilers, Lecture 13 Run;me systems for object- oriented languages. Görel Hedin Revised:

EDAN65: Compilers, Lecture 13 Run;me systems for object- oriented languages. Görel Hedin Revised: EDAN65: Compilers, Lecture 13 Run;me systems for object- oriented languages Görel Hedin Revised: 2014-10- 13 This lecture Regular expressions Context- free grammar ATribute grammar Lexical analyzer (scanner)

More information

Exercises on ML. Programming Languages. Chanseok Oh

Exercises on ML. Programming Languages. Chanseok Oh Exercises on ML Programming Languages Chanseok Oh chanseok@cs.nyu.edu Dejected by an arcane type error? - foldr; val it = fn : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b - foldr (fn x=> fn y => fn z => (max

More information

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

More information

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University Lecture 7: Type Systems and Symbol Tables CS 540 George Mason University Static Analysis Compilers examine code to find semantic problems. Easy: undeclared variables, tag matching Difficult: preventing

More information

Vulnerability Analysis (III): Sta8c Analysis

Vulnerability Analysis (III): Sta8c Analysis Computer Security Course. Vulnerability Analysis (III): Sta8c Analysis Slide credit: Vijay D Silva 1 Efficiency of Symbolic Execu8on 2 A Sta8c Analysis Analogy 3 Syntac8c Analysis 4 Seman8cs- Based Analysis

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 4a Andrew Tolmach Portland State University 1994-2016 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information

CIS 341 Final Examination 4 May 2017

CIS 341 Final Examination 4 May 2017 CIS 341 Final Examination 4 May 2017 1 /14 2 /15 3 /12 4 /14 5 /34 6 /21 7 /10 Total /120 Do not begin the exam until you are told to do so. You have 120 minutes to complete the exam. There are 14 pages

More information

(Refer Slide Time: 4:00)

(Refer Slide Time: 4:00) Principles of Programming Languages Dr. S. Arun Kumar Department of Computer Science & Engineering Indian Institute of Technology, Delhi Lecture - 38 Meanings Let us look at abstracts namely functional

More information

CA Compiler Construction

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

More information

CMSC330. Objects, Functional Programming, and lambda calculus

CMSC330. Objects, Functional Programming, and lambda calculus CMSC330 Objects, Functional Programming, and lambda calculus 1 OOP vs. FP Object-oriented programming (OOP) Computation as interactions between objects Objects encapsulate mutable data (state) Accessed

More information

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018 CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Autumn 2018 Typical workflow concrete syntax (string) "(fn x => x + x) 4" Parsing Possible errors / warnings

More information

CSE341 Spring 2017, Final Examination June 8, 2017

CSE341 Spring 2017, Final Examination June 8, 2017 CSE341 Spring 2017, Final Examination June 8, 2017 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

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

Types, Type Inference and Unification

Types, Type Inference and Unification Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

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

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2017-19: Type

More information

News. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values

News. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values CSE 130: Programming Languages Environments & Closures News PA 3 due THIS Friday (5/1) Midterm NEXT Friday (5/8) Ranjit Jhala UC San Diego Recap: Functions as first-class values Arguments, return values,

More information

Mini-ML. CS 502 Lecture 2 8/28/08

Mini-ML. CS 502 Lecture 2 8/28/08 Mini-ML CS 502 Lecture 2 8/28/08 ML This course focuses on compilation techniques for functional languages Programs expressed in Standard ML Mini-ML (the source language) is an expressive core subset of

More information

CSE341 Autumn 2017, Final Examination December 12, 2017

CSE341 Autumn 2017, Final Examination December 12, 2017 CSE341 Autumn 2017, Final Examination December 12, 2017 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

More information

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 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 information

Side note: Tail Recursion. Begin at the beginning. Side note: Tail Recursion. Base Types. Base Type: int. Base Type: int

Side note: Tail Recursion. Begin at the beginning. Side note: Tail Recursion. Base Types. Base Type: int. Base Type: int Begin at the beginning Epressions (Synta) Compile-time Static Eec-time Dynamic Types Values (Semantics) 1. Programmer enters epression 2. ML checks if epression is well-typed Using a precise set of rules,

More information

Tail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial

Tail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial Begin at the beginning Epressions (Synta) Compile-time Static Eec-time Dynamic Types Values (Semantics) 1. Programmer enters epression 2. ML checks if epression is well-typed Using a precise set of rules,

More information

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 17: Types and Type-Checking 25 Feb 08 CS 412/413 Spring 2008 Introduction to Compilers 1 What Are Types? Types describe the values possibly

More information

Scoping and Type Checking

Scoping and Type Checking #1 Scoping and Type Checking #2 #3 Recall: Review Sets Exist Ask me to look at your answers! Derivations and parse trees are closely related, but if we ask you to draw a parse tree you must draw the parse

More information

Metaprogramming assignment 3

Metaprogramming assignment 3 Metaprogramming assignment 3 Optimising embedded languages Due at noon on Thursday 29th November 2018 This exercise uses the BER MetaOCaml compiler, which you can install via opam. The end of this document

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

More information

Verification of an ML compiler. Lecture 3: Closures, closure conversion and call optimisations

Verification of an ML compiler. Lecture 3: Closures, closure conversion and call optimisations Verification of an ML compiler Lecture 3: Closures, closure conversion and call optimisations Marktoberdorf Summer School MOD 2017 Magnus O. Myreen, Chalmers University of Technology Implementing the ML

More information

Parsing Scheme (+ (* 2 3) 1) * 1

Parsing Scheme (+ (* 2 3) 1) * 1 Parsing Scheme + (+ (* 2 3) 1) * 1 2 3 Compiling Scheme frame + frame halt * 1 3 2 3 2 refer 1 apply * refer apply + Compiling Scheme make-return START make-test make-close make-assign make- pair? yes

More information

Modules and Representa/on Invariants

Modules and Representa/on Invariants Modules and Representa/on Invariants COS 326 David Walker Princeton University slides copyright 2017 David Walker permission granted to reuse these slides for non-commercial educa/onal purposes LAST TIME

More information

Types and evaluation

Types and evaluation Type Soundness 1 Types and evaluation Why is a type system useful? It can rule out ill-formed programs before we run them What information can a type system give us? The type of data the program should

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 2005 P. N. Hilfinger Project #2: Static Analyzer for Pyth Due: Wednesday, 6 April

More information