Skip to main content

bevy_reflect/path/
access.rs

1//! Representation for individual element accesses within a path.
2
3use alloc::borrow::Cow;
4use bevy_reflect_derive::Reflect;
5use core::fmt;
6
7use super::error::AccessErrorKind;
8use crate::{enums::VariantType, AccessError, PartialReflect, ReflectKind, ReflectMut, ReflectRef};
9
10type InnerResult<T> = Result<T, AccessErrorKind>;
11
12/// A singular element access within a path.
13/// Multiple accesses can be combined into a [`ParsedPath`](super::ParsedPath).
14///
15/// Can be applied to a [`dyn Reflect`](crate::Reflect) to get a reference to the targeted element.
16#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
17#[reflect(Debug, Clone, PartialEq, PartialOrd, Hash)]
18pub enum Access<'a> {
19    /// A name-based field access on a struct.
20    Field(Cow<'a, str>),
21    /// A index-based field access on a struct.
22    FieldIndex(usize),
23    /// An index-based access on a tuple.
24    TupleIndex(usize),
25    /// An index-based access on a list.
26    ListIndex(usize),
27}
28
29impl fmt::Display for Access<'_> {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            Access::Field(field) => write!(f, ".{field}"),
33            Access::FieldIndex(index) => write!(f, "#{index}"),
34            Access::TupleIndex(index) => write!(f, ".{index}"),
35            Access::ListIndex(index) => write!(f, "[{index}]"),
36        }
37    }
38}
39
40impl<'a> Access<'a> {
41    /// Converts this into an "owned" value.
42    ///
43    /// If the [`Access`] is of variant [`Field`](Access::Field),
44    /// the field's [`Cow<str>`] will be converted to its owned
45    /// counterpart, which doesn't require a reference.
46    pub fn into_owned(self) -> Access<'static> {
47        match self {
48            Self::Field(value) => Access::Field(Cow::Owned(value.into_owned())),
49            Self::FieldIndex(value) => Access::FieldIndex(value),
50            Self::TupleIndex(value) => Access::TupleIndex(value),
51            Self::ListIndex(value) => Access::ListIndex(value),
52        }
53    }
54
55    pub(super) fn element<'r>(
56        &self,
57        base: &'r dyn PartialReflect,
58        offset: Option<usize>,
59    ) -> Result<&'r dyn PartialReflect, AccessError<'a>> {
60        self.element_inner(base)
61            .and_then(|opt| opt.ok_or(AccessErrorKind::MissingField(base.reflect_kind())))
62            .map_err(|err| err.with_access(self.clone(), offset))
63    }
64
65    fn element_inner<'r>(
66        &self,
67        base: &'r dyn PartialReflect,
68    ) -> InnerResult<Option<&'r dyn PartialReflect>> {
69        use ReflectRef::*;
70
71        let invalid_variant =
72            |expected, actual| AccessErrorKind::IncompatibleEnumVariantTypes { expected, actual };
73
74        match (self, base.reflect_ref()) {
75            (Self::Field(field), Struct(struct_ref)) => Ok(struct_ref.field(field.as_ref())),
76            (Self::Field(field), Enum(enum_ref)) => match enum_ref.variant_type() {
77                VariantType::Struct => Ok(enum_ref.field(field.as_ref())),
78                actual => Err(invalid_variant(VariantType::Struct, actual)),
79            },
80            (&Self::FieldIndex(index), Struct(struct_ref)) => Ok(struct_ref.field_at(index)),
81            (&Self::FieldIndex(index), Enum(enum_ref)) => match enum_ref.variant_type() {
82                VariantType::Struct => Ok(enum_ref.field_at(index)),
83                actual => Err(invalid_variant(VariantType::Struct, actual)),
84            },
85            (Self::Field(_) | Self::FieldIndex(_), actual) => {
86                Err(AccessErrorKind::IncompatibleTypes {
87                    expected: ReflectKind::Struct,
88                    actual: actual.into(),
89                })
90            }
91
92            (&Self::TupleIndex(index), TupleStruct(tuple)) => Ok(tuple.field(index)),
93            (&Self::TupleIndex(index), Tuple(tuple)) => Ok(tuple.field(index)),
94            (&Self::TupleIndex(index), Enum(enum_ref)) => match enum_ref.variant_type() {
95                VariantType::Tuple => Ok(enum_ref.field_at(index)),
96                actual => Err(invalid_variant(VariantType::Tuple, actual)),
97            },
98            (Self::TupleIndex(_), actual) => Err(AccessErrorKind::IncompatibleTypes {
99                expected: ReflectKind::Tuple,
100                actual: actual.into(),
101            }),
102
103            (&Self::ListIndex(index), List(list)) => Ok(list.get(index)),
104            (&Self::ListIndex(index), Array(list)) => Ok(list.get(index)),
105            (Self::ListIndex(_), actual) => Err(AccessErrorKind::IncompatibleTypes {
106                expected: ReflectKind::List,
107                actual: actual.into(),
108            }),
109        }
110    }
111
112    pub(super) fn element_mut<'r>(
113        &self,
114        base: &'r mut dyn PartialReflect,
115        offset: Option<usize>,
116    ) -> Result<&'r mut dyn PartialReflect, AccessError<'a>> {
117        let kind = base.reflect_kind();
118
119        self.element_inner_mut(base)
120            .and_then(|maybe| maybe.ok_or(AccessErrorKind::MissingField(kind)))
121            .map_err(|err| err.with_access(self.clone(), offset))
122    }
123
124    fn element_inner_mut<'r>(
125        &self,
126        base: &'r mut dyn PartialReflect,
127    ) -> InnerResult<Option<&'r mut dyn PartialReflect>> {
128        use ReflectMut::*;
129
130        let invalid_variant =
131            |expected, actual| AccessErrorKind::IncompatibleEnumVariantTypes { expected, actual };
132
133        match (self, base.reflect_mut()) {
134            (Self::Field(field), Struct(struct_mut)) => Ok(struct_mut.field_mut(field.as_ref())),
135            (Self::Field(field), Enum(enum_mut)) => match enum_mut.variant_type() {
136                VariantType::Struct => Ok(enum_mut.field_mut(field.as_ref())),
137                actual => Err(invalid_variant(VariantType::Struct, actual)),
138            },
139            (&Self::FieldIndex(index), Struct(struct_mut)) => Ok(struct_mut.field_at_mut(index)),
140            (&Self::FieldIndex(index), Enum(enum_mut)) => match enum_mut.variant_type() {
141                VariantType::Struct => Ok(enum_mut.field_at_mut(index)),
142                actual => Err(invalid_variant(VariantType::Struct, actual)),
143            },
144            (Self::Field(_) | Self::FieldIndex(_), actual) => {
145                Err(AccessErrorKind::IncompatibleTypes {
146                    expected: ReflectKind::Struct,
147                    actual: actual.into(),
148                })
149            }
150
151            (&Self::TupleIndex(index), TupleStruct(tuple)) => Ok(tuple.field_mut(index)),
152            (&Self::TupleIndex(index), Tuple(tuple)) => Ok(tuple.field_mut(index)),
153            (&Self::TupleIndex(index), Enum(enum_mut)) => match enum_mut.variant_type() {
154                VariantType::Tuple => Ok(enum_mut.field_at_mut(index)),
155                actual => Err(invalid_variant(VariantType::Tuple, actual)),
156            },
157            (Self::TupleIndex(_), actual) => Err(AccessErrorKind::IncompatibleTypes {
158                expected: ReflectKind::Tuple,
159                actual: actual.into(),
160            }),
161
162            (&Self::ListIndex(index), List(list)) => Ok(list.get_mut(index)),
163            (&Self::ListIndex(index), Array(list)) => Ok(list.get_mut(index)),
164            (Self::ListIndex(_), actual) => Err(AccessErrorKind::IncompatibleTypes {
165                expected: ReflectKind::List,
166                actual: actual.into(),
167            }),
168        }
169    }
170
171    /// Returns a reference to this [`Access`]'s inner value as a [`&dyn Display`](fmt::Display).
172    pub fn display_value(&self) -> &dyn fmt::Display {
173        match self {
174            Self::Field(value) => value,
175            Self::FieldIndex(value) | Self::TupleIndex(value) | Self::ListIndex(value) => value,
176        }
177    }
178
179    pub(super) fn kind(&self) -> &'static str {
180        match self {
181            Self::Field(_) => "field",
182            Self::FieldIndex(_) => "field index",
183            Self::TupleIndex(_) | Self::ListIndex(_) => "index",
184        }
185    }
186}