Skip to main content

Add support for reified parameter types

No replies
forax
Offline
Joined: 2004-10-07
Points: 0

Wells, the last two years, i have seen a lot of post
pro or against the way tiger implements Generics.

First, i want thanks the JSR14 experts because they
made a great jobs. Now, i could write a code in 5.0
that contains a lot of parametrized types and
that interacts with apis that are compliants with
older java versions (1.2 to 1.4 for me).

Yes, i have some unsafe warnings but in my current project
i have 13 unsafe warnings/conversions for more than
8 000 lines of codes.

But now it's time to go a step further : i want to choose
for a peculiar problem, if i need non reifiable or reifiable parametrized type in the same way i choose
a static or non static method.

So, i propose to add support to reified parameter types to
Mustang not in replacement by in addition to current
type system.

Let me provide an example, i want a linked list
that known the type of it's element to implement
a correct toArray() but i don't want to spend
a reference to hold the reified type in all entries.

@Reifiable class MyLinkedList {
private int size;
private Entry first;

void add(E e) {
first=new Entry(e,first);
}

E[] toArray() {
E[] array=new E[size];
// ok because here E is reifiable
int i=0;
for(E cur=first;cur!=null;cur=cur.next)
array[i++]=cur.value;
return array;
}

@Reifiable(false) static class Entry {
E value;
Entry next;
}
}

And javac could generate for me a code like this :

@Reifiable class MyLinkedList {
private int size;
private Entry first;
private final Class $E$class; // aha

// argument type injection
public MyLinkedList(Class $E$class) {
this.$E$class=$E$class;
}

void add(Object e) {
// assign a reifiable type to a not one, ok
first=new Entry(e,first);
}

Object[] toArray() {
//E[] array=new E[size];
Object[] array=Arrays.newInstance($E$class,size);

int i=0;
for(Object cur=first;cur!=null;cur=cur.next)
//array[i++]=cur.value;
Arrays.set(array,i++,cur.value);
// there is a little optimisation
// because cur.value is not a reifiable type
// the compiler should insert a Class.cast
// Arrays.set(array,i++,$E$class.cast(cur.value))
// but because arrays perform this test too.
return array;
}

@Reifiable(false) static class Entry {
// introduce nothing
Object value;
Entry next;
}
}

And now in the main :

public static void main(String[] args) {
MyLinkedList l=new MyLinkedList();
for(String s:args) {
l.add(s); // add a reified type
}
List l2=Arrays.asList(args);
l.add(l2.get(0)); // add a not reified type
}

is compiled like this :

public static void main(String[] args) {
MyLinkedList l=new MyLinkedList(String.class);
for(String s:args) {
l.add(s); // ok
}
List l2=Arrays.asList(args);
l.add((String)l2.get(0)); // must insert a cast
}

What do you think about that ?

Rémi Forax