unityrs_core/env/
object_tree.rs1use std::sync::Arc;
6
7use super::resource_data::top_container;
8use super::{DerefError, Environment};
9use crate::container::View;
10use crate::object::ObjectRef;
11use crate::provider::{NoTree, ScriptIdent, TreeRef, TreeRequest, TreeSource};
12use crate::typetree::Tree;
13use crate::walk::{ParseError, ReadDetail, ReadError, ReadErrorKind};
14
15fn is_value_error(e: &ParseError) -> bool {
22 match e {
23 ParseError::CheckRead { .. }
24 | ParseError::Deref(DerefError::Null)
25 | ParseError::NoTypeTree {
26 why: Some(NoTree::NoEntry),
27 ..
28 } => true,
29 ParseError::Provider(p) => {
30 p.python_exception
31 .as_ref()
32 .is_some_and(crate::provider::PythonException::is_value_error)
33 && p.limit.is_none()
34 && p.memory.is_none()
35 && p.allocator.is_none()
36 }
37 ParseError::Read(r) => match &r.detail {
38 ReadDetail::Eof { exception, .. }
39 | ReadDetail::BoostEof { exception, .. }
40 | ReadDetail::Python(exception) => {
41 matches!(
42 *exception,
43 "ValueError"
44 | "UnicodeError"
45 | "UnicodeDecodeError"
46 | "UnicodeEncodeError"
47 | "UnicodeTranslateError"
48 )
49 }
50 ReadDetail::NegativeLength(_)
51 | ReadDetail::ArrayChildren
52 | ReadDetail::PairChildren
53 | ReadDetail::RefTypeNotFound => true,
54 ReadDetail::NoRefTypes { reader, absent } => {
55 *reader == crate::value::ReadBy::Boost || !absent
56 }
57 ReadDetail::Stream(e) => e.exception() == "ValueError",
58 ReadDetail::RefTypeNoTree
59 | ReadDetail::Limit(_)
60 | ReadDetail::Charge(_)
61 | ReadDetail::Tree(_) => false,
62 },
63 _ => false,
64 }
65}
66
67#[derive(Debug, thiserror::Error)]
70pub enum MonoBehaviourError {
71 #[error("MonoBehaviour detected, but no typetree_generator set to the environment!")]
73 NoGenerator,
74 #[error("Failed to generate MonoBehaviour node for {}{}{} of {}!", PythonStr(&.0.namespace),
76 if .0.namespace.is_empty() { "" } else { "." }, PythonStr(&.0.class), PythonStr(&.0.assembly))]
77 MissingNode(ScriptIdent),
78 #[error(transparent)]
80 Parse(#[from] ParseError),
81}
82const _: () = crate::send_sync::<MonoBehaviourError>();
83
84struct PythonStr<'a>(&'a crate::RawStr);
87impl std::fmt::Display for PythonStr<'_> {
88 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 for chunk in self.0.as_bytes().utf8_chunks() {
90 f.write_str(chunk.valid())?;
91 for &byte in chunk.invalid() {
92 write!(f, "\\u{:04x}", 0xdc00 + u16::from(byte))?;
93 }
94 }
95 Ok(())
96 }
97}
98
99impl MonoBehaviourError {
100 #[must_use]
102 pub fn is_value_error(&self) -> bool {
103 match self {
104 Self::NoGenerator | Self::MissingNode(_) => true,
105 Self::Parse(e) => is_value_error(e),
106 }
107 }
108}
109
110impl Environment {
111 pub fn object_tree(
137 &self,
138 obj: &ObjectRef,
139 nodes: Option<&Arc<Tree>>,
140 ) -> Result<Option<TreeRef>, ParseError> {
141 let _top = top_container(obj.file());
142 let found = self.room(|| obj.tree(nodes))?;
143 let Some(class_tree) = found else {
144 return Ok(None);
145 };
146 let chain = &obj.file().context().providers;
147 if !matches!(class_tree.source, TreeSource::Provider(_))
148 || class_tree.tree.root_type() != b"MonoBehaviour"
149 || !chain.accepts_scripts()
150 {
151 return Ok(Some(class_tree));
152 }
153 match self.generate_monobehaviour_node(obj, Some(&class_tree.tree)) {
154 Ok(tree) => Ok(Some(tree)),
155 Err(e) if e.is_value_error() => Ok(Some(class_tree)),
156 Err(MonoBehaviourError::Parse(e)) => Err(e),
157 Err(_) => Ok(Some(class_tree)),
158 }
159 }
160
161 pub fn generate_monobehaviour_node(
165 &self,
166 obj: &ObjectRef,
167 nodes: Option<&Arc<Tree>>,
168 ) -> Result<TreeRef, MonoBehaviourError> {
169 let _top = top_container(obj.file());
170 let chain = &obj.file().context().providers;
171 if !chain.accepts_scripts() {
172 return Err(MonoBehaviourError::NoGenerator);
173 }
174 let head = self.room(|| obj.parse_monobehaviour_head(nodes))?;
175 let ident = self.script_ident(obj, &head)?;
176 let unversioned = crate::UnityVersion::from_packed(0);
180 let version = obj.file().version().map_or(&unversioned, |v| &v.version);
181 let req = TreeRequest {
182 class_id: obj.class_id(),
183 version,
184 script: Some(&ident),
185 };
186 chain
187 .lookup(&req)
188 .map_err(ParseError::from)?
189 .ok_or(MonoBehaviourError::MissingNode(ident))
190 }
191
192 fn script_ident(
196 &self,
197 obj: &ObjectRef,
198 head: &crate::Parsed,
199 ) -> Result<ScriptIdent, ParseError> {
200 let attr_error = || {
201 ParseError::Read(ReadError {
202 kind: ReadErrorKind::Other,
203 at: 0,
204 detail: ReadDetail::Python("AttributeError"),
205 })
206 };
207 let view = View::new(head).ok_or_else(attr_error)?;
208 let script = view
209 .attr(view.root(), b"m_Script")
210 .map_err(|_| attr_error())?;
211 let pptr = view.pptr(script).map_err(|_| attr_error())?;
212 let target = match self.deref(obj.file(), pptr) {
214 Ok(t) => t,
215 Err(e) => return Err(ParseError::Deref(e)),
216 };
217 let script = self.room(|| target.read_typetree_object(None, false))?;
219 if script.bytes_read != i64::from(target.info().byte_size) {
223 return Err(ParseError::Read(ReadError {
224 kind: ReadErrorKind::Other,
225 at: 0,
226 detail: ReadDetail::Python("ValueError"),
227 }));
228 }
229 let sview = View::new(&script).ok_or_else(attr_error)?;
230 let field = |name: &[u8]| {
231 sview
232 .attr(sview.root(), name)
233 .map(|n| n.value())
234 .map_err(|_| attr_error())
235 };
236 let text = |value: &crate::Value| {
238 use crate::Value;
239 let formatted = match value {
240 Value::Str(s) => return Ok(s.clone()),
241 Value::Int(i) => i.to_string(),
242 Value::UInt(i) => i.to_string(),
243 Value::Bool(b) => if *b { "True" } else { "False" }.to_owned(),
244 Value::F32(b) => crate::pyfloat::py_float_repr(f64::from(f32::from_bits(*b))),
245 Value::F64(b) => crate::pyfloat::py_float_repr(f64::from_bits(*b)),
246 _ => return Err(attr_error()),
247 };
248 crate::RawStr::charged(formatted.as_bytes(), target.file().meter())
249 .map_err(|e| ParseError::Read(crate::walk::charge_error(0, e)))
250 };
251 let namespace = text(field(b"m_Namespace")?)?;
252 Ok(ScriptIdent {
253 assembly: match field(b"m_AssemblyName")? {
254 crate::Value::Str(s) => s.clone(),
255 _ => return Err(attr_error()),
256 },
257 namespace,
258 class: text(field(b"m_ClassName")?)?,
259 })
260 }
261}