You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "guan404ming (via GitHub)" <gi...@apache.org> on 2026/01/11 15:38:37 UTC

[PR] feat: Add ffi::Expected for exception-free error handling [tvm-ffi]

guan404ming opened a new pull request, #399:
URL: https://github.com/apache/tvm-ffi/pull/399

   ## Why
   
    Enable exception-free C++ API similar to Rust's Result or C++23's std::expected, as requested in #234.
   
    ## How
   
    - Add `Expected<T>` class holding either success value T or Error
    - Add `Function::CallExpected<T>()` for exception-free function calls
    - Add `is_expected` type trait and Expected handling in `unpack_call`
    - Support registering functions that return `Expected<T>`"


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3808998072

   Thanks for bringing up the discussion! I agree with keeping the design simple. While return type deduction is nice, explicit type specification is a fair trade-off to keep the API clean.
   
   I think type deduction works for most cases. For exceptions, users can simply use like `Expected<long>::Ok(x)`. For a foundational library like `tvm-ffi`, the complexity of `PartialExpected` isn't worth the marginal benefit in my opinion. This strikes the right balance between simplicity and usability.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2723622389


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,51 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      // Success - cast result to T and return Ok
+      return Expected<T>::Ok(std::move(result).cast<T>());

Review Comment:
   Nice catch. I think there is a potential edge case that we probably don't want ot try casting if `T = Any`. Here is updated implementation
   
   ```c
   if (ret_code == 0) {
     if constexpr (std::is_same_v<T, Any>) {
       return Expected<T>::Ok(std::move(result));
     } else {
       if (auto val = std::move(result).template as<T>()) {
         return Expected<T>::Ok(std::move(*val));
       } else {
         return Expected<T>::Err(Error(
             "TypeError",
             "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr(), ""));
       }
     }
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2720048302


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();

Review Comment:
   Actually we might not need both here, @tqchen would like to hear your opinion if we wanna keep one of them



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2721959809


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return data_.cast<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.
+ * \note Returns Expected<Any> to allow usage in contexts where T is inferred.
+ */
+template <typename T = Any>

Review Comment:
   Yes, that would be better. Thanks.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2732889922


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   Thanks for the detailed breakdown of the four scenarios (C0/C1 + W0/W1) which really helped clarify the design considerations. Based on my understanding, the key question is about the C0 + W1 scenario (normal Call() on a function returning Expected<T>). Here's how I see the two possible directions: 
   
   Option A: Keep current behavior (auto-unwrap)   
   ``` c                                                                                                                              
     // Current implementation                                                                                                                                                      
     if (expected_result.is_ok()) {                                                                                                                                                 
         *rv = std::move(expected_result).value();  // unwrap value                                                                                                                 
     } else {                                                                                                                                                                       
         throw std::move(expected_result).error();  // throw error                                                                                                                  
     }  
     ```                                                                                                                                                                            
     - Pros: Caller uses Call<T>() and gets the value directly                                                                                                                      
     - Cons: Cannot distinguish "returned error" from "raised error"                                                                                                                
                                                                                                                                                                                    
     Option B: No unwrap, return Expected directly                                                                                                                                  
     ```c
     // Proposed change                                                                                                                                                             
     *rv = f(...);  // return Expected as-is                                                                                                                                        
     ```
     - Pros: Clear distinction between returned vs raised errors                                                                                                                    
     - Cons: Caller must use Call<Expected<T>>() and handle it explicitly 
     
   Personally, I'd slightly lean toward Option B after @tqchen's breakdown. If a function explicitly chooses to return Expected, I think we should respect that and let the caller receive it directly.                                                                                                                                             
   
   I'd like to confirm your preference before updating the implementation. Happy to add regression tests or update implementation for whichever approach we go with.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2732904347


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   agree option B is better



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3819103124

   Thanks for the feedback! After reviewing the design options and looking at real-world patterns, I agree that we should support implicit conversion. Here is some of my note to clarify all thing:
   
   ### Pros and Cons
   
   | Approach | Success Return | Error Return | Pros | Cons |
   |----------|---------------|--------------|------|------|
   | Factory functions (current) | `return ExpectedOk(x);` | `return ExpectedErr<T>(err);` | Explicit intent | Asymmetric API - Ok deduces type, Err requires explicit `<T>` |
   | Static methods only | `return Expected<T>::Ok(x);` | `return Expected<T>::Err(err);` | No extra functions | Verbose, type repeated |
   | Implicit conversion | `return x;` | `return Error(...);` | Concise, symmetric, follows C++ conventions | Slightly less explicit |
   
   ### C++ Standard Precedent
   
   From [cppreference std::expected](https://en.cppreference.com/w/cpp/utility/expected):
   
   >`std::expected<T,E>` provides implicit conversion from `T` for the success case, and uses `std::unexpected<E>` for errors.
   
   Similarly, `std::optional<T>` allows implicit conversion from `T`.
   
   ### XGrammar Current Pattern
   
   Looking at [XGrammar's exception.h](https://github.com/mlc-ai/xgrammar/blob/main/include/xgrammar/exception.h), they currently use traditional C++ exceptions:
   
   ```cpp
   // Current XGrammar (exceptions)
   Grammar Grammar::FromJSON(const std::string& json) {
       if (!valid) throw InvalidJSONError("...");
       return grammar;
   }
   
   // With Expected + implicit conversion
   Expected<Grammar> Grammar::FromJSON(const std::string& json) {
       if (!valid) return Error("InvalidJSONError", "...");
       return grammar;
   }
   ```
   
   The implicit conversion approach makes migration from exception-based code more natural.
   
   ### Implementation
   
   I think to add implicit converting constructors would be ideal to handle this feat:
   
   ```cpp
   template <typename T>
   class Expected {
    public:
     Expected(T value) : data_(Any(std::move(value))) {}      // implicit from T
     Expected(Error error) : data_(Any(std::move(error))) {}  // implicit from Error
     // ...
   };
   ```
   
   This eliminates the asymmetry issue where `ExpectedOk` deduces type but `ExpectedErr<T>` requires explicit specification. In this way, we then could remove `ExpectedOk()`, `ExpectedErr()`  factory functions and `Expected<T>::Ok()`, `Expected<T>::Err()` static methods accordingly. Does this approach sound reasonable? Happy to discuss if there are any concerns or alternative suggestions.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3835147350

   Some final comments, @Kathryn-cat @DarkSharpness @Seven-Streams  please take another look


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2755387816


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,64 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = std::move(result).template as<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",
+                     "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr(),
+                     "");

Review Comment:
   This one makes sense to me, just updated.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2755677357


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {

Review Comment:
   T should take higher priority than Error as that is the fast path, always hold the value as optional first and move that value, avoid double has value checking



##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",
+                     "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr() +
+                         ", but got " + result.GetTypeKey(),
+                     "");
+      }
+    } else if (ret_code == -2) {
+      // Environment error already set (e.g., Python KeyboardInterrupt)
+      // We still throw this since it's a signal, not a normal error
+      throw ::tvm::ffi::EnvErrorAlreadySet();
+    } else {
+      // Error occurred - retrieve from safe call context and return Err
+      return details::MoveFromSafeCallRaised();

Review Comment:
   Explicitly use Unexpected



##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,9 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {
+    *rv = f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name,

Review Comment:
   looks like this is not necessary, please cross check



##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",
+                     "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr() +
+                         ", but got " + result.GetTypeKey(),
+                     "");
+      }
+    } else if (ret_code == -2) {
+      // Environment error already set (e.g., Python KeyboardInterrupt)
+      // We still throw this since it's a signal, not a normal error

Review Comment:
   i think explicitly throw here is not as good since it breaks the assumption of no exception. Actually we find it is better to further unify things a bit, i made https://github.com/apache/tvm-ffi/pull/425 so we don't have to handle -2 



##########
include/tvm/ffi/function_details.h:
##########
@@ -67,6 +72,19 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {
+  using value_type = void;
+};
+
+template <typename T>
+struct is_expected<Expected<T>> : std::true_type {
+  using value_type = T;
+};
+
+template <typename T>
+inline constexpr bool is_expected_v = is_expected<T>::value;

Review Comment:
   not sure if this is needed anymore given the new convention



##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);

Review Comment:
   move optional bvalue should be `*std::move(val)`, would be good to confirm with genai



##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",

Review Comment:
   I know it is a bit more verbose, but i think it is helpful to always use Unexpected(Errror()), and ban implicit conversion from Error



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760376696


##########
include/tvm/ffi/function_details.h:
##########
@@ -67,6 +72,19 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {
+  using value_type = void;
+};
+
+template <typename T>
+struct is_expected<Expected<T>> : std::true_type {
+  using value_type = T;
+};
+
+template <typename T>
+inline constexpr bool is_expected_v = is_expected<T>::value;

Review Comment:
   I think i think it is worthwhile minimizing the code mainly because is_expected_v may be a future std type, the test uscase seems to be a duplication, so still good to remove here



##########
tests/cpp/test_expected.cc:
##########
@@ -0,0 +1,347 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <gtest/gtest.h>
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/container/array.h>
+#include <tvm/ffi/error.h>
+#include <tvm/ffi/expected.h>
+#include <tvm/ffi/function.h>
+#include <tvm/ffi/memory.h>
+#include <tvm/ffi/optional.h>
+#include <tvm/ffi/reflection/registry.h>
+
+#include "./testing_object.h"
+
+namespace {
+
+using namespace tvm::ffi;
+using namespace tvm::ffi::testing;
+
+// Test implicit construction from success value
+TEST(Expected, BasicOk) {
+  Expected<int> result = 42;
+
+  EXPECT_TRUE(result.is_ok());
+  EXPECT_FALSE(result.is_err());
+  EXPECT_TRUE(result.has_value());
+  EXPECT_EQ(result.value(), 42);
+  EXPECT_EQ(result.value_or(0), 42);
+}
+
+// Test implicit construction from error
+TEST(Expected, BasicErr) {
+  Expected<int> result = Error("RuntimeError", "test error", "");
+
+  EXPECT_FALSE(result.is_ok());
+  EXPECT_TRUE(result.is_err());
+  EXPECT_FALSE(result.has_value());
+
+  Error err = result.error();
+  EXPECT_EQ(err.kind(), "RuntimeError");
+  EXPECT_EQ(err.message(), "test error");
+}
+
+// Test explicit construction via Unexpected wrapper
+TEST(Expected, UnexpectedWrapper) {
+  Expected<int> result = Unexpected(Error("RuntimeError", "unexpected error", ""));
+
+  EXPECT_FALSE(result.is_ok());
+  EXPECT_TRUE(result.is_err());
+  EXPECT_EQ(result.error().kind(), "RuntimeError");
+  EXPECT_EQ(result.error().message(), "unexpected error");
+}
+
+// Test Unexpected deduction guide and error() accessor
+TEST(Expected, UnexpectedAPI) {
+  auto u = Unexpected(Error("TypeError", "type mismatch", ""));
+  static_assert(std::is_same_v<decltype(u), Unexpected<Error>>);
+
+  EXPECT_EQ(u.error().kind(), "TypeError");
+  EXPECT_EQ(u.error().message(), "type mismatch");
+
+  Error moved_err = std::move(u).error();
+  EXPECT_EQ(moved_err.kind(), "TypeError");
+}
+
+// Test value_or with error
+TEST(Expected, ValueOrWithError) {
+  Expected<int> result = Error("RuntimeError", "test error", "");
+  EXPECT_EQ(result.value_or(99), 99);
+}
+
+// Test with ObjectRef types
+TEST(Expected, ObjectRefType) {
+  Expected<TInt> result = TInt(123);
+
+  EXPECT_TRUE(result.is_ok());
+  EXPECT_EQ(result.value()->value, 123);
+}
+
+// Test with String type
+TEST(Expected, StringType) {
+  Expected<String> result = String("hello");
+
+  EXPECT_TRUE(result.is_ok());
+  EXPECT_EQ(result.value(), "hello");
+
+  Expected<String> err_result = Error("ValueError", "bad string", "");
+  EXPECT_TRUE(err_result.is_err());
+}
+
+// Test TypeTraits conversion: Expected -> Any -> Expected
+TEST(Expected, TypeTraitsRoundtrip) {
+  Expected<int> original = 42;
+
+  // Convert to Any (should unwrap to int)
+  Any any_value = original;
+  EXPECT_EQ(any_value.cast<int>(), 42);
+
+  // Convert back to Expected (should reconstruct as Ok)
+  Expected<int> recovered = any_value.cast<Expected<int>>();
+  EXPECT_TRUE(recovered.is_ok());
+  EXPECT_EQ(recovered.value(), 42);
+}
+
+// Test TypeTraits conversion with Error
+TEST(Expected, TypeTraitsErrorRoundtrip) {
+  Expected<int> original = Error("TypeError", "conversion failed", "");
+
+  // Convert to Any (should unwrap to Error)
+  Any any_value = original;
+  EXPECT_TRUE(any_value.as<Error>().has_value());
+
+  // Convert back to Expected (should reconstruct as Err)
+  Expected<int> recovered = any_value.cast<Expected<int>>();
+  EXPECT_TRUE(recovered.is_err());
+  EXPECT_EQ(recovered.error().kind(), "TypeError");
+}
+
+// Test move semantics
+TEST(Expected, MoveSemantics) {
+  Expected<String> result = String("test");
+  EXPECT_TRUE(result.is_ok());
+
+  String value = std::move(result).value();
+  EXPECT_EQ(value, "test");
+}
+
+// Test CallExpected with normal function
+TEST(Expected, CallExpectedNormal) {
+  auto safe_add = [](int a, int b) { return a + b; };
+
+  Function func = Function::FromTyped(safe_add);
+  Expected<int> result = func.CallExpected<int>(5, 3);
+
+  EXPECT_TRUE(result.is_ok());
+  EXPECT_EQ(result.value(), 8);
+}
+
+// Test CallExpected with throwing function
+TEST(Expected, CallExpectedThrowing) {
+  auto throwing_func = [](int a) -> int {
+    if (a < 0) {
+      TVM_FFI_THROW(ValueError) << "Negative value not allowed";
+    }
+    return a * 2;
+  };
+
+  Function func = Function::FromTyped(throwing_func);
+
+  // Normal case
+  Expected<int> result_ok = func.CallExpected<int>(5);
+  EXPECT_TRUE(result_ok.is_ok());
+  EXPECT_EQ(result_ok.value(), 10);
+
+  // Error case
+  Expected<int> result_err = func.CallExpected<int>(-1);
+  EXPECT_TRUE(result_err.is_err());
+  EXPECT_EQ(result_err.error().kind(), "ValueError");
+}
+
+// Test that lambda returning Expected works directly
+TEST(Expected, LambdaDirectCall) {
+  auto safe_divide = [](int a, int b) -> Expected<int> {
+    if (b == 0) {
+      return Error("ValueError", "Division by zero", "");
+    }
+    return a / b;
+  };
+
+  // Direct call to lambda should work
+  Expected<int> result = safe_divide(10, 2);
+  EXPECT_TRUE(result.is_ok());
+  EXPECT_EQ(result.value(), 5);
+
+  // Check the value can be extracted
+  int val = result.value();
+  EXPECT_EQ(val, 5);
+
+  // Check assigning to Any works
+  Any any_val = result.value();
+  EXPECT_EQ(any_val.cast<int>(), 5);
+}
+
+// Test registering function that returns Expected
+TEST(Expected, RegisterExpectedReturning) {
+  auto safe_divide = [](int a, int b) -> Expected<int> {
+    if (b == 0) {
+      return Error("ValueError", "Division by zero", "");
+    }
+    return a / b;
+  };
+
+  // Verify the FunctionInfo extracts Expected<int> as return type
+  using FuncInfo = tvm::ffi::details::FunctionInfo<decltype(safe_divide)>;
+  static_assert(std::is_same_v<FuncInfo::RetType, Expected<int>>,
+                "Return type should be Expected<int>");
+  static_assert(tvm::ffi::details::is_expected_v<FuncInfo::RetType>,

Review Comment:
   this duplicates with the is_same_v assertion on top



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3860341618

   Thanks for all reviews and input!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3796702371

   The ci passed after the upgrade!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2728849027


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   This behavior can be a bit confusing. If the ffi.Function is explicitly returning Expected Value (instead of throw using the error handling mechanism, then the function should successully return  instead of implicitly throw when error is found?
   
   Mayb need a regression testcase for this



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return data_.cast<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {

Review Comment:
   I think it is good to do round of API review, can you list all the APIs that are not conforming to std::expected, list their names, and discuss choice(i know some comes from rust API style, but good to be explicit). Would be good to list the APIs in the comment



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2774010710


##########
include/tvm/ffi/function_details.h:
##########
@@ -67,6 +72,16 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {

Review Comment:
   Thanks, just removed!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2723246677


##########
include/tvm/ffi/function_details.h:
##########
@@ -67,10 +72,23 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {
+  using value_type = void;
+};
+
+template <typename T>
+struct is_expected<Expected<T>> : std::true_type {
+  using value_type = T;
+};
+
+template <typename T>
+inline constexpr bool is_expected_v = is_expected<T>::value;
+
 // NOTE: return type can only support non-reference managed returns
 template <typename T>
-static constexpr bool RetSupported =
-    (std::is_same_v<T, Any> || std::is_void_v<T> || TypeTraits<T>::convert_enabled);
+static constexpr bool RetSupported = (std::is_same_v<T, Any> || std::is_void_v<T> ||
+                                      TypeTraits<T>::convert_enabled || is_expected_v<T>);

Review Comment:
   I think `convert_enabled` is already True here, `is_expected_v` might be redundant



##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {
+    R expected_result = f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{
+        args, Is, optional_name, f_sig}...);
+    if (expected_result.is_ok()) {
+      *rv = expected_result.value();
+    } else {
+      throw expected_result.error();

Review Comment:
   Perhaps use move?
   ```
   if (expected_result.is_ok()) {
     *rv = std::move(expected_result).value();
   } else {
     throw std::move(expected_result).error();
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2728927201


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   i think the current design unwraps `Expected<T>` at the FFI boundary. `CallExpected` use safe_call to catch the error and return `Expected<T>`; on the contrary, the normal call path would throw an error. This might seem a bit convoluted. Do you have better suggested ideas?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3750388314

   @guan404ming Thanks for the contribution! I will take a closer look sometime this week to provide a round of review.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3827265929

   > One minor thing on consistency with c++, i think it might makes sense to have Unexpected(Error()) so we are being explicit that this is an Unexpected value
   
   Thanks for the nice catch just updated with `Unexpected`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: Add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3734834977

   ## Summary of Changes
   
   Hello @guan404ming, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
   
   This pull request significantly improves the error handling capabilities within the FFI layer by introducing a new Expected<T> type. This type provides a robust, exception-free mechanism for FFI functions to communicate either a successful result or a detailed error, aligning with modern C++ practices and similar patterns in other languages. The changes ensure that FFI calls can explicitly manage potential failures without relying on exceptions for control flow, leading to more predictable and maintainable code.
   
   ### Highlights
   
   * **Introduced ffi::Expected<T>**: A new type for exception-free error handling, similar to Rust's Result or C++23's std::expected, allowing functions to return either a success value T or an Error.
   * **Added Function::CallExpected<T>()**: A new method for FFI function calls that returns an Expected<T>, converting any caught exceptions into Error objects within the Expected type.
   * **Enhanced FFI Type System**: Integrated Expected<T> into the FFI type traits (is_expected and RetSupported) and the unpack_call mechanism, enabling seamless handling of functions returning Expected<T>.
   * **Support for Registering Expected-Returning Functions**: Functions that return Expected<T> can now be registered with the FFI system, allowing them to be called from other languages or contexts while preserving the explicit error handling.
   
   🧠 **New Feature in Public Preview:** You can now enable **Memory** to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
   
   
   
   
   
   
   
   <details>
   <summary><b>Using Gemini Code Assist</b></summary>
   <br>
   
   The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
   
   <b>Invoking Gemini</b>
   
   You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
   
   Feature | Command | Description
   --- | --- | ---
   Code Review | `/gemini review` | Performs a code review for the current pull request in its current state.
   Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state.
   Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments.
   Help | `/gemini help` | Displays a list of available commands.
   
   <b>Customization</b>
   
   To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
   
   <b>Limitations & Feedback</b>
   
   Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
   
   <b>You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the [Gemini Code Assist IDE Extension](https://cloud.google.com/products/gemini/code-assist).</b>
   </details>
   
   
   
   
   [^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3793844891

   @tqchen the CI fails because tvm-ffi's DLPack version is 1.0.2, while dlpack exchange api is tested against PyTorch's native impl (DLPack 1.0.3), perhaps we need to upgrade tvm-ffi's DLPack version


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3806780249

   thanks @guan404ming , cc @Ubospica @Seven-Streams @junrushao @DarkSharpness for quick check on APIs
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Seven-Streams (via GitHub)" <gi...@apache.org>.
Seven-Streams commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3823401134

   Currently, in XGrammar's result library, [`ResultOk(...)` and `ResultErr(...)`](https://github.com/Ubospica/xgrammar/blob/15dc61d02ed24820215ca1d491d6a07ba32fff50/cpp/support/utils.h#L124-L212) are used to return success or error values, and I think it is easy to use. In addition, I also agree that implicit conversion is a good choice, since it follows [the examples in cppreference](https://en.cppreference.com/w/cpp/utility/expected.html) well.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760043569


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",
+                     "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr() +
+                         ", but got " + result.GetTypeKey(),
+                     "");
+      }
+    } else if (ret_code == -2) {
+      // Environment error already set (e.g., Python KeyboardInterrupt)
+      // We still throw this since it's a signal, not a normal error

Review Comment:
   Changed to return `Unexpected(Error("EnvErrorAlreadySet", ...))`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760049220


##########
include/tvm/ffi/function_details.h:
##########
@@ -67,6 +72,19 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {
+  using value_type = void;
+};
+
+template <typename T>
+struct is_expected<Expected<T>> : std::true_type {
+  using value_type = T;
+};
+
+template <typename T>
+inline constexpr bool is_expected_v = is_expected<T>::value;

Review Comment:
   I think the trait is still used in test assertions (test_expected.cc:213) to verify Expected type detection, so I keeping it for now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2754949642


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Wrapper to explicitly construct an Expected in the error state.
+ */
+struct Unexpected {
+  /*! \brief Construct from an error. */
+  // NOLINTNEXTLINE(google-explicit-constructor,runtime/explicit)
+  Unexpected(Error error) : error_(std::move(error)) {}
+  /*! \brief The wrapped error. */
+  Error error_;

Review Comment:
   It will be more consistent in this way, thanks. I just updated with your suggestion.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2773975239


##########
include/tvm/ffi/function_details.h:
##########
@@ -67,6 +72,16 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {

Review Comment:
   same goes for is_expected, let us remove this, i think we are good to go



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2721948756


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return data_.cast<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.
+ * \note Returns Expected<Any> to allow usage in contexts where T is inferred.
+ */
+template <typename T = Any>
+TVM_FFI_INLINE Expected<T> ExpectedErr(Error error) {
+  return Expected<T>::Err(std::move(error));
+}
+
+// TypeTraits specialization for Expected<T>
+template <typename T>
+inline constexpr bool use_default_type_traits_v<Expected<T>> = false;
+
+template <typename T>
+struct TypeTraits<Expected<T>> : public TypeTraitsBase {
+  TVM_FFI_INLINE static void CopyToAnyView(const Expected<T>& src, TVMFFIAny* result) {
+    const TVMFFIAny* src_any = reinterpret_cast<const TVMFFIAny*>(&src.data_);
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      TypeTraits<T>::MoveToAny(TypeTraits<T>::CopyFromAnyViewAfterCheck(src_any), result);

Review Comment:
   Thanks, this is more clearer.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2723612542


##########
include/tvm/ffi/function_details.h:
##########
@@ -67,10 +72,23 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {
+  using value_type = void;
+};
+
+template <typename T>
+struct is_expected<Expected<T>> : std::true_type {
+  using value_type = T;
+};
+
+template <typename T>
+inline constexpr bool is_expected_v = is_expected<T>::value;
+
 // NOTE: return type can only support non-reference managed returns
 template <typename T>
-static constexpr bool RetSupported =
-    (std::is_same_v<T, Any> || std::is_void_v<T> || TypeTraits<T>::convert_enabled);
+static constexpr bool RetSupported = (std::is_same_v<T, Any> || std::is_void_v<T> ||
+                                      TypeTraits<T>::convert_enabled || is_expected_v<T>);

Review Comment:
   You right, let me remove it.



##########
include/tvm/ffi/function_details.h:
##########
@@ -67,10 +72,23 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {
+  using value_type = void;
+};
+
+template <typename T>
+struct is_expected<Expected<T>> : std::true_type {
+  using value_type = T;
+};
+
+template <typename T>
+inline constexpr bool is_expected_v = is_expected<T>::value;
+
 // NOTE: return type can only support non-reference managed returns
 template <typename T>
-static constexpr bool RetSupported =
-    (std::is_same_v<T, Any> || std::is_void_v<T> || TypeTraits<T>::convert_enabled);
+static constexpr bool RetSupported = (std::is_same_v<T, Any> || std::is_void_v<T> ||
+                                      TypeTraits<T>::convert_enabled || is_expected_v<T>);

Review Comment:
   You're right, let me remove it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3842896148

   /gemini review


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3825401880

   One minor thing on consistency with c++, i think it might makes sense to have Unexpected(Error()) so we are being explicit that this is an Unexpected value


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760010373


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);

Review Comment:
   Verified and changed to `*std::move(val)`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2755330429


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,64 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = std::move(result).template as<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",
+                     "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr(),
+                     "");

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The current implementation uses `as<T>()` to extract the result, which performs a strict type check without conversions. This is inconsistent with the typical behavior of `any.cast<T>()`, which allows for conversions (e.g., from an `int` result to a `float` expectation). Using `try_cast<T>()` would align `CallExpected` with the more flexible casting semantics of the FFI, improving user experience.
   
   Additionally, the current `TypeError` message doesn't include the actual type received, which can make debugging difficult. Including the received type key in the error message would be very helpful.
   
   I suggest the following change to use `try_cast` and improve the error message.
   
   ```c
           if (auto val = result.template try_cast<T>()) {
             return std::move(*val);
           }
           return Error("TypeError",
                        "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr() +
                            ", but got " + result.GetTypeKey(),
                        "");
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760008081


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",

Review Comment:
   All error returns now use explicit `Unexpected()` wrapper instead of implicit Error conversion.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3801227235

   Thanks @guan404ming , i think we are close, i have one behavior comment. Besides that, given this is new public API, i think it would be helpful to do a round of quick API review, can you provide a list of APIs(including methods), would be good to categorize them as:
   
   - C0: strictly follows c++ standard
   - C1: others and list rationale(e.g. we follows rust API)
   
   Would also be good to discuss move and value copy behavior.
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3738767666

   Thanks a lot for the contribution, this would benefit from careful reviews, @junrushao @DarkSharpness @Ubospica can you help


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2707910540


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";

Review Comment:
   Done. Changed value() to throw the contained error directly instead of a generic RuntimeError:                                                               
   ```
   if (is_err()) {                                                                                                                                              
     throw data_.cast<Error>();                                                                                                                                 
   }  
   ``` 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2707914418


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }

Review Comment:
   Changed is_err() to return !is_ok() and also fixed is_ok() to check for Error first.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2707916147


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();
+  }
+
+  /*!
+   * \brief Access the error value.
+   * \return The error value.
+   * \note Behavior is undefined if the Expected contains a success value.

Review Comment:
   Sure, I've updated the docstring and changed from TVM_FFI_ICHECK to TVM_FFI_THROW(RuntimeError)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2731999783


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   There are two ways that Expected<T> get returned
   
   - W0: Expected<T> get "raised" internally by setting the TLS value via TVMFFISetRaised
   - W1: Expected<T> get returned as a normal return value
   
   And there are two ways to call a function now
   - C0: Normal call
   - C1: CallExpected
   
   Would be good to discuss the overall relation in the mix of four cases
   
   - C0+ W0: we need to throw the error to caller
   - C0 + W1: no error should be thrown, the Expected<T>  should be returned to the caller
   - C1 + W0: we should return Expected<Any> with the error "raised" set to the returned Expected value
   - C1 + W1: we need to return the Expected<T>, note that in this case it is harder to distinguish error being returned versus error being raised if the desirable logic is to return an error, but this is more of a rare case.
   
   In any case, it would be good first to make sure behavior of C0 is correct, and the particular context seems to suggest C0+W1, in such case, we should return the value to the caller.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3830414381

   > The new changes look great to me. Thank you so much!
   
   Thanks for your review!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2723151710


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,51 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      // Success - cast result to T and return Ok
+      return Expected<T>::Ok(std::move(result).cast<T>());

Review Comment:
   Here's a tricky part. If the result does not match the type T, `cast<T>()` will throw, and this error will escape CallExpected.
   
   Some proposed change: (feel free to brainstorm better ones)
   ```
   if (ret_code == 0) {
     if (auto val = std::move(result).template as<T>()) {
       return Expected<T>::Ok(std::move(*val));
     } else {
       return Expected<T>::Err(Error("TypeError", 
           "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr(), ""));
     }
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3793862881

   > > Since it introduces new function calling API to the users, @guan404ming could you document the usage?
   > 
   > Sure, I think I could do it as a follow up after this one!
   
   Thanks @guan404ming , I think the PR is in good state, let's wait for CI to be fixed and get it in!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2707192640


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";

Review Comment:
   If `value()` failed, it appears that it throws an error here but doesn't preserve the original error. Is it possible to retain the original error information?



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();

Review Comment:
   For large data, we can use move instead of copy, so I agree with Gemini that we can add an overload function here:
   ```
   TVM_FFI_INLINE T value() && {
     if (is_err()) { throw error(); }
     return std::move(data_).cast<T>();
   }
   ```



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }

Review Comment:
   It is likely that `ObjectRef` as a base class of `Error` can have both `is_ok()=True` and `is_err()=True`, since `CheckAnyStrict` relies on inheritance checking, not type matching. I would suggest returning `!is_ok()` here.



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }

Review Comment:
   Also it would be helpful to enhance the test cases on this.



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();
+  }
+
+  /*!
+   * \brief Access the error value.
+   * \return The error value.
+   * \note Behavior is undefined if the Expected contains a success value.

Review Comment:
   Let's instead of saying "behavior is undefined", say it throws a RuntimeError on bad access.
   
   Perhaps change the function body into 
   ```
     if (!is_err()) {
       TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
     }
   ```
   to mimic `value()` impl.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Ubospica (via GitHub)" <gi...@apache.org>.
Ubospica commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2750458451


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();

Review Comment:
   I feel it's fine to have both, since their usage would be different: `std::move(expected).value()` (for the move overload) vs `expected.value()` (for the const& overload), and this also follows C++ standard.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3793794964

   > Since it introduces new function calling API to the users, @guan404ming could you document the usage?
   
   Sure, I think I could do it as a follow up after this one!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2728927201


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   i think the current design unwraps `Expected<T>` at the FFI boundary. `CallExpected` use safe_call to catch the error and return `Expected<T>`; on the contrary, the normal call path would throw an error. This will keep a standard exception model for all callers.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2728927201


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   i think the current design unwraps `Expected<T>` and throws error at the FFI boundary. `CallExpected` use safe_call to catch the error and return `Expected<T>`; on the contrary, the normal call path would throw an error. This will keep a standard exception model for all callers.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3836455196

   /gemini review


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2759961379


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,9 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {
+    *rv = f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name,

Review Comment:
   It did, just removed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760008081


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",

Review Comment:
   All error returns now use explicit `Unexpected()` wrapper instead of implicit Error conversion, which I think would be more helpful!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760376696


##########
include/tvm/ffi/function_details.h:
##########
@@ -67,6 +72,19 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {
+  using value_type = void;
+};
+
+template <typename T>
+struct is_expected<Expected<T>> : std::true_type {
+  using value_type = T;
+};
+
+template <typename T>
+inline constexpr bool is_expected_v = is_expected<T>::value;

Review Comment:
   i see, it is worthwhile minimizing the code mainly because is_expected_v may be a future std type, the test uscase seems to be a duplication, so still good to remove here



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2721973994


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {

Review Comment:
   I think maybe we should keep this since that is kind of standard practice std::optional and C++23 std::expected both have value_or.
   
   ref [std::expected (C++23)](https://en.cppreference.com/w/cpp/utility/expected/value_or.html) and [std::optional (C++17)](https://en.cppreference.com/w/cpp/utility/optional/value_or)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2679756709


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();
+  }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `value()` method is `const`-qualified, which means it always returns a copy of the contained value. This can be inefficient when the `Expected` object is an rvalue (e.g., a temporary returned from a function). Consider adding an rvalue-qualified overload to allow moving the value out. This would improve performance in scenarios like `std::move(expected).value()`.
   
   You can change the existing method to be `const&`-qualified and add a `&&`-qualified overload:
   ```cpp
   TVM_FFI_INLINE T value() const& {
     if (is_err()) {
       TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
     }
     return data_.cast<T>();
   }
   
   TVM_FFI_INLINE T value() && {
     if (is_err()) {
       TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
     }
     return std::move(data_).cast<T>();
   }
   ```



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();
+  }
+
+  /*!
+   * \brief Access the error value.
+   * \return The error value.
+   * \note Behavior is undefined if the Expected contains a success value.
+   *       Always check is_err() before calling this method.
+   */
+  TVM_FFI_INLINE Error error() const {
+    TVM_FFI_ICHECK(is_err()) << "Expected does not contain an error";
+    return data_.cast<Error>();
+  }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Similar to `value()`, the `error()` method is `const`-qualified and always returns a copy. You can add an rvalue-qualified overload to allow moving the `Error` object out, which is more efficient.
   ```cpp
   TVM_FFI_INLINE Error error() const& {
     TVM_FFI_ICHECK(is_err()) << "Expected does not contain an error";
     return data_.cast<Error>();
   }
   
   TVM_FFI_INLINE Error error() && {
     TVM_FFI_ICHECK(is_err()) << "Expected does not contain an error";
     return std::move(data_).cast<Error>();
   }
   ```



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();
+  }
+
+  /*!
+   * \brief Access the error value.
+   * \return The error value.
+   * \note Behavior is undefined if the Expected contains a success value.
+   *       Always check is_err() before calling this method.
+   */
+  TVM_FFI_INLINE Error error() const {
+    TVM_FFI_ICHECK(is_err()) << "Expected does not contain an error";
+    return data_.cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return *data_.as<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.
+ * \note Returns Expected<Any> to allow usage in contexts where T is inferred.
+ */
+template <typename T = Any>
+TVM_FFI_INLINE Expected<T> ExpectedErr(Error error) {
+  return Expected<T>::Err(std::move(error));
+}
+
+// TypeTraits specialization for Expected<T>
+template <typename T>
+inline constexpr bool use_default_type_traits_v<Expected<T>> = false;
+
+template <typename T>
+struct TypeTraits<Expected<T>> : public TypeTraitsBase {
+  TVM_FFI_INLINE static void CopyToAnyView(const Expected<T>& src, TVMFFIAny* result) {
+    // Extract value from src.data_ and copy it properly
+    const TVMFFIAny* src_any = reinterpret_cast<const TVMFFIAny*>(&src.data_);
+
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      // It contains T, copy it out and move to result
+      T value = TypeTraits<T>::CopyFromAnyViewAfterCheck(src_any);
+      TypeTraits<T>::MoveToAny(std::move(value), result);
+    } else {
+      // It contains Error, copy it out and move to result
+      Error err = TypeTraits<Error>::CopyFromAnyViewAfterCheck(src_any);
+      TypeTraits<Error>::MoveToAny(std::move(err), result);
+    }
+  }
+
+  TVM_FFI_INLINE static void MoveToAny(Expected<T> src, TVMFFIAny* result) {
+    // Extract value from src.data_ and move it properly
+    TVMFFIAny* src_any = reinterpret_cast<TVMFFIAny*>(&src.data_);
+
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      // It contains T, move it out and move to result
+      T value = TypeTraits<T>::MoveFromAnyAfterCheck(src_any);
+      TypeTraits<T>::MoveToAny(std::move(value), result);
+    } else {
+      // It contains Error, move it out and move to result
+      Error err = TypeTraits<Error>::MoveFromAnyAfterCheck(src_any);
+      TypeTraits<Error>::MoveToAny(std::move(err), result);
+    }
+  }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   Similar to `CopyToAnyView`, the `MoveToAny` implementation can be greatly simplified. Since `src` is passed by value (effectively a move), you can move the underlying `Any` object directly. This is more readable and directly expresses the intent of moving the contained value.
   
   ```c
     TVM_FFI_INLINE static void MoveToAny(Expected<T> src, TVMFFIAny* result) {
       // An Expected<T> is represented by its underlying value (T or Error)
       // at the FFI boundary. We can simply move the contained Any.
       *result = details::AnyUnsafe::MoveAnyToTVMFFIAny(std::move(src.data_));
     }
   ```



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();
+  }
+
+  /*!
+   * \brief Access the error value.
+   * \return The error value.
+   * \note Behavior is undefined if the Expected contains a success value.
+   *       Always check is_err() before calling this method.
+   */
+  TVM_FFI_INLINE Error error() const {
+    TVM_FFI_ICHECK(is_err()) << "Expected does not contain an error";
+    return data_.cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return *data_.as<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.
+ * \note Returns Expected<Any> to allow usage in contexts where T is inferred.
+ */
+template <typename T = Any>
+TVM_FFI_INLINE Expected<T> ExpectedErr(Error error) {
+  return Expected<T>::Err(std::move(error));
+}
+
+// TypeTraits specialization for Expected<T>
+template <typename T>
+inline constexpr bool use_default_type_traits_v<Expected<T>> = false;
+
+template <typename T>
+struct TypeTraits<Expected<T>> : public TypeTraitsBase {
+  TVM_FFI_INLINE static void CopyToAnyView(const Expected<T>& src, TVMFFIAny* result) {
+    // Extract value from src.data_ and copy it properly
+    const TVMFFIAny* src_any = reinterpret_cast<const TVMFFIAny*>(&src.data_);
+
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      // It contains T, copy it out and move to result
+      T value = TypeTraits<T>::CopyFromAnyViewAfterCheck(src_any);
+      TypeTraits<T>::MoveToAny(std::move(value), result);
+    } else {
+      // It contains Error, copy it out and move to result
+      Error err = TypeTraits<Error>::CopyFromAnyViewAfterCheck(src_any);
+      TypeTraits<Error>::MoveToAny(std::move(err), result);
+    }
+  }

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The implementation of `CopyToAnyView` is correct but can be simplified. Instead of checking the type and manually performing a copy-then-move for each case, you can leverage the `Any` type's copy constructor to handle the logic. This makes the code more concise and less error-prone, as it relies on the already-tested `Any` copy semantics.
   
   ```c
     TVM_FFI_INLINE static void CopyToAnyView(const Expected<T>& src, TVMFFIAny* result) {
       // An Expected<T> is represented by its underlying value (T or Error)
       // at the FFI boundary. We can simply copy the contained Any.
       Any copied_any = src.data_;
       *result = details::AnyUnsafe::MoveAnyToTVMFFIAny(std::move(copied_any));
     }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2723611923


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {
+    R expected_result = f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{
+        args, Is, optional_name, f_sig}...);
+    if (expected_result.is_ok()) {
+      *rv = expected_result.value();
+    } else {
+      throw expected_result.error();

Review Comment:
   Sure, updated!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3811411475

   agree that simplicity can be helpful, just want to make sure xgrammar can switch to make use of the new impl here. once you think the remaining apis are good please explicitly approve,  @Ubospica @Seven-Streams @junrushao @DarkSharpness
   
    


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3811460688

   Thinking a bit more about partial deduction, it might be useful to think about the usages, the main thing to consider is consistency with `std::optional`, the following code is generally a common pattern:
   
   ```c++
   std::optional<long> func_optional(bool valid, int x) {
      if (value) return x;
      return std::nullopt;
   }
   ```
   
   We can find that return value conversion from x to `std::optional<long>` is automated by the return type. 
   
   So what @DarkSharpness mentioned is that it is desirable to have similar syntax. In which case ExpectedOk and ExpectedErr follows the similar rationale of targetted usage. 
   
   ```c++
   Expected<long> func_optional_rvalue_deduce(bool valid, int x) {
      if (value) return ExpectedOk(x);
      return ExpectedErr(Error("ValueError", "xx"));
   }
   ```
   
   In the current impl, we need to write it as
   ```c++
   Expected<long> func_optional_param_deduce(bool valid, int x) {
      if (value) return Expected<long>(x);
      return Expected<long>(Error("ValueError", "xx"));
   }
   ```
   
   The main question we want to ask is the common usage scenarios the sugar ExpectedOk/ExpectedErr, e.g. are they mostly used in the case similar to `func_optional` where we want to simplify by deducing from return values, if so, then I think the deferred deduction is wortwhile, alternatively we should left out the  ExpectedOk/ExpectedErr sugar since for most common case we expect people to explicitly write `Expected<T>`
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "DarkSharpness (via GitHub)" <gi...@apache.org>.
DarkSharpness commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3807017802

   > Here is the API review
   > 
   > ```
   > | API                | Category | Notes                                                              |                                                                         
   > |--------------------|----------|--------------------------------------------------------------------|                                                                         
   > | is_ok()            | C0       | Follows std::expected::has_value() semantics                       |                                                                         
   > | is_err()           | C1       | Rust-style naming; equivalent to !has_value()                      |                                                                         
   > | has_value()        | C0       | Alias for is_ok(), follows C++ standard                            |                                                                         
   > | value()            | C0       | Follows std::expected::value()                                     |                                                                         
   > | value() &&         | C1       | Move-qualified overload for efficiency (not in C++23 standard)     |                                                                         
   > | error()            | C0       | Follows std::expected::error()                                     |                                                                         
   > | error() &&         | C1       | Move-qualified overload for efficiency                             |                                                                         
   > | value_or(default)  | C0       | Follows std::expected::value_or()                                  |                                                                         
   > | ExpectedOk(value)  | C1       | Rust-style helper; C++ standard has no equivalent factory function |                                                                         
   > | ExpectedErr(error) | C1       | Rust-style helper; C++ standard has no equivalent factory function |                                                                         
   > ```
   > 
   > Rationale for C1 APIs:
   > 
   > * Move-qualified overloads (&&): Added for performance when the Expected is a temporary, avoiding unnecessary copies of large objects.
   > * ExpectedOk() / ExpectedErr(): Rust-style factory functions for cleaner syntax with type deduction. C++23 std::expected relies on constructors instead.
   > * is_err(): Rust naming convention; provides symmetry with is_ok().
   > 
   > APIs not implemented (compared to C++23 std::expected):
   > 
   > * operator bool(): can use has_value() or is_ok() instead
   > * operator*() / operator->(): unchecked access, omitted for safety
   > * Monadic operations (and_then, transform, or_else, transform_error): may add in future if needed
   
   Thanks for the detailed API review.
   
   One small difference worth calling out for `ExpectedOk` / `ExpectedErr` is a C++-specific type deduction behavior compared to Rust. In Rust, generic parameters can be inferred from the return type, while in C++ template argument deduction only considers function arguments, not the return type. This means that with factory-style helpers like `ExpectedOk`, the deduced type may sometimes differ from the desired return type. For example:
   
   ```C++
   template <typename T>
   Expect <T> ExpectOk(T value);
   
   Expect<long> function(int x) {
     return ExpectOk(x); // <- in many cases, we want [T = long], which deduced from return type.
                         // but in this case T will deduced as int, which may lead to compile error.
   }
   ```
   
   In such cases, C++ cannot deduce `T = long` from the return type, which may lead to a compilation error.
   
   I'm not sure whether this will cause some inconvenience in real usage, but the current design is reasonable for simplicity.
   
   In XGrammar we implement something like `PartialExpected`, which can be implicitly converted to any `Expected<T>` and solves the return type inference problem. However, this actually introduces much complexity https://github.com/mlc-ai/xgrammar/blob/aa44ded202fdaa2cb55f48deb31d17c9822a8a1f/cpp/support/utils.h#L130-L212
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3823923434

   > In comparison, the enum-based error would be more efficient, but I don't think it's a blocker. To support this, we may consider supporting errno in the Error class in the future. Another consideration is whether we should expose ffi::expected to Python. I feel it is nice to have in the future. For this PR, it may not be required to simplify the scope.
   
   Thanks for the detailed review and the XGrammar comparison! The enum-based error and Python exposure are both good ideas worth exploring. I think we can keep them as follow-up items to keep this PR focused on the core Expected<T> with implicit conversion support.
   
   > Currently, in XGrammar's result library, [ResultOk(...) and ResultErr(...)](https://github.com/Ubospica/xgrammar/blob/15dc61d02ed24820215ca1d491d6a07ba32fff50/cpp/support/utils.h#L124-L212) are used to return success or error values, and I think it is easy to use.
   
   The current implementation removes them since implicit conversion makes them redundant. But given that XGrammar uses a similar pattern (ResultOk/ResultErr), I want to confirm whether we prefer to keep both options available for users who favor the explicit style.
   
   > I think to add implicit converting constructors would be ideal to handle this feat:
   
   Just updated with implicit conversion as planned please take another look thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2754332863


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Wrapper to explicitly construct an Expected in the error state.
+ */
+struct Unexpected {
+  /*! \brief Construct from an error. */
+  // NOLINTNEXTLINE(google-explicit-constructor,runtime/explicit)
+  Unexpected(Error error) : error_(std::move(error)) {}
+  /*! \brief The wrapped error. */
+  Error error_;

Review Comment:
   consider align with `std::unexpected<E>` API, make it a class and keep it an private member. The error can be accessed via error() member function https://en.cppreference.com/w/cpp/utility/expected/unexpected.html
   
   Would be good to see if we can use Unexpected<E> for E as subclass of Error if such auto deduction is possible.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760008081


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",

Review Comment:
   Reordered to check T first (fast path), then Error. Now uses try_cast for both to avoid double checking.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2761880385


##########
include/tvm/ffi/function_details.h:
##########
@@ -67,6 +72,19 @@ static constexpr bool ArgSupported =
       std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, AnyView> ||
       TypeTraitsNoCR<T>::convert_enabled));
 
+template <typename T>
+struct is_expected : std::false_type {
+  using value_type = void;
+};
+
+template <typename T>
+struct is_expected<Expected<T>> : std::true_type {
+  using value_type = T;
+};
+
+template <typename T>
+inline constexpr bool is_expected_v = is_expected<T>::value;

Review Comment:
   Make sense to me. Just removed!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Ubospica (via GitHub)" <gi...@apache.org>.
Ubospica commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3822626031

   Thanks for the thorough discussion! I agree it would be great to follow C++ conventions. Adding implicit conversion looks like a reasonable approach.
   
   I also checked XGrammar's implementation of Expected (at https://github.com/Ubospica/xgrammar/blob/15dc61d02ed24820215ca1d491d6a07ba32fff50/cpp/support/utils.h#L251, called Result). It's more like a C++ imitation of the Result in rust. There is one difference in usage: It allows enum-based error.
   
   ```
   enum class SchemaErrorType : int {
     kInvalidSchema = 0,
     kUnsatisfiableSchema = 1,
   };
   
   using SchemaError = TypedError<SchemaErrorType>;
   
   Result<SchemaSpecPtr, SchemaError> Parse(
         const picojson::value& schema, const std::string& rule_name_hint = "root"
   );
   ```
   
   `std::expected` also supports it through customizing E to an enum class in `std::expected<T, E>`.
   
   We currently restrict the error kind to `tvm::ffi::Error`. I think the design is good because it simplifies the error handling. Also, it allows customizing the kind through its `std::string kind` parameter.
   
   In comparison, the enum-based error would be more efficient, but I don't think it's a blocker. To support this, we may consider supporting errno in the Error class in the future.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen merged PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2728927201


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   the current design unwraps `Expected<T>` and throws error at the FFI boundary. `CallExpected` use safe_call to catch the error and return `Expected<T>`; on the contrary, the normal call path would throw an error. This will keep a standard exception model for all callers.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2728927201


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   the current design unwraps `Expected<T>` and throws error at the FFI boundary. `CallExpected` use safe_call to catch the error and return `Expected<T>`; on the contrary, the normal call path would throw an error.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2723622389


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,51 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      // Success - cast result to T and return Ok
+      return Expected<T>::Ok(std::move(result).cast<T>());

Review Comment:
   Nice catch. The implementation looks good. I think there is a potential edge case that we probably don't want ot try casting if `T = Any`. Here is updated implementation
   
   ```c
   if (ret_code == 0) {
     if constexpr (std::is_same_v<T, Any>) {
       return Expected<T>::Ok(std::move(result));
     } else {
       if (auto val = std::move(result).template as<T>()) {
         return Expected<T>::Ok(std::move(*val));
       } else {
         return Expected<T>::Err(Error(
             "TypeError",
             "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr(), ""));
       }
     }
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2723622389


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,51 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      // Success - cast result to T and return Ok
+      return Expected<T>::Ok(std::move(result).cast<T>());

Review Comment:
   I think there is a potential edge case that we probably don't want ot try casting if `T = Any`. Here is updated implementation
   
   ```c
   if (ret_code == 0) {
     if constexpr (std::is_same_v<T, Any>) {
       return Expected<T>::Ok(std::move(result));
     } else {
       if (auto val = std::move(result).template as<T>()) {
         return Expected<T>::Ok(std::move(*val));
       } else {
         return Expected<T>::Err(Error("TypeError",
                                       "CallExpected: result type mismatch, expected " +
                                           TypeTraits<T>::TypeStr(),
                                       ""));
       }
     }
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2723622389


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,51 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      // Success - cast result to T and return Ok
+      return Expected<T>::Ok(std::move(result).cast<T>());

Review Comment:
   I think there is a potential edge case that we probably don't want ot try casting if `T = Any`. Here is updated implementation
   
   ```c
   if (ret_code == 0) {
     if constexpr (std::is_same_v<T, Any>) {
       return Expected<T>::Ok(std::move(result));
     } else {
       if (auto val = std::move(result).template as<T>()) {
         return Expected<T>::Ok(std::move(*val));
       } else {
         return Expected<T>::Err(Error(
             "TypeError",
             "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr(), ""));
       }
     }
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3794001099

   Here is the upgrade pr https://github.com/apache/tvm-ffi/pull/420. I've checked there is no any compat issue need to be updated in our src code.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "Kathryn-cat (via GitHub)" <gi...@apache.org>.
Kathryn-cat commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2720125190


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {

Review Comment:
   I think this function might be rarely used, because the philosophy of `Expected<T>` is handling error explicitly. Let's leave it for discussion here.



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return data_.cast<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.
+ * \note Returns Expected<Any> to allow usage in contexts where T is inferred.
+ */
+template <typename T = Any>
+TVM_FFI_INLINE Expected<T> ExpectedErr(Error error) {
+  return Expected<T>::Err(std::move(error));
+}
+
+// TypeTraits specialization for Expected<T>
+template <typename T>
+inline constexpr bool use_default_type_traits_v<Expected<T>> = false;
+
+template <typename T>
+struct TypeTraits<Expected<T>> : public TypeTraitsBase {
+  TVM_FFI_INLINE static void CopyToAnyView(const Expected<T>& src, TVMFFIAny* result) {
+    const TVMFFIAny* src_any = reinterpret_cast<const TVMFFIAny*>(&src.data_);
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      TypeTraits<T>::MoveToAny(TypeTraits<T>::CopyFromAnyViewAfterCheck(src_any), result);
+    } else {
+      TypeTraits<Error>::MoveToAny(TypeTraits<Error>::CopyFromAnyViewAfterCheck(src_any), result);
+    }
+  }
+
+  TVM_FFI_INLINE static void MoveToAny(Expected<T> src, TVMFFIAny* result) {
+    TVMFFIAny* src_any = reinterpret_cast<TVMFFIAny*>(&src.data_);
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      TypeTraits<T>::MoveToAny(TypeTraits<T>::MoveFromAnyAfterCheck(src_any), result);
+    } else {
+      TypeTraits<Error>::MoveToAny(TypeTraits<Error>::MoveFromAnyAfterCheck(src_any), result);
+    }
+  }
+
+  TVM_FFI_INLINE static bool CheckAnyStrict(const TVMFFIAny* src) {
+    return TypeTraits<T>::CheckAnyStrict(src) || TypeTraits<Error>::CheckAnyStrict(src);
+  }
+
+  TVM_FFI_INLINE static Expected<T> CopyFromAnyViewAfterCheck(const TVMFFIAny* src) {
+    if (TypeTraits<T>::CheckAnyStrict(src)) {
+      return Expected<T>::Ok(TypeTraits<T>::CopyFromAnyViewAfterCheck(src));
+    }
+    return Expected<T>::Err(TypeTraits<Error>::CopyFromAnyViewAfterCheck(src));
+  }
+
+  TVM_FFI_INLINE static Expected<T> MoveFromAnyAfterCheck(TVMFFIAny* src) {
+    if (TypeTraits<T>::CheckAnyStrict(src)) {
+      return Expected<T>::Ok(TypeTraits<T>::MoveFromAnyAfterCheck(src));
+    }
+    return Expected<T>::Err(TypeTraits<Error>::MoveFromAnyAfterCheck(src));
+  }
+
+  TVM_FFI_INLINE static std::optional<Expected<T>> TryCastFromAnyView(const TVMFFIAny* src) {
+    if (auto opt = TypeTraits<T>::TryCastFromAnyView(src)) {
+      return Expected<T>::Ok(*std::move(opt));
+    }
+    if (auto opt_err = TypeTraits<Error>::TryCastFromAnyView(src)) {
+      return Expected<T>::Err(*std::move(opt_err));
+    }
+    return std::nullopt;
+  }
+
+  TVM_FFI_INLINE static std::string GetMismatchTypeInfo(const TVMFFIAny* src) {

Review Comment:
   Let's remove this



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return data_.cast<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.
+ * \note Returns Expected<Any> to allow usage in contexts where T is inferred.
+ */
+template <typename T = Any>
+TVM_FFI_INLINE Expected<T> ExpectedErr(Error error) {
+  return Expected<T>::Err(std::move(error));
+}
+
+// TypeTraits specialization for Expected<T>
+template <typename T>
+inline constexpr bool use_default_type_traits_v<Expected<T>> = false;
+
+template <typename T>
+struct TypeTraits<Expected<T>> : public TypeTraitsBase {
+  TVM_FFI_INLINE static void CopyToAnyView(const Expected<T>& src, TVMFFIAny* result) {
+    const TVMFFIAny* src_any = reinterpret_cast<const TVMFFIAny*>(&src.data_);
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      TypeTraits<T>::MoveToAny(TypeTraits<T>::CopyFromAnyViewAfterCheck(src_any), result);
+    } else {
+      TypeTraits<Error>::MoveToAny(TypeTraits<Error>::CopyFromAnyViewAfterCheck(src_any), result);
+    }
+  }
+
+  TVM_FFI_INLINE static void MoveToAny(Expected<T> src, TVMFFIAny* result) {
+    TVMFFIAny* src_any = reinterpret_cast<TVMFFIAny*>(&src.data_);
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      TypeTraits<T>::MoveToAny(TypeTraits<T>::MoveFromAnyAfterCheck(src_any), result);

Review Comment:
   ditto,
   ```
     if (src.is_err()) {
       TypeTraits<Error>::MoveToAny(std::move(src).error(), result);
     } else {
       TypeTraits<T>::MoveToAny(std::move(src).value(), result);
     }
   ```



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return data_.cast<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.
+ * \note Returns Expected<Any> to allow usage in contexts where T is inferred.
+ */
+template <typename T = Any>
+TVM_FFI_INLINE Expected<T> ExpectedErr(Error error) {
+  return Expected<T>::Err(std::move(error));
+}
+
+// TypeTraits specialization for Expected<T>
+template <typename T>
+inline constexpr bool use_default_type_traits_v<Expected<T>> = false;
+
+template <typename T>
+struct TypeTraits<Expected<T>> : public TypeTraitsBase {
+  TVM_FFI_INLINE static void CopyToAnyView(const Expected<T>& src, TVMFFIAny* result) {
+    const TVMFFIAny* src_any = reinterpret_cast<const TVMFFIAny*>(&src.data_);
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      TypeTraits<T>::MoveToAny(TypeTraits<T>::CopyFromAnyViewAfterCheck(src_any), result);
+    } else {
+      TypeTraits<Error>::MoveToAny(TypeTraits<Error>::CopyFromAnyViewAfterCheck(src_any), result);
+    }
+  }
+
+  TVM_FFI_INLINE static void MoveToAny(Expected<T> src, TVMFFIAny* result) {
+    TVMFFIAny* src_any = reinterpret_cast<TVMFFIAny*>(&src.data_);
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      TypeTraits<T>::MoveToAny(TypeTraits<T>::MoveFromAnyAfterCheck(src_any), result);
+    } else {
+      TypeTraits<Error>::MoveToAny(TypeTraits<Error>::MoveFromAnyAfterCheck(src_any), result);
+    }
+  }
+
+  TVM_FFI_INLINE static bool CheckAnyStrict(const TVMFFIAny* src) {
+    return TypeTraits<T>::CheckAnyStrict(src) || TypeTraits<Error>::CheckAnyStrict(src);
+  }
+
+  TVM_FFI_INLINE static Expected<T> CopyFromAnyViewAfterCheck(const TVMFFIAny* src) {
+    if (TypeTraits<T>::CheckAnyStrict(src)) {
+      return Expected<T>::Ok(TypeTraits<T>::CopyFromAnyViewAfterCheck(src));
+    }
+    return Expected<T>::Err(TypeTraits<Error>::CopyFromAnyViewAfterCheck(src));
+  }
+
+  TVM_FFI_INLINE static Expected<T> MoveFromAnyAfterCheck(TVMFFIAny* src) {
+    if (TypeTraits<T>::CheckAnyStrict(src)) {
+      return Expected<T>::Ok(TypeTraits<T>::MoveFromAnyAfterCheck(src));
+    }
+    return Expected<T>::Err(TypeTraits<Error>::MoveFromAnyAfterCheck(src));
+  }
+
+  TVM_FFI_INLINE static std::optional<Expected<T>> TryCastFromAnyView(const TVMFFIAny* src) {
+    if (auto opt = TypeTraits<T>::TryCastFromAnyView(src)) {
+      return Expected<T>::Ok(*std::move(opt));
+    }
+    if (auto opt_err = TypeTraits<Error>::TryCastFromAnyView(src)) {
+      return Expected<T>::Err(*std::move(opt_err));
+    }
+    return std::nullopt;
+  }
+
+  TVM_FFI_INLINE static std::string GetMismatchTypeInfo(const TVMFFIAny* src) {
+    return TypeTraitsBase::GetMismatchTypeInfo(src);
+  }
+
+  TVM_FFI_INLINE static std::string TypeStr() {
+    return "Expected<" + TypeTraits<T>::TypeStr() + ">";
+  }
+
+  TVM_FFI_INLINE static std::string TypeSchema() {
+    return R"({"type":"Expected","args":[)" + details::TypeSchema<T>::v() + "]}";

Review Comment:
   Maybe also mention `{"type":"ffi.Error"}` in type schema?



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return data_.cast<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.
+ * \note Returns Expected<Any> to allow usage in contexts where T is inferred.
+ */
+template <typename T = Any>
+TVM_FFI_INLINE Expected<T> ExpectedErr(Error error) {
+  return Expected<T>::Err(std::move(error));
+}
+
+// TypeTraits specialization for Expected<T>
+template <typename T>
+inline constexpr bool use_default_type_traits_v<Expected<T>> = false;
+
+template <typename T>
+struct TypeTraits<Expected<T>> : public TypeTraitsBase {
+  TVM_FFI_INLINE static void CopyToAnyView(const Expected<T>& src, TVMFFIAny* result) {
+    const TVMFFIAny* src_any = reinterpret_cast<const TVMFFIAny*>(&src.data_);
+    if (TypeTraits<T>::CheckAnyStrict(src_any)) {
+      TypeTraits<T>::MoveToAny(TypeTraits<T>::CopyFromAnyViewAfterCheck(src_any), result);

Review Comment:
   We possibly don't need to create a copy of T then move it.
   
   Possible simplification:
   ```
     if (src.is_err()) {
       TypeTraits<Error>::CopyToAnyView(src.error(), result);
     } else {
       TypeTraits<T>::CopyToAnyView(src.value(), result);
     }
   ```



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return data_.cast<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.
+ * \note Returns Expected<Any> to allow usage in contexts where T is inferred.
+ */
+template <typename T = Any>

Review Comment:
   Perhaps `template <typename T>` is cleaner? Do we have to default to `Any` here



##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   * \note Checks for Error first to handle cases where T is a base class of Error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return !data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return !is_ok(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*! \brief Access the success value. Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() const& {
+    if (is_err()) throw data_.cast<Error>();
+    return data_.cast<T>();
+  }
+  /*! \brief Access the success value (rvalue). Throws the contained error if is_err(). */
+  TVM_FFI_INLINE T value() && {
+    if (is_err()) throw std::move(data_).template cast<Error>();
+    return std::move(data_).template cast<T>();
+  }
+
+  /*! \brief Access the error. Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() const& {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return data_.cast<Error>();
+  }
+  /*! \brief Access the error (rvalue). Throws RuntimeError if is_ok(). */
+  TVM_FFI_INLINE Error error() && {
+    if (!is_err()) TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains value, not error";
+    return std::move(data_).template cast<Error>();
+  }
+
+  /*!
+   * \brief Get the success value or a default value.
+   * \param default_value The value to return if Expected contains an error.
+   * \return The success value if present, otherwise the default value.
+   */
+  template <typename U = std::remove_cv_t<T>>
+  TVM_FFI_INLINE T value_or(U&& default_value) const {
+    if (is_ok()) {
+      return data_.cast<T>();
+    }
+    return T(std::forward<U>(default_value));
+  }
+
+ private:
+  friend struct TypeTraits<Expected<T>>;
+
+  /*!
+   * \brief Private constructor from Any.
+   * \param data The data containing either T or Error.
+   * \note This constructor is used by TypeTraits for conversion.
+   */
+  explicit Expected(Any data) : data_(std::move(data)) {
+    TVM_FFI_ICHECK(data_.as<T>().has_value() || data_.as<Error>().has_value())
+        << "Expected must contain either T or Error";
+  }
+
+  Any data_;  // Holds either T or Error
+};
+
+/*!
+ * \brief Helper function to create Expected::Ok with type deduction.
+ * \tparam T The success type (deduced from argument).
+ * \param value The success value.
+ * \return Expected<T> containing the success value.
+ */
+template <typename T>
+TVM_FFI_INLINE Expected<T> ExpectedOk(T value) {
+  return Expected<T>::Ok(std::move(value));
+}
+
+/*!
+ * \brief Helper function to create Expected::Err.
+ * \param error The error value.
+ * \return Expected<Any> containing the error.

Review Comment:
   Let's fix the comment here, should return `Expected<T>` same as the ExpectedOk case.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#issuecomment-3806261746

   Here is the API review
   
   ```
   | API                | Category | Notes                                                              |                                                                         
   |--------------------|----------|--------------------------------------------------------------------|                                                                         
   | is_ok()            | C0       | Follows std::expected::has_value() semantics                       |                                                                         
   | is_err()           | C1       | Rust-style naming; equivalent to !has_value()                      |                                                                         
   | has_value()        | C0       | Alias for is_ok(), follows C++ standard                            |                                                                         
   | value()            | C0       | Follows std::expected::value()                                     |                                                                         
   | value() &&         | C1       | Move-qualified overload for efficiency (not in C++23 standard)     |                                                                         
   | error()            | C0       | Follows std::expected::error()                                     |                                                                         
   | error() &&         | C1       | Move-qualified overload for efficiency                             |                                                                         
   | value_or(default)  | C0       | Follows std::expected::value_or()                                  |                                                                         
   | ExpectedOk(value)  | C1       | Rust-style helper; C++ standard has no equivalent factory function |                                                                         
   | ExpectedErr(error) | C1       | Rust-style helper; C++ standard has no equivalent factory function |                                                                         
   ```
   
   Rationale for C1 APIs:                                                                                                                                                         
   - Move-qualified overloads (&&): Added for performance when the Expected is a temporary, avoiding unnecessary copies of large objects.                                         
   - ExpectedOk() / ExpectedErr(): Rust-style factory functions for cleaner syntax with type deduction. C++23 std::expected relies on constructors instead.                       
   - is_err(): Rust naming convention; provides symmetry with is_ok().
   
   
   APIs not implemented (compared to C++23 std::expected):                                                                                                                        
   - operator bool() — can use has_value() or is_ok() instead                                                                                                                     
   - operator*() / operator->() — unchecked access; omitted for safety                                                                                                            
   - Monadic operations (and_then, transform, or_else, transform_error) — may add in future if needed  


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2732974623


##########
include/tvm/ffi/function_details.h:
##########
@@ -219,6 +237,14 @@ TVM_FFI_INLINE void unpack_call(std::index_sequence<Is...>, const std::string* o
   // use index sequence to do recursive-less unpacking
   if constexpr (std::is_same_v<R, void>) {
     f(ArgValueWithContext<std::tuple_element_t<Is, PackedArgs>>{args, Is, optional_name, f_sig}...);
+  } else if constexpr (is_expected_v<R>) {

Review Comment:
   Updated with option B. Please take another look, thanks!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760036473


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {

Review Comment:
   Reordered to check T first (fast path), then Error. Now uses try_cast for both to avoid double checking.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760043569


##########
include/tvm/ffi/function.h:
##########
@@ -643,6 +643,65 @@ class Function : public ObjectRef {
     static_cast<FunctionObj*>(data_.get())->CallPacked(args.data(), args.size(), result);
   }
 
+  /*!
+   * \brief Call the function and return Expected<T> for exception-free error handling.
+   * \tparam T The expected return type (default: Any).
+   * \param args The arguments to pass to the function.
+   * \return Expected<T> containing either the result or an error.
+   *
+   * This method provides exception-free calling by catching all exceptions
+   * and returning them as Error values in the Expected type.
+   *
+   * \code
+   * Function func = Function::GetGlobal("risky_function");
+   * Expected<int> result = func.CallExpected<int>(arg1, arg2);
+   * if (result.is_ok()) {
+   *   int value = result.value();
+   * } else {
+   *   Error err = result.error();
+   * }
+   * \endcode
+   */
+  template <typename T = Any, typename... Args>
+  TVM_FFI_INLINE Expected<T> CallExpected(Args&&... args) const {
+    constexpr size_t kNumArgs = sizeof...(Args);
+    AnyView args_pack[kNumArgs > 0 ? kNumArgs : 1];
+    PackedArgs::Fill(args_pack, std::forward<Args>(args)...);
+
+    Any result;
+    FunctionObj* func_obj = static_cast<FunctionObj*>(data_.get());
+
+    // Use safe_call path to catch exceptions
+    int ret_code = func_obj->safe_call(func_obj, reinterpret_cast<const TVMFFIAny*>(args_pack),
+                                       kNumArgs, reinterpret_cast<TVMFFIAny*>(&result));
+
+    if (ret_code == 0) {
+      if constexpr (std::is_same_v<T, Any>) {
+        return std::move(result);
+      } else {
+        // Check if result is Error (from Expected-returning function that returned Err)
+        if (result.template as<Error>().has_value()) {
+          return std::move(result).template cast<Error>();
+        }
+        // Try to extract as T
+        if (auto val = result.template try_cast<T>()) {
+          return std::move(*val);
+        }
+        return Error("TypeError",
+                     "CallExpected: result type mismatch, expected " + TypeTraits<T>::TypeStr() +
+                         ", but got " + result.GetTypeKey(),
+                     "");
+      }
+    } else if (ret_code == -2) {
+      // Environment error already set (e.g., Python KeyboardInterrupt)
+      // We still throw this since it's a signal, not a normal error

Review Comment:
   Just removed, thanks for the pr!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2760396052


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,236 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Wrapper to explicitly construct an Expected in the error state.
+ * \tparam E The error type, must derive from Error.
+ */
+template <typename E = Error>
+class Unexpected {
+  static_assert(std::is_base_of_v<Error, std::remove_cv_t<E>>,
+                "Unexpected<E> requires E to be Error or a subclass of Error.");
+
+ public:
+  /*! \brief Construct from an error value. */
+  explicit Unexpected(E error) : error_(std::move(error)) {}
+
+  /*! \brief Access the stored error. */
+  const E& error() const& noexcept { return error_; }
+  /*! \brief Access the stored error. */
+  E& error() & noexcept { return error_; }
+  /*! \brief Access the stored error (rvalue). */
+  const E&& error() const&& noexcept { return std::move(error_); }
+  /*! \brief Access the stored error (rvalue). */
+  E&& error() && noexcept { return std::move(error_); }
+
+ private:
+  E error_;
+};
+
+#ifndef TVM_FFI_DOXYGEN_MODE
+template <typename E>
+Unexpected(E) -> Unexpected<E>;
+#endif
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return Error("ValueError", "Division by zero");
+ *   }
+ *   return a / b;
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Implicit constructor from a success value.
+   * \param value The success value.
+   */
+  // NOLINTNEXTLINE(google-explicit-constructor,runtime/explicit)
+  Expected(T value) : data_(Any(std::move(value))) {}
+
+  /*!
+   * \brief Implicit constructor from an error.
+   * \param error The error value.
+   */
+  // NOLINTNEXTLINE(google-explicit-constructor,runtime/explicit)
+  Expected(Error error) : data_(Any(std::move(error))) {}
+
+  /*! \brief Implicit constructor from an Unexpected wrapper. */
+  template <typename E, typename = std::enable_if_t<std::is_base_of_v<Error, std::remove_cv_t<E>>>>
+  // NOLINTNEXTLINE(google-explicit-constructor,runtime/explicit)
+  Expected(Unexpected<E> unexpected) : data_(Any(Error(std::move(unexpected).error()))) {}

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   The constructor for `Expected` from `Unexpected<E>` currently wraps the error in an `Error()` constructor call. This can lead to object slicing if `E` is a custom error type that derives from `tvm::ffi::Error`. When sliced, the specific type information of the custom error is lost, and it becomes a base `Error` object. This prevents callers from downcasting the error to its original derived type to handle specific error conditions.
   
   By removing the `Error()` wrapper, the `Any` container will correctly store the derived error type, preserving its full information and allowing for proper polymorphic error handling.
   
   ```c
     Expected(Unexpected<E> unexpected) : data_(Any(std::move(unexpected).error())) {}
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] feat: add ffi::Expected for exception-free error handling [tvm-ffi]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #399:
URL: https://github.com/apache/tvm-ffi/pull/399#discussion_r2707912393


##########
include/tvm/ffi/expected.h:
##########
@@ -0,0 +1,256 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/ffi/expected.h
+ * \brief Runtime Expected container type for exception-free error handling.
+ */
+#ifndef TVM_FFI_EXPECTED_H_
+#define TVM_FFI_EXPECTED_H_
+
+#include <tvm/ffi/any.h>
+#include <tvm/ffi/error.h>
+
+#include <type_traits>
+#include <utility>
+
+namespace tvm {
+namespace ffi {
+
+/*!
+ * \brief Expected<T> provides exception-free error handling for FFI functions.
+ *
+ * Expected<T> is similar to Rust's Result<T, Error> or C++23's std::expected.
+ * It can hold either a success value of type T or an error of type Error.
+ *
+ * \tparam T The success type. Must be Any-compatible and cannot be Error.
+ *
+ * Usage:
+ * \code
+ * Expected<int> divide(int a, int b) {
+ *   if (b == 0) {
+ *     return ExpectedErr(Error("ValueError", "Division by zero"));
+ *   }
+ *   return ExpectedOk(a / b);
+ * }
+ *
+ * Expected<int> result = divide(10, 2);
+ * if (result.is_ok()) {
+ *   int value = result.value();
+ * } else {
+ *   Error err = result.error();
+ * }
+ * \endcode
+ */
+template <typename T>
+class Expected {
+ public:
+  static_assert(!std::is_same_v<T, Error>, "Expected<Error> is not allowed. Use Error directly.");
+
+  /*!
+   * \brief Create an Expected with a success value.
+   * \param value The success value.
+   * \return Expected containing the success value.
+   */
+  static Expected Ok(T value) { return Expected(Any(std::move(value))); }
+
+  /*!
+   * \brief Create an Expected with an error.
+   * \param error The error value.
+   * \return Expected containing the error.
+   */
+  static Expected Err(Error error) { return Expected(Any(std::move(error))); }
+
+  /*!
+   * \brief Check if the Expected contains a success value.
+   * \return True if contains success value, false if contains error.
+   */
+  TVM_FFI_INLINE bool is_ok() const { return data_.as<T>().has_value(); }
+
+  /*!
+   * \brief Check if the Expected contains an error.
+   * \return True if contains error, false if contains success value.
+   */
+  TVM_FFI_INLINE bool is_err() const { return data_.as<Error>().has_value(); }
+
+  /*!
+   * \brief Alias for is_ok().
+   * \return True if contains success value.
+   */
+  TVM_FFI_INLINE bool has_value() const { return is_ok(); }
+
+  /*!
+   * \brief Access the success value.
+   * \return The success value.
+   * \throws RuntimeError if the Expected contains an error.
+   */
+  TVM_FFI_INLINE T value() const {
+    if (is_err()) {
+      TVM_FFI_THROW(RuntimeError) << "Bad expected access: contains error";
+    }
+    return data_.cast<T>();

Review Comment:
   Agree as well. I've added both const& and && qualified overloads for value(): 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org