8#include <unordered_set>
23struct CompiledStatement {
24 enum class Kind { Step, If, Choice, Loop, Parallel, Break, Continue, Label, Jump };
36 std::vector<std::vector<CompiledStatement>>
lanes;
44struct CompiledOption {
47 std::vector<CompiledStatement>
body;
62bool isComparisonOperator(
const std::string&
text) {
66const char* comparisonSpelling(
const std::string&
text) {
67 if (
text ==
"==")
return "eq";
68 if (
text ==
"!=")
return "ne";
69 if (
text ==
">")
return "gt";
70 if (
text ==
"<")
return "lt";
71 if (
text ==
">=")
return "ge";
77 StoryParser(std::vector<DnutToken>
tokens, std::string
path,
const StepKindRegistry&
registry,
83 if (isIdentifier(
"story") || isIdentifier(
"common")) {
86 }
catch (
const ParseAbort&) {
96 const DnutToken& cur()
const {
return tokens_[index_]; }
97 const DnutToken& peek(std::size_t
offset)
const {
103 DnutToken advance() {
104 const DnutToken
token = tokens_[index_];
105 if (!atEnd()) ++index_;
108 bool isPunct(
const std::string&
text)
const {
111 bool isIdentifier(
const std::string&
text)
const {
116 output_.diagnostics.push_back(
118 errorLine_ =
token.line;
123 void expectPunct(
const std::string&
text) {
124 if (!isPunct(
text)) errorHere(
"expected '" +
text +
"'");
127 std::string expectIdentifier(
const std::string& what) {
129 return advance().text;
131 std::string nextNodeId() {
return "n" + std::to_string(++nodeCounter_); }
139 if (isPunct(
"}"))
return;
144 }
else if (isPunct(
"}")) {
145 if (
depth == 0)
return;
154 void skipForeignBlock() {
157 if (
depth == 0 && (isIdentifier(
"story") || isIdentifier(
"common")))
return;
160 }
else if (isPunct(
"}")) {
168 const bool isCommon = isIdentifier(
"common");
170 invalidStep_ =
false;
171 const std::string
id = expectIdentifier(isCommon ?
"a common-event id" :
"a story id");
172 bool repeatable = isCommon;
175 const std::string modifier = cur().text;
176 if (modifier ==
"repeatable") {
181 if (modifier ==
"version") {
185 version =
static_cast<int>(std::strtol(advance().
text.c_str(),
nullptr, 10));
186 if (
version < 1) errorHere(
"version must be positive");
189 errorHere(std::string(
"unknown ") + (isCommon ?
"common" :
"story") +
" modifier '" + modifier +
"'");
192 std::vector<CompiledStatement>
body;
193 parseBlockBody(
body);
198 asset.repeatable = repeatable;
199 const std::string endId = nextNodeId();
200 SequenceNode endNode;
202 endNode.type =
"end";
204 pendingJumps_.clear();
206 const std::string entry = emitBlock(
body, endId, asset);
207 asset.entry = entry.empty() ? endId : entry;
208 asset.nodes.push_back(std::move(endNode));
211 bool publishable = !invalidStep_;
212 if (
auto validated = asset.validate(); !validated.ok()) {
213 const auto* diagnostic = validated.error();
214 output_.diagnostics.push_back(
215 {
DnutSeverity::Error, path_, 0, 0, diagnostic ? diagnostic->message() :
"invalid sequence asset"});
218 if (!publishedIds_.insert(asset.id).second) {
219 output_.diagnostics.push_back(
221 std::string(
"duplicate ") + (isCommon ?
"common" :
"story") +
" id '" + asset.id +
"'"});
224 if (publishable) output_.assets.push_back(std::move(asset));
227 void parseBlockBody(std::vector<CompiledStatement>&
out) {
230 if (atEnd()) errorHere(
"unterminated block");
236 out.push_back(parseStatement());
237 }
catch (
const ParseAbort&) {
243 CompiledStatement parseStatement() {
245 const std::string keyword = cur().text;
246 if (keyword ==
"if")
return parseIf();
247 if (keyword ==
"choice")
return parseChoice();
248 if (keyword ==
"wait")
return parseWait();
249 if (keyword ==
"call" || keyword ==
"common")
return parseCall();
250 if (keyword ==
"loop")
return parseLoop();
251 if (keyword ==
"break")
return parseBreakOrContinue(
true);
252 if (keyword ==
"continue")
return parseBreakOrContinue(
false);
253 if (keyword ==
"label")
return parseLabel();
254 if (keyword ==
"jump")
return parseJump();
255 if (keyword ==
"parallel")
return parseParallel();
256 if (keyword ==
"end") {
258 CompiledStatement statement;
259 statement.type =
"end";
260 statement.nodeId = nextNodeId();
266 CompiledStatement parseStep() {
267 const DnutToken
start = cur();
268 CompiledStatement statement;
269 statement.type = advance().text;
270 statement.nodeId = nextNodeId();
272 peek(1).
text ==
"=") {
273 const std::string
field = advance().text;
275 statement.payload.set(field, parseValue());
281 SequenceNode candidate;
282 candidate.id = statement.nodeId;
283 candidate.type = statement.type;
284 candidate.payload = statement.payload;
285 if (
auto validated = registry_.validate(candidate); !validated.ok()) {
286 const auto* diagnostic = validated.error();
288 diagnostic ? diagnostic->message() :
"invalid step"});
294 CompiledStatement parseWait() {
296 CompiledStatement statement;
297 statement.type =
"wait";
298 statement.nodeId = nextNodeId();
300 statement.payload.set(
"duration", numberValue(advance().
text));
303 if (isIdentifier(
"duration")) {
306 statement.payload.set(
"duration", parseValue());
309 errorHere(
"wait requires a duration");
312 CompiledStatement parseCall() {
314 CompiledStatement statement;
315 statement.type =
"call";
316 statement.nodeId = nextNodeId();
317 statement.payload.set(
"target",
eve::Value::string(expectIdentifier(
"a called sequence id")));
321 CompiledStatement parseLoop() {
322 const DnutToken
start = cur();
324 CompiledStatement statement;
325 statement.kind = CompiledStatement::Kind::Loop;
326 statement.nodeId = nextNodeId();
327 statement.sourceLine =
start.line;
328 statement.sourceColumn =
start.column;
329 statement.name =
"forever";
330 if (isIdentifier(
"while")) {
332 statement.name =
"while";
333 statement.condition = parseCondition();
334 }
else if (isIdentifier(
"times")) {
337 statement.name =
"times";
338 statement.payload.set(
"count", parseValue());
340 parseBlockBody(statement.thenBody);
344 CompiledStatement parseBreakOrContinue(
bool isBreak) {
345 const DnutToken
start = cur();
347 CompiledStatement statement;
348 statement.kind = isBreak ? CompiledStatement::Kind::Break : CompiledStatement::Kind::Continue;
349 statement.type = isBreak ?
"break" :
"continue";
350 statement.nodeId = nextNodeId();
351 statement.sourceLine =
start.line;
352 statement.sourceColumn =
start.column;
356 CompiledStatement parseLabel() {
357 const DnutToken
start = cur();
359 CompiledStatement statement;
360 statement.kind = CompiledStatement::Kind::Label;
361 statement.type =
"label";
362 statement.nodeId = nextNodeId();
363 statement.name = expectIdentifier(
"a label name");
364 statement.sourceLine =
start.line;
365 statement.sourceColumn =
start.column;
369 CompiledStatement parseJump() {
370 const DnutToken
start = cur();
372 CompiledStatement statement;
373 statement.kind = CompiledStatement::Kind::Jump;
374 statement.type =
"jump";
375 statement.nodeId = nextNodeId();
376 statement.name = expectIdentifier(
"a label name");
377 statement.sourceLine =
start.line;
378 statement.sourceColumn =
start.column;
382 CompiledStatement parseParallel() {
383 const DnutToken
start = cur();
385 CompiledStatement statement;
386 statement.kind = CompiledStatement::Kind::Parallel;
387 statement.type =
"parallel";
388 statement.nodeId = nextNodeId();
389 statement.sourceLine =
start.line;
390 statement.sourceColumn =
start.column;
392 while (!isPunct(
"}")) {
393 if (atEnd()) errorHere(
"unterminated parallel block");
394 if (!isIdentifier(
"lane")) errorHere(
"parallel accepts only lane blocks");
396 std::vector<CompiledStatement> lane;
397 parseBlockBody(lane);
398 statement.lanes.push_back(std::move(lane));
401 if (statement.lanes.size() < 2) errorHere(
"parallel requires at least two lanes");
405 CompiledStatement parseIf() {
407 CompiledStatement statement;
408 statement.kind = CompiledStatement::Kind::If;
409 statement.nodeId = nextNodeId();
410 statement.condition = parseCondition();
411 parseBlockBody(statement.thenBody);
412 if (isIdentifier(
"else")) {
414 parseBlockBody(statement.elseBody);
419 CompiledStatement parseChoice() {
421 CompiledStatement statement;
422 statement.kind = CompiledStatement::Kind::Choice;
423 statement.nodeId = nextNodeId();
425 while (!isPunct(
"}")) {
426 if (atEnd()) errorHere(
"unterminated choice block");
427 if (!isIdentifier(
"option")) errorHere(
"choice accepts only option statements");
429 CompiledOption option;
430 option.nodeId = nextNodeId();
432 option.label = advance().text;
433 if (isIdentifier(
"when")) {
435 option.condition = parseCondition();
437 parseBlockBody(option.body);
438 statement.options.push_back(std::move(option));
441 if (statement.options.empty()) errorHere(
"choice requires at least one option");
445 eve::Value parseCondition() {
return parseOr(); }
449 while (isPunct(
"||")) {
453 object !=
nullptr &&
object->contains(
"any") &&
object->at(
"any").isArray()) {
454 object->at(
"any").pushBack(std::move(
right));
458 operands.emplace_back(std::move(
left));
459 operands.emplace_back(std::move(
right));
461 combined.emplace(
"any", std::move(operands));
470 while (isPunct(
"&&")) {
474 object !=
nullptr &&
object->contains(
"all") &&
object->at(
"all").isArray()) {
475 object->at(
"all").pushBack(std::move(
right));
479 operands.emplace_back(std::move(
left));
480 operands.emplace_back(std::move(
right));
482 combined.emplace(
"all", std::move(operands));
500 return parseComparison();
505 const std::string variable = advance().text;
507 errorHere(
"condition requires a comparison operator (== != > < >= <=)");
508 const std::string
operation = advance().text;
512 {
"value", std::move(expected)}});
523 switch (cur().
kind) {
527 if (isIdentifier(
"true")) {
531 if (isIdentifier(
"false")) {
536 default: errorHere(
"expected a literal value");
break;
540 std::string emitBlock(
const std::vector<CompiledStatement>&
statements,
const std::string& next,
541 SequenceAsset& asset) {
542 std::string continuation =
next;
544 continuation = emitStatement(*it, continuation, asset);
548 std::string emitStatement(
const CompiledStatement& statement,
const std::string& next, SequenceAsset& asset) {
549 if (statement.kind == CompiledStatement::Kind::Step) {
551 node.id = statement.nodeId;
552 node.type = statement.type;
554 node.payload = statement.payload;
555 asset.nodes.push_back(std::move(
node));
556 return statement.nodeId;
558 if (statement.kind == CompiledStatement::Kind::If) {
559 const std::string thenEntry = emitBlock(statement.thenBody, next, asset);
560 const std::string elseEntry = emitBlock(statement.elseBody, next, asset);
562 node.id = statement.nodeId;
563 node.type =
"branch";
564 node.next = elseEntry;
566 route.condition = statement.condition;
567 route.target = thenEntry;
568 node.routes.push_back(std::move(route));
569 asset.nodes.push_back(std::move(
node));
570 return statement.nodeId;
572 if (statement.kind == CompiledStatement::Kind::Choice) {
574 node.id = statement.nodeId;
575 node.type =
"choice";
577 for (
const auto& option : statement.
options) {
579 route.label = option.label;
580 route.condition = option.condition;
581 route.target = emitBlock(option.body, next, asset);
582 node.routes.push_back(std::move(route));
584 asset.nodes.push_back(std::move(
node));
585 return statement.nodeId;
587 if (statement.kind == CompiledStatement::Kind::Loop) {
588 loopStack_.push_back({statement.nodeId,
next});
589 const std::string bodyEntry = emitBlock(statement.thenBody, statement.nodeId, asset);
590 loopStack_.pop_back();
592 node.id = statement.nodeId;
596 if (statement.name ==
"times") {
600 if (statement.name ==
"while") route.condition = statement.condition;
601 route.target = bodyEntry;
602 node.routes.push_back(std::move(route));
603 asset.nodes.push_back(std::move(
node));
604 return statement.nodeId;
606 if (statement.kind == CompiledStatement::Kind::Break ||
607 statement.kind == CompiledStatement::Kind::Continue) {
608 if (loopStack_.empty()) {
610 statement.sourceColumn,
611 statement.type +
" is not inside a loop"});
615 node.id = statement.nodeId;
616 node.type = statement.type;
617 node.next = loopStack_.empty()
619 : (statement.kind == CompiledStatement::Kind::Break ? loopStack_.back().afterNodeId
620 : loopStack_.back().loopNodeId);
621 asset.nodes.push_back(std::move(
node));
622 return statement.nodeId;
624 if (statement.kind == CompiledStatement::Kind::Label) {
625 if (!labels_.emplace(statement.name, statement.nodeId).second) {
627 statement.sourceColumn,
"duplicate label '" + statement.name +
"'"});
631 node.id = statement.nodeId;
635 asset.nodes.push_back(std::move(
node));
636 return statement.nodeId;
638 if (statement.kind == CompiledStatement::Kind::Jump) {
640 node.id = statement.nodeId;
644 asset.nodes.push_back(std::move(
node));
645 pendingJumps_.push_back({statement.nodeId, statement.name, statement.sourceLine, statement.sourceColumn});
646 return statement.nodeId;
648 if (statement.kind == CompiledStatement::Kind::Parallel) {
649 const std::string joinId = nextNodeId();
653 asset.nodes.push_back(std::move(join));
656 node.id = statement.nodeId;
657 node.type =
"parallel";
660 for (
const auto& lane : statement.
lanes) {
662 route.target = emitBlock(lane, joinId, asset);
663 node.routes.push_back(std::move(route));
665 asset.nodes.push_back(std::move(
node));
666 return statement.nodeId;
668 output_.diagnostics.push_back(
674 void resolveJumps(SequenceAsset& asset) {
675 for (
const auto& jump : pendingJumps_) {
676 auto found = labels_.find(jump.name);
677 if (
found == labels_.end()) {
679 "jump targets unknown label '" + jump.name +
"'"});
683 SequenceNode*
node =
nullptr;
684 for (
auto& candidate : asset.
nodes) {
685 if (candidate.id == jump.nodeId) {
703 std::vector<DnutToken> tokens_;
704 std::size_t index_ = 0;
706 const StepKindRegistry& registry_;
707 DnutCompileOutput& output_;
708 int nodeCounter_ = 0;
711 bool invalidStep_ =
false;
712 std::unordered_set<std::string> publishedIds_;
713 std::vector<LoopEmitFrame> loopStack_;
717 std::map<std::string, std::string> labels_;
718 std::vector<PendingJump> pendingJumps_;
728 const auto* diagnostic =
tokens.error();
730 diagnostic ? diagnostic->message() :
"could not lex the document"});
ActionParameterOperation operation
std::vector< CompiledStatement > thenBody
std::vector< std::vector< CompiledStatement > > lanes
Parallel lane bodies (parallel { lane {…} lane {…} }).
std::vector< CompiledStatement > elseBody
Registry-driven compiler for the `.dnut` story dialect.
Shared lexer for every `.dnut` dialect.
std::array< float, 3 > position
const eve::script::BindingContractRegistry & registry
std::vector< Token > tokens
const SquirrelValueOptions & options
The canonical owning dynamic value used by data-facing protocols.
bool isInt64() const noexcept
Return true when this value is an Int64.
std::map< std::string, Value > Object
double asDouble() const
Return the Double payload; the caller must have checked the kind.
static Value number(double value)
Compatibility factory for a Double value.
static Value string(std::string value)
Compatibility factory for a string value.
std::int64_t asInt() const
Return the Int64 payload; the caller must have checked the kind.
std::vector< Value > Array
static Value integer(std::int64_t value)
Compatibility factory for an Int64 value.
static Value boolean(bool value)
Compatibility factory for a boolean value.
Canonical step vocabulary owner and runtime handler router.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
EVENGINE_API_PLATFORM bool hasErrors(const std::vector< DnutDiagnostic > &diagnostics)
Return whether any diagnostic is an error.
eve::Result< std::vector< DnutToken > > lexDnut(std::string_view source, const std::string &path)
Lex one .dnut source buffer into owned tokens.
DnutCompileOutput compileDnut(std::string_view source, const std::string &path, const StepKindRegistry ®istry)
Compile every story block of one .dnut document.
@ String
Quoted string with escapes already resolved.
@ Identifier
Bare word: keyword, field name, identifier, or bare enum value.
@ Punctuator
One- or two-character punctuator such as {, =, ==, ->.
@ EndOfFile
Synthetic terminal token; always the last element.
@ Number
Unsigned numeric literal; sign handling belongs to the parser.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Result< VehiclePhysicsStatus > synchronize(VehicleEntity &vehicle, std::shared_ptr< VehicleWheelRuntime > &runtime)
Owning outcome of compiling one .dnut document.
std::vector< DnutDiagnostic > diagnostics
bool hasErrors() const
Return whether any collected diagnostic has error severity.