Principles of Programming Languages
|
|
- Primrose Dawson
- 5 years ago
- Views:
Transcription
1 Principles of Programming Languages Lesson 14 Type Checking Collaboration and Management Dana Fisman 1
2 Type Checking We return to the issue of type safety we discussed informally, in the introduction to FP via Typescript. A program is type-safe if we can guarantee that in no run we will encounter a type-error A type-error occurs when a procedure is applied to inappropriate data Example: (+ 7 'ok) + contract violation Expected: number? Given: 'ok argument position: 2nd
3 Type annotation As you recall Typesctipt extends Javascript with optional type annotation. Scheme does not support type annotation We will define L5, an extension of L4 that allows type annotation L5, unlike L1-L4, is not a subset of Scheme
4 L5 Scheme L4 define L1 only primitive ops and types L2 L3 cond lambda cons car cdr '() list letrec L5
5 Type annotation Ex. (define f (lambda ([n : number]) : number (+ n 3)))
6 Type checker Expression E Type Checker Type of E Type-Error #...
7 Program Correctness When is a program correct? We distinguish two type of plausibility criteria for programs correctness: PL Safety: o Type correctness o No division by zero o No array out-of-bounds accesses o No null-dereferences Verification: Correctness with regard to its specification E.g. o For a factorial program: Given a positive integer it returns n! o For a resource allocation program: a process requiring resource will eventually be granted access to the resource
8 Program Analysis We distinguish two approaches for checking correctness criteria for programs: Static Analysis o Only the text of the program is analyzed Dynamic Analysis o The program is analyzed in a runtime environment Static analysis provides stronger guarantees, since it proves correctness (of the criterion at hand) on every possible run.
9 Type Checking Checking there are no type errors, is easier with full type declaration. But scheme has no type declaration. We will tackle the problem in two phases: 1. We first analyze programs that include full type annotations and verify that they satisfy their type declarations. 2. We then analyze programs that include partial type annotations (and possibly no annotations at all) and infer the types of all variable declarations and functions.
10 Types Types are sets of values The set of all possible computed values of a program is partitioned into subsets In some PL partition is not the correct word, since a value can belong to several subsets (belong to several types)
11 Types in L4 Value = Number Boolean Prim-op Closure Void Sexp SExp = Symbol Number Boolean List(Sexp) Pair(Sexp, Sexp) List(Sexp) = '() Pair(SExp, List(Sexp)) Pair(Sexp) = (Sexp, Sexp) Closure = defined inductively as a mapping from tuple to values
12 Type Systems The semantics of a programming language defines a type system: it determines which types exist across the domain of computed values, how new types can be constructed o (through the usage of type constructors - such as Pair or List or Procedures) the possible relations among types o o o typea is contained in typeb typea is disjoint from typeb there is an overlap between typea and typeb
13 Type Compatibility If a variable was declared to have typea, can we assign it an expression with value of typeb? Simplest form: Identity: if typea is identical to typeb Aka invariance (the set of values passed cannot vary) Method used in Scheme More complex forms: Subtyping: if typea is a subtype of typeb Method used in TypeScript
14 Soundness A given expression is type safe if its evaluation will never lead to type errors. The goal of type checking is to verify that o if an expression E is assigned type T, o then, whenever E is computed, its value will be of type T. If the type system has this property, we say that it is sound.
15 Type Errors The type checker inspects every application node in the AST When checking an application node, it examines the types of the operands. If the operands are not of the expected type, this is an operator invocation error. This is a potential type error. The type checker then needs to take some actions o The kind of actions is part of the language design o Examples of action: Refuse to execute / compile Preform corrective measures (e.g. type casting).
16 Associating Expressions with Types Type checking and type inference requires associating program expressions with types. In order to achieve this, we need to define two syntactic extensions to our language: Define a type language to specify type expressions. Define a way in the language to associate variables and procedures to type expressions.
17 Type Language We now formally define the type language we have actually already been using: ;; Purpose: Identity ;; Signature: id(x) ;; Type: [T -> T] (define id (lambda (x) x))
18 Type Language - Ex Examples of type expressions we d like to be able to derive: number boolean void [number -> boolean] [number * number -> boolean] [number -> [number -> boolean]] [Empty -> number] [Empty -> void] [T1 -> T1]
19 Type Language - Def <texp> ::= <atomic-te> <composite-te> <tvar> <atomic-te> ::= <num-te> <bool-te> <void-te> <num-te> ::= number // num-te() <bool-te> ::= boolean // bool-te() <void-te> ::= void // void-te() <composite-te> ::= <proc-te> <tuple-te> <non-tuple-te> ::= <atomic-te> <proc-te> <tvar> <proc-te> ::= [ <tuple-te> -> <non-tuple-te> ] // proc-te(param-tes: list(te), return-te: te) <tuple-te> ::= <non-empty-tuple-te> <empty-te> <non-empty-tuple-te> ::= ( <non-tuple-te> * )* <non-tuple-te> // tuple-te(tes: list(te)) <empty-te> ::= Empty <tvar> ::= a symbol starting with T // tvar(id: Symbol)
20 Type Annotations L5 extends L4 with type annotation from the type language we just defined Type annotations can occur in two specific places o As part of a variable declarations o As part of a procedure expression, to specify the expected return type
21 Type Annotations Def. <program> ::= (L5 <exp>+) <exp> ::= <define-exp> <cexp> <define-exp> ::= (define <var-decl> <cexp>) <binding> ::= ( <var-decl> <cexp> ) // var-decl(var:symbol, type:texp) <var-decl> ::= <symbol> [ <symbol> : <texp>] <cexp> ::= <num-exp> // num-exp(val:number) <bool-exp> // bool-exp(val:boolean) <prim-op> // prim-op(op:symbol) <var-ref> // var-ref(var:symbol) (if <exp> <exp> <exp>) // if-exp(test,then,else) (quote <sexp>) // lit-exp(val:sexp) (let (<binding>*) <cexp>+) // let-exp(bindings:list(binding), body:list(cexp)) (letrec (<binding>*) <cexp>+) // letrec-exp(bindings:list(binding), body:list(cexp)) (<cexp> <cexp>*) // app-exp(rator:cexp, rands:list(cexp)) // proc-exp(params:list(var-decl), body:list(cexp), return-te: Texp) (lambda ( <var-decl>*) [: <texp>]? <cexp>+) <prim-op> ::= + - * / < > = not eq? cons car cdr pair? list? number? boolean? symbol? display newline <num-exp> ::= a number token <bool-exp> ::= #t #f <var-ref> ::= an identifier token <sexp> ::= a symbol token ( <sexp>* )
22 Type Annotations Ex. (define [x : number] 5) (define [f : [number -> number]] (lambda ([x : number]) : number (* x x)) (define [g : [number * number -> number]] (lambda ([x : number] [y : number]) : number (+ x y)) (let (([a : number] 1) ([b : boolean] #t)) (if b a (+ a 1))) (letrec (([a : (number -> number)] (lambda ([x : number]) : number (* x x)))) (a 3)) (define [id : (T1 -> T1)] (lambda ([x : T1]) : T1 x))
23 Type Annotations Ex. The type annotations are optional. Thus the following is also legal: (define f (lambda ([x : number]) (* x x))) (let ((a 1)) (+ a a))
24 L5 parsing implementation Code in L5-ast.rkt Functions: parse-texp(concrete-type-expression) --> texp AST unparse-texp(texp) --> concrete-type-expression parsel5(concrete-l5) --> L5 AST unparsel5(l5ast) --> concrete L5 program
25 Type expression ASTs (parse-texp 'number) => 'num-te (parse-texp 'boolean) => 'bool-te (parse-texp 'void) => 'void-te (parse-texp 'T1) => '(tvar T1) (parse-texp '(T * T -> boolean)) => '(proc-te ((tvar T) (tvar T)) bool-te) (parse-texp '(number -> (number -> number))) => '(proc-te (num-te) (proc-te (num-te) num-te)) (parse-texp '(Empty -> void)) => '(proc-te () void-te)
26 L5 ASTs (parsel5 '(define [x : number] 1)) => '(def-exp (var-decl x num-te) (num-exp 1)) (parsel5 '(lambda ([x : number]) : number x)) => '(proc-exp ((var-decl x num-te)) ((var-ref x)) num-te)
27 Type Analysis Alg. The type checker alg: Input: L5-AST of fully typed L5-expr E Output: o o Type of E if E is type safe, one of the following errors otherwise: An attempt to apply a value which is neither a primitive nor a closure in an application expression. An attempt to apply a procedure or a primitive operator to the wrong number of arguments. An attempt to apply primitives to wrong type of arguments (for example, + to a non-number value) An attempt to use a non-boolean expression as the test in an if-expression.
28 Type of typeof-exp What should be the type of typeof-exp? Perhaps: typeof-exp: Expr -> TExp Works for atomic expressions typeof-exp(<num-exp val>) => num-te But what if the expression has variables? It depends on the value assigned to the variable We must then also provide the typeof-exp procedure a type-environment typeof-exp: Expr * TEnv-> TExp
29 Type checker Fully typed expression E, type environment TEnv Type Checker Type of E Applying non-proc / Wrong # of args / Wrong type of args / Non-boolean test
30 Type Environment A type environment is a mapping of a finite set of variables to type expressions (i.e. a substitution) o E.g. {x : number, y : [number -> T] } Built inductively: 1. The empty type environment, denoted {}, makes no assumptions about types of variables. 2. An extended-environment combines new assumptions about variable-type mappings with an existing type environment (i.e. a substitution composition) o E.g. {x : number, y : [number -> T] } o {z: Boolean} = {x : number, y : [number -> T], z: Boolean}
31 Typeof on atoms & var-ref typeof-exp: Expr * TEnv-> Texp typeof-exp(<num-exp val>, Tenv) => num-te typeof-exp(<bool-exp val>, Tenv) => bool-te typeof-exp(<varref var>, Tenv) => Tenv(var) What if v is not in Tenv? For now, we throw an error, because we consider only fully-typed programs. We will come back to this when we consider type inference.
32 Typing Statements A typing statement is a true or false formula stating a judgment about whether it is true that a certain expression e has type Te in type environment Tenv Notation: Tenv ` e:t Examples: {x:number} ` (+ x 5):Number {x:boolean} ` (+ x 5):Number {f:[t1 -> T2], g:t1} ` (f g):t2 {f:[t1 -> T2]} ` (f g):t2 {f:[empty -> T2], g:t2} ` (f g):t2 {f:[empty -> T2], g:t2} ` (f):t2
33 Typing Axioms As in any deductive systems, we have axioms and inference rules. Typing axiom Number: For every type environment _Tenv and number _n: _Tenv ` (num_exp _n) : Number Typing axiom Boolean : For every type environment _Tenv and boolean _b: _Tenv ` (bool_exp _b) : Boolean Typing axiom Variable : For every type environment _Tenv and variable _v: _Tenv ` (varref _v) : _Tenv(_v)
34 Typing Axioms Typing Axioms for primitive operators: Typing axiom for +: For every type environment _Tenv: _Tenv ` + : [Number * * Number -> Number ] Typing axiom for <: For every type environment _Tenv: _Tenv ` < : [Number * Number -> Boolean] Typing axiom for not: For every type environment _Tenv and type expressions _S: _Tenv ` not: [_S -> Boolean]
35 Typing Rule for Procedures Typing inference rule for Procedure Def: For every type environment _Tenv, variables _x1,..., _xn, n >= 0 expressions _e1,..., _em, m >= 1, and type expressions _S1,...,_Sn, _U1,...,_Um : Procedure with parameters (n > 0): If _Tenv o {_x1:_s1,..., _xn:_sn } ` _ei:_ui for all i = 1..m, Then _Tenv ` (lambda (_x1... _xn ) _e1... _em) : [_S1 *... * _Sn -> _Um] Parameter-less Procedure (n = 0): If _Tenv ` _ei:_ui for all i=1..m, Then _Tenv `(lambda () _e1... _em) : [Empty -> _Um]
36 Exhaustive Sub-Expression Typing Every typing rule for expression E requires typing statements for all sub-expressions of E. This property guarantees type safety the typing algorithm assign a type to every subexpression which is evaluated at run-time. Still missing: Typing rule for if-exp Typing rule for application expressions Typing rules for let and letrec expressions Later on
37 Type Checking Algorithm ;; Purpose: Compute the type of an expression ;; Signature: typeof=exp(exp, tenv) ;; Type: [Exp * Tenv -> TExp] ;; Precondition: Exp is fully typed ;; Postcondition: Texp is the type Exp in TEnv ;; Traverse the AST and check the type according to the exp type. (define typeof-exp (lambda (exp tenv) (cond [(num-exp? exp) (typeof-num-exp exp)] [(bool-exp? exp) (typeof-bool-exp exp)] [(prim-op? exp) (typeof-prim-op exp)] [(var-ref? exp) (apply-tenv tenv (var-ref->var exp))] [(if-exp? exp) (typeof-if-exp exp tenv)] [(proc-exp? exp) (typeof-proc-exp exp tenv)] [(let-exp? exp) (typeof-let-exp exp tenv)] [(letrec-exp? exp) (typeof-letrec-exp exp tenv)] [(app-exp? exp) (typeof-app-exp exp tenv)] [else (error "Unknown exp type" exp)])))
38 Type Checking Algorithm The atomic cases are simple, and don t require the Tenv ;; a number literal has type num-te ;; Type: [Num-exp -> Num-te] (define typeof-num-exp (lambda (num) (make-num-te))) ;; a boolean literal has type bool-te ;; Type: [Bool-exp -> Bool-te] (define typeof-bool-exp (lambda (bool) (make-bool-te)))
39 Type Checking Algorithm Primitive operators are mapped to their type expression: ;; primitive ops have known proc-te types ;; Type: [Prim-op -> Proc-te] (define typeof-prim-op (lambda (x) (let ([num-op-te (parse-texp '(number * number -> number))] [num-comp-op-te (parse-texp '(number * number -> boolean))] [bool-op-te (parse-texp '(boolean -> boolean))] [x (prim-op->op x)]) (cond [(eq? x '+) num-op-te] [(eq? x '-) num-op-te] [(eq? x '*) num-op-te] [(eq? x '/) num-op-te] [(eq? x '<) num-comp-op-te] [(eq? x '>) num-comp-op-te] [(eq? x '=) num-comp-op-te] [(eq? x 'not) bool-op-te] ))))
40 Type Inference for If What should be the type inference rule for if? o Clearly we should demand the test to be of type Boolean o What about the then-expr and else-expr? Should they be of the same type? Allowing them to have different type will complicate the type inference system. We thus require them to be of the same type. Typing inference rule for If: For every type environment _Tenv, expressions _test, _then, _else type expressions _S If _Tenv ` _test: Boolean _Tenv ` _then: _S _Tenv ` _else: _S Then _Tenv ` (if _test _then _else) : _S
41 Type Checking Algorithm For if expression : ;; Purpose: compute the type of an if-exp ;; Signature: typeof-if-exp(ifexp, tenv) ;; Type: [If-exp * Tenv -> Texp] ;; Typing rule: ;; if type<test>(tenv) = boolean ;; type<then>(tenv) = t1 ;; type<else>(tenv) = t1 ;; then type<(if test then else)>(tenv) = t1 (define typeof-if-exp (lambda (ifexp tenv) (let ([test-te (typeof-exp (if-exp->test ifexp) tenv)] [then-te (typeof-exp (if-exp->then ifexp) tenv)] [else-te (typeof-exp (if-exp->else ifexp) tenv)]) (check-equal-type! test-te (make-bool-te) ifexp) (check-equal-type! then-te else-te ifexp) then-te)))
42 Type Constraint Check For type checking, the type-constraint check is a simple equality We will change this when we consider type inference. ;; Purpose: Check that type expressions are equivalent ;; as part of a fully-annotated type check process of exp. ;; Throws an error if the types are different ;; - void otherwise. ;; Exp is only passed for documentation purposes. ;; Type: [TE * TE * Exp -> Void] (define check-equal-type! (lambda (te1 te2 exp) (or (equal? te1 te2) (error "Incompatible types " (unparse-texp te1) (unparse-texp te2) (unparse exp)))))
43 Type Checking Algorithm For procedures: ;; Purpose: compute the type of a proc-exp ;; Signature: typeof-proc-exp(proc, tenv) ;; Type: [proc-exp * Tenv -> Texp] ;; Typing rule: ;; If type<body>(extend-tenv(x1=t1,...,xn=tn; tenv)) = t ;; then type<lambda (x1:t1,...,xn:tn) : t exp)>(tenv) = (t1 *... * tn -> t) (define typeof-proc-exp (lambda (proc tenv) (let ([params (proc-exp->params proc)] [body (proc-exp->body proc)]) (let ([params-tes (map var-decl->texp params)] [return-te (proc-exp->return-te proc)]) (check-equal-type! (typeof-exps body (extend-tenv tenv (map var-decl->var params) params-tes)) return-te proc) (make-proc-te params-tes return-te)))))
44 Typing Rule for Application Typing inference rule for Application: For every: type environment _Tenv, expressions _f, _e1,..., _en, n 0, and type expressions _S1,..., _Sn, _S: Procedure with parameters (n > 0): If _Tenv ` _f:[_s1*...*_sn -> _S], _Tenv ` _e1:_s1,..., _Tenv ` _en:_sn Then _Tenv ` (_f _e1... _en):_s Parameter-less Procedure (n = 0): If _Tenv ` _f:[empty -> _S] Then _Tenv ` (_f):_s
45 Type Checking Algorithm ;; Purpose: compute the type of an app-exp ;; Signature: typeof-app-exp(app, tenv) ;; Type: [app-exp * Tenv -> Texp] ;; Typing rule: ;; If type<rator>(tenv) = (t1*..*tn -> t) ;; type<rand1>(tenv) = t1 ;;... ;; type<randn>(tenv) = tn ;; then type<(rator rand1...randn)>(tenv) = t ;; We also check the correct number of arguments is passed. (define typeof-app-exp (lambda (app tenv) (let ([rator (app-exp->rator app)] [rands (app-exp->rands app)]) (let ([rator-te (typeof-exp rator tenv)]) (if (not (= (length rands) (length (proc-te->param-tes rator-te)))) (error "Wrong number of arguments passed to procedure" (unparse app)) 'number-or-args-ok) (for-each (lambda (rand-i t-i) (check-equal-type! (typeof-exp rand-i tenv) t-i app)) rands (proc-te->param-tes rator-te)) (proc-te->return-te rator-te)))))
46 Type Checking Examples (if (> 1 2) 1 2)) => 'number (if (= 1 2) #t #f)) => 'boolean (lambda ([x : number]) : number x)) => '(number -> number) (lambda ([x : number]) : boolean (> x 1))) => '(number -> boolean) (lambda ([x : number]) : (number -> number) (lambda ([y : number]) : number (* y x)))) => (number -> (number -> number))
47 Type Checking Examples (lambda ([f : (number -> number)]) : number (f 2))) => ((number -> number) -> number) (let (([x : number] 1)) (* x 2))) => 'number (let (([x : number] 1) ([y : number] 2)) (lambda ([a : number]) : number (+ (* x a) y)))) => (number -> number) (lambda ([x : number]) : number (let (([y : number] x)) (+ x y)))) => (number -> number)
48 Type Checking Alg. Overview It is a typical syntax-driven traversal of the expression AST. All the nodes in the AST are exhaustively traversed. On each node, we apply a typing rule and compute a type value. We maintain an environment reflecting the scope of variables o When a new scope is created (in procedure expressions), we extend the environment with the type of the declared parameters. o When variables are bound (e.g. in application expressions, let or letrec expressions) we check they adhere to the declared type
49 Type Checker vs. Interpreter Type Checker Interpreter Static Analysis: sees only program text Binds identifiers to types Compresses set of values (even of size) into types Always terminates Parses the body of an expr exactly once Dynamic Analysis: runs over actual data Binds identifiers to values (or locations) Treats elements of a certain type distinctly Might not terminate Parses the body of an expr zero to times
50 Summary We designed a type language to specify the expected type of variables and expressions in the language. We extend the syntax of the programming language to allow association of type annotations (in the type language) with variable declarations and procedures. The semantics of the programming language specifies typing rules Typing rules determine the type of each expression type o under the assumption that the variables are associated to specific types. The assumptions we make about the typing of variables are specified in a type environment. The type checking algorithm determines how to traverse the AST of an expression to check that all the nodes in the expression are correctly typed and compatible with the type annotations.
51 Summary Type safety is one of the conditions we must check to prove correctness: Type checking consists of verifying the type of all sub-expressions, o and possibly infer missing types. Program correctness can be checked either statically or dynamically. In static program correctness the program text is analyzed without running it.
52 Summary We designed a type language to specify the expected type of variables and expressions in the language. We extend the syntax of the programming language to allow association of type annotations (in the type language) with variable declarations and procedures. The semantics of the programming language specifies typing rules
53 Summary Typing rules determine the type of each expression type o under the assumption that the variables are associated to specific types. The assumptions we make about the typing of variables are specified in a type environment. The type checking algorithm determines how to traverse the AST of an expression to check that all the nodes in the expression are correctly typed and compatible with the type annotations.
Principles of Programming Languages
Principles of Programming Languages Slides by Dana Fisman based on book by Mira Balaban and lecuture notes by Michael Elhadad Lesson 15 Type Inference Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172
More informationעקרונות שפות תכנות 2018 תרגול 8 Type Inference System
עקרונות שפות תכנות 2018 תרגול 8 Type Inference System Type Inference System The Type Inference System is a TypeScript Implementation of the algorithm for Type Checking and Inference using Type Equations.
More informationPrinciples of Programming Languages
Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished
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 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 information6.821 Programming Languages Handout Fall MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Compvter Science
6.821 Programming Languages Handout Fall 2002 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Compvter Science Problem Set 6 Problem 1: cellof Subtyping Do exercise 11.6
More informationScheme in Scheme: The Metacircular Evaluator Eval and Apply
Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,
More informationעקרונות שפות תכנות, סמסטר ב' 2016 תרגול 7: הסקת טיפוסים סטטית. Axiomatic Type Inference
עקרונות שפות תכנות, סמסטר ב' 2016 תרגול 7: הסקת טיפוסים סטטית 1. Axiomatic type inference 2. Type inference using type constraints נושאי התרגול: Axiomatic Type Inference Definition (seen in class): A Type-substitution
More informationComp 311: Sample Midterm Examination
Comp 311: Sample Midterm Examination October 29, 2007 Name: Id #: Instructions 1. The examination is closed book. If you forget the name for a Scheme operation, make up a name for it and write a brief
More informationPrinciples of Programming Languages
Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Collaboration and Management Dana Fisman Lesson 2 - Types with TypeScript 1 Types What are types in programming languages? What types are you
More informationComp 411 Principles of Programming Languages Lecture 7 Meta-interpreters. Corky Cartwright January 26, 2018
Comp 411 Principles of Programming Languages Lecture 7 Meta-interpreters Corky Cartwright January 26, 2018 Denotational Semantics The primary alternative to syntactic semantics is denotational semantics.
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 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 information1 Lexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler
More information1. For every evaluation of a variable var, the variable is bound.
7 Types We ve seen how we can use interpreters to model the run-time behavior of programs. Now we d like to use the same technology to analyze or predict the behavior of programs without running them.
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 informationLexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a
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 informationLexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2016 Lecture 7a Andrew Tolmach Portland State University 1994-2016 Values and Types We divide the universe of values according to types A type is a set of values and a
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 informationCSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018
CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018 Deliverables: Your code (submit to PLC server). A13 participation survey (on Moodle, by the day after the A13 due date). This is
More information6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter
6.037 Lecture 4 Interpretation Interpretation Parts of an interpreter Meta-circular Evaluator (Scheme-in-scheme!) A slight variation: dynamic scoping Original material by Eric Grimson Tweaked by Zev Benjamin,
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 informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationPrinciples of Programming Languages
Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 4 - Type Checking Collaboration and Management Dana Fisman 1 Why declare types? Declaring types allows the compiler to detect errors
More informationLecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Lecture 13. Notation. The rules. Evaluation Rules So Far
Lecture Outline Operational Semantics of Cool Lecture 13 COOL operational semantics Motivation Notation The rules Prof. Aiken CS 143 Lecture 13 1 Prof. Aiken CS 143 Lecture 13 2 Motivation We must specify
More informationOperational Semantics of Cool
Operational Semantics of Cool Key Concepts semantics: the meaning of a program, what does program do? how the code is executed? operational semantics: high level code generation steps of calculating values
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 informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationIntroduction to Scheme
How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free
More informationLECTURE 16. Functional Programming
LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative
More informationCOP4020 Programming Languages. Functional Programming Prof. Robert van Engelen
COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts
More informationType Checking and Type Inference
Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled
More informationScheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.
Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu
More 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 informationName EID. (calc (parse '{+ {with {x {+ 5 5}} {with {y {- x 3}} {+ y y} } } z } ) )
CS 345 Spring 2010 Midterm Exam Name EID 1. [4 Points] Circle the binding instances in the following expression: (calc (parse '+ with x + 5 5 with y - x 3 + y y z ) ) 2. [7 Points] Using the following
More informationCSCC24 Functional Programming Scheme Part 2
CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages
More informationProcedures. EOPL3: Section 3.3 PROC and App B: SLLGEN
Procedures EOPL3: Section 3.3 PROC and App B: SLLGEN The PROC language Expression ::= proc (Identifier) Expression AST: proc-exp (var body) Expression ::= (Expression Expression) AST: call-exp (rator rand)
More informationOperational Semantics. One-Slide Summary. Lecture Outline
Operational Semantics #1 One-Slide Summary Operational semantics are a precise way of specifying how to evaluate a program. A formal semantics tells you what each expression means. Meaning depends on context:
More informationLexical Addresses. let x = 1 y = 2 in let f = proc (x) +(x, y) in (f x) let _ = 1 _ = 2 in let _ = proc (_) +(<0,0>, <1,1>) in (<0,0> <1,0>)
Lexical Addresses As we saw in the last lecture, the expression might be compiled to let x = 1 y = 2 in let f = proc (x) +(x, y) in (f x) let _ = 1 _ = 2 in let _ = proc (_) +(, ) in ( )
More information;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for
Page 1/11 (require (lib "trace")) Allow tracing to be turned on and off (define tracing #f) Define a string to hold the error messages created during syntax checking (define error msg ""); Used for fancy
More informationCS 360 Programming Languages Interpreters
CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like
More 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 informationComputer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing
Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible
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 informationOutline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference
Type Checking Outline General properties of type systems Types in programming languages Notation for type rules Logical rules of inference Common type rules 2 Static Checking Refers to the compile-time
More informationFall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationIntermediate Code Generation
Intermediate Code Generation In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target
More informationUNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2010 P. N. Hilfinger CS 164: Final Examination (revised) Name: Login: You have
More informationFall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationProject 2: Scheme Interpreter
Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same
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 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 informationThe SPL Programming Language Reference Manual
The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming
More informationScheme Quick Reference
Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries
More informationScheme Quick Reference
Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete
More informationLecture Outline. COOL operational semantics. Operational Semantics of Cool. Motivation. Notation. The rules. Evaluation Rules So Far.
Lecture Outline Operational Semantics of Cool COOL operational semantics Motivation Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Notation The rules CS781(Prasad) L24CG 1 CS781(Prasad)
More informationSpring 2018 Discussion 7: March 21, Introduction. 2 Primitives
CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme
More informationFall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of
1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Fall Semester, 1996 Lecture Notes { October 31,
More informationUser-defined Functions. Conditional Expressions in Scheme
User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment
More informationTyped Scheme: Scheme with Static Types
Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit
More informationPrinciples of Programming Languages 2017W, Functional Programming
Principles of Programming Languages 2017W, Functional Programming Assignment 3: Lisp Machine (16 points) Lisp is a language based on the lambda calculus with strict execution semantics and dynamic typing.
More informationType 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 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 informationTypes 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 informationCOMP520 - GoLite Type Checking Specification
COMP520 - GoLite Type Checking Specification Vincent Foley March 5, 2017 1 Introduction This document presents the typing rules for all the language constructs (i.e. declarations, statements, expressions)
More informationCOMP520 - GoLite Type Checking Specification
COMP520 - GoLite Type Checking Specification Vincent Foley April 8, 2018 1 Introduction This document presents the typing rules for all the language constructs (i.e. declarations, statements, expressions)
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationIntroduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples
Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the
More informationCSE413: 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 informationC311 Lab #3 Representation Independence: Representation Independent Interpreters
C311 Lab #3 Representation Independence: Representation Independent Interpreters Will Byrd webyrd@indiana.edu February 5, 2005 (based on Professor Friedman s lecture on January 29, 2004) 1 Introduction
More informationStatic Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1
Static Semantics Lecture 15 (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Current Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing
More informationCS 314 Principles of Programming Languages
CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.
More information1 Introduction. 3 Syntax
CS 6110 S18 Lecture 19 Typed λ-calculus 1 Introduction Type checking is a lightweight technique for proving simple properties of programs. Unlike theorem-proving techniques based on axiomatic semantics,
More informationA Small Interpreted Language
A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that
More informationCSCE 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 informationTyped Racket: Racket with Static Types
Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type
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 informationFP Foundations, Scheme
FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages
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 informationSCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017
SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationChapter 3. Describing Syntax and Semantics
Chapter 3 Describing Syntax and Semantics Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Attribute Grammars Describing the Meanings of Programs:
More informationCMSC 330: Organization of Programming Languages. Operational Semantics
CMSC 330: Organization of Programming Languages Operational Semantics Notes about Project 4, Parts 1 & 2 Still due today (7/2) Will not be graded until 7/11 (along with Part 3) You are strongly encouraged
More 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 informationCSE341: 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 informationOutline. Introduction Concepts and terminology The case for static typing. Implementing a static type system Basic typing relations Adding context
Types 1 / 15 Outline Introduction Concepts and terminology The case for static typing Implementing a static type system Basic typing relations Adding context 2 / 15 Types and type errors Type: a set of
More informationTypes 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 informationOrganization of Programming Languages CS3200/5200N. Lecture 11
Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages
More informationScheme: Expressions & Procedures
Scheme: Expressions & Procedures CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, March 31, 2017 Glenn G. Chappell Department of Computer Science University
More informationLecture 16: Object Programming Languages
Lecture 16: Object Programming Languages Introduction Corresponds to EOPL 5.1 and 5.2 Goal: to introduce Object Oriented Programming Language (OOPL) concepts using the EOPL extensible language framework
More informationCS 6110 S11 Lecture 25 Typed λ-calculus 6 April 2011
CS 6110 S11 Lecture 25 Typed λ-calculus 6 April 2011 1 Introduction Type checking is a lightweight technique for proving simple properties of programs. Unlike theorem-proving techniques based on axiomatic
More informationPrinciples of Programming Languages
Principles of Programming Languages Slides by Yaron Gonen and Dana Fisman Based on Book by Mira Balaban and Lesson 20 Lazy Lists Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172 1 Lazy
More informationA LISP Interpreter in ML
UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,
More informationCOP4020 Programming Assignment 1 - Spring 2011
COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to
More informationCSE341 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 informationReview: Concrete syntax for Impcore
Review: Concrete syntax for Impcore Definitions and expressions: def ::= (define f (x1... xn) exp) (val x exp) exp (use filename) (check-expect exp1 exp2) (check-error exp) exp ::= integer-literal ;; atomic
More informationDiscussion 12 The MCE (solutions)
Discussion 12 The MCE (solutions) ;;;;METACIRCULAR EVALUATOR FROM CHAPTER 4 (SECTIONS 4.1.1-4.1.4) of ;;;; STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS ;;;from section 4.1.4 -- must precede def of
More informationStatic Checking and Type Systems
1 Static Checking and Type Systems Chapter 6 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University, 2007-2009 2 The Structure of our Compiler Revisited Character stream Lexical
More informationThe Substitution Model
The Substitution Model Prof. Clarkson Fall 2017 Today s music: Substitute by The Who Review Previously in 3110: simple interpreter for expression language abstract syntax tree (AST) evaluation based on
More information