Haxe

From Wikipedia, the free encyclopedia
  (Redirected from HaXe)
Jump to: navigation, search
Not to be confused with Hack (programming language).
Haxe
HaxeLanguageLogo.jpeg
Paradigm Multi-paradigm
Developer Haxe Foundation
Appeared in 2005
3.1.3 / April 13, 2014; 8 months ago (2014-04-13)
Static
Implementation language
OCaml
Platform IA-32, x64
OS Windows, OS X, Linux
License GPL v2, library: MIT
.hx .hxml
Website haxe.org

Haxe is an open-source high-level multiplatform programming language and compiler that can produce applications and source code for many different platforms from a single code-base.[1] Code written in the Haxe language can be source-to-source compiled into Adobe Flash applications, JavaScript programs, Java, C#, C++ standalone applications (to some extent),[2] Python, PHP, Apache CGI, and Node.js server-side applications.[3][4]

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.[3] Haxe also includes platform-specific API, but as of 2012, it only supports a subset of the functionality available in each platform,[5] with only the Flash platform API fully usable. Haxe can also compile to Neko code, which runs in the Neko runtime created by the same developer. Haxe as an integral part of the OpenFL framework, which allows the creation of multi-platform video games.

Haxe was developed by Nicolas Cannasse and other contributors, and was named Haxe because it was short, simple, and "has an X inside", which the author humorously asserts is necessary to make any new technology a success.[6]

Architecture[edit]

Development of Haxe was started in October 2005 and the first beta version was released in February 2006. Haxe 1.0 was released in April 2006, with support for Adobe Flash applications, and Haxe 2.0 was released in July 2006, adding support for Javascript programs.

Haxe is the successor to the open-source ActionScript 2 compiler MTASC, also built by Nicolas Cannasse,[7] and is released under the GNU General Public License version 2 or later.[8] Haxe has much in common with ActionScript 3. The Haxe compiler is developed in the OCaml language. No knowledge of OCaml is necessary to develop applications using Haxe.

To help leverage existing code, the open-source community has created experimental source code converters for the following languages:

  • ActionScript 3 to Haxe[9]
  • C# to Haxe[10]

Advantages to using Haxe include:

  • Platform independence
  • A fully developed high-level language
  • Target devices that only support C++[11]

Compiler[edit]

The Haxe compiler is separated into one frontend and multiple backends. The frontend is responsible for parsing and type-checking the input language, applying macros, general optimizations, various transformations, and for producing the intermediate representation of the code, the typed abstract syntax tree (AST). Each of the backends is responsible for translating that AST into either sourcecode or bytecode for the respective target.

The compiler is written in OCaml. It can be run in server-mode to provide code completion for IDEs and maintain a cache, to speed up compilation even more.[12]

The Haxe compiler is an optimizing compiler, and contains the following optimization features:

The performance of applications developed in Haxe varies depending on the target platform.

In the case of ActionScript 3, programs produced using the Haxe compiler usually run faster than programs produced using the old Adobe Systems Flex SDK compiler.[13]

However, using Action Script Compiler 2 (ASC2) and with proper code design [14] many have reported comparable performance. Especially that ASC2 is now an optimizing compiler (including inlining).

Platform support[edit]

The Haxe language can compile into bytecode for different virtual machines such as the Adobe Flash Player and Neko, and can generate source code in ActionScript 3, JavaScript, and includes experimental support for C++ and C#. This strategy of "compiling" to multiple source code languages is inspired by the write once, run anywhere paradigm. It also allows the programmer to choose the best platform for the job.

In Haxe, platforms are known as "targets", which are Haxe modules that provide access to core-APIs (language and bytecode targets), for the compiler-backends that are responsible for generating the respective code, and for runtimes with specific APIs that go beyond the core language support (platform-targets).

  • Bytecode Targets - There are targets that produce bytecode (Neko, SWF, SWF8) that is being passed as-is to the respective runtime. Haxe API is available as well as platform specific features under the platform's namespace.
  • Language Targets - There are targets that produce sourcecode (AS3, C++, C#, Java), that has to be compiled by a third-party compiler, or passed as-is to the respective runtime which compiles the code and executes it (JavaScript, PHP). Specific mechanisms exist to interact with low-level aspects of the target-language to ease development. Unsupported API can be added into Haxe files by embedding source code written in the target-language.
  • Platform Targets - For most of the targets, multiple runtimes with different purposes exist. JavaScript, for instance, is in widespread use as a scripting language in browsers, game-engines, office-applications, as server-side language for runtimes like NodeJs, and much more.
  • External ow toModules - Extern type definitions ("extern class" in Haxe) all describe the types of platform-native APIs, as well as those of runtimes and libraries written in the target language, to the Haxe compiler, so that static type-checking can be applied.
Code Generator Output Platform Usage Since Haxe Version
AVM1[3] byte code Adobe Flash Player 6+ Desktop, Browser 2005 (alpha)
AVM2[3] byte code Adobe Flash Player 9+, Adobe AIR, Tamarin VM Desktop, Browser, Server 2005 (alpha)
ActionScript 3[3] source Adobe Flash Player 9+ Server, Desktop 2007 (1.12)
C++ (hxcpp)[3] source Windows, Linux, Mac OS X Server, Desktop, CLI 2009 (2.04)
C++ source Android,[15] Apple iOS,[2] Palm webOS[16] Mobile 2009 (2.04)
C#[3] source .NET Framework Server, Desktop, Mobile 2012 (2.10)
Java[3] source Java Server, Desktop 2012 (2.10)
JavaScript[3] source HTML 5, NodeJS, PhoneGap Server, Desktop, Browser, Mobile 2006 (beta)
Neko[3] byte code NekoVM Server, Desktop, CLI 2005 (alpha)
PHP[3] source PHP Server 2008 (2.0)
python[3] source python CLI, Web, Desktop 2014 (3.2)

Language[edit]

Haxe is a general-purpose language with object-oriented programming, exceptions, and type inference with class parameters. Generic classes, reflectivity, iterators, and functional programming are built-in functionality of the language and libraries.[17] Unusual among programming languages, Haxe contains a type system which is both strong and dynamic. The compiler will check types implicitly and give compile-time errors, but it also enables the programmer to bypass type-checking and rely on the target platform's dynamic type-handling.

The Haxe language is similar to ECMAScript, although almost no ECMAScript code will run on Haxe without modifications. Unlike ECMAScript, Haxe is a compiled language. The Haxe language is inspired by ActionScript and C#, supporting features of both.

Since Haxe had its origins in ActionScript 3, all of the existing Flash API can be used, although Haxe requires better-formed code and programming standards than Adobe compilers (for example, with regard to scoping and data typing).

Type system[edit]

Haxe is a statically typed language. It has a rich type system that offers classes, interfaces, function/method types, anonymous types, algebraic data types (ADTs, called "enum" in Haxe), abstract types. Classes, ADTs and function types allow parametric polymorphism based on type erasure, sometimes also called "Generics" in object oriented programming languages.

Bounded quantification is also part of the feature set: type parameters can be constrained to a set of zero or more types.

Haxe doesn't offer variance annotations for type parameters, the type constructors are always invariant in their parameter types.

Subtype polymorphism is supported via standard, single-inheritance.

Further, Haxe supports both structural typing and nominal typing. To ease the burden on the programmer, without sacrificing type safety, Haxe supports type-inference, which in many cases alleviates the need to write out types explicitly.

Classes[edit]

Classes (keyword "class") in Haxe are similar to those in Java or AS3. Their fields can be either methods, variables or properties, each static or per instance respectively. Haxe supports the accessors "public" and "private", as well as more advanced methods for access control (ACL, link), that are denoted using annotations. Methods and static variables of constant values can be inlined using the "inline" keyword.

Interfaces in Haxe are very similar to those in, for example, Java.


interface ICreature {
    public var birth:Date;
    public var name:String;
 
    public function age():Int;
}
 
class Fly implements ICreature {
    public var birth:Date;
    public var name:String;
 
    public function age():Int return Date.now().getFullYear() - birth.getFullYear();
}

Enumerated types[edit]

Enumerated types are a key feature of the language; they can have parameters of their own and be recursive.[18] They are similar to algebraic data types (ADT) in languages like ML or Haskell. Technically speaking, they are proper sum types, with the provision that the product types they include must be defined within them. This means they are not simply indexed "magic-number" values as in most languages, and can be used to elegantly solve complex programming problems:

enum Color {
    red;
    green;
    blue;
    rgb( r : Int, g : Int, b : Int );
}
 
class Colors {
    static function toInt ( c : Color ) : Int {
        return switch ( c ) {
            case red: 0xFF0000;
            case green: 0x00FF00;
            case blue: 0x0000FF;
            case rgb(r, g, b): (r << 16) | (g << 8) | b;
        }
    }
    static function validCalls() {
        var redint = toInt(Color.red);
        var rgbint = toInt(Color.rgb(100, 100, 100));
    }
}

Haxe also supports parametrised enums types. Examples of this include Haxe standard library types Option, Either and ConsList, with ConsList also being recursive:

enum Option<T> {
    Some(v:T);
    None;
}
 
enum Either<T,U> {
    Left(v:T);
    Right(v:U);
}
 
enum ConsList<T> {
    Nil;
    Cons(head:T,tail:ConsList<T>);
}

Anonymous types[edit]

Anonymous types are defined by denoting their structure explicitly, they can be given an alias by using a type definition (keyword "typedef"):

typedef Anon = { a:Int, b:String, c:Float->Void };

Function types[edit]

Functions are first-class values in Haxe. Their type is denoted by using arrows between argument types, and the argument type(s) and return type respectively, as common in many functional languages. However, unlike in prominent examples like Haskell or the ML-family of languages, not all functions are unary functions (functions with one argument only), and in Haxe, functions can't be partially applied per default. Therefore the following type signatures have different semantics than in the aforementioned languages. The type F is a function that takes an Int and a String as arguments, and returns a value of type Float.

The same notation in a language with unary functions only, would refer to a function that takes an Int as argument, and returns a function of Type String->Float.

Types F2 and F3 denote the same type. Both are binary functions that return a binary function of type F. For F3 the syntax to declare a function type within a function type is used.

typedef F = Int->String->Float;
 
typedef F2 = Int->String->F;
typedef F3 = Int->String->(Int->String->Float);

Abstract types[edit]

A concept called abstract types is the latest addition to the Haxe type system. They allow to reuse existing types for specific purposes, like implementing types for units of measurement, to greatly reduce the risk of mixing up values of the same underlying type, but with different meanings (e.g. miles vs. km). The term "abstract type" as it is used in Haxe refer to something different from a conventional abstract type.

The following example assumes that the metric system is the default, while a conversion to miles is necessary for legacy data. Haxe is able to automatically convert miles to kilometers, but not in the opposite direction.

abstract Kilometer(Float) {
    public function new(v:Float) this = v;
}
 
abstract Mile(Float) {
    public function new(v:Float) this = v;
    @:to public inline function toKilometer():Kilometer return (new Kilometer(this / 0.62137));
}
 
class Test {
  static var km:Kilometer;
  static function main(){
    var one100Miles = new Mile(100);
    km = one100Miles;
 
    trace(km); // 160.935
  }
}

As the example shows, no explicit conversion is required for the assignment "km = one100Miles;" to do the right thing.

Structural typing[edit]

Structural typing plays a major role in many functional programming languages, and only to a much lesser extent in common OOP languages. Unlike in (exclusively) nominative type systems, the equality of two types isn't established by some kind of name tag, but rather by the structure of a type. Structural types can be thought of as implicit interfaces:

class FooBar {
 
   public var foo:Int;
   public var bar:String;
 
   public function new(){ foo=1; bar="2";}
 
   function anyFooBar(v:{foo:Int,bar:String}) trace(v.foo);
 
   static function test(){
        var fb = new FooBar();
        fb.anyFooBar(fb);
        fb.anyFooBar({foo:123,bar:"456"});
   }
}

See also[edit]

Also on the Haxe platform:

Other languages that compile to JavaScript:

Other multi-platform languages:

References[edit]

External links[edit]