Tuesday, March 20, 2007

Meta programming and static typing

There is a new episode at software engineering radio called 'dynamic languages for static minds'. The discussion about AOP being the Meta Programming Protocol for static languages got me to some ideas about a possible convenient concrete syntax for "my imaginary language".

There are two different things I want to do:
1) Changing the implementation of Methods at runtime
2) Adding new Methods at runtime, where no static signature exists

The first one is straight forward:
Changing the class globally, could be described like this:
String bla = "Bla";
Person.class.addDefinition("toString", {
// a block using the current context
return bla+super.toString();
});
)
So this would overwrite the 'toString' method for all instances of Person.
Of course we, would need something like ruby blocks (statically typed of course).
Changing the implementation of a class globally might be helpful, but sometimes we want to overwrite the behavior for one instance only :
String bla = "Bla";
Person p = new Person();
Person.class.addDefinition("toString", {
// can use the context
return bla+super.toString();
});
);
In Java we can do something like this with anonymous classes, but this is restricted to object creation time and the use of constructors. With the syntax from above we could change the behaviour of every (managed) object at any time.

Looks like AOP at runtime, maybe a pointcut syntax would be cool, too:
String bla = "Bla";
Person p = new Person();
Person.class.addDefinition("*", {
print(...);
return proceed();
});
);
Dynamically adding new Methods, where no static signature exists, can be done with the same API. To provide a compact and readable syntax for incovation of statically unknown features we need a special invocation operator (two dots '..') escaping the static type checker:

String bla = "Bla";
Person p = new Person();
p.class.addDefinition("notStatic", |String x|{
return ....;
});
);
// invoke the new method
p..notStatic("holla"); // note the two dots
I've written something about this syntax in a previous post.
I'm wondering if there are already languages implementing similar ideas?