Skip to content

Instantly share code, notes, and snippets.

@haxiomic
Last active May 8, 2021 18:48
Show Gist options
  • Save haxiomic/06c1007495f853129c384a39c99bfa28 to your computer and use it in GitHub Desktop.
Save haxiomic/06c1007495f853129c384a39c99bfa28 to your computer and use it in GitHub Desktop.
Return a value for an expression passed into a macro, even if that expression references other variables (so long as those variables are declared with inline). Originally from this thread https://community.haxe.org/t/macro-constant-arg-inline-final/3007
/**
Return a value for an expression passed into a macro, even if that expression references other variables (so long as those variables are declared with inline)
**/
function evalConstExpr(x: Expr) {
return try {
ExprTools.getValue(Context.getTypedExpr(Context.typeExpr(x)));
} catch (e) {
Context.error("Must be a constant expression (i.e. and expression containing only constants or variables declared with `inline`", x.pos);
}
}
@haxiomic
Copy link
Author

haxiomic commented May 8, 2021

Example

#if macro
import haxe.io.Path;
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.ExprTools;
import sys.FileSystem;
import sys.io.File;
#end

macro function embedDirectory(pathExpr: ExprOf<String>) {
	function evalConstExpr(x: Expr) {
		return try {
			ExprTools.getValue(Context.getTypedExpr(Context.typeExpr(x)));
		} catch (e) {
			Context.error("Must be a constant expression (i.e. and expression containing only constants or variables declared with `inline`", x.pos);
		}
	}

	var path = evalConstExpr(pathExpr);

	for (name in FileSystem.readDirectory(path)) {
		var filePath = Path.join([path, name]);
		var bytes = File.getBytes(filePath);
		Context.addResource(filePath, bytes);
	}
	return macro null;
}
inline final iconDirectory = 'Icons';
...
Assets.embedDirectory(iconDirectory);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment