Files
IfcOpenShell/src/ifcopenshell-python/ifcopenshell/express/schema_class.py
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

545 lines
20 KiB
Python
Raw Normal View History

# IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2021 Thomas Krijnen <thomas@aecgeeks.com>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IfcOpenShell is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
import operator
import nodes
import codegen
import templates
from collections import defaultdict
try:
import ifcopenshell.ifcopenshell_wrapper as w
except:
pass
2020-11-01 20:08:27 +07:00
class LateBoundSchemaInstantiator:
def __init__(self, schema_name):
self.schema_name = schema_name
2020-11-01 20:08:27 +07:00
self.schema_name_title = schema_name.capitalize()
self.declarations = {}
self.names = []
# We need to make sure anonymous types are not gc'ed.
self.cache = []
2020-11-01 20:08:27 +07:00
def aggregation_type(self, aggr_type, bound1, bound2, decl_type):
2020-11-01 20:08:27 +07:00
self.cache.append(
w.aggregation_type(getattr(w.aggregation_type, aggr_type + "_type"), bound1, bound2, decl_type)
)
return self.cache[-1]
2020-11-01 20:08:27 +07:00
def simple_type(self, type):
self.cache.append(w.simple_type(getattr(w.simple_type, type + "_type")))
return self.cache[-1]
2020-11-01 20:08:27 +07:00
def named_type(self, type):
self.cache.append(w.named_type(self.declarations[str(type)]))
return self.cache[-1]
2020-11-01 20:08:27 +07:00
def declare(self, definition_type, name):
self.names.append(str(name))
2020-11-01 20:08:27 +07:00
def begin_schema(self):
self.names.sort(key=str.lower)
2020-11-01 20:08:27 +07:00
def typedef(self, name, declared_type):
index_in_schema = self.names.index(str(name))
self.declarations[str(name)] = w.type_declaration(name, index_in_schema, declared_type)
2020-11-01 20:08:27 +07:00
def enumeration(self, name, enum):
schema_name = self.schema_name
index_in_schema = self.names.index(str(name))
self.declarations[str(name)] = w.enumeration_type(name, index_in_schema, sorted(enum.values))
2020-11-01 20:08:27 +07:00
def entity(self, name, type):
index_in_schema = self.names.index(str(name))
supertype = None if len(type.supertypes) == 0 else self.declarations[str(type.supertypes[0])]
self.declarations[str(name)] = w.entity(name, type.abstract, index_in_schema, supertype)
2020-11-01 20:08:27 +07:00
def select(self, name, type):
index_in_schema = self.names.index(str(name))
children = [self.declarations[str(v)] for v in type.values]
self.declarations[str(name)] = w.select_type(name, index_in_schema, children)
2020-11-01 20:08:27 +07:00
def entity_attributes(self, name, attribute_definitions, is_derived):
attributes = []
for attr_name, decl_type, optional in attribute_definitions:
attributes.append(w.attribute(attr_name, decl_type, optional))
self.declarations[str(name)].set_attributes(attributes, is_derived)
self.cache.append(attributes)
2020-11-01 20:08:27 +07:00
def inverse_attributes(self, name, inv_attrs):
attributes = []
for attr_name, aggr_type, bound1, bound2, entity_ref, attribute_entity, attribute_entity_index in inv_attrs:
en = self.declarations[str(entity_ref)]
2020-11-01 20:08:27 +07:00
attributes.append(
w.inverse_attribute(
attr_name,
getattr(w.inverse_attribute, aggr_type + "_type"),
bound1,
bound2,
en,
en.attributes()[attribute_entity_index],
)
)
self.declarations[str(name)].set_inverse_attributes(attributes)
2020-11-01 20:08:27 +07:00
def entity_subtypes(self, name, tys):
self.declarations[str(name)].set_subtypes([self.declarations[str(v)] for v in tys])
2020-11-01 20:08:27 +07:00
def finalize(self, can_be_instantiated_set, override_schema_name=None):
self.schema = w.schema_definition(
override_schema_name or self.schema_name, list(self.declarations.values()), None
)
class EarlyBoundCodeWriter:
def __init__(self, schema_name):
self.strings = []
self.schema_name = schema_name
self.schema_name_title = schema_name.capitalize()
2020-11-01 20:08:27 +07:00
self.statements = [
"",
'#include "../ifcparse/IfcSchema.h"',
'#include "../ifcparse/%(schema_name_title)s.h"' % self.__dict__,
"",
"using namespace IfcParse;",
"",
]
self.names = []
def make_string(self, s):
try:
i = self.strings.index(s)
except ValueError:
self.strings.append(s)
i = len(self.strings) - 1
return "strings[%d]" % i
2020-11-01 20:08:27 +07:00
def aggregation_type(self, aggr_type, bound1, bound2, decl_type):
2020-11-01 20:08:27 +07:00
return (
"new aggregation_type(aggregation_type::%(aggr_type)s_type, %(bound1)d, %(bound2)d, %(decl_type)s)"
% locals()
)
def simple_type(self, type):
return "new simple_type(simple_type::%s_type)" % type
2020-11-01 20:08:27 +07:00
def named_type(self, type):
return "new named_type(%s_%s_type)" % (self.schema_name, type)
2020-11-01 20:08:27 +07:00
def declare(self, definition_type, name):
schema_name = self.schema_name
2020-11-01 20:08:27 +07:00
self.statements.append("%(definition_type)s* %(schema_name)s_%(name)s_type = 0;" % locals())
self.names.append(name)
2020-11-01 20:08:27 +07:00
def begin_schema(self):
self.names.sort(key=str.lower)
2020-11-01 20:08:27 +07:00
self.statements.append("{factory_placeholder}")
self.statements.append("using namespace std::string_literals;")
self.statements.append("{strings_placeholder}")
2020-11-01 20:08:27 +07:00
self.statements.append(
"""
#if defined(__clang__)
__attribute__((optnone))
#elif defined(__GNUC__) || defined(__GNUG__)
#pragma GCC push_options
#pragma GCC optimize ("O0")
#elif defined(_MSC_VER)
#pragma optimize("", off)
#endif
2020-11-01 20:08:27 +07:00
"""
)
self.statements.append("IfcParse::schema_definition* %s_populate_schema() {" % self.schema_name)
def typedef(self, name, declared_type):
name_string = self.make_string(name)
schema_name = self.schema_name
index_in_schema = self.names.index(name)
2020-11-01 20:08:27 +07:00
self.statements.append(
' %(schema_name)s_%(name)s_type = new type_declaration(%(name_string)s, %(index_in_schema)d, %(declared_type)s);'
2020-11-01 20:08:27 +07:00
% locals()
)
def enumeration(self, name, enum):
schema_name = self.schema_name
index_in_schema = self.names.index(name)
name_string = self.make_string(name)
# @tfk we don't sort for correspondence with header file
# values = sorted(enum.values)
values = enum.values
2020-11-01 20:08:27 +07:00
self.statements.append(
' %(schema_name)s_%(name)s_type = new enumeration_type(%(name_string)s, %(index_in_schema)d, {'
2020-11-01 20:08:27 +07:00
% locals()
)
self.statements.extend(map(lambda v: ' %s%s' % (self.make_string(v), '' if v == values[-1] else ','), values))
self.statements.append(' });')
2020-11-01 20:08:27 +07:00
def entity(self, name, type):
schema_name = self.schema_name
index_in_schema = self.names.index(name)
name_string = self.make_string(name)
2020-11-01 20:08:27 +07:00
supertype = "0" if len(type.supertypes) == 0 else "%s_%s_type" % (self.schema_name, type.supertypes[0])
is_abstract = "true" if type.abstract else "false"
2020-11-01 20:08:27 +07:00
self.statements.append(
' %(schema_name)s_%(name)s_type = new entity(%(name_string)s, %(is_abstract)s, %(index_in_schema)d, %(supertype)s);'
2020-11-01 20:08:27 +07:00
% locals()
)
def select(self, name, type):
schema_name = self.schema_name
index_in_schema = self.names.index(name)
name_string = self.make_string(name)
values = sorted(map(str, type.values))
2020-11-01 20:08:27 +07:00
self.statements.append(
' %(schema_name)s_%(name)s_type = new select_type(%(name_string)s, %(index_in_schema)d, {'
2020-11-01 20:08:27 +07:00
% locals()
)
self.statements.extend(
map(lambda v: " %s_%s_type%s" % (self.schema_name, v, '' if v == values[-1] else ','), values)
)
self.statements.append(" });")
2020-11-01 20:08:27 +07:00
def entity_attributes(self, name, attribute_definitions, is_derived):
schema_name = self.schema_name
self.statements.append(" %(schema_name)s_%(name)s_type->set_attributes({" % locals())
for attr_name, decl_type, optional in attribute_definitions:
name_string = self.make_string(attr_name)
optional_cpp = str(optional).lower()
tail = '' if attr_name == attribute_definitions[-1][0] else ','
2020-11-01 20:08:27 +07:00
self.statements.append(
' new attribute(%(name_string)s, %(decl_type)s, %(optional_cpp)s)%(tail)s'
2020-11-01 20:08:27 +07:00
% locals()
)
self.statements.append(" },{")
2020-11-01 20:08:27 +07:00
self.statements.append(
" " + " ".join(map(lambda i, b: "%s%s" % (str(b).lower(), '' if i == len(is_derived) - 1 else ','), range(len(is_derived)), is_derived))
2020-11-01 20:08:27 +07:00
)
self.statements.append(" });")
def inverse_attributes(self, name, inv_attrs):
schema_name = self.schema_name
self.statements.append(" %(schema_name)s_%(name)s_type->set_inverse_attributes({" % locals())
for attr_name, aggr_type, bound1, bound2, entity_ref, attribute_entity, attribute_entity_index in inv_attrs:
name_string = self.make_string(attr_name)
tail = '' if attr_name == inv_attrs[-1][0] else ','
2020-11-01 20:08:27 +07:00
self.statements.append(
' new inverse_attribute(%(name_string)s, inverse_attribute::%(aggr_type)s_type, %(bound1)d, %(bound2)d, %(schema_name)s_%(entity_ref)s_type, %(schema_name)s_%(attribute_entity)s_type->attributes()[%(attribute_entity_index)d])%(tail)s'
2020-11-01 20:08:27 +07:00
% locals()
)
self.statements.append(" });")
2020-11-01 20:08:27 +07:00
def entity_subtypes(self, name, tys):
schema_name = self.schema_name
self.statements.append(" %(schema_name)s_%(name)s_type->set_subtypes({" % locals())
2020-11-01 20:08:27 +07:00
self.statements.append(
(" " + "".join(map(lambda t: ("%%(schema_name)s_%s_type%s" % (t, '' if t == tys[-1] else ',')), tys))) % locals()
)
self.statements.append(" });")
2020-11-01 20:08:27 +07:00
def finalize(self, can_be_instantiated_set):
schema_name = self.schema_name
schema_name_string = self.make_string(self.schema_name)
schema_name_title = self.schema_name.capitalize()
2020-11-01 20:08:27 +07:00
num_declarations = len(self.names)
2020-11-01 20:08:27 +07:00
self.statements.append("")
self.statements.append(
" std::vector<const declaration*> declarations= {"
2020-11-01 20:08:27 +07:00
)
for type_name in self.names:
tail = '' if type_name == self.names[-1] else ','
self.statements.append(" %(schema_name)s_%(type_name)s_type%(tail)s" % locals())
self.statements.append(" };")
2020-11-01 20:08:27 +07:00
self.statements.append(
' return new schema_definition(%(schema_name_string)s, declarations, new %(schema_name)s_instance_factory());'
2020-11-01 20:08:27 +07:00
% locals()
)
self.statements.extend(("}", ""))
self.statements.append(
"""
#if defined(__clang__)
#elif defined(__GNUC__) || defined(__GNUG__)
#pragma GCC pop_options
#elif defined(_MSC_VER)
#pragma optimize("", on)
#endif
2020-11-01 20:08:27 +07:00
"""
)
self.statements.extend(
(
"static std::unique_ptr<schema_definition> schema;",
"",
"void %s::clear_schema() {" % schema_name_title,
" schema.reset();",
"}",
2020-11-01 20:08:27 +07:00
"",
)
)
self.statements.extend(
(
"const schema_definition& %s::get_schema() {" % schema_name_title,
" if (!schema) {",
" schema.reset(%(schema_name)s_populate_schema());" % locals(),
" }",
" return *schema;",
2020-11-01 20:08:27 +07:00
"}",
"",
"",
)
)
def can_be_instantiated(idx_name):
name = idx_name[1]
return name in can_be_instantiated_set
2020-11-01 20:08:27 +07:00
instance_mapping = """switch(data->type()->index_in_schema()) {
%s
default: throw IfcParse::IfcException(data->type()->name() + " cannot be instantiated");
}
2020-11-01 20:08:27 +07:00
""" % "\n ".join(
map(
lambda tup: ("case %%d: return new ::%s::%%s(data);" % schema_name_title) % tup,
filter(can_be_instantiated, enumerate(self.names)),
)
)
2020-11-01 20:08:27 +07:00
self.statements[self.statements.index("{factory_placeholder}")] = (
"""
class %(schema_name)s_instance_factory : public IfcParse::instance_factory {
virtual IfcUtil::IfcBaseClass* operator()(IfcEntityInstanceData* data) const {
%(instance_mapping)s
}
};
2020-11-01 20:08:27 +07:00
"""
% locals()
)
strings_list = ",\n".join('"%s"s' % s for s in self.strings)
self.statements[self.statements.index("{strings_placeholder}")] = (
"static std::string strings[] = {%s};" % strings_list
)
def __str__(self):
2020-11-01 20:08:27 +07:00
return "\n".join(self.statements)
class SchemaClass(codegen.Base):
def __init__(self, mapping, code=EarlyBoundCodeWriter):
2020-11-01 20:08:27 +07:00
class UnmetDependenciesException(Exception):
pass
2015-09-08 20:40:54 +02:00
schema_name = mapping.schema.name
self.schema_name = schema_name_title = schema_name.capitalize()
2015-09-08 20:40:54 +02:00
declared_types = []
2020-11-01 20:08:27 +07:00
x = code(schema_name)
2020-11-01 20:08:27 +07:00
def get_declared_type(type, emitted_names=None):
if isinstance(type, nodes.SimpleType):
type = type.type
if isinstance(type, nodes.NamedType):
type = str(type)
if isinstance(type, nodes.AggregationType):
aggr_type = type.aggregate_type
2020-11-01 20:08:27 +07:00
make_bound = lambda b: -1 if b == "?" else int(b)
bound1, bound2 = map(make_bound, (type.bounds.lower, type.bounds.upper))
2018-01-29 15:03:12 +01:00
decl_type = get_declared_type(type.type, emitted_names)
return x.aggregation_type(aggr_type, bound1, bound2, decl_type)
elif isinstance(type, nodes.BinaryType):
return x.simple_type("binary")
2017-12-11 14:20:30 +01:00
elif isinstance(type, nodes.StringType):
return x.simple_type("string")
elif isinstance(type, str):
if mapping.schema.is_type(type) or mapping.schema.is_entity(type):
2018-01-29 15:03:12 +01:00
if emitted_names is None or type.lower() in emitted_names:
return x.named_type(type)
else:
raise UnmetDependenciesException(type)
else:
return x.simple_type(type)
else:
raise ValueError("No declared type for <%r>" % type)
def find_inverse_name_and_index(entity_name, attribute_name):
entity_name_orig = entity_name
attributes_per_subtype = []
while True:
entity = mapping.schema.entities[entity_name]
2020-11-01 20:08:27 +07:00
attr_names = list(map(operator.attrgetter("name"), entity.attributes))
if len(attr_names):
attributes_per_subtype.append((entity_name, attr_names))
2020-11-01 20:08:27 +07:00
if len(entity.supertypes) != 1:
break
entity_name = entity.supertypes[0]
index = 0
for et, attrs in attributes_per_subtype[::-1]:
2020-11-01 20:08:27 +07:00
try:
return et, attrs.index(attribute_name)
except:
pass
2017-12-11 14:20:30 +01:00
else:
raise Exception("No attribute named %s.%s" % (entity_name_orig, attribute_name))
2015-09-08 20:40:54 +02:00
2020-11-01 20:08:27 +07:00
collections_by_type = (
("entity", mapping.schema.entities),
("type_declaration", mapping.schema.simpletypes),
("select_type", mapping.schema.selects),
("enumeration_type", mapping.schema.enumerations),
)
2015-09-08 20:40:54 +02:00
for definition_type, collection in collections_by_type:
2015-09-08 20:40:54 +02:00
for name in collection.keys():
x.declare(definition_type, name)
2020-11-01 20:08:27 +07:00
declarations_by_index = []
2020-11-01 20:08:27 +07:00
x.begin_schema()
2020-11-01 20:08:27 +07:00
2018-01-29 15:03:12 +01:00
emitted = set()
2022-12-26 11:29:32 +01:00
len_to_emit = len(mapping.schema) - len(mapping.schema.rules) - len(mapping.schema.functions)
2020-11-01 20:08:27 +07:00
def write_simpletype(schema_name, name, type):
2018-01-29 15:03:12 +01:00
try:
declared_type = get_declared_type(type, emitted)
except UnmetDependenciesException:
2019-01-20 14:27:09 +01:00
# @todo?
# print("Unmet", repr(name))
2018-01-29 15:03:12 +01:00
return False
x.typedef(name, declared_type)
2020-11-01 20:08:27 +07:00
2018-01-29 15:03:12 +01:00
def write_enumeration(schema_name, name, enum):
x.enumeration(name, enum)
2020-11-01 20:08:27 +07:00
2018-01-29 15:03:12 +01:00
def write_entity(schema_name, name, type):
if len(type.supertypes) == 0 or set(map(lambda s: s.lower(), type.supertypes)) < emitted:
x.entity(name, type)
2020-11-01 20:08:27 +07:00
else:
return False
2018-01-29 15:03:12 +01:00
def write_select(schema_name, name, type):
if set(map(lambda s: str(s).lower(), type.values)) < emitted:
x.select(name, type)
2020-11-01 20:08:27 +07:00
else:
return False
2018-01-29 15:03:12 +01:00
def write(name):
if mapping.schema.is_simpletype(name):
fn = write_simpletype
elif mapping.schema.is_enumeration(name):
fn = write_enumeration
elif mapping.schema.is_entity(name):
fn = write_entity
elif mapping.schema.is_select(name):
fn = write_select
2022-12-26 11:29:32 +01:00
elif name in mapping.schema.rules:
return
elif name in mapping.schema.functions:
return
2020-11-01 20:08:27 +07:00
2018-01-29 15:03:12 +01:00
decl = mapping.schema[name]
if isinstance(decl, nodes.TypeDeclaration):
decl = decl.type
2018-01-29 15:03:12 +01:00
return fn(schema_name, name, decl) is not False
2020-11-01 20:08:27 +07:00
2018-01-29 15:03:12 +01:00
while len(emitted) < len_to_emit:
for name in mapping.schema:
2020-11-01 20:08:27 +07:00
if name.lower() in emitted:
continue
2018-01-29 15:03:12 +01:00
if write(name):
emitted.add(name.lower())
declarations_by_index.append(name)
2020-11-01 20:08:27 +07:00
declared_types.append("%(schema_name)s_%(name)s_type" % locals())
2018-01-29 15:03:12 +01:00
2015-09-08 20:40:54 +02:00
num_declarations = len(declared_types)
2020-11-01 20:08:27 +07:00
for name, type in mapping.schema.entities.items():
derived = set(mapping.derived_in_supertype(type))
2020-11-01 20:08:27 +07:00
attribute_names = list(map(operator.attrgetter("name"), mapping.arguments(type)))
is_derived = [b in derived for b in attribute_names]
attribute_definitions = []
for attr in type.attributes:
decl_type = get_declared_type(attr.type)
attribute_definitions.append((attr.name, decl_type, attr.optional))
x.entity_attributes(name, attribute_definitions, is_derived)
2020-11-01 20:08:27 +07:00
for name, type in mapping.schema.entities.items():
if type.inverse:
inv_attrs = []
for attr in type.inverse:
if attr.bounds:
2020-11-01 20:08:27 +07:00
make_bound = lambda b: -1 if b == "?" else int(b)
bound1, bound2 = map(make_bound, (attr.bounds.lower, attr.bounds.upper))
else:
bound1, bound2 = -1, -1
attr_name, aggr_type, entity_ref = attr.name, attr.type, attr.entity
2020-11-01 20:08:27 +07:00
if aggr_type is None:
aggr_type = "unspecified"
attribute_entity, attribute_entity_index = find_inverse_name_and_index(entity_ref, attr.attribute)
2020-11-01 20:08:27 +07:00
inv_attrs.append(
(attr_name, aggr_type, bound1, bound2, entity_ref, attribute_entity, attribute_entity_index)
)
x.inverse_attributes(name, inv_attrs)
2020-11-01 20:08:27 +07:00
subtypes = defaultdict(list)
2020-11-01 20:08:27 +07:00
for name, type in mapping.schema.entities.items():
for ty in type.supertypes:
subtypes[ty].append(name)
2020-11-01 20:08:27 +07:00
for name, tys in subtypes.items():
x.entity_subtypes(name, tys)
2020-11-01 20:08:27 +07:00
can_be_instantiated_set = set(
list(mapping.schema.entities.keys())
+ list(mapping.schema.simpletypes.keys())
+ list(mapping.schema.enumerations.keys())
)
x.finalize(can_be_instantiated_set)
2020-11-01 20:08:27 +07:00
self.str = str(x)
2020-11-01 20:08:27 +07:00
self.file_name = "%s-schema.cpp" % self.schema_name
self.code = x
def __repr__(self):
return self.str
2020-05-15 14:28:56 +02:00
2020-11-01 20:08:27 +07:00
2020-05-15 14:28:56 +02:00
Generator = SchemaClass