载入中...
搜索中...
未找到
SettlementRules.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <cctype>
5#include <cmath>
6#include <cstdlib>
7#include <iomanip>
8#include <limits>
9#include <memory>
10#include <optional>
11#include <set>
12#include <sstream>
13#include <string_view>
14#include <utility>
15
16namespace eve::settlement {
17namespace {
18
19constexpr std::size_t kMaximumConditionSource = 4096;
20constexpr std::size_t kMaximumConditionNodes = 256;
21constexpr std::size_t kMaximumConditionDepth = 32;
22constexpr std::size_t kMaximumEvaluationSteps = 1024;
23
24enum class ExpressionType : std::uint8_t { Unknown, Boolean, Number, String };
25
26enum class ExpressionKind : std::uint8_t {
27 Literal,
28 Field,
29 HasTag,
30 Not,
31 Negate,
32 Add,
35 Divide,
36 Equal,
38 Less,
40 Greater,
42 And,
43 Or,
44 Minimum,
45 Maximum,
46 Clamp,
48};
49
50struct ExpressionNode {
51 ExpressionKind kind = ExpressionKind::Literal;
52 ExpressionType type = ExpressionType::Boolean;
53 std::uint16_t left = 0;
54 std::uint16_t right = 0;
55 std::uint16_t third = 0;
57 std::string name;
58};
59
60struct ExpressionProgram {
61 std::vector<ExpressionNode> nodes;
62 std::uint16_t root = 0;
63};
64
65enum class TokenKind : std::uint8_t { End, Identifier, Number, String, Symbol };
66
67struct Token {
68 TokenKind kind = TokenKind::End;
69 std::string text;
70 std::size_t line = 1;
71 std::size_t column = 1;
72};
73
74const char* typeName(ExpressionType type) noexcept {
75 switch (type) {
76 case ExpressionType::Unknown: return "Unknown";
77 case ExpressionType::Boolean: return "Boolean";
78 case ExpressionType::Number: return "Number";
79 case ExpressionType::String: return "String";
80 }
81 return "Unknown";
82}
83
84eve::Diagnostic expressionDiagnostic(eve::DiagnosticCode code, std::string message, std::string path,
85 const Token& token, std::string expected = {}, std::string actual = {}) {
86 eve::DiagnosticDetails details{{"line", std::to_string(token.line)}, {"column", std::to_string(token.column)}};
87 if (!expected.empty()) details.emplace_back("expected", std::move(expected));
88 if (!actual.empty()) details.emplace_back("actual", std::move(actual));
89 return eve::Diagnostic::error(code, std::move(message), std::move(path), details, "settlement.condition");
90}
91
92eve::Result<std::vector<Token>> tokenize(std::string_view source, const std::string& path) {
93 std::vector<Token> tokens;
94 std::size_t offset = 0;
95 std::size_t line = 1;
96 std::size_t column = 1;
97 auto advance = [&](char value) {
98 ++offset;
99 if (value == '\n') {
100 ++line;
101 column = 1;
102 } else {
103 ++column;
104 }
105 };
106 while (offset < source.size()) {
107 const char value = source[offset];
108 if (value == ' ' || value == '\t' || value == '\r' || value == '\n') {
109 advance(value);
110 continue;
111 }
112 Token token;
113 token.line = line;
114 token.column = column;
115 if (std::isalpha(static_cast<unsigned char>(value)) || value == '_') {
116 token.kind = TokenKind::Identifier;
117 while (offset < source.size()) {
118 const char next = source[offset];
119 if (!std::isalnum(static_cast<unsigned char>(next)) && next != '_' && next != '.') break;
120 token.text.push_back(next);
121 advance(next);
122 }
123 tokens.push_back(std::move(token));
124 continue;
125 }
126 if (std::isdigit(static_cast<unsigned char>(value)) ||
127 (value == '.' && offset + 1 < source.size() &&
128 std::isdigit(static_cast<unsigned char>(source[offset + 1])))) {
129 token.kind = TokenKind::Number;
130 const std::size_t begin = offset;
131 char* end = nullptr;
132 const std::string remaining(source.substr(begin));
133 const double number = std::strtod(remaining.c_str(), &end);
134 if (end == remaining.c_str() || !std::isfinite(number))
135 return eve::Result<std::vector<Token>>::failure(
136 expressionDiagnostic(eve::DiagnosticCode::ParseError, "condition contains an invalid number", path,
137 token, "finite Number", token.text));
138 const auto length = static_cast<std::size_t>(end - remaining.c_str());
139 token.text.assign(source.substr(begin, length));
140 for (std::size_t index = 0; index < length; ++index) advance(source[begin + index]);
141 tokens.push_back(std::move(token));
142 continue;
143 }
144 if (value == '"') {
145 token.kind = TokenKind::String;
146 advance(value);
147 bool closed = false;
148 while (offset < source.size()) {
149 const char next = source[offset];
150 if (next == '"') {
151 advance(next);
152 closed = true;
153 break;
154 }
155 if (next == '\n' || next == '\r') break;
156 if (next == '\\') {
157 advance(next);
158 if (offset >= source.size()) break;
159 const char escaped = source[offset];
160 switch (escaped) {
161 case 'n': token.text.push_back('\n'); break;
162 case 'r': token.text.push_back('\r'); break;
163 case 't': token.text.push_back('\t'); break;
164 case '"': token.text.push_back('"'); break;
165 case '\\': token.text.push_back('\\'); break;
166 default:
167 return eve::Result<std::vector<Token>>::failure(expressionDiagnostic(
168 eve::DiagnosticCode::ParseError, "condition contains an unsupported string escape",
169 path, token, "supported escape", std::string("\\") + escaped));
170 }
171 advance(escaped);
172 continue;
173 }
174 token.text.push_back(next);
175 advance(next);
176 }
177 if (!closed)
178 return eve::Result<std::vector<Token>>::failure(
179 expressionDiagnostic(eve::DiagnosticCode::ParseError, "condition string is not terminated", path,
180 token, "closing quote"));
181 tokens.push_back(std::move(token));
182 continue;
183 }
184 token.kind = TokenKind::Symbol;
185 token.text.push_back(value);
186 if (offset + 1 < source.size()) {
187 const std::string_view pair = source.substr(offset, 2);
188 if (pair == "&&" || pair == "||" || pair == "==" || pair == "!=" || pair == "<=" || pair == ">=") {
189 token.text.push_back(source[offset + 1]);
190 advance(value);
191 advance(source[offset]);
192 tokens.push_back(std::move(token));
193 continue;
194 }
195 }
196 if (std::string_view("!<>+-*/(),").find(value) == std::string_view::npos)
197 return eve::Result<std::vector<Token>>::failure(
198 expressionDiagnostic(eve::DiagnosticCode::ParseError, "condition contains an unsupported character",
199 path, token, "condition operator", token.text));
200 advance(value);
201 tokens.push_back(std::move(token));
202 }
203 tokens.push_back(Token{TokenKind::End, {}, line, column});
204 return eve::Result<std::vector<Token>>::success(std::move(tokens));
205}
206
207class ExpressionParser {
208public:
209 ExpressionParser(std::vector<Token> tokens, std::string path)
210 : tokens_(std::move(tokens)), path_(std::move(path)) {}
211
213 const auto root = parseOr(0);
214 if (error_) return eve::Result<ExpressionProgram>::failure(std::move(*error_));
215 if (current().kind != TokenKind::End) {
216 fail("condition contains trailing input", "end of expression", current().text);
217 return eve::Result<ExpressionProgram>::failure(std::move(*error_));
218 }
219 if (nodes_[root].type != ExpressionType::Boolean) {
220 fail("condition root must be Boolean", "Boolean", typeName(nodes_[root].type));
221 return eve::Result<ExpressionProgram>::failure(std::move(*error_));
222 }
223 return eve::Result<ExpressionProgram>::success(ExpressionProgram{std::move(nodes_), root});
224 }
225
226private:
227 const Token& current() const noexcept { return tokens_[position_]; }
228
229 bool accept(std::string_view text) {
230 if (current().text != text) return false;
231 ++position_;
232 return true;
233 }
234
235 void expect(std::string_view text) {
236 if (!accept(text)) fail("condition expected '" + std::string(text) + "'", std::string(text), current().text);
237 }
238
239 void fail(std::string message, std::string expected = {}, std::string actual = {}) {
240 if (!error_)
241 error_ = expressionDiagnostic(eve::DiagnosticCode::ParseError, std::move(message), path_, current(),
242 std::move(expected), std::move(actual));
243 }
244
245 std::uint16_t add(ExpressionNode node) {
246 if (nodes_.size() >= kMaximumConditionNodes) {
247 fail("condition exceeds the node limit", std::to_string(kMaximumConditionNodes));
248 return 0;
249 }
250 nodes_.push_back(std::move(node));
251 return static_cast<std::uint16_t>(nodes_.size() - 1);
252 }
253
254 std::uint16_t binary(ExpressionKind kind, ExpressionType result, std::uint16_t left, std::uint16_t right,
255 ExpressionType operand, const Token& operation) {
256 if (error_) return 0;
257 bind(left, operand);
258 bind(right, operand);
259 if (nodes_[left].type != operand || nodes_[right].type != operand) {
260 error_ = expressionDiagnostic(
261 eve::DiagnosticCode::TypeMismatch, "condition operator has incompatible operands", path_, operation,
262 typeName(operand), std::string(typeName(nodes_[left].type)) + "," + typeName(nodes_[right].type));
263 return 0;
264 }
265 return add(ExpressionNode{kind, result, left, right});
266 }
267
268 void bind(std::uint16_t index, ExpressionType type) {
269 if (nodes_[index].type == ExpressionType::Unknown && nodes_[index].kind == ExpressionKind::Field)
270 nodes_[index].type = type;
271 }
272
273 std::uint16_t parseOr(std::size_t depth) {
274 auto left = parseAnd(depth + 1);
275 while (!error_ && current().text == "||") {
276 const auto operation = current();
277 ++position_;
278 left = binary(ExpressionKind::Or, ExpressionType::Boolean, left, parseAnd(depth + 1),
279 ExpressionType::Boolean, operation);
280 }
281 return left;
282 }
283
284 std::uint16_t parseAnd(std::size_t depth) {
285 auto left = parseEquality(depth + 1);
286 while (!error_ && current().text == "&&") {
287 const auto operation = current();
288 ++position_;
289 left = binary(ExpressionKind::And, ExpressionType::Boolean, left, parseEquality(depth + 1),
290 ExpressionType::Boolean, operation);
291 }
292 return left;
293 }
294
295 std::uint16_t parseEquality(std::size_t depth) {
296 auto left = parseComparison(depth + 1);
297 while (!error_ && (current().text == "==" || current().text == "!=")) {
298 const auto operation = current();
299 ++position_;
300 const auto right = parseComparison(depth + 1);
301 if (!error_ && nodes_[left].type == ExpressionType::Unknown &&
302 nodes_[right].type != ExpressionType::Unknown)
303 bind(left, nodes_[right].type);
304 if (!error_ && nodes_[right].type == ExpressionType::Unknown &&
305 nodes_[left].type != ExpressionType::Unknown)
306 bind(right, nodes_[left].type);
307 if (!error_ && nodes_[left].type == ExpressionType::Unknown &&
308 nodes_[right].type == ExpressionType::Unknown) {
309 error_ = expressionDiagnostic(eve::DiagnosticCode::TypeMismatch,
310 "condition cannot infer either equality operand type", path_, operation,
311 "one typed operand", "Unknown,Unknown");
312 return 0;
313 }
314 if (!error_ && nodes_[left].type != nodes_[right].type) {
315 error_ = expressionDiagnostic(eve::DiagnosticCode::TypeMismatch,
316 "condition equality operands must have the same type", path_, operation,
317 typeName(nodes_[left].type), typeName(nodes_[right].type));
318 return 0;
319 }
320 left = add(ExpressionNode{operation.text == "==" ? ExpressionKind::Equal : ExpressionKind::NotEqual,
321 ExpressionType::Boolean, left, right});
322 }
323 return left;
324 }
325
326 std::uint16_t parseComparison(std::size_t depth) {
327 auto left = parseAdditive(depth + 1);
328 while (!error_ &&
329 (current().text == "<" || current().text == "<=" || current().text == ">" || current().text == ">=")) {
330 const auto operation = current();
331 ++position_;
332 const auto right = parseAdditive(depth + 1);
333 ExpressionKind kind = ExpressionKind::Less;
334 if (operation.text == "<=")
335 kind = ExpressionKind::LessEqual;
336 else if (operation.text == ">")
337 kind = ExpressionKind::Greater;
338 else if (operation.text == ">=")
339 kind = ExpressionKind::GreaterEqual;
340 left = binary(kind, ExpressionType::Boolean, left, right, ExpressionType::Number, operation);
341 }
342 return left;
343 }
344
345 std::uint16_t parseAdditive(std::size_t depth) {
346 auto left = parseMultiplicative(depth + 1);
347 while (!error_ && (current().text == "+" || current().text == "-")) {
348 const auto operation = current();
349 ++position_;
350 left =
351 binary(operation.text == "+" ? ExpressionKind::Add : ExpressionKind::Subtract, ExpressionType::Number,
352 left, parseMultiplicative(depth + 1), ExpressionType::Number, operation);
353 }
354 return left;
355 }
356
357 std::uint16_t parseMultiplicative(std::size_t depth) {
358 auto left = parseUnary(depth + 1);
359 while (!error_ && (current().text == "*" || current().text == "/")) {
360 const auto operation = current();
361 ++position_;
362 const auto right = parseUnary(depth + 1);
363 if (!error_ && operation.text == "/" && nodes_[right].kind == ExpressionKind::Literal) {
364 if (const auto* value = nodes_[right].literal.getIf<double>(); value && *value == 0.0) {
365 error_ = expressionDiagnostic(eve::DiagnosticCode::InvalidArgument,
366 "condition contains constant division by zero", path_, operation,
367 "non-zero Number", "0");
368 return 0;
369 }
370 }
371 left = binary(operation.text == "*" ? ExpressionKind::Multiply : ExpressionKind::Divide,
372 ExpressionType::Number, left, right, ExpressionType::Number, operation);
373 }
374 return left;
375 }
376
377 std::uint16_t parseUnary(std::size_t depth) {
378 if (depth > kMaximumConditionDepth) {
379 fail("condition exceeds the nesting limit", std::to_string(kMaximumConditionDepth));
380 return 0;
381 }
382 if (current().text == "!" || current().text == "-") {
383 const auto operation = current();
384 ++position_;
385 const auto child = parseUnary(depth + 1);
386 const auto expected = operation.text == "!" ? ExpressionType::Boolean : ExpressionType::Number;
387 if (!error_) bind(child, expected);
388 if (!error_ && nodes_[child].type != expected) {
389 error_ = expressionDiagnostic(eve::DiagnosticCode::TypeMismatch,
390 "condition unary operator has an incompatible operand", path_, operation,
391 typeName(expected), typeName(nodes_[child].type));
392 return 0;
393 }
394 return add(
395 ExpressionNode{operation.text == "!" ? ExpressionKind::Not : ExpressionKind::Negate, expected, child});
396 }
397 return parsePrimary(depth + 1);
398 }
399
400 std::uint16_t parseFunction(std::string name, const Token& token, std::size_t depth) {
401 expect("(");
402 std::vector<std::uint16_t> arguments;
403 if (!error_ && current().text != ")") {
404 do {
405 arguments.push_back(parseOr(depth + 1));
406 } while (!error_ && accept(","));
407 }
408 expect(")");
409 if (error_) return 0;
410 if (name == "has_tag") {
411 if (arguments.size() != 1 || nodes_[arguments[0]].kind != ExpressionKind::Literal ||
412 nodes_[arguments[0]].type != ExpressionType::String) {
413 error_ = expressionDiagnostic(eve::DiagnosticCode::TypeMismatch, "has_tag expects one string literal",
414 path_, token, "has_tag(String literal)");
415 return 0;
416 }
417 ExpressionNode node{ExpressionKind::HasTag, ExpressionType::Boolean};
418 node.name = *nodes_[arguments[0]].literal.getIf<std::string>();
419 return add(std::move(node));
420 }
421 const std::size_t arity = name == "clamp" ? 3 : (name == "abs" ? 1 : 2);
422 if ((name != "min" && name != "max" && name != "clamp" && name != "abs") || arguments.size() != arity) {
423 error_ = expressionDiagnostic(eve::DiagnosticCode::ParseError,
424 "condition uses an unknown function or invalid arity", path_, token,
425 "min/max(2), clamp(3), abs(1), or has_tag(1)", name);
426 return 0;
427 }
428 for (const auto argument : arguments) {
429 bind(argument, ExpressionType::Number);
430 if (nodes_[argument].type != ExpressionType::Number) {
431 error_ =
432 expressionDiagnostic(eve::DiagnosticCode::TypeMismatch, "numeric function received a non-number",
433 path_, token, "Number", typeName(nodes_[argument].type));
434 return 0;
435 }
436 }
437 ExpressionNode node;
438 node.type = ExpressionType::Number;
439 node.left = arguments[0];
440 node.right = arguments.size() > 1 ? arguments[1] : 0;
441 node.third = arguments.size() > 2 ? arguments[2] : 0;
442 if (name == "min")
443 node.kind = ExpressionKind::Minimum;
444 else if (name == "max")
445 node.kind = ExpressionKind::Maximum;
446 else if (name == "clamp")
447 node.kind = ExpressionKind::Clamp;
448 else
449 node.kind = ExpressionKind::Absolute;
450 return add(std::move(node));
451 }
452
453 std::uint16_t parsePrimary(std::size_t depth) {
454 if (depth > kMaximumConditionDepth) {
455 fail("condition exceeds the nesting limit", std::to_string(kMaximumConditionDepth));
456 return 0;
457 }
458 const auto token = current();
459 if (accept("(")) {
460 const auto expression = parseOr(depth + 1);
461 expect(")");
462 return expression;
463 }
464 if (token.kind == TokenKind::Number) {
465 ++position_;
466 ExpressionNode node{ExpressionKind::Literal, ExpressionType::Number};
467 node.literal = eve::Value(std::strtod(token.text.c_str(), nullptr));
468 return add(std::move(node));
469 }
470 if (token.kind == TokenKind::String) {
471 ++position_;
472 ExpressionNode node{ExpressionKind::Literal, ExpressionType::String};
473 node.literal = eve::Value(token.text);
474 return add(std::move(node));
475 }
476 if (token.kind != TokenKind::Identifier) {
477 fail("condition expected a literal, field, function, or parenthesized expression", "expression",
478 token.text);
479 return 0;
480 }
481 ++position_;
482 if (token.text == "true" || token.text == "false") {
483 ExpressionNode node{ExpressionKind::Literal, ExpressionType::Boolean};
484 node.literal = eve::Value(token.text == "true");
485 return add(std::move(node));
486 }
487 if (current().text == "(") return parseFunction(token.text, token, depth + 1);
488 ExpressionNode node{ExpressionKind::Field, ExpressionType::Unknown};
489 node.name = token.text;
490 if (token.text == "kind" || token.text == "resource")
491 node.type = ExpressionType::String;
492 else if (token.text == "magnitude" || token.text == "tick")
493 node.type = ExpressionType::Number;
494 else if (!token.text.starts_with("context.") || token.text.size() == std::string_view("context.").size()) {
495 error_ = expressionDiagnostic(eve::DiagnosticCode::NotFound, "condition references an unknown field", path_,
496 token, "kind, resource, magnitude, tick, or context.<name>", token.text);
497 return 0;
498 }
499 return add(std::move(node));
500 }
501
502 std::vector<Token> tokens_;
503 std::string path_;
504 std::size_t position_ = 0;
505 std::vector<ExpressionNode> nodes_;
506 std::optional<eve::Diagnostic> error_;
507};
508
509struct EvaluatedValue {
510 ExpressionType type = ExpressionType::Boolean;
511 bool boolean = false;
512 double number = 0.0;
513 std::string string;
514};
515
516eve::Result<EvaluatedValue> evaluationFailure(eve::DiagnosticCode code, std::string message, std::string path) {
518 eve::Diagnostic::error(code, std::move(message), std::move(path), {}, "settlement.condition"));
519}
520
521const eve::Value* findContextValue(const eve::Value& root, std::string_view path) {
522 const eve::Value* current = &root;
523 while (!path.empty()) {
524 const auto split = path.find('.');
525 const auto part = path.substr(0, split);
526 if (part.empty() || !current->isObject()) return nullptr;
527 current = current->find(std::string(part));
528 if (!current) return nullptr;
529 if (split == std::string_view::npos) break;
530 path.remove_prefix(split + 1);
531 }
532 return current;
533}
534
535eve::Result<EvaluatedValue> evaluateNode(const ExpressionProgram& program, std::uint16_t index,
536 const SettlementRequest& request, std::size_t& steps) {
537 if (++steps > kMaximumEvaluationSteps)
538 return evaluationFailure(eve::DiagnosticCode::PreconditionViolation,
539 "condition exceeded the evaluation step limit", "when");
540 const auto& node = program.nodes[index];
541 if (node.kind == ExpressionKind::Literal) {
542 EvaluatedValue result;
543 result.type = node.type;
544 if (const auto* value = node.literal.getIf<bool>())
545 result.boolean = *value;
546 else if (const auto* value = node.literal.getIf<double>())
547 result.number = *value;
548 else if (const auto* value = node.literal.getIf<std::string>())
549 result.string = *value;
551 }
552 if (node.kind == ExpressionKind::HasTag) {
553 const bool present = std::find(request.tags.begin(), request.tags.end(), node.name) != request.tags.end();
554 EvaluatedValue result;
555 result.type = ExpressionType::Boolean;
556 result.boolean = present;
558 }
559 if (node.kind == ExpressionKind::Field) {
560 EvaluatedValue result;
561 result.type = node.type;
562 if (node.name == "kind")
563 result.string = request.kind;
564 else if (node.name == "resource")
565 result.string = request.resource;
566 else if (node.name == "magnitude")
567 result.number = request.magnitude;
568 else if (node.name == "tick")
569 result.number = static_cast<double>(request.tick.value());
570 else {
571 auto contextPath = std::string_view(node.name).substr(std::string_view("context.").size());
572 const auto* value = findContextValue(request.context, contextPath);
573 if (!value)
574 return evaluationFailure(eve::DiagnosticCode::NotFound, "condition context field is missing",
575 node.name);
576 if (node.type == ExpressionType::Boolean) {
577 const auto* typed = value->getIf<bool>();
578 if (!typed)
579 return evaluationFailure(eve::DiagnosticCode::TypeMismatch,
580 "condition context field is not Boolean", node.name);
581 result.boolean = *typed;
582 } else if (node.type == ExpressionType::String) {
583 const auto* typed = value->getIf<std::string>();
584 if (!typed)
585 return evaluationFailure(eve::DiagnosticCode::TypeMismatch, "condition context field is not String",
586 node.name);
587 result.string = *typed;
588 } else if (const auto* integer = value->getIf<std::int64_t>()) {
589 result.number = static_cast<double>(*integer);
590 } else if (const auto* real = value->getIf<double>(); real && std::isfinite(*real)) {
591 result.number = *real;
592 } else {
593 return evaluationFailure(eve::DiagnosticCode::TypeMismatch,
594 "condition context field is not a finite Number", node.name);
595 }
596 }
598 }
599 auto leftResult = evaluateNode(program, node.left, request, steps);
600 if (!leftResult) return leftResult;
601 auto left = std::move(leftResult).takeValue();
602 if (node.kind == ExpressionKind::Not) {
603 left.boolean = !left.boolean;
605 }
606 if (node.kind == ExpressionKind::Negate) {
607 left.number = -left.number;
609 }
610 if (node.kind == ExpressionKind::Absolute) {
611 left.number = std::abs(left.number);
613 }
614 if (node.kind == ExpressionKind::And && !left.boolean) return eve::Result<EvaluatedValue>::success(std::move(left));
615 if (node.kind == ExpressionKind::Or && left.boolean) return eve::Result<EvaluatedValue>::success(std::move(left));
616 auto rightResult = evaluateNode(program, node.right, request, steps);
617 if (!rightResult) return rightResult;
618 auto right = std::move(rightResult).takeValue();
619 EvaluatedValue result;
620 switch (node.kind) {
621 case ExpressionKind::Add:
622 result.type = ExpressionType::Number;
623 result.number = left.number + right.number;
624 break;
625 case ExpressionKind::Subtract:
626 result.type = ExpressionType::Number;
627 result.number = left.number - right.number;
628 break;
629 case ExpressionKind::Multiply:
630 result.type = ExpressionType::Number;
631 result.number = left.number * right.number;
632 break;
633 case ExpressionKind::Divide:
634 if (right.number == 0.0)
635 return evaluationFailure(eve::DiagnosticCode::InvalidArgument, "condition attempted division by zero",
636 "when");
637 result.type = ExpressionType::Number;
638 result.number = left.number / right.number;
639 break;
640 case ExpressionKind::Minimum:
641 result.type = ExpressionType::Number;
642 result.number = std::min(left.number, right.number);
643 break;
644 case ExpressionKind::Maximum:
645 result.type = ExpressionType::Number;
646 result.number = std::max(left.number, right.number);
647 break;
648 case ExpressionKind::Clamp: {
649 auto thirdResult = evaluateNode(program, node.third, request, steps);
650 if (!thirdResult) return thirdResult;
651 const auto third = std::move(thirdResult).takeValue();
652 if (right.number > third.number)
653 return evaluationFailure(eve::DiagnosticCode::InvalidArgument,
654 "condition clamp minimum exceeds maximum", "when");
655 result.type = ExpressionType::Number;
656 result.number = std::clamp(left.number, right.number, third.number);
657 break;
658 }
659 case ExpressionKind::Equal:
660 case ExpressionKind::NotEqual: {
661 result.type = ExpressionType::Boolean;
662 bool equal = false;
663 if (left.type == ExpressionType::Boolean)
664 equal = left.boolean == right.boolean;
665 else if (left.type == ExpressionType::Number)
666 equal = left.number == right.number;
667 else
668 equal = left.string == right.string;
669 result.boolean = node.kind == ExpressionKind::Equal ? equal : !equal;
670 break;
671 }
672 case ExpressionKind::Less:
673 result.type = ExpressionType::Boolean;
674 result.boolean = left.number < right.number;
675 break;
676 case ExpressionKind::LessEqual:
677 result.type = ExpressionType::Boolean;
678 result.boolean = left.number <= right.number;
679 break;
680 case ExpressionKind::Greater:
681 result.type = ExpressionType::Boolean;
682 result.boolean = left.number > right.number;
683 break;
684 case ExpressionKind::GreaterEqual:
685 result.type = ExpressionType::Boolean;
686 result.boolean = left.number >= right.number;
687 break;
688 case ExpressionKind::And:
689 result.type = ExpressionType::Boolean;
690 result.boolean = left.boolean && right.boolean;
691 break;
692 case ExpressionKind::Or:
693 result.type = ExpressionType::Boolean;
694 result.boolean = left.boolean || right.boolean;
695 break;
696 default:
697 return evaluationFailure(eve::DiagnosticCode::InvariantViolation,
698 "condition contains an invalid instruction", "when");
699 }
700 if (result.type == ExpressionType::Number && !std::isfinite(result.number))
701 return evaluationFailure(eve::DiagnosticCode::InvalidArgument, "condition produced a non-finite number",
702 "when");
704}
705
706std::string digestCondition(std::string_view source) {
707 std::uint64_t hash = 1469598103934665603ull;
708 constexpr std::string_view version = "settlement-condition-v1\n";
709 for (const char value : version) {
710 hash ^= static_cast<unsigned char>(value);
711 hash *= 1099511628211ull;
712 }
713 for (const char value : source) {
714 hash ^= static_cast<unsigned char>(value);
715 hash *= 1099511628211ull;
716 }
717 std::ostringstream stream;
718 stream << std::hex << std::setfill('0') << std::setw(16) << hash;
719 return stream.str();
720}
721
722struct CompiledExpression {
723 std::shared_ptr<const ExpressionProgram> program;
724 std::string digest;
725};
726
727eve::Result<CompiledExpression> compileExpression(std::string_view source, const std::string& path) {
728 if (source.size() > kMaximumConditionSource) {
729 Token token;
731 expressionDiagnostic(eve::DiagnosticCode::InvalidArgument, "condition exceeds the source length limit",
732 path, token, std::to_string(kMaximumConditionSource), std::to_string(source.size())));
733 }
734 auto tokenResult = tokenize(source, path);
735 if (!tokenResult) return eve::Result<CompiledExpression>::failure(tokenResult.status());
736 ExpressionParser parser(std::move(tokenResult).takeValue(), path);
737 auto programResult = parser.parse();
738 if (!programResult) return eve::Result<CompiledExpression>::failure(programResult.status());
739 CompiledExpression compiled;
740 compiled.program = std::make_shared<ExpressionProgram>(std::move(programResult).takeValue());
741 compiled.digest = digestCondition(source);
742 return eve::Result<CompiledExpression>::success(std::move(compiled));
743}
744
745bool contains(const std::vector<std::string>& values, const std::string& value) {
746 return std::find(values.begin(), values.end(), value) != values.end();
747}
748
749bool matches(const RuleFilter& filter, const SettlementRequest& request) {
750 if (!filter.kinds.empty() && !contains(filter.kinds, request.kind)) return false;
751 for (const auto& tag : filter.requiredTags)
752 if (!contains(request.tags, tag)) return false;
753 for (const auto& tag : filter.excludedTags)
754 if (contains(request.tags, tag)) return false;
755 return true;
756}
757
758eve::Result<void> applyRule(const SettlementRule& rule,
759 const std::function<eve::Result<bool>(const SettlementRequest&)>& condition,
760 const std::string& conditionDigest, SettlementContext& context) {
761 if (!matches(rule.filter, context.request()))
763 if (condition) {
764 auto accepted = condition(context.request());
765 if (!accepted) return eve::Result<void>::failure(accepted.status());
767 }
768 const double operand = rule.value + rule.valuePerExtraStack * static_cast<double>(rule.stacks - 1);
769 const double before = context.magnitude();
770 double removed = 0.0;
771 auto outcome = [&]() -> eve::Result<void> {
772 switch (rule.operation) {
773 case RuleOperation::Add: return context.setMagnitude(std::max(0.0, before + operand));
774 case RuleOperation::Multiply: return context.setMagnitude(before * operand);
776 removed = std::min(before, operand);
777 if (auto changed = context.setMagnitude(before - removed); !changed) return changed;
778 return context.addResisted(removed);
780 removed = before * operand;
781 if (auto changed = context.setMagnitude(before - removed); !changed) return changed;
782 return context.addResisted(removed);
784 removed = std::min(before, operand);
785 if (auto changed = context.setMagnitude(before - removed); !changed) return changed;
786 return context.addAbsorbed(removed);
787 case RuleOperation::ClampMaximum: return context.setClampMax(operand);
788 case RuleOperation::Critical: context.setCritical(operand != 0.0); return eve::Result<void>::success();
792 if (!context.request().source.isValid() || context.projectedResult().applied == 0.0)
794 const double magnitude = context.projectedResult().applied * operand;
795 if (!std::isfinite(magnitude))
797 eve::DiagnosticCode::InvariantViolation, "derived settlement magnitude overflowed",
798 "operation"));
799 SettlementRequest derived;
800 derived.source = rule.operation == RuleOperation::Reflect ? context.request().target
801 : context.request().source;
802 derived.target = context.request().source;
803 derived.kind = rule.operation == RuleOperation::Reflect ? "damage" : "heal";
804 derived.resource = context.request().resource;
805 derived.magnitude = magnitude;
806 derived.tick = context.request().tick;
807 derived.correlation = context.request().correlation;
808 derived.trigger = "rule:" + rule.id;
809 derived.tags.push_back(rule.operation == RuleOperation::Reflect ? "trigger:reflect"
810 : "trigger:lifesteal");
811 return context.emitDerived(std::move(derived));
812 }
813 }
815 "unknown settlement rule operation", "operation"));
816 }();
817 if (!outcome) return outcome;
818 if (context.request().trace == SettlementTraceLevel::Full) {
819 context.setStageDetail("rule", eve::Value(rule.id));
820 context.setStageDetail("source", eve::Value(rule.source));
821 context.setStageDetail("stacks", eve::Value(static_cast<std::int64_t>(rule.stacks)));
822 context.setStageDetail("operand", eve::Value(operand));
823 if (!conditionDigest.empty()) context.setStageDetail("condition_digest", eve::Value(conditionDigest));
824 }
826}
827
828} // namespace
829
830eve::Result<void> SettlementRuleSet::configure(std::vector<SettlementRule> rules) {
831 std::set<std::string> ids;
832 std::vector<ConditionFunction> conditions;
833 std::vector<std::string> conditionDigests;
834 conditions.reserve(rules.size());
835 conditionDigests.reserve(rules.size());
836 for (std::size_t index = 0; index < rules.size(); ++index) {
837 const auto& rule = rules[index];
838 const auto path = "rules[" + std::to_string(index) + "]";
839 if (rule.id.empty()) return eve::Result<void>::failure(
840 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "settlement rule id must not be empty", path + ".id"));
841 if (!ids.insert(rule.id).second) return eve::Result<void>::failure(
842 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "settlement rule ids must be unique", path + ".id"));
843 if (rule.stacks == 0) return eve::Result<void>::failure(
844 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "settlement rule stack count must be positive", path + ".stacks"));
845 if (!std::isfinite(rule.value) || !std::isfinite(rule.valuePerExtraStack))
847 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "settlement rule operands must be finite", path + ".value"));
848 if (rule.stage == StageKind::Validate || rule.stage == StageKind::Apply || rule.stage == StageKind::Event)
850 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "settlement rule cannot mutate a terminal or validation phase", path + ".stage"));
851 if (rule.stage == StageKind::Decision && rule.operation != RuleOperation::Immune)
853 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "decision-stage rules currently support only immune outcomes", path + ".operation"));
854 if (rule.operation == RuleOperation::Immune && rule.stage != StageKind::Decision)
856 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "immune rules must run in the decision stage", path + ".stage"));
857 const bool triggerOperation =
858 rule.operation == RuleOperation::Lifesteal || rule.operation == RuleOperation::Reflect;
859 if (rule.stage == StageKind::Trigger && !triggerOperation)
861 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "trigger-stage rules require a derived-request operation", path + ".operation"));
862 if (triggerOperation && rule.stage != StageKind::Trigger)
864 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "derived-request rules must run in the trigger stage", path + ".stage"));
865 if ((rule.operation == RuleOperation::Multiply || rule.operation == RuleOperation::ResistFlat ||
866 rule.operation == RuleOperation::AbsorbFlat || rule.operation == RuleOperation::ClampMaximum ||
867 triggerOperation) &&
868 (rule.value < 0.0 || rule.valuePerExtraStack < 0.0))
870 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "settlement rule operation requires non-negative operands", path + ".value"));
871 if (rule.operation == RuleOperation::ResistPercent &&
872 (rule.value < 0.0 || rule.value > 1.0 || rule.valuePerExtraStack < 0.0 ||
873 rule.value + rule.valuePerExtraStack * static_cast<double>(rule.stacks - 1) > 1.0))
875 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "settlement resistance percentage must remain in [0,1]", path + ".value"));
876 if (rule.when.empty()) {
877 conditions.emplace_back();
878 conditionDigests.emplace_back();
879 } else {
880 auto compiled = compileExpression(rule.when, path + ".when");
881 if (!compiled) return eve::Result<void>::failure(compiled.status());
882 auto expression = std::move(compiled).takeValue();
883 auto program = std::move(expression.program);
884 conditions.emplace_back([program = std::move(program)](const SettlementRequest& request) {
885 std::size_t steps = 0;
886 auto evaluated = evaluateNode(*program, program->root, request, steps);
887 if (!evaluated) return eve::Result<bool>::failure(evaluated.status());
888 return eve::Result<bool>::success(std::move(evaluated).takeValue().boolean);
889 });
890 conditionDigests.push_back(std::move(expression.digest));
891 }
892 }
893 rules_ = std::move(rules);
894 conditions_ = std::move(conditions);
895 conditionDigests_ = std::move(conditionDigests);
897}
898
900 struct InstalledRule {
901 SettlementRule rule;
902 std::function<eve::Result<bool>(const SettlementRequest&)> condition;
903 std::string digest;
904 };
905 std::vector<InstalledRule> rules;
906 rules.reserve(rules_.size());
907 for (std::size_t index = 0; index < rules_.size(); ++index)
908 rules.push_back(InstalledRule{rules_[index], conditions_[index], conditionDigests_[index]});
909 std::sort(rules.begin(), rules.end(), [](const auto& left, const auto& right) {
910 const auto leftStage = static_cast<std::uint8_t>(left.rule.stage);
911 const auto rightStage = static_cast<std::uint8_t>(right.rule.stage);
912 if (leftStage != rightStage) return leftStage < rightStage;
913 if (left.rule.priority != right.rule.priority) return left.rule.priority < right.rule.priority;
914 return left.rule.id < right.rule.id;
915 });
916 for (auto& installed : rules) {
917 const auto stage = installed.rule.stage;
918 // Canonical policy stages use simple names (for example
919 // source_modifiers). The prefix deliberately sorts rules after the
920 // domain policy while Clamp's terminal boundary still sorts last.
921 const auto name = std::string("zz_rule.") + installed.rule.id;
922 const auto priority = installed.rule.priority;
923 auto added = pipeline.addStage(stage, name, priority,
924 [rule = std::move(installed.rule), condition = std::move(installed.condition),
925 digest = std::move(installed.digest)](SettlementContext& context) {
926 return applyRule(rule, condition, digest, context);
927 });
928 if (!added) return added;
929 }
931}
932
933} // namespace eve::settlement
ActionParameterOperation operation
int root
Definition AnimSmr.cpp:119
int priority
bool changed
eve::Value condition
std::string name
Definition ECS.cpp:154
std::string message
DiagnosticCode code
const GltfImportRequest & request
HexVec3 left
HexVec3 right
float length
size_t offset
bool present
std::map< std::string, Node > nodes
Poco::JSON::Object::Ptr result
std::unordered_set< std::string > tags
const std::string * tag
OceanGpuFrameToken token
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
Object::Ptr value
std::string hash
int steps
const RoadNode * node
double number
int removed
std::string filter
unsigned line
std::string text
std::string_view source
size_t begin
unsigned column
size_t end
std::string kind
std::vector< Token > tokens
double current
std::uint16_t third
std::string digest
eve::Value literal
std::string string
std::shared_ptr< const ExpressionProgram > program
Declarative, domain-neutral rules for buffs and gameplay effects.
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
uint32_t index
const VegetationPresetContext & context
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.
void value() const
Mark a successful void operation as checked.
Definition Result.h:560
const Status & status() const noexcept
Inspect the structured operation status.
Definition Result.h:521
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
Mutable calculation frame visible to policy and custom stage code.
Definition Settlement.h:338
Deterministically ordered, composable settlement pipeline.
Definition Settlement.h:542
eve::Result< void > addStage(StageKind kind, std::string name, int priority, StageFunction function)
Add one named custom stage; duplicate names are rejected.
eve::Result< void > configure(std::vector< SettlementRule > rules)
Atomically replace all rules after validating ids, operands and phases.
eve::Result< void > install(SettlementPipeline &pipeline) const
Install a stable snapshot as custom stages on a pipeline.
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
@ Number
Unsigned numeric literal; sign handling belongs to the parser.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
Result< void > accepted()
Build a successful write/validation result.
ModelData parse(std::span< const uint8_t > bytes)
Parse.
std::vector< DiagnosticDetail > DiagnosticDetails
Owning collection of diagnostic details with stable insertion order.
Definition Diagnostic.h:88
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
@ TypeMismatch
A stable reference resolved to a different canonical domain type.
enum EVENGINE_API_FOUNDATION String
OT_STRING.
Definition Runtime.h:119
Domain-neutral input to one settlement operation.
Definition Settlement.h:107
One owning, serializable projection of a buff/effect contribution.