generate_datatypes.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. #!/usr/bin/env python
  2. # This Source Code Form is subject to the terms of the Mozilla Public
  3. # License, v. 2.0. If a copy of the MPL was not distributed with this
  4. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. from __future__ import print_function
  6. import sys
  7. import time
  8. import platform
  9. import getpass
  10. from collections import OrderedDict
  11. import re
  12. import xml.etree.ElementTree as etree
  13. import itertools
  14. import argparse
  15. import csv
  16. from nodeset_compiler.opaque_type_mapping import opaque_type_mapping, get_base_type_for_opaque
  17. types = OrderedDict() # contains types that were already parsed
  18. typedescriptions = {} # contains type nodeids
  19. excluded_types = ["NodeIdType", "InstanceNode", "TypeNode", "Node", "ObjectNode",
  20. "ObjectTypeNode", "VariableNode", "VariableTypeNode", "ReferenceTypeNode",
  21. "MethodNode", "ViewNode", "DataTypeNode",
  22. "NumericRange", "NumericRangeDimensions",
  23. "UA_ServerDiagnosticsSummaryDataType", "UA_SamplingIntervalDiagnosticsDataType",
  24. "UA_SessionSecurityDiagnosticsDataType", "UA_SubscriptionDiagnosticsDataType",
  25. "UA_SessionDiagnosticsDataType"]
  26. builtin_types = ["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
  27. "Int64", "UInt64", "Float", "Double", "String", "DateTime", "Guid",
  28. "ByteString", "XmlElement", "NodeId", "ExpandedNodeId", "StatusCode",
  29. "QualifiedName", "LocalizedText", "ExtensionObject", "DataValue",
  30. "Variant", "DiagnosticInfo"]
  31. # Some types can be memcpy'd off the binary stream. That's especially important
  32. # for arrays. But we need to check if they contain padding and whether the
  33. # endianness is correct. This dict gives the C-statement that must be true for the
  34. # type to be overlayable. Parsed types are added if they apply.
  35. builtin_overlayable = {"Boolean": "true",
  36. "SByte": "true", "Byte": "true",
  37. "Int16": "UA_BINARY_OVERLAYABLE_INTEGER",
  38. "UInt16": "UA_BINARY_OVERLAYABLE_INTEGER",
  39. "Int32": "UA_BINARY_OVERLAYABLE_INTEGER",
  40. "UInt32": "UA_BINARY_OVERLAYABLE_INTEGER",
  41. "Int64": "UA_BINARY_OVERLAYABLE_INTEGER",
  42. "UInt64": "UA_BINARY_OVERLAYABLE_INTEGER",
  43. "Float": "UA_BINARY_OVERLAYABLE_FLOAT",
  44. "Double": "UA_BINARY_OVERLAYABLE_FLOAT",
  45. "DateTime": "UA_BINARY_OVERLAYABLE_INTEGER",
  46. "StatusCode": "UA_BINARY_OVERLAYABLE_INTEGER",
  47. "Guid": "(UA_BINARY_OVERLAYABLE_INTEGER && " + \
  48. "offsetof(UA_Guid, data2) == sizeof(UA_UInt32) && " + \
  49. "offsetof(UA_Guid, data3) == (sizeof(UA_UInt16) + sizeof(UA_UInt32)) && " + \
  50. "offsetof(UA_Guid, data4) == (2*sizeof(UA_UInt32)))"}
  51. # Type aliases
  52. type_aliases = { "CharArray" : "String" }
  53. def getTypeName(xmlTypeName):
  54. typeName = xmlTypeName[xmlTypeName.find(":")+1:]
  55. return type_aliases.get(typeName, typeName);
  56. # Escape C strings:
  57. def makeCLiteral(value):
  58. return re.sub(r'(?<!\\)"', r'\\"', value.replace('\\', r'\\\\').replace('\n', r'\\n').replace('\r', r''))
  59. # Strip invalid characters to create valid C identifiers (variable names etc):
  60. def makeCIdentifier(value):
  61. return re.sub(r'[^\w]', '', value)
  62. ################
  63. # Type Classes #
  64. ################
  65. class StructMember(object):
  66. def __init__(self, name, memberType, isArray):
  67. self.name = name
  68. self.memberType = memberType
  69. self.isArray = isArray
  70. def getNodeidTypeAndId(nodeId):
  71. if not '=' in nodeId:
  72. return "UA_NODEIDTYPE_NUMERIC, {{{0}}}".format(nodeId)
  73. if nodeId.startswith("i="):
  74. return "UA_NODEIDTYPE_NUMERIC, {{{0}}}".format(nodeId[2:])
  75. if nodeId.startswith("s="):
  76. strId = nodeId[2:]
  77. return "UA_NODEIDTYPE_STRING, {{ .string = UA_STRING_STATIC(\"{id}\") }}".format(id=strId.replace("\"", "\\\""))
  78. class Type(object):
  79. def __init__(self, outname, xml, namespace):
  80. self.name = xml.get("Name")
  81. self.ns0 = ("true" if namespace == 0 else "false")
  82. self.typeIndex = makeCIdentifier(outname.upper() + "_" + self.name.upper())
  83. self.outname = outname
  84. self.description = ""
  85. self.pointerfree = "false"
  86. self.overlayable = "false"
  87. if self.name in builtin_types:
  88. self.builtin = "true"
  89. else:
  90. self.builtin = "false"
  91. self.members = [StructMember("", self, False)] # Returns one member: itself. Overwritten by some types.
  92. for child in xml:
  93. if child.tag == "{http://opcfoundation.org/BinarySchema/}Documentation":
  94. self.description = child.text
  95. break
  96. def datatype_c(self):
  97. xmlEncodingId = "0"
  98. binaryEncodingId = "0"
  99. if self.name in typedescriptions:
  100. description = typedescriptions[self.name]
  101. typeid = "{%s, %s}" % (description.namespaceid, getNodeidTypeAndId(description.nodeid))
  102. xmlEncodingId = description.xmlEncodingId
  103. binaryEncodingId = description.binaryEncodingId
  104. else:
  105. typeid = "{0, UA_NODEIDTYPE_NUMERIC, {0}}"
  106. idName = makeCIdentifier(self.name)
  107. return "{\n UA_TYPENAME(\"%s\") /* .typeName */\n" % idName + \
  108. " " + typeid + ", /* .typeId */\n" + \
  109. " sizeof(UA_" + idName + "), /* .memSize */\n" + \
  110. " " + self.typeIndex + ", /* .typeIndex */\n" + \
  111. " " + str(len(self.members)) + ", /* .membersSize */\n" + \
  112. " " + self.builtin + ", /* .builtin */\n" + \
  113. " " + self.pointerfree + ", /* .pointerFree */\n" + \
  114. " " + self.overlayable + ", /* .overlayable */\n" + \
  115. " " + binaryEncodingId + ", /* .binaryEncodingId */\n" + \
  116. " %s_members" % idName + " /* .members */\n}"
  117. def members_c(self):
  118. idName = makeCIdentifier(self.name)
  119. if len(self.members)==0:
  120. return "#define %s_members NULL" % (idName)
  121. members = "static UA_DataTypeMember %s_members[%s] = {" % (idName, len(self.members))
  122. before = None
  123. i = 0
  124. size = len(self.members)
  125. for index, member in enumerate(self.members):
  126. i += 1
  127. memberName = makeCIdentifier(member.name)
  128. memberNameCapital = memberName
  129. if len(memberName) > 0:
  130. memberNameCapital = memberName[0].upper() + memberName[1:]
  131. m = "\n{\n UA_TYPENAME(\"%s\") /* .memberName */\n" % memberNameCapital
  132. m += " %s_%s, /* .memberTypeIndex */\n" % (member.memberType.outname.upper(), makeCIdentifier(member.memberType.name.upper()))
  133. m += " "
  134. if not before:
  135. m += "0,"
  136. else:
  137. if member.isArray:
  138. m += "offsetof(UA_%s, %sSize)" % (idName, memberName)
  139. else:
  140. m += "offsetof(UA_%s, %s)" % (idName, memberName)
  141. m += " - offsetof(UA_%s, %s)" % (idName, makeCIdentifier(before.name))
  142. if before.isArray:
  143. m += " - sizeof(void*),"
  144. else:
  145. m += " - sizeof(UA_%s)," % makeCIdentifier(before.memberType.name)
  146. m += " /* .padding */\n"
  147. m += " %s, /* .namespaceZero */\n" % member.memberType.ns0
  148. m += (" true" if member.isArray else " false") + " /* .isArray */\n}"
  149. if i != size:
  150. m += ","
  151. members += m
  152. before = member
  153. return members + "};"
  154. def datatype_ptr(self):
  155. return "&" + self.outname.upper() + "[" + makeCIdentifier(self.outname.upper() + "_" + self.name.upper()) + "]"
  156. def functions_c(self):
  157. idName = makeCIdentifier(self.name)
  158. funcs = "static UA_INLINE void\nUA_%s_init(UA_%s *p) {\n memset(p, 0, sizeof(UA_%s));\n}\n\n" % (idName, idName, idName)
  159. funcs += "static UA_INLINE UA_%s *\nUA_%s_new(void) {\n return (UA_%s*)UA_new(%s);\n}\n\n" % (idName, idName, idName, self.datatype_ptr())
  160. if self.pointerfree == "true":
  161. funcs += "static UA_INLINE UA_StatusCode\nUA_%s_copy(const UA_%s *src, UA_%s *dst) {\n *dst = *src;\n return UA_STATUSCODE_GOOD;\n}\n\n" % (idName, idName, idName)
  162. funcs += "static UA_INLINE void\nUA_%s_deleteMembers(UA_%s *p) {\n memset(p, 0, sizeof(UA_%s));\n}\n\n" % (idName, idName, idName)
  163. else:
  164. funcs += "static UA_INLINE UA_StatusCode\nUA_%s_copy(const UA_%s *src, UA_%s *dst) {\n return UA_copy(src, dst, %s);\n}\n\n" % (idName, idName, idName, self.datatype_ptr())
  165. funcs += "static UA_INLINE void\nUA_%s_deleteMembers(UA_%s *p) {\n UA_deleteMembers(p, %s);\n}\n\n" % (idName, idName, self.datatype_ptr())
  166. funcs += "static UA_INLINE void\nUA_%s_delete(UA_%s *p) {\n UA_delete(p, %s);\n}" % (idName, idName, self.datatype_ptr())
  167. return funcs
  168. def encoding_h(self):
  169. idName = makeCIdentifier(self.name)
  170. enc = "static UA_INLINE size_t\nUA_%s_calcSizeBinary(const UA_%s *src) {\n return UA_calcSizeBinary(src, %s);\n}\n"
  171. enc += "static UA_INLINE UA_StatusCode\nUA_%s_encodeBinary(const UA_%s *src, UA_Byte **bufPos, const UA_Byte *bufEnd) {\n return UA_encodeBinary(src, %s, bufPos, &bufEnd, NULL, NULL);\n}\n"
  172. enc += "static UA_INLINE UA_StatusCode\nUA_%s_decodeBinary(const UA_ByteString *src, size_t *offset, UA_%s *dst) {\n return UA_decodeBinary(src, offset, dst, %s, NULL);\n}"
  173. return enc % tuple(list(itertools.chain(*itertools.repeat([idName, idName, self.datatype_ptr()], 3))))
  174. class BuiltinType(Type):
  175. def __init__(self, name):
  176. self.name = name
  177. self.ns0 = "true"
  178. self.typeIndex = makeCIdentifier("UA_TYPES_" + self.name.upper())
  179. self.outname = "ua_types"
  180. self.description = ""
  181. self.pointerfree = "false"
  182. if self.name in builtin_overlayable.keys():
  183. self.pointerfree = "true"
  184. self.overlayable = "false"
  185. if name in builtin_overlayable:
  186. self.overlayable = builtin_overlayable[name]
  187. self.builtin = "true"
  188. self.members = [StructMember("", self, False)] # builtin types contain only one member: themselves (drops into the jumptable during processing)
  189. class EnumerationType(Type):
  190. def __init__(self, outname, xml, namespace):
  191. Type.__init__(self, outname, xml, namespace)
  192. self.pointerfree = "true"
  193. self.overlayable = "UA_BINARY_OVERLAYABLE_INTEGER"
  194. self.members = [StructMember("", types["Int32"], False)] # encoded as uint32
  195. self.builtin = "true"
  196. self.typeIndex = "UA_TYPES_INT32"
  197. self.elements = OrderedDict()
  198. for child in xml:
  199. if child.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedValue":
  200. self.elements[child.get("Name")] = child.get("Value")
  201. def typedef_h(self):
  202. if sys.version_info[0] < 3:
  203. values = self.elements.iteritems()
  204. else:
  205. values = self.elements.items()
  206. return "typedef enum {\n " + ",\n ".join(map(lambda kv : makeCIdentifier("UA_" + self.name.upper() + "_" + kv[0].upper()) + \
  207. " = " + kv[1], values)) + \
  208. ",\n __UA_{0}_FORCE32BIT = 0x7fffffff\n".format(makeCIdentifier(self.name.upper())) + "} " + \
  209. "UA_{0};\nUA_STATIC_ASSERT(sizeof(UA_{0}) == sizeof(UA_Int32), enum_must_be_32bit);".format(makeCIdentifier(self.name))
  210. class OpaqueType(Type):
  211. def __init__(self, outname, xml, namespace, baseType):
  212. Type.__init__(self, outname, xml, namespace)
  213. self.baseType = baseType
  214. self.members = [StructMember("", types[baseType], False)] # encoded as string
  215. def typedef_h(self):
  216. return "typedef UA_" + self.baseType + " UA_%s;" % self.name
  217. class StructType(Type):
  218. def __init__(self, outname, xml, namespace):
  219. Type.__init__(self, outname, xml, namespace)
  220. self.members = []
  221. lengthfields = [] # lengthfields of arrays are not included as members
  222. for child in xml:
  223. if child.get("LengthField"):
  224. lengthfields.append(child.get("LengthField"))
  225. for child in xml:
  226. if not child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  227. continue
  228. if child.get("Name") in lengthfields:
  229. continue
  230. memberName = child.get("Name")
  231. memberName = memberName[:1].lower() + memberName[1:]
  232. memberTypeName = getTypeName(child.get("TypeName"))
  233. memberType = types[memberTypeName]
  234. isArray = True if child.get("LengthField") else False
  235. self.members.append(StructMember(memberName, memberType, isArray))
  236. self.pointerfree = "true"
  237. self.overlayable = "true"
  238. before = None
  239. for m in self.members:
  240. if m.isArray or m.memberType.pointerfree != "true":
  241. self.pointerfree = "false"
  242. self.overlayable = "false"
  243. else:
  244. self.overlayable += "\n\t\t && " + m.memberType.overlayable
  245. if before:
  246. self.overlayable += "\n\t\t && offsetof(UA_%s, %s) == (offsetof(UA_%s, %s) + sizeof(UA_%s))" % \
  247. (makeCIdentifier(self.name), makeCIdentifier(m.name), makeCIdentifier(self.name), makeCIdentifier(before.name), makeCIdentifier(before.memberType.name))
  248. if "false" in self.overlayable:
  249. self.overlayable = "false"
  250. before = m
  251. def typedef_h(self):
  252. if len(self.members) == 0:
  253. return "typedef void * UA_%s;" % makeCIdentifier(self.name)
  254. returnstr = "typedef struct {\n"
  255. for member in self.members:
  256. if member.isArray:
  257. returnstr += " size_t %sSize;\n" % makeCIdentifier(member.name)
  258. returnstr += " UA_%s *%s;\n" % (makeCIdentifier(member.memberType.name), makeCIdentifier(member.name))
  259. else:
  260. returnstr += " UA_%s %s;\n" % (makeCIdentifier(member.memberType.name), makeCIdentifier(member.name))
  261. return returnstr + "} UA_%s;" % makeCIdentifier(self.name)
  262. #########################
  263. # Parse Typedefinitions #
  264. #########################
  265. def parseTypeDefinitions(outname, xmlDescription, namespace):
  266. def typeReady(element):
  267. "Are all member types defined?"
  268. for child in element:
  269. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  270. childname = getTypeName(child.get("TypeName"))
  271. if childname not in types:
  272. return False
  273. return True
  274. def unknownTypes(element):
  275. "Return all unknown types"
  276. unknowns = []
  277. for child in element:
  278. if child.tag == "{http://opcfoundation.org/BinarySchema/}Field":
  279. childname = getTypeName(child.get("TypeName"))
  280. if childname not in types:
  281. unknowns.append(childname)
  282. return unknowns
  283. def skipType(name):
  284. if name in excluded_types:
  285. return True
  286. if "Test" in name: # skip all test types
  287. return True
  288. if re.search("NodeId$", name) != None:
  289. return True
  290. return False
  291. snippets = {}
  292. for typeXml in etree.parse(xmlDescription).getroot():
  293. if not typeXml.get("Name"):
  294. continue
  295. name = typeXml.get("Name")
  296. snippets[name] = typeXml
  297. detectLoop = len(snippets)+1
  298. while(len(snippets) > 0):
  299. if detectLoop == len(snippets):
  300. name, typeXml = (snippets.items())[0]
  301. raise RuntimeError("Infinite loop detected trying to processing types " + name + ": unknonwn subtype " + str(unknownTypes(typeXml)))
  302. detectLoop = len(snippets)
  303. for name, typeXml in list(snippets.items()):
  304. if name in types or skipType(name):
  305. del snippets[name]
  306. continue
  307. if not typeReady(typeXml):
  308. continue
  309. if name in builtin_types:
  310. types[name] = BuiltinType(name)
  311. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  312. types[name] = EnumerationType(outname, typeXml, namespace)
  313. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  314. types[name] = OpaqueType(outname, typeXml, namespace, get_base_type_for_opaque(name)['name'])
  315. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  316. types[name] = StructType(outname, typeXml, namespace)
  317. else:
  318. raise Exception("Type not known")
  319. del snippets[name]
  320. ##########################
  321. # Parse TypeDescriptions #
  322. ##########################
  323. class TypeDescription(object):
  324. def __init__(self, name, nodeid, namespaceid):
  325. self.name = name
  326. self.nodeid = nodeid
  327. self.namespaceid = namespaceid
  328. self.xmlEncodingId = "0"
  329. self.binaryEncodingId = "0"
  330. def parseTypeDescriptions(f, namespaceid):
  331. definitions = {}
  332. csvreader = csv.reader(f, delimiter=',')
  333. delay_init = []
  334. for index, row in enumerate(csvreader):
  335. if len(row) < 3:
  336. continue
  337. if row[2] == "Object":
  338. # Check if node name ends with _Encoding_(DefaultXml|DefaultBinary) and store the node id in the corresponding DataType
  339. m = re.match('(.*?)_Encoding_Default(Xml|Binary)$',row[0])
  340. if (m):
  341. baseType = m.group(1)
  342. if baseType not in types:
  343. continue
  344. delay_init.append({
  345. "baseType": baseType,
  346. "encoding": m.group(2),
  347. "id": row[1]
  348. })
  349. continue
  350. if row[2] != "DataType":
  351. continue
  352. if row[0] == "BaseDataType":
  353. definitions["Variant"] = TypeDescription(row[0], row[1], namespaceid)
  354. elif row[0] == "Structure":
  355. definitions["ExtensionObject"] = TypeDescription(row[0], row[1], namespaceid)
  356. elif row[0] not in types:
  357. continue
  358. else:
  359. definitions[row[0]] = TypeDescription(row[0], row[1], namespaceid)
  360. for i in delay_init:
  361. if i["baseType"] not in definitions:
  362. raise Exception("Type {} not found in definitions file.".format(i["baseType"]))
  363. if i["encoding"] == "Xml":
  364. definitions[i["baseType"]].xmlEncodingId = i["id"]
  365. else:
  366. definitions[i["baseType"]].binaryEncodingId = i["id"]
  367. return definitions
  368. def merge_dicts(*dict_args):
  369. """
  370. Given any number of dicts, shallow copy and merge into a new dict,
  371. precedence goes to key value pairs in latter dicts.
  372. """
  373. result = {}
  374. for dictionary in dict_args:
  375. result.update(dictionary)
  376. return result
  377. ###############################
  378. # Parse the Command Line Input#
  379. ###############################
  380. parser = argparse.ArgumentParser()
  381. parser.add_argument('-c', '--type-csv',
  382. metavar="<typeDescriptions>",
  383. type=argparse.FileType('r'),
  384. dest="type_csv",
  385. action='append',
  386. default=[],
  387. help='csv file with type descriptions')
  388. parser.add_argument('--namespace',
  389. type=int,
  390. dest="namespace",
  391. default=0,
  392. help='namespace id of the generated type nodeids (defaults to 0)')
  393. parser.add_argument('-s', '--selected-types',
  394. metavar="<selectedTypes>",
  395. type=argparse.FileType('r'),
  396. dest="selected_types",
  397. action='append',
  398. default=[],
  399. help='file with list of types (among those parsed) to be generated. If not given, all types are generated')
  400. parser.add_argument('--no-builtin',
  401. action='store_true',
  402. dest="no_builtin",
  403. help='Do not generate builtin types')
  404. parser.add_argument('-t', '--type-bsd',
  405. metavar="<typeBsds>",
  406. type=argparse.FileType('r'),
  407. dest="type_bsd",
  408. action='append',
  409. default=[],
  410. help='bsd file with type definitions')
  411. parser.add_argument('outfile',
  412. metavar='<outputFile>',
  413. help='output file w/o extension')
  414. args = parser.parse_args()
  415. outname = args.outfile.split("/")[-1]
  416. inname = ', '.join(list(map(lambda x:x.name.split("/")[-1], args.type_bsd)))
  417. ################
  418. # Create Types #
  419. ################
  420. for builtin in builtin_types:
  421. types[builtin] = BuiltinType(builtin)
  422. for f in args.type_bsd:
  423. parseTypeDefinitions(outname, f, args.namespace)
  424. typedescriptions = {}
  425. for f in args.type_csv:
  426. typedescriptions = merge_dicts(typedescriptions, parseTypeDescriptions(f, args.namespace))
  427. # Read the selected data types
  428. selected_types = []
  429. for f in args.selected_types:
  430. selected_types += list(filter(len, [line.strip() for line in f]))
  431. # Use all types if none are selected
  432. if len(selected_types) == 0:
  433. selected_types = types.keys()
  434. #############################
  435. # Write out the Definitions #
  436. #############################
  437. fh = open(args.outfile + "_generated.h",'w')
  438. ff = open(args.outfile + "_generated_handling.h",'w')
  439. fe = open(args.outfile + "_generated_encoding_binary.h",'w')
  440. fc = open(args.outfile + "_generated.c",'w')
  441. def printh(string):
  442. print(string, end='\n', file=fh)
  443. def printf(string):
  444. print(string, end='\n', file=ff)
  445. def printe(string):
  446. print(string, end='\n', file=fe)
  447. def printc(string):
  448. print(string, end='\n', file=fc)
  449. def iter_types(v):
  450. l = None
  451. if sys.version_info[0] < 3:
  452. l = list(v.itervalues())
  453. else:
  454. l = list(v.values())
  455. if len(selected_types) > 0:
  456. l = list(filter(lambda t: t.name in selected_types, l))
  457. if args.no_builtin:
  458. l = list(filter(lambda t: type(t) != BuiltinType, l))
  459. return l
  460. ################
  461. # Print Header #
  462. ################
  463. printh('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  464. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  465. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  466. #ifndef ''' + outname.upper() + '''_GENERATED_H_
  467. #define ''' + outname.upper() + '''_GENERATED_H_
  468. #ifdef UA_NO_AMALGAMATION
  469. #include "ua_types.h"
  470. ''' + ('#include "ua_types_generated.h"\n' if outname != "ua_types" else '') + '''
  471. #else
  472. #include "open62541.h"
  473. #endif
  474. _UA_BEGIN_DECLS
  475. ''')
  476. filtered_types = iter_types(types)
  477. printh('''/**
  478. * Every type is assigned an index in an array containing the type descriptions.
  479. * These descriptions are used during type handling (copying, deletion,
  480. * binary encoding, ...). */''')
  481. printh("#define " + outname.upper() + "_COUNT %s" % (str(len(filtered_types))))
  482. printh("extern UA_EXPORT const UA_DataType " + outname.upper() + "[" + outname.upper() + "_COUNT];")
  483. i = 0
  484. for t in filtered_types:
  485. printh("\n/**\n * " + t.name)
  486. printh(" * " + "^" * len(t.name))
  487. if t.description == "":
  488. printh(" */")
  489. else:
  490. printh(" * " + t.description + " */")
  491. if type(t) != BuiltinType:
  492. printh(t.typedef_h() + "\n")
  493. printh("#define " + makeCIdentifier(outname.upper() + "_" + t.name.upper()) + " " + str(i))
  494. i += 1
  495. printh('''
  496. _UA_END_DECLS
  497. #endif /* %s_GENERATED_H_ */''' % outname.upper())
  498. ##################
  499. # Print Handling #
  500. ##################
  501. printf('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  502. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  503. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  504. #ifndef ''' + outname.upper() + '''_GENERATED_HANDLING_H_
  505. #define ''' + outname.upper() + '''_GENERATED_HANDLING_H_
  506. #include "''' + outname + '''_generated.h"
  507. _UA_BEGIN_DECLS
  508. #if defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
  509. # pragma GCC diagnostic push
  510. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  511. # pragma GCC diagnostic ignored "-Wmissing-braces"
  512. #endif
  513. ''')
  514. for t in filtered_types:
  515. printf("\n/* " + t.name + " */")
  516. printf(t.functions_c())
  517. printf('''
  518. #if defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
  519. # pragma GCC diagnostic pop
  520. #endif
  521. _UA_END_DECLS
  522. #endif /* %s_GENERATED_HANDLING_H_ */''' % outname.upper())
  523. ###########################
  524. # Print Description Array #
  525. ###########################
  526. printc('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  527. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  528. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  529. #include "''' + outname + '''_generated.h"''')
  530. for t in filtered_types:
  531. printc("")
  532. printc("/* " + t.name + " */")
  533. printc(t.members_c())
  534. printc("const UA_DataType %s[%s_COUNT] = {" % (outname.upper(), outname.upper()))
  535. for t in filtered_types:
  536. # printc("")
  537. printc("/* " + t.name + " */")
  538. printc(t.datatype_c() + ",")
  539. printc("};\n")
  540. ##################
  541. # Print Encoding #
  542. ##################
  543. printe('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  544. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  545. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  546. #include "ua_types_encoding_binary.h"
  547. #include "''' + outname + '''_generated.h"''')
  548. for t in filtered_types:
  549. printe("\n/* " + t.name + " */")
  550. printe(t.encoding_h())
  551. fh.close()
  552. ff.close()
  553. fc.close()
  554. fe.close()