-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMetaCircularVirtualMachine.mpp
More file actions
642 lines (529 loc) · 25.4 KB
/
MetaCircularVirtualMachine.mpp
File metadata and controls
642 lines (529 loc) · 25.4 KB
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
export module CppUtils.Language.MetaCircularVirtualMachine;
import std;
import CppUtils.Container.MeshNetwork;
import CppUtils.Container.SafeShared;
import CppUtils.Execution.Event;
import CppUtils.Execution.ScopeGuard;
import CppUtils.Language.AST;
import CppUtils.String;
import CppUtils.Thread.SharedLocker;
import CppUtils.Thread.ThreadPool;
import CppUtils.Type.Specialization;
export namespace CppUtils::Language
{
namespace v1
{
struct MetaCircularVirtualMachine
{
using Cursor = String::Cursor<std::string_view>;
[[nodiscard]] inline constexpr auto exists(Type::Token instruction) const noexcept -> bool
{
const auto range = scopes | std::views::reverse;
auto it = std::ranges::find_if(range, [instruction](const auto scope) -> bool {
return scope.get().exists(instruction);
});
return it != std::ranges::end(range);
}
[[nodiscard]] inline constexpr auto operator()(
Cursor& cursor,
const ASTNode& instruction = ASTNode{Type::hash("main")})
-> std::expected<void, std::string_view>
{
using namespace String::Literals;
if (instruction.value == "call"_token)
{
if (std::empty(instruction.nodes)) [[unlikely]]
return std::unexpected{R"(Missing argument in the "call" instruction)"};
if (auto it = functions.find(instruction.nodes.front().value); it != std::cend(functions))
return it->second(cursor, instruction.nodes.front(), *this);
else [[unlikely]]
return std::unexpected{"Unknown function"};
}
auto grammar = [this, instruction]() -> std::reference_wrapper<ASTNode> {
const auto range = scopes | std::views::reverse;
auto it = std::ranges::find_if(range, [instruction](const auto scope) -> bool {
return scope.get().exists(instruction.value);
});
return it != std::ranges::end(range) ? *it : scopes.front();
}();
if (not grammar.get().exists(instruction.value)) [[unlikely]]
return std::unexpected{"Unknown lexeme"};
auto lexemes = std::ref(grammar.get()[instruction.value].nodes);
for (auto instructionPosition = 0uz; not exit and instructionPosition < std::size(lexemes.get()); ++instructionPosition)
{
const auto& lexeme = lexemes.get()[instructionPosition];
if (auto result = operator()(cursor, lexeme); not result) [[unlikely]]
return result;
if (not grammar.get().exists(instruction.value)) [[unlikely]]
return {};
lexemes = std::ref(grammar.get()[instruction.value].nodes);
}
exit = false;
return {};
}
[[nodiscard]] inline auto getScope() -> ASTNode&
{
return scopes.back().get();
}
std::unordered_map<Type::Token, std::function<std::expected<void, std::string_view>(Cursor&, const ASTNode&, MetaCircularVirtualMachine&)>> functions;
ASTNode rootAst = {0uz, {ASTNode{Type::hash("main")}}};
std::vector<std::reference_wrapper<ASTNode>> scopes = {std::ref(rootAst)};
bool exit = false;
};
}
inline namespace v2
{
struct MetaCircularVirtualMachine
{
using MeshNodePtr = Container::MeshNodePtr<Type::Token, Type::Token>;
struct StepResult final
{
std::expected<MeshNodePtr, std::string_view> value;
};
struct Environment final
{
Thread::SharedLocker<std::unordered_map<Type::Token, std::function<StepResult(MetaCircularVirtualMachine&, MeshNodePtr)>>> functions;
Thread::ThreadPool threadPool;
Thread::SharedLocker<std::unordered_map<std::size_t, std::shared_ptr<std::future<void>>>> threads;
Thread::SharedLocker<std::unordered_map<std::size_t, std::shared_ptr<Execution::Event>>> events;
std::atomic<std::size_t> nextThreadId{0};
std::atomic<std::size_t> nextEventId{0};
Thread::SharedLocker<std::string> firstErrorMessage;
std::atomic<bool> stopRequested{false};
};
MeshNodePtr context = MeshNodePtr::makeRoot(0uz);
std::shared_ptr<Environment> environment;
[[nodiscard]] static inline auto next(MeshNodePtr instruction) noexcept -> MeshNodePtr
{
using namespace String::Literals;
return instruction.at("next"_token)
.and_then([](auto branch) { return branch.front(); })
.value_or(MeshNodePtr{});
}
template<class T = MetaCircularVirtualMachine>
inline auto addFunction(Type::Token token, auto&& function) -> void
{
using namespace String::Literals;
auto functions = environment->functions.uniqueAccess();
if (not functions->contains(token))
{
functions.value()[token] = [function = std::forward<decltype(function)>(function)](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> StepResult {
return StepResult{function(static_cast<T&>(interpreter), instruction)};
};
if (not context.contains(token))
context[token] >> MeshNodePtr::make(token);
}
}
template<String::FixedString Name>
static auto arithmeticOperation(auto&& operation)
{
return [operation = std::forward<decltype(operation)>(operation)](MetaCircularVirtualMachine&, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
using namespace String::Literals;
static constexpr auto lhsError = Name + ": Missing lhs";
static constexpr auto rhsError = Name + ": Missing rhs";
static constexpr auto resultError = Name + ": Missing result";
auto lhs = instruction.at("lhs"_token).and_then([](auto branch) { return branch.front(); });
if (not lhs)
return std::unexpected{static_cast<std::string_view>(lhsError)};
auto rhs = instruction.at("rhs"_token).and_then([](auto branch) { return branch.front(); });
if (not rhs)
return std::unexpected{static_cast<std::string_view>(rhsError)};
auto result = instruction.at("result"_token).and_then([](auto branch) { return branch.front(); });
if (not result)
return std::unexpected{static_cast<std::string_view>(resultError)};
const auto lhsValue = lhs->getValue().value();
const auto rhsValue = rhs->getValue().value();
result->setValue(operation(lhsValue, rhsValue));
return next(instruction);
};
}
inline explicit MetaCircularVirtualMachine(std::shared_ptr<Environment> environment):
environment{std::move(environment)}
{}
inline MetaCircularVirtualMachine():
environment{std::make_shared<Environment>()}
{
using namespace std::literals;
using namespace String::Literals;
environment->threadPool.setOnError([environment = environment](std::exception_ptr exceptionPointer) {
if (environment->stopRequested.exchange(true))
return;
try
{
if (exceptionPointer)
std::rethrow_exception(exceptionPointer);
}
catch (const std::exception& exception)
{
environment->firstErrorMessage.uniqueAccess().value() = exception.what();
}
catch (...)
{
environment->firstErrorMessage.uniqueAccess().value() = "Unknown background error";
}
});
addFunction("set"_token, [](MetaCircularVirtualMachine&, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto targetNode = instruction.at("target"_token).and_then([](auto branch) { return branch.front(); });
if (not targetNode)
return std::unexpected{"set: Missing target"sv};
auto valueNode = instruction.at("value"_token).and_then([](auto branch) { return branch.front(); });
if (not valueNode)
return std::unexpected{"set: Missing value"sv};
auto value = valueNode->getValue().value();
targetNode->setValue(value);
return next(instruction);
});
addFunction("size"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto sourceNode = instruction.at("source"_token).and_then([](auto branch) { return branch.front(); }).value_or(interpreter.context);
auto branchNameNode = instruction.at("branch"_token).and_then([](auto branch) { return branch.front(); });
if (not branchNameNode)
return std::unexpected{"size: Missing branch name"sv};
auto sizeNode = instruction.at("size"_token).and_then([](auto branch) { return branch.front(); });
if (not sizeNode)
return std::unexpected{"size: Missing result node"sv};
auto branchName = branchNameNode->getValue().value();
sizeNode->setValue(std::size(sourceNode[branchName]));
return next(instruction);
});
addFunction("create"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto valueNode = instruction.at("value"_token).and_then([](auto branch) { return branch.front(); });
const auto value = valueNode ? valueNode->getValue().value() : 0uz;
auto destinationNode = instruction.at("destination"_token).and_then([](auto branch) { return branch.front(); }).value_or(interpreter.context);
auto branchPath = instruction.at("branch"_token);
if (not branchPath or std::empty(branchPath.value()))
return std::unexpected{"create: Missing branch path"sv};
auto currentDestination = destinationNode;
const auto& pathNodes = branchPath.value();
for (auto i = 0uz; i < std::size(pathNodes) - 1; ++i)
{
auto token = pathNodes[i]->getValue().value();
if (auto nextDestination = currentDestination[token].front(); not nextDestination)
{
auto intermediateNode = MeshNodePtr::make(0uz);
currentDestination[token] >> intermediateNode;
currentDestination = intermediateNode;
}
else
currentDestination = nextDestination.value();
}
auto finalKey = pathNodes.back()->getValue().value();
currentDestination[finalKey] >> MeshNodePtr::make(value);
return next(instruction);
});
addFunction("reference"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto sourceNode = instruction.at("sourceBase"_token).and_then([](auto branch) { return branch.front(); }).value_or(interpreter.context);
auto targetNode = sourceNode;
if (auto targetBranch = instruction.at("sourcePath"_token))
{
for (auto node : targetBranch.value())
{
auto token = node.getValue().value();
auto nextNode = targetNode.at(token).and_then([](auto branch) { return branch.front(); });
if (not nextNode)
return std::unexpected{"reference: Source path not found"sv};
targetNode = nextNode.value();
}
}
auto destinationNode = instruction.at("destinationBase"_token).and_then([](auto branch) { return branch.front(); }).value_or(interpreter.context);
auto branchPath = instruction.at("destinationPath"_token);
if (not branchPath or std::empty(branchPath.value()))
return std::unexpected{"reference: Missing destination path"sv};
auto currentDestination = destinationNode;
const auto& pathNodes = branchPath.value();
for (auto i = 0uz; i < std::size(pathNodes) - 1; ++i)
{
auto token = pathNodes[i]->getValue().value();
if (auto nextDestination = currentDestination[token].front(); not nextDestination)
{
auto newNode = MeshNodePtr::make(0uz);
currentDestination[token] >> newNode;
currentDestination = newNode;
}
else
currentDestination = nextDestination.value();
}
auto finalKey = pathNodes.back()->getValue().value();
currentDestination[finalKey] >> targetNode;
return next(instruction);
});
addFunction("jump"_token, [](MetaCircularVirtualMachine&, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto conditionNode = instruction.at("condition"_token).and_then([](auto branch) { return branch.front(); });
if (not conditionNode or conditionNode->getValue().value() != 0)
return instruction.at("next"_token).and_then([](auto branch) { return branch.front(); }).value_or(MeshNodePtr{});
return instruction.at("else"_token)
.and_then([](auto branch) { return branch.front(); })
.value_or(MeshNodePtr{});
});
addFunction("return"_token, [](MetaCircularVirtualMachine&, MeshNodePtr) -> std::expected<MeshNodePtr, std::string_view> {
return MeshNodePtr{};
});
addFunction("link"_token, [](MetaCircularVirtualMachine&, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
return instruction.at("source"_token).and_then([&](auto sources) {
return instruction.at("branch"_token).and_then([&](auto branches) -> std::expected<void, std::string_view> {
for (auto branch : branches)
if (auto result = instruction.at("target"_token).and_then([&](auto targets) -> std::expected<void, std::string_view> {
for (auto source : sources)
for (auto target : targets)
source[branch.getValue().value()] >> target;
return {};
});
not result)
return result;
return {};
});
}).transform([&instruction] { return next(instruction); });
});
addFunction("unlink"_token, [](MetaCircularVirtualMachine&, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
return instruction.at("source"_token).and_then([&](auto sources) {
return instruction.at("branch"_token).and_then([&](auto branches) -> std::expected<void, std::string_view> {
auto targetsBranch = instruction.at("target"_token);
for (auto source : sources)
for (const auto& branch : branches)
if (auto branchNodes = source[branch.getValue().value()]; targetsBranch)
for (const auto& target : targetsBranch.value())
branchNodes - target;
else
branchNodes.clear();
return {};
});
}).transform([&instruction] { return next(instruction); });
});
addFunction("call"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto function = instruction.at("function"_token).and_then([](auto branch) { return branch.front(); });
if (not function)
return std::unexpected{"call: No function"sv};
auto context = MeshNodePtr::makeRoot("context"_token);
context["scope"_token] >> interpreter.context;
if (auto inputs = instruction.at("input"_token))
for (auto input : inputs.value())
context["input"_token] >> input;
if (auto outputs = instruction.at("output"_token))
for (auto output : outputs.value())
context["output"_token] >> output;
auto previousContext = std::exchange(interpreter.context, std::move(context));
auto result = interpreter(function.value());
interpreter.context = std::move(previousContext);
if (not result)
return std::unexpected{result.error()};
return next(instruction);
});
addFunction("=="_token, [](MetaCircularVirtualMachine&, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
return instruction.at("lhs"_token).and_then([](auto branch) { return branch.front(); }).and_then([&](MeshNodePtr lhs) {
return instruction.at("rhs"_token).and_then([](auto branch) { return branch.front(); }).and_then([&, lhs](MeshNodePtr rhs) {
return instruction.at("result"_token).and_then([](auto branch) { return branch.front(); }).and_then([&, lhs, rhs](MeshNodePtr result) -> std::expected<void, std::string_view> {
const auto lhsValue = lhs.getValue().value();
const auto rhsValue = rhs.getValue().value();
result.setValue(lhsValue == rhsValue);
return {};
});
});
}).transform([&instruction] { return next(instruction); });
});
addFunction("not"_token, [](MetaCircularVirtualMachine&, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
return instruction.at("value"_token).and_then([](auto branch) { return branch.front(); }).and_then([&](MeshNodePtr value) -> std::expected<void, std::string_view> {
const auto result = not static_cast<bool>(value.getValue().value());
value.setValue(result);
return {};
}).transform([&instruction] { return next(instruction); });
});
addFunction("+"_token, arithmeticOperation<"+">(std::plus<>{}));
addFunction("-"_token, arithmeticOperation<"-">(std::minus<>{}));
addFunction("*"_token, arithmeticOperation<"*">(std::multiplies<>{}));
addFunction("/"_token, arithmeticOperation<"/">(std::divides<>{}));
addFunction("%"_token, arithmeticOperation<"%">(std::modulus<>{}));
addFunction("<"_token, arithmeticOperation<"<">(std::less<>{}));
addFunction("thread"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto targetInstruction = instruction.at("target"_token).and_then([](auto branch) { return branch.front(); });
if (not targetInstruction)
return std::unexpected{"thread: Missing target"sv};
auto threadContext = MeshNodePtr::makeRoot("threadContext"_token);
threadContext["scope"_token] >> interpreter.context;
if (auto inputs = instruction.at("input"_token))
for (auto input : inputs.value())
threadContext["input"_token] >> input;
if (auto outputs = instruction.at("output"_token))
for (auto output : outputs.value())
threadContext["output"_token] >> output;
auto task = [target = targetInstruction.value(),
threadContext = std::move(threadContext),
environment = interpreter.environment,
&interpreter]() mutable {
auto threadInterpreter = interpreter.makeExecutionContext(std::move(environment));
threadInterpreter->context = std::move(threadContext);
if (auto result = (*threadInterpreter)(target); not result)
throw std::runtime_error{std::string{result.error()}};
};
auto threadId = interpreter.environment->nextThreadId++;
interpreter.environment->threads.uniqueAccess().value()[threadId] = std::make_shared<std::future<void>>(interpreter.environment->threadPool.call(task));
auto threadIdNode = instruction.at("threadId"_token).and_then([](auto branch) { return branch.front(); });
if (not threadIdNode)
return std::unexpected{"thread: Missing result node"sv};
threadIdNode->setValue(threadId);
return next(instruction);
});
addFunction("join"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto threadIdNode = instruction.at("thread"_token).and_then([](auto branch) { return branch.front(); });
if (not threadIdNode)
return std::unexpected{"join: Missing thread id"sv};
auto threadId = threadIdNode->getValue().value();
auto future = [&]() -> std::shared_ptr<std::future<void>> {
auto threads = interpreter.environment->threads.sharedAccess();
if (auto it = threads.value().find(threadId); it != std::end(threads.value()))
return it->second;
return nullptr;
}();
if (future and future->valid())
future->wait();
{
auto threads = interpreter.environment->threads.uniqueAccess();
threads.value().erase(threadId);
}
return next(instruction);
});
addFunction("detach"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto threadIdNode = instruction.at("thread"_token).and_then([](auto branch) { return branch.front(); });
if (not threadIdNode)
return std::unexpected{"detach: Missing thread id"sv};
auto threadId = threadIdNode->getValue().value();
auto threads = interpreter.environment->threads.uniqueAccess();
threads.value().erase(threadId);
return next(instruction);
});
addFunction("event"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto eventIdNode = instruction.at("eventId"_token).and_then([](auto branch) { return branch.front(); });
if (not eventIdNode)
return std::unexpected{"event: Missing result node"sv};
auto eventId = interpreter.environment->nextEventId++;
interpreter.environment->events.uniqueAccess().value()[eventId] = std::make_shared<Execution::Event>();
eventIdNode->setValue(eventId);
return next(instruction);
});
addFunction("wait"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto idNode = instruction.at("event"_token).and_then([](auto branch) { return branch.front(); });
if (not idNode)
return std::unexpected{"wait: Missing event id"sv};
auto id = idNode->getValue().value();
auto event = [&]() -> std::shared_ptr<Execution::Event> {
auto events = interpreter.environment->events.sharedAccess();
if (auto it = events.value().find(id); it != std::end(events.value()))
return it->second;
return nullptr;
}();
if (event)
event->wait();
return next(instruction);
});
addFunction("notify"_token, [](MetaCircularVirtualMachine& interpreter, MeshNodePtr instruction) -> std::expected<MeshNodePtr, std::string_view> {
auto idNode = instruction.at("event"_token).and_then([](auto branch) { return branch.front(); });
if (not idNode)
return std::unexpected{"notify: Missing event id"sv};
auto id = idNode->getValue().value();
auto event = [&]() -> std::shared_ptr<Execution::Event> {
auto events = interpreter.environment->events.sharedAccess();
if (auto it = events.value().find(id); it != std::end(events.value()))
return it->second;
return nullptr;
}();
if (event)
event->notify();
return next(instruction);
});
}
virtual ~MetaCircularVirtualMachine() = default;
[[nodiscard]] virtual inline auto makeExecutionContext(std::shared_ptr<Environment> environment) const -> std::unique_ptr<MetaCircularVirtualMachine>
{
return std::make_unique<MetaCircularVirtualMachine>(std::move(environment));
}
private:
[[nodiscard]] inline auto resultWithBackgroundErrors(std::expected<void, std::string_view> result) const -> std::expected<void, std::string_view>
{
if (not environment->stopRequested.load())
return result;
if (auto firstError = environment->firstErrorMessage.sharedAccess(); not std::empty(firstError.value()))
return std::unexpected{std::string_view{firstError.value()}};
return result;
}
public:
[[nodiscard]] inline auto reportError(std::string_view message) const -> std::expected<void, std::string_view>
{
if (not environment->stopRequested.exchange(true))
environment->firstErrorMessage.uniqueAccess().value() = message;
return resultWithBackgroundErrors(std::unexpected{message});
}
[[nodiscard]] inline auto get(Type::Token token) -> std::expected<MeshNodePtr, std::string_view>
{
using namespace std::literals;
using namespace String::Literals;
for (auto scope = context;
scope;
scope = scope.at("scope"_token).and_then([](auto stack) { return stack.front(); }).value_or(MeshNodePtr{}))
if (auto node = scope.at(token).and_then([](auto stack) { return stack.back(); }))
return node;
return std::unexpected{"Unknown node"sv};
}
[[nodiscard]] inline auto resolve(Type::Token token) -> std::expected<MeshNodePtr, std::string_view>
{
using namespace std::literals;
auto currentToken = token;
auto lastResult = std::expected<MeshNodePtr, std::string_view>{std::unexpect, "Unknown node"sv};
while (true)
{
auto found = get(currentToken);
if (not found)
return lastResult;
if (lastResult and found.value() == lastResult.value())
return found;
const auto nextToken = found->getValue().value();
if (nextToken == currentToken)
return found;
lastResult = found;
currentToken = nextToken;
}
}
[[nodiscard]] inline auto operator()(MeshNodePtr instruction) -> std::expected<void, std::string_view>
{
using namespace String::Literals;
while (instruction and not environment->stopRequested.load())
{
auto result = resolve(instruction.getValue().value());
auto definition = result ? result.value() : instruction;
auto definitionToken = definition.getValue().value();
if (auto function = [&]() -> std::function<StepResult(MetaCircularVirtualMachine&, MeshNodePtr)> {
auto functions = environment->functions.sharedAccess();
if (auto functionIt = functions.value().find(definitionToken); functionIt != std::cend(functions.value()))
return functionIt->second;
return nullptr;
}())
if (auto result = function(*this, instruction).value)
instruction = result.value();
else
return reportError(result.error());
else if (auto branch = definition.at("next"_token))
instruction = branch.value().front().value_or(MeshNodePtr{});
else
break;
}
return resultWithBackgroundErrors({});
}
[[nodiscard]] inline auto operator()(Type::Token token) -> std::expected<void, std::string_view>
{
using namespace std::literals;
if (auto instruction = get(token))
return (*this)(instruction.value());
if (auto function = [&]() -> std::function<StepResult(MetaCircularVirtualMachine&, MeshNodePtr)> {
auto functions = environment->functions.sharedAccess();
if (auto functionIt = functions.value().find(token); functionIt != std::cend(functions.value()))
return functionIt->second;
return nullptr;
}())
{
if (auto result = function(*this, MeshNodePtr::make(token)).value)
return resultWithBackgroundErrors((*this)(result.value()));
else
return reportError(result.error());
}
return reportError("Unknown function"sv);
}
};
}
}