-
-
Notifications
You must be signed in to change notification settings - Fork 965
Expand file tree
/
Copy pathparse.cpp
More file actions
4430 lines (4006 loc) · 180 KB
/
Copy pathparse.cpp
File metadata and controls
4430 lines (4006 loc) · 180 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/********************************************************************************
* *
* This file is part of IfcOpenShell. *
* *
* IfcOpenShell is free software: you can redistribute it and/or modify *
* it under the terms of the Lesser GNU General Public License as published by *
* the Free Software Foundation, either version 3.0 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 *
* Lesser GNU General Public License for more details. *
* *
* You should have received a copy of the Lesser GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
********************************************************************************/
#include "parse.h"
#include "express.h"
#include "character_decoder.h"
#include "exception.h"
#include "file.h"
#include "logger.h"
#include "schema.h"
#include "si_prefix.h"
#include "file_reader.h"
#include "utils.h"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/variant.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <ctime>
#include <set>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <string>
#include <iomanip>
#include <charconv>
#include <type_traits>
#include <unordered_map>
#include <functional>
#include <thread>
#include <exception>
#include <cstdlib>
// Apple clang's libc++ has no floating-point std::from_chars overload (it's
// =deleted), so on macOS doubles are parsed via strtod_l with a cached "C"
// locale — locale-independent, unlike strtod. Other platforms (libstdc++,
// MSVC STL) have working float from_chars and are left unchanged.
#if defined(__APPLE__)
#include <xlocale.h>
#include <locale.h>
#endif
#ifdef USE_MMAP
#include <boost/filesystem/path.hpp>
#endif
#define PERMISSIVE_FLOAT
using namespace ifcopenshell;
template <typename Reader>
spf_lexer<Reader>::spf_lexer(Reader* stream_, ifcopenshell::logger& log)
: decoder_(nullptr)
, logger_(log) {
stream = stream_;
decoder_ = new character_decoder<Reader>(stream_, logger_);
}
template <typename Reader>
spf_lexer<Reader>::~spf_lexer() {
delete decoder_;
}
template <typename Reader>
size_t spf_lexer<Reader>::skip_whitespace() const {
size_t index = 0;
while (!stream->eof()) {
char character = stream->peek();
if ((character == ' ' || character == '\r' || character == '\n' || character == '\t')) {
stream->increment();
++index;
} else {
break;
}
}
return index;
}
template <typename Reader>
size_t spf_lexer<Reader>::skip_comment() const {
if (stream->eof()) {
return 0;
}
char character = stream->peek();
if (character != '/') {
return 0;
}
stream->increment();
character = stream->peek();
if (character != '*') {
stream->seek(stream->tell() - 1);
return 0;
}
size_t index = 2;
char intermediate = 0;
while (!stream->eof()) {
character = stream->peek();
stream->increment();
++index;
if (character == '/' && intermediate == '*') {
break;
}
intermediate = character;
}
return index;
}
template <typename Reader>
std::string& spf_lexer<Reader>::get_temp_string() const {
const size_t idx = pool_index++;
const size_t slice = idx >> 4;
const size_t offset = idx & 0xF;
while (stringpool_.size() <= slice) {
stringpool_.push_back(std::make_unique<std::array<std::string, 16>>());
}
// std::wcout << "Num contexts: " << idx << std::endl;
return (*stringpool_[slice])[offset];
}
#if defined(__APPLE__) || defined(__EMSCRIPTEN__)
double ifcopenshell::parse_double_c(const char* start, char** end) {
static const locale_t loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t)0);
return strtod_l(start, end, loc);
}
#endif
template class IFC_PARSE_API ifcopenshell::spf_lexer<file_reader<full_buffer_impl>>;
template class IFC_PARSE_API ifcopenshell::spf_lexer<file_reader<paged_file_impl>>;
template class IFC_PARSE_API ifcopenshell::spf_lexer<file_reader<pushed_sequential_impl>>;
#ifdef USE_MMAP
template class IFC_PARSE_API ifcopenshell::spf_lexer<file_reader<mmap_impl>>;
#endif
#define IFC_INSTANTIATE_LEXER_NEXT(Reader) \
template IFC_PARSE_API token ifcopenshell::spf_lexer<Reader>::next<ifcopenshell::full_tokens>(); \
template IFC_PARSE_API token ifcopenshell::spf_lexer<Reader>::next<ifcopenshell::index_tokens>();
IFC_INSTANTIATE_LEXER_NEXT(file_reader<full_buffer_impl>)
IFC_INSTANTIATE_LEXER_NEXT(file_reader<paged_file_impl>)
IFC_INSTANTIATE_LEXER_NEXT(file_reader<pushed_sequential_impl>)
#ifdef USE_MMAP
IFC_INSTANTIATE_LEXER_NEXT(file_reader<mmap_impl>)
#endif
#undef IFC_INSTANTIATE_LEXER_NEXT
bool token::is_operator() {
return type == Token_OPERATOR;
}
bool token::is_operator(char character) {
return type == Token_OPERATOR && value_char == character;
}
bool token::is_identifier() {
return type == Token_IDENTIFIER;
}
bool token::is_string() {
return type == Token_STRING;
}
bool token::is_enumeration() {
// @nb this is a bit confusing?
return type == Token_ENUMERATION || type == Token_BOOL;
}
bool token::is_binary() {
return type == Token_BINARY;
}
bool token::is_keyword() {
return type == Token_KEYWORD;
}
bool token::is_int() {
return type == Token_INT;
}
bool token::is_bool() {
// Bool and logical share the same storage type, just logical unknown is stored as 'U'.
return type == Token_BOOL && value_char != 'U';
}
bool token::is_logical() {
return type == Token_BOOL;
}
bool token::is_float() {
#ifdef PERMISSIVE_FLOAT
/// NB: We are being more permissive here then allowed by the standard
return type == Token_FLOAT || type == Token_INT;
#else
return type == Token_FLOAT;
#endif
}
int64_t token::as_int() {
if (type != Token_INT) {
throw invalid_token_exception(start_pos, to_string(), "integer");
}
return value_int;
}
unsigned token::as_identifier() {
if (type != Token_IDENTIFIER) {
throw invalid_token_exception(start_pos, to_string(), "instance name");
}
return (unsigned) value_int;
}
bool token::as_bool() {
if (type != Token_BOOL) {
throw invalid_token_exception(start_pos, to_string(), "boolean");
}
return value_char == 'T';
}
boost::logic::tribool token::as_logical() {
if (type != Token_BOOL) {
throw invalid_token_exception(start_pos, to_string(), "logical");
}
if (value_int == 'F') {
return false;
}
if (value_int == 'T') {
return true;
}
return boost::logic::indeterminate;
}
double token::as_float() {
#ifdef PERMISSIVE_FLOAT
if (type == Token_INT) {
/// NB: We are being more permissive here then allowed by the standard
return value_int;
} // ----> continues beyond preprocessor directive
#endif
if (type == Token_FLOAT) {
return value_double;
}
throw invalid_token_exception(start_pos, to_string(), "real");
}
const std::string& token::as_string() {
if (is_string() || is_enumeration() || is_binary() || is_keyword()) {
// @todo quotes
return *value_string;
}
throw invalid_token_exception(start_pos, to_string(), "string");
}
boost::dynamic_bitset<> token::as_binary() {
const std::string& str = as_string();
if (str.empty()) {
throw exception("token is not a valid binary sequence");
}
std::string::const_iterator it = str.begin();
int n = *it - '0';
if ((n < 0 || n > 3) || (str.size() == 1 && n != 0)) {
throw exception("token is not a valid binary sequence");
}
++it;
unsigned i = (str.size() - 1) * 4 - n;
boost::dynamic_bitset<> bitset(i);
for (; it != str.end(); ++it) {
const std::string::value_type& c = *it;
int value = (c < 'A') ? (c - '0') : (c - 'A' + 10);
for (unsigned j = 0; j < 4; ++j) {
if (i-- == 0) {
break;
}
if ((value & (1 << (3 - j))) != 0) {
bitset.set(i);
}
}
}
return bitset;
}
std::string token::to_string() {
switch (type) {
case Token_OPERATOR:
case Token_BOOL:
return std::string(1, value_char);
case Token_INT:
return std::to_string(value_int);
case Token_IDENTIFIER:
return "#" + std::to_string(value_int);
case Token_FLOAT: {
std::ostringstream oss;
oss << std::setprecision(15) << value_double;
return oss.str();
}
case Token_STRING:
case Token_ENUMERATION:
case Token_BINARY:
case Token_KEYWORD:
return as_string();
case Token_NONE:
throw invalid_token_exception(start_pos, "", "");
}
throw exception("Unknown token type");
}
std::string ifcopenshell::encode_spf_string(const std::string& value) {
return character_encoder(value);
}
std::string ifcopenshell::decode_spf_string(const std::string& value) {
std::string wrapped;
auto value_p = &value;
if (!value.empty() && value.front() != '\'') {
wrapped = "'" + value + "'";
value_p = &wrapped;
}
file_reader<full_buffer_impl> reader(*value_p, caller_fed_tag{});
spf_lexer<file_reader<full_buffer_impl>> lexer(&reader);
token decoded = lexer.next();
if (!decoded.is_string()) {
throw exception("Expected an SPF string");
}
return decoded.as_string();
}
namespace {
template<typename Variant, typename T>
struct is_type_in_variant;
template<typename T, typename First, typename... Rest>
struct is_type_in_variant<std::variant<First, Rest...>, T>
{
static constexpr bool value = std::is_same<T, First>::value || is_type_in_variant<std::variant<Rest...>, T>::value;
};
template<typename T, typename Last>
struct is_type_in_variant<std::variant<Last>, T>
{
static constexpr bool value = std::is_same<T, Last>::value;
};
template<typename Variant, typename T>
constexpr bool is_type_in_variant_v = is_type_in_variant<Variant, T>::value;
class parameter_type_view {
const ifcopenshell::declaration* declaration_;
const std::vector<const ifcopenshell::attribute*>* attributes_;
std::unique_ptr<ifcopenshell::named_type> transient_named_type_;
public:
parameter_type_view(const ifcopenshell::declaration* declaration)
: declaration_(declaration)
, attributes_(nullptr)
{
if (declaration_ && declaration_->as_entity()) {
attributes_ = &declaration_->as_entity()->all_attributes();
} else if (declaration_ && declaration_->as_enumeration_type()) {
transient_named_type_.reset(new ifcopenshell::named_type(const_cast<ifcopenshell::declaration*>(declaration_)));
}
}
size_t size() const {
if (attributes_) {
return attributes_->size();
}
return declaration_ ? 1 : 0;
}
const ifcopenshell::parameter_type* operator[](size_t index) const {
if (attributes_) {
return index < attributes_->size() ? (*attributes_)[index]->type_of_attribute() : nullptr;
}
if (index != 0 || !declaration_) {
return nullptr;
}
if (auto* type_declaration = declaration_->as_type_declaration()) {
return type_declaration->declared_type();
}
if (declaration_->as_enumeration_type()) {
return transient_named_type_.get();
}
return nullptr;
}
};
const ifcopenshell::parameter_type* unwrap_type_declarations(const ifcopenshell::parameter_type* parameter_type) {
while (parameter_type && parameter_type->as_named_type() &&
parameter_type->as_named_type()->declared_type()->as_type_declaration()) {
parameter_type = parameter_type->as_named_type()->declared_type()->as_type_declaration()->declared_type();
}
return parameter_type;
}
ifcopenshell::declaration* declared_type(const ifcopenshell::parameter_type* parameter_type) {
parameter_type = unwrap_type_declarations(parameter_type);
return parameter_type && parameter_type->as_named_type() ? parameter_type->as_named_type()->declared_type() : nullptr;
}
const ifcopenshell::aggregation_type* aggregate_parameter_type(const ifcopenshell::parameter_type* parameter_type) {
parameter_type = unwrap_type_declarations(parameter_type);
return parameter_type ? parameter_type->as_aggregation_type() : nullptr;
}
const ifcopenshell::aggregation_type* nested_aggregation_type(const ifcopenshell::aggregation_type* aggregate_type) {
return aggregate_type ? aggregate_parameter_type(aggregate_type->type_of_element()) : nullptr;
}
void warn_attribute_count(
const ifcopenshell::declaration* declaration,
std::optional<size_t> instance_name,
size_t expected_size,
size_t actual_size,
ifcopenshell::logger& logger
) {
if (!declaration || expected_size == actual_size) {
return;
}
if (declaration->schema() == &Header_section_schema::get_schema()) {
logger.warning("VAL", 15, "Expected " + std::to_string(expected_size) + " attribute values, found " + std::to_string(actual_size) + " for header entity " + declaration->name());
} else {
logger.warning("VAL", 16, "Expected " + std::to_string(expected_size) + " attribute values, found " + std::to_string(actual_size) + (instance_name ? std::string(" for instance #" + std::to_string(*instance_name)) : std::string("")));
}
}
template <typename Fn>
void dispatch_token_direct(ifcopenshell::token token, ifcopenshell::declaration* declaration, int attribute_index, logger& logger, Fn&& fn) {
if (token.is_binary()) {
fn(token.as_binary());
} else if (token.is_bool()) {
fn(token.as_bool());
} else if (token.is_logical()) {
fn(token.as_logical());
} else if (token.is_enumeration()) {
const auto& value = token.as_string();
if (declaration && declaration->as_enumeration_type()) {
try {
fn(enumeration_reference(declaration->as_enumeration_type(), declaration->as_enumeration_type()->lookup_enum_offset(value)));
} catch (ifcopenshell::exception&) {
logger.error("VAL", 12, "An enumeration literal '" + value + "' is not valid for type '" + declaration->name() + "' at offset " + std::to_string(token.start_pos));
}
} else {
logger.error("VAL", 13, "An enumeration literal '" + value + "' is not expected at attribute index '" + std::to_string(attribute_index) + "' at offset " + std::to_string(token.start_pos));
}
} else if (token.is_int()) {
fn(token.as_int());
} else if (token.is_float()) {
fn(token.as_float());
} else if (token.is_identifier()) {
fn(ifcopenshell::reference_or_simple_type{ifcopenshell::instance_reference{(int) token.as_identifier(), token.start_pos}});
} else if (token.is_string()) {
fn(token.as_string());
} else if (token.is_operator('*')) {
fn(derived{});
}
}
typedef std::variant<
blank,
std::vector<int64_t>,
std::vector<double>,
std::vector<std::string>,
std::vector<boost::dynamic_bitset<>>,
std::vector<ifcopenshell::reference_or_simple_type>,
std::vector<std::vector<int64_t>>,
std::vector<std::vector<double>>,
std::vector<std::vector<ifcopenshell::reference_or_simple_type>>
> direct_aggregate_storage;
struct direct_aggregate {
direct_aggregate_storage storage;
size_t pending_empty_aggregates = 0;
size_t values = 0;
ifcopenshell::logger& logger_;
explicit direct_aggregate(ifcopenshell::logger& logger)
: logger_(logger) {}
template <typename T>
void append(const T& value) {
++values;
if constexpr (is_type_in_variant_v<direct_aggregate_storage, std::vector<std::decay_t<T>>>) {
if constexpr (
std::is_same_v<std::decay_t<T>, std::vector<int64_t>> ||
std::is_same_v<std::decay_t<T>, std::vector<double>> ||
std::is_same_v<std::decay_t<T>, std::vector<ifcopenshell::reference_or_simple_type>>
) {
if (storage.index() == 0 && pending_empty_aggregates) {
append_promoted(value);
return;
}
}
if (pending_empty_aggregates) {
logger_.error("VAL", 14, "Inconsistent aggregate valuation while attempting to append " + std::string(typeid(T).name()) + " after an empty nested aggregate");
pending_empty_aggregates = 0;
}
if (storage.index() == 0) {
storage = std::vector<std::decay_t<T>>{value};
} else if (auto* vector = std::get_if<std::vector<std::decay_t<T>>>(&storage)) {
vector->push_back(value);
} else {
append_promoted(value);
}
} else {
logger_.error("UNS", 31, std::string("Aggregates of ") + typeid(T).name() + " are not supported in the IfcOpenShell parser");
}
}
void append_empty_nested() {
++values;
if (auto* int_vector = std::get_if<std::vector<std::vector<int64_t>>>(&storage)) {
int_vector->emplace_back();
} else if (auto* double_vector = std::get_if<std::vector<std::vector<double>>>(&storage)) {
double_vector->emplace_back();
} else if (auto* reference_vector = std::get_if<std::vector<std::vector<ifcopenshell::reference_or_simple_type>>>(&storage)) {
reference_vector->emplace_back();
} else if (storage.index() == 0) {
++pending_empty_aggregates;
} else {
logger_.error("Inconsistent aggregate valuation while attempting to append an empty nested aggregate");
}
}
private:
template <typename T>
void append_promoted(const T& value) {
if constexpr (std::is_same_v<std::decay_t<T>, int64_t>) {
if (auto* vector = std::get_if<std::vector<double>>(&storage)) {
vector->push_back((double) value);
return;
}
}
if constexpr (std::is_same_v<std::decay_t<T>, double>) {
if (auto* vector = std::get_if<std::vector<int64_t>>(&storage)) {
std::vector<double> promoted(vector->begin(), vector->end());
promoted.push_back(value);
storage = std::move(promoted);
return;
}
}
if constexpr (std::is_same_v<std::decay_t<T>, std::vector<int64_t>>) {
if (storage.index() == 0) {
std::vector<std::vector<int64_t>> promoted(pending_empty_aggregates);
pending_empty_aggregates = 0;
promoted.push_back(value);
storage = std::move(promoted);
return;
}
if (auto* vector = std::get_if<std::vector<std::vector<int64_t>>>(&storage)) {
vector->push_back(value);
return;
}
if (auto* vector = std::get_if<std::vector<std::vector<double>>>(&storage)) {
std::vector<double> promoted(value.begin(), value.end());
vector->push_back(std::move(promoted));
return;
}
}
if constexpr (std::is_same_v<std::decay_t<T>, std::vector<double>>) {
if (storage.index() == 0) {
std::vector<std::vector<double>> promoted(pending_empty_aggregates);
pending_empty_aggregates = 0;
promoted.push_back(value);
storage = std::move(promoted);
return;
}
if (auto* vector = std::get_if<std::vector<std::vector<double>>>(&storage)) {
vector->push_back(value);
return;
}
if (auto* vector = std::get_if<std::vector<std::vector<int64_t>>>(&storage)) {
std::vector<std::vector<double>> promoted;
promoted.reserve(vector->size() + 1);
for (const auto& nested : *vector) {
promoted.emplace_back(nested.begin(), nested.end());
}
promoted.push_back(value);
storage = std::move(promoted);
return;
}
}
if constexpr (std::is_same_v<std::decay_t<T>, std::vector<ifcopenshell::reference_or_simple_type>>) {
if (storage.index() == 0) {
std::vector<std::vector<ifcopenshell::reference_or_simple_type>> promoted(pending_empty_aggregates);
pending_empty_aggregates = 0;
promoted.push_back(value);
storage = std::move(promoted);
return;
}
if (auto* vector = std::get_if<std::vector<std::vector<ifcopenshell::reference_or_simple_type>>>(&storage)) {
vector->push_back(value);
return;
}
}
auto current = std::visit([](auto v) {
if constexpr (!std::is_same_v<decltype(v), blank>) {
return std::string(typeid(typename decltype(v)::value_type).name());
} else {
return std::string{};
}
}, storage);
logger_.error("Inconsistent aggregate valuation while attempting to append " + std::string(typeid(T).name()) + " to an aggregate of " + current);
}
};
void append_empty_direct_aggregate(const ifcopenshell::aggregation_type* aggregate_type, direct_aggregate& target) {
if (!aggregate_type) {
target.append_empty_nested();
return;
}
auto argument_type = ifcopenshell::make_aggregate(ifcopenshell::from_parameter_type(aggregate_type->type_of_element()));
if (argument_type == ifcopenshell::Argument_AGGREGATE_OF_INT) {
target.storage = std::vector<int64_t>{};
} else if (argument_type == ifcopenshell::Argument_AGGREGATE_OF_DOUBLE) {
target.storage = std::vector<double>{};
} else if (argument_type == ifcopenshell::Argument_AGGREGATE_OF_STRING) {
target.storage = std::vector<std::string>{};
} else if (argument_type == ifcopenshell::Argument_AGGREGATE_OF_BINARY) {
target.storage = std::vector<boost::dynamic_bitset<>>{};
} else if (argument_type == ifcopenshell::Argument_AGGREGATE_OF_ENTITY_INSTANCE) {
target.storage = std::vector<ifcopenshell::reference_or_simple_type>{};
} else if (argument_type == ifcopenshell::Argument_AGGREGATE_OF_AGGREGATE_OF_INT) {
target.storage = std::vector<std::vector<int64_t>>{};
} else if (argument_type == ifcopenshell::Argument_AGGREGATE_OF_AGGREGATE_OF_DOUBLE) {
target.storage = std::vector<std::vector<double>>{};
} else if (argument_type == ifcopenshell::Argument_AGGREGATE_OF_AGGREGATE_OF_ENTITY_INSTANCE) {
target.storage = std::vector<std::vector<ifcopenshell::reference_or_simple_type>>{};
} else {
target.append_empty_nested();
}
}
template <typename T>
void set_direct_attribute(
in_memory_attribute_storage& storage,
std::optional<size_t> instance_name,
ifcopenshell::unresolved_references* references_to_resolve,
bool resolve_in_place,
size_t attribute_index,
int resolve_reference_index,
const T& value
) {
constexpr bool holds_references =
std::is_same_v<std::decay_t<T>, ifcopenshell::reference_or_simple_type> ||
std::is_same_v<std::decay_t<T>, std::vector<ifcopenshell::reference_or_simple_type>> ||
std::is_same_v<std::decay_t<T>, std::vector<std::vector<ifcopenshell::reference_or_simple_type>>>;
if constexpr (holds_references) {
// A diverted reference (resolve_reference_index != -1) belongs to a
// simple type instance nested in an attribute of the owner. In place
// it is written into that instance's own slot, so nothing is diverted.
if (resolve_in_place && instance_name) {
if constexpr (std::is_same_v<std::decay_t<T>, ifcopenshell::reference_or_simple_type>) {
if (const auto* reference = std::get_if<ifcopenshell::instance_reference>(&value)) {
storage.set(attribute_index, *reference);
} else {
storage.set(attribute_index, std::get<express::base>(value));
}
} else {
storage.set(attribute_index, value);
}
} else if (instance_name && references_to_resolve) {
references_to_resolve->push_back({{(uint32_t) *instance_name, resolve_reference_index == -1 ? (uint8_t) attribute_index : (uint8_t) resolve_reference_index}, value});
}
} else {
storage.set(attribute_index, value);
}
}
template <typename Reader>
void skip_aggregate(ifcopenshell::spf_lexer<Reader>* tokens) {
size_t depth = 1;
while (depth) {
token next = tokens->next();
if (!next) {
break;
}
if (next.is_operator('(')) {
++depth;
} else if (next.is_operator(')')) {
--depth;
}
}
}
template <typename Reader>
direct_aggregate read_direct_aggregate(
ifcopenshell::impl::in_memory_file_storage& storage,
ifcopenshell::spf_lexer<Reader>* tokens,
std::optional<size_t> entity_instance_name,
const ifcopenshell::entity* entity,
int attribute_index,
const ifcopenshell::aggregation_type* aggregate_type,
ifcopenshell::logger& logger
) {
direct_aggregate aggregate(logger);
token next = tokens->next();
while (next) {
if (next.is_operator(',')) {
} else if (next.is_operator(')')) {
break;
} else if (next.is_operator('(')) {
auto nested = read_direct_aggregate(storage, tokens, entity_instance_name, entity, attribute_index, nested_aggregation_type(aggregate_type), logger);
if (nested.values == 0 && nested.storage.index() == 0) {
aggregate.append_empty_nested();
} else {
std::visit([&aggregate](const auto& value) {
if constexpr (!std::is_same_v<std::decay_t<decltype(value)>, blank>) {
aggregate.append(value);
}
}, nested.storage);
}
} else if (next.is_keyword()) {
try {
const auto* declaration = (storage.schema ? storage.schema : storage.file->schema())->declaration_by_name(next.as_string());
tokens->next();
auto data = storage.load(tokens, entity_instance_name, declaration, entity, attribute_index);
storage.read_simple_type_instances.push_back(data);
aggregate.append(ifcopenshell::reference_or_simple_type{express::base(data)});
} catch (exception& e) {
logger.error("SYN", 123, std::string(e.what()) + " at offset " + std::to_string(next.start_pos));
}
} else {
if (next.is_identifier() && entity && entity_instance_name) {
storage.register_inverse((unsigned)*entity_instance_name, entity, next.value_int, attribute_index);
}
dispatch_token_direct(next, aggregate_type && aggregate_type->type_of_element()->as_named_type() ? aggregate_type->type_of_element()->as_named_type()->declared_type() : nullptr, attribute_index, logger, [&aggregate](const auto& value) {
aggregate.append(value);
});
}
next = tokens->next();
}
if (aggregate.values == 0) {
append_empty_direct_aggregate(aggregate_type, aggregate);
}
return aggregate;
}
} // namespace
//
// Reads the arguments from a list of tokens directly into instance_data storage.
// Additionally, registers the ids (i.e. #[\d]+) in the inverse map.
//
template <typename Reader>
shared_pointer_type ifcopenshell::impl::in_memory_file_storage::load(
ifcopenshell::spf_lexer<Reader>* tokens,
std::optional<size_t> entity_instance_name,
const ifcopenshell::declaration* declaration,
const ifcopenshell::entity* entity,
int attribute_index,
bool coerce_attribute_count
) {
static_cast<void>(coerce_attribute_count);
auto storage = load_attributes<Reader, in_memory_attribute_storage>(tokens, entity_instance_name, declaration, entity, attribute_index);
return ifcopenshell::make_pointer_type<instance_data>(file, declaration, (declaration && declaration->as_entity()) ? (uint32_t)entity_instance_name.value_or(0) : 0, std::move(storage));
}
template <typename Reader, typename Storage>
Storage ifcopenshell::impl::in_memory_file_storage::load_attributes(
ifcopenshell::spf_lexer<Reader>* tokens,
std::optional<size_t> entity_instance_name,
const ifcopenshell::declaration* declaration,
const ifcopenshell::entity* entity,
int attribute_index
) {
parameter_type_view parameter_types(declaration);
const size_t expected_size = parameter_types.size();
Storage storage(expected_size);
token next = tokens->next();
size_t attribute_index_within_data = 0;
size_t values_read = 0;
while (next) {
if (next.is_operator(',')) {
++attribute_index_within_data;
} else if (next.is_operator(')')) {
break;
} else {
++values_read;
const bool retain_value = attribute_index_within_data < expected_size;
const ifcopenshell::parameter_type* parameter_type = retain_value ? parameter_types[attribute_index_within_data] : nullptr;
const int reference_attribute_index = attribute_index == -1 ? (int) attribute_index_within_data : attribute_index;
if (next.is_operator('(')) {
if (retain_value) {
auto aggregate = read_direct_aggregate(*this, tokens, entity_instance_name, entity, reference_attribute_index, aggregate_parameter_type(parameter_type), logger_.get());
std::visit([&](const auto& value) {
if constexpr (!std::is_same_v<std::decay_t<decltype(value)>, blank>) {
set_direct_attribute(storage, entity_instance_name, references_to_resolve, resolve_references_in_place, attribute_index_within_data, attribute_index, value);
}
}, aggregate.storage);
} else {
skip_aggregate(tokens);
}
} else if (next.is_keyword()) {
try {
const auto* simple_declaration = (schema ? schema : file->schema())->declaration_by_name(next.as_string());
tokens->next();
if (retain_value) {
auto data = load(tokens, entity_instance_name, simple_declaration, entity, reference_attribute_index);
read_simple_type_instances.push_back(data);
storage.set(attribute_index_within_data, express::base(data));
} else {
skip_aggregate(tokens);
}
} catch (exception& e) {
logger_.get().message(ifcopenshell::logger::LOG_ERROR, std::string(e.what()) + " at offset " + std::to_string(next.start_pos));
--values_read;
}
} else {
if (next.is_identifier() && entity && entity_instance_name) {
register_inverse((unsigned)*entity_instance_name, entity, next.value_int, reference_attribute_index);
}
if (retain_value) {
dispatch_token_direct(next, declared_type(parameter_type), (int) attribute_index_within_data, logger_.get(), [&](const auto& value) {
set_direct_attribute(storage, entity_instance_name, references_to_resolve, resolve_references_in_place, attribute_index_within_data, attribute_index, value);
});
}
}
}
next = tokens->next();
}
warn_attribute_count(declaration, entity_instance_name, expected_size, values_read, logger_.get());
return storage;
}
template <typename Reader>
void ifcopenshell::impl::in_memory_file_storage::try_read_semicolon(ifcopenshell::spf_lexer<Reader>* tokens) const {
auto old_offset = tokens->stream->tell();
token semilocon = tokens->next();
if (!semilocon.is_operator(';')) {
tokens->stream->seek(old_offset);
}
}
void ifcopenshell::impl::in_memory_file_storage::register_inverse(unsigned id_from, const ifcopenshell::entity* from_entity, int inst_id, int attribute_index) {
if (!register_inverses_) {
return;
}
// Assume a check on token type has already been performed
byref_excl_.add((uint32_t)inst_id, (uint32_t)id_from, (uint16_t)from_entity->index_in_schema(), attribute_index);
}
void ifcopenshell::impl::in_memory_file_storage::unregister_inverse(unsigned id_from, const ifcopenshell::entity* from_entity, const express::base& inst, int attribute_index) {
if (!byref_excl_.remove((uint32_t)inst.id(), (uint32_t)id_from, (uint16_t)from_entity->index_in_schema(), attribute_index)) {
// @todo inverses also need to be populated when multiple instances are added to a new file.
// throw ifcopenshell::exception("Instance not found among inverses");
}
}
namespace {
template <typename T>
std::string to_string_fixed_width(const T& t, size_t) {
// @todo currently inactive
std::ostringstream oss;
oss << /*std::setfill('0') << std::setw(w) <<*/ t;
return oss.str();
}
}
void ifcopenshell::impl::rocks_db_file_storage::register_inverse(unsigned id_from, const ifcopenshell::entity* from_entity, int inst_id, int attribute_index) {
#ifndef IFOPSH_WITH_ROCKSDB
(void)id_from;
(void)from_entity;
(void)inst_id;
(void)attribute_index;
#endif
#ifdef IFOPSH_WITH_ROCKSDB
static std::string s;
uint32_t v = id_from;
s.resize(sizeof(uint32_t));
memcpy(s.data(), &v, sizeof(uint32_t));
auto key = "v|" + to_string_fixed_width(inst_id, 10) + "|" + to_string_fixed_width(from_entity->index_in_schema(), 4) + "|" + to_string_fixed_width(attribute_index, 2);
db->Merge(wopts, key, s);
/*
// Python client does not support merges
// @todo turn this into a setting
{
std::string current;
db->Get(rocksdb::ReadOptions{}, key, ¤t);
auto new_val = current + s;
db->Put(wopts, key, new_val);
}*/
#endif
}
void ifcopenshell::impl::rocks_db_file_storage::unregister_inverse(unsigned id_from, const ifcopenshell::entity* from_entity, const express::base& inst, int attribute_index) {
#ifndef IFOPSH_WITH_ROCKSDB
(void)id_from;
(void)from_entity;
(void)inst;
(void)attribute_index;
#endif
#ifdef IFOPSH_WITH_ROCKSDB
static std::string s;
auto inst_id = inst.id();
auto key = "v|" + to_string_fixed_width(inst_id, 10) + "|" + to_string_fixed_width(from_entity->index_in_schema(), 4) + "|" + to_string_fixed_width(attribute_index, 2);
if (db->Get(rocksdb::ReadOptions{}, key, &s).ok()) {
std::vector<uint32_t> vals(s.size() / sizeof(uint32_t));
memcpy(vals.data(), s.data(), s.size());
auto it = std::find(vals.begin(), vals.end(), (uint32_t)id_from);
if (it != vals.end()) {
vals.erase(it);
} else {
file->logger().error("Unregistering non-existant inverse #" + std::to_string(id_from) + " on instance #" + std::to_string(inst_id) + " at attribute " + std::to_string(attribute_index));
}
s.resize(vals.size() * sizeof(uint32_t));
memcpy(s.data(), vals.data(), s.size());
db->Put(wopts, key, s);
}
#endif
}
void ifcopenshell::impl::rocks_db_file_storage::add_type_ref(const express::base& new_entity)
{
#ifndef IFOPSH_WITH_ROCKSDB
(void)new_entity;
#endif
#ifdef IFOPSH_WITH_ROCKSDB
size_t v;
std::string s(sizeof(size_t), ' ');
if (new_entity.declaration().as_entity()) {
v = new_entity.id();
memcpy(s.data(), &v, sizeof(size_t));
// no merges yet, because the python client doesn't support them
db->Merge(wopts, "t|" + std::to_string(new_entity.declaration().index_in_schema()), s);
/*{
std::string current;
// @todo this uses the same key-namespace as typedecl instances, not a direct conflict, but also not very clear
auto key = "t|" + std::to_string(new_entity.declaration().index_in_schema());
db->Get(rocksdb::ReadOptions{}, key, ¤t);
auto new_val = current + s;
db->Put(wopts, key, new_val);
}*/
}
// not only mapping also register type
v = new_entity.declaration().index_in_schema();
memcpy(s.data(), &v, sizeof(size_t));
db->Put(wopts, (new_entity.declaration().as_entity() ? "i|" : "t|") + std::to_string(new_entity.id() ? new_entity.id() : new_entity.identity()) + "|_", s);
#endif
}
void ifcopenshell::impl::rocks_db_file_storage::remove_type_ref(const express::base& new_entity)
{
#ifndef IFOPSH_WITH_ROCKSDB
(void)new_entity;
#endif
#ifdef IFOPSH_WITH_ROCKSDB
if (new_entity.declaration().as_entity()) {
std::string s;
auto key = "t|" + std::to_string(new_entity.declaration().index_in_schema());
if (db->Get(rocksdb::ReadOptions{}, key, &s).ok()) {
std::vector<size_t> vals(s.size() / sizeof(size_t));
memcpy(vals.data(), s.data(), s.size());
vals.erase(std::find(vals.begin(), vals.end(), (size_t)new_entity.id()));
s.resize(vals.size() * sizeof(size_t));