Translation to Target Language - Object

Transcrição

Translation to Target Language - Object
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
4.2
4.3
4.4
4.5
Intermediate Languages
Optimization
Command Selection
Register Allocation
Code Generation
5. Garbage Collection
6. XML Processing (DOM, SAX, XSLT)
Ina Schaefer
Translation to Target Language
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
Concepts of Object-Oriented Programming Languages
Example: Object-Oriented Language Concepts
Beispiel: (objektorientierte Sprachkonzepte)
class Person {
String name;
int gebdatum; /* in der Form JJJJMMTT */
Person( String n, int gd ) {
name = n;
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);
}
}
Ina Schaefer
class Student extends
Person {
Translation to Target Language
5
Concepts of Object-Oriented Programming Languages
(datum%10000);
}
Example: Object-Oriented Language Concepts (2)
}
class Student extends Person {
int matrikelnr;
int semester;
Student(String n,int gd,int mnr,int sem) {
super( n, gd );
matrikelnr = mnr;
semester = sem;
}
public void drucken() {
super.drucken();
System.out.println( "Mnr:"+ matrikelnr);
System.out.println(
i
"Sem:" + semester);
}
}
26.06.2007
Ina Schaefer
© A. Poetzsch-Heffter, TU Kaiserslautern
Translation to Target Language
254
6
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];
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();
}
} }
Das Beispiel zeigt Klassen, Objekterzeugung,
The
example demonstrates
classes,
creation, inheritance
Vererbung
(mit Subtyping
undobject
Spezialisierung)
sowie (with
subtyping and specialization) and dynamic method binding.
dynamisches Binden von Methoden.
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
Translation with Procedural Languages
Translation of Types and Methods
• Basis data types of Java → basis data types of C, for example:
I int → int
I boolean → int
(typedef int boolean;)
• Reference types of Java → pointer types of C, for example:
I String → String*
I Person → Person*
where String and Person are record types in C.
Ina Schaefer
Translation to Target Language
9
Translation with Procedural Languages
R f
Referenztypen
t
von
Java
J
! Zeigertypen
Z
von C
Implementation
of Example
in iC t
z.B. String
nach String*
Person
nach Person*
wobei String und Person in C geeignete Verbundtypen
Fields
areWir
realized
sind.
i d
Wi
betrachten
b t byhtrecord
die
di types:
Implementierung
I l
ti
von Person:
typedef struct sPerson Person;
struct sPerson {
String*
g name;
;
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",
printf(
Name:%s\n , this
this->name
>name );
Ina Schaefer
Translation to Target Language
10
String*
g name;
;
Translation with Procedural Languages
int
gebdatum; /* in der Form JJJJMMTT */
void
(*drucken)(
Person*
);
Implementation
of Example
in C (2)
boolean (*hat_geburtstag)( Person*, int );
};
Methods
are realized
by procedures:
Methoden
werden
als Prozeduren realisiert:
void Person_drucken( Person* this ) {
printf("Name:%s\n",
printf(
Name:%s\n , this
this->name
>name );
printf("Geb:%d\n",this->gebdatum);
}
boolean Person_hat_geburtstag
(Person* this,int datum){
(Person
return (this->gebdatum%10000)==(datum%10000);
}
26.06.2007
Ina Schaefer
© A. Poetzsch-Heffter, TU Kaiserslautern
Translation to Target Language
256
11
Translation with Procedural Languages
Implementation of Example in C (3)
Constructors are realized as procedures:
Konstruktoren werden als Prozeduren realisiert:
Person PersonK( String
Person*
String* n, int gd ) {
Person* this =
(Person*) malloc( sizeof(Person) );
this->name
= n;
this->gebdatum
= gd;
this->drucken
hi
d
k
= Person_drucken;
d
k
this->hat_geburtstag = Person_hat_geburtstag;
return this;
}
Übersetzung von Vererbung/Spezialisierung:
Bzgl.
g der Verbundkomponenten
p
wird Vererbung
g
Ina Schaefer
Translation to Target Language
12
}
Translation with Procedural Languages
Translation of Inheritance and Specialization
Übersetzung von Vererbung/Spezialisierung:
Inheritance
to record
components
is realized
Bzgl.
g with
der respect
Verbundkomponenten
p
wird Vererbung
g by
duplication:
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
semester;
};
Zu beachten ist die notwendige Typanpassung beim
Type conversions
for implicit
are necessary.
i li it A
impliziten
Argument
t iinarguments
d
der „Unterklasse“.
U t of
kl subclass
“
Ina Schaefer
Translation to Target Language
13
Translation with Procedural Languages
Translation of Inheritance and Specialization (2)
Bzgl. der Methoden lässt sich Vererbung ohne
InheritanceCodeduplikation
with respect to
methods
be realized
umsetzen;
diecan
Methoden
der without code
duplication.
Methodslassen
of superclass
be reused after appropriate
Oberklasse
sich nach can
geeigneter
Typkonvertierung unverändert verwenden:
type conversion.
Student* StudentK
(String* n,int
n int gd,int
gd int mnr,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;
}
Ina Schaefer
Spezialisierung wirdTranslation
durchtozusätzliche
Attribute (s.o.)
Target Language
14
Translation with Procedural Languages
return
this;
}
Translation
of Inheritance and Specialization (3)
Spezialisierung wird durch zusätzliche Attribute (s.o.)
und neue
Prozeduren
realisiert,
dieand
ggf.procedures
die
Specialization
is realized
by additional
attributes
that
überschriebenen
Methoden aufrufen:
may call
overridden methods:
void Student_drucken( Student* this ) {
Person_drucken( (Person*)this );
printf("Mnr:%d\n", this->matrikelnr );
printf("Sem:%d\n",
p
(
\ , this->semester );
}
26.06.2007
Ina Schaefer
© A. Poetzsch-Heffter, TU Kaiserslautern
Translation to Target Language
258
15
Translation with Procedural Languages
Translation
of Objectvon
Creation
& Method
Übersetzung
Objekterzeugung
und Invocation
Methodenaufruf:
• Object creation
corresponds
to call
of the
constructor.
• Objekterzeugung
entspricht
einem
„Konstruktoraufruf“;
• Method•invocation
is realized
bySelektion
selection
and call of method
Methodenaufruf
wird durch
und
derobject
zum Objekt gehörenden Methode realisiert.
belongingAufruf
to the
void main( String* argv[] ) {
int i;
Person* pf[3];
pf[0] = PersonK( "Meyer", 19631007 );
pf[1] = (Person*)
StudentK("M\"uller",19641223,758475,5);
pf[2] = (Person*)
StudentK("Planck",18580423,3454545,47);
for( i = 0; i<3; i = i+1 ) {
pf[i]->drucken( pf[i] );
}
}
Ina Schaefer
Zu beachten ist die
doppelte
pp to Target
Angabe
g
des Zielobjekts
j
Translation
Language
16
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
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
referenziert
werden
können.
• Als Identität des Objekts wird häufig die
Object Layout
(2)
Anfangsadresse des Speicherbereichs
verwendet (bzw. eine geeignete andere Adresse).
Example:
Beispiel: (Objektlayout)
KlassenClass and&
MethodenMethod
Information
Information
zu
forKlasse
Class AA
class A {
int a1;
private int a2;
}
Objektreferenz
Object
Reference
class:
a1:
•
a2:
Wie bei Verbunden werden Attributinstanzen/Instanzvariablen
über eine Relativadresse (offset) bzgl. der Objektreferenz
records,
attribute instances/instance variables are addressed
adressiert.
As for
a relative address (offset) with respect to the object reference.
26.06.2007
Ina Schaefer
© A. Poetzsch-Heffter, TU Kaiserslautern
Translation to Target Language
by
261
20
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 {
int b;
...
}
Class and&
KlassenMethod
MethodenMethoden
Information
Information
forKlasse
Class CC
zu
class C extends B {
int c;
}
Objektreferenz
j Reference
Object
class:
a1:
•
a2:
b:
c:
Ina Schaefer
Die Größe der
einzelnen
Translation
to Instanzvariablen
Target Language hängt selbst-
21
Translation of Classes
Object Layout (4)
Remarks:
Bemerkungen:
• In the above example,
we have
nothaben
considered
attribute instances
• Im obigen
Beispiel
wir Attributinstanzen
der
Klasse
Object
vernachlässigt
of the class Object.
Private Attributinstanzen
von Oberklassen
• Private attribute •instances
of superclasses
have to bemüssen
present in
auch in Instanzen von Unterklassen vorhanden sein:
all instances of subclasses:
class A {
int a1;
private int a2;
int m() { return a2; }
}
class B extends A {
int b;
int n() { return m(); }
}
• Zur Klassen
Klassen- und Methodeninformation siehe unten.
Ina Schaefer
Translation to Target Language
22
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
Translation of Classes
man bei Auswertung
von E in S erhält.
Alternative Object Layout
Alternatives Objektlayout:
In some cases, also an object descriptor is used. Here, the example of
a C object:Teilweise wird auch mit einem Objektdeskriptor
gearbeitet,
b it t hier
hi am Beispiel
B i i l eines
i
C-Objekts:
C Obj kt
Class and&
KlassenMethod
MethodenInformation
Information
forKlasse
Class CC
zu
Object Reference
Objektreferenz
Descriptor
Deskriptor
class:
•
•
a1:
a2:
b:
c:
Ina Schaefer
26.06.2007
Translation
to Target Language
© A.
Poetzsch-Heffter,
TU Kaiserslautern
264
25
Translation of Classes
Alternative Object Layout (2)
Remarks:
• Pros:
I
I
all object descriptors have the same memory requirements
memory block for instance variables can be more easily moved
(simplifies for instance garbage collection)
• Cons:
I more memory per object
I additional dereferencing step for accessing instance variables
Ina Schaefer
Translation to Target Language
26
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 method getName
Ina Schaefer
Translation to Target Language
28
Translation
of Classes
besitzt unter
anderem:
• die statische Methode forName
• die Instanzmethode getMethod
Example: Introspection in Java (2)
import java.lang.reflect.*;
public class Inspektor {
public static void main(String[]
p
(
g[] ss)
) {
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.println( ");" );
}
} catch( ClassNotFoundException e ) {
System.out.println("Klasse
System.out.println(
Klasse "+
+ ss[0]+"
ss[0]+ fehlt
fehlt");
);
}
} }
26.06.2007
Ina Schaefer
© A. Poetzsch-Heffter, TU Kaiserslautern
Translation to Target Language
266
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
Translation of Classes
einer Klasse
die gleichen Methoden haben, kann
man die Methodeninformation aller Objekte einer
Virtual Method
Table
Klasse gemeinsam speichern. Dadurch spart man
gegenüber der Realisierung von 3.2.2 erheblich
an Speicher.
Classically, method
information is stored in a virtual method/functions
Wir betrachten
hier
die klassische
Realisierung
table. (For simplicity,
class
information
is not
shown) mit
einer Methodentabelle (virtual method/functions table):
class
int
int
int
int
}
A {
a1;
a2;
() { ... }
m()
n( int i ) {...}
Alle
all A-Objekte
objects
teilen
sich
mtab
share
mtab
A::m
Objektreferenz
Object
Reference
mtab:
a1:
•
A::n
a2:
(Aus Gründen der Übersichtlichkeit haben wir auf
die Angabe von Klasseninformation verzichtet.)
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
(s. Beispiel) Translation of Classes
Method Overriding
Beispiel: (Überschreiben von Methoden)
class
int
int
int
int
}
A {
a1;
mtab:
a2;
a1:
m() { ... }
a2:
n( int i ){...}
class B extends A {
int b;
int m() { ... }
void p() { ... }
}
mtab:
a1:
•
•
A::m
A::n
B::m
A::n
B::p
p
a2:
b:
26.06.2007
Ina Schaefer
© A. Poetzsch-Heffter, TU Kaiserslautern
Translation to Target Language
268
33
Translation of Classes
Method Overriding (2)
Adressierung einer Methode jeweils indirekt über
A method is addressed indirectly by the method table and the relative
Methodentabelle und Relativadresse:
address:
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();
... avar.m()
() ... // M[avar.mtab]+RA(m)
M[
t b]+RA( )
! B::m
... avar.n(7) ... // M[avar.mtab]+RA(n)
! A::n
Ina Schaefer
Translation to Target Language
34
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
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)
Beispiel: (Mehrfachvererbung)
Example:
In folgendem Klassendiagramm erbt E mehrfach:
A
k3
k4
B
k1
k2
C
k5
D
k2
k3
E
k6
Problematik:
Ina Schaefer
Translation
to Target
Languageerben, d.h. von
• Soll E die Attribute
von
A doppelt
38
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
Unter der Annahme, dass E von A doppelt erbt,
components:
besitzt ein E-Objekt die folgenden Komponenten:
•
A
B
C
D
E
B::k1
B::k2
A::k3
A::k4
C::k5
A::k3
A::k4
D::k2
D::k3
E::k6
Ina Schaefer
Translation to Target Language
40
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
Further Aspects of Object-Oriented Languages
• Reflexion
Example: Local Classes
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
Ina Schaefer
© A. Poetzsch-Heffter, TU Kaiserslautern
Translation to Target Language
273
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?
Questions:
Was ist die Ausgabe und warum?
• Are there errors?
• What is the output and why?
Lesen Sie zu Abschnitt 3.2:
Ina Schaefer
Translation to Target Language
44
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)
attributed (abstract)
syntax tree (SL)
Scanner
Translator
token stream
abstract syntax tree (TL)
Parser
Code
Generator
(abstract) syntax tree
Name & Type
Analysis
Ina Schaefer
Output File
(target code)
Translation to Target Language
46
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
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
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
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