generate_datatypes.py 24 KB

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