12.1 Accessing Target-specific Syntax

When writing code for a particular target, it might be necessary to access certain features that are only available on that target and inaccessible in Haxe code. It is still possible to access these features using the target-specific Syntax APIs:

Important note: Before using these functions, make sure there is no alternative available in the Haxe Standard Library. The resulting syntax can not be validated by the Haxe compiler, which may result in invalid or error-prone code in the output. When checking if a particular feature is available in the standard library, consult the API documentation. Target-specific APIs are placed into a package named after the target, e.g. JavaScript-specific APIs are in the top-level js package. Most targets have a Lib class in their package which provides some common methods for that target.

Syntax.code(expr, args...)
since Haxe 4.0.0

Injects raw code expressions. The expression is a string which may include {0}, {1}, {2}, etc. - these are replaced with the corresponding arguments provided to the function. This is important if the code needs to reference Haxe fields, since the names of variables in the generated output may not correspond to their names in Haxe code. The Haxe compiler will take care of adding quotes if strings are provided. The function can also return values, although the return type is always Dynamic.

An example of js.Syntax.code:

var myMessage = "Is Haxe great?";
var output:Bool = js.Syntax.code("confirm({0})", myMessage);

The generated JavaScript output is:

var myMessage = "Is Haxe great?";
var output = confirm(myMessage);

Other functions are documented in the corresponding API sections. These generally include native operators that are not available in Haxe.

Other platforms

It is planned to implement Syntax APIs for other targets in future releases. For the time being, it is still possible to access target-specific syntax on some of the other platforms, albeit in a less type-safe manner, using an untyped expression:

  • C++ untyped __cpp__(expr, args...)
  • C# untyped __cs__(expr, args...)
  • Java untyped __java__(expr, args...)
  • Lua untyped __lua__(expr, args...)

The arguments for these follow exactly the same semantics as Syntax.code.