GJ Specication

zhaozj2021-02-17  55

GJ Specication

Gilad Bracha, Sun Microsystems

Martin Odersky, University of South Australia

David Stoutamire, Sun Microsystems

Philip Wadler, Lucent Technology Technologies

May 1998

1 summary

We propose to add generic type and methods to the javatm programing language.

THESE Are Both Explained and Implement by Translation Into The Current Language. The Current Language. The

Translation Closely Mimics The Way Gnerics Are Emulated by Programmers: in a nutshell,

IT ERASES All Type Parameters, Maps Type Variables To Their Bounds, And Inserts Casts AS

NEEDED. Some Subtleties of the Translation Are Caused by The Handling of Overriding.

The main bene t of gj over the current java programing language lies in the added

Expressiveness and Safety That Stems from Making Type Parameters Explicit and MAKING

Type Casts Implicit. this is crucial for use libraries Such as collections in a

EXIBLE, YET

Safe Way.

GJ Is Designed to Be Fully Backwards Compatible with the Current Language, MAKING THE

Transition from non-generic to generic programing very easy. in particular, one can

Retro T EXISTING LIBRARY CLASS with generic interfaces without changing their code.

This Paper Gives A Speci CATION for GJ. IT Has A Company Paper Which Gives An Overview

And Rational Of GJ's Concepts [Bosw98]. The present paper is Organized as Follows.

Section 2 Explains How Parameterized Types Are Declared and Used. Section 3 Explains

Polymorphic Methods. Section 4 Explains How Parameterized Types Integrate with Exceptions.

Section 5 Explains What Changes in The Java Programming Language's Expression

Constructs. Section 6 Explains How Gj Is Translated Into The Java Virtual Machine (JVM).

Section 7 Explains How Generic Type Information Is Stored In Class Les. Where Possible, We Follow The Format and Convertions The Java Language Speci CATION (JLS) [GLS96].

2 Types

There Are Two New Forms of Types in GJ, Parameterized Types and Type Variables.

1

2.1 Type Syntax

A parameterized type consists in a class or interface type c and a parameter section

HT1;::::; TNI. c Must Be the name of a parameterized class or interface, The Types in the

Parameter List ht1;:::::::: TNI Must Match The Number of Declared Parameters of C, And

Each Actual Parameter Must Be a Subtype of The Formal Parameter's Bound Type.

In The Following, WHENEVER WE Speak of a class or interface type, we include the parameterized

Version As Well, UNSS Explicitly Excluded.

A Type Variable IS An Uquali Ed Identi Er. Type Variables Are Introducted by Parameterized

Class and interface declarations (Section 2.2) and by polymorphic method declarations

(Section 3.1).

Syntax (See JLS, SEC. 4)

Referencetype :: = ClassorInterfaceType

| ArrayType

| TYPEVARIABLE

Typevariable :: = Identifier

ClassorInterfaceType :: = ClassorInterface Typeargumentsopt

Classorinterface :: = Identifier

| ClassorInterfaceType. Identifier

TYPEARGUMENTS :: =

Referencetypelist :: = Referenceype

| Referencetypelist, Referencetype

EXAMPLE 1 Parameterized Types.

Vector

SEQ >

SEQ .zipper

Collection

PAIR

2

// Vector - Illegal, Primitive Types Cannot Be Parameters

// Pair - Illegal, Not Enough Parameters

// Pair - Illegal, Too Many Parameters

2.2 Parameterized Type Declarationsa Parameterized Class or Interface Declaration de Nes a set of types, one for Each Possible

Instantiation of the Type Parameter Section. All Parameterized Types Share The Same Class

Or Interface at runtime. for instance, the code

Vector x = new vector ();

Vector y = new vector ();

Return x.getClass () == y.getClass ();

Will Yield True.

SYNTAX (See JLS, SECS. 8.1, 9.1)

ClassDeclaration :: = ModifierSopt Class Identifier TypeParametersopt

Superopt Interfacesopt ClassBody

InterfaceDeclarative :: = ModifierSopt Interface Identifier

TypeParametersopt ExtendsinterfacesoPT

InterfaceBody

TypeParameters :: =

TypeParameterList :: = TypeParameterList, TypeParameter

| TypeParameter

TypeParameter :: = Typevariable TypeBoundopt

TypeBound :: = Extends ClassType

Implements InterfacePE

3

The Type Parameter Section Follows The Class Name and is Delimited by <> Brackets. IT

de Nes One or More Type Variables That Act As Parameters. Type Parameters Have AN

Optional class or interface type as a bound; if the bound is missing, java.lang.object

Is Assumed. The Scope of a Type Parameter Is All of the Declared Class, Except Any Static

MEMBERS or Initializers, But includeing the Type Parameter Section Itself. Therefore,

Type Parameters Can Appear As Parts of Their Own Bounds, or As Bounds of Other Type

Parameters declared in the same section.

Example 2 Mutually Recursive Type Variable Bounds.

Interface convertibleto {

A convert ();

}

Class Reprchange

B Implements ConvertibleTo > {

A a a;

Void set (b x) {a = x.convert ();} b get () {return a.convert ();

}

Parameterized Declarations Can Be Nested Inside Other Declarations.

Example 3 Nested Parameterized Class Declarations.

Class seq {

A head;

SEQ tail;

SEQ () {this (null, null);}

Boolean ISempty () {Return Tail == NULL;}

SEQ (a head, seq tail) {this.Head = head; this.tail = tail;}

Class Zipper {

SEQ > ZIP (SEQ That) {

IF (this.isempty () || That.isempty ())

Return New SEQ > ();

Else

Return New SEQ > (

New Pair (this.head, That.Head),

THIS. Tail.zip (That.tail);

}

}

}

Class client {{{{

SEQ strs =

4

New SEQ ("A", New SEQ ("B", New SEQ ())));

SEQ Nums =

New SEQ (New Integer (1),

New SEQ (New Double (1.5),

New seq ()));

SEQ .zipper zipper = strs.new zipper ();

SEQ > comBined = zipper.zip (nums);

}

2.3 Handling Conncutive Type Parameter Brackets

Connecutive Type Parameter Brackets do not need to be self whitespace.

THIS Leads to a problem in That The Lexical Analyzer Will Map The Two Consecutive

Closing Angle Brackets in a Type Such As Vector > To The Right-Shift Symbol

>>. Similarly, Three Consecutive Closing Angle Brackets Would Be Recognized As a Unary

Right-Shift Symbol >>>. To make up for this Irregularity, We Re ne the grammar for types

And Type Parameters as Follows.

Syntax (See JLS, SEC. 4)

Referencetype :: = ClassorInterfaceType | ArrayType

| TYPEVARIABLE

ClassorInterfaceType :: = Name

| Name

Referencetypelist1 :: = referencetype1

| RefresceTypelist, Referencetype1

Referencetype1 :: = Referencetype>

| Name

Referencetypelist2 :: = referencetype2

| Referencetypelist, ReferenceysPe2

Referencetype2 :: = Referencetype >>

| Name

5

Referencetypelist3 :: = referencetype3

| Referencetypelist, ReferenceysPe3

Referencetype3 :: = ReferenceType >>>

TypeParameters :: =

TypeParameterList1 :: = TypeParameter1

| TypeParameterList, TypeParameter1

TypeParameter1 :: = TypeParameter>

Typevariable Extends Referenceype2

Typevariable Implements Referencetype2

2.4 Subtypes, Supertypes, Member Types

In The Following, Assumeth A Class Declaration C with parameters a1; :::; an Which Have

Bounds S1; :::; Sn. That Class Declaration de Nes a set of types cht1; :::; tni, WHERE EACH

Argument Type Ti Ranges over Subtypes of the Corresponding Bound Type. That IS,

Each Ti Is A Subtype of

Si [A1: = T1; :::; an: = TN]

WHERE [A: = T] DENOTES SUBSTITION of the TYPE VARIABLE A with the TYPE T.

The de nitions of subtype and supertype are generalized to parameterized type. Given

a class or interface declaration for cha1; :::; ani, the direct supertypes of the parameterized

Type cha1; :::; ani area

The Type Given In The Extends Clause of The Class Declaration IF An Extends Clause

IS present, or java.lang.object Otherwise, and

The Set of Types Given In The Implements Clause of The Class Declaration if An Implements

Clause is present.

: A es; es es c c c;;;;;;;;;;;;

Is The Substitution [A1: = T1; :::; AN: = TN].

6

The SuperTypes of a Type Are Obtained by Transitive Closure Over the Direct Supertype

Relation. The Subtypes of a Type T Are All Types U Such That T IS A Supertype OF U.

Subtyping Does NOT Extend Through parameterized type: t a subtype of u does not imply

That Chti Is a Subtype of Chui. To support translation by Type EraSure, We Impose

The Restriction That A Class May Not Directly or Indirectly Implement An Interface TWICE

Such That The Two Implementations Have Dierent Parameters. Hence, Every SuperClass

And Implement Interface of A Parameterized Type Can Be Augment by Parameterization

TO EXACTLY One Supertype. Here is An Example of An Illegal Multiple Inheritance of

An interface:

Class B Implements I

Class C Extends B Implements I

A connectionquence of the parameterized type concept is this now the Type of a class member

IS NO LONGER XED, But Depends on The Concrete Arguments Substituted for The Class Parameters.

Here Are The Relevant de Nitions. Assume again a class or interface declaration

Of c with parameters a1; :::;

Let m be a member declaration in c, whose type as declared is THEN THE TYPE

Of m in the type cht1; :::; TNI IS T [A1: = T1; :::; an: = tn].

Let M Be a Member Declaration in A Supertype of Cht1; :::; TNI. Then the Type of

M in cht1; :::; TNI is the Type of M in That Supertype.

2.5 RAW TYPES

To Facilitate Interfacing with non-generic legacy code, it is also Possible To Use as a type

The EraSure of a parameterized class welh ing is called a rasingpepe. Variables of a raw type can be assigned from values ​​of any of the Type's parametric

Instances. for Instance, IT IS Possible To Assign A Vector To a Vector. The

Reverse Assignment from Vector To Vector Is Unsafe from The Standpoint of

The generic semantics (Since The Vector Might Have Had A Dierent Element Type), But IS

STILL Permitted in Order To Enable Interfacing with Legacy Code. in this case, Compilers

For Gj Will Issue A Warning Message That The Assignment IS DepRecated.

The superclasses (respectively, interfaces) of a raw type is the raw versions of the

Superclasses (Interfaces) of any of its parameterized instances.

The Type of a Member Declaration M in A Raw Type C Is ITS ERSED TYPE (See Section 6.1).

However, To Make Sure That Potential Violations of GJ's Typing Rules Are Always

Agged,

Some Accesses to Members of a Raw Type Will Result In / Unchecked "Warning Messages.

The rules for generating unchecked Warnings for Raw Types Are As Follows:

A Method Call to a Raw Type Generates An Unchecked Warning If The EraSure Changes

The Argument Types.

Seduce

A Eld Assignment To a Raw Type Generates An Unchecked Warning IF ERASURE CHANGES

The Eld Type.

No unchecked warning is required for a Method Call atly the result type changes,

For Reading from a Eld, or for a class instance creeion of a raw type.

The SuperType of a class May be a raw type. Member Accesses for the class area

As Normal, and Member Accesses for the supertype area. in the

Constructor of the class, calls to super service..

EXAMPLE 4 RAW TYPES.CLASS CELL

A value;

Cell (a v) {value = v;

A get () {return value;}

Void set (a v) {value = v;}

}

Cell x = new cell ("ABC");

X.Value; // ok, HAS TYPE OBJECT

x.get (); // ok, HAS TYPE Object

X.Put ("DEF"); // Deprecated

3 Polymorphic Methods

3.1 Method Declarations

Syntax (See JLS 8.4)

MethodHeader:

ModifierSopt TypeParametersopt Type MethodDeclarator throwsopt

| ModifierSopt TypeParametersopt Void Medeclarator throwsopt

Method Declarations Can Have A Type Parameter Section Like Classes Have. The Parameter

Section precedes the result type of the method.

EXAMPLE 5 POLYMORPHIC METHODS.

Static void swap (elem [] a, int i, int j) {

ELEM TEMP = a [i]; a [i] = a [j]; a [j] = TEMP;

}

8

Void > Sort (elem [] a) {

For (int i = 0; i

For (int J = 0; j

IF (a [j] .compareto (a [i]) <0) SWAP (A, I, J);

}

Class seq {

SEQ > zip (SEQ That) {

IF (this.isempty () || That.isempty ())

Return New SEQ > ();

Else

Return New SEQ > (

New Pair (this.head, That.Head),

This.Tail. zip (this.tail);

}

}

The de nition of / havning the same arguments "is extended to Polymorphic Methods as

Follows:

Two Method Declarations M and N Have the Same Arguments IF Either None of Them

Has Type Parameters and Their Argument Types Agree, or They Have The Same Number of

Type parameters, Say Ha1; :::: for m and hb1; :::; bni for n, and atter renaming each

.

IT Is Illegal To Declare Two Methods with The Same Name in A Class if these Methods Have

The Same Argument Types in Some Instantization of the Class.

3.2 Overriding

The de nition of overriding is adapted straightforwardly to parameterized types:

A class or interface cha1; :::; ani may contain a declaration for a method with the same

Name and the Same Argument Types as a Method Declaration in One of The Supertypes

Of cha1 ;:::; ani. in this case, the declaration in c is said to (directly) Override the

Declarative in the supertype.

GJ Requires That The Result Type of A Method Is A Subtype of The Result Types of All

Methods It Overrides. this is more general Than the Java Programming Language, Which

Requires the result Types to be identical. See section 6.2 for an importation scheme

TO Support this generalization.

9

Example 6 The Following Declarations Are Legal in GJ.

Class c imports cloneable {

C copy () {return (c) clone ();

...

}

Class D Extends C Implements Cloneable {

D coupy () {return (d) clone ();

...

}

4 Exceptions

To Enable a Direct Mapping Into The JVM, TYPE Parameters Are Not ALOWED in Catch

Clauses or throws Lists. It is still Possible to have more parameterized extensions of throwable

But One Uses The Raw Class Name of Such An Extension In a catch clause or throws list.

The name of a parameterized class in a throws list indeicates one any of its instances

Might Be Thrown. Analog (The Name of a parameterized class in a catch clause Will

Cover Any Parameterized Instance of the Class.

EXAMPLE 7 parameterized exceptions.

Class Excparam Extends Exception {a value;

ExcParam (a value) {this.value = value;

}

Class Excinteger Extends ExcParam {

EXCINTEGER (INT I) {Super (New Integer (i));}

INT INTVALUE () {Return Value.intValue ();

}

Class test {

Void throwexc (INT i) throws ExcParam, Excinteger {

Throw i == 0? New ExcParam ("Zero"): New Excinteger (i);

}

INT TryEXC (INT i) {

Try {

Throwexc (i)

} catch (excinteger em) {

Return ex1.intValue ();

} catch (eXCPARAM EX2) {

10

Return 0;

}

}

}

5 Expressions

5.1 Class Instance Creation Expressions

A class instance creation expression for a parameterized class consists of the full parameterized

Type of the instance to be create and arguments to a constructor for what

TYPE.

Syntax (See JLS, SEC. 15.8)

ClassInstanceCreationExpression :: = new name type typeargumentsopt (argumentlistopt)

)

Example 8 Class Instance Creation Expresss.

// with explicit type parameters

New vector ();

New Pair , SEQ > (

New SEQ (New Integer (0), New SEQ ()),

New SEQ ("ABC", New SEQ ()));

5.2 Array CREATION Expressions

The element type in an array code expression is a fully parameterized type. It is IS

Deprecated to create.............

SYNTAX (See JLS, Sec. 15.9)

ArrayCreationExpression :: = New PrimitiveType DIMEXPRS DIMSOPT

| New ClassorInterfaceType DIMEXPRS DIMSOPT

| New Primitidype DIMS ArrayInitializer

| New ClassorInterfaceType DIMS ArrayInitializer

EXAMPLE 9 Array Creation Expresss.

New Vector [N]

New Seq [10] [20] []

11

5.3 Cast ExpressionSthe Target Type for a cast can be becomterized type.

SYNTAX (See JLS, Sec. 15.15)

Castexpression :: = (PrimitiveType Dimsopt) UnaryExpression

| (Referencetype) UnaryExpressionNotPlusminus

The Usual Rules for Casting Conversions (SPEC, SEC. 5.5) Apply. Since Type Parameters Are

NOT MAINTAINED AT RUN-TIME, We Have to Require That The Correctness of Type Parameters

Given in the target type of a cast can be assertained staticly. this is enforced by

Re Ning The Casting Conversion Rules As Follows:

A Value of Type S Can Be Cast to a parameterized type tiff one of the following two

Conditions Holds:

T IS a Subtype of S, and there no other subtypes of s with the same erasure

(See Section 6.1) AS T.

T is a superType of S.

Note That Even Parameterized Subtypes of a Given Type Are Not Unique, IT WILL

Always Be Possible To Cast to the Raw Type Given by Their CommMon EraSure.

Example 10 Assume The Declarations

Class Dictionary EXTENDS Object {...}

Class Hashtable Extends Dictionary {...}

Dictionary d;

Object O;

THE FOLLOWING ARE LEGAL:

(Hashtable ) D // Legal, Has Type: Hashtable

(Hashtable) o // legal, HAS TYPE: HASHTABLE

But The Following Are NOT:

(Hashtable ) D // Illegal, Not a Subtype

(Hashtable ) O // ILLEGAL, NOT UNIQUE SUBTYPE

12

5.4 Type Comparison Operator

Type Comparison Can Involve Parameterized Types. The Rules of Casting Conversions, AS

De Ned In Section 5.3, Apply.

SYNTAX (See JLS, Sec. 15.19)

RelationALEXPIPRESSION

:: = ...

| RelationALEXPRESSION InstanceOf Type

Example 11 Type Comparisons.

Class SEQ Implements List {Static Boolean ISSEQ (List X) {

Return X InstanceOf SEQ

}

Static Boolean ISSEQ (Object X) {

Return X InstanceOf SEQ

}

Static Boolean ISseqarray (Object X) {

Return X InstanceOf SEQ []

}

}

Example 12 Type Comparisons and Type Casts with Type Construction.

Class Pair {

A fst; b SND;

Public Boolean Equals (Object Other) {

Return

Other InstanceOf Pair &&

Equals (FST, ((Pair) Other) .fst) &&

Equals (SND, ((Pair) Other); SND);

}

Private Boolean Equals (Object X, Object Y) {

Return x == null && y == null || x! = null && x.equals (y);

}

}

13

5.5 Polymorphic Method Invocation

Polymorphic Method Invocations Do Not Have Special Syntax. Type Parameters of Polymorphic

Methods are elided; They is inferred from value parameters aciding to the

Rules Given In Section 5.6.

SYNTAX (See JLS 15.11)

MethodInvocation :: = MethodeExpr (argumentlistopt)

MethodeXpr :: = methodname

| Primary. Identifier

| super. Identifier

Example 13 Polymorphic Method Calls with Implicit Type Parameters (See EXAMPLE 5)

SWAP (INTS, 1, 3) SWAP (INTS, 1, 3)

Sort (strings) Sort (strings)

Strings.zip (INTS) Strings. Zip (INTS)

Optional Extension. If Desired, One Can Also Admit Explicit Parameterization for

Methods. In That Case, The Parameter Section of a Polymorphic Method Invocation

Would IMMEDIATELY Precede The Method Name.

SYNTAX (See JLS 15.11)

MethodInvocation :: = MethodeExpr (argumentlistopt)

Methodexpr :: = MethodID

| Primary. Methodid

Super. MethodID

Methodid :: = Typeargumentsopt MethodName

Example 14 Polymorphic Method Calls with explicit Type Parameters (See Example 5) SWAP (INTS, 1, 3)

Sort (Strings)

Strings. Zip (INTS)

The conveention of passing parameters before the method name is Made Necessary By

PARSING CONSTRAINTS: with the more conventional / type parameters after method name

Convention the expression f (a (d)) Would Have Two Possible Parses. The alternative

Of using [] Brackets for Types Poses Other Problems.

5.6 Type Parameter Inference

Type Parameters of a Call to a Polymorphic Method Are InferRed from The Call's Value

Parameters. To make Inference Work, We make use of a bottom type null, Which IS

14

A Subtype of Every Reference Type. This Type Already Exists in the java programming

Language as the Type of Null. We Postulate That The Subtyping Relationship Between

Null and Reference Types Is Proted Through Constructionors: if Ti T And U Are Identical

Types Excepter That Where T Has Occurrences of Null U Has Occurrences of Other Reference

Types, THEN T IS A SUBTYPE OF U.

Type Parameter Inference Inserts the Most Speci C Parameter Types Such That

1. Each Actual Argument Type Is A Subtype of The Corresponding Formal Argument

TYPE,

2. No Type Variable That Occurs More Than On The Method's Result Type Is Instantiated

TO a Type Containing NULL.

IT is an error if Most Speci C Parameter Types Do Not Exist or Are Not Unique.

EXAMPLE 15 TYPE Parameter Inference.

Assume the Polymorphic Method Declarations:

STATIC SEQ NIL () {Return New SEQ ();

STATIC SEQ CONS (A x, SEQ XS) {RETURN New SEQ (X, XS);}

THE FOLLOWING Are Legal Expressions:

CONS ("abc", nil ()) // of type: SEQ cons (New IOException (), cons (New error (), nil ()))))

// of type: SEQ

NIL (); // of type: seq

Cons (null, nil ()); // of type: SEQ

The Second Restriction Above Needs Some Explanation. Note That A Covariance Rule Applies

To Types Containing Null. for Any Type Context TC, TYPE U, TC [Null] IS A Subtype OF

TC [U]. General Covariance Leads to unsound type systems, sowe to argue Carefult

That Our Type System With ITS Restricted Form of Covariance is Still Sound. The Soundness

Argument Goes as Follows: Since One Cannot Declare Variables of Type Tchnulli, All One

Can do with a value of this type is assign or pass it is there is a variable or parameter of

Some Other Type. There Are Now Three Possibilities, Depending on The Variable's Type:

THE VARIABLE'S TYPE IS An Unparameterized Supertype of The Raw Type Tc. In this

Case the assignment is clearly legal.

The variable's type is tc0hti for some type t and supertype tc0 of tc. Now,

The only value of null is null, Which is Also a value of every reference type t.

Hence, Any Value of Type Tchnulli Will Also Be a Value of Type Tc0hti, So the

Assignment is Sound.

15

The variable is a parameter p whose type is a type variable, a. The code thing

Accesses P in The Method Body Is Innsitive To The Type of The Actual Parameter, SO

The Method Body Itself Cannot Give Rise To Type Errors. Furthermore, by Restriction

(2.) Above, The Method's Formal Result Type Will Contain At Most ONE OCCURENCE OF

A, So the actual type of the method Application is again of the form tc0hnulli,

WHERE TC0 is a type context.

WITHOUT RESTRICTION (2.) Type Soundness Would Be Compromised, As Is Shown by Thefollowing Example.

EXAMPLE 16 An Unsafe Situation for Type Parameter Inference.

PAIR duplicate (a x) {return new pair (x, x);}

Void Crackit (Pair , SEQ > P) {

P.fst.head: = "Hello";

Integer i = p.snd.head;

}

CRACKIT (CONS (CONS (NULL, NIL ()))))))))))))))))))))))))))))))

THIS WILL EECTIVELY ASSIGN A STRING TO ANTEGER. The questionm is what the duplicate

Method Returns The Same Value Under Two Type Parameters Which Then Get Matched

Against Dierent Types. I.E.

Duplicate (CONS (NULL, NIL ()))))

HAS Type

Pair , SEQ >

But The Two Seq Parameters Really Stand for the Same Object, Hence It Is Unsound

To widen these Types to Dierent Seq Types. The GJ Compiler Will Report An Error for

THE CALL

CRACKIT (CONS (NULL, NIL ())))))

The Error Message Will State That An Uninstantiated Type Parameter APPEARES SEVERAL

Times in the result type of a method.

16

6 Translation

In The Following We Explain How Gj Programs Are Translated To JVM Bytecodes. In A

Nutshell, The Translation Proceeds By Erasing All Type Parameters, Mapping Type Variables

To Their Bounds, and INSERTING CASTS AS NEEDED. Some Subtleties of The Translation Are

Caused by the handling of overriding.

6.1 Translation of Types

As Part of Its Translation Process, A GJ Compiler Will Map Every Parameterized Type To

ITS Type EraSure. Type EraSure Is A Mapping from Gj Types To ConvertIal (Unparameterized)

Types. We write jtj for the EraSure of Type T. The EraSure Mapping IS DE DED

As Follows.

The EraSure of a parameterized type cht1; :::; TNI is C.

The EraSure of a Nested Type T: C Is Jtj: C.The EraSure of an Array Type T [] is jtj [].

The EraSure of a Type Variable is The EraSure of The Type Variable's Bound.

The EraSure of Every Other Type is The Type Itself.

6.2 Translation of Methods

Each Method T M (T1; :::; TN) IS Translated to a Method with the Same Name Whose Return

Type and Argument Types Are The EraSures of The Corresponding Types in The Original

Method. in Adduration, IF a Method Declaration Tm (T1; :::::) IS inherited (and POSSIBLY)

Overridden) in an extension where a type parameter of the class or interface is instantiated,

Such That The Method Now Has A Dierent Type EraSure, a Bridge Method Will B

Generated. The Type of the bridge method is the Type EraSure of the method in the base

Class or Interface. in the bridge method's body all arguments to the method Will be Cast

To Their Type Erasures in The Extending Class, After Which The Call Will Bewarded To

The Original Method OR An Overriding Instance.

EXAMPLE 17 Bridge Methods.

Class C {Abstract A ID (A x);

Class D Extends C {String ID (String X) {Return X;}}

This Will Be Translated TO:

In one

Class C {Abstract Object ID (Object X);

Class D Extends C {

String ID (string x) {returnix}

Object ID (Object X) {RETURN ID (String);

}

Note That The Translation Scheme CAN Produce Methods with Identical Names and Argument

Types, Yet with Dierent Result Types, All Declared In The Same Class. Here's AN

EXAMPLE:

EXAMPLE 18 Bridge Methods with The Same Parameters as Normal Methods.

Class c {Abstract a next ();

Class D Extends C {String Next () {Return "";}}

This Will Be Translated TO:

Class C {Abstract Object next ();

Class D Extends C {String Next / * 1 * / () {Return "";

Object next / * 2 * / () {return next / * 1 * / ();

}

A Java Compiler Would Reject That Program Because of the Double Declaration of Next.

But the bytecode representation of the program is legal, since the bytecode always

Refers to a method via its the full signature and therefore can distinguish betWeen THE

TWO Occurrences of Next. Since We Cannot Make The Same DistInction in The Java Source,

We Resorted to indices in / * ... * / comments to make clear which method a name refers

TO.

The Same Technique IS Used To Implement Method Overriding with Covariant Return

Types1.

Example 19 Overriding with Covariant Return Types.

Class C {C DUP () {...}}

Class D Extends C {D DUP () {...}

This Translates TO:

Class C {C DUP ();

Class D {

D dup / * 1 * / () {...}

C DUP / * 2 * / () {Return DUP / * 1 * / ();

}

1COVARIANT RETURN TYPES WERE AT Some Time Before Version 1.0 Part of The Java Programming Language

But got removed later

18

Sinceade Our Translation of Methods Erases Types, IT IS Possible That Dierent Methods with

Identical Names But Dierent Types Are Mapped to Methods with The Same Type EraSure.

Such a Case, IF IT Arises, IS Considered to Be An Error In The Original GJ Program. There

Are Three Rules to Prevent Signature Clashs Caused by The Translation. Say a Method

Declaration M Indirectly Overrides a Method Declaration M0 IF The IS A (Possibly Empty)

Path of Method Declarations

M = m0; m1; :::; mn = m0

Such That Mi Overrides Mi 1. The One Must Have:

Rule 1 Methods Decland in The Same Class with The Same Name Must Have Dierent

ERASURES.

Rule 2 IF a Method Declaration M in Class C Has The Same Name and Type EraSure AS

A Method Declaration M0 in A Superclass D of C THEN M IN C Must Indirectly Overridem0 in D.

Rule 3 IF a Method Declaration M in A Superclass D of C Has The Same Name and TYPE

ERASURE AS A Method Declaration M0 in An Interface I Implement by C THEN THERE MUST

Be a Method Declaration M00 in C or One of Its Superclasses That Indirectly Overrides M

IN D and Implements M0 IN I.

EXAMPLE 20 Name Clash Excluded by Rule 2.

Class C {A ID (A x) {...}}

Class D Extends C {

Object ID (Object X) {...}

}

This Is Illegal Since C.ID and D.ID Have The Same Type EraSure, YET D.ID DOES NOT OVERRIDE

C.ID. hence, rule 2 is violated.

EXAMPLE 21 Name Clash Excluded by Rule 3.

Class C {A ID (A x) {...}}

Interface I {A ID (a x);}

Class D Extends C Implements I {

String ID (string x) {...}

Integer ID (Integer X) {...}

}

This Is Also Illegal, Since C.ID and I.ID Have The Same Type EraSure Yet There IS NO

Single Method in D That Indirectly Overrides C.ID and Implements I.ID. Hence, Rule 3

Is violated.

19

6.3 Translation Of Expressions

Expressions Are Translated Unchanged Excepter That Casts Are Inserted Where Necessary.

There Are Two Situations Where A Cast Needs to be inserted.

1. Field Access Where The Eld's Type is a type parameter. EXAMPLE:

Class Cell {a value; a getValue ();

...

String f (Cell Cell) {

Return Cell.Value;

}

Since the Type EraSure of Cell.Value is java.lang.object, yet f returns a string, the

Return Statement Needs to Be Translated To

Return (String) Cell.Value;

2. Method Invocation, WHERE The Method's Return Type Is A Type Parameter. For instance,

In The Context of the Above Example The Statementstring X = Cell.getValue ();

Needs to be translated to:

String x = (string) Cell.getValue ();

7 THE SIGNATURE CLASLATTRIBUTE

Class Les Need to Carry Gj's Additional Type Information in a Backwards Compatible Way.

This is acid ,,,,,,,

And Elds. The structure of this attribute is as follows:

"SIGNATURE" (U4 attr-length, u2 signature-index)

When use as an attribute of a method or eld, A Signature Gives the full gj type of

That Method or Eld. When Used As a class attribute, A Signature INDICES The TYPE

Parameters of The Class, Followed by ITS Supertype, Followed by All ITS Interfaces.

The Type Syntax In Signatures IS Extended to Parameterized Types and Type Variables.

There Is Also a New Signature Syntax for Formal Type Parameters. The Syntax Extensions

For Signature Strings Are As Follows:

Syntax

20

MethodorfieldSignature :: = TypeSignature

ClassSignature :: = ParameterPartopt

Super_typessital interface_typessatures

TypeSignatures :: = TypeSignatures TypeSignature

|

TypeSignature :: = ...

ClasStypeSignature

|METHODTYPESIGNATURE

| TypevariableSignature

ClassTypeSignature :: = 'L' Ident Typeargumentsopt ';'

ClassTypeSignature '.' Ident ';' Typeargumentsopt

MethodTypeSignature :: = Typearguments '(' typeesignatures ')' TypeSignature

TYPEVARIABLESIGNATURE :: = 'T' Ident ';'

Typearguments :: = '<' TypeSignature TypeSignatures '>'

ParameterPart :: = '<' parametersignature parametersignatures '>'

Parametersignatures :: = Parametersignatures Parametersignature |

Parametersignature :: = Ident ':' Bound_TypeSignature

twenty one

References

[Bosw98] Gilad Bracha, Martin Odersky, David Stoutamire, And Philip Wadler. Making

The Future Safe for the Past: Adding Genericity to the Java Programming

Submiited to Oopsla98, 1998.

[GLS96] James Gosling, Bill Joy, And Guy Steler. The Java Language Speci CATION. Java

SERIES, Sun Microsystems, ISBN 0-201-63451-1, 1996.

twenty two


New Post(0)