Haxe Manual
HaxeManual
User Manual:
Open the PDF directly: View PDF
.
Page Count: 208
| Download | |
| Open PDF In Browser | View PDF |
Haxe 3 Manual
Haxe Foundation
September 11, 2018
Contents
1
Introduction
1.1 What is Haxe? . . . . . . . . . . . .
1.2 About this Document . . . . . . . .
1.2.1 Authors and contributions
1.2.2 License . . . . . . . . . . . .
1.3 Hello World . . . . . . . . . . . . .
1.4 History . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
I
Language Reference
2
Types
2.1 Basic Types . . . . . . . . . . . . . . . . . . .
2.1.1 Numeric types . . . . . . . . . . . .
2.1.2 Overflow . . . . . . . . . . . . . . . .
2.1.3 Numeric Operators . . . . . . . . . .
2.1.4 Bool . . . . . . . . . . . . . . . . . . .
2.1.5 Void . . . . . . . . . . . . . . . . . .
2.2 Nullability . . . . . . . . . . . . . . . . . . .
2.2.1 Optional Arguments and Nullability
2.3 Class Instance . . . . . . . . . . . . . . . . .
2.3.1 Class constructor . . . . . . . . . . .
2.3.2 Inheritance . . . . . . . . . . . . . . .
2.3.3 Interfaces . . . . . . . . . . . . . . .
2.4 Enum Instance . . . . . . . . . . . . . . . . .
2.4.1 Enum Constructor . . . . . . . . . .
2.4.2 Using enums . . . . . . . . . . . . .
2.5 Anonymous Structure . . . . . . . . . . . .
2.5.1 JSON for Structure Values . . . . . .
2.5.2 Class Notation for Structure Types .
2.5.3 Optional Fields . . . . . . . . . . . .
2.5.4 Impact on Performance . . . . . . .
2.5.5 Extensions . . . . . . . . . . . . . . .
2.6 Function Type . . . . . . . . . . . . . . . . .
2.6.1 Optional Arguments . . . . . . . . .
2.6.2 Default values . . . . . . . . . . . . .
2.7 Dynamic . . . . . . . . . . . . . . . . . . . .
2.7.1 Dynamic with Type Parameter . . .
2.7.2 Implementing Dynamic . . . . . . .
2.7.3 Dynamic access . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
7
7
8
8
9
9
9
11
1
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
12
13
13
13
14
15
15
16
17
17
18
18
19
20
21
22
22
24
24
24
25
25
26
26
27
28
29
29
30
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
30
31
33
35
37
38
39
40
40
Type System
3.1 Typedef . . . . . . . . . . . . . . . . . . . . . . . .
3.2 Type Parameters . . . . . . . . . . . . . . . . . . .
3.2.1 Constraints . . . . . . . . . . . . . . . . .
3.3 Generic . . . . . . . . . . . . . . . . . . . . . . . .
3.3.1 Construction of generic type parameters
3.4 Variance . . . . . . . . . . . . . . . . . . . . . . .
3.5 Unification . . . . . . . . . . . . . . . . . . . . . .
3.5.1 Between Class/Interface . . . . . . . . . .
3.5.2 Structural Subtyping . . . . . . . . . . . .
3.5.3 Monomorphs . . . . . . . . . . . . . . . .
3.5.4 Function Return . . . . . . . . . . . . . . .
3.5.5 Common Base Type . . . . . . . . . . . .
3.6 Type Inference . . . . . . . . . . . . . . . . . . . .
3.6.1 Top-down Inference . . . . . . . . . . . .
3.6.2 Limitations . . . . . . . . . . . . . . . . .
3.7 Modules and Paths . . . . . . . . . . . . . . . . .
3.7.1 Module Sub-Types . . . . . . . . . . . . .
3.7.2 Import . . . . . . . . . . . . . . . . . . . .
3.7.3 Import defaults / import.hx . . . . . . . .
3.7.4 Resolution Order . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
41
41
42
43
44
45
46
48
49
49
49
49
50
50
51
52
52
53
54
56
56
Class Fields
4.1 Variable . . . . . . . . . . . . . . . . . . . . . . . . .
4.2 Property . . . . . . . . . . . . . . . . . . . . . . . .
4.2.1 Common accessor identifier combinations
4.2.2 Impact on the type system . . . . . . . . . .
4.2.3 Rules for getter and setter . . . . . . . . . .
4.3 Method . . . . . . . . . . . . . . . . . . . . . . . . .
4.3.1 Overriding Methods . . . . . . . . . . . . .
4.3.2 Effects of variance and access modifiers . .
4.4 Access Modifier . . . . . . . . . . . . . . . . . . . .
4.4.1 Visibility . . . . . . . . . . . . . . . . . . . .
4.4.2 Inline . . . . . . . . . . . . . . . . . . . . . .
4.4.3 Dynamic . . . . . . . . . . . . . . . . . . . .
4.4.4 Override . . . . . . . . . . . . . . . . . . . .
4.4.5 Static . . . . . . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
59
59
60
62
63
64
65
66
67
68
68
69
71
71
71
2.8
2.9
3
4
2.7.4 Any type . . . . . . . . . .
Abstract . . . . . . . . . . . . . .
2.8.1 Implicit Casts . . . . . . .
2.8.2 Operator Overloading . .
2.8.3 Array Access . . . . . . .
2.8.4 Enum abstracts . . . . . .
2.8.5 Forwarding abstract fields
2.8.6 Core-type abstracts . . . .
Monomorph . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
2
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
5
6
Expressions
5.1 Blocks . . . . . . . .
5.2 Constants . . . . . .
5.3 Binary Operators .
5.4 Unary Operators .
5.5 Array Declaration .
5.6 Object Declaration
5.7 Field Access . . . .
5.8 Array Access . . . .
5.9 Function Call . . .
5.10 var . . . . . . . . .
5.11 Local Functions . .
5.12 new . . . . . . . . .
5.13 for . . . . . . . . . .
5.14 while . . . . . . . .
5.15 do-while . . . . . .
5.16 if . . . . . . . . . . .
5.17 switch . . . . . . . .
5.18 try/catch . . . . . .
5.19 return . . . . . . . .
5.20 break . . . . . . . .
5.21 continue . . . . . .
5.22 throw . . . . . . . .
5.23 cast . . . . . . . . .
5.23.1 unsafe cast .
5.23.2 safe cast . .
5.24 type check . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
72
74
75
76
76
76
76
76
77
77
77
78
78
78
79
80
80
81
81
82
82
82
83
83
83
84
84
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Language Features
6.1 Conditional Compilation . . . . . . .
6.2 Externs . . . . . . . . . . . . . . . . .
6.3 Static Extension . . . . . . . . . . . .
6.3.1 In the Haxe Standard Library
6.4 Pattern Matching . . . . . . . . . . .
6.4.1 Introduction . . . . . . . . . .
6.4.2 Enum matching . . . . . . . .
6.4.3 Variable capture . . . . . . . .
6.4.4 Structure matching . . . . . .
6.4.5 Array matching . . . . . . . .
6.4.6 Or patterns . . . . . . . . . .
6.4.7 Guards . . . . . . . . . . . . .
6.4.8 Match on multiple values . .
6.4.9 Extractors . . . . . . . . . . .
6.4.10 Exhaustiveness checks . . . .
6.4.11 Useless pattern checks . . . .
6.4.12 Single pattern check . . . . .
6.5 String Interpolation . . . . . . . . . .
6.6 Array Comprehension . . . . . . . .
6.7 Map Comprehension . . . . . . . . .
6.8 Iterators . . . . . . . . . . . . . . . .
6.9 Function Bindings . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
85
. 88
. 89
. 91
. 91
. 92
. 92
. 93
. 93
. 94
. 94
. 95
. 95
. 95
. 95
. 97
. 97
. 98
. 98
. 99
. 100
. 101
. 102
3
6.10 Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
6.11 Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
6.12 Inline Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
II
Compiler Reference
108
7
Compiler Usage
109
7.1 HXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.2 Global Compiler Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
8
Compiler Features
8.1 Built-in Compiler Metadata . . . .
8.2 Dead Code Elimination . . . . . . .
8.3 Compiler Services . . . . . . . . . .
8.3.1 Overview . . . . . . . . . .
8.3.2 Field access completion . .
8.3.3 Call argument completion .
8.3.4 Type path completion . . .
8.3.5 Usage completion . . . . . .
8.3.6 Position completion . . . .
8.3.7 Top-level completion . . . .
8.3.8 Completion server . . . . .
8.4 Resources . . . . . . . . . . . . . . .
8.4.1 Embedding resources . . .
8.4.2 Retrieving text resources . .
8.4.3 Retrieving binary resources
8.4.4 Implementation details . .
8.5 Runtime Type Information . . . . .
8.5.1 RTTI structure . . . . . . . .
8.6 Static Analyzer . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
116
116
120
121
121
122
123
124
126
126
127
128
129
129
129
130
130
130
131
133
Macros
9.1 Macro Context . . . . . . . . .
9.2 Arguments . . . . . . . . . . .
9.2.1 ExprOf . . . . . . . . .
9.2.2 Constant Expressions
9.2.3 Rest Argument . . . .
9.3 Reification . . . . . . . . . . .
9.3.1 Expression Reification
9.3.2 Type Reification . . . .
9.3.3 Class Reification . . .
9.4 Tools . . . . . . . . . . . . . .
9.5 Type Building . . . . . . . . .
9.5.1 Enum building . . . .
9.5.2 @:autoBuild . . . . . .
9.5.3 @:genericBuild . . . .
9.6 Limitations . . . . . . . . . . .
9.6.1 Macro-in-Macro . . . .
9.6.2 Static extension . . . .
9.6.3 Build Order . . . . . .
9.6.4 Type Parameters . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
134
135
136
136
137
137
138
138
138
139
139
140
141
142
143
145
145
145
146
146
9
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
4
9.7
III
Initialization Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Standard Library
10 Standard Library
10.1 String . . . . . . . . . . . . . . . .
10.2 Data Structures . . . . . . . . . .
10.2.1 Array . . . . . . . . . . . .
10.2.2 Vector . . . . . . . . . . .
10.2.3 List . . . . . . . . . . . . .
10.2.4 GenericStack . . . . . . .
10.2.5 Map . . . . . . . . . . . .
10.2.6 Option . . . . . . . . . . .
10.3 Regular Expressions . . . . . . .
10.3.1 Matching . . . . . . . . . .
10.3.2 Groups . . . . . . . . . . .
10.3.3 Replace . . . . . . . . . . .
10.3.4 Split . . . . . . . . . . . .
10.3.5 Map . . . . . . . . . . . .
10.3.6 Implementation Details .
10.4 Math . . . . . . . . . . . . . . . .
10.4.1 Special Numbers . . . . .
10.4.2 Mathematical Errors . . .
10.4.3 Integer Math . . . . . . .
10.4.4 Extensions . . . . . . . . .
10.5 Lambda . . . . . . . . . . . . . . .
10.6 Template . . . . . . . . . . . . . .
10.7 Reflection . . . . . . . . . . . . . .
10.8 Serialization . . . . . . . . . . . .
10.8.1 Serialization format . . .
10.9 Xml . . . . . . . . . . . . . . . . .
10.9.1 Getting started with Xml
10.9.2 Parsing Xml . . . . . . . .
10.9.3 Encoding Xml . . . . . . .
10.10Json . . . . . . . . . . . . . . . . .
10.10.1 Parsing JSON . . . . . . .
10.10.2 Encoding JSON . . . . . .
10.10.3 Implementation details .
10.11Input/Output . . . . . . . . . . .
10.12Sys/sys . . . . . . . . . . . . . . .
10.13Remoting . . . . . . . . . . . . . .
10.13.1 Remoting Connection . .
10.13.2 Implementation details .
10.14Unit Testing . . . . . . . . . . . .
IV
148
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Miscellaneous
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
149
149
149
149
151
151
152
153
154
155
156
156
157
157
158
158
158
159
159
159
159
160
162
164
166
168
169
170
171
171
171
171
172
172
172
172
172
173
174
175
178
11 Haxelib
179
5
12 Target Details
12.1 JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . .
12.1.1 Getting started with Haxe/JavaScript . . . . . .
12.1.2 Using external JavaScript libraries . . . . . . . .
12.1.3 Using Untyped JavaScript . . . . . . . . . . . . .
12.1.4 JavaScript untyped functions . . . . . . . . . . .
12.1.5 JavaScript target Metadata . . . . . . . . . . . . .
12.1.6 Exposing Haxe classes for JavaScript . . . . . . .
12.1.7 Loading extern classes using ”require” function
12.2 Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.2.1 Getting started with Haxe/Flash . . . . . . . . .
12.2.2 Embedding resources . . . . . . . . . . . . . . .
12.2.3 Using external Flash libraries . . . . . . . . . . .
12.2.4 Flash target Metadata . . . . . . . . . . . . . . .
12.3 Neko . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4 PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4.1 Getting started with Haxe/PHP . . . . . . . . .
12.4.2 PHP untyped functions . . . . . . . . . . . . . .
12.5 C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.5.1 Getting started with Haxe/C++ . . . . . . . . .
12.5.2 The Hxcpp Build Environment . . . . . . . . . .
12.5.3 build.xml File Format . . . . . . . . . . . . . . .
12.5.4 Using C++ Defines . . . . . . . . . . . . . . . . .
12.5.5 Using C++ Pointers . . . . . . . . . . . . . . . . .
12.6 Cppia . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.6.1 Getting started with Haxe/Cppia . . . . . . . .
12.7 Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7.1 Getting started with Haxe/Java . . . . . . . . . .
12.8 C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8.1 Getting started with Haxe/C# . . . . . . . . . .
12.8.2 .NET version and external libraries . . . . . . . .
12.8.3 Haxe/C# Defines . . . . . . . . . . . . . . . . . .
12.8.4 Haxe/C# Metadata . . . . . . . . . . . . . . . . .
12.8.5 Injecting raw C# code . . . . . . . . . . . . . . .
12.9 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.10Lua . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.10.1 Getting started with Haxe/Lua . . . . . . . . . .
12.10.2 Using external Lua libraries . . . . . . . . . . . .
12.10.3 Version flags . . . . . . . . . . . . . . . . . . . . .
12.10.4 Multireturns . . . . . . . . . . . . . . . . . . . . .
12.11HashLink . . . . . . . . . . . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
180
180
180
181
183
184
185
185
187
187
187
188
189
189
190
190
190
190
191
191
192
193
194
197
197
197
197
197
198
198
199
200
200
200
201
201
201
202
202
202
203
13 Debugging
13.1 Logging and Trace . . . . . . . .
13.2 Position Information Parameter .
13.3 Tracing Types . . . . . . . . . . .
13.4 Debugging in JavaScript . . . . .
13.5 Source Maps . . . . . . . . . . . .
13.5.1 Source Maps in JavaScript
13.5.2 Source Maps in Php7 . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
204
204
205
205
205
206
206
207
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
6
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Chapter 1
Introduction
1.1
What is Haxe?
Haxe consists of a high-level, open source programming language and a compiler. It allows
compilation of programs, written using an ECMAScript1 -oriented syntax, to multiple target languages. Employing proper abstraction, it is possible to maintain a single code-base which compiles to multiple targets.
Haxe is strongly typed but the typing system can be subverted where required. Utilizing
type information, the Haxe type system can detect errors at compile-time which would only be
noticeable at run-time in the target language. Furthermore, type information can be used by the
target generators to generate optimized and robust code.
Currently, there are nine supported target languages which allow for different use-cases:
Name
JavaScript
Neko
HashLink
PHP
Python
Lua
C++
ActionScript 3
Flash
Java
C#
Output type
Sourcecode
Bytecode
Bytecode
Sourcecode
Sourcecode
Sourcecode
Sourcecode
Sourcecode
Bytecode
Sourcecode
Sourcecode
Main usages
Browser, Desktop, Mobile, Server
Desktop, Server, CLI
Desktop, Mobile, Game consoles
Server
Desktop, Server
Desktop, Scripting
Desktop, Mobile, Server, Game consoles
Desktop, Mobile
Desktop, Mobile
Desktop, Mobile, Server
Desktop, Mobile, Server
The remainder of section 1 gives a brief overview of what a Haxe program looks like and how
Haxe evolved since its inception in 2005.
Types (Chapter 2) introduces the seven different kinds of types in Haxe and how they interact
with each other. The discussion of types is continued in Type System (Chapter 3), where features
like unification, type parameters and type inference are explained.
Class Fields (Chapter 4) is all about the structure of Haxe classes and, among other topics,
deals with properties, inline fields and generic functions.
In Expressions (Chapter 5) we see how to actually get programs to do something by using
expressions.
1 http://www.ecma-international.org/publications/standards/Ecma-327.htm
7
Language Features (Chapter 6) describes some of the Haxe features in detail such as pattern
matching, string interpolation and dead code elimination. This concludes the Haxe language reference.
We continue with the Haxe compiler reference, which first handles the basics in Compiler
Usage (Chapter 7) before getting into the advanced features in Compiler Features (Chapter 8).
Finally, we will venture into the exciting land of haxe macros in Macros (Chapter 9) to see how
some common tasks can be greatly simplified.
In the following chapter, Standard Library (Chapter 10), we explore important types and
concepts from the Haxe Standard Library. We then learn about Haxe’s package manager Haxelib
in Haxelib (Chapter 11).
Haxe abstracts away many target differences, but sometimes it is important to interact with a
target directly, which is the subject of Target Details (Chapter 12).
1.2
About this Document
This document is the official manual for Haxe 3. As such, it is not a beginner’s tutorial and does
not teach programming. However, the topics are roughly designed to be read in order and there
are references to topics “previously seen” and topics “yet to come”. In some cases, an earlier
section makes use of the information of a later section if it simplifies the explanation. These
references are linked accordingly and it should generally not be a problem to read ahead on
other topics.
We use a lot of Haxe source code to keep a practical connection of theoretical matters. These
code examples are often complete programs that come with a main function and can be compiled
as-is. However, sometimes only the most important parts are shown. Source code looks like this:
1
Haxe code here
Occasionally, we demonstrate how Haxe code is generated, for which we usually show the
JavaScript target.
Furthermore, we define a set of terms in this document. Predominantly, this is done when
introducing a new type or when a term is specific to Haxe. We do not define every new aspect
we introduce, e.g. what a class is, to avoid cluttering the text. A definition looks like this:
Definition: Definition name
Definition description
In a few places, this document has trivia-boxes. These include off-the-record information such
as why certain decisions were made during Haxe’s development or how a particular feature has
been changed in past Haxe versions. This information is generally not important and can be
skipped as it is only meant to convey trivia:
Trivia: About Trivia
This is trivia.
1.2.1
Authors and contributions
Most of this document’s content was written by Simon Krajewski while working for the Haxe
Foundation. We would like to thank these people for their contributions:
8
• Dan Korostelev: Additional content and editing
• Caleb Harper: Additional content and editing
• Josefiene Pertosa: Editing
• Miha Lunar: Editing
• Nicolas Cannasse: Haxe creator
1.2.2
License
The Haxe Manual by Haxe Foundation is licensed under a Creative Commons Attribution 4.0
International License.
Based on a work at github.com/HaxeFoundation/HaxeManual.
1.3
Hello World
The following program prints “Hello World” after being compiled and run:
1
2
3
4
5
class Main {
static public function main():Void {
trace("Hello World");
}
}
This can be tested by saving the above code to a file named Main.hx and invoking the Haxe
Compiler like so: haxe -main Main --interp. It then generates the following output: Main.hx:3:
Hello world. There are several things to learn from this:
• Haxe programs are saved in files with an extension of .hx.
• The Haxe Compiler is a command-line tool which can be invoked with parameters such as
-main Main and --interp.
• Haxe programs have classes (Main, upper-case), which have functions (main, lower-case).
• The name of the file containing main Haxe class is the same as name of the class itself (in
this case Main.hx).
Related content
• Beginner tutorials and examples in the Haxe Code Cookbook.
1.4
History
The Haxe project was started on 22 October 2005 by French developer Nicolas Cannasse as a successor to the popular open-source ActionScript 2 compiler MTASC (Motion-Twin Action Script
Compiler) and the in-house MTypes language, which experimented with the application of type
inference to an object oriented language. Nicolas’ long-time passion for programming language
design and the rise of new opportunities to mix different technologies as part of his game developer work at Motion-Twin led to the creation of a whole new language.
Being spelled haXe back then, its beta version was released in February 2006 with the first
supported targets being AVM2 -bytecode and Nicolas’ own Neko virtual machine3 .
2 Adobe
Virtual Machine
3 http://nekovm.org
9
Nicolas Cannasse, who remains leader of the Haxe project to this date, kept on designing
Haxe with a clear vision, subsequently leading to the Haxe 1.0 release in May 2006. This first
major release came with support for JavaScript code generation and already had some of the
features that define Haxe today such as type inference and structural sub-typing.
Haxe 1 saw several minor releases over the course of two years, adding the Flash AVM2 target
along with the haxelib-tool in August 2006 and the ActionScript 3 target in March 2007. During
these months, there was a strong focus on improving stability, which resulted in several minor
bug-fix releases.
Haxe 2.0 was released in July 2008, including the PHP target, courtesy of Franco Ponticelli. A
similar effort by Hugh Sanderson lead to the addition of the C++ target in July 2009 with the Haxe
2.04 release.
Just as with Haxe 1, what followed were several months of stability releases. In January 2011,
Haxe 2.07 was released with the support of macros. Around that time, Bruno Garcia joined the
team as maintainer of the JavaScript target, which saw vast improvements in the subsequent
2.08 and 2.09 releases.
After the release of 2.09, Simon Krajewski joined the team and work towards Haxe 3 began.
Furthermore, Cauê Waneck’s Java and C# targets found their way into the Haxe builds. It was
then decided to make one final Haxe 2 release, which happened in July 2012 with the release of
Haxe 2.10.
In late 2012, the Haxe 3 switch was flipped and the Haxe Compiler team, now backed by the
newly established Haxe Foundation4 , focused on this next major version. Haxe 3 was subsequently
released in May 2013.
4 http://haxe-foundation.org
10
Part I
Language Reference
11
Chapter 2
Types
The Haxe Compiler employs a rich type system which helps detecting type-related errors in a
program at compile-time. A type error is an invalid operation on a given type such as dividing
by a String, trying to access a field of an Integer or calling a function with not enough (or too
many) arguments.
In some languages this additional safety comes at a price because programmers are forced to
explicitly assign types to syntactic constructs:
1
var myButton:MySpecialButton = new MySpecialButton(); // As3
1
MySpecialButton* myButton = new MySpecialButton(); // C++
The explicit type annotations are not required in Haxe, because the compiler can infer the type:
1
var myButton = new MySpecialButton(); // Haxe
We will explore type inference in detail later in Type Inference (Section 3.6). For now, it is sufficient to say that the variable myButton in the above code is known to be an instance of class
MySpecialButton.
The Haxe type system knows seven type groups:
Class instance: an object of a given class or interface
Enum instance: a value of a Haxe enumeration
Structure: an anonymous structure, i.e. a collection of named fields
Function: a compound type of several arguments and one return
Dynamic: a wildcard type which is compatible with any type
Abstract: a compile-time type which is represented by a different type at runtime
Monomorph: an unknown type which may later become a different type
We will describe each of these type groups and how they relate to each other in the next
chapters.
12
Definition: Compound Type
A compound type is a type which has sub-types. This includes any type with type parameters
(3.2) and the function (2.6) type.
2.1
Basic Types
Basic types are Bool, Float and Int. They can easily be identified in the syntax by values such
as
• true and false for Bool,
• 1, 0, -1 and 0xFF0000 for Int and
• 1.0, 0.0, -1.0, 1e10 for Float.
Basic types are not classes (2.3) in Haxe. They are implemented as abstract types (2.8) and are
tied to the compiler’s internal operator-handling as described in the following sections.
2.1.1
Numeric types
Type: Float
Represents a double-precision IEEE 64-bit floating point number.
Type: Int
Represents an integral number.
While every Int can be used where a Float is expected (that is, Int is assignable to or unifies
with Float), the reverse is not true: Assigning a Float to an Int might lose precision and is not
allowed implicitly.
2.1.2
Overflow
For performance reasons, the Haxe Compiler does not enforce any overflow behavior. The burden of checking for overflows falls to the target platform. Here are some platform specific notes
on overflow behavior:
C++, Java, C#, Neko, Flash: 32-bit signed integers with usual overflow practices
PHP, JS, Flash 8: No native Int type, loss of precision will occur if they reach their float limit (252 )
Alternatively, the haxe.Int32 and haxe.Int64 classes can be used to ensure correct overflow
behavior regardless of the platform at the cost of additional computations depending on the
platform.
13
2.1.3
Numeric Operators
This the list of numeric operators in Haxe, grouped by descending priority.
Operator
++
-+
-
*
/
%
Operator
==
!=
<
<=
>
>=
Operator
˜
&
|
ˆ
<<
>>
>>>
Arithmetic
Operand 1
Int
Float
decrement
Int
Float
addition
Float
Float
Int
Int
subtraction
Float
Float
Int
Int
multiplication
Float
Float
Int
Int
division
Float
Float
Int
Int
modulo
Float
Float
Int
Int
Comparison
Operation
Operand 1
equal
Float/Int
not equal
Float/Int
less than
Float/Int
less than or equal
Float/Int
greater than
Float/Int
great than or equal
Float/Int
Bitwise
Operation
Operand 1
bitwise negation
Int
bitwise and
Int
bitwise or
Int
bitwise xor
Int
shift left
Int
shift right
Int
unsigned shift right Int
Operation
increment
Operand 2
N/A
N/A
N/A
N/A
Float
Int
Float
Int
Float
Int
Float
Int
Float
Int
Float
Int
Float
Int
Float
Int
Float
Int
Float
Int
Return
Int
Float
Int
Float
Float
Float
Float
Int
Float
Float
Float
Int
Float
Float
Float
Int
Float
Float
Float
Float
Float
Float
Float
Int
Operand 2
Float/Int
Float/Int
Float/Int
Float/Int
Float/Int
Float/Int
Return
Bool
Bool
Bool
Bool
Bool
Bool
Operand 2
N/A
Int
Int
Int
Int
Int
Int
Return
Int
Int
Int
Int
Int
Int
Int
Equality For enums:
Enum without parameters Are always represent the same value, so MyEnum.A == MyEnum.A.
Enum with parameters Can be compared with a.equals(b) (which is a short for Type.enumEquals()).
14
Dynamic: Comparison involving at least one Dynamic value is unspecifed and platformspecific.
2.1.4
Bool
Type: Bool
Represents a value which can be either true or false.
Values of type Bool are a common occurrence in conditions such as if (5.16) and while (5.14).
The following operators accept and return Bool values:
• && (and)
• || (or)
• ! (not)
Haxe guarantees that compound boolean expressions are evaluated from left to right and
only as far as necessary at run-time. For instance, an expression like A && B will evaluate A first
and evaluate B only if the evaluation of A yielded true. Likewise, the expressions A || B will
not evaluate B if the evaluation of A yielded true, because the value of B is irrelevant in that
case. This is important in cases such as this:
1
if (object != null && object.field == 1) { }
Accessing object.field if object is null would lead to a run-time error, but the check
for object != null guards against it.
2.1.5
Void
Type: Void
Void denotes the absence of a type. It is used to express that something (usually a function)
has no value.
Void is a special case in the type system because it is not actually a type. It is used to express
the absence of a type, which applies mostly to function arguments and return types. We have
already “seen” Void in the initial “Hello World” example:
1
2
3
4
5
class Main {
static public function main():Void {
trace("Hello World");
}
}
The function type will be explored in detail in the section Function Type (Section 2.6) but a
quick preview helps here: The type of the function main in the example above is Void->Void,
which reads as “it has no arguments and returns nothing”. Haxe does not allow fields and
variables of type Void and will complain if an attempt at declaring such is made:
1
2
// Arguments and variables of type Void are not allowed
var x:Void;
15
2.2
Nullability
Definition: nullable
A type in Haxe is considered nullable if null is a valid value for it.
It is common for programming languages to have a single, clean definition for nullability. However, Haxe has to find a compromise in this regard due to the nature of Haxe’s target languages:
While some of them allow and; in fact, default to null for anything, others do not even allow
null for certain types. This necessitates the distinction of two types of target languages:
Definition: Static target
Static targets employ their own type system where null is not a valid value for basic types.
This is true for the Flash, C++, Java and C# targets.
Definition: Dynamic target
Dynamic targets are more lenient with their types and allow null values for basic types.
This applies to the JavaScript, PHP, Neko and Flash 6-8 targets.
There is nothing to worry about when working with null on dynamic targets; however, static
ones may require some thought. For starters, basic types are initialized to their default values.
Definition: Default values
Basic types have the following default values on static targets:
Int: 0
Float: NaN on Flash, 0.0 on other static targets
Bool: false
As a consequence, the Haxe Compiler does not allow the assignment of null to a basic type
on static targets. In order to achieve this, the basic type has to be wrapped as Null:
1
2
3
// error on static platforms
var a:Int = null;
var b:Null = null; // allowed
Similarly, basic types cannot be compared to null unless wrapped:
1
2
3
4
5
var a : Int = 0;
// error on static platforms
if( a == null ) { ... }
var b : Null = 0;
if( b != null ) { ... } // allowed
This restriction extends to all situations where unification (3.5) is performed.
16
Type: Null
On static targets the types Null, Null and Null can be used to
allow null as a value. On dynamic targets this has no effect. Null can also be used with
other types in order to document that null is an allowed value.
If a null-value is “hidden” in Null or Dynamic and assigned to a basic type, the default
value is used:
var n : Null = null;
var a : Int = n;
3 trace(a); // 0 on static platforms
1
2
2.2.1
Optional Arguments and Nullability
Optional arguments also have to be accounted for when considering nullability.
In particular, there must be a distinction between native optional arguments which are not
nullable and Haxe-specific optional arguments which might be. The distinction is made by using
the question-mark optional argument:
1
2
3
4
5
6
// x is a native Int (not nullable)
function foo(x : Int = 0) {}
// y is Null (nullable)
function bar( ?y : Int) {}
// z is also Null
function opt( ?z : Int = -1) {}
Trivia: Argument vs. Parameter
In some other programming languages, argument and parameter are used interchangeably. In
Haxe, argument is used when referring to methods and parameter refers to Type Parameters
(Section 3.2).
2.3
Class Instance
Similar to many object-oriented languages, classes are the primary data structure for the majority
of programs in Haxe. Each Haxe class has an explicit name, an implied path and zero or more
class fields. Here we will focus on the general structure of classes and their relations, while
leaving the details of class fields for Class Fields (Chapter 4).
The following code example serves as basis for the remainder of this section:
class Point {
var x : Int;
var y : Int;
public function new(x,y) {
this.x = x;
6
this.y = y;
7
}
8
public function toString() {
1
2
3
4
5
17
9
10
11
return "Point("+x+","+y+")";
}
}
Semantically, this class represents a point in discrete 2-dimensional space - but this is not
important here. Let us instead describe the structure:
• The keyword class denotes that we are declaring a class.
• Point is the name of the class and could be anything conforming to the rules for type
identifiers (5).
• Enclosed in curly braces {} are the class fields,
• Which consist of two variable fields x and y of type Int,
• followed by a special function field named new, which is the constructor of the class,
• as well as a normal function toString.
There is a special type in Haxe which is compatible with all classes:
Type: Class
This type is compatible with all class types which means that all classes (not their instances)
can be assigned to it. At compile-time, Class is the common base type of all class types.
However, this relation is not reflected in generated code.
This type is useful when an API requires a value to be a class, but not a specific one. This
applies to several methods of the Haxe reflection API (10.7).
2.3.1
Class constructor
Instances of classes are created by calling the class constructor - a process commonly referred to
as instantiation. Another name for class instances is object. Nevertheless, we prefer the term class
instance to emphasize the analogy between classes/class instances and enums/enum instances
(2.4).
1
var p = new Point(-1, 65);
This will yield an instance of class Point, which is assigned to a variable named p. The constructor of Point receives the two arguments -1 and 65 and assigns them to the instance variables x
and y respectively (compare its definition in Class Instance (Section 2.3)). We will revisit the exact meaning of the new expression later in the section 5.12. For now, we just think of it as calling
the class constructor and returning the appropriate object.
2.3.2
Inheritance
Classes may inherit from other classes, which in Haxe is denoted by the extends keyword:
class Point3 extends Point {
var z : Int;
public function new(x,y,z) {
super(x,y);
5
this.z = z;
6
}
7 }
1
2
3
4
18
This relation is often described as ”is-a”: Any instance of class Point3 is also an instance of
Point. Point is then known as the parent class of Point3, which is a child class of Point. A
class may have many child classes, but only one parent class. The term “a parent class of class
X” usually refers to its direct parent class, the parent class of its parent class and so on.
The code above is very similar to the original Point class, with two new constructs being
shown:
• extends Point denotes that this class inherits from class Point
• super(x, y) is the call to the constructor of the parent class, in this case Point.new
It is not necessary for child classes to define their own constructors, but if they do, a call to
super() is mandatory. Unlike some other object-oriented languages, this call can appear anywhere in the constructor code and does not have to be the first expression.
A class may override methods (4.3) of its parent class, which requires the explicit override
keyword. The effects and restrictions of this are detailed in Overriding Methods (Section 4.3.1).
2.3.3
Interfaces
An interface can be understood as the signature of a class because it describes the public fields of
a class. Interfaces do not provide implementations but pure structural information:
1
2
3
interface Printable {
public function toString():String;
}
The syntax is similar to classes, with the following exceptions:
• interface keyword is used instead of class keyword
• functions do not have any expressions (5)
• every field must have an explicit type
Interfaces, unlike structural subtyping (3.5.2), describe a static relation between classes. A given
class is only considered to be compatible to an interface if it explicitly states so:
1
class Point implements Printable { }
Here, the implements keyword denotes that Point has a ”is-a” relationship to Printable,
i.e. each instance of Point is also an instance of Printable. While a class may only have one
parent class, it may implement multiple interfaces through multiple implements keywords:
1
2
class Point implements Printable
implements Serializable
The compiler checks if the implements assumption holds. That is, it makes sure the class actually does implement all the fields required by the interface. A field is considered implemented
if the class or any of its parent classes provide an implementation.
Interface fields are not limited to methods. They can be variables and properties as well:
1
2
3
interface Placeable {
public var x:Float;
public var y:Float;
19
4
5
6
7
8
9
}
class Main implements Placeable {
public var x:Float;
public var y:Float;
static public function main() { }
10 }
Interfaces can extend multiple other interfaces using the extends keyword:
1
interface Debuggable extends Printable extends Serializable
Trivia: Implements Syntax
Haxe versions prior to 3.0 required multiple implements keywords to be separated by a
comma. We decided to adhere to the de-facto standard of Java and got rid of the comma.
This was one of the breaking changes between Haxe 2 and 3.
2.4
Enum Instance
Haxe provides powerful enumeration (short: enum) types, which are actually an algebraic data
type (ADT)1 . While they cannot have any expressions (5), they are very useful for describing data
structures:
1
2
3
4
5
6
enum Color {
Red;
Green;
Blue;
Rgb(r:Int, g:Int, b:Int);
}
Semantically, this enum describes a color which is either red, green, blue or a specified RGB
value. The syntactic structure is as follows:
• The keyword enum denotes that we are declaring an enum.
• Color is the name of the enum and could be anything conforming to the rules for type
identifiers (5).
• Enclosed in curly braces {} are the enum constructors,
• which are Red, Green and Blue taking no arguments,
• as well as Rgb taking three Int arguments named r, g and b.
The Haxe type system provides a type which unifies with all enum types:
Type: Enum
This type is compatible with all enum types. At compile-time, Enum can be seen as the
common base type of all enum types. However, this relation is not reflected in generated
code.
1 http://en.wikipedia.org/wiki/Algebraic_data_type
20
2.4.1
Enum Constructor
Similar to classes and their constructors, enums provide a way of instantiating them by using
one of their constructors. However, unlike classes, enums provide multiple constructors which
can easily be used through their name:
1
2
3
var a = Red;
var b = Green;
var c = Rgb(255, 255, 0);
In this code the type of variables a, b and c is Color. Variable c is initialized using the Rgb
constructor with arguments.
All enum instances can be assigned to a special type named EnumValue.
Type: EnumValue
EnumValue is a special type which unifies with all enum instances. It is used by the Haxe
Standard Library to provide certain operations for all enum instances and can be employed
in user-code accordingly in cases where an API requires an enum instance, but not a specific
one.
It is important to distinguish enum types and enum constructors, as this example demonstrates:
1
2
3
4
5
6
7
8
enum Color {
Red;
Green;
Blue;
Rgb(r:Int, g:Int, b:Int);
}
class Main {
static public function main() {
var ec:EnumValue = Red; // valid
var en:Enum = Color; // valid
// Error: Color should be Enum
//var x:Enum = Red;
}
15 }
9
10
11
12
13
14
If the commented line is uncommented, the program does not compile because Red (an enum
constructor) cannot be assigned to a variable of type Enum (an enum type). The relation
is analogous to a class and its instance.
Trivia: Concrete type parameter for Enum
One of the reviewers of this manual was confused about the difference between Color and
Enum in the example above. Indeed, using a concrete type parameter there is pointless and only serves the purpose of demonstration. Usually we would omit the type there
and let type inference (3.6) deal with it.
However, the inferred type would be different from Enum. The compiler infers a
pseudo-type which has the enum constructors as “fields”. As of Haxe 3.2.0, it is not possible
to express this type in syntax but also, it is never necessary to do so.
21
2.4.2
Using enums
Enums are a good choice if only a finite set of values should be allowed. The individual constructors (2.4.1) then represent the allowed variants and enable the compiler to check if all possible
values are respected. This can be seen here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
enum Color {
Red;
Green;
Blue;
Rgb(r:Int, g:Int, b:Int);
}
class Main {
static function main() {
var color = getColor();
switch (color) {
case Red: trace("Color was red");
case Green: trace("Color was green");
case Blue: trace("Color was blue");
case Rgb(r, g, b): trace("Color had a red value of " +r);
}
}
static function getColor():Color {
return Rgb(255, 0, 255);
}
}
After retrieving the value of color by assigning the return value of getColor() to it, a
switch expression (5.17) is used to branch depending on the value. The first three cases Red,
Green and Blue are trivial and correspond to the constructors of Color that have no arguments.
The final case Rgb(r, g, b) shows how the argument values of a constructor can be extracted:
they are available as local variables within the case body expression, just as if a var expression
(5.10) had been used.
Advanced information on using the switch expression will be explored later in the section
on pattern matching (6.4).
2.5
Anonymous Structure
Anonymous structures can be used to group data without explicitly creating a type. The following example creates a structure with two fields x and name, and initializes their values to 12 and
"foo" respectively:
class Main {
static public function main() {
var myStructure = { x: 12, name: "foo"};
}
5 }
1
2
3
4
The general syntactic rules follow:
1. A structure is enclosed in curly braces {} and
22
2. Has a comma-separated list of key-value-pairs.
3. A colon separates the key, which must be a valid identifier (5), from the value.
4. The value can be any Haxe expression.
Rule 4 implies that structures can be nested and complex, e.g.:
1
2
3
4
5
6
7
8
var user = {
name : "Nicolas",
age : 32,
pos : [
{ x : 0, y : 0 },
{ x : 1, y : -1 }
],
};
Fields of structures, like classes, are accessed using a dot (.) like so:
1
2
3
4
// get value of name, which is "Nicolas"
user.name;
// set value of age to 33
user.age = 33;
It is worth noting that using anonymous structures does not subvert the typing system. The
compiler ensures that only available fields are accessed, which means the following program
does not compile:
1
2
3
4
5
6
7
class Test {
static public function main() {
var point = { x: 0.0, y: 12.0 };
// { y : Float, x : Float } has no field z
point.z;
}
}
The error message indicates that the compiler knows the type of point: It is a structure with
fields x and y of type Float. Since it has no field z, the access fails. The type of point is
known through type inference (3.6), which thankfully saves us from using explicit types for local
variables. However, if point was a field, explicit typing would be necessary:
1
2
3
4
5
class Path {
var start : { x : Int, y : Int };
var target : { x : Int, y : Int };
var current : { x : Int, y : Int };
}
To avoid this kind of redundant type declaration, especially for more complex structures, it is
advised to use a typedef (3.1):
1
2
typedef Point = { x : Int, y : Int }
23
3
4
5
6
7
class Path {
var start : Point;
var target : Point;
var current : Point;
}
You may also use Extensions (2.5.5) to “inherit” fields from other structures.
1
typedef Point3 = { > Point, z : Int }
2.5.1
JSON for Structure Values
It is also possible to use JavaScript Object Notation for structures by using string literals for the
keys:
1
var point = { "x" : 1, "y" : -5 };
While any string literal is allowed, the field is only considered part of the type if it is a valid Haxe
identifier (5). Otherwise, Haxe syntax does not allow expressing access to such a field, and reflection (10.7) has to be employed through the use of Reflect.field and Reflect.setField.
2.5.2
Class Notation for Structure Types
When defining a structure type, Haxe allows using the same syntax as described in Class Fields
(Chapter 4). The following typedef (3.1) declares a Point type with variable fields x and y of
type Int:
typedef Point = {
var x : Int;
3
var y : Int;
4 }
1
2
2.5.3
Optional Fields
Fields of a structure type can be made optional. In the standard notation, this is achieved by
prefixing the field name with a ?:
1
2
3
4
5
typedef User = {
age : Int,
name : String,
?phoneNumber : String
}
In class notation, the @:optional metadata can be used instead:
1
2
3
4
5
typedef User = {
var age : Int;
var name : String;
@:optional var phoneNumber : String;
}
24
2.5.4
Impact on Performance
Using structures and, by extension, structural subtyping (3.5.2) has no impact on performance
when compiling to dynamic targets (2.2). However, on static targets (2.2) a dynamic lookup has
to be performed which is typically slower than a static field access.
2.5.5
Extensions
Extensions are used to express that a structure has all the fields of a given type as well as some
additional fields of its own:
1
2
3
4
5
6
7
8
9
10
11
12
typedef IterableWithLength = {
> Iterable,
// read only property
var length(default, null):Int;
}
class Main {
static public function main() {
var array = [1, 2, 3];
var t:IterableWithLength = array;
}
}
The greater-than operator > denotes that an extension of Iterable is being created, with
the additional class fields following. In this case, a read-only property (4.2) length of type Int
is required.
In order to be compatible with IterableWithLength, a type then must be compatible
with Iterable and also provide a read-only length property of type Int. The example
assigns an Array, which happens to fulfill these requirements.
Since Haxe 3.1.0
It is also possible to extend multiple structures:
typedef WithLength = {
var length(default, null):Int;
3 }
1
2
4
5
6
7
8
typedef IterableWithLengthAndPush = {
> Iterable,
> WithLength,
function push(a:T):Int;
9 }
10
11
12
13
14
class Main {
static public function main() {
var array = [1, 2, 3];
var t:IterableWithLengthAndPush = array;
15
}
16 }
25
2.6
Function Type
The function type, along with the monomorph (2.9), is a type which is usually well-hidden from
Haxe users, yet present everywhere. We can make it surface by using $type, a special Haxe
identifier which outputs the type its expression has during compilation :
1
2
3
4
5
6
7
8
9
10
11
class Main {
static public function main() {
// i : Int -> s : String -> Bool
$type(test);
$type(test(1, "foo")); // Bool
}
static function test(i:Int, s:String):Bool {
return true;
}
}
There is a strong resemblance between the declaration of function test and the output of the
first $type expression, yet also a subtle difference:
• Function arguments are separated by the special arrow token -> instead of commas, and
• the function return type appears at the end after another ->.
In either notation it is obvious that the function test accepts a first argument of type Int,
a second argument of type String and returns a value of type Bool. If a call to this function,
such as test(1, "foo"), is made within the second $type expression, the Haxe typer checks
if 1 can be assigned to Int and if "foo" can be assigned to String. The type of the call is then
equal to the type of the value test returns, which is Bool.
If a function type has other function types as argument or return type, parentheses can be
used to group them correctly. For example, Int -> (Int -> Void) -> Void represents a
function which has a first argument of type Int, a second argument of function type Int ->
Void and a return of Void.
2.6.1
Optional Arguments
Optional arguments are declared by prefixing an argument identifier with a question mark ?:
class Main {
static public function main() {
// ?i : Int -> ?s : String -> String
$type(test);
trace(test()); // i: null, s: null
trace(test(1)); // i: 1, s: null
7
trace(test(1, "foo")); // i: 1, s: foo
8
trace(test("foo")); // i: null, s: foo
9
}
1
2
3
4
5
6
10
11
12
13
14
static function test(?i:Int, ?s:String) {
return "i: " +i + ", s: " +s;
}
}
26
Function test has two optional arguments: i of type Int and s of String. This is directly
reflected in the function type output by line 3. This example program calls test four times and
prints its return value.
1. The first call is made without any arguments.
2. The second call is made with a singular argument 1.
3. The third call is made with two arguments 1 and "foo".
4. The fourth call is made with a singular argument "foo".
The output shows that optional arguments which are omitted from the call have a value of null.
This implies that the type of these arguments must admit null as value, which raises the question of its nullability (2.2). The Haxe Compiler ensures that optional basic type arguments are
nullable by inferring their type as Null when compiling to a static target (2.2).
While the first three calls are intuitive, the fourth one might come as a surprise: It is indeed
allowed to skip optional arguments if the supplied value is assignable to a later argument.
2.6.2
Default values
Haxe allows default values for arguments by assigning a constant value to them:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Main {
static public function main() {
// ?i : Int -> ?s : String -> String
$type(test);
trace(test()); // i: 12, s: bar
trace(test(1)); // i: 1, s: bar
trace(test(1, "foo")); // i: 1, s: foo
trace(test("foo")); // i: 12, s: foo
}
static function test(?i = 12, s = "bar") {
return "i: " +i + ", s: " +s;
}
}
This example is very similar to the one from Optional Arguments (Section 2.6.1), with the only
difference being that the values 12 and "bar" are assigned to the function arguments i and s
respectively. The effect is that the default values are used instead of null should an argument
be omitted from the call.
Default values in Haxe are not part of the type and are not replaced at call-site (unless the
function is inlined (4.4.2), which can be considered as a more typical approach. On some targets
the compiler may still pass null for omitted argument values and generate code similar to this
into the function:
1
2
3
4
5
static function test(i = 12, s = "bar") {
if (i == null) i = 12;
if (s == null) s = "bar";
return "i: " +i + ", s: " +s;
}
This should be considered in performance-critical code where a solution without default values
may sometimes be more viable.
27
2.7
Dynamic
While Haxe has a static type system, this type system can, in effect, be turned off by using the
Dynamic type. A dynamic value can be assigned to anything; and anything can be assigned to it.
This has several drawbacks:
• The compiler can no longer type-check assignments, function calls and other constructs
where specific types are expected.
• Certain optimizations, in particular when compiling to static targets, can no longer be employed.
• Some common errors, e.g. a typo in a field access, can not be caught at compile-time and
likely cause an error at runtime.
• Dead Code Elimination (Section 8.2) cannot detect used fields if they are used through
Dynamic.
It is very easy to come up with examples where the usage of Dynamic can cause problems at
runtime. Consider compiling the following two lines to a static target:
1
2
var d:Dynamic = 1;
d.foo;
Trying to run a compiled program in the Flash Player yields an error Property foo not
found on Number and there is no default value. Without Dynamic, this would have
been detected at compile-time.
Trivia: Dynamic Inference before Haxe 3
The Haxe 3 compiler never infers a type to Dynamic, so users must be explicit about it.
Previous Haxe versions used to infer arrays of mixed types, e.g. [1, true, "foo"], as
Array. We found that this behavior introduced too many type problems and
thus removed it for Haxe 3.
Use of Dynamic should be minimized as there are better options in many situations but sometimes it is just practical to use it. Parts of the Haxe Reflection (Section 10.7) API use it and it
is sometimes the best option when dealing with custom data structures that are not known at
compile-time.
Dynamic behaves in a special way when being unified (3.5) with a monomorph (2.9). Monomorphs
are never bound to Dynamic which can have surprising results in examples such as this:
1
2
3
4
5
6
7
8
9
10
11
12
class Main {
static function main() {
var jsonData = ’[1, 2, 3]’;
var json = haxe.Json.parse(jsonData);
$type(json); // Unknown<0>
for (i in 0...json.length) {
// Array access is not allowed on
// {+ length : Int }
trace(json[0]);
}
}
}
28
Although the return type of Json.parse is Dynamic, the type of local variable json is
not bound to it and remains a monomorph. It is then inferred as an anonymous structure
(2.5) upon the json.length field access, which causes the following json[0] array access
to fail. In order to avoid this, the variable json can be explicitly typed as Dynamic by using var
json:Dynamic.
Trivia: Dynamic in the Standard Library
Dynamic was quite frequent in the Haxe Standard Library before Haxe 3. With the continuous improvements of the Haxe type system the occurrences of Dynamic were reduced over
the releases leading to Haxe 3.
2.7.1
Dynamic with Type Parameter
Dynamic is a special type because it allows explicit declaration with and without a type parameter (3.2). If such a type parameter is provided, the semantics described in Dynamic (Section 2.7)
are constrained to all fields being compatible with the parameter type:
1
2
3
4
5
6
7
var att : Dynamic = xml.attributes;
// valid, value is a String
att.name = "Nicolas";
// dito (this documentation is quite old)
att.age = "26";
// error, value is not a String
att.income = 0;
2.7.2
Implementing Dynamic
Classes can implement (2.3.3) Dynamic and Dynamic which enables arbitrary field access.
In the former case, fields can have any type, in the latter, they are constrained to be compatible
with the parameter type:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class ImplementsDynamic
implements Dynamic {
public var present:Int;
public function new() {}
}
class Main {
static public function main() {
var c = new ImplementsDynamic();
// valid, present is an existing field
c.present = 1;
// valid, assigned value is a String
c.stringField = "foo";
// error, Int should be String
//c.intField = 1;
}
}
29
Implementing Dynamic does not satisfy the requirements of other implemented interfaces.
The expected fields still have to be implemented explicitly.
Classes that implement Dynamic (with or without type parameter) can also utilize a special
method named resolve. If a read access (4.2) is made and the field in question does not exist,
the resolve method is called with the field name as argument:
class Resolve implements Dynamic {
public var present:Int;
public function new() {}
function resolve(field:String) {
return "Tried to resolve " +field;
6
}
7 }
1
2
3
4
5
8
9
10
11
12
13
14
15
16
class Main {
static public function main() {
var c = new Resolve();
c.present = 2;
trace(c.present);
trace(c.resolveMe);
}
}
2.7.3
Dynamic access
DynamicAccess is an abstract type (2.8) for working with anonymous structures (2.5) that
are intended to hold collections of objects by the string key. Basically DynamicAccess wraps
Reflectstd-reflection calls in a Map-like interface.
1
2
3
4
5
6
7
class Main {
static public function main() {
var user:haxe.DynamicAccess = {};
// Sets values for specified keys.
user.set("name", "Mark");
user.set("age", 25);
8
9
10
11
12
13
14
15
16
// Returns values by specified keys.
trace(user.get("name")); // "Mark"
trace(user.get("age")); // 25
// Tells if the structure contains a specified key
trace(user.exists("name")); // true
}
}
2.7.4
Any type
Any is a type that is compatible with any other in both ways. It serves one purpose - to hold
values of any type, but to actually use that values, an explicit casting is required. That way the
code doesn’t suddently become dynamically typed and we keep all the static typing goodness,
like advanced type system features and optimizations.
30
The implementation is quite simple:
1
abstract Any(Dynamic) from Dynamic to Dynamic {}
This type don’t make any assumptions about what the value actually is and whether it supports fields or any operations - this is up to the user.
class Main {
static function setAnyValue(value:Any) {
trace(value);
4
}
1
2
3
5
6
7
8
9
static function getAnyValue():Any {
return 42;
}
static function main() {
// value of any type works
setAnyValue("someValue");
setAnyValue(42);
10
11
12
13
14
15
16
17
18
19
20
var value = getAnyValue();
$type(value); // Any, not Unknown<0>
21
22
23
24
25
26
if (Std.is(value, String)) {
// explicit promotion, type-safe
trace((value : String).charCodeAt(0));
}
// won’t compile: no dynamic field access
// value.charCodeAt(0);
}
}
It’s a more type-safe alternative to Dynamic, because it doesn’t support field access or operators and it’s bound to monomorphs. So, to work with the actual value, it needs to be explicitly
promoted to another type.
2.8
Abstract
An abstract type is a type which is actually a different type at run-time. It is a compile-time
feature which defines types “over” concrete types in order to modify or augment their behavior:
abstract AbstractInt(Int) {
inline public function new(i:Int) {
3
this = i;
4
}
5 }
1
2
We can derive the following from this example:
• The keyword abstract denotes that we are declaring an abstract type.
31
• AbstractInt is the name of the abstract and could be anything conforming to the rules
for type identifiers.
• Enclosed in parenthesis () is the underlying type Int.
• Enclosed in curly braces {} are the fields,
• which are a constructor function new accepting one argument i of type Int.
Definition: Underlying Type
The underlying type of an abstract is the type which is used to represent said abstract at
runtime. It is usually a concrete (i.e. non-abstract) type but could be another abstract type as
well.
The syntax is reminiscent of classes and the semantics are indeed similar. In fact, everything
in the “body” of an abstract (that is everything after the opening curly brace) is parsed as class
fields. Abstracts may have method (4.3) fields and non-physical (4.2.3) property (4.2) fields.
Furthermore, abstracts can be instantiated and used just like classes:
1
2
3
4
5
6
class Main {
static public function main() {
var a = new AbstractInt(12);
trace(a); //12
}
}
As mentioned before, abstracts are a compile-time feature, so it is interesting to see what the
above actually generates. A suitable target for this is JavaScript, which tends to generate concise
and clean code. Compiling the above (using haxe -main MyAbstract -js myabstract.js)
shows this JavaScript code:
1
2
var a = 12;
console.log(a);
The abstract type Abstract completely disappeared from the output and all that is left is a value
of its underlying type, Int. This is because the constructor of Abstract is inlined - something
we shall learn about later in the section Inline (Section 4.4.2) - and its inlined expression assigns
a value to this. This might be surprising when thinking in terms of classes. However, it is
precisely what we want to express in the context of abstracts. Any inlined member method of an
abstract can assign to this, and thus modify the “internal value”.
A good question at this point is “What happens if a member function is not declared inline”
because the code obviously has to go somewhere. Haxe creates a private class, known to be the
implementation class, which has all the abstract member functions as static functions accepting an
additional first argument this of the underlying type.
Trivia: Basic Types and abstracts
Before the advent of abstract types, all basic types were implemented as extern classes or
enums. While this nicely took care of some aspects such as Int being a “child class” of
Float, it caused issues elsewhere. For instance, with Float being an extern class, it would
unify with the empty structure {}, making it impossible to constrain a type to accepting only
real objects.
32
2.8.1
Implicit Casts
Unlike classes, abstracts allow defining implicit casts. There are two kinds of implicit casts:
Direct: Allows direct casting of the abstract type to or from another type. This is defined by
adding to and from rules to the abstract type and is only allowed for types which unify
with the underlying type of the abstract.
Class field: Allows casting via calls to special cast functions. These functions are defined using
@:to and @:from metadata. This kind of cast is allowed for all types.
The following code example shows an example of direct casting:
abstract MyAbstract(Int) from Int to Int {
inline function new(i:Int) {
this = i;
}
5 }
1
2
3
4
6
7
8
9
10
class Main {
static public function main() {
var a:MyAbstract = 12;
var b:Int = a;
11
}
12 }
We declare MyAbstract as being from Int and to Int, meaning it can be assigned from Int
and assigned to Int. This is shown in lines 9 and 10, where we first assign the Int 12 to variable
a of type MyAbstract (this works due to the from Int declaration) and then that abstract back
to variable b of type Int (this works due to the to Int declaration).
Class field casts have the same semantics, but are defined completely differently:
abstract MyAbstract(Int) {
inline function new(i:Int) {
3
this = i;
4
}
1
2
5
6
7
8
@:from
static public function fromString(s:String) {
return new MyAbstract(Std.parseInt(s));
}
9
10
11
12
13
14
15
16
17
18
19
20
@:to
public function toArray() {
return [this];
}
}
class Main {
static public function main() {
var a:MyAbstract = "3";
var b:Array = a;
21
trace(b); // [3]
22
}
23 }
33
By adding @:from to a static function, that function qualifies as implicit cast function from its
argument type to the abstract. These functions must return a value of the abstract type. They
must also be declared static.
Similarly, adding @:to to a function qualifies it as implicit cast function from the abstract to
its return type.
In the example the method fromString allows the assignment of value "3" to variable a
of type MyAbstract while the method toArray allows assigning that abstract to variable b of
type Array.
When using this kind of cast, calls to the cast-functions are inserted where required. This
becomes obvious when looking at the JavaScript output:
1
2
var a = _ImplicitCastField.MyAbstract_Impl_.fromString("3");
var b = _ImplicitCastField.MyAbstract_Impl_.toArray(a);
This can be further optimized by inlining (4.4.2) both cast functions, turning the output into the
following:
1
2
var a = Std.parseInt("3");
var b = [a];
The selection algorithm when assigning a type A to a type B with at least one of them being an
abstract is simple:
1. If A is not an abstract, go to 3.
2. If A defines a to-conversions that admits B, go to 6.
3. If B is not an abstract, go to 5.
4. If B defines a from-conversions that admits A, go to 6.
5. Stop, unification fails.
6. Stop, unification succeeds.
By design, implicit casts are not transitive, as the following example shows:
1
2
3
4
abstract A(Int) {
public function new() this = 0;
@:to public function toB() return new B();
}
5
6
7
8
9
10
abstract B(Int) {
public function new() this = 0;
@:to public function toC() return new C();
}
11
12
13
14
15
16
abstract C(Int) {
public function new() this = 0;
}
class Main {
static public function main() {
17
var a = new A();
34
No
A is abstract
Yes
Yes
A defines to for B
No
No B is abstract
Yes
B defines from for A
Yes
No
Unification fails
Unification succeeds
Figure 2.1: Selection algorithm flow chart.
var b:B = a; // valid, uses A.toB
var c:C = b; // valid, uses B.toC
var c:C = a; // error, A should be C
18
19
20
21
22
}
}
While the individual casts from A to B and from B to C are allowed, a transitive cast from A to C
is not. This is to avoid ambiguous cast-paths and retain a simple selection algorithm.
2.8.2
Operator Overloading
Abstracts allow overloading of unary and binary operators by adding the @:op metadata to class
fields:
1
2
3
4
5
6
abstract MyAbstract(String) {
public inline function new(s:String) {
this = s;
}
@:op(A * B)
public function repeat(rhs:Int):MyAbstract {
var s:StringBuf = new StringBuf();
for (i in 0...rhs)
s.add(this);
return new MyAbstract(s.toString());
}
7
8
9
10
11
12
13
14
15
}
class Main {
35
16
17
18
19
20
static public function main() {
var a = new MyAbstract("foo");
trace(a * 3); // foofoofoo
}
}
By defining @:op(A * B), the function repeat serves as operator method for the multiplication * operator when the type of the left value is MyAbstract and the type of the right value is
Int. The usage is shown in line 17, which turns into this when compiled to JavaScript:
1
2
console.log(_AbstractOperatorOverload.
MyAbstract_Impl_.repeat(a,3));
Similar to implicit casts with class fields (2.8.1), a call to the overload method is inserted where
required.
The example repeat function is not commutative: While MyAbstract * Int works, Int
* MyAbstract does not. If this should be allowed as well, the @:commutative metadata can
be added. If it should work only for Int * MyAbstract, but not for MyAbstract * Int, the
overload method can be made static, accepting Int and MyAbstract as first and second type
respectively.
Overloading unary operators is analogous:
abstract MyAbstract(String) {
public inline function new(s:String) {
this = s;
4
}
1
2
3
5
6
7
8
9
10
11
12
13
14
15
@:op(++A) public function pre()
return "pre" + this;
@:op(A++) public function post()
return this + "post";
}
class Main {
static public
var a = new
trace(++a);
16
trace(a++);
17
}
18 }
function main() {
MyAbstract("foo");
// prefoo
// foopost
Both binary and unary operator overloads can return any type.
Exposing underlying type operations It is also possible to omit the method body of a @:op
function, but only if the underlying type of the abstract allows the operation in question and if
the resulting type can be assigned back to the abstract.
abstract MyAbstractInt(Int) from Int to Int {
// The following line exposes the (A > B) operation from the
underlying Int
3
// type. Note that no function body is used:
4
@:op(A > B) static function gt( a:MyAbstractInt, b:MyAbstractInt ) :
Bool;
1
2
36
5
6
7
8
9
10
}
class Main {
static function main() {
var a:MyAbstractInt = 42;
if(a > 0) trace(’Works fine, > operation implemented!’);
11
12
13
// The < operator is not implemented.
// This will cause an ’Cannot compare MyAbstractInt and Int’ error
:
if(a < 100) { }
14
15
16
}
}
2.8.3
Array Access
Array access describes the particular syntax traditionally used to access the value in an array at
a certain offset. This is usually only allowed with arguments of type Int. Nevertheless, with
abstracts it is possible to define custom array access methods. The Haxe Standard Library (10)
uses this in its Map type, where the following two methods can be found:
1
2
3
4
5
6
7
8
9
@:arrayAccess
public inline function get(key:K) {
return this.get(key);
}
@:arrayAccess
public inline function arrayWrite(k:K, v:V):V {
this.set(k, v);
return v;
}
There are two kinds of array access methods:
• If an @:arrayAccess method accepts one argument, it is a getter.
• If an @:arrayAccess method accepts two arguments, it is a setter.
The methods get and arrayWrite seen above then allow the following usage:
1
2
3
4
5
6
7
class Main {
public static function main() {
var map = new Map();
map["foo"] = 1;
trace(map["foo"]);
}
}
At this point it should not be surprising to see that calls to the array access fields are inserted
in the output:
1
2
map.set("foo",1);
console.log(map.get("foo")); // 1
37
Order of array access resolving Due to a bug in Haxe versions before 3.2 the order of checked
:arrayAccess fields was undefined. This was fixed for Haxe 3.2 so that the fields are now
consistently checked from top to bottom:
abstract AString(String) {
public function new(s) this = s;
@:arrayAccess function getInt1(k:Int) {
return this.charAt(k);
}
@:arrayAccess function getInt2(k:Int) {
7
return this.charAt(k).toUpperCase();
8
}
9 }
1
2
3
4
5
6
10
11
12
13
14
15
16
class Main {
static function main() {
var a = new AString("foo");
trace(a[0]); // f
}
}
The array access a[0] is resolved to the getInt1 field, leading to lower case f being returned. The result might be different in Haxe versions before 3.2.
Fields which are defined earlier take priority even if they require an implicit cast (2.8.1).
2.8.4
Enum abstracts
Since Haxe 3.1.0
By adding the :enum metadata to an abstract definition, that abstract can be used to define
finite value sets:
1
2
3
4
5
6
7
8
9
10
11
12
13
@:enum
abstract HttpStatus(Int) {
var NotFound = 404;
var MethodNotAllowed = 405;
}
class Main {
static public function main() {
var status = HttpStatus.NotFound;
var msg = printStatus(status);
}
static function printStatus(status:HttpStatus) {
return switch(status) {
case NotFound:
"Not found";
case MethodNotAllowed:
"Method not allowed";
}
}
14
15
16
17
18
19
20
21
}
38
The Haxe Compiler replaces all field access to the HttpStatus abstract with their values, as
evident in the JavaScript output:
1
2
3
4
5
6
7
8
9
10
11
12
Main.main = function() {
var status = 404;
var msg = Main.printStatus(status);
};
Main.printStatus = function(status) {
switch(status) {
case 404:
return "Not found";
case 405:
return "Method not allowed";
}
};
This is similar to accessing variables declared as inline (4.4.2), but has several advantages:
• The typer can ensure that all values of the set are typed correctly.
• The pattern matcher checks for exhaustiveness (6.4.10) when matching (6.4) an enum abstract.
• Defining fields requires less syntax.
2.8.5
Forwarding abstract fields
Since Haxe 3.1.0
When wrapping an underlying type, it is sometimes desirable to “keep” parts of its functionality. Because writing forwarding functions by hand is cumbersome, Haxe allows adding the
:forward metadata to an abstract type:
@:forward(push, pop)
abstract MyArray(Array) {
public inline function new() {
this = [];
5
}
6 }
1
2
3
4
7
8
9
10
11
12
13
14
15
16
class Main {
static public function main() {
var myArray = new MyArray();
myArray.push(12);
myArray.pop();
// MyArray has no field length
//myArray.length;
}
}
The MyArray abstract in this example wraps Array. Its :forward metadata has two arguments which correspond to the field names to be forwarded to the underlying type. In this
example, the main method instantiates MyArray and accesses its push and pop methods. The
commented line demonstrates that the length field is not available.
39
As usual we can look at the JavaScript output to see how the code is being generated:
1
2
3
4
5
Main.main = function() {
var myArray = [];
myArray.push(12);
myArray.pop();
};
It is also possible to use :forward without any arguments in order to forward all fields. Of
course the Haxe Compiler still ensures that the field actually exists on the underlying type.
Trivia: Implemented as macro
Both the :enum and :forward functionality were originally implemented using build
macros (9.5). While this worked nicely in non-macro code, it caused issues if these features
were used from within macros. The implementation was subsequently moved to the compiler.
2.8.6
Core-type abstracts
The Haxe Standard Library defines a set of basic types as core-type abstracts. They are identified
by the :coreType metadata and the lack of an underlying type declaration. These abstracts can
still be understood to represent a different type. Still, that type is native to the Haxe target.
Introducing custom core-type abstracts is rarely necessary in user code as it requires the Haxe
target to be able to make sense of it. However, there could be interesting use-cases for authors of
macros and new Haxe targets.
In contrast to opaque abstracts, core-type abstracts have the following properties:
• They have no underlying type.
• They are considered nullable unless they are annotated with :notNull metadata.
• They are allowed to declare array access (2.8.3) functions without expressions.
• Operator overloading fields (2.8.2) that have no expression are not forced to adhere to the
Haxe type semantics.
2.9
Monomorph
A monomorph is a type which may, through unification (3.5), morph into a different type later.
We shall see details about this type when talking about type inference (3.6).
40
Chapter 3
Type System
We learned about the different kinds of types in Types (Chapter 2) and it is now time to see how
they interact with each other. We start off easy by introducing typedef (3.1), a mechanism to give
a name (or alias) to a more complex type. Among other things, this will come in handy when
working with types having type parameters (3.2).
A lot of type-safety is achieved by checking if two given types of the type groups above
are compatible. Meaning, the compiler tries to perform unification between them as detailed in
Unification (Section 3.5).
All types are organized in modules and can be addressed through paths. Modules and Paths
(Section 3.7) will give a detailed explanation of the related mechanics.
3.1
Typedef
We briefly looked at typedefs while talking about anonymous structures (2.5) and saw how we
could shorten a complex structure type (2.5) by giving it a name. This is precisely what typedefs
are good for. Giving names to structure types might even be considered their primary use. In
fact, it is so common that the distinction appears somewhat blurry and many Haxe users consider
typedefs to actually be the structure.
A typedef can give a name to any other type:
1
typedef IA = Array;
This enables us to use IA in places where we would normally use Array. While this
saves only a few keystrokes in this particular case, it can make a much bigger difference for more
complex, compound types. Again, this is why typedef and structures seem so connected:
1
2
3
4
typedef User = {
var age : Int;
var name : String;
}
A typedef is not a textual replacement but actually a real type. It can even have type parameters
(3.2) as the Iterable type from the Haxe Standard Library demonstrates:
1
2
3
typedef Iterable = {
function iterator() : Iterator;
}
41
3.2
Type Parameters
Haxe allows parametrization of a number of types, as well as class fields (4) and enum constructors (2.4.1). Type parameters are defined by enclosing comma-separated type parameter names
in angle brackets <>. A simple example from the Haxe Standard Library is Array:
class Array {
function push(x : T) : Int;
3 }
1
2
Whenever an instance of Array is created, its type parameter T becomes a monomorph (2.9).
That is, it can be bound to any type, but only one at a time. This binding can happen
explicitly by invoking the constructor with explicit types (new Array()) or
implicitly by type inference (3.6), e.g. when invoking arrayInstance.push("foo").
Inside the definition of a class with type parameters, these type parameters are an unspecific type.
Unless constraints (3.2.1) are added, the compiler has to assume that the type parameters could
be used with any type. As a consequence, it is not possible to access fields of type parameters
or cast (5.23) to a type parameter type. It is also not possible to create a new instance of a type
parameter type, unless the type parameter is generic (3.3) and constrained accordingly.
The following table shows where type parameters are allowed:
Parameter on
Class
Enum
Enum Constructor
Function
Structure
Bound upon
instantiation
instantiation
instantiation
invocation
instantiation
Notes
Can also be bound upon member field access.
Allowed for methods and named local lvalue functions.
With function type parameters being bound upon invocation, such a type parameter (if unconstrained) accepts any type. However, only one type per invocation is accepted. This can be
utilized if a function has multiple arguments:
class Main {
static public function main() {
equals(1, 1);
// runtime message: bar should be foo
equals("foo", "bar");
6
// compiler error: String should be Int
7
equals(1, "foo");
8
}
1
2
3
4
5
9
10
11
12
13
14
15
static function equals(expected:T, actual:T) {
if (actual != expected) {
trace(’$actual should be $expected’);
}
}
}
Both arguments expected and actual of the equals function have type T. This implies
that for each invocation of equals the two arguments must be of the same type. The compiler
admits the first call (both arguments being of Int) and the second call (both arguments being of
String) but the third attempt causes a compiler error.
42
Trivia: Type parameters in expression syntax
We often get the question why a method with type parameters cannot be called as
method(x). The error messages the compiler gives are not very helpful. However, there is a simple reason for that: The above code is parsed as if both < and > were binary
operators, yielding (method < String) > (x).
3.2.1
Constraints
Type parameters can be constrained to multiple types:
1
2
3
4
5
6
7
8
9
10
11
typedef Measurable = {
public var length(default, null):Int;
}
class Main {
static public function main() {
trace(test([]));
trace(test(["bar", "foo"]));
// String should be Iterable
//test("foo");
}
12
13
14
15
16
17
18
19
20
21
#if (haxe_ver >= 4)
static function test & Measurable>(a:T) {
#else
static function test, Measurable)>(a:T) {
#end
if (a.length == 0) return "empty";
return a.iterator().next();
}
}
Type parameter T of method test is constrained to the types Iterable and Measurable.
The latter is defined using a typedef (3.1) for convenience and requires compatible types to have
a read-only property (4.2) named length of type Int. The constraints then say that a type is
compatible if
• it is compatible with Iterable and
• has a length-property of type Int.
We can see that invoking test with an empty array in line 7 and an Array in line
8 works fine. This is because Array has both a length-property and an iterator-method.
However, passing a String as argument in line 9 fails the constraint check because String is
not compatible with Iterable.
When constraining to a single type, the parentheses can be omitted:
1
2
3
4
5
class Main {
static public function main() {
trace(test([]));
trace(test(["bar", "foo"]));
}
43
6
7
8
9
10
static function test>(a:T) {
return a.iterator().next();
}
}
3.3
Generic
Usually, the Haxe Compiler generates only a single class or function even if it has type parameters. This results in a natural abstraction where the code generator for the target language has
to assume that a type parameter could be of any type. The generated code then might have to
perform some type checks which can be detrimental to performance.
A class or function can be made generic by attributing it with the :generic metadata (6.10).
This causes the compiler to emit a distinct class/function per type parameter combination with
mangled names. A specification like this can yield a boost in performance-critical code portions
on static targets (2.2) at the cost of a larger output size:
@:generic
class MyValue {
public var value:T;
public function new(value:T) {
this.value = value;
6
}
7 }
1
2
3
4
5
8
9
10
11
class Main {
static public function main() {
var a = new MyValue("Hello");
12
var b = new MyValue(42);
13
}
14 }
It seems unusual to see the explicit type MyValue here as we usually let type
inference (3.6) deal with this. Nonetheless, it is indeed required in this case. The compiler has to
know the exact type of a generic class upon construction. The JavaScript output shows the result:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
(function () { "use strict";
var Test = function() { };
Test.main = function() {
var a = new MyValue_String("Hello");
var b = new MyValue_Int(5);
};
var MyValue_Int = function(value) {
this.value = value;
};
var MyValue_String = function(value) {
this.value = value;
};
Test.main();
})();
44
We can identify that MyValue and MyValue have become MyValue_String and MyValue_Int respectively. This is similar for generic functions:
class Main {
static public function main() {
method("foo");
method(1);
5
}
1
2
3
4
6
7
8
@:generic static function method(t:T) { }
}
Again, the JavaScript output makes it obvious:
1
2
3
4
5
6
7
8
9
10
11
12
(function () { "use strict";
var Main = function() { }
Main.method_Int = function(t) {
}
Main.method_String = function(t) {
}
Main.main = function() {
Main.method_String("foo");
Main.method_Int(1);
}
Main.main();
})();
3.3.1
Construction of generic type parameters
Definition: Generic Type Parameter
A type parameter is said to be generic if its containing class or method is generic.
It is not possible to construct normal type parameters, e.g. new T() is a compiler error. The
reason for this is that Haxe generates only a single function and the construct makes no sense in
that case. This is different when the type parameter is generic: Since we know that the compiler
will generate a distinct function for each type parameter combination, it is possible to replace the
T new T() with the real type.
1
2
3
4
import haxe.Constraints;
class Main {
static public function main() {
5
var s:String = make();
6
var t:haxe.Template = make();
7
}
8
9
10
11
12
13
@:generic
static function makeVoid>>():T {
return new T("foo");
}
}
45
It should be noted that top-down inference (3.6.1) is used here to determine the actual type
of T. There are two requirements for this kind of type parameter construction to work: The constructed type parameter must be
1. generic and
2. be explicitly constrained (3.2.1) to having a constructor (2.3.1).
Here, 1. is given by make having the @:generic metadata, and 2. by T being constrained to
Constructible. The constraint holds for both String and haxe.Template as both have a
constructor accepting a singular String argument. Sure enough, the relevant JavaScript output
looks as expected:
1
2
3
4
5
6
7
8
9
10
11
12
var Main = function() { }
Main.__name__ = true;
Main.make_haxe_Template = function() {
return new haxe.Template("foo");
}
Main.make_String = function() {
return new String("foo");
}
Main.main = function() {
var s = Main.make_String();
var t = Main.make_haxe_Template();
}
3.4
Variance
While variance is also relevant in other places, it occurs particularly often with type parameters
and comes as a surprise in this context. Additionally, it is very easy to trigger variance errors:
1
2
3
4
5
6
class Base {
public function new() { }
}
class Child extends Base { }
class Main {
public static function main () {
var children = [new Child()];
// Array should be Array
// Type parameters are invariant
// Child should be Base
13
var bases:Array = children;
14
}
15 }
7
8
9
10
11
12
Apparently, an Array cannot be assigned to an Array , even though Child
can be assigned to Base. The reason for this might be somewhat unexpected: It is not allowed
because arrays can be written to, e.g. via their push() method. It is easy to generate problems
by ignoring variance errors:
46
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Base {
public function new() { }
}
class Child extends Base { }
class OtherChild extends Base { }
class Main {
public static function main () {
var children = [new Child()];
// subvert type checker
var bases:Array = cast children;
bases.push(new OtherChild());
for(child in children) {
trace(child);
}
}
}
Here we subvert the type checker by using a cast (5.23), thus allowing the assignment after the commented line. With that we hold a reference bases to the original array, typed as
Array . This allows pushing another type compatible with Base (OtherChild) onto
that array. However, our original reference children is still of type Array and things
go bad when we encounter the OtherChild instance in one of its elements while iterating.
If Array had no push() method and no other means of modification, the assignment would
be safe because no incompatible type could be added to it. In Haxe, we can achieve this by
restricting the type accordingly using structural subtyping (3.5.2):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Base {
public function new() { }
}
class Child extends Base { }
typedef MyArray = {
public function pop():T;
}
class Main {
public static function main () {
var a = [new Child()];
var b:MyArray = a;
}
}
We can safely assign with b being typed as MyArray and MyArray only having a
pop() method. There is no method defined on MyArray which could be used to add incompatible types, it is thus said to be covariant.
Definition: Covariance
A compound type (2) is considered covariant if its component types can be assigned to less
47
specific components, i.e. if they are only read, but never written.
Definition: Contravariance
A compound type (2) is considered contravariant if its component types can be assigned to
less generic components, i.e. if they are only written, but never read.
3.5
Unification
Unification is the heart of the type system and contributes immensely to the robustness of Haxe
programs. It describes the process of checking if a type is compatible to another type.
Definition: Unification
Unification between two types A and B is a directional process which answers the question
if A can be assigned to B. It may mutate either type if it is or has a monomorph (2.9).
Unification errors are very easy to trigger:
1
2
3
4
5
6
class Main {
static public function main() {
// Int should be String
var s:String = 1;
}
}
We try to assign a value of type Int to a variable of type String, which causes the compiler
to try and unify Int with String. This is, of course, not allowed and makes the compiler emit the
error Int should be String.
In this particular case, the unification is triggered by an assignment, a context in which the “is
assignable to” definition is intuitive. It is one of several cases where unification is performed:
Assignment: If a is assigned to b, the type of a is unified with the type of b.
Function call: We have briefly seen this one while introducing the function (2.6) type. In general,
the compiler tries to unify the first given argument type with the first expected argument
type, the second given argument type with the second expected argument type and so on
until all argument types are handled.
Function return: Whenever a function has a return e expression, the type of e is unified with
the function return type. If the function has no explicit return type, it is inferred to the type
of e and subsequent return expressions are inferred against it.
Array declaration: The compiler tries to find a minimal type between all given types in an array
declaration. Refer to Common Base Type (Section 3.5.5) for details.
Object declaration: If an object is declared “against” a given type, the compiler unifies each
given field type with each expected field type.
Operator unification: Certain operators expect certain types which the given types are unified
against. For instance, the expression a && b unifies both a and b with Bool and the
expression a == b unifies a with b.
48
3.5.1
Between Class/Interface
When defining unification behavior between classes, it is important to remember that unification
is directional: We can assign a more specialized class (e.g. a child class) to a generic class (e.g. a
parent class) but the reverse is not valid.
The following assignments are allowed:
• child class to parent class
• class to implementing interface
• interface to base interface
These rules are transitive, meaning that a child class can also be assigned to the base class of its
base class, an interface its base class implements, the base interface of an implementing interface
and so on.
3.5.2
Structural Subtyping
Definition: Structural Subtyping
Structural subtyping defines an implicit relation between types that have the same structure.
Structural sub-typing in Haxe is allowed when unifying
• a class (2.3) with a structure (2.5) and
• a structure with another structure.
The following example is part of the Lambda class of the Haxe Standard Library (10):
1
2
3
public static function empty(it : Iterable):Bool {
return !it.iterator().hasNext();
}
The empty-method checks if an Iterable has an element. For this purpose, it is not necessary
to know anything about the argument type other than the fact that it is considered an iterable.
This allows calling the empty-method with any type that unifies with Iterable which
applies to a lot of types in the Haxe Standard Library.
This kind of typing can be very convenient but extensive use may be detrimental to performance on static targets, which is detailed in Impact on Performance (Section 2.5.4).
3.5.3
Monomorphs
Unification of types having or being a monomorph (2.9) is detailed in Type Inference (Section 3.6).
3.5.4
Function Return
Unification of function return types may involve the Void-type (2.1.5) and requires a clear definition of what unifies with Void. With Void describing the absence of a type, it is not assignable
to any other type, not even Dynamic. This means that if a function is explicitly declared as
returning Dynamic, it cannot return Void.
49
The opposite applies as well: If a function declares a return type of Void, it cannot return
Dynamic or any other type. However, this direction of unification is allowed when assigning
function types:
1
var func:Void->Void = function() return "foo";
The right-hand function clearly is of type Void->String, yet we can assign it to the variable
func of type Void->Void. This is because the compiler can safely assume that the return type
is irrelevant, given that it could not be assigned to any non-Void type.
3.5.5
Common Base Type
Given a set of multiple types, a common base type is a type which all types of the set unify against:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Base {
public function new() { }
}
class Child1 extends Base { }
class Child2 extends Base { }
class Main {
static public function main() {
var a = [new Child1(), new Child2()];
$type(a); // Array
}
}
Although Base is not mentioned, the Haxe Compiler manages to infer it as the common type
of Child1 and Child2. The Haxe Compiler employs this kind of unification in the following
situations:
• array declarations
• if/else
• cases of a switch
3.6
Type Inference
The effects of type inference have been seen throughout this document and will continue to be
important. A simple example shows type inference at work:
1
2
3
4
5
6
7
8
class Main {
public static function main() {
var x = null;
$type(x); // Unknown<0>
x = "foo";
$type(x); // String
}
}
The special construct $type was previously mentioned in order to simplify the explanation of
the Function Type (Section 2.6) type, so let us now introduce it officially:
50
Construct: $type
$type is a compile-time mechanism being called like a function, with a single argument. The
compiler evaluates the argument expression and then outputs the type of that expression.
In the example above, the first $type prints Unknown<0>. This is a monomorph (2.9), a type
that is not yet known. The next line x = "foo" assigns a String literal to x, which causes
the unification (3.5) of the monomorph with String. We then see that the type of x indeed has
changed to String.
Whenever a type other than Dynamic (Section 2.7) is unified with a monomorph, that monomorph
becomes that type: it morphs into that type. Therefore it cannot morph into a different type afterwards, a property expressed in the mono part of its name.
Following the rules of unification, type inference can occur in compound types:
1
2
3
4
5
6
7
8
class Main {
public static function main() {
var x = [];
$type(x); // Array>
x.push("foo");
$type(x); // Array
}
}
Variable x is first initialized to an empty Array. At this point we can tell that the type of x is an
array, but we do not yet know the type of the array elements. Consequentially, the type of x is
Array>. It is only after pushing a String onto the array that we know the type
to be Array.
3.6.1
Top-down Inference
Most of the time, types are inferred on their own and may then be unified with an expected type.
In a few places, however, an expected type may be used to influence inference. We then speak of
top-down inference.
Definition: Expected Type
Expected types occur when the type of an expression is known before that expression has
been typed, e.g. because the expression is argument to a function call. They can influence
typing of that expression through what is called top-down inference (3.6.1).
A good example are arrays of mixed types. As mentioned in Dynamic (Section 2.7), the compiler refuses [1, "foo"] because it cannot determine an element type. Employing top-down
inference, this can be overcome:
class Main {
static public function main() {
var a:Array = [1, "foo"];
}
5 }
1
2
3
4
Here, the compiler knows while typing [1, "foo"] that the expected type is Array,
so the element type is Dynamic. Instead of the usual unification behavior where the compiler
would attempt (and fail) to determine a common base type (3.5.5), the individual elements are
typed against and unified with Dynamic.
51
We have seen another interesting use of top-down inference when construction of generic
type parameters (3.3.1) was introduced:
1
2
3
4
5
6
7
8
9
10
11
12
13
import haxe.Constraints;
class Main {
static public function main() {
var s:String = make();
var t:haxe.Template = make();
}
@:generic
static function makeVoid>>():T {
return new T("foo");
}
}
The explicit types String and haxe.Template are used here to determine the return type
of make. This works because the method is invoked as make(), so we know the return type will
be assigned to the variables. Utilizing this information, it is possible to bind the unknown type
T to String and haxe.Template respectively.
3.6.2
Limitations
Type inference saves a lot of manual type hints when working with local variables, but sometimes
the type system still needs some help. In fact, it does not even try to infer the type of a variable
(4.1) or property (4.2) field unless it has a direct initialization.
There are also some cases involving recursion where type inference has limitations. If a function calls itself recursively while its type is not (completely) known yet, type inference may infer
a wrong, too specialized type.
A different kind of limitation involves the readability of code. If type inference is overused
it might be difficult to understand parts of a program due to the lack of visible types. This is
particularly true for method signatures. It is recommended to find a good balance between type
inference and explicit type hints.
3.7
Modules and Paths
Definition: Module
All Haxe code is organized in modules, which are addressed using paths. In essence, each
.hx file represents a module which may contain several types. A type may be private, in
which case only its containing module can access it.
The distinction of a module and its containing type of the same name is blurry by design. In fact,
addressing haxe.ds.StringMap can be considered shorthand for haxe.ds.StringMap.StringMa
The latter version consists of four parts:
1. the package haxe.ds
2. the module name StringMap
3. the type name StringMap
52
4. the type parameter Int
If the module and type name are equal, the duplicate can be removed, leading to the haxe.ds.StringMapT or a setter named set_field of type T->T.
61
Trivia: Accessor names
In Haxe 2, arbitrary identifiers were allowed as access identifiers and would lead to custom
accessor method names to be admitted. This made parts of the implementation quite tricky
to deal with. In particular, Reflect.getProperty() and Reflect.setProperty() had
to assume that any name could have been used, requiring the target generators to generate
meta-information and perform lookups.
We disallowed these identifiers and went for the get_ and set_ naming convention which
greatly simplified implementation. This was one of the breaking changes between Haxe 2
and 3.
4.2.1
Common accessor identifier combinations
The next example shows common access identifier combinations for properties:
class Main {
// read from outside, write only within Main
3
public var ro(default, null):Int;
1
2
4
5
6
7
8
// write from outside, read only within Main
public var wo(null, default):Int;
// access through getter get_x and setter
// set_x
public var x(get, set):Int;
9
10
11
12
13
14
// read access through getter, no write
// access
public var y(get, never):Int;
15
16
17
18
19
20
// required by field x
function get_x() return 1;
// required by field x
function set_x(x) return x;
21
22
23
24
25
// required by field y
function get_y() return 1;
function new() {
var v = x;
x = 2;
x += 1;
}
26
27
28
29
30
31
32
33
34
static public function main() {
new Main();
}
}
The JavaScript output helps understand what the field access in the main-method is compiled
to:
62
1
2
3
4
5
6
var Main = function() {
var v = this.get_x();
this.set_x(2);
var _g = this;
_g.set_x(_g.get_x() + 1);
};
As specified, the read access generates a call to get_x(), while the write access generates a
call to set_x(2) where 2 is the value being assigned to x. The way the += is being generated
might look a little odd at first, but can easily be justified by the following example:
1
2
3
4
class Main {
public var x(get, set):Int;
function get_x() return 1;
function set_x(x) return x;
5
6
7
8
9
10
11
public function new() { }
static public function main() {
new Main().x += 1;
}
}
What happens here is that the expression part of the field access to x in the main method
is complex: It has potential side-effects, such as the construction of Main in this case. Thus, the
compiler cannot generate the += operation as new Main().x = new Main().x + 1 and has
to cache the complex expression in a local variable:
1
2
3
4
Main.main = function() {
var _g = new Main();
_g.set_x(_g.get_x() + 1);
}
4.2.2
Impact on the type system
The presence of properties has several consequences on the type system. Most importantly, it is
necessary to understand that properties are a compile-time feature and thus require the types to be
known. If we were to assign a class with properties to Dynamic, field access would not respect
accessor methods. Likewise, access restrictions no longer apply and all access is virtually public.
When using get or set access identifier, the compiler ensures that the getter and setter actually exists. The following code snippet does not compile:
1
2
3
4
5
class Main {
// Method get_x required by property x is missing
public var x(get, null):Int;
static public function main() {}
}
The method get_x is missing, but it need not be declared on the class defining the property
itself as long as a parent class defines it:
63
1
2
3
4
5
6
class Base {
public function get_x() return 1;
}
class Main extends Base {
// ok, get_x is declared by parent class
7
public var x(get, null):Int;
8
9
10
static public function main() {}
}
The dynamic access modifier works exactly like get or set, but does not check for the
existence
4.2.3
Rules for getter and setter
Visibility of accessor methods has no effect on the accessibility of its property. That is, if a property is public and defined to have a getter, that getter may be defined as private regardless.
Both getter and setter may access their physical field for data storage. The compiler ensures
that this kind of field access does not go through the accessor method if made from within the
accessor method itself, thus avoiding infinite recursion:
1
2
class Main {
public var x(default, set):Int;
3
4
5
6
7
8
9
function set_x(newX) {
return x = newX;
}
static public function main() {}
}
However, the compiler assumes that a physical field exists only if at least one of the access
identifiers is default or null.
Definition: Physical field
A field is considered to be physical if it is either
• a variable (4.1)
• a property (4.2) with the read-access or write-access identifier being default or null
• a property (4.2) with :isVar metadata (6.10)
If this is not the case, access to the field from within an accessor method causes a compilation
error:
class Main {
// This field cannot be accessed because it is not a real variable
3
public var x(get, set):Int;
1
2
4
5
6
function get_x() {
return x;
64
}
7
8
9
10
11
12
13
14
function set_x(x) {
return this.x = x;
}
static public function main() {}
}
If a physical field is indeed intended, it can be forced by attributing the field in question with
the :isVar metadata (6.10):
class Main {
// @isVar forces the field to be physical allowing the program to
compile.
3
@:isVar public var x(get, set):Int;
1
2
4
function get_x() {
return x;
}
5
6
7
8
9
10
11
12
13
14
function set_x(x) {
return this.x = x;
}
static public function main() {}
}
Trivia: Property setter type
It is not uncommon for new Haxe users to be surprised by the type of a setter being required
to be T->T instead of the seemingly more natural T->Void. After all, why would a setter
have to return something?
The rationale is that we still want to be able to use field assignments using setters as rightside expressions. Given a chain like x = y = 1, it is evaluated as x = (y = 1). In order
to assign the result of y = 1 to x, the former must have a value. If y had a setter returning
Void, this would not be possible.
4.3
Method
While variables (4.1) hold data, methods are defining behavior of a program by hosting expressions (5). We have seen method fields in every code example of this document with even the
initial Hello World (1.3) example containing a main method:
class Main {
static public function main():Void {
trace("Hello World");
4
}
5 }
1
2
3
Methods are identified by the function keyword. We can also learn that they
1. have a name (here: main),
65
2. have an argument list (here: empty ()),
3. have a return type (here: Void),
4. may have access modifiers (4.4) (here: static and public) and
5. may have an expression (here: {trace("Hello World");}).
We can also look at the next example to learn more about arguments and return types:
1
2
3
4
5
6
7
8
9
class Main {
static public function main() {
myFunc("foo", 1);
}
static function myFunc(f:String, i) {
return true;
}
}
Arguments are given by an opening parenthesis ( after the field name, a comma , separated
list of argument specifications and a closing parenthesis ). Additional information on the argument specification is described in Function Type (Section 2.6).
The example demonstrates how type inference (3.6) can be used for both argument and return
types. The method myFunc has two arguments but only explicitly gives the type of the first one,
f, as String. The second one, i, is not type-hinted and it is left to the compiler to infer its type
from calls made to it. Likewise, the return type of the method is inferred from the return true
expression as Bool.
4.3.1
Overriding Methods
Overriding fields is instrumental for creating class hierarchies. Many design patterns utilize it,
but here we will explore only the basic functionality. In order to use overrides in a class, it is
required that this class has a parent class (2.3.2). Let us consider the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Base {
public function new() { }
public function myMethod() {
return "Base";
}
}
class Child extends Base {
public override function myMethod() {
return "Child";
}
}
class Main {
static public function main() {
var child:Base = new Child();
trace(child.myMethod()); // Child
}
}
66
The important components here are:
• the class Base which has a method myMethod and a constructor,
• the class Child which extends Base and also has a method myMethod being declared
with override, and
• the Main class whose main method creates an instance of Child, assigns it to a variable
child of explicit type Base and calls myMethod() on it.
The variable child is explicitly typed as Base to highlight an important difference: At
compile-time the type is known to be Base, but the runtime still finds the correct method myMethod
on class Child. This is because field access is resolved dynamically at runtime.
The Child class can access methods it has overridden by calling super.methodName():
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Base {
public function new() { }
public function myMethod() {
return "Base";
}
}
class Child extends Base {
public override function myMethod() {
return "Child";
}
public function callHome() {
return super.myMethod();
}
}
class Main {
static public function main() {
var child = new Child();
trace(child.callHome()); // Base
}
}
The section on Inheritance (Section 2.3.2) explains the use of super() from within a new
constructor.
4.3.2
Effects of variance and access modifiers
Overriding adheres to the rules of variance (3.4). That is, their argument types allow contravariance (less specific types) while their return type allows covariance (more specific types):
1
2
3
4
class Base {
public function new() { }
}
5
6
class Child extends Base {
private function method(obj:Child):Child {
67
7
8
9
10
11
12
return obj;
}
}
class ChildChild extends Child {
public override function method(obj:Base):ChildChild {
13
return null;
14
}
15 }
16
17
18
class Main {
static public function main() { }
19 }
Intuitively, this follows from the fact that arguments are “written to” the function and the
return value is “read from” it.
The example also demonstrates how visibility (4.4.1) may be changed: An overriding field
may be public if the overridden field is private, but not the other way around.
It is not possible to override fields which are declared as inline (4.4.2). This is due to the
conflicting concepts: While inlining is done at compile-time by replacing a call with the function
body, overriding fields necessarily have to be resolved at runtime.
4.4
4.4.1
Access Modifier
Visibility
Fields are by default private, meaning that only the class and its sub-classes may access them.
They can be made public by using the public access modifier, allowing access from anywhere.
1
2
3
4
5
6
class MyClass {
static public function available() {
unavailable();
}
static private function unavailable() { }
}
7
8
9
10
11
12
class Main {
static public function main() {
MyClass.available();
// Cannot access private field unavailable
MyClass.unavailable();
13
}
14 }
Access to field available of class MyClass is allowed from within Main because it is denoted as being public. However, while access to field unavailable is allowed from within
class MyClass, it is not allowed from within class Main because it is private (explicitly, although this identifier is redundant here).
The example demonstrates visibility through static fields, but the rules for member fields are
equivalent. The following example demonstrates visibility behavior for when inheritance (2.3.2)
is involved.
1
class Base {
68
2
3
4
5
6
7
public function new() { }
private function baseField() { }
}
class Child1 extends Base {
private function child1Field() { }
8 }
9
10
11
12
13
14
15
16
17
18
19
20
21
class Child2 extends Base {
public function child2Field() {
var child1 = new Child1();
child1.baseField();
// Cannot access private field child1Field
child1.child1Field();
}
}
class Main {
static public function main() { }
}
We can see that access to child1.baseField() is allowed from within Child2 even though
child1 is of a different type, Child1. This is because the field is defined on their common ancestor class Base, contrary to field child1Field which can not be accessed from within Child2.
Omitting the visibility modifier usually defaults the visibility to private, but there are exceptions where it becomes public instead:
1. If the class is declared as extern.
2. If the field is declared on an interface (2.3.3).
3. If the field overrides (4.3.1) a public field.
4. If the class has metadata @:publicFields, which forces all class fields of inheriting
classes to be public.
Trivia: Protected
Haxe has no notion of a protected keyword known from Java, C++ and other objectoriented languages. However, its private behavior is equal to those language’s protected
behavior, so Haxe actually lacks their real private behavior.
4.4.2
Inline
The inline keyword allows function bodies to be directly inserted in place of calls to them. This
can be a powerful optimization tool, but should be used judiciously as not all functions are good
candidates for inline behavior. The following example demonstrates the basic usage:
1
2
3
4
5
class Main {
static inline function mid(s1:Int, s2:Int) {
return (s1 + s2) / 2;
}
69
6
7
8
9
10
11
static public function main() {
var a = 1;
var b = 2;
var c = mid(a, b);
}
}
The generated JavaScript output reveals the effect of inline:
1
2
3
4
5
6
7
8
9
(function () { "use strict";
var Main = function() { }
Main.main = function() {
var a = 1;
var b = 2;
var c = (a + b) / 2;
}
Main.main();
})();
As evident, the function body (s1 + s2) / 2 of field mid was generated in place of the
call to mid(a, b), with s1 being replaced by a and s2 being replaced by b. This avoids a
function call which, depending on the target and frequency of occurrences, may yield noticeable
performance improvements.
It is not always easy to judge if a function qualifies for being inline. Short functions that have
no writing expressions (such as a = assignment) are usually a good choice, but even more complex functions can be candidates. However, in some cases inlining can actually be detrimental
to performance, e.g. because the compiler has to create temporary variables for complex expressions.
Inline is not guaranteed to be done. The compiler might cancel inlining for various reasons
or a user could supply the --no-inline command line argument to disable inlining. The only
exception is if the class is extern (6.2) or if the class field has the :extern metadata (6.10), in
which case inline is forced. If it cannot be done, the compiler emits an error.
It is important to remember this when relying on inline:
1
2
3
class Main {
public static function main () { }
static function test() {
if (Math.random() > 0.5) {
return "ok";
} else {
error("random failed");
}
}
4
5
6
7
8
9
10
11
12
13
14
15
@:extern static inline function error(s:String) {
throw s;
}
}
If the call to error is inlined the program compiles correctly because the control flow checker
is satisfied due to the inlined throw (5.22) expression. If inline is not done, the compiler only sees
a function call to error and emits the error A return is missing here.
70
4.4.3
Dynamic
Methods can be denoted with the dynamic keyword to make them (re-)bindable:
class Main {
static dynamic function test() {
return "original";
4
}
1
2
3
5
6
7
8
9
10
11
static public function main() {
trace(test()); // original
test = function() { return "new"; }
trace(test()); // new
}
}
The first call to test() invokes the original function which returns the String "original".
In the next line, test is assigned a new function. This is precisely what dynamic allows: Function fields can be assigned a new function. As a result, the next invocation of test() returns the
String "new".
Dynamic fields cannot be inline for obvious reasons: While inlining is done at compiletime, dynamic functions necessarily have to be resolved at runtime.
4.4.4
Override
The access modifier override is required when a field is declared which also exists on a parent
class (2.3.2). Its purpose is to ensure that the author of a class is aware of the override as this may
not always be obvious in large class hierarchies. Likewise, having override on a field which
does not actually override anything (e.g. due to a misspelled field name) triggers an error.
The effects of overriding fields are detailed in Overriding Methods (Section 4.3.1). This modifier is only allowed on method (4.3) fields.
4.4.5
Static
All fields are member fields unless the modifier static is used. Static fields are used “on the
class” whereas non-static fields are used “on a class instance”:
class Main {
static function main() {
Main.staticField; // static read
Main.staticField = 2; // static write
5
}
1
2
3
4
6
7
8
static var staticField:Int;
}
Static variable (4.1) and property (4.2) fields can have arbitrary initialization expressions (5).
71
Chapter 5
Expressions
Expressions in Haxe define what a program does. Most expressions are found in the body of a
method (4.3), where they are combined to express what that method should do. This section
explains the different kinds of expressions. Some definitions help here:
Definition: Name
A general name may refer to
• a type,
• a local variable,
• a local function or
• a field.
Definition: Identifier
Haxe identifiers start with an underscore _, a dollar $, a lower-case character a-z or an
upper-case character A-Z. After that, any combination and number of _, A-Z, a-z and 0-9
may follow.
Further limitations follow from the usage context, which are checked upon typing:
• Type names must start with an upper-case letter A-Z or an underscore _.
• Leading dollars are not allowed for any kind of name (5) (dollar-names are mostly used
for macro reification (9.3)).
Since Haxe 3.3.0
Haxe reserves the identifier prefix _hx_ for internal use. This is not enforced by the parser or
typer.
Keywords The following Haxe keywords may not be used as identifiers:
• abstract
• break
72
• case
• cast
• catch
• class
• continue
• default
• do
• dynamic
• else
• enum
• extends
• extern
• false
• for
• function
• if
• implements
• import
• in
• inline
• interface
• macro
• new
• null
• override
• package
• private
• public
• return
• static
• switch
73
• this
• throw
• true
• try
• typedef
• untyped
• using
• var
• while
Related content
• Haxe Code Cookbook article: Everything is an expression.
5.1
Blocks
A block in Haxe starts with an opening curly brace { and ends with a closing curly brace }. A
block may contain several expressions, each of which is followed by a semicolon ;. The general
syntax is thus:
1
2
3
4
5
6
{
expr1;
expr2;
...
exprN;
}
The value and by extension the type of a block-expression is equal to the value and the type of
the last sub-expression.
Blocks can contain local variables declared by var expression (5.10), as well as local functions declared by function expressions (5.11). These are available within the block and within
sub-blocks, but not outside the block. Also, they are available only after their declaration. The
following example uses var, but the same rules apply to function usage:
1
2
3
4
5
6
7
8
9
10
11
12
{
a; // error, a is not declared yet
var a = 1; // declare a
a; // ok, a was declared
{
a; // ok, a is available in sub-blocks
}
// ok, a is still available after
// sub-blocks
a;
}
a; // error, a is not available outside
74
At runtime, blocks are evaluated from top to bottom. Control flow (e.g. exceptions (5.18) or
return expressions (5.19)) may leave a block before all expressions are evaluated.
Variable Shadowing Haxe allows local variable shadowing within the same block. This means
that a var or function can be declared with the same name that was previously available in a
block, effectively hiding it from the further code:
1
2
3
4
5
6
{
var v = 42; // declare v
$type(v); // Int
var v = "hi"; // declare a new v
$type(v); // String, previous declaration is not available
}
It might come as a surprise that this is allowed, but it’s useful to avoid pollution of local name
space and thus prevent accidental usage of a wrong variable.
Note, that the shadowing strictly follows syntax, so if a variable was captured in a closure
before it was shadowed, that closure would still reference the original declaration:
1
2
3
4
5
6
7
8
{
var a = 1;
function f() {
trace(a);
}
var a = 2;
f(); // traces 1
}
5.2
Constants
The Haxe syntax supports the following constants:
Int: An integer (2.1.1), such as 0, 1, 97121, -12, 0xFF0000.
Float: A floating point number (2.1.1), such as 0.0, 1., .3, -93.2.
String: A string of characters (10.1), such as "", "foo", ’’, ’bar’.
true,false: A boolean (2.1.4) value.
/haxe/i: A regular expression (10.3) literal.
null: The null value.
Furthermore, the internal syntax structure treats identifiers (5) as constants, which may be
relevant when working with macros (9).
75
5.3
Binary Operators
5.4
Unary Operators
5.5
Array Declaration
Arrays are initialized by enclosing comma , separated values in brackets []. A plain [] represents the empty array, whereas [1, 2, 3] initializes an array with three elements 1, 2 and
3.
The generated code may be less concise on platforms that do not support array initialization.
Essentially, such initialization code then looks like this:
var a = new Array();
a.push(1);
3 a.push(2);
4 a.push(3);
1
2
This should be considered when deciding if a function should be inlined (4.4.2) as it may inline
more code than visible in the syntax.
Advanced initialization techniques are described in Array Comprehension (Section 6.6).
5.6
Object Declaration
Object declaration begins with an opening curly brace { after which key:value-pairs separated
by comma , follow, and which ends in a closing curly brace }.
1
2
3
4
5
6
{
key1:value1,
key2:value2,
...
keyN:valueN
}
Further details of object declaration are described in the section about anonymous structures
(2.5).
5.7
Field Access
Field access is expressed by using the dot . followed by the name of the field.
1
object.fieldName
This syntax is also used to access types within packages in the form of pack.Type.
The typer ensures that an accessed field actually exist and may apply transformations depending on the nature of the field. If a field access is ambiguous, understanding the resolution
order (3.7.4) may help.
76
5.8
Array Access
Array access is expressed by using an opening bracket [ followed by the index expression and a
closing bracket ].
1
expr[indexExpr]
This notation is allowed with arbitrary expressions, but at typing level only certain combinations are admitted:
• expr is of Array or Dynamic and indexExpr is of Int
• expr is an abstract type (2.8) which defines a matching array access (2.8.3)
5.9
Function Call
Functions calls consist of an arbitrary subject expression followed by an opening parenthesis (,
a comma , separated list of expressions as arguments and a closing parenthesis ).
1
2
3
4
5
subject(); // call with no arguments
subject(e1); // call with one argument
subject(e1, e2); // call with two arguments
// call with multiple arguments
subject(e1, ..., eN);
Related content
• Haxe Code Cookbook article: How to declare functions
• Class Methods: Method (Section 4.3)
5.10
var
The var keyword allows declaring multiple variables, separated by comma ,. Each variable
has a valid identifier (5) and optionally a value assignment following the assignment operator =.
Variables can also have an explicit type-hint.
var a; // declare local a
var b:Int; // declare variable b of type Int
// declare variable c, initialized to value 1
var c = 1;
5 // declare an uninitialized variable d
6 // and variable e initialized to value 2
7 var d,e = 2;
1
2
3
4
The scoping behavior of local variables is described in Blocks (Section 5.1).
77
5.11
Local Functions
Haxe supports first-class functions and allows declaring local functions in expressions. The syntax follows class field methods (4.3):
class Main {
static public function main() {
var value = 1;
function myLocalFunction(i) {
return value + i;
}
trace(myLocalFunction(2)); // 3
8
}
9 }
1
2
3
4
5
6
7
We declare myLocalFunction inside the block expression (5.1) of the main class field. It
takes one argument i and adds it to value, which is defined in the outside scope.
The scoping is equivalent to that of variables (5.10) and for the most part writing a named
local function can be considered equal to assigning an unnamed local function to a local variable:
1
var myLocalFunction = function(a) { }
However, there are some differences related to type parameters and the position of the function. We speak of a “lvalue” function if it is not assigned to anything upon its declaration, and
an “rvalue” function otherwise.
• Lvalue functions require a name and can have type parameters (3.2).
• Rvalue functions may have a name, but cannot have type parameters.
5.12
new
The new keyword signals that a class (2.3) or an abstract (2.8) is being instantiated. It is followed
by the type path (3.7) of the type which is to be instantiated. It may also list explicit type parameters (3.2) enclosed in <> and separated by comma ,. After an opening parenthesis ( follow the
constructor arguments, again separated by comma ,, with a closing parenthesis ) at the end.
1
2
3
4
5
6
7
class Main {
static public function main() {
new Main(12, "foo");
}
function new(t:T, s:String) { }
}
Within the main method we instantiate an instance of Main itself, with an explicit type parameter Int and the arguments 12 and "foo". As we can see, the syntax is very similar to the
function call syntax (5.9) and it is common to speak of “constructor calls”.
5.13
for
Haxe does not support traditional for-loops known from C. Its for keyword expects an opening
parenthesis (, then a variable identifier followed by the keyword in and an arbitrary expres78
sion used as iterating collection. After the closing parenthesis ) follows an arbitrary loop body
expression.
1
for (v in e1) e2;
The typer ensures that the type of e1 can be iterated over, which is typically the case if it has
an iterator (6.8) method returning an Iterator, or if it is an Iterator itself.
Variable v is then available within loop body e2 and holds the value of the individual elements of collection e1.
var list = ["apple", "pear", "banana"];
for (v in list) {
trace(v);
}
// apple
6 // pear
7 // banana
1
2
3
4
5
Range iteration Haxe has a special range operator to iterate over intervals. It is a binary operator taking two Int operands: min...max returns an IntIterator instance that iterates from min
(inclusive) to max (exclusive). Note that max may not be smaller than min.
1
for (i in 0...10) trace(i); // 0 to 9
The type of a for expression is always Void, meaning it has no value and cannot be used as
right-side expression.
The control flow of loops can be affected by break (5.20) and continue (5.21) expressions.
1
2
3
4
5
6
7
8
9
for (i in 0...10) {
if (i == 2) continue; // skip 2
if (i == 5) break; // stop at 5
trace(i);
}
// 0
// 1
// 3
// 4
Related content
• Manual: Haxe iterators documentation (6.8), Haxe Data Structures documentation (10.2)
• Cookbook: Haxe iterators examples, Haxe data structures examples
5.14
while
A normal while loop starts with the while keyword, followed by an opening parenthesis (, the
condition expression and a closing parenthesis ). After that follows the loop body expression:
79
1
while(condition) expression;
The condition expression has to be of type Bool.
Upon each iteration, the condition expression is evaluated. If it evaluates to false, the loop
stops, otherwise it evaluates the loop body expression.
class Main {
static public function main() {
var f = 0.0;
while (f < 0.5) {
trace(f);
f = Math.random();
}
8
}
9 }
1
2
3
4
5
6
7
This kind of while-loop is not guaranteed to evaluate the loop body expression at all: If the
condition does not hold from the start, it is never evaluated. This is different for do-while loops
(5.15).
5.15
do-while
A do-while loop starts with the do keyword followed by the loop body expression. After that
follows the while keyword, an opening parenthesis (, the condition expression and a closing
parenthesis ):
1
do expression while(condition);
The condition expression has to be of type Bool.
As the syntax suggests, the loop body expression is always evaluated at least once, unlike
while (5.14) loops.
5.16
if
Conditional expressions come in the form of a leading if keyword, a condition expression enclosed in parentheses () and a expression to be evaluated in case the condition holds:
1
if (condition) expression;
The condition expression has to be of type Bool.
Optionally, expression may be followed by the else keyword as well as another expression to be evaluated if the condition does not hold:
1
if (condition) expression1 else expression2;
Here, expression2 may consist of another if expression:
1
2
3
if (condition1) expression1
else if(condition2) expression2
else expression3
80
If the value of an if expression is required, e.g. for var x = if(condition) expression1
else expression2, the typer ensures that the types of expression1 and expression2
unify (3.5). If no else expression is given, the type is inferred to be Void.
5.17
switch
A basic switch expression starts with the switch keyword and the switch subject expression, as
well as the case expressions between curly braces {}. Case expressions either start with the case
keyword and are followed by a pattern expression, or consist of the default keyword. In both
cases a colon : and an optional case body expression follows:
switch subject {
case pattern1: case-body-expression-1;
3
case pattern2: case-body-expression-2;
4
default: default-expression;
5 }
1
2
Case body expressions never “fall through”, so the break (5.20) keyword is not supported in
Haxe.
Switch expressions can be used as value; in that case the types of all case body expressions
and the default expression must unify (3.5).
Related content
• Further details on syntax of pattern expressions are detailed in Pattern Matching (Section 6.4).
• Snippets and tutorials about pattern matching in the Haxe Code Cookbook.
5.18
try/catch
Haxe allows catching values using its try/catch syntax:
1
2
3
try try-expr
catch(varName1:Type1) catch-expr-1
catch(varName2:Type2) catch-expr-2
If during runtime the evaluation of try-expression causes a throw (5.22), it can be caught
by any subsequent catch block. These blocks consist of
• a variable name which holds the thrown value,
• an explicit type annotation which determines which types of values to catch, and
• the expression to execute in that case.
Haxe allows throwing and catching any kind of value, it is not limited to types inheriting
from a specific exception or error class. Catch blocks are checked from top to bottom with the
first one whose type is compatible with the thrown value being picked.
This process has many similarities to the compile-time unification (3.5) behavior. However,
since the check has to be done at runtime there are several restrictions:
81
• The type must exist at runtime: Class instances (2.3), enum instances (2.4), abstract core
types (2.8.6) and Dynamic (2.7).
• Type parameters can only be Dynamic (2.7).
5.19
return
A return expression can come with or without a value expression:
1
2
return;
return expression;
It leaves the control-flow of the innermost function it is declared in, which has to be distinguished when local functions (5.11) are involved:
function f1() {
function f2() {
return;
}
5
f2();
6
expression;
7 }
1
2
3
4
The return leaves local function f2, but not f1, meaning expression is still evaluated.
If return is used without a value expression, the typer ensures that the return type of the
function it returns from is of Void. If it has a value expression, the typer unifies (3.5) its type with
the return type (explicitly given or inferred by previous return expressions) of the function it
returns from.
5.20
break
The break keyword leaves the control flow of the innermost loop (for or while) it is declared
in, stopping further iterations:
while(true) {
expression1;
3
if (condition) break;
4
expression2;
5 }
1
2
Here, expression1 is evaluated for each iteration, but as soon as condition holds, the
current iteration is terminated without evaluating expression2, and no more iteration is done.
The typer ensures that it appears only within a loop. The break keyword in switch cases
(5.17) is not supported in Haxe.
5.21
continue
The continue keyword ends the current iteration of the innermost loop (for or while) it is
declared in, causing the loop condition to be checked for the next iteration:
82
1
2
3
4
5
while(true) {
expression1;
if(condition) continue;
expression2;
}
Here, expression1 is evaluated for each iteration, but if condition holds, expression2
is not evaluated for the current iteration. Unlike break, iterations continue.
The typer ensures that it appears only within a loop.
5.22
throw
Haxe allows throwing any kind of value using its throw syntax:
1
throw expr
A value which is thrown like this can be caught by catch blocks (5.18). If no such block
catches it, the behavior is target-dependent.
5.23
cast
Haxe allows two kinds of casts:
1
2
cast expr; // unsafe cast
cast (expr, Type); // safe cast
5.23.1
unsafe cast
Unsafe casts are useful to subvert the type system. The compiler types expr as usual and then
wraps it in a monomorph (2.9). This allows the expression to be assigned to anything.
Unsafe casts do not introduce any dynamic (2.7) types, as the following example shows:
1
2
3
4
5
6
7
8
9
10
class Main {
public static function main() {
var i = 1;
$type(i); // Int
var s = cast i;
$type(s); // Unknown<0>
Std.parseInt(s);
$type(s); // String
}
}
Variable i is typed as Int and then assigned to variable s using the unsafe cast cast i. This
causes s to be of an unknown type, a monomorph. Following the usual rules of unification (3.5),
it can then be bound to any type, such as String in this example.
These casts are called ”unsafe” because the runtime behavior for invalid casts is not defined.
While most dynamic targets (2.2) are likely to work, it might lead to undefined errors on static
targets (2.2).
Unsafe casts have little to no runtime overhead.
83
5.23.2
safe cast
Unlike unsafe casts (5.23.1), the runtime behavior in case of a failing cast is defined for safe casts:
1
2
3
4
5
6
7
8
9
class Base {
public function new() { }
}
class Child1 extends Base {}
class Child2 extends Base {}
class Main {
public static function main() {
var child1:Base = new Child1();
var child2:Base = new Child2();
cast(child1, Base);
// Exception: Class cast error
cast(child1, Child2);
16
}
17 }
10
11
12
13
14
15
In this example we first cast a class instance of type Child1 to Base, which succeeds because
Child1 is a child class (2.3.2) of Base. We then try to cast the same class instance to Child2,
which is not allowed because instances of Child2 are not instances of Child1.
The Haxe compiler guarantees that an exception of type String is thrown (5.22) in this case.
This exception can be caught using a try/catch block (5.18).
Safe casts have a runtime overhead. It is important to understand that the compiler already
generates type checks, so it is redundant to add manual checks, e.g. using Std.is. The intended
usage is to try the safe cast and catch the String exception.
5.24
type check
Since Haxe 3.1.0
It is possible to employ compile-time type checks using the following syntax:
1
(expr : type)
The parentheses are mandatory. Unlike safe casts (5.23.2) this construct has no run-time impact. It has two compile-time implications:
1. Top-down inference (3.6.1) is used to type expr with type type.
2. The resulting typed expression is unified (3.5) with type type.
This has the usual effect of both operations such as the given type being used as expected
type when performing unqualified identifier resolution (3.7.4) and the unification checking for
abstract casts (2.8.1).
84
Chapter 6
Language Features
Abstract types (2.8):
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.
Extern classes (6.2):
Externs can be used to describe target-specific interaction in a type-safe manner.
Anonymous structures (2.5):
Data can easily be grouped in anonymous structures, minimizing the necessity of small data
classes.
1
2
var point = { x: 0, y: 10 };
point.x += 10;
Array Comprehension (6.6):
Create and populate arrays quickly using for loops and logic.
1
var evenNumbers = [ for (i in 0...100) if (i%2==0) i ];
Classes, interfaces and inheritance (2.3):
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 (6.1):
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
js.Browser.alert("Hello");
#elseif sys
4
Sys.println("Hello");
5 #end
1
2
3
(Generalized) Algebraic Data Types (2.4):
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.
85
1
2
3
4
5
enum Result {
Success(data:Array);
UserError(msg:String);
SystemError(msg:String, position:PosInfos);
}
Inlined calls (4.4.2):
Functions can be designated 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 (6.8):
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.
1
2
3
for (i in [1, 2, 3]) {
trace(i);
}
Local functions and closures (5.11):
Functions in Haxe are not limited to class fields and can be declared in expressions as well,
allowing powerful closures.
1
2
3
4
5
6
7
var buffer = "";
function append(s:String) {
buffer += s;
}
append("foo");
append("bar");
trace(buffer); // foobar
Metadata (6.10):
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;
3 }
4 trace(haxe.rtti.Meta.getFields(MyClass).value.range); // [1,8]
1
2
Static Extensions (6.3):
Existing classes and other types can be augmented with additional functionality through using static extensions.
1
2
using StringTools;
" Me & You
".trim().htmlEscape();
String Interpolation (6.5):
Strings declared with a single quotes are able to access variables in the current context.
1
trace(’My name is $name and I work in ${job.industry}’);
86
Partial function application (6.9):
Any function can be applied partially, providing the values of some arguments and leaving
the rest to be filled in later.
1
2
3
4
var map = new haxe.ds.IntMap();
var setToTwelve = map.set.bind(_, 12);
setToTwelve(1);
setToTwelve(2);
Pattern Matching (6.4):
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) {
3
case { foo: i }: trace(i);
4
default:
5 }
1
2
Properties (4.2):
Variable class fields can be designed as properties with custom read and write access, allowing fine grained access control.
1
2
3
4
5
6
7
8
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;
}
Access control (6.11):
The access control language feature uses the Haxe metadata syntax to force or allow access
classes or fields.
Type Parameters, Constraints and Variance (3.2):
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.
1
2
3
4
5
class Main {
static function main() {
new Main("foo");
new Main(12); // use type inference
}
6
7
8
}
function new(a:A) { }
87
6.1
Conditional Compilation
Haxe allows conditional compilation by using #if, #elseif and #else and checking for compiler flags.
Definition: Compiler Flag
A compiler flag is a configurable value which may influence the compilation process. Such
a flag can be set by invoking the command line with -D key=value or just -D key, in
which case the value defaults to "1". The compiler also sets several flags internally to pass
information between different compilation steps.
This example demonstrates usage of conditional compilation:
1
2
3
4
5
6
7
8
9
10
11
class Main {
public static function main(){
#if !debug
trace("ok");
#elseif (debug_level > 3)
trace(3);
#else
trace("debug level too low");
#end
}
}
Compiling this without any flags will leave only the trace("ok"); line in the body of the
main method. The other branches are discarded while parsing the file. These other branches
must still contain valid Haxe syntax, but the code is not type-checked.
The conditions after #if and #elseif allow the following expressions:
• Any identifier is replaced by the value of the compiler flag by the same name. Note that
-D some-flag from command line leads to the flags some-flag and some_flag to be
defined.
• The values of String, Int and Float constants are used directly.
• The boolean operators && (and), || (or) and ! (not) work as expected, however the full
expression must be completely contained by parentheses.
• The operators ==, !=, >, >=, <, <= can be used to compare values.
• Parentheses () can be used to group expressions as usual.
The Haxe parser does not parse some-flag as a single token and instead reads it as a subtraction binary operator some - flag. In cases like this the underscore version some_flag
has to be used.
Working with compiler flags Compiler flags are available at compile time, the following methods only work in macro context:
• To see if a compiler flag is set, use haxe.macro.Context.defined("any_flag").
• To get the value of a compiler flag, use haxe.macro.Context.definedValue("any_flag").
• To get a map of all compiler flags with its value use haxe.macro.Context.getDefines().
88
Haxelibs By default, each used haxelib version is automatically added as flag, e.g. when you
add -lib actuate, the compiler adds -D actuate=1.8.7. To test if a library exists in current
context, use #if actuate. To check a specific haxelib version, use the operators, for example
#if (actuate <= "1.8.7")
Built-in Compiler Flags An exhaustive list of all built-in defines can be obtained by invoking
the Haxe Compiler with the --help-defines argument. The Haxe Compiler allows multiple
-D flags per compilation.
Related content
• See also the Compiler Flags list (7.2).
6.2
Externs
Externs can be used to describe target-specific interaction in a type-safe manner. They are defined
like normal classes, except that
• the class keyword is preceded by the extern keyword,
• methods (4.3) have no expressions,
• all argument and return types are explicit, and
• the default visibility (4.4.1) is public (private must be specified explicitly).
A common example from the Haxe Standard Library (10) is the Math class, as an excerpt
shows:
extern class Math
{
3
static var PI(default,null) : Float;
4
static function floor(v:Float):Int;
5 }
1
2
We see that externs can define both methods and variables (actually, PI is declared as a readonly property (4.2)). Once this information is available to the compiler, it allows field access
accordingly and also knows the types:
1
2
3
4
5
6
class Main {
static public function main() {
var pi = Math.floor(Math.PI);
$type(pi); // Int
}
}
This works because the return type of method floor is declared to be Int.
The Haxe Standard Library comes with many externs for the Flash and JavaScript target.
They allow accessing the native APIs in a type-safe manner and are instrumental for designing
higher-level APIs. There are also externs for many popular native libraries on haxelib (11).
The Flash, Java and C# targets allow direct inclusion of native libraries from command line
(7). Target-specific details are explained in the respective sections of Target Details (Chapter 12).
Some targets such as Python or JavaScript may require generating additional ”import” code
that loads an extern class from a native module. Haxe provides ways to declare such dependencies also described in respective sections Target Details (Chapter 12).
89
Rest arguments and type choices
Since Haxe 3.2.0
The haxe.extern package provides two types that help mapping native semantics to Haxe:
Rest: This type can be used as a final function argument to allow passing an arbitrary number of additional call arguments. The type parameter can be used to constrain these arguments to a specific type.
EitherType: This type allows using either of its parameter types, thus representing a
type choice. It can be nested to allow more than two different types.
We demonstrate the usage in this code sample:
1
2
3
import haxe.extern.Rest;
import haxe.extern.EitherType;
4
5
6
7
8
9
extern class MyExtern {
static function f1(s:String, r:Rest):Void;
static function f2(e:EitherType):Void;
}
10
11
12
13
14
15
16
17
18
19
class Main {
static function main() {
MyExtern.f1("foo", 1, 2, 3); // use 1, 2, 3 as rest argument
MyExtern.f1("foo"); // no rest argument
//MyExtern.f1("foo", "bar"); // String should be Int
MyExtern.f2("foo");
MyExtern.f2(12);
//MyExtern.f2(true); // Bool should be EitherType
}
}
Visibility Externs support the private visibility modifier. However, because the default visibility in an extern class is public, private needs to be explicitly specified.
Specifying private members is helpful when an API intends to allow overriding functions.
Also, Haxe cannot prevent subclasses from reusing field names unless if the fields are included
in the extern definition. This is important on targets such as JavaScript where reusing a super
class’s field name as a new field in a subclass is not supported.
1
2
3
4
5
6
7
8
extern class ExampleSuperClass
{
private function new(); // Require subclassing to use.
// Only allow subclasses access to this overridable function.
private function overridableFunction():String;
// This function is implicitly public:
function doSomething():String;
}
90
6.3
Static Extension
Definition: Static Extension
A static extension allows pseudo-extending existing types without modifying their source.
In Haxe this is achieved by declaring a static method with a first argument of the extending
type and then bringing the defining class into context through using.
Static extensions can be a powerful tool which allows augmenting types without actually changing them. The following example demonstrates the usage:
1
using Main.IntExtender;
2
3
4
5
6
7
class IntExtender {
static public function triple(i:Int) {
return i * 3;
}
}
8
9
10
11
12
13
class Main {
static public function main() {
trace(12.triple());
}
}
Clearly, Int does not natively provide a triple method, yet this program compiles and outputs 36 as expected. This is because the call to 12.triple() is transformed into IntExtender.triple(12)
There are three requirements for this:
1. Both the literal 12 and the first argument of triple are known to be of type Int.
2. The class IntExtender is brought into context through using Main.IntExtender.
3. Int does not have a triple field by itself (if it had, that field would take priority over the
static extension).
Static extensions are usually considered syntactic sugar and indeed they are, but it is worth
noting that they can have a dramatic effect on code readability: Instead of nested calls in the form
of f1(f2(f3(f4(x)))), chained calls in the form of x.f4().f3().f2().f1() can be used.
Following the rules previously described in Resolution Order (Section 3.7.4), multiple using
expressions are checked from bottom to top, with the types within each module as well as the
fields within each type being checked from top to bottom. Using a module (as opposed to a
specific type of a module, see Modules and Paths (Section 3.7)) as static extension brings all its
types into context.
Related content
• Haxe snippets and tutorials about static extensions in the Haxe Code Cookbook.
6.3.1
In the Haxe Standard Library
Several classes in the Haxe Standard Library are suitable for static extension usage. The next
example shows the usage of StringTools:
91
1
2
3
4
5
6
using StringTools;
class Main {
static public function main() {
"adc".replace("d", "b");
}
7 }
While String does not have a replace functionality by itself, the using StringTools
static extension provides one. As usual, the JavaScript output nicely shows the transformation:
1
2
3
Main.main = function() {
StringTools.replace("adc","d","b");
}
The following classes from the Haxe Standard Library are designed to be used as static extensions:
StringTools: Provides extended functionality on strings, such as replacing or trimming.
Lambda: Provides functional methods on iterables.
haxe.EnumTools: Provides type information functionality on enums and their instances.
haxe.macro.Tools: Provides different extensions for working with macros (see Tools (Section 9.4)).
Trivia: “using” using
Since the using keyword was added to the language, it has been common to talk about
certain problems with “using using” or the effect of “using using”. This makes for awkward
English in many cases, so the author of this manual decided to call the feature by what it
actually is: Static extension.
6.4
6.4.1
Pattern Matching
Introduction
Pattern matching is the process of branching depending on a value matching given, possibly
deep patterns. In Haxe, all pattern matching is done within a switch expression (5.17) where
the individual case expressions represent the patterns. Here we will explore the syntax for
different patterns using this data structure as running example:
1
2
3
4
enum Tree {
Leaf(v:T);
Node(l:Tree, r:Tree);
}
Some pattern matcher basics include:
• Patterns will always be matched from top to bottom.
• The topmost pattern that matches the input value has its expression executed.
• A _ pattern matches anything, so case _: is equal to default:
92
Related content
• More about the switch expression (5.17).
• Haxe snippets and tutorials about pattern matching in the Haxe Code Cookbook.
6.4.2
Enum matching
Enums can be matched by their constructors in a natural way:
var myTree = Node(Leaf("foo"), Node(Leaf("bar"), Leaf("foobar")));
var match = switch(myTree) {
// matches any Leaf
case Leaf(_): "0";
// matches any Node that has r = Leaf
case Node(_, Leaf(_)): "1";
// matches any Node that has has
// r = another Node, which has
// l = Leaf("bar")
case Node(_, Node(Leaf("bar"), _)): "2";
// matches anything
case _: "3";
}
trace(match); // 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
The pattern matcher will check each case from top to bottom and pick the first one that
matches the input value. The following manual interpretation of each case rule helps understanding the process:
case Leaf(_): matching fails because myTree is a Node
case Node(_, Leaf(_)): matching fails because the right sub-tree of myTree is not a Leaf,
but another Node
case Node(_, Node(Leaf("bar"), _)): matching succeeds
case _: this is not checked here because the previous line matched
6.4.3
Variable capture
It is possible to catch any value of a sub-pattern by matching it against an identifier:
1
2
3
4
5
6
7
var myTree = Node(Leaf("foo"), Node(Leaf("bar"), Leaf("foobar")));
var name = switch(myTree) {
case Leaf(s): s;
case Node(Leaf(s), _): s;
case _: "none";
}
trace(name); // foo
This would return one of the following:
• If myTree is a Leaf, its name is returned.
• If myTree is a Node whose left sub-tree is a Leaf, its name is returned (this will apply here,
returning "foo").
93
• Otherwise "none" is returned.
It is also possible to use = to capture values which are further matched:
var node = switch(myTree) {
case Node(leafNode = Leaf("foo"), _): leafNode;
case x: x;
}
trace(node); // Leaf(foo)
1
2
3
4
5
Here, leafNode is bound to Leaf("foo") if the input matches that. In all other cases,
myTree itself is returned: case x works similar to case _ in that it matches anything, but
with an identifier name like x it also binds the matched value to that variable.
6.4.4
Structure matching
It is also possible to match against the fields of anonymous structures and instances:
var myStructure = {
name: "haxe",
rating: "awesome"
};
var value = switch(myStructure) {
case { name: "haxe", rating: "poor" }:
throw false;
case { rating: "awesome", name: n }:
n;
case _:
"no awesome language found";
}
trace(value); // haxe
1
2
3
4
5
6
7
8
9
10
11
12
13
In the second case we bind the matched name field to identifier n if rating matches "awesome".
Of course this structure could also be put into the Tree from the previous example to combine
structure and enum matching.
6.4.5
Array matching
Arrays can be matched on fixed length:
1
2
3
4
5
6
7
8
9
var myArray = [1, 6];
var match = switch(myArray) {
case [2, _]: "0";
case [_, 6]: "1";
case []: "2";
case [_, _, _]: "3";
case _: "4";
}
trace(match); // 1
This will trace 1 because myArray[1] matches 6, and myArray[0] is allowed to be anything.
94
6.4.6
Or patterns
The | operator can be used anywhere within patterns to describe multiple accepted patterns:
var match = switch(7) {
case 4 | 1: "0";
case 6 | 7: "1";
case _: "2";
}
trace(match); // 1
1
2
3
4
5
6
If there is a captured variable in an or-pattern, it must appear in both its sub-patterns.
6.4.7
Guards
It is also possible to further restrict patterns with the case ...
if(condition): syntax:
var myArray = [7, 6];
var s = switch(myArray) {
case [a, b] if (b > a):
b + ">" +a;
case [a, b]:
b + "<=" +a;
case _: "found something else";
}
trace(s); // 6<=7
1
2
3
4
5
6
7
8
9
The first case has an additional guard condition if (b > a). It will only be selected if that
condition holds, otherwise matching continues with the next case.
6.4.8
Match on multiple values
Array syntax can be used to match on multiple values:
var s = switch [1, false, "foo"] {
case [1, false, "bar"]: "0";
case [_, true, _]: "1";
case [_, false, _]: "2";
}
trace(s); // 2
1
2
3
4
5
6
This is quite similar to usual array matching, but there are differences:
• The number of elements is fixed, so patterns of different array length will not be accepted.
• It is not possible to capture the switch value in a variable, i.e. case x is not allowed (case
_ still is).
6.4.9
Extractors
Since Haxe 3.1.0
Extractors allow applying transformations to values being matched. This is often useful when
a small operation is required on a matched value before matching can continue:
95
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
enum Test {
TString(s:String);
TInt(i:Int);
}
class Main {
static public function main() {
var e = TString("fOo");
switch(e) {
case TString(temp):
switch(temp.toLowerCase()) {
case "foo": true;
case _: false;
}
case _: false;
}
}
}
Here we have to capture the argument value of the TString enum constructor in a variable
temp and use a nested switch on temp.toLowerCase(). Obviously, we want matching to
succeed if TString holds a value of "foo" regardless of its casing. This can be simplified with
extractors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
enum Test {
TString(s:String);
TInt(i:Int);
}
class Main {
static public function main() {
var e = TString("fOo");
var success = switch(e) {
case TString(_.toLowerCase() => "foo"):
true;
case _:
false;
}
}
}
Extractors are identified by the extractorExpression => match expression. The compiler generates code which is similar to the previous example, but the original syntax was greatly
simplified. Extractors consist of two parts, which are separated by the => operator:
1. The left side can be any expression, where all occurrences of underscore _ are replaced with
the currently matched value.
2. The right side is a pattern which is matched against the result of the evaluation of the left
side.
Since the right side is a pattern, it can contain another extractor. The following example
“chains” two extractors:
96
class Main {
static public function main() {
switch(3) {
case add(_, 1) => mul(_, 3) => a:
trace(a);
}
7
}
1
2
3
4
5
6
8
9
10
11
12
13
14
15
16
static function add(i1:Int, i2:Int) {
return i1 + i2;
}
static function mul(i1:Int, i2:Int) {
return i1 * i2;
}
}
This traces 12 as a result of the calls to add(3, 1), where 3 is the matched value, and
mul(4, 3) where 4 is the result of the add call. It is worth noting that the a on the right side of
the second => operator is a capture variable (6.4.3).
It is currently not possible to use extractors within or-patterns (6.4.6):
1
2
3
4
5
6
7
8
class Main {
static public function main() {
switch("foo") {
// Extractors in or patterns are not allowed
case (_.toLowerCase() => "foo") | "bar":
}
}
}
However, it is possible to have or-patterns on the right side of an extractor, so the previous
example would compile without the parentheses.
6.4.10
Exhaustiveness checks
The compiler ensures that no possible cases are forgotten:
1
2
3
switch(true) {
case false:
} // Unmatched patterns: true
The matched type Bool admits two values true and false, but only false is checked.
6.4.11
Useless pattern checks
In a similar fashion, the compiler detects patterns which will never match the input value:
1
2
3
4
switch(Leaf("foo")) {
case Leaf(_)
| Leaf("foo"): // This pattern is unused
case Node(l,r):
97
5
6
case _: // This pattern is unused
}
6.4.12
Single pattern check
The compiler provides the function match to check if an enum value matches a given pattern:
var myTree = Node(Leaf("foo"), Node(Leaf("bar"), Leaf("foobar")));
var value = "foo";
trace(myTree.match(Leaf(_))); // false
trace(myTree.match(Node(_)|Leaf(_))); // true
trace(myTree.match(Node(Leaf("foo"),_))); // true
trace(myTree.match(Node(Leaf(value),_))); // true
1
2
3
4
5
6
As this function only tests if the pattern is matched, guards and variable capture are unavailable.
The match function is equivalent to a switch with a single case for the given pattern,
returning true, and a default returning false.
myTree.match(Node(_));
// is equivalent to
switch(myTree) {
case Node(_):
true;
case _:
false;
}
1
2
3
4
5
6
7
8
See the EnumValue API documentation (since Haxe 3.2.1) for more information.
6.5
String Interpolation
With Haxe 3 it is no longer necessary to manually concatenate parts of a string due to the introduction of String Interpolation. Special identifiers, denoted by the dollar sign $ within a String
enclosed by single-quote ’ characters, are evaluated as if they were concatenated identifiers:
1
2
3
var x = 12;
// The value of x is 12
trace(’The value of x is $x’);
Furthermore, it is possible to include whole expressions in the string by using ${expr}, with
expr being any valid Haxe expression:
1
2
3
var x = 12;
// The sum of 12 and 3 is 15
trace(’The sum of $x and 3 is ${x + 3}’);
String interpolation is a compile-time feature and has no impact on the runtime. The above
example is equivalent to manual concatenation, which is exactly what the compiler generates:
1
trace("The sum of " + x + " and 3 is " + (x + 3));
98
Of course the use of single-quote enclosed strings without any interpolation remains valid, but
care has to be taken regarding the $ character as it triggers interpolation. If an actual dollar-sign
should be used in the string, $$ can be used.
Trivia: String Interpolation before Haxe 3
String Interpolation has been a Haxe feature since version 2.09. Back then, the macro
Std.format had to be used, being both slower and less comfortable than the new string
interpolation syntax.
6.6
Array Comprehension
Array comprehension in Haxe uses existing syntax to allow concise initialization of arrays. It is
identified by for or while constructs:
1
2
3
4
5
class Main {
static public function main() {
var a = [for (i in 0...10) i];
trace(a); // [0,1,2,3,4,5,6,7,8,9]
6
7
8
9
10
var i = 0;
var b = [while(i < 10) i++];
trace(b); // [0,1,2,3,4,5,6,7,8,9]
}
}
Variable a is initialized to an array holding the numbers 0 to 9. The compiler generates code
which adds the value of each loop iteration to the array, so the following code would be equivalent:
1
2
var a = [];
for (i in 0...10) a.push(i);
Variable b is initialized to an array with the same values, but through a different comprehension style using while instead of for. Again, the following code would be equivalent:
var i = 0;
var b = [];
3 while(i < 10) b.push(i++);
1
2
The loop expression can be anything, including conditions and nested loops, so the following
works as expected:
1
2
3
4
5
6
7
8
9
class Main {
static public function main() {
var a = [
for (a in 1...11)
for(b in 2...4)
if (a % b == 0)
a+ "/" +b
];
// [2/2,3/3,4/2,6/2,6/3,8/2,9/3,10/2]
99
10
11
12
trace(a);
}
}
6.7
Map Comprehension
Map comprehension in Haxe uses existing syntax to allow concise initialization for Map. Maps
are initialized like arrays, but use the map literal syntax with the => operator. It is identified by
for or while constructs:
1
2
3
4
class Main {
static public function main() {
var a = [for (i in 0...5) i => ’number ${i}’];
trace(a); // {0 => number 0, 1 => number 1, 2 => number 2, 3 =>
number 3, 4 => number 4}
5
6
7
8
var i = 0;
var b = [while(i < 5) i => ’number ${i++}’];
trace(b); // {0 => number 0, 1 => number 1, 2 => number 2, 3 =>
number 3, 4 => number 4}
}
9
10
}
Variable a is initialized to an Map holding keys from 0 to 4 and string values. The compiler
generates code which adds the value of each loop iteration to the map, so the following code
would be equivalent:
1
2
var a = new Map();
for (i in 0...5) a.set(i, ’number ${i}’);
Variable b is initialized to an Map with the same keys and values, but through a different comprehension style using while instead of for. Again, the following code would be equivalent:
1
2
3
var i = 0;
var b = new Map();
while(i < 5) b.set(i, ’number ${i++}’);
The loop expression can be anything, including conditions and nested loops, so the following
works as expected:
1
2
3
4
5
6
7
8
9
10
11
12
class Main {
static public function main() {
var a = [
for (x in 0...5)
for(y in 0...5)
if (x != y)
x => y
];
// {0 => 4, 1 => 4, 2 => 4, 3 => 4, 4 => 3}
trace(a);
}
}
100
6.8
Iterators
With Haxe it is very easy to define custom iterators and iterable data types. These concepts are
represented by the types Iterator and Iterable respectively:
1
2
3
4
5
6
7
typedef Iterator = {
function hasNext() : Bool;
function next() : T;
}
typedef Iterable = {
function iterator() : Iterator;
8 }
Any class (2.3) which structurally unifies (3.5.2) with one of these types can be iterated over
using a for-loop (5.13). That is, if the class defines methods hasNext and next with matching return types it is considered an iterator, if it defines a method iterator returning an Iterator
it is considered an iterable type.
1
2
3
4
5
6
class MyStringIterator {
var s:String;
var i:Int;
public function new(s:String) {
this.s = s;
i = 0;
}
7
8
9
10
11
12
13
14
15
16
17
18
public function hasNext() {
return i < s.length;
}
public function next() {
return s.charAt(i++);
}
}
class Main {
static public function main() {
var myIt = new MyStringIterator("string");
for (chr in myIt) {
trace(chr);
}
25
}
26 }
19
20
21
22
23
24
The type MyStringIterator in this example qualifies as iterator: It defines a method
hasNext returning Bool and a method next returning String, making it compatible with
Iterator. The main method instantiates it, then iterates over it.
1
2
3
class MyArrayWrap {
var a:Array;
public function new(a:Array) {
101
this.a = a;
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
}
public function iterator() {
return a.iterator();
}
}
class Main {
static public function main() {
var myWrap = new MyArrayWrap([1, 2, 3]);
for (elt in myWrap) {
trace(elt);
}
}
}
Here we do not setup a full iterator like in the previous example, but instead define that the
MyArrayWrap has a method iterator, effectively forwarding the iterator method of the
wrapped Array type.
Related content
• See the Iterator API documentation.
• Haxe snippets and tutorials about iterators in the Haxe Code Cookbook.
6.9
Function Bindings
Haxe 3 allows binding functions with partially applied arguments. Each function type can be
considered to have a bind field, which can be called with the desired number of arguments in
order to create a new function. This is demonstrated here:
1
2
3
4
5
6
7
8
9
10
11
12
class Main {
static public function main() {
var map = new haxe.ds.IntMap();
var f = map.set.bind(_, "12");
$type(map.set); // Int -> String -> Void
$type(f); // Int -> Void
f(1);
f(2);
f(3);
trace(map); // {1 => 12, 2 => 12, 3 => 12}
}
}
Line 4 binds the function map.set to a variable named f, and applies 12 as second argument.
The underscore _ is used to denote that this argument is not bound, which is shown by comparing the types of map.set and f: The bound String argument is effectively cut from the type,
turning a Int->String->Void type into Int->Void.
A call to f(1) then actually invokes map.set(1, "12"), the calls to f(2) and f(3) are
analogous. The last line proves that all three indices indeed are mapped to the value "12".
102
The underscore _ can be skipped for trailing arguments, so the first argument could be bound
through map.set.bind(1), yielding a String->Void function that sets a new value for index
1 on invocation.
Optional arguments By default, trailing optional arguments are bound to their default values
and do not become arguments of the result function. This can be changed by using an explicit
underscore _ instead, in which case the optional argument of the original function becomes a
non-optional argument of the result function.
1
2
3
4
5
class Main {
static function test(a:Int, ?b:String):Void {}
static public function main() {
var fn = test.bind(1);
$type(fn); // Void->Void
fn(’foo’); //Compiler error: Too many arguments
6
7
8
9
10
11
12
13
var fn = test.bind(1, _);
$type(fn); // ?String->Void
fn(’foo’); //works
}
}
Trivia: Callback
Prior to Haxe 3, Haxe used to know a callback-keyword which could be called with a
function argument followed by any number of binding arguments. The name originated
from a common usage were a callback-function is created with the this-object being bound.
Callback would allow binding of arguments only from left to right as there was no support
for the underscore _. The choice to use an underscore was controversial and several other
suggestions were made, none of which were considered superior. After all, the underscore
_ at least looks like it’s saying “fill value in here”, which nicely describes its semantics.
6.10
Metadata
Several constructs can be attributed with custom metadata:
• class and enum declarations
• Class fields
• Enum constructors
• Expressions
These metadata information can be obtained at runtime through the haxe.rtti.Meta API:
1
2
3
4
5
import haxe.rtti.Meta;
@author("Nicolas")
@:keep
class MyClass {
103
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@range(1, 8)
var value:Int;
@broken
static function method() { }
}
class Main {
static public function main() {
// { author : ["Nicolas"] }
trace(Meta.getType(MyClass));
// [1,8]
trace(Meta.getFields(MyClass).value.range);
// { broken: null }
trace(Meta.getStatics(MyClass).method);
}
}
We can easily identify metadata by the leading @ character, followed by the metadata name
and, optionally, by a number of comma-separated constant arguments enclosed in parentheses.
• Class MyClass has an author metadata with a single String argument "Nicolas", as
well as a :keep metadata without arguments.
• The member variable value has a range metadata with two Int arguments 1 and 8.
• The static method method has a broken metadata without arguments.
The main method accesses these metadata values using their API. The output reveals the
structure of the obtained data:
• There is a field for each metadata, with the field name being the metadata name.
• The field values correspond to the metadata arguments. If there are no arguments, the field
value is null. Otherwise the field value is an array with one element per argument.
Allowed values for metadata arguments are:
• Constants (5.2)
• Arrays declarations (5.5) (if all their elements qualify)
• Object declarations (5.6) (if all their field values qualify)
Compile-time Metadata Metadata starting with :, such as @:keep, is available at compile time
only; it is omitted at runtime. It may be used by macros or by the Haxe compiler itself. Unlike
runtime metadata, arguments to compile-time metadata can be any valid expression.
Built-in Compiler Metadata An exhaustive list of all defined metadata can be obtained by
running haxe --help-metas from command line.
Related content
• See also the Compiler Metadata list (8.1).
104
6.11
Access Control
Access control can be used if the basic visibility (4.4.1) options are not sufficient. It is applicable
at class-level and at field-level and knows two directions:
Allowing access: The target is granted access to the given class or field by using the :allow(target)
metadata (6.10).
Forcing access: A target is forced to allow access to the given class or field by using the :access(target)
metadata (6.10).
In this context, a target can be the dot-path (3.7) to
• a class field,
• a class or abstract type, or
• a package.
Target does not respect imports, so the fully qualified path has to be used.
If it is a class or abstract type, access modification extends to all fields of that type. Likewise,
if it is a package, access modification extends to all types of that package and recursively to all
fields of these types.
1
2
3
4
5
6
7
@:allow(Main)
class MyClass {
static private var foo: Int;
}
class Main {
static public function main() {
8
MyClass.foo;
9
}
10 }
Here, MyClass.foo can be accessed from the main-method because MyClass is annotated
with @:allow(Main). This would also work with @:allow(Main.main) and both versions
could alternatively be annotated to the field foo instead of the class MyClass:
1
2
3
4
5
6
7
8
9
10
class MyClass {
@:allow(Main.main)
static private var foo: Int;
}
class Main {
static public function main() {
MyClass.foo;
}
}
If a type cannot be modified to allow this kind of access, the accessing method may force
access:
1
2
3
class MyClass {
static private var foo: Int;
}
105
4
5
6
7
8
9
class Main {
@:access(MyClass.foo)
static public function main() {
MyClass.foo;
}
10 }
The @:access(MyClass.foo) annotation effectively subverts the visibility of the foo field
within the main-method.
Trivia: On the choice of metadata
The access control language feature uses the Haxe metadata syntax instead of additional
language-specific syntax. There are several reasons for that:
• Additional syntax often adds complexity to the language parsing, and also adds (too)
many keywords.
• Additional syntax requires additional learning by the language user, whereas metadata
syntax is something that is already known.
• The metadata syntax is flexible enough to allow extension of this feature.
• The metadata can be accessed/generated/modified by Haxe macros.
Of course, the main drawback of using metadata syntax is that you get no error report in
case you misspell either the metadata key (@:access for instance) or the class/package name.
However, with this feature you will get an error when you try to access a private field that
you are not allowed to, therefore there is no possibility for silent errors.
Since Haxe 3.1.0
If access is allowed to an interface (2.3.3), it extends to all classes implementing that interface:
class MyClass {
@:allow(I)
static private var foo: Int;
4 }
1
2
3
5
6
7
8
9
interface I { }
class Main implements I {
static public function main() {
10
MyClass.foo;
11
}
12 }
This is also true for access granted to parent classes, in which case it extends to all child
classes.
106
Trivia: Broken feature
Access extension to child classes and implementing classes was supposed to work in Haxe
3.0 and even documented accordingly. While writing this manual it was found that this part
of the access control implementation was simply missing.
6.12
Inline Constructors
Since Haxe 3.1.0
If a constructor is declared to be inline (4.4.2), the compiler may try to optimize it away in
certain situations. There are several requirements for this to work:
• The result of the constructor call must be directly assigned to a local variable.
• The expression of the constructor field must only contain assignments to its fields.
The following example demonstrates constructor inlining:
class Point {
public var x:Float;
3
public var y:Float;
1
2
4
5
6
7
8
9
10
11
12
13
public inline function new(x:Float, y:Float) {
this.x = x;
this.y = y;
}
}
class Main {
static public function main() {
var pt = new Point(1.2, 9.3);
14
}
15 }
A look at the JavaScript output reveals the effect:
1
2
3
4
Main.main = function() {
var pt_x = 1.2;
var pt_y = 9.3;
};
107
Part II
Compiler Reference
108
Chapter 7
Compiler Usage
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 and neko) 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 (Chapter 11) library. By default the most recent version in the local Haxelib repository is used. To require a specific library version use -lib
library_name:version. To require a version from git use -lib library_name:git:https://gi
where the optional #commit can be a branch, tag or commit hash.
-main dot_path Sets the main class.
-D Define a conditional compilation flag (6.1).
Output:
-js file_name.js Generates JavaScript (12.1) source code in specified file.
-as3 directory Generates ActionScript 3 source code in specified directory.
-swf file_name.swf Generates the specified file as Flash (12.2) .swf.
-neko file_name.n Generates Neko (12.3) binary as specified file.
-php directory Generates PHP (12.4) source code in specified directory. Use -D php7 for
PHP7 source code.
109
-cpp directory Generates C++ (12.5) source code in specified directory and compiles it using
native C++ compiler.
-cs directory Generates C# (12.8) source code in specified directory.
-java directory Generates Java (12.7) source code in specified directory and compiles it using the Java Compiler.
-python file_name.py Generates Python (12.9) source code in the specified file.
-lua file_name.lua Generates Lua (12.9) source code in the specified file.
-hl file_name.hl Generates HashLink (12.11) byte code in specified file.
-cppia file_name.cppia Generates the specified script as cppia (12.6) file.
-x Shortcut for compiling and executing a neko file.
--no-output compiles but does not generate any file.
--interp interpret the program using internal macro system.
Other global arguments
-xml Generate XML types description. Useful for API documentation generation tools
like Dox.
-v Turn on verbose mode.
-dce Set the Dead Code Elimination (Section 8.2) mode (default std).
-debug Add debug information to the compiled code.
-resource [@name] Add a named resource file.
-prompt Prompt on error.
-cmd Run the specified command after a successful compilation.
--no-traces Don’t compile trace calls in the program.
--gen-hx-classes Generate hx headers for all input classes.
--display Display code tips to provide completion information for IDEs and editors (8.3.1).
--times Measure compilation times.
--no-inline Disable Inline (Section 4.4.2).
--no-opt Disable code optimizations.
--remap Remap a package to another one.
--macro Call the given initialization macro (9.7) before typing anything else.
--wait Wait on the given port for commands to run).
--connect Connect on the given port and run commands there).
--cwd Set current working directory.
110
Target specific arguments
--php-front Select the name for the php front file.
--php-lib Select the name for the php lib folder.
--php-prefix Prefix all classes with given name.
-swf-version Change the SWF version.
-swf-header Define SWF header (width:height:fps:color).
-swf-lib Add the SWF library to the compiled SWF.
-swf-lib-extern Use the SWF library for type checking.
--flash-strict More type strict flash API.
-java-lib Add an external JAR or class directory library.
-net-lib [@std] Add an external .NET DLL file.
-net-std Add a root std .NET DLL search path.
-c-arg Pass option arg to the native Java/C# compiler.
Trivia: Run commands after compilation
Use -cmd to run the specified command after a successful compilation. It can be used to run
(testing) tools or to directly run the build, e.g. -cmd java -jar bin/Main.jar (for Java),
-cmd node main.js (for Node.js) or -cmd neko Main.n (for Neko) etcetera.
Global compiler configuration macros: In order to include single modules, their paths can be
listed directly on command line or in hxml: haxe ... ModuleName pack.ModuleName.
For more specific includes or excludes, use these initialization macros (9.7):
--macro include(pack:String, recursive=true, ?ignore:Array, ?classPaths:A
Includes all modules in package pack in the compilation. If recursive is true, the compiler recursively adds all sub-packages.
--macro exclude(pack:String, recursive=true Exclude a specific class, enum, or all
classes and enums in a package from being generated. Excluded types become extern. If
recursive is true, the compiler recursively excludes all sub-packages.
--macro excludeFile(fileName:String) Exclude classes and enums listed from given
external file (one per line) from being generated.
--macro keep(?path:String, ?paths:Array, recursive=true) Marks a
package, module or sub-type dot path to be kept by DCE. This also extends to the sub-types
of resolved modules. If recursive is true, the compiler recursively keeps all sub-packages
for package paths.
--macro includeFile(file:String, position) Embed a JavaScript file at compile time.
position can be either ”top”, ”inline” or ”closure”.
The full documentation of these methods can be found in the haxe.macro.Compiler API
documentation.
111
Help
haxe -version Print the current Haxe compiler version.
haxe -help Display this list of options.
haxe --help-defines Print help for all compiler specific defines (7.2).
haxe --help-metas Print help for all compiler metadata (6.1).
Related content
• Compilation tutorials in the Haxe Code Cookbook.
7.1
HXML
Compiler arguments (7) can be stored in a .hxml file and can be executed with haxe .
In hxml it is possible to use newlines and comments which makes it easier to maintain Haxe
build configurations. It is possible to supply more arguments after the hxml file, e.g. haxe
build.hxml -debug.
Example:
This example has a configuration which compiles the class file website.HomePage.hx to
JavaScript into a file called bin/homepage.js, which is located in the src class path. And uses
full dead code elimination.
1
2
3
4
-cp src
-dce full
-js bin/homepage.js
-main website.HomePage
Multiple build compilations Hxml configurations allow multiple compilation using these arguments:
--next Separate several Haxe compilations.
--each Append preceding parameters to all haxe compilations separated by --next. This
reduces the repeating params.
Example:
This example has a configuration which compiles three different classes into their own JavaScript
files. Each build uses src as class path and uses full dead code elimination.
1
2
3
4
5
6
7
8
9
-cp src
-dce full
--each
-js bin/homepage.js
-main website.HomePage
--next
112
10
11
12
13
14
15
16
17
-js bin/gallery.js
-main website.GalleryPage
--next
-js bin/contact.js
-main website.ContactPage
Comments inside hxml Inside .hxml files use a hash (i.e. #) to comment out the rest of the line.
Calling build configurations inside HXML:
It is possible to create a configuration that looks like this:
build-server.hxml
--next
build-website.hxml
4 --next
5 build-game.hxml
1
2
3
7.2
Global Compiler Flags
Starting from Haxe 3.0, you can get the list of supported compiler flags (6.1) by running haxe
--help-defines
Flag
absolute-path
advanced-telemetry
analyzer
as3
check-xml-proxy
core-api
core-api-serialize
cppia
dce=
dce-debug
debug
display
dll-export
dll-import
doc-gen
dump
Global Compiler Flags
Description
Print absolute file path in trace output
Allow the SWF to be measured with Monocle tool
Use static analyzer for optimization (experimental)
Defined when outputing flash9 as3 source code
Check the used fields of the xml proxy
Defined in the core api context
Mark some generated core api classes with the
Serializable attribute on C#
Generate experimental cpp instruction assembly
Set the dead code elimination (8.2) mode (default std)
Show dead code elimination (8.2) log
Activated when compiling with -debug
Activated during completion
GenCPP experimental linking
GenCPP experimental linking
Do not perform any removal/change in order to
correctly generate documentation
Dump the complete typed AST for internal debugging
in a dump subdirectory - use dump=pretty for
Haxe-like formatting
continued on next page
113
Flag
dump-dependencies
dump-ignore-var-ids
erase-generics
fdb
file-extension
flash-strict
flash-use-stage
force-lib-check
force-native-property
format-warning
gencommon-debug
haxe-boot
haxe-ver
hxcpp-api-level
include-prefix
interp
java-ver=[version:5-7]
js-classic
js-es5
js-unflatten
keep-old-output
loop-unroll-max-cost
macro
macro-times
net-ver=
net-target=
neko-source
neko-v1
network-sandbox
Global Compiler Flags
Description
Dump the classes dependencies in a dump subdirectory
Remove variable IDs from non-pretty dumps (helps
with diff)
Erase generic classes on C#
Enable full flash debug infos for FDB interactive
debugging
Output filename extension for cpp source code
More strict typing for flash target
Keep the SWF library initial stage
Force the compiler to check -net-lib and -java-lib added
classes (internal)
Tag all properties with :nativeProperty metadata
for 3.1 compatibility
Print a warning for each formated string, for 2.x
compatibility
GenCommon internal
Given the name ’haxe’ to the flash boot class instead of a
generated name
The current Haxe version value. Version 3.1.3 is 3.103,
version 3.2.0 is 3.200, 3.1.10 is 3.110. version 3.4.0 is
3.400 etc. This allows doing #if (haxe_ver >=
3.103)
Provided to allow compatibility between hxcpp versions
prepend path to generated include files
The code is compiled to be run with --interp
Sets the Java version to be targeted
Don’t use a function wrapper and strict mode in JS
output
Generate JS for ES5-compliant runtimes
Generate nested objects for packages and types
Keep old source files in the output directory (for
C#/Java)
Maximum cost (number of expressions * iterations)
before loop unrolling is canceled (default 250)
Defined when code is compiled in the macro context (9)
Display per-macro timing when used with --times
Sets the .NET version to be targeted
Sets the .NET target. Defaults to net. xbox, micro (Micro
Framework , compact (Compact Framework) are some
valid values
Output neko source instead of bytecode
Keep Neko 1.x compatibility
Use local network sandbox instead of local file access
one
continued on next page
114
Flag
no-compilation
no-copt
no-debug
no-deprecation-warnings
no-flash-override
no-opt
no-pattern-matching
no-inline
no-root
no-macro-cache
no-simplify
no-swf-compress
no-traces
php-prefix
real-position
replace-files
scriptable
shallow-expose
source-map-content
swc
swf-compress-level=<1-9>
swf-debug-password=
swf-direct-blit
swf-gpu
swf-metadata=
swf-preloader-frame
swf-protected
swf-script-timeout
swf-use-doabc
sys
unsafe
use-nekoc
use-rtti-doc
vcproj
Global Compiler Flags
Description
Disable CPP final compilation
Disable completion optimization (for debug purposes)
Remove all debug macros from cpp output
Do not warn if fields annotated with @:deprecated
are used
Change overrides on some basic classes into HX suffixed
methods flash only
Disable optimizations
Disable pattern matching (6.4)
Disable inlining (4.4.2)
GenCS internal
Disable macro context caching
Disable simplification filter
Disable SWF output compression
Disable all trace calls
Compiled with --php-prefix
Disables haxe source mapping when targetting C#
GenCommon internal
GenCPP internal
Expose types to surrounding scope of Haxe generated
closure without writing to window object
Include the hx sources as part of the JS source map
Output a SWC instead of a SWF
Set the amount of compression for the SWF output
Set a password for debugging. The password field is
encrypted by using the MD5 algorithm and prevents
unauthorised debugging of your swf. Without this flag
-D fdb will use no password.
Use hardware acceleration to blit graphics
Use GPU compositing features when drawing graphics
Include contents of as metadata in the swf.
Insert empty first frame in swf. To be used together with
-D flash-use-stage and -swf-lib
Compile Haxe private as protected in the SWF instead of
public
Maximum ActionScript processing time before script
stuck dialog box displays (in seconds)
Use DoAbc swf-tag instead of DoAbcDefine
Defined for all system platforms
Allow unsafe code when targeting C#
Use nekoc compiler instead of internal one
Allows access to documentation during compilation
GenCPP internal
115
Chapter 8
Compiler Features
8.1
Built-in Compiler Metadata
Starting from Haxe 3.0, you can get the list of defined compiler metadata by running haxe
--help-metas
Flag
@:abi
@:abstract
@:access (Target path)
@:allow (Target path)
@:analyzer
@:annotation
@:arrayAccess
@:autoBuild (Build
macro call)
@:bind
@:bitmap (Bitmap file
path)
@:bridgeProperties
@:build (Build macro
call)
@:buildXml
@:callable
@:classCode
@:commutative
@:compilerGenerated
Global Metadata
Description
Function ABI/calling convention
Sets the underlying class implementation as ’abstract’
Forces private access to package type or field, see Access
Control (6.11)
Allows private access from package type or field, see
Access Control (6.11)
Used to configure the static analyzer
Annotation (@interface) definitions on -java-lib
imports will be annotated with this metadata. Has no
effect on types compiled by Haxe
Allows Array access (2.8.3) on an abstract
Extends @:build metadata to all extending and
implementing classes. See Macro autobuild (9.5.2)
Override Swf class declaration
Embeds given bitmap data into the class (must extend
flash.display.BitmapData)
Creates native property bridges for all Haxe properties
in this class
Builds a class or enum from a macro. See Type Building
(9.5)
Specify xml data to be injected into Build.xml
Abstract forwards call to its underlying type
Used to inject platform-native code into a class
Declares an abstract operator as commutative
Marks a field as generated by the compiler. Shouldn’t be
used by the end user
Targets
cpp
cs java
all
all
all
java
all
all
flash
flash
cs
all
cpp
all
cs java
all
cs java
continued on next page
116
Flag
@:coreApi
@:coreType
@:cppFileCode
@:cppInclude
@:cppNamespaceCode
@:dce
@:debug
@:decl
@:delegate
@:depend
@:deprecated
@:event
@:enum
@:expose
(?Name=Class path)
@:extern
@:fakeEnum (Type
name)
@:file(File path)
@:final
@:font (TTF path
Range String)
@:forward (List of field
names)
@:forwardStatics (List
of field names)
@:from
@:functionCode
@:functionTailCode
@:generic
Global Metadata
Description
Identifies this class as a core api class (forces Api check)
Identifies an abstract as core type (2.8.6) so that it
requires no implementation
Code to be injected into generated cpp file
File to be included in generated cpp file
Forces Dead Code Elimination (8.2) even when not -dce
full is specified
Forces debug information to be generated into the Swf
even without -debug
Automatically added by -net-lib on delegates
Automatically added by -java-lib on class fields
annotated with @Deprecated annotation. Has no effect
on types compiled by Haxe
Automatically added by -net-lib on events. Has no
effect on types compiled by Haxe
Defines finite value sets to abstract definitions. See
enum abstracts (2.8.4)
Makes the class available on the window object or
exports for node.js. See exposing Haxe classes for
JavaScript (12.1.6)
Marks the field as extern so it is not generated
Treat enum as collection of values of the specified type
Targets
all
all
cpp
cpp
cpp
all
flash
cpp
cs
cpp
java
cs
all
js
all
all
Includes a given binary file into the target Swf and
associates it with the class (must extend
flash.utils.ByteArray)
Prevents a class from being extended
Embeds the given TrueType font into the class (must
extend flash.text.Font)
Forwards field access (2.8.5) to underlying type
flash
Forwards static field access (2.8.5) to underlying type
all
Specifies that the field of the abstract is a cast operation
from the type identified in the function. See Implicit
Casts (2.8.1)
Injects native code into the beginning of the function
Injects native code into the end of the function
Marks a class or class field as generic (3.3) so each type
parameter combination generates its own type/field
all
all
flash
all
cs cpp
cpp
all
continued on next page
117
Flag
@:genericBuild
@:getter (Class field
name)
@:hack
@:headerClassCode
@:headerCode
@:headerNamespaceCode
@:hxGen
@:ifFeature (Feature
name)
@:include
@:internal
@:isVar
@:javaCanonical
(Output type
package,Output type
name)
@:jsRequire
@:keep
@:keepInit
@:keepSub
@:macro
@:mergeBlock
@:meta
@:multiType (Relevant
type parameters)
@:native (Output type
path)
@:native
@:nativeChildren
@:nativeGen
@:nativeProperty
@:noCompletion
Global Metadata
Description
Builds instances of a type using the specified macro
Generates a native getter function on the given field
Allows extending classes marked as @:final
Code to be injected into the generated class, in the
header
Code to be injected into the generated header file
Annotates that an extern class was generated by Haxe
Causes a field to be kept by DCE (8.2) if the given
feature is part of the compilation
Generates the annotated field/class with internal
access
Forces a physical field to be generated for properties that
otherwise would not require one
Used by the Java target to annotate the canonical path of
the type
Targets
all
flash
all
cpp
cpp
cpp
cs java
all
cpp
cs java
all
java
Generate javascript module require expression for given
extern
Causes a field or type to be kept by DCE (8.2)
Causes a class to be kept by DCE (8.2) even if all its field
are removed
Extends @:keep metadata to all implementing and
extending classes
(deprecated)
Merge the annotated block into the current scope
Internally used to mark a class field as being the
metadata field
Specifies that an abstract chooses its this-type from its
@:to functions
Rewrites the path of a class or enum during generation
js
Add the native keyword to the generated field (JNI)
Annotates that all children from a type should be treated
as if it were an extern definition - platform native
Annotates that a type should be treated as if it were an
extern definition - platform native
Use native properties which will execute even with
dynamic usage
Prevents the compiler from suggesting completion (8.3)
on this field
java
cs java
all
all
all
all
all
all
all
all
cs java
cpp
all
continued on next page
118
Flag
@:noDebug
@:noDoc
@:noImportGlobal
@:noPrivateAccess
@:noStack
@:noUsing
@:nonVirtual
@:notNull
@:ns
@:op (The operation)
@:optional
@:overload (Function
specification)
@:privateAccess
@:property
@:protected
@:public
@:publicFields
@:pythonImport
@:readOnly
@:remove
@:require (Compiler
flag to check)
@:rtti
@:runtime
@:runtimeValue
@:selfCall
@:setter (Class field
name)
@:sound (File path)
Global Metadata
Description
Does not generate debug information into the Swf even
if -debug is set
Prevents a type from being included in documentation
generation
Prevents a static field from being imported with import
Class.*
Disallow private access to anything for the annotated
expression
Prevents a field from being used with using
Declares function to be non-virtual
Declares an abstract type as not accepting null values
(2.2)
Internally used by the Swf generator to handle
namespaces
Declares an abstract field as being an operator overload
(2.8.2)
Marks the field of a structure as optional. See Optional
Arguments (2.2.1)
Allows the field to be called with different argument
types. Function specification cannot be an expression
Allow private access to anything for the annotated
expression
Marks a property field to be compiled as a native C#
property
Marks a class field as being protected
Marks a class field as being public
Forces all class fields of inheriting classes to be public
Generates python import statement for extern classes
Generates a field with the readonly native keyword
Causes an interface to be removed from all
implementing classes before generation
Allows access to a field only if the specified compiler
flag (6.1) is set
Adds runtime type informations. See RTTI (8.5)
Marks an abstract as being a runtime value
Translates method calls into calling object directly
Generates a native setter function on the given field
Includes a given .wav or .mp3 file into the target Swf
and associates it with the class (must extend
flash.media.Sound)
Targets
flash
all
all
all
cpp
all
cpp
all
flash
all
all
all
all
cs
all
all
all
python
cs
all
all
all
all
all
js
flash
flash
continued on next page
119
Flag
@:sourceFile
@:strict
@:struct
@:structAccess
@:structInit
@:suppressWarnings
@:throws (Type as
String)
@:to
@:transient
@:unbound
@:unifyMinDynamic
@:unreflective
@:unsafe
@:value
@:void
@:volatile
8.2
Global Metadata
Description
Source code filename for external class
Used to declare a native C# attribute or a native Java
metadata. Is type checked
Marks a class definition as a struct
Marks an extern class as using struct access(’.’) not
pointer(’-¿’)
Allows one to initialize the class with a structure that
matches constructor parameters
Adds a SuppressWarnings annotation for the generated
Java class
Adds a throws declaration to the generated function
Specifies that the field of the abstract is a cast operation
to the type identified in the function. See Implicit Casts
(2.8.1)
Adds the transient flag to the class field
Compiler internal to denote unbounded global variable
Allows a collection of types to unify to Dynamic
Declares a class or a method with the C#’s unsafe flag
Used to store default values for fields and function
arguments
Use Cpp native ’void’ return type
Targets
cpp
cs java
cs
cpp
all
java
java
all
java
all
all
cpp
cs
all
cpp
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:
-dce std: Only classes in the Haxe Standard Library are affected by DCE. This is the default
setting on all targets.
-dce no: No DCE is performed.
-dce full: All classes are affected by DCE.
The DCE-algorithm works well with typed code, but may fail when dynamic (2.7) or reflection
(10.7) is involved. This may require explicit marking of fields or classes as being used by attributing the following metadata:
@: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.
@:keepSub: If used on a class, it works like @:keep on the annotated class as well as all subclasses.
@: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.
120
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 (6.1).
Trivia: DCE-rewrite
DCE was originally implemented in Haxe 2.07. This implementation considered a function to
be used when it was explicitly typed. The problem with that was that several features, most
importantly interfaces, would cause all class fields to be typed in order to verify type-safety.
This effectively subverted DCE completely, prompting the rewrite for Haxe 2.10.
Trivia: DCE and try.haxe.org
DCE for the JavaScript target saw vast improvements when the website http://try.
haxe.org was published. Initial reception of the generated JavaScript code was mixed,
leading to a more fine-grained selection of which code to eliminate.
8.3
8.3.1
Compiler Services
Overview
The rich type system (3) of the Haxe Compiler makes it difficult for IDEs and editors to provide
accurate completion information. Between type inference (3.6) and macros (9), 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:
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.
position: The byte position (not character position) of where to check for completion in the given
file.
mode: The completion mode to use (see below).
We will look into the following completion modes in detail:
Field access (8.3.2): Provides a list of fields that can be accessed on a given type.
Call argument (8.3.3): Reports the type of the function which is currently being called.
Type path (8.3.4): Lists sub-packages, sub-types and static fields.
Usage (8.3.5): Lists all occurrences of a given type, field or variable in all compiled files. (mode:
"usage")
Position (8.3.6): Reports the position of where a given type, field or variable is defined. (mode:
"position")
Top-level (8.3.7): Lists all identifiers which are available at a given position. (mode: "toplevel")
121
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 (8.3.8) which ensures
that only those files are re-compiled that actually changed or had any of their dependencies
changes.
General notes on the interface
• The position-argument can be set to 0 if the file in question contains a pipeline | character
at the position of interest. This is very useful for demonstration and testing as it allows
us to ignore the byte-counting process a real IDE would have to do. The examples in this
section are making use of this feature. Note that this only works in places where | is not
valid syntax otherwise, e.g. after dots (.|) and opening parentheses ((|).
• The output is HTML-escaped so that &, < and > become &, < and
> respectively.
• Otherwise any documentation output is preserved which means longer documentation
might include new-line and tab-characters as it does in the source files.
• When run in completion mode, the compiler does not display errors but instead tries to
ignore them or recover from them. If a critical error occurs while getting completion, the
Haxe Compiler prints the error message instead of the completion output. Any non-XML
output can be treated as a critical error message.
8.3.2
Field access completion
Field completion is triggered after a dot . character to list the fields that are available on the
given type. The compiler parses and types everything up to the point of completion and then
outputs the relevant information to stderr:
1
2
3
4
5
class Main {
public static function main() {
trace("Hello".|
}
}
If this file is saved to Main.hx, the completion can be invoked using the command haxe
--display Main.hx@0. The output looks similar to this (we omit several fields for brevity
and improve the formatting for readability):
1
2
3
4
5
6
7
8
9
10
11
12
Int
The number of characters in ‘this‘ String.
index : Int -> String
Returns the character at position ‘index‘ of ‘this‘ String.
If ‘index‘ is negative or exceeds ‘this.length‘, the empty String
122
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"" is returned.
index : Int -> Null<Int>
Returns the character code at position ‘index‘ of ‘this‘ String.
If ‘index‘ is negative or exceeds ‘this.length‘, null is returned.
To obtain the character code of a single character, "x".code can
be used instead to inline the character code at compile time.
Note that this only works on String literals of length 1.
The XML structure follows:
• The document node list encloses several nodes i, each representing a field.
• The n attribute contains the name of the field.
• The t node contains the type of the field.
• the d node contains the documentation of the field.
Since Haxe 3.2.0
When compiling with -D display-details, each field additionally has a k attribute which
can either be var or method. This allows distinguishing method fields from variable fields that
have a function type.
8.3.3
Call argument completion
Call argument completion is triggered after an opening parenthesis character ( to show the type
of the function that is currently being called. It works for any function call as well as constructor
calls:
1
2
3
4
5
class Main {
public static function main() {
trace("Hello".split(|
}
}
If this file is saved to Main.hx, the completion can be invoked using the command haxe
--display Main.hx@0. The output looks like this:
1
2
3
delimiter : String -> Array<String>
IDEs can parse this to recognize that the called function requires one argument named delimiter
of type String and returns an Array.
123
Trivia: Problems with the output structure
We acknowledge that the current format requires a bit of manual parsing which can be annoying. In the future we might look into providing a more structured output, especially for
functions.
8.3.4
Type path completion
Type path completion can occur in import declarations (3.7.2), using declarations (6.3) or any
place a type is referenced. We can identify three different cases:
package completion
that package:
This lists all sub-packages of the haxe package as well as all modules in
1
import haxe.|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
124
import module completion This lists all sub-types (3.7.1) of the module haxe.Unserializer
as well as all its public static fields (because these can be imported too):
1
import haxe.Unserializer.|
haxe.TypeResolver
4
5
This value can be set to use custom type resolvers.
1
2
3
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
A type resolver finds a Class or Enum instance from a given String
.
By default, the haxe Type Api is used.
A type resolver must provide two methods:
1. resolveClass(name:String):Class<Dynamic> is called to
determine a Class from a class name
2. resolveEnum(name:String):Enum<Dynamic> is called to
determine an Enum from an enum name
This value is applied when a new Unserializer instance is created.
Changing it afterwards has no effect on previously created
instances.
v : String -> Dynamic
Unserializes ‘v‘ and returns the according value.
26
27
28
29
30
31
This is a convenience function for creating a new instance of
Unserializer with ‘v‘ as buffer and calling its unserialize()
method once.
32
33
34
1
using haxe.Unserializer.|
other module completion This lists all sub-types (3.7.1) of the module haxe.Unserializer:
1
using haxe.Unserializer.|
125
1
2
3
4
5
class Main {
static public function main() {
var x:haxe.Unserializer.|
}
}
1
2
3
4
8.3.5
Usage completion
Since Haxe 3.2.0
Usage completion is enabled by using the "usage" mode argument (see Overview (Section 8.3.1)). We demonstrate it here using a local variable. Note that it would work with fields
and types the same way:
1
2
3
4
5
6
7
8
class Main {
public static function main() {
var a = 1;
var b = a + 1;
trace(a);
a.|
}
}
If this file is saved to Main.hx, the completion can be invoked using the command haxe
--display Main.hx@0@usage. The output looks like this:
main.hx:4: characters 9-10
main.hx:5: characters 7-8
4 main.hx:6: characters 1-2
5
1
2
3
8.3.6
Position completion
Since Haxe 3.2.0
Position completion is enabled by using the "position" mode argument (see Overview
(Section 8.3.1)). We demonstrate it using a field. Note that it would work with local variables
and types the same way:
1
2
3
4
class Main {
static public function main() {
"foo".split.|
}
126
If this file is saved to Main.hx, the completion can be invoked using the command haxe
--display Main.hx@0@position. The output looks like this:
1
2
3
std/string.hx:124: characters 1-54
Trivia: Effects of omitting a target specifier
In this example the compiler reports the standard String.hx definition which does not actually have an implementation. This happens because we did not specify any target, which
is allowed in completion-mode. If the command line arguments included, say, -neko
neko.n, the reported position would instead be std/neko/_std/string.hx:84:
lines 84-98.
8.3.7
Top-level completion
Since Haxe 3.2.0
Top-level completion displays all identifiers which the Haxe Compiler knows about at a given
compilation position. This is the only completion method for which we need a real position
argument in order to demonstrate its effect:
class Main {
static public function main() {
3
var a = 1;
4
}
5 }
1
2
6
7
8
enum MyEnum {
MyConstructor1;
9
MyConstructor2(s:String);
10 }
If this file is saved to Main.hx, the completion can be invoked using the command haxe
--display Main.hx@63@toplevel. The output looks similar to this (we omit several entries
for brevity):
1
2
3
4
5
6
7
8
9
10
11
12
a
main
MyConstructor1
MyConstructor2
sys
haxe
Int
Float
MyEnum
Main
127
The structure of the XML depends on the k attribute of each entry. In all cases the node value
of the i nodes contains the relevant name.
local, member, static, enum, global: The t attribute holds the type of the variable or field.
global, type: The p attribute holds the path of the module which contains the type or field.
8.3.8
Completion server
To get the best speed for both compilation and completion, you can use the --wait commandline parameter to start a Haxe compilation server. You can also use -v to have the server print
the log. Here’s an example:
1
haxe -v --wait 6000
You can then connect to the Haxe server, send command-line parameters followed by a 0 byte
and, then, read the response (either completion result or errors).
Use the --connect command-line parameter to have Haxe send its compilation commands
to the server instead of executing them directly :
1
haxe --connect 6000 myproject.hxml
Please note that you can use the parameter --cwd at the first sent command line to change
the Haxe server’s current working directory. Usually class paths and other files are relative to
your project.
How it works
The compilation server will cache the following things:
parsed files the files will only get parsed again if they are modified or if there was a parse error
haxelib calls the previous results of haxelib calls will be reused (only for completion : they are
ignored when doing a compilation)
typed modules compilation modules will be cached after a successful compilation and can be
reused in later compilation/completions if none of their dependencies have been modified
You can get precise reading of the times spent by the compiler and how using the compilation
server affects them by adding --times to the command line.
Protocol As the following Haxe/Neko example shows, you can simply connect on the server
port and send all commands (one per line) ending with a 0 binary char. You can, then, read the
results.
Macros and other commands can log events which are not errors. From the command line,
we can see the difference between what is printed on stdout and what is print on stderr. This
is not the case in socket mode. In order to differentiate between the two, log messages (not errors)
are prefixed with a
x01 character and all newline-characters in the message are replaced by the same
x01 character.
Warnings and other messages can also be considered errors, but are not fatal ones. If a fatal
error occurred, it will send a single
x02 message-line.
Here’s some code that will treat connection to the server and handle the protocol details:
128
class Main {
static function main() {
var newline = "\n";
var s = new sys.net.Socket();
s.connect(new sys.net.Host("127.0.0.1"),6000);
s.write("--cwd /my/project" + newline);
7
s.write("myproject.hxml" + newline);
8
s.write("\000");
1
2
3
4
5
6
9
10
11
12
var hasError = false;
for (line in s.read().split(newline)) {
switch (line.charCodeAt(0)) {
case 0x01:
Sys.print(line.substr(1).split("\x01").join(
newline));
case 0x02:
hasError = true;
default:
Sys.stderr().writeString(line + newline);
}
}
if (hasError) Sys.exit(1);
13
14
15
16
17
18
19
20
21
22
23
}
}
Effect on macros
8.4
The compilation server can have some side effects on macro execution (9).
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.
8.4.1
Embedding resources
External files are embedded using the -resource compiler argument:
1
-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.
8.4.2
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:
129
1
2
3
4
5
class Main {
static function main() {
trace(haxe.Resource.getString("welcome"));
}
}
The code above will display the content of the hello message.txt file that we included earlier
using welcome as the identifier.
8.4.3
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");
4
trace(bytes.readString(0, bytes.length));
5
}
6 }
1
2
3
The return type of getBytes method is haxe.io.Bytes, which is an object providing access
to individual bytes of the data.
8.4.4
Implementation details
Haxe uses the target platform’s native resource embedding if there is one, otherwise it provides
its own implementation.
• Flash resources are embedded as ByteArray definitions
• C# resources are included in the compiled assembly
• Java resources are packed in the resulting JAR file
• C++ resources are stored in global byte array constants.
• JavaScript resources are serialized in Haxe serialization format and stored in a static field of
haxe.Resource class.
• Neko resources are stored as strings in a static field of haxe.Resource class.
8.5
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 (Section 8.5.1).
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:
130
@:rtti
class Main {
var x:String;
static function main() {
var rtti = haxe.rtti.Rtti.getRtti(Main);
trace(rtti);
7
}
8 }
1
2
3
4
5
6
8.5.1
RTTI structure
General type information
path: The type path (3.7) of the type.
module: The type path of the module (3.7) containing the type.
file: The full slash path of the .hx file containing the type. This might be null in case there is no
such file, e.g. if the type is defined through a macro (9).
params: An array of strings representing the names of the type parameters (3.2) the type has. As
of Haxe 3.2.0, this does not include the constraints (3.2.1).
doc: The documentation of the type. This information is only available if the compiler flag (6.1)
-D use_rtti_doc was in place. Otherwise, or if the type has no documentation, the
value is null.
isPrivate: Whether or not the type is private (3.7.1).
platforms: A list of strings representing the targets where the type is available.
meta: The meta data the type was annotated with.
Class type information
isExtern: Whether or not the class is extern (6.2).
isInterface: Whether or not the class is actually an interface (2.3.3).
superClass: The class’ parent class defined by its type path and list of type parameters.
interfaces: The list of interfaces defined by their type path and list of type parameters.
fields: The list of member class fields (4), described in Class field information (Section 8.5.1).
statics: The list of static class fields, described in Class field information (Section 8.5.1).
tdynamic: The type which is dynamically implemented (2.7.2) by the class or null if no such
type exists.
Enum type information
isExtern: Whether or not the enum is extern (6.2).
constructors: The list of enum constructors.
131
Abstract type information
to: An array containing the defined implicit to casts (2.8.1).
from: An array containing the defined implicit from casts (2.8.1).
impl: The class type information (8.5.1) of the implementing class.
athis: The underlying type (2.8) of the abstract.
Class field information
name: The name of the field.
type: The type of the field.
isPublic: Whether or not the field is public (4.4.1).
isOverride: Whether or not the field overrides (4.4.4) another field.
doc: The documentation of the field. This information is only available if the compiler flag (6.1)
-D use_rtti_doc was in place. Otherwise, or if the field has no documentation, the
value is null.
get: The read access behavior (4.2) of the field.
set: The write access behavior (4.2) of the field.
params: An array of strings representing the names of the type parameters (3.2) the field has. As
of Haxe 3.2.0, this does not include the constraints (3.2.1).
platforms: A list of strings representing the targets where the field is available.
meta: The meta data the field was annotated with.
line: The line number where the field is defined. This information is only available if the field
has an expression. Otherwise the value is null.
overloads: The list of available overloads for the fields or null if no overloads exists.
Enum constructor information
name: The name of the constructor.
args: The list of arguments the constructor has or null if no arguments are available.
doc: The documentation of the constructor. This information is only available if the compiler
flag (6.1) -D use_rtti_doc was in place. Otherwise, or if the constructor has no documentation, the value is null.
platforms: A list of strings representing the targets where the constructor is available.
meta: The meta data the constructor was annotated with.
132
8.6
Static Analyzer
Since Haxe 3.3.0
Haxe 3.3.0 introduces a new static analyzer for code optimizations. It is enabled by using the
-D analyzer-optimize compiler flag (7.2) and consists of multiple modules (8.6) which can
be configured globally with a compiler flag (7.2) as well as at type-level and field-level with a
compiler metadata (8.1):
Global configuration To globally enable an analyzer module -D analyzer-module is used.
To globally disable a module -D analyzer-no-module is used. In both cases “module” represents the name of the module to be disabled or enabled:
1
2
3
4
# Global enable from command line
haxe -D analyzer-module
# Global disable from command line
haxe -D analyzer-no-module
Local configuration To enable an analyzer module for a given type or field @:analyzer(module)
is used. To disable a module @:analyzer(no_module) is used. In both cases “module” represents the name of the module to be disabled or enabled:
@:analyzer(module)
class C {
@:analyzer(module) function f() { } // Field-level enable
@:analyzer(no_module) function f() { } // Field-level disable
}
@:analyzer(no_module)
7 class D { } // Type-level disable
1
2
3
4
5
6
Modules The static analyzer currently comes with the following modules. Unless noted otherwise they are enabled if -D analyzer is used.
const_propagation : Implements sparse conditional constant propagation to promote values
that are known at compile-time to usage places. Also detects dead branches.
copy_propagation : Detects local variables that alias other local variables and replaces them
accordingly.
local_dce : Detects and removes unused local variables.
fusion : Moves variable expressions to its usage in case of single-occurrence. By default, only
compiler-generated variables are handled. This can be changed by using the compiler flag
‘-D analyzer-user-var-fusion or the metadata @:analyzer(user_var_fusion).
purity_inference : Infers if fields are “pure”, i.e. do not have any side-effects. This can
improve the effect of the fusion module.
133
Chapter 9
Macros
Macros are without a doubt the most advanced feature in Haxe. They are often perceived as dark
magic that only a select few are capable of mastering, yet there is nothing magical (and certainly
nothing dark) about them.
Definition: Abstract Syntax Tree (AST)
The AST is the result of parsing Haxe code into a typed structure. This structure is exposed
to macros through the types defined in the file haxe/macro/Expr.hx of the Haxe Standard
Library.
• Expression
• Complex Type
• haxe.macro.Expr
parse
Lexer / Parser
Source code
Output
Abstract Syntax Tree (AST)
• Typed Expression
• Type
• haxe.macro.Type
Macro processor
transform
generate
Generator
Typer
Typed AST
Abstract Syntax Tree (AST)
type
Figure 9.1: The role of macros during compilation.
A basic macro is a syntax-transformation. It receives zero or more expressions (5) and also
134
returns an expression. If a macro is called, it effectively inserts code at the place it was called
from. In that respect, it could be compared to a preprocessor like #define in C++, but a Haxe
macro is not a textual replacement tool.
We can identify different kinds of macros, which are run at specific compilation stages:
Initialization Macros: These are provided by command line using the --macro compiler parameter. They are executed after the compiler arguments were processed and the typer
context has been created, but before any typing was done (see Initialization Macros (Section 9.7)).
Build Macros: These are defined for classes, enums and abstracts through the @:build or @:autoBuild
metadata (6.10). They are executed per-type, after the type has been set up (including its
relation to other types, such as inheritance for classes) but before its fields are typed (see
Type Building (Section 9.5)).
Expression Macros: These are normal functions which are executed as soon as they are typed.
Related content
• See the macro API documentation for details about its tools, classes an methods.
• See the macro snippets and tutorials section in the Haxe Code Cookbook.
9.1
Macro Context
Definition: Macro Context
The macro context is the environment in which the macro is executed. Depending on the
macro type, it can be considered to be a class being built or a function being typed. Contextual
information can be obtained through the haxe.macro.Context API.
Haxe macros have access to different contextual information depending on the macro type. Other
than querying such information, the context also allows some modifications such as defining a
new type or registering certain callbacks. It is important to understand that not all information
is available for all macro kinds, as the following examples demonstrate:
• Initialization macros will find that the Context.getLocal*() methods return null.
There is no local type or method in the context of an initialization macro.
• Only build macros get a proper return value from Context.getBuildFields(). There
are no fields being built for the other macro kinds.
• Build macros have a local type (if incomplete), but no local method, so Context.getLocalMethod()
returns null.
The context API is complemented by the haxe.macro.Compiler API detailed in Initialization Macros (Section 9.7). While this API is available to all macro kinds, care has to be taken for
any modification outside of initialization macros. This stems from the natural limitation of undefined build order (9.6.3), which could cause e.g. a flag definition through Compiler.define()
to take effect before or after a conditional compilation (6.1) check against that flag.
135
Related content
• See the macro Context API documentation.
• See the macro snippets and tutorials section in the Haxe Code Cookbook.
9.2
Arguments
Most of the time, arguments to macros are expressions represented as an instance of enum
Expr. As such, they are parsed but not typed, meaning they can be anything conforming to
Haxe’s syntax rules. The macro can then inspect their structure, or (try to) get their type using
haxe.macro.Context.typeof().
It is important to understand that arguments to macros are not guaranteed to be evaluated,
so any intended side-effect is not guaranteed to occur. On the other hand, it is also important to
understand that an argument expression may be duplicated by a macro and used multiple times
in the returned expression:
1
2
3
4
5
6
7
8
9
10
11
12
13
import haxe.macro.Expr;
class Main {
static public function main() {
var x = 0;
var b = add(x++);
trace(x); // 2
}
macro static function add(e:Expr) {
return macro $e + $e;
}
}
The macro add is called with x++ as argument and thus returns x++ + x++ using expression
reification (9.3.1), causing x to be incremented twice.
9.2.1
ExprOf
Since Expr is compatible with any possible input, Haxe provides the type haxe.macro.ExprOf.
For the most part, this type is identical to Expr, but it allows constraining the type of accepted
expressions. This is useful when combining macros with static extensions (6.3):
1
2
3
4
import haxe.macro.Expr;
using Main;
class Main {
static public function main() {
identity("foo");
identity(1);
"foo".identity();
// Int has no field identity
//1.identity();
11
}
5
6
7
8
9
10
12
13
macro static function identity(e:ExprOf) {
136
14
15
16
return e;
}
}
The two direct calls to identity are accepted, even though the argument is declared as
ExprOf. It might come as a surprise that the Int 1 is accepted, but it is a logical
consequence of what was explained about macro arguments (9.2): The argument expressions are
never typed, so it is not possible for the compiler to check their compatibility by unifying (3.5).
This is different for the next two lines which are using static extensions (note the using
Main): For these it is mandatory to type the left side ("foo" and 1) first in order to make sense
of the identity field access. This makes it possible to check the types against the argument
types, which causes 1.identity() to not consider Main.identity() as a suitable field.
9.2.2
Constant Expressions
A macro can be declared to expect constant (5.2) arguments:
class Main {
static public function main() {
3
const("foo", 1, 1.5, true);
4
}
1
2
5
6
7
8
9
10
11
12
13
macro static function const(s:String, i:Int, f:Float, b:Bool) {
trace(s);
trace(i);
trace(f);
trace(b);
return macro null;
}
}
With these it is not necessary to detour over expressions as the compiler can use the provided
constants directly.
9.2.3
Rest Argument
If the final argument of a macro is of type Array, the macro accepts an arbitrary number
of extra arguments which are available from that array:
1
2
3
4
5
6
import haxe.macro.Expr;
class Main {
static public function main() {
myMacro("foo", a, b, c);
}
7
8
9
10
11
12
13
14
macro static function myMacro(e1:Expr, extra:Array) {
for (e in extra) {
trace(e);
}
return macro null;
}
}
137
9.3
Reification
The Haxe Compiler allows reification of expressions, types and classes to simplify working with
macros. The syntax for reification is macro expr, where expr is any valid Haxe expression.
9.3.1
Expression Reification
Expression reification is used to create instances of haxe.macro.Expr in a convenient way.
The Haxe Compiler accepts the usual Haxe syntax and translates it to an expression object. It
supports several escaping mechanisms, all of which are triggered by the $ character:
${} and $e{}: Expr -> Expr This can be used to compose expressions. The expression within
the delimiting { } is executed, with its value being used in place.
$a{}: Array -> Array or Array -> Expr If used in a place where
an Array is expected (e.g. call arguments, block elements), $a{} treats its value as
that array. Otherwise it generates an array declaration.
$b{}: Array -> Expr Generates a block expression from the given expression array.
$i{}: String -> Expr Generates an identifier from the given string.
$p{}: Array -> Expr Generates a field expression from the given string array.
$v{}: Dynamic -> Expr Generates an expression depending on the type of its argument. This
is only guaranteed to work for basic types (2.1) and enum instances (2.4).
Additionally the metadata (6.10) @:pos(p) can be used to map the position of the annotated
expression to p instead of the place it is reified at.
This kind of reification only works in places where the internal structure expects an expression. This disallows object.${fieldName}, but object.$fieldName works. This is true for
all places where the internal structure expects a string:
• field access object.$name
• variable name var $name = 1;
Since Haxe 3.1.0
• field name { $name:
1}
• function name function $name() { }
• catch variable name try e() catch($name:Dynamic) { }
Furthermore, a new expression can be reified by providing haxe.macro.TypePath argument:
new $typePath()
9.3.2
Type Reification
Type reification is used to create instances of haxe.macro.Expr.ComplexType in a convenient way. It is identified by a macro : Type, where Type can be any valid type path expression. This is similar to explicit type hints in normal code, e.g. for variables in the form of var
x:Type.
Each constructor of ComplexType has a distinct syntax:
138
TPath: macro :
pack.Type
TFunction: macro :
Arg1 -> Arg2 -> Return
TAnonymous: macro :
{ field:
Type }
TParent: macro :
(Type)
TExtend: macro :
{> Type, field:
TOptional: macro :
9.3.3
Type }
?Type
Class Reification
It is also possible to use reification to obtain an instance of haxe.macro.Expr.TypeDefinition.
This is indicated by the macro class syntax as shown here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Main {
macro static function generateClass(funcName:String) {
var c = macro class MyClass {
public function new() { }
public function $funcName() {
trace($v{funcName} + " was called");
}
}
haxe.macro.Context.defineType(c);
return macro new MyClass();
}
public static function main() {
var c = generateClass("myFunc");
c.myFunc();
}
}
The generated TypeDefinition instance is typically passed to haxe.macro.Context.defineType
in order to add a new type to the calling context (not the macro context itself).
This kind of reification can also be useful to obtain instances of haxe.macro.Expr.Field,
which are available from the fields array of the generated TypeDefinition.
9.4
Tools
The Haxe Standard Library comes with a set of tool-classes to simplify working with macros.
These classes work best as static extensions (6.3) and can be brought into context either individually or as a whole through using haxe.macro.Tools. These classes are:
ComplexTypeTools: Allows printing ComplexType instances in a human-readable way. Also
allows determining the Type corresponding to a ComplexType.
ExprTools: Allows printing Expr instances in a human-readable way. Also allows iterating
and mapping expressions.
MacroStringTools: Offers useful operations on strings and string expressions in macro context.
139
TypeTools: Allows printing Type instances in a human-readable way. Also offers several
useful operations on types, such as unifying (3.5) them or getting their corresponding
ComplexType.
Furthermore the haxe.macro.Printer class has public methods for printing various types
as a human-readable format. This can be helpful when debugging macros.
Trivia: The tinkerbell library and why Tools.hx works
We learned about static extensions that using a module implies that all its types are brought
into static extension context. As it turns out, such a type can also be a typedef (3.1) to another
type. The compiler then considers this type part of the module, and extends static extension
accordingly.
This “trick” was first used in Juraj Kirchheim’s tinkerbell1 library for exactly the same
purpose. Tinkerbell provided many useful macro tools long before they made it into the
Haxe Compiler and Haxe Standard Library. It remains the primary library for additional
macro tools and offers other useful functionality as well.
9.5
Type Building
Type-building macros are different from expression macros in several ways:
• They do not return expressions, but an array of class fields. Their return type must be set
explicitly to Array.
• Their context (9.1) has no local method and no local variables.
• Their context does have build fields, available from haxe.macro.Context.getBuildFields().
• They are not called directly, but are argument to a @:build or @:autoBuild metadata
(6.10) on a class (2.3) or enum (2.4) declaration.
The following example demonstrates type building. Note that it is split up into two files
for a reason: If a module contains a macro function, it has to be typed into macro context as
well. This is often a problem for type-building macros because the type to be built could only
be loaded in its incomplete state, before the building macro has run. We recommend to always
define type-building macros in their own module.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import haxe.macro.Context;
import haxe.macro.Expr;
class TypeBuildingMacro {
macro static public function build(fieldName:String):Array {
var fields = Context.getBuildFields();
var newField = {
name: fieldName,
doc: null,
meta: [],
access: [AStatic, APublic],
kind: FVar(macro : String, macro "my default"),
pos: Context.currentPos()
};
fields.push(newField);
140
16
17
18
1
2
3
4
5
6
return fields;
}
}
@:build(TypeBuildingMacro.build("myFunc"))
class Main {
static public function main() {
trace(Main.myFunc); // my default
}
}
The build method of TypeBuildingMacro performs three steps:
1. It obtains the build fields using Context.getBuildFields().
2. It declares a new haxe.macro.expr.Field field using the funcName macro argument
as field name. This field is a String variable (4.1) with a default value "my default"
(from the kind field) and is public and static (from the access field).
3. It adds the new field to the build field array and returns it.
This macro is argument to the @:build metadata on the Main class. As soon as this type is
required, the compiler does the following:
1. It parses the module file, including the class fields.
2. It sets up the type, including its relation to other types through inheritance (2.3.2) and
interfaces (2.3.3).
3. It executes the type-building macro according to the @:build metadata.
4. It continues typing the class normally with the fields returned by the type-building macro.
This allows adding and modifying class fields at will in a type-building macro. In our example, the macro is called with a "myFunc" argument, making Main.myFunc a valid field access.
If a type-building macro should not modify anything, the macro can return null. This indicates to the compiler that no changes are intended and is preferable to returning Context.getBuildFields(
9.5.1
Enum building
Building enums (2.4) is analogous to building classes with a simple mapping:
• Enum constructors without arguments are variable fields FVar.
• Enum constructors with arguments are method fields FFun.
1
2
3
4
5
6
import haxe.macro.Context;
import haxe.macro.Expr;
class EnumBuildingMacro {
macro static public function build():Array {
var noArgs = makeEnumField("A", FVar(null, null));
7
var eFunc = macro function(value:Int) { };
8
var fInt = switch (eFunc.expr) {
9
case EFunction(_,f): f;
141
case _: throw "false";
}
var intArg = makeEnumField("B", FFun(fInt));
return [noArgs, intArg];
10
11
12
13
14
15
}
static function makeEnumField(name, kind) {
return {
name: name,
doc: null,
meta: [],
access: [],
kind: kind,
pos: Context.currentPos()
}
}
16
17
18
19
20
21
22
23
24
25
26
1
2
3
4
5
6
7
8
9
10
11
}
@:build(EnumBuildingMacro.build())
enum E { }
class Main {
static public function main() {
switch(E.A) {
case A:
case B(v):
}
}
}
Because enum E is annotated with a :build metadata, the called macro builds two constructors A and B “into” it. The former is added with the kind being FVar(null, null), meaning
it is a constructor without argument. For the latter, we use reification (9.3.1) to obtain an instance
of haxe.macro.Expr.Function with a singular Int argument.
The main method proves the structure of our generated enum by matching (6.4) it. We can
see that the generated type is equivalent to this:
1
2
3
4
enum E {
A;
B(value:Int);
}
9.5.2
@:autoBuild
If a class has the :autoBuild metadata, the compiler generates :build metadata on all extending classes. If an interface has the :autoBuild metadata, the compiler generates :build
metadata on all implementing classes and all extending interfaces. Note that :autoBuild does
not imply :build on the class/interface itself.
1
2
3
import haxe.macro.Context;
import haxe.macro.Expr;
142
4
5
6
7
8
9
class AutoBuildingMacro {
macro static public
function fromInterface():Array {
trace("fromInterface: " + Context.getLocalType());
return null;
}
10
11
12
13
14
15
macro static public
function fromBaseClass():Array {
trace("fromBaseClass: " + Context.getLocalType());
return null;
}
16
}
1
2
3
4
5
@:autoBuild(AutoBuildingMacro.fromInterface())
interface I { }
6
7
8
9
10
@:autoBuild(AutoBuildingMacro.fromBaseClass())
class Base { }
interface I2 extends I { }
class Main extends Base implements I2 {
static public function main() { }
11 }
This outputs during compilation:
AutoBuildingMacro.hx:6:
fromInterface: TInst(I2,[])
AutoBuildingMacro.hx:6:
4
fromInterface: TInst(Main,[])
5 AutoBuildingMacro.hx:11:
6
fromBaseClass: TInst(Main,[])
1
2
3
It is important to keep in mind that the order of these macro executions is undefined, which
is detailed in Build Order (Section 9.6.3).
Related content
• Haxe snippets and tutorials about build macros in the Haxe Code Cookbook.
9.5.3
@:genericBuild
Since Haxe 3.1.0
Normal build-macros (9.5) are run per-type and are already very powerful. In some cases it is
useful to run a build macro per type usage instead, i.e. whenever it actually appears in the code.
Among other things this allows accessing the concrete type parameters in the macro.
@:genericBuild is used just like @:build by adding it to a type with the argument being
a macro call:
1
2
import haxe.macro.Expr;
import haxe.macro.Context;
143
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
import haxe.macro.Type;
class GenericBuildMacro1 {
static public function build() {
switch (Context.getLocalType()) {
case TInst(_, [t1]):
trace(t1);
case t:
Context.error("Class expected", Context.currentPos());
}
return null;
}
}
@:genericBuild(GenericBuildMacro1.build())
class MyType { }
class Main {
static function main() {
var x:MyType;
var x:MyType;
}
}
When running this example the compiler outputs TAbstract(Int,[]) and TInst(String,[]),
indicating that it is indeed aware of the concrete type parameters of MyType. The macro logic
could use this information to generate a custom type (using haxe.macro.Context.defineType)
or refer to an existing one. For brevity we return null here which asks the compiler to infer (3.6)
the type.
In Haxe 3.1 the return type of a @:genericBuild macro has to be a haxe.macro.Type.
Haxe 3.2 allows (and prefers) returning a haxe.macro.ComplexType instead, which is the
syntactic representation of a type. This is easier to work with in many cases because types can
simply be referenced by their paths.
Const type parameter Haxe allows passing constant expression (5.2) as a type parameter if the
type parameter name is Const. This can be utilized in the context of @:genericBuild macros
to pass information from the syntax directly to the macro:
1
2
3
4
import haxe.macro.Expr;
import haxe.macro.Context;
import haxe.macro.Type;
5
6
7
8
class GenericBuildMacro2 {
static public function build() {
switch (Context.getLocalType()) {
case TInst(_,[TInst(_.get() => { kind: KExpr(macro $v{(s:String)
}) },_)]):
trace(s);
case t:
Context.error("Class expected", Context.currentPos());
}
return null;
9
10
11
12
13
144
14
15
}
}
1
2
3
@:genericBuild(GenericBuildMacro2.build())
class MyType { }
4
5
6
7
8
class Main {
static function main() {
var x:MyType<"myfile.txt">;
}
}
Here the macro logic could load a file and use its contents to generate a custom type.
Related content
• Haxe snippets and tutorials about build macros in the Haxe Code Cookbook.
9.6
Limitations
9.6.1
Macro-in-Macro
9.6.2
Static extension
The concepts of static extensions (6.3) and macros are somewhat conflicting: While the former
requires a known type in order to determine used functions, macros execute before typing on
plain syntax. It is thus not surprising that combining these two features can lead to issues. Haxe
3.0 would try to convert the typed expression back to a syntax expression, which is not always
possible and may lose important information. We recommend that it is used with caution.
Since Haxe 3.1.0
The combination of static extensions and macros was reworked for the 3.1.0 release. The Haxe
Compiler does not even try to find the original expression for the macro argument and instead
passes a special @:this this expression. While the structure of this expression conveys no
information, the expression can still be typed correctly:
1
2
3
4
5
import haxe.macro.Context;
import haxe.macro.Expr;
using Main;
using haxe.macro.Tools;
6
7
8
9
10
11
class Main {
static public function main() {
#if !macro
var a = "foo";
a.test();
12
#end
13
}
14
15
16
17
macro static function test(e:ExprOf) {
trace(e.toString()); // @:this this
// TInst(String,[])
145
18
19
20
21
trace(Context.typeof(e));
return e;
}
}
9.6.3
Build Order
The build order of types is unspecified and this extends to the execution order of build-macros
(9.5). While certain rules can be determined, we strongly recommend to not rely on the execution
order of build-macros. If type building requires multiple passes, this should be reflected directly
in the macro code. In order to avoid multiple build-macro execution on the same type, state can
be stored in static variables or added as metadata (6.10) to the type in question:
1
2
3
4
5
6
import haxe.macro.Context;
import haxe.macro.Expr;
#if !macro
@:autoBuild(MyMacro.build())
#end
7 interface I1 { }
8
9
10
11
12
13
14
15
16
17
18
#if !macro
@:autoBuild(MyMacro.build())
#end
interface I2 { }
class C implements I1 implements I2 { }
19
20
21
22
23
24
class MyMacro {
macro static public function build():Array {
var c = Context.getLocalClass().get();
if (c.meta.has(":processed")) return null;
c.meta.add(":processed",[],c.pos);
// process here
return null;
}
}
25
26
27
28
class Main {
static public function main() { }
}
With both interfaces I1 and I2 having :autoBuild metadata, the build macro is executed
twice for class C. We guard against duplicate processing by adding a custom :processed metadata to the class, which can be checked during the second macro execution.
9.6.4
9.7
Type Parameters
Initialization Macros
Initialization macros are invoked from command line by using the --macro callExpr(args)
command. This registers a callback which the compiler invokes after creating its context, but
146
before typing what was argument to -main. This then allows configuring the compiler in some
ways.
If the argument to --macro is a call to a plain identifier, that identifier is looked up in the
class haxe.macro.Compiler which is part of the Haxe Standard Library. It comes with several
useful initialization macros which are detailed in its API.
As an example, the include macro allows inclusion of an entire package for compilation, recursively if necessary. The command line argument for this would then be --macro include(’some.pack’
true).
Of course it is also possible to define custom initialization macros to perform various tasks before the real compilation. A macro like this would then be invoked via --macro some.Class.theMacro(ar
For instance, as all macros share the same context (9.1), an initialization macro could set the value
of a static field which other macros use as configuration.
147
Part III
Standard Library
148
Chapter 10
Standard Library
10.1
String
Type: String
A String is a sequence of characters.
Character code Use the .code property on a constant single-char string in order to compile its
ASCII character code:
1
"#".code // will compile as 35
Related content
• See the String API for details about its methods.
10.2
Data Structures
10.2.1
Array
An Array is a collection of elements. It has one type parameter (3.2) which corresponds to the
type of these elements. Arrays can be created in three ways:
1. By using their constructor: new Array()
2. By using array declaration syntax (5.5): [1, 2, 3]
3. By using array comprehension (6.6): [for (i in 0...10) if (i % 2 == 0) i]
Arrays come with an API to cover most use-cases. Additionally they allow read and write
array access (5.8):
class Main {
static public function main() {
3
var a = [1, 2, 3];
4
trace(a[1]); // 2
5
a[1] = 1;
1
2
149
6
7
8
trace(a[1]); // 1
}
}
Since array access in Haxe is unbounded, i.e. it is guaranteed to not throw an exception, this
requires further discussion:
• If a read access is made on a non-existing index, a target-dependent value is returned.
• If a write access is made with a positive index which is out of bounds, null (or the default
value (2.2) for basic types (2.1) on static targets (2.2)) is inserted at all positions between the
last defined index and the newly written one.
• If a write access is made with a negative index, the result is unspecified.
Arrays define an iterator (6.8) over their elements. This iteration is typically optimized by the
compiler to use a while loop (5.14) with array index:
1
2
3
4
5
6
7
8
9
10
class Main {
static public function main() {
var scores = [110, 170, 35];
var sum = 0;
for (score in scores) {
sum += score;
}
trace(sum); // 315
}
}
Haxe generates this optimized JavaScript output:
1
2
3
4
5
6
7
8
9
10
11
Main.main = function() {
var scores = [110,170,35];
var sum = 0;
var _g = 0;
while(_g < scores.length) {
var score = scores[_g];
++_g;
sum += score;
}
console.log(sum);
};
Haxe does not allow arrays of mixed types unless the parameter type is forced to Dynamic
(2.7):
class Main {
static public function main() {
// Compile Error: Arrays of mixed types are only allowed if the
type is
4
// forced to Array
5
//var myArray = [10, "Bob", false];
1
2
3
6
7
8
// Array with mixed types
var myExplicitArray:Array = [10, "Sally", true];
150
9
10
}
}
Trivia: Dynamic Arrays
In Haxe 2, mixed type array declarations were allowed. In Haxe 3, arrays can have mixed
types only if they are explicitly declared as Array.
Related content
• See the Array API for details about its methods.
• Data structures tutorials and examples in the Haxe Code Cookbook.
10.2.2
Vector
A Vector is an optimized fixed-length collection of elements. Much like Array (10.2.1), it has one
type parameter (3.2) and all elements of a vector must be of the specified type, it can be iterated
over using a for loop (5.13) and accessed using array access syntax (2.8.3). However, unlike Array
and List, vector length is specified on creation and cannot be changed later.
1
2
3
4
class Main {
static function main() {
var vec = new haxe.ds.Vector(10);
for (i in 0...vec.length) {
vec[i] = i;
}
5
6
7
8
9
10
11
12
13
trace(vec[0]); // 0
trace(vec[5]); // 5
trace(vec[9]); // 9
}
}
haxe.ds.Vector is implemented as an abstract type (2.8) over a native array implementation for given target and can be faster for fixed-size collections, because the memory for storing
its elements is pre-allocated.
Related content
• See the Vector API for details about the vector methods.
• Data structures tutorials and examples in the Haxe Code Cookbook.
10.2.3
List
A List is a collection for storing elements. On the surface, a list is similar to an Array (Section 10.2.1). However, the underlying implementation is very different. This results in several
functional differences:
1. A list can not be indexed using square brackets, i.e. [0].
151
2. A list can not be initialized.
3. There are no list comprehensions.
4. A list can freely modify/add/remove elements while iterating over them.
A simple example for working with lists:
1
2
3
4
5
6
7
8
class Main {
static public function main() {
var myList = new List();
for (ii in 0...5)
myList.add(ii);
trace(myList); //{0, 1, 2, 3, 4}
}
}
Related content
• See the List API for details about the list methods.
• Data structures tutorials and examples in the Haxe Code Cookbook.
10.2.4
GenericStack
A GenericStack, like Array and List is a container for storing elements. It has one type parameter (3.2) and all elements of the stack must be of the specified type. Here is a small example
program for initializing and working with a GenericStack.
1
2
3
4
5
6
7
8
9
10
11
import haxe.ds.GenericStack;
class Main {
static public function main() {
var myStack = new GenericStack();
for (ii in 0...5)
myStack.add(ii);
trace(myStack); //{4, 3, 2, 1, 0}
trace(myStack.pop()); //4
}
}
Trivia: FastList
In Haxe 2, the GenericStack class was known as FastList. Since its behavior more closely
resembled a typical stack, the name was changed for Haxe 3.
The Generic in GenericStack is literal. It is attributed with the :generic metadata. Depending on the target, this can lead to improved performance on static targets. See Generic (Section 3.3) for more details.
Related content
• See the GenericStack API for details about its methods.
• Data structures tutorials and examples in the Haxe Code Cookbook.
152
10.2.5
Map
A Map is a container composed of key, value pairs. A Map is also commonly referred to as an associative array, dictionary, or symbol table. The following code gives a short example of working
with maps:
class Main {
static public function main() {
// Maps are initialized like arrays, but
// use the map literal syntax with the
// ’=>’ operator. Maps can have their
// key value types defined explicity
var map1:Map =
8
[1 => "one", 2=>"two"];
1
2
3
4
5
6
7
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Or they can infer their key value types
var map2 = [
"one"=>1,
"two"=>2,
"three"=>3
];
$type(map2); // Map
// Keys must be unique
// Error: Duplicate Key
//var map3 = [1=>"dog", 1=>"cat"];
// Maps values can be accessed using array
// accessors "[]"
var map4 = ["M"=>"Monday", "T"=>"Tuesday"];
trace(map4["M"]); //Monday
// Maps iterate over their values by
// default
var valueSum;
for (value in map4) {
trace(value); // Monday \n Tuesday
}
// Can iterate over keys by using the
// keys() method
for (key in map4.keys()) {
trace(key); // M \n T
}
// Like arrays, a new Map can be made using
// comprehension
var map5 = [
for (key in map4.keys())
key => "FRIDAY!!"
];
// {M => FRIDAY!!, T => FRIDAY!!}
153
47
48
49
trace(map5);
}
}
Under the hood, a Map is an abstract (2.8) type. At compile time, it gets converted to one of
several specialized types depending on the key type:
• String: haxe.ds.StringMap
• Int: haxe.ds.IntMap
• EnumValue: haxe.ds.EnumValueMap
• {}: haxe.ds.ObjectMap
The Map type does not exist at runtime and has been replaced with one of the above objects.
Map defines array access (2.8.3) using its key type.
Related content
• See the Map API for details of its methods.
• Data structures tutorials and examples in the Haxe Code Cookbook.
10.2.6
Option
An Option is an enum (2.4) in the Haxe Standard Library which is defined like so:
enum Option {
Some(v:T);
None;
4 }
1
2
3
It can be used in various situations, such as communicating whether or not a method had a
valid return and if so, what value it returned:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import haxe.ds.Option;
class Main {
static public function main() {
var result = trySomething();
switch (result) {
case None:
trace("Got None");
case Some(s):
trace("Got a value: " +s);
}
}
static function trySomething():Option {
if (Math.random() > 0.5) {
return None;
} else {
return Some("Success");
}
154
20
21
}
}
10.3
Regular Expressions
Haxe has built-in support for regular expressions1 . They can be used to verify the format of a
string, transform a string or extract some regular data from a given text.
Haxe has special syntax for creating regular expressions. We can create a regular expression
object by typing it between the ˜/ combination and a single / character:
1
var r = ˜/haxe/i;
Alternatively, we can create regular expression with regular syntax:
1
var r = new EReg("haxe", "i");
First argument is a string with regular expression pattern, second one is a string with flags
(see below).
We can use standard regular expression patterns such as:
• . any character
• * repeat zero-or-more
• + repeat one-or-more
• ? optional zero-or-one
• [A-Z0-9] character ranges
• [ˆ\r\n\t] character not-in-range
• (...) parenthesis to match groups of characters
• ˆ beginning of the string (beginning of a line in multiline matching mode)
• $ end of the string (end of a line in multiline matching mode)
• | ”OR” statement.
For example, the following regular expression matches valid email addresses:
1
˜/[A-Z0-9._\%-]+@[A-Z0-9.-]+\.[A-Z][A-Z][A-Z]?/i;
Please notice that the i at the end of the regular expression is a flag that enables case-insensitive
matching.
The possible flags are the following:
• i case insensitive matching
• g global replace or split, see below
• m multiline matching, ˆ and $ represent the beginning and end of a line
• s the dot . will also match newlines (Neko, C++, PHP, Flash and Java targets only)
• u use UTF-8 matching (Neko and C++ targets only)
1 http://en.wikipedia.org/wiki/Regular
expression
155
Related content
• See the EReg API for details about its methods.
• Haxe snippets and tutorials about regular expressions in the Haxe Code Cookbook.
10.3.1
Matching
Probably one of the most common uses for regular expressions is checking whether a string
matches the specific pattern. The match method of a regular expression object can be used to do
that:
1
2
3
4
5
6
7
8
9
class Main {
static function main() {
var r = ˜/world/;
var str = "hello world";
// true : ’world’ was found in the string
trace(r.match(str));
trace(r.match("hello !")); // false
}
}
10.3.2
Groups
Specific information can be extracted from a matched string by using groups. If match() returns
true, we can get groups using the matched(X) method, where X is the number of a group
defined by regular expression pattern:
1
2
3
4
5
6
7
8
9
10
class Main {
static function main() {
var str = "Nicolas is 26 years old";
var r =
˜/([A-Za-z]+) is ([0-9]+) years old/;
r.match(str);
trace(r.matched(1)); // "Nicolas"
trace(r.matched(2)); // "26"
}
}
Note that group numbers start with 1 and r.matched(0) will always return the whole
matched substring.
The r.matchedPos() will return the position of this substring in the original string:
1
2
3
4
5
6
7
8
9
10
class Main {
static function main() {
var str = "abcdeeeeefghi";
var r = ˜/e+/;
r.match(str);
trace(r.matched(0)); // "eeeee"
// { pos : 4, len : 5 }
trace(r.matchedPos());
}
}
156
Additionally, r.matchedLeft() and r.matchedRight() can be used to get substrings to
the left and to the right of the matched substring:
class Main {
static function main() {
var r = ˜/b/;
r.match("abc");
trace(r.matchedLeft()); // a
trace(r.matched(0)); // b
trace(r.matchedRight()); // c
8
}
9 }
1
2
3
4
5
6
7
10.3.3
Replace
A regular expression can also be used to replace a part of the string:
1
2
3
4
5
6
7
8
9
class Main {
static function main() {
var str = "aaabcbcbcbz";
// g : replace all instances
var r = ˜/b[ˆc]/g;
// "aaabcbcbcxx"
trace(r.replace(str,"xx"));
}
}
We can use $X to reuse a matched group in the replacement:
1
2
3
4
5
6
7
8
class Main {
static function main() {
var str = "{hello} {0} {again}";
var r = ˜/{([a-z]+)}/g;
// "*hello* {0} *again*"
trace(r.replace(str,"*$1*"));
}
}
10.3.4
Split
A regular expression can also be used to split a string into several substrings:
1
2
3
4
5
6
7
8
class Main {
static function main() {
var str = "XaaaYababZbbbW";
var r = ˜/[ab]+/g;
// ["X","Y","Z","W"]
trace(r.split(str));
}
}
157
10.3.5
Map
The map method of a regular expression object can be used to replace matched substrings using a
custom function. This function takes a regular expression object as its first argument so we may
use it to get additional information about the match being done and do conditional replacement.
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Main {
static function main() {
var r = ˜/(dog|fox)/g;
var s = "The quick brown fox jumped over the lazy dog.";
var s2 = r.map(s, function(r) {
var match = r.matched(0);
switch (match) {
case ’dog’: return ’fox’;
case ’fox’: return ’dog’;
default: throw ’Unknown animal: $match’;
};
});
trace(s2); // The quick brown dog jumped over the lazy fox.
}
}
10.3.6
Implementation Details
Regular Expressions are implemented:
• in JavaScript, the runtime is providing the implementation with the object RegExp.
• in Neko and C++, the PCRE library is used
• in Flash, PHP, C# and Java, native implementations are used
• in Flash 6/8, the implementation is not available
10.4
Math
Haxe includes a floating point math library for some common mathematical operations. Most of
the functions operate on and return floats. However, an Int can be used where a Float is
expected, and Haxe also converts Int to Float during most numeric operations (see Numeric
Operators (Section 2.1.3) for more details).
Here are some example uses of the math library:
1
2
3
4
5
6
7
8
9
10
class Main {
static public function main() {
var x = 1/2;
var y = 20.2;
var z = -2;
trace(Math.abs(z)); //2
trace(Math.sin(x*Math.PI)); //1
trace(Math.ceil(y)); //21
158
// log is the natural logarithm
trace(Math.log(Math.exp(5))); //5
11
12
13
14
15
16
17
18
19
20
// Output for neko target, may vary
// depending on platform
trace(1/0); //inf
trace(-1/0); //-inf
trace(Math.sqrt(-1)); //nan
}
}
Related content
• See the Math API documentation for all available functions.
• Haxe snippets and tutorials about math in the Haxe Code Cookbook.
10.4.1
Special Numbers
The math library has definitions for several special numbers:
• NaN (Not a Number): returned when a mathematically incorrect operation is executed, e.g.
Math.sqrt(-1)
• POSITIVE INFINITY: e.g. divide a positive number by zero
• NEGATIVE INFINITY: e.g. divide a negative number by zero
• PI : 3.1415...
10.4.2
Mathematical Errors
Although neko can fluidly handle mathematical errors, like division by zero, this is not true for
all targets. Depending on the target, mathematical errors may produce exceptions and ultimately
errors.
10.4.3
Integer Math
If you are targeting a platform that can utilize integer operations, e.g. integer division, it should
be wrapped in Std.int() for improved performance. The Haxe Compiler can then optimize for
integer operations. An example:
1
var intDivision = Std.int(6.2/4.7);
10.4.4
Extensions
It is common to see Static Extension (Section 6.3) used with the math library. This code shows a
simple example:
159
1
2
3
4
5
6
class MathStaticExtension {
/* Converts an angle in radians to degrees */
inline public static function toDegrees(radians:Float):Float {
return radians * 180 / Math.PI;
}
}
1
2
3
4
5
using MathStaticExtension;
class Main {
public static function main() {
var ang = 1/2*Math.PI;
6
trace(ang.toDegrees()); //90
7
}
8 }
10.5
Lambda
Definition: Lambda
Lambda is a functional language concept within Haxe that allows you to apply a function to
a list or iterators (6.8). The Lambda class is a collection of functional methods in order to use
functional-style programming with Haxe.
It is ideally used with using Lambda (see Static Extension (6.3)) and then acts as an extension
to Iterable types.
On static platforms, working with the Iterable structure might be slower than performing
the operations directly on known types, such as Array and List.
Lambda Functions The Lambda class allows us to operate on an entire Iterable at once.
This is often preferable to looping routines since it is less error prone and easier to read. For
convenience, the Array and List class contains some of the frequently used methods from the
Lambda class.
It is helpful to look at an example. The exists function is specified as:
1
static function exists( it : Iterable, f : A -> Bool ) : Bool
Most Lambda functions are called in similar ways. The first argument for all of the Lambda
functions is the Iterable on which to operate. Many also take a function as an argument.
Lambda.array, Lambda.list Convert Iterable to Array or List. It always returns a new
instance.
Lambda.count Count the number of elements. If the Iterable is a Array or List it is faster to
use its length property.
Lambda.empty Determine if the Iterable is empty. For all Iterables it is best to use the this
function; it’s also faster than compare the length (or result of Lambda.count) to zero.
Lambda.has Determine if the specified element is in the Iterable.
160
Lambda.exists Determine if criteria is satisfied by an element.
Lambda.indexOf Find out the index of the specified element.
Lambda.find Find first element of given search function.
Lambda.foreach Determine if every element satisfies a criteria.
Lambda.iter Call a function for each element.
Lambda.concat Merge two Iterables, returning a new List.
Lambda.filter Find the elements that satisfy a criteria, returning a new List.
Lambda.map, Lambda.mapi Apply a conversion to each element, returning a new List.
Lambda.fold Functional fold, which is also known as reduce, accumulate, compress or inject.
This example demonstrates the Lambda filter and map on a set of strings:
1
2
3
4
5
6
using Lambda;
class Main {
static function main() {
var words = [’car’, ’boat’, ’cat’, ’frog’];
var isThreeLetters = function(word) return word.length == 3;
var capitalize = function(word) return word.toUpperCase();
7
8
9
10
// Three letter words and capitalized.
trace(words.filter(isThreeLetters).map(capitalize)); // [CAR,
CAT]
}
11
12
}
This example demonstrates the Lambda count, has, foreach and fold function on a set of ints.
using Lambda;
class Main {
3
static function main() {
4
var numbers = [1, 3, 5, 6, 7, 8];
1
2
5
6
7
8
trace(numbers.count()); // 6
trace(numbers.has(4)); // false
// test if all numbers are greater/smaller than 20
trace(numbers.foreach(function(v) return v < 20)); // true
trace(numbers.foreach(function(v) return v > 20)); // false
9
10
11
12
13
14
15
16
17
// sum all the numbers
var sum = function(num, total) return total += num;
trace(numbers.fold(sum, 0)); // 30
}
}
161
Related content
• See the Lambda API documentation for all available functions.
10.6
Template
Haxe comes with a standard template system with an easy to use syntax which is interpreted by
a lightweight class called haxe.Template.
A template is a string or a file that is used to produce any kind of string output depending on
the input. Here is a small template example:
1
2
3
4
5
6
7
8
9
class Main {
static function main() {
var sample = "My name is ::name::, ::age::
em> years old";
var user = {name:"Mark", age:30};
var template = new haxe.Template(sample);
var output = template.execute(user);
trace(output);
}
}
The console will trace My name is Mark, 30 years old.
Expressions An expression can be put between the ::, the syntax allows the current possibilities:
::name:: the variable name
::expr.field:: field access
::(expr):: the expression expr is evaluated
::(e1 op e2):: the operation op is applied to e1 and e2
::(135):: the integer 135. Float constants are not allowed
Conditions It is possible to test conditions using ::if flag1::. Optionally, the condition
may be followed by ::elseif flag2:: or ::else::. Close the condition with ::end::.
1
::if isValid:: valid ::else:: invalid ::end::
Operators can be used but they don’t deal with operator precedence. Therefore it is required
to enclose each operation in parentheses (). Currently, the following operators are allowed: +,
-, *, /, >, <, >=, <=, ==, !=, && and ||.
For example ::((1 + 3) == (2 + 2)):: will display true.
1
::if (points == 10):: Great! ::end::
To compare to a string, use double quotes " in the template.
1
::if (name == "Mark"):: Hi Mark ::end::
162
Iterating Iterate on a structure by using ::foreach::. End the loop with ::end::.
1
2
3
4
5
6
7
8
9
10
11
12
Name
Age
::foreach users::
::name::
::age::
::end::
Sub-templates
a parameter.
1
2
3
To include templates in other templates, pass the sub-template result string as
var users = [{name:"Mark", age:30}, {name:"John", age:45}];
var userTemplate = new haxe.Template("::foreach users:: ::name::(::age
::) ::end::");
4 var userOutput = userTemplate.execute({users: users});
5
6
7
8
var template = new haxe.Template("The users are ::users::");
var output = template.execute({users: userOutput});
trace(output);
The console will trace The users are Mark(30) John(45).
Template macros To call custom functions while parts of the template are being rendered, provide a macros object to the argument of Template.execute. The key will act as the template
variable name, the value refers to a callback function that should return a String. The first
argument of this macro function is always a resolve() method, followed by the given arguments. The resolve function can be called to retrieve values from the template context. If macros
has no such field, the result is unspecified.
The following example passes itself as macro function context and executes display from
the template.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Main {
static function main() {
new Main();
}
public function new() {
var user = {name:"Mark", distance:3500};
var sample = "The results: $$display(::user::,::time::)";
var template = new haxe.Template(sample);
var output = template.execute({user:user, time: 15}, this);
trace(output);
}
function display(resolve:String->Dynamic, user:User, time:Int) {
163
15
16
17
18
return user.name + " ran " + (user.distance/1000) + " kilometers
in " + time + " minutes";
}
}
typedef User = {name:String, distance:Int}
The console will trace The results:
Mark ran 3.5 kilometers in 15 minutes.
Globals Use the Template.globals object to store values that should be applied across all haxe.Template
instances. This has lower priority than the context argument of Template.execute.
Using resources To separate the content from the code, consider using the resource embedding system (8.4). Place the template-content in a new file called sample.mtt, add -resource
sample.mtt@my_sample to the compiler arguments and retrieve the content using haxe.Resource.getSt
1
2
3
4
5
6
7
8
9
class Main {
static function main() {
var sample = haxe.Resource.getString("my_sample");
var user = {name:"Mark", age:30};
var template = new haxe.Template(sample);
var output = template.execute(user);
trace(output);
}
}
When running the template system on the server side, you can simply use neko.Lib.print
or php.Lib.print instead of trace to display the HTML template to the user.
Related content
• See the Template API for details about its methods.
10.7
Reflection
Haxe supports runtime reflection of types and fields. Special care has to be taken here because
runtime representation generally varies between targets. In order to use reflection correctly it
is necessary to understand what kind of operations are supported and what is not. Given the
dynamic nature of reflection, this can not always be determined at compile-time.
The reflection API consists of two classes:
Reflect: A lightweight API which work best on anonymous structures (2.5), with limited support
for classes (2.3).
Type: A more robust API for working with classes and enums (2.4).
The available methods are detailed in the API for Reflect and Type.
Reflection can be a powerful tool, but it is important to understand why it can also cause
problems. As an example, several functions expect a String (10.1) argument and try to resolve it
to a type or field. This is vulnerable to typing errors:
class Main {
static function main() {
3
trace(Type.resolveClass("Mian")); // null
1
2
164
4
5
}
}
However, even if there are no typing errors it is easy to come across unexpected behavior:
class Main {
static function main() {
// null
trace(Type.resolveClass("haxe.Template"));
5
}
6 }
1
2
3
4
The problem here is that the compiler never actually “sees” the type haxe.Template, so it
does not compile it into the output. Furthermore, even if it were to see the type there could be
issues arising from dead code elimination (8.2) eliminating types or fields which are only used
via reflection.
Another set of problems comes from the fact that, by design, several reflection functions expect arguments of type Dynamic (2.7), meaning the compiler cannot check if the passed in arguments are correct. The following example demonstrates a common mistake when working with
callMethod:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Main {
static function main() {
// wrong
//Reflect.callMethod(Main, "f", []);
// right
Reflect.callMethod(Main,
Reflect.field(Main, "f"), []);
}
static function f() {
trace(’Called’);
}
}
The commented out call would be accepted by the compiler because it assigns the string "f"
to the function argument func which is specified to be Dynamic.
A good advice when working with reflection is to wrap it in a few functions within an application or API which are called by otherwise type-safe code. An example could look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typedef MyStructure = {
name: String,
score: Int
}
class Main {
static function main() {
var data = reflective();
// At this point data is nicely typed as MyStructure
}
static function reflective():MyStructure {
// Work with reflection here to get some values we want to return.
return {
name: "Reflection",
165
16
17
18
19
score: 0
}
}
}
While the method reflective could internally work with reflection (and Dynamic for that
matter) a lot, its return value is a typed structure which the callers can use in a type-safe manner.
10.8
Serialization
Many runtime values can be serialized and deserialized using the haxe.Serializer and haxe.Unserializer
classes. Both support two usages:
1. Create an instance and continuously call the serialize/unserialize method to handle
multiple values.
2. Call their static run method to serialize/deserialize a single value.
The following example demonstrates the first usage:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import haxe.Serializer;
import haxe.Unserializer;
class Main {
static function main() {
var serializer = new Serializer();
serializer.serialize("foo");
serializer.serialize(12);
var s = serializer.toString();
trace(s); // y3:fooi12
var unserializer = new Unserializer(s);
trace(unserializer.unserialize()); // foo
trace(unserializer.unserialize()); // 12
}
}
The result of the serialization (here stored in local variable s) is a String (10.1) and can
be passed around at will, even remotely. Its format is described in Serialization format (Section 10.8.1).
Supported values
• null
• Bool, Int and Float (including infinities and NaN)
• String
• Date
• haxe.io.Bytes (encoded as base64)
• Array (10.2.1) and List (10.2.3)
166
• haxe.ds.StringMap, haxe.ds.IntMap and haxe.ds.ObjectMap
• anonymous structures (2.5)
• Haxe class instances (2.3) (not native ones)
• enum instances (2.4)
Serialization configuration Serialization can be configured in two ways. For both a static variable can be set to influence all haxe.Serializer instances, and a member variable can be set to only
influence a specific instance:
USE_CACHE, useCache: If true, repeated structures or class/enum instances are serialized by
reference. This can avoid infinite loops for recursive data at the expense of longer serialization time. By default, object caching is disabled; strings however are always cached.
USE_ENUM_INDEX, useEnumIndex: If true, enum constructors are serialized by their index instead of their name. This can make the resulting string shorter, but breaks if enum constructors are inserted into the type before deserialization. This behavior is disabled by default.
Deserialization behavior If the serialization result is stored and later used for deserialization,
care has to be taken to maintain compatibility when working with class and enum instances. It
is then important to understand exactly how unserialization is implemented.
• The type has to be available in the runtime where the deserialization is made. If dead
code elimination (8.2) is active, a type which is used only through serialization might be
removed.
• Each Unserializer has a member variable resolver which is used to resolve classes
and enums by name. Upon creation of the Unserializer this is set to Unserializer.DEFAULT_RESOLVER. Both that and the instance member can be set to a custom resolver.
• Classes are resolved by name using resolver.resolveClass(name). The instance is
then created using Type.createEmptyInstance, which means that the class constructor
is not called. Finally, the instance fields are set according to the serialized value.
• Enums are resolved by name using resolver.resolveEnum(name). The enum instance
is then created using Type.createEnum, using the serialized argument values if available.
If the constructor arguments were changed since serialization, the result is unspecified.
Custom (de)serialization If a class defines the member method hxSerialize, that method is
called by the serializer and allows custom serialization of the class. Likewise, if a class defines
the member method hxUnserialize it is called by the deserializer:
1
2
3
4
5
6
7
8
9
10
import haxe.Serializer;
import haxe.Unserializer;
class Main {
var x:Int;
var y:Int;
static function main() {
var s = Serializer.run(new Main(1, 2));
167
var c:Main = Unserializer.run(s);
trace(c.x); // 1
trace(c.y); // -1
11
12
13
14
15
16
}
function new(x, y) {
this.x = x;
this.y = y;
}
17
18
19
20
21
22
@:keep
function hxSerialize(s:Serializer) {
s.serialize(x);
}
23
24
25
26
27
28
29
30
31
@:keep
function hxUnserialize(u:Unserializer) {
x = u.unserialize();
y = -1;
}
}
In this example we decide that we want to ignore the value of member variable y and do not
serialize it. Instead we default it to -1 in hxUnserialize. Both methods are annotated with the
@:keep metadata to prevent dead code elimination (8.2) from removing them as they are never
properly referenced in the code.
See Serializer and Unserializer API documentation for details.
10.8.1
Serialization format
Each supported value is translated to a distinct prefix character, followed by the necessary data.
null: n
Int: z for zero, or i followed by the integer display (e.g. i456)
Float:
NaN: k
negative infinity: m
positive infinity: p
finite floats: d followed by the float display (e.g. d1.45e-8)
Bool: t for true, f for false
String: y followed by the url encoded string length, then : and the url encoded string (e.g.
y10:hi%20there for "hi there".
name-value pairs: a serialized string representing the name followed by the serialized value
structure: o followed by the list of name-value pairs and terminated by g (e.g. oy1:xi2y1:kng
for {x:2, k:null})
List: l followed by the list of serialized items, followed by h (e.g. lnnh for a list of two null
values)
168
Array: a followed by the list of serialized items, followed by h. For multiple consecutive null
values, u followed by the number of null values is used (e.g. ai1i2u4i7ni9h for
[1,2,null,null,null,null,7,null,9])
Date: v followed by the date itself (e.g. v2010-01-01 12:45:10)
haxe.ds.StringMap: b followed by the name-value pairs, followed by h (e.g. by1:xi2y1:knh
for {"x" => 2, "k" => null})
haxe.ds.IntMap: q followed by the key-value pairs, followed by h. Each key is represented
as : (e.g. q:4n:5i45:6i7h for {4 => null, 5 => 45, 6 => 7})
haxe.ds.ObjectMap: M followed by serialized value pairs representing the key and value,
followed by h
haxe.io.Bytes: s followed by the length of the base64 encoded bytes, then : and the byte
representation using the codes A-Za-z0-9% (e.g. s3:AAA for 2 bytes equal to 0, and
s10:SGVsbG8gIQ for haxe.io.Bytes.ofString("Hello !"))
exception: x followed by the exception value
class instance: c followed by the serialized class name, followed by the name-value pairs of the
fields, followed by g (e.g. cy5:Pointy1:xzy1:yzg for new Point(0, 0) (having two
integer fields x and y)
enum instance (by name): w followed by the serialized enum name, followed by the serialized
constructor name, followed by :, followed by the number of arguments, followed by the argument values (e.g. wy3:Fooy1:A:0 for Foo.A (with no arguments), wy3:Fooy1:B:2i4n
for Foo.B(4,null))
enum instance (by index): j followed by the serialized enum name, followed by :, followed
by the constructor index (starting from 0), followed by :, followed by the number of arguments, followed by the argument values (e.g. jy3:Foo:0:0 for Foo.A (with no arguments), jy3:Foo:1:2i4n for Foo.B(4,null))
cache references:
String: R followed by the corresponding index in the string cache (e.g. R456)
class, enum or structure r followed by the corresponding index in the object cache (e.g.
r42)
custom: C followed by the class name, followed by the custom serialized data, followed by g
Cached elements and enum constructors are indexed from zero.
10.9
Xml
Haxe provides built-in support for working with XML2 data via the haxe.Xml class.
2 http://en.wikipedia.org/wiki/XML
169
10.9.1
Getting started with Xml
Creating a root element
method.
1
2
A Xml root element can be created using the Xml.createElement
var root = Xml.createElement(’root’);
trace(root); //
An root node element can also be created by parsing a String containing the XML data.
1
2
var root = Xml.parse(’ ’).firstElement();
trace(root); //
Creating child elements Adding child elements to the root can be done using the addChild
method.
1
2
3
var child:Xml = Xml.createElement(’child’);
root.addChild(child);
trace(root); //
Adding attributes to an element can be done by using the set() method.
1
2
child.set(’name’, ’John’);
trace(root); //
Accessing elements and values This code parses an XML string into an object structure Xml
and then accesses properties of the object.
1
2
var xmlString = ’Haxe is great! ’;
var xml:Xml = Xml.parse(xmlString).firstElement();
3
4
5
6
trace(xml.nodeName); // hello
trace(xml.get(’name’)); // world!
trace(xml.firstChild().nodeValue); // Haxe is great!
The difference between firstChild and firstElement is that the second function will
return the first child with the type Xml.Element.
Iterate on Xml elements
elements.
1
2
3
4
5
6
7
8
9
10
11
12
We can as well use other methods to iterate either over children or
for (child in xml) {
// iterate on all children.
}
for (elt in xml.elements()) {
// iterate on all elements.
}
for (user in xml.elementsNamed("user")) {
// iterate on all elements with a nodeName "user".
}
for (att in xml.attributes()) {
// iterator on all attributes.
}
See Xml API documentation for details about its methods.
170
10.9.2
Parsing Xml
The static method Xml.parse can be used to parse XML data and obtain a Haxe value from it.
1
2
var xml = Xml.parse(’Haxe is great! ’).firstElement();
trace(xml.firstChild().nodeValue);
10.9.3
Encoding Xml
The method xml.toString() can be used to obtain the String representation.
1
2
3
4
var xml = Xml.createElement(’root’);
xml.addChild(Xml.createElement(’child1’));
xml.addChild(Xml.createElement(’child2’));
5
trace(xml.toString()); //
10.10
Json
Haxe provides built-in support for (de-)serializing JSON3 data via the haxe.Json class.
Related content
• See the Haxe Json API documentation.
• Haxe snippets and tutorials about JSON in the Haxe Code Cookbook.
10.10.1
Parsing JSON
Use the haxe.Json.parse static method to parse JSON data and obtain a Haxe value from it:
1
2
3
4
5
6
7
class Main {
static function main() {
var s = ’{"rating": 5}’;
var o = haxe.Json.parse(s);
trace(o); // { rating: 5 }
}
}
Note that the type of the object returned by haxe.Json.parse is Dynamic, so if the structure of our data is well-known, we may want to specify a type using anonymous structures (2.5).
This way we provide compile-time checks for accessing our data and most likely more optimal
code generation, because compiler knows about types in a structure:
1
2
3
4
5
typedef MyData = {
var name:String;
var tags:Array;
}
6
7
class Main {
static function main() {
3 http://en.wikipedia.org/wiki/JSON
171
var s = ’{
"name": "Haxe",
"tags": ["awesome"]
}’;
var o:MyData = haxe.Json.parse(s);
trace(o.name); // Haxe (a string)
// awesome (a string in an array)
trace(o.tags[0]);
8
9
10
11
12
13
14
15
16
17
}
}
10.10.2
Encoding JSON
Use the haxe.Json.stringify static method to encode a Haxe value into a JSON string:
1
2
3
4
5
6
7
class Main {
static function main() {
var o = {rating: 5};
var s = haxe.Json.stringify(o);
trace(s); // {"rating":5}
}
}
10.10.3
Implementation details
The haxe.Json API automatically uses native implementation on targets where it is available, i.e.
JavaScript, Flash and PHP and provides its own implementation for other targets.
Usage of Haxe own implementation can be forced with -D haxeJSON compiler argument.
This will also provide serialization of enums (2.4) by their index, maps (10.2.5) with string keys
and class instances.
Older browsers (Internet Explorer 7, for instance) may not have native JSON implementation.
In case it’s required to support them, we can include one of the JSON implementations available
on the internet in the HTML page. Alternatively, a -D old_browser compiler argument that
will make haxe.Json try to use native JSON and, in case it’s not available, fallback to its own
implementation.
10.11
Input/Output
10.12
Sys/sys
10.13
Remoting
Haxe remoting is a way to communicate between different platforms. With Haxe remoting, applications can transmit data transparently, send data and call methods between server and client
side.
Related content
• See the remoting package on the API documentation for more details on its classes.
172
10.13.1
Remoting Connection
In order to use remoting, there must be a connection established. There are two kinds of Haxe
Remoting connections:
haxe.remoting.Connection is used for synchronous connections, where the results can be directly
obtained when calling a method.
haxe.remoting.AsyncConnection is used for asynchronous connections, where the results are events
that will happen later in the execution process.
Start a connection There are some target-specific constructors with different purposes that can
be used to set up a connection:
All targets: HttpAsyncConnection.urlConnect(url:String) Returns an asynchronous
connection to the given URL which should link to a Haxe server application.
Flash: ExternalConnection.jsConnect(name:String, ctx:Context) Allows a connection to the local JavaScript Haxe code. The JS Haxe code must be compiled with the
class ExternalConnection included. This only works with Flash Player 8 and higher.
AMFConnection.urlConnect(url:String) and AMFConnection.connect( cnx :
Allows a connection to an AMF Remoting server such as Flash Media Server or AMFPHP.
NetConn
SocketConnection.create(sock:flash.XMLSocket) Allows remoting communications over an XMLSocket
LocalConnection.connect(name:String) Allows remoting communications over
a Flash LocalConnection
JavaScript: ExternalConnection.flashConnect(name:String, obj:String, ctx:Context)
Allows a connection to a given Flash Object. The Haxe Flash content must be loaded
and it must include the haxe.remoting.Connection class. This only works with
Flash 8 and higher.
Neko: HttpConnection.urlConnect(url:String) Will work like the asynchronous version but in synchronous mode.
SocketConnection.create(...) Allows real-time communications with a Flash client
which is using an XMLSocket to connect to the server.
Remoting context Before communicating between platforms, a remoting context has to be defined. This is a shared API that can be called on the connection at the client code.
This server code example creates and shares an API:
class Server {
function new() { }
3
function foo(x, y) { return x + y; }
1
2
4
5
6
7
8
9
10
11
static function main() {
var ctx = new haxe.remoting.Context();
ctx.addObject("Server", new Server());
if(haxe.remoting.HttpConnection.handleRequest(ctx))
{
return;
173
12
13
14
15
16
17
}
// handle normal request
trace("This is a remoting server !");
}
}
Using the connection Using a connection is pretty convenient. Once the connection is obtained,
use classic dot-access to evaluate a path and then use call() to call the method in the remoting
context and get the result. The asynchronous connection takes an additional function parameter
that will be called when the result is available.
This client code example connects to the server remoting context and calls a function foo()
on its API.
1
2
3
4
5
6
7
class Client {
static function main() {
var cnx = haxe.remoting.HttpAsyncConnection.urlConnect("http://
localhost/");
cnx.setErrorHandler( function(err) { trace(’Error: $err’); } );
cnx.Server.foo.call([1,2], function(data) { trace(’Result: $data’)
; });
}
}
To make this work for the Neko target, setup a Neko Web Server, point the url in the Client
to "http://localhost2000/remoting.n" and compile the Server using -main Server
-neko remoting.n.
Error handling
• When an error occurs in a asynchronous call, the error handler is called as seen in the
example above.
• When an error occurs in a synchronous call, an exception is raised on the caller-side as if
we were calling a local method.
Data serialization
(10.8).
Haxe Remoting can send a lot of different kinds of data. See Serialization
Related content
• See the remoting package on the API documentation for more details on its classes.
10.13.2
Implementation details
JavaScript security specifics The html-page wrapping the js client must be served from the
same domain as the one where the server is running. The same-origin policy restricts how a
document or script loaded from one origin can interact with a resource from another origin. The
same-origin policy is used as a means to prevent some of the cross-site request forgery attacks.
To use the remoting across domain boundaries, CORS (cross-origin resource sharing) needs
to be enabled by defining the header X-Haxe-Remoting in the .htaccess:
174
1
2
3
4
# Enable CORS
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header set Access-Control-Allow-Headers: X-Haxe-Remoting
See same-origin policy for more information on this topic.
Also note that this means that the page can’t be served directly from the file system "file:///C:/exampl
Flash security specifics When Flash accesses a server from a different domain, set up a crossdomain.xml
file on the server, enabling the X-Haxe headers.
3
4
1
2
Arguments types are not ensured There is no guarantee of any kind that the arguments types
will be respected when a method is called using remoting. That means even if the arguments of
function foo are typed to Int, the client will still be able to use strings while calling the method.
This can lead to security issues in some cases. When in doubt, check the argument type when
the function is called by using the Std.is method.
10.14
Unit Testing
The Haxe Standard Library provides basic unit testing classes from the haxe.unit package.
Creating new test cases First, create a new class extending haxe.unit.TestCase and add own
test methods. Every test method name must start with ”test”.
1
2
3
4
5
class MyTestCase extends haxe.unit.TestCase {
public function testBasic() {
assertEquals("A", "A");
}
}
Running unit tests To run the test, an instance of haxe.unit.TestRunner has to be created. Add
the TestCase using the add method and call run to start the test.
class Main {
static function main() {
3
var r = new haxe.unit.TestRunner();
4
r.add(new MyTestCase());
5
// add other TestCases here
1
2
6
7
8
9
10
// finally, run the tests
r.run();
}
}
175
The result of the test looks like this:
Class: MyTestCase
.
3 OK 1 tests, 0 failed, 1 success
1
2
Test functions
The haxe.unit.TestCase class comes with three test functions.
assertEquals(expected, actual) Succeeds if expected and actual are equal
assertTrue(a) Succeeds if a is true
assertFalse(a) Succeeds if a is false
Setup and tear down To run code before or after the test, override the functions setup and
tearDown in the TestCase.
setup is called before each test runs.
tearDown is called once after all tests are run.
1
2
class MyTestCase extends haxe.unit.TestCase {
var value:String;
3
4
5
6
7
8
9
10
11
override public function setup() {
value = "foo";
}
public function testSetup() {
assertEquals("foo", value);
}
}
Comparing Complex Objects With complex objects it can be difficult to generate expected values to compare to the actual ones. It can also be a problem that assertEquals doesn’t do a
deep comparison. One way around these issues is to use a string as the expected value and compare it to the actual value converted to a string using Std.string. Below is a trivial example
using an array.
1
2
3
4
public function testArray() {
var actual = [1,2,3];
assertEquals("[1, 2, 3]", Std.string(actual));
}
Run unit test This is an example showing how to run your unit tests (on Neko and Node.js)
after compilation using a HXML (7.1).
176
1
2
3
4
5
6
7
8
9
10
11
-cp source/main/haxe
-cp source/test/haxe
-main your.package.TestRunnerMain
--each
-neko output/neko/test.n
-cmd neko ./output/neko/test.n
--next
-js output/javascript/test.js
-cmd node ./output/javascript/test.js
Related content
• See the haxe.unit package on the API documentation for more details.
177
Part IV
Miscellaneous
178
Chapter 11
Haxelib
Haxelib’s documentation is available at lib.haxe.org/documentation/using-haxelib/.
179
Chapter 12
Target Details
12.1
JavaScript
Haxe provides the ability to target JavaScript. It does so by transpiling Haxe to JavaScript. The
current implementation targets ECMAScript 5. But it is possible to target lower versions using
-D js-es=.
When choosing the JavaScript target, only the used Haxe code of the project (and used parts
of the standard library) are transpiled to JavaScript. This results in optimal filesize which is
also readable. Source maps (13.5.1) are available and there are several ways to get debug (13)
information. The standard library aims to have same functionality across all targets.
Usage You may want to compile Haxe to JavaScript in the following scenarios:
Client-side JavaScript Interacting with DOM elements. Haxe provides up to date typed interfaces to interact with the Document Object Model, allowing creation and update of DOM
elements.
Haxe can be used together with existing third-party libraries and frameworks, such as jQuery,
React or Vue. To access third-party frameworks with a strongly-typed API, there are extern libraries available on Haxelib. Alternatively, it is possible to create own externs (see Using external
JavaScript libraries (Section 12.1.2)) or use the dynamic type to access any framework, see Using
Untyped JavaScript (Section 12.1.3).
Creating graphics using Canvas and WebGL Use Haxe to create graphical elements on a web
page using WebGL.
Libraries like OpenFL, Heaps and Kha make use of WebGL as one of their backends.
Creating Haxe code that targets server-side JavaScript Working with server-side technology. Haxe
can be used to create server-side JavaScript like Node.js.
Getting started with Haxe/JavaScript (Section 12.1.1)
12.1.1
Getting started with Haxe/JavaScript
Haxe can be a powerful tool for developing JavaScript applications. Let’s look at our first sample.
This is a very simple example showing the toolchain.
Create a new folder and save this class as Main.hx.
1
2
3
import js.Browser;
class Main {
static function main() {
180
var button = Browser.document.createButtonElement();
button.textContent = "Click me!";
button.onclick = function(event) {
Browser.alert("Haxe is great");
}
Browser.document.body.appendChild(button);
4
5
6
7
8
9
10
11
}
}
To compile, either run the following from the command line:
1
haxe -js main-javascript.js -main Main
Another possibility is to create and run (double-click) a file called compile.hxml. In this
example the hxml file should be in the same directory as the example class.
1
2
-js main-javascript.js
-main Main
The output will be a main-javascript.js, which creates and adds a clickable button to the document body.
Run the JavaScript To display the output in a browser, create an HTML-document called
index.html and open it.
5
6
1
2
3
4
More information
• Debugging in JavaScript (Section 13.4)
• Haxe/JavaScript tutorials
• Haxe JavaScript API docs
• MDN JavaScript Reference
• Haxe/Javascript documentation by Matthijs Kamstra
12.1.2
Using external JavaScript libraries
The externs mechanism (6.2) provides access to the native APIs in a type-safe manner. It assumes
that the defined types exist at run-time but assumes nothing about how and where those types
are defined.
An example of an extern class is the jQuery class of the Haxe Standard Library. To illustrate,
here is a simplified version of this extern class:
181
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package js.jquery;
@:native("$") extern class JQuery {
/**
Creates DOM elements on the fly from the provided string of
raw HTML.
OR
Accepts a string containing a CSS selector which is then used
to match a set of elements.
OR
Binds a function to be executed when the DOM has finished
loading.
**/
@:selfCall
@:overload(function(element:js.html.Element):Void { })
@:overload(function(selection:js.jquery.JQuery):Void { })
@:overload(function(callback:haxe.Constraints.Function):Void { })
@:overload(function(selector:String, ?context:haxe.extern.
EitherType):Void { })
public function new():Void;
/**
Adds the specified class(es) to each element in the set of
matched elements.
**/
@:overload(function(_function:Int -> String -> String):js.jquery.
JQuery { })
public function addClass(className:String):js.jquery.JQuery;
19
20
21
22
23
24
/**
Get the HTML contents of the first element in the set of
matched elements.
OR
Set the HTML contents of each element in the set of matched
elements.
25
26
**/
@:overload(function(htmlString:String):js.jquery.JQuery { })
@:overload(function(_function:Int -> String -> String):js.jquery.
JQuery { })
public function html():String;
27
28
29
30
31
}
Note that functions can be overloaded to accept different types of arguments and return values, using the @:overload metadata. Function overloading works only in externs.
Using this extern, we can use jQuery like this:
import js.jquery.*;
..
new JQuery("#my-div").addClass("brand-success").html("haxe is great!")
;
4 ..
1
2
3
182
The package and class name of the extern class should be the same as defined in the external
library. If that is not the case, rewrite the path of a class using @:native.
1
package my.application.media;
2
3
4
5
@:native(’external.library.media.video’)
extern class Video {
..
Some JavaScript libraries favor instantiating classes without using the new keyword. To
prevent the Haxe compiler outputting the new keyword when using a class, we can attach a
@:selfCall metadata to its constructor. For example, when we instantiate the jQuery extern
class above, new JQuery() will be outputted as $() instead of new $(). The @:selfCall
metadata can also be attached to a method. In this case, the method will be interpreted as a direct
call to the object, illustrated as follows:
extern class Functor {
public function new():Void;
3
@:selfCall function call():Void;
4 }
1
2
5
6
7
8
class Test {
static function main() {
var f = new Functor();
9
f.call(); // will be outputted as ‘f();‘
10
}
11 }
Beside externs, Typedefs (3.1) can be another great way to name (or alias) a JavaScript type.
The major difference between typedefs and externs is that, typedefs are duck-typed but externs
are not. Typedefs are suitable for common data structures, e.g. point ({x:Float, y:Float}).
Use of a point structure typedef for function arguments allows external JavaScript functions to
accept point class instances from Haxe or from another JavaScript library. It is also useful for
typing JSON objects.
The Haxe Standard Library comes with externs of jQuery and SWFObject. Their version
compatibility is summarized as follows:
Haxe version
3.3
3.23.3
3.2-
Library
jQuery 1.12.1 / 2.2.1
jQuery 1.6.4
SWFObject 2.3
SWFObject 1.5
Externs location
¡code¿js.jquery.*¡/code¿
¡code¿js.JQuery¡/code¿
¡code¿js.swfobject.*¡/code¿
¡code¿js.SWFObject¡/code¿
There are many externs for other popular native libraries available on Haxelib library (11). To
view a list of them, check out the extern tag.
12.1.3
Using Untyped JavaScript
In Haxe, it is possible to call an exposed function thanks to the untyped keyword. This can be
useful in some cases if we don’t want to write externs. Anything untyped that is valid syntax
will be generated as it is.
183
1
untyped window.trackEvent("page1");
See also JavaScript untyped functions (Section 12.1.4) to inject raw JavaScript.
12.1.4
JavaScript untyped functions
These functions allow to access specific JavaScript platform features. It works only when the
Haxe compiler is targeting JavaScript and should always be prefixed with untyped.
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.
untyped __js__(expr, params) Injects raw JavaScript expressions (12.1.3). It’s allowed
to use {0}, {1}, {2} etc in the expression and use the rest arguments to feed Haxe fields. The
Haxe compiler will take care of the surrounding quotes if needed. The function can also return
values.
1
2
3
4
5
untyped __js__(’alert("Haxe is great!")’);
// output: alert("Haxe is great!");
var myMessage = "Haxe is great!";
untyped __js__(’alert({0})’, myMessage);
6 // output:
7 // var myMessage = "Haxe is great!";
8 // alert(myMessage);
9
10
11
var myVar:Bool = untyped __js__(’confirm({0})’, "Are you sure?");
// output: var myVar = confirm("Are you sure?");
12
13
14
var hexString:String = untyped __js__(’({0}).toString({1})’, 255, 16);
// output: var hexString = (255).toString(16);
untyped __instanceof__(o,cl)
1
2
3
var myString = new String("Haxe is great");
var isString = untyped __instanceof__(myString, String);
output: var isString = (myString instanceof String);
untyped __typeof__(o)
1
2
Same as o instanceof cl in JavaScript.
Same as typeof o in JavaScript.
var isNodeJS = untyped __typeof__(window) == null;
output: var isNodeJS = typeof(window) == null;
untyped __strict_eq__(a,b)
”triple equals” or ”identity”).
Same as a === b in JavaScript, tests on strict equality (or
184
1
2
3
4
var a = "0";
var b = 0;
var isEqual = untyped __strict_eq__(a, b);
output: var isEqual = ((a) === b);
untyped __strict_neq__(a,b)
equality.
1
2
3
4
Same as a !== b in JavaScript, tests on negative strict
var a = "0";
var b = 0;
var isntEqual = untyped __strict_neq__(a, b);
output: var isntEqual = ((a) !== b);
Expression injection In some cases it may be needed to inject raw JavaScript code into Haxegenerated code. With the __js__ function we can inject pure JavaScript code fragments into the
output. This code is always untyped and can not be validated, so it accepts invalid code in the
output, which is error-prone. This could, for example, write a JavaScript comment in the output.
1
untyped __js__(’// haxe is great!’);
A more useful demonstration would be to call a function and pass arguments using the __js__ function. This example illustrates how to call this function and how to pass parameters.
Note that the code interpolation will wrap the quotes around strings in the generated output.
1
2
// Haxe code:
var myVar = untyped __js__(’myObject.myJavaScriptFunction({0}, {1})’,
"Mark", 31);
This will generate the following JavaScript code:
1
2
// JavaScript Code
var myVar = myObject.myJavaScriptFunction("Mark", 31);
12.1.5
JavaScript target Metadata
This is the list of JavaScript specific metadata. For more information, see also the complete list of
all Haxe built-in metadata (8.1).
Metadata
@:expose (?Name=Class path)
@:jsRequire
@:selfCall
12.1.6
JavaScript metadata
Description
Makes the class available on the window object or exports for node.js
Generate javascript module require expression for given extern
Translates method calls into calling object directly
Exposing Haxe classes for JavaScript
It is possible to make Haxe classes or static fields available for usage in plain JavaScript. To
expose, add the @:expose metadata to the desired class or static fields.
This example exposes the Haxe class MyClass.
185
1
2
3
4
5
6
7
8
9
10
@:expose
class MyClass {
var name:String;
function new(name:String) {
this.name = name;
}
public function foo() {
return ’Greetings from $name!’;
}
}
It generates the following JavaScript output:
1
2
3
4
5
6
7
8
9
10
(function ($hx_exports) { "use strict";
var MyClass = $hx_exports.MyClass = function(name) {
this.name = name;
};
MyClass.prototype = {
foo: function() {
return "Greetings from " + this.name + "!";
}
};
})(typeof window != "undefined" ? window : exports);
By passing globals (like window or exports) as parameters to our anonymous function in
the JavaScript module, it becomes available which allows to expose the Haxe generated module.
In plain JavaScript it is now possible to create an instance of the class and call its public
functions.
1
2
3
// JavaScript code
var instance = new MyClass(’Mark’);
console.log(instance.foo()); // logs a message in the console
The package path of the Haxe class will be completely exposed. To rename the class or define
a different package for the exposed class, use @:expose("my.package.MyExternalClass")
Shallow expose When the code generated by Haxe is part of a larger JavaScript project and
wrapped in a large closure it is not always necessary to expose the Haxe types to global variables. Compiling the project using -D shallow-expose allows the types or static fields to be
available for the surrounding scope of the generated closure only.
When the code is compiled using -D shallow-expose, the generated output will look like
this:
1
2
3
4
5
6
7
8
var $hx_exports = $hx_exports || {};
(function () { "use strict";
var MyClass = $hx_exports.MyClass = function(name) {
this.name = name;
};
MyClass.prototype = {
foo: function() {
return "Greetings from " + this.name + "!";
186
9
10
11
12
}
};
})();
var MyClass = $hx_exports.MyClass;
In this pattern, a var statement is used to expose the module; it doesn’t write to the window
or exports object.
12.1.7
Loading extern classes using ”require” function
Since Haxe 3.2.0
Modern JavaScript platforms, such as Node.js provide a way of loading objects from external
modules using the ”require” function. Haxe supports automatic generation of ”require” statements for extern classes.
This feature can be enabled by specifying @:jsRequire metadata for the extern class. If
our extern class represents a whole module, we pass a single argument to the @:jsRequire
metadata specifying the name of the module to load:
1
2
3
4
@:jsRequire("fs")
extern class FS {
static function readFileSync(path:String, encoding:String):String;
}
In case our extern class represents an object within a module, second @:jsRequire argument specifies an object to load from a module:
1
2
3
4
@:jsRequire("http", "Server")
extern class HTTPServer {
function new();
}
The second argument is a dotted-path, so we can load sub-objects in any hierarchy.
If we need to load custom JavaScript objects in runtime, a js.Lib.require function can be
used. It takes String as its only argument and returns Dynamic, so it is advised to be assigned
to a strictly typed variable.
12.2
Flash
12.2.1
Getting started with Haxe/Flash
Developing Flash applications is really easy with Haxe. Let’s look at our first code sample. This
is a basic example showing most of the toolchain.
Create a new folder and save this class as Main.hx.
import flash.Lib;
import flash.display.Shape;
class Main {
4
static function main() {
5
var stage = Lib.current.stage;
1
2
3
6
7
8
9
// create a center aligned rounded gray square
var shape = new Shape();
shape.graphics.beginFill(0x333333);
187
shape.graphics.drawRoundRect(0, 0, 100, 100, 10);
shape.x = (stage.stageWidth - 100) / 2;
shape.y = (stage.stageHeight - 100) / 2;
10
11
12
13
14
15
16
stage.addChild(shape);
}
}
To compile this, either run the following from the command line:
1
haxe -swf main-flash.swf -main Main -swf-version 15 -swf-header
960:640:60:f68712
Another possibility is to create and run (double-click) a file called compile.hxml. In this
example the hxml file should be in the same directory as the example class.
-swf main-flash.swf
-main Main
3 -swf-version 15
4 -swf-header 960:640:60:f68712
1
2
The output will be a main-flash.swf with size 960x640 pixels at 60 FPS with an orange background color and a gray square in the center.
Display the Flash Run the SWF standalone using the Standalone Debugger FlashPlayer.
To display the output in a browser using the Flash plugin, create an HTML-document called
index.html and open it.
1
2
3
4
5
6
Source Exif Data:
File Type : PDF File Type Extension : pdf MIME Type : application/pdf PDF Version : 1.5 Linearized : No Page Count : 208 Page Mode : UseOutlines Author : Title : Subject : Creator : LaTeX with hyperref package Producer : pdfTeX-1.40.19 Create Date : 2018:09:11 23:01:07+02:00 Modify Date : 2018:09:11 23:01:07+02:00 Trapped : False PTEX Fullbanner : This is MiKTeX-pdfTeX 2.9.6668 (1.40.19)EXIF Metadata provided by EXIF.tools