[macro] add SignletonMacro
This commit is contained in:
55
src/main/haxework/macro/SingletonMacro.hx
Normal file
55
src/main/haxework/macro/SingletonMacro.hx
Normal file
@@ -0,0 +1,55 @@
|
||||
package haxework.macro;
|
||||
|
||||
import haxe.macro.TypeTools;
|
||||
import haxe.macro.Context;
|
||||
import haxe.macro.ExprTools;
|
||||
import haxe.macro.Expr;
|
||||
import haxe.macro.Type;
|
||||
|
||||
class SingletonMacro {
|
||||
|
||||
private static inline var metaName:String = ":singleton";
|
||||
|
||||
public static function has(classType:ClassType):Bool {
|
||||
return classType.meta.has(metaName);
|
||||
}
|
||||
|
||||
private var classType:ClassType;
|
||||
private var fields:Array<Field>;
|
||||
|
||||
public function new(classType:ClassType, fields:Array<Field>) {
|
||||
this.classType = classType;
|
||||
this.fields = fields;
|
||||
}
|
||||
|
||||
|
||||
public function apply():Array<Field> {
|
||||
var result:Array<Field> = fields.slice(0);
|
||||
var classTypePath:TypePath = {
|
||||
pack: classType.pack,
|
||||
name: classType.name,
|
||||
};
|
||||
var type:ComplexType = TPath(classTypePath);
|
||||
result.push({
|
||||
name: 'instance',
|
||||
access: [APublic, AStatic],
|
||||
pos: Context.currentPos(),
|
||||
kind: FProp('get', 'null', type),
|
||||
});
|
||||
var typeStr = classType.name;
|
||||
result.push({
|
||||
name: 'get_instance',
|
||||
access: [APrivate, AStatic],
|
||||
pos: Context.currentPos(),
|
||||
kind: FFun({
|
||||
args: [],
|
||||
ret: type,
|
||||
expr: macro $b{[
|
||||
macro if (instance == null) instance = new $classTypePath(),
|
||||
macro return instance
|
||||
]},
|
||||
}),
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package haxework.macro;
|
||||
|
||||
import haxe.macro.Type.ClassType;
|
||||
import haxe.macro.Expr;
|
||||
import haxe.macro.Type;
|
||||
|
||||
class Util {
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package haxework.parser;
|
||||
|
||||
import haxework.macro.SingletonMacro.SingletonMacro;
|
||||
import haxework.macro.StyleMacro;
|
||||
import haxe.macro.TypeTools;
|
||||
import haxe.macro.Context;
|
||||
@@ -63,6 +64,11 @@ class Parser {
|
||||
var style = new StyleMacro(ct, fields);
|
||||
fields = style.apply();
|
||||
}
|
||||
if (SingletonMacro.has(ct)) {
|
||||
modify = true;
|
||||
var singleton = new SingletonMacro(ct, fields);
|
||||
fields = singleton.apply();
|
||||
}
|
||||
processed.set(localName, true);
|
||||
modify ? fields : null;
|
||||
default: null;
|
||||
|
||||
Reference in New Issue
Block a user