The Environment Model. Nate Foster Spring 2018

Similar documents
The Environment Model

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

CS Lecture 7: The dynamic environment. Prof. Clarkson Spring Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack

Formal Semantics. Prof. Clarkson Fall Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack

The Substitution Model. Nate Foster Spring 2018

The Substitution Model

CS 360 Programming Languages Interpreters

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

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

Type Inference. Prof. Clarkson Fall Today s music: Cool, Calm, and Collected by The Rolling Stones

Environments

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

6.001 Notes: Section 15.1

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

Semantic Analysis. Lecture 9. February 7, 2018

CMSC 330: Organization of Programming Languages. Operational Semantics

6.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

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

CS 11 Ocaml track: lecture 7

CS558 Programming Languages

To figure this out we need a more precise understanding of how ML works

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

(Provisional) Lecture 22: Rackette Overview, Binary Tree Analysis 10:00 AM, Oct 27, 2017

CMSC 330: Organization of Programming Languages

Recap: Functions as first-class values

CS558 Programming Languages

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

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

The role of semantic analysis in a compiler

Typical workflow. CSE341: Programming Languages. Lecture 17 Implementing Languages Including Closures. Reality more complicated

So what does studying PL buy me?

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CSE 12 Abstract Syntax Trees

Functions. Nate Foster Spring 2018

Interpreters. Prof. Clarkson Fall Today s music: Step by Step by New Kids on the Block

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

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

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

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

Lecture 13 CIS 341: COMPILERS

CS558 Programming Languages

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

Whereweare. CS-XXX: Graduate Programming Languages. Lecture 7 Lambda Calculus. Adding data structures. Data + Code. What about functions

Data Types. Guest Lecture: Andrew Myers Spring 2018

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

CMSC 330: Organization of Programming Languages

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

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

CSCE 314 Programming Languages. Type System

CSE 341: Programming Languages

CSE 341 : Programming Languages

Compiler construction

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

Data Types. Prof. Clarkson Fall Today s music: Pokémon Theme by Jason Paige

Compilers: The goal. Safe. e : ASM

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

Concepts of Programming Languages

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

Note that in this definition, n + m denotes the syntactic expression with three symbols n, +, and m, not to the number that is the sum of n and m.

Lecture 5: The Untyped λ-calculus

CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions

Syntax Errors; Static Semantics

An Introduction to Functions

CS 242. Fundamentals. Reading: See last slide

CS558 Programming Languages

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

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

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

CS 11 Haskell track: lecture 1

CS 6110 S11 Lecture 12 Naming and Scope 21 February 2011

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Programs as data first-order functional language type checking

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

CS558 Programming Languages. Winter 2013 Lecture 3

Lecture 15 CIS 341: COMPILERS

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

CSCI B522 Lecture 11 Naming and Scope 8 Oct, 2009

Programming Languages

Chapter 1. Fundamentals of Higher Order Programming

COMP 1130 Lambda Calculus. based on slides by Jeff Foster, U Maryland

Functions & First Class Function Values

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

ENVIRONMENT MODEL: FUNCTIONS, DATA 18

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

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

CSCI-GA Scripting Languages

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

CS 415 Midterm Exam Spring 2002

G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

Ways to implement a language

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Late Binding; OOP as a Racket Pattern

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

Functional Programming. Pure Functional Programming

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

Organization of Programming Languages CS3200/5200N. Lecture 11

From the λ-calculus to Functional Programming Drew McDermott Posted

Transcription:

The Environment Model Nate Foster Spring 2018

Review Previously in 3110: Interpreters: ASTs, evaluation, parsing Formal syntax: BNF Formal semantics: dynamic: small-step substitution model static semantics Today: More formal dynamic semantics: large-step, environment model

Review Small-step substitution model: substitute value for variable in body of let and functions Good mental model Not efficient: too much substitution at run time Big-step environment model: maintain a dictionary that binds variables to values What OCaml really does

New evaluation relation Big-step semantics: we model just the reduction from the original expression to the final value Suppose e --> e' -->... --> v Abstract to e ==> v forget intermediate expressions read as e evaluates down to v, equiv. e big-steps to v textbook notation: e v Goal: for all expressions e and values v, e ==> v if and only if e -->* v A 4110 theorem

Values Constants are already done evaluating 42 ==> 42 true ==> true In fact, all values big-step to themselves v ==> v

Operator evaluation e1 + e2 ==> v if e1 ==> i1 and e2 ==> i2 and v is the result of primitive operation i1 + i2 e.g., "big" ^ "red" ==> "bigred" 1 + 2 ==> 3 1 + (2+3) ==> 6

Variables What does a variable name evaluate to? x ==>??? Trick question: we don t have enough information to answer it Need to know what value variable was bound to e.g., let x = 2 in x+1 e.g., (fun x -> x+1) 2 e.g., match 2 with x -> x+1 All evaluate to 3, but we reach a point where we need to know binding of x Until now, we've never needed this, because we always substituted before we ever get to a variable name

Variables OCaml doesn't actually do substitution (fun x -> 42) 0 waste of runtime resources to do substitution inside 42 Instead, OCaml lazily substitutes by maintaining dynamic environment

Dynamic environment Dictionary of bindings of all current variables Changes throughout evaluation: No bindings at $: $ let x = 42 in let y = false in e One binding {x:42} at $: let x = 42 in $ let y = false in e Two bindings {x:42,y:false} at $: let x = 42 in let y = false in $ e

Variable evaluation To evaluate x in environment env Look up value v of x in env Return v Type checking guarantees that variable is bound, so we can t ever fail to find a binding in dynamic environment

Evaluation relation Extended notation: <env, e> ==> v Meaning: in dynamic environment env, expression e big-steps to value v <env, e> is called a machine configuration

Variable evaluation <env, x> ==> v if v = env(x) env(x): meaning: the value to which env binds x think of it as looking up x in dictionary env

Redo: evaluation with environment <env, v> ==> v <env, e1 + e2> ==> v if <env, e1> ==> i1 and <env, e2> ==> i2 and v is the result of primitive operation i1+i2

Let expressions To evaluate let x = e1 in e2 in environment env Evaluate the binding expression e1 to a value v1 in environment env <env, e1> ==> v1 Extend the environment to bind x to v1 env = env[x -> v1] new notation Evaluate the body expression e2 to a value v2 in extended environment env <env, e2> ==> v2 Return v2

Let expression evaluation rule <env, let x=e1 in e2> ==> v2 if <env, e1> ==> v1 and <env[x -> v1], e2> ==> v2 Example: (let {} be the empty environment) <{},let x = 42 in x> ==> 42 Because... <{}, 42> ==> 42 and <{}[x -> 42], x> ==> 42 Because {x:42}(x)=42

Function values v1.0 Anonymous functions are values: <env, fun x -> e> ==> fun x -> e

Function application v1.0 To evaluate e1 e2 in environment env Evaluate e1 to a value v1 in environment env <env,e1> ==> v1 Note that v1 must be a function value fun x -> e because function application type checks Evaluate e2 to a value v2 in environment env <env,e2> ==> v2 Extend environment to bind formal parameter x to actual value v2 env = env[x -> v2] Evaluate body e to a value v in environment env <env,e> ==> v Return v

Function application rule v1.0 <env,e1 e2> ==> v if <env,e1> ==> fun x -> e and <env,e2> ==> v2 and <env[x -> v2],e> ==> v Example: <{},(fun x -> x) 1> ==> 1 b/c <{},fun x -> x> ==> fun x -> x and <{},1> ==> 1 and <{}[x -> 1], x> ==> 1

Why different answers? Two different rules for variable scope: Rule of dynamic scope (our semantics so far) Rule of lexical scope (OCaml)

Dynamic scope Rule of dynamic scope: The body of a function is evaluated in the current dynamic environment at the time the function is called, not the old dynamic environment that existed at the time the function was defined. Causes our semantics to use latest binding of x Thus return 2

Lexical scope Rule of lexical scope: The body of a function is evaluated in the old dynamic environment that existed at the time the function was defined, not the current environment when the function is called. Causes OCaml to use earlier binding of x Thus return 1

Lexical scope Rule of lexical scope: The body of a function is evaluated in the old dynamic environment that existed at the time the function was defined, not the current environment when the function is called. Causes OCaml to use earlier binding of x Thus return 1

Lexical vs. dynamic scope Consensus after decades of programming language design is that lexical scope is the right choice it supports the Principle of Name Irrelevance: name of variable shouldn't matter to meaning of program programmers free to change names of local variables type checker can prevent more run-time errors Dynamic scope is useful in some situations Some languages use it as the norm (e.g., Emacs LISP, LaTeX) Some languages have special ways to do it (e.g., Perl, Racket) But most languages just don t have it Exception handling resembles dynamic scope: raise e transfers control to the most recent exception handler like how dynamic scope uses most recent binding of variable 26

Implementing time travel Q: How can functions be evaluated in old environments? A: The language implementation keeps old environments around as necessary 27

Implementing time travel A function value is really a data structure called a function closure that has two parts: The code, an expression e The environment env that was current when the function was defined We'll notate that data structure as ( e, env ) ( e, env ) is like a pair But indivisible: you cannot write OCaml syntax to access the pieces And inexpressible: you cannot directly write it in OCaml syntax

Function application v2.0 orange = changed from v1.0 To evaluate e1 e2 in environment env Evaluate e1 to a value v1 in environment env <env,e1> ==> v1 Note that v1 must be closure ( fun x -> e, defenv ) Evaluate e2 to a value v2 in environment env <env,e2> ==> v2 Extend closure environment to bind formal parameter x to actual value v2 env = defenv[x -> v2] Evaluate body e to a value v in environment env <env,e> ==> v Return v

Function application rule v2.0 <env, e1 e2> ==> v if <env, e1> ==> ( fun x -> e, defenv ) and <env, e2> ==> v2 and <defenv[x -> v2], e> ==> v

Function values v2.0 Anonymous functions fun x-> e are closures: <env, fun x -> e> ==> ( fun x -> e, env )

Closures in OCaml bytecode compiler https://github.com/ocaml/ocaml/search?q=kclosure

Closures in Java Nested classes can simulate closures Used everywhere for Swing GUI! http://docs.oracle.com/javase/tutorial/uiswing/event s/generalrules.html#innerclasses You ve done it yourself already in 2110 Java 8 adds higher-order functions and closures

Closures in C In C, a function pointer is just a code pointer, period. No environment. To simulate closures, a common idiom: Define function pointers to take an extra, explicit environment argument But without generics, no good choice for type of list elements or the environment Use void* and various type casts From Linux kernel: http://lxr.freeelectrons.com/source/include/linux/kthread.h#l13 34

Interpreter for expr. lang. See interp4.ml in code for this lecture for implementation with closures

Upcoming events [today] A4 out [tomorrow] spring break starts!