### Example Usage of Exported Function Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-tests.html Demonstrates how to call the `user_function` in an example context. ```c x = user_function(22); ``` -------------------------------- ### Rendered Kernel-Doc Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-directive.html How the kernel-doc documentation for a C function is rendered in reST, including its description, parameters, and example. ```text kernel-doc option :symbols: ### user_function int user_function(int a, ...) function that can only be called in user context Parameters: * **a** (int) – some argument * **ellipsis** (ellipsis) – ellipsis operator #### Description This function makes no sense, it’s only a kernel-doc demonstration. #### Example ``` x = user_function(22); ``` #### Return Returns first argument ``` -------------------------------- ### Comprehensive Kernel-Doc Example with Special Sections Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-syntax.html Illustrates a complete kernel-doc comment including context, example usage, and return value descriptions, suitable for kernel functions. ```c /** * user_function() - function that can only be called in user context * @a: some argument * @...: ellipsis operator * * This function makes no sense, it's only a kernel-doc demonstration. * * Example: * x = user_function(22); * * Return: * Returns first argument */ int user_function(int a, ...) { return a; } ``` -------------------------------- ### Install LinuxDoc from PyPI Source: https://return42.github.io/linuxdoc/_sources/install.rst.txt Use this command to install or update the LinuxDoc package from the Python Package Index. ```bash python -m pip install -U linuxdoc ``` -------------------------------- ### C Function with Kernel-Doc Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-directive.html Example of a C function documented using kernel-doc syntax, including parameters, description, example usage, and return value. ```c /** * user_function() - function that can only be called in user context * @a: some argument * @...: ellipsis operator * * This function makes no sense, it's only a kernel-doc demonstration. * * Example: * x = user_function(22); * * Return: * Returns first argument */ int user_function(int a, ...) { return a; } ``` -------------------------------- ### Minimal Kernel-Doc Function Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-syntax.html A basic example of a kernel-doc comment for a function with no parameters or detailed description. ```c /** * my_function */ ``` -------------------------------- ### C Function Call Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble.html A simple C function call as an example within kernel-doc. ```c user_function(22); ``` -------------------------------- ### Snippet Example: Hello World Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kernel-doc-directive.rst.txt A basic C code snippet demonstrating the 'hello-world' snippet marker used by kernel-doc. ```c /* parse-SNIP: hello-world */ #include int main() { printf("Hello World\n"); return 0; } /* parse-SNAP: */ ``` -------------------------------- ### C Function Example: user_sum Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble-debug.html Illustrates how to call the `user_sum` function with specific integer arguments. Used for documentation examples. ```c x = user_sum(1, 2); ``` -------------------------------- ### C Function Example: user_function Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble-debug.html Provides an example of calling the `user_function`. This snippet is for demonstrating usage within documentation. ```c x = user_function(22); ``` -------------------------------- ### Install Bleeding Edge LinuxDoc from Git Source: https://return42.github.io/linuxdoc/_sources/install.rst.txt Install the latest development version of LinuxDoc into your user site-packages directory from its GitHub repository. ```bash python -m pip install -U --user git+http://github.com/return42/linuxdoc.git ``` -------------------------------- ### Vintage Kernel-Doc Comment Example Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/vintage-kernel-doc-mode.rst.txt An example of a comment in the vintage kernel-doc mode, illustrating how it might appear in source code. ```text * In contrast to the other drm_get_*_name functions this one here returns a * const pointer and hence is threadsafe. ``` -------------------------------- ### Basic C Main Function Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/reST-kernel-doc-mode.html A simple C main function demonstrating basic structure and standard output. ```c int main() { printf("Hello World\n"); return 0; } ``` -------------------------------- ### SYSCALL Macro Example Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kernel-doc-tests.rst.txt Shows how to document symbols related to the SYSCALL macro, specifically targeting 'sys_tgkill'. ```rst .. kernel-doc:: ./all-in-a-tumble.c :symbols: sys_tgkill ``` -------------------------------- ### C function rst_mode Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble-debug.html A simple C 'main' function demonstrating basic printf usage, intended as an example within documentation. ```c int main() { printf("Hello World\n"); return 0; } ``` -------------------------------- ### Rendered Code Snippet Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-directive.html This is the rendered output of the 'hello-world' code snippet, showing line numbers as specified by the `:linenos:` option in the `kernel-doc` directive. ```text 1#include 2int main() { 3 printf("Hello World\n"); 4 return 0; 5} ``` -------------------------------- ### Extracting Code Snippets with kernel-doc Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-directive.html This example shows how to extract a specific code snippet labeled 'hello-world' from a C source file using the `kernel-doc` directive with the `:snippets:` option. The `:language:` and `:linenos:` options are also demonstrated. ```c /* parse-SNIP: hello-world */ #include int main() { printf("Hello World\n"); return 0; } /* parse-SNAP: */ ``` ```rst .. kernel-doc:: ./all-in-a-tumble.c :snippets: hello-world :language: c :linenos: ``` -------------------------------- ### Missing Exports Example Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kernel-doc-tests.rst.txt Demonstrates handling of missing exports where the export glob pattern matches no files or no exports are found. ```rst .. kernel-doc:: ./all-in-a-tumble.c :export: ./match_files_without_exports* ``` -------------------------------- ### Python Sphinx Extension Setup Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/kfigure.html Sets up the kfigure Sphinx extension, registering directives for kernel-image, kernel-figure, and kernel-render. It also connects to the 'builder-inited' event to check for necessary tools. ```python # setup conversion tools and sphinx extension # ------------------------------------------- # Graphviz's dot(1) support dot_cmd = None # ImageMagick' convert(1) support convert_cmd = None def setup(app): # check toolchain first app.connect("builder-inited", setupTools) # image handling app.add_directive("kernel-image", KernelImage) app.add_node( kernel_image, html=(visit_kernel_image, pass_handle), latex=(visit_kernel_image, pass_handle), texinfo=(visit_kernel_image, pass_handle), text=(visit_kernel_image, pass_handle), man=(visit_kernel_image, pass_handle), ) # figure handling app.add_directive("kernel-figure", KernelFigure) app.add_node( kernel_figure, html=(visit_kernel_figure, pass_handle), latex=(visit_kernel_figure, pass_handle), texinfo=(visit_kernel_figure, pass_handle), text=(visit_kernel_figure, pass_handle), man=(visit_kernel_figure, pass_handle), ) # render handling app.add_directive("kernel-render", KernelRender) app.add_node( kernel_render, html=(visit_kernel_render, pass_handle), latex=(visit_kernel_render, pass_handle), texinfo=(visit_kernel_render, pass_handle), text=(visit_kernel_render, pass_handle), man=(visit_kernel_render, pass_handle), ) app.connect("doctree-read", add_kernel_figure_to_std_domain) return dict(version=__version__, parallel_read_safe=True, parallel_write_safe=True) [docs] def setupTools(app): # pylint: disable=unused-argument """ Check available build tools and log some *verbose* messages. This function is called once, when the builder is initiated. """ global dot_cmd, convert_cmd # pylint: disable=global-statement # pylint: disable=deprecated-method app_log.info("kfigure: check installed tools ...") dot_cmd = which("dot") convert_cmd = which("convert") ``` -------------------------------- ### Gather exported symbols using :export:, :exp-method:, :exp-ids: Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kernel-doc-tests.rst.txt This example shows how to gather function documentation using :export:, :exp-method:, and :exp-ids: options. It targets functions exported from a C file and present in a header file. ```rst .. kernel-doc:: ./all-in-a-tumble.c :snippets: user_sum-c ``` -------------------------------- ### Flat-Table Directive Example Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/table-markup.rst.txt Demonstrates the use of the `flat-table` directive with options for header rows, stub columns, column widths, CSS classes, and table names. Includes examples of row and column spanning, comments, and automatic cell spanning. ```rst .. flat-table:: flat-table example :header-rows: 2 :stub-columns: 1 :widths: 1 1 1 1 2 :class: my-class :name: my-flat-table * - :rspan:`1` head / stub - :cspan:`3` head 1.1-4 * - head 2.1 - head 2.2 - head 2.3 - head 2.4 * .. row body 1 / this is a comment - row 1 - :rspan:`2` cell 1-3.1 - cell 1.2 - cell 1.3 - cell 1.4 * .. Comments and targets are allowed on *table-row* stage. .. _`row body 2`: - row 2 - cell 2.2 - :rspan:`1` :cspan:`1` cell 2.3 with a span over * col 3-4 & * row 2-3 * - row 3 - cell 3.2 * - row 4 - cell 4.1 - cell 4.2 - cell 4.3 - cell 4.4 * - row 5 - cell 5.1 with automatic span to rigth end * - row 6 - cell 6.1 - .. ``` -------------------------------- ### Highlighted C Code Block Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/reST-kernel-doc-mode.html Shows a C code block with syntax highlighting enabled, intended for inclusion in documentation. ```c // Hello World program #include int main() { printf("Hello World"); } ``` -------------------------------- ### Example of Internal Function Documentation (Macro) Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-tests.html Shows the generated documentation for an internal function when using macro exports. ```rst int foo(int a, ...) function that can only be called in user context Parameters: * **a** (int) – some argument * **ellipsis** (ellipsis) – ellipsis operator ##### Description This function makes no sense, it’s only a kernel-doc demonstration. ##### Example ``` x = foo(42); ``` ##### Return Returns first argument ``` -------------------------------- ### Example of Internal Function Documentation (Macro) Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-tests.html Shows the generated documentation for an internal function when using macro exports. ```rst int bar(int a, ...) function that can only be called in user context Parameters: * **a** (int) – some argument * **ellipsis** (ellipsis) – ellipsis operator ##### Description This function makes no sense, it’s only a kernel-doc demonstration. ##### Example ``` x = bar(42); ``` ##### Return Returns first argument ``` -------------------------------- ### Basic C Main Function Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble.html A standard C main function demonstrating basic program structure and output. This is a common entry point for C programs. ```c int main() { printf("Hello World\n"); return 0; } ``` -------------------------------- ### Example of Internal Function Documentation (Attribute) Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-tests.html Displays the documentation for an internal function when using attribute exports. ```rst int internal_function(void) the answer Parameters: * **void** – no arguments ##### Context !sanity() ##### Return The answer to the ultimate question of life, the universe and everything. ``` -------------------------------- ### Example Usage of Exported Sum Function Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-tests.html Demonstrates how to call the `user_sum` function with two integer arguments. ```c x = user_sum(1, 2); ``` -------------------------------- ### Basic List Table Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/table-markup.html Demonstrates the basic structure of a `list-table` directive with header and stub columns. Use this for simple tables where colspan/rowspan are not required. ```rst .. list-table:: list-table example :header-rows: 1 :stub-columns: 1 :class: my-class :name: my-list-table * - .. - head col 1 - head col 2 * - stub col row 1 - column - column * - stub col row 2 - column - column * - stub col row 3 - column - column ``` -------------------------------- ### C Function Call Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble-debug.html Shows a simple C function call, typically used within documentation to illustrate function usage. ```c user_function(22); ``` -------------------------------- ### reST Section Structure Example Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/reST-kernel-doc-mode.rst.txt Demonstrates how reST handles line breaks after colons for section titles, rendering 'prints out: hello world' on a single line. ```rst prints out: hello world ``` -------------------------------- ### Write Section with Content Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/kernel_doc.html Writes a section including header and content, handling special formatting for 'example' sections and general content highlighting. ```python def write_section(self, header, content, sec_level=2, ID=None): if not self.options.no_header: if ID: self.write_anchor(ID) self.write_header(header, sec_level=sec_level) if header.lower() == "example": self.write("\n.. code-block:: c\n\n") for l in textwrap.dedent(content).split("\n"): if not l.strip(): self.write("\n") else: self.write(self.INDENT, l, "\n") else: content = self.format_block(content) content = self.highlight(content) self.write("\n" + content) self.write("\n") ``` -------------------------------- ### Rendered Example of :symbols: Directive Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kernel-doc-directive.rst.txt Demonstrates how the :symbols: directive renders documentation for a function, including cross-referencing capabilities. ```rst .. kernel-doc:: ./all-in-a-tumble.c :symbols: user_function :module: foo ``` -------------------------------- ### Python: Handling Blank Lines in Documentation Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/kernel_doc.html This snippet demonstrates how to detect blank lines following a '@parameter' tag to signify the start of a description section in kernel documentation. ```python self.debug( "blank lines after @parameter --> start 'Description' section" ) self.dump_section(self.ctx.section, self.ctx.contents) self.ctx.last_offset = self.ctx.line_no self.ctx.section = self.section_descr self.ctx.contents = "" self.in_doc_sect = True self.debug( "FLAGs: in_doc_sect=%(s)s / in_purpose=%(p)s", s=self.in_doc_sect, p=self.in_purpose, ) else: self.ctx.contents += "\n" ``` -------------------------------- ### Sphinx build command with output directory Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/man-pages.rst.txt This command builds man pages using the `kernel-doc-man` builder and places them in the specified output directory. It also includes an example of the build output messages. ```bash sphinx-build -b kernel-doc-man docs dist/docs/man building [kernel-doc-man]: all manpages ... scan master tree for kernel-doc man-pages ... writing man pages ... user_function.2 internal_function.2 ... ``` -------------------------------- ### reST Sectioning Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/reST-kernel-doc-mode.html Demonstrates how reST handles section titles with colons, ensuring expected rendering and avoiding unintended section creation. ```text prints out: hello world ``` -------------------------------- ### Insert SVG Figure using kernel-figure Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kfigure.rst.txt This example demonstrates how to insert an SVG image using the kernel-figure directive. Ensure the necessary build tools like ImageMagick and Graphviz are installed for optimal rendering. ```rst .. _svg_image_example: .. kernel-figure:: svg_image.svg :alt: simple SVG image SVG figure example ``` -------------------------------- ### linuxdoc.kfigure.setupTools Source: https://return42.github.io/linuxdoc/src/linuxdoc.kfigure.html Checks for available build tools and logs verbose messages. This function is intended to be called once when the builder is initiated. ```APIDOC ## setupTools(app) ### Description Checks available build tools and logs verbose messages. Called once when the builder is initiated. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ERROR HANDLING: None ``` -------------------------------- ### KernelDocMan Builder Setup Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/manKernelDoc.html This Python code sets up the kernel-doc-man builder for Sphinx. It adds the custom builder and directive, and defines a custom node type for man pages. ```python #!/usr/bin/env python3 # SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-docstring, invalid-name, unnecessary-pass """ kernel-doc-man ~~~~~~~~~~~~~~ Implementation of the ``kernel-doc-man`` builder. User documentation see :ref:`man-pages`. """ # ============================================================================== # imports # ============================================================================== import collections import re from os import path from docutils import nodes from docutils.frontend import OptionParser from docutils.io import FileOutput from docutils.parsers.rst import Directive from docutils.transforms import Transform from docutils.utils import new_document from sphinx import addnodes from sphinx.builders.manpage import ManualPageBuilder from sphinx.util import logging from sphinx.util.console import bold, darkgreen # pylint: disable=no-name-in-module from sphinx.util.nodes import inline_all_toctrees from sphinx.writers.manpage import ManualPageWriter from .kernel_doc import Container logger = logging.getLogger(__name__) # ============================================================================== # common globals # ============================================================================== DEFAULT_MAN_SECT = 9 # The version numbering follows numbering of the specification # (Documentation/books/kernel-doc-HOWTO). __version__ = "1.0" # ============================================================================== def setup(app): # ============================================================================== app.add_builder(KernelDocManBuilder) app.add_directive("kernel-doc-man", KernelDocMan) app.add_node( kernel_doc_man, html=(skip_kernel_doc_man, None), latex=(skip_kernel_doc_man, None), texinfo=(skip_kernel_doc_man, None), text=(skip_kernel_doc_man, None), man=(skip_kernel_doc_man, None), ) return dict(version=__version__, parallel_read_safe=True, parallel_write_safe=True) # ============================================================================== ``` -------------------------------- ### C Function with reST and Kernel-Doc Markup Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble-src.html A dummy C function demonstrating the use of reStructuredText (reST) and kernel-doc markup within comments. This includes parameter descriptions, cross-referencing, and highlighting syntax. ```c /* * rst_mode - dummy to demonstrate reST & kernel-doc markup in comments * @a: first argument * @b: second argument * Context: :c:func:`in_gizmo_mode`. * * Long description. This function has two integer arguments. The first is * ``parameter_a`` and the second is ``parameter_b``. * * As long as the reST / sphinx-doc toolchain uses `intersphinx * `__ you can refer * definitions *outside* like :c:type:`struct media_device `. If * the description of ``media_device`` struct is found in any of the intersphinx * locations, a hyperref to this target is generated a build time. * * Example: * int main() { * printf("Hello World\n"); * return 0; * } * * Return: Sum of ``parameter_a`` and the second is ``parameter_b``. * * highlighting: * The highlight pattern, are non regular reST markups. They are only available * within kernel-doc comments, helping C developers to write short and compact * documentation. * * - user_function() : function * - @a : name of a parameter * - &struct my_struct : name of a structure (including the word struct) * - &union my_union : name of a union * - &my_struct->a or &my_struct.b - member of a struct or union. * - &enum my_enum : name of a enum * - &typedef my_typedef : name of a typedef * - %CONST : name of a constant. * - $ENVVAR : environmental variable * * The kernel-doc parser translates the pattern above to the corresponding reST */ ``` -------------------------------- ### C Enum Definition Example Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/kernel_doc.html Example of a C enum definition as it would be formatted for kernel documentation. ```c enum my_enum { ENUM_VAL_1, ENUM_VAL_2, ENUM_VAL_3 }; ``` -------------------------------- ### Kernel-Doc for Functions (with Description and Parameters) Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kernel-doc-syntax.rst.txt Demonstrates a kernel-doc comment for a function including a short description, a parameter description, and a detailed explanation. ```c /** * my_function - does my stuff * @my_arg: its mine damnit * * Does my stuff explained. */ ``` -------------------------------- ### Configure Documentation Generation Options Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/rstKernelDoc.html Sets up options for kernel documentation parsing based on provided flags. It handles selecting specific documentation sections, exporting symbols, and managing include paths. ```python if ( "doc" not in self.options and "export" not in self.options and "internal" not in self.options and "functions" not in self.options and "snippets" not in self.options ): # if no explicit content is selected, then print all, including all # DOC sections opts.use_all_docs = True if "doc" in self.options: opts.no_header = bool("no-header" in self.options) opts.use_names.append(self.options.get("doc")) if "export" in self.options: kerneldoc.Parser.gather_context(kerneldoc.readFile(opts.fname), ctx, opts) exp_files.extend( (self.options.get("export") or "").replace(",", " ").split() ) opts.error_missing = True elif "internal" in self.options: # gather exported symbols and add them to the ignore-list of names kerneldoc.Parser.gather_context(kerneldoc.readFile(opts.fname), ctx, opts) exp_files.extend( (self.options.get("internal") or "").replace(",", " ").split() ) if "functions" in self.options: opts.error_missing = True opts.use_names.extend(self.options["functions"].replace(",", " ").split()) for pattern in exp_files: if pattern[0] == "/": pattern = pattern[1:] pattern = path.join(opts.src_tree, pattern) if not glob.has_magic(pattern) and not path.lexists(pattern): # if pattern is a filename (is not a glob pattern) and this file # does not exists, an error is raised. raise FaultyOption("file (pattern) not found: %s" % pattern) for fname in glob.glob(pattern): self.env.note_dependency(path.abspath(fname)) kerneldoc.Parser.gather_context(kerneldoc.readFile(fname), ctx, opts) if "export" in self.options: if not ctx.exported_symbols: raise FaultyOption( "using option :export: but there are no exported symbols" ) opts.use_names.extend(ctx.exported_symbols) if "internal" in self.options: opts.skip_names.extend(ctx.exported_symbols) return opts ``` -------------------------------- ### Prepare for Writing Documentation Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/manKernelDoc.html A placeholder method for adding logic before the documentation writing process begins. ```python def prepare_writing(self, docnames): """A place where you can add logic before :meth:`write_doc` is run""" pass ``` -------------------------------- ### State 2: Scanning Field Start Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/kernel_doc.html Represents the parser state where it is scanning for the start of a field within a documentation block. ```python [docs] def state_2(self, line): """state: 2 - scanning field start.""" ``` -------------------------------- ### SVG Example for Kernel-Render Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kfigure.html An example of embedding SVG code within the kernel-render directive to generate a Scalable Vector Graphics image. ```svg ``` -------------------------------- ### Write Documentation Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/manKernelDoc.html A placeholder method for the actual writing of documentation to the filesystem. ```python def write_doc(self, docname, doctree): """Where you actually write something to the filesystem.""" pass ``` -------------------------------- ### DOT Language Example for Kernel-Render Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kfigure.html An example of embedding DOT language within the kernel-render directive to generate a Graphviz DOT graph. ```dot digraph G { "Hello" -> "World" } ``` -------------------------------- ### Documenting a C function with kernel-doc markup Source: https://return42.github.io/linuxdoc/_sources/kernel-doc-intro.rst.txt This example demonstrates how to document a C function using kernel-doc markup, including a short description, argument descriptions, a longer detailed description, and return value description. It also shows the use of reST inline and block markups within the kernel-doc comment. ```c /** * foobar() - short function description of foobar * * @arg1: Describe the first argument to foobar. * @arg2: Describe the second argument to foobar. One can provide multiple line * descriptions for arguments. * * A longer description, with more discussion of the function foobar() that * might be useful to those using or modifying it. Begins with empty comment * line and may include additional embedded empty comment lines. Within, you * can refer other definitions (e.g. &struct my_struct, &typedef my_typedef, * %CONSTANT, $ENVVAR etc.). * * The longer description can have multiple paragraphs and you can use reST * inline markups like *emphasise* and **emphasis strong**. You also have reST * block markups like lists or literal available: * * Ordered List: * - item one * - item two * - literal block:: * * a + b --> x * * Return: * Describe the return value of foobar. */ int foobar(int arg1, int arg2); ``` -------------------------------- ### rstKernelDoc Module Initialization Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/rstKernelDoc.html Sets up the Sphinx application by adding configuration values and registering the 'kernel-doc' directive. This snippet shows the standard way to initialize Sphinx extensions. ```python # SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=missing-docstring, invalid-name """ rstKernelDoc ~~~~~~~~~~~~ Implementation of the ``kernel-doc`` reST-directive. The ``kernel-doc`` (:py:class:`KernelDoc`) directive includes contend from linux kernel source code comments. """ # ============================================================================== # imports # ============================================================================== import glob from sphinx.util import logging from io import StringIO from os import path import six from docutils import nodes from docutils.parsers.rst import Directive, directives from docutils.statemachine import ViewList from docutils.utils import SystemMessage from fspath import OS_ENV from sphinx.util.docutils import switch_source_input from . import kernel_doc as kerneldoc # ============================================================================== # common globals # ============================================================================== __version__ = "3.0" [docs] class ParserCache: """A simple (in process) cache for :py:obj:`KernelDocParser` objects (read :py:obj:`PARSER_CACHE`) """ def __init__(self): self._cache = {} def get_id(self, opts): """Generate a cache ID from the options of the kernel-doc directive. Some of the options control the parsing rules and thus in the end the parsing result. """ return ( opts.fname, opts.exp_method, tuple(opts.exp_ids), tuple(opts.known_attrs), ) def get(self, opts): x = self.get_id(opts) return self._cache.get(x) def set(self, opts, parser): self._cache[self.get_id(opts)] = parser PARSER_CACHE = ParserCache() """ToDo: this type of cache (in process) does not (fully) support sphinx's paralell build (job option -j N) where builds are spanned over processes. Sphinx-build creates a new job (process) not for each kernel-doc directive but for each rest-file (that contains at least one kernel-doc directive). """ app_log = logging.getLogger("application") def setup(app): app.add_config_value("kernel_doc_raise_error", False, "env") app.add_config_value("kernel_doc_verbose_warn", True, "env") app.add_config_value("kernel_doc_mode", "reST", "env") app.add_config_value("kernel_doc_mansect", None, "env") app.add_config_value("kernel_doc_exp_method", None, "env") app.add_config_value("kernel_doc_exp_ids", None, "env") app.add_config_value("kernel_doc_known_attrs", None, "env") app.add_config_value("kernel_doc_srctree", kerneldoc.SRCTREE, "env") app.add_directive("kernel-doc", KernelDoc) return dict(version=__version__, parallel_read_safe=True, parallel_write_safe=True) [docs] class KernelDocParser(kerneldoc.Parser): # pylint: disable=deprecated-method def __init__(self, app, *args, **kwargs): super().__init__(*args, **kwargs) self.app = app # ------------------------------------------------- # bind the parser logging to the sphinx application # ------------------------------------------------- # pylint: disable=arguments-differ def error(self, message, **replace): replace["fname"] = self.options.fname replace["line_no"] = replace.get("line_no", self.ctx.line_no) self.errors += 1 message = ("%(fname)s:%(line_no)s: [kernel-doc ERROR] : " + message) % replace app_log.error(message) def warn(self, message, **replace): replace["fname"] = self.options.fname replace["line_no"] = replace.get("line_no", self.ctx.line_no) self.warnings += 1 message = ("%(fname)s:%(line_no)s: [kernel-doc WARN] : " + message) % replace app_log.warning(message) ``` -------------------------------- ### Literal Block Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/reST-kernel-doc-mode.html An example of a literal block in reST, used to display preformatted text, such as ASCII art or simple diagrams, preserving whitespace. ```text +------+ +------+ |\ |\ | +----+-+ +-+----+ | | | | | | | | | +-+----+ | | +----+-+ \| \| |/ |/ +------+ +------+ foo() bar() ``` -------------------------------- ### Regular Expression for Start of State 5 Documentation Block Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/kernel_doc.html Detects the beginning of a multi-line documentation block in state 5, typically starting with '/**'. ```Python doc_state5_start = RE(r"^\\s*/\\*\\*\\s*$") ``` -------------------------------- ### Building and Gzipping Man Pages Source: https://return42.github.io/linuxdoc/linuxdoc-howto/man-pages.html Command to build man pages using the kernel-doc-man builder and then compress them using gzip. ```bash $ sphinx-build -b kernel-doc-man docs dist/docs/man building [kernel-doc-man]: all manpages ... scan master tree for kernel-doc man-pages ... writing man pages ... user_function.2 internal_function.2 ... $ find dist/docs/man -name '*.[0-9]' -exec gzip -nf {} + ``` -------------------------------- ### Kernel-Doc Directive Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-directive.html Example of a kernel-doc directive in reStructuredText to document a specific symbol from a header file. This is used when the definition of a symbol is not found during the build process. ```rst .. kernel-doc:: ./all-in-a-tumble.h :symbols: no_longer_exist ``` -------------------------------- ### Kernel-Doc Snippet Definition Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kernel-doc-syntax.rst.txt Defines a region in C source code to be extracted as a documentation snippet. The region is identified by a start comment '/* parse-SNIP: */' and ends with '/* parse-SNAP: */' or another snippet start. ```c /* parse-SNIP: */ /* parse-SNAP: */ ``` -------------------------------- ### Initialize and Run KernelDoc Directive Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/rstKernelDoc.html Sets up the necessary environment and state for the KernelDoc directive. It handles option validation, such as preventing the use of both 'symbols' and 'functions' options simultaneously. ```python def run(self): # ToDo: think about again; these members has been added for convenience self.parser = None # pylint: disable=attribute-defined-outside-init self.doc = self.state.document # pylint: disable=attribute-defined-outside-init self.env = ( self.doc.settings.env ) # pylint: disable=attribute-defined-outside-init self.nodes = [] # pylint: disable=attribute-defined-outside-init if "symbols" in self.options and "functions" in self.options: error = self.state_machine.reporter.error( ( 'Error in "%s" directive: used option :symbols:' " and its alias :functions:" % self.name ), nodes.literal_block(self.block_text, self.block_text), line=self.lineno, ) raise SystemMessage(error, 4) if "symbols" in self.options: self.options["functions"] = self.options["symbols"] ``` -------------------------------- ### Include all-in-a-tumble.h documentation Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/all-in-a-tumble.rst.txt Use the kernel-doc directive to include documentation from the C header file. The ':module:' option is used here for specific module targeting. ```rst .. kernel-doc:: ./all-in-a-tumble.h :module: example ``` -------------------------------- ### Get Partial Document Tree Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/manKernelDoc.html Creates a new document tree from a list of children nodes. ```python def get_partial_document(self, children): doc_tree = new_document("") doc_tree += children return doc_tree ``` -------------------------------- ### Display Help for linuxdoc.lint Source: https://return42.github.io/linuxdoc/src/linuxdoc.lint.html Shows the available command-line options for the `linuxdoc.lint` tool. Use this to understand its capabilities and parameters. ```bash $ linuxdoc.lint --help ``` -------------------------------- ### C Hello World Program Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble-src.html A basic C program that prints 'Hello World' to the console. This is a standard entry point for C programming. ```c #include int main() { printf("Hello World\n"); return 0; } ``` -------------------------------- ### Start Snippet Region Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-syntax.html Use 'parse-SNIP' followed by a snippet name to begin a region for extracting code. ```c /* parse-SNIP: */ ``` -------------------------------- ### Include all-in-a-tumble.c documentation Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/all-in-a-tumble.rst.txt Use the kernel-doc directive to include documentation from the C source file. The ':module:' option is used here for specific module targeting. ```rst .. kernel-doc:: ./all-in-a-tumble.c :module: example ``` -------------------------------- ### Function with Export Attribute Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-tests.html Example of a C function marked with `API_EXPORTED` attribute, intended for documentation via kernel-doc. ```c /** * user_sum() - another function that can only be called in user context * @a: first argument * @b: second argument * * This function makes no sense, it's only a kernel-doc demonstration. * * Example: * x = user_sum(1, 2); * * Return: * Returns the sum of the @a and @b */ API_EXPORTED int user_sum(int a, int b) { return a + b; } ``` -------------------------------- ### Call user_function in C Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble.html Example of calling the user_function, which is intended for user context. It takes an integer argument and an ellipsis. ```c x = user_function(22); ``` -------------------------------- ### Include man-page as download item Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kernel-doc-tests.rst.txt Demonstrates how to include a man-page as a downloadable item in HTML output using the :download: directive. A relative build path is required. ```rst :download:`user_function.2.gz <../../dist/docs/man/user_function.2.gz>` ``` -------------------------------- ### Include Media Controller Header File with Environment Variable Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/kernel-include-directive.rst.txt Demonstrates how to use the kernel-include directive to include a header file whose path is defined by an environment variable. This is useful for dynamic path resolution during the build process. ```rst .. _media_header: **************************** Media Controller Header File **************************** .. kernel-include:: $BUILDDIR/media.h.rst ``` -------------------------------- ### Kernel-doc Error Message for Missing Exports Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-tests.html An example of the error message generated when a kernel-doc :export: directive matches no symbols. ```rst /share/linuxdoc/docs/linuxdoc-howto/kernel-doc-tests.rst:350: (ERROR/3) using option :export: but there are no exported symbols .. kernel-doc:: ./all-in-a-tumble.c :export: ./match_files_without_exports* ``` -------------------------------- ### Include all-in-a-tumble.c documentation with known attributes Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/all-in-a-tumble.rst.txt Use the kernel-doc directive to include documentation from the C source file, specifying known attributes. The ':module:' option is used here for specific module targeting. ```rst .. kernel-doc:: ./all-in-a-tumble.c :module: example :known-attrs: API_EXPORTED ``` -------------------------------- ### Kernel Doc Initializer Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/kernel_doc.html Initializes the kernel documentation generator with options and parser. ```python def __init__(self): self.options = None self.parser = None self.dumped_names = [] self.translated_names = set() ``` -------------------------------- ### Regular Expression for Documentation Content Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/kernel_doc.html Captures the main body of a documentation block, starting after the initial documentation comment pattern. ```Python doc_content = RE(doc_com_body.pattern + r"(.*)") ``` -------------------------------- ### Python Setup Function for KernelInclude Directive Source: https://return42.github.io/linuxdoc/_modules/linuxdoc/kernel_include.html This function registers the 'kernel-include' directive with the Sphinx application. It returns metadata about the extension. ```python # ============================================================================== def setup(app): # ============================================================================== app.add_directive("kernel-include", KernelInclude) return dict(version=__version__, parallel_read_safe=True, parallel_write_safe=True) # ============================================================================== ``` -------------------------------- ### Kernel-Doc Function with Short Description and Parameter Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-syntax.html Demonstrates a kernel-doc comment including a short description for the function and a description for its parameter. ```c /** * my_function - does my stuff * @my_arg: its mine damnit * * Does my stuff explained. */ ``` -------------------------------- ### reST Cross-Referencing Kernel-Doc Source: https://return42.github.io/linuxdoc/linuxdoc-howto/kernel-doc-directive.html Examples of cross-referencing C constructs and specific documentation sections within reST documents using Sphinx. ```rst * C constructs in Sphinx >= 3.1 :c:func:`foo.user_function` * refer sections: :ref:`Example `, :ref:`Return ` ... ``` -------------------------------- ### Sphinx build command for kernel-doc-man Source: https://return42.github.io/linuxdoc/_sources/linuxdoc-howto/man-pages.rst.txt This command initiates the Sphinx build process using the `kernel-doc-man` builder to generate man pages. ```bash sphinx-build -b kernel-doc-man ... ``` -------------------------------- ### Display grepdoc Help Source: https://return42.github.io/linuxdoc/src/linuxdoc.grepdoc.html Use the --help flag to display the usage information for the linuxdoc.grepdoc command. ```bash $ linuxdoc.grepdoc --help ``` -------------------------------- ### Call user_sum in C Source: https://return42.github.io/linuxdoc/linuxdoc-howto/all-in-a-tumble.html Example of calling the user_sum function, designed for user context. It takes two integer arguments and returns their sum. ```c x = user_sum(1, 2); ``` -------------------------------- ### ASCII Art Literal Block Example Source: https://return42.github.io/linuxdoc/linuxdoc-howto/reST-kernel-doc-mode.html Demonstrates a literal block containing ASCII art, preserving whitespace and characters exactly as written. ```text +------+ +------+ |\ |\ /| /| | +----+-+ +-+----+ | | | | | | | | | +-+----+ | | +----+-+ \| |\ |/ |/ +------+ +------+ foo() bar() ```