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
|
/*
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 <algorithm>
#include <core/common/RttiBuilder.hpp>
#include <core/common/Utils.hpp>
#include <core/common/VariantReader.hpp>
#include <core/model/Document.hpp>
#include <core/model/Domain.hpp>
#include <core/model/Project.hpp>
#include <core/model/Typesystem.hpp>
#include <core/parser/ParserScope.hpp>
#include <core/parser/ParserContext.hpp>
#include "DocumentHandler.hpp"
#include "State.hpp"
namespace ousia {
namespace parser_stack {
/* DocumentHandler */
bool DocumentHandler::start(Variant::mapType &args)
{
Rooted<Document> document =
context().getProject()->createDocument(args["name"].asString());
document->setLocation(location());
scope().push(document);
scope().setFlag(ParserFlag::POST_HEAD, false);
return true;
}
void DocumentHandler::end() { scope().pop(); }
/* DocumentChildHandler */
void DocumentChildHandler::preamble(Handle<Node> parentNode,
std::string &fieldName,
DocumentEntity *&parent, bool &inField)
{
// Check if the parent in the structure tree was an explicit field
// reference.
inField = parentNode->isa(&RttiTypes::DocumentField);
if (inField) {
fieldName = parentNode->getName();
parentNode = scope().selectOrThrow(
{&RttiTypes::StructuredEntity, &RttiTypes::AnnotationEntity});
} else {
// If it wasn't an explicit reference, we use the default field.
fieldName = DEFAULT_FIELD_NAME;
}
// Reference the parent entity explicitly.
parent = nullptr;
if (parentNode->isa(&RttiTypes::StructuredEntity)) {
parent = static_cast<DocumentEntity *>(
parentNode.cast<StructuredEntity>().get());
} else if (parentNode->isa(&RttiTypes::AnnotationEntity)) {
parent = static_cast<DocumentEntity *>(
parentNode.cast<AnnotationEntity>().get());
}
}
static void createPath(const NodeVector<Node> &path, DocumentEntity *&parent,
size_t p0 = 1)
{
// TODO (@benjamin): These should be pushed onto the scope and poped once
// the scope is left. Otherwise stuff may not be correclty resolved.
size_t S = path.size();
for (size_t p = p0; p < S; p = p + 2) {
parent = static_cast<DocumentEntity *>(
parent->createChildStructuredEntity(
path[p].cast<StructuredClass>(), Variant::mapType{},
path[p - 1]->getName(), "").get());
}
}
static void createPath(const std::string &firstFieldName,
const NodeVector<Node> &path, DocumentEntity *&parent)
{
// Add the first element
parent = static_cast<DocumentEntity *>(
parent->createChildStructuredEntity(path[0].cast<StructuredClass>(),
Variant::mapType{}, firstFieldName,
"").get());
createPath(path, parent, 2);
}
bool DocumentChildHandler::start(Variant::mapType &args)
{
scope().setFlag(ParserFlag::POST_HEAD, true);
Rooted<Node> parentNode = scope().selectOrThrow(
{&RttiTypes::Document, &RttiTypes::StructuredEntity,
&RttiTypes::AnnotationEntity, &RttiTypes::DocumentField});
std::string fieldName;
DocumentEntity *parent;
bool inField;
preamble(parentNode, fieldName, parent, inField);
// Try to find a FieldDescriptor for the given tag if we are not in a
// field already. This does _not_ try to construct transparent paths
// in between.
if (!inField && parent != nullptr &&
parent->getDescriptor()->hasField(name())) {
Rooted<DocumentField> field{
new DocumentField(parentNode->getManager(), name(), parentNode)};
field->setLocation(location());
scope().push(field);
return true;
}
// Otherwise create a new StructuredEntity
// TODO: Consider Anchors and AnnotationEntities
Rooted<StructuredClass> strct =
scope().resolve<StructuredClass>(Utils::split(name(), ':'), logger());
if (strct == nullptr) {
// if we could not resolve the name, throw an exception.
throw LoggableException(
std::string("\"") + name() + "\" could not be resolved.",
location());
}
std::string name;
auto it = args.find("name");
if (it != args.end()) {
name = it->second.asString();
args.erase(it);
}
Rooted<StructuredEntity> entity;
if (parentNode->isa(&RttiTypes::Document)) {
entity = parentNode.cast<Document>()->createRootStructuredEntity(
strct, args, name);
} else {
// calculate a path if transparent entities are needed in between.
std::string lastFieldName = fieldName;
if (inField) {
Rooted<FieldDescriptor> field =
parent->getDescriptor()->getFieldDescriptor(fieldName);
auto pathRes =
field.cast<FieldDescriptor>()->pathTo(strct, logger());
if (!pathRes.second) {
throw LoggableException(
std::string("An instance of \"") + strct->getName() +
"\" is not allowed as child of field \"" + fieldName +
"\"",
location());
}
if (!pathRes.first.empty()) {
createPath(fieldName, pathRes.first, parent);
lastFieldName = DEFAULT_FIELD_NAME;
}
} else {
auto path = parent->getDescriptor()->pathTo(strct, logger());
if (path.empty()) {
throw LoggableException(
std::string("An instance of \"") + strct->getName() +
"\" is not allowed as child of an instance of \"" +
parent->getDescriptor()->getName() + "\"",
location());
}
// create all transparent entities until the last field.
createPath(path, parent);
if (path.size() > 1) {
lastFieldName = DEFAULT_FIELD_NAME;
}
}
// create the entity for the new element at last.
entity = parent->createChildStructuredEntity(strct, args, lastFieldName,
name);
}
entity->setLocation(location());
scope().push(entity);
return true;
}
void DocumentChildHandler::end() { scope().pop(); }
bool DocumentChildHandler::convertData(Handle<FieldDescriptor> field,
Variant &data, Logger &logger)
{
bool valid = true;
Rooted<Type> type = field->getPrimitiveType();
// If the content is supposed to be of type string, we only need to check
// for "magic" values -- otherwise just call the "parseGenericString"
// function on the string data
if (type->isa(&RttiTypes::StringType)) {
const std::string &str = data.asString();
// TODO: Referencing constants with "." separator should also work
if (Utils::isIdentifier(str)) {
data.markAsMagic();
}
} else {
// Parse the string as generic string, assign the result
auto res = VariantReader::parseGenericString(
data.asString(), logger, data.getLocation().getSourceId(),
data.getLocation().getStart());
data = res.second;
}
// Now try to resolve the value for the primitive type
return valid && scope().resolveValue(data, type, logger);
}
bool DocumentChildHandler::data(Variant &data)
{
Rooted<Node> parentNode = scope().selectOrThrow(
{&RttiTypes::StructuredEntity, &RttiTypes::AnnotationEntity,
&RttiTypes::DocumentField});
std::string fieldName;
DocumentEntity *strctParent;
bool inField;
preamble(parentNode, fieldName, strctParent, inField);
Rooted<Descriptor> desc = strctParent->getDescriptor();
// The parent from which we need to connect to the primitive content.
Rooted<Node> parentClass;
// We distinguish two cases here: One for fields that are given.
if (inField) {
// Retrieve the actual FieldDescriptor
Rooted<FieldDescriptor> field = desc->getFieldDescriptor(fieldName);
if (field == nullptr) {
logger().error(
std::string("Can't handle data because no field with name \"") +
fieldName + "\" exists in descriptor\"" + desc->getName() +
"\".",
location());
return false;
}
// If it is a primitive field directly, try to parse the content.
if (field->isPrimitive()) {
// Add it as primitive content.
if (!convertData(field, data, logger())) {
return false;
}
strctParent->createChildDocumentPrimitive(data, fieldName);
return true;
}
// If it is not primitive we need to connect via transparent elements
// and default fields.
parentClass = field;
} else {
// In case of default fields we need to construct via default fields
// and maybe transparent elements.
parentClass = desc;
}
// Search through all permitted default fields of the parent class that
// allow primitive content at this point and could be constructed via
// transparent intermediate entities.
// Retrieve all default fields at this point, either from the field
// descriptor or the structured class
NodeVector<FieldDescriptor> defaultFields;
if (inField) {
defaultFields = parentClass.cast<FieldDescriptor>()->getDefaultFields();
} else {
defaultFields = parentClass.cast<StructuredClass>()->getDefaultFields();
}
// Try to parse the data using the type specified by the respective field.
// If that does not work we proceed to the next possible field.
std::vector<LoggerFork> forks;
for (auto field : defaultFields) {
// Then try to parse the content using the type specification.
forks.emplace_back(logger().fork());
if (!convertData(field, data, forks.back())) {
continue;
}
// The conversion worked, commit any possible warnings
forks.back().commit();
// Construct the necessary path
if (inField) {
NodeVector<Node> path =
parentClass.cast<FieldDescriptor>()->pathTo(field, logger());
createPath(fieldName, path, strctParent);
} else {
auto pathRes = desc->pathTo(field, logger());
assert(pathRes.second);
createPath(pathRes.first, strctParent);
}
// Then create the primitive element
strctParent->createChildDocumentPrimitive(data);
return true;
}
// No field was found that might take the data -- dump the error messages
// from the loggers
logger().error("Could not read data with any of the possible fields:",
SourceLocation{}, MessageMode::NO_CONTEXT);
size_t f = 0;
for (auto field : defaultFields) {
logger().note(std::string("Field ") + Utils::join(field->path(), ".") +
std::string(":"),
SourceLocation{}, MessageMode::NO_CONTEXT);
forks[f].commit();
f++;
}
return false;
}
namespace States {
const State Document = StateBuilder()
.parent(&None)
.createdNodeType(&RttiTypes::Document)
.elementHandler(DocumentHandler::create)
.arguments({Argument::String("name", "")});
const State DocumentChild = StateBuilder()
.parents({&Document, &DocumentChild})
.createdNodeTypes({&RttiTypes::StructureNode,
&RttiTypes::AnnotationEntity,
&RttiTypes::DocumentField})
.elementHandler(DocumentChildHandler::create);
}
}
namespace RttiTypes {
const Rtti DocumentField = RttiBuilder<ousia::parser_stack::DocumentField>(
"DocumentField").parent(&Node);
}
}
|