generate_datatypes.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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 re.search("NodeId$", name) != None:
  298. return True
  299. return False
  300. snippets = {}
  301. for typeXml in etree.parse(xmlDescription).getroot():
  302. if not typeXml.get("Name"):
  303. continue
  304. name = typeXml.get("Name")
  305. snippets[name] = typeXml
  306. detectLoop = len(snippets)+1
  307. while(len(snippets) > 0):
  308. if detectLoop == len(snippets):
  309. name, typeXml = (snippets.items())[0]
  310. raise RuntimeError("Infinite loop detected trying to processing types " + name + ": unknonwn subtype " + str(unknownTypes(typeXml)))
  311. detectLoop = len(snippets)
  312. for name, typeXml in list(snippets.items()):
  313. if name in types or skipType(name):
  314. del snippets[name]
  315. continue
  316. if not typeReady(typeXml):
  317. continue
  318. if name in builtin_types:
  319. types[name] = BuiltinType(name)
  320. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}EnumeratedType":
  321. types[name] = EnumerationType(outname, typeXml, namespace)
  322. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}OpaqueType":
  323. types[name] = OpaqueType(outname, typeXml, namespace, get_base_type_for_opaque(name)['name'])
  324. elif typeXml.tag == "{http://opcfoundation.org/BinarySchema/}StructuredType":
  325. types[name] = StructType(outname, typeXml, namespace)
  326. else:
  327. raise Exception("Type not known")
  328. del snippets[name]
  329. ##########################
  330. # Parse TypeDescriptions #
  331. ##########################
  332. class TypeDescription(object):
  333. def __init__(self, name, nodeid, namespaceid):
  334. self.name = name
  335. self.nodeid = nodeid
  336. self.namespaceid = namespaceid
  337. self.xmlEncodingId = "0"
  338. self.binaryEncodingId = "0"
  339. def parseTypeDescriptions(f, namespaceid):
  340. definitions = {}
  341. csvreader = csv.reader(f, delimiter=',')
  342. delay_init = []
  343. for index, row in enumerate(csvreader):
  344. if len(row) < 3:
  345. continue
  346. if row[2] == "Object":
  347. # Check if node name ends with _Encoding_(DefaultXml|DefaultBinary) and store the node id in the corresponding DataType
  348. m = re.match('(.*?)_Encoding_Default(Xml|Binary)$',row[0])
  349. if (m):
  350. baseType = m.group(1)
  351. if baseType not in types:
  352. continue
  353. delay_init.append({
  354. "baseType": baseType,
  355. "encoding": m.group(2),
  356. "id": row[1]
  357. })
  358. continue
  359. if row[2] != "DataType":
  360. continue
  361. if row[0] == "BaseDataType":
  362. definitions["Variant"] = TypeDescription(row[0], row[1], namespaceid)
  363. elif row[0] == "Structure":
  364. definitions["ExtensionObject"] = TypeDescription(row[0], row[1], namespaceid)
  365. elif row[0] not in types:
  366. continue
  367. else:
  368. definitions[row[0]] = TypeDescription(row[0], row[1], namespaceid)
  369. for i in delay_init:
  370. if i["baseType"] not in definitions:
  371. raise Exception("Type {} not found in definitions file.".format(i["baseType"]))
  372. if i["encoding"] == "Xml":
  373. definitions[i["baseType"]].xmlEncodingId = i["id"]
  374. else:
  375. definitions[i["baseType"]].binaryEncodingId = i["id"]
  376. return definitions
  377. def merge_dicts(*dict_args):
  378. """
  379. Given any number of dicts, shallow copy and merge into a new dict,
  380. precedence goes to key value pairs in latter dicts.
  381. """
  382. result = {}
  383. for dictionary in dict_args:
  384. result.update(dictionary)
  385. return result
  386. ###############################
  387. # Parse the Command Line Input#
  388. ###############################
  389. parser = argparse.ArgumentParser()
  390. parser.add_argument('-c', '--type-csv',
  391. metavar="<typeDescriptions>",
  392. type=argparse.FileType('r'),
  393. dest="type_csv",
  394. action='append',
  395. default=[],
  396. help='csv file with type descriptions')
  397. parser.add_argument('--namespace',
  398. type=int,
  399. dest="namespace",
  400. default=0,
  401. help='namespace id of the generated type nodeids (defaults to 0)')
  402. parser.add_argument('-s', '--selected-types',
  403. metavar="<selectedTypes>",
  404. type=argparse.FileType('r'),
  405. dest="selected_types",
  406. action='append',
  407. default=[],
  408. help='file with list of types (among those parsed) to be generated. If not given, all types are generated')
  409. parser.add_argument('--no-builtin',
  410. action='store_true',
  411. dest="no_builtin",
  412. help='Do not generate builtin types')
  413. parser.add_argument('-t', '--type-bsd',
  414. metavar="<typeBsds>",
  415. type=argparse.FileType('r'),
  416. dest="type_bsd",
  417. action='append',
  418. default=[],
  419. help='bsd file with type definitions')
  420. parser.add_argument('outfile',
  421. metavar='<outputFile>',
  422. help='output file w/o extension')
  423. args = parser.parse_args()
  424. outname = args.outfile.split("/")[-1]
  425. inname = ', '.join(list(map(lambda x:x.name.split("/")[-1], args.type_bsd)))
  426. ################
  427. # Create Types #
  428. ################
  429. for builtin in builtin_types:
  430. types[builtin] = BuiltinType(builtin)
  431. for f in args.type_bsd:
  432. parseTypeDefinitions(outname, f, args.namespace)
  433. typedescriptions = {}
  434. for f in args.type_csv:
  435. typedescriptions = merge_dicts(typedescriptions, parseTypeDescriptions(f, args.namespace))
  436. # Read the selected data types
  437. selected_types = []
  438. for f in args.selected_types:
  439. selected_types += list(filter(len, [line.strip() for line in f]))
  440. # Use all types if none are selected
  441. if len(selected_types) == 0:
  442. selected_types = types.keys()
  443. #############################
  444. # Write out the Definitions #
  445. #############################
  446. fh = open(args.outfile + "_generated.h",'w')
  447. ff = open(args.outfile + "_generated_handling.h",'w')
  448. fe = open(args.outfile + "_generated_encoding_binary.h",'w')
  449. fc = open(args.outfile + "_generated.c",'w')
  450. def printh(string):
  451. print(string, end='\n', file=fh)
  452. def printf(string):
  453. print(string, end='\n', file=ff)
  454. def printe(string):
  455. print(string, end='\n', file=fe)
  456. def printc(string):
  457. print(string, end='\n', file=fc)
  458. def iter_types(v):
  459. l = None
  460. if sys.version_info[0] < 3:
  461. l = list(v.itervalues())
  462. else:
  463. l = list(v.values())
  464. if len(selected_types) > 0:
  465. l = list(filter(lambda t: t.name in selected_types, l))
  466. if args.no_builtin:
  467. l = list(filter(lambda t: type(t) != BuiltinType, l))
  468. return l
  469. ################
  470. # Print Header #
  471. ################
  472. printh('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  473. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  474. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  475. #ifndef ''' + outname.upper() + '''_GENERATED_H_
  476. #define ''' + outname.upper() + '''_GENERATED_H_
  477. #ifdef UA_ENABLE_AMALGAMATION
  478. #include "open62541.h"
  479. #else
  480. #include "ua_types.h"
  481. ''' + ('#include "ua_types_generated.h"\n' if outname != "ua_types" else '') + '''
  482. #endif
  483. _UA_BEGIN_DECLS
  484. ''')
  485. filtered_types = iter_types(types)
  486. printh('''/**
  487. * Every type is assigned an index in an array containing the type descriptions.
  488. * These descriptions are used during type handling (copying, deletion,
  489. * binary encoding, ...). */''')
  490. printh("#define " + outname.upper() + "_COUNT %s" % (str(len(filtered_types))))
  491. printh("extern UA_EXPORT const UA_DataType " + outname.upper() + "[" + outname.upper() + "_COUNT];")
  492. i = 0
  493. for t in filtered_types:
  494. printh("\n/**\n * " + t.name)
  495. printh(" * " + "^" * len(t.name))
  496. if t.description == "":
  497. printh(" */")
  498. else:
  499. printh(" * " + t.description + " */")
  500. if type(t) != BuiltinType:
  501. printh(t.typedef_h() + "\n")
  502. printh("#define " + makeCIdentifier(outname.upper() + "_" + t.name.upper()) + " " + str(i))
  503. i += 1
  504. printh('''
  505. _UA_END_DECLS
  506. #endif /* %s_GENERATED_H_ */''' % outname.upper())
  507. ##################
  508. # Print Handling #
  509. ##################
  510. printf('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  511. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  512. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  513. #ifndef ''' + outname.upper() + '''_GENERATED_HANDLING_H_
  514. #define ''' + outname.upper() + '''_GENERATED_HANDLING_H_
  515. #include "''' + outname + '''_generated.h"
  516. _UA_BEGIN_DECLS
  517. #if defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
  518. # pragma GCC diagnostic push
  519. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  520. # pragma GCC diagnostic ignored "-Wmissing-braces"
  521. #endif
  522. ''')
  523. for t in filtered_types:
  524. printf("\n/* " + t.name + " */")
  525. printf(t.functions_c())
  526. printf('''
  527. #if defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 6
  528. # pragma GCC diagnostic pop
  529. #endif
  530. _UA_END_DECLS
  531. #endif /* %s_GENERATED_HANDLING_H_ */''' % outname.upper())
  532. ###########################
  533. # Print Description Array #
  534. ###########################
  535. printc('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  536. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  537. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  538. #include "''' + outname + '''_generated.h"''')
  539. for t in filtered_types:
  540. printc("")
  541. printc("/* " + t.name + " */")
  542. printc(t.members_c())
  543. printc("const UA_DataType %s[%s_COUNT] = {" % (outname.upper(), outname.upper()))
  544. for t in filtered_types:
  545. # printc("")
  546. printc("/* " + t.name + " */")
  547. printc(t.datatype_c() + ",")
  548. printc("};\n")
  549. ##################
  550. # Print Encoding #
  551. ##################
  552. printe('''/* Generated from ''' + inname + ''' with script ''' + sys.argv[0] + '''
  553. * on host ''' + platform.uname()[1] + ''' by user ''' + getpass.getuser() + \
  554. ''' at ''' + time.strftime("%Y-%m-%d %I:%M:%S") + ''' */
  555. #ifdef UA_ENABLE_AMALGAMATION
  556. # include "open62541.h"
  557. #else
  558. # include "ua_types_encoding_binary.h"
  559. # include "''' + outname + '''_generated.h"
  560. #endif
  561. ''')
  562. for t in filtered_types:
  563. printe("\n/* " + t.name + " */")
  564. printe(t.encoding_h())
  565. fh.close()
  566. ff.close()
  567. fc.close()
  568. fe.close()