generate_datatypes.py 26 KB

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