HaxeFoundation / HaxeFoundation/haxe

macro new - was: Configurable @:structInit initializer

Open
#5,292 19 comments 4 reactions 1 assignee Claimed by @Simn View on GitHub
Dominant language
Haxe
Stars
6.9k
Forks
715
Avg merge
2d 2h
Merged PRs (30d)
11

Description

> @Simn, you know what I'm talking about. ;D

As of Haxe 3.3.0-rc1, classes annotated with `@:structInit` will have their constructor called with arguments from the struct literal expression.

I'm proposing a small addition to this mechanism to allow a macro to modify this expression. ~~Instead of always mapping it to a constructor call, pass it to a macro call.~~ By allowing constructors to be macros:

``` haxe
@:structInit
class Point {
// one Expr per constructor argument?
// array of Expr?
// EDIT: we have inline new, why not macro new?
public macro function new(e : Expr) {
// ...
}

var x : Int;
var y : Int;
}
```

This would allow us to implement several things in libraries:
- Object pooling
- Immutable objects with statically known instance memoization
- (replace `var p : Point = {};` with `var p = Point.empty;`)
- Type conversion: `var p : Point = {x: "1", y: "2"}; => macro calling Std.parseInt`

Because `@:structInit` would reverse the macro call "responsibility", this gives us new macro powers without having to abuse `@:build` or similar at the instantiation point.

---

If the compiler would pass array literals to `macro structInit` as well, this would allow implementing set literals using array syntax:

```
var s : Set = [1, 2, 3];
s.contains(1) // => true
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.