Add TypeMap with test.

This commit is contained in:
Juraj Kirchheim
2016-04-19 12:52:45 +02:00
parent 0284615f99
commit c3cecad472
4 changed files with 68 additions and 1 deletions

View File

@@ -408,4 +408,8 @@ Here, `Value` will just use a plain expression, whereas `Arg` and `OptArg` will
### Expression Level Transformation
Because the state of a constructor is rather delicate, the API prohibits you to just mess around with the whole constructor body at an expression level. For that to happen, you can register `onGenerate` hooks. These will be called when the corresponding `ClassBuilder` does its export. The hooks are cleared after the export.
Because the state of a constructor is rather delicate, the API prohibits you to just mess around with the whole constructor body at an expression level. For that to happen, you can register `onGenerate` hooks. These will be called when the corresponding `ClassBuilder` does its export. The hooks are cleared after the export.
# TypeMap
You can find a type map, i.e. a map where the keys are `haxe.macro.Type`, in `tink.macro.TypeMap`. It's pretty much an ordinary map. Currently, it relies rather strongly on [`haxe.macro.TypeTools.toString()`](http://api.haxe.org/haxe/macro/TypeTools.html#toString) and it remains to be determined whether that is a reliable choice. Please report any issues you might face.

32
src/tink/macro/TypeMap.hx Normal file
View File

@@ -0,0 +1,32 @@
package tink.macro;
import haxe.Constraints.IMap;
import haxe.ds.BalancedTree;
import haxe.macro.Context;
import haxe.macro.Type;
using haxe.macro.Tools;
using tink.MacroApi;
class TypeMap<V> extends BalancedTree<Type, V> implements IMap<Type, V> {
var follow:Bool;
public function new(?noFollow:Bool) {
this.follow = noFollow != true;
super();
}
override function compare(k1:Type, k2:Type):Int {
if (follow) {
k1 = k1.reduce();
k2 = k2.reduce();
}
//trace(k1.toString());
//trace(k2.toString());
return switch k1.getIndex() - k2.getIndex() {
case 0: Reflect.compare(k1.toString(), k2.toString());//TODO: this may be rather expensive and not very reliable
case v: v;
}
}
}

View File

@@ -11,6 +11,7 @@ class Run {
new Exprs(),
new Types(),
new Positions(),
new TypeMapTest(),
];
#end
macro static function test() {

30
tests/TypeMapTest.hx Normal file
View File

@@ -0,0 +1,30 @@
package;
import haxe.unit.TestCase;
import tink.macro.TypeMap;
using haxe.macro.Context;
class TypeMapTest extends TestCase {
function testMap() {
var t = new TypeMap();
var t1 = (macro [{ foo: [{ bar: '5' }]}]).typeof();
var t2 = (macro [{ foo: [{ bar: 5 }]}]).typeof();
t.set(t1, 0);
assertEquals(Lambda.count(t), 1);
t.set(t2, 1);
assertEquals(Lambda.count(t), 2);
t.set(t1, 2);
assertEquals(Lambda.count(t), 2);
t.set(t2, 3);
assertEquals(Lambda.count(t), 2);
assertEquals(t.get(t1), 2);
assertEquals(t.get(t2), 3);
assertTrue(true);
}
}