diff --git a/src/main/haxework/macro/SingletonMacro.hx b/src/main/haxework/macro/SingletonMacro.hx new file mode 100644 index 0000000..41edc76 --- /dev/null +++ b/src/main/haxework/macro/SingletonMacro.hx @@ -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; + + public function new(classType:ClassType, fields:Array) { + this.classType = classType; + this.fields = fields; + } + + + public function apply():Array { + var result:Array = 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; + } +} diff --git a/src/main/haxework/macro/Util.hx b/src/main/haxework/macro/Util.hx index 85a69d2..697f006 100644 --- a/src/main/haxework/macro/Util.hx +++ b/src/main/haxework/macro/Util.hx @@ -1,7 +1,7 @@ package haxework.macro; -import haxe.macro.Type.ClassType; import haxe.macro.Expr; +import haxe.macro.Type; class Util { diff --git a/src/main/haxework/parser/Parser.hx b/src/main/haxework/parser/Parser.hx index ffc3d5f..efc505d 100644 --- a/src/main/haxework/parser/Parser.hx +++ b/src/main/haxework/parser/Parser.hx @@ -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;