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
|
/*
Ousía
Copyright (C) 2014 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 <cassert>
#include <set>
#include "XmlOutput.hpp"
#include <core/common/Variant.hpp>
#include <core/common/VariantWriter.hpp>
// TODO: This should not be here -- remove this once we have a proper
// transformation system.
#include <transformations/uniqueid/UniqueIdTransformation.hpp>
namespace ousia {
namespace xml {
// TODO: Use impl class to avoid having to pass so many parameters to static
// functions (like e.g. in UniqueIdTransformation.cpp)
/**
* Wrapper structure for transformation parameters.
*/
struct TransformParams {
Manager &mgr;
Logger &logger;
bool pretty;
bool flat;
SourceId documentId;
// this stores all already serialized dependent typesystems and ontologies.
std::unordered_set<SourceId> serialized;
TransformParams(Manager &mgr, Logger &logger, bool pretty, bool flat,
SourceId documentId)
: mgr(mgr),
logger(logger),
pretty(pretty),
flat(flat),
documentId(documentId)
{
}
};
/**
* Helper function used for attaching the unique id of nodes (if available) to
* the XML elements.
*
* @param elem is the XML element to which the unique id should be attached.
* @param managed is the managed object from which the id should be looked up.
*/
static void attachId(Handle<Element> elem, Handle<Managed> managed)
{
// Check whether the managed object has an "id" attached to it
Rooted<ManagedVariant> id = managed->readData<ManagedVariant>("id");
if (id != nullptr && id->v.isString()) {
// We have an id that is a string, add it to the element
elem->getAttributes().emplace("id", id->v.asString());
}
}
/*
* These are forward method declarations to allow for cross-references of
* methods.
*/
/*
* Ontology transformation.
*/
static Rooted<Element> transformOntology(Handle<Element> parent,
Handle<Ontology> o,
TransformParams &P);
/*
* Typesystem transformation.
*/
static std::string getTypeRef(Handle<Typesystem> referencing,
Handle<Type> referenced);
static Rooted<Element> transformStructTypeEntry(Handle<Element> parent,
const std::string &tagName,
Handle<StructType> t,
Handle<Attribute> a,
TransformParams &P);
static Rooted<Element> transformStructType(Handle<Element> parent,
const std::string &structTagName,
const std::string &fieldTagName,
Handle<StructType> t,
TransformParams &P);
static Rooted<Element> transformTypesystem(Handle<Element> parent,
Handle<Typesystem> t,
TransformParams &P);
/*
* Attribute transformation.
*/
static std::map<std::string, std::string> transformAttributes(
const std::string &name, DocumentEntity *entity, TransformParams &P);
static void addNameAttribute(Handle<ousia::Node> n,
std::map<std::string, std::string> &attrs);
/*
* DocumentEntity transformation.
*/
static void transformChildren(DocumentEntity *parentEntity,
Handle<Element> parent, TransformParams &P);
static Rooted<Element> transformStructuredEntity(Handle<Element> parent,
Handle<StructuredEntity> s,
TransformParams &P);
/*
* Annotations.
*/
static Rooted<Element> transformAnchor(Handle<Element> parent, Handle<Anchor> a,
TransformParams &P);
/*
* DocumentPrimitives.
*/
static std::string toString(Variant v, TransformParams &P);
static Rooted<Text> transformPrimitive(Handle<Element> parent,
Handle<Type> type,
Handle<DocumentPrimitive> p,
TransformParams &P);
/*
* The actual transformation implementation starts here.
*/
static Rooted<Element> createImportElement(Handle<Element> parent,
Handle<ousia::Node> referenced,
ResourceManager &resourceManager,
const std::string &rel,
TransformParams &P)
{
SourceLocation loc = referenced->getLocation();
// check if the source location is the same as for the whole document.
// in that case we do not want to make an import statement.
if (P.documentId == loc.getSourceId()) {
return nullptr;
}
// if that is not the case, we try to find the respective resource.
Resource res = resourceManager.getResource(loc.getSourceId());
if (!res.isValid()) {
return nullptr;
}
// if we found it we create an import element.
Rooted<Element> import{new Element{
P.mgr, parent, "import", {{"rel", rel}, {"src", res.getLocation()}}}};
return import;
}
void XmlTransformer::writeXml(Handle<Document> doc, std::ostream &out,
Logger &logger, ResourceManager &resourceManager,
bool pretty, bool flat)
{
// Create unique ids for the nodes
UniqueIdTransformation::transform(doc);
Manager &mgr = doc->getManager();
// the outermost tag is the document itself.
Rooted<Element> document{new Element{mgr, {nullptr}, "document"}};
// create parameter wrapper object
TransformParams P{mgr, logger, pretty, flat,
doc->getLocation().getSourceId()};
// write imports for all referenced ontologies.
for (auto o : doc->getOntologies()) {
if (!flat) {
Rooted<Element> import = createImportElement(
document, o, resourceManager, "ontology", P);
if (import != nullptr) {
document->addChild(import);
// add the import as namespace information to the document node
// as well.
document->getAttributes().emplace(
std::string("xmlns:") + o->getName(), o->getName());
continue;
} else {
logger.warning(std::string(
"The location of ontology \"" + o->getName() +
"\" could not be retrieved using the given ResourceManager."
" The ontology is now serialized inline."));
}
}
Rooted<Element> ontology = transformOntology(document, o, P);
if (ontology != nullptr) {
document->addChild(ontology);
}
}
// write imports for all referenced typesystems.
for (auto t : doc->getTypesystems()) {
if (!flat) {
Rooted<Element> import = createImportElement(
document, t, resourceManager, "typesystem", P);
if (import != nullptr) {
document->addChild(import);
continue;
} else {
logger.warning(
std::string("The location of typesystem \"" + t->getName() +
"\" could not be retrieved using the given "
"ResourceManager. "
" The typesystem is now serialized inline."));
}
}
Rooted<Element> typesystem = transformTypesystem(document, t, P);
if (typesystem != nullptr) {
document->addChild(typesystem);
}
}
// transform the root element (and, using recursion, everything below it)
Rooted<Element> root =
transformStructuredEntity(document, doc->getRoot(), P);
document->addChild(root);
// then serialize.
document->serialize(
out, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>",
pretty);
}
/*
* Ontology transformation functions.
*/
static std::string getStringForBool(bool val)
{
if (val) {
return "true";
} else {
return "false";
}
}
static std::string getStructuredClassRef(Handle<Descriptor> referencing,
Handle<StructuredClass> referenced)
{
std::string res;
if (referencing->getParent() == referenced->getParent()) {
res = referenced->getName();
} else {
res = referenced->getParent().cast<Ontology>()->getName() + "." +
referenced->getName();
}
return res;
}
static Rooted<Element> transformTokenDescriptor(Handle<Element> parent,
const TokenDescriptor &descr,
const std::string &tagName,
TransformParams &P)
{
if (descr.isEmpty()) {
return nullptr;
}
Rooted<Element> tag{new Element(P.mgr, parent, tagName)};
Rooted<xml::Node> token;
if (descr.special) {
token = Rooted<Element>{
new Element(P.mgr, tag, Token::specialName(descr.id))};
} else {
token = Rooted<Text>{new Text(P.mgr, tag, descr.token)};
}
tag->addChild(token);
if (!descr.greedy) {
tag->getAttributes()["greedy"] = "false";
}
return tag;
}
static Rooted<Element> transformFieldDescriptor(Handle<Element> parent,
Handle<FieldDescriptor> fd,
TransformParams &P)
{
// find the correct tag name.
std::string tagName;
if (fd->isPrimitive()) {
tagName = "primitive";
} else {
tagName = "field";
}
// transform the attributes.
std::map<std::string, std::string> attrs;
addNameAttribute(fd, attrs);
bool isSubtree = fd->getFieldType() == FieldDescriptor::FieldType::SUBTREE;
if (isSubtree) {
attrs.emplace("subtree", getStringForBool(true));
}
if (fd->isOptional()) {
attrs.emplace("optional", getStringForBool(true));
}
// TODO: whitespace mode?
// create the XML element itself.
Rooted<Element> fieldDescriptor{new Element(P.mgr, parent, tagName, attrs)};
// translate the syntax.
Rooted<Element> syntax{new Element(P.mgr, parent, "syntax")};
{
Rooted<Element> open =
transformTokenDescriptor(syntax, fd->getOpenToken(), "open", P);
if (open != nullptr) {
syntax->addChild(open);
}
Rooted<Element> close =
transformTokenDescriptor(syntax, fd->getCloseToken(), "close", P);
if (close != nullptr) {
syntax->addChild(close);
}
}
if (!syntax->getChildren().empty()) {
fieldDescriptor->addChild(syntax);
}
if (!fd->isPrimitive()) {
// translate the child references.
for (auto s : fd->getChildren()) {
std::string ref =
getStructuredClassRef(fd->getParent().cast<Descriptor>(), s);
Rooted<Element> childRef{new Element(P.mgr, fieldDescriptor,
"childRef", {{"ref", ref}})};
fieldDescriptor->addChild(childRef);
}
} else {
// translate the primitive type.
fieldDescriptor->getAttributes().emplace(
"type", getTypeRef(nullptr, fd->getPrimitiveType()));
}
return fieldDescriptor;
}
static void transformDescriptor(Handle<Element> elem, Handle<Element> syntax,
Handle<Descriptor> d, TransformParams &P)
{
// add name.
addNameAttribute(d, elem->getAttributes());
// transform the attributes descriptor.
Rooted<Element> attributes = transformStructType(
elem, "attributes", "attribute", d->getAttributesDescriptor(), P);
// remove the parent entry if it is there.
attributes->getAttributes().erase("parent");
if (!attributes->getChildren().empty()) {
elem->addChild(attributes);
}
// transform the syntactic sugar description.
{
Rooted<Element> open =
transformTokenDescriptor(syntax, d->getOpenToken(), "open", P);
if (open != nullptr) {
syntax->addChild(open);
}
Rooted<Element> close =
transformTokenDescriptor(syntax, d->getCloseToken(), "close", P);
if (close != nullptr) {
syntax->addChild(close);
}
}
// transform all field descriptors.
for (auto fd : d->getFieldDescriptors()) {
Rooted<Element> fieldDescriptor = transformFieldDescriptor(elem, fd, P);
elem->addChild(fieldDescriptor);
}
}
static Rooted<Element> transformStructuredClass(Handle<Element> parent,
Handle<StructuredClass> s,
TransformParams &P)
{
Rooted<Element> structuredClass{new Element(P.mgr, parent, "struct")};
// transform the specific StructuredClass properties.
if (s->getCardinality() != Cardinality::any()) {
structuredClass->getAttributes().emplace(
"cardinality", toString(Variant(s->getCardinality()), P));
}
if (s->getSuperclass() != nullptr) {
structuredClass->getAttributes().emplace(
"isa", getStructuredClassRef(s, s->getSuperclass()));
}
if (s->isTransparent()) {
structuredClass->getAttributes().emplace("transparent",
getStringForBool(true));
}
if (s->hasRootPermission()) {
structuredClass->getAttributes().emplace("root",
getStringForBool(true));
}
// transform the syntactic sugar descriptors
Rooted<Element> syntax{new Element(P.mgr, structuredClass, "syntax")};
{
Rooted<Element> shortForm =
transformTokenDescriptor(syntax, s->getShortToken(), "short", P);
if (shortForm != nullptr) {
syntax->addChild(shortForm);
}
}
// transform the descriptor properties
transformDescriptor(structuredClass, syntax, s, P);
if (!syntax->getChildren().empty()) {
structuredClass->addChild(syntax);
}
return structuredClass;
}
static Rooted<Element> transformAnnotationClass(Handle<Element> parent,
Handle<AnnotationClass> a,
TransformParams &P)
{
Rooted<Element> annotationClass{new Element(P.mgr, parent, "struct")};
Rooted<Element> syntax{new Element(P.mgr, annotationClass, "syntax")};
transformDescriptor(annotationClass, syntax, a, P);
if (!syntax->getChildren().empty()) {
annotationClass->addChild(syntax);
}
return annotationClass;
}
static Rooted<Element> transformOntology(Handle<Element> parent,
Handle<Ontology> o, TransformParams &P)
{
// only transform this ontology if it was not transformed already.
if (o->getLocation().getSourceId() != P.documentId) {
// also: store that we have serialized this ontology.
if (!P.serialized.insert(o->getLocation().getSourceId()).second) {
return nullptr;
}
}
if (P.flat) {
// transform all referenced ontologies if we want a standalone version.
for (auto o2 : o->getOntologies()) {
Rooted<Element> refOnto = transformOntology(parent, o2, P);
if (refOnto != nullptr) {
parent->addChild(refOnto);
}
}
// transform all referenced typesystems if we want a standalone version.
for (auto t : o->getTypesystems()) {
Rooted<Element> refTypes = transformTypesystem(parent, t, P);
if (refTypes != nullptr) {
parent->addChild(refTypes);
}
}
}
// transform the ontology itself.
// create an XML element for the ontology.
Rooted<Element> ontology{new Element(P.mgr, parent, "ontology")};
addNameAttribute(o, ontology->getAttributes());
// transform all StructuredClasses.
for (auto s : o->getStructureClasses()) {
Rooted<Element> structuredClass =
transformStructuredClass(ontology, s, P);
ontology->addChild(structuredClass);
}
// transform all AnnotationClasses.
for (auto a : o->getAnnotationClasses()) {
Rooted<Element> annotationClass =
transformAnnotationClass(ontology, a, P);
ontology->addChild(annotationClass);
}
// return the transformed Ontology.
return ontology;
}
/*
* Typesystem transformation functions.
*/
static std::string getTypeRef(Handle<Typesystem> referencing,
Handle<Type> referenced)
{
std::string typeRef;
if (referencing != referenced->getTypesystem() &&
!(referenced->getTypesystem()->isa(&RttiTypes::SystemTypesystem))) {
// qualify the name if that's necessary.
typeRef = referenced->getTypesystem()->getName() + "." +
referenced->getName();
} else {
typeRef = referenced->getName();
}
return typeRef;
}
static Rooted<Element> transformStructTypeEntry(Handle<Element> parent,
const std::string &tagName,
Handle<StructType> t,
Handle<Attribute> a,
TransformParams &P)
{
// create an xml element for the attribute.
Rooted<Element> attribute{new Element(P.mgr, parent, tagName)};
addNameAttribute(a, attribute->getAttributes());
// add the type reference
{
std::string typeRef = getTypeRef(t->getTypesystem(), a->getType());
attribute->getAttributes().emplace("type", typeRef);
}
// set the default value.
if (!a->getDefaultValue().isNull() &&
(!a->getDefaultValue().isObject() ||
a->getDefaultValue().asObject() != nullptr)) {
attribute->getAttributes().emplace("default",
toString(a->getDefaultValue(), P));
}
return attribute;
}
static Rooted<Element> transformStructType(Handle<Element> parent,
const std::string &structTagName,
const std::string &fieldTagName,
Handle<StructType> t,
TransformParams &P)
{
// create an xml element for the struct type itself.
Rooted<Element> structType{new Element(P.mgr, parent, structTagName)};
addNameAttribute(t, structType->getAttributes());
// transformt the parent reference.
if (t->getParentStructure() != nullptr) {
std::string typeRef =
getTypeRef(t->getTypesystem(), t->getParentStructure());
structType->getAttributes().emplace("parent", typeRef);
}
// transform all attributes.
for (auto &a : t->getOwnAttributes()) {
Rooted<Element> attribute =
transformStructTypeEntry(structType, fieldTagName, t, a, P);
structType->addChild(attribute);
}
return structType;
}
static Rooted<Element> transformEnumType(Handle<Element> parent,
Handle<EnumType> e, TransformParams &P)
{
// create an xml element for the enum type itself.
Rooted<Element> enumType{new Element(P.mgr, parent, "enum")};
addNameAttribute(e, enumType->getAttributes());
// add all entries.
for (std::string &name : e->names()) {
Rooted<Element> enumEntry{new Element(P.mgr, enumType, "entry")};
enumType->addChild(enumEntry);
Rooted<Text> enumName{new Text(P.mgr, enumEntry, name)};
enumEntry->addChild(enumName);
}
return enumType;
}
static Rooted<Element> transformConstant(Handle<Element> parent,
Handle<Typesystem> t,
Handle<Constant> c, TransformParams &P)
{
// create an xml element for the constant.
Rooted<Element> constant{new Element(P.mgr, parent, "constant")};
addNameAttribute(c, constant->getAttributes());
// add the type reference
{
std::string typeRef = getTypeRef(t, c->getType());
constant->getAttributes().emplace("type", typeRef);
}
// add the value
constant->getAttributes().emplace("value", toString(c->getValue(), P));
return constant;
}
static Rooted<Element> transformTypesystem(Handle<Element> parent,
Handle<Typesystem> t,
TransformParams &P)
{
// do not transform the system typesystem.
if (t->isa(&RttiTypes::SystemTypesystem)) {
return nullptr;
}
// only transform this typesystem if it was not transformed already.
if (t->getLocation().getSourceId() != P.documentId) {
// also: store that we have serialized this ontology.
if (!P.serialized.insert(t->getLocation().getSourceId()).second) {
return nullptr;
}
}
if (P.flat) {
// transform all referenced typesystems if we want a standalone version.
for (auto t2 : t->getTypesystemReferences()) {
Rooted<Element> refTypes = transformTypesystem(parent, t2, P);
if (refTypes != nullptr) {
parent->addChild(refTypes);
}
}
}
// transform the typesystem itself.
// create an XML element for the ontology.
Rooted<Element> typesystem{new Element(P.mgr, parent, "typesystem")};
addNameAttribute(t, typesystem->getAttributes());
// transform all types
for (auto tp : t->getTypes()) {
Rooted<Element> type;
if (tp->isa(&RttiTypes::StructType)) {
type = transformStructType(typesystem, "struct", "field",
tp.cast<StructType>(), P);
} else if (tp->isa(&RttiTypes::EnumType)) {
type = transformEnumType(typesystem, tp.cast<EnumType>(), P);
} else {
P.logger.warning(std::string("Type ") + tp->getName() +
" can not be serialized, because it is neither a "
"StructType nor an EnumType.");
}
if (type != nullptr) {
typesystem->addChild(type);
}
}
// transform all constants.
for (auto c : t->getConstants()) {
Rooted<Element> constant = transformConstant(typesystem, t, c, P);
typesystem->addChild(constant);
}
// return the transformed Ontology.
return typesystem;
}
/*
* DocumentEntity attributes transform functions.
*/
static std::map<std::string, std::string> transformAttributes(
const std::string &name, DocumentEntity *entity, TransformParams &P)
{
// copy the attributes.
Variant attrs = entity->getAttributes();
// build them.
entity->getDescriptor()->getAttributesDescriptor()->build(attrs, P.logger);
// get the array representation.
Variant::arrayType attrArr = attrs.asArray();
// transform them to string key-value pairs.
NodeVector<Attribute> as =
entity->getDescriptor()->getAttributesDescriptor()->getAttributes();
std::map<std::string, std::string> xmlAttrs;
// Write the element name if one was given
if (!name.empty()) {
xmlAttrs.emplace("name", name);
}
// Write other user defined properties
for (size_t a = 0; a < as.size(); a++) {
xmlAttrs.emplace(as[a]->getName(), toString(attrArr[a], P));
}
return xmlAttrs;
}
static void addNameAttribute(Handle<ousia::Node> n,
std::map<std::string, std::string> &attrs)
{
// copy the name attribute.
if (!n->getName().empty()) {
attrs.emplace("name", n->getName());
}
}
/*
* StructureNode transform functions.
*/
static void transformChildren(DocumentEntity *parentEntity,
Handle<Element> parent, TransformParams &P)
{
ManagedVector<FieldDescriptor> fieldDescs =
parentEntity->getDescriptor()->getFieldDescriptors();
for (size_t f = 0; f < fieldDescs.size(); f++) {
NodeVector<StructureNode> field = parentEntity->getField(f);
Rooted<FieldDescriptor> fieldDesc = fieldDescs[f];
// if this is not the default field create an intermediate node for it.
Rooted<Element> par = parent;
if (fieldDesc->getFieldType() != FieldDescriptor::FieldType::TREE) {
par = Rooted<Element>{
new Element(P.mgr, parent, fieldDesc->getName())};
parent->addChild(par);
}
if (!fieldDesc->isPrimitive()) {
for (auto c : field) {
// transform each child.
Rooted<Element> child;
if (c->isa(&RttiTypes::StructuredEntity)) {
child = transformStructuredEntity(
par, c.cast<StructuredEntity>(), P);
} else {
assert(c->isa(&RttiTypes::Anchor));
child = transformAnchor(par, c.cast<Anchor>(), P);
}
if (child != nullptr) {
par->addChild(child);
}
}
} else {
// if the field is primitive we expect a single child.
if (field.empty()) {
continue;
}
assert(field.size() == 1);
assert(field[0]->isa(&RttiTypes::DocumentPrimitive));
Rooted<DocumentPrimitive> prim = field[0].cast<DocumentPrimitive>();
// transform the primitive content.
Rooted<Text> text =
transformPrimitive(par, fieldDesc->getPrimitiveType(), prim, P);
if (text != nullptr) {
par->addChild(text);
}
}
}
}
static Rooted<Element> transformStructuredEntity(Handle<Element> parent,
Handle<StructuredEntity> s,
TransformParams &P)
{
// create the XML element itself.
Rooted<Element> elem{new Element{
P.mgr, parent, s->getDescriptor()->getName(),
transformAttributes(s->getName(), s.get(), P),
s->getDescriptor()->getParent().cast<Ontology>()->getName()}};
attachId(elem, s);
// then transform the children.
transformChildren(s.get(), elem, P);
return elem;
}
static Rooted<Element> transformAnchor(Handle<Element> parent, Handle<Anchor> a,
TransformParams &P)
{
Rooted<Element> elem;
if (a->isStart()) {
// if this is the start anchor we append all the additional information
// of the annotation here.
// transform the attributes.
auto attrs = transformAttributes("", a->getAnnotation().get(), P);
elem = Rooted<Element>{new Element(
P.mgr, parent, a->getAnnotation()->getDescriptor()->getName(),
attrs, "a:start")};
// and handle the children.
transformChildren(a->getAnnotation().get(), elem, P);
// attach a possible id to the anchor
attachId(elem, a->getAnnotation());
} else if (a->isEnd()) {
/*
* in principle !a->isStart() should imply a->isEnd() but if no
* annotation is set both is false, so we check it to be sure.
* In case of an end anchor we just create an empty element with the
* annotation name.
*/
std::map<std::string, std::string> attrs;
addNameAttribute(a->getAnnotation(), attrs);
elem = Rooted<Element>{new Element(
P.mgr, parent, a->getAnnotation()->getDescriptor()->getName(),
attrs, "a:end")};
} else {
P.logger.warning("Ignoring disconnected Anchor", *a);
}
return elem;
}
/*
* Primitive transform functions.
*/
static std::string toString(Variant v, TransformParams &P)
{
if (v.isString()) {
return v.asString();
} else {
return VariantWriter::writeOusiaToString(v, P.pretty);
}
}
static Rooted<Text> transformPrimitive(Handle<Element> parent,
Handle<Type> type,
Handle<DocumentPrimitive> p,
TransformParams &P)
{
// transform the primitive content.
Variant content = p->getContent();
if (!type->build(content, P.logger)) {
return nullptr;
}
// special treatment for struct types because they get built as arrays,
// which is not so nice for output purposes.
if (type->isa(&RttiTypes::StructType)) {
Variant::mapType map;
Variant::arrayType arr = content.asArray();
size_t a = 0;
for (Handle<Attribute> attr :
type.cast<StructType>()->getAttributes()) {
map.emplace(attr->getName(), arr[a++]);
}
content = std::move(map);
}
Rooted<Text> text{new Text(P.mgr, parent, toString(content, P))};
return text;
}
}
}
|