载入中...
搜索中...
未找到
MapObjectContract.cpp
浏览该文件的文档.
2#include "common/ValueRead.h"
3
4#include "common/Value.h"
5
6#include <cerrno>
7#include <charconv>
8#include <cmath>
9#include <cstdlib>
10#include <map>
11#include <optional>
12#include <set>
13#include <string>
14
15namespace eve::map {
16namespace {
17
18const eve::Value* member(const eve::Value::Object& object, std::string_view name) {
19 const auto found = object.find(std::string(name));
20 return found == object.end() ? nullptr : &found->second;
21}
22
23bool booleanMember(const eve::Value::Object& object, std::string_view name, bool fallback, bool& output) {
24 const auto* value = member(object, name);
25 if (!value) {
26 output = fallback;
27 return true;
28 }
29 auto parsed = eve::readBoolValue(*value);
30 if (!parsed) return false;
31 output = parsed.value();
32 return true;
33}
34
35bool numericValue(const eve::Value& value, double& output) {
37 if (!parsed) return false;
38 output = parsed.value();
39 return std::isfinite(output);
40}
41
42bool parseInteger(std::string_view text, std::int64_t& output) {
43 if (text.empty()) return false;
44 const auto parsed = std::from_chars(text.data(), text.data() + text.size(), output);
45 return parsed.ec == std::errc{} && parsed.ptr == text.data() + text.size();
46}
47
48bool parseNumber(const std::string& text, double& output) {
49 if (text.empty()) return false;
50 char* end = nullptr;
51 errno = 0;
52 output = std::strtod(text.c_str(), &end);
53 return errno != ERANGE && end == text.c_str() + text.size() && std::isfinite(output);
54}
55
56bool stableName(std::string_view name) {
57 if (name.empty() || name.size() > 256) return false;
58 for (unsigned char character : name)
59 if (character < 0x20 || character == 0x7f) return false;
60 return true;
61}
62
63struct PropertyRule {
64 std::string name;
65 std::string kind;
66 bool required = false;
67 std::optional<double> minimum;
68 std::optional<double> maximum;
69 std::set<std::string> choices;
70};
71
72struct TypeRule {
74 std::map<std::string, PropertyRule> properties;
75};
76
77eve::Result<void> validateProperty(const std::string& value, const PropertyRule& rule,
78 const std::string& path) {
79 double numeric = 0.0;
80 if (rule.kind == "string") {
81 if (!rule.choices.empty() && !rule.choices.contains(value))
83 eve::DiagnosticCode::InvalidArgument, "property value is outside its enum", path, {}, "map.object-contract"));
84 } else if (rule.kind == "int") {
85 std::int64_t integer = 0;
86 if (!parseInteger(value, integer))
88 eve::DiagnosticCode::TypeMismatch, "property must be an integer", path, {}, "map.object-contract"));
89 numeric = static_cast<double>(integer);
90 } else if (rule.kind == "number") {
91 if (!parseNumber(value, numeric))
93 eve::DiagnosticCode::TypeMismatch, "property must be a finite number", path, {}, "map.object-contract"));
94 } else if (rule.kind == "bool") {
95 if (value != "true" && value != "false")
97 eve::DiagnosticCode::TypeMismatch, "property must be true or false", path, {}, "map.object-contract"));
98 } else {
100 eve::DiagnosticCode::Unsupported, "unsupported property kind", path, {}, "map.object-contract"));
101 }
102 if (rule.minimum && numeric < *rule.minimum)
104 eve::DiagnosticCode::InvalidArgument, "property is below its minimum", path, {}, "map.object-contract"));
105 if (rule.maximum && numeric > *rule.maximum)
107 eve::DiagnosticCode::InvalidArgument, "property exceeds its maximum", path, {}, "map.object-contract"));
109}
110
111} // namespace
112
113eve::Result<void> validateMapObjects(std::span<const MapObject> objects, std::string_view contractJson) {
114 auto parsed = eve::Value::fromJson(contractJson);
115 if (!parsed.ok()) return eve::Result<void>::failure(parsed.status());
116 const auto* root = parsed.value().getIf<eve::Value::Object>();
118 eve::DiagnosticCode::TypeMismatch, "contract root must be an object", "$contract", {}, "map.object-contract"));
119
120 const eve::Value* schema = member(*root, "schema");
121 const eve::Value* version = member(*root, "version");
122 const eve::Value* typesValue = member(*root, "types");
123 if (!schema || !schema->isString() || schema->asString() != "eve.map.object-contract")
126 "unsupported contract schema; expected {schema:\"eve.map.object-contract\",version:1,"
127 "types:[{type,properties:[{name,kind}]}]} (not schemaId / map-of-types)",
128 "$contract.schema", {}, "map.object-contract"));
129 if (!version || !version->isInt64() || version->asInt() != 1)
132 "unsupported contract version; expected version:1 with types:[{type,properties:[{name,kind}]}]",
133 "$contract.version", {}, "map.object-contract"));
134 const auto* types = typesValue ? typesValue->getIf<eve::Value::Array>() : nullptr;
135 if (!types)
137 eve::DiagnosticCode::TypeMismatch, "types must be an array of {type,properties:[{name,kind}]} rules",
138 "$contract.types", {}, "map.object-contract"));
139
140 bool requireUniqueNames = true;
141 bool allowUnknownTypes = false;
142 if (!booleanMember(*root, "requireUniqueNames", true, requireUniqueNames))
144 eve::DiagnosticCode::TypeMismatch, "requireUniqueNames must be boolean", "$contract.requireUniqueNames", {}, "map.object-contract"));
145 if (!booleanMember(*root, "allowUnknownTypes", false, allowUnknownTypes))
147 eve::DiagnosticCode::TypeMismatch, "allowUnknownTypes must be boolean", "$contract.allowUnknownTypes", {}, "map.object-contract"));
148
149 std::map<std::string, TypeRule> rules;
150 for (std::size_t typeIndex = 0; typeIndex < types->size(); ++typeIndex) {
151 const std::string base = "$contract.types[" + std::to_string(typeIndex) + "]";
152 const auto* definition = (*types)[typeIndex].getIf<eve::Value::Object>();
154 eve::DiagnosticCode::TypeMismatch, "type rule must be an object", base, {}, "map.object-contract"));
155 const eve::Value* type = member(*definition, "type");
156 if (!type || !type->isString() || type->asString().empty())
158 eve::DiagnosticCode::InvalidArgument, "type must be a non-empty string", base + ".type", {}, "map.object-contract"));
159 TypeRule typeRule;
160 if (!booleanMember(*definition, "allowUnknownProperties", false, typeRule.allowUnknownProperties))
162 eve::DiagnosticCode::TypeMismatch, "allowUnknownProperties must be boolean", base + ".allowUnknownProperties", {}, "map.object-contract"));
163 const eve::Value* propertiesValue = member(*definition, "properties");
164 const auto* properties = propertiesValue ? propertiesValue->getIf<eve::Value::Array>() : nullptr;
165 if (propertiesValue && !properties)
167 eve::DiagnosticCode::TypeMismatch, "properties must be an array", base + ".properties", {}, "map.object-contract"));
168 if (properties) {
169 for (std::size_t propertyIndex = 0; propertyIndex < properties->size(); ++propertyIndex) {
170 const std::string propertyPath = base + ".properties[" + std::to_string(propertyIndex) + "]";
171 const auto* definitionObject = (*properties)[propertyIndex].getIf<eve::Value::Object>();
172 if (!definitionObject)
174 eve::DiagnosticCode::TypeMismatch, "property rule must be an object", propertyPath, {}, "map.object-contract"));
175 const eve::Value* name = member(*definitionObject, "name");
176 const eve::Value* kind = member(*definitionObject, "kind");
177 if (!name || !name->isString() || name->asString().empty())
179 eve::DiagnosticCode::InvalidArgument, "property name must be non-empty", propertyPath + ".name", {}, "map.object-contract"));
180 if (!kind || !kind->isString())
182 eve::DiagnosticCode::TypeMismatch, "property kind must be a string", propertyPath + ".kind", {}, "map.object-contract"));
183 PropertyRule propertyRule{name->asString(), kind->asString()};
184 if (!booleanMember(*definitionObject, "required", false, propertyRule.required))
186 eve::DiagnosticCode::TypeMismatch, "required must be boolean", propertyPath + ".required", {}, "map.object-contract"));
187 for (std::string_view field : {std::string_view("min"), std::string_view("max")}) {
188 if (const eve::Value* bound = member(*definitionObject, field)) {
189 double number = 0.0;
190 if (!numericValue(*bound, number))
192 eve::DiagnosticCode::TypeMismatch, std::string(field) + " must be numeric", propertyPath + "." + std::string(field), {}, "map.object-contract"));
193 (field == "min" ? propertyRule.minimum : propertyRule.maximum) = number;
194 }
195 }
196 if (propertyRule.minimum && propertyRule.maximum && *propertyRule.minimum > *propertyRule.maximum)
198 eve::DiagnosticCode::InvalidArgument, "min must not exceed max", propertyPath, {}, "map.object-contract"));
199 if (const eve::Value* enumValue = member(*definitionObject, "enum")) {
200 const auto* choices = enumValue->getIf<eve::Value::Array>();
201 if (!choices)
203 eve::DiagnosticCode::TypeMismatch, "enum must be an array", propertyPath + ".enum", {}, "map.object-contract"));
204 for (const eve::Value& choice : *choices) {
205 if (!choice.isString())
207 eve::DiagnosticCode::TypeMismatch, "enum values must be strings", propertyPath + ".enum", {}, "map.object-contract"));
208 if (!propertyRule.choices.emplace(choice.asString()).second)
210 eve::DiagnosticCode::AlreadyExists, "duplicate enum value", propertyPath + ".enum", {}, "map.object-contract"));
211 }
212 }
213 if (!typeRule.properties.emplace(propertyRule.name, std::move(propertyRule)).second)
215 eve::DiagnosticCode::AlreadyExists, "duplicate property rule", propertyPath + ".name", {}, "map.object-contract"));
216 }
217 }
218 if (!rules.emplace(type->asString(), std::move(typeRule)).second)
220 eve::DiagnosticCode::AlreadyExists, "duplicate type rule", base + ".type", {}, "map.object-contract"));
221 }
222
223 std::set<std::string> names;
224 for (std::size_t objectIndex = 0; objectIndex < objects.size(); ++objectIndex) {
225 const MapObject& object = objects[objectIndex];
226 const std::string base = "$objects[" + std::to_string(objectIndex) + "]";
227 if (!std::isfinite(object.x) || !std::isfinite(object.y) || !std::isfinite(object.width) ||
228 !std::isfinite(object.height) || object.width < 0.f || object.height < 0.f)
230 eve::DiagnosticCode::InvalidArgument, "object geometry must be finite and non-negative", base, {}, "map.object-contract"));
231 if (requireUniqueNames && (!stableName(object.name) || !names.emplace(object.name).second))
233 eve::DiagnosticCode::Conflict, "object names must be unique, bounded, non-empty, and control-free", base + ".name", {}, "map.object-contract"));
234 const auto type = rules.find(object.type);
235 if (type == rules.end()) {
236 if (!allowUnknownTypes)
238 eve::DiagnosticCode::Unsupported, "object type is not admitted", base + ".type", {}, "map.object-contract"));
239 continue;
240 }
241 for (const auto& [name, rule] : type->second.properties) {
242 const auto property = object.properties.find(name);
243 if (property == object.properties.end()) {
244 if (rule.required)
246 eve::DiagnosticCode::NotFound, "required property is missing", base + ".properties." + name, {}, "map.object-contract"));
247 continue;
248 }
249 auto valid = validateProperty(property->second, rule, base + ".properties." + name);
250 if (!valid.ok()) return valid;
251 }
252 if (!type->second.allowUnknownProperties) {
253 for (const auto& [name, value] : object.properties) {
254 (void)value;
255 if (!type->second.properties.contains(name))
257 eve::DiagnosticCode::Unsupported, "property is not admitted", base + ".properties." + name, {}, "map.object-contract"));
258 }
259 }
260 }
262}
263
264} // namespace eve::map
double y
double x
int root
Definition AnimSmr.cpp:119
std::string output
std::string name
Definition ECS.cpp:154
float maximum[3]
float minimum[3]
std::uint32_t height
std::uint32_t width
std::map< std::string, PropertyRule > properties
bool allowUnknownProperties
bool required
std::set< std::string > choices
bool valid
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
double number
bool found
std::string text
size_t end
std::string kind
float(ui::Theme::* member)[4]
Owning, renderer-independent dynamic values.
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
const std::string & asString() const
Return the string payload; the caller must have checked the kind.
Definition Value.cpp:207
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
bool isString() const noexcept
Return true when this value is a string.
Definition Value.h:106
std::vector< Value > Array
Definition Value.h:33
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
StateValue objects
Definition Snapshot.cpp:110
Result< double > numericValue(const Value &value)
Read an Integer or Number as an owning double without applying domain validation.
放置世界:格子占用(多通道)+ 地形语义 + 已放置建筑实例。 行为由 PlacementSystem 提供;本类暴露便于脚本绑定的薄封装方法。 坐标换算统一走 eve::grid(支持 rectang...
eve::Result< void > validateMapObjects(std::span< const MapObject > objects, std::string_view contractJson)
Validate map objects against an owning JSON content contract.
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
@ TypeMismatch
A stable reference resolved to a different canonical domain type.
Result< bool > readBoolValue(const Value &value)
Read a Bool without coercing integers, strings or other kinds.
Definition Value.cpp:50
Result< double > readNumericDoubleValue(const Value &value)
Read an Int64 or Double as a double without imposing a finite-value policy.
Definition Value.cpp:74
A named, typed rectangle object from a Tiled objectgroup layer. Used by Map::setObjects / getObject* ...
Definition MapObject.h:13