• Keine Ergebnisse gefunden

Translation to Target Language - Object-Oriented Language Constructs -

N/A
N/A
Protected

Academic year: 2022

Aktie "Translation to Target Language - Object-Oriented Language Constructs -"

Copied!
27
0
0

Wird geladen.... (Jetzt Volltext ansehen)

Volltext

(1)

Translation to Target Language

- Object-Oriented Language Constructs - Lecture Compilers SS 2009

Dr.-Ing. Ina Schaefer

Software Technology Group TU Kaiserslautern

Ina Schaefer Translation to Target Language 1

Content of Lecture

1. Introduction: Overview and Motivation 2. Syntax- and Type Analysis

2.1 Lexical Analysis

2.2 Context-Free Syntax Analysis 2.3 Context-Sensitive Syntax Analysis 3. Translation to Target Language

3.1 Translation of Imperative Language Constructs 3.2 Translation of Object-Oriented Language Constructs 4. Selected Aspects of Compilers

4.1 Intermediate Languages 4.2 Optimization

4.3 Command Selection 4.4 Register Allocation 4.5 Code Generation 5. Garbage Collection

6. XML Processing (DOM, SAX, XSLT)

Ina Schaefer Translation to Target Language 2

(2)

Outline

1. Concepts of Object-Oriented Programming Languages 2. Translation with Procedural Languages

3. Translation of Classes

4. Problems of Multiple Inheritance

5. Further Aspects of Object-Oriented Languages 6. Summary - A Simple Compiler

Ina Schaefer Translation to Target Language 3

Concepts of Object-Oriented Programming Languages

Concepts of Object-Oriented Programming Languages

We consider a class-based language and use Java as an example.

Important Concepts:

Classes and Object Creation

Encapsulation

Subtyping and Inheritance

Dynamic Method Binding

Ina Schaefer Translation to Target Language 4

(3)

Concepts of Object-Oriented Programming Languages

Example: Object-Oriented Language Concepts Beispiel: (objektorientierte Sprachkonzepte)

class Person { String name;

String name;

int gebdatum; /* in der Form JJJJMMTT */

Person( String n, int gd ) { name = n;

gebdatum = gd;

gebdatum gd;

}

public void drucken() {

System.out.println("Name:"+ this.name);

System.out.println("Geb:"+ this.gebdatum);

}

boolean hat_geburtstag ( int datum ) { return (this.gebdatum%10000) ==

(datum%10000);

} } }

class Student extends Person { int matrikelnr;

int semester;

int semester;

Student(String n,int gd,int mnr,int sem) { super( n, gd );

matrikelnr = mnr;

semester = sem;

semester sem;

}

public void drucken() { super.drucken();

System.out.println( "Mnr:"+ matrikelnr);

i

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 254

System.out.println( "Sem:" + semester);

} }

Ina Schaefer Translation to Target Language 5

Concepts of Object-Oriented Programming Languages

Example: Object-Oriented Language Concepts (2) Beispiel: (objektorientierte Sprachkonzepte)

class Person { String name;

String name;

int gebdatum; /* in der Form JJJJMMTT */

Person( String n, int gd ) { name = n;

gebdatum = gd;

gebdatum gd;

}

public void drucken() {

System.out.println("Name:"+ this.name);

System.out.println("Geb:"+ this.gebdatum);

}

boolean hat_geburtstag ( int datum ) { return (this.gebdatum%10000) ==

(datum%10000);

} } }

class Student extends Person { int matrikelnr;

int semester;

int semester;

Student(String n,int gd,int mnr,int sem) { super( n, gd );

matrikelnr = mnr;

semester = sem;

semester sem;

}

public void drucken() { super.drucken();

System.out.println( "Mnr:"+ matrikelnr);

i

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 254

System.out.println( "Sem:" + semester);

} }

Ina Schaefer Translation to Target Language 6

(4)

Concepts of Object-Oriented Programming Languages

Example: Object-Oriented Language Concepts (3)

class Test {

public static void main( String[] argv ) { int i;

Person[] pf = new Person[3];

Person[] pf new Person[3];

pf[0] = new Person( "Meyer", 19631007 );

pf[1] = new Student("M\"uller",19641223,758475,5);

pf[2] = new Student("Planck",18580423,3454545,47);

for( i = 0; i<3; i = i+1 ) { pf[i].drucken();

pf[i].drucken();

} } }

Das Beispiel zeigt Klassen, Objekterzeugung,

Vererbung (mit Subtyping und Spezialisierung) sowie Vererbung (mit Subtyping und Spezialisierung) sowie dynamisches Binden von Methoden.

Anhand des obigen Beispiels erläutern wir die

3.2.2 Umsetzung mit

prozeduralen Sprachen

Anhand des obigen Beispiels erläutern wir die grundlegenden Übersetzungsschemata:

Klassen, Klassentypen ! Verbundtypen, Zeigertypen Objekterzeugung ! Allokation dyn. Variablen/Objekte Objekterzeugung ! Allokation dyn. Variablen/Objekte Methoden, Konstruktoren ! Prozeduren

dyn. Bindung ! Verwendung von Prozedurzeigern mit Selektion von Verbundkomponenten

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 255

mit Selektion von Verbundkomponenten Als Zielsprache verwenden wir hier C.

The example demonstrates classes, object creation, inheritance (with subtyping and specialization) and dynamic method binding.

Ina Schaefer Translation to Target Language 7

Translation with Procedural Languages

Translation with Procedural Languages

Translation Schemes:

Classes, class types record types, pointer types

Object creation Allocation of dynamic variables/objects

Methods, constructors procedures

Dynamic binding Use of procedure pointers with selection of record components

We illustrate these schemes at the above example. The considered target language is C.

Ina Schaefer Translation to Target Language 8

(5)

Translation with Procedural Languages

Translation of Types and Methods

Basis data types of Java basis data types of C, for example:

! intint

! boolean int

(typedef int boolean;)

Reference types of Java pointer types of C, for example:

! StringString*

! Person Person*

where String and Person are record types in C.

Ina Schaefer Translation to Target Language 9

Translation with Procedural Languages

Implementation of Example in C

Fields are realized by record types:

Übersetzung der Typen und Methoden:

Basisdatentypen von Java ! Basisdatentypen von z.B. int nach int

boolean nach int

R f t J ! Z i t C

( typedef int boolean; )

Referenztypen von Java ! Zeigertypen von C z.B. String nach String*

Person nach Person*

wobei String und Person in C geeignete Verbundtypen i d Wi b t ht di I l ti

typedef struct sPerson Person;

struct sPerson { String* name;

sind. Wir betrachten die Implementierung von Person :

g ;

int gebdatum; /* in der Form JJJJMMTT */

void (*drucken)( Person* );

boolean (*hat_geburtstag)( Person*, int );

};

Methoden werden als Prozeduren realisiert:

void Person_drucken( Person* this ) { printf("Name:%s\n", this->name );

printf( Name:%s\n , this >name );

printf("Geb:%d\n",this->gebdatum);

}

boolean Person_hat_geburtstag

(Person* this,int datum){

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 256

(Person this,int datum){

return (this->gebdatum%10000)==(datum%10000);

}

Ina Schaefer Translation to Target Language 10

(6)

Translation with Procedural Languages

Implementation of Example in C (2)

Methods are realized by procedures:

Übersetzung der Typen und Methoden:

Basisdatentypen von Java ! Basisdatentypen von z.B. int nach int

boolean nach int

R f t J ! Z i t C

( typedef int boolean; ) Referenztypen von Java ! Zeigertypen von C

z.B. String nach String*

Person nach Person*

wobei String und Person in C geeignete Verbundtypen i d Wi b t ht di I l ti

typedef struct sPerson Person;

struct sPerson { String* name;

sind. Wir betrachten die Implementierung von Person:

g ;

int gebdatum; /* in der Form JJJJMMTT */

void (*drucken)( Person* );

boolean (*hat_geburtstag)( Person*, int );

};

Methoden werden als Prozeduren realisiert:

void Person_drucken( Person* this ) { printf("Name:%s\n", this->name );

printf( Name:%s\n , this >name );

printf("Geb:%d\n",this->gebdatum);

}

boolean Person_hat_geburtstag

(Person* this,int datum){

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 256

(Person this,int datum){

return (this->gebdatum%10000)==(datum%10000);

}

Ina Schaefer Translation to Target Language 11

Translation with Procedural Languages

Implementation of Example in C (3)

Constructors are realized as procedures:

Person* PersonK( String* n, int gd ) { Konstruktoren werden als Prozeduren realisiert:

Person PersonK( String n, int gd ) { Person* this =

(Person*) malloc( sizeof(Person) );

this->name = n;

this->gebdatum = gd;

hi d k d k

this->drucken = Person_drucken;

this->hat_geburtstag = Person_hat_geburtstag;

return this;

}

Übersetzung von Vererbung/Spezialisierung:

Bzgl. der Verbundkomponenten wird Vererbung g p g im Wesentlichen durch Duplikation realisiert:

typedef struct sStudent Student;

struct sStudent { String* name;

int gebdatum; /* in der Form JJJJMMTT */

void (*drucken)( Student* );

boolean (*hat_geburtstag)( Student*, int );

int matrikelnr;

int matrikelnr;

int semester;

};

Zu beachten ist die notwendige Typanpassung beim

i li it A t i d U t kl “

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 257

impliziten Argument in der „Unterklasse“.

Ina Schaefer Translation to Target Language 12

(7)

Translation with Procedural Languages

Translation of Inheritance and Specialization

Inheritance with respect to record components is realized by duplication:

Person* PersonK( String* n, int gd ) { Konstruktoren werden als Prozeduren realisiert:

Person PersonK( String n, int gd ) { Person* this =

(Person*) malloc( sizeof(Person) );

this->name = n;

this->gebdatum = gd;

hi d k d k

this->drucken = Person_drucken;

this->hat_geburtstag = Person_hat_geburtstag;

return this;

}

Übersetzung von Vererbung/Spezialisierung:

Bzgl. der Verbundkomponenten wird Vererbung g p g im Wesentlichen durch Duplikation realisiert:

typedef struct sStudent Student;

struct sStudent { String* name;

int gebdatum; /* in der Form JJJJMMTT */

void (*drucken)( Student* );

boolean (*hat_geburtstag)( Student*, int );

int matrikelnr;

int matrikelnr;

int semester;

};

Zu beachten ist die notwendige Typanpassung beim

i li it A t i d U t kl “

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 257

impliziten Argument in der „Unterklasse“.

Type conversions for implicit arguments of subclass are necessary.

Ina Schaefer Translation to Target Language 13

Translation with Procedural Languages

Translation of Inheritance and Specialization (2)

Inheritance with respect to methods can be realized without code duplication. Methods of superclass can be reused after appropriate type conversion.

Bzgl. der Methoden lässt sich Vererbung ohne Codeduplikation umsetzen; die Methoden der Oberklasse lassen sich nach geeigneter

Student* StudentK

(String* n int gd int mnr int sem ) { Oberklasse lassen sich nach geeigneter

Typkonvertierung unverändert verwenden:

(String* n,int gd,int mnr,int sem ) { Student* this =

(Student*) malloc(sizeof(Student));

this->name = n;

this->gebdatum = gd;

this->matrikelnr = mnr;

this->semester = sem;

this->drucken = Student_drucken;

this->hat_geburtstag =

(boolean(*)(Student* int)) (boolean(*)(Student*,int))

Person_hat_geburtstag;

return this;

}

Spezialisierung wird durch zusätzliche Attribute (s.o.) und neue Prozeduren realisiert, die ggf. die

überschriebenen Methoden aufrufen:

void Student_drucken( Student* this ) { Person_drucken( (Person*)this );

printf("Mnr:%d\n", this->matrikelnr );

printf("Sem:%d\n", this->semester );

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 258

p ( \ , );

}

Ina Schaefer Translation to Target Language 14

(8)

Translation with Procedural Languages

Translation of Inheritance and Specialization (3)

Specialization is realized by additional attributes and procedures that may call overridden methods:

Bzgl. der Methoden lässt sich Vererbung ohne Codeduplikation umsetzen; die Methoden der Oberklasse lassen sich nach geeigneter

Student* StudentK

(String* n int gd int mnr int sem ) {

Oberklasse lassen sich nach geeigneter Typkonvertierung unverändert verwenden:

(String* n,int gd,int mnr,int sem ) { Student* this =

(Student*) malloc(sizeof(Student));

this->name = n;

this->gebdatum = gd;

this->matrikelnr = mnr;

this->semester = sem;

this->drucken = Student_drucken;

this->hat_geburtstag =

(boolean(*)(Student* int)) (boolean(*)(Student*,int))

Person_hat_geburtstag;

return this;

}

Spezialisierung wird durch zusätzliche Attribute (s.o.) und neue Prozeduren realisiert, die ggf. die

überschriebenen Methoden aufrufen:

void Student_drucken( Student* this ) { Person_drucken( (Person*)this );

printf("Mnr:%d\n", this->matrikelnr );

printf("Sem:%d\n", this->semester );

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 258

p ( \ , );

}

Ina Schaefer Translation to Target Language 15

Translation with Procedural Languages

Translation of Object Creation & Method Invocation

Object creation corresponds to call of the constructor.

Method invocation is realized by selection and call of method belonging to the object

Übersetzung von Objekterzeugung und Methodenaufruf:

Methodenaufruf:

• Objekterzeugung entspricht einem „Konstruktoraufruf“;

• Methodenaufruf wird durch Selektion und

void main( String* argv[] ) { int i;

Aufruf der zum Objekt gehörenden Methode realisiert.

Person* pf[3];

pf[0] = PersonK( "Meyer", 19631007 );

pf[1] = (Person*)

StudentK("M\"uller",19641223,758475,5);

pf[2] = (Person*) pf[2] = (Person*)

StudentK("Planck",18580423,3454545,47);

for( i = 0; i<3; i = i+1 ) { pf[i]->drucken( pf[i] );

} } }

Zu beachten ist die doppelte Angabe des Zielobjektspp g j beim „Methodenaufruf“.

Dynamische Bindung wird also durch Verwendung von Prozedurzeigern erreicht.

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 259

g

Ina Schaefer Translation to Target Language 16

(9)

Translation with Procedural Languages

Translation of Object Creation & Method Invocation (2)

Note the duplicate reference to the target object in a "method call".

Dynamic binding is realized by usage of procedure pointers.

Remarks:

Record components are not "inherited" and have to be re-listed for each subclass.

No usage of superclass constructor

Explicit type conversion necessary

Direct pointers to methods of an object use needlessly much memory.

Dynamic binding only requires dereferencing which is almost as efficient as an ordinary procedure call.

Ina Schaefer Translation to Target Language 17

Translation of Classes

Translation of Classes

Classes declare:

attributes (in Java: fields)

constructors

methods

In the following, we consider a language that supports only single inheritance (cf. Java), i.e., each class (except Object) has exactly one superclass.

Ina Schaefer Translation to Target Language 18

(10)

Translation of Classes

Object Layout

Objects are handled as memory areas on the heap:

Each object of class C gets a variable (object state) for each inherited and for each attribute declared in C.

Additionally, it gets a variable for referring to information about the class and its methods.

As object identity, often the start address of the memory area is used (or another appropriate address).

Ina Schaefer Translation to Target Language 19

Translation of Classes

Object Layout (2)

Example:

Objekte werden als Speicherbereiche auf der Halde verwaltet:

Objektlayout:

der Halde verwaltet:

• Dabei enthält ein Objekt einer Klasse K für jedes ererbte und jedes in K deklarierte Attribut eine Variable (Objektzustand).

• Zusätzlich enthält es eine Variable, mittels der Informationen über Methoden bzw. die Klasse referenziert werden können.

• Als Identität des Objekts wird häufig die

• Als Identität des Objekts wird häufig die Anfangsadresse des Speicherbereichs

verwendet (bzw. eine geeignete andere Adresse).

Beispiel: (Objektlayout)

class A { int a1;

private int a2;

Klassen- &

Methoden- Information private int a2;

}

Information zu Klasse A

class:

Objektreferenz

class:

a1:

a2:

Wie bei Verbunden werden Attributinstanzen/Instanzvariablen

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 261

Wie bei Verbunden werden Attributinstanzen/Instanzvariablen über eine Relativadresse (offset) bzgl. der Objektreferenz adressiert.

Object Reference

Class and Method Information

for Class A

As for records, attribute instances/instance variables are addressed by a relative address (offset) with respect to the object reference.

Ina Schaefer Translation to Target Language 20

(11)

Translation of Classes

Object Layout (3)

The size of the instance variables depends on their type. In Java, int and float variables require 4 bytes, long and double variables require 8 bytes.

class A { int a1;

private int a2;

...

}

class B extends A { class B extends A {

int b;

...

} Klassen- &

Methoden- class C extends B {

int c;

}

Methoden Information zu Klasse C

Objektreferenz

class:

a1:

a2:

j

b:

c:

Die Größe der einzelnen Instanzvariablen hängt selbst- verständlich von deren Typ ab. So benötigt man in Java für int- und float-Variablen beispielsweise 4 Byte, für long- und double-Variablen 8-Byte.

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 262

Object Reference

Class and Method Information for Class C

Ina Schaefer Translation to Target Language 21

Translation of Classes

Object Layout (4)

Remarks:

In the above example, we have not considered attribute instances of the class Object.

Private attribute instances of superclasses have to be present in all instances of subclasses:

Bemerkungen:

• Im obigen Beispiel haben wir Attributinstanzen der Klasse Object vernachlässigt

• Private Attributinstanzen von Oberklassen müssen auch in Instanzen von Unterklassen vorhanden sein:

class A { int a1;

private int a2;

int m() { return a2; } }

class B extends A { int b;

int n() { return m(); } int n() { return m(); } }

• Zur Klassen- und Methodeninformation siehe unten.Zur Klassen und Methodeninformation siehe unten.

• Die Reihenfolge der Attributinstanzen ist wichtig, um Subtyping zu ermöglichen:

Jedes Unterklassen-Objekt muss überall dort eingesetzt werden können, wo ein Oberklassen- Objekt erwartet wird.

Deshalb müssen die Attributinstanzen der Oberklasse in Ober und Unterklasse Objekten

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 263

Oberklasse in Ober- und Unterklasse-Objekten die gleiche Relativadresse besitzen.

Ina Schaefer Translation to Target Language 22

(12)

Translation of Classes

Object Layout (5)

The ordering of attribute instances is important to allow for subtyping:

Each subclass object can be placed in all positions where a superclass object is expected.

Thus, the attribute instances of the superclass have to have the same relative addresses in all sub- and superclass objects.

Ina Schaefer Translation to Target Language 23

Translation of Classes

Example: Access to Subclass Objects

A avar = new B();

... a.avar.a2...

The relative address of a2 has to be independent of the dynamic type of avar. The dynamic type of a reference-typed expression E in a state S is the type of the object that is obtained by evaluating E in the state S.

Ina Schaefer Translation to Target Language 24

(13)

Translation of Classes

Alternative Object Layout

In some cases, also an object descriptor is used. Here, the example of a C object:

Beispiel: (Zugriff auf Unterklassen-Objekte)

A B()

A avar = new B();

... avar.a2 ...

d.h. Relativadresse von a2 muss unabhängig vom dynamischen Typ von avar sein wobei der

dynamischen Typ von avar sein, wobei der

dynamische Typ eines referenzwertigen Ausdrucks E in einem Zustand S der Typ des Objekts ist, das

man bei Auswertung von E in S erhält.

Alternatives Objektlayout:

Teilweise wird auch mit einem Objektdeskriptor b it t hi B i i l i C Obj kt gearbeitet, hier am Beispiel eines C-Objekts:

Klassen- &

Methoden- Objektreferenz

Information zu Klasse C

class:

Deskriptor

a1:

a2:

b:

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 264

c:

Object Reference Class and

Method Information

for Class C

Descriptor

Ina Schaefer Translation to Target Language 25

Translation of Classes

Alternative Object Layout (2)

Remarks:

Pros:

! all object descriptors have the same memory requirements

! memory block for instance variables can be more easily moved (simplifies for instance garbage collection)

Cons:

! more memory per object

! additional dereferencing step for accessing instance variables

Ina Schaefer Translation to Target Language 26

(14)

Translation of Classes

Class Information

The content (and the extend) of the class information depends on the language. Three typical examples:

Class information is not provided at runtime.

Class information contains all information required for dynamic type conversion :

A avar = new b();

B bvar = (B) avar;

Class information is represented by an object that allows introspection (requesting class information at runtime) and reflection (modifying the program at runtime).

Ina Schaefer Translation to Target Language 27

Translation of Classes

Example: Introspection in Java

Java supports introspection by using objects of the class Class. For each type in a Java program, there exists one object of the class Class. The class Class contains amongst others:

the static method forName

the instance methodgetName

Ina Schaefer Translation to Target Language 28

(15)

Translation of Classes

Example: Introspection in Java (2)

Beispiel: (Introspektion in Java)

Java unterstützt Introspektion mittels Objekten der Klasse Class Für jeden Typ eines Java-Programms Klasse Class. Für jeden Typ eines Java-Programms gibt es ein Objekt der Klasse Class. Die Klasse Class besitzt unter anderem:

• die statische Methode forName

• die Instanzmethode getMethod

import java.lang.reflect.*;

public class Inspektor {

public static void main(String[] ss) {

die Instanzmethode getMethod

p ( g[] ) {

try{

Class klasse = Class.forName( ss[0] );

Method[] methoden = klasse.getMethods();

for( int i = 0; i < methoden.length; i++ ){

Method m = methoden[i];

Class retType = m.getReturnType();

String methName = m.getName();

Class[] parTypes = m.getParameterTypes();

S stem o t p int( etT pe getName() + " "

System.out.print(retType.getName() + " "

+ methName+"(" );

for( int j = 0; j < parTypes.length; j++ ){

if( j > 0 ) System.out.print(", ");

System.out.print( parTypes[j].getName() );

System.out.print( parTypes[j].getName() );

}

System.out.println( ");" );

}

} catch( ClassNotFoundException e ) {

System.out.println("Klasse "+ ss[0]+" fehlt");

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 266 System.out.println( Klasse + ss[0]+ fehlt );

} } }

Ina Schaefer Translation to Target Language 29

Translation of Classes

Realization of Methods

Method information allows accessing methods belonging to an object:

It provides the data structure for realization of dynamic binding.

In class-based languages, all objects of a class have the same methods; thus, method information of all objects of a class can be stored together. (more memory-efficient compared to realization by procedures)

Ina Schaefer Translation to Target Language 30

(16)

Translation of Classes

Virtual Method Table

Classically, method information is stored in a virtual method/functions table. (For simplicity, class information is not shown)

Methodenrealisierung:

Die Methodeninformation ermöglicht den Zugriff auf die zu einem Objekt gehörenden Methoden:

die zu einem Objekt gehörenden Methoden:

• Sie liefert die Datenstruktur zur Realisierung des dynamischen Bindens.

• Da bei klassenbasierten Sprachen alle Objekte p j einer Klasse die gleichen Methoden haben, kann man die Methodeninformation aller Objekte einer Klasse gemeinsam speichern. Dadurch spart man gegenüber der Realisierung von 3.2.2 erheblich gegenüber der Realisierung von 3.2.2 erheblich an Speicher.

Wir betrachten hier die klassische Realisierung mit einer Methodentabelle (virtual method/functions table):

class A { int a1;

int a2;

int m() { ... }

Alle A-Objekte teilen sich mtab

() { }

int n( int i ) {...}

}

Objektreferenz A::m

A::n mtab:

a1:

a2:

A::n

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 267

(Aus Gründen der Übersichtlichkeit haben wir auf die Angabe von Klasseninformation verzichtet.)

Object Reference

all objects share mtab

Ina Schaefer Translation to Target Language 31

Translation of Classes

Virtual Method Table (2)

For each class, there exists exactly one method table. The pointer to the method table is set by the constructor.

The method table contains pointers to the method implementations.

This technique allows for subtyping, as the relative address of the subclass methods can be chosen such that there are the same addresses in super- and subclasses.

It further allows method overriding by changing the according method entry.

Ina Schaefer Translation to Target Language 32

(17)

Translation of Classes

Method Overriding

• Es existiert also für jede Klasse genau eine Methodentabelle. Der Zeiger auf die Methoden- tabelle wird vom Konstruktor gesetzt

tabelle wird vom Konstruktor gesetzt.

• Die Methodentabelle enthält Zeiger auf die Methodenimplementierungen.

• Die Technik ermöglicht Subtyping, da die Relativ-g yp g, adressen von Oberklasse-Methoden so gewählt werden können, dass sie in Ober- und Unterklasse gleich sind.

• Die Technik ermöglicht Überschreiben durch

• Die Technik ermöglicht Überschreiben durch Ausstausch des entsprechenden Eintrags (s. Beispiel)

Beispiel: (Überschreiben von Methoden)

class A {

int a1; mtab:

A::nA::m

int a2;

int m() { ... } int n( int i ){...}

}

a1:

a2:

A::n

class B extends A { int b;

int m() { ... } void p() { ... }

mtab:

a1:

B::m A::n B::p

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 268

} a2:

p b:

Ina Schaefer Translation to Target Language 33

Translation of Classes

Method Overriding (2)

A method is addressed indirectly by the method table and the relative address:

Adressierung einer Methode jeweils indirekt über Methodentabelle und Relativadresse:

Methodentabelle und Relativadresse:

A avar = new A();

... avar.m() ... // M[avar.mtab]+RA(m)

! A::m

... avar.n(7) ... // M[avar.mtab]+RA(n)

! A::n

A avar = new B();

() // M[ t b]+RA( ) ... avar.m() ... // M[avar.mtab]+RA(m)

! B::m

... avar.n(7) ... // M[avar.mtab]+RA(n)

! A::n

Wie bei den Instanzvariablen gewährleistet die richtige Wie bei den Instanzvariablen gewährleistet die richtige Reihenfolge der Einträge in der Methodentabelle,

dass auf ein Unterklassen-Objekt wie auf ein Oberklassen-Objekt zugegriffen werden kann.

Dabei werden automatisch überschreibende Methoden ausgewählt, sofern vorhanden.

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 269

Ina Schaefer Translation to Target Language 34

(18)

Translation of Classes

Method Overriding (3)

As for instance variables, the correct ordering of the entries in the method table allows that a subclass object can be accessed in the same way as a superclass object.

Overriding methods are selected automatically, if applicable.

Ina Schaefer Translation to Target Language 35

Translation of Classes

Realization of Constructors

Constructors are realized by procedures. Source language semantics typically requires the following for an object of class C:

Allocation of memory of the new C object

Recursive calls of the superclass constructors

Execution of the called constructor of C

Potentially: class loading, initialisation of variables

Ina Schaefer Translation to Target Language 36

(19)

Problems of Multiple Inheritance

Multiple Inheritance

The translation technique considered so far can only be used for languages with single inheritance. In this section, we sketch

the concept of multiple inheritance

the problems associated with multiple inheritance Multiple inheritance exists, for instance, in C++ or Eiffel.

With multiple inheritance, a class can inherit from several classes.

Ina Schaefer Translation to Target Language 37

Problems of Multiple Inheritance

Multiple Inheritance (2)

Example: Beispiel: (Mehrfachvererbung)

In folgendem Klassendiagramm erbt E mehrfach:

A k3 k4 B

k1 k2

C D

k5 k2

k3

E k6

Problematik:

Problematik:

• Soll E die Attribute von A doppelt erben, d.h. von jeder Komponente zwei Kopien besitzen?

(nur relevant im Zusammenhang mit Attributen)

• Wie sollen Namenskonflikte aufgelöst werden?

( E erbt zwei Komponenten mit Namen k2)

• Mit welchen Techniken können E-Objekte so realisiert

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 271

werden, dass sie auch als A-, B-, C- und D-Objekte auftreten können?

Ina Schaefer Translation to Target Language 38

(20)

Problems of Multiple Inheritance

Difficulties of Multiple Inheritance

Does E inherit the attributes of A twice, i.e. does it contain two copies of each component? (only relevant for attributes)

How are name conflicts resolved? (E inherits two components with name k2.)

How can E objects be realized such that they can be used as A, B, C or D objects in the same way?

Ina Schaefer Translation to Target Language 39

Problems of Multiple Inheritance

Difficulties of Multiple Inheritance (2)

Assuming, E inherits twice from A, an E object contains the following components:Unter der Annahme, dass E von A doppelt erbt,

besitzt ein E-Objekt die folgenden Komponenten:

E B::k1

B::k2 A::k3

D C B

A

A::k3 A::k4 C::k5 A::k3 A::k4 A::k4 D::k2 D::k3 E::k6

Mit obigem Komponentenlayout kann ein E-Objekt direkt als B- und C-Objekt verwendet werden, nicht aber als A- oder D-Objekt.

Lösungsansätze:

1. Implizite Typkonvertierung mit Veränderung der Referenz in den Speicherbereich

Referenz in den Speicherbereich.

(Nachteil: ggf. Problem bei Objektidentität) 2. Adressierung mit klassenspezifischen, global

verwendbaren Relativadressen (s. Appel).

(N ht il i ht d l t P

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 272

(Nachteil: nicht modular, gesamtes Programm muss bekannt sein).

Ina Schaefer Translation to Target Language 40

(21)

Problems of Multiple Inheritance

Difficulties of Multiple Inheritance (3)

With the above object layout, E can be used directly as a B object or as a C object, but not as an A or D object.

Solutions:

Implicit type conversion with modification of the reference into the memory area (Drawback: potentially, problem with object identity)

Addressing with class-specific, global relative addresses

(cf. Appel) (Drawback: non-modular, complete program has to be known)

Ina Schaefer Translation to Target Language 41

Further Aspects of Object-Oriented Languages

Further Aspects of Object-Oriented Languages

Static methods

Nested classes

Virtual classes

Encapsulation aspects

Dynamic Loading

Reflection

Ina Schaefer Translation to Target Language 42

(22)

Further Aspects of Object-Oriented Languages

Example: Local Classes

3.2.5 Weitere Aspekte bei OO-Sprachen

• statische Methoden

• geschachtelte Klassen

• virtuelle Klassen

• Kapselungsaspekte

• dynamisches Laden

• Reflexion

Beispiel: (Lokale Klassen)

class Outer {

Outer w( int j ) { int i = 2;

class Local extends Outer { Outer w( int jj ) {

System.out.println("i == " +i);

System.out.println("j == " +j);

return this;

} }

System.out.println("j == " + j );

return new Local();

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 273

} }

Ina Schaefer Translation to Target Language 43

Further Aspects of Object-Oriented Languages

Example: Local Classes (2)

public class LocalClassTest {

static public void main(String[] args){

Outer ov = new Outer();

ov.w( 5 ).w( 7 );

ov.w( 7 ).w( 9 );

} }

Gibt es Fehler?

Was ist die Ausgabe und warum?

Was ist die Ausgabe und warum?

Lesen Sie zu Abschnitt 3.2:

Wilhelm, Maurer:

Abschnitt 5 2 und Anfang von 5 3 (S 182 195)

• Abschnitt 5.2 und Anfang von 5.3 (S. 182-195) Appel:

• Sections 14.1-14.3, S. 303-310

26.06.2007 © A. Poetzsch-Heffter, TU Kaiserslautern 274

Questions:

Are there errors?

What is the output and why?

Ina Schaefer Translation to Target Language 44

(23)

Further Aspects of Object-Oriented Languages

Literature

Recommended Reading:

Wilhelm, Maurer: Sect. 5.2 and 5.3. (pp. 182 – 195)

Appel: Sect. 14.1–14.3, (pp. 303 – 310)

Ina Schaefer Translation to Target Language 45

Summary - A Simple Compiler

A Simple Compiler - Structure

Input File (source code)

Scanner

Parser

Name & Type Analysis

Translator

Code Generator

Output File (target code)

token stream

(abstract) syntax tree

attributed (abstract) syntax tree (SL)

abstract syntax tree (TL)

Ina Schaefer Translation to Target Language 46

(24)

Summary - A Simple Compiler

Tools for Compiler Realization

Scanner: JFlex

Parser: ANTLR, JavaCup

Abstract Syntax and Attribution for Name and Type Analysis and Translation/Code Generation: Katja

Ina Schaefer Translation to Target Language 47

Summary - A Simple Compiler

Scanner Specification - MiniJava in JFlex

[...]

DIGIT = [0-9]

LETTER = [a-zA-Z]

%%[ \t\n\r]* { }

"//" [^\r\n]* (\n | \r | \r\n) { }

"/*" [^*] ~"*/" { }

"class" { return symbol(TokenType.CLASS); } [...]

"void" { return symbol(TokenType.VOID); }

"static" { return symbol(TokenType.STATIC); }

"int" { return symbol(TokenType.INT); }

"boolean" { return symbol(TokenType.BOOLEAN); }

"return" { return symbol(TokenType.RETURN); }

"if" { return symbol(TokenType.IF); }

"else" { return symbol(TokenType.ELSE); }

"while" { return symbol(TokenType.WHILE); } [...]

Ina Schaefer Translation to Target Language 48

(25)

Summary - A Simple Compiler

Parser Specification - MiniJava in JavaCUP

[...] Statement ::=

Block:b

{: RESULT = b; :}

| IF:s ParExpression:e Statement:stm

{: RESULT = If(sleft, sright, e, stm, Block(-1,-1)); :}

| IF:s ParExpression:e Statement:stm ELSE Statement:estm {: RESULT = If(sleft, sright, e, stm, estm); :}

| WHILE:s ParExpression:e Statement:body

{: RESULT = While(sleft, sright, e, body); :}

| RETURN:s Expression:e SEMI

{: RESULT = Return(sleft, sright, e); :}

| RETURN:s SEMI

{: RESULT = VoidReturn(sleft, sright); :}

| SEMI:s

{: RESULT = Block(sleft, sright); :}

| ExpressionStatement:e

{: RESULT = e; :} ; [...]

Ina Schaefer Translation to Target Language 49

Summary - A Simple Compiler

Katja Specification for MiniJava Abstract Syntax

[...]

Statement = Block ( Integer line, Integer column, BlockStatements body )

| If ( Integer line, Integer column, Expression cond, Statement thenStmt, Statement elseStmt )

| While ( Integer line, Integer column,

Expression cond, Statement body )

| Return ( Integer line, Integer column, Expression retValue )

| VoidReturn ( Integer line, Integer column )

| Assignment ( Integer line, Integer column, Expression left, Expression right )

| Expression [...]

Ina Schaefer Translation to Target Language 50

(26)

Summary - A Simple Compiler

Implementation of Name Analysis using Katja

public static DeclarationPos lookupIn

final ScopePos scope, final IdentifierPos id) throws CantFind {

DeclarationPos result;

if (scope == null) throw new CantFind(id);

// search in cache if we already made that lookup [...]

result = scope.Switch(new ScopePos.Switch<DeclarationPos, NE>() { public DeclarationPos CaseBlockStatementsPos

(final BlockStatementsPos term) throws NE { [...]

}

Ina Schaefer Translation to Target Language 51

Summary - A Simple Compiler

Implementation of Name Analysis using Katja (2)

public DeclarationPos CaseMethodDeclPos(final MethodDeclPos term) throws NE {

for (FormalParameterPos param : term.params()) {

if (nameEquals(param.ident(), id)) return param;

}

return null; // did not find declaration of id }

public DeclarationPos CaseClassBodyDeclsPos

(final ClassBodyDeclsPos term) throws NE { [...]

}

Ina Schaefer Translation to Target Language 52

(27)

Summary - A Simple Compiler

Implementation of Name Analysis using Katja (3)

public DeclarationPos CaseTypeDeclsPos(final TypeDeclsPos term) throws NE {

for (TypeDeclPos typeDeclPos : term) { if (nameEquals(typeDeclPos.ident(), id))

return (ClassDeclPos) typeDeclPos;

}

return null; // did not find declaration of id }); }

return result;

}

Ina Schaefer Translation to Target Language 53

Referenzen

ÄHNLICHE DOKUMENTE

For the pilot study presented here, the performance of two randomly chosen students was compared over the two sessions (activation of the target language German in the first session

3.1 Translation of Imperative Language Constructs 3.1.1 Language Constructs of Procedural Language 3.1.2 Assembly and Machine Languages.. 3.1.3 Translation of Variables and Data

3.1 Translation of Imperative Language Constructs 3.1.1 Language Constructs of Procedural Language 3.1.2 Assembly and Machine Languages 3.1.3 Translation of Variables and Data

3.2 Translation of Object-Oriented Language Constructs 3.2.1 Concepts of Object-Oriented Programming Languages 3.2.2 Translation into Procedural Languages.. 3.2.3 Translation

Analoge to parameters, also procedure-local variables have to be stored in the stack frame, because there is one instance of the local variables for each procedure

Analoge to parameters, also procedure-local variables have to be stored in the stack frame, because there is one instance of the local variables for each procedure

Unified modeling language: Infrastructure, version 2.4.1. Unified modeling language: Superstructure,

This work therefore describes an approach to integrate fuzzy sets and constraints expressed in the Object Constraint Language (OCL) in a combined constraint reasoning process..