16 def walk_counters(s, pathset):
19 r2 = {"name": e.name, "elements": e.block}
36 d.append({"enumtype": e.enumtype})
44 d = {"reply": e.reply}
48 d["stream_msg"] = e.stream_message
50 d["events"] = e.events
55 def walk_defs(s, is_message=False):
61 if b.type == "Option":
65 d.append([b.fieldtype, b.fieldname, b.limit])
67 d.append([b.fieldtype, b.fieldname])
68 elif b.type == "Array":
70 d.append([b.fieldtype, b.fieldname, b.length, b.lengthfield])
72 d.append([b.fieldtype, b.fieldname, b.length])
73 elif b.type == "Union":
76 raise ValueError("Error in processing array type %s" % b)
78 if is_message and t.crc:
80 c["crc"] = "{0:#0{1}x}".format(t.crc, 10)
81 c["options"] = t.options
83 c["comment"] = t.comment
95 def contents_to_c_string(contents):
96 # Escape backslashes and double quotes
97 contents = contents.replace("\\", "\\\\").replace('"', '\\"')
98 # Replace newlines with \n
99 contents = contents.replace("\n", "\\n")
100 return '"' + contents + '"'
103 def run(output_dir, apifilename, s):
105 sys.stderr.write("Missing --outputdir argument")
108 basename = os.path.basename(apifilename)
109 filename_json_repr = os.path.join(output_dir + "/" + basename + "_json.h")
110 filename, _ = os.path.splitext(basename)
111 modulename = filename.replace(".", "_")
115 j["types"] = walk_defs([o for o in s["types"] if o.__class__.__name__ == "Typedef"])
116 j["messages"] = walk_defs(s["Define"], True)
117 j["unions"] = walk_defs([o for o in s["types"] if o.__class__.__name__ == "Union"])
118 j["enums"] = walk_enums([o for o in s["types"] if o.__class__.__name__ == "Enum"])
119 j["enumflags"] = walk_enums(
120 [o for o in s["types"] if o.__class__.__name__ == "EnumFlag"]
122 j["services"] = walk_services(s["Service"])
123 j["options"] = s["Option"]
125 o.name: o.alias for o in s["types"] if o.__class__.__name__ == "Using"
127 j["vl_api_version"] = hex(s["file_crc"])
128 j["imports"] = walk_imports(i for i in s["Import"])
129 j["counters"], j["paths"] = walk_counters(s["Counters"], s["Paths"])
130 r = json.dumps(j, indent=4, separators=(",", ": "))
131 c_string = contents_to_c_string(r)
132 with open(filename_json_repr, "w", encoding="UTF-8") as f:
133 print(f"const char *json_api_repr_{modulename} = {c_string};", file=f)
134 # return json.dumps(j, indent=4, separators=(",", ": "))