From Bauman National Library
This page was last modified on 8 June 2016, at 20:24.
Paradigm Multi-paradigm
Developer Haxe Foundation
Typing discipline Static
Platform IA-32, x86-64
License GPL v2, library: MIT
Website haxe.org

Haxe is an open source toolkit based on a modern high level strictly typed programming language, a state-of-the-art light-speed cross-compiler, a complete cross-platform standard library, and ways to access to each platform's native capabilities.

Haxe includes a set of common functionality that is supported across all platforms, such as numeric data types, text, arrays, binary and some common file formats[1][2]. Haxe also includes platform-specific API for Adobe Flash, C++, PHP and other languages[1][3]. Code written in the Haxe language can be source-to-source compiled into ActionScript 3 code, JavaScript programs, Java, C#, C++ standalone applications, Python, PHP, Apache CGI, and Node.js server-side applications[1][2][4].

The Haxe Foundation

After years of open source development, the Haxe Foundation was created to fund long term Haxe development and provide support to companies using Haxe[5].

The goals of the Haxe Foundation are:

  • To support the whole Haxe ecosystem by funding core technologies
  • To provide a single point of contact for companies that wish to evaluate Haxe as a potential solution
  • To offer Paid Support Plans ensuring that somebody will always be available to answer the phone when you need help
  • To help the Haxe Open Source Community by organizing events and user groups


The Haxe Toolkit is a powerful open source toolkit which will help you take your development to the next level. Instead of developing a separate optimized version of your application, software, game or framework for each platform you target, you can have Haxe compile your project directly into your target language or platform.

In allowing you to target most mainstream platforms natively, it will not only add flexibility to your development process, but also save valuable time and resources.

To help you do this, the toolkit contains three main components:

  • the Haxe Language - a modern high-level, strictly typed programming language
  • the Haxe Standard Library - a complete cross-platform standard library
  • the Haxe Compiler - an incredibly fast cross-compiler

Apart from these features, the Haxe Toolkit also provides you with a range of additional tools that will make using Haxe even more effective.

Programming Language

The Haxe programming language is a very modern high level programming language. It is strictly typed and very easy to learn if you are already familiar with Java, C++, PHP, AS3 or any similar object oriented language[6].

As the Haxe Language has been specially designed for the Haxe Toolkit, we have paid extra attention to its flexibility[7][8]. As such, the language easily adapts the native behaviours of the different platforms you have targeted in your development project. This enables extremely efficient cross-platform development, ultimately saving time and resources.

Hello World

The Haxe Programming Language was designed to be simple yet powerful. Its syntax largely follows the ECMAScript standard, but deviates where necessary. The following program demonstrates "Hello World" written in Haxe:

class HelloWorld {
    static public function main() {
        trace("Hello World");

With Haxe installed and this program saved in a file called "HelloWorld.hx", this can be compiled from the commandline, for example to JavaScript:

haxe -main HelloWorld -js HelloWorld.js

or to Java:

haxe -main HelloWorld -java path/to/java/out

Most Haxe code is organized in classes and functions, making Haxe an object-oriented language reminiscent of Java, ActionScript 3 and C#. However, Haxe has been designed with expressiveness in mind, yielding a powerful language through easily readable syntax.


Abstract types: An abstract type is a compile-time construct which is represented in a different way at runtime. This allows giving a whole new meaning to existing types.

  • Anonymous structures

Data can easily be grouped in anonymous structures, minimizing the necessity of small data classes.

var point = { x: 0, y: 10 };
point.x += 10;
  • Array Comprehension

Create and populate arrays quickly using for loops and logic.

var evenNumbers = [ for (i in 0...100) if (i%2 == 0) i ];
  • Classes, interfaces and inheritance

Haxe allows structuring code in classes, making it an object-oriented language. Common related features known from languages such as Java are supported, including inheritance and interfaces.

  • Conditional compilation

Conditional Compilation allows compiling specific code depending on compilation parameters. This is instrumental for abstracting target-specific differences, but can also be used for other purposes, such as more detailed debugging.

#if js
#elseif sys
  • Algebraic Data Types (Generalized)

Structure can be expressed through algebraic data types (ADT), which are known as enums in the Haxe Language. Furthermore, Haxe supports their generalized variant known as GADT.

enum Result {
    SystemError(msg:String, position:PosInfos);
  • Inlined calls

Functions can be designed as being inline, allowing their code to be inserted at call-site. This can yield significant performance benefits without resorting to code duplication via manual inlining.

  • Iterators

Iterating over a set of values, e.g. the elements of an array, is very easy in Haxe courtesy of iterators. Custom classes can quickly implement iterator functionality to allow iteration.

for (i in [1, 2, 3]) {
  • Local functions and closures

Functions in Haxe are not limited to class fields and can be declared in expressions as well, allowing powerful closures.

var buffer = "";
function append(s:String) {
    buffer += s;
trace(buffer); // foobar
  • Metadata

Add metadata to fields, classes or expressions. This can communicate information to the compiler, macros, or runtime classes.

class MyClass {
    @range(1, 8) var value:Int;
trace(haxe.rtti.Meta.getFields(MyClass).value.range); // [1,8]
  • Static Extensions

Existing classes and other types can be augmented with additional functionality through using static extensions.

using StringTools;
"  Me &amp; You    ".trim().htmlEscape();
  • String Interpolation

Strings declared with a single quotes are able to access variables in the current context.

trace('My name is $name and I work in ${job.industry}');
  • Partial function application

Any function can be applied partially, providing the values of some arguments and leaving the rest to be filled in later.

var map = new haxe.ds.IntMap();
var setToTwelve = map.set.bind(_, 12);
  • Pattern Matching

Complex structures can be matched against patterns, extracting information from an enum or a structure and defining specific operations for specific value combination.

var a = { foo: 12 };
switch (a) {
    case { foo: i }: trace(i);
  • Properties

Variable class fields can be designed as properties with custom read and write access, allowing fine grained access control.

public var color(get,set);
function get_color() {
    return element.style.backgroundColor;
function set_color(c:String) {
    trace('Setting background of element to $c');
    return element.style.backgroundColor = c;
  • Type Parameters, Constraints and Variance

Types can be parametrized with type parameters, allowing typed containers and other complex data structures. Type parameters can also be constrained to certain types and respect variance rules.

class Main<A> {
    static function main() {
        new Main<String>("foo");
        new Main(12); // use type inference

    function new(a:A) { }

Standard Library

The Haxe Standard Library provides common purpose tools without trying to be an exhaustive collection of data structures and algorithms. A Haxe distribution comes with a std directory containing the Haxe Standard Library. Its contents can be categorized like so:

  • General purpose: The std directory itself contains a few top-level classes such as Array, Map or String which can be used on all targets. The haxe sub-directory provides additional data structures, input/output APIs and many more tools.
  • System: The sys sub-directory contains APIs related to file systems and database. Additionally, the Sys top-level class allows various interaction with the operating system. They can only be accessed when compiling to a target of the sys-category (C++, C#, Java, Neko, PHP).
  • Target specific: Each Haxe target has a distinct sub-directory containing target-specific APIs. These can only be accessed when compiling to the given target.

General purpose API

Available on all targets.


  • Array: Typed collection which defines several ECMA-compliant operations
  • Date, DateTools: Operations related to dates and timestamps
  • EReg: Regular Expressions
  • Lambda: Operations over iterables
  • Map: Key-to-value mapping data structure
  • Math: ECMA-compliant mathematical functions
  • Reflect: Field-related reflection
  • Std: Runtime type-checking; numerical parsing; conversion to Int and String
  • String: Basic operations on String
  • StringBuf: Optimized for building Strings
  • StringTools: Various extensions to String
  • Type: Type-related reflection
  • Xml: Cross-platform XML

The haxe package:

  • haxe.Http: HTTP requests
  • haxe.Json: Encoding and decoding JSON
  • haxe.Resource: Work with Haxe resources
  • haxe.Serializer: Serialize arbitrary objects as String
  • haxe.Template: Simple templating system
  • haxe.Timer: Repeated/delayed execution; measuring
  • haxe.Unserializer: Complement to haxe.Serializer
  • haxe.Utf8: Cross-platform UTF8 strings
  • haxe.crypto: Various encryption algorhtms
  • haxe.macro: Types for working with Haxe macros
  • haxe.remoting: Remoting between various client and server types
  • haxe.rtti: Run-time type information
  • haxe.unit: Basic unit-test framework
  • haxe.web: Map URLs to operations
  • haxe.xml: Complementary XML tools
  • haxe.zip: Support of the ZIP-format

The haxe.ds package:

  • haxe.ds.ArraySort: Stable, cross-platform array sorting
  • haxe.ds.BalancedTree: Balanced tree data structure
  • haxe.ds.EnumValueMap: Map type supporting enum value keys
  • haxe.ds.GenericStack: Stack data structure which is optimized on static targets
  • haxe.ds.IntMap: Map type supporting Int keys
  • haxe.ds.ObjectMap: Map type supporting object keys
  • haxe.ds.StringMap: Map type supporting string keys
  • haxe.ds.Vector: Fixed-size data structure

The haxe.io package:

  • haxe.io.Bytes: Byte operations on native representations
  • haxe.io.BytesBuffer: Optimized for building Bytes
  • haxe.io.Path: Operations on path strings

System API

Available on C++, C#, Java, Neko and PHP.

  • Sys: Execute native commands; interact with stdin, stdout and stderr; various other native operations
  • sys.FileSystem: Read and modify directories; obtain information on files and directories
  • sys.db: APIs for working with MySQL and SQLite databases
  • sys.io.File: Read and write file content; copy files
  • sys.io.Process: Use native processes

Target Specific APIs

  • cpp:
    • cpp.Lib: Low level interactions with cpp target
    • cpp.net: Tools for interacting with networks and running servers
    • cpp.vm: Thread API, debugger, profiler etc.
    • cpp.zip: API for working with zip compression
  • cs: API for C# target
  • flash:
    • flash Externs for Flash API
    • flash.Lib Basic interactions with the Flash platform
    • flash.Memory Extern for Flash Memory API
    • flash.Vector Extern for Flash Vectors
  • flash8:
    • flash8 Externs for Flash 8 API
  • java: API for Java target
  • js:
    • js.Browser: Shortcuts for common browser functions
    • js.Cookie: Helpers for interacting with HTTP cookies in the browser
    • js.JQuery: Extern class and helpers for jQuery
    • js.Lib: Shortcuts for alert(), eval() and debugger
    • js.html: Externs for interacting with the browser DOM
  • neko:
    • neko.Lib: Low level interactions with neko platform
    • neko.Web: Work with HTTP requests and responses
    • neko.net: Tools for interacting with networks and running servers
    • neko.vm: API for multi-threaded applications
    • neko.zip: API for working with zip compression
  • php:
    • php.Lib: Low level interactions with PHP platform
    • php.Session: Work with native PHP sessions
    • php.Web: Work with HTTP requests and responses
    • php.db.PDO: Additional PDO driver for database interactions


The Haxe Compiler is responsible for translating the Haxe programming language to the target platform native source code or binary. Each platform is natively supported, without any overhead coming from running inside a virtual machine. The Haxe Compiler is very efficient and can compile thousands of classes in seconds.

Basic Usage

The Haxe Compiler is typically invoked from command line with several arguments which have to answer two questions:

  • What should be compiled?
  • What should the output be?

To answer the first question, it is usually sufficient to provide a class path via the -cp path argument, along with the main class to be compiled via the -main dot_path argument. The Haxe Compiler then resolves the main class file and begins compilation.

The second question usually comes down to providing an argument specifying the desired target. Each Haxe target has a dedicated command line switch, such as -js file_name for JavaScript and -php directory for PHP. Depending on the nature of the target, the argument value is either a file name (for -js, -swf, -neko and -python) or a directory path.

Common arguments

  • Input:
    • -cp path Adds a class path where .hx source files or packages (sub-directories) can be found.
    • -lib library_name Adds a Haxelib library.
    • -main dot_path Sets the main class.
  • Output:
    • -js file_name Generates JavaScript source code in specified file.
    • -as3 directory Generates ActionScript 3 source code in specified directory.
    • -swf file_name Generates the specified file as Flash .swf.
    • -neko file_name Generates Neko binary as specified file.
    • -php directory Generates PHP source code in specified directory.
    • -cpp directory Generates C++ source code in specified directory and compiles it using native C++ compiler.
    • -cs directory Generates C# source code in specified directory.
    • -java directory Generates Java source code in specified directory and compiles it using the Java Compiler.
    • -python file_name Generates Python source code in the specified file.


  • Built-in Compiler Metadata

Starting from Haxe 3.0, you can get the list of defined compiler metadata by running haxe --help-metas

Metadata Description Platfrom
@:abi Function ABI/calling convention cpp
@:abstract Sets the underlying class implementation as abstract type cs java
@:access (Target path) Forces private access to package type or field all
@:allow (Target path) Allows private access from package type or field all
@:analyzer Used to configure the static analyzer all
@:annotation Annotation (@interface) definitions on -java-lib imports will be annotated with this metadata. Has no effect on types compiled by Haxe java
@:arrayAccess Allows Array access on an abstract all
@:autoBuild (Build macro call) Extends @:build metadata to all extending and implementing classes. See Macro autobuild all
@:bind Override Swf class declaration flash
@:bitmap (Bitmap file path) _Embeds given bitmap data into the class (must extend flash.display.BitmapData) flash
@:bridgeProperties Creates native property bridges for all Haxe properties in this class cs
@:build (Build macro call) Builds a class or enum from a macro. See Type Building all
@:buildXml Specify xml data to be injected into Build.xml cpp
@:callable Abstract forwards call to its underlying type all
@:classCode Used to inject platform-native code into a class cs java
@:commutative Declares an abstract operator as commutative all
@:compilerGenerated Marks a field as generated by the compiler. Shouldn't be used by the end user cs java
@:coreApi Identifies this class as a core api class (forces Api check) all
@:coreType Identifies an abstract as core type so that it requires no implementation all
@:cppFileCode Code to be injected into generated cpp file cpp
@:cppInclude File to be included in generated cpp file cpp
@:cppNamespaceCode cpp
@:dce Forces Dead Code Elimination even when not -dce full is specified all
@:debug Forces debug information to be generated into the Swf even without -debug flash
@:decl cpp
@:defParam all
@:delegate Automatically added by -net-lib on delegates cs
@:depend cpp
@:deprecated Automatically added by -java-lib on class fields annotated with @Deprecated annotation. Has no effect on types compiled by Haxe java
@:event Automatically added by -net-lib on events. Has no effect on types compiled by Haxe cs
@:enum Defines finite value sets to abstract definitions. all
@:expose (?Name=Class path) Makes the class available on the window object or exports for node.js. See exposing Haxe classes for JavaScript js
@:extern Marks the field as extern so it is not generated all
@:fakeEnum (Type name) Treat enum as collection of values of the specified type all
@:file(File path) Includes a given binary file into the target Swf and associates it with the class (must extend flash.utils.ByteArray) flash
@:final Prevents a class from being extended all
@:font (TTF path Range String) Embeds the given TrueType font into the class (must extend flash.text.Font) flash
@:forward (List of field names) Forwards field access to underlying type all
@:from Specifies that the field of the abstract is a cast operation from the type identified in the function. all
@:functionCode cpp
@:functionTailCode cpp
@:generic Marks a class or class field as generic so each type parameter combination generates its own type/field all
@:genericBuild Builds instances of a type using the specified macro all
@:getter (Class field name) Generates a native getter function on the given field flash
@:hack Allows extending classes marked as @:final all
@:headerClassCode Code to be injected into the generated class, in the header cpp
@:headerCode Code to be injected into the generated header file cpp
@:headerNamespaceCode cpp
@:hxGen Annotates that an extern class was generated by Haxe cs java
@:ifFeature (Feature name) Causes a field to be kept by DCE if the given feature is part of the compilation all
@:include cpp
@:initPackage all
@:internal Generates the annotated field/class with internal access cs java
@:isVar Forces a physical field to be generated for properties that otherwise would not require one all
@:javaCanonical (Output type package,Output type name) Used by the Java target to annotate the canonical path of the type java
@:jsRequire Generate javascript module require expression for given extern js
@:keep Causes a field or type to be kept by DCE all
@:keepInit Causes a class to be kept by DCE even if all its field are removed all
@:keepSub Extends @:keep metadata to all implementing and extending classes all
@:macro (deprecated) all
@:mergeBlock Merge the annotated block into the current scope all
@:meta Internally used to mark a class field as being the metadata field all
@:multiType (Relevant type parameters) Specifies that an abstract chooses its this-type from its @:to functions all
@:native (Output type path) Rewrites the path of a class or enum during generation all
@:nativeChildren Annotates that all children from a type should be treated as if it were an extern definition - platform native cs java
@:nativeGen Annotates that a type should be treated as if it were an extern definition - platform native cs java
@:nativeProperty Use native properties which will execute even with dynamic usage cpp
@:noCompletion Prevents the compiler from suggesting completion on this field all
@:noDebug Does not generate debug information into the Swf even if -debug is set flash
@:noDoc Prevents a type from being included in documentation generation all
@:noImportGlobal Prevents a static field from being imported with import Class.* all
@:noPrivateAccess Disallow private access to anything for the annotated expression all
@:noStack cpp
@:noUsing Prevents a field from being used with using all
@:nonVirtual Declares function to be non-virtual cpp
@:notNull Declares an abstract type as not accepting null values all
@:ns Internally used by the Swf generator to handle namespaces flash
@:op (The operation) Declares an abstract field as being an operator overload all
@:optional Marks the field of a structure as optional all
@:overload (Function specification) Allows the field to be called with different argument types. Function specification cannot be an expression all
@:privateAccess Allow private access to anything for the annotated expression all
@:property Marks a property field to be compiled as a native C# property cs
@:protected Marks a class field as being protected all
@:public Marks a class field as being public all
@:publicFields Forces all class fields of inheriting classes to be public all
@:pythonImport Generates python import statement for extern classes python
@:readOnly Generates a field with the readonly native keyword cs
@:remove Causes an interface to be removed from all implementing classes before generation all
@:require (Compiler flag to check) Allows access to a field only if the specified compiler flag is set all
@:rtti Adds runtime type informations all
@:runtime all
@:runtimeValue Marks an abstract as being a runtime value all
@:selfCall Translates method calls into calling object directly js
@:setter (Class field name) Generates a native setter function on the given field flash
@:sound (File path) Includes a given .wav or .mp3 file into the target Swf and associates it with the class (must extend flash.media.Sound) flash
@:sourceFile Source code filename for external class cpp
@:strict Used to declare a native C# attribute or a native Java metadata. Is type checked cs java
@:struct Marks a class definition as a struct cs
@:structAccess Marks an extern class as using struct access('.') not pointer('->') cpp
@:suppressWarnings Adds a SuppressWarnings annotation for the generated Java class java
@:throws (Type as String) Adds a throws declaration to the generated function java
@:to Specifies that the field of the abstract is a cast operation to the type identified in the function all
@:transient Adds the transient flag to the class field java
@:unbound Compiler internal to denote unbounded global variable all
@:unifyMinDynamic Allows a collection of types to unify to Dynamic all
@:unreflective cpp
@:unsafe Declares a class or a method with the C#'s unsafe flag cs
@:usage all
@:value Used to store default values for fields and function arguments all
@:void Use Cpp native 'void' return type cpp
@:volatile cs java
  • Dead Code Elimination

Dead Code Elimination or DCE is a compiler feature which removes unused code from the output. After typing, the compiler evaluates the DCE entry-points (usually the main-method) and recursively determines which fields and types are used. Used fields are marked accordingly and unmarked fields are then removed from their classes.

DCE has three modes which are set when invoking the command line:

  1. -dce std: Only classes in the Haxe Standard Library are affected by DCE. This is the default setting on all targets.
  2. -dce no: No DCE is performed.
  3. -dce full: All classes are affected by DCE.

The DCE-algorithm works well with typed code, but may fail when dynamic or reflection is involved. This may require explicit marking of fields or classes as being used by attributing the following metadata:

  1. @:keep: If used on a class, the class along with all fields is unaffected by DCE. If used on a field, that field is unaffected by DCE.
  2. @:keepSub: If used on a class, it works like @:keep on the annotated class as well as all subclasses.
  3. @:keepInit: Usually, a class which had all fields removed by DCE (or is empty to begin with) is removed from the output. By using this metadata, empty classes are kept.

If a class needs to be marked with @:keep from the command line instead of editing its source code, there is a compiler macro available for doing so: --macro keep('type dot path') See the haxe.macro.Compiler.keep API for details of this macro. It will mark package, module or sub-type to be kept by DCE and includes them for compilation.

The compiler automatically defines the flag dce with a value of either "std", "no" or "full" depending on the active mode. This can be used in conditional compilation.

  • Completion

The rich type system of the Haxe Compiler makes it difficult for IDEs and editors to provide accurate completion information. Between type inference and macros, it would require a substantial amount of work to replicate the required processing. This is why the Haxe Compiler comes with a built-in completion mode for third-party software to use.

All completion is triggered using the --display file@position[@mode] compiler argument. The required arguments are:

  1. file: The file to check for completion. This must be an absolute or relative path to a .hx file. It does not respect any class paths or libraries.
  2. position: The byte position (not character position) of where to check for completion in the given file.
  3. mode: The completion mode to use (see below).
  4. Field access: Provides a list of fields that can be accessed on a given type.
  5. Call argument: Reports the type of the function which is currently being called.
  6. Type path: Lists sub-packages, sub-types and static fields.
  7. Usage: Lists all occurrences of a given type, field or variable in all compiled files. (mode: "usage")
  8. Position: Reports the position of where a given type, field or variable is defined. (mode: "position")
  9. Top-level: Lists all identifiers which are available at a given position. (mode: "toplevel")

Due to Haxe being a very fast compiler, it is often sufficient to rely on the normal compiler invocation for completion. For bigger projects Haxe provides a server mode which ensures that only those files are re-compiled that actually changed or had any of their dependencies changes.

  • Resources

Haxe provides a simple resource embedding system that can be used for embedding files directly into the compiled application.

While it may be not optimal to embed large assets such as images or music in the application file, it comes in very handy for embedding smaller resources like configuration or XML data.

  • Embedding resources

External files are embedded using the -resource compiler argument:

-resource hello_message.txt@welcome

The string after the @ symbol is the resource identifier which is used in the code for retrieving the resource. If it is omitted (together with the @ symbol) then the file name will become the resource identifier.

  • Retrieving text resources

To retrieve the content of an embedded resource we use the static method getString of haxe.Resource, passing a resource identifier to it:

class Main {
  static function main() {

The code above will display the content of the hello_message.txt file that we included earlier using welcome as the identifier.

  • Retrieving binary resources

While it's not recommended to embed large binary files in the application, it still may be useful to embed binary data. The binary representation of an embedded resource can be accessed using the static method getBytes of haxe.Resource:

class Main {
  static function main() {
    var bytes = haxe.Resource.getBytes("welcome");
    trace(bytes.readString(0, bytes.length));

The return type of getBytes method is haxe.io.Bytes, which is an object providing access to individual bytes of the data.

  • Implementation details

Haxe uses the target platform's native resource embedding if there is one, otherwise it provides its own implementation.

  1. Flash resources are embedded as ByteArray definitions
  2. C# resources are included in the compiled assembly
  3. Java resources are packed in the resulting JAR file
  4. C++ resources are stored in global byte array constants.
  5. JavaScript resources are serialized in Haxe serialization format and stored in a static field of haxe.Resource class.
  6. Neko resources are stored as strings in a static field of haxe.Resource class.
  • Runtime Type Information

The Haxe compiler generates runtime type information (RTTI) for classes that are annotated or extend classes that are annotated with the :rtti metadata. This information is stored as a XML string in a static field __rtti and can be processed through haxe.rtti.XmlParser. The resulting structure is described in RTTI structure.

since Haxe 3.2.0

The type haxe.rtti.Rtti has been introduced in order to simplify working with RTTI. Retrieving this information is now very easy:

class Main {
  var x:String;
  static function main() {
    var rtti = haxe.rtti.Rtti.getRtti(Main);


Cite error: Invalid <references> tag; parameter "group" is allowed only.

Use <references />, or <references group="..." />
  1. 1.0 1.1 1.2 Ponticelli, Franco (2008-02-11). Professional haXe and Neko. Wiley. ISBN 0470122137.
  2. 2.0 2.1 "Haxe Docs"
  3. "Haxe Docs"
  4. "GameHaxe website"
  5. [1]
  6. Grden, John; Mineault, Patrick; Balkan, Aral; Hughes, Marc; Arnold, Wade (2008-07-16). The Essential Guide to Open Source Flash Development. Apress. p. Chapter 9 (Using Haxe). ISBN 1430209941.
  7. [2]
  8. Fisher, Matt (2013-01-01). HTML5 for Flash Developers. Packt Publishing Ltd. ISBN 1849693331.