generate_datatypes.py 26 KB

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