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
|
/*
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 <core/common/Exceptions.hpp>
#include <core/common/Utils.hpp>
#include <core/model/Typesystem.hpp>
#include "ParserScope.hpp"
namespace ousia {
/* Class ParserScopeBase */
ParserScopeBase::ParserScopeBase() {}
ParserScopeBase::ParserScopeBase(const NodeVector<Node> &nodes) : nodes(nodes)
{
}
Rooted<Node> ParserScopeBase::resolve(const Rtti &type,
const std::vector<std::string> &path,
Logger &logger)
{
// Go up the stack and try to resolve the
for (auto it = nodes.rbegin(); it != nodes.rend(); it++) {
std::vector<ResolutionResult> res = (*it)->resolve(type, path);
// Abort if the object could not be resolved
if (res.empty()) {
continue;
}
// Log an error if the object is not unique
if (res.size() > 1) {
logger.error(std::string("The reference \"") +
Utils::join(path, ".") + ("\" is ambigous!"));
logger.note("Referenced objects are:", SourceLocation{},
MessageMode::NO_CONTEXT);
for (const ResolutionResult &r : res) {
logger.note(Utils::join(r.path(), "."), *(r.node));
}
}
return res[0].node;
}
return nullptr;
}
/* Class DeferredResolution */
DeferredResolution::DeferredResolution(const NodeVector<Node> &nodes,
const std::vector<std::string> &path,
const Rtti &type,
ResolutionResultCallback resultCallback,
Handle<Node> owner)
: scope(nodes),
resultCallback(resultCallback),
path(path),
type(type),
owner(owner)
{
}
bool DeferredResolution::resolve(
const std::unordered_multiset<const Node *> &ignore, Logger &logger)
{
// Fork the logger to prevent error messages from being shown if we actively
// ignore the resolution result
LoggerFork loggerFork = logger.fork();
Rooted<Node> res = scope.resolve(type, path, loggerFork);
if (res != nullptr) {
if (!ignore.count(res.get())) {
loggerFork.commit();
try {
// Push the location onto the logger default location stack
GuardedLogger loggerGuard(logger, *owner);
resultCallback(res, owner, logger);
}
catch (LoggableException ex) {
logger.log(ex);
}
return true;
}
} else {
loggerFork.commit();
}
return false;
}
void DeferredResolution::fail(Logger &logger)
{
try {
resultCallback(nullptr, owner, logger);
}
catch (LoggableException ex) {
logger.log(ex);
}
}
/* Class ParserScope */
ParserScope::ParserScope(const NodeVector<Node> &nodes,
const std::vector<ParserFlagDescriptor> &flags)
: ParserScopeBase(nodes), flags(flags), topLevelDepth(nodes.size())
{
}
ParserScope::ParserScope() : topLevelDepth(0) {}
bool ParserScope::checkUnwound(Logger &logger) const
{
if (nodes.size() != topLevelDepth) {
logger.error("Not all open elements have been closed!",
SourceLocation{}, MessageMode::NO_CONTEXT);
logger.note("Still open elements are: ", SourceLocation{},
MessageMode::NO_CONTEXT);
for (size_t i = topLevelDepth + 1; i < nodes.size(); i++) {
logger.note(std::string("Element of interal type ") +
nodes[i]->type().name +
std::string(" defined here:"),
*nodes[i]);
}
return false;
}
return true;
}
ParserScope ParserScope::fork() { return ParserScope{nodes, flags}; }
bool ParserScope::join(const ParserScope &fork, Logger &logger)
{
// Make sure the fork has been unwound
if (!fork.checkUnwound(logger)) {
return false;
}
// Insert the deferred resolutions of the fork into our own deferred
// resolution list
deferred.insert(deferred.end(), fork.deferred.begin(), fork.deferred.end());
awaitingResolution.insert(fork.awaitingResolution.begin(),
fork.awaitingResolution.end());
return true;
}
void ParserScope::push(Handle<Node> node)
{
const size_t currentDepth = nodes.size();
if (currentDepth == topLevelDepth) {
topLevelNodes.push_back(node);
}
nodes.push_back(node);
}
void ParserScope::pop()
{
// Make sure pop is not called without an element on the stack
const size_t currentDepth = nodes.size();
if (currentDepth == topLevelDepth) {
throw LoggableException{"No element here to end!"};
}
// Remove all flags from the stack that were set for higher stack depths.
size_t newLen = 0;
for (ssize_t i = flags.size() - 1; i >= 0; i--) {
if (flags[i].depth < currentDepth) {
newLen = i + 1;
break;
}
}
flags.resize(newLen);
// Remove the element from the stack
nodes.pop_back();
}
NodeVector<Node> ParserScope::getTopLevelNodes() const { return topLevelNodes; }
Rooted<Node> ParserScope::getRoot() const { return nodes.front(); }
Rooted<Node> ParserScope::getLeaf() const { return nodes.back(); }
Rooted<Node> ParserScope::select(RttiSet types, int maxDepth)
{
ssize_t minDepth = 0;
if (maxDepth >= 0) {
minDepth = static_cast<ssize_t>(nodes.size()) - (maxDepth + 1);
}
for (ssize_t i = nodes.size() - 1; i >= minDepth; i--) {
if (nodes[i]->type().isOneOf(types)) {
return nodes[i];
}
}
return nullptr;
}
void ParserScope::setFlag(ParserFlag flag, bool value)
{
// Fetch the current stack depth
const size_t currentDepth = nodes.size();
// Try to change the value of the flag if it was already set on the same
// stack depth
for (auto it = flags.rbegin(); it != flags.rend(); it++) {
if (it->depth == currentDepth) {
if (it->flag == flag) {
it->value = value;
return;
}
} else {
break;
}
}
// Insert a new element into the flags list
flags.emplace_back(currentDepth, flag, value);
}
bool ParserScope::getFlag(ParserFlag flag)
{
for (auto it = flags.crbegin(); it != flags.crend(); it++) {
if (it->flag == flag) {
return it->value;
}
}
return false;
}
bool ParserScope::resolve(const Rtti &type,
const std::vector<std::string> &path,
Handle<Node> owner, Logger &logger,
ResolutionImposterCallback imposterCallback,
ResolutionResultCallback resultCallback)
{
if (!resolve(type, path, owner, logger, resultCallback)) {
resultCallback(imposterCallback(), owner, logger);
return false;
}
return true;
}
bool ParserScope::resolve(const Rtti &type,
const std::vector<std::string> &path,
Handle<Node> owner, Logger &logger,
ResolutionResultCallback resultCallback)
{
// Try to directly resolve the node
Rooted<Node> res = ParserScopeBase::resolve(type, path, logger);
if (res != nullptr && !awaitingResolution.count(res.get())) {
try {
resultCallback(res, owner, logger);
}
catch (LoggableException ex) {
logger.log(ex, *owner);
}
return true;
}
// Mark the owner as "awaitingResolution", preventing it from being returned
// as resolution result
if (owner != nullptr) {
awaitingResolution.insert(owner.get());
}
deferred.emplace_back(nodes, path, type, resultCallback, owner);
return false;
}
bool ParserScope::resolveType(const std::vector<std::string> &path,
Handle<Node> owner, Logger &logger,
ResolutionResultCallback resultCallback)
{
// Check whether the given path denotes an array, if yes recursively resolve
// the inner type and wrap it in an array type (this allows multi
// dimensional arrays).
if (!path.empty()) {
const std::string &last = path.back();
if (last.size() >= 2 && last.substr(last.size() - 2, 2) == "[]") {
// Type ends with "[]", remove this from the last element in the
// list
std::vector<std::string> p = path;
p.back() = p.back().substr(0, last.size() - 2);
// Resolve the rest of the type
return resolveType(p, owner, logger,
[resultCallback](Handle<Node> resolved,
Handle<Node> owner,
Logger &logger) {
if (resolved != nullptr) {
Rooted<ArrayType> arr{new ArrayType{resolved.cast<Type>()}};
resultCallback(arr, owner, logger);
} else {
resultCallback(nullptr, owner, logger);
}
});
}
}
// Requested type is not an array, call the usual resolve function
return resolve(RttiTypes::Type, path, owner, logger, resultCallback);
}
bool ParserScope::resolveType(const std::string &name, Handle<Node> owner,
Logger &logger,
ResolutionResultCallback resultCallback)
{
return resolveType(Utils::split(name, '.'), owner, logger, resultCallback);
}
bool ParserScope::resolveTypeWithValue(const std::vector<std::string> &path,
Handle<Node> owner, Variant &value,
Logger &logger,
ResolutionResultCallback resultCallback)
{
// Fork the parser scope -- constants need to be resolved in the same
// context as this resolve call
std::shared_ptr<ParserScope> scope = std::make_shared<ParserScope>(fork());
return resolveType(
path, owner, logger,
[=](Handle<Node> resolved, Handle<Node> owner, Logger &logger) mutable {
// Abort if the lookup failed
if (resolved == nullptr) {
resultCallback(resolved, owner, logger);
return;
}
// Fetch the type reference and the manager reference
Rooted<Type> type = resolved.cast<Type>();
Manager *mgr = &type->getManager();
// The type has been resolved, try to resolve magic values as
// constants and postpone calling the callback function until
// all magic values have been resolved
std::shared_ptr<bool> isAsync = std::make_shared<bool>(false);
std::shared_ptr<int> magicCount = std::make_shared<int>(0);
type->build(value, logger, [=](Variant &magicValue, bool isValid,
ManagedUid innerTypeUid) mutable {
// Fetch the inner type
Rooted<Type> innerType =
dynamic_cast<Type *>(mgr->getManaged(innerTypeUid));
if (innerType == nullptr) {
return;
}
// Fetch a pointer at the variant
Variant *magicValuePtr = &magicValue;
// Increment the number of encountered magic values
(*magicCount)++;
// Try to resolve the value as constant
std::string constantName = magicValue.asMagic();
scope->resolve<Constant>(constantName, owner, logger,
[=](Handle<Node> resolved,
Handle<Node> owner,
Logger &logger) mutable {
if (resolved != nullptr) {
// Make sure the constant is of the correct inner type
Rooted<Constant> constant = resolved.cast<Constant>();
Rooted<Type> constantType = constant->getType();
if (constantType != innerType) {
logger.error(
std::string("Expected value of type \"") +
innerType->getName() +
std::string("\" but found constant \"") +
constant->getName() +
std::string(" of type \"") +
constantType->getName() + "\" instead.",
*owner);
} else if (!isValid) {
logger.error("Identifier \"" + constantName +
"\" is not a valid " +
innerType->getName(),
*owner);
}
// Nevertheless, no matter what happened, set the value
// of the original magic variant to the given constant
*magicValuePtr = constant->getValue();
}
// Decrement the number of magic values, call the callback
// function if all magic values have been resolved
(*magicCount)--;
if ((*magicCount) == 0 && (*isAsync)) {
resultCallback(resolved, owner, logger);
}
});
});
// Now we are asynchronous
(*isAsync) = true;
// Directly call the callback function if there were no magic values
// involved
if ((*magicCount) == 0) {
resultCallback(resolved, owner, logger);
}
});
}
bool ParserScope::resolveTypeWithValue(const std::string &name,
Handle<Node> owner, Variant &value,
Logger &logger,
ResolutionResultCallback resultCallback)
{
return resolveTypeWithValue(Utils::split(name, '.'), owner, value, logger,
resultCallback);
}
bool ParserScope::performDeferredResolution(Logger &logger)
{
// Repeat the resolution process as long as something has changed in the
// last iteration (resolving a node may cause other nodes to be resolvable).
while (true) {
// Iterate over all deferred resolution processes,
bool hasChange = false;
for (auto it = deferred.begin(); it != deferred.end();) {
if (it->resolve(awaitingResolution, logger)) {
if (it->owner != nullptr) {
awaitingResolution.erase(it->owner.get());
}
it = deferred.erase(it);
hasChange = true;
} else {
it++;
}
}
// Abort if nothing has changed in the last iteration
if (!hasChange) {
// In a last step, clear the "awaitingResolution" list to allow
// cyclical dependencies to be resolved
if (!awaitingResolution.empty()) {
awaitingResolution.clear();
} else {
break;
}
}
}
// We were successful if there are no more deferred resolutions
if (deferred.empty()) {
return true;
}
// Output error messages for all elements for which resolution did not
// succeed.
for (auto &failed : deferred) {
failed.fail(logger);
logger.error(std::string("Could not resolve ") + failed.type.name +
std::string(" \"") + Utils::join(failed.path, ".") +
std::string("\""),
*failed.owner);
}
deferred.clear();
return false;
}
}
|