pure python kernel-doc parser and more
Subsystems (5)
cover pure python kernel-doc parser and more
Hi Jon,
here is my RFC, replacing the kernel-doc parser perl script with a python implementation. The parser is implemented as module and is used by several kernel-doc applications:
* kerneldoc : the parser
* kerneldoc-lint : liniting
* kerneldoc-src2rst : autodoc source tree
* manKernelDoc.py : a builder generating man-pages
All this is mainly merged 1:1 from my POC at:
https://github.com/return42/linuxdoc commit 3991d3c
Since it is merged 1:1, you will notice it's CodingStyle is (ATM) not kernel compliant and it lacks a user doc ('Documentation/doc-guide'). Take this as a starting point to play around and gain some experience with the parser and its applications. CodingStyle and user documentation will be patched when the community agreed about functionalities.
Thanks
-- Markus --
[1] https://www.mail-archive.com/[email protected]/msg09002.html
Markus Heiser (6):
kernel-doc: pure python kernel-doc parser (preparation)
kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
kernel-doc: add kerneldoc-lint command
kernel-doc: insert TODOs on kernel-doc errors
kernel-doc: add kerneldoc-src2rst command
kernel-doc: add man page builder (target mandocs)
Documentation/Makefile.sphinx | 8 +- Documentation/admin-guide/conf.py | 2 + Documentation/admin-guide/index.rst | 2 + Documentation/conf.py | 8 +- Documentation/core-api/conf.py | 2 + Documentation/core-api/index.rst | 2 + Documentation/dev-tools/conf.py | 2 + Documentation/dev-tools/index.rst | 2 + Documentation/doc-guide/conf.py | 2 + Documentation/doc-guide/index.rst | 2 + Documentation/driver-api/conf.py | 2 + Documentation/driver-api/index.rst | 2 + Documentation/gpu/conf.py | 2 + Documentation/gpu/index.rst | 2 + Documentation/media/Makefile | 1 + Documentation/media/conf.py | 2 + Documentation/media/index.rst | 2 + Documentation/process/conf.py | 2 + Documentation/process/index.rst | 2 + Documentation/security/conf.py | 2 + Documentation/security/index.rst | 9 + Documentation/sphinx/fspath.py | 435 +++++ Documentation/sphinx/kernel_doc.py | 2908 ++++++++++++++++++++++++++++++++++ Documentation/sphinx/kerneldoc.py | 149 -- Documentation/sphinx/lint.py | 121 ++ Documentation/sphinx/manKernelDoc.py | 408 +++++ Documentation/sphinx/rstKernelDoc.py | 560 +++++++ Documentation/sphinx/src2rst.py | 229 +++ scripts/kerneldoc | 11 + scripts/kerneldoc-lint | 11 + scripts/kerneldoc-src2rst | 11 + 31 files changed, 4748 insertions(+), 155 deletions(-) create mode 100644 Documentation/sphinx/fspath.py create mode 100755 Documentation/sphinx/kernel_doc.py delete mode 100644 Documentation/sphinx/kerneldoc.py create mode 100755 Documentation/sphinx/lint.py create mode 100755 Documentation/sphinx/manKernelDoc.py create mode 100755 Documentation/sphinx/rstKernelDoc.py create mode 100755 Documentation/sphinx/src2rst.py create mode 100755 scripts/kerneldoc create mode 100755 scripts/kerneldoc-lint create mode 100755 scripts/kerneldoc-src2rst
Signature · 1 line
2.7.4
RFC PATCH 1/6 kernel-doc: pure python kernel-doc parser (preparation)
This is the first patch of a series which merges a pure python implementation of the kernel-doc parser. It adds the prerequisites which are needed by the pure python implementation (which comes later in the series).
The fspath module in this patch is a reduced implementation of pypi's fspath [1]. As an alternative to this patch we can add an external dependence which can be installed from PyPi with 'pip install fspath' see [2] (but I guess we won't more external dependencies).
[1] https://pypi.python.org/pypi/fspath/
{2] https://return42.github.io/fspath/
--- Documentation/sphinx/fspath.py | 435 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 435 insertions(+) create mode 100644 Documentation/sphinx/fspath.py
Documentation/sphinx/fspath.py new file +435 -0
@@ -0,0 +1,435 @@ +# -*- coding: utf-8; mode: python -*- +u""" +Handling path names and executables more comfortable. +""" + +# ============================================================================== +# imports +# ============================================================================== + +import io +import os +from os import path +import re +import shutil +import subprocess +import sys +from glob import iglob + +import six + +# ============================================================================== +class FSPath(six.text_type): +# ============================================================================== + + u""" + A path name to a file or folder. + + Handling path names more comfortable, e.g.: + + * concatenate path names with the division operator ``/`` + * call functions like *mkdir* on path names + * get properties like *EXISTS* + + .. code-block:: python + + >>> folder = fspath.FSPath("/tmp") + >>> folder.EXISTS + True + >>> (folder / "subfolder").makedirs() + >>> list(folder.reMatchFind(".*sub")) + ['/tmp/subfolder'] + >>> (folder / "test.txt").FILENAME + 'test' + >>> (folder / "test.txt").DIRNAME + '/tmp' + >>> six.print_("topfolder" / folder) + topfolder/temp + >>> six.print_(folder + "addedstr") + tmpaddedstr + >>> six.print_((folder/"foo"/"bar.txt").splitpath()) + (u'/tmp/foo', u'bar.txt') + >>> six.print_(folder / "foo" / "../bar.txt") + tmp/bar.txt + """ + + def __new__(cls, pathname): + u"""Constructor of a path name object. + + Regardless of how the encoding of the file system is, the ``pathname`` + is converted to unicode. The conversion of byte strings is based the + default encodings. + + To issue "File-system Encoding" See also: + + * https://docs.python.org/3.5/howto/unicode.html#unicode-filenames + """ + pathname = path.normpath(path.expanduser(six.text_type(pathname))) + return super(FSPath, cls).__new__(cls, pathname) + + @property + def VALUE(self): + u"""string of the path name""" + return six.text_type(self) + + @property + def EXISTS(self): + u"""True if file/pathname exist""" + return path.exists(self) + + @property + def SIZE(self): + u"""Size in bytes""" + return path.getsize(self) + + @property + def isReadable(self): + u"""True if file/path is readable""" + return os.access(self, os.R_OK) + + @property + def isWriteable(self): + u"""True if file/path is writeable""" + return os.access(self, os.W_OK) + + @property + def isExecutable(self): + u"""True if file is executable""" + return os.access(self, os.X_OK) + + @property + def ISDIR(self): + u"""True if path is a folder""" + return path.isdir(self) + + @property + def ISFILE(self): + u"""True if path is a file""" + return path.isfile(self) + + @property + def ISLINK(self): + u"""True if path is a symbolic link""" + return path.islink(self) + + @property + def DIRNAME(self): + u"""The path name of the folder, where the file is located + + E.g.: ``/path/to/folder/filename.ext`` --> ``/path/to/folder`` + """ + return self.__class__(path.dirname(self)) + + @property + def BASENAME(self): + u"""The path name with suffix, but without the folder name. + + E.g.: ``/path/to/folder/filename.ext`` --> ``filename.ext`` + """ + return self.__class__(path.basename(self)) + + @property + def FILENAME(self): + u"""The path name without folder and suffix. + + E.g.: ``/path/to/folder/filename.ext`` --> ``filename`` + + """ + return self.__class__(path.splitext(path.basename(self))[0]) + + @property + def SUFFIX(self): + u"""The filename suffix + + E.g.: ``/path/to/folder/filename.ext`` --> ``.ext`` + + """ + return self.__class__(path.splitext(self)[1]) + + @property + def SKIPSUFFIX(self): + u"""The complete file name without suffix. + + E.g.: ``/path/to/folder/filename.ext`` --> ``/path/to/folder/filename`` + """ + return self.__class__(path.splitext(self)[0]) + + @property + def ABSPATH(self): + u"""The absolute pathname + + E.g: ``../to/../to/folder/filename.ext`` --> ``/path/to/folder/filename.ext`` + + """ + return self.__class__(path.abspath(self)) + + @property + def REALPATH(self): + u"""The real pathname without symbolic links.""" + return self.__class__(path.realpath(self)) + + @property + def POSIXPATH(self): + u"""The path name in *POSIX* notation. + + Helpfull if you are on MS-Windows and need the POSIX name. + """ + if os.sep == "/": + return six.text_type(self) + else: + p = six.text_type(self) + if p[1] == ":": + p = "/" + p.replace(":", "", 1) + return p.replace(os.sep, "/") + + @property + def NTPATH(self): + u"""The path name in the Windows (NT) notation. + """ + if os.sep == "\\": + return six.text_type(self) + else: + return six.text_type(self).replace(os.sep, "\\") + + @property + def EXPANDVARS(self): + u"""Path with environment variables expanded.""" + return self.__class__(path.expandvars(self)) + + @property + def EXPANDUSER(self): + u"""Path with an initial component of ~ or ~user replaced by that user's home.""" + return self.__class__(path.expanduser(self)) + + @classmethod + def getHOME(cls): + u"""User's home folder.""" + return cls(path.expanduser("~")) + + def makedirs(self, mode=0o775): + u"""Recursive directory creation, default mode is 0o775 (octal).""" + if not self.ISDIR: + return os.makedirs(self, mode) + + def __div__(self, pathname): + return self.__class__(self.VALUE + os.sep + six.text_type(pathname)) + __truediv__ = __div__ + + def __rdiv__(self, pathname): + return self.__class__(six.text_type(pathname) + os.sep + self.VALUE) + + def __add__(self, other): + return self.__class__(self.VALUE + six.text_type(other)) + + def __radd__(self, other): + return self.__class__(six.text_type(other) + self.VALUE) + + def relpath(self, start): + return self.__class__(path.relpath(self, start)) + + def splitpath(self): + head, tail = path.split(self) + return (self.__class__(head), self.__class__(tail)) + + def listdir(self): + for name in os.listdir(self): + yield self.__class__(name) + + def glob(self, pattern): + for name in iglob(self / pattern ): + yield self.__class__(name) + + def walk(self, topdown=True, onerror=None, followlinks=False): + for dirpath, dirnames, filenames in os.walk(self, topdown, onerror, followlinks): + yield (self.__class__(dirpath), + [self.__class__(x) for x in dirnames], + [self.__class__(x) for x in filenames] ) + + def reMatchFind(self, name, isFile=True, isDir=True, followlinks=False): + + # find first e.g: next(myFolder.reMatchFind(r".*name.*"), None) + + name_re = re.compile(name) + for folder, dirnames, filenames in self.walk(followlinks=followlinks): + if isDir: + for d_name in [x for x in dirnames if name_re.match(x)]: + yield folder / d_name + if isFile: + for f_name in [x for x in filenames if name_re.match(x)]: + yield folder / f_name + + def suffix(self, newSuffix): + return self.__class__(self.SKIPSUFFIX + newSuffix) + + def copyfile(self, dest, preserve=False): + u"""Copy the file src to the file or directory dest. + + Argument preserve copies permission bits. + """ + if preserve: + shutil.copy2(self, dest) + else: + shutil.copy(self, dest) + + def copytree(self, dest, symlinks=False, ignore=None): + u"""Recursively copy the entire directory tree""" + shutil.copytree(self, dest, symlinks, ignore) + + def move(self, dest): + u"""Move path to another location (dest)""" + shutil.move(self, dest) + + def delete(self): + u"""remove file/folder""" + if self.ISDIR: + self.rmtree() + else: + os.remove(self) + + def rmtree(self, ignore_errors=False, onerror=None): + u"""remove tree""" + shutil.rmtree(self, ignore_errors, onerror) + + def openTextFile( + self, mode = 'r', encoding = 'utf-8' + , errors = 'strict', buffering = 1 + , newline = None): + u"""Open file as text file""" + return io.open( + self, mode=mode, encoding=encoding + , errors=errors, buffering=buffering + , newline=newline) + + def readFile(self, encoding='utf-8', errors='strict'): + u"""read entire file""" + with self.openTextFile(encoding=encoding, errors=errors) as f: + return f.read() + + def Popen(self, *args, **kwargs): + u"""Get a ``subprocess.Popen`` object (``proc``). + + The path name of the self-object is the programm to call. The program + arguments are given py ``*args`` and the ``*kwargs`` are passed to the + ``subprocess.Popen`` constructor. The ``universal_newlines=True`` is + true by default. + + see https://docs.python.org/3/library/subprocess.html#popen-constructor + + .. code-block:: python + + import six + from fspath import FSPath + proc = FSPath("arp").Popen("-a",) + stdout, stderr = proc.communicate() + retVal = proc.returncode + six.print_("stdout: %s" % stdout) + six.print_("stderr: %s" % stderr) + six.print_("exit code = %d" % retVal) + + """ + + defaults = { + 'stdout' : subprocess.PIPE, + 'stderr' : subprocess.PIPE, + 'stdin' : subprocess.PIPE, + 'universal_newlines' : True + } + defaults.update(kwargs) + return subprocess.Popen([self,] + list(args), **defaults) + + +# ============================================================================== +def which(fname, findall=True): +# ============================================================================== + u""" + Searches the fname in the enviroment ``PATH``. + + This *which* is not POSIX conform, it searches the fname (without extension) + and the fname with one of the ".exe", ".cmd", ".bat" extension. If nothing + is found, ``None` is returned if something matches, a list (``set``) is + returned. With option ``findall=False`` the first match is returned or + ``None``, if nothing is found. + """ + exe = ["", ".exe", ".cmd", ".bat"] + if sys.platform != 'win32': + exe = [""] + envpath = os.environ.get('PATH', None) or os.defpath + + locations = set() + for folder in envpath.split(os.pathsep): + for ext in exe: + fullname = FSPath(folder + os.sep + fname + ext) + if fullname.ISFILE: + if not findall: + return fullname + locations.add(fullname) + return locations or None + +# ============================================================================== +def callEXE(cmd, *args, **kwargs): +# ============================================================================== + + u""" + Synchronous command call ``cmd`` with arguments ``*args`` . + + The ``*kwargs`` are passed to the ``subprocess.Popen`` constructor. The + return value is a three-digit tuple ``(stdout, stderr, rc)``. + + .. code-block:: python + + import six + from fspath import callEXE + out, err, rc = callEXE("arp", "-a") + + six.print_("stdout: %s" % out) + six.print_("stderr: %s" % err) + six.print_("exit code = %d" % rc) + """ + + exe = which(cmd, findall=False) + if exe is None: + raise IOError('command "%s" not availble!' % cmd) + proc = exe.Popen(*args, **kwargs) + stdout, stderr = proc.communicate() + rc = proc.returncode + return (stdout, stderr, rc) + + +# ============================================================================== +class DevNull(object): # pylint: disable=R0903 +# ============================================================================== + + """A dev/null file descriptor.""" + def write(self, *args, **kwargs): + pass + +DevNull = DevNull() + +# ============================================================================== +class OS_ENV(dict): +# ============================================================================== + + u""" + Environment object (singleton). + + .. code-block:: python + + >>> if OS_ENV.get("SHELL") is None: + OS_ENV.SHELL = "/bin/bash" + >>> OS_ENV.MY_NAME + '/bin/bash' + """ + @property + def __dict__(self): + return os.environ + + def __getattr__(self, attr): + return os.environ[attr] + + def __setattr__(self, attr, val): + os.environ[attr] = val + + def get(self, attr, default=None): + return os.environ.get(attr, default) + +OS_ENV = OS_ENV()
Signature · 1 line
2.7.4
RFC PATCH 2/6 kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
In reply to Markus HeiserThis patch is the initial merge of a pure python implementation to parse kernel-doc comments and generate reST from.
It consist mainly of to parts, the parser module (kerneldoc.py) and the sphinx-doc extension (rstKernelDoc.py). For the command line, there is also a 'scripts/kerneldoc' added.::
scripts/kerneldoc --help
The main two parts are merged 1:1 from
https://github.com/return42/linuxdoc commit 3991d3c
Take this as a starting point, there is a lot of work to do (WIP). Since it is merged 1:1, you will also notice it's CodingStyle is (ATM) not kernel compliant and it lacks a user doc ('Documentation/doc-guide').
I will send patches for this when the community agreed about functionalities. I guess there are a lot of topics we have to agree about. E.g. the py-implementation is more strict the perl one. When you build doc with the py-module you will see a lot of additional errors and warnings compared to the sloppy perl one.
I also guess that kernel_doc.py module needs some clean up, but first follow the patch series to see what additional functionalities it brings.
I few words about it's history: I started this implementation very early as a part of a POC in May 2016:
https://github.com/return42/sphkerneldoc
Later I implemented the 'linuxdoc' suite mentioned above. Since beginning, all bug fixes has been merged which has been applied to the perl one from the kernel's source tree. The test was always to run the kernel-doc parser against the whole source tree and see if there are changes which might be a regression. A partial history of reST output changes can be found here:
https://github.com/return42/sphkerneldoc/tree/master/linux_src_doc
At the beginning I spent weeks/month in testing, reviewing the logs and the produced output. At that time, while testing against whole source tree, I found several bugs in the perl version I ported. Sorry that I have not mailed all those bugs to the kernel-doc ML back, but my first aim was to implement a replacement and not to merge improvements downwards. This was also the time I implemented several improvements in linting. To sum, thats why I hope, a switch to py-version brings progress without any regression.
--- Documentation/Makefile.sphinx | 3 +- Documentation/conf.py | 6 +- Documentation/sphinx/kernel_doc.py | 2908 ++++++++++++++++++++++++++++++++++ Documentation/sphinx/kerneldoc.py | 149 -- Documentation/sphinx/rstKernelDoc.py | 560 +++++++ scripts/kerneldoc | 11 + 6 files changed, 3483 insertions(+), 154 deletions(-) create mode 100755 Documentation/sphinx/kernel_doc.py delete mode 100644 Documentation/sphinx/kerneldoc.py create mode 100755 Documentation/sphinx/rstKernelDoc.py create mode 100755 scripts/kerneldoc
Documentation/Makefile.sphinx +1 -2
@@ -37,8 +37,7 @@ HAVE_PDFLATEX := $(shell if which $(PDFLATEX) >/dev/null 2>&1; then echo 1; else PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter KERNELDOC = $(srctree)/scripts/kernel-doc -KERNELDOC_CONF = -D kerneldoc_srctree=$(srctree) -D kerneldoc_bin=$(KERNELDOC) -ALLSPHINXOPTS = $(KERNELDOC_CONF) $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) +ALLSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
Documentation/conf.py +3 -3
@@ -34,7 +34,7 @@ from load_config import loadConfig # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = ['kerneldoc', 'rstFlatTable', 'kernel_include', 'cdomain'] +extensions = ['rstKernelDoc', 'rstFlatTable', 'kernel_include', 'cdomain' ] # The name of the math extension changed on Sphinx 1.4 if major == 1 and minor > 3:
@@ -505,8 +505,8 @@ pdf_documents = [ # kernel-doc extension configuration for running Sphinx directly (e.g. by Read # the Docs). In a normal build, these are supplied from the Makefile via command # line arguments. -kerneldoc_bin = '../scripts/kernel-doc' -kerneldoc_srctree = '..' +kernel_doc_verbose_warn = False +kernel_doc_raise_error = False # ------------------------------------------------------------------------------ # Since loadConfig overwrites settings from the global namespace, it has to be
Documentation/sphinx/kernel_doc.py new file +2908 -0
2,908 lines not on this page · raw message
Documentation/sphinx/kerneldoc.py deleted +0 -149
65 lines not on this page · raw message
Documentation/sphinx/rstKernelDoc.py new file +560 -0
560 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.7.4
Part of the diff is not shown here. View the raw message.
Jonathan Corbet
maintainerRe: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
Quoted 17 lines · On Tue, 24 Jan 2017 20:52:40 +0100 Markus Heiser <[email protected]>…
This patch is the initial merge of a pure python implementation to parse kernel-doc comments and generate reST from.
It consist mainly of to parts, the parser module (
kerneldoc.py) and the sphinx-doc extension (rstKernelDoc.py). For the command line, there is also a 'scripts/kerneldoc' added.::scripts/kerneldoc --helpThe main two parts are merged 1:1 from
https://github.com/return42/linuxdoc commit 3991d3c
Take this as a starting point, there is a lot of work to do (WIP). Since it is merged 1:1, you will also notice it's CodingStyle is (ATM) not kernel compliant and it lacks a user doc ('
Documentation/doc-guide').
Quoted 5 lines
I will send patches for this when the community agreed about functionalities. I guess there are a lot of topics we have to agree about. E.g. the py-implementation is more strict the perl one. When you build doc with the py-module you will see a lot of additional errors and warnings compared to the sloppy perl one.
Again, quick comments...
- I would *much* rather evolve our existing Sphinx extension in the direction we want it to go than to just replace it wholesale. Replacement is the wrong approach for a few reasons, including the need to minimize change and preserve credit for Jani's work. Can we work on that basis, please?
Ideally at the time of merging, we would be able to build the docs with *either* kerneldoc.
- I'll have to try it out to see how noisy it is. I'm not opposed to stricter checks; indeed, they could be a good thing. But we might want to have an option so we can cut back on the noise by default.
Thanks,
jon
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
Quoted 28 lines · Jonathan Corbet
Quoted 17 lines · On Tue, 24 Jan 2017 20:52:40 +0100 Markus Heiser <[email protected]>…
This patch is the initial merge of a pure python implementation to parse kernel-doc comments and generate reST from.
It consist mainly of to parts, the parser module (
kerneldoc.py) and the sphinx-doc extension (rstKernelDoc.py). For the command line, there is also a 'scripts/kerneldoc' added.::scripts/kerneldoc --helpThe main two parts are merged 1:1 from
https://github.com/return42/linuxdoc commit 3991d3c
Take this as a starting point, there is a lot of work to do (WIP). Since it is merged 1:1, you will also notice it's CodingStyle is (ATM) not kernel compliant and it lacks a user doc ('
Documentation/doc-guide').Quoted 5 lines
I will send patches for this when the community agreed about functionalities. I guess there are a lot of topics we have to agree about. E.g. the py-implementation is more strict the perl one. When you build doc with the py-module you will see a lot of additional errors and warnings compared to the sloppy perl one.
Again, quick comments...
Quoted 8 lines
- I would *much* rather evolve our existing Sphinx extension in the direction we want it to go than to just replace it wholesale. Replacement is the wrong approach for a few reasons, including the need to minimize change and preserve credit for Jani's work. Can we work on that basis, please?
Ideally at the time of merging, we would be able to build the docs with *either* kerneldoc.
Seconded, I think renaming the extension string like this is just fairly pointless busy-work. Kernel-doc isn't interacting perfectly with rst, but now we already have a sizeable amount of stuff converted and going through all that once more needs imo som really clear benefits. I think bug-for-bug compatibility would be much better. Later on we could do changes, on a change-by-change basis.
-Daniel
Quoted 9 lines
- I'll have to try it out to see how noisy it is. I'm not opposed to stricter checks; indeed, they could be a good thing. But we might want to have an option so we can cut back on the noise by default.
Thanks,
jon
Signature · 3 lines
Daniel Vetter Software Engineer, Intel Corporation http://blog.ffwll.ch
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
Hi Jon, hi Daniel !
Am 25.01.2017 um 07:37 schrieb Daniel Vetter <[email protected]>:
Quoted 7 lines
Quoted 7 lines
Again, quick comments...
- I would *much* rather evolve our existing Sphinx extension in the direction we want it to go than to just replace it wholesale. Replacement is the wrong approach for a few reasons, including the need to minimize change and preserve credit for Jani's work. Can we work on that basis, please?
Sure. But I fear I haven't understood you right .... last post was:
Quoted 5 lines
Markus, would you consider sending out a new patch set for review? What I would like to do see is something adding the new script for the Sphinx toolchain, while leaving the DocBook build unchanged, using the old script. We could then delete it once the last template file has moved over.
talking about DocBook and now I read ...
Quoted 2 lines
Quoted 2 lines
Ideally at the time of merging, we would be able to build the docs with *either* kerneldoc.
Now I'am totally confused ... it's no about you, but I do not understand you clearly ... can you help a conceptual man?
Quoted 2 lines
Seconded, I think renaming the extension string like this is just fairly pointless busy-work.
Hi Daniel, please help me, what did you mean with "renaming" the extension string and "busy-work"?
There is a renaming of module's name but there should no work outside this patch ...
Quoted 3 lines
Kernel-doc isn't interacting perfectly with rst, but
now we already have a sizeable amount of stuff converted and going through all that once more needs imo som really clear benefits.
from authors POV nothing has changed.
Quoted 2 lines
I think bug-for-bug compatibility would be much better. Later on we could do changes, on a change-by-change basis.
Both sphinx-extensions (the one we have and the one in the series) are adapter to a "parser backend".
1. Documentation/sphinx/kerneldoc.py <--> scripts/kerneldoc -rst
2. Documentation/sphinx/rstKernelDoc.py <--> import module Documentation/sphinx/kernel_doc.py
Maintain two adapters for the two backends is possible. But one adapter for two complete different backends .. is this what you mean?
Quoted 3 lines
Quoted 3 lines
- I'll have to try it out to see how noisy it is. I'm not opposed to stricter checks; indeed, they could be a good thing. But we might want to have an option so we can cut back on the noise by default.
As said, I'am willing to go communities way, it seems just a communication problem (on my side) to understand what this way would be.
I try to sum what I guess ... e.g. to build output as usual with (1.)
$ make htmldocs
to build with the py-parser and its sphinx-extension (see 2. above)::
$ USE_PY_PARSER=1 make htmldocs
this should be easy and I can realize it in v2, but is this what you want?
Please give me some more hints / Thanks a lot!
--Markus--
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
In reply to Jonathan CorbetQuoted 20 lines · Jonathan Corbet
Quoted 17 lines · On Tue, 24 Jan 2017 20:52:40 +0100 Markus Heiser <[email protected]>…
This patch is the initial merge of a pure python implementation to parse kernel-doc comments and generate reST from.
It consist mainly of to parts, the parser module (
kerneldoc.py) and the sphinx-doc extension (rstKernelDoc.py). For the command line, there is also a 'scripts/kerneldoc' added.::scripts/kerneldoc --helpThe main two parts are merged 1:1 from
https://github.com/return42/linuxdoc commit 3991d3c
Take this as a starting point, there is a lot of work to do (WIP). Since it is merged 1:1, you will also notice it's CodingStyle is (ATM) not kernel compliant and it lacks a user doc ('
Documentation/doc-guide').
Quoted 5 lines
Quoted 5 lines
I will send patches for this when the community agreed about functionalities. I guess there are a lot of topics we have to agree about. E.g. the py-implementation is more strict the perl one. When you build doc with the py-module you will see a lot of additional errors and warnings compared to the sloppy perl one.
Markus, thanks for your work on this.
Quoted 7 lines
Again, quick comments...
- I would *much* rather evolve our existing Sphinx extension in the direction we want it to go than to just replace it wholesale. Replacement is the wrong approach for a few reasons, including the need to minimize change and preserve credit for Jani's work. Can we work on that basis, please?
I would grossly downplay the role of preserving credit for what I've done, and put much more emphasis on the need to create a patch series that gradually, step by step, evolves the current approach into something better.
Excuse me for my bluntness, but I think changing everything in a single commit, or even a few commits, is strictly not acceptable.
When I changed *small* things in scripts/kernel-doc, I would make htmldocs before and after the change, and recursively diff the produced output to ensure there were no surprises. We already have enough documentation that a manual eyeballing of the output is simply not sufficient to ensure things don't break.
The diff in output between before and after this series? 160k lines of unified diff without context ('diff -u0 -r old new | wc -l').
Many of the changes are improvements on the result, such as using proper <div> tags for function parameter lists etc., but clearly changing the output should be independent of changing the parser, so we have some chance of validating the parser.
Quoted 2 lines
Ideally at the time of merging, we would be able to build the docs with *either* kerneldoc.
I'd be fine with switching over in a single commit that doesn't drastically change the output. A drop-in replacement. But that's not the case here.
Quoted 3 lines
- I'll have to try it out to see how noisy it is. I'm not opposed to stricter checks; indeed, they could be a good thing. But we might want to have an option so we can cut back on the noise by default.
The increase in 'make htmldocs' build log was from 1521 to 2791 lines in my tree. Arguably there was useful extra diagnosis, but some of it was the printouts of long lists of definitions that were not found, one per line. So it could be condensed without losing info too.
On to performance. With the default build options the new system was noticeably slower than the current one, with a 50% increase on my machine. But what really caught me by surprise was that passing SPHINXOPTS=-j5 to parallelize worked better on the current system, making the new one a whopping 70% slower. Of course, the argument is that the proposed parser does more and is better, but due to the monolithic change it's impossible to pinpoint the culprit or do a proper cost/benefit analysis on this. Again, this calls for a more broken down series of patches to make the changes.
Finally, while I'd love to see scripts/kernel-doc go, I do have to ask if changing roughly 3k lines of Perl to roughly 3k lines of Python (*) really makes everything better? They both still parse everything using a large pile of regular expressions and a clunky state machine. When I look at the code, I'm afraid I do not get that liberating feeling of throwing out old junk in favor of something small or elegant or even obviously more maintainable than the old one. The new one offers more features, but repeatedly we face the problem that it's all lumped in together with the parser change. We should be able to look at the parser change and the other improvements separately.
That said, perhaps having an elegant parser (perhaps based on a compiler plugin) is incompatible with the idea of making it a bug-for-bug drop-in replacement of the old one, and it's something we need to think about.
All in all I think the message should be clear: this needs to be split into small, incremental changes. Just like we do everything in the kernel.
BR,
Jani.
(*) Please do not get hung up on these numbers. The Python version does
more in some ways, but adds more deps such as fspath that's not included in the figures, and the Perl version outputs more formats. It's not an apples to apples comparison. Let's just say they are somewhere in the same ballpark.
Signature · 1 line
Jani Nikula, Intel Open Source Technology Center
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
Quoted 10 lines · Jani Nikula
Finally, while I'd love to see
scripts/kernel-docgo, I do have to ask if changing roughly 3k lines of Perl to roughly 3k lines of Python (*) really makes everything better? They both still parse everything using a large pile of regular expressions and a clunky state machine. When I look at the code, I'm afraid I do not get that liberating feeling of throwing out old junk in favor of something small or elegant or even obviously more maintainable than the old one. The new one offers more features, but repeatedly we face the problem that it's all lumped in together with the parser change. We should be able to look at the parser change and the other improvements separately.
I share this concern a lot. The kernel-doc perl is a horror show, but it's a horror show that 3-4 people now somewhat understand. Simply translating the entire script into python leaves us with the same horror show, but in a different language. And personally I'm not versed at all in either of them (and I think that applies to many kernel hackers), so seems a wash.
If the new script would implement the state machinery in some parser-combinator library to make it much easier to maintain, while still being bug-for-bug compatible, then I'd be much, much more in favour of doing this. And once we go to that amount of effort, then rewriting it in python for more consistency with sphinx is definitely a good idea.
Quoted 3 lines
That said, perhaps having an elegant parser (perhaps based on a compiler plugin) is incompatible with the idea of making it a bug-for-bug drop-in replacement of the old one, and it's something we need to think about.
Yeah, I fear we'll always need our own parser to avoid breaking the world. But there's definitely better ways out there to write parsers than cobbling together regexes in a state machine that uses globals :-) -Daniel
Signature · 3 lines
Daniel Vetter Software Engineer, Intel Corporation http://blog.ffwll.ch
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
In reply to Jani NikulaAm 25.01.2017 um 11:24 schrieb Jani Nikula <[email protected]>:
Quoted 1 line
Markus, thanks for your work on this.
Thanks for your comments!
Quoted 2 lines
Excuse me for my bluntness, but I think changing everything in a single commit, or even a few commits, is strictly not acceptable.
OK, I understand.
Quoted 6 lines
When I changed *small* things in
scripts/kernel-doc, I would make htmldocs before and after the change, and recursively diff the produced output to ensure there were no surprises. We already have enough documentation that a manual eyeballing of the output is simply not sufficient to ensure things don't break.
Quoted 7 lines
The diff in output between before and after this series? 160k lines of unified diff without context ('diff -u0 -r old new | wc -l').
Many of the changes are improvements on the result, such as using proper <div> tags for function parameter lists etc., but clearly changing the output should be independent of changing the parser, so we have some chance of validating the parser.
Hmm ... I try to sort my thoughts on this:
The both parser are generating reST output. We have tested reST output so it should be enough to compare the reST from the old one with the new one ... at least theoretical.
But the problem I see here is, that the perl script generates a reST output which I can't use. As an example we can take a look at the man-page builder I shipped in the series.
https://www.mail-archive.com/[email protected]/msg09017.html
In the commit message there is a small example:
<section docname="basics ...>
<title>get_sd_load_idx</title>
<kernel_doc_man manpage="get_sd_load_idx.9"/>
...
<desc desctype="function" domain="c"....>
<desc_signature ....>
<desc_type>int</desc_type>
...You see that it has <section> tag with childs <title/>, <kernel_doc_man/> and so on. This structured markup is used by builders, they navigate through the structured tree picking up nodes and spit out some man-page html, or whatever builder it is.
ATM the perl parser generates a reST output which does not have such a structured tree, so the builder can't navigate in.
So, what I mean is, the new parser has to generate a complete different reST output and thats why we can't compare the perl parser with python one on a reST basis ... and if reST is different, HTML is different :(
So we do not have any chance to track regression when switching from the old to the new parser.
Thats are my thoughts on this topic, may be you have a solution for this?
Quoted 6 lines
Quoted 3 lines
Ideally at the time of merging, we would be able to build the docs with *either* kerneldoc.
I'd be fine with switching over in a single commit that doesn't drastically change the output.
One solution might be to improve the reST output of the perl script first, so that it produce something which has a structure and we all can agree on (short: reST output is the reference, ATM the reference need some improvements)
If this is a way we like to go, I can send a patch for the perl script, so that we can commit one a reST reference.
Quoted 11 lines
A drop-in replacement. But that's not the
case here.Quoted 3 lines
- I'll have to try it out to see how noisy it is. I'm not opposed to stricter checks; indeed, they could be a good thing. But we might want to have an option so we can cut back on the noise by default.
The increase in 'make htmldocs' build log was from 1521 to 2791 lines in my tree. Arguably there was useful extra diagnosis, but some of it was the printouts of long lists of definitions that were not found, one per line. So it could be condensed without losing info too.
Yes, this was just a 1:1 merge from my POC, there are a lot of things which could be meld down. ATM, for me it is important to get a feedback on the functionalities and concepts of kernel-doc apps (RFC).
Quoted 9 lines
On to performance. With the default build options the new system was noticeably slower than the current one, with a 50% increase on my machine. But what really caught me by surprise was that passing SPHINXOPTS=-j5 to parallelize worked better on the current system, making the new one a whopping 70% slower. Of course, the argument is that the proposed parser does more and is better, but due to the monolithic change it's impossible to pinpoint the culprit or do a proper cost/benefit analysis on this. Again, this calls for a more broken down series of patches to make the changes.
Ups, I have to look closer ... I thought the py-solution is faster since it does not for processes and does some caching.
Quoted 11 lines
Finally, while I'd love to see
scripts/kernel-docgo, I do have to ask if changing roughly 3k lines of Perl to roughly 3k lines of Python (*) really makes everything better? They both still parse everything using a large pile of regular expressions and a clunky state machine. When I look at the code, I'm afraid I do not get that liberating feeling of throwing out old junk in favor of something small or elegant or even obviously more maintainable than the old one. The new one offers more features, but repeatedly we face the problem that it's all lumped in together with the parser change. We should be able to look at the parser change and the other improvements separately.
Quoted 3 lines
That said, perhaps having an elegant parser (perhaps based on a compiler plugin) is incompatible with the idea of making it a bug-for-bug drop-in replacement of the old one, and it's something we need to think about.
Before I started implementing the parser I thought about separating parsing from generating reST. I played a bit with pycparser
https://github.com/eliben/pycparser
but I realized that the coverage of those parser might be not enough for the kernel sources. At this time you mentioned sparse. I haven't had time to at sparse but I guess that this is the tool.
-- Markus --
Quoted 17 lines
All in all I think the message should be clear: this needs to be split into small, incremental changes. Just like we do everything in the kernel.
BR,
Jani.(*) Please do not get hung up on these numbers. The Python version does
more in some ways, but adds more deps such as fspath that's not included in the figures, and the Perl version outputs more formats. It's not an apples to apples comparison. Let's just say they are somewhere in the same ballpark.Signature · 1 line
Jani Nikula, Intel Open Source Technology Center
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
Quoted 28 lines · Markus Heiser
Am 25.01.2017 um 11:24 schrieb Jani Nikula <[email protected]>:
Quoted 1 line
Markus, thanks for your work on this.
Thanks for your comments!
Quoted 2 lines
Excuse me for my bluntness, but I think changing everything in a single commit, or even a few commits, is strictly not acceptable.
OK, I understand.
Quoted 6 lines
When I changed *small* things in
scripts/kernel-doc, I would make htmldocs before and after the change, and recursively diff the produced output to ensure there were no surprises. We already have enough documentation that a manual eyeballing of the output is simply not sufficient to ensure things don't break.Quoted 7 lines
The diff in output between before and after this series? 160k lines of unified diff without context ('diff -u0 -r old new | wc -l').
Many of the changes are improvements on the result, such as using proper <div> tags for function parameter lists etc., but clearly changing the output should be independent of changing the parser, so we have some chance of validating the parser.
Hmm ... I try to sort my thoughts on this:
Quoted 7 lines
The both parser are generating reST output. We have tested reST output so it should be enough to compare the reST from the old one with the new one ... at least theoretical.
But the problem I see here is, that the perl script generates a reST output which I can't use. As an example we can take a look at the man-page builder I shipped in the series.
Sorry, I still don't understand *why* you can't use the same rst. Your explanation seems to relate to man pages, but man pages come *afterwards*, and are a separate improvement. I know you talk about lack of proper structure and all that, but *why* can it strictly not be used, if the *current* rst clearly can be used?
BR,
Jani.
Quoted 121 lines
https://www.mail-archive.com/[email protected]/msg09017.html
In the commit message there is a small example:
<section docname="basics ...>
<title>get_sd_load_idx</title> <kernel_doc_man manpage="get_sd_load_idx.9"/> ... <desc desctype="function" domain="c"....> <desc_signature ....> <desc_type>int</desc_type> ...You see that it has <section> tag with childs <title/>, <kernel_doc_man/> and so on. This structured markup is used by builders, they navigate through the structured tree picking up nodes and spit out some man-page html, or whatever builder it is.
ATM the perl parser generates a reST output which does not have such a structured tree, so the builder can't navigate in.
So, what I mean is, the new parser has to generate a complete different reST output and thats why we can't compare the perl parser with python one on a reST basis ... and if reST is different, HTML is different :(
So we do not have any chance to track regression when switching from the old to the new parser.
Thats are my thoughts on this topic, may be you have a solution for this?
Quoted 6 lines
Quoted 3 lines
Ideally at the time of merging, we would be able to build the docs with *either* kerneldoc.
I'd be fine with switching over in a single commit that doesn't drastically change the output.
One solution might be to improve the reST output of the perl script first, so that it produce something which has a structure and we all can agree on (short: reST output is the reference, ATM the reference need some improvements)
If this is a way we like to go, I can send a patch for the perl script, so that we can commit one a reST reference.
Quoted 11 lines
A drop-in replacement. But that's not the
case here.Quoted 3 lines
- I'll have to try it out to see how noisy it is. I'm not opposed to stricter checks; indeed, they could be a good thing. But we might want to have an option so we can cut back on the noise by default.
The increase in 'make htmldocs' build log was from 1521 to 2791 lines in my tree. Arguably there was useful extra diagnosis, but some of it was the printouts of long lists of definitions that were not found, one per line. So it could be condensed without losing info too.
Yes, this was just a 1:1 merge from my POC, there are a lot of things which could be meld down. ATM, for me it is important to get a feedback on the functionalities and concepts of kernel-doc apps (RFC).
Quoted 9 lines
On to performance. With the default build options the new system was noticeably slower than the current one, with a 50% increase on my machine. But what really caught me by surprise was that passing SPHINXOPTS=-j5 to parallelize worked better on the current system, making the new one a whopping 70% slower. Of course, the argument is that the proposed parser does more and is better, but due to the monolithic change it's impossible to pinpoint the culprit or do a proper cost/benefit analysis on this. Again, this calls for a more broken down series of patches to make the changes.
Ups, I have to look closer ... I thought the py-solution is faster since it does not for processes and does some caching.
Quoted 11 lines
Finally, while I'd love to see
scripts/kernel-docgo, I do have to ask if changing roughly 3k lines of Perl to roughly 3k lines of Python (*) really makes everything better? They both still parse everything using a large pile of regular expressions and a clunky state machine. When I look at the code, I'm afraid I do not get that liberating feeling of throwing out old junk in favor of something small or elegant or even obviously more maintainable than the old one. The new one offers more features, but repeatedly we face the problem that it's all lumped in together with the parser change. We should be able to look at the parser change and the other improvements separately.Quoted 3 lines
That said, perhaps having an elegant parser (perhaps based on a compiler plugin) is incompatible with the idea of making it a bug-for-bug drop-in replacement of the old one, and it's something we need to think about.
Before I started implementing the parser I thought about separating parsing from generating reST. I played a bit with pycparser
https://github.com/eliben/pycparser
but I realized that the coverage of those parser might be not enough for the kernel sources. At this time you mentioned sparse. I haven't had time to at sparse but I guess that this is the tool.
-- Markus --
Quoted 17 lines
All in all I think the message should be clear: this needs to be split into small, incremental changes. Just like we do everything in the kernel.
BR,
Jani.(*) Please do not get hung up on these numbers. The Python version does
more in some ways, but adds more deps such as fspath that's not included in the figures, and the Perl version outputs more formats. It's not an apples to apples comparison. Let's just say they are somewhere in the same ballpark.Signature · 1 line
Jani Nikula, Intel Open Source Technology Center
Signature · 1 line
Jani Nikula, Intel Open Source Technology Center
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
Am 25.01.2017 um 21:59 schrieb Jani Nikula <[email protected]>:
Quoted 9 lines
Quoted 3 lines
But the problem I see here is, that the perl script generates a reST output which I can't use. As an example we can take a look at the man-page builder I shipped in the series.
Sorry, I still don't understand *why* you can't use the same rst. Your explanation seems to relate to man pages, but man pages come *afterwards*, and are a separate improvement. I know you talk about lack of proper structure and all that, but *why* can it strictly not be used, if the *current* rst clearly can be used?
"afterwards" is the word, that lets me slowly realize, that I have to stop solving the world's problems with one patch. Now I guess how my next patch series has to look like. Thanks! ... for being patient with me.
Before I start, I want to hear your thoughts about the parsing aspect ...
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
That said, perhaps having an elegant parser (perhaps based on a compiler plugin) is incompatible with the idea of making it a bug-for-bug drop-in replacement of the old one, and it's something we need to think about.
Did you have any suggestions?
-- Markus --
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
Quoted 12 lines · Markus Heiser
Am 25.01.2017 um 21:59 schrieb Jani Nikula <[email protected]>:
Quoted 9 lines
Quoted 3 lines
But the problem I see here is, that the perl script generates a reST output which I can't use. As an example we can take a look at the man-page builder I shipped in the series.
Sorry, I still don't understand *why* you can't use the same rst. Your explanation seems to relate to man pages, but man pages come *afterwards*, and are a separate improvement. I know you talk about lack of proper structure and all that, but *why* can it strictly not be used, if the *current* rst clearly can be used?
Quoted 4 lines
"afterwards" is the word, that lets me slowly realize, that I have to stop solving the world's problems with one patch. Now I guess how my next patch series has to look like. Thanks! ... for being patient with me.
Indeed, we change the world, one small incremental patch at a time. ;)
Quoted 9 lines
Before I start, I want to hear your thoughts about the parsing aspect ...
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
That said, perhaps having an elegant parser (perhaps based on a compiler plugin) is incompatible with the idea of making it a bug-for-bug drop-in replacement of the old one, and it's something we need to think about.
Did you have any suggestions?
The perfect is the enemy of the good... If we see that the current Perl parser just rewritten in Python really is an improvement, we should consider it. But as I wrote, there are still issues there, like performance, that we need to understand. I'll mostly defer to Jon on this.
But before we plunge on with this, I would like to see at least some research into reusing existing parsers which I would expect are plentiful. We may end up deciding regexps are the way to go after all, but I'd like it to be based on a decision rather than a lack of one. And we might decide to look at this as a later improvement instead as well.
I've looked at python-clang myself, but it's a huge dependency, and it's not trivial to cover all the things that the current one does with that. I'd dismiss that.
BR,
Jani.
Signature · 1 line
Jani Nikula, Intel Open Source Technology Center
Jonathan Corbet
maintainerRe: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
In reply to Markus HeiserQuoted 8 lines · On Wed, 25 Jan 2017 20:07:47 +0100 Markus Heiser <[email protected]>…
So, what I mean is, the new parser has to generate a complete different reST output and thats why we can't compare the perl parser with python one on a reST basis ... and if reST is different, HTML is different :(
So we do not have any chance to track regression when switching from the old to the new parser.
Thats are my thoughts on this topic, may be you have a solution for this?
The solution, I think, is as has been described by others in the thread. I'll make a try at it now :)
The objectives in a patch set are something like this:
- Replace the kernel-doc utility with one that is easier to maintain and enhance.
- Add various enhancements (man pages, linting, better output, better parsing) to the docs build system.
What everybody is complaining about here is that all of that stuff is being thrown in together into a single patch set. We don't do things that way because long experience says we'll create a mess that takes a long time to straighten out again.
As I said before, I'm very much amenable to the idea of replacing kernel-doc with one that is easier to work with. I haven't yet had the time to look closely enough at yours to have an opinion on whether it does that or not. But, assuming it does, the proper way to make this change is to provide a new kerneldoc that behaves as closely to the old one as possible, with an absolute minimum of output changes.
Doing it that way probably seems like a pretty annoying request. But it lets us validate its basic mechanics and be confident that we won't break the docs build in weird ways. It also lets us evaluate the question of whether the replacement has merit in its own right, independent of any other change we want to make. Give me a new kerneldoc that passes those tests, and I'll happily merge it. (I have some sympathy with the idea that we should look into other parsers, but I would not hold up a new kerneldoc that passed those tests on this basis alone.)
*Then* we can start adding the other stuff, which, from a first look, appears to be stuff that we very much want to have. Each one of those, too, should stand alone and pass muster on its own merits. Changes presented in this way could be merged in the same development cycle if they are ready, but we need to be able to evaluate each one separately.
Does this make sense? We all really appreciate the work you're doing here, we're just asking that it be done in an evolutionary manner so we can evaluate it properly.
Thanks,
jon
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
Quoted 4 lines · Jonathan Corbet
Give me a new kerneldoc that passes those tests, and I'll happily merge it. (I have some sympathy with the idea that we should look into other parsers, but I would not hold up a new kerneldoc that passed those tests on this basis alone.)
I'll just note in passing that having another parser that actually works for our needs might be a pink unicorn pony. It might exist, it might not, and someone would have to put in the hours to try to find it, tame it, and bring it to the kernel. But it would be awesome to have. Switching to a homebrew Python parser first does not preclude a unicorn hunt later.
BR,
Jani.
Signature · 1 line
Jani Nikula, Intel Open Source Technology Center
Re: [RFC PATCH v1 2/6] kernel-doc: replace kernel-doc perl parser with a pure python one (WIP)
Am 26.01.2017 um 20:26 schrieb Jani Nikula <[email protected]>:
Quoted 6 lines · Jonathan Corbet
Quoted 4 lines
Give me a new kerneldoc that passes those tests, and I'll happily merge it. (I have some sympathy with the idea that we should look into other parsers, but I would not hold up a new kerneldoc that passed those tests on this basis alone.)
Quoted 6 lines
I'll just note in passing that having another parser that actually works for our needs might be a pink unicorn pony. It might exist, it might not, and someone would have to put in the hours to try to find it, tame it, and bring it to the kernel. But it would be awesome to have. Switching to a homebrew Python parser first does not preclude a unicorn hunt later.
Here are my experience about parsing C code and kernel-doc comments.
The reg-expressions divide into two parts:
a.) those parsing "C sources", catching up function prototypes, structs etc. and
b.) those parsing "kernel-doc comments", catching up attribute descriptions,
cross references etc.
When I developed the py-version in my POC I realized that the reg-expressions parsing C sources (a.) aren't so bad. They have a long history and are well tested against kernel' sources (As far as I remember, I added only one regexp more to match function prototypes).
This was the time where I looked at some other parsing tool and after a day I throw away the idea of using a external parser tool, first.
Most problems I have had, was parsing the kernel-doc markup itself. E.g. the ambiguous attribute markup "* @foo: lorem" and its cross-ref "@foo". The latter syntax is ambiguous, it fails mostly on new-lines and with strings like "[email protected]".
When I looked at the whole sources, I also realized that we have two flavors of kernel-doc markups.
b.1) Those from traditional DocBook where whitespaces aren't markups and
b.2) those which has been rewritten with reST markup in, where whitespaces are a
part of the reST.
But this was only the half truth of b.2) : the 'new' markup did not only consists of pure reST markup. For convince it is a mix of kernel-doc markup and reST markup (e.g. remember the cross-ref mentioned above).
I suppose that we will never completely get rid off traditional (b.1), since this means; changing the whole kernel source ;)
At that time I wanted to implement a parser which has the ability to handle both flavors. A (undocumented) 'vintage' mode an the user-documented 'reST' mode. But what is the criteria to switch from one mode to the other? For this I made a primitive assumption: every C source file which is used in a ".. kernel-doc::" directive has to be marked up with the modern reST flavor.
ATM, the py-version of kernel-doc implements the same state machine as the perl one and the modes are implemented in the same state machine (not perfect but it worked for me first, suppose we can make it better).
I remember about a very early discussion we had about those modes and I know that it doesn't find friends in the community (at that time). May be today we have more experience and new ideas.
I really like to see (to work on) a parser with we can parse the whole kernel source and generate reST from.
What do you think, is it a bloody idea?
Thanks!
-- Markus --
RFC PATCH 3/6 kernel-doc: add kerneldoc-lint command
In reply to Markus Heiserthis patch adds a command to lint kernel-doc comments.::
scripts/kerneldoc-lint --help
The lint check include (only) kernel-doc rules described at [1]. It does not check against reST (sphinx-doc) markup used in the kernel-doc comments. Since reST markups could include depencies to the build- context (e.g. open/closed refs) only a sphinx-doc build can check the reST markup in the context of the document it builds.
With 'kerneldoc-lint' command you can check a single file or a whole folder, e.g:
scripts/kerneldoc-lint include/drm
...
scripts/kerneldoc-lint include/media/media-device.h
The lint-implementation is a part of the parser module (kernel_doc.py). The comandline implementation consist only of a argument parser ('opts') which calls the kernel-doc parser with a 'NullTranslator'.::
parser = kerneldoc.Parser(opts, kerneldoc.NullTranslator())
Latter is also a small example of how-to implement kernel-doc applications with the kernel-doc parser architecture.
[1] https://www.kernel.org/doc/html/latest/doc-guide/kernel-doc.html#writing-kernel-doc-comments
--- Documentation/sphinx/lint.py | 121 +++++++++++++++++++++++++++++++++++++++++++ scripts/kerneldoc-lint | 11 ++++ 2 files changed, 132 insertions(+) create mode 100755 Documentation/sphinx/lint.py create mode 100755 scripts/kerneldoc-lint
Documentation/sphinx/lint.py new file +121 -0
@@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8; mode: python -*- +# pylint: disable=C0103 + +u""" + lint + ~~~~ + + Implementation of the ``kerneldoc-lint`` command. + + :copyright: Copyright (C) 2016 Markus Heiser + :license: GPL Version 2, June 1991 see Linux/COPYING for details. + + The ``kernel-doclint`` command *lints* documentation from Linux kernel's + source code comments, see ``--help``:: + + $ kernel-lintdoc --help + + .. note:: + + The kernel-lintdoc command is under construction, no stable release + yet. The command-line arguments might be changed/extended in the near + future.""" + +# ------------------------------------------------------------------------------ +# imports +# ------------------------------------------------------------------------------ + +import sys +import argparse + +#import six + +from fspath import FSPath +import kernel_doc as kerneldoc + +# ------------------------------------------------------------------------------ +# config +# ------------------------------------------------------------------------------ + +MSG = lambda msg: sys.__stderr__.write("INFO : %s\n" % msg) +ERR = lambda msg: sys.__stderr__.write("ERROR: %s\n" % msg) +FATAL = lambda msg: sys.__stderr__.write("FATAL: %s\n" % msg) + +epilog = u"""This implementation of uses the kernel-doc parser +from the linuxdoc extension, for detail informations read +http://return42.github.io/sphkerneldoc/books/kernel-doc-HOWTO""" + +# ------------------------------------------------------------------------------ +def main(): +# ------------------------------------------------------------------------------ + + CLI = argparse.ArgumentParser( + description = ("Lint *kernel-doc* comments from source code") + , epilog = epilog + , formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + CLI.add_argument( + "srctree" + , help = "File or folder of source code." + , type = lambda x: FSPath(x).ABSPATH) + + CLI.add_argument( + "--sloppy" + , action = "store_true" + , help = "Sloppy linting, reports only severe errors.") + + CLI.add_argument( + "--markup" + , choices = ["reST", "kernel-doc"] + , default = "reST" + , help = ( + "Markup of the comments. Change this option only if you know" + " what you do. New comments must be marked up with reST!")) + + CLI.add_argument( + "--verbose", "-v" + , action = "store_true" + , help = "verbose output with log messages to stderr" ) + + CLI.add_argument( + "--debug" + , action = "store_true" + , help = "debug messages to stderr" ) + + CMD = CLI.parse_args() + kerneldoc.DEBUG = CMD.debug + kerneldoc.VERBOSE = CMD.verbose + + if not CMD.srctree.EXISTS: + ERR("%s does not exists or is not a folder" % CMD.srctree) + sys.exit(42) + + if CMD.srctree.ISDIR: + for fname in CMD.srctree.reMatchFind(r"^.*\.[ch]$"): + if fname.startswith(CMD.srctree/"Documentation"): + continue + lintdoc_file(fname, CMD) + else: + fname = CMD.srctree + CMD.srctree = CMD.srctree.DIRNAME + lintdoc_file(fname, CMD) + +# ------------------------------------------------------------------------------ +def lintdoc_file(fname, CMD): +# ------------------------------------------------------------------------------ + + fname = fname.relpath(CMD.srctree) + opts = kerneldoc.ParseOptions( + rel_fname = fname + , src_tree = CMD.srctree + , verbose_warn = not (CMD.sloppy) + , markup = CMD.markup ) + + parser = kerneldoc.Parser(opts, kerneldoc.NullTranslator()) + try: + parser.parse() + except Exception: # pylint: disable=W0703 + FATAL("kernel-doc comments markup of %s seems buggy / can't parse" % opts.fname) + return +
scripts/kerneldoc-lint new file +11 -0
@@ -0,0 +1,11 @@ +#!/usr/bin/python + +import sys +from os import path + +linuxdoc = path.abspath(path.join(path.dirname(__file__), '..')) +linuxdoc = path.join(linuxdoc, 'Documentation', 'sphinx') +sys.path.insert(0, linuxdoc) + +import lint +lint.main()
Signature · 1 line
2.7.4
Re: [RFC PATCH v1 3/6] kernel-doc: add kerneldoc-lint command
Quoted 21 lines · Markus Heiser
this patch adds a command to lint kernel-doc comments.::
scripts/kerneldoc-lint --helpThe lint check include (only) kernel-doc rules described at [1]. It does not check against reST (sphinx-doc) markup used in the kernel-doc comments. Since reST markups could include depencies to the build- context (e.g. open/closed refs) only a sphinx-doc build can check the reST markup in the context of the document it builds.
With 'kerneldoc-lint' command you can check a single file or a whole folder, e.g:
scripts/kerneldoc-lintinclude/drm
...
scripts/kerneldoc-lintinclude/media/media-device.hThe lint-implementation is a part of the parser module (
kernel_doc.py). The comandline implementation consist only of a argument parser ('opts') which calls the kernel-doc parser with a 'NullTranslator'.::
Quoted 8 lines
parser =
kerneldoc.Parser(opts, kerneldoc.NullTranslator())Latter is also a small example of how-to implement kernel-doc applications with the kernel-doc parser architecture.
[1] https://www.kernel.org/doc/html/latest/doc-guide/kernel-doc.html#writing-kernel-doc-comments
Signed-off-by Markus Heiser <[email protected]>
Didn't we have a patch from Jani to gives us a make target doing this? I think that'd be even neater ...
-Daniel
Quoted 154 lines
--- Documentation/sphinx/lint.py | 121 +++++++++++++++++++++++++++++++++++++++++++ scripts/kerneldoc-lint | 11 ++++ 2 files changed, 132 insertions(+) create mode 100755 Documentation/sphinx/lint.py create mode 100755 scripts/kerneldoc-lintDocumentation/sphinx/lint.py new file +121
-0@@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8; mode: python -*- +# pylint: disable=C0103 + +u""" + lint + ~~~~ + + Implementation of the ``kerneldoc-lint`` command. + + :copyright: Copyright (C) 2016 Markus Heiser + :license: GPL Version 2, June 1991 see Linux/COPYING for details. + + The ``kernel-doclint`` command *lints* documentation from Linux kernel's + source code comments, see ``--help``:: + + $ kernel-lintdoc --help + + .. note:: + + The kernel-lintdoc command is under construction, no stable release + yet. The command-line arguments might be changed/extended in the near + future.""" + +# ------------------------------------------------------------------------------ +# imports +# ------------------------------------------------------------------------------ + +import sys +import argparse + +#import six + +from fspath import FSPath +import kernel_doc as kerneldoc + +# ------------------------------------------------------------------------------ +# config +# ------------------------------------------------------------------------------ + +MSG = lambda msg: sys.__stderr__.write("INFO : %s\n" % msg) +ERR = lambda msg: sys.__stderr__.write("ERROR: %s\n" % msg) +FATAL = lambda msg: sys.__stderr__.write("FATAL: %s\n" % msg) + +epilog = u"""This implementation of uses the kernel-doc parser +from the linuxdoc extension, for detail informations read +http://return42.github.io/sphkerneldoc/books/kernel-doc-HOWTO""" + +# ------------------------------------------------------------------------------ +def main(): +# ------------------------------------------------------------------------------ + + CLI = argparse.ArgumentParser( + description = ("Lint *kernel-doc* comments from source code") + , epilog = epilog + , formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + CLI.add_argument( + "srctree" + , help = "File or folder of source code." + , type = lambda x: FSPath(x).ABSPATH) + + CLI.add_argument( + "--sloppy" + , action = "store_true" + , help = "Sloppy linting, reports only severe errors.") + + CLI.add_argument( + "--markup" + , choices = ["reST", "kernel-doc"] + , default = "reST" + , help = ( + "Markup of the comments. Change this option only if you know" + " what you do. New comments must be marked up with reST!")) + + CLI.add_argument( + "--verbose", "-v" + , action = "store_true" + , help = "verbose output with log messages to stderr" ) + + CLI.add_argument( + "--debug" + , action = "store_true" + , help = "debug messages to stderr" ) + + CMD = CLI.parse_args() + kerneldoc.DEBUG = CMD.debug + kerneldoc.VERBOSE = CMD.verbose + + if not CMD.srctree.EXISTS: + ERR("%s does not exists or is not a folder" % CMD.srctree) + sys.exit(42) + + if CMD.srctree.ISDIR: + for fname in CMD.srctree.reMatchFind(r"^.*\.[ch]$"): + if fname.startswith(CMD.srctree/"Documentation"): + continue + lintdoc_file(fname, CMD) + else: + fname = CMD.srctree + CMD.srctree = CMD.srctree.DIRNAME + lintdoc_file(fname, CMD) + +# ------------------------------------------------------------------------------ +def lintdoc_file(fname, CMD): +# ------------------------------------------------------------------------------ + + fname = fname.relpath(CMD.srctree) + opts = kerneldoc.ParseOptions( + rel_fname = fname + , src_tree = CMD.srctree + , verbose_warn = not (CMD.sloppy) + , markup = CMD.markup ) + + parser = kerneldoc.Parser(opts, kerneldoc.NullTranslator()) + try: + parser.parse() + except Exception: # pylint: disable=W0703 + FATAL("kernel-doc comments markup of %s seems buggy / can't parse" % opts.fname) + return +scripts/kerneldoc-lint new file +11
-0@@ -0,0 +1,11 @@ +#!/usr/bin/python + +import sys +from os import path + +linuxdoc = path.abspath(path.join(path.dirname(__file__), '..')) +linuxdoc = path.join(linuxdoc, 'Documentation', 'sphinx') +sys.path.insert(0, linuxdoc) + +import lint +lint.main()Signature · 1 line
2.7.4
Signature · 3 lines
Daniel Vetter Software Engineer, Intel Corporation http://blog.ffwll.ch
Re: [RFC PATCH v1 3/6] kernel-doc: add kerneldoc-lint command
Quoted 27 lines · Daniel Vetter
Quoted 26 lines · Markus Heiser
this patch adds a command to lint kernel-doc comments.::
scripts/kerneldoc-lint --helpThe lint check include (only) kernel-doc rules described at [1]. It does not check against reST (sphinx-doc) markup used in the kernel-doc comments. Since reST markups could include depencies to the build- context (e.g. open/closed refs) only a sphinx-doc build can check the reST markup in the context of the document it builds.
With 'kerneldoc-lint' command you can check a single file or a whole folder, e.g:
scripts/kerneldoc-lintinclude/drm
...
scripts/kerneldoc-lintinclude/media/media-device.hThe lint-implementation is a part of the parser module (
kernel_doc.py). The comandline implementation consist only of a argument parser ('opts') which calls the kernel-doc parser with a 'NullTranslator'.::parser =
kerneldoc.Parser(opts, kerneldoc.NullTranslator())Latter is also a small example of how-to implement kernel-doc applications with the kernel-doc parser architecture.
Quoted 6 lines
Quoted 3 lines
[1] https://www.kernel.org/doc/html/latest/doc-guide/kernel-doc.html#writing-kernel-doc-comments
Signed-off-by Markus Heiser <[email protected]>Didn't we have a patch from Jani to gives us a make target doing this? I think that'd be even neater ...
Yes, see below. It's simplistic and it has an external dependency, but it got the job done. And it does not depend on Sphinx; it's just a kernel-doc and rst lint, not Sphinx lint. Whether that's a good or a bad thing is debatable.
Anyway, I do think the approach of making 'make CHECK=the-tool C=1' work is what we should aim at. Markus' patch could probably be made to do that by accepting the same arguments that are passed to compilers.
BR,
Jani.
Quoted 1 line
From
96e780dea5fe0cafcb500d7e16a16f85416dea6dMon Sep 17 00:00:00 2001
From: Jani Nikula <[email protected]>
Date: Tue, 31 May 2016 18:11:33 +0300
Subject: [PATCH] kernel-doc-rst-lint: add tool to check kernel-doc and rst
correctness
Organization: Intel Finland Oy - BIC 0357606-4 - Westendinkatu 7, 02160 Espoo
Cc: Jani Nikula <[email protected]>
Simple kernel-doc and reStructuredText lint tool that can be used independently and as a kernel build CHECK tool to validate kernel-doc comments.
Independent usage:
$ kernel-doc-rst-lint FILE
Kernel CHECK usage:
$ make CHECK=scripts/kernel-doc-rst-lint C=1 # (or C=2)
Depends on docutils and the rst-lint package
https://pypi.python.org/pypi/restructuredtext_lint
--- scripts/kernel-doc-rst-lint | 106 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100755 scripts/kernel-doc-rst-lint
scripts/kernel-doc-rst-lint new file +106 -0
@@ -0,0 +1,106 @@ +#!/usr/bin/env python +# coding=utf-8 +# +# Copyright © 2016 Intel Corporation +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice (including the next +# paragraph) shall be included in all copies or substantial portions of the +# Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# Authors: +# Jani Nikula <[email protected]> +# +# Simple kernel-doc and reStructuredText lint tool that can be used +# independently and as a kernel build CHECK tool to validate kernel-doc +# comments. +# +# Independent usage: +# $ kernel-doc-rst-lint FILE +# +# Kernel CHECK usage: +# $ make CHECK=scripts/kernel-doc-rst-lint C=1 # (or C=2) +# +# Depends on docutils and the rst-lint package +# https://pypi.python.org/pypi/restructuredtext_lint +# + +import os +import subprocess +import sys + +from docutils.parsers.rst import directives +from docutils.parsers.rst import Directive +from docutils.parsers.rst import roles +from docutils import nodes, statemachine +import restructuredtext_lint + +class DummyDirective(Directive): + required_argument = 1 + optional_arguments = 0 + option_spec = { } + has_content = True + + def run(self): + return [] + +# Fake the Sphinx C Domain directives and roles +directives.register_directive('c:function', DummyDirective) +directives.register_directive('c:type', DummyDirective) +roles.register_generic_role('c:func', nodes.emphasis) +roles.register_generic_role('c:type', nodes.emphasis) + +# We accept but ignore parameters to be compatible with how the kernel build +# invokes CHECK. +if len(sys.argv) < 2: + sys.stderr.write('usage: kernel-doc-rst-lint [IGNORED OPTIONS] FILE\n'); + sys.exit(1) + +infile = sys.argv[len(sys.argv) - 1] +cmd = ['scripts/kernel-doc', '-rst', infile] + +try: + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) + out, err = p.communicate() + + # python2 needs conversion to unicode. + # python3 with universal_newlines=True returns strings. + if sys.version_info.major < 3: + out, err = unicode(out, 'utf-8'), unicode(err, 'utf-8') + + # kernel-doc errors + sys.stderr.write(err) + if p.returncode != 0: + sys.exit(p.returncode) + + # restructured text errors + lines = statemachine.string2lines(out, 8, convert_whitespace=True) + lint_errors = restructuredtext_lint.lint(out, infile) + for error in lint_errors: + # Ignore INFO + if error.level <= 1: + continue + + print(error.source + ': ' + error.type + ': ' + error.full_message) + if error.line is not None: + print('Context:') + print('\t' + lines[error.line - 1]) + print('\t' + lines[error.line]) + +except Exception as e: + sys.stderr.write(str(e) + '\n') + sys.exit(1)
Signature · 8 lines
2.1.4 -- Jani Nikula, Intel Open Source Technology Center
Re: [RFC PATCH v1 3/6] kernel-doc: add kerneldoc-lint command
Am 25.01.2017 um 09:21 schrieb Jani Nikula <[email protected]>:
Quoted 7 lines
Yes, see below. It's simplistic and it has an external dependency, but it got the job done. And it does not depend on Sphinx; it's just a kernel-doc and rst lint, not Sphinx lint. Whether that's a good or a bad thing is debatable.
Anyway, I do think the approach of making 'make CHECK=the-tool C=1' work is what we should aim at.
Ah, cool ... didn't know C=1 before .. I will consider it in v2.
Quoted 2 lines
Markus' patch could probably be made to do
that by accepting the same arguments that are passed to compilers.
Is this what you mean?
make W=n [targets] Enable extra gcc checks, n=1,2,3 where
1: warnings which may be relevant and do not occur too often 2: warnings which occur quite often but may still be relevant 3: more obscure warnings, can most likely be ignored Multiple levels can be combined with W=12 or W=123
Thanks!
--Markus--
Re: [RFC PATCH v1 3/6] kernel-doc: add kerneldoc-lint command
Quoted 9 lines · Markus Heiser
Am 25.01.2017 um 09:21 schrieb Jani Nikula <[email protected]>:
Quoted 7 lines
Yes, see below. It's simplistic and it has an external dependency, but it got the job done. And it does not depend on Sphinx; it's just a kernel-doc and rst lint, not Sphinx lint. Whether that's a good or a bad thing is debatable.
Anyway, I do think the approach of making 'make CHECK=the-tool C=1' work is what we should aim at.
Quoted 6 lines
Ah, cool ... didn't know C=1 before .. I will consider it in v2.
Quoted 2 lines
Markus' patch could probably be made to do
that by accepting the same arguments that are passed to compilers.Is this what you mean?
No. The build system passes the same (or roughly the same) arguments to the CHECK tool as it passes to the compiler. You need to handle them in your tool, possibly just ignoring them if they're not relevant.
BR,
Jani.
Quoted 11 lines
make W=n [targets] Enable extra gcc checks, n=1,2,3 where
1: warnings which may be relevant and do not occur too often 2: warnings which occur quite often but may still be relevant 3: more obscure warnings, can most likely be ignored Multiple levels can be combined with W=12 or W=123Thanks!
--Markus--
Signature · 1 line
Jani Nikula, Intel Open Source Technology Center
RFC PATCH 4/6 kernel-doc: insert TODOs on kernel-doc errors
In reply to Markus HeiserThe rstKernelDoc.py sphinx-extensions inserts '.. todo::' on errors. With this patch sphinx.ext.todo extension [1] is activated. This is similar to what we know from DocBook's *Oops* functionality of the kernel-doc perl script [2].
I added this functionality (only) to the subproject, to left the main build untouched. E.g. run::
make SPHINXDIRS="driver-api" htmldocs
open the HTML output and scroll down to see those *Oops* (TODO) boxes.
The *Oops* in the HTML output helps authors to find rough errors and increase the quality of the documentation. ATM there are to many errors (false positives) and it needs some discussion. Take this as a starting point.
[1] http://www.sphinx-doc.org/en/stable/ext/todo.html
[2] http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/scripts/kernel-doc#n3073
--- Documentation/admin-guide/conf.py | 2 ++ Documentation/admin-guide/index.rst | 2 ++ Documentation/conf.py | 3 ++- Documentation/core-api/conf.py | 2 ++ Documentation/core-api/index.rst | 2 ++ Documentation/dev-tools/conf.py | 2 ++ Documentation/dev-tools/index.rst | 2 ++ Documentation/doc-guide/conf.py | 2 ++ Documentation/doc-guide/index.rst | 2 ++ Documentation/driver-api/conf.py | 2 ++ Documentation/driver-api/index.rst | 2 ++ Documentation/gpu/conf.py | 2 ++ Documentation/gpu/index.rst | 2 ++ Documentation/media/conf.py | 2 ++ Documentation/media/index.rst | 2 ++ Documentation/process/conf.py | 2 ++ Documentation/process/index.rst | 2 ++ Documentation/security/conf.py | 2 ++ Documentation/security/index.rst | 9 +++++++++ 19 files changed, 45 insertions(+), 1 deletion(-)
Documentation/admin-guide/conf.py +2 -0
@@ -8,3 +8,5 @@ latex_documents = [ ('index', 'linux-user.tex', 'Linux Kernel User Documentation', 'The kernel development community', 'manual'), ] + +todo_include_todos = True
Documentation/admin-guide/index.rst +2 -0
@@ -67,3 +67,5 @@ configure specific aspects of kernel behavior to your liking. ======= * :ref:`genindex` + + .. todolist::
Documentation/conf.py +2 -1
@@ -34,7 +34,8 @@ from load_config import loadConfig # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = ['rstKernelDoc', 'rstFlatTable', 'kernel_include', 'cdomain' ] +extensions = ['rstKernelDoc', 'rstFlatTable', 'kernel_include', 'cdomain', + 'sphinx.ext.todo' ] # The name of the math extension changed on Sphinx 1.4 if major == 1 and minor > 3:
Documentation/core-api/conf.py +2 -0
@@ -8,3 +8,5 @@ latex_documents = [ ('index', 'core-api.tex', project, 'The kernel development community', 'manual'), ] + +todo_include_todos = True
Documentation/core-api/index.rst +2 -0
@@ -32,3 +32,5 @@ Interfaces for kernel debugging ======= * :ref:`genindex` + + .. todolist::
Documentation/dev-tools/conf.py +2 -0
@@ -8,3 +8,5 @@ latex_documents = [ ('index', 'dev-tools.tex', project, 'The kernel development community', 'manual'), ] + +todo_include_todos = True
Documentation/dev-tools/index.rst +2 -0
@@ -31,3 +31,5 @@ whole; patches welcome! ======= * :ref:`genindex` + + .. todolist::
Documentation/doc-guide/conf.py +2 -0
@@ -8,3 +8,5 @@ latex_documents = [ ('index', 'kernel-doc-guide.tex', 'Linux Kernel Documentation Guide', 'The kernel development community', 'manual'), ] + +todo_include_todos = True
Documentation/doc-guide/index.rst +2 -0
@@ -18,3 +18,5 @@ How to write kernel documentation ======= * :ref:`genindex` + + .. todolist::
Documentation/driver-api/conf.py +2 -0
@@ -8,3 +8,5 @@ latex_documents = [ ('index', 'driver-api.tex', project, 'The kernel development community', 'manual'), ] + +todo_include_todos = True
Documentation/driver-api/index.rst +2 -0
@@ -38,3 +38,5 @@ available subsections can be seen below. ======= * :ref:`genindex` + + .. todolist::
Documentation/gpu/conf.py +2 -0
@@ -8,3 +8,5 @@ latex_documents = [ ('index', 'gpu.tex', project, 'The kernel development community', 'manual'), ] + +todo_include_todos = True
Documentation/gpu/index.rst +2 -0
@@ -20,3 +20,5 @@ Linux GPU Driver Developer's Guide ======= * :ref:`genindex` + + .. todolist::
Documentation/media/conf.py +2 -0
@@ -8,3 +8,5 @@ latex_documents = [ ('index', 'media.tex', 'Linux Media Subsystem Documentation', 'The kernel development community', 'manual'), ] + +todo_include_todos = True
Documentation/media/index.rst +2 -0
@@ -17,3 +17,5 @@ Contents: ======= * :ref:`genindex` + + .. todolist::
Documentation/process/conf.py +2 -0
@@ -8,3 +8,5 @@ latex_documents = [ ('index', 'process.tex', 'Linux Kernel Development Documentation', 'The kernel development community', 'manual'), ] + +todo_include_todos = True
Documentation/process/index.rst +2 -0
@@ -55,3 +55,5 @@ lack of a better place. ======= * :ref:`genindex` + + .. todolist::
Documentation/security/conf.py +2 -0
@@ -6,3 +6,5 @@ latex_documents = [ ('index', 'security.tex', project, 'The kernel development community', 'manual'), ] + +todo_include_todos = True
Documentation/security/index.rst +9 -0
@@ -5,3 +5,12 @@ Security documentation .. toctree:: tpm/index + +.. only:: subproject and html + + Indices + ======= + + * :ref:`genindex` + + .. todolist::
Signature · 1 line
2.7.4
RFC PATCH 5/6 kernel-doc: add kerneldoc-src2rst command
In reply to Markus Heiserthis patch adds a command to auto-generate documentation from kernel's source tree.::
scripts/kerneldoc-src2rst --help
E.g. to autodoc the kernel's ./include folder use::
scripts/kerneldoc-src2rst ./include /tmp/test123
Quoted 1 line
From the resulting reST-doctree you can build HTML rendered output like
the one in [1]. I use it to see, if patches on the kernel_doc.py parser cause a regression (compare reST before/after the patch). Autodoc the whole source tree takes a long time. To speed up, the src2rst module uses multiprocessing from [2]. This means, it consumes all your CPUs. If you don't want this, use option '--threads=n'.
[1] https://h2626237.stratoserver.net/kernel/linux_src_doc/index.html
[2] https://docs.python.org/3.6/library/multiprocessing.html
--- Documentation/sphinx/src2rst.py | 229 ++++++++++++++++++++++++++++++++++++++++ scripts/kerneldoc-src2rst | 11 ++ 2 files changed, 240 insertions(+) create mode 100755 Documentation/sphinx/src2rst.py create mode 100755 scripts/kerneldoc-src2rst
Documentation/sphinx/src2rst.py new file +229 -0
@@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8; mode: python -*- +# pylint: disable=C0103 + +u""" + src2rst + ~~~~~~~ + + Implementation of the ``kerneldoc-src2rst`` command. + + :copyright: Copyright (C) 2016 Markus Heiser + :license: GPL Version 2, June 1991 see Linux/COPYING for details. + + The ``kerneldoc-src2rst`` command extracts documentation from Linux kernel's + source code comments, see ``--help``:: + + $ kerneldoc-src2rst --help + +""" + +# ------------------------------------------------------------------------------ +# imports +# ------------------------------------------------------------------------------ + +import sys +import argparse +import re +import multiprocessing + +import six + +from fspath import FSPath, OS_ENV +import kernel_doc as kerneldoc + +# ------------------------------------------------------------------------------ +# config +# ------------------------------------------------------------------------------ + +MARKUP = "kernel-doc" # "reST" +MSG = lambda msg: sys.__stderr__.write("INFO : %s\n" % msg) +ERR = lambda msg: sys.__stderr__.write("ERROR: %s\n" % msg) +FATAL = lambda msg: sys.__stderr__.write("FATAL: %s\n" % msg) +IGNORE = ['kernel-doc.rst'] + +TEMPLATE_INDEX=u"""\ +.. -*- coding: utf-8; mode: rst -*- + +================================================================================ +%(title)s +================================================================================ + +.. toctree:: + :maxdepth: 1 + +""" + +CMD = None # global used by multiprocessing +SRCTREE = FSPath(OS_ENV.get("srctree", "")) + +# ------------------------------------------------------------------------------ +def main(): +# ------------------------------------------------------------------------------ + + global CMD # pylint: disable=W0603, W0621 + + CLI = argparse.ArgumentParser( + description = ("Parse *kernel-doc* comments from source code") + , formatter_class=argparse.ArgumentDefaultsHelpFormatter) + + CLI.add_argument( + "srctree" + , help = "Folder of source code." + , type = lambda x: FSPath(x).ABSPATH) + + CLI.add_argument( + "doctree" + , help = "Folder to place reST documentation." + , type = lambda x: FSPath(x).ABSPATH) + + CLI.add_argument( + "--sloppy" + , action = "store_true" + , help = "Sloppy comment check, reports only severe errors.") + + CLI.add_argument( + "--force" + , action = "store_true" + , help = "Don't stop if doctree exists.") + + CLI.add_argument( + "--threads" + , type = int + , default = multiprocessing.cpu_count() + , help = "Use up to n threads.") + + CLI.add_argument( + "--markup" + , choices = ["reST", "kernel-doc", "auto"] + , default = "auto" + , help = ( + "Markup of the comments. Change this option only if you know" + " what you do. New comments must be marked up with reST!")) + + CMD = CLI.parse_args() + + if not CMD.srctree.EXISTS: + ERR("%s does not exists." % CMD.srctree) + sys.exit(42) + + if not CMD.srctree.ISDIR: + ERR("%s is not a folder." % CMD.srctree) + sys.exit(42) + + if not CMD.force and CMD.doctree.EXISTS: + ERR("%s is in the way, remove it first" % CMD.doctree) + sys.exit(42) + + CMD.rst_files = set() + if CMD.markup == "auto": + CMD.rst_files = docgrep(SRCTREE/"Documentation") + + pool = multiprocessing.Pool(CMD.threads) + pool.map(autodoc_file, gather_filenames(CMD)) + pool.close() + pool.join() + + insert_index_files(CMD.doctree) + +# ------------------------------------------------------------------------------ +def gather_filenames(cmd): +# ------------------------------------------------------------------------------ + MSG("gather files ...") + + for fname in cmd.srctree.reMatchFind(r"^.*\.[ch]$"): + if fname.startswith(CMD.srctree/"Documentation"): + continue + yield fname + +# ------------------------------------------------------------------------------ +def autodoc_file(fname): +# ------------------------------------------------------------------------------ + + fname = fname.relpath(CMD.srctree) + markup = CMD.markup + + if CMD.markup == "kernel-doc" and fname in CMD.rst_files: + markup = "reST" + + opts = kerneldoc.ParseOptions( + rel_fname = fname + , src_tree = CMD.srctree + , verbose_warn = not (CMD.sloppy) + , markup = markup ) + + parser = kerneldoc.Parser(opts, kerneldoc.NullTranslator()) + try: + parser.parse() + except Exception: # pylint: disable=W0703 + FATAL("kernel-doc markup of %s seems buggy / can't parse" % opts.fname) + return + + if not parser.ctx.dump_storage: + # no kernel-doc comments found + MSG("parsed: NONE comments: %s" % opts.fname) + return + + MSG("parsed: %4d comments: %s" % (len(parser.ctx.dump_storage), opts.fname)) + + try: + rst = six.StringIO() + translator = kerneldoc.ReSTTranslator() + opts.out = rst + + # First try to output reST, this might fail, because the kernel-doc + # parser part is to tollerant ("bad lines", "function name and function + # declaration are different", etc ...). + parser.parse_dump_storage(translator=translator) + + outFile = CMD.doctree / fname.replace(".","_") + ".rst" + outFile.DIRNAME.makedirs() + with outFile.openTextFile(mode="w") as out: + out.write(rst.getvalue()) + + except Exception: # pylint: disable=W0703 + FATAL("kernel-doc markup of %s seems buggy / can't parse" % opts.fname) + return + +# ------------------------------------------------------------------------------ +def insert_index_files(folder): +# ------------------------------------------------------------------------------ + + for folder, dirnames, filenames in folder.walk(): + ctx = kerneldoc.Container( title = folder.FILENAME ) + dirnames.sort() + filenames.sort() + indexFile = folder / "index.rst" + MSG("create index: %s" % indexFile) + with indexFile.openTextFile(mode="w") as index: + index.write(TEMPLATE_INDEX % ctx) + for d in dirnames: + index.write(" %s/index\n" % d.FILENAME) + for f in filenames: + if f.FILENAME == "index": + continue + index.write(" %s\n" % f.FILENAME) + +# ------------------------------------------------------------------------------ +def docgrep(folder): +# ------------------------------------------------------------------------------ + + # Hackisch script to grep all '.. kernel-doc::' directives. The assumption + # is, that comments from the source files used in those directives are + # allready migratetd to the reST format. I guess that (ATM) 95-99% of the + # comments are not migrated, those will be parsed with the old kernel-doc + # comment style introduced by the old DocBook toolchain. + + pat = re.compile(r"^\s*\.\.\s+kernel-doc::\s*([^\s]+)\s*$") + out = set() + for rstFile in folder.reMatchFind(r".*\.rst"): + if rstFile.BASENAME in IGNORE: + continue + #print(rstFile) + with rstFile.openTextFile() as f: + for l in f: + match = pat.search(l) + if match: + #print(match.group(1)) + out.add(match.group(1)) + return sorted(out)
scripts/kerneldoc-src2rst new file +11 -0
@@ -0,0 +1,11 @@ +#!/usr/bin/python + +import sys +from os import path + +linuxdoc = path.abspath(path.join(path.dirname(__file__), '..')) +linuxdoc = path.join(linuxdoc, 'Documentation', 'sphinx') +sys.path.insert(0, linuxdoc) + +import src2rst +src2rst.main()
Signature · 1 line
2.7.4
RFC PATCH 6/6 kernel-doc: add man page builder (target mandocs)
In reply to Markus HeiserThis patch brings man page build we already know from the DocBook toolchain. It adds a sphinx extension 'manKernelDoc' which consists of:
* '.. kernel-doc-man::' : directive implemented in class KernelDocMan
* 'kernel_doc_man' : *invisible* node
* 'kernel-doc-man' : an alternative man builder (class KernelDocManBuilder)
The 'kernel-doc-man' builder produces manual pages in the groff format. It is a *man* page sphinx-builder mainly written to generate manual pages from kernel-doc comments by:
* scanning the master doc-tree for sections marked with the '.. kernel-doc-man::' directive and build manual pages for theses sections.
* reorder / rename (sub-) sections according to the conventions that should be employed when writing man pages for the Linux man-pages project, see man-pages(7) ... (has to be discussed if we really need such a reordering).
A few words about How the 'kernel-doc-man' builder an the kernel-doc parser work together:
It starts with the kernel-doc parser which builds small reST-doctrees from the comments of functions, structs and so on. The kernel-doc parser has an option (see 'kernel_doc.ParseOptions.man_sect=n') which can be activated e.g. on a *per* kernel-doc directive::
.. kernel-doc:: include/linux/debugobjects.h
:man-sect: 9
or alternative it can be activated globally with::
kernel_doc_mansect = 9
in the conf.py (this is what this patch does).
With option 'man_sect=n' the kernel-doc parser inserts *invisible* 'kernel_doc_man' nodes in the reST-doctree. Here is a view on such a doctree where the <kernel_doc_man/> is a child of the <section> describing 'get_sd_load_idx' function::
<section docname="basics" dupnames="get_sd_load_idx"
ids="get-sd-load-idx id86" names="get_sd_load_idx">
<title>get_sd_load_idx</title>
<kernel_doc_man manpage="get_sd_load_idx.9"/>
...
<desc desctype="function" domain="c" noindex="False" objtype="function">
<desc_signature first="False" ids="c.get_sd_load_idx" names="c.get_sd_load_idx">
<desc_type>int</desc_type>
...After the whole doctree is build by sphinx-build it is stored in the env and the builder takes place. These *invisible* 'kernel_doc_man' nodes will be ignored by all builders (html, pdf etc.) except the 'kernel-doc-man' builder. The later picks up those nodes from the doctree and builds a manpage from the surrounding <section>.
--- Documentation/Makefile.sphinx | 5 +- Documentation/conf.py | 3 +- Documentation/media/Makefile | 1 + Documentation/sphinx/manKernelDoc.py | 408 +++++++++++++++++++++++++++++++++++ 4 files changed, 415 insertions(+), 2 deletions(-) create mode 100755 Documentation/sphinx/manKernelDoc.py
Documentation/Makefile.sphinx +4 -1
@@ -89,10 +89,12 @@ epubdocs: xmldocs: @$(foreach var,$(SPHINXDIRS),$(call loop_cmd,sphinx,xml,$(var),xml,$(var))) +mandocs: + @$(foreach var,$(SPHINXDIRS),$(call loop_cmd,sphinx,kernel-doc-man,$(var),man,$(var))) + # no-ops for the Sphinx toolchain sgmldocs: psdocs: -mandocs: installmandocs: cleandocs:
@@ -106,6 +108,7 @@ dochelp: @echo ' htmldocs - HTML' @echo ' latexdocs - LaTeX' @echo ' pdfdocs - PDF' + @echo ' mandocs - man pages' @echo ' epubdocs - EPUB' @echo ' xmldocs - XML' @echo ' cleandocs - clean all generated files'
Documentation/conf.py +2 -1
@@ -35,7 +35,7 @@ from load_config import loadConfig # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['rstKernelDoc', 'rstFlatTable', 'kernel_include', 'cdomain', - 'sphinx.ext.todo' ] + 'manKernelDoc', 'sphinx.ext.todo' ] # The name of the math extension changed on Sphinx 1.4 if major == 1 and minor > 3:
@@ -508,6 +508,7 @@ pdf_documents = [ # line arguments. kernel_doc_verbose_warn = False kernel_doc_raise_error = False +kernel_doc_mansect = 9 # ------------------------------------------------------------------------------ # Since loadConfig overwrites settings from the global namespace, it has to be
Documentation/media/Makefile +1 -0
@@ -103,6 +103,7 @@ html: all epub: all xml: all latex: $(IMGPDF) all +kernel-doc-man: $(BUILDDIR) ${TARGETS} clean: -rm -f $(DOTTGT) $(IMGTGT) ${TARGETS} 2>/dev/null
Documentation/sphinx/manKernelDoc.py new file +408 -0
408 lines not on this page · raw message
Signature · 1 line
2.7.4