CppGenerator.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #!/usr/bin/env python3
  2. # -*- Coding: UTF-8 -*-
  3. # ---------------------------------------------------------------------------
  4. # Open Asset Import Library (ASSIMP)
  5. # ---------------------------------------------------------------------------
  6. #
  7. # Copyright (c) 2006-2010, ASSIMP Development Team
  8. #
  9. # All rights reserved.
  10. #
  11. # Redistribution and use of this software in source and binary forms,
  12. # with or without modification, are permitted provided that the following
  13. # conditions are met:
  14. #
  15. # * Redistributions of source code must retain the above
  16. # copyright notice, this list of conditions and the
  17. # following disclaimer.
  18. #
  19. # * Redistributions in binary form must reproduce the above
  20. # copyright notice, this list of conditions and the
  21. # following disclaimer in the documentation and/or other
  22. # materials provided with the distribution.
  23. #
  24. # * Neither the name of the ASSIMP team, nor the names of its
  25. # contributors may be used to endorse or promote products
  26. # derived from this software without specific prior
  27. # written permission of the ASSIMP Development Team.
  28. #
  29. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  30. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  31. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  32. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  33. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  34. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  35. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  36. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  37. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  38. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  39. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40. # ---------------------------------------------------------------------------
  41. """Generate the C++ glue code needed to map EXPRESS to C++"""
  42. import sys, os, re
  43. input_template_h = 'IFCReaderGen.h.template'
  44. input_template_cpp = 'IFCReaderGen.cpp.template'
  45. output_file_h = os.path.join('..','..','code','IFCReaderGen.h')
  46. output_file_cpp = os.path.join('..','..','code','IFCReaderGen.cpp')
  47. template_entity_predef = '\tstruct {entity};\n'
  48. template_entity_predef_ni = '\ttypedef NotImplemented {entity}; // (not currently used by Assimp)\n'
  49. template_entity = r"""
  50. // C++ wrapper for {entity}
  51. struct {entity} : {parent} ObjectHelper<{entity},{argcnt}> {{ {entity}() : Object("{entity}") {{}}
  52. {fields}
  53. }};"""
  54. template_entity_ni = ''
  55. template_type = r"""
  56. // C++ wrapper type for {type}
  57. typedef {real_type} {type};"""
  58. template_stub_decl = '\tDECL_CONV_STUB({type});\n'
  59. template_schema = '\t\tSchemaEntry("{normalized_name}",&STEP::ObjectHelper<{type},{argcnt}>::Construct )\n'
  60. template_schema_type = '\t\tSchemaEntry("{normalized_name}",NULL )\n'
  61. template_converter = r"""
  62. // -----------------------------------------------------------------------------------------------------------
  63. template <> size_t GenericFill<{type}>(const DB& db, const LIST& params, {type}* in)
  64. {{
  65. {contents}
  66. }}"""
  67. template_converter_prologue_a = '\tsize_t base = GenericFill(db,params,static_cast<{parent}*>(in));\n'
  68. template_converter_prologue_b = '\tsize_t base = 0;\n'
  69. template_converter_check_argcnt = '\tif (params.GetSize() < {max_arg}) {{ throw STEP::TypeError("expected {max_arg} arguments to {name}"); }}'
  70. template_converter_code_per_field = r""" do {{ // convert the '{fieldname}' argument
  71. boost::shared_ptr<const DataType> arg = params[base++];{handle_unset}{convert}
  72. }} while(0);
  73. """
  74. template_allow_optional = r"""
  75. if (dynamic_cast<const UNSET*>(&*arg)) break;"""
  76. template_allow_derived = r"""
  77. if (dynamic_cast<const ISDERIVED*>(&*arg)) {{ in->ObjectHelper<Assimp::IFC::{type},{argcnt}>::aux_is_derived[{argnum}]=true; break; }}"""
  78. template_convert_single = r"""
  79. try {{ GenericConvert( in->{name}, arg, db ); break; }}
  80. catch (const TypeError& t) {{ throw TypeError(t.what() + std::string(" - expected argument {argnum} to {classname} to be a `{full_type}`")); }}"""
  81. template_converter_ommitted = '// this data structure is not used yet, so there is no code generated to fill its members\n'
  82. template_converter_epilogue = '\treturn base;'
  83. import ExpressReader
  84. def get_list_bounds(collection_spec):
  85. start,end = [(int(n) if n!='?' else 0) for n in re.findall(r'(\d+|\?)',collection_spec)]
  86. return start,end
  87. def get_cpp_type(field,schema):
  88. isobjref = field.type in schema.entities
  89. base = field.type
  90. if isobjref:
  91. base = 'Lazy< '+(base if base in schema.whitelist else 'NotImplemented')+' >'
  92. if field.collection:
  93. start,end = get_list_bounds(field.collection)
  94. base = 'ListOf< {0}, {1}, {2} >'.format(base,start,end)
  95. if not isobjref:
  96. base += '::Out'
  97. if field.optional:
  98. base = 'Maybe< '+base+' >'
  99. return base
  100. def generate_fields(entity,schema):
  101. fields = []
  102. for e in entity.members:
  103. fields.append('\t\t{type} {name};'.format(type=get_cpp_type(e,schema),name=e.name))
  104. return '\n'.join(fields)
  105. def handle_unset_args(field,entity,schema,argnum):
  106. n = ''
  107. # if someone derives from this class, check for derived fields.
  108. if any(entity.name==e.parent for e in schema.entities.values()):
  109. n += template_allow_derived.format(type=entity.name,argcnt=len(entity.members),argnum=argnum)
  110. if not field.optional:
  111. return n+''
  112. return n+template_allow_optional.format()
  113. def get_single_conversion(field,schema,argnum=0,classname='?'):
  114. typen = field.type
  115. name = field.name
  116. if field.collection:
  117. typen = 'LIST'
  118. return template_convert_single.format(type=typen,name=name,argnum=argnum,classname=classname,full_type=field.fullspec)
  119. def count_args_up(entity,schema):
  120. return len(entity.members) + (count_args_up(schema.entities[entity.parent],schema) if entity.parent else 0)
  121. def resolve_base_type(base,schema):
  122. if base in ('INTEGER','REAL','STRING','ENUMERATION','BOOLEAN','NUMBER', 'SELECT','LOGICAL'):
  123. return base
  124. if base in schema.types:
  125. return resolve_base_type(schema.types[base].equals,schema)
  126. print(base)
  127. return None
  128. def gen_type_struct(typen,schema):
  129. base = resolve_base_type(typen.equals,schema)
  130. if not base:
  131. return ''
  132. if typen.aggregate:
  133. start,end = get_list_bounds(typen.aggregate)
  134. base = 'ListOf< {0}, {1}, {2} >'.format(base,start,end)
  135. return template_type.format(type=typen.name,real_type=base)
  136. def gen_converter(entity,schema):
  137. max_arg = count_args_up(entity,schema)
  138. arg_idx = arg_idx_ofs = max_arg - len(entity.members)
  139. code = template_converter_prologue_a.format(parent=entity.parent) if entity.parent else template_converter_prologue_b
  140. if entity.name in schema.blacklist_partial:
  141. return code+template_converter_ommitted+template_converter_epilogue;
  142. if max_arg > 0:
  143. code +=template_converter_check_argcnt.format(max_arg=max_arg,name=entity.name)
  144. for field in entity.members:
  145. code += template_converter_code_per_field.format(fieldname=field.name,
  146. handle_unset=handle_unset_args(field,entity,schema,arg_idx-arg_idx_ofs),
  147. convert=get_single_conversion(field,schema,arg_idx,entity.name))
  148. arg_idx += 1
  149. return code+template_converter_epilogue
  150. def get_base_classes(e,schema):
  151. def addit(e,out):
  152. if e.parent:
  153. out.append(e.parent)
  154. addit(schema.entities[e.parent],out)
  155. res = []
  156. addit(e,res)
  157. return list(reversed(res))
  158. def get_derived(e,schema):
  159. def get_deriv(e,out): # bit slow, but doesn't matter here
  160. s = [ee for ee in schema.entities.values() if ee.parent == e.name]
  161. for sel in s:
  162. out.append(sel.name)
  163. get_deriv(sel,out)
  164. res = []
  165. get_deriv(e,res)
  166. return res
  167. def get_hierarchy(e,schema):
  168. return get_derived(e.schema)+[e.name]+get_base_classes(e,schema)
  169. def sort_entity_list(schema):
  170. deps = []
  171. entities = schema.entities
  172. for e in entities.values():
  173. deps += get_base_classes(e,schema)+[e.name]
  174. checked = []
  175. for e in deps:
  176. if e not in checked:
  177. checked.append(e)
  178. return [entities[e] for e in checked]
  179. def work(filename):
  180. schema = ExpressReader.read(filename,silent=True)
  181. entities, stub_decls, schema_table, converters, typedefs, predefs = '','',[],'','',''
  182. whitelist = []
  183. with open('entitylist.txt', 'rt') as inp:
  184. whitelist = [n.strip() for n in inp.read().split('\n') if n[:1]!='#' and n.strip()]
  185. schema.whitelist = set()
  186. schema.blacklist_partial = set()
  187. for ename in whitelist:
  188. try:
  189. e = schema.entities[ename]
  190. except KeyError:
  191. # type, not entity
  192. continue
  193. for base in [e.name]+get_base_classes(e,schema):
  194. schema.whitelist.add(base)
  195. for base in get_derived(e,schema):
  196. schema.blacklist_partial.add(base)
  197. schema.blacklist_partial -= schema.whitelist
  198. schema.whitelist |= schema.blacklist_partial
  199. # uncomment this to disable automatic code reduction based on whitelisting all used entities
  200. # (blacklisted entities are those who are in the whitelist and may be instanced, but will
  201. # only be accessed through a pointer to a base-class.
  202. #schema.whitelist = set(schema.entities.keys())
  203. #schema.blacklist_partial = set()
  204. for ntype in schema.types.values():
  205. typedefs += gen_type_struct(ntype,schema)
  206. schema_table.append(template_schema_type.format(normalized_name=ntype.name.lower()))
  207. sorted_entities = sort_entity_list(schema)
  208. for entity in sorted_entities:
  209. parent = entity.parent+',' if entity.parent else ''
  210. if entity.name in schema.whitelist:
  211. converters += template_converter.format(type=entity.name,contents=gen_converter(entity,schema))
  212. schema_table.append(template_schema.format(type=entity.name,normalized_name=entity.name.lower(),argcnt=len(entity.members)))
  213. entities += template_entity.format(entity=entity.name,argcnt=len(entity.members),parent=parent,fields=generate_fields(entity,schema))
  214. predefs += template_entity_predef.format(entity=entity.name)
  215. stub_decls += template_stub_decl.format(type=entity.name)
  216. else:
  217. entities += template_entity_ni.format(entity=entity.name)
  218. predefs += template_entity_predef_ni.format(entity=entity.name)
  219. schema_table.append(template_schema.format(type="NotImplemented",normalized_name=entity.name.lower(),argcnt=0))
  220. schema_table = ','.join(schema_table)
  221. with open(input_template_h,'rt') as inp:
  222. with open(output_file_h,'wt') as outp:
  223. # can't use format() here since the C++ code templates contain single, unescaped curly brackets
  224. outp.write(inp.read().replace('{predefs}',predefs).replace('{types}',typedefs).replace('{entities}',entities).replace('{converter-decl}',stub_decls))
  225. with open(input_template_cpp,'rt') as inp:
  226. with open(output_file_cpp,'wt') as outp:
  227. outp.write(inp.read().replace('{schema-static-table}',schema_table).replace('{converter-impl}',converters))
  228. if __name__ == "__main__":
  229. sys.exit(work(sys.argv[1] if len(sys.argv)>1 else 'schema.exp'))