Metacircular Evaluation SICP Chapter 4 Mark Boady.

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.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
Scheme in Scheme?!? …the metacircular evaluator….
1 The metacircular evaluator Names Extend the calculator to store intermediate results as named values (define x (+ 4 5)) store result as x (+ x.
1 Programming Languages (CS 550) Operational Semantics of Scheme using Substitution and the Lambda Calculus Jeremy R. Johnson TexPoint fonts used in EMF.
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.
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.
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,
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.
1 Programming Languages (CS 550) Lecture 5 Summary Object Oriented Programming and Implementation* Jeremy R. Johnson *Lecture based on notes from SICP.
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.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
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.
Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is a good way to learn more about programming languages  Interpreters are.
1 The Evaluator. 2 Compiler vs. Interpreter Command Processing Unit The Computer Program in Low Level Machine Language Program in High Level Language.
The environment-based operational semantics Chapter
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 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.
David Evans CS200: Computer Science University of Virginia Computer Science Lecture 27: Types of Types “It would appear.
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.
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
Introduction to Scheme
September 4, 1997 Programming Languages (CS 550) Lecture 6 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts.
Env. Model Implementation
Original material by Eric Grimson
Nondeterministic Evaluation
Mini Language Interpreter Programming Languages (CS 550)
The Metacircular Evaluator
Lecture 23 Pages : Separating Syntactic Analysis from Execution. We omit many details so you have to read the section in the book. The halting.
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
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 based on notes from SICP
Lecture 25: The Metacircular Evaluator Eval Apply
Presentation transcript:

Metacircular Evaluation SICP Chapter 4 Mark Boady

Metacircular Evaluator An interpreter built for a language using the same language as it is interpreting. We will be looking at a Scheme interpreter written in scheme Read Chapter 4 of SICP for a more detailed look at this interpreter Why? Extending an interpreted language Debuggers

Jikes RVM A Java Research Virtual Machine written in Java The RVM runs on the JVM Used For Research in: Garbage Collection Dynamic Parallelization Machine Learning for dynamic compilation Dynamic Typing Distributed VM

Scheme Metacircular Evaluator Eval Takes an expression and an Environment Environment = Variable Names and Values Returns the result of evaluating the expression Apply Takes a Procedure and a list of arguments Produces an expression for eval (+ (* 4 5) 6)

Eval Definition (define (eval exp env) (cond ((self- evaluating? exp) exp) ((variable? exp) (lookup-variable- value exp env)) ((quoted? exp) (text-of- quotation exp)) ((assignment? exp) (eval- assignment exp env)) ((definition? exp) (eval- definition exp env)) ((if? exp) (eval- if exp env)) ((lambda? exp) (make-procedure (lambda- parameters exp) (lambda- body exp) env)) ((begin? exp) (eval- sequence (begin-actions exp) env)) ((cond? exp) (eval (cond- >if exp) env)) ((application? exp) (apply (eval (operator exp) en v) (list-of- values (operands exp) env))) (else (error "Unknown expression t ype -- EVAL" exp))))

(define (beval exp env) (cond ((boolean? exp) exp) ((conjunct? exp) (beval-and exp env)) ((disjunct? exp) (beval-or exp env)) ((negate? exp) (beval-not exp env)) ((variable? exp)... ; You'll need to supply your own function that takes a frame, returns the assoc. value (else (error "beval: illegal syntax")))))

Apply Definition (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 (proc edure- environment procedure)))) (else (error "Unknown procedure type -- APPLY" procedure))))

What do eval and apply do? Eval Takes the expression and determines what the expression is Passes the work to a helper function that evaluates the specific type For procedures, pass control to apply Apply Determine the type of procedure Add to the environment Pass control to Eval

Concept We want to eval (+ 4 5) ((application? exp) (apply (eval (operator exp) en v) (list-of-values (operands exp) env))) List-of-values evaluates the inputs to the procedure Apply performs the actual procedure With a primitive (like +) the underlying language handles it With a custom procedure, we need to pass back to eval

Metacircular

Basic Example (eval ‘(+ a 5) ‘((a 10) (b 7)) Evaluate the expression a+5 with the variables a=10, b=7 Eval starts with a procedure and sees it is an apply Eval evaluates the inputs to the procedure Looks up variable values in this case Apply is asked to handle with (+ 10 5) Apply can determine 10+5=15 using the underlying system

Details Getting the arguments of a Procedure (apply (eval (operator exp) env) (list-of- values (operands exp) env))) (define (list-of-values exps env) (if (no- operands? exps) '() (cons (eval (first- operand exps) env) (list-of-values (rest- operands exps) env))))

If Statements (define (eval-if exp env) (if (true? (eval (if- predicate exp) env)) (eval (if- consequent exp) env) (eval (if- alternative exp) env))) Only Evaluate based on the true case (define (true? X) (not (eq? x false))) (define (if-alternative exp) (if (not (null? (cdddr exp))) (cadddr exp) 'false))

Evaluating Sequences (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)))) Evaluate the sequence of expressions in a procedure body

Assigning Variables (define (eval-assignment exp env) (set-variable- value! (assignment- variable exp) (eval (assignment- value exp) env) env) 'ok) set-variable-value! Bounds a value to a name

Expressions Basic functionality is implemented directly Assignment (define (assignment? exp) (tagged- list? exp 'set!)) (define (assignment- variable exp) (cadr exp)) (define (assignment- value exp) (caddr exp)) Derived Expressions Some functionality is implemented using existing functionality Cond can be transformed into if statements Let statements can be transformed in lambda expressions

Derived Expressions Let expressions are derived expressions, because (let (( )... ( )) ) is equivalent to ((lambda (... ) )... )

Derived Expressions (let ((a 4) (b 6)) (+ a b)) Value 10 ( (lambda (a b) (+ a b)) 4 6) Value 10 We can write a command that will translate a let to a lambda. Let eval handle the lambda command using existing tools.

Environment (lookup-variable-value ) returns the value that is bound to the symbol in the environment, or signals an error if the variable is unbound. (extend-environment ) returns a new environment, consisting of a new frame in which the symbols in the list are bound to the corresponding elements in the list, where the enclosing environment is the environment.

Environment (define-variable! ) adds to the first frame in the environment a new binding that associates the variable with the value. (set-variable-value! ) changes the binding of the variable in the environment so that the variable is now bound to the value, or signals an error if the variable is unbound.

Environments There are multiple scopes in the environment We make changes to the most recent Example: Initial memory: ( ( (a b) (5 7) ) ) A new function is called with inputs b=6, c=7 We push a new set of variables into the environment New Memory: ( ( (b c) (6 7) ) ( (a b) (5 7) ) ) When the function call is over we remove it from the environment New Memory: ( ( (a b) (5 7) ) )

Environments (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 va ls)) (else (scan (cdr vars) (cdr vals))))) (if (eq? env th e-empty- environment) (error "Unbound variable" var) (let ((fr ame (first-frame env))) (scan (frame- variables frame) (frame-values frame))))) (env- loop env))

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

Primitives (define primitive-procedures (list (list 'car car) (list 'cdr cdr) (list 'cons cons) (list 'null? null?) (list '- -) (list '+ +) )) (define (apply-primitive-procedure proc args) (apply-in- underlying-scheme (primitive- implementation proc) args))

Running the Evaluator Load the File (load "ch4-mcevalM.scm") Initialize the Global Environment (define the-global-environment (setup-environment)) Initialize the Evaluator (driver-loop) We can now execute code!

Running (load "ch4-mcevalM.scm") (define the-global-environment (setup-environment)) (driver-loop) ;;; M-Eval input: (define (append x y) (if (null? x) y (cons (car x) (append (cdr x) y)))) ;;; M-Eval value: ok ;;; M-Eval input: (append '(a b c) '(d e f)) ;;; M-Eval value: (a b c d e f)

Driver Loop (define input-prompt ";;; M-Eval input:") (define output- prompt ";;; M-Eval value:") (define (driver- loop) (prompt-for-input input- prompt) (let ((input (read))) (let ((output (eval input the-global-environment))) (announce-output output- prompt) (user-print output))) (driver- loop)) (define (prompt-for- input string) (newline) (newline) (display string) (newlin e))

Environments (define (setup-environment) (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true true initial-env) (define-variable! 'false false initial-env) initial-env))