载入中...
搜索中...
未找到
DnutParser.cpp
浏览该文件的文档.
2
7
8#include <cstdio>
9#include <cstdlib>
10#include <stdexcept>
11#include <string>
12#include <utility>
13#include <vector>
14
15namespace eve::dialogue {
16namespace {
17
18class PoolParseError final : public std::runtime_error {
19public:
20 PoolParseError(const eve::dnut::DnutToken& token, std::string message)
21 : std::runtime_error(std::move(message)), line(token.line), column(token.column) {}
22
23 int line;
24 int column;
25};
26
27std::string floatToString(double value) {
28 char buffer[64];
29 std::snprintf(buffer, sizeof(buffer), "%g", value);
30 return buffer;
31}
32
33std::string scalarToString(const DataValue& value) {
34 if (value.isString()) return value.asString();
35 if (value.isInt64()) return std::to_string(value.asInt());
36 if (value.isDouble()) return floatToString(value.asDouble());
37 if (value.isBool()) return value.asBool() ? "true" : "false";
38 return {};
39}
40
41DataValue numberValue(const std::string& raw) {
42 if (raw.find_first_of(".eE") != std::string::npos)
43 return DataValue::number(std::strtod(raw.c_str(), nullptr));
44 return DataValue::integer(std::strtoll(raw.c_str(), nullptr, 10));
45}
46
47class PoolBlockParser {
48public:
49 PoolBlockParser(const std::vector<eve::dnut::DnutToken>& tokens, const eve::dnut::DnutBlock& block)
50 : tokens_(tokens), end_(block.endToken), index_(block.beginToken) {}
51
52 std::pair<std::string, DataValue> parse() {
53 expectKeyword("pool");
54 const std::string poolId = expectIdentifier("pool name");
55 long long noRepeat = -1;
56 while (isIdentifier("noRepeat")) {
57 advance();
58 expectPunct("=");
59 if (cur().kind != eve::dnut::DnutTokenKind::Number) fail("noRepeat must be a number");
60 noRepeat = std::strtoll(advance().text.c_str(), nullptr, 10);
61 }
62 expectPunct("{");
63
64 std::vector<DataValue> lines;
65 int lineIndex = 1;
66 while (!isPunct("}")) {
67 if (atEnd()) fail("unterminated pool block");
68 if (isIdentifier("pool")) fail("pool blocks cannot be nested");
69 if (isIdentifier("when")) {
70 advance();
71 DataValue condition = parseOr();
72 expectPunct("{");
73 while (!isPunct("}")) {
74 if (atEnd()) fail("unterminated when block");
75 lines.push_back(parseLine(poolId, lineIndex++, &condition));
76 }
77 advance();
78 } else {
79 lines.push_back(parseLine(poolId, lineIndex++, nullptr));
80 }
81 }
82 advance();
84 fields.emplace("lines", DataValue::array(std::move(lines)));
85 if (noRepeat >= 0) fields.emplace("noRepeat", DataValue::integer(noRepeat));
86 return {poolId, DataValue::object(std::move(fields))};
87 }
88
89private:
90 const eve::dnut::DnutToken& cur() const {
91 const std::size_t position = index_ < tokens_.size() ? index_ : tokens_.size() - 1;
92 return tokens_[position];
93 }
94 bool atEnd() const { return index_ >= end_ || cur().kind == eve::dnut::DnutTokenKind::EndOfFile; }
95 eve::dnut::DnutToken advance() {
96 const auto token = cur();
97 if (!atEnd()) ++index_;
98 return token;
99 }
100 bool isPunct(const char* text) const {
101 return cur().kind == eve::dnut::DnutTokenKind::Punctuator && cur().text == text;
102 }
103 bool isIdentifier(const char* text) const {
104 return cur().kind == eve::dnut::DnutTokenKind::Identifier && cur().text == text;
105 }
106 [[noreturn]] void fail(std::string message) const { throw PoolParseError(cur(), std::move(message)); }
107 void expectKeyword(const char* text) {
108 if (!isIdentifier(text)) fail("expected '" + std::string(text) + "'");
109 advance();
110 }
111 void expectPunct(const char* text) {
112 if (!isPunct(text)) fail("expected '" + std::string(text) + "'");
113 advance();
114 }
115 std::string expectIdentifier(const std::string& description) {
116 if (cur().kind != eve::dnut::DnutTokenKind::Identifier) fail("expected " + description);
117 return advance().text;
118 }
119
120 DataValue parseLiteral() {
121 if (isPunct("-")) {
122 advance();
123 if (cur().kind != eve::dnut::DnutTokenKind::Number) fail("'-' must be followed by a number");
124 DataValue value = numberValue(advance().text);
125 return value.isInt64() ? DataValue::integer(-value.asInt()) : DataValue::number(-value.asDouble());
126 }
127 if (cur().kind == eve::dnut::DnutTokenKind::String) return DataValue::string(advance().text);
128 if (cur().kind == eve::dnut::DnutTokenKind::Number) return numberValue(advance().text);
129 if (isIdentifier("true")) {
130 advance();
131 return DataValue::boolean(true);
132 }
133 if (isIdentifier("false")) {
134 advance();
135 return DataValue::boolean(false);
136 }
137 fail("expected a string, number, true, or false");
138 }
139
140 DataValue parseComparison() {
141 const std::string variable = expectIdentifier("a condition variable");
142 if (cur().kind != eve::dnut::DnutTokenKind::Punctuator) fail("expected a comparison operator");
143 const std::string operation = advance().text;
144 std::string mapped;
145 if (operation == "==")
146 mapped = "eq";
147 else if (operation == "!=")
148 mapped = "ne";
149 else if (operation == ">")
150 mapped = "gt";
151 else if (operation == "<")
152 mapped = "lt";
153 else if (operation == ">=")
154 mapped = "ge";
155 else if (operation == "<=")
156 mapped = "le";
157 else
158 fail("unsupported comparison operator '" + operation + "'");
159 return DataValue::object(
160 {{"var", DataValue::string(variable)}, {"op", DataValue::string(mapped)}, {"value", parseLiteral()}});
161 }
162
163 DataValue parseNot() {
164 if (isPunct("!")) {
165 advance();
166 return DataValue::object({{"not", parseNot()}});
167 }
168 if (isPunct("(")) {
169 advance();
170 DataValue value = parseOr();
171 expectPunct(")");
172 return value;
173 }
174 return parseComparison();
175 }
176
177 DataValue parseAnd() {
178 DataValue left = parseNot();
179 while (isPunct("&&")) {
180 advance();
181 DataValue right = parseNot();
182 if (DataValue* all = left.find("all"); all && all->isArray())
183 all->pushBack(std::move(right));
184 else
185 left = DataValue::object({{"all", DataValue::array({std::move(left), std::move(right)})}});
186 }
187 return left;
188 }
189
190 DataValue parseOr() {
191 DataValue left = parseAnd();
192 while (isPunct("||")) {
193 advance();
194 DataValue right = parseAnd();
195 if (DataValue* any = left.find("any"); any && any->isArray())
196 any->pushBack(std::move(right));
197 else
198 left = DataValue::object({{"any", DataValue::array({std::move(left), std::move(right)})}});
199 }
200 return left;
201 }
202
203 void parseAttributes(int sourceLine, DataValue::Object& out) {
204 while (!atEnd() && cur().line == sourceLine && !isPunct("}")) {
205 const std::string name = expectIdentifier("an attribute name");
206 if (name == "meta" && isPunct("(")) {
207 advance();
208 DataValue::Object metadata;
209 while (!isPunct(")")) {
210 const std::string key = expectIdentifier("a metadata key");
211 expectPunct("=");
212 DataValue value = parseLiteral();
213 const std::string scalar = scalarToString(value);
214 if (scalar.empty() && !value.isString()) fail("metadata values must be scalar");
215 metadata.emplace(key, DataValue::string(scalar));
216 if (isPunct(","))
217 advance();
218 else if (!isPunct(")"))
219 fail("expected ',' or ')' in metadata");
220 }
221 advance();
222 out.emplace("meta", DataValue::object(std::move(metadata)));
223 continue;
224 }
225 if (name == "tags") {
226 expectPunct("=");
227 expectPunct("[");
228 std::vector<DataValue> tags;
229 while (!isPunct("]")) {
230 if (cur().kind != eve::dnut::DnutTokenKind::String) fail("tag values must be quoted strings");
231 tags.push_back(DataValue::string(advance().text));
232 if (isPunct(","))
233 advance();
234 else if (!isPunct("]"))
235 fail("expected ',' or ']' in tags");
236 }
237 advance();
238 out.emplace("tags", DataValue::array(std::move(tags)));
239 continue;
240 }
241 expectPunct("=");
242 if (name != "weight" && name != "i18n" && name != "id") fail("unknown pool line attribute '" + name + "'");
243 out.emplace(name, parseLiteral());
244 }
245 }
246
247 DataValue parseLine(const std::string& poolId, int lineIndex, const DataValue* inheritedCondition) {
248 const int sourceLine = cur().line;
249 std::string speaker;
250 if (isPunct("-")) {
251 advance();
252 } else {
253 if (isIdentifier("when")) fail("when blocks cannot be nested");
254 speaker = expectIdentifier("a speaker or '-'");
255 expectPunct(":");
256 }
257 if (cur().kind != eve::dnut::DnutTokenKind::String) fail("expected quoted dialogue text");
259 fields.emplace("speaker", DataValue::string(speaker));
260 fields.emplace("text", DataValue::string(advance().text));
261 if (inheritedCondition) fields.emplace("when", *inheritedCondition);
262
264 parseAttributes(sourceLine, attributes);
265 const bool hasId = attributes.contains("id");
266 fields.merge(attributes);
267 if (!hasId) fields.emplace("id", DataValue::string(poolId + "." + std::to_string(lineIndex)));
268 return DataValue::object(std::move(fields));
269 }
270
271 const std::vector<eve::dnut::DnutToken>& tokens_;
272 std::size_t end_;
273 std::size_t index_;
274};
275
276void addError(std::vector<ConversationDiagnostic>& diagnostics, const std::string& path, int line, int column,
277 std::string message, std::string code = "DnutParseError") {
278 diagnostics.push_back({ConversationDiagnostic::Severity::Error,
279 path,
280 line,
281 path + ":" + std::to_string(line) + ": " + message,
282 std::move(code),
283 column,
284 {}});
285}
286
287bool validateEnvelope(const std::vector<eve::dnut::DnutToken>& tokens, const std::string& path,
288 std::vector<ConversationDiagnostic>& diagnostics, DnutDocument& document) {
289 if (tokens.size() < 5 || tokens[0].kind != eve::dnut::DnutTokenKind::Identifier || tokens[0].text != "schema" ||
291 tokens[2].text != "version" || tokens[3].kind != eve::dnut::DnutTokenKind::Number) {
292 const auto& token = tokens.front();
293 addError(diagnostics, path, token.line, token.column, "expected schema \"eve.dnut\" and version 1");
294 return false;
295 }
296 document.schema = tokens[1].text;
297 document.version = static_cast<int>(std::strtol(tokens[3].text.c_str(), nullptr, 10));
298 if (document.schema != "eve.dnut" || document.version != DnutDocument::CurrentVersion) {
299 addError(diagnostics, path, tokens[0].line, tokens[0].column, "unsupported dnut schema or version",
300 "UnsupportedSchemaVersion");
301 return false;
302 }
303 return true;
304}
305
306} // namespace
307
308eve::Result<DnutDocument> parseDnutDocument(const std::string& source, const std::string& path,
309 std::vector<ConversationDiagnostic>& diagnostics) {
310 DnutDocument document;
311 auto tokensResult = eve::dnut::lexDnut(source, path);
312 if (!tokensResult.ok()) {
313 const eve::Diagnostic* error = tokensResult.error();
314 int line = 1;
315 int column = 1;
316 if (error)
317 for (const auto& [key, value] : error->details()) {
318 if (key == "line") line = std::atoi(value.c_str());
319 if (key == "column") column = std::atoi(value.c_str());
320 }
321 addError(diagnostics, path, line, column, error ? error->message() : "could not lex dnut");
323 eve::DiagnosticCode::ParseError, diagnostics.back().message, path, {}, "dialogue.dnut.parse"));
324 }
325 std::vector<eve::dnut::DnutToken> tokens = std::move(tokensResult).takeValue();
326 if (!validateEnvelope(tokens, path, diagnostics, document))
328 eve::DiagnosticCode::UnknownVersion, diagnostics.back().message, path, {}, "dialogue.dnut.parse"));
329
330 auto blocksResult = eve::dnut::scanDnutBlocks(tokens, path);
331 if (!blocksResult.ok()) {
332 const eve::Diagnostic* error = blocksResult.error();
333 addError(diagnostics, path, 1, 1, error ? error->message() : "could not scan dnut blocks");
335 eve::DiagnosticCode::ParseError, diagnostics.back().message, path, {}, "dialogue.dnut.parse"));
336 }
337
338 DataValue::Object pools;
339 try {
340 for (const auto& block : blocksResult.value()) {
341 if (block.kind == "pool") {
342 auto [id, pool] = PoolBlockParser(tokens, block).parse();
343 if (pools.contains(id))
344 throw PoolParseError(tokens[block.beginToken], "duplicate pool id '" + id + "'");
345 pools.emplace(std::move(id), std::move(pool));
346 } else if (block.kind != "conversation" && block.kind != "story") {
347 throw PoolParseError(tokens[block.beginToken], "unknown top-level block '" + block.kind + "'");
348 }
349 }
350 } catch (const PoolParseError& error) {
351 addError(diagnostics, path, error.line, error.column, error.what());
353 eve::DiagnosticCode::ParseError, diagnostics.back().message, path, {}, "dialogue.dnut.parse"));
354 }
356 root.emplace("pools", std::move(pools));
357 document.poolRoot = DataValue::object(std::move(root));
358
360 auto registered = registerDialogueSequenceSteps(registry);
361 if (!registered.ok()) return eve::Result<DnutDocument>::failure(registered.status());
363 for (const auto& diagnostic : compiled.diagnostics)
364 diagnostics.push_back({diagnostic.severity == eve::dnut::DnutSeverity::Error
367 diagnostic.path,
368 diagnostic.line,
369 diagnostic.message,
370 "DnutParseError",
371 diagnostic.column,
372 {}});
373 if (compiled.hasErrors())
375 eve::DiagnosticCode::ParseError, diagnostics.back().message, path, {}, "dialogue.dnut.parse"));
376 document.conversations = std::move(compiled.assets);
377 return eve::Result<DnutDocument>::success(std::move(document));
378}
379
380} // namespace eve::dialogue
ActionParameterOperation operation
int root
Definition AnimSmr.cpp:119
Dialogue payload codecs for L1 sequence assets.
Shared top-level block discovery for `.dnut` dialects.
int sourceLine
eve::Value condition
Registry-driven compiler for the `.dnut` story dialect.
Shared lexer for every `.dnut` dialect.
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
double raw
std::string message
DiagnosticCode code
HexVec3 left
HexVec3 right
std::array< float, 3 > position
std::string id
const char * description
bool all
std::unordered_set< std::string > tags
OceanGpuFrameToken token
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
const eve::script::BindingContractRegistry & registry
Object::Ptr value
std::map< std::string, double > attributes
double number
unsigned line
std::string text
ScriptStructure out
std::string_view source
unsigned column
std::string kind
std::vector< Token > tokens
std::vector< std::string_view > lines
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
std::map< std::string, Value > Object
Definition Value.h:34
static Value number(double value)
Compatibility factory for a Double value.
Definition Value.h:117
static Value string(std::string value)
Compatibility factory for a string value.
Definition Value.h:121
static Value array(Array value)
Compatibility factory for an array value.
Definition Value.cpp:128
static Value integer(std::int64_t value)
Compatibility factory for an Int64 value.
Definition Value.h:115
static Value boolean(bool value)
Compatibility factory for a boolean value.
Definition Value.h:119
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
Canonical step vocabulary owner and runtime handler router.
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
eve::Result< DnutDocument > parseDnutDocument(const std::string &source, const std::string &path, std::vector< ConversationDiagnostic > &diagnostics)
Parse pools and conversations from one versioned dnut token stream.
eve::Value DataValue
Canonical data value used by dialogue pools, conditions and scripts.
Definition Dialogue.h:37
eve::Result< void > registerDialogueSequenceSteps(eve::dnut::StepKindRegistry &registry)
Register dialogue's line, choice, and command contracts and validators.
eve::Result< std::vector< DnutBlock > > scanDnutBlocks(const std::vector< DnutToken > &tokens, const std::string &path)
Discover balanced top-level dialect blocks in one lexed document.
eve::Result< std::vector< DnutToken > > lexDnut(std::string_view source, const std::string &path)
Lex one .dnut source buffer into owned tokens.
Definition DnutLexer.cpp:96
@ 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.
DnutCompileOutput compileDnutConversations(std::string_view source, const std::string &path, const StepKindRegistry &registry)
Compile legacy conversation blocks into canonical sequence assets.
ModelData parse(std::span< const uint8_t > bytes)
Parse.
UI-neutral syntax tree produced by the single dnut parser.
static constexpr int CurrentVersion
One top-level dialect block in a shared token buffer.
Owning outcome of compiling one .dnut document.
std::vector< DnutDiagnostic > diagnostics
One lexed token with its exact source anchor.
Definition DnutLexer.h:31