Macro: How to count the number of callback function parameters?

I need to check the number of parameters for callback functions, and doing it when using an inline arrow function works fine. Try Haxe !

However, I don’t know how to do the same thing when passing a standard function reference.
Can anyone help me in this…?

function main() {
	// inline arrow function example
	final length = getNumParams((i:Int, s:String) -> trace(i));
	trace('Arrow function parameters length: ' + length); // works!

	// standard function reference example
	final length = getNumParams(exampleCallback);
	trace('Standard function parameters length: ' + length); // How to..?
}

function exampleCallback(i:Int, s:String)
	trace(i);

macro function getNumParams(fnExpr:haxe.macro.Expr) {
	switch fnExpr.expr {
		// Count the number of parameters in an inline arrow function:
		case EFunction(x, a):
			return macro $v{a.args.length}; // works!

		// Count the number of parameters in a function reference:
		case EConst(x):			
			// How to...?
		default:
	}

	return macro null;
}

You could type the expression (you might want to add some error handling):

haxe.macro.Context.typeof(fnExpr)

Which gives you the information you’re after (and more):

TFun([{name: i, t: TAbstract(Int,[]), opt: false},{name: s, t: TInst(String,[]), opt: false}],TAbstract(Void,[]))

Thanks, Rudy! I’ll give it a try!

Seems to work just as expected: Try Haxe !