Skip to contentSkip to conversation

Don't generate netlink .rst files inside $(srctree)

PATCH Superseded Mauro Carvalho Chehab 3 participants 27 messages Jun 26, 2025 – Jul 9, 2025

Subsystems (6)

v8 of 10 Superseded Latest is v10 →

lore
Share & tools
lore
#22 lore raw

PATCH v8 13/13 docs: parser_yaml.py: fix backward compatibility with old docutils

In reply to Mauro Carvalho Chehab

As reported by Akira, older docutils versions are not compatible with the way some Sphinx versions send tab_width. Add a code to address it.

---
 Documentation/sphinx/parser_yaml.py | 4 ++++
 1 file changed, 4 insertions(+)
Documentation/sphinx/parser_yaml.py +4 -0
index 8288e2ff7c7c..1602b31f448e 100755
@@ -77,6 +77,10 @@ class YamlParser(Parser):
 
                 result.append(line, document.current_source, lineoffset)
 
+            # Fix backward compatibility with docutils < 0.17.1
+            if "tab_width" not in vars(document.settings):
+                document.settings.tab_width = 8
+
             rst_parser = RSTParser()
             rst_parser.parse('\n'.join(result), document)
 
Signature · 1 line
2.49.0
#9 lore raw

PATCH v8 6/13 docs: use parser_yaml extension to handle Netlink specs

In reply to Mauro Carvalho Chehab

Instead of manually calling ynl_gen_rst.py, use a Sphinx extension. This way, no .rst files would be written to the Kernel source directories.

We are using here a toctree with :glob: property. This way, there is no need to touch the netlink/specs/index.rst file every time a new Netlink spec is added/renamed/removed.

---
 Documentation/Makefile                        | 17 ----------------
 Documentation/conf.py                         | 20 ++++++++++++++-----
 Documentation/networking/index.rst            |  2 +-
 .../networking/netlink_spec/readme.txt        |  4 ----
 Documentation/sphinx/parser_yaml.py           |  4 ++--
 5 files changed, 18 insertions(+), 29 deletions(-)
 delete mode 100644 Documentation/networking/netlink_spec/readme.txt
Documentation/Makefile +0 -17
index b98477df5ddf..820f07e0afe6 100644
@@ -104,22 +104,6 @@ quiet_cmd_sphinx = SPHINX  $@ --> file://$(abspath $(BUILDDIR)/$3/$4)
 		cp $(if $(patsubst /%,,$(DOCS_CSS)),$(abspath $(srctree)/$(DOCS_CSS)),$(DOCS_CSS)) $(BUILDDIR)/$3/_static/; \
 	fi
 
-YNL_INDEX:=$(srctree)/Documentation/networking/netlink_spec/index.rst
-YNL_RST_DIR:=$(srctree)/Documentation/networking/netlink_spec
-YNL_YAML_DIR:=$(srctree)/Documentation/netlink/specs
-YNL_TOOL:=$(srctree)/tools/net/ynl/pyynl/ynl_gen_rst.py
-
-YNL_RST_FILES_TMP := $(patsubst %.yaml,%.rst,$(wildcard $(YNL_YAML_DIR)/*.yaml))
-YNL_RST_FILES := $(patsubst $(YNL_YAML_DIR)%,$(YNL_RST_DIR)%, $(YNL_RST_FILES_TMP))
-
-$(YNL_INDEX): $(YNL_RST_FILES)
-	$(Q)$(YNL_TOOL) -o $@ -x
-
-$(YNL_RST_DIR)/%.rst: $(YNL_YAML_DIR)/%.yaml $(YNL_TOOL)
-	$(Q)$(YNL_TOOL) -i $< -o $@
-
-htmldocs texinfodocs latexdocs epubdocs xmldocs: $(YNL_INDEX)
-
 htmldocs:
 	@$(srctree)/scripts/sphinx-pre-install --version-check
 	@+$(foreach var,$(SPHINXDIRS),$(call loop_cmd,sphinx,html,$(var),,$(var)))
@@ -186,7 +170,6 @@ refcheckdocs:
 	$(Q)cd $(srctree);scripts/documentation-file-ref-check
 
 cleandocs:
-	$(Q)rm -f $(YNL_INDEX) $(YNL_RST_FILES)
 	$(Q)rm -rf $(BUILDDIR)
 	$(Q)$(MAKE) BUILDDIR=$(abspath $(BUILDDIR)) $(build)=Documentation/userspace-api/media clean
 
Documentation/conf.py +15 -5
index df99a4d96b58..61dcc5fecb7c 100644
@@ -106,6 +106,15 @@ exclude_patterns = []
 dyn_include_patterns = []
 dyn_exclude_patterns = ["output"]
 
+# Currently, only netlink/specs has a parser for yaml.
+# Prefer using include patterns if available, as it is faster
+if has_include_patterns:
+    dyn_include_patterns.append("netlink/specs/*.yaml")
+else:
+    dyn_exclude_patterns.append("netlink/*.yaml")
+    dyn_exclude_patterns.append("devicetree/bindings/**.yaml")
+    dyn_exclude_patterns.append("core-api/kho/bindings/**.yaml")
+
 # Properly handle include/exclude patterns
 # ----------------------------------------
 
@@ -166,12 +175,12 @@ extensions = [
     "kernel_include",
     "kfigure",
     "maintainers_include",
+    "parser_yaml",
     "rstFlatTable",
     "sphinx.ext.autosectionlabel",
     "sphinx.ext.ifconfig",
     "translations",
 ]
-
 # Since Sphinx version 3, the C function parser is more pedantic with regards
 # to type checking. Due to that, having macros at c:function cause problems.
 # Those needed to be escaped by using c_id_attributes[] array
@@ -268,10 +277,11 @@ else:
 # Add any paths that contain templates here, relative to this directory.
 templates_path = ["sphinx/templates"]
 
-# The suffix(es) of source filenames.
-# You can specify multiple suffix as a list of string:
-# source_suffix = ['.rst', '.md']
-source_suffix = '.rst'
+# The suffixes of source filenames that will be automatically parsed
+source_suffix = {
+    ".rst": "restructuredtext",
+    ".yaml": "yaml",
+}
 
 # The encoding of source files.
 # source_encoding = 'utf-8-sig'
Documentation/networking/index.rst +1 -1
index ac90b82f3ce9..b7a4969e9bc9 100644
@@ -57,7 +57,7 @@ Contents:
    filter
    generic-hdlc
    generic_netlink
-   netlink_spec/index
+   ../netlink/specs/index
    gen_stats
    gtp
    ila
Documentation/networking/netlink_spec/readme.txt deleted +0 -4
deleted file mode 100644
index 030b44aca4e6..000000000000
@@ -1,4 +0,0 @@
-SPDX-License-Identifier: GPL-2.0
-
-This file is populated during the build of the documentation (htmldocs) by the
-tools/net/ynl/pyynl/ynl_gen_rst.py script.
Documentation/sphinx/parser_yaml.py +2 -2
index 585a7ec81ba0..fa2e6da17617 100755
@@ -18,9 +18,9 @@ from sphinx.util import logging
 from sphinx.parsers import Parser
 
 srctree = os.path.abspath(os.environ["srctree"])
-sys.path.insert(0, os.path.join(srctree, "tools/net/ynl/pyynl"))
+sys.path.insert(0, os.path.join(srctree, "tools/net/ynl/pyynl/lib"))
 
-from netlink_yml_parser import YnlDocGenerator        # pylint: disable=C0413
+from doc_generator import YnlDocGenerator        # pylint: disable=C0413
 
 logger = logging.getLogger(__name__)
 
Signature · 1 line
2.49.0
#18 lore raw

PATCH v8 11/13 tools: netlink_yml_parser.py: add line numbers to parsed data

In reply to Mauro Carvalho Chehab

When something goes wrong, we want Sphinx error to point to the right line number from the original source, not from the processed ReST data.

---
 tools/net/ynl/pyynl/lib/doc_generator.py | 34 ++++++++++++++++++++++--
 1 file changed, 32 insertions(+), 2 deletions(-)
tools/net/ynl/pyynl/lib/doc_generator.py +32 -2
index 866551726723..a9d8ab6f2639 100644
@@ -20,6 +20,16 @@
 from typing import Any, Dict, List
 import yaml
 
+LINE_STR = '__lineno__'
+
+class NumberedSafeLoader(yaml.SafeLoader):
+    """Override the SafeLoader class to add line number to parsed data"""
+
+    def construct_mapping(self, node):
+        mapping = super().construct_mapping(node)
+        mapping[LINE_STR] = node.start_mark.line
+
+        return mapping
 
 class RstFormatters:
     """RST Formatters"""
@@ -127,6 +137,11 @@ class RstFormatters:
         """Return a formatted label"""
         return f".. _{title}:\n\n"
 
+    @staticmethod
+    def rst_lineno(lineno: int) -> str:
+        """Return a lineno comment"""
+        return f".. LINENO {lineno}\n"
+
 class YnlDocGenerator:
     """YAML Netlink specs Parser"""
 
@@ -144,6 +159,9 @@ class YnlDocGenerator:
         """Parse 'do' section and return a formatted string"""
         lines = []
         for key in do_dict.keys():
+            if key == LINE_STR:
+                lines.append(self.fmt.rst_lineno(do_dict[key]))
+                continue
             lines.append(self.fmt.rst_paragraph(self.fmt.bold(key), level + 1))
             if key in ['request', 'reply']:
                 lines.append(self.parse_do_attributes(do_dict[key], level + 1) + "\n")
@@ -174,6 +192,10 @@ class YnlDocGenerator:
             lines.append(self.fmt.rst_paragraph(operation["doc"]) + "\n")
 
             for key in operation.keys():
+                if key == LINE_STR:
+                    lines.append(self.fmt.rst_lineno(operation[key]))
+                    continue
+
                 if key in preprocessed:
                     # Skip the special fields
                     continue
@@ -233,6 +255,9 @@ class YnlDocGenerator:
         for definition in defs:
             lines.append(self.fmt.rst_section(namespace, 'definition', definition["name"]))
             for k in definition.keys():
+                if k == LINE_STR:
+                    lines.append(self.fmt.rst_lineno(definition[k]))
+                    continue
                 if k in preprocessed + ignored:
                     continue
                 lines.append(self.fmt.rst_fields(k, self.fmt.sanitize(definition[k]), 0))
@@ -268,6 +293,9 @@ class YnlDocGenerator:
                 lines.append(self.fmt.rst_subsubsection(attr_line))
 
                 for k in attr.keys():
+                    if k == LINE_STR:
+                        lines.append(self.fmt.rst_lineno(attr[k]))
+                        continue
                     if k in preprocessed + ignored:
                         continue
                     if k in linkable:
@@ -306,6 +334,8 @@ class YnlDocGenerator:
         lines = []
 
         # Main header
+        lineno = obj.get('__lineno__', 0)
+        lines.append(self.fmt.rst_lineno(lineno))
 
         family = obj['name']
 
@@ -354,7 +384,7 @@ class YnlDocGenerator:
     def parse_yaml_file(self, filename: str) -> str:
         """Transform the YAML specified by filename into an RST-formatted string"""
         with open(filename, "r", encoding="utf-8") as spec_file:
-            yaml_data = yaml.safe_load(spec_file)
-            content = self.parse_yaml(yaml_data)
+            numbered_yaml = yaml.load(spec_file, Loader=NumberedSafeLoader)
+            content = self.parse_yaml(numbered_yaml)
 
         return content
Signature · 1 line
2.49.0
#12 lore raw

PATCH v8 7/13 docs: uapi: netlink: update netlink specs link

In reply to Mauro Carvalho Chehab

With the recent parser_yaml extension, and the removal of the auto-generated ReST source files, the location of netlink specs changed.

Update uAPI accordingly.

---
 Documentation/userspace-api/netlink/index.rst | 2 +-
 Documentation/userspace-api/netlink/specs.rst | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
Documentation/userspace-api/netlink/index.rst +1 -1
index c1b6765cc963..83ae25066591 100644
@@ -18,4 +18,4 @@ Netlink documentation for users.
 
 See also:
  - :ref:`Documentation/core-api/netlink.rst <kernel_netlink>`
- - :ref:`Documentation/networking/netlink_spec/index.rst <specs>`
+ - :ref:`Documentation/netlink/specs/index.rst <specs>`
Documentation/userspace-api/netlink/specs.rst +1 -1
index 1b50d97d8d7c..debb4bfca5c4 100644
@@ -15,7 +15,7 @@ kernel headers directly.
 Internally kernel uses the YAML specs to generate:
 
  - the C uAPI header
- - documentation of the protocol as a ReST file - see :ref:`Documentation/networking/netlink_spec/index.rst <specs>`
+ - documentation of the protocol as a ReST file - see :ref:`Documentation/netlink/specs/index.rst <specs>`
  - policy tables for input attribute validation
  - operation tables
 
Signature · 1 line
2.49.0
#7 lore raw

PATCH v8 5/13 docs: sphinx: add a parser for yaml files for Netlink specs

In reply to Mauro Carvalho Chehab

Add a simple sphinx.Parser to handle yaml files and add the the code to handle Netlink specs. All other yaml files are ignored.

The code was written in a way that parsing yaml for different subsystems and even for different parts of Netlink are easy.

All it takes to have a different parser is to add an import line similar to:

from netlink_yml_parser import YnlDocGenerator

adding the corresponding parser somewhere at the extension:

netlink_parser = YnlDocGenerator()

And then add a logic inside parse() to handle different doc outputs, depending on the file location, similar to:

if "/netlink/specs/" in fname:
msg = self.netlink_parser.parse_yaml_file(fname)

---
 Documentation/sphinx/parser_yaml.py | 104 ++++++++++++++++++++++++++++
 1 file changed, 104 insertions(+)
 create mode 100755 Documentation/sphinx/parser_yaml.py
Documentation/sphinx/parser_yaml.py new file +104 -0
new file mode 100755
index 000000000000..585a7ec81ba0
@@ -0,0 +1,104 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright 2025 Mauro Carvalho Chehab <[email protected]>
+
+"""
+Sphinx extension for processing YAML files
+"""
+
+import os
+import re
+import sys
+
+from pprint import pformat
+
+from docutils.parsers.rst import Parser as RSTParser
+from docutils.statemachine import ViewList
+
+from sphinx.util import logging
+from sphinx.parsers import Parser
+
+srctree = os.path.abspath(os.environ["srctree"])
+sys.path.insert(0, os.path.join(srctree, "tools/net/ynl/pyynl"))
+
+from netlink_yml_parser import YnlDocGenerator        # pylint: disable=C0413
+
+logger = logging.getLogger(__name__)
+
+class YamlParser(Parser):
+    """
+    Kernel parser for YAML files.
+
+    This is a simple sphinx.Parser to handle yaml files inside the
+    Kernel tree that will be part of the built documentation.
+
+    The actual parser function is not contained here: the code was
+    written in a way that parsing yaml for different subsystems
+    can be done from a single dispatcher.
+
+    All it takes to have parse YAML patches is to have an import line:
+
+            from some_parser_code import NewYamlGenerator
+
+    To this module. Then add an instance of the parser with:
+
+            new_parser = NewYamlGenerator()
+
+    and add a logic inside parse() to handle it based on the path,
+    like this:
+
+            if "/foo" in fname:
+                msg = self.new_parser.parse_yaml_file(fname)
+    """
+
+    supported = ('yaml', )
+
+    netlink_parser = YnlDocGenerator()
+
+    def rst_parse(self, inputstring, document, msg):
+        """
+        Receives a ReST content that was previously converted by the
+        YAML parser, adding it to the document tree.
+        """
+
+        self.setup_parse(inputstring, document)
+
+        result = ViewList()
+
+        try:
+            # Parse message with RSTParser
+            for i, line in enumerate(msg.split('\n')):
+                result.append(line, document.current_source, i)
+
+            rst_parser = RSTParser()
+            rst_parser.parse('\n'.join(result), document)
+
+        except Exception as e:
+            document.reporter.error("YAML parsing error: %s" % pformat(e))
+
+        self.finish_parse()
+
+    # Overrides docutils.parsers.Parser. See sphinx.parsers.RSTParser
+    def parse(self, inputstring, document):
+        """Check if a YAML is meant to be parsed."""
+
+        fname = document.current_source
+
+        # Handle netlink yaml specs
+        if "/netlink/specs/" in fname:
+            msg = self.netlink_parser.parse_yaml_file(fname)
+            self.rst_parse(inputstring, document, msg)
+
+        # All other yaml files are ignored
+
+def setup(app):
+    """Setup function for the Sphinx extension."""
+
+    # Add YAML parser
+    app.add_source_parser(YamlParser)
+    app.add_source_suffix('.yaml', 'yaml')
+
+    return {
+        'version': '1.0',
+        'parallel_read_safe': True,
+        'parallel_write_safe': True,
+    }
Signature · 1 line
2.49.0
#15 lore raw

PATCH v8 9/13 docs: netlink: remove obsolete .gitignore from unused directory

In reply to Mauro Carvalho Chehab

The previous code was generating source rst files under Documentation/networking/netlink_spec/. With the Sphinx YAML parser, this is now gone. So, stop ignoring *.rst files inside netlink specs directory.

---
 Documentation/networking/netlink_spec/.gitignore | 1 -
 1 file changed, 1 deletion(-)
 delete mode 100644 Documentation/networking/netlink_spec/.gitignore
Documentation/networking/netlink_spec/.gitignore deleted +0 -1
deleted file mode 100644
index 30d85567b592..000000000000
@@ -1 +0,0 @@
-*.rst
Signature · 1 line
2.49.0
#5 lore raw

PATCH v8 4/13 tools: ynl_gen_rst.py: cleanup coding style

In reply to Mauro Carvalho Chehab

Cleanup some coding style issues pointed by pylint and flake8.

No functional changes.

---
 tools/net/ynl/pyynl/lib/doc_generator.py | 74 +++++++++---------------
 1 file changed, 26 insertions(+), 48 deletions(-)
tools/net/ynl/pyynl/lib/doc_generator.py +26 -48
index 80e468086693..866551726723 100644
@@ -18,17 +18,12 @@
 """
 
 from typing import Any, Dict, List
-import os.path
-import sys
-import argparse
-import logging
 import yaml
 
 
-# ==============
-# RST Formatters
-# ==============
 class RstFormatters:
+    """RST Formatters"""
+
     SPACE_PER_LEVEL = 4
 
     @staticmethod
@@ -36,81 +31,67 @@ class RstFormatters:
         """Return space to format"""
         return " " * (level * RstFormatters.SPACE_PER_LEVEL)
 
-
     @staticmethod
     def bold(text: str) -> str:
         """Format bold text"""
         return f"**{text}**"
 
-
     @staticmethod
     def inline(text: str) -> str:
         """Format inline text"""
         return f"``{text}``"
 
-
     @staticmethod
     def sanitize(text: str) -> str:
         """Remove newlines and multiple spaces"""
         # This is useful for some fields that are spread across multiple lines
         return str(text).replace("\n", " ").strip()
 
-
     def rst_fields(self, key: str, value: str, level: int = 0) -> str:
         """Return a RST formatted field"""
         return self.headroom(level) + f":{key}: {value}"
 
-
     def rst_definition(self, key: str, value: Any, level: int = 0) -> str:
         """Format a single rst definition"""
         return self.headroom(level) + key + "\n" + self.headroom(level + 1) + str(value)
 
-
     def rst_paragraph(self, paragraph: str, level: int = 0) -> str:
         """Return a formatted paragraph"""
         return self.headroom(level) + paragraph
 
-
     def rst_bullet(self, item: str, level: int = 0) -> str:
         """Return a formatted a bullet"""
         return self.headroom(level) + f"- {item}"
 
-
     @staticmethod
     def rst_subsection(title: str) -> str:
         """Add a sub-section to the document"""
         return f"{title}\n" + "-" * len(title)
 
-
     @staticmethod
     def rst_subsubsection(title: str) -> str:
         """Add a sub-sub-section to the document"""
         return f"{title}\n" + "~" * len(title)
 
-
     @staticmethod
     def rst_section(namespace: str, prefix: str, title: str) -> str:
         """Add a section to the document"""
         return f".. _{namespace}-{prefix}-{title}:\n\n{title}\n" + "=" * len(title)
 
-
     @staticmethod
     def rst_subtitle(title: str) -> str:
         """Add a subtitle to the document"""
         return "\n" + "-" * len(title) + f"\n{title}\n" + "-" * len(title) + "\n\n"
 
-
     @staticmethod
     def rst_title(title: str) -> str:
         """Add a title to the document"""
         return "=" * len(title) + f"\n{title}\n" + "=" * len(title) + "\n\n"
 
-
     def rst_list_inline(self, list_: List[str], level: int = 0) -> str:
         """Format a list using inlines"""
         return self.headroom(level) + "[" + ", ".join(self.inline(i) for i in list_) + "]"
 
-
     @staticmethod
     def rst_ref(namespace: str, prefix: str, name: str) -> str:
         """Add a hyperlink to the document"""
@@ -119,10 +100,9 @@ class RstFormatters:
                     'nested-attributes': 'attribute-set',
                     'struct': 'definition'}
         if prefix in mappings:
-            prefix = mappings[prefix]
+            prefix = mappings.get(prefix, "")
         return f":ref:`{namespace}-{prefix}-{name}`"
 
-
     def rst_header(self) -> str:
         """The headers for all the auto generated RST files"""
         lines = []
@@ -132,7 +112,6 @@ class RstFormatters:
 
         return "\n".join(lines)
 
-
     @staticmethod
     def rst_toctree(maxdepth: int = 2) -> str:
         """Generate a toctree RST primitive"""
@@ -143,16 +122,13 @@ class RstFormatters:
 
         return "\n".join(lines)
 
-
     @staticmethod
     def rst_label(title: str) -> str:
         """Return a formatted label"""
         return f".. _{title}:\n\n"
 
-# =======
-# Parsers
-# =======
 class YnlDocGenerator:
+    """YAML Netlink specs Parser"""
 
     fmt = RstFormatters()
 
@@ -164,7 +140,6 @@ class YnlDocGenerator:
 
         return "\n".join(lines)
 
-
     def parse_do(self, do_dict: Dict[str, Any], level: int = 0) -> str:
         """Parse 'do' section and return a formatted string"""
         lines = []
@@ -177,16 +152,16 @@ class YnlDocGenerator:
 
         return "\n".join(lines)
 
-
     def parse_do_attributes(self, attrs: Dict[str, Any], level: int = 0) -> str:
         """Parse 'attributes' section"""
         if "attributes" not in attrs:
             return ""
-        lines = [self.fmt.rst_fields("attributes", self.fmt.rst_list_inline(attrs["attributes"]), level + 1)]
+        lines = [self.fmt.rst_fields("attributes",
+                                     self.fmt.rst_list_inline(attrs["attributes"]),
+                                     level + 1)]
 
         return "\n".join(lines)
 
-
     def parse_operations(self, operations: List[Dict[str, Any]], namespace: str) -> str:
         """Parse operations block"""
         preprocessed = ["name", "doc", "title", "do", "dump", "flags"]
@@ -194,7 +169,8 @@ class YnlDocGenerator:
         lines = []
 
         for operation in operations:
-            lines.append(self.fmt.rst_section(namespace, 'operation', operation["name"]))
+            lines.append(self.fmt.rst_section(namespace, 'operation',
+                                              operation["name"]))
             lines.append(self.fmt.rst_paragraph(operation["doc"]) + "\n")
 
             for key in operation.keys():
@@ -206,7 +182,8 @@ class YnlDocGenerator:
                     value = self.fmt.rst_ref(namespace, key, value)
                 lines.append(self.fmt.rst_fields(key, value, 0))
             if 'flags' in operation:
-                lines.append(self.fmt.rst_fields('flags', self.fmt.rst_list_inline(operation['flags'])))
+                lines.append(self.fmt.rst_fields('flags',
+                                                 self.fmt.rst_list_inline(operation['flags'])))
 
             if "do" in operation:
                 lines.append(self.fmt.rst_paragraph(":do:", 0))
@@ -220,7 +197,6 @@ class YnlDocGenerator:
 
         return "\n".join(lines)
 
-
     def parse_entries(self, entries: List[Dict[str, Any]], level: int) -> str:
         """Parse a list of entries"""
         ignored = ["pad"]
@@ -235,17 +211,19 @@ class YnlDocGenerator:
                 if type_:
                     field_name += f" ({self.fmt.inline(type_)})"
                 lines.append(
-                    self.fmt.rst_fields(field_name, self.fmt.sanitize(entry.get("doc", "")), level)
+                    self.fmt.rst_fields(field_name,
+                                        self.fmt.sanitize(entry.get("doc", "")),
+                                        level)
                 )
             elif isinstance(entry, list):
                 lines.append(self.fmt.rst_list_inline(entry, level))
             else:
-                lines.append(self.fmt.rst_bullet(self.fmt.inline(self.fmt.sanitize(entry)), level))
+                lines.append(self.fmt.rst_bullet(self.fmt.inline(self.fmt.sanitize(entry)),
+                                                 level))
 
         lines.append("\n")
         return "\n".join(lines)
 
-
     def parse_definitions(self, defs: Dict[str, Any], namespace: str) -> str:
         """Parse definitions section"""
         preprocessed = ["name", "entries", "members"]
@@ -270,7 +248,6 @@ class YnlDocGenerator:
 
         return "\n".join(lines)
 
-
     def parse_attr_sets(self, entries: List[Dict[str, Any]], namespace: str) -> str:
         """Parse attribute from attribute-set"""
         preprocessed = ["name", "type"]
@@ -279,7 +256,8 @@ class YnlDocGenerator:
         lines = []
 
         for entry in entries:
-            lines.append(self.fmt.rst_section(namespace, 'attribute-set', entry["name"]))
+            lines.append(self.fmt.rst_section(namespace, 'attribute-set',
+                                              entry["name"]))
             for attr in entry["attributes"]:
                 type_ = attr.get("type")
                 attr_line = attr["name"]
@@ -301,13 +279,13 @@ class YnlDocGenerator:
 
         return "\n".join(lines)
 
-
     def parse_sub_messages(self, entries: List[Dict[str, Any]], namespace: str) -> str:
         """Parse sub-message definitions"""
         lines = []
 
         for entry in entries:
-            lines.append(self.fmt.rst_section(namespace, 'sub-message', entry["name"]))
+            lines.append(self.fmt.rst_section(namespace, 'sub-message',
+                                              entry["name"]))
             for fmt in entry["formats"]:
                 value = fmt["value"]
 
@@ -315,13 +293,14 @@ class YnlDocGenerator:
                 for attr in ['fixed-header', 'attribute-set']:
                     if attr in fmt:
                         lines.append(self.fmt.rst_fields(attr,
-                                                self.fmt.rst_ref(namespace, attr, fmt[attr]),
-                                                1))
+                                                         self.fmt.rst_ref(namespace,
+                                                                          attr,
+                                                                          fmt[attr]),
+                                                         1))
                 lines.append("\n")
 
         return "\n".join(lines)
 
-
     def parse_yaml(self, obj: Dict[str, Any]) -> str:
         """Format the whole YAML into a RST string"""
         lines = []
@@ -344,7 +323,8 @@ class YnlDocGenerator:
         # Operations
         if "operations" in obj:
             lines.append(self.fmt.rst_subtitle("Operations"))
-            lines.append(self.parse_operations(obj["operations"]["list"], family))
+            lines.append(self.parse_operations(obj["operations"]["list"],
+                                               family))
 
         # Multicast groups
         if "mcast-groups" in obj:
@@ -368,11 +348,9 @@ class YnlDocGenerator:
 
         return "\n".join(lines)
 
-
     # Main functions
     # ==============
 
-
     def parse_yaml_file(self, filename: str) -> str:
         """Transform the YAML specified by filename into an RST-formatted string"""
         with open(filename, "r", encoding="utf-8") as spec_file:
Signature · 1 line
2.49.0
#2 lore raw

PATCH v8 2/13 tools: ynl_gen_rst.py: Split library from command line tool

In reply to Mauro Carvalho Chehab

As we'll be using the Netlink specs parser inside a Sphinx extension, move the library part from the command line parser.

While here, change the code which generates an index file to parse inputs from both .rst and .yaml extensions. With that, the tool can easily be tested with:

tools/net/ynl/pyynl/ynl_gen_rst.py -x -o Documentation/netlink/specs/foo.rst

Without needing to first generate a temp directory with the rst files.

---
 tools/net/ynl/pyynl/lib/__init__.py      |   2 +
 tools/net/ynl/pyynl/lib/doc_generator.py | 382 +++++++++++++++++++++++
 tools/net/ynl/pyynl/ynl_gen_rst.py       | 375 +---------------------
 3 files changed, 400 insertions(+), 359 deletions(-)
 create mode 100644 tools/net/ynl/pyynl/lib/doc_generator.py
tools/net/ynl/pyynl/lib/__init__.py +2 -0
index 71518b9842ee..5f266ebe4526 100644
@@ -4,6 +4,8 @@ from .nlspec import SpecAttr, SpecAttrSet, SpecEnumEntry, SpecEnumSet, \
     SpecFamily, SpecOperation, SpecSubMessage, SpecSubMessageFormat
 from .ynl import YnlFamily, Netlink, NlError
 
+from .doc_generator import YnlDocGenerator
+
 __all__ = ["SpecAttr", "SpecAttrSet", "SpecEnumEntry", "SpecEnumSet",
            "SpecFamily", "SpecOperation", "SpecSubMessage", "SpecSubMessageFormat",
            "YnlFamily", "Netlink", "NlError"]
tools/net/ynl/pyynl/lib/doc_generator.py new file +382 -0

382 lines not on this page · raw message

tools/net/ynl/pyynl/ynl_gen_rst.py +16 -359

423 lines not on this page · raw message

Signature · 1 line
2.49.0
#16 lore raw

PATCH v8 10/13 MAINTAINERS: add netlink_yml_parser.py to linux-doc

In reply to Mauro Carvalho Chehab

The documentation build depends on the parsing code at ynl_gen_rst.py. Ensure that changes to it will be c/c to linux-doc ML and maintainers by adding an entry for it. This way, if a change there would affect the build, or the minimal version required for Python, doc developers may know in advance.

---
 MAINTAINERS | 1 +
 1 file changed, 1 insertion(+)
MAINTAINERS +1 -0
index a92290fffa16..ffe3afdad157 100644
@@ -7202,6 +7202,7 @@ F:	scripts/get_abi.py
 F:	scripts/kernel-doc*
 F:	scripts/lib/abi/*
 F:	scripts/lib/kdoc/*
+F:	tools/net/ynl/pyynl/lib/doc_generator.py
 F:	scripts/sphinx-pre-install
 X:	Documentation/ABI/
 X:	Documentation/admin-guide/media/
Signature · 1 line
2.49.0
#0 lore raw

v8 cover Don't generate netlink .rst files inside $(srctree)

Hi Jon,

That's the newest version of the parser-yaml series, addressing the points raised by Donald.

I dropped patches unrelated to the YAML work. Those were already merged at docs-next.

-

As discussed at:
https://lore.kernel.org/all/[email protected]/

changeset f061c9f7d058 ("Documentation: Document each netlink family") added a logic which generates *.rst files inside $(srctree). This is bad when O=<BUILDDIR> is used.

A recent change renamed the yaml files used by Netlink, revealing a bad side effect: as "make cleandocs" don't clean the produced files and symbols appear duplicated for people that don't build the kernel from scratch.

This series adds an yaml parser extension and uses an index file with glob for *. We opted to write such extension in a way that no actual yaml conversion code is inside it. This makes it flexible enough to handle other types of yaml files in the future. The actual yaml conversion logic were placed at netlink_yml_parser.py.

As requested by YNL maintainers, this version has netlink_yml_parser.py inside tools/net/ynl/pyynl/ directory. I don't like mixing libraries with binaries, nor to have Python libraries spread all over the Kernel. IMO, the best is to put all of them on a common place (scripts/lib, python/lib, lib/python, ...) but, as this can be solved later, for now let's keep it this way.

---

v8:
- minor fixes based on Donald's feedback;
- removed unrelated patches.

v7:
- Added a patch to cleanup conf.py and address coding style issues;
- Added a docutils version check logic to detect known issues when building the docs with too old or too new docutils version. The actuall min/max vesion depends on Sphinx version.

v6:
- YNL doc parser is now at tools/net/ynl/pyynl/lib/doc_generator.py;
- two patches got merged;
- added instructions to test docs with Sphinx 3.4.3 (minimal supported version);
- minor fixes.

v5:
- some patch reorg;
- netlink_yml_parser.py is now together with ynl tools;
- minor fixes.

v4:
- Renamed the YNL parser class;
- some minor patch cleanups and merges;
- added an extra patch to fix a insert_pattern/exclude_pattern logic when SPHINXDIRS is used.

v3:
- Two series got merged altogether:
- https://lore.kernel.org/linux-doc/[email protected]/T/#t
- https://lore.kernel.org/linux-doc/[email protected]

- Added an extra patch to update MAINTAINERS to point to YNL library
- Added a (somewhat unrelated) patch that remove warnings check when running "make cleandocs".

Mauro Carvalho Chehab (13):
docs: netlink: netlink-raw.rst: use :ref: instead of :doc:
tools: ynl_gen_rst.py: Split library from command line tool
docs: netlink: index.rst: add a netlink index file
tools: ynl_gen_rst.py: cleanup coding style
docs: sphinx: add a parser for yaml files for Netlink specs
docs: use parser_yaml extension to handle Netlink specs
docs: uapi: netlink: update netlink specs link
tools: ynl_gen_rst.py: drop support for generating index files
docs: netlink: remove obsolete .gitignore from unused directory
MAINTAINERS: add netlink_yml_parser.py to linux-doc
tools: netlink_yml_parser.py: add line numbers to parsed data
docs: parser_yaml.py: add support for line numbers from the parser
docs: parser_yaml.py: fix backward compatibility with old docutils

 Documentation/Makefile                        |  17 -
 Documentation/conf.py                         |  20 +-
 Documentation/netlink/specs/index.rst         |  13 +
 Documentation/networking/index.rst            |   2 +-
 .../networking/netlink_spec/.gitignore        |   1 -
 .../networking/netlink_spec/readme.txt        |   4 -
 Documentation/sphinx/parser_yaml.py           | 116 +++++
 Documentation/userspace-api/netlink/index.rst |   2 +-
 .../userspace-api/netlink/netlink-raw.rst     |   6 +-
 Documentation/userspace-api/netlink/specs.rst |   2 +-
 MAINTAINERS                                   |   1 +
 tools/net/ynl/pyynl/lib/__init__.py           |   2 +
 tools/net/ynl/pyynl/lib/doc_generator.py      | 398 ++++++++++++++++++
 tools/net/ynl/pyynl/ynl_gen_rst.py            | 384 +----------------
 14 files changed, 558 insertions(+), 410 deletions(-)
 create mode 100644 Documentation/netlink/specs/index.rst
 delete mode 100644 Documentation/networking/netlink_spec/.gitignore
 delete mode 100644 Documentation/networking/netlink_spec/readme.txt
 create mode 100755 Documentation/sphinx/parser_yaml.py
 create mode 100644 tools/net/ynl/pyynl/lib/doc_generator.py
Signature · 1 line
2.49.0
#4 lore raw

PATCH v8 3/13 docs: netlink: index.rst: add a netlink index file

Instead of generating the index file, use glob to automatically include all data from yaml.

---
 Documentation/netlink/specs/index.rst | 13 +++++++++++++
 1 file changed, 13 insertions(+)
 create mode 100644 Documentation/netlink/specs/index.rst
Documentation/netlink/specs/index.rst new file +13 -0
new file mode 100644
index 000000000000..7f7cf4a096f2
@@ -0,0 +1,13 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+.. _specs:
+
+=============================
+Netlink Family Specifications
+=============================
+
+.. toctree::
+   :maxdepth: 1
+   :glob:
+
+   *
Signature · 1 line
2.49.0
#21 lore raw

PATCH v8 12/13 docs: parser_yaml.py: add support for line numbers from the parser

In reply to Mauro Carvalho Chehab

Instead of printing line numbers from the temp converted ReST file, get them from the original source.

---
 Documentation/sphinx/parser_yaml.py      | 12 ++++++++++--
 tools/net/ynl/pyynl/lib/doc_generator.py | 16 ++++++++++++----
 2 files changed, 22 insertions(+), 6 deletions(-)
Documentation/sphinx/parser_yaml.py +10 -2
index fa2e6da17617..8288e2ff7c7c 100755
@@ -54,6 +54,8 @@ class YamlParser(Parser):
 
     netlink_parser = YnlDocGenerator()
 
+    re_lineno = re.compile(r"\.\. LINENO ([0-9]+)$")
+
     def rst_parse(self, inputstring, document, msg):
         """
         Receives a ReST content that was previously converted by the
@@ -66,8 +68,14 @@ class YamlParser(Parser):
 
         try:
             # Parse message with RSTParser
-            for i, line in enumerate(msg.split('\n')):
-                result.append(line, document.current_source, i)
+            lineoffset = 0;
+            for line in msg.split('\n'):
+                match = self.re_lineno.match(line)
+                if match:
+                    lineoffset = int(match.group(1))
+                    continue
+
+                result.append(line, document.current_source, lineoffset)
 
             rst_parser = RSTParser()
             rst_parser.parse('\n'.join(result), document)
tools/net/ynl/pyynl/lib/doc_generator.py +12 -4
index a9d8ab6f2639..7f4f98983cdf 100644
@@ -158,9 +158,11 @@ class YnlDocGenerator:
     def parse_do(self, do_dict: Dict[str, Any], level: int = 0) -> str:
         """Parse 'do' section and return a formatted string"""
         lines = []
+        if LINE_STR in do_dict:
+            lines.append(self.fmt.rst_lineno(do_dict[LINE_STR]))
+
         for key in do_dict.keys():
             if key == LINE_STR:
-                lines.append(self.fmt.rst_lineno(do_dict[key]))
                 continue
             lines.append(self.fmt.rst_paragraph(self.fmt.bold(key), level + 1))
             if key in ['request', 'reply']:
@@ -187,13 +189,15 @@ class YnlDocGenerator:
         lines = []
 
         for operation in operations:
+            if LINE_STR in operation:
+                lines.append(self.fmt.rst_lineno(operation[LINE_STR]))
+
             lines.append(self.fmt.rst_section(namespace, 'operation',
                                               operation["name"]))
             lines.append(self.fmt.rst_paragraph(operation["doc"]) + "\n")
 
             for key in operation.keys():
                 if key == LINE_STR:
-                    lines.append(self.fmt.rst_lineno(operation[key]))
                     continue
 
                 if key in preprocessed:
@@ -253,10 +257,12 @@ class YnlDocGenerator:
         lines = []
 
         for definition in defs:
+            if LINE_STR in definition:
+                lines.append(self.fmt.rst_lineno(definition[LINE_STR]))
+
             lines.append(self.fmt.rst_section(namespace, 'definition', definition["name"]))
             for k in definition.keys():
                 if k == LINE_STR:
-                    lines.append(self.fmt.rst_lineno(definition[k]))
                     continue
                 if k in preprocessed + ignored:
                     continue
@@ -284,6 +290,9 @@ class YnlDocGenerator:
             lines.append(self.fmt.rst_section(namespace, 'attribute-set',
                                               entry["name"]))
             for attr in entry["attributes"]:
+                if LINE_STR in attr:
+                    lines.append(self.fmt.rst_lineno(attr[LINE_STR]))
+
                 type_ = attr.get("type")
                 attr_line = attr["name"]
                 if type_:
@@ -294,7 +303,6 @@ class YnlDocGenerator:
 
                 for k in attr.keys():
                     if k == LINE_STR:
-                        lines.append(self.fmt.rst_lineno(attr[k]))
                         continue
                     if k in preprocessed + ignored:
                         continue
Signature · 1 line
2.49.0
#1 lore raw

PATCH v8 1/13 docs: netlink: netlink-raw.rst: use :ref: instead of :doc:

In reply to Mauro Carvalho Chehab

Currently, rt documents are referred with:

Documentation/userspace-api/netlink/netlink-raw.rst: :doc:rt-link<../../networking/netlink_spec/rt-link> Documentation/userspace-api/netlink/netlink-raw.rst: :doc:tc<../../networking/netlink_spec/tc> Documentation/userspace-api/netlink/netlink-raw.rst: :doc:tc<../../networking/netlink_spec/tc>

Having :doc: references with relative paths doesn't always work, as it may have troubles when O= is used. Also that's hard to maintain, and may break if we change the way rst files are generated from yaml. Better to use instead a reference for the netlink family.

So, replace them by Sphinx cross-reference tag that are created by ynl_gen_rst.py.

---
 Documentation/userspace-api/netlink/netlink-raw.rst | 6 +++---
 tools/net/ynl/pyynl/ynl_gen_rst.py                  | 5 +++--
 2 files changed, 6 insertions(+), 5 deletions(-)
Documentation/userspace-api/netlink/netlink-raw.rst +3 -3
index 31fc91020eb3..aae296c170c5 100644
@@ -62,8 +62,8 @@ Sub-messages
 ------------
 
 Several raw netlink families such as
-:doc:`rt-link<../../networking/netlink_spec/rt-link>` and
-:doc:`tc<../../networking/netlink_spec/tc>` use attribute nesting as an
+:ref:`rt-link<netlink-rt-link>` and
+:ref:`tc<netlink-tc>` use attribute nesting as an
 abstraction to carry module specific information.
 
 Conceptually it looks as follows::
@@ -162,7 +162,7 @@ then this is an error.
 Nested struct definitions
 -------------------------
 
-Many raw netlink families such as :doc:`tc<../../networking/netlink_spec/tc>`
+Many raw netlink families such as :ref:`tc<netlink-tc>`
 make use of nested struct definitions. The ``netlink-raw`` schema makes it
 possible to embed a struct within a struct definition using the ``struct``
 property. For example, the following struct definition embeds the
tools/net/ynl/pyynl/ynl_gen_rst.py +3 -2
index 0cb6348e28d3..7bfb8ceeeefc 100755
@@ -314,10 +314,11 @@ def parse_yaml(obj: Dict[str, Any]) -> str:
 
     # Main header
 
-    lines.append(rst_header())
-
     family = obj['name']
 
+    lines.append(rst_header())
+    lines.append(rst_label("netlink-" + family))
+
     title = f"Family ``{family}`` netlink specification"
     lines.append(rst_title(title))
     lines.append(rst_paragraph(".. contents:: :depth: 3\n"))
Signature · 1 line
2.49.0
#13 lore raw

PATCH v8 8/13 tools: ynl_gen_rst.py: drop support for generating index files

In reply to Mauro Carvalho Chehab

As we're now using an index file with a glob, there's no need to generate index files anymore.

---
 tools/net/ynl/pyynl/ynl_gen_rst.py | 28 ----------------------------
 1 file changed, 28 deletions(-)
tools/net/ynl/pyynl/ynl_gen_rst.py +0 -28
index 010315fad498..90ae19aac89d 100755
@@ -31,9 +31,6 @@ def parse_arguments() -> argparse.Namespace:
 
     # Index and input are mutually exclusive
     group = parser.add_mutually_exclusive_group()
-    group.add_argument(
-        "-x", "--index", action="store_true", help="Generate the index page"
-    )
     group.add_argument("-i", "--input", help="YAML file name")
 
     args = parser.parse_args()
@@ -63,27 +60,6 @@ def write_to_rstfile(content: str, filename: str) -> None:
         rst_file.write(content)
 
 
-def generate_main_index_rst(parser: YnlDocGenerator, output: str) -> None:
-    """Generate the `networking_spec/index` content and write to the file"""
-    lines = []
-
-    lines.append(parser.fmt.rst_header())
-    lines.append(parser.fmt.rst_label("specs"))
-    lines.append(parser.fmt.rst_title("Netlink Family Specifications"))
-    lines.append(parser.fmt.rst_toctree(1))
-
-    index_dir = os.path.dirname(output)
-    logging.debug("Looking for .rst files in %s", index_dir)
-    for filename in sorted(os.listdir(index_dir)):
-        base, ext = os.path.splitext(filename)
-        if filename == "index.rst" or ext not in [".rst", ".yaml"]:
-            continue
-        lines.append(f"   {base}\n")
-
-    logging.debug("Writing an index file at %s", output)
-    write_to_rstfile("".join(lines), output)
-
-
 def main() -> None:
     """Main function that reads the YAML files and generates the RST files"""
 
@@ -102,10 +78,6 @@ def main() -> None:
 
         write_to_rstfile(content, args.output)
 
-    if args.index:
-        # Generate the index RST file
-        generate_main_index_rst(parser, args.output)
-
 
 if __name__ == "__main__":
     main()
Signature · 1 line
2.49.0
reviewer Tested-by on v8 13/13
#23 lore raw

Re: [PATCH v8 13/13] docs: parser_yaml.py: fix backward compatibility with old docutils

In reply to Mauro Carvalho Chehab

Hi Mauro,

Quoted 4 lines · Mauro Carvalho Chehab

As reported by Akira, older docutils versions are not compatible with the way some Sphinx versions send tab_width. Add a code to address it.

Tested OK against debian:11's and almalinux:9's Sphinx 3.4.3, both of which have docutils 0.16 bundled.

opensuse/leap:15.6's Sphinx 4.2.0 has docutils 0.16 with it, but it is python 3.6 base and it does't work with the ynl integration. As opensuse/leap:15.6 provides Sphinx 7.2.6 (on top of python 3.11) as an alternative, obsoleting it should be acceptable.

Quoted 2 lines

Thanks, Akira

Quoted 19 lines
---
 Documentation/sphinx/parser_yaml.py | 4 ++++
 1 file changed, 4 insertions(+)
Documentation/sphinx/parser_yaml.py +4 -0
index 8288e2ff7c7c..1602b31f448e 100755
@@ -77,6 +77,10 @@ class YamlParser(Parser):
 
                 result.append(line, document.current_source, lineoffset)
 
+            # Fix backward compatibility with docutils < 0.17.1
+            if "tab_width" not in vars(document.settings):
+                document.settings.tab_width = 8
+
             rst_parser = RSTParser()
             rst_parser.parse('\n'.join(result), document)
 
#24 lore raw

Re: [PATCH v8 13/13] docs: parser_yaml.py: fix backward compatibility with old docutils

Hi Akira,

Em Fri, 27 Jun 2025 08:59:16 +0900
Akira Yokosawa <[email protected]> escreveu:

Quoted 8 lines

Hi Mauro,

Quoted 4 lines · Mauro Carvalho Chehab

As reported by Akira, older docutils versions are not compatible with the way some Sphinx versions send tab_width. Add a code to address it.

Quoted 7 lines

Tested OK against debian:11's and almalinux:9's Sphinx 3.4.3, both of which have docutils 0.16 bundled.

opensuse/leap:15.6's Sphinx 4.2.0 has docutils 0.16 with it, but it is python 3.6 base and it does't work with the ynl integration. As opensuse/leap:15.6 provides Sphinx 7.2.6 (on top of python 3.11) as an alternative, obsoleting it should be acceptable.

Thank you for the tests! At changes.rst we updated the minimum python requirement to:

	Python (optional)      3.9.x            python3 --version

So, I guess we can keep this way.

The 3.9 requirement reflects the needs of most scripts. Still, for doc build, the min requirement was to support f-string, so Python 3.6.

In this specific case, it is likely some minor incompatibility, as vermin tool thinks that 3.6 would be enough:

	$ vermin --no-tips --hidden --pessimistic -v tools/net/ynl/pyynl/ynl_gen_rst.py Documentation/sphinx/parser_yaml.py tools/net/ynl/pyynl/lib/*.py
	Detecting python files..
	Analyzing 6 files using 24 processes..
	2.3, 3.0     /new_devel/v4l/docs/Documentation/sphinx/parser_yaml.py
	~2, ~3       /new_devel/v4l/docs/tools/net/ynl/pyynl/lib/__init__.py
	!2, 3.6      /new_devel/v4l/docs/tools/net/ynl/pyynl/lib/doc_generator.py
	!2, 3.6      /new_devel/v4l/docs/tools/net/ynl/pyynl/lib/nlspec.py
	!2, 3.6      /new_devel/v4l/docs/tools/net/ynl/pyynl/lib/ynl.py
	!2, 3.4      /new_devel/v4l/docs/tools/net/ynl/pyynl/ynl_gen_rst.py
	Minimum required versions: 3.6
	Incompatible versions:     2

If the change is minimal, I don't mind having it fixed.

Anyway, IMO we need to add a checker at scripts/sphinx-pre-install to warn against too old Python versions.

Quoted 20 lines
Quoted 2 lines

Thanks, Akira

Quoted 12 lines
---
 Documentation/sphinx/parser_yaml.py | 4 ++++
 1 file changed, 4 insertions(+)
Documentation/sphinx/parser_yaml.py +0 -0
index 8288e2ff7c7c..1602b31f448e 100755
@@ -77,6 +77,10 @@ class YamlParser(Parser):
 
                 result.append(line, document.current_source, lineoffset)
 
Quoted 8 lines

Documentation/sphinx/parser_yaml.py class YamlParser(Parser): · line 86

Quoted 7 lines
Documentation/sphinx/parser_yaml.py +4 -0
+            # Fix backward compatibility with docutils < 0.17.1
+            if "tab_width" not in vars(document.settings):
+                document.settings.tab_width = 8
+
             rst_parser = RSTParser()
             rst_parser.parse('\n'.join(result), document)
 

Thanks,
Mauro

#25 lore raw

Re: [PATCH v8 13/13] docs: parser_yaml.py: fix backward compatibility with old docutils

[Dropping most CCs, +CC: Matthew]

Hi Mauro,

Quoted 4 lines · Mauro Carvalho Chehab

Hi Akira,

Em Fri, 27 Jun 2025 08:59:16 +0900
Akira Yokosawa <[email protected]> escreveu:

[...]

Quoted 9 lines
Quoted 5 lines

opensuse/leap:15.6's Sphinx 4.2.0 has docutils 0.16 with it, but it is python 3.6 base and it does't work with the ynl integration. As opensuse/leap:15.6 provides Sphinx 7.2.6 (on top of python 3.11) as an alternative, obsoleting it should be acceptable.

Thank you for the tests! At changes.rst we updated the minimum python requirement to:

Quoted 7 lines
	Python (optional)      3.9.x            python3 --version

So, I guess we can keep this way.

The 3.9 requirement reflects the needs of most scripts. Still, for doc build, the min requirement was to support f-string, so Python 3.6.

Sorry, I was barking up the wrong tree.

An example of messages from opensuse/leap:15.6's Sphinx looks like this:

WARNING: kernel-doc './scripts/kernel-doc.py -rst -enable-lineno -export ./fs/pstore/blk.c' processing failed with: AttributeError("'str' object has no attribute 'removesuffix'",)

The "removesuffix" is already there in scripts/lib/kdoc/kdoc_parser.py at current docs-next. It was added by commit 27ad33b6b349 ("kernel-doc: Fix symbol matching for dropped suffixes") submitted by Matthew.

But I have to ask, do we really want the compatibility with python <3.9 restored?

Thanks, Akira

maintainer
#8 lore raw

Re: [PATCH v8 05/13] docs: sphinx: add a parser for yaml files for Netlink specs

In reply to Mauro Carvalho Chehab
Quoted 11 lines · Mauro Carvalho Chehab

Add a simple sphinx.Parser to handle yaml files and add the the code to handle Netlink specs. All other yaml files are ignored.

The code was written in a way that parsing yaml for different subsystems and even for different parts of Netlink are easy.

All it takes to have a different parser is to add an import line similar to:

from netlink_yml_parser import YnlDocGenerator

This should be: from doc_generator import YnlDocGenerator

Quoted 33 lines

adding the corresponding parser somewhere at the extension:

netlink_parser = YnlDocGenerator()

And then add a logic inside parse() to handle different doc outputs, depending on the file location, similar to:

if "/netlink/specs/" in fname:
msg = self.netlink_parser.parse_yaml_file(fname)

---
 Documentation/sphinx/parser_yaml.py | 104 ++++++++++++++++++++++++++++
 1 file changed, 104 insertions(+)
 create mode 100755 Documentation/sphinx/parser_yaml.py
Documentation/sphinx/parser_yaml.py new file +11 -0
new file mode 100755
index 000000000000..585a7ec81ba0
@@ -0,0 +1,104 @@
+# SPDX-License-Identifier: GPL-2.0
+# Copyright 2025 Mauro Carvalho Chehab <[email protected]>
+
+"""
+Sphinx extension for processing YAML files
+"""
+
+import os
+import re
+import sys
+

Documentation/sphinx/parser_yaml.py line 21

Quoted 10 lines
Documentation/sphinx/parser_yaml.py new file +10 -0
+from pprint import pformat
+
+from docutils.parsers.rst import Parser as RSTParser
+from docutils.statemachine import ViewList
+
+from sphinx.util import logging
+from sphinx.parsers import Parser
+
+srctree = os.path.abspath(os.environ["srctree"])
+sys.path.insert(0, os.path.join(srctree, "tools/net/ynl/pyynl"))

So that it doesn't need to be changed in a later patch, this should be:

... "tools/net/ynl/pyynl/lib"

Documentation/sphinx/parser_yaml.py line 23

Quoted 2 lines
Documentation/sphinx/parser_yaml.py new file +2 -0
+
+from netlink_yml_parser import YnlDocGenerator        # pylint: disable=C0413

So that it doesn't need to be changed in a later patch, this should be:

from doc_generator ...

Quoted 80 lines
Documentation/sphinx/parser_yaml.py new file +80 -0
+logger = logging.getLogger(__name__)
+
+class YamlParser(Parser):
+    """
+    Kernel parser for YAML files.
+
+    This is a simple sphinx.Parser to handle yaml files inside the
+    Kernel tree that will be part of the built documentation.
+
+    The actual parser function is not contained here: the code was
+    written in a way that parsing yaml for different subsystems
+    can be done from a single dispatcher.
+
+    All it takes to have parse YAML patches is to have an import line:
+
+            from some_parser_code import NewYamlGenerator
+
+    To this module. Then add an instance of the parser with:
+
+            new_parser = NewYamlGenerator()
+
+    and add a logic inside parse() to handle it based on the path,
+    like this:
+
+            if "/foo" in fname:
+                msg = self.new_parser.parse_yaml_file(fname)
+    """
+
+    supported = ('yaml', )
+
+    netlink_parser = YnlDocGenerator()
+
+    def rst_parse(self, inputstring, document, msg):
+        """
+        Receives a ReST content that was previously converted by the
+        YAML parser, adding it to the document tree.
+        """
+
+        self.setup_parse(inputstring, document)
+
+        result = ViewList()
+
+        try:
+            # Parse message with RSTParser
+            for i, line in enumerate(msg.split('\n')):
+                result.append(line, document.current_source, i)
+
+            rst_parser = RSTParser()
+            rst_parser.parse('\n'.join(result), document)
+
+        except Exception as e:
+            document.reporter.error("YAML parsing error: %s" % pformat(e))
+
+        self.finish_parse()
+
+    # Overrides docutils.parsers.Parser. See sphinx.parsers.RSTParser
+    def parse(self, inputstring, document):
+        """Check if a YAML is meant to be parsed."""
+
+        fname = document.current_source
+
+        # Handle netlink yaml specs
+        if "/netlink/specs/" in fname:
+            msg = self.netlink_parser.parse_yaml_file(fname)
+            self.rst_parse(inputstring, document, msg)
+
+        # All other yaml files are ignored
+
+def setup(app):
+    """Setup function for the Sphinx extension."""
+
+    # Add YAML parser
+    app.add_source_parser(YamlParser)
+    app.add_source_suffix('.yaml', 'yaml')
+
+    return {
+        'version': '1.0',
+        'parallel_read_safe': True,
+        'parallel_write_safe': True,
+    }
maintainer
#10 lore raw

Re: [PATCH v8 06/13] docs: use parser_yaml extension to handle Netlink specs

In reply to Mauro Carvalho Chehab
Quoted 10 lines · Mauro Carvalho Chehab

Instead of manually calling ynl_gen_rst.py, use a Sphinx extension. This way, no .rst files would be written to the Kernel source directories.

We are using here a toctree with :glob: property. This way, there is no need to touch the netlink/specs/index.rst file every time a new Netlink spec is added/renamed/removed.

This patch doesn't currently merge in the net-next tree because it depends on a series in docs-next.

Documentation/sphinx/parser_yaml.py from sphinx.util import logging · line 23

Quoted 13 lines
Documentation/sphinx/parser_yaml.py +2 -2
index 585a7ec81ba0..fa2e6da17617 100755
@@ -18,9 +18,9 @@ from sphinx.util import logging
 from sphinx.parsers import Parser
 
 srctree = os.path.abspath(os.environ["srctree"])
-sys.path.insert(0, os.path.join(srctree, "tools/net/ynl/pyynl"))
+sys.path.insert(0, os.path.join(srctree, "tools/net/ynl/pyynl/lib"))
 
-from netlink_yml_parser import YnlDocGenerator        # pylint: disable=C0413
+from doc_generator import YnlDocGenerator        # pylint: disable=C0413

Please fix up patch 5 so that this diff can be dropped.

maintainer Reviewed-by on v8 2/13
#3 lore raw

Re: [PATCH v8 02/13] tools: ynl_gen_rst.py: Split library from command line tool

In reply to Mauro Carvalho Chehab
Quoted 7 lines · Mauro Carvalho Chehab

As we'll be using the Netlink specs parser inside a Sphinx extension, move the library part from the command line parser.

While here, change the code which generates an index file to parse inputs from both .rst and .yaml extensions. With that, the tool can easily be tested with:

Quoted 6 lines

tools/net/ynl/pyynl/ynl_gen_rst.py -x -o Documentation/netlink/specs/foo.rst

Without needing to first generate a temp directory with the rst files.

maintainer
#6 lore raw

Re: [PATCH v8 04/13] tools: ynl_gen_rst.py: cleanup coding style

In reply to Mauro Carvalho Chehab

tools/net/ynl/pyynl/lib/doc_generator.py class RstFormatters: · line 103

Quoted 9 lines · Mauro Carvalho Chehab

@staticmethod
def rst_ref(namespace: str, prefix: str, name: str) -> str:
"""Add a hyperlink to the document"""

tools/net/ynl/pyynl/lib/doc_generator.py +1 -1
@@ -119,10 +100,9 @@ class RstFormatters:
                     'nested-attributes': 'attribute-set',
                     'struct': 'definition'}
         if prefix in mappings:
-            prefix = mappings[prefix]
+            prefix = mappings.get(prefix, "")

This gives me a sad face because fixing the erroneous pylint warning makes the code look worse. I'd prefer to either suppress the warning or to change this:

if prefix in mappings:
prefix = mappings[prefix]

to this:

prefix = mappings.get(prefix, prefix)

But IMHO the intent of the original is clearer.

maintainer Reviewed-by on v8 10/13
#17 lore raw

Re: [PATCH v8 10/13] MAINTAINERS: add netlink_yml_parser.py to linux-doc

In reply to Mauro Carvalho Chehab
Quoted 9 lines · Mauro Carvalho Chehab

The documentation build depends on the parsing code at ynl_gen_rst.py. Ensure that changes to it will be c/c to linux-doc ML and maintainers by adding an entry for it. This way, if a change there would affect the build, or the minimal version required for Python, doc developers may know in advance.

maintainer
#19 lore raw

Re: [PATCH v8 11/13] tools: netlink_yml_parser.py: add line numbers to parsed data

In reply to Mauro Carvalho Chehab
Quoted 17 lines · Mauro Carvalho Chehab

When something goes wrong, we want Sphinx error to point to the right line number from the original source, not from the processed ReST data.

---
 tools/net/ynl/pyynl/lib/doc_generator.py | 34 ++++++++++++++++++++++--
 1 file changed, 32 insertions(+), 2 deletions(-)
tools/net/ynl/pyynl/lib/doc_generator.py +0 -0
index 866551726723..a9d8ab6f2639 100644
@@ -20,6 +20,16 @@
 from typing import Any, Dict, List
 import yaml
 

tools/net/ynl/pyynl/lib/doc_generator.py line 32

Quoted 10 lines
tools/net/ynl/pyynl/lib/doc_generator.py +10 -0
+LINE_STR = '__lineno__'
+
+class NumberedSafeLoader(yaml.SafeLoader):
+    """Override the SafeLoader class to add line number to parsed data"""
+
+    def construct_mapping(self, node):
+        mapping = super().construct_mapping(node)
+        mapping[LINE_STR] = node.start_mark.line
+
+        return mapping

pylint gives these 2 warnings:

tools/net/ynl/pyynl/lib/doc_generator.py:25:0: R0901: Too many ancestors (9/7) (too-many-ancestors)
tools/net/ynl/pyynl/lib/doc_generator.py:28:4: W0221: Number of parameters was 3 in 'SafeConstructor.construct_mapping' and is now 2 in overriding 'NumberedSafeLoader.construct_mapping' method (arguments-differ)

#26 lore raw

Re: [PATCH v8 13/13] docs: parser_yaml.py: fix backward compatibility with old docutils

In reply to Akira Yokosawa

Em Fri, 27 Jun 2025 17:37:16 +0900
Akira Yokosawa <[email protected]> escreveu:

Quoted 32 lines

[Dropping most CCs, +CC: Matthew]

Hi Mauro,

Quoted 4 lines · Mauro Carvalho Chehab

Hi Akira,

Em Fri, 27 Jun 2025 08:59:16 +0900
Akira Yokosawa <[email protected]> escreveu:

[...]

Quoted 9 lines
Quoted 5 lines

opensuse/leap:15.6's Sphinx 4.2.0 has docutils 0.16 with it, but it is python 3.6 base and it does't work with the ynl integration. As opensuse/leap:15.6 provides Sphinx 7.2.6 (on top of python 3.11) as an alternative, obsoleting it should be acceptable.

Thank you for the tests! At changes.rst we updated the minimum python requirement to:

Quoted 7 lines
	Python (optional)      3.9.x            python3 --version

So, I guess we can keep this way.

The 3.9 requirement reflects the needs of most scripts. Still, for doc build, the min requirement was to support f-string, so Python 3.6.

Sorry, I was barking up the wrong tree.

An example of messages from opensuse/leap:15.6's Sphinx looks like this:

Quoted 8 lines

WARNING: kernel-doc './scripts/kernel-doc.py -rst -enable-lineno -export ./fs/pstore/blk.c' processing failed with: AttributeError("'str' object has no attribute 'removesuffix'",)

The "removesuffix" is already there in scripts/lib/kdoc/kdoc_parser.py at current docs-next. It was added by commit 27ad33b6b349 ("kernel-doc: Fix symbol matching for dropped suffixes") submitted by Matthew.

But I have to ask, do we really want the compatibility with python <3.9 restored?

I actually wrote a patch addressing that. Yet, looking at the results from the tests I did for the sphinx-pre-install script, what we have is:

PASSED 1 - OS: AlmaLinux release 9.6 (Sage Margay), Python: 3.9.21, hostname: almalinux-test PASSED 1 - OS: Arch Linux, Python: 3.13.5
PASSED 1 - OS: CentOS Stream release 9, Python: 3.9.23, hostname: centos-test
PASSED 1 - OS: Debian GNU/Linux 12, Python: 3.11.2, hostname: debian-test
PASSED 1 - OS: Devuan GNU/Linux 5, Python: 3.11.2, hostname: devuan-test
PASSED 1 - OS: Fedora release 42 (Adams), Python: 3.13.5
PASSED 1 - OS: Gentoo Base System release 2.17, Python: 3.13.3
PASSED 1 - OS: Kali GNU/Linux 2025.2, Python: 3.13.3, hostname: kali-test
PASSED 1 - OS: Mageia 9, Python: 3.10.11, hostname: mageia-test
PASSED 1 - OS: Linux Mint 22, Python: 3.10.12, hostname: mint-test
PASSED 1 - OS: openEuler release 25.03, Python: 3.11.11, hostname: openeuler-test
PASSED 1 - OS: OpenMandriva Lx 4.3, Python: 3.9.8, hostname: openmandriva-test
PASSED 1 - OS: openSUSE Tumbleweed, Python: 3.13.5, hostname: opensuse-test
PASSED 1 - OS: Rocky Linux release 8.9 (Green Obsidian), Python: 3.6.8, hostname: rockylinux8-test PASSED 3 - Sphinx on venv: Sphinx Sphinx 7.4.7, Docutils 0.21.2, Python3.9.20
PASSED 1 - OS: Rocky Linux release 9.6 (Blue Onyx), Python: 3.9.21, hostname: rockylinux-test PASSED 1 - OS: Springdale Open Enterprise Linux release 9.2 (Parma), Python: 3.9.16, hostname: springdalelinux-test PASSED 1 - OS: Ubuntu 24.04.2 LTS, Python: 3.12.3, hostname: ubuntu-lts-test
PASSED 1 - OS: Ubuntu 25.04, Python: 3.13.3, hostname: ubuntu-test

This is after running the script a second time after installing either python 311 or python39 on openSUSE and OpenMandriva. On both, it is possible to install distro-provided packages with Python 3.9 or 3.11.

The only exception for RHEL8-based distros. On those, the installed version is 3.6.x, which doesn't have f-strings. So, it won't work anyway. Yet, RHEL8 powertools/epel repositories have enough to install python 3.9 and Sphinx via venv.

With that in mind, I don't see any reason why restoring backward-compatibility with 3.7.

But, someone things otherwise, the patch addressing it is enclosed.

---

[PATCH] scripts: kdoc: make it backward-compatible with Python 3.7

There was a change at kdoc that ended breaking compatibility with Python 3.7: str.removesuffix() was introduced on version 3.9.

Restore backward compatibility.

Fixes 27ad33b6b349 ("kernel-doc: Fix symbol matching for dropped suffixes")
scripts/lib/kdoc/kdoc_parser.py +3 -1
index 831f061f61b8..6273141033a8 100644
@@ -1214,7 +1214,9 @@ class KernelDoc:
         # Found an export, trim out any special suffixes
         #
         for suffix in suffixes:
-            symbol = symbol.removesuffix(suffix)
+            # Be backward compatible with Python < 3.9
+            if symbol.endswith(suffix):
+                symbol = symbol[:-len(suffix)]
         function_set.add(symbol)
         return True
 
#11 lore raw

Re: [PATCH v8 06/13] docs: use parser_yaml extension to handle Netlink specs

In reply to Donald Hunter

Em Fri, 27 Jun 2025 11:28:40 +0100
Donald Hunter <[email protected]> escreveu:

Quoted 10 lines
Quoted 8 lines · Mauro Carvalho Chehab

Instead of manually calling ynl_gen_rst.py, use a Sphinx extension. This way, no .rst files would be written to the Kernel source directories.

We are using here a toctree with :glob: property. This way, there is no need to touch the netlink/specs/index.rst file every time a new Netlink spec is added/renamed/removed.

Quoted 5 lines
Quoted 2 lines

This patch doesn't currently merge in the net-next tree because it depends on a series in docs-next.

True. It has to either be applied on docs-next or you need to merge from it if you want to apply on your tree.

This patch depends at the changes there to properly address include_pattern/exclude_pattern.

Regards,
Mauro

#20 lore raw

Re: [PATCH v8 11/13] tools: netlink_yml_parser.py: add line numbers to parsed data

In reply to Donald Hunter

Em Fri, 27 Jun 2025 12:03:07 +0100
Donald Hunter <[email protected]> escreveu:

Quoted 32 lines
Quoted 17 lines · Mauro Carvalho Chehab

When something goes wrong, we want Sphinx error to point to the right line number from the original source, not from the processed ReST data.

---
 tools/net/ynl/pyynl/lib/doc_generator.py | 34 ++++++++++++++++++++++--
 1 file changed, 32 insertions(+), 2 deletions(-)
tools/net/ynl/pyynl/lib/doc_generator.py +0 -0
index 866551726723..a9d8ab6f2639 100644
@@ -20,6 +20,16 @@
 from typing import Any, Dict, List
 import yaml
 

tools/net/ynl/pyynl/lib/doc_generator.py line 32

Quoted 10 lines
tools/net/ynl/pyynl/lib/doc_generator.py +10 -0
+LINE_STR = '__lineno__'
+
+class NumberedSafeLoader(yaml.SafeLoader):
+    """Override the SafeLoader class to add line number to parsed data"""
+
+    def construct_mapping(self, node):
+        mapping = super().construct_mapping(node)
+        mapping[LINE_STR] = node.start_mark.line
+
+        return mapping  

pylint gives these 2 warnings:

Quoted 1 line

tools/net/ynl/pyynl/lib/doc_generator.py:25:0: R0901: Too many ancestors (9/7) (too-many-ancestors)

I'm yet to find any pylint Rxxx warning that I didn't have to disable ;-)

This particular one is useless for us, as it basically tells that PyYAML has a big class hierarchy.

Quoted 1 line

tools/net/ynl/pyynl/lib/doc_generator.py:28:4: W0221: Number of parameters was 3 in 'SafeConstructor.construct_mapping' and is now 2 in overriding 'NumberedSafeLoader.construct_mapping' method (arguments-differ)

I'll fix this one to prevent potential future issues.

Changing the code to:

-class NumberedSafeLoader(yaml.SafeLoader):
+class NumberedSafeLoader(yaml.SafeLoader): # pylint: disable=R0901
"""Override the SafeLoader class to add line number to parsed data"""

- def construct_mapping(self, node):
- mapping = super().construct_mapping(node)
+ def construct_mapping(self, node, *args, **kwargs):
+ mapping = super().construct_mapping(node, *args, **kwargs)
mapping[LINE_STR] = node.start_mark.line

return mapping

This should hopefully be future-proof.

Regards,
Mauro