generate_datatypes.py 26 KB

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