generate_datatypes.py 25 KB

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