macro-type-decoder

A collection of helper functions and utilities for working with Haxe types and macros. This library simplifies decoding types, generating code, and handling macro-related tasks.
https://gitlab.com/dani_987/haxe-macro-type-decoder

To install, run:

haxelib install macro-type-decoder 1.1.0 

See using Haxelib in Haxelib documentation for more information.

README.md

Haxe Macro Type Decoder

A collection of helper functions and utilities for working with Haxe types and macros. This library simplifies decoding types, generating code, and handling macro-related tasks.

Features

  • Decode Haxe types to structured data for macro processing.
  • Generate unique names for identifiers in macros.
  • Create constant-returning functions in macro-generated classes.
  • Convert types to readable strings at compile time.
  • Easily define new types and fields in macros.
  • Save arbitrary values as macro expressions for code generation.
  • Generate Haxe files from macros (see generate/GenerateHaxeFile.hx).
  • Advanced type name and position helpers for macros.

Installation

haxelib install macro-type-decoder

Usage

1. Decoding Types in Macros

Decode a Haxe type to a structured representation for easier macro processing.

#if macro
using hx.macro.MacroTypeDecorderHelper;

var someType: Type = ...;
var decoded: hx.macro.MacroTypeDecorderHelper.DecodedType = someType.decode();
#end

2. Creating Unique Names in Macros

Generate unique identifier names to avoid collisions in macro-generated code.

using hx.macro.MacroTypeHelper;

var builder = MacroTypeHelper.createNameBuilder("prefix");
builder.next().get(); // "prefix_1"
builder.next().get(); // "prefix_2"

3. Defining Constant Value Functions in Macros

Easily define functions that return constant values in macro-generated types.

#if macro
using hx.macro.MacroDefineHelper;

Context.defineType({
    pack: ["my", "package"],
    name: "MyGeneratedClass",
    pos: MacroDefineHelper.getPosition(),
    params: [],
    kind: TDClass(),
    fields: [
        // Public constructor
        "new".toPublicFunction([], macro {}, macro: Void),

        // Public function returning a constant array
        "getSomeList".toPublicConstValueFunction([1, 2, 3], macro : Array<Int>),

        // Public function returning a constant map
        "getSomeMap".toPublicConstValueFunction(["a" => 1, "b" => 2], macro : Map<String, Int>),

        // Private static function
        "helper".toPrivateStaticFunction([], MacroDefineHelper.toExpr(EConst(CInt("42"))), macro:Int),

        // Variable field
        "myVar".toVariable(macro:Int, true, MacroDefineHelper.toExpr(EConst(CInt("7")))),

        // Using toExprBlock to create a function body
        "sum".toPublicFunction(
            [],
            [
                EVar("a", macro:Int, EConst(CInt("3")).toExpr()).toExpr(),
                EReturn(EConst(CInt("5")).toExpr()).toExpr()
            ].toExprBlock(),
            macro:Int
        )
    ],
});
#end

There are many more useful helpers in MacroDefineHelper. See the source for details.

4. Type Information at Runtime

Get string representations and decoded data for types at runtime.

var info = new hx.macro.TypeToStringPrinter<Map<Int, String>>();
info.getString(); // "Map<Int,String>"
info.getDecodedData(); // { nullable: false, decoded: TypeMap({decoded:TypeInt}, {decoded:TypeString}) }

Other Utility Functions

This library provides additional helpers for macro programming:

Save Arbitrary Values as Macro Expressions

Use MacroValueSaverExpr to generate Haxe expressions that reconstruct arbitrary values at compile time:

#if macro
import hx.macro.MacroValueSaverExpr;
import haxe.macro.Expr;

var exprs: Array<Expr> = MacroValueSaverExpr.saveToVariable([1, 2, 3], "myArr");
#end

Generate Haxe Files from Macros

Use generate.GenerateHaxeFile to write generated classes to disk:

#if macro
import hx.macro.generate.GenerateHaxeFile;

var generator = new GenerateHaxeFile("output", ["my", "package"]);
generator.writeClass("MyGeneratedClass.hx", () -> myTypeDefinition);
#end

Macro Position Helpers

MacroPositionHelper provides utilities to convert PosInfos to macro positions, useful for accurate error reporting and code generation.

Examples

See the test directory for comprehensive usage examples:

For more details, see the source code

Contributors
dani-987
Version
1.1.0
Published
1 year ago
License
MIT

All libraries are free

Every month, more than a thousand developers use Haxelib to find, share, and reuse code — and assemble it in powerful new ways. Enjoy Haxe; It is great!

Explore Haxe

Haxe Manual

Haxe Code Cookbook

Haxe API documentation

You can try Haxe in the browser! try.haxe.org

Join us on GitHub!

Haxe is being developed on GitHub. Feel free to contribute or report issues to our projects.

Haxe on GitHub

⌂