1 The metacircular evaluator. 2 2. Names Extend the calculator to store intermediate results as named values (define x (+ 4 5)) store result as x (+ x.

Slides:



Advertisements
Similar presentations
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Advertisements

Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is a good way to learn more about programming languages  Interpreters are.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
Scheme in Scheme?!? …the metacircular evaluator….
1 Programming Languages (CS 550) Operational Semantics of Scheme using Substitution and the Lambda Calculus Jeremy R. Johnson TexPoint fonts used in EMF.
Metacircular Evaluation SICP Chapter 4 Mark Boady.
1 Programming Languages (CS 550) Lecture 7 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts used in EMF. Read.
מבוא מורחב למדעי המחשב תרגול 13 Lazy Evaluation. Lazy Evaluation Implementation Two types of values – Delayed Values – Actual Values Introduce two functions.
1 The Metacircular Evaluator Chapter 4 Section 4.1 We will not cover every little detail in the lectures, so you MUST read Section 4.1 in full.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 11. Metacircular Evaluator 4.1, pages definitions file on web 2.
(define applicative-eval (lambda (exp) (cond ((atomic? exp) (eval-atomic exp)) ((special-form? exp) (eval-special-form exp)) ((list-form? exp) (eval-list.
1 Lecture 18 Continue Evaluator. 2 z9 true#t + twice Representing procedures (eval '(define twice (lambda (x) (+ x x))) GE) symbol primitive scheme procedure.
6.001 SICP 1 Normal (Lazy) Order Evaluation Memoization Streams.
David Evans CS200: Computer Science University of Virginia Computer Science Lecture 26: In Praise of Idleness.
Functional programming: LISP Originally developed for symbolic computing Main motivation: include recursion (see McCarthy biographical excerpt on web site).
SICP Interpretation part 1 Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 21. Overview 1. Dynamic Binding 2. Lazy Evaluation 3. More MC-Eval 2.
Lexical vs. Dynamic Scope …where do I point to?. Intro… Remember in Scheme whenever we call a procedure we pop a frame and point it to where the procedure.
6.001 SICP SICP – Evaluation I Recitation 11/19/2004 Eval review Evaluation examples define lambda apply New language elements.
SICP Variations on a Scheme Scheme Evaluator – A Grand Tour Techniques for language design: Interpretation: eval/apply Semantics vs. syntax Syntactic.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Scheme More MCE examples. Q1 new special form which defines global variables (static ) search the global environment – Variable exists: does nothing,
SICP Variations on a Scheme (2) Beyond Scheme – designing language variants: Lazy evaluation Complete conversion – normal order evaluator Upward.
The environment model evaluator and compiler 1 The env model evaluator Motivation In one word: Efficiency Saves repeated renaming and substitution: Using.
1 Saves repeated renaming and substitution: explicit substitution is replaced by variable bindings using new data structures (frame, environment). Can.
1 Continue Evaluator. 2 z9 true#t + twice Representing procedures (eval '(define twice (lambda (x) (+ x x))) GE) symbol primitive scheme procedure + symbol.
Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is aa good way to learn more about programming languages  Interpreters are.
1 The metacircular evaluator (Cont.) Defining new procedures (define (lambda? e) (tag-check e 'lambda)) (define (eval exp env) (cond ((number? exp)
Scheme in Scheme 1. Why implement Scheme in Scheme  Implementing a language is a good way to learn more about programming languages  Interpreters are.
CS220 Programming Principles 프로그래밍의 이해 2002 가을학기 Class 15: Meta-Circular Evaluator 한 태숙.
SICP Interpretation Parts of an interpreter Arithmetic calculator Names Conditionals and if Storing procedures in the environment Environment as.
1 Subt. model interpreter: Structure of the interpreter ASP Derived expressions Core Test Data structures Utils A racket lib Proc / Primitive-Proc. Global.
Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is a good way to learn more about programming languages  Interpreters are.
SICP Explicit-control evaluator Big ideas: how to connect evaluator to machine instructions how to achieve tail recursion Obfuscation: tightly.
The environment-based operational semantics Chapter
מבוא מורחב 1 Lecture #9. מבוא מורחב 2 Symbol: a primitive type constructors: (quote alpha) ==> quote is a special form. One argument: a name. selectors.
1 Lecture 20 Lazy Evaluation Continued (4.2.1, 4.2.2) MC-eval examples from exams (Time permitting)
1 Read-Eval-Print Loop (define (driver-loop) (prompt-for-input input-prompt) (let ((input (read))) (let ((output (eval input the-global-env))) (announce-output.
1 Subt. model interpreter: Introduction Abstract Syntax Parser Abstract Syntax Parser Derived Expressions Core Test Data Structures Utils (a racket lib)
1 Programming Languages (CS 550) Lecture 4 Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
1 Env. Model Implementation & Analyzer Practice Session #10 Env. Model Implementation & Analyzer Practice Session #10.
1 Lecture 19 Dynamic Scoping Lazy Evaluation (4.2.1, 4.2.2)
1/ SICP Variations on a Scheme Scheme Evaluator – A Grand Tour Making the environment model concrete Defining eval defines the language –Provides.
CS 598 Scripting Languages Design and Implementation 10. Interpreters Part I: Lisp.
1 Lecture 19 Review last lecture on evaluator, Dynamic Scoping Lazy Evaluation (4.2.1, 4.2.2)
CS61A Lecture Colleen Lewis 1. Clicker poll Are you in a two person group for project 4? A)Yes – I have my partner B)No – I plan to work.
1 Vectors, binary search, and sorting. 2 We know about lists O(n) time to get the n-th item. Consecutive cons cell are not necessarily consecutive in.
1 The Evaluator. 2 Compiler vs. Interpreter Command Processing Unit The Computer Program in Low Level Machine Language Program in High Level Language.
Evaluators for Functional Programming 1. How to describe (specify) a programming language? 1.Syntax: atoms, primitives, combination and abstraction means.
SICP Interpretation part 2 Store operators in the environment Environment as explicit parameter Defining new procedures.
Operational Semantics of Scheme
Lecture 4: Metacircles Eval Apply David Evans
6.001 SICP Variations on a Scheme
6.001 SICP Object Oriented Programming
Env. Model Implementation
Original material by Eric Grimson
The Metacircular Evaluator
Dynamic Scoping Lazy Evaluation
The Metacircular Evaluator
The Metacircular Evaluator (Continued)
Lecture 26: The Metacircular Evaluator Eval Apply
6.001 SICP Further Variations on a Scheme
Streams, Delayed Evaluation and a Normal Order Interpreter
Lecture #9 מבוא מורחב.
6.001 SICP Variations on a Scheme
6.001 SICP Interpretation Parts of an interpreter
topics interpreters meta-linguistic abstraction eval and apply
Rehearsal: Lazy Evaluation Infinite Streams in our lazy evaluator
Lecture 25: The Metacircular Evaluator Eval Apply
Presentation transcript:

1 The metacircular evaluator

2 2. Names Extend the calculator to store intermediate results as named values (define x (+ 4 5)) store result as x (+ x 2) use that result Store bindings between names and values in a table

3 2. Names ( define (define? exp) (tag-check exp 'define)) (define (eval exp) (cond ((number? exp) exp) ((symbol? exp) (lookup exp)) ((sum? exp) (eval-sum exp)) ((define? exp) (eval-define exp)) (else (error "unknown expression " exp)))) (define environment (make-frame nil nil)) (define (lookup name) (lookup-variable-value name environment)) (define (eval-define exp) (let ((name (cadr exp)) (defined-to-be (eval (caddr exp)))) (add-binding-to-frame! name defined-to-be environment) ‘undefined))

4 (define (make-frame variables values) (cons variables values)) (define (lookup-variable-value var frame) (define (scan vars vals) (cond ((null? vars) (error "Unbound variable" var)) ((eq? var (car vars) (car vals)) (else (scan (cdr vars) (cdr vals))))) (let ((vars (car frame)) (vals (cdr frame))) (scan vars vals))) (define (add-binding-to-frame! var val frame) (set-car! frame (cons var (car frame))) (set-cdr! frame (cons val (cdr frame))))

5 The environment is a single frame list of values list of variables frame xy4 5

6 Evaluation of (eval '(define x (+ 4 5))) (eval '(+ 4 5)) (eval 4) ==> 4 (eval 5) ==> 5 ==> 9 names values x 9 ==> undefined (eval '(+ x 2)) (eval 'x) ==> 9 (eval 2) ==> 2 ==> 11 (define x (+ 4 5)) (+ x 2)

7 2. Things to observe Use scheme function symbol? to check for a name the reader converts sequences of characters like "x" to symbols in the parse tree Can use any implementation of the environment, in particular we could use put and get from previous lectures. eval-define recursively calls eval on the second subtree but not on the first one eval-define returns a special undefined value

8 3. Conditionals and if Extend the calculator to handle conditionals and if: (if (> y 6) (+ y 2) 15) > an operation that returns a boolean if an operation that evaluates the first subexp, checks if value is true or false

9 3. Conditionals and if (define (greater? exp) (tag-check exp ’>)) (define (if? exp) (tag-check exp 'if)) (define (eval exp) (cond ((number? exp) exp) ((symbol? exp) (lookup exp)) ((sum? exp) (eval-sum exp)) ((greater? exp) (eval-greater exp)) ((define? exp) (eval-define exp)) ((if? exp) (eval-if exp)) (else (error "unknown expression " exp)))) (define (eval-greater exp) (> (eval (cadr exp)) (eval (caddr exp))))

10 (define (eval-if exp) (if (true? (eval (if-predicate exp))) (eval (if-consequent exp)) (eval (if-alternative exp)))) (define (if-predicate exp) (cadr exp)) (define (if-consequent exp) (caddr exp)) (define (if-alternative exp) (if (not (null? (cdddr exp))) (cadddr exp) 'false)) (define (true? x) (not (eq? x #f))) (define (false? x) (eq? x #f)) (eval '(define y 9)) (eval '(if (> y 6) (+ y 2) 15))

11 We are just walking through a tree … (eval ) 6y> if 6y>2y+ 15 Then (eval ) or (eval 15 ) 2y>

12 Evaluation of (eval '(if (> y 6) (+ y 2) 15)) (eval '(> y 6)) (eval 'y) ==> 9 (eval 6) ==> 6 ==> #t (eval '(+ y 2)) (eval 'y) ==> 9 (eval 2) ==> 2 ==> 11

13 3. Things to observe eval-greater is just like eval-sum from page 1 recursively call eval on both argument expressions call scheme > to compute value eval-if does not call eval on all argument expressions: call eval on the predicate call eval on the consequent or on the alternative but not both

14 4. Store operators in the environment Want to add lots of operators but keep eval short Operations like + and > are similar evaluate all the argument subexpressions perform the operation on the resulting values Call this standard pattern an application Implement a single case in eval for all applications Approach: eval the first subexpression of an application put a name in the environment for each operation value of that name is an procedure apply the procedure to the operands

15 4. Store procedures in the environment (define (application? e) (pair? e)) (define (eval exp) (cond ((number? exp) exp) ((symbol? exp) (lookup exp)) ((define? exp) (eval-define exp)) ((if? exp) (eval-if exp)) ((application? exp) (apply (eval (car exp)) (map eval (cdr exp)))) (else (error "unknown expression " exp)))) ;; rename scheme’s apply so we can reuse the name (define scheme-apply apply) (define (apply procedure arguments) (if (primitive-procedure? procedure) (apply-primitive-procedure procedure arguments) (error "operator not a procedure: " procedure))) (define (apply-primitive-procedure proc args) (scheme-apply (primitive-implementation proc) args))

16 4. Store procedures in the environment (define prim-tag 'primitive) (define (make-primitive scheme-proc)(list prim-tag scheme-proc)) (define (primitive-procedure? e) (tag-check e prim-tag)) (define (primitive-implementation prim) (cadr prim)) (define environment (make-frame nil nil)) (add-binding-to-frame! environment ’+ (make-primitive +)) (add-binding-to-frame! environment ’> (make-primitive >)) (add-binding-to-frame! environment 'true #t) (eval '(define z 9)) (eval '(+ 9 6)) (eval '(if true 10 15))

17 The Environment after first green line names values z 9 true #t > + symbol primitive scheme procedure > symbol primitive scheme procedure +

18 Evaluation of (+ 9 6) (eval '(+ 9 6)) (apply (eval +) (map eval '(9 6))) (apply '(primitive #[add]) (list (eval 9) (eval 6)) (apply '(primitive #[add]) '(9 6)) (scheme-apply (primitive-implementation '(primitive #[add])) '(9 6)) (scheme-apply #[add] '(9 6)) 15

19 Evaluation of (if true 10 15) (eval '(if true 10 15)) (eval-if '(if true 10 15)) (if (true? (eval 'true))...) (if (true? (lookup 'true)))...) (if (true? #t)...) (eval 10) 10 Apply is never called!

20 4. Things to observe applications must be last case in eval no tag check applications evaluate all subexpressions expressions that need special handling, like if, gets their own case in eval

21 5. Environment as explicit parameter change from (eval '(+ 6 4)) to (eval '(+ 6 4) environment) all procedures that call eval have extra argument lookup and define use environment from argument No other change from evaluator 4

22 5. Environment as explicit parameter ;This change is boring! Exactly the same functionality as #4. (define (eval exp env) (cond ((number? exp) exp) ((symbol? exp) (lookup exp env)) ((define? exp) (eval-define exp env)) ((if? exp) (eval-if exp env)) ((application? exp) (apply (eval (car exp) env) (map (lambda (e) (eval e env)) (cdr exp)))) (else (error "unknown expression " exp)))) (define (lookup name env) (lookup-variable-value name env)) (define (eval-define exp env) (let ((name (cadr exp)) (defined-to-be (eval (caddr exp) env))) (add-binding-to-frame! name defined-to-be env) ‘undefined))

23 5. Environment as explicit parameter (define (eval-if exp env) (if (true? (eval (if-predicate exp) env)) (eval (if-consequent exp) env) (eval (if-alternative exp) env)))

24 6. Defining new procedures Want to add new procedures For example, a scheme program: (define twice (lambda (x) (+ x x))) (twice 4) Strategy: Add a case for lambda to eval –the value of lambda is a compound procedure Extend apply to handle compound procedures Implement environment model

25 6. Defining new procedures (define (lambda? e) (tag-check e 'lambda)) (define (eval exp env) (cond ((number? exp) exp) ((symbol? exp) (lookup exp env)) ((define? exp) (eval-define exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (eval-lambda exp env)) ((application? exp) (apply (eval (car exp) env) (map (lambda (e) (eval e env)) (cdr exp)))) (else (error "unknown expression " exp)))) (define (eval-lambda exp env) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) (define (lambda-parameters exp) (cadr exp)) (define (lambda-body exp) (cddr exp)) (define (make-procedure parameters body env) (list 'procedure parameters body env))

26 6. Defining new procedures (define (apply procedure arguments) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) arguments (procedure-env procedure)))) (else (error "Unknown procedure type -- APPLY" procedure)))) (define (compound-procedure? exp) (tag-check exp ‘procedure)) (define (procedure-parameters compound) (cadr compound)) (define (procedure-body compound) (caddr compound)) (define (procedure-env compound) (cadddr compound))

27 (define (eval-sequence exps env) (cond ((last-exp? exps) (eval (first-exp exps) env)) (else (eval (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) (define (last-exp? seq) (null? (cdr seq))) (define (first-exp seq) (car seq)) (define (rest-exps seq) (cdr seq))

28 How the Environment Works Abstractly – in our environment diagrams: Concretely – our implementation (as in SICP) E2 x: 10 plus: (procedure...) E1 environment manipulation 3. list of values enclosing- environment list of variables frame xplus 10 E2 procedure

29 Extending the Environment (extend-environment '(x y) (list 4 5) E2) E1 E2 x: 10 plus: (procedure...) E3 x: 4 y: 5 Abstractly Concretely E2 list of values list of variables frame xy4 E3 5 E1

30 (define (extend-environment vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied" vars vals) (error "Too few arguments supplied" vars vals))))

31 "Scanning" the environment Look for a variable in the environment... Look for a variable in a frame... –loop through the list of vars and list of vals in parallel –detect if the variable is found in the frame If not found in frame (out of variables in the frame), look in enclosing environment

32 (define (lookup-variable-value var env) (define (env-loop env) (define (scan vars vals) (cond ((null? vars) (env-loop (enclosing-environment env))) ((eq? var (car vars)) (car vals)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env)) (define (frame-variables frame) (car frame)) (define (frame-values frame) (cdr frame)) (define (enclosing-environment env) (cdr env))

33 (define (define-variable! var val env) (let ((frame (first-frame env))) (define (scan vars vals) (cond ((null? vars) (add-binding-to-frame! var val frame)) ((eq? var (car vars)) (set-car! vals val)) (else (scan (cdr vars) (cdr vals))))) (scan (frame-variables frame) (frame-values frame)))) (define (eval-define exp env) (let ((name (cadr exp)) (defined-to-be (eval (caddr exp) env))) (define-variable! name defined-to-be env) ‘undefined))