generate_datatypes.py 26 KB

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