Skip to main content

tvm_ffi/extra/
visit_error_context.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! The context an error carries to name the nodes a failed visit unwound
21//! through.
22
23// The Rust side of C++ `tvm/ffi/extra/visit_error_context.h`.
24
25use crate::any::AnyView;
26use crate::collections::array::Array;
27use crate::derive::Object;
28use crate::error::{Error, Result};
29use crate::function::Function;
30use crate::object::{self, Object, ObjectArc, ObjectRef, ObjectRefCore};
31use crate::reflection::{AccessPath, TypeAttrColumn};
32use crate::tvm_ffi_sys::{TVMFFIAny, TVMFFIObject, TVMFFITypeIndex};
33use crate::type_traits::AnyCompatible;
34
35/// The payload that `Error::extra_context` carries to name the nodes a failed
36/// visit unwound through, laid out as the C++ `VisitErrorContextObj`.
37#[repr(C)]
38#[derive(Object)]
39#[object(type_key = "ffi.VisitErrorContext", final)]
40pub(crate) struct VisitErrorContextObj {
41    base_: Object,
42    /// Visited nodes, innermost first; an entry may be `None`.
43    reverse_visit_pattern: Array<Option<ObjectRef>>,
44    /// The `extra_context` the error carried before this context replaced it.
45    prev_error_context: Option<ObjectRef>,
46}
47
48/// The type attribute holding a root type's visit-error enrichment hook,
49/// `(Error, ObjectRef) -> Error`, as C++ `type_attr::kEnrichVisitError`.
50const ENRICH_VISIT_ERROR_ATTR: &str = "__ffi_enrich_visit_error__";
51
52/// `context` as a visit error context, if it is one.
53fn as_context(context: &ObjectRef) -> Option<&VisitErrorContextObj> {
54    let object = ObjectArc::as_ptr(ObjectRef::data(context));
55    // SAFETY: `context` keeps its object alive; the type is checked first.
56    unsafe {
57        object::is_instance_of::<VisitErrorContextObj>((*object.cast::<TVMFFIObject>()).type_index)
58            .then(|| &*object.cast::<VisitErrorContextObj>())
59    }
60}
61
62/// The access paths from `root` to where a failed structural traversal of `root`
63/// stopped, as recorded in `error`'s visit context; empty if `error` has none.
64// As C++ `VisitErrorContext::TryGetFromError` then `FindAccessPaths`, full matches only.
65pub fn find_access_paths<R>(root: &R, error: &Error) -> Result<Array<AccessPath>>
66where
67    R: ObjectRefCore + AnyCompatible,
68{
69    let Some(context) = error
70        .extra_context()
71        .filter(|context| as_context(context).is_some())
72    else {
73        return Ok(Array::default());
74    };
75    Function::get_global("ffi.VisitErrorContext.FindAccessPaths")?
76        .call_packed(&[
77            AnyView::from(root),
78            AnyView::from(context),
79            AnyView::from(&false),
80        ])?
81        .try_into()
82}
83
84/// Pass `error` from a traversal of the borrowed `root` to the hook that
85/// `root`'s exact type registers, if `root` is an object and `error` carries a
86/// visit context. A missing or failing hook keeps the original error.
87// As C++ `VisitErrorContext::EnrichVisitError`, called once per public traversal.
88#[cold]
89#[inline(never)]
90pub(crate) fn enrich_visit_error(error: Error, root: TVMFFIAny) -> Error {
91    if root.type_index < TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32
92        || error.extra_context().and_then(as_context).is_none()
93    {
94        return error;
95    }
96    // Looked up on each error, so a column or hook registered later is found.
97    let Some(hook) = TypeAttrColumn::lookup(ENRICH_VISIT_ERROR_ATTR)
98        .and_then(|column| column.get(root.type_index))
99        .and_then(|hook| Function::try_from(hook).ok())
100    else {
101        return error;
102    };
103    // SAFETY: the traversal's caller keeps `root` live through this call.
104    let root = unsafe { AnyView::from_raw_ffi_any(root) };
105    match hook
106        .call_packed(&[AnyView::from(&error), root])
107        .and_then(Error::try_from)
108    {
109        Ok(enriched) => enriched,
110        Err(_) => error,
111    }
112}
113
114/// Name the visited object in `raw` in the error's visit context.
115// As C++ `detail::UpdateVisitErrorContext`.
116#[cold]
117pub(crate) fn update_visit_error_context(mut error: Error, raw: TVMFFIAny) -> Error {
118    // Copy-on-write at each level: the Error, its context and the context's pattern
119    // are each copied only when shared, so an error owned by the unwinding frame is
120    // appended in place.
121    if raw.type_index < TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32 {
122        return error;
123    }
124    // SAFETY: the traversal input remains live during annotation. Conversion
125    // acquires ownership before the temporary view ends; raw is an object tag.
126    let Ok(node) = ObjectRef::try_from(unsafe { AnyView::from_raw_ffi_any(raw) }) else {
127        return error;
128    };
129    // Callback, policy and default descent can report the same frame.
130    if let Some(context) = error.extra_context().and_then(as_context)
131        && context
132            .reverse_visit_pattern
133            .iter()
134            .next_back()
135            .and_then(Option::as_ref)
136            .is_some_and(|last| last.same_as(&node))
137    {
138        return error;
139    }
140    let slot = error.extra_context_mut();
141    let previous = slot.take();
142    let context = match previous {
143        Some(previous) if as_context(&previous).is_some() => {
144            // SAFETY: `previous` was checked to be a `VisitErrorContextObj`.
145            let mut context = unsafe {
146                ObjectArc::from_raw(
147                    ObjectArc::into_raw(ObjectRef::into_data(previous))
148                        .cast::<VisitErrorContextObj>(),
149                )
150            };
151            if !ObjectArc::is_unique(&context) {
152                context = ObjectArc::new(VisitErrorContextObj {
153                    base_: Object::new(),
154                    reverse_visit_pattern: context.reverse_visit_pattern.clone(),
155                    prev_error_context: context.prev_error_context.clone(),
156                });
157            }
158            // SAFETY: this handle is the context's only reference.
159            unsafe {
160                (*ObjectArc::as_mut_ptr(&mut context))
161                    .reverse_visit_pattern
162                    .push(Some(node))
163            };
164            context
165        }
166        previous => ObjectArc::new(VisitErrorContextObj {
167            base_: Object::new(),
168            reverse_visit_pattern: Array::from_vec(vec![Some(node)]),
169            prev_error_context: previous,
170        }),
171    };
172    // SAFETY: every object starts with the root `Object` header.
173    *slot = Some(unsafe {
174        ObjectRef::from_data(ObjectArc::from_raw(
175            ObjectArc::into_raw(context).cast::<Object>(),
176        ))
177    });
178    error
179}