COMMUNITY

[macro] How to create macro expression of a parameterized type?

This thing doesn’t work:

var expr: haxe.macro.Expr = macro Array<Int>; //error: Expected expression

How make it work?

You can’t create a “type expression” (class reference) with type parameters, neither via normal syntax, neither with a macro. What do you want to achieve?

I have a method:

static function addGetter(fieldName: String, fieldType: ComplexType, fields: Array<Field>)
{
	fieldName = capitalizeFirstLetter(fieldName);
	var getterName = 'get${fieldName}';
	fields.push(
	(
		macro interface I 
		{
			function $getterName(): $fieldType;
		}
	).fields[0]
	);
}

I need create ComplexType var for Array<SomeData> type to pass in the function parameter “fieldType”.

I found a workaround as:

static function addGetter(fieldName: String, fieldType: ComplexType, fields: Array<Field>, 
		isList: Bool = false)
	{
		fieldName = capitalizeFirstLetter(fieldName);
		var getterName = 'get${fieldName}';
		if (!isList)
		{
			fields.push(
				(
					macro interface I 
					{
						function $getterName(): $fieldType;
					}
				).fields[0]
			);
		}
		else 
		{
			fields.push(
				(
					macro interface I 
					{
						function $getterName(): Array<$fieldType>;
					}
				).fields[0]
			);
		}
	}

Ah, then you are just missing the :, see https://haxe.org/manual/macro-reification-type.html

I’ll take a look it. Thank you :slight_smile:

Returning to the subject of macro:, it’s look like it’s impossible to use constuction like this:

switch (cType)
{
	case TPath({name: name, pack: [pack]}):
	{		
       var expr = $v{'$pack.subPack.$name'};
       var complexType = macro: Array<expr>;
          ...
    }
...
}

It is not, because expression reification creates Expr, where as type parameters expect ComplexType so you can’t mix them up. Something like this would work:

var elemType = TPath({pack: [pack, subPack], name: name});
var arrayType = macro : Array<$elemType>;

It’s clear. Thanks again:)