Haxe (programming language)

from Wikipedia, the free encyclopedia
Knuckle
logo
Basic data
Publishing year: 2005
Developer: Motion twin
Current  version : 4.0.5   (December 17, 2019)
Influenced by: ActionScript , OCaml , JavaScript
Operating system : Windows , Linux , macOS
License : GPL v2
haxe.org

Haxe is an object-oriented , JavaScript- like programming language . The ability to create executable programs for Adobe Flash , JavaScript, PHP , C ++ and Neko VM from Haxe code , together with powerful remoting (ability to send objects and method calls to other systems, see separate section) make Haxe ideal for the Programming web applications, which is why it is also known as the universal web-oriented language .

history

The French company Motion Twin was founded in 2001 and has been developing Flash-based websites and games ever since. The development of Haxe is closely interwoven with the company's history. Nicolas Cannasse, co-founder of Motion Twin, is considered the inventor of Haxe.

2003 to 2005: Tools for working with ActionScript

To make working with ActionScript easier, Motion Twin began developing the ActionScriptMetaLanguage in December 2003 . Programs written in it are converted into normal ActionScript by a separate precompiler. In this step, type and parameter checks are carried out at compile time , whereby the type inference explained below is also used. The resulting ActionScript code is then converted into a SWF file using the Flash compiler , which is then displayed to the user using the Flash Player. For comparison: Without the use of the ActionScriptMetaLanguage , the type check is only possible at runtime, which makes it difficult to find program errors.

In April 2004, the ActionScriptMetaLanguage was expanded to include new types and from then on was called MotionTypes . A little later, the compiler was able to generate SWF bytecode directly without going through the Macromedia compiler.

Both ActionScriptMetaLanguage and MotionTypes are only used within the company. In contrast, MTASC , the MotionTwin Actionscript Compiler , was presented to the public as a beta version in October 2004. This compiler is independent of MotionTypes, because it creates SWF bytecode from ordinary ActionScript (which had meanwhile reached language version 2.0). Together with other free software, the FAMES program package (consisting of Flashout , ASDT , MTASC, Eclipse and SwfMill ) resulted , which made it possible for the first time to create Flash applications without the proprietary software from Macromedia or Adobe .

On July 14, 2005, just two days after the public launch of Flash Player 8, MTASC already supported this version of Flash.

From 2005: Development of an own language and technology

Initially, it was planned to focus on the Neko language (also developed by Motion Twin) in the future, and to use Neko with other technologies, such as B. ActionScript 2.0, Java and Ruby to combine.

When Adobe announced ActionScript 3.0 and the numerous MTASC users were waiting for the new language features to be supported by MTASC, Motion Twin announced that it would stop development and instead advance the new technology, haXe .

Development began on October 22, 2005. After alpha versions in November 2005 and beta versions around February 2006, release version 1.0 followed on May 17, 2006. The current version is 3.1.3, which was published on April 13, 2014. The Haxe compiler is free, open software under the GNU General Public License, the supplied libraries are under the BSD license .

Naming and pronunciation

The name haXe was chosen because it is “short, simple and cool” and contains an X , which, according to the author, is necessary for a new technology to be successful.

There is no official pronunciation of the name haXe . International pronunciations are "hex" (which should come close to a French pronunciation), "häcks" and "aytch äx".

language

Haxe is an independent programming language that is syntactically based on JavaScript or ActionScript and Java , but also introduces its own syntax elements.

Syntax overview

The following code example provides an overview of the typical structure of a Haxe source code file. It also shows some advanced options that the programmer does not necessarily have to master:

package my.pack;

import flash.Lib;

/** Dokumentation im Javadoc-Stil */
class MyClass<EinTyp> extends MyOtherClass, implements MyInterface {

    private var id : Int;
    private static var idCounter : Int;

    public var typisierteVariable : EinTyp;

    // Es folgt eine Eigenschaft samt get- und set-Methode.
    // Der Typ der Eigenschaft wird als Typenparameter angegeben.
    public var x(getX,setX) : EinTyp;
    private var my_x : EinTyp;

    private function getX() {
        return my_x;
    }

    private function setX( v : EinTyp) {
        my_x = v;
        trace("Wert von x wurde geändert!");
        return my_x;
    }



    /** Dies ist ein Konstruktor */
    public function new()
    {
        id = idCounter++;
    }

    function foo() : Void {
        for(x in 3...7)
            trace("Eine Zahl " + x);
    }

    /** Einsprungpunkt für die Anwendung */
    static function main()
    {
        var instanz = new MyClass<Bool>();
        instanz.x = true;    // ruft den setter auf, welcher eine Warnung per trace ausgeben wird
    }
}

At this point it should be emphasized again that this code can run without changes in all three compiler targets.

Feature overview

Most of the following Haxe features are also known from widely used object-oriented languages ​​such as C ++ or Java and are therefore not explained in detail:

However, the following features, which many common languages ​​offer, are missing in Haxe:

Type inference

Programming languages ​​are usually typed statically or dynamically. With static typing, each variable, each attribute and each parameter is uniquely assigned a type that remains constant at runtime.

// Java-Beispiel (Java ist statisch typisiert):
int x;
x = 3;    // geht
x = "hallo"; // geht nicht

In a dynamically typed language, variables, attributes and parameters do not have a clearly defined type:

// Javascript-Beispiel (Javascript ist dynamisch typisiert):
var x;
x = 3;    // geht
x = "hallo"; // geht

Haxe combines both approaches. On the one hand, it is up to the programmer whether the type of a variable is specified or not. On the other hand, the compiler deduces ( inference means inference ) independently the type of each variable that has not been specified by the programmer and treats it as if it were statically typed. As a third alternative, the programmer can explicitly declare it as dynamic and thus cancel the type inference:

// Haxe-Beispiel (in diesem Fall statisch):
var x : Int;
x = 3;    // geht
x = "hallo"; // geht nicht

// Haxe-Beispiel (in diesem Fall statisch durch Typinferenz):
var x;
x = 3;    // geht, Compiler schließt darauf, dass x vom Typ 'Int' ist
x = "hallo"; // geht nicht

// Haxe-Beispiel (in diesem Fall dynamisch):
var x : Dynamic;
x = 3;    // geht
x = "hallo"; // geht

The languages ​​for which Haxe can represent a substitute (Javascript, ActionScript, PHP, etc.) are usually typed dynamically. The advantage of type inference is shown again in the following example:

function bar() : Array<Int> {
    var retval = [1,2,3,4];
    if(Math.random() < 0.001)  // Math.random() liefert zufälligen Wert zwischen 0 und 1
        retval.push(5.001);   // ACHTUNG: Diese Zeile erzeugt einen Compiler-Fehler
    return retval;
}

The retval array is not typed by the programmer. However, the compiler can recognize from the method header that the array must be of type Int in order to later serve as the return value. Inserting the value 5.001 contradicts this, so the compiler will report an error. Without type inference, this error would only be noticed at runtime and only when the marked line is executed. Due to the if condition, this would only occur after approx. 1000 test runs, i. H. possibly only after the software has been delivered to the customer.

Conditional compiling

A large part of the Haxe code can be run on all target platforms (see section Target platforms ). However, there is often no way around platform-specific adjustments. These can be integrated as follows:

#if flash
    // haXecode für Flash-Plattform (beliebige Version)
    // z.&nbsp;B. wird folgendes ein Quadrat mittels eines Flash-MovieClip-Objektes anzeigen:
    var mc : flash.MovieClip = flash.Lib.current;
    mc.beginFill(0xFF0000);
    mc.moveTo(50,50);
    mc.lineTo(100,50);
    mc.lineTo(100,100);
    mc.lineTo(50,100);
    mc.endFill();
#elseif js
    // haXecode für Javascript-Plattform
    // z.&nbsp;B. Zugriff auf das Browser-DOM um etwas anzuzeigen
#elseif neko
    // haXecode für die neko-Plattform
#error
    // wird automatisch den Fehler "Not implemented on this platform" ausgeben
#end

Enumeration types

Enumerated types are a key function of language. They can have parameters of their own and can be recursive, allowing them to be treated like classes. Enums in Haxe are not just indexed "magic numbers" as in most languages, but are more abstract: They have no value of their own, but can be instantiated, as the following example shows:

    enum Farbe {
        rot;
        gruen;
        blau;
        rgb: ( r : Int, g : Int, b : Int );
    }

    class Farben {
        static function nachInt( c : Farbe ) : Int {
            return switch( c ) {
                case rot: 0xFF000;
                case gruen: 0x00FF00;
                case blau: 0x0000FF;
                case rgb(r,g,b): (r << 16) | (g << 8) | b;
            }
        }
        static function gueltigeAufrufe() {
             var rotint = nachInt(rot);
             var rgbint = nachInt(rgb(100,100,100));
        }
    }
(Aus der Haxe-Referenz, modifiziert)

more details

Function parameters can be defined very precisely in Haxe:

function mehrereParameter(dreidimensionalsArray : Array<Array<Array<Int>>>, stringval : String, boolval : Bool) {}
function optionalerParameter( ?i : Int ) : Int {return 0;} // optional int value returning an int
function funktionAlsParameter( f : Void -> Void ) {f();} // call a function with no parameters
function eineAndereFunktionAlsParameter( f : Int -> Int ) {var result = f(1);} // call a function that returns an int, with an int parameter
function kannAllesMoeglicheSein(d : Dynamic) : Dynamic {return d;} // function which takes any kind of type and returns it

Target platforms

Code written in Haxe is compiled (as opposed to other languages ​​which are interpreted ). You can choose between the following goals:

  • Flash, more precisely:
    • SWF bytecode for AVM 1 (corresponds to Flash 6,7,8)
    • SWF byte code for AVM 2 (corresponds to Flash 9)
    • ActionScript 3.0 source code
  • JavaScript
  • Neko VM
  • C ++ (from version 2.04)
  • PHP (from version 2.0)
  • Java bytecode
  • C # bytecode (experimental)

The otherwise rather unknown Neko deserves special attention: It can be used on the server side (as a standalone server or as an Apache module modneko ). On the other hand, it can also be used directly on the client. To do this, he must install the Neko VM on his computer. With Screenweaver HX it is possible to implement desktop applications using a Haxe, where the logic is implemented in Neko, but the user interface is implemented using Flash.

From version 2.0, PHP is also supported as a server-side language, which is usually pre-installed on web servers, in contrast to the rather unknown Neko VM.

Classes written in Haxe can be used after compilation as SWF in Actionscript code, conversely, compiled Actionscript classes can be used by Haxe code, one can even derive from it.

Libraries and APIs

The language core from Haxe and a number of supplied libraries are available for all target platforms. This includes two different XML APIs (both are available everywhere), regular expressions, exceptions, remoting, reflection, math (trigonometric functions, pseudo random numbers etc.) and the handling of dates and times. As long as a class only makes use of these APIs , it can be compiled for all targets without any modifications. It is irrelevant for the programmer whether these are wrappers (which encapsulate a native library) or whether these are completely implemented in Haxe. Language features from Haxe that are not available in the target language (e.g. interfaces, generics, etc.) do not cause any problems, because they are converted into equivalent code by the compiler.

In addition, Haxe offers full access to the platform-specific APIs. In the case of Flash, this applies to B. MovieClips and graphic filters, with Javascript the interaction with the browser window, and with Neko access to system resources such as local files.

Graphical user interfaces

Haxe enables large parts of the graphical user interface to be implemented with it, but portability clearly reaches its limits here. Without additional software packages, it is not possible to write a single GUI that can run in Flash, HTML / Javascript and as a desktop application at the same time. However, it is possible to write two or three separate GUIs that use the same application core (see Model View Controller ).

Frameworks are currently being developed to describe the GUI once, so that it is displayed equally on the various platforms and represents the same application. For example, jeash makes the classes known from Flash available in JavaScript (using the canvas element from HTML5). Neash does the same for development in C ++ . In this way, Flash-like content can also be made available on mobile platforms such as Android and iPhone.

Rich Internet Applications - Comparison between Haxe and other solutions

Today's rich Internet applications differ from classic websites in that application logic is increasingly being shifted from the server to the client. This allows for faster responses to user input, less traffic and a desktop-like look and feel . Until recently, a large number of programming languages ​​were required to design such RIAs. Haxe and also other current approaches (see end of section) allow working with a single language.

Implementation with multiple languages

Two technologies have long been competing to create RIAs: Ajax and Flash . Although Java applets are the oldest and most mature technology in this area, they have never been able to achieve the importance of Javascript and Flash for the average user. New technologies such as JavaFX , the Flash-based Flex and Microsoft Silverlight are also pushing into this area by introducing new languages ​​( JavaFX Script , MXML and XAML ), which are mostly combined with the already existing ones.

What all the concepts have in common is that the Internet application is distributed: The user interface and time-critical parts of the logic run on the client (within the web browser), the data management and all security-relevant logic is on the server. The communication takes place asynchronously (i.e. unnoticed by the user in the background) using HTTP . In order to make these web applications available offline and without a browser, the user must also run the parts on his computer that were originally outsourced to the server. This is made possible in part by Adobe Integrated Runtime (AIR) and Gears .

Virtually all of the above-mentioned techniques require the developer to be able to master different languages. In extreme cases, these are HTML , CSS , XML , JavaScript , ActionScript and a server-side language such as. B. PHP , Ruby , Perl or Java . In addition, the individual parts also have to work together across languages, for which an XML or text-based interface must be created between them. Working with these languages ​​is made more difficult by the fact that they not only have a different syntax, but often a completely different type system. The object orientation in Javascript is fundamentally different from z. B. the one in Java.

Implementation with Haxe

When developing with Haxe, server, client and possibly desktop components can be written in the same language. In addition, Haxe remoting enables objects and method calls to be sent beyond language and computer limits. So the developer has to

  • only master one programming language ( markup languages ​​such as HTML and CSS may still be necessary)
  • do not decide early on whether a part of the program should run on the client or server side
  • do not decide early on whether to offer the user a Flash or Ajax interface
  • Do not design and implement any textual interfaces between the application levels

Haxe is particularly suitable for multi-layer Internet applications. Due to language features that other languages ​​often lack, Haxe can make development easier even for simple, single-layer applications.

Other approaches with a single language

Both Rich Ajax Platform and Google Web Toolkit allow the developer to develop RIAs while programming both the client and server side in Java. Both generate a servlet and client-side code in Javascript. Unlike Haxe, both offer their own widgets from which HTML pages are automatically generated. In contrast, Haxe requires the developer to generate HTML himself, unless he completely dispenses with the use of HTML. Flash is not supported by these two solutions, but the Rich Ajax Platform can create standalone desktop applications based on SWT.

OpenLaszlo does not only use a single language, because ECMAScript is embedded in the declarative XML dialect LZX. Similar to Haxe, however, OpenLaszlo can also generate a Flash and a DHTML interface from it. In this respect, it is superior to Haxe, as Haxe cannot generate a user interface for its part (see section Graphical User Interfaces above).

Remoting

Haxe makes it possible to send virtually any objects and method calls between the supported platforms. In any case, synchronous and asynchronous connections are available. The procedure is similar to Remote Procedure Call .

Flash objects and Javascripts can communicate with one another within a page, and both can directly access a Neko server. Servers or Neko desktop applications can communicate with one another in the same way. In addition, Flash programs written with haXe can access a Flash Media Server (also AMFPHP ).

The following source code could be used in Flash, Javascript or a second Neko server to call the method myMethod on a Neko server . The return value or an exception thrown there is forwarded to one of the two local callback methods:

// Verbindung zu Neko-Server aufbauen
var verbindung = haxe.remoting.AsyncConnection.urlConnect("http://einedomain.com/neko");

// anonyme Callback-Methode für den Fehlerfall anmelden
verbindung.onError = function(err) { trace("Fehler : "+Std.string(err)); };

// Callback-Methode für den Erfolgsfall
var beiErfolg = function(r) { trace("Rückgabewert : "+Std.string(r)); };

// Methode auf dem Server aufrufen. Entspricht dort dem Aufruf
// mein.package.MeineAndereKlasse.meineMethode(0,1);
verbindung.mein.package.MeineAndereKlasse.meineMethode.call([0,1],beiErfolg);

Other possible uses become conceivable via the HTTP requests to the server that are common with Ajax . A possible application example: An RIA with HTML surface and application logic in Javascript contains a complex calculation. If Flash is available on the user computer, it is delegated to a 1 × 1-pixel Flash object (assuming that Flash bytecode is executed significantly faster than Javascript). If no flash is available, the calculation is carried out on the server. If neither the server nor Flash are available, the calculation runs locally via Javascript. The calculation itself only has to be implemented once in Haxe.

Compiler implementation and performance

The Haxe compiler is implemented in Objective CAML . Since Haxe-generated code runs in virtual machines, no further knowledge of this language is necessary to develop applications with Haxe. This also means that the performance varies depending on the target platform, as each platform has to be adapted so that the available resources can be optimally used.

A benchmark shows that Haxe Flash-9-Bytecode (AVM2) compiles with better performance than the equivalent AS3 code on Adobe's compiler. Since this performance test, the compiler has been improved even further, including: A. by adding inline functionality.

To simplify the translation of several classes for different compilation goals, hxml files are used. These are simple text files with instructions for the compiler. The entire project can be compiled by double-clicking on it.

Since the compiler is a command line application, it can also be integrated into existing development environments. FlashDevelop comes with inherent support for Haxe.

Web links

Individual evidence

  1. MTASC and Actionscript 3 . Accessed January 2, 2011. (English)
  2. Haxe changelog . Retrieved June 5, 2014. (English)
  3. haXe license page . Archived from the original on May 12, 2012. Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. Accessed January 2, 2011. (English) @1@ 2Template: Webachiv / IABot / haxe.org
  4. haXe mailing list contribution to the debate . Archived from the original on March 28, 2007. Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. Accessed January 2, 2011. (English) @1@ 2Template: Webachiv / IABot / lists.motion-twin.com
  5. haXe mailing list contribution to the debate . Archived from the original on February 20, 2011. Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. Accessed January 2, 2011. (English) @1@ 2Template: Webachiv / IABot / lists.motion-twin.com
  6. haXe language reference . Archived from the original on February 25, 2011. Info: The archive link was automatically inserted and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. Accessed January 2, 2011. (English) @1@ 2Template: Webachiv / IABot / haxe.org
  7. haXe language reference about enums . Archived from the original on February 25, 2011. Info: The archive link was automatically inserted and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. Accessed January 2, 2011. (English) @1@ 2Template: Webachiv / IABot / haxe.org
  8. Mailing list article about Java . Archived from the original on February 20, 2011. Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. Accessed January 2, 2011. (English) @1@ 2Template: Webachiv / IABot / lists.motion-twin.com
  9. launchpad.net
  10. code.google.com
  11. Game Haxe Blog , entries for use on Android and iPhone.
  12. Porting the Actionscript Physics Library to haXe . Accessed January 2, 2011. (English)