HaxeFoundation / haxe.org-comments

Repository to collect comments of our haxe.org websites
2 stars 2 forks source link

[haxe.org/manual] Type Reification #39

Open utterances-bot opened 4 years ago

utterances-bot commented 4 years ago

Type Reification - Haxe - The Cross-platform Toolkit

Haxe is an open source toolkit based on a modern, high level, strictly typed programming language.

https://haxe.org/manual/macro-reification-type.html

ghost commented 4 years ago

I need some example understand the concept of reification.I am very confused.

sonygod commented 3 years ago

https://stackoverflow.com/questions/34974996/creating-a-function-in-a-macro @ghost

markknol commented 3 years ago

Reification, as far as I understand it, is some sort of sugar to create expressions more easily. The internal structure of the compiler is using enums, so as a simple example you want a macro function to return 123 as expression, you could do this:

public static macro function getNumber() {
  var calculatedValue = 123;
  return {expr: EConst(CInt(calculatedValue)), pos: Context.currentPos()};
}

This can become super unmanagable if you want to return more than just a number, imaging constructing a full class like that🤯 That's what reification is for. Of course, it still requires a bit of knowledge of what you are going to return, in our case we will return a basic type, so we need the macro $v{ } reification-function. This allows to rewrite the macro above to the following:

public static macro function getNumber():ExprOf<Int> {
  var calculatedValue = 123;
  return macro $v{calculatedValue}; 
]

Now there are many reinfication functions to construct anything virtually anything you can do in "normal" Haxe code, on this page the syntax for types is explained. Hope this helps to give you bit of understanding, but also take a look here and check out some real examples at the Haxe cookbook https://code.haxe.org/category/macros/