summaryrefslogtreecommitdiff
path: root/src/core/model/Domain.cpp
blob: ca8f88921facdf76f91ec02e6c81cd1a4886c660 (plain)
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
/*
    Ousía
    Copyright (C) 2014, 2015  Benjamin Paaßen, Andreas Stöckel

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <memory>
#include <queue>
#include <set>

#include <core/common/RttiBuilder.hpp>
#include <core/common/Exceptions.hpp>

#include "Domain.hpp"

namespace ousia {

/* Helper Functions */

struct PathState {
	std::shared_ptr<PathState> pred;
	Node *node;
	size_t length;

	PathState(std::shared_ptr<PathState> pred, Node *node)
	    : pred(pred), node(node)
	{
		if (pred == nullptr) {
			length = 1;
		} else {
			length = pred->length + 1;
		}
	}
};

static void constructPath(std::shared_ptr<PathState> state,
                          NodeVector<Node> &vec)
{
	if (state->pred != nullptr) {
		constructPath(state->pred, vec);
	}
	vec.push_back(state->node);
}

static NodeVector<Node> pathTo(const Node *start, Logger &logger,
                               Handle<Node> target, bool &success)
{
	success = false;
	// shortest path.
	NodeVector<Node> shortest;
	// state queue for breadth-first search.
	std::queue<std::shared_ptr<PathState>> states;
	if (start->isa(&RttiTypes::Descriptor)) {
		const Descriptor *desc = static_cast<const Descriptor *>(start);
		// initially put every field descriptor on the queue.
		NodeVector<FieldDescriptor> fields = desc->getFieldDescriptors();

		for (auto fd : fields) {
			if (fd == target) {
				// if we have found the target directly, return without search.
				success = true;
				return shortest;
			}
			if (fd->getFieldType() == FieldDescriptor::FieldType::TREE) {
				states.push(std::make_shared<PathState>(nullptr, fd.get()));
			}
		}
	} else {
		const FieldDescriptor *field =
		    static_cast<const FieldDescriptor *>(start);
		// initially put every child and its subclasses to the queue.
		for (auto c : field->getChildrenWithSubclasses()) {
			// if we have found the target directly, return without search.
			if (c == target) {
				success = true;
				return shortest;
			}
			if (c->isTransparent()) {
				states.push(std::make_shared<PathState>(nullptr, c.get()));
			}
		}
	}
	// set of visited nodes.
	std::unordered_set<const Node *> visited;
	while (!states.empty()) {
		std::shared_ptr<PathState> current = states.front();
		states.pop();
		// do not proceed if this node was already visited.
		if (!visited.insert(current->node).second) {
			continue;
		}
		// also do not proceed if we can't get better than the current shortest
		// path anymore.
		if (!shortest.empty() && current->length > shortest.size()) {
			continue;
		}

		bool fin = false;
		if (current->node->isa(&RttiTypes::StructuredClass)) {
			const StructuredClass *strct =
			    static_cast<const StructuredClass *>(current->node);

			// look through all fields.
			NodeVector<FieldDescriptor> fields = strct->getFieldDescriptors();
			for (auto fd : fields) {
				// if we found our target, break off the search in this branch.
				if (fd == target) {
					fin = true;
					continue;
				}
				// only continue in the TREE field.
				if (fd->getFieldType() == FieldDescriptor::FieldType::TREE) {
					states.push(std::make_shared<PathState>(current, fd.get()));
				}
			}
		} else {
			// otherwise this is a FieldDescriptor.
			const FieldDescriptor *field =
			    static_cast<const FieldDescriptor *>(current->node);
			// and we proceed by visiting all permitted children.
			for (auto c : field->getChildrenWithSubclasses()) {
				// if we found our target, break off the search in this branch.
				if (c == target) {
					fin = true;
					continue;
				}
				// We only allow to continue our path via transparent children.
				if (c->isTransparent()) {
					states.push(std::make_shared<PathState>(current, c.get()));
				}
			}
		}
		// check if we are finished.
		if (fin) {
			success = true;
			// if so we look if we found a shorter path than the current minimum
			if (shortest.empty() || current->length < shortest.size()) {
				NodeVector<Node> newPath;
				constructPath(current, newPath);
				shortest = newPath;
			} else if (current->length == shortest.size()) {
				// if the length is the same the result is ambigous and we log
				// an error.
				NodeVector<Node> newPath;
				constructPath(current, newPath);
				logger.error(
				    std::string("Can not unambigously create a path from \"") +
				    start->getName() + "\" to \"" + target->getName() + "\".");
				logger.note("Dismissed the path:", SourceLocation{},
				            MessageMode::NO_CONTEXT);
				for (auto n : newPath) {
					logger.note(n->getName());
				}
			}
		}
	}
	return shortest;
}

template <typename F>
static NodeVector<Node> collect(const Node *start, F match)
{
	// result
	NodeVector<Node> res;
	// queue for breadth-first search of graph.
	std::queue<Rooted<Node>> q;
	// put the initial node on the stack.
	q.push(const_cast<Node *>(start));
	// set of visited nodes.
	std::unordered_set<const Node *> visited;
	while (!q.empty()) {
		Rooted<Node> n = q.front();
		q.pop();
		// do not proceed if this node was already visited.
		if (!visited.insert(n.get()).second) {
			continue;
		}

		if (n->isa(&RttiTypes::StructuredClass)) {
			Rooted<StructuredClass> strct = n.cast<StructuredClass>();

			// look through all fields.
			NodeVector<FieldDescriptor> fields = strct->getFieldDescriptors();
			for (auto fd : fields) {
				// note matches.
				if (match(fd)) {
					res.push_back(fd);
				}
				// only continue in the TREE field.
				if (fd->getFieldType() == FieldDescriptor::FieldType::TREE) {
					q.push(fd);
				}
			}
		} else {
			// otherwise this is a FieldDescriptor.
			Rooted<FieldDescriptor> field = n.cast<FieldDescriptor>();
			// and we proceed by visiting all permitted children.
			for (auto c : field->getChildrenWithSubclasses()) {
				// note matches.
				if (match(c)) {
					res.push_back(c);
				}
				// We only continue our search via transparent children.
				if (c->isTransparent()) {
					q.push(c);
				}
			}
		}
	}
	return res;
}

/* Class FieldDescriptor */

FieldDescriptor::FieldDescriptor(Manager &mgr, Handle<Type> primitiveType,
                                 Handle<Descriptor> parent, FieldType fieldType,
                                 std::string name, bool optional)
    : Node(mgr, std::move(name), parent),
      children(this),
      fieldType(fieldType),
      primitiveType(acquire(primitiveType)),
      optional(optional),
      primitive(true)
{
}

FieldDescriptor::FieldDescriptor(Manager &mgr, Handle<Descriptor> parent,
                                 FieldType fieldType, std::string name,
                                 bool optional)
    : Node(mgr, std::move(name), parent),
      children(this),
      fieldType(fieldType),
      optional(optional),
      primitive(false)
{
}

bool FieldDescriptor::doValidate(Logger &logger) const
{
	bool valid = true;
	// check parent type
	if (getParent() == nullptr) {
		logger.error(std::string("Field \"") + getName() + "\" has no parent!",
		             *this);
		valid = false;
	} else if (!getParent()->isa(&RttiTypes::Descriptor)) {
		logger.error(std::string("The parent of Field \"") + getName() +
		                 "\" is not a descriptor!",
		             *this);
		valid = false;
	}
	// check name
	if (getName().empty()) {
		if (fieldType != FieldType::TREE) {
			logger.error(std::string("Field \"") + getName() +
			                 "\" is not the main field but has an empty name!",
			             *this);
			valid = false;
		}
	} else {
		valid = valid & validateName(logger);
	}

	// check consistency of FieldType with the rest of the FieldDescriptor.
	if (primitive) {
		if (children.size() > 0) {
			logger.error(std::string("Field \"") + getName() +
			                 "\" is supposed to be primitive but has "
			                 "registered child classes!",
			             *this);
			valid = false;
		}
		if (primitiveType == nullptr) {
			logger.error(std::string("Field \"") + getName() +
			                 "\" is supposed to be primitive but has "
			                 "no primitive type!",
			             *this);
			valid = false;
		}
	} else {
		if (primitiveType != nullptr) {
			logger.error(std::string("Field \"") + getName() +
			                 "\" is supposed to be non-primitive but has "
			                 "a primitive type!",
			             *this);
			valid = false;
		}
		// if this is not a primitive field we require at least one child.
		if (children.empty()) {
			logger.error(std::string("Field \"") + getName() +
			                 "\" is non primitive but does not allow children!",
			             *this);
			valid = false;
		}
	}
	/*
	 * we are not allowed to call the validation functions of each child because
	 * this might lead to cycles. What we should do, however, is to check if
	 * there are duplicates.
	 */
	std::set<std::string> names;
	for (Handle<StructuredClass> c : getChildrenWithSubclasses()) {
		if (!names.insert(c->getName()).second) {
			logger.error(std::string("Field \"") + getName() +
			                 "\" had multiple children with the name \"" +
			                 c->getName() + "\"",
			             *this);
			valid = false;
		}
	}

	return valid;
}

static void gatherSubclasses(NodeVector<StructuredClass> &res,
                             Handle<StructuredClass> strct)
{
	for (auto sub : strct->getSubclasses()) {
		res.push_back(sub);
		gatherSubclasses(res, sub);
	}
}

NodeVector<StructuredClass> FieldDescriptor::getChildrenWithSubclasses() const
{
	NodeVector<StructuredClass> res;
	for (auto c : children) {
		res.push_back(c);
		gatherSubclasses(res, c);
	}
	return res;
}

bool FieldDescriptor::removeChild(Handle<StructuredClass> c)
{
	auto it = children.find(c);
	if (it != children.end()) {
		invalidate();
		children.erase(it);
		return true;
	}
	return false;
}

std::pair<NodeVector<Node>, bool> FieldDescriptor::pathTo(
    Handle<StructuredClass> childDescriptor, Logger &logger) const
{
	bool success = false;
	NodeVector<Node> path =
	    ousia::pathTo(this, logger, childDescriptor, success);
	return std::make_pair(path, success);
}
NodeVector<Node> FieldDescriptor::pathTo(Handle<FieldDescriptor> field,
                                         Logger &logger) const
{
	bool success = false;
	return ousia::pathTo(this, logger, field, success);
}
NodeVector<FieldDescriptor> FieldDescriptor::getDefaultFields() const
{
	// TODO: In principle a cast would be nicer here, but for now we copy.
	NodeVector<Node> nodes = collect(this, [](Handle<Node> n) {
		if (!n->isa(&RttiTypes::FieldDescriptor)) {
			return false;
		}
		Handle<FieldDescriptor> f = n.cast<FieldDescriptor>();
		return f->getFieldType() == FieldDescriptor::FieldType::TREE &&
		       f->isPrimitive();
	});
	NodeVector<FieldDescriptor> res;
	for (auto n : nodes) {
		res.push_back(n.cast<FieldDescriptor>());
	}
	return res;
}

/* Class Descriptor */

void Descriptor::doResolve(ResolutionState &state)
{
	const NodeVector<Attribute> &attributes =
	    attributesDescriptor->getAttributes();
	continueResolveComposita(attributes, attributes.getIndex(), state);
	continueResolveComposita(fieldDescriptors, fieldDescriptors.getIndex(),
	                         state);
}

bool Descriptor::doValidate(Logger &logger) const
{
	bool valid = true;
	// check parent type
	if (getParent() == nullptr) {
		logger.error(
		    std::string("Descriptor \"") + getName() + "\" has no parent!",
		    *this);
		valid = false;
	} else if (!getParent()->isa(&RttiTypes::Domain)) {
		logger.error(std::string("The parent of Descriptor \"") + getName() +
		                 "\" is not a Domain!",
		             *this);
		valid = false;
	}
	// check name
	if (getName().empty()) {
		logger.error("The name of this Descriptor is empty!", *this);
		valid = false;
	} else {
		valid = valid & validateName(logger);
	}
	// ensure that no attribute with the key "name" exists.
	if (attributesDescriptor == nullptr) {
		logger.error(std::string("Descriptor \"") + getName() +
		             "\" has no Attribute specification!");
		valid = false;
	} else {
		if (attributesDescriptor->hasAttribute("name")) {
			logger.error(
			    std::string("Descriptor \"") + getName() +
			    "\" has an attribute \"name\" which is a reserved word!");
			valid = false;
		}
		valid = valid & attributesDescriptor->validate(logger);
	}
	// check that only one FieldDescriptor is of type TREE.
	auto fds = Descriptor::getFieldDescriptors();
	bool hasTREE = false;
	for (auto fd : fds) {
		if (fd->getFieldType() == FieldDescriptor::FieldType::TREE) {
			if (!hasTREE) {
				hasTREE = true;
			} else {
				logger.error(
				    std::string("Descriptor \"") + getName() +
				        "\" has multiple TREE fields, which is not permitted",
				    *fd);
				valid = false;
				break;
			}
		}
	}

	// check attributes and the FieldDescriptors
	return valid & continueValidationCheckDuplicates(fds, logger);
}

NodeVector<Node> Descriptor::pathTo(Handle<StructuredClass> target,
                                    Logger &logger) const
{
	bool success = false;
	return ousia::pathTo(this, logger, target, success);
}

std::pair<NodeVector<Node>, bool> Descriptor::pathTo(
    Handle<FieldDescriptor> field, Logger &logger) const
{
	bool success = false;
	NodeVector<Node> path = ousia::pathTo(this, logger, field, success);
	return std::make_pair(path, success);
}

NodeVector<FieldDescriptor> Descriptor::getDefaultFields() const
{
	// TODO: In principle a cast would be nicer here, but for now we copy.
	NodeVector<Node> nodes = collect(this, [](Handle<Node> n) {
		if (!n->isa(&RttiTypes::FieldDescriptor)) {
			return false;
		}
		Handle<FieldDescriptor> f = n.cast<FieldDescriptor>();
		return f->getFieldType() == FieldDescriptor::FieldType::TREE &&
		       f->isPrimitive();
	});
	NodeVector<FieldDescriptor> res;
	for (auto n : nodes) {
		res.push_back(n.cast<FieldDescriptor>());
	}
	return res;
}

NodeVector<StructuredClass> Descriptor::getPermittedChildren() const
{
	// TODO: In principle a cast would be nicer here, but for now we copy.
	NodeVector<Node> nodes = collect(this, [](Handle<Node> n) {
		return n->isa(&RttiTypes::StructuredClass);
	});
	NodeVector<StructuredClass> res;
	for (auto n : nodes) {
		res.push_back(n.cast<StructuredClass>());
	}
	return res;
}

static ssize_t getFieldDescriptorIndex(const NodeVector<FieldDescriptor> &fds,
                                       const std::string &name)
{
	if (fds.empty()) {
		return -1;
	}

	if (name == DEFAULT_FIELD_NAME) {
		if (fds.back()->getFieldType() == FieldDescriptor::FieldType::TREE) {
			return fds.size() - 1;
		} else {
			/* The last field has to be the TREE field. If the last field does
			 * not have the FieldType TREE no TREE-field exists at all. So we
			 * return -1.
			 */
			return -1;
		}
	}

	for (size_t f = 0; f < fds.size(); f++) {
		if (fds[f]->getName() == name) {
			return f;
		}
	}
	return -1;
}

ssize_t Descriptor::getFieldDescriptorIndex(const std::string &name) const
{
	NodeVector<FieldDescriptor> fds = getFieldDescriptors();
	return ousia::getFieldDescriptorIndex(fds, name);
}

ssize_t Descriptor::getFieldDescriptorIndex(Handle<FieldDescriptor> fd) const
{
	size_t f = 0;
	for (auto &fd2 : getFieldDescriptors()) {
		if (fd == fd2) {
			return f;
		}
		f++;
	}
	return -1;
}

Rooted<FieldDescriptor> Descriptor::getFieldDescriptor(
    const std::string &name) const
{
	NodeVector<FieldDescriptor> fds = getFieldDescriptors();
	ssize_t idx = ousia::getFieldDescriptorIndex(fds, name);
	if (idx != -1) {
		return fds[idx];
	} else {
		return nullptr;
	}
}

bool Descriptor::addAndSortFieldDescriptor(Handle<FieldDescriptor> fd,
                                           Logger &logger)
{
	// only add it if we need to.
	auto fds = getFieldDescriptors();
	if (fds.find(fd) == fds.end()) {
		invalidate();
		// check if the previous field is a tree field already.
		if (!fds.empty() && !fieldDescriptors.empty() &&
		    fds.back()->getFieldType() == FieldDescriptor::FieldType::TREE &&
		    fd->getFieldType() != FieldDescriptor::FieldType::TREE) {
			// if so we add the new field before the TREE field.
			fieldDescriptors.insert(fieldDescriptors.end() - 1, fd);
			return true;
		} else {
			fieldDescriptors.push_back(fd);
		}
	}
	return false;
}

bool Descriptor::addFieldDescriptor(Handle<FieldDescriptor> fd, Logger &logger)
{
	if (fd->getParent() == nullptr) {
		fd->setParent(this);
	}
	return addAndSortFieldDescriptor(fd, logger);
}

bool Descriptor::moveFieldDescriptor(Handle<FieldDescriptor> fd, Logger &logger)
{
	bool sorted = addAndSortFieldDescriptor(fd, logger);
	Handle<Managed> par = fd->getParent();
	if (par != this) {
		if (par != nullptr) {
			// remove the FieldDescriptor from the old parent.
			par.cast<Descriptor>()->removeFieldDescriptor(fd);
		}
		fd->setParent(this);
	}
	return sorted;
}

bool Descriptor::copyFieldDescriptor(Handle<FieldDescriptor> fd, Logger &logger)
{
	Rooted<FieldDescriptor> copy;
	if (fd->isPrimitive()) {
		copy = Rooted<FieldDescriptor>{new FieldDescriptor(
		    getManager(), fd->getPrimitiveType(), this, fd->getFieldType(),
		    fd->getName(), fd->isOptional())};
	} else {
		/*
		 * In case of non-primitive FieldDescriptors we also want to copy the
		 * child references.
		 */
		copy = Rooted<FieldDescriptor>{
		    new FieldDescriptor(getManager(), this, fd->getFieldType(),
		                        fd->getName(), fd->isOptional())};
		for (auto c : fd->getChildren()) {
			copy->addChild(c);
		}
	}
	return addFieldDescriptor(copy, logger);
}

bool Descriptor::removeFieldDescriptor(Handle<FieldDescriptor> fd)
{
	auto it = fieldDescriptors.find(fd);
	if (it != fieldDescriptors.end()) {
		invalidate();
		fieldDescriptors.erase(it);
		fd->setParent(nullptr);
		return true;
	}
	return false;
}

std::pair<Rooted<FieldDescriptor>, bool>
Descriptor::createPrimitiveFieldDescriptor(Handle<Type> primitiveType,
                                           Logger &logger,
                                           FieldDescriptor::FieldType fieldType,
                                           std::string name, bool optional)
{
	Rooted<FieldDescriptor> fd{new FieldDescriptor(getManager(), primitiveType,
	                                               this, fieldType,
	                                               std::move(name), optional)};
	bool sorted = addFieldDescriptor(fd, logger);
	return std::make_pair(fd, sorted);
}

std::pair<Rooted<FieldDescriptor>, bool> Descriptor::createFieldDescriptor(
    Logger &logger, FieldDescriptor::FieldType fieldType, std::string name,
    bool optional)
{
	Rooted<FieldDescriptor> fd{new FieldDescriptor(
	    getManager(), this, fieldType, std::move(name), optional)};
	bool sorted = addFieldDescriptor(fd, logger);
	return std::make_pair(fd, sorted);
}

/* Class StructuredClass */

StructuredClass::StructuredClass(Manager &mgr, std::string name,
                                 Handle<Domain> domain, Variant cardinality,
                                 Handle<StructuredClass> superclass,
                                 bool transparent, bool root)
    : Descriptor(mgr, std::move(name), domain),
      cardinality(cardinality),
      superclass(acquire(superclass)),
      subclasses(this),
      transparent(transparent),
      root(root)
{
	ExceptionLogger logger;
	if (superclass != nullptr) {
		superclass->addSubclass(this, logger);
	}
	if (domain != nullptr) {
		domain->addStructuredClass(this);
	}
}

bool StructuredClass::doValidate(Logger &logger) const
{
	bool valid = true;
	// check if all registered subclasses have this StructuredClass as parent.
	for (Handle<StructuredClass> sub : subclasses) {
		if (sub->getSuperclass() != this) {
			logger.error(std::string("Struct \"") + sub->getName() +
			                 "\" is registered as subclass of \"" + getName() +
			                 "\" but does not have it as superclass!",
			             *this);
			valid = false;
		}
	}
	// check the cardinality.
	if (!cardinality.isCardinality()) {
		logger.error(cardinality.toString() + " is not a cardinality!", *this);
		valid = false;
	}
	// check the validity of this superclass.
	if (superclass != nullptr) {
		valid = valid & superclass->validate(logger);
	}
	// check the validity as a Descriptor.
	/*
	 * Note that we do not check the validity of all subclasses. This is because
	 * it will lead to cycles as the subclasses would call validate on their
	 * superclass, which is this one.
	 */
	return valid & Descriptor::doValidate(logger);
}

void StructuredClass::setSuperclass(Handle<StructuredClass> sup, Logger &logger)
{
	if (superclass == sup) {
		return;
	}
	// remove this subclass from the old superclass.
	if (superclass != nullptr) {
		superclass->removeSubclass(this, logger);
	}
	// set the new superclass
	superclass = acquire(sup);
	invalidate();
	// add this class as new subclass of the new superclass.
	if (sup != nullptr) {
		sup->addSubclass(this, logger);
		// set the attribute descriptor supertype
		getAttributesDescriptor()->setParentStructure(
		    sup->getAttributesDescriptor(), logger);
	} else {
		getAttributesDescriptor()->setParentStructure(nullptr, logger);
	}
}

bool StructuredClass::isSubclassOf(Handle<StructuredClass> c) const
{
	if (c == nullptr || superclass == nullptr) {
		return false;
	}
	if (c == superclass) {
		return true;
	}
	return superclass->isSubclassOf(c);
}

void StructuredClass::addSubclass(Handle<StructuredClass> sc, Logger &logger)
{
	if (sc == nullptr) {
		return;
	}
	// check if we already have that class.
	if (subclasses.find(sc) == subclasses.end()) {
		invalidate();
		subclasses.push_back(sc);
	}
	sc->setSuperclass(this, logger);
}

void StructuredClass::removeSubclass(Handle<StructuredClass> sc, Logger &logger)
{
	// if we don't have this subclass we can return directly.
	if (sc == nullptr) {
		return;
	}
	auto it = subclasses.find(sc);
	if (it == subclasses.end()) {
		return;
	}
	// otherwise we have to erase it.
	invalidate();
	subclasses.erase(it);
	sc->setSuperclass(nullptr, logger);
}

Rooted<FieldDescriptor> StructuredClass::gatherFieldDescriptors(
    NodeVector<FieldDescriptor> &current,
    std::set<std::string> &overriddenFields, bool hasTREE) const
{
	Rooted<FieldDescriptor> mainField;
	NodeVector<FieldDescriptor> tmp;
	// first gather the non-overridden fields.
	for (auto f : Descriptor::getFieldDescriptors()) {
		if (overriddenFields.insert(f->getName()).second) {
			bool isTREE = f->getFieldType() == FieldDescriptor::FieldType::TREE;
			if (!isTREE) {
				tmp.push_back(f);
			} else {
				if (!hasTREE) {
					hasTREE = true;
					mainField = f;
				}
			}
		}
	}
	// append all non-overridden superclass fields.

	if (superclass != nullptr) {
		Rooted<FieldDescriptor> super_main_field =
		    superclass->gatherFieldDescriptors(current, overriddenFields,
		                                       hasTREE);
		if (!hasTREE) {
			mainField = super_main_field;
		}
	}
	// then append all subtree fields of this level.
	current.insert(current.end(), tmp.begin(), tmp.end());
	// and return the main field.
	return mainField;
}

NodeVector<FieldDescriptor> StructuredClass::getFieldDescriptors() const
{
	// in this case we return a NodeVector of Rooted entries without owner.
	NodeVector<FieldDescriptor> vec;
	std::set<std::string> overriddenFields;
	Rooted<FieldDescriptor> mainField =
	    gatherFieldDescriptors(vec, overriddenFields, false);
	if (mainField != nullptr) {
		vec.push_back(mainField);
	}
	return vec;
}

/* Class AnnotationClass */

AnnotationClass::AnnotationClass(Manager &mgr, std::string name,
                                 Handle<Domain> domain)
    : Descriptor(mgr, std::move(name), domain)
{
	if (domain != nullptr) {
		domain->addAnnotationClass(this);
	}
}

/* Class Domain */

void Domain::doResolve(ResolutionState &state)
{
	continueResolveComposita(structuredClasses, structuredClasses.getIndex(),
	                         state);
	continueResolveComposita(annotationClasses, annotationClasses.getIndex(),
	                         state);
	continueResolveReferences(typesystems, state);
	continueResolveReferences(domains, state);
}

bool Domain::doValidate(Logger &logger) const
{
	// check validity of name, of StructuredClasses, of AnnotationClasses and
	// TypeSystems.
	return validateName(logger) &
	       continueValidationCheckDuplicates(structuredClasses, logger) &
	       continueValidationCheckDuplicates(annotationClasses, logger) &
	       continueValidationCheckDuplicates(typesystems, logger);
}

void Domain::doReference(Handle<Node> node)
{
	if (node->isa(&RttiTypes::Typesystem)) {
		referenceTypesystem(node.cast<Typesystem>());
	}
	if (node->isa(&RttiTypes::Domain)) {
		referenceDomain(node.cast<Domain>());
	}
}

RttiSet Domain::doGetReferenceTypes() const
{
	return RttiSet{&RttiTypes::Domain, &RttiTypes::Typesystem};
}

void Domain::addStructuredClass(Handle<StructuredClass> s)
{
	// only add it if we need to.
	if (structuredClasses.find(s) == structuredClasses.end()) {
		invalidate();
		structuredClasses.push_back(s);
	}
	Handle<Managed> par = s->getParent();
	if (par != this) {
		if (par != nullptr) {
			// remove the StructuredClass from the old parent.
			par.cast<Domain>()->removeStructuredClass(s);
		}
		s->setParent(this);
	}
}

bool Domain::removeStructuredClass(Handle<StructuredClass> s)
{
	auto it = structuredClasses.find(s);
	if (it != structuredClasses.end()) {
		invalidate();
		structuredClasses.erase(it);
		s->setParent(nullptr);
		return true;
	}
	return false;
}

Rooted<StructuredClass> Domain::createStructuredClass(
    std::string name, Variant cardinality, Handle<StructuredClass> superclass,
    bool transparent, bool root)
{
	return Rooted<StructuredClass>{new StructuredClass(
	    getManager(), std::move(name), this, cardinality, superclass,
	    std::move(transparent), std::move(root))};
}

void Domain::addAnnotationClass(Handle<AnnotationClass> a)
{
	// only add it if we need to.
	if (annotationClasses.find(a) == annotationClasses.end()) {
		invalidate();
		annotationClasses.push_back(a);
	}
	Handle<Managed> par = a->getParent();
	if (par != this) {
		if (par != nullptr) {
			// remove the StructuredClass from the old parent.
			par.cast<Domain>()->removeAnnotationClass(a);
		}
		a->setParent(this);
	}
}

bool Domain::removeAnnotationClass(Handle<AnnotationClass> a)
{
	auto it = annotationClasses.find(a);
	if (it != annotationClasses.end()) {
		invalidate();
		annotationClasses.erase(it);
		a->setParent(nullptr);
		return true;
	}
	return false;
}

Rooted<AnnotationClass> Domain::createAnnotationClass(std::string name)
{
	return Rooted<AnnotationClass>{
	    new AnnotationClass(getManager(), std::move(name), this)};
}

/* Type registrations */

namespace RttiTypes {
const Rtti FieldDescriptor =
    RttiBuilder<ousia::FieldDescriptor>("FieldDescriptor").parent(&Node);
const Rtti Descriptor =
    RttiBuilder<ousia::Descriptor>("Descriptor").parent(&Node);
const Rtti StructuredClass =
    RttiBuilder<ousia::StructuredClass>("StructuredClass")
        .parent(&Descriptor)
        .composedOf(&FieldDescriptor);
const Rtti AnnotationClass =
    RttiBuilder<ousia::AnnotationClass>("AnnotationClass").parent(&Descriptor);
const Rtti Domain = RttiBuilder<ousia::Domain>("Domain")
                        .parent(&RootNode)
                        .composedOf({&StructuredClass, &AnnotationClass});
}
}