Skip to main content

nadir_scene/
reflect.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! [`Reflect`] and [`FromValue`]: walking a value's fields by name, and
16//! turning it into a [`Value`] and back.
17
18use std::any::Any;
19use std::borrow::Cow;
20use std::error::Error;
21use std::fmt;
22
23use nadir_assets::{AssetServer, Scope};
24use nadir_codec::json::Value;
25use nadir_core::log::warn;
26
27/// A value whose fields can be walked by name, and that turns into a
28/// [`Value`] and back: what saves, prefabs, the inspector and settings
29/// need. The macros [`reflect_struct!`](crate::reflect_struct),
30/// [`reflect_enum!`](crate::reflect_enum) and
31/// [`reflect_newtype!`](crate::reflect_newtype) implement it; so does this
32/// crate for the built-in types (`docs/subsystems/scene.md`).
33///
34/// Both directions take a [`ReflectContext`]: it names the source being
35/// read, keeps the path to the field being read, and collects warnings
36/// (ADR-0020).
37pub trait Reflect: 'static {
38    /// The type's name: for the macros' types, its name as written
39    /// (`Health`), which prefabs and saves use.
40    fn type_name(&self) -> &'static str;
41
42    /// What sort of value it is.
43    fn kind(&self) -> ReflectKind;
44
45    /// The fields of a struct, in order; none for other kinds.
46    fn fields(&self) -> &'static [FieldInfo];
47
48    /// The variants of an enum, by name, in order, as data writes them:
49    /// what an inspector offers to pick from. None for other kinds, and by
50    /// default: [`reflect_enum!`](crate::reflect_enum) gives its enum's.
51    fn variants(&self) -> &'static [&'static str] {
52        &[]
53    }
54
55    /// Field `index` of a struct, or element `index` of a list or an
56    /// option.
57    fn field(&self, index: usize) -> Option<&dyn Reflect>;
58
59    /// Field or element `index`, to change it.
60    fn field_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>;
61
62    /// The value as a [`Value`].
63    fn to_value(&self, cx: &mut ReflectContext<'_>) -> Value;
64
65    /// Sets the value from `value`. A field that `value` does not name
66    /// keeps its value; a field it names that the type does not have is a
67    /// warning. On an error, what was applied before it stays applied.
68    ///
69    /// # Errors
70    ///
71    /// If `value` does not fit the type: a [`ReflectError`] naming the
72    /// source and the path to the field.
73    fn apply_value(
74        &mut self,
75        value: &Value,
76        cx: &mut ReflectContext<'_>,
77    ) -> Result<(), ReflectError>;
78}
79
80/// A reflected type that can be made from a [`Value`]: for a struct, its
81/// `Default` with the value applied.
82pub trait FromValue: Reflect + Sized {
83    /// The type's name, as [`Reflect::type_name`] gives it.
84    const TYPE_NAME: &'static str;
85
86    /// Makes a value of the type from `value`.
87    ///
88    /// # Errors
89    ///
90    /// As [`Reflect::apply_value`].
91    fn from_value(value: &Value, cx: &mut ReflectContext<'_>) -> Result<Self, ReflectError>;
92}
93
94/// What sort of value a [`Reflect`] is.
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
96pub enum ReflectKind {
97    /// A struct with named fields.
98    Struct,
99    /// An enum with unit variants, written as its variant's name.
100    Enum,
101    /// A number, a boolean, a string, or a value type such as `Vec2`.
102    Primitive,
103    /// A list: `Vec<T>`.
104    List,
105    /// An `Option<T>`.
106    Option,
107    /// An asset handle, written as the asset's path (ADR-0020, ADR-0038).
108    Handle,
109}
110
111/// One field of a reflected struct.
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub struct FieldInfo {
114    /// Its name, which data uses.
115    pub name: &'static str,
116    /// Its type as written in the struct, for display.
117    pub type_name: &'static str,
118    /// Its doc comment, line by line as written, each line ending in a
119    /// newline, and each `///` line keeping the space after the slashes.
120    /// Empty if it has none.
121    pub doc: &'static str,
122}
123
124/// One step of the path to a field, for messages.
125#[derive(Clone, Debug, PartialEq, Eq)]
126enum Segment {
127    Field(&'static str),
128    /// A member whose name the data gives, such as a prefab's component.
129    Key(String),
130    Index(usize),
131    /// A place given as text, where a value begins in its source:
132    /// `components.Health`.
133    Origin(String),
134}
135
136/// The asset server a context reads handles with, if it has one.
137enum Assets<'a> {
138    None,
139    /// To write handles as their paths: hashing and saving never load.
140    Shared(&'a AssetServer),
141    /// To read them too, each loaded in the scope.
142    Loading(&'a mut AssetServer, Scope),
143}
144
145/// What reading or writing reflected values needs besides the values:
146/// the name of the source, for messages, the path to the field at hand,
147/// and the warnings so far; and what some types need to read or write
148/// themselves (ADR-0038):
149///
150/// - the asset server, which an asset [`Handle`](nadir_core::Handle) is
151///   written and read through, as its asset's path:
152///   [`ReflectContext::with_assets`] to write handles,
153///   [`ReflectContext::loading`] to read them too;
154/// - resources of the types that need them, such as the facade's clips and
155///   collision layers: [`ReflectContext::with_resource`];
156/// - whether the values are for a hash, which leaves out what changes each
157///   frame: [`ReflectContext::hashing`].
158pub struct ReflectContext<'a> {
159    source: Cow<'a, str>,
160    path: Vec<Segment>,
161    warnings: Vec<ReflectWarning>,
162    assets: Assets<'a>,
163    resources: Vec<&'a dyn Any>,
164    hashing: bool,
165}
166
167impl<'a> ReflectContext<'a> {
168    /// A context for reading or writing `source`: a file's path, or any
169    /// name that tells the reader where the data came from. It has no asset
170    /// server and no resources, and is not for a hash.
171    pub fn new(source: &'a str) -> Self {
172        Self {
173            source: Cow::Borrowed(source),
174            path: Vec::new(),
175            warnings: Vec::new(),
176            assets: Assets::None,
177            resources: Vec::new(),
178            hashing: false,
179        }
180    }
181
182    /// This context with `server`, to write asset handles as their paths.
183    /// Reading a handle needs [`ReflectContext::loading`].
184    pub fn with_assets(mut self, server: &'a AssetServer) -> Self {
185        self.assets = Assets::Shared(server);
186        self
187    }
188
189    /// This context with `server`, to read asset handles, each loaded in
190    /// `scope`, as well as to write them.
191    pub fn loading(mut self, server: &'a mut AssetServer, scope: Scope) -> Self {
192        self.assets = Assets::Loading(server, scope);
193        self
194    }
195
196    /// This context with `resource`, for the types whose values need it:
197    /// [`ReflectContext::resource`] finds it by its type. One of a type
198    /// given before is replaced.
199    pub fn with_resource<T: Any>(mut self, resource: &'a T) -> Self {
200        self.resources.retain(|known| !known.is::<T>());
201        self.resources.push(resource);
202        self
203    }
204
205    /// This context for a hash: [`ReflectContext::is_hashing`] is true, so
206    /// that a type leaves out what the engine rewrites each frame, such as
207    /// the facade's `Sprite` frame an animator shows. A context for a hash
208    /// never loads an asset.
209    pub fn hashing(mut self) -> Self {
210        self.hashing = true;
211        self
212    }
213
214    /// Whether the values are for a hash: see [`ReflectContext::hashing`].
215    pub fn is_hashing(&self) -> bool {
216        self.hashing
217    }
218
219    /// The asset server, to write a handle as its asset's path, if the
220    /// context has one.
221    pub fn assets(&self) -> Option<&AssetServer> {
222        match &self.assets {
223            Assets::None => None,
224            Assets::Shared(server) => Some(server),
225            Assets::Loading(server, _) => Some(server),
226        }
227    }
228
229    /// The asset server, to load an asset, and the scope to load it in, if
230    /// the context is [`ReflectContext::loading`].
231    pub fn assets_mut(&mut self) -> Option<(&mut AssetServer, Scope)> {
232        match &mut self.assets {
233            Assets::Loading(server, scope) => Some((server, *scope)),
234            Assets::None | Assets::Shared(_) => None,
235        }
236    }
237
238    /// The resource of type `T` given with [`ReflectContext::with_resource`],
239    /// if there is one.
240    pub fn resource<T: Any>(&self) -> Option<&T> {
241        self.resources
242            .iter()
243            .find_map(|resource| resource.downcast_ref::<T>())
244    }
245
246    /// The name of the source.
247    pub fn source(&self) -> &str {
248        &self.source
249    }
250
251    /// Runs `f` with `source` as the source, for a value read from another
252    /// file than the rest, such as a prefab's base, and puts the source
253    /// back again, whatever `f` returns. The path is kept.
254    pub fn with_source<R>(&mut self, source: &str, f: impl FnOnce(&mut Self) -> R) -> R {
255        let outer = std::mem::replace(&mut self.source, Cow::Owned(source.to_string()));
256        let result = f(self);
257        self.source = outer;
258        result
259    }
260
261    /// Runs `f` with `source` as the source and `at` as the path, for a
262    /// value read from where it is in another file, such as a prefab's
263    /// `components.Health`, and puts both back again, whatever `f` returns.
264    /// An empty `at` is the source's root.
265    pub fn with_origin<R>(&mut self, source: &str, at: &str, f: impl FnOnce(&mut Self) -> R) -> R {
266        let path = if at.is_empty() {
267            Vec::new()
268        } else {
269            vec![Segment::Origin(at.to_string())]
270        };
271        let outer_path = std::mem::replace(&mut self.path, path);
272        let result = self.with_source(source, f);
273        self.path = outer_path;
274        result
275    }
276
277    /// The path to the field at hand, as text, as errors give it:
278    /// `entities[2].overrides`.
279    pub fn at(&self) -> String {
280        self.path()
281    }
282
283    /// The warnings so far, in order.
284    pub fn warnings(&self) -> &[ReflectWarning] {
285        &self.warnings
286    }
287
288    /// Runs `f` with field `name` added to the path, and takes it off
289    /// again, whatever `f` returns.
290    pub fn field<R>(&mut self, name: &'static str, f: impl FnOnce(&mut Self) -> R) -> R {
291        self.path.push(Segment::Field(name));
292        let result = f(self);
293        self.path.pop();
294        result
295    }
296
297    /// Runs `f` with member `key`, whose name the data gives, added to the
298    /// path, as [`ReflectContext::field`]: a prefab's component, say.
299    pub fn key<R>(&mut self, key: &str, f: impl FnOnce(&mut Self) -> R) -> R {
300        self.path.push(Segment::Key(key.to_string()));
301        let result = f(self);
302        self.path.pop();
303        result
304    }
305
306    /// Runs `f` with element `index` added to the path, as
307    /// [`ReflectContext::field`].
308    pub fn index<R>(&mut self, index: usize, f: impl FnOnce(&mut Self) -> R) -> R {
309        self.path.push(Segment::Index(index));
310        let result = f(self);
311        self.path.pop();
312        result
313    }
314
315    /// An error at the current path.
316    pub fn error(&self, kind: ReflectErrorKind) -> ReflectError {
317        ReflectError {
318            source: self.source.to_string(),
319            path: self.path(),
320            kind,
321        }
322    }
323
324    /// Logs a warning about the value at the current path, which writing it
325    /// could not avoid: a handle the asset server does not know, say,
326    /// written as `null`.
327    pub fn warn(&self, message: &str) {
328        let path = self.path();
329        if path.is_empty() {
330            warn!("{}: {message}", self.source);
331        } else {
332            warn!("{}: at `{path}`: {message}", self.source);
333        }
334    }
335
336    /// The error for `found` where `expected` was due, at the current path.
337    pub fn expected(&self, expected: &'static str, found: &Value) -> ReflectError {
338        self.error(ReflectErrorKind::Expected {
339            expected,
340            found: describe(found),
341        })
342    }
343
344    /// Notes, and logs, that the data gave `field`, which `type_name` has
345    /// not got.
346    pub fn unknown_field(&mut self, type_name: &'static str, field: &str) {
347        let warning = ReflectWarning {
348            source: self.source.to_string(),
349            type_name,
350            field: field.to_string(),
351            path: self.path(),
352        };
353        warn!("{warning}");
354        self.warnings.push(warning);
355    }
356
357    /// The path as text: `components.Health.max`, `layers[2]`.
358    fn path(&self) -> String {
359        let mut path = String::new();
360        for segment in &self.path {
361            match segment {
362                Segment::Field(name) => {
363                    if !path.is_empty() {
364                        path.push('.');
365                    }
366                    path.push_str(name);
367                }
368                Segment::Key(name) | Segment::Origin(name) => {
369                    if !path.is_empty() {
370                        path.push('.');
371                    }
372                    path.push_str(name);
373                }
374                Segment::Index(index) => {
375                    path.push('[');
376                    path.push_str(&index.to_string());
377                    path.push(']');
378                }
379            }
380        }
381        path
382    }
383}
384
385/// How a [`Value`] is described in messages: "a string", "null".
386fn describe(value: &Value) -> &'static str {
387    match value {
388        Value::Null => "null",
389        Value::Bool(_) => "a boolean",
390        Value::Int(_) => "an integer",
391        Value::Float(_) => "a number that is not an integer an i64 can hold",
392        Value::String(_) => "a string",
393        Value::Array(_) => "an array",
394        Value::Object(_) => "an object",
395    }
396}
397
398/// A field that data gave and its type has not got: kept out of the value,
399/// and never silently.
400#[derive(Clone, Debug, PartialEq, Eq)]
401pub struct ReflectWarning {
402    /// Where the data came from.
403    pub source: String,
404    /// The type that has no such field.
405    pub type_name: &'static str,
406    /// The field the data gave.
407    pub field: String,
408    /// The path to the value of that type.
409    pub path: String,
410}
411
412impl fmt::Display for ReflectWarning {
413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414        write!(
415            f,
416            "{}: `{}` has no field `{}`, so it was left out",
417            self.source, self.type_name, self.field
418        )?;
419        if !self.path.is_empty() {
420            write!(f, " (at `{}`)", self.path)?;
421        }
422        Ok(())
423    }
424}
425
426/// A value that does not fit its type.
427#[derive(Clone, Debug, PartialEq)]
428pub struct ReflectError {
429    /// Where the data came from.
430    pub source: String,
431    /// The path to the value: `Health.max`, `layers[2]`; empty for the
432    /// value itself.
433    pub path: String,
434    /// What is wrong.
435    pub kind: ReflectErrorKind,
436}
437
438/// What is wrong with a value: see [`ReflectError`].
439///
440/// Non-exhaustive (ADR-0038): types that need more of the context than a
441/// value, such as handles, brought more ways to fail.
442#[derive(Clone, Debug, PartialEq)]
443#[non_exhaustive]
444pub enum ReflectErrorKind {
445    /// The value is of another sort.
446    Expected {
447        /// What the type needs: "an integer".
448        expected: &'static str,
449        /// What the value is.
450        found: &'static str,
451    },
452    /// A number the type cannot hold.
453    OutOfRange {
454        /// The type.
455        type_name: &'static str,
456        /// The number, as written.
457        value: String,
458    },
459    /// A name that is none of the enum's variants.
460    UnknownVariant {
461        /// The enum.
462        type_name: &'static str,
463        /// The name the data gave.
464        found: String,
465        /// The variants it could be.
466        variants: &'static [&'static str],
467    },
468    /// A color that is not `#rrggbb` or `#rrggbbaa`.
469    BadColor(String),
470    /// An array of the wrong length.
471    WrongLength {
472        /// How many elements the type needs.
473        expected: usize,
474        /// How many there are.
475        found: usize,
476    },
477    /// An object lacks a member the type needs.
478    MissingField {
479        /// The member.
480        field: &'static str,
481    },
482    /// Reading the value needs what the context does not have, such as the
483    /// asset server.
484    NoContext {
485        /// What it needs: "the asset server, to load an asset".
486        needs: &'static str,
487    },
488    /// A path that is not an asset path, or not one of the type's.
489    BadAssetPath {
490        /// The path the data gave.
491        path: String,
492        /// Why not.
493        reason: String,
494    },
495    /// A name the context knows nothing of, such as a clip's or a
496    /// collision layer's.
497    UnknownName {
498        /// What it should name: "clip".
499        what: &'static str,
500        /// The name the data gave.
501        name: String,
502    },
503}
504
505impl fmt::Display for ReflectError {
506    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507        write!(f, "{}: ", self.source)?;
508        if !self.path.is_empty() {
509            write!(f, "at `{}`: ", self.path)?;
510        }
511        match &self.kind {
512            ReflectErrorKind::Expected { expected, found } => {
513                write!(f, "expected {expected}, found {found}")
514            }
515            ReflectErrorKind::OutOfRange { type_name, value } => {
516                write!(f, "{value} does not fit in a `{type_name}`")
517            }
518            ReflectErrorKind::UnknownVariant {
519                type_name,
520                found,
521                variants,
522            } => write!(
523                f,
524                "`{found}` is not a `{type_name}`: it is one of {}",
525                variants.join(", ")
526            ),
527            ReflectErrorKind::BadColor(text) => {
528                write!(f, "`{text}` is not a color: write `#rrggbb` or `#rrggbbaa`")
529            }
530            ReflectErrorKind::WrongLength { expected, found } => {
531                write!(f, "expected {expected} elements, found {found}")
532            }
533            ReflectErrorKind::MissingField { field } => write!(f, "`{field}` is missing"),
534            ReflectErrorKind::NoContext { needs } => {
535                write!(
536                    f,
537                    "reading this needs {needs}, which the reader was not given"
538                )
539            }
540            ReflectErrorKind::BadAssetPath { path, reason } => {
541                write!(f, "`{path}` is not an asset path for this: {reason}")
542            }
543            ReflectErrorKind::UnknownName { what, name } => {
544                write!(f, "there is no {what} named `{name}`")
545            }
546        }
547    }
548}
549
550impl Error for ReflectError {}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555
556    #[test]
557    fn the_path_is_restored_whatever_the_field_returns() {
558        let mut cx = ReflectContext::new("level.klvl");
559        let failed: Result<(), ReflectError> = cx.field("entities", |cx| {
560            cx.index(3, |cx| {
561                cx.field("Health", |cx| Err(cx.expected("an integer", &Value::Null)))
562            })
563        });
564        let error = failed.expect_err("an error");
565        assert_eq!(error.path, "entities[3].Health");
566        assert_eq!(
567            error.to_string(),
568            "level.klvl: at `entities[3].Health`: expected an integer, found null"
569        );
570        // The failed field left nothing behind on the path.
571        assert_eq!(cx.path(), "");
572        cx.field("a", |cx| cx.unknown_field("A", "b"));
573        assert_eq!(
574            cx.warnings()[0].to_string(),
575            "level.klvl: `A` has no field `b`, so it was left out (at `a`)"
576        );
577    }
578}