RFC: Function and delegate upper bounds

Argentum functions and delegates are value types, not references. This makes it impossible to create classes parameterized with function and delegate prototypes and this in turn makes it impossible to create containers of functions and delegates and multicast delegates/multiple subscriptions.

Proposal:

  • add two special types fn and delegate
  • fn is a super-type for all functions: any function can cast to fn
  • delegate is a super-type for all delegates
  • these types can be stored/copied/disposed/compared to
  • these types cannot be called (because the actual prototype is unknown)
  • these types cannot cast to anything (because functions and delegates have no runtime type info for safe casts)
  • these two base types are suitable to be base types for class/interface parameters.

Example of class parameterized by fn type: array of arbitrary functions:

class FnArray(F fn) {  // FnArray is FFI class, F is a function type parameter
   …
   size() int;        // C99 FFI implementations
   getAt(i int) F;    //
   setAt(i int, f F); //
   add(f F);          //

   each(visitor(F)) {  // argentum implementation
      forRange(0, size()) \visitor(getAt(_))
   }
}

// two functions having int->void types
fn f1(i int) {...}
fn f2(i int) {...}

// crate FnArray instance parameterized with int->void prototype
// type fn(int) already exists in Argentum
myFns = FnArray(fn(int))
    .add(f1).add(f2);    // and fill it with f1 and f2

// call all fns in array with int parameter
myFns.each`f f(42)

And the same for delegates

class DlArray(D delegate) {
  // same set of FFI methods
  each(visitor(D)) {
    forRange(0, size())`i visitor(getAt(i))
  }
}

// Create delegate-array and fill it with some inline and method delegates
// Type &(int) already exists
myDl = DlArray(&(int))
   .add(app.&d1(i int){...})
   .add(listener.f2);

// Call all delegates in array
mtFns.each\_(42)

Implementation of this proposal is trivial:

  • extend type system with 2 types
  • implement basic fn/delegate map/array types in ag-runtime lib

Leave a Reply

Your email address will not be published. Required fields are marked *