generate_datatypes.py 27 KB

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