Compiling Objects in Class-Based Languages CS 153: Compilers.

Slides:



Advertisements
Similar presentations
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
Advertisements

A little bit on Class-Based OO Languages CS153: Compilers Greg Morrisett.
This lecture is a bit of a departure in that we’ll cover how C++’s features are actually implemented. This implementation will look suspiciously similar.
Lecture 10: Part 1: OO Issues CS 540 George Mason University.
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Compiling Object Oriented Programs Mooly Sagiv Chapter
Lecture 2: Object Oriented Programming I
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
CSE341: Programming Languages Lecture 26 Subtyping for OOP Dan Grossman Fall 2011.
Road Map Introduction to object oriented programming. Classes
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS102 Data Types in Java CS 102 Java’s Central Casting.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
1 CSE 303 Lecture 24 Inheritance in C++, continued slides created by Marty Stepp
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
1 Inheritance in Java CS 3331 Fall Outline  Overloading  Inheritance and object initialization  Subtyping  Overriding  Hiding.
Types in programming languages What are types, and why do we need them? Types in programming languages1.
OOP Languages: Java vs C++
Comparison of OO Programming Languages © Jason Voegele, 2003.
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Internet Software Development Classes and Inheritance Paul J Krause.
Adapted from Prof. Necula UCB CS 1641 Overview of COOL ICOM 4029 Lecture 2 ICOM 4029 Fall 2008.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Implementation: Part 3 Software Construction Lecture 8.
Class Inheritance UNC-CHAPEL HILL COMP 401 BRIAN CRISTANTE 5 FEBRUARY 2015.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
The Procedure Abstraction, Part VI: Inheritance in OOLs Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Guided Notes Ch. 9 ADT and Modules Ch. 10 Object-Oriented Programming PHP support for OOP and Assignment 4 Term project proposal C++ and Java Designer.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
Types in programming languages1 What are types, and why do we need them?
CS 261 – Data Structures Introduction to C Programming.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
Copyright © 2005 Elsevier Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though few languages provide it.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
CS 3180 (Prasad)L67Classes1 Classes and Interfaces Inheritance Polymorphism.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
Object Model Baojian Hua What ’ s an Object Model? An object model dictates how to represent an object in memory A good object.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Modern Programming Tools And Techniques-I
Object-oriented Programming in Java
Java Primer 1: Types, Classes and Operators
Programming Language Concepts (CIS 635)
Inheritance, Polymorphism and the Object Memory Model
Compiler Design 18. Object Oriented Semantic Analysis (Symbol Tables, Type Checking) Kanat Bolazar March 30, 2010.
Inheritance in Java CS 3331 Fall 2009.
Java Programming Language
ICOM 4029 Fall 2003 Lecture 2 (Adapted from Prof. Necula UCB CS 164)
Presentation transcript:

Compiling Objects in Class-Based Languages CS 153: Compilers

Object-Oriented Language? It should be clear that there are several families of OO languages: Prototype-based (e.g. Javascript, Lua) Class-based (e.g. C++, Java, C#) We will focus on the compilation of class-based OO languages.

A brief incomplete history of OO (Early 60’s) Key concepts emerge in various languages/programs: sketchpad (Sutherland), SIMSCRIPT (Hoare), and probably many others. (1967) Simula 67 (Dahl, Nygaard) crystalizes many ideas (class, object, subclass, dispatch) into a coherent OO language (1972) Smalltalk (Kay) introduces the concept of object- oriented programming (you should try Squeak!) (1978) Modula-2 (Wirth) (1985) Eiffel (Meyer) (1990’s) OO programming becomes mainstream: C++, Java, C#, …

Classes What’s the difference between a class and an object?

Classes What’s the difference between a class and an object? Class (a blueprint for objects) declared fields / instance variables values may differ from object to object usually mutable methods shared by all objects of a class inherited from superclasses usually immutable implicit receiver object ( this, self ) all have visibility: public / private/ protected

Code generation for objects Methods Generate method body code Generate method calls (dispatching) Fields Memory layout Alignment

Jish Abstract Syntax type tipe = Int_t|Bool_t |Class_t of class_name type exp = Var of var | Int of int | Nil | Var of var | Assign of var * exp | New of class_name | Invoke of exp * var * (exp list) |... type stmt = Exp of exp | Seq of stmt*stmt |... type method = Method of {mname:var, mret_tipe:tipe option, margs:var*tipe list, mbody:stmt} type class = Class of {cname:class_name, csuper:class_name, cinstance_vars:var*tipe list, cmethods:method list}

The need for dynamic dispatching Methods look like functions, type-checked like functions… what’s different? Problem: compiler can’t tell what code to run when a method is called, in general. interface Point { int getx(); float norm(); } class ColoredPoint implements Point { … float norm() { return sqrt(x*x+y*y); } class 3DPoint implements Point { … float norm() return sqrt(x*x+y*y+z*z); } Point p = new 3DPoint(...); p.norm(); Solution: dispatch table (vtable, virtual method table)

Method dispatch Idea: every method has its own offset Offset is used to look up method in vtable class A { void foo() {.. } } class B extends A { void bar() {.. } void baz() {.. } } class C extends B { void foo() {…} void bar() {…} void baz() {…} void quux() {…} }

vtable A foo | B bar, baz | C quux

Fields Work similarly, calculate offset into object. class Pt2d extends Object { int x; /* offset 4 */ int y; /* offset 8 */ void movex(int i) { x = x + i; } void movey(int i) { y = y + i; } } class Pt3d extends Pt2d { int z; /* offset 12 */ void movez(int i) { z = z + i; } }

Fields Values of fields placed in object Accesses to fields are indexed loads Need to know size of superclasses – can be a problem e.g., Java – field offsets resolved at dynamic link/load time class Pt3d extends Pt2d { int z; /* offset = size(Pt2d) + 4 = 12 */ void movez(int i) { z = z + i; } }

Object layout

Field layout in Java (actually) public abstract class AbstractMap implements Map { Set keySet; Collection values; } public class HashMap extends AbstractMap { Entry[] table; int size; int threshold; float loadFactor; int modCount; boolean useAltHashing; int hashSeed; } Will keySet be the first field in HashMap? Will table be the 3rd field in HashMap?

Field Layout in Java (actually) $ java -jar target/java-object-layout.jar java.util.HashMap java.util.HashMap offset size type description 0 12 (object header + first field alignment) 12 4 Set AbstractMap.keySet 16 4 Collection AbstractMap.values 20 4 int HashMap.size 24 4 int HashMap.threshold 28 4 float HashMap.loadFactor 32 4 int HashMap.modCount 36 4 int HashMap.hashSeed 40 1 boolean HashMap.useAltHashing 41 3 (alignment/padding gap) 44 4 Entry[] HashMap.table 48 4 Set HashMap.entrySet 52 4 (loss due to the next object alignment) 56 (object boundary, size estimate) VM reports 56 bytes per instance

Field Layout in Java Instead, the attributes are organized in memory in the following order: 1.doubles and longs 2.ints and floats 3.shorts and chars 4.booleans and bytes 5.references Why was there a reference as the first field in HashMap ?

Compiling to Cish For every method m(x 1,…,x n ), generate a Cish function m(self,vtables,x 1,…,x n ). At startup, for every class C, create a record of C's methods (the vtable.) Collect all of the vtables into a big record. we will pass this data structure to each method as the vtables argument. wouldn't need this if we had a global variable in Cish for storing the vtables. Create a Main object and invoke its main() method.

Operations new C create a record big enough to hold a C object initialize the object's vtable pointer. initialize instance variables with default values 0 is default for int, false for bool, null for objects. return pointer to object as result e.m(e1,…,en) evaluate e to an object. extract a pointer to the m method from e's vtable invoke m, passing to it e,e1,…,en e is passed as self, or this. in a real system, must check that e isn't null!

Operations (continued) x, x := e read or write a variable. the variable could be a local or an instance variable. if it's an instance variable, we must use the "self" pointer to access the value. *(this+offset(x)) = [| e |] (C)e -- type casts if e has type D and D ≤ C, succeeds. (upcast) if e has type D and C ≤ D, performs a run-time check to make sure the object is actually (at least) a C. (downcast) if e has type D, and C is unrelated to D, then generates a compile-time error.

Subtleties in Type-Checking: Every object has a run-time type. Essentially its vtable. The type-checker tracks a static type. some super-type of the object. NB: Java confuses super-types and super-classes. In reality, if e is of type C, then e could be nil or a C object. Java "C" = ML "C option"

Subtyping vs. Inheritance Inheritance is a way to assemble classes Simple inheritance: D extends C implies D  C a read of instance variable x defined in C? okay because D has it too. an invocation of method m defined in C? okay because D has it too. m : (C self,T 1,…,T n )  T Read C instance variables, invoke C methods.

Overriding: class List { int hd; List tl; void append(List y) { if (tl == Nil) tl := y; else tl.append(y); } class DList extends List { DList prev; void append(DList y) { if (tl == Nil) { tl := y; if (y != Nil) y.prev := self; } else { tl.append(y); } Java won't let you say this…

Best you can do: class List { int hd; List tl; void append(List y) { if (tl == Nil) tl := y; else tl.append(y); } class DList extends List { DList prev; void append(List y) { if (tl == Nil) { tl := y; if (y != Nil) ((DList)y).prev := self; } else { tl.append(y); } Run-time type-check

What We Wish we Had… Don't just "copy" when inheriting: Also replace super-class name with sub-class name. That is, we need a "self" type as much as a self value. But this will not, in general, give you that the sub-class is a sub-type of the super-class. why?

Overloading In Java you can override a method, and you can also overload a method With overloading, you don’t update the behavior of a method, instead, within a class hierarchy, you have different methods with the same name However, for a call to such an overloaded method, we must be able to figure out which one to call at compile time

Danger of Overriding + Overloading Class C { Boolean equals(C other) { … } // 1 } Class SC extends C { Boolean equals(C other) { … } // 2 Boolean equals(SC other) { … } // 3 } C c = new C(); SC sc = new SC(); C c’ = new SC(); c.equals(c) ; c.equals(sc) ; c.equals(c’); c’.equals(c) ; c’.equals(sc) ; c’.equals(c’) ; sc.equals(c) ; sc.equals(sc) ; sc.equals(c’);