summaryrefslogtreecommitdiff
path: root/src/transformations/uniqueid/UniqueIdTransformation.cpp
blob: c901540ebf58b3f501b9ccd46229240e372e2b81 (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
/*
    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 <queue>
#include <set>
#include <string>

#include <core/common/Utils.hpp>
#include <core/common/Variant.hpp>

#include "UniqueIdTransformation.hpp"

namespace ousia {

namespace {
/**
 * Internally used implementation class used for a single transformation pass.
 */
class UniqueIdTransformationImpl {
private:
	/**
	 * Set containing all ids that are already present in the document.
	 */
	std::unordered_set<std::string> ids;

	/**
	 * Vector containing all elements that still need an id.
	 */
	ManagedVector<Node> nodesWithoutId;

	/**
	 * Set preventing multi-insertion into the nodesWithoutId vector.
	 */
	std::unordered_set<Managed *> nodesWithoutIdSet;

	/**
	 * Traverse the document tree -- find all elements with primitive content.
	 */
	std::queue<Rooted<StructuredEntity>> queue;

	/**
	 * Method used to iterate over all fields of a DocumentEntity and to place
	 * the corresponding elements on a queue.
	 */
	void processFields(const DocumentEntity *entity);

	/**
	 * Searches the variant for any object references.
	 */
	void processVariant(const Variant &data);

	/**
	 * Used to build the id prefix.
	 *
	 * @return a string containing the prefix.
	 */
	std::string buildId(Handle<Node> node);

public:
	/**
	 * Applys the transformation to the given document.
	 *
	 * @param doc is the document for which unique IDs should be generated.
	 */
	void transform(Handle<Document> doc);
};

void UniqueIdTransformationImpl::processVariant(const Variant &var)
{
	if (var.isArray()) {
		for (const auto &elem : var.asArray()) {
			processVariant(elem);
		}
	} else if (var.isMap()) {
		for (const auto &elem : var.asMap()) {
			processVariant(elem.second);
		}
	} else if (var.isObject()) {
		Rooted<Managed> obj = var.asObject();
		if (!obj->hasDataKey("id") && obj->isa(&RttiTypes::Node)) {
			if (nodesWithoutIdSet.count(obj.get()) == 0) {
				nodesWithoutId.push_back(obj.cast<Node>());
				nodesWithoutIdSet.insert(obj.get());
			}
		}
	}
}

void UniqueIdTransformationImpl::processFields(const DocumentEntity *entity)
{
	for (const NodeVector<StructureNode> &nodes : entity->getFields()) {
		for (Rooted<StructureNode> node : nodes) {
			// Check whether the node has the "id"-data field attached to it --
			// if yes, store the id in the ids list
			Rooted<ManagedVariant> id = node->readData<ManagedVariant>("id");
			if (id != nullptr && id->v.isString()) {
				ids.insert(id->v.asString());
			}

			// If the node is a structured entity just push it onto the stack
			if (node->isa(&RttiTypes::StructuredEntity)) {
				queue.push(node.cast<StructuredEntity>());
			} else if (node->isa(&RttiTypes::DocumentPrimitive)) {
				// This is a primitive node -- check whether it references any
				// other, if yes, check whether the primitive field is an object
				// that references another entry
				processVariant(node.cast<DocumentPrimitive>()->getContent());
			}
		}
	}
}

std::string UniqueIdTransformationImpl::buildId(Handle<Node> node)
{
	// Fetch the name of the node -- if non is set, use the type name
	std::string name = node->getName().empty() ? node->type()->name : node->getName();

	// Try to fetch a Descriptor instance for the node
	Rooted<Descriptor> descriptor;
	if (node->isa(&RttiTypes::StructuredEntity)) {
		descriptor = node.cast<StructuredEntity>()->getDescriptor();
	} else if (node->isa(&RttiTypes::AnnotationEntity)) {
		descriptor = node.cast<AnnotationEntity>()->getDescriptor();
	}

	// If a Descriptor instance is found, preprend the path to the Descriptor
	// declaration
	if (descriptor != nullptr) {
		return Utils::join(descriptor->path(), "_") + "_" + name;
	}

	// Otherwise just return the name
	return name;
}

void UniqueIdTransformationImpl::transform(Handle<Document> doc)
{
	// Push the document root element onto the queue
	queue.push(doc->getRoot());

	// Push the fields of all annotations onto the queue
	for (Rooted<AnnotationEntity> annotation : doc->getAnnotations()) {
		processFields(annotation.get());
	}

	// Iterate over all queue elements and process the fields of those elements
	while (!queue.empty()) {
		processFields(queue.front().get());
		queue.pop();
	}

	// Generate ids for all referenced elements that do not yet have ids
	std::map<std::string, size_t> seqNos;
	for (Rooted<Node> node : nodesWithoutId) {
		// Generate a first id
		std::string id = buildId(node);

		// If the id name is not unique, append a sequence number
		if (ids.count(id) != 0) {
			std::string prefix = id;
			size_t seqNo = 0;

			// Find the last sequence number for this prefix
			auto it = seqNos.find(prefix);
			if (it != seqNos.end()) {
				seqNo = it->second;
			}

			// Increment the sequence number and make sure the resulting name
			// is unique
			do {
				seqNo++;
				id = prefix + "_" + std::to_string(seqNo);
			} while (ids.count(id) > 0);

			// Store the new sequence number in the seqNos map
			seqNos.emplace(prefix, seqNo);
		}

		// Remember the generated id
		ids.insert(id);

		// Store the resulting string as "id"
		node->storeData("id",
		                Variant::fromString(id).toManaged(node->getManager()));
	}
}
}

void UniqueIdTransformation::transform(Handle<Document> doc)
{
	UniqueIdTransformationImpl().transform(doc);
}
}