Progress: Reflection

Tuesday, October 13, 2009
A small sample of some working code that uses reflection:

def testFindMethod() {
  let m = Module.thisModule();
  let f1 = m.findMethod("sample");
  Debug.assertTrue(f1 isa Method);
  let f2 = m.findMethod("ample");
  Debug.assertFalse(f2 isa Method);

def sample() {}

What this code does is to get a reference to the current module, and look up a method named 'sample'. Note that the reason for the funny 'isa' tests is because I haven't completely worked out the issues surrounding NULL pointers yet.

I also plan to support getting the module pointer for a type via "Module.of(typename)", however that isn't done yet. For one thing, the compiler does not yet support passing a type name as a function argument. My eventual plan is to implicitly convert type names into instances of TypeLiteral[typename] whenever they are used as values. In other words, types are not objects -- but you can use them like objects in most cases.

The next step is to be able to call a method via reflection. In order to do this, however, I will need to work on boxing of primitive types, since the "invoke" method takes an array of Object[]. I've started working on this already. At this point, the "Boxed" class is pretty simple:

/** A reference type used to contain a value type. */
class Boxed[%T] {
  let value:T;
  def construct(value:T) {
    self.value = value;

So for example, you can create a Boxed integer via "Boxed(3)". However, it will be more convenient once I support "auto-boxing", which is the ability to implicitly convert a value type into a boxed type as needed. So for example, if I have a method that takes an argument of type "Object", and I pass it an integer, it will automatically wrap it in a Boxed[int].

The issue I need to resolve is whether auto-boxing should be a special feature of the Boxed type. The alternative is to implement user-definable implicit conversion operators as in C++, so that any class can potentially define a silent conversion from one type to another. While this is a powerful and useful feature, it it also one that is easily abused.


Post a Comment