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

Slides:



Advertisements
Similar presentations
CS61A Lecture 8 Data Abstraction Tom Magrino and Jon Kotker UC Berkeley EECS June 28, 2012.
Advertisements

1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Metacircular Evaluation SICP Chapter 4 Mark Boady.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
6.001 SICP SICP – October environment Trevor Darrell 32-D512 Office Hour: W web page:
Intro to Robots Robots are Everywhere. Intro to Robots Various robots in use today lawnmower pet baby seal for convalescents gutter cleaner home security.
1 Functional languages (e.g. Scheme, ML) Scheme is a functional language. Scheme is based on lambda calculus. lambda abstraction = function definition.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
David Evans CS150: Computer Science University of Virginia Computer Science Lecture 28: Implementing Interpreters.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
CS61A Lecture 3 Higher Order Functions Jon Kotker and Tom Magrino UC Berkeley EECS June 20, 2012.
Python quick start guide
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
CS1022 Computer Programming & Principles Lecture 1.2 A brief introduction to Python.
CS61A Lecture 21 Scheme Jom Magrotker UC Berkeley EECS July 24, 2012.
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
CS61A Lecture 22 Interpretation Jom Magrotker UC Berkeley EECS July 25, 2012.
CS61A Lecture 13 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 10, 2012.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Formal Semantics Chapter Twenty-ThreeModern Programming Languages, 2nd ed.1.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Lecture 31: Laziness University of Virginia cs1120 Fall 2009 David Evans.
David Evans CS150: Computer Science University of Virginia Computer Science Lecture 30: Laziness.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
CS61A Lecture 20 Object-Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
CMSC 330: Organization of Programming Languages Operational Semantics a.k.a. “WTF is Project 4, Part 3?”
Python Let’s get started!.
1/33 Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
Fall 2008Programming Development Techniques 1 Topic 17 Assignment, Local State, and the Environment Model of Evaluation Section 3.1 & 3.2.
CS61A Lecture 10 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 3, 2012.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
(Thunking about Thunks)
Operational Semantics of Scheme
Lecture 4: Metacircles Eval Apply David Evans
Lesson 06: Functions Class Participation: Class Chat:
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation
CS1022 Computer Programming & Principles
6.001 SICP Variations on a Scheme
Env. Model Implementation
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
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
Coding Concepts (Basics)
The Metacircular Evaluator (Continued)
6.001 SICP Further Variations on a Scheme
Streams, Delayed Evaluation and a Normal Order Interpreter
6.001 SICP Variations on a Scheme
CISC101 Reminders All assignments are now posted.
6.001 SICP Interpretation Parts of an interpreter
Assignments and Procs w/Params
Introduction to the Lab
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:

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

2 C OMPUTER S CIENCE IN THE N EWS

3 T ODAY Interpretation: Review and More! Py, Python written in Python.

S TRUCTURE A ND I NTERPRETATION OF C OMPUTER P ROGRAMS How do we structure our programs? What functions do we need? What classes should we design? How do we structure our programs? What functions do we need? What classes should we design? How can we make the computer understand our code? How does the computer currently understand our code? How can we make the computer understand our code? How does the computer currently understand our code?

5 R EVIEW : I NTERPRETATION >>> The main question for this module is: What exactly happens at the prompt for the interpreter? More importantly, what is an interpreter? What happens here?

6 R EVIEW : I NTERPRETATION READ EVAL PRINT

7 R EVIEW : E VALUATION 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.

8 R EVIEW : E VAL AND A PPLY The eval - apply cycle is essential to the evaluation of an expression, and thus to the interpretation of many computer languages. It is not specific to calc. eval receives the expression (and in some interpreters, the environment) and returns a function and arguments; apply applies the function on its arguments and returns another expression, which can be a value. Functions, Arguments

9 A NNOUNCEMENTS 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 very sorry about this and hope you’ll understand. Starting next week we will be holding discussions in 320 instead of 310 Soda.

10 PYPY 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

11 PYPY 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 small number of updates before you see it in homework and lab, as it’s still in beta.

12 P Y : W HY ? Many of you are wondering... We admit that it sounds sort of redundant. HOWEVER... “Why would you write a Python using Python?!?!!?”

13 P Y : W HY ? Many of you are wondering... 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. “Why would you write a Python using Python?!?!!?”

14 P Y : W HY ? Many of you are wondering... Turns out it has been done before (and is sometimes better than other versions)! “Why would you write a Python using Python?!?!!?”

15 P Y : W HY SO S MALL ? The other question you might be asking is... – 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. “Why not all of Python?”

16 P Y : D EMO If you were in lecture, you saw a small demonstration of the language here.

17 L OOKING AT P IE P Y Unlike calc, it is organized into a variety of files. Core parts: interpreter.py parsing.py environments.py statements.py values.py

18 L OOKING AT P IE P Y 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.

19 L OOKING AT P IE P Y : REPL def read_eval_print_loop(interactive=True): while True: try: statement = py_read_and_parse() value = statement.evaluate(the_global_environment) if value != None and interactive: print(repr(value)) except...:... Read in a statement and produce a Stmt object. Evaluate the statement we read. Use the global environment. Print the (representation of) the resulting value, if there is one. Repeatedly...

20 L OOKING AT P IE P Y : REPL py_read_and_parse().evaluate(the_global_environment) print(repr(...))

21 L OOKING AT P IE P Y : E NVIRONMENTS In this language, we use the environment model to keep track of variable names and their values. In Py, this is implemented in a class Environment, which behaves much like a dictionary. G count0

22 L OOKING AT P IE P Y : E NVIRONMENTS class Environment:... def __init__(self, enclosing_environment=None): self.enclosing = enclosing_environment self.bindings = {} self.nonlocals = []... The environment that this one extends. The bindings (variable names and their values) found in this frame. Names that should not be bound in this frame.

23 L OOKING AT P IE P Y : E NVIRONMENTS class Environment: def __init__(self, enclosing_environment=None): self.enclosing = enclosing_environment self.bindings = {} self.nonlocals = []... self.bindings self.enclosing self.nonlocals Your notes somewhere on the side:

24 L OOKING AT P IE P Y : E NVIRONMENTS class Environment:... def is_global(self): return self.enclosing is None def note_nonlocal(self, var): self.nonlocals.append(var)... “Am I the global environment?” Make a note of a variable name that is to be treated as nonlocal for this frame.

25 L OOKING AT P IE P Y : E NVIRONMENTS class Environment:... def __getitem__(self, var): if var in self.bindings: return self.bindings[var] elif not self.is_global(): return self.enclosing[var] else: raise give back the value. If I have the variable in my frame... If there are more frames to look through look at the next frame. Otherwise, we’ve got a problem! *Note: In Py, nonlocal fills the role of both global and nonlocal in regular Python.

26 L OOKING AT P IE P Y : E NVIRONMENTS class Environment:... 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)... If the variable is nonlocal and doesn’t already exist, it belongs in a different frame. Otherwise, add (or update) the binding in this frame.

27 B REAK

28 L OOKING AT P IE P Y : S TATEMENTS Yesterday, we saw the class Exp, which Calc used to represent expressions it read in and evaluated. Py has something similar, which is the Stmt class. Unlike Exp : – Stmt isn’t limited to function calls. – Stmt will handle evaluating itself, rather than having a separate function operate on them.

29 L OOKING AT P IE P Y : S TATEMENTS class AssignStmt(Stmt): def __init__(self, target, expr): self.target = target self.expr = expr evaluate def evaluate(self, env): env[self.target] = self.expr.evaluate(env) Create the statement with all of the information that the statement is composed of. Evaluate this statement in a given environment.

30 L OOKING AT P IE P Y : C ALL E XPRESSIONS class CallExpr(Expr): def __init__(self, op_expr, opnd_exprs): self.op_expr = op_expr self.opnd_exprs = opnd_exprs def evaluate(self, env): func_value = self.op_expr.evaluate(env) opnd_values = [opnd.evaluate(env) for opnd in self.opnd_exprs] apply return func_value.apply(opnd_values) A call expression has an operator and a series of operands. Evaluate the operator. Evaluate the operands. Apply the value of the operator onto the value of the operands.

31 L OOKING AT P IE P Y : R EPRESENTING F UNCTIONS

32 L OOKING AT P IE P Y : P RIMITIVE F UNCTIONS class Function: def __init__(self, *args): raise NotImplementedError() apply def apply(self, operands): raise NotImplementedError() 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.

33 L OOKING AT P IE P Y : P RIMITIVE F UNCTIONS 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)),... ] def setup_global(): for name, primitive in primitive_functions: the_global_environment[name] = primitive In the interpreter, there’s a function which loads up the global environment with primitive functions, setup_global.

34 L OOKING AT P IE P Y : U SER -D EFINED F UNCTIONS 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) 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 for statement in self.body: try: evaluate statement.evaluate(call_env) except StopFunction as sf: return sf.return_value return None Make a new frame. Bind the arguments. Step into the environment and evaluate each statement of the body until something is returned or we reach the end (and return None).

35 L OOKING AT P IE P Y : U SER -D EFINED F UNCTIONS 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) raise StopFunction(self.expr.evaluate(env)) 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. ReturnStmt raises one when evaluated. CompoundFunction catches it in apply.

36 P Y : T HAT ’ S P RETTY M UCH I T There’s some other little bits that we might not have focused on today, but the code outside of parsing.py and testing.py should be 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, similar to (but not the same as) the way things will work on the project.

37 C ONCLUSION 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 loop reads 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.