STRUCTURE AND INTERPRETATION COMPUTER PROGRAMS >>> COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 23 Py TODAY REVIEW: INTERPRETATION 7/26/2012 READ PRINT

Similar documents
STRUCTURE AND INTERPRETATION COMPUTER PROGRAMS COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 23 Py TODAY 7/26/2012

CS61A Lecture 23 Py. Jom Magrotker UC Berkeley EECS July 26, 2012

TAIL RECURSION, SCOPE, AND PROJECT 4 11

CS61A Notes Week 13: Interpreters

SCHEME AND CALCULATOR 5b

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

CS61A Lecture 20 Object Oriented Programming: Implementation. Jom Magrotker UC Berkeley EECS July 23, 2012

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012

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

INTERPRETERS AND TAIL CALLS 9

INTERPRETATION AND SCHEME LISTS 12

Discussion 12 The MCE (solutions)

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

CS61A Lecture 28 Distributed Computing. Jom Magrotker UC Berkeley EECS August 6, 2012

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

Review Analyzing Evaluator. CS61A Lecture 25. What gets returned by mc-eval? (not analyzing eval) REVIEW What is a procedure?

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

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

COMPUTER SCIENCE IN THE NEWS (TWO YEARS AGO) CS61A Lecture 16 Mutable Data Structures TODAY REVIEW: OOP CLASS DESIGN 7/24/2012

EXCEPTIONS, CALCULATOR 10

SCHEME INTERPRETER GUIDE 4

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

ENVIRONMENT MODEL: FUNCTIONS, DATA 18

INTERPRETATION AND SCHEME LISTS 12

RLISTS AND THE ENVIRONMENT MODEL 9

CS61A Lecture 16 Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 16, 2012

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

61A Lecture 26. Monday, October 31

Intro. Scheme Basics. scm> 5 5. scm>

Iterators & Generators

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

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 24 Infinite Sequences LAZY EVALUATION AGENDA 8/7/2012. Jom Magrotker UC Berkeley EECS July 30, 2012

CS61A Lecture 24 Infinite Sequences. Jom Magrotker UC Berkeley EECS July 30, 2012

CS61A Lecture 26 Logic Programming. Jom Magrotker UC Berkeley EECS August 1, 2012

MEMOIZATION, RECURSIVE DATA, AND SETS

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

CALCULATOR Calculator COMPUTER SCIENCE 61A. July 24, 2014

Lecture #21: Search and Sets. Last modified: Wed Mar 9 15:44: CS61A: Lecture #21 1

Public-Service Announcement

CS61A Lecture 27 Logic Programming. Jom Magrotker UC Berkeley EECS August 2, 2012

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 14 Object Oriented Programming TODAY 7/11/2012 WHERE WE WERE: FUNCTIONAL PROGRAMMING

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

61A Lecture 2. Wednesday, September 4, 2013

C311 Lab #3 Representation Independence: Representation Independent Interpreters

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

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

Hacettepe University Computer Engineering Department. Programming in. BBM103 Introduction to Programming Lab 1 Week 4. Fall 2018

CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter

TUPLES AND RECURSIVE LISTS 5

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

Syntactic Sugar: Using the Metacircular Evaluator to Implement the Language You Want

Objects CHAPTER 6. FIGURE 1. Concrete syntax for the P 3 subset of Python. (In addition to that of P 2.)

CS 360 Programming Languages Interpreters

Functions and Decomposition

YESTERDAY: DISTRIBUTED COMPUTING

User-defined Functions. Conditional Expressions in Scheme

An Explicit Continuation Evaluator for Scheme

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

CS61A Lecture 29 Parallel Computing. Jom Magrotker UC Berkeley EECS August 7, 2012

Principles of Programming Languages 2017W, Functional Programming

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

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CS1 Lecture 5 Jan. 25, 2019

Lecture 2: SML Basics

61A Lecture 3. Friday, September 5

OBJECT ORIENTED PROGRAMMING 6

(scheme-1) has lambda but NOT define

;; definition of function, fun, that adds 7 to the input (define fun (lambda (x) (+ x 7)))

CS61A Lecture 21. Amir Kamil UC Berkeley March 11, 2013

Programming with Python

Problem Set 8. Lecture 32: Truthiness. Lecture 32: Truthiness. Problem Set 9 Team requests and ideas due Monday ( me before midnight)

CS 61A Discussion 8: Scheme. March 23, 2017

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

MetacircularScheme! (a variant of lisp)

Documentation for LISP in BASIC

CS61A Midterm 2 Review (v1.1)

Comp 151. Control structures.

CS61A Lecture 9 Immutable Data Structures. Jom Magrotker UC Berkeley EECS July 2, 2012

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

Write a procedure powerset which takes as its only argument a set S and returns the powerset of S.

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science. Issued: Wed. 26 April 2017 Due: Wed.

CS 314 Principles of Programming Languages. Lecture 16

An Explicit-Continuation Metacircular Evaluator

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

CMSC 201 Computer Science I for Majors

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Lecture 12: Conditional Expressions and Local Binding

Lexical vs. Dynamic Scope

61A Lecture 2. Friday, August 28, 2015

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

CIS192 Python Programming

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013

CS 61A HKN Review Session. Nathan Zhang, Caleb Wyllie

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Mid-Term 2 Grades

Transcription:

COMPUTER SCIENCE IN THE NEWS CS61A Lecture 23 Py Jom Magrotker UC Berkeley EECS July 26, 2012 http://www.theverge.com/2012/7/26/3188043/robot-baby-osaka-university-asada-laboratory 2 TODAY Interpretation: Review and More! Py, Python written in Python. STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS 3 REVIEW: INTERPRETATION REVIEW: INTERPRETATION >>> What happens here? The main question for this module is: What exactly happens at the prompt for the interpreter? More importantly, what is an interpreter? PRINT EVAL READ 5 6 1

REVIEW: EVALUATION Evaluation finds the value of an expression, using its corresponding expression tree. It discovers the form of an expression and then executes the corresponding evaluation rule. REVIEW: EVAL AND APPLY The eval-applycycleis essential to the evaluation of an expression, and thus to the interpretation of many computer languages. It is not specific to calc. evalreceives the expression (and in some interpreters, the environment) and returns a function and arguments; applyapplies the function on its arguments and returns another expression, which can be a value. Functions, Arguments 7 http://mitpress.mit.edu/sicp/full-text/sicp/book/img283.gif 8 ANNOUNCEMENTS Project 3 is due Today. Homework 11 is due Saturday, July 28. Coming out today. Tom has been delayed in formatting it and what not because the computer he keeps that material on was having issues and was being repaired (took longer than expected). We are verysorry about this and hope you ll understand. Starting next week we will be holding discussions in 320 instead of 310 Soda. PY Tom developed a Python written in Python. He calls it Py. (He s actually quite proud of it ) Py has: Numbers True/False None Primitive Functions Variables Def statements Including return and nonlocal If statements Lambdas Comments 9 10 PY If you re logged onto an instructional computer, you can find the code in ~cs61a/lib/python_modules/py/ Or, when logged in, you can run it using: python3 m py.interpreter There might be a smallnumber of updates before you see it in homework and lab, as it s still in beta. PY: WHY? Many of you are wondering We admit that it sounds sort of redundant. HOWEVER Why would you write a Python using Python?!?!!? 11 12 2

PY: WHY? Many of you are wondering Why would you write a Python using Python?!?!!? It is instructive! We haven t seen a full programming language yet. We already know how this language works, so we can focus on the interpretation. PY: WHY? Many of you are wondering Why would you write a Python using Python?!?!!? Turns out it has been done before (and is sometimes better than other versions)! http://www.pypy.org 13 14 PY: WHY SOSMALL? PY: DEMO The other question you might be asking is Why not all of Python? We wanted to keep the code small. What we did implement is, more or less, enough to do the majority of interesting things a modern programming language does. If you were in lecture, you saw a small demonstration of the language here. 15 16 LOOKING ATPIEPY Unlike calc, it is organized into a variety of files. Core parts: interpreter.py parsing.py environments.py statements.py values.py LOOKING ATPIEPY In principle, works the same as Calc. What s different? Uses the environment model of computation. We have variables and they are made available in various (possibly shared) environments. Functions have parameters, bodies, and know what environment to extend when being applied. Statements (Expression Trees) are a bit smarter. Handles evaluating themselves. Uses attributes instead of general lists. 17 18 3

REPL REPL def read_eval_print_loop(interactive=true): while True: Repeatedly try: statement = py_read_and_parse() value = statement.evaluate(the_global_environment) if value!= None and interactive: print(repr(value)) except : Evaluate the statement we read. Use the global environment. py_read_and_parse().evaluate(the_global_environment) print(repr()) 19 20 In this language, we use the environment model to keep track of variable names and their values. G count 0 In Py, this is implemented in a class Environment, which behaves much like a dictionary. 21 def init (self, enclosing_environment=none): self.enclosing = enclosing_environment self.bindings = {} self.nonlocals = [] Names that should not be bound in this frame. 22 def init (self, enclosing_environment=none): self.enclosing = enclosing_environment self.bindings = {} self.nonlocals = [] Your notes somewhere on the side: self.nonlocals def is_global(self): return self.enclosing is None def note_nonlocal(self, var): self.nonlocals.append(var) 23 24 4

def getitem (self, var): if var in self.bindings: return self.bindings[var] elif not self.is_global(): return self.enclosing[var] else: raise Otherwise, we ve got a problem! *Note:In Py, nonlocal fills the role of both global and nonlocal in regular Python. 25 def set_variable(self, var, val, is_nonlocal=false): if is_nonlocal and var not in self.bindings: self.enclosing.set_variable(var, val, is_nonlocal) elif not is_nonlocal or var in self.bindings: self.bindings[var] = val def setitem (self, var, val): self.set_variable(var, val, var in self.nonlocals) 26 LOOKING AT PIE PY: STATEMENTS Yesterday, we saw the class Exp, which Calcused to represent expressions it read in and evaluated. BREAK Pyhas something similar, which is the Stmtclass. Unlike Exp: Stmt isn t limited to function calls. Stmtwill handle evaluating itself, rather than having a separate function operate on them. http://invisiblebread.com/2012/06/new-workspace/ http://wondermark.com/wp-content/uploads/2012/07/sheep.gif 27 28 LOOKING AT PIE PY: STATEMENTS LOOKING AT PIE PY: CALL EXPRESSIONS class AssignStmt(Stmt): def init (self, target, expr): self.target = target self.expr = expr Create the statement with all of the information that the statement is composed of. def evaluate(self, env): env[self.target] = self.expr.evaluate(env) Evaluate this statement in a given environment. 29 class CallExpr(Expr): def init (self, op_expr, opnd_exprs): self.op_expr = op_expr self.opnd_exprs = opnd_exprs A call expression has an operator and a series of operands. def evaluate(self, env): Evaluate the operator. func_value = self.op_expr.evaluate(env) opnd_values = [opnd.evaluate(env) Evaluate the operands. for opnd in self.opnd_exprs] return func_value.apply(opnd_values) Applythe valueof the operator onto the valueof the operands. 30 5

REPRESENTING FUNCTIONS So we ve seen the eval of the Pyinterpreter and how it keeps track of state. = + + PRIMITIVE FUNCTIONS class Function: def init (self, *args): raise NotImplementedError() def apply(self, operands): raise NotImplementedError() How do we represent functions? Not that different from double bubbles! 31 class PrimitiveFunction(Function): def init (self, procedure): self.body = procedure def apply(self, operands): return self.body(*operands) Primitives allow you access to a function under the hood. They simply call the under the hood procedure on the values when applied. 32 PRIMITIVE FUNCTIONS primitive_functions = [ ("or", PrimitiveFunction(lambda x, y: x or y)), ("and", PrimitiveFunction(lambda x, y: x and y)), ("not", PrimitiveFunction(lambda x: not x)), ("eq", PrimitiveFunction(lambda x, y: x == y)), ("ne", PrimitiveFunction(lambda x, y: x!= y)), ] In the interpreter, there s a function which loads up the global environment with primitive functions, setup_global. def setup_global(): for name, primitive in primitive_functions: the_global_environment[name] = primitive USER-DEFINED FUNCTIONS class CompoundFunction(Function): def init (self, args, body, env): self.args = args self.body = body self.env = env def apply(self, operands): call_env = Environment(self.env) Make a new frame. if len(self.args)!= len(operands): raise TypeError("Wrong number of arguments passed to function!") for name, value in zip(self.args, operands): call_env[name] = value Bind the arguments. for statement in self.body: try: statement.evaluate(call_env) Step into the environment and evaluate each statement of the body. except StopFunction as sf: return sf.return_value until something is returned return None or we reach the end (and return None). 33 34 USER-DEFINED FUNCTIONS class StopFunction(BaseException): def init (self, return_value): self.return_value = return_value class ReturnStmt(Stmt): def init (self, expr=none): self.expr = expr def evaluate(self, env): if self.expr is None: raise StopFunction(None) Returning values from functions turns out to be harder than simply identifying one of the body statements as a return (what if the return is inside an if statement?). We implemented it as an exception. ReturnStmtraises one when evaluated. CompoundFunctioncatches it in apply. raise StopFunction(self.expr.evaluate(env)) PY: THAT S PRETTY MUCH IT There s some other little bits that we might not have focused on today, but the code outside of parsing.py and testing.py shouldbe relatively easy to follow once you get a sense of where things live. We should note that this code is not necessarily representative of how all interpreters work (in fact that s just plain false). It is, however, similarto (but notthe same as) the way things will work on the project. 35 36 6

CONCLUSION An interpreter is a function that, when applied to an expression, performs the actions required to evaluate that expression. We saw an interpreter for a subset of the Python language, Py, written in Python. The read-eval-print loopreads user input, evaluates the statement in the input, and prints the resulting value. To implement the environment model of computation, we use Environments! Environments can be implemented like dictionaries. Using an object oriented approach, we can have our expression trees be responsible for evaluating themselves. Apply is now the job of the Function class, which represents function values. 37 7