diff --git a/apps/twnlua/docgen.py b/apps/twnlua/docgen.py new file mode 100755 index 0000000..a57aba1 --- /dev/null +++ b/apps/twnlua/docgen.py @@ -0,0 +1,53 @@ +#!/bin/env python3 + +import sys, json + +with open(sys.argv[1], 'r') if sys.argv[1] != "-" else sys.stdin as f: + api_source = f.read() + +api = json.loads(api_source) + +def to_lua_type_annot(typename): + basetype = typename.rsplit(' *', 1)[0] + if typename == "char *": + return "string" + elif basetype == "float": + return "number" + elif basetype == "bool": + return "boolean" + elif basetype == "Control": + return "Control" + elif basetype == "Vec2": + return r"{ x: number, y: number }" + elif basetype == "Vec3": + return r"{ x: number, y: number, z: number }" + elif basetype == "Color": + return r"{ r: number, g: number, b: number, a: number }" + elif basetype == "Rect": + return r"{ x: number, y: number, w: number, h: number }" + else: + return "unknown" + # raise BaseException("Unhandled type for annotation: %s" % typename) + +type_annotations, enum_annotations = {}, {} +type_annotations["ctx"] = r"{ %s, udata: table }" % \ + ', '.join("%s: %s" % (f["name"], to_lua_type_annot(f["type"])) for f in api["types"]["Context"]["fields"]) + +for annot in type_annotations: + print("---@type " + type_annotations[annot]) + print(r"%s = nil" % annot) + +enum_annotations["Control"] = \ + '|'.join('\'"%s"\'' % e for e in api["types"]["Control"]["enums"]) + +for annot in enum_annotations: + print("---@alias %s %s" % (annot, enum_annotations[annot])) + +procedure_annotations = {} +for procedure, procedure_desc in api["procedures"].items(): + procedure_annotations[procedure] = r"{ %s }" % \ + ', '.join("%s: %s" % (p["name"], to_lua_type_annot(p["type"]) + '?' * ("default" in p)) for p in procedure_desc["params"]) + +for annot in procedure_annotations: + print("---@param args " + procedure_annotations[annot]) + print("function %s(args) end" % annot)