COMMUNITY

Macro & deep merge objects

macro

(Thomas Fétiveau) #1

Hi there!
I’m looking for a macro way to deep merge objects.
I’ve found this : https://code.haxe.org/category/macros/combine-objects.html
Which is almost good except it doesn’t deep merge.
Is there anybody there that has enough macro knowledge to update this macro so that it’s able to deep merge?
Just to be clear, I’m looking for this:

typedef MyStruct = {
  ? a : Int
  ? b : { ? ba : Int, ? bb : String },
  ? c : String
}

var a : MyStruct = { a: 0, b: { ba: 9} };
var b : MyStruct = { c: '0' };
var c : MyStruct = { a: 3, b: { bb: 'a' } }; 

var r : MyStruct = combine(a,b,c); // gives: { a: 3, b: { ba: 9, bb: 'a' }, c: '0' }

(Jens Fischer) #2

This might be useful? :slight_smile:


(Thomas Fétiveau) #3

How would you use it with my example?

With this:

a = StructDefaultsMacro.applyDefaults(a,b);
a = StructDefaultsMacro.applyDefaults(a,c);

I’m getting:

$ haxe build.hxml 
StructDefaultsMacro.hx:18: characters 38-39 : Unable to retrieve struct fields

(Rudy Ges) #4

What is a in your example? It doesn’t seem to be a struct, while in your original example it was.

It is supposed to work (http://try-haxe.mrcdk.com/#530F5), though the recursivity rules don’t seem to really match your needs.

Edit:

This macro relies on 3 things:

  • variables should be of struct types (TAnonymous)
  • subtypes should be proper typedefs
  • the second argument is the default values, and should be complete

http://try-haxe.mrcdk.com/#dfB44