Is it possible to use conditional compilation with a Macro?

Hello,

I was about to write my very first haxe macro but I need the returned expression to be platform-specific, is there any way to do that ? Maybe differently ?

Here is the code, I also tried to have one “count_args” function per platform but it doesn’t seem to work either (compiler says the function doesn’t exist)

class ArgumentsCount 
{

	macro public static function count_args(func:Expr)
	{
		#if flash
		return macro untyped $func.length;
		#elseif neko
		return macro untyped ($nargs)($func);
		#elseif cpp
		return macro untyped $func.__ArgCount();
		#elseif html5
		return macro untyped $func.length;
		#end
		//return macro untyped $func.length;
		return macro 123;
	}
	
}

edit : just realized I could simply make a static function and inline it :stuck_out_tongue: but my question still stands, I’m curious :slight_smile:

Context.defined() might work.

if (Context.defined("flash")) {

} else if (Context.defined("neko")) {

}
2 Likes

Nice ! It works, except for Neko where the macro thing doesn’t like $nargs (the $ is for Neko here, contrary to $func)

Here is the class with both static and macro functions

class ArgumentsCount 
{
	
	//inline public static function count_args(func:Function):Int
	//{
		//#if flash
		//return untyped func.length;
		//#elseif neko
		//return untyped ($nargs)(func);
		//#elseif cpp
		//return untyped func.__ArgCount();
		//#elseif html5
		//return untyped func.length;
		//#else
		//throw new Error("ArgumentsCount.count_args ::: unsupported platform");
		//#end
	//}

	macro public static function count_args(func:Expr)
	{
		if (Context.defined("flash"))
		{
			return macro untyped $func.length;
		}
		else if (Context.defined("neko"))
		{
			return macro untyped ($nargs)($func);
		}
		else if (Context.defined("cpp"))
		{
			return macro untyped $func.__ArgCount();
		}
		else if (Context.defined("html5"))
		{
			return macro untyped $func.length;
		}
		return macro 123;
	}
	
}

The $ character triggers expression reification in macros. I think you need to use expression reification to work around the expression reification (whoa…).

Maybe something like this?

var f = "$nargs";
return macro $i{f}($func);

my head ! :grin:
It makes sense, but compiler complains about “unknown identifer” with f’s content… no biggie though, I’m currently happy with the static inlined version.
I’ll read the macro docs again, they might make more sense to me now :slight_smile: