Procedures. EOPL3: Section 3.3 PROC and App B: SLLGEN

Similar documents
Lecture 3: Expressions

Lecture 12: Conditional Expressions and Local Binding

B The SLLGEN Parsing System

Lecture 2: Data Types and their Representations; Syntax: Scanning and Parsing

Konzepte von Programmiersprachen

Mid-Term 2 Grades

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

Functional Programming. Pure Functional Programming

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

Lexical 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>)

Comp 411 Principles of Programming Languages Lecture 7 Meta-interpreters. Corky Cartwright January 26, 2018

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Comp 311: Sample Midterm Examination

Data Abstraction. An Abstraction for Inductive Data Types. Philip W. L. Fong.

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

CS 342 Lecture 8 Data Abstraction By: Hridesh Rajan

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

Principles of Programming Languages

Principles of Programming Languages 2017W, Functional Programming

A LISP Interpreter in ML

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

Lecture 16: Object Programming Languages

An Introduction to Functions

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

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Discussion 12 The MCE (solutions)

CMSC 330: Organization of Programming Languages

Lecture 15 CIS 341: COMPILERS

Higher-Order Functions (Part I)

Functions & First Class Function Values

COP4020 Programming Assignment 1 - Spring 2011

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

Higher-Order Functions

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

CS 360 Programming Languages Interpreters

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

Programming Languages and Compilers (CS 421)

Introduction to Scheme

Hofl, a Higher-order Functional Language. 1 An Overview of Hofl. 2 Abstractions and Function Applications

Compiling and Interpreting Programming. Overview of Compilers and Interpreters

FOFL and FOBS: First-Order Functions

Essentials of Programming Languages Language

Essentials of Programming Languages Language

CS251 Programming Languages Handout # 36 Prof. Lyn Turbak April 4, 2007 Wellesley College Revised April 14, Scoping in Hofl

Building up a language SICP Variations on a Scheme. Meval. The Core Evaluator. Eval. Apply. 2. syntax procedures. 1.

CMSC 330: Organization of Programming Languages. Lambda Calculus

CS 415 Midterm Exam Spring 2002

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

CMSC 330: Organization of Programming Languages. Operational Semantics

Turtles All The Way Down

1. For every evaluation of a variable var, the variable is bound.

CSE341, Spring 2013, Final Examination June 13, 2013

CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018

Code example: sfact SICP Explicit-control evaluator. Example register machine: instructions. Goal: a tail-recursive evaluator.

CS 275 Name Final Exam Solutions December 16, 2016

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

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

Assigning to a Variable

Hofl: First-class Functions and Scoping

cs173: Programming Languages Midterm Exam

CVO103: Programming Languages. Lecture 5 Design and Implementation of PLs (1) Expressions

The role of semantic analysis in a compiler

Project 2: Scheme Interpreter

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

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

Name EID. (calc (parse '{+ {with {x {+ 5 5}} {with {y {- x 3}} {+ y y} } } z } ) )

Environments

CMSC 330: Organization of Programming Languages

COP4020 Programming Languages. Compilers and Interpreters Robert van Engelen & Chris Lacher

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP)

CMSC 330: Organization of Programming Languages. Lambda Calculus

Ruby: Introduction, Basics

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

9 Objects and Classes

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

Basics of Using Lisp! Gunnar Gotshalks! BLU-1

Scala : an LLVM-targeted Scala compiler

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

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

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

The Environment Model. Nate Foster Spring 2018

Functional Programming. Pure Functional Languages

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

CA Compiler Construction

LECTURE 3. Compiler Phases

Functional Programming

CS 314 Principles of Programming Languages

CSE 401 Midterm Exam Sample Solution 2/11/15

A lexical analyzer generator for Standard ML. Version 1.6.0, October 1994

Principles of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages

Implementing Continuations

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

Functions and Recursion. Dr. Philip Cannata 1

C311 Lab #3 Representation Independence: Representation Independent Interpreters

Agenda. CS301 Session 9. Abstract syntax: top level. Abstract syntax: expressions. The uscheme interpreter. Approaches to solving the homework problem

CS 342 Lecture 6 Scheme Procedures and Closures By: Hridesh Rajan

CMSC 330: Organization of Programming Languages

Decaf Language Reference Manual

Lecture 13 CIS 341: COMPILERS

Transcription:

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) PROC includes all of LET language Anonymous procedure One parameter always CS7100(pm) 2

Semantics of Procedures (This slide is for procedures in general.) Procedure Definition Store formal parameters and body Procedure Invocation Evaluate body in an environment that binds formals to actual argument values Interpretation of free-variables: Two methods Use env at proc definition (lexical/static scoping) Use env at proc call (dynamic scoping) CS7100(pm) 3

Scoping and Binding references (f x y) f, x, and y declarations (lambda (x) (+ x 3)) (let ((x (+ y 7))) (+ x 3)) y, and second/right x are refs first/left x is a declaration lexical scoping rules CS7100(pm) 4

Kinds of Scope Static or Lexical scope determined by structure of program Scheme, C++, Java, and many compiled languages Dynamic scope determined by path of execution Lisp dialects, Perl, and many interpreted languages Global Scope File scope Local Scope Block Body of a procedure Body of a loop Scope alters the meaning CS7100(pm) 5

Example-1 of PROC let f = proc (x) --(x,11) in (f (f 77)) Defines an anonymous procedure with one formal parameter named x. Body of the procedure: --(x,11) Binds the name f to this procedure. Invokes f with actual argument 77. Invokes f again with the result of above. (will use two -- just for visibility) CS7100(pm) 6

Example-2 of PROC (proc (f) (f (f 77)) proc (x) --(x,11)) This example is derived from the production Expression ::= (Expression Expression) so is (f (f 77)) so is (f 77) proc (f) (f (f 77)) is the rator. It defines an anonymous procedure with one formal parameter named f. proc (x) --(x,11)) is the rand. It also defines an anonymous procedure with one formal parameter named x. CS7100(pm) 7

Example-3 of PROC let x = 200 in let f = proc (z) --(z, x) in let x = 100 in let g = proc (z) --(z, x) in --((f 1), (g 1)) Illustrates scope issues x and z appear four times each. Lexical scoping In --((f 1), (g 1)), the bodies of f and g must be evaluated in the env they were defined. In f, x is bound to 200 In g, x is bound to 100 CS7100(pm) 8

Example Programs of PROC Example-1 and -2 produce same result, but different mechanisms. Previous two slides gave semantics informally Watch out: a very seductive approach Next few slides: interpreter based CS7100(pm) 9

Example Calc w/ Spec 1 CS7100(pm) 10

Example Calc w/ Spec 2 CS7100(pm) 11

Example Calc w/ Spec 3 CS7100(pm) 12

Example Calc w/ Spec 4 CS7100(pm) 13

Recall value-of value-of is an operator with two operands an AST an environment (value-of ast env) PROC = LET + two more productions Bring in all value-of specs from LET Additions are shown on next few slides CS7100(pm) 14

additional value-of specs (value-of (proc-exp var body) ρ) = (proc-val (procedure var body ρ)) (value-of (call-exp rator rand) ρ) = (let ( (proc (expval->proc (value-of rator ρ))) (arg (value-of rand ρ))) (apply-procedure proc arg)) To be defined: proc-val, apply-procedure CS7100(pm) 15

Spec of apply-procedure (apply-procedure (procedure var body ρ) val) = (value-of body [var=val]ρ ) apply-procedure takes two arguments: an AST of a procedure definition an argument for the parameter of the procedure yields an expressed value CS7100(pm) 16

Impl of apply-procedure (define proc? (lambda (pc) (procedure? pc))) (define procedure (lambda (var body env) (lambda (val) (value-of body (extend-env var val (define apply-procedure (lambda (pc val) (pc val))) env))))) procedure? provided from r5rs Names being bound: proc? procedure apply-procedure env is an environment ASTs: body, pc, val, var Use of procedure? is too liberal. procedure is not self-contained; takes three arguments: param name var body AST environment CS7100(pm) 17

Alternate impl called Closures (define-datatype proc proc? (procedure (var identifier?) (body expression?) (saved-env environment?))) (define apply-procedure (lambda (pc val) (cases proc pc (procedure (var body saved-env) (value-of body (extend-env var val saved-env)))))) Defining a new data type called proc Has only one variant procedure That has three parts var which must be an id body an expression saved-env an environment apply-procedure takes pc and val. cases proc pc pc is expected to be of type proc code for each variant of proc only one variant procedure here CS7100(pm) 18

the data type expval is now (define-datatype expval expval? (num-val (num number?)) (bool-val (bool boolean?)) (proc-val (proc proc?))) CS7100(pm) 19

value-of: two new clauses (proc-exp (var body) (proc-val (procedure var body env))) (call-exp (rator rand) (let ( (proc (expval->proc (value-of rator env))) (arg (value-of rand env))) (apply-procedure proc arg))) CS7100(pm) 20

Curried procedures In PROC, procedures with multiple arguments can be had as in: let f = proc (x) proc (y)... in ((f 3) 4) proc (x) yields a procedure Named after Haskell Brooks Curry (1900 1982), a combinatory logician. CS7100(pm) 21

chapter3/proc-lang/ Two subdirectories chapter3/proc-lang/proc-rep: procedural implementation chapter3/proc-lang/ds-rep: data type based (i.e., closure) Both directories have the following files data-structures.scm drscheme-init.scm environments.scm interp.scm lang.scm tests.scm top.scm CS7100(pm) 22

EOPL3 Appendix B SLLGEN (define scanner-spec-1...) (define grammar-1...) (sllgen:make-define-datatypes scanner-spec-1 grammar-1) (define list-the-datatypes (lambda () (sllgen:list-define-datatypes scanner-spec-1 grammar-1))) (define just-scan (sllgen:make-string-scanner scannerspec-1 grammar-1)) (define scan&parse (sllgen:make-string-parser scannerspec-1 grammar-1)) (define read-eval-print (sllgen:make-rep-loop "--> " valueof--program (sllgen:make-stream-parser scannerspec-1 grammar-1))) sllgen:make-definedatatypes: generates a define-datatype for each production of the grammar, for use by cases. sllgen:make-string-scanner takes a scanner spec and a grammar and generates a scanning procedure read-eval-print loop CS7100(pm) 23

Lexical Analysis (define the-lexical-spec '((whitespace (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol) (number (digit (arbno digit)) number) (number ("-" digit (arbno digit)) number) )) the-lexical-spec from chapter3/ proc-lang/*/lang.scm scanners are specified by reg exp next slide All our languages use this lexical analysis. CS7100(pm) 24

SLLGEN Scanner Spec Scanner-spec ::= ({Regexp-and-action} ) Regexp-and-action ::= (Name ({Regexp} ) Action) Name ::= Symbol Regexp ::= String letter digit whitespace any ::= (not Character) (or {Regexp} ) ::= (arbno Regexp) (concat {Regexp} ) Action ::= skip symbol number string A scanner specification in SLLGEN is a list that satisfies the grammar at left CS7100(pm) 25

The SLLGEN Parsing System (define the-grammar '((program (expression) a-program) (expression (number) const-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression (identifier) var-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) the-grammar of PROC from chapter3/ proc-lang/*/lang.scm Double-quoted items are terminals/tokens. (expression ("proc" "(" identifier ")" expression) proc-exp) (expression ("(" expression expression ")") call-exp) )) CS7100(pm) 26

Specifying Grammars Grammar ::= ({Production} ) Production ::= (Lhs ({Ritem} ) Prodname) Lhs ::= Symbol Ritem ::= Symbol String ::= (arbno {Ritem} ) ::= (separated-list {Ritem} String) Prod-name ::= Symbol A grammar in SLLGEN is a list described by the grammar at left CS7100(pm) 27

HW2 Problem (define closure (lambda (ids body env) (let ((freevars (set-diff (free-vars body) ids))) (let ((saved-env (extend-env freevars (map (lambda (v) freevars) (empty-env)))) (lambda (args) (eval-expression body (extend-env ids args saved-env))))))) (apply-env env v)) http://www.cs.wright.edu/~pmateti/cour ses/7100/top/7100-hw2.html In our data-structure representation of procedures, we have kept the entire environment in the closure. But of course all we need are the bindings for the free variables. Modify the representation of procedures to retain only the free variables. flat closure rep shown left consists of exactly one rib of free variables and their values. free-vars: ykwim ;-) set-diff: difference of two sets map provided from r5rs CS7100(pm) 28