Exceptions and Continuations. Lecture #19: More Special Effects Exceptions and OOP. Approach II: Non-Standard Return. Approach I: Do Nothing

Similar documents
Approach I: Do Nothing

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division DO NOT. P. N.

CSE341: Programming Languages Lecture 23 Multiple Inheritance, Mixins, Interfaces, Abstract Methods. Dan Grossman Autumn 2018

CS558 Programming Languages Winter 2013 Lecture 8

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

CS558 Programming Languages

Object typing and subtypes

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

History C++ Design Goals. How successful? Significant constraints. Overview of C++

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11

Data Structures (list, dictionary, tuples, sets, strings)

Subtyping (Dynamic Polymorphism)

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

C++ Yanyan SHEN. slide 1

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Objects, Encapsulation, Inheritance (2)

CS 536 Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 11

COL728 Minor2 Exam Compiler Design Sem II, Answer all 5 questions Max. Marks: 20

LECTURE 19. Subroutines and Parameter Passing

CSE 401/M501 Compilers

CIT Week13 Lecture

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

CS 11 java track: lecture 3

CS11 Advanced C++ Fall Lecture 3

CS 3 Introduction to Software Engineering. 3: Exceptions

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

VIRTUAL FUNCTIONS Chapter 10

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Method Resolution Approaches. Dynamic Dispatch

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS11 Introduction to C++ Fall Lecture 7

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

CSE 331 Software Design & Implementation

CS64 Week 5 Lecture 1. Kyle Dewey

CSE 303: Concepts and Tools for Software Development

Conformance. Object-Oriented Programming Spring 2015

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

abstract binary class composition diamond Error Exception executable extends friend generic hash implementation implements

Late Binding; OOP as a Racket Pattern

Exceptions and Design

CPS 506 Comparative Programming Languages. Programming Language

CSE 504: Compiler Design. Runtime Environments

Subtypes and Subclasses

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Don t Believe the Hype. CS152: Programming Languages. Lecture 21 Object-Oriented Programming. Class-based OOP. So what is OOP?

Compiler construction 2009

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Data Abstraction. Hwansoo Han

What are the characteristics of Object Oriented programming language?

Lecture #16: Introduction to Runtime Organization. Last modified: Fri Mar 19 00:17: CS164: Lecture #16 1

Programming Languages. Streams Wrapup, Memoization, Type Systems, and Some Monty Python

CS159. Nathan Sprague

G Programming Languages - Fall 2012

Lecture Topics. Administrivia

QUIZ. Source:

Implementing Interfaces. Marwan Burelle. July 20, 2012

Programming Languages and Techniques (CIS120)

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

Run-Time Data Structures

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Syntax Errors; Static Semantics

What about Object-Oriented Languages?

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

Internal Classes and Exceptions

Lecture 13: more class, C++ memory management

Weeks 6&7: Procedures and Parameter Passing

Lecture 10: building large projects, beginning C++, C++ and structs

CS152: Programming Languages. Lecture 23 Advanced Concepts in Object-Oriented Programming. Dan Grossman Spring 2011

CS11 Introduction to C++ Fall Lecture 6

CS 31: Intro to Systems ISAs and Assembly. Martin Gagné Swarthmore College February 7, 2017

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Functions and Procedures

CS 480 Fall Runtime Environments. Mike Lam, Professor. (a.k.a. procedure calls and heap management)

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 10

Object Oriented Programming: Based on slides from Skrien Chapter 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Object Oriented Paradigm

Wednesday, October 15, 14. Functions

Rules and syntax for inheritance. The boring stuff

Project Compiler. CS031 TA Help Session November 28, 2011

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

Run-time Environments - 2

CS-XXX: Graduate Programming Languages. Lecture 22 Class-Based Object-Oriented Programming. Dan Grossman 2012

CSE Lecture In Class Example Handout

Object Model. Object Oriented Programming Spring 2015

CS61B Lecture #13: Packages, Access, Etc.

CS61B Lecture #13: Packages, Access, Etc.

Typical Runtime Layout. Tiger Runtime Environments. Example: Nested Functions. Activation Trees. code. Memory Layout

Distributed Systems Theory 4. Remote Procedure Call. October 17, 2008

CGS 2405 Advanced Programming with C++ Course Justification

Object-oriented features

CSE 401 Final Exam. March 14, 2017 Happy π Day! (3/14) This exam is closed book, closed notes, closed electronics, closed neighbors, open mind,...

CS 2110 AEW SIGN UP FOR 1 CREDIT S/U COURSE!!!

Transcription:

Lecture #19: More Special Effects Exceptions and OOP Test #2 in two weeks (14 April), in class. Autograder runs Sunday night sometime. Exceptions and Continuations Exception-handling in programming languages is a very limited form of continuation. Execution continues after a function call that is still active when exception raised. Java provides mechanism to return a value with the exception, but this adds no new complexity. Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 1 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 2 Approach I: Do Nothing Some say keep it simple; don t bother with exceptions. Use return code convention: Example: C libraryfunctions often returneither for OK or nonzero for various degrees of badness. Problems: Forgetting to check. Code clutter. Clumsiness: makes value-returning functions less useful. Slight cost in always checking return codes. Approach II: Non-Standard Return First idea is to modify calls so that they look like this: OK: call _f jmp OK code to handle exception code for normal return To throw exception: Put type of exception in some standard register or memory location. Return to instruction after normal return. Awkward for the ia2(above). Easier on machines that allow returning to a register+constant offset address [why?]. Exception-handling code decides whether it can handle the exception, and does another exception return if not. Problem: Requires small distributed overhead for every function call. Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 4

Approach III: Stack manipulation C does not have an exception mechanism built into its syntax, but uses library routines: jmp_buf catch_point; void Caller () { if (setjmp (catch_point) == ) { normal case, which eventually gets down to Callee else { handle exception void Callee () {... // Throw exception: longjmp (catch_point, 42);... Caller s FP, SP, catch point: addr of setjmp call & others Callee s frame. other frames. Caller s frame. Approach III: Discussion On exception, call to setjmp appears to return twice, with two different values. Does not require help from compiler, But implementation is architecture-specific. Overhead imposed on every setjmp call. If used to implement try and catch, therefore, would impose cost on every try. Subtle problems involving variables that are stored in registers: The jmp buf typically has to store such registers, but That means the value of some local variables may revert unpredictably upon a longjmp. Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 5 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 6 Approach IV: PC tables Sun s Java implementation uses a different approach. Compiler generates a table mapping instruction addresses (program counter (PC) values) to exception handlers for each function. If needed, compiler also leaves behind information necessary to return from a function ( unwind the stack ) when exception thrown. To throw exception E: while (current PC doesn t map to handler for E) unwind stack to last caller Under this approach, a try-catch incurs no cost unless there is an exception, but Throwing and handling the exception more expensive than other approaches, and Tables add space. New Topic: Dynamic Method Selection and OOP Interesting language feature introduced by Simula 67, Smalltalk, C++, Java: the virtual function (to use C++ terminology). Problem: Arrange classes in a hierarchy of types. Instance of subtype is an instance of its supertype(s). In particular, inherits their methods, but can override them. A dynamic effect: Cannot in general tell from program text what body of code executed by a given call. Implementation difficulty (as usual) depends on details of a language s semantics. Some things still static: Names of functions, numbers of arguments are (usually) known Compiler can handle overloading by inventing new names for functions. E.g.,G++encodesafunctionf(intx)inclassQas ZN1Q1fEi, and f(int x, int y) as ZN1Q1fEii. Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 7 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 8

I. Fully Dynamic Approach Regular Python has a completely dynamic approach to the problem: class x = 2; def f (self): return 42 a = A (); b = A () print a.x, a.f() # Prints 2 42 a.x = lambda (self, z): self.w * z a.f = 1; a.w = 5 print a.x(), a.f, a.w # Prints 15 1 5 print b.x(), b.f, b.w # Error print A.x # Prints 2 A.x = lambda (self): 19 A.f = 2 A.v = 1 c = A () print c.x (), c.f, c.v # Prints 19, 2, 1 Characteristics of Dynamic Approach Each class instance is independent. Contents of class definition merely used until a new value is assigned to an attribute of the instance. New attributes can be added freely to instances or to class. In other variants of this approach, there are no classes at all, only instances, and we get new instances by cloning existing objects, and possibly then adding new attributes. Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 9 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 1 Implementing the Dynamic Approach Simple strategy: just put a dictionary in every instance, and in class. Create an instance by making fresh copy of class s dictionary. Check for value of attribute in object s dictionary, then in that of its class, superclass, etc. All checking at runtime. All objects (or pointers) carry around dynamic type. Pros and Cons of Dynamic Approach Extremely flexible Conceptually simple Implementation easy Space overhead: every instance has pointers to all methods Time overhead: lookup on each call No static checking Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 11 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 12

II. Straight Single Inheritance, Dynamic Typing Each class has fixed set of methods and instance variables Methods have fixed definition in each class. Classes can inherit from single superclass. Otherwise, types of parameters, variables, etc., still dynamic Basically technique in Smalltalk, Objective C. Implementing the Smalltalk-like Approach Instances need not carry around copies of function pointers. Instead, each class has a data structure mapping method names to functions, and instance-variable names to offsets from the start of the object. a: class def f (...): body1 def g (...): body2 x = class B(A): def f (...): body def h (...): body4 y = 2 a = A () b = B () b: class: class: 2 super x@4: super f: body h: body4 y@8: 2 y is stored at offset 8 from start of instance Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 1 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 14 Pros and Cons of Smalltalk Approach Only need to store modifiable things instance variables in instances. Data structure can be a bit faster at accessing than fully dynamic method But still, not much static checking possible, and Some lookup of method names required. Single Inheritance with Static Types Consider Java without interfaces. Type can inherit from at most one immediate superclass. For an access, x.w, insist that compiler knows a supertype of x s dynamic type that defines w. Insist that all possible overridings of a method have compatible parameter lists and return values. Use a techniquesimilar to previous one, but put entriesfor all methods (whether or not overridden) in each class data structure. Such class data structures are called virtual tables or vtables in C++ parlance. Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 15 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 16

Implementation of Simple Static Single Inheritance class A { void f () { body1 void g () { body2 int x = class B extends A { void f () { body void h () { body4 int y = 2 --------- a = new A () b = new B () a: b: 2 f: body h: body4 No need to store offsets of x and y; compiler knows where they are. Also, compiler knows where to find f, g, h virtual tables. Important: offsets of variables in instances and of method pointers in virtual tables are known constants, the same for all subtypes. So compiler knows how to call methods of b even if static type is A! Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 17 Interfaces Java allows interface inheritance of any number of interface types (introduces no new bodies). This complicates life: consider class A { class B { interface C { int x; int y; f (); public f () {... g () {... h () {... public f () {... /*----------------------------------------------------*/ class A2 extends A class B2 extends B implements C implements C {... {... /*----------------------------------------------------*/ void f (C y) { y.f () // How can this work? We can compile A and B without knowledge of C, A2, B2. How can we make the virtual table of A2 and B2 compatible with each other so that f is at same known offset regardless of whether dynamic type of C is A2 or B2? (Above isn t hardest example!) Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 18 Interface Implementation I: Brute Force One approach is to have the system assign a different offset globally to each different function signature (Functions f(int x) and f() have different function signatures) So in previous example, the virtual tables can be: C: : unused : pntr to B.g : unused 4: unused 4: pntr to B.h 4: unused 8: pntr to A.f 8: pntr to B.f 8: unused A2: B2: : unused : pntr to B.g 4: unused 4: pntr to B.h 8: pntr to A.f 8: pntr to B.f Interface Implementation II: Make Interface Values Different Another approach is to represent values of static type C (an interface type) differently. Converting value x2 of type B2 to C then causes C to point to a two-word quantity: Pointer to x2 Pointer to a cut-down virtual table containing just the f entry from B2 (at offset ). Means that converting to interface requires work and allocates storage. No slowing of method calls. But, Total size of tables gets big (some optimization possible). And, must take into account all classes before laying out tables. Complicates dynamic linking. Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 19 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 2

Interface Implementation II, Illustrated Improving Interface Implementation II class A { void f () { body1 void g () { body2 void h () { body int x = ; interface C { void g (); class B extends A implements C { c: obj: h: body C table for How can we avoid doing allocation to create value of interface type C? One method: extend the virtual table of all types to include an interface vector. Each entry in this vector identifies an interface the type implements, plus the table (e.g. C table for B in last slide). To implement C c = b from last slide, just copy pointer b, as for the usual cases when assigning to a variable whose type is a supertype of the value assigned. B b = new B (); b: C c = b; // Create "interface object" c.g (); // Get g from c.vtbl,... //...and use c.obj as this. h: body To implement c.g() from last slide, find the C table in the interface vector for object pointed to be c and fetch the entry for g. Just call as usual. Question for the reader: How best to design the interface vector? Want fetching of c.g to be fast, So best to avoid having to actually perform a search at execution time. How? Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 21 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 22 Full Multiple Interitance Java allows multiple inheritance only via interfaces. Important point: interfaces don t have instance variables. Instance variables basically mess everything up for multiple inheritance, assuming we want to keep constant offsets to instance variables. class A { class B { int x = 19; int y = 42; void f () {... x... h()... void g () {... y... h()... void h () {... void h () {... class D extends A, B { // Where do x and y go? void h () {... IfaDisaD,thenaD.fexpectsthat this pointstoana,ad.gexpects that it points to a B, but ad.h expects it to point to a D. How can these all be true?? Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 2 Implementing Full Multiple Inheritance I Idea is to extend the contents of the virtual table with an offset for each method. Offset tells how to adjust the this pointer before calling. For the classes from the last slide: ana : 4: 19 ab : 4: 42 ad : 4: 8: 12: 19 42 h: body of B.h D (B part): h: body of D.h -8 h: body of A.h D: h: body of D.h Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 24 8

Implementing Full Multiple Inheritance I (contd.) To call ad.g, Fetch function address of g from D table. Call it, but first add 8 to pointer value ofad so as to get a pointer to the B part of ad. When ad.g eventually calls h (actually this.h), this refers to the B part of ad. Its virtual table is D (B part) in the preceding slide. Fetching h from that table gives us D.h,......which we call, after first adding the -8 offset from the table to this. Thus, we end up calling D.h with a this value that points to ad, as it expects. Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 25 Implementing Full Multiple Inheritance II First implementation slows things down in all cases to accommodate unusual case. Would be better if only the methods inherited from B (for example) needed extra work. Alternative design: use stubs to adjust the this pointer. Define B.g 1 to add 8 to the this pointer by 8 and then call B.g; and D.h 1 to subtract 8 and then call D.h.: : 4: 19 : 4: 42 : 4: 19 8: 12: 42 h: body of B.h D (B part): h: body of D.h 1 h: body of A.h D: h: body of D.h 1 Last modified: Thu Apr 1 16:8:21 21 CS164: Lecture #19 26