This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new df63eca803 feat(bindings/cpp): generate ListOptions from core (#9331)
df63eca803 is described below

commit df63eca803be6002efced6873f5a00cd6628d18f
Author: Chitral Verma <[email protected]>
AuthorDate: Sat Nov 28 21:00:32 2026 +0530

    feat(bindings/cpp): generate ListOptions from core (#9331)
    
    * feat(bindings/cpp): generate ListOptions from core
    
    Generate opendal::ListOptions and the three layers behind it from
    core/core/src/types/options.rs with the shared core_options parser: the
    public struct in a new generated include/options.hpp, the cxx bridge
    struct in src/options.rs, the C++ ToFfiOptions conversion in
    src/utils/options_converter.cpp, and the Rust conversion into core.
    
    data_structure.hpp includes options.hpp, as it includes the generated
    capability.hpp and metadata.hpp. ListOptions keeps its member names,
    types, default member initializers, and order, so positional and
    designated initializers, structured bindings, and its layout stay the
    same. The other option structs stay hand-written.
    
    Generation fails when a listed member is missing from core, is listed
    twice, or changes kind in core. A core field that the table does not
    list stays unexposed, keeps its core default, and is named in the
    generated Rust conversion.
    
    Part of #9324.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fixup! feat(bindings/cpp): generate ListOptions from core
    
    Document each generated ListOptions member with the first paragraph of
    its core doc comment, wrapped like the Capability and Metadata headers.
    The frozen-surface test now pins the declarations without comments, and
    a new test pins each member comment to core's doc text.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fixup! feat(bindings/cpp): generate ListOptions from core
    
    Document ListOptions members with core's full doc comments and render
    rustdoc links as plain code spans.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fixup! feat(bindings/cpp): generate ListOptions from core
    
    - Render code spans that name a core capability as the member of the
      generated C++ class, e.g. `opendal::Capability::list_with_start_after`,
      spelled by `cpp_name`. Unknown paths and option member names, which
      keep their core names in C++, stay as written.
    - Test that changing the kind of core `start_after` to `bool` fails
      generation.
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    ---------
    
    Signed-off-by: Chitral Verma <[email protected]>
---
 .github/workflows/ci_bindings_cpp.yml         |   1 +
 bindings/cpp/CMakeLists.txt                   |   6 +-
 bindings/cpp/build.rs                         |  10 +-
 bindings/cpp/include/data_structure.hpp       |  13 +-
 bindings/cpp/include/options.hpp              |  58 +++
 bindings/cpp/src/lib.rs                       |  36 +-
 bindings/cpp/src/operator.cpp                 |  17 +-
 bindings/cpp/src/options.rs                   |  67 +++
 bindings/cpp/src/options_test.rs              |  74 ++++
 bindings/cpp/src/utils/options_converter.cpp  |  63 +++
 bindings/cpp/src/utils/options_converter.hpp  |  32 ++
 bindings/cpp/tests/options_test.cpp           |  82 ++++
 dev/src/generate/cpp.rs                       | 584 +++++++++++++++++++++++++-
 dev/src/generate/cpp/options_converter_cpp.j2 |  63 +++
 dev/src/generate/cpp/options_converter_hpp.j2 |  33 ++
 dev/src/generate/cpp/options_hpp.j2           |  46 ++
 dev/src/generate/cpp/options_rs.j2            |  73 ++++
 17 files changed, 1205 insertions(+), 53 deletions(-)

diff --git a/.github/workflows/ci_bindings_cpp.yml 
b/.github/workflows/ci_bindings_cpp.yml
index ab49dfab78..21cbd5ae3e 100644
--- a/.github/workflows/ci_bindings_cpp.yml
+++ b/.github/workflows/ci_bindings_cpp.yml
@@ -27,6 +27,7 @@ on:
     paths:
       - "core/core/src/types/capability.rs"
       - "core/core/src/types/metadata.rs"
+      - "core/core/src/types/options.rs"
       - "dev/src/generate/**"
       - "bindings/cpp/**"
       - "examples/cpp/**"
diff --git a/bindings/cpp/CMakeLists.txt b/bindings/cpp/CMakeLists.txt
index 1db63cdba2..c6a5b90b56 100644
--- a/bindings/cpp/CMakeLists.txt
+++ b/bindings/cpp/CMakeLists.txt
@@ -111,8 +111,8 @@ set(CARGO_MANIFEST ${PROJECT_SOURCE_DIR}/Cargo.toml)
 
 # Keep bridge files with the CMake build that selected their Cargo features.
 set(CXX_BRIDGE_DIR ${CMAKE_CURRENT_BINARY_DIR}/cxxbridge)
-set(RUST_BRIDGE_CPP ${CXX_BRIDGE_DIR}/opendal-cpp/src/lib.rs.cc 
${CXX_BRIDGE_DIR}/opendal-cpp/src/capability.rs.cc 
${CXX_BRIDGE_DIR}/opendal-cpp/src/metadata.rs.cc)
-set(RUST_HEADER_FILE ${CXX_BRIDGE_DIR}/opendal-cpp/src/lib.rs.h 
${CXX_BRIDGE_DIR}/opendal-cpp/src/capability.rs.h 
${CXX_BRIDGE_DIR}/opendal-cpp/src/metadata.rs.h ${CXX_BRIDGE_DIR}/rust/cxx.h)
+set(RUST_BRIDGE_CPP ${CXX_BRIDGE_DIR}/opendal-cpp/src/lib.rs.cc 
${CXX_BRIDGE_DIR}/opendal-cpp/src/capability.rs.cc 
${CXX_BRIDGE_DIR}/opendal-cpp/src/metadata.rs.cc 
${CXX_BRIDGE_DIR}/opendal-cpp/src/options.rs.cc)
+set(RUST_HEADER_FILE ${CXX_BRIDGE_DIR}/opendal-cpp/src/lib.rs.h 
${CXX_BRIDGE_DIR}/opendal-cpp/src/capability.rs.h 
${CXX_BRIDGE_DIR}/opendal-cpp/src/metadata.rs.h 
${CXX_BRIDGE_DIR}/opendal-cpp/src/options.rs.h ${CXX_BRIDGE_DIR}/rust/cxx.h)
 if (OPENDAL_ENABLE_ASYNC)
     list(APPEND RUST_BRIDGE_CPP ${CXX_BRIDGE_DIR}/opendal-cpp/src/async.rs.cc)
     list(APPEND RUST_HEADER_FILE ${CXX_BRIDGE_DIR}/opendal-cpp/src/async.rs.h 
${CXX_BRIDGE_DIR}/rust/cxx_async.h)
@@ -222,7 +222,7 @@ if (OPENDAL_ENABLE_TESTING)
         )
     endif()
 
-    list(APPEND TEST_SOURCE_FILE tests/basic_test.cpp 
tests/capability_test.cpp tests/layer_test.cpp tests/metadata_test.cpp 
tests/timestamp_test.cpp tests/test_main.cpp)
+    list(APPEND TEST_SOURCE_FILE tests/basic_test.cpp 
tests/capability_test.cpp tests/layer_test.cpp tests/metadata_test.cpp 
tests/options_test.cpp tests/timestamp_test.cpp tests/test_main.cpp)
     if (OPENDAL_ENABLE_ASYNC)
         list(APPEND TEST_SOURCE_FILE tests/async_test.cpp)
     endif()
diff --git a/bindings/cpp/build.rs b/bindings/cpp/build.rs
index b7956952dd..fb462bf96c 100644
--- a/bindings/cpp/build.rs
+++ b/bindings/cpp/build.rs
@@ -46,6 +46,8 @@ fn export_bridge(out_dir: &Path, bridge_dir: &Path) -> 
io::Result<()> {
         ("sources", "opendal-cpp/src/lib.rs.cc"),
         ("include", "opendal-cpp/src/metadata.rs.h"),
         ("sources", "opendal-cpp/src/metadata.rs.cc"),
+        ("include", "opendal-cpp/src/options.rs.h"),
+        ("sources", "opendal-cpp/src/options.rs.cc"),
     ];
     if cfg!(feature = "async") {
         files.extend([
@@ -69,10 +71,16 @@ fn main() -> io::Result<()> {
             "src/capability.rs",
             "src/lib.rs",
             "src/metadata.rs",
+            "src/options.rs",
             "src/async.rs",
         ][..]
     } else {
-        &["src/capability.rs", "src/lib.rs", "src/metadata.rs"][..]
+        &[
+            "src/capability.rs",
+            "src/lib.rs",
+            "src/metadata.rs",
+            "src/options.rs",
+        ][..]
     };
     let _ = cxx_build::bridges(sources);
 
diff --git a/bindings/cpp/include/data_structure.hpp 
b/bindings/cpp/include/data_structure.hpp
index f430c0efb5..2c4de58c23 100644
--- a/bindings/cpp/include/data_structure.hpp
+++ b/bindings/cpp/include/data_structure.hpp
@@ -28,6 +28,7 @@
 
 #include "capability.hpp"
 #include "metadata.hpp"
+#include "options.hpp"
 
 namespace opendal {
 
@@ -171,16 +172,4 @@ struct DeleteOptions {
   bool recursive{false};
 };
 
-/**
- * @struct ListOptions
- * @brief Options for list and lister operations.
- */
-struct ListOptions {
-  std::optional<std::size_t> limit;
-  std::optional<std::string> start_after;
-  bool recursive{false};
-  bool versions{false};
-  bool deleted{false};
-};
-
 }  // namespace opendal
diff --git a/bindings/cpp/include/options.hpp b/bindings/cpp/include/options.hpp
new file mode 100644
index 0000000000..2806081ab6
--- /dev/null
+++ b/bindings/cpp/include/options.hpp
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ */
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
+// opendal/dev/src/generate/cpp.rs.
+
+#pragma once
+
+#include <cstddef>
+#include <optional>
+#include <string>
+
+namespace opendal {
+
+/**
+ * @struct ListOptions
+ * @brief Options for list and lister operations.
+ */
+struct ListOptions {
+  /// Maximum results per request (backend hint) to control memory and
+  /// throttling.
+  std::optional<std::size_t> limit;
+  /// Start listing after this key, excluding the key itself.
+  ///
+  /// Setting this requires `opendal::Capability::list_with_start_after`.
+  std::optional<std::string> start_after;
+  /// Whether to list recursively under the prefix; default `false`.
+  ///
+  /// Setting this option to `true` requires the operator's effective
+  /// `opendal::Capability::list_with_recursive` capability.
+  bool recursive{false};
+  /// Include object versions; default `false`.
+  ///
+  /// Requires `opendal::Capability::list_with_versions`.
+  bool versions{false};
+  /// Include delete markers; default `false`.
+  ///
+  /// Requires `opendal::Capability::list_with_deleted`.
+  bool deleted{false};
+};
+
+}  // namespace opendal
diff --git a/bindings/cpp/src/lib.rs b/bindings/cpp/src/lib.rs
index 32ee0e6bd9..f3d5ddfaf3 100644
--- a/bindings/cpp/src/lib.rs
+++ b/bindings/cpp/src/lib.rs
@@ -21,6 +21,7 @@ mod capability;
 mod layer;
 mod lister;
 mod metadata;
+mod options;
 mod reader;
 mod types;
 mod writer;
@@ -28,6 +29,9 @@ mod writer;
 #[cfg(feature = "testing")]
 mod test_support;
 
+#[cfg(test)]
+mod options_test;
+
 pub use layer::LayerBuilder;
 
 use std::collections::HashMap;
@@ -149,14 +153,6 @@ mod ffi {
         recursive: bool,
     }
 
-    struct FfiListOptions {
-        limit: OptionalUsize,
-        start_after: OptionalString,
-        recursive: bool,
-        versions: bool,
-        deleted: bool,
-    }
-
     #[cxx_name = "SeekDir"]
     enum SeekFrom {
         Start = 0,
@@ -191,6 +187,13 @@ mod ffi {
         type Metadata = crate::metadata::ffi::Metadata;
     }
 
+    // Generated from core by `dev/src/generate/cpp.rs`; see src/options.rs.
+    unsafe extern "C++" {
+        include!("opendal-cpp/src/options.rs.h");
+        #[namespace = "opendal::ffi::options"]
+        type FfiListOptions = crate::options::ffi::FfiListOptions;
+    }
+
     extern "Rust" {
         type Operator;
         type Reader;
@@ -508,17 +511,6 @@ fn delete_options(opts: ffi::FfiDeleteOptions) -> 
od::options::DeleteOptions {
     }
 }
 
-fn list_options(opts: ffi::FfiListOptions) -> od::options::ListOptions {
-    od::options::ListOptions {
-        limit: optional_usize(opts.limit),
-        start_after: optional_string(opts.start_after),
-        recursive: opts.recursive,
-        versions: opts.versions,
-        deleted: opts.deleted,
-        glob: None,
-    }
-}
-
 impl Operator {
     fn read(&self, path: &str) -> Result<Vec<u8>> {
         Ok(self.0.read(path)?.to_vec())
@@ -593,7 +585,7 @@ impl Operator {
     fn list_options(&self, path: &str, opts: ffi::FfiListOptions) -> 
Result<Vec<ffi::Entry>> {
         Ok(self
             .0
-            .list_options(path, list_options(opts))?
+            .list_options(path, opts.into())?
             .into_iter()
             .map(Into::into)
             .collect())
@@ -637,9 +629,7 @@ impl Operator {
     }
 
     fn lister_options(&self, path: &str, opts: ffi::FfiListOptions) -> 
Result<*mut Lister> {
-        let lister = Box::into_raw(Box::new(Lister(
-            self.0.lister_options(path, list_options(opts))?,
-        )));
+        let lister = Box::into_raw(Box::new(Lister(self.0.lister_options(path, 
opts.into())?)));
         Ok(lister)
     }
 
diff --git a/bindings/cpp/src/operator.cpp b/bindings/cpp/src/operator.cpp
index b3d54c63d7..8b62ae1739 100644
--- a/bindings/cpp/src/operator.cpp
+++ b/bindings/cpp/src/operator.cpp
@@ -26,6 +26,7 @@
 #include "utils/capability_converter.hpp"
 #include "utils/ffi_converter.hpp"
 #include "utils/metadata_converter.hpp"
+#include "utils/options_converter.hpp"
 #include "utils/rust_converter.hpp"
 
 namespace opendal {
@@ -177,16 +178,6 @@ ffi::FfiDeleteOptions ToFfiOptions(const DeleteOptions 
&options) {
                                options.recursive};
 }
 
-ffi::FfiListOptions ToFfiOptions(const ListOptions &options) {
-  return ffi::FfiListOptions{
-      ToFfiOptionalUsize(options.limit),
-      ToFfiOptionalString(options.start_after),
-      options.recursive,
-      options.versions,
-      options.deleted,
-  };
-}
-
 const ffi::Operator &CheckedOperator(const ffi::Operator *op) {
   if (op == nullptr) {
     throw std::logic_error(
@@ -346,7 +337,7 @@ std::vector<Entry> Operator::List(std::string_view path) {
 std::vector<Entry> Operator::List(std::string_view path,
                                   const ListOptions &options) {
   auto rust_vec = CheckedOperator(operator_).list_options(
-      utils::rust_str(path), ToFfiOptions(options));
+      utils::rust_str(path), utils::ToFfiOptions(options));
 
   std::vector<Entry> entries;
   entries.reserve(rust_vec.size());
@@ -362,8 +353,8 @@ Lister Operator::GetLister(std::string_view path) {
 }
 
 Lister Operator::GetLister(std::string_view path, const ListOptions &options) {
-  return CheckedOperator(operator_).lister_options(utils::rust_str(path),
-                                                   ToFfiOptions(options));
+  return CheckedOperator(operator_).lister_options(
+      utils::rust_str(path), utils::ToFfiOptions(options));
 }
 
 Reader Operator::GetReader(std::string_view path) {
diff --git a/bindings/cpp/src/options.rs b/bindings/cpp/src/options.rs
new file mode 100644
index 0000000000..23a12f9600
--- /dev/null
+++ b/bindings/cpp/src/options.rs
@@ -0,0 +1,67 @@
+// 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.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by 
opendal/dev/src/generate/cpp.rs.
+
+/// Shared operation options structs, kept in their own bridge so they can be
+/// generated from core and reused by the main bridge in `lib.rs`.
+///
+/// `lib.rs.h` includes this bridge's header, so this bridge cannot use the
+/// value structs of `lib.rs` and declares its own in a nested namespace.
+#[cxx::bridge(namespace = "opendal::ffi::options")]
+pub mod ffi {
+    struct OptionalString {
+        has_value: bool,
+        value: String,
+    }
+
+    struct OptionalUsize {
+        has_value: bool,
+        value: usize,
+    }
+
+    struct FfiListOptions {
+        limit: OptionalUsize,
+        start_after: OptionalString,
+        recursive: bool,
+        versions: bool,
+        deleted: bool,
+    }
+}
+
+fn optional_string(v: ffi::OptionalString) -> Option<String> {
+    v.has_value.then_some(v.value)
+}
+
+fn optional_usize(v: ffi::OptionalUsize) -> Option<usize> {
+    v.has_value.then_some(v.value)
+}
+
+impl From<ffi::FfiListOptions> for opendal::options::ListOptions {
+    fn from(opts: ffi::FfiListOptions) -> Self {
+        Self {
+            limit: optional_usize(opts.limit),
+            start_after: optional_string(opts.start_after),
+            recursive: opts.recursive,
+            versions: opts.versions,
+            deleted: opts.deleted,
+            // Not exposed in C++ yet:
+            // - `glob`
+            ..Default::default()
+        }
+    }
+}
diff --git a/bindings/cpp/src/options_test.rs b/bindings/cpp/src/options_test.rs
new file mode 100644
index 0000000000..6d6d53e529
--- /dev/null
+++ b/bindings/cpp/src/options_test.rs
@@ -0,0 +1,74 @@
+// 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.
+
+//! The generated `ListOptions` conversion in `options.rs` carries every bridge
+//! field to the core field of the same name, and absent values stay absent.
+
+use opendal::options::ListOptions;
+
+use crate::options::ffi;
+
+fn bridge_list_options(limit: Option<usize>, start_after: Option<&str>) -> 
ffi::FfiListOptions {
+    ffi::FfiListOptions {
+        limit: ffi::OptionalUsize {
+            has_value: limit.is_some(),
+            value: limit.unwrap_or(7),
+        },
+        start_after: ffi::OptionalString {
+            has_value: start_after.is_some(),
+            value: start_after.unwrap_or("ignored").to_string(),
+        },
+        recursive: false,
+        versions: false,
+        deleted: false,
+    }
+}
+
+#[test]
+fn test_list_options_carry_every_field() {
+    let opts = ffi::FfiListOptions {
+        recursive: true,
+        versions: true,
+        deleted: true,
+        ..bridge_list_options(Some(16), Some("start_after"))
+    };
+
+    let expected = ListOptions {
+        limit: Some(16),
+        start_after: Some("start_after".to_string()),
+        recursive: true,
+        versions: true,
+        deleted: true,
+        ..Default::default()
+    };
+    assert_eq!(ListOptions::from(opts), expected);
+}
+
+#[test]
+fn test_list_options_keep_explicit_zero_limit() {
+    let opts = bridge_list_options(Some(0), None);
+
+    assert_eq!(ListOptions::from(opts).limit, Some(0));
+}
+
+#[test]
+fn test_list_options_keep_absent_values_absent() {
+    // C++ sends a value behind `has_value == false`; it must not reach core.
+    let opts = bridge_list_options(None, None);
+
+    assert_eq!(ListOptions::from(opts), ListOptions::default());
+}
diff --git a/bindings/cpp/src/utils/options_converter.cpp 
b/bindings/cpp/src/utils/options_converter.cpp
new file mode 100644
index 0000000000..c1b357ef5d
--- /dev/null
+++ b/bindings/cpp/src/utils/options_converter.cpp
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
+// opendal/dev/src/generate/cpp.rs.
+
+#include "utils/options_converter.hpp"
+
+#include <cstddef>
+#include <optional>
+#include <string>
+
+#include "utils/rust_converter.hpp"
+
+namespace opendal::utils {
+
+namespace {
+
+ffi::options::OptionalString ToFfiOptionalString(
+    const std::optional<std::string> &value) {
+  if (value.has_value()) {
+    return ffi::options::OptionalString{true, rust_string(*value)};
+  }
+  return ffi::options::OptionalString{false, rust::String()};
+}
+
+ffi::options::OptionalUsize ToFfiOptionalUsize(
+    const std::optional<std::size_t> &value) {
+  if (value.has_value()) {
+    return ffi::options::OptionalUsize{true, *value};
+  }
+  return ffi::options::OptionalUsize{false, 0};
+}
+
+}  // namespace
+
+ffi::options::FfiListOptions ToFfiOptions(const ListOptions &options) {
+  return ffi::options::FfiListOptions{
+      ToFfiOptionalUsize(options.limit),
+      ToFfiOptionalString(options.start_after),
+      options.recursive,
+      options.versions,
+      options.deleted,
+  };
+}
+
+}  // namespace opendal::utils
diff --git a/bindings/cpp/src/utils/options_converter.hpp 
b/bindings/cpp/src/utils/options_converter.hpp
new file mode 100644
index 0000000000..ba41d354f3
--- /dev/null
+++ b/bindings/cpp/src/utils/options_converter.hpp
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
+// opendal/dev/src/generate/cpp.rs.
+
+#pragma once
+
+#include "options.hpp"
+#include "options.rs.h"
+
+namespace opendal::utils {
+
+ffi::options::FfiListOptions ToFfiOptions(const ListOptions &options);
+
+}  // namespace opendal::utils
diff --git a/bindings/cpp/tests/options_test.cpp 
b/bindings/cpp/tests/options_test.cpp
new file mode 100644
index 0000000000..5288f6f493
--- /dev/null
+++ b/bindings/cpp/tests/options_test.cpp
@@ -0,0 +1,82 @@
+/*
+ * 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 <cstddef>
+#include <string>
+
+#include "gtest/gtest.h"
+#include "opendal.hpp"
+#include "utils/options_converter.hpp"
+
+TEST(OptionsTest, ListOptionsPositionalInitializerReachesBridge) {
+  // Every member in the order `data_structure.hpp` declared them before
+  // `ListOptions` was generated.
+  const opendal::ListOptions options{
+      /*limit=*/16,
+      /*start_after=*/"start_after",
+      /*recursive=*/true,
+      /*versions=*/true,
+      /*deleted=*/true,
+  };
+
+  const auto ffi = opendal::utils::ToFfiOptions(options);
+
+  EXPECT_TRUE(ffi.limit.has_value);
+  EXPECT_EQ(ffi.limit.value, std::size_t{16});
+  EXPECT_TRUE(ffi.start_after.has_value);
+  EXPECT_EQ(std::string(ffi.start_after.value), "start_after");
+  EXPECT_TRUE(ffi.recursive);
+  EXPECT_TRUE(ffi.versions);
+  EXPECT_TRUE(ffi.deleted);
+}
+
+TEST(OptionsTest, ListOptionsStructuredBindingsKeepMemberOrder) {
+  opendal::ListOptions options;
+  auto &[limit, start_after, recursive, versions, deleted] = options;
+
+  EXPECT_EQ(&limit, &options.limit);
+  EXPECT_EQ(&start_after, &options.start_after);
+  EXPECT_EQ(&recursive, &options.recursive);
+  EXPECT_EQ(&versions, &options.versions);
+  EXPECT_EQ(&deleted, &options.deleted);
+}
+
+TEST(OptionsTest, ListOptionsKeepExplicitZeroLimit) {
+  opendal::ListOptions options;
+  options.limit = 0;
+
+  const auto ffi = opendal::utils::ToFfiOptions(options);
+
+  EXPECT_TRUE(ffi.limit.has_value);
+  EXPECT_EQ(ffi.limit.value, std::size_t{0});
+}
+
+TEST(OptionsTest, DefaultListOptionsReachBridgeAbsent) {
+  // A const object can be default-initialized only while each scalar member
+  // has a default member initializer.
+  const opendal::ListOptions options;
+
+  const auto ffi = opendal::utils::ToFfiOptions(options);
+
+  EXPECT_FALSE(ffi.limit.has_value);
+  EXPECT_FALSE(ffi.start_after.has_value);
+  EXPECT_FALSE(ffi.recursive);
+  EXPECT_FALSE(ffi.versions);
+  EXPECT_FALSE(ffi.deleted);
+}
diff --git a/dev/src/generate/cpp.rs b/dev/src/generate/cpp.rs
index 302e62187f..273c7647d7 100644
--- a/dev/src/generate/cpp.rs
+++ b/dev/src/generate/cpp.rs
@@ -22,8 +22,13 @@
 //! copy between them. All three are rendered from the same field list.
 //! `opendal::Metadata` crosses the same three layers and is rendered from the
 //! core accessor list.
+//!
+//! Operation options cross four layers: the public struct, the cxx shared
+//! struct, the C++ `ToFfiOptions` conversion, and the Rust conversion into
+//! core. All four are rendered from `OPTIONS`.
 
 use super::capability;
+use super::core_options::{self, OptionKind};
 use super::metadata::{self, MetadataKind};
 use anyhow::{Context, Result, bail};
 use minijinja::value::Serde;
@@ -183,7 +188,8 @@ const FROZEN_PUBLIC_ORDER: &[&str] = &[
 
 pub fn generate(workspace_dir: &Path) -> Result<()> {
     generate_capability(workspace_dir)?;
-    generate_metadata(workspace_dir)
+    generate_metadata(workspace_dir)?;
+    generate_options(workspace_dir)
 }
 
 /// Order core names for a public C++ class by its append-only `frozen` list,
@@ -509,6 +515,312 @@ fn render_metadata(workspace_dir: &Path) -> 
Result<Vec<(&'static str, String)>>
     Ok(rendered)
 }
 
+/// One core options struct that crosses into C++, and the fields it carries.
+struct OptionsSpec {
+    /// Core struct name, also the name of the public C++ struct.
+    name: &'static str,
+    /// `@brief` of the public C++ struct.
+    brief: &'static str,
+    /// Carried core fields and their kinds, in the declaration order of the
+    /// public C++ struct.
+    ///
+    /// Callers may brace-initialize the public struct by position or with
+    /// designated initializers, so this order is append-only. A core field
+    /// that is not listed is not exposed in C++ and keeps its core default.
+    fields: &'static [(&'static str, OptionKind)],
+}
+
+/// Options structs generated into `include/options.hpp`. The other options
+/// structs are still hand-written in `include/data_structure.hpp`.
+const OPTIONS: &[OptionsSpec] = {
+    use OptionKind::*;
+
+    &[OptionsSpec {
+        name: "ListOptions",
+        brief: "Options for list and lister operations.",
+        fields: &[
+            ("limit", OptionUsize),
+            ("start_after", OptionString),
+            ("recursive", Bool),
+            ("versions", Bool),
+            ("deleted", Bool),
+        ],
+    }]
+};
+
+/// Render model of one options struct. Every per-kind decision is made in
+/// `option_member`, so the templates stay structural.
+#[derive(Debug, Serialize)]
+struct OptionsModel {
+    /// Core struct name, also the public C++ struct name.
+    name: &'static str,
+    /// Name of the cxx bridge struct.
+    bridge_name: String,
+    /// `@brief` of the public C++ struct.
+    brief: &'static str,
+    /// Carried fields, in `OptionsSpec::fields` order.
+    members: Vec<OptionMember>,
+    /// Core fields that C++ does not expose, in core order.
+    unexposed: Vec<String>,
+    /// Whether the Rust conversion leaves core fields to `Default::default()`.
+    fills_defaults: bool,
+}
+
+#[derive(Debug, PartialEq, Serialize)]
+struct OptionMember {
+    /// Field name in core, the bridge struct, and the public C++ struct.
+    name: String,
+    /// Core field doc with rustdoc links rendered as code spans, each
+    /// paragraph wrapped for the header's `///` comments. An empty line
+    /// separates paragraphs.
+    hpp_doc_lines: Vec<String>,
+    /// Declaration of the public C++ member.
+    hpp_member: String,
+    /// Field type in the cxx bridge struct.
+    bridge_type: &'static str,
+    /// Expression converting the public C++ member into the bridge field.
+    cpp_value: String,
+    /// Expression converting the bridge field into the core field.
+    rust_value: String,
+}
+
+/// Map one core option field to its public C++ member, bridge field, and
+/// conversions.
+///
+/// Fails for a kind the bridge cannot carry yet, so such a field cannot be
+/// listed in `OPTIONS` by mistake.
+fn option_member(
+    options: &str,
+    field: &core_options::OptionField,
+    kind: OptionKind,
+    capabilities: &[capability::CapabilityField],
+) -> Result<OptionMember> {
+    let name = field.name.as_str();
+    let member = format!("options.{name}");
+    let bridge_field = format!("opts.{name}");
+    // (public type, member initializer, bridge type, C++ conversion, Rust
+    // conversion)
+    let (cpp_type, cpp_init, bridge_type, cpp_value, rust_value) = match kind {
+        OptionKind::Bool => ("bool", "{false}", "bool", member, bridge_field),
+        OptionKind::OptionUsize => (
+            "std::optional<std::size_t>",
+            "",
+            "OptionalUsize",
+            format!("ToFfiOptionalUsize({member})"),
+            format!("optional_usize({bridge_field})"),
+        ),
+        OptionKind::OptionString => (
+            "std::optional<std::string>",
+            "",
+            "OptionalString",
+            format!("ToFfiOptionalString({member})"),
+            format!("optional_string({bridge_field})"),
+        ),
+        _ => bail!("the C++ bridge cannot carry `{options}::{name}` of kind 
{kind:?} yet"),
+    };
+    Ok(OptionMember {
+        name: name.to_string(),
+        hpp_doc_lines: option_doc_lines(&field.doc, capabilities),
+        hpp_member: format!("{cpp_type} {name}{cpp_init};"),
+        bridge_type,
+        cpp_value,
+        rust_value,
+    })
+}
+
+/// The core doc comment of an option field as it reads in the C++ header.
+///
+/// Each paragraph is wrapped to fit the header's `///` comments, and an empty
+/// line separates paragraphs. Rustdoc links become plain code spans, because
+/// Doxygen cannot resolve Rust paths:
+/// ``[`Capability::list_with_limit`](crate::Capability::list_with_limit)``
+/// and ``[`crate::layers::SimulateLayer`]`` keep only their code span. Code
+/// spans that name a C++ member then use its C++ name (see `cpp_code_span`);
+/// other code spans stay as written.
+fn option_doc_lines(doc: &[String], capabilities: 
&[capability::CapabilityField]) -> Vec<String> {
+    let mut lines = Vec::new();
+    for paragraph in doc.split(|line| line.trim().is_empty()) {
+        if paragraph.is_empty() {
+            continue;
+        }
+        if !lines.is_empty() {
+            lines.push(String::new());
+        }
+        let text = paragraph
+            .iter()
+            .map(|line| cpp_code_spans(&strip_rustdoc_links(line.trim()), 
capabilities))
+            .collect::<Vec<_>>()
+            .join(" ");
+        lines.extend(wrap_doc(&text, HPP_DOC_PREFIX, HPP_COLUMN_LIMIT));
+    }
+    lines
+}
+
+/// Replace each rustdoc intra-doc link in `line` with its code span.
+fn strip_rustdoc_links(line: &str) -> String {
+    let mut out = String::with_capacity(line.len());
+    let mut rest = line;
+    while let Some(start) = rest.find("[`") {
+        let Some(len) = rest[start + 1..].find("`]") else {
+            break;
+        };
+        out.push_str(&rest[..start]);
+        out.push_str(&rest[start + 1..start + len + 2]);
+        rest = &rest[start + len + 3..];
+        if let Some(target) = rest.strip_prefix('(')
+            && let Some(end) = target.find(')')
+        {
+            rest = &target[end + 1..];
+        }
+    }
+    out.push_str(rest);
+    out
+}
+
+/// Replace each code span in `line` that names a C++ member with its C++ name.
+fn cpp_code_spans(line: &str, capabilities: &[capability::CapabilityField]) -> 
String {
+    let mut out = String::with_capacity(line.len());
+    let mut rest = line;
+    while let Some(start) = rest.find('`') {
+        let Some(len) = rest[start + 1..].find('`') else {
+            break;
+        };
+        let code = &rest[start + 1..start + 1 + len];
+        out.push_str(&rest[..=start]);
+        out.push_str(&cpp_code_span(code, capabilities).unwrap_or_else(|| 
code.to_string()));
+        out.push('`');
+        rest = &rest[start + len + 2..];
+    }
+    out.push_str(rest);
+    out
+}
+
+/// The C++ name of a code span that names a member of the C++ surface, or
+/// `None` to keep the code span as written.
+///
+/// A core capability such as `Capability::list_with_start_after` reads
+/// `opendal::Capability::list_with_start_after`, the member of the
+/// `opendal::Capability` that `Operator::Info()` returns, spelled by
+/// `cpp_name`. Option members keep their core names in C++, so a span such as
+/// `start_after` stays as written.
+fn cpp_code_span(code: &str, capabilities: &[capability::CapabilityField]) -> 
Option<String> {
+    let name = code
+        .strip_prefix("crate::")
+        .unwrap_or(code)
+        .strip_prefix("Capability::")?;
+    capabilities
+        .iter()
+        .any(|f| f.name == name)
+        .then(|| format!("opendal::Capability::{}", cpp_name(name)))
+}
+
+/// Check `specs` against the parsed core structs and build their render
+/// models.
+///
+/// Fails if a listed struct or field is missing from core, because dropping it
+/// would silently break source compatibility, if a field is listed twice, or
+/// if a field's kind in core differs from its listed kind, because that would
+/// change the public C++ member type.
+fn options_models(
+    parsed: &[core_options::OptionsStruct],
+    specs: &[OptionsSpec],
+    capabilities: &[capability::CapabilityField],
+) -> Result<Vec<OptionsModel>> {
+    let mut models = Vec::with_capacity(specs.len());
+    for spec in specs {
+        let core = parsed
+            .iter()
+            .find(|s| s.name == spec.name)
+            .with_context(|| format!("OPTIONS struct `{}` is missing from 
core", spec.name))?;
+        let mut members = Vec::with_capacity(spec.fields.len());
+        for (i, &(name, kind)) in spec.fields.iter().enumerate() {
+            if spec.fields[..i].iter().any(|(listed, _)| *listed == name) {
+                bail!("OPTIONS lists `{}::{name}` twice", spec.name);
+            }
+            let field = core
+                .fields
+                .iter()
+                .find(|f| f.name == name)
+                .with_context(|| {
+                    format!(
+                        "OPTIONS member `{}::{name}` is missing from core",
+                        spec.name
+                    )
+                })?;
+            if field.kind != kind {
+                bail!(
+                    "core `{}::{name}` has kind {:?}, but OPTIONS lists 
{kind:?}",
+                    spec.name,
+                    field.kind
+                );
+            }
+            members.push(option_member(spec.name, field, kind, capabilities)?);
+        }
+        let unexposed: Vec<String> = core
+            .fields
+            .iter()
+            .filter(|f| !spec.fields.iter().any(|(listed, _)| *listed == 
f.name))
+            .map(|f| f.name.clone())
+            .collect();
+        models.push(OptionsModel {
+            name: spec.name,
+            bridge_name: format!("Ffi{}", spec.name),
+            brief: spec.brief,
+            fills_defaults: !unexposed.is_empty() || 
core.has_unmirrored_fields,
+            members,
+            unexposed,
+        });
+    }
+    Ok(models)
+}
+
+fn generate_options(workspace_dir: &Path) -> Result<()> {
+    for (relative, rendered) in render_options(workspace_dir)? {
+        fs::write(workspace_dir.join(relative), format!("{rendered}\n"))?;
+    }
+    Ok(())
+}
+
+/// Render every options output as `(path relative to workspace, content)`.
+fn render_options(workspace_dir: &Path) -> Result<Vec<(&'static str, String)>> 
{
+    let parsed = 
core_options::parse(&workspace_dir.join("core/core/src/types/options.rs"))?;
+    let capabilities = 
capability::parse(&workspace_dir.join("core/core/src/types/capability.rs"))?;
+    let options = options_models(&parsed, OPTIONS, &capabilities)?;
+
+    let mut env = Environment::new();
+    env.add_template("options_hpp", include_str!("cpp/options_hpp.j2"))?;
+    env.add_template("options_rs", include_str!("cpp/options_rs.j2"))?;
+    env.add_template(
+        "options_converter_hpp",
+        include_str!("cpp/options_converter_hpp.j2"),
+    )?;
+    env.add_template(
+        "options_converter_cpp",
+        include_str!("cpp/options_converter_cpp.j2"),
+    )?;
+
+    let outputs = [
+        ("options_hpp", "bindings/cpp/include/options.hpp"),
+        ("options_rs", "bindings/cpp/src/options.rs"),
+        (
+            "options_converter_hpp",
+            "bindings/cpp/src/utils/options_converter.hpp",
+        ),
+        (
+            "options_converter_cpp",
+            "bindings/cpp/src/utils/options_converter.cpp",
+        ),
+    ];
+    let mut rendered = Vec::with_capacity(outputs.len());
+    for (template, relative) in outputs {
+        let content = env
+            .get_template(template)?
+            .render(context! { options => Serde(&options) })?;
+        rendered.push((relative, content));
+    }
+    Ok(rendered)
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -637,6 +949,276 @@ mod tests {
         assert!(err.contains("`cache_control` is missing from core"));
     }
 
+    /// `ListOptions` as `bindings/cpp/include/data_structure.hpp` declared it 
on
+    /// `main` before it was generated, copied verbatim. Callers depend on each
+    /// member's name, type, default member initializer, and position. The
+    /// generated header adds member doc comments, which this text omits.
+    const MAIN_LIST_OPTIONS: &str = r#"/**
+ * @struct ListOptions
+ * @brief Options for list and lister operations.
+ */
+struct ListOptions {
+  std::optional<std::size_t> limit;
+  std::optional<std::string> start_after;
+  bool recursive{false};
+  bool versions{false};
+  bool deleted{false};
+};"#;
+
+    fn parsed_options() -> Vec<core_options::OptionsStruct> {
+        
core_options::parse(&workspace_dir().join("core/core/src/types/options.rs"))
+            .expect("parse core options")
+    }
+
+    fn rendered_options(path: &str) -> String {
+        render_options(&workspace_dir())
+            .unwrap()
+            .into_iter()
+            .find(|(relative, _)| *relative == path)
+            .map(|(_, content)| content)
+            .expect("rendered output")
+    }
+
+    #[test]
+    fn test_rendered_options_header_keeps_main_list_options() {
+        let header = rendered_options("bindings/cpp/include/options.hpp");
+        let declarations: String = header
+            .lines()
+            .filter(|line| !line.starts_with("  ///"))
+            .map(|line| format!("{line}\n"))
+            .collect();
+        assert!(
+            declarations.contains(MAIN_LIST_OPTIONS),
+            "header no longer 
declares:\n{MAIN_LIST_OPTIONS}\n\nheader:\n{header}"
+        );
+        assert_eq!(header.matches("\nstruct ").count(), 1);
+    }
+
+    /// Split doc text into paragraphs, each joined into one line of words.
+    fn paragraphs<'a>(lines: impl IntoIterator<Item = &'a str>) -> Vec<String> 
{
+        let mut paragraphs = vec![Vec::new()];
+        for line in lines {
+            match line.trim() {
+                "" => paragraphs.push(Vec::new()),
+                text => paragraphs.last_mut().unwrap().push(text),
+            }
+        }
+        paragraphs
+            .into_iter()
+            .filter(|words| !words.is_empty())
+            .map(|words| words.join(" "))
+            .collect()
+    }
+
+    #[test]
+    fn test_rendered_options_header_documents_members_with_core_docs() {
+        let header = rendered_options("bindings/cpp/include/options.hpp");
+        let lines: Vec<&str> = header.lines().collect();
+        let list = parsed_options()
+            .into_iter()
+            .find(|s| s.name == "ListOptions")
+            .unwrap();
+        for (name, _) in OPTIONS[0].fields {
+            // Core's full doc, with `[`code`](target)` and `[`code`]` links
+            // reduced to their code span.
+            let core_doc = list
+                .fields
+                .iter()
+                .find(|f| f.name == *name)
+                .unwrap()
+                .doc
+                .join("\n");
+            let mut plain = String::new();
+            let mut rest = core_doc.as_str();
+            while let Some(at) = rest.find("](") {
+                let close = rest[at..].find(')').unwrap();
+                plain.push_str(&rest[..at + 1]);
+                rest = &rest[at + close + 1..];
+            }
+            plain.push_str(rest);
+            // C++ callers read capabilities from the `opendal::Capability`
+            // that `Operator::Info()` returns.
+            let plain = plain
+                .replace("[`", "`")
+                .replace("`]", "`")
+                .replace("`Capability::", "`opendal::Capability::");
+            let expected = paragraphs(plain.lines());
+            assert!(
+                !expected.is_empty(),
+                "core `ListOptions::{name}` has no doc"
+            );
+
+            let decl = lines
+                .iter()
+                .position(|line| {
+                    !line.starts_with("  ///")
+                        && (line.ends_with(&format!(" {name};"))
+                            || line.ends_with(&format!(" {name}{{false}};")))
+                })
+                .unwrap_or_else(|| panic!("header lacks `{name}`"));
+            let mut comment: Vec<&str> = lines[..decl]
+                .iter()
+                .rev()
+                .map_while(|line| line.strip_prefix("  ///"))
+                .collect();
+            comment.reverse();
+            assert_eq!(
+                paragraphs(comment),
+                expected,
+                "doc of `ListOptions::{name}`"
+            );
+        }
+        // A rendered intra-doc link, copied from core's `start_after` doc.
+        assert!(header.contains(
+            "  ///\n  /// Setting this requires 
`opendal::Capability::list_with_start_after`.\n"
+        ));
+        assert!(!header.contains("[`"));
+        assert!(!header.contains("](crate::"));
+        assert!(!header.contains(" `Capability::"));
+
+        // Each referenced capability is a member of the generated C++ class.
+        let capability_header = 
rendered("bindings/cpp/include/capability.hpp");
+        let mut referenced = 0;
+        for reference in header.split("`opendal::Capability::").skip(1) {
+            let member = &reference[..reference.find('`').unwrap()];
+            assert!(
+                capability_header.contains(&format!("  bool 
{member}{{false}};\n")),
+                "capability.hpp lacks `{member}`"
+            );
+            referenced += 1;
+        }
+        assert_eq!(referenced, 4);
+    }
+
+    #[test]
+    fn test_option_doc_lines_render_rustdoc_links_as_code() {
+        let doc = [
+            "Requires 
[`Capability::list_with_limit`](crate::Capability::list_with_limit).",
+            "",
+            "Rely on [`crate::layers::SimulateLayer`] and 
[`Self::recursive`].",
+            "A [plain](https://opendal.apache.org) link and `code` stay.",
+        ]
+        .map(String::from);
+        assert_eq!(
+            option_doc_lines(&doc, &core_fields()),
+            [
+                "Requires `opendal::Capability::list_with_limit`.",
+                "",
+                "Rely on `crate::layers::SimulateLayer` and `Self::recursive`. 
A",
+                "[plain](https://opendal.apache.org) link and `code` stay.",
+            ]
+        );
+    }
+
+    #[test]
+    fn test_option_doc_lines_use_cpp_names() {
+        let doc = [
+            "- Pagination: `limit`, `start_after`.",
+            "",
+            "Requires 
[`Capability::list_with_start_after`](crate::Capability::list_with_start_after).",
+            "",
+            "Requires [`crate::Capability::list_with_versions`] and 
`Capability::delete`.",
+            "",
+            "Unknown `Capability::no_such_flag`, 
[`crate::ErrorKind::Unsupported`], `glob`, and prose Capability::list stay.",
+        ]
+        .map(String::from);
+        assert_eq!(
+            option_doc_lines(&doc, &core_fields()),
+            [
+                "- Pagination: `limit`, `start_after`.",
+                "",
+                "Requires `opendal::Capability::list_with_start_after`.",
+                "",
+                "Requires `opendal::Capability::list_with_versions` and",
+                "`opendal::Capability::delete_feature`.",
+                "",
+                "Unknown `Capability::no_such_flag`, 
`crate::ErrorKind::Unsupported`,",
+                "`glob`, and prose Capability::list stay.",
+            ]
+        );
+    }
+
+    #[test]
+    fn test_new_core_field_stays_unexposed() {
+        let mut parsed = parsed_options();
+        let before = options_models(&parsed, OPTIONS, &core_fields()).unwrap();
+        let list = parsed.iter_mut().find(|s| s.name == 
"ListOptions").unwrap();
+        list.fields.insert(
+            1,
+            core_options::OptionField {
+                name: "new_mid".to_string(),
+                kind: OptionKind::OptionString,
+                doc: Vec::new(),
+            },
+        );
+
+        let after = options_models(&parsed, OPTIONS, &core_fields()).unwrap();
+
+        assert_eq!(before[0].members, after[0].members);
+        assert_eq!(after[0].unexposed[0], "new_mid");
+        assert_eq!(after[0].unexposed[1..], before[0].unexposed[..]);
+        assert!(after[0].fills_defaults);
+    }
+
+    #[test]
+    fn test_options_models_reject_incompatible_specs() {
+        use OptionKind::*;
+
+        let parsed = parsed_options();
+        let error = |name: &'static str, fields: &'static [(&'static str, 
OptionKind)]| {
+            let spec = OptionsSpec {
+                name,
+                brief: "",
+                fields,
+            };
+            options_models(&parsed, &[spec], &core_fields())
+                .unwrap_err()
+                .to_string()
+        };
+
+        assert_eq!(
+            error("MissingOptions", &[]),
+            "OPTIONS struct `MissingOptions` is missing from core"
+        );
+        assert_eq!(
+            error("ListOptions", &[("missing", OptionString)]),
+            "OPTIONS member `ListOptions::missing` is missing from core"
+        );
+        assert_eq!(
+            error(
+                "ListOptions",
+                &[("limit", OptionUsize), ("limit", OptionUsize)]
+            ),
+            "OPTIONS lists `ListOptions::limit` twice"
+        );
+        assert_eq!(
+            error("ListOptions", &[("limit", OptionU64)]),
+            "core `ListOptions::limit` has kind OptionUsize, but OPTIONS lists 
OptionU64"
+        );
+        // Core changing a listed field to another kind the bridge carries must
+        // fail too, instead of silently turning `start_after` into a `bool`.
+        let mut changed = parsed.clone();
+        let list = changed
+            .iter_mut()
+            .find(|s| s.name == "ListOptions")
+            .unwrap();
+        list.fields
+            .iter_mut()
+            .find(|f| f.name == "start_after")
+            .unwrap()
+            .kind = Bool;
+        assert_eq!(
+            options_models(&changed, OPTIONS, &core_fields())
+                .unwrap_err()
+                .to_string(),
+            "core `ListOptions::start_after` has kind Bool, but OPTIONS lists 
OptionString"
+        );
+        assert_eq!(
+            error("ReadOptions", &[("if_modified_since", OptionTimestamp)]),
+            "the C++ bridge cannot carry `ReadOptions::if_modified_since` of 
kind OptionTimestamp yet"
+        );
+    }
+
     #[test]
     fn test_accessor_lines_match_clang_format() {
         // Layouts that clang-format 18 and 23 produce with bindings/cpp's
diff --git a/dev/src/generate/cpp/options_converter_cpp.j2 
b/dev/src/generate/cpp/options_converter_cpp.j2
new file mode 100644
index 0000000000..f06f8b95be
--- /dev/null
+++ b/dev/src/generate/cpp/options_converter_cpp.j2
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
+// opendal/dev/src/generate/cpp.rs.
+
+#include "utils/options_converter.hpp"
+
+#include <cstddef>
+#include <optional>
+#include <string>
+
+#include "utils/rust_converter.hpp"
+
+namespace opendal::utils {
+
+namespace {
+
+ffi::options::OptionalString ToFfiOptionalString(
+    const std::optional<std::string> &value) {
+  if (value.has_value()) {
+    return ffi::options::OptionalString{true, rust_string(*value)};
+  }
+  return ffi::options::OptionalString{false, rust::String()};
+}
+
+ffi::options::OptionalUsize ToFfiOptionalUsize(
+    const std::optional<std::size_t> &value) {
+  if (value.has_value()) {
+    return ffi::options::OptionalUsize{true, *value};
+  }
+  return ffi::options::OptionalUsize{false, 0};
+}
+
+}  // namespace
+{%- for s in options %}
+
+ffi::options::{{ s.bridge_name }} ToFfiOptions(const {{ s.name }} &options) {
+  return ffi::options::{{ s.bridge_name }}{
+{%- for m in s.members %}
+      {{ m.cpp_value }},
+{%- endfor %}
+  };
+}
+{%- endfor %}
+
+}  // namespace opendal::utils
diff --git a/dev/src/generate/cpp/options_converter_hpp.j2 
b/dev/src/generate/cpp/options_converter_hpp.j2
new file mode 100644
index 0000000000..b22dd2a927
--- /dev/null
+++ b/dev/src/generate/cpp/options_converter_hpp.j2
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
+// opendal/dev/src/generate/cpp.rs.
+
+#pragma once
+
+#include "options.hpp"
+#include "options.rs.h"
+
+namespace opendal::utils {
+{% for s in options %}
+ffi::options::{{ s.bridge_name }} ToFfiOptions(const {{ s.name }} &options);
+{%- endfor %}
+
+}  // namespace opendal::utils
diff --git a/dev/src/generate/cpp/options_hpp.j2 
b/dev/src/generate/cpp/options_hpp.j2
new file mode 100644
index 0000000000..df368aca02
--- /dev/null
+++ b/dev/src/generate/cpp/options_hpp.j2
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+// DO NOT EDIT IT MANUALLY. This file is generated by
+// opendal/dev/src/generate/cpp.rs.
+
+#pragma once
+
+#include <cstddef>
+#include <optional>
+#include <string>
+
+namespace opendal {
+{%- for s in options %}
+
+/**
+ * @struct {{ s.name }}
+ * @brief {{ s.brief }}
+ */
+struct {{ s.name }} {
+{%- for m in s.members %}
+{%- for line in m.hpp_doc_lines %}
+  ///{% if line %} {{ line }}{% endif %}
+{%- endfor %}
+  {{ m.hpp_member }}
+{%- endfor %}
+};
+{%- endfor %}
+
+}  // namespace opendal
diff --git a/dev/src/generate/cpp/options_rs.j2 
b/dev/src/generate/cpp/options_rs.j2
new file mode 100644
index 0000000000..0961ba943e
--- /dev/null
+++ b/dev/src/generate/cpp/options_rs.j2
@@ -0,0 +1,73 @@
+// 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.
+
+// DO NOT EDIT IT MANUALLY. This file is generated by 
opendal/dev/src/generate/cpp.rs.
+
+/// Shared operation options structs, kept in their own bridge so they can be
+/// generated from core and reused by the main bridge in `lib.rs`.
+///
+/// `lib.rs.h` includes this bridge's header, so this bridge cannot use the
+/// value structs of `lib.rs` and declares its own in a nested namespace.
+#[cxx::bridge(namespace = "opendal::ffi::options")]
+pub mod ffi {
+    struct OptionalString {
+        has_value: bool,
+        value: String,
+    }
+
+    struct OptionalUsize {
+        has_value: bool,
+        value: usize,
+    }
+{%- for s in options %}
+
+    struct {{ s.bridge_name }} {
+{%- for m in s.members %}
+        {{ m.name }}: {{ m.bridge_type }},
+{%- endfor %}
+    }
+{%- endfor %}
+}
+
+fn optional_string(v: ffi::OptionalString) -> Option<String> {
+    v.has_value.then_some(v.value)
+}
+
+fn optional_usize(v: ffi::OptionalUsize) -> Option<usize> {
+    v.has_value.then_some(v.value)
+}
+{%- for s in options %}
+
+impl From<ffi::{{ s.bridge_name }}> for opendal::options::{{ s.name }} {
+    fn from(opts: ffi::{{ s.bridge_name }}) -> Self {
+        Self {
+{%- for m in s.members %}
+            {{ m.name }}: {{ m.rust_value }},
+{%- endfor %}
+{%- if s.unexposed %}
+            // Not exposed in C++ yet:
+{%- for name in s.unexposed %}
+            // - `{{ name }}`
+{%- endfor %}
+{%- endif %}
+{%- if s.fills_defaults %}
+            ..Default::default()
+{%- endif %}
+        }
+    }
+}
+{%- endfor %}
\ No newline at end of file

Reply via email to