Skip to content

Add support for generic methods - #372

Open
thekid wants to merge 8 commits into
xp-framework:mainfrom
thekid:feature/generic-methods
Open

Add support for generic methods#372
thekid wants to merge 8 commits into
xp-framework:mainfrom
thekid:feature/generic-methods

Conversation

@thekid

@thekid thekid commented Aug 8, 2026

Copy link
Copy Markdown
Member

This pull request adds the possibility to define methods with their own generic type arguments. Implemented via inserting typeargs as first parameter and __call().

Example

Declaration:

use lang\Generic;

#[Generic(self: 'T')]
class ListOf {
  public private(set) $elements= [];

  #[Generic(params: 'T...')]
  public function __construct(... $args) {
    $this->elements= $args;
  }

  #[Generic(self: 'M', params: 'function(T): M', return: 'self<M>')]
  public function map($map) {
    $m= create("new self<$M>");
    foreach ($this->elements as $element) {
      $m->elements[]= $map($element);
    }
    return $m;
  }
}

Calls:

$list= create('new ListOf<string>', 'Hello', 'World!');

// Returns a ListOf<int>
$lengths= $list->{'map<int>'}(strlen(...));

// Contains [5, 6]
$lengths->elements;

Implementation status

  • Proof of concept
  • Argument verification
  • Reflection

See also

@thekid

thekid commented Aug 8, 2026

Copy link
Copy Markdown
Member Author

Reflection

For C#, we need to use MakeGenericMethod:

using System;
using System.Reflection;

public class Sample
{
    public void GenericMethod<T>()
    {
      Console.WriteLine($"GenericMethod<{typeof(T).Name}> invoked");
    }
}

class Program
{
    static void Main()
    {
        var instance = new Sample();
        Type runtimeType = typeof(string);
        
        // 1. Get MethodInfo for the generic method definition
        MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
        
        // 2. Construct the generic method with the runtime type
        MethodInfo constructed = method.MakeGenericMethod(runtimeType);
        
        // 3. Invoke it on the instance
        constructed.Invoke(instance, null);
    }
}

See https://stackoverflow.com/questions/232535/how-do-i-call-a-generic-method-using-a-type-variable

thekid added 3 commits August 8, 2026 18:40
* 1 => `T_CLASS_C`
* 2 => `T_METHOD_C`
* 3 => `T_CALLABLE`
* 4 => `T_FUNCTION`
* 5 => `T_IMPLEMENTS`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant