chitralverma commented on code in PR #9332:
URL: https://github.com/apache/opendal/pull/9332#discussion_r4726037414


##########
dev/src/generate/python.rs:
##########
@@ -626,6 +629,276 @@ const PYTHON_LICENSE_HEADER: &str = "\
 # under the License.
 ";
 
+/// A Python options class generated from the core options struct of the
+/// same name. The class and field docstrings come from the core doc comments.
+struct PyOptions {
+    /// The class name, e.g. `ListOptions`.
+    name: &'static str,
+    /// The keyword arguments in their Python order: the name, which is also
+    /// the core field and the Rust field it sets, and the kind that core
+    /// field must have. A core field that no keyword argument sets is not
+    /// exposed and keeps its default.
+    options: &'static [(&'static str, OptionKind)],
+}
+
+/// The Python options classes generated from `core/core/src/types/options.rs`.
+/// The other classes in `bindings/python/src/options.rs` are hand-written.
+const GENERATED_OPTIONS: &[PyOptions] = &[PyOptions {
+    name: "ListOptions",
+    options: &[
+        ("limit", OptionKind::OptionUsize),
+        ("start_after", OptionKind::OptionString),
+        ("recursive", OptionKind::Bool),
+        ("versions", OptionKind::Bool),
+        ("deleted", OptionKind::Bool),
+    ],
+}];
+
+/// The class order of `options.py`, which hand-written and generated classes
+/// share.
+const OPTIONS_PY_ORDER: &[&str] = &[
+    "ReadOptions",
+    "WriteOptions",
+    "ListOptions",
+    "StatOptions",
+    "CopyOptions",
+    "RenameOptions",
+    "DeleteOptions",
+];
+
+/// Render model of one generated Python options class.
+#[derive(Debug, Serialize)]
+struct PyClass {
+    name: &'static str,
+    /// The core doc comment, one entry per line.
+    doc: Vec<String>,
+    fields: Vec<PyField>,
+    /// Every field of the core struct in core order, with the expression
+    /// that sets it.
+    conversion: Vec<ConvertField>,
+}
+
+#[derive(Debug, Serialize)]
+struct PyField {
+    name: &'static str,
+    kind: OptionKind,
+    /// The core doc comment, one entry per line.
+    doc: Vec<String>,
+    rust_type: &'static str,
+}
+
+#[derive(Debug, Serialize)]
+struct ConvertField {
+    name: String,
+    expr: String,
+}
+
+/// The Rust field type of a keyword argument and its `options.py` type, for
+/// the core kinds that generated classes expose so far.
+fn option_types(kind: OptionKind) -> Option<(&'static str, 
options::OptionType)> {
+    Some(match kind {
+        OptionKind::OptionString => ("Option<String>", 
options::OptionType::Str),
+        OptionKind::OptionUsize => ("Option<usize>", options::OptionType::Int),
+        OptionKind::Bool => ("Option<bool>", options::OptionType::Bool),
+        _ => return None,
+    })
+}
+
+/// The value of a core field that Python does not expose. Every core options
+/// struct derives `Default`, so this equals the field's default.
+fn default_expr(kind: OptionKind) -> &'static str {
+    match kind {
+        OptionKind::Bool => "false",
+        OptionKind::Usize => "0",
+        OptionKind::BytesRange => "Default::default()",
+        _ => "None",
+    }
+}
+
+/// The docstring of a generated class or field: the core doc comment, one
+/// entry per line.
+///
+/// Rustdoc links become plain code spans, because Python documentation
+/// 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 core capability then use its Python name (see
+/// [`py_code_span`]); other code spans stay as written.
+fn py_doc(
+    core_doc: &[String],
+    item: &str,
+    capabilities: &[CapabilityField],
+) -> Result<Vec<String>> {
+    if core_doc.iter().all(|line| line.is_empty()) {
+        bail!("core {item} has no doc comment");
+    }
+    let mut lines = Vec::with_capacity(core_doc.len());
+    for line in core_doc {
+        let mut unlinked = String::with_capacity(line.len());
+        let mut rest = line.as_str();
+        while let Some(start) = rest.find("[`") {
+            let Some(len) = rest[start + 1..].find("`]") else {
+                break;
+            };
+            unlinked.push_str(&rest[..start]);
+            unlinked.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..];
+            }
+        }
+        unlinked.push_str(rest);
+
+        let mut out = String::with_capacity(unlinked.len());
+        let mut rest = unlinked.as_str();
+        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(&py_code_span(code, capabilities).unwrap_or_else(|| 
code.to_string()));
+            out.push('`');
+            rest = &rest[start + len + 2..];
+        }
+        out.push_str(rest);
+        if out.contains('"') || out.contains('\\') {
+            bail!(
+                "core {item} doc line `{out}` has a character docstrings must 
escape; \

Review Comment:
   (AI-generated reply) Fixed in 6d5f53554 (head a6e8d19c8, which merges main).
   
   **Docstrings through `just fmt`.** D301 accepts `\u` escapes, so both 
docstrings now use them:
   
   - `options.py`: the generator writes a backslash as `\u005c`, and a `"` that 
would join the surrounding quotes as `\u0022`: a leading `"`, every third `"` 
in a row, and quotes right before inline closing quotes. The leading `"` was 
the D210 failure. `ruff format` put a space between `"""` and the `"`, and D210 
then rejected the docstring.
   - `_opendal.pyi`: pyo3-introspection 0.30.1 always writes a backslash as 
`\\` and every third `"` as `\"`. No pyclass doc text avoids that, because the 
text must keep the backslash. `scripts/postprocess_stubs.py` therefore rewrites 
those docstrings in the stubs with the same `\u` escapes before `just fmt` 
runs. The pyclass `///` doc, and so the runtime `__doc__`, stays core's text 
unescaped. Stubs without a backslash in a docstring are unchanged.
   - With the sample applied, the escaped `options.py` summary line is 90 
characters, so E501 also failed `just fmt`. `ruff.toml` now exempts 
`options.py` from E501, as it already exempts `config.py` and `capability.pyi`, 
the other generated files that copy core docs.
   
   With the sample as core's `ListOptions` summary on a6e8d19c8, `just 
stub-gen`, a second `just fmt`, and `just lint` exit 0. Python's `ast` reads 
the sample summary back from `ListKwargs` in `options.py` and from 
`ListOptions` in `_opendal.pyi`, and the runtime `__doc__` of both classes 
matches. After I reverted the sample, `just stub-gen` and every `ci_odev.yml` 
generator plus `cargo fmt` leave `git diff --exit-code` clean.
   
   Regression tests:
   - `test_list_options_survive_any_core_doc` pins the rendered `options.py` 
lines for the sample. It also checks that every backslash in `options.py` 
starts a `\u` escape, that no docstring opens with `""""`, the values Python's 
`ast` reads back, and that the generated pyclass doc is the sample unescaped.
   - New `bindings/python/tests/test_stub_docstrings.py` runs the ruff steps of 
`just fmt` with the binding's `ruff.toml` on that `ListKwargs` line, and on the 
`ListOptions` stub docstring as pyo3-introspection writes it after 
`escape_docstrings`. It then checks the parsed values. It runs in the 
behavior-test jobs. In CI, the `stubs` job's `just stub-gen` + `git diff 
--exit-code` covers the real pipeline.
   - Scratch mutations that fail these tests: in the generator, a backslash 
written as `\\`, or no leading-quote, trailing-quote, or `"""` escape. In 
`postprocess_stubs.py`, turning off `escape_docstrings`, or its leading- or 
trailing-quote escape. Dropping the E501 entry also fails.
   
   **Capability check.** The test now takes each field's capability from the 
docs generated from unmodified core, which name it as `op.capability().x` 
whatever markup core uses. With the `recursive` link changed to the plain code 
span, the generated Python files are byte-identical and all 11 Python generator 
tests pass. The same core edit fails the test as of 2bcb5b7a9. Naming the wrong 
capability for `recursive` (`list_with_versions`) still fails 3 tests, whether 
as a rustdoc link or a plain code span.
   



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to