-
-
Notifications
You must be signed in to change notification settings - Fork 87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Create "Autobuild fields from enum type param" #181
Draft
Geokureli
wants to merge
8
commits into
HaxeFoundation:master
Choose a base branch
from
Geokureli:patch-1
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
70665ac
Create "Add enum values as fields"
Geokureli e8acd20
Update add-enum-values-as-fields.md
Geokureli 0a99690
More practical example
Geokureli 672dc9c
fix explanation
Geokureli 798b364
tags
Geokureli 4ba2f92
Update and rename add-enum-values-as-fields.md to autobuild-fields-fr…
Geokureli 460f8aa
add missing file extension
Geokureli e72cec5
remove unused line
Geokureli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
143 changes: 143 additions & 0 deletions
143
assets/content/cookbook/Macros/autobuild-fields-from-enum.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
[tags]: / "autobuild-macro,building-fields" | ||
|
||
# Autobuild fields from enum type param | ||
|
||
This macro function adds fields corresponding to an extended type's enum type param. | ||
|
||
```haxe | ||
import haxe.macro.Expr; | ||
import haxe.macro.Context; | ||
import haxe.macro.Type; | ||
|
||
using haxe.macro.Tools; | ||
|
||
class Macro { | ||
public static function buildSet():Array<Field> { | ||
final fields = Context.getBuildFields(); | ||
|
||
try { | ||
return switch Context.getLocalType() { | ||
// Extract the type parameter | ||
case TInst(getEnumType(_.get()) => enumType, _): | ||
// Generate fields | ||
addFields(enumType, fields); | ||
|
||
fields; | ||
case found: | ||
throw 'Expected TInst, found: $found'; | ||
} | ||
} catch(e) { | ||
// Catch thrown errors and point them to the failing class | ||
Context.error(e.message, Context.currentPos()); | ||
return Context.getBuildFields(); | ||
} | ||
} | ||
|
||
static function getEnumType(local:ClassType):EnumType { | ||
return switch local.superClass.params { | ||
case [_.follow() => param]: | ||
switch param { | ||
case TEnum(type, []): | ||
type.get(); | ||
case TEnum(_, _): | ||
throw "Enums with type params are not allowed"; | ||
case found: | ||
throw 'T must be an Enum type, found: $found'; | ||
} | ||
case found: | ||
throw 'Expected <T:EnumValue>, found: $found'; | ||
} | ||
} | ||
|
||
static function addFields(enumType:EnumType, fields:Array<Field>) { | ||
// Add a getter for each enum value | ||
for (name => field in enumType.constructs) { | ||
// Determine the full path of the enum field | ||
final path = enumType.module.split("."); | ||
path.push(enumType.name); | ||
path.push(field.name); | ||
|
||
// Create a getter that calls has() with the corresponding enum field | ||
final getterName = 'get_$name'; | ||
final newFields = (macro class TempClass { | ||
public var $name(get, never):Bool; | ||
|
||
@:noCompletion inline function $getterName() return has($p{path}); | ||
}).fields; | ||
fields.push(newFields[0]); | ||
fields.push(newFields[1]); | ||
} | ||
} | ||
} | ||
|
||
``` | ||
|
||
## Usage | ||
|
||
The macro is used via [@:autoBuild](https://haxe.org/manual/macro-auto-build.html) | ||
|
||
```haxe | ||
class Test { | ||
static function main() { | ||
// poised dagger damage types | ||
final dmg = new DamageSet([Poison, Piercing, Slashing]); | ||
trace(dmg.Acid); // false | ||
trace(dmg.Bludgeoning); // false | ||
trace(dmg.Cold); // false | ||
trace(dmg.Fire); // false | ||
trace(dmg.Force); // false | ||
trace(dmg.Lightning); // false | ||
trace(dmg.Necrotic); // false | ||
trace(dmg.Piercing); // true | ||
trace(dmg.Poison); // true | ||
trace(dmg.Psychic); // false | ||
trace(dmg.Radiant); // false | ||
trace(dmg.Slashing); // true | ||
trace(dmg.Thunder); // false | ||
} | ||
} | ||
|
||
class DamageSet extends EnumSet<DamageType> {} | ||
|
||
enum DamageType { | ||
Acid; | ||
Bludgeoning; | ||
Cold; | ||
Fire; | ||
Force; | ||
Lightning; | ||
Necrotic; | ||
Piercing; | ||
Poison; | ||
Psychic; | ||
Radiant; | ||
Slashing; | ||
Thunder; | ||
} | ||
|
||
@:autoBuild(Macro.buildSet()) | ||
class EnumSet<E:EnumValue> { | ||
final list = new Array<E>(); | ||
|
||
public function new(list:Array<E>) { | ||
for (item in list) | ||
add(item); | ||
} | ||
|
||
inline public function has(value:E):Bool { | ||
return list.contains(value); | ||
} | ||
|
||
public function add(value:E) { | ||
if (has(value) == false) | ||
list.push(value); | ||
} | ||
|
||
public function remove(value:E) { | ||
list.remove(value); | ||
} | ||
} | ||
``` | ||
Notice that a field for each `DamageType` were added to `DamageSet` | ||
|
||
> Author: [George Kurelic](https://github.com/geokureli) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've found that this is my preferred way of handling macro errors, using throw everywhere, catching them and converting them to a
Context.error
that points to the line that triggered the macro. This is more informative to the dev utilizing the macro, but less informative to devs adding to or maintaining the macro, which I fix by temporarily commenting out the try/catch.Would it be better or simpler to just use Context.error everywhere and remove the try? Alternatively should I trim down the error handling altogether and just have a simpler but perhaps more fragile example that just needs to work for the given usage example?