Context provides an API for macro programming.

It contains common functions that interact with the macro interpreter to query or set information. Other API functions are available in the tools classes:

Static methods

staticaddResource(name:String, data:Bytes):Void

Available on macro, neko

Makes resource data available as name.

The resource is then available using the haxe.macro.Resource API.

If a previous resource was bound to name, it is overwritten.

Compilation server : when using the compilation server, the resource is bound to the Haxe module which calls the macro, so it will be included again if that module is reused. If this resource concerns several modules, prefix its name with a $ sign, this will bind it to the macro module instead.

staticcontainsDisplayPosition(pos:Position):Bool

Available on macro, neko

Check if current display position is within pos.

staticcurrentPos():Position

Available on macro, neko

Returns the position at which the macro was called.

staticdefineModule(modulePath:String, types:Array<TypeDefinition>, ?imports:Array<ImportExpr>, ?usings:Array<TypePath>):Void

Available on macro, neko

Defines a new module as modulePath with several TypeDefinition types. This is analogous to defining a .hx file.

The individual types can reference each other and any identifier respects the imports and usings as usual, expect that imports are not allowed to have .* wildcards or as s shorthands.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticdefineType(t:TypeDefinition, ?moduleDependency:String):Void

Available on macro, neko

Defines a new type from TypeDefinition t.

If moduleDependency is given and is not null, it should contain a module path that will be used as a dependency for the newly defined module instead of the current module.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticdefined(s:String):Bool

Available on macro, neko

Tells if the conditional compilation flag s has been set.

Compiler flags are set using the -D command line parameter, or by calling haxe.macro.Compiler.define.

See also:

staticdefinedValue(key:String):Null<String>

Available on macro, neko

Returns the value defined for the conditional compilation flag key.

If no value is defined for key, null is returned.

Compiler flags values are set using the -D key=value command line parameter, or by calling haxe.macro.Compiler.define.

The default value is "1".

See also:

@:value({ depth : 0 })staticerror(msg:String, pos:Position, depth:Int = 0):Dynamic

Available on macro, neko

Displays a compilation error msg at the given Position pos and aborts the current macro call.

@:value({ depth : 0 })staticfatalError(msg:String, pos:Position, depth:Int = 0):Dynamic

Available on macro, neko

Displays a compilation error msg at the given Position pos and aborts the compilation.

staticfilterMessages(predicate:Message ‑> Bool):Void

Available on macro, neko

Filters all current info/warning messages. Filtered out messages will not be displayed by the compiler.

staticfollow(t:Type, ?once:Bool):Type

Available on macro, neko

Follows a type.

See haxe.macro.TypeTools.follow for details.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

@:value({ once : false })staticfollowWithAbstracts(t:Type, once:Bool = false):Type

Available on macro, neko

Follows a type, including abstracts' underlying implementation

See haxe.macro.TypeTools.followWithAbstracts for details.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticgetAllModuleTypes():Array<ModuleType>

Available on macro, neko

Returns an array of module types to be generated in the output.

This list may change depending on the phase of compilation and should not be treated as conclusive until the generation phase.

Modifying the returned array has no effect on the compilation.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticgetBuildFields():Array<Field>

Available on macro, neko

Returns an Array of fields of the class which is to be built.

This is only defined for @:build/@:autoBuild macros.

staticgetCallArguments():Null<Array<Expr>>

Available on macro, neko

Returns the call arguments that lead to the invocation of the current @:genericBuild macro, if available.

Returns null if the current macro is not a @:genericBuild macro.

staticgetClassPath():Array<String>

Available on macro, neko

Returns an Array of current class paths in the order of their declaration.

Modifying the returned array has no effect on the compiler. Class paths can be added using haxe.macro.Compiler.addClassPath.

staticgetDefines():Map<String, String>

Available on macro, neko

Returns a map of all conditional compilation flags that have been set.

Compiler flags are set using the -D command line parameter, or by calling haxe.macro.Compiler.define.

Modifying the returned map has no effect on the compiler.

See also:

staticgetDisplayMode():DisplayMode

Available on macro, neko

staticgetExpectedType():Null<Type>

Available on macro, neko

Returns the type which is expected at the place the macro is called.

This affects usages such as var x:Int = macroCall(), where the expected type will be reported as Int.

Might return null if no specific type is expected or if the calling macro is not an expression-macro.

staticgetLocalClass():Null<Ref<ClassType>>

Available on macro, neko

Returns the current class in which the macro was called.

If no such class exists, null is returned.

staticgetLocalImports():Array<ImportExpr>

Available on macro, neko

Returns an Array of all imports in the context the macro was called.

Modifying the returned array has no effect on the compiler.

staticgetLocalMethod():Null<String>

Available on macro, neko

Returns the name of the method from which the macro was called.

If no such method exists, null is returned.

staticgetLocalModule():String

Available on macro, neko

Returns the current module path in/on which the macro was called.

staticgetLocalTVars():Map<String, TVar>

Available on macro, neko

Similar to getLocalVars, but returns elements of type TVar instead of Type.

staticgetLocalType():Null<Type>

Available on macro, neko

Returns the current type in/on which the macro was called.

If no such type exists, null is returned.

staticgetLocalUsing():Array<Ref<ClassType>>

Available on macro, neko

Returns an Array of classes which are available for using usage in the context the macro was called.

Modifying the returned array has no effect on the compiler.

staticgetLocalVars():Map<String, Type>

Deprecated: "Use Context.getLocalTVars() instead"

Available on macro, neko

Returns a map of local variables accessible in the context the macro was called.

The keys of the returned map are the variable names, the values are their types.

Modifying the returned map has no effect on the compiler.

staticgetMacroStack():Array<Position>

Available on macro, neko

Get the call stack (excluding the call to Context.getMacroStack() that led to current macro.

staticgetMainExpr():Null<TypedExpr>

Available on macro, neko

Returns the typed expression of the call to the main function.

This function will only work in the generation phase. Any calls made outside a function passed to haxe.macro.Context.onGenerate or haxe.macro.Context.onAfterGenerate will return null.

staticgetMessages():Array<Message>

Available on macro, neko

Gets a list of all current compilation info/warning messages.

staticgetModule(name:String):Array<Type>

Available on macro, neko

Resolves a module identified by name and returns an Array of all its contained types.

The resolution follows the usual class path rules where the last declared class path has priority.

If no module can be found, an exception of type String is thrown.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticgetPosInfos(p:Position):{min:Int, max:Int, file:String}

Available on macro, neko

Returns the information stored in Position p.

staticgetResources():Map<String, Bytes>

Available on macro, neko

Returns a map of all registered resources for this compilation unit.

Modifying the returned map has no effect on the compilation, use haxe.macro.Context.addResource to add new resources to the compilation unit.

staticgetType(name:String):Type

Available on macro, neko

Resolves a type identified by name.

The resolution follows the usual class path rules where the last declared class path has priority.

If no type can be found, an exception of type String is thrown.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticgetTypedExpr(t:TypedExpr):Expr

Available on macro, neko

Returns a syntax-level expression corresponding to typed expression t.

This process may lose some information.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

@:value({ depth : 0 })staticinfo(msg:String, pos:Position, depth:Int = 0):Void

Available on macro, neko

Displays a compilation info msg at the given Position pos.

staticinitMacrosDone():Bool

Available on macro, neko

Check if compiler is past initializations macros or not. When it is, configuration phase is over and parsing/typing can start.

staticmakeExpr(v:Dynamic, pos:Position):Expr

Available on macro, neko

Builds an expression from v.

This method generates AST nodes depending on the macro-runtime value of v. As such, only basic types and enums are supported and the behavior for other types is undefined.

The provided Position pos is used for all generated inner AST nodes.

staticmakeMonomorph():Type

Available on macro, neko

Creates and returns a new instance of monomorph (TMono) type.

Returned monomorph can be used with e.g. Context.unify to make the compiler bind the monomorph to an actual type and let macro further process the resulting type.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticmakePosition(inf:{min:Int, max:Int, file:String}):Position

Available on macro, neko

Builds a Position from inf.

staticonAfterGenerate(callback:() ‑> Void):Void

Available on macro, neko

Adds a callback function callback which is invoked after the compiler generation phase.

Compilation has completed at this point and cannot be influenced anymore. However, contextual information is still available.

Note: the callback is still invoked when generation is disabled with --no-output.

staticonAfterInitMacros(callback:() ‑> Void):Void

Available on macro, neko

Adds a callback function callback which is invoked after the compiler is done running initialization macros, when typing begins.

onAfterInitMacros should be used to delay typer-dependant code from your initialization macros, to properly separate configuration phase and actual typing.

staticonAfterTyping(callback:Array<ModuleType> ‑> Void):Void

Available on macro, neko

Adds a callback function callback which is invoked after the compiler is done typing, but before optimization. The callback receives the types which have been typed.

It is possible to define new types in the callback, in which case it will be called again with the new types as argument.

@:value({ persistent : true })staticonGenerate(callback:Array<Type> ‑> Void, persistent:Bool = true):Void

Available on macro, neko

Adds a callback function callback which is invoked after the compiler's typing phase, just before its generation phase.

The callback receives an Array containing all types which are about to be generated. Modifications are limited to metadata, it is mainly intended to obtain information.

By default, the callback is made before types are stored in the compilation server, if active. This means that any effect persists for the next compilation. If persistent is set to false, changes to types made by the callback only affect the current compilation. If no compilation server is used, this flag has no effect.

Note: the callback is still invoked when generation is disabled with --no-output.

staticonMacroContextReused(callb:() ‑> Bool):Void

Deprecated:

Available on macro, neko

staticonTypeNotFound(callback:String ‑> TypeDefinition):Void

Available on macro, neko

Adds a callback function callback which is invoked when a type name cannot be resolved.

The callback may return a type definition, which is then used for the expected type. If it returns null, the type is considered to still not exist.

staticparse(expr:String, pos:Position):Expr

Available on macro, neko

Parses expr as Haxe code, returning the corresponding AST.

String interpolation of single quote strings within expr is not supported.

The provided Position pos is used for all generated inner AST nodes.

staticparseInlineString(expr:String, pos:Position):Expr

Available on macro, neko

Similar to parse, but error positions are reported within the provided String expr.

staticregisterModuleDependency(modulePath:String, externFile:String):Void

Available on macro, neko

Manually adds a dependency between module modulePath and an external file externFile.

This affects the compilation cache, causing the module to be typed if externFile has changed.

Has no effect if the compilation cache is not used.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticregisterModuleReuseCall(modulePath:String, macroCall:String):Void

Deprecated:

Available on macro, neko

@:value({ depth : 0 })staticreportError(msg:String, pos:Position, depth:Int = 0):Void

Available on macro, neko

Displays a compilation error msg at the given Position pos without aborting the current macro call.

staticresolveComplexType(t:ComplexType, p:Position):ComplexType

Available on macro, neko

Resolve type t and returns the corresponding ComplexType.

Resolving the type may result in a compiler error which can be caught using try ... catch. Resolution is performed based on the current context in which the macro is called. The difference with resolveType is that it only performs type resolution, it does not build any type or trigger macros.

staticresolvePath(file:String):String

Available on macro, neko

Resolves a file name file based on the current class paths.

The resolution follows the usual class path rules where the last declared class path has priority.

If a class path was declared relative, this method returns the relative file path. Otherwise it returns the absolute file path.

If no type can be found, an exception of type String is thrown.

staticresolveType(t:ComplexType, p:Position):Type

Available on macro, neko

Resolve type t and returns the corresponding Type.

Resolving the type may result in a compiler error which can be caught using try ... catch. Resolution is performed based on the current context in which the macro is called.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticsignature(v:Dynamic):String

Available on macro, neko

Returns a hashed MD5 signature of value v.

staticstoreExpr(e:Expr):Expr

Available on macro, neko

Types expression e, stores the resulting typed expression internally and returns a syntax-level expression that can be returned from a macro and will be replaced by the stored typed expression.

If e is null or invalid, an exception is thrown.

A call to storeExpr(e) is equivalent to storeTypedExpr(typeExpr(e)) without the overhead of encoding and decoding between regular and macro runtime.

NOTE: the returned value references an internally stored typed expression that is reset between compilations, so care should be taken when storing the expression returned by this method in a static variable and using the compilation server.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticstoreTypedExpr(t:TypedExpr):Expr

Available on macro, neko

Store typed expression t internally and give a syntax-level expression that can be returned from a macro and will be replaced by the stored typed expression.

If t is null or invalid, an exception is thrown.

NOTE: the returned value references an internally stored typed expression that is reset between compilations, so care should be taken when storing the expression returned by this method in a static variable and using the compilation server.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

statictimer(id:String):() ‑> Void

Available on macro, neko

Creates a timer which will be printed in the compilation report if --times compilation argument is set.

Note that a timer may be omitted from the report if the amount of time measured is too small.

This method immediately starts a timer and returns a function to stop it:

var stopTimer = haxe.macro.Context.timer("my heavy task");
runTask();
stopTimer();

statictoComplexType(t:Type):Null<ComplexType>

Available on macro, neko

Returns the ComplexType corresponding to the given Type t.

See haxe.macro.TypeTools.toComplexType for details.

statictypeAndStoreExpr(e:Expr):{type:Ref<Type>, expr:Expr}

Available on macro, neko

This function works like storeExpr, but also returns access to the expression's type through the type field of the return value.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

statictypeExpr(e:Expr):TypedExpr

Available on macro, neko

Types expression e and returns the corresponding TypedExpr.

Typing the expression may result in a compiler error which can be caught using try ... catch. Note that not all compiler errors can be caught this way because the compiler might delay various checks to a later stage, at which point the exception handler is no longer active.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

statictypeof(e:Expr):Type

Available on macro, neko

Types expression e and returns its type.

Typing the expression may result in a compiler error which can be caught using try ... catch.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticunify(t1:Type, t2:Type):Bool

Available on macro, neko

Tries to unify t1 and t2 and returns true if successful.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

@:value({ depth : 0 })staticwarning(msg:String, pos:Position, depth:Int = 0):Void

Available on macro, neko

Displays a compilation warning msg at the given Position pos.

staticwithImports<X>(imports:Array<String>, usings:Array<String>, code:() ‑> X):X

Available on macro, neko

Executes code in a context that has imports and usings added.

This is equivalent to temporarily having import and using statements in a file. These are only active during the execution of code and do not affect anything afterwards. This is true even if code throws an exception.

If any argument is null, the result is unspecified.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.

staticwithOptions<X>(options:{allowTransform:Null<Bool>, allowInlining:Null<Bool>}, code:() ‑> X):X

Available on macro, neko

Executes code in a context that has some compiler options set, restore the compiler to its default behavior afterwards.

allowInlining: enable or disable inlining during typing with typeExpr.

allowTransform: when disabled, the code typed with typeExpr will be almost exactly the same as the input code. This will disable some abstract types transformations.

Usage of this function from initialization macros is deprecated and may cause compilation server issues. Use Context.onAfterInitMacros to run your code once typer is ready to be used.