xref: /linux/scripts/lib/abi/abi_parser.py (revision 2a21d80dfb4135b4766d8ff3231a3ea1c19bcc83)
1#!/usr/bin/env python3
2# pylint: disable=R0902,R0903,R0911,R0912,R0913,R0914,R0915,R0917,C0302
3# Copyright(c) 2025: Mauro Carvalho Chehab <mchehab@kernel.org>.
4# SPDX-License-Identifier: GPL-2.0
5
6"""
7Parse ABI documentation and produce results from it.
8"""
9
10from argparse import Namespace
11import logging
12import os
13import re
14
15from pprint import pformat
16from random import randrange, seed
17
18# Import Python modules
19
20from helpers import AbiDebug, ABI_DIR
21
22
23class AbiParser:
24    """Main class to parse ABI files"""
25
26    TAGS = r"(what|where|date|kernelversion|contact|description|users)"
27    XREF = r"(?:^|\s|\()(\/(?:sys|config|proc|dev|kvd)\/[^,.:;\)\s]+)(?:[,.:;\)\s]|\Z)"
28
29    def __init__(self, directory, logger=None,
30                 enable_lineno=False, show_warnings=True, debug=0):
31        """Stores arguments for the class and initialize class vars"""
32
33        self.directory = directory
34        self.enable_lineno = enable_lineno
35        self.show_warnings = show_warnings
36        self.debug = debug
37
38        if not logger:
39            self.log = logging.getLogger("get_abi")
40        else:
41            self.log = logger
42
43        self.data = {}
44        self.what_symbols = {}
45        self.file_refs = {}
46        self.what_refs = {}
47
48        # Ignore files that contain such suffixes
49        self.ignore_suffixes = (".rej", ".org", ".orig", ".bak", "~")
50
51        # Regular expressions used on parser
52        self.re_abi_dir = re.compile(r"(.*)" + ABI_DIR)
53        self.re_tag = re.compile(r"(\S+)(:\s*)(.*)", re.I)
54        self.re_valid = re.compile(self.TAGS)
55        self.re_start_spc = re.compile(r"(\s*)(\S.*)")
56        self.re_whitespace = re.compile(r"^\s+")
57
58        # Regular used on print
59        self.re_what = re.compile(r"(\/?(?:[\w\-]+\/?){1,2})")
60        self.re_escape = re.compile(r"([\.\x01-\x08\x0e-\x1f\x21-\x2f\x3a-\x40\x7b-\xff])")
61        self.re_unprintable = re.compile(r"([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xff]+)")
62        self.re_title_mark = re.compile(r"\n[\-\*\=\^\~]+\n")
63        self.re_doc = re.compile(r"Documentation/(?!devicetree)(\S+)\.rst")
64        self.re_abi = re.compile(r"(Documentation/ABI/)([\w\/\-]+)")
65        self.re_xref_node = re.compile(self.XREF)
66
67    def warn(self, fdata, msg, extra=None):
68        """Displays a parse error if warning is enabled"""
69
70        if not self.show_warnings:
71            return
72
73        msg = f"{fdata.fname}:{fdata.ln}: {msg}"
74        if extra:
75            msg += "\n\t\t" + extra
76
77        self.log.warning(msg)
78
79    def add_symbol(self, what, fname, ln=None, xref=None):
80        """Create a reference table describing where each 'what' is located"""
81
82        if what not in self.what_symbols:
83            self.what_symbols[what] = {"file": {}}
84
85        if fname not in self.what_symbols[what]["file"]:
86            self.what_symbols[what]["file"][fname] = []
87
88        if ln and ln not in self.what_symbols[what]["file"][fname]:
89            self.what_symbols[what]["file"][fname].append(ln)
90
91        if xref:
92            self.what_symbols[what]["xref"] = xref
93
94    def _parse_line(self, fdata, line):
95        """Parse a single line of an ABI file"""
96
97        new_what = False
98        new_tag = False
99        content = None
100
101        match = self.re_tag.match(line)
102        if match:
103            new = match.group(1).lower()
104            sep = match.group(2)
105            content = match.group(3)
106
107            match = self.re_valid.search(new)
108            if match:
109                new_tag = match.group(1)
110            else:
111                if fdata.tag == "description":
112                    # New "tag" is actually part of description.
113                    # Don't consider it a tag
114                    new_tag = False
115                elif fdata.tag != "":
116                    self.warn(fdata, f"tag '{fdata.tag}' is invalid", line)
117
118        if new_tag:
119            # "where" is Invalid, but was a common mistake. Warn if found
120            if new_tag == "where":
121                self.warn(fdata, "tag 'Where' is invalid. Should be 'What:' instead")
122                new_tag = "what"
123
124            if new_tag == "what":
125                fdata.space = None
126
127                if content not in self.what_symbols:
128                    self.add_symbol(what=content, fname=fdata.fname, ln=fdata.ln)
129
130                if fdata.tag == "what":
131                    fdata.what.append(content.strip("\n"))
132                else:
133                    if fdata.key:
134                        if "description" not in self.data.get(fdata.key, {}):
135                            self.warn(fdata, f"{fdata.key} doesn't have a description")
136
137                        for w in fdata.what:
138                            self.add_symbol(what=w, fname=fdata.fname,
139                                            ln=fdata.what_ln, xref=fdata.key)
140
141                    fdata.label = content
142                    new_what = True
143
144                    key = "abi_" + content.lower()
145                    fdata.key = self.re_unprintable.sub("_", key).strip("_")
146
147                    # Avoid duplicated keys but using a defined seed, to make
148                    # the namespace identical if there aren't changes at the
149                    # ABI symbols
150                    seed(42)
151
152                    while fdata.key in self.data:
153                        char = randrange(0, 51) + ord("A")
154                        if char > ord("Z"):
155                            char += ord("a") - ord("Z") - 1
156
157                        fdata.key += chr(char)
158
159                    if fdata.key and fdata.key not in self.data:
160                        self.data[fdata.key] = {
161                            "what": [content],
162                            "file": [fdata.file_ref],
163                            "path": fdata.ftype,
164                            "line_no": fdata.ln,
165                        }
166
167                    fdata.what = self.data[fdata.key]["what"]
168
169                self.what_refs[content] = fdata.key
170                fdata.tag = new_tag
171                fdata.what_ln = fdata.ln
172
173                if fdata.nametag["what"]:
174                    t = (content, fdata.key)
175                    if t not in fdata.nametag["symbols"]:
176                        fdata.nametag["symbols"].append(t)
177
178                return
179
180            if fdata.tag and new_tag:
181                fdata.tag = new_tag
182
183                if new_what:
184                    fdata.label = ""
185
186                    if "description" in self.data[fdata.key]:
187                        self.data[fdata.key]["description"] += "\n\n"
188
189                    if fdata.file_ref not in self.data[fdata.key]["file"]:
190                        self.data[fdata.key]["file"].append(fdata.file_ref)
191
192                    if self.debug == AbiDebug.WHAT_PARSING:
193                        self.log.debug("what: %s", fdata.what)
194
195                if not fdata.what:
196                    self.warn(fdata, "'What:' should come first:", line)
197                    return
198
199                if new_tag == "description":
200                    fdata.space = None
201
202                    if content:
203                        sep = sep.replace(":", " ")
204
205                        c = " " * len(new_tag) + sep + content
206                        c = c.expandtabs()
207
208                        match = self.re_start_spc.match(c)
209                        if match:
210                            # Preserve initial spaces for the first line
211                            fdata.space = match.group(1)
212                            content = match.group(2) + "\n"
213
214                self.data[fdata.key][fdata.tag] = content
215
216            return
217
218        # Store any contents before tags at the database
219        if not fdata.tag and "what" in fdata.nametag:
220            fdata.nametag["description"] += line
221            return
222
223        if fdata.tag == "description":
224            content = line.expandtabs()
225
226            if self.re_whitespace.sub("", content) == "":
227                self.data[fdata.key][fdata.tag] += "\n"
228                return
229
230            if fdata.space is None:
231                match = self.re_start_spc.match(content)
232                if match:
233                    # Preserve initial spaces for the first line
234                    fdata.space = match.group(1)
235
236                    content = match.group(2) + "\n"
237            else:
238                if content.startswith(fdata.space):
239                    content = content[len(fdata.space):]
240
241                else:
242                    fdata.space = ""
243
244            if fdata.tag == "what":
245                w = content.strip("\n")
246                if w:
247                    self.data[fdata.key][fdata.tag].append(w)
248            else:
249                self.data[fdata.key][fdata.tag] += content
250            return
251
252        content = line.strip()
253        if fdata.tag:
254            if fdata.tag == "what":
255                w = content.strip("\n")
256                if w:
257                    self.data[fdata.key][fdata.tag].append(w)
258            else:
259                self.data[fdata.key][fdata.tag] += "\n" + content.rstrip("\n")
260            return
261
262        # Everything else is error
263        if content:
264            self.warn(fdata, "Unexpected content", line)
265
266    def parse_file(self, fname, path, basename):
267        """Parse a single file"""
268
269        ref = f"abi_file_{path}_{basename}"
270        ref = self.re_unprintable.sub("_", ref).strip("_")
271
272        # Store per-file state into a namespace variable. This will be used
273        # by the per-line parser state machine and by the warning function.
274        fdata = Namespace
275
276        fdata.fname = fname
277        fdata.name = basename
278
279        pos = fname.find(ABI_DIR)
280        if pos > 0:
281            f = fname[pos:]
282        else:
283            f = fname
284
285        fdata.file_ref = (f, ref)
286        self.file_refs[f] = ref
287
288        fdata.ln = 0
289        fdata.what_ln = 0
290        fdata.tag = ""
291        fdata.label = ""
292        fdata.what = []
293        fdata.key = None
294        fdata.xrefs = None
295        fdata.space = None
296        fdata.ftype = path.split("/")[0]
297
298        fdata.nametag = {}
299        fdata.nametag["what"] = [f"File {path}/{basename}"]
300        fdata.nametag["type"] = "File"
301        fdata.nametag["path"] = fdata.ftype
302        fdata.nametag["file"] = [fdata.file_ref]
303        fdata.nametag["line_no"] = 1
304        fdata.nametag["description"] = ""
305        fdata.nametag["symbols"] = []
306
307        self.data[ref] = fdata.nametag
308
309        if self.debug & AbiDebug.WHAT_OPEN:
310            self.log.debug("Opening file %s", fname)
311
312        with open(fname, "r", encoding="utf8", errors="backslashreplace") as fp:
313            for line in fp:
314                fdata.ln += 1
315
316                self._parse_line(fdata, line)
317
318            if "description" in fdata.nametag:
319                fdata.nametag["description"] = fdata.nametag["description"].lstrip("\n")
320
321            if fdata.key:
322                if "description" not in self.data.get(fdata.key, {}):
323                    self.warn(fdata, f"{fdata.key} doesn't have a description")
324
325                for w in fdata.what:
326                    self.add_symbol(what=w, fname=fname, xref=fdata.key)
327
328    def _parse_abi(self, root=None):
329        """Internal function to parse documentation ABI recursively"""
330
331        if not root:
332            root = self.directory
333
334        with os.scandir(root) as obj:
335            for entry in obj:
336                name = os.path.join(root, entry.name)
337
338                if entry.is_dir():
339                    self._parse_abi(name)
340                    continue
341
342                if not entry.is_file():
343                    continue
344
345                basename = os.path.basename(name)
346
347                if basename == "README":
348                    continue
349
350                if basename.startswith("."):
351                    continue
352
353                if basename.endswith(self.ignore_suffixes):
354                    continue
355
356                path = self.re_abi_dir.sub("", os.path.dirname(name))
357
358                self.parse_file(name, path, basename)
359
360    def parse_abi(self, root=None):
361        """Parse documentation ABI"""
362
363        self._parse_abi(root)
364
365        if self.debug & AbiDebug.DUMP_ABI_STRUCTS:
366            self.log.debug(pformat(self.data))
367
368    def desc_txt(self, desc):
369        """Print description as found inside ABI files"""
370
371        desc = desc.strip(" \t\n")
372
373        return desc + "\n\n"
374
375    def desc_rst(self, desc):
376        """Enrich ReST output by creating cross-references"""
377
378        # Remove title markups from the description
379        # Having titles inside ABI files will only work if extra
380        # care would be taken in order to strictly follow the same
381        # level order for each markup.
382        desc = self.re_title_mark.sub("\n\n", "\n" + desc)
383        desc = desc.rstrip(" \t\n").lstrip("\n")
384
385        # Python's regex performance for non-compiled expressions is a lot
386        # than Perl, as Perl automatically caches them at their
387        # first usage. Here, we'll need to do the same, as otherwise the
388        # performance penalty is be high
389
390        new_desc = ""
391        for d in desc.split("\n"):
392            if d == "":
393                new_desc += "\n"
394                continue
395
396            # Use cross-references for doc files where needed
397            d = self.re_doc.sub(r":doc:`/\1`", d)
398
399            # Use cross-references for ABI generated docs where needed
400            matches = self.re_abi.findall(d)
401            for m in matches:
402                abi = m[0] + m[1]
403
404                xref = self.file_refs.get(abi)
405                if not xref:
406                    # This may happen if ABI is on a separate directory,
407                    # like parsing ABI testing and symbol is at stable.
408                    # The proper solution is to move this part of the code
409                    # for it to be inside sphinx/kernel_abi.py
410                    self.log.info("Didn't find ABI reference for '%s'", abi)
411                else:
412                    new = self.re_escape.sub(r"\\\1", m[1])
413                    d = re.sub(fr"\b{abi}\b", f":ref:`{new} <{xref}>`", d)
414
415            # Seek for cross reference symbols like /sys/...
416            # Need to be careful to avoid doing it on a code block
417            if d[0] not in [" ", "\t"]:
418                matches = self.re_xref_node.findall(d)
419                for m in matches:
420                    # Finding ABI here is more complex due to wildcards
421                    xref = self.what_refs.get(m)
422                    if xref:
423                        new = self.re_escape.sub(r"\\\1", m)
424                        d = re.sub(fr"\b{m}\b", f":ref:`{new} <{xref}>`", d)
425
426            new_desc += d + "\n"
427
428        return new_desc + "\n\n"
429
430    def doc(self, output_in_txt=False, show_symbols=True, show_file=True,
431            filter_path=None):
432        """Print ABI at stdout"""
433
434        part = None
435        for key, v in sorted(self.data.items(),
436                             key=lambda x: (x[1].get("type", ""),
437                                            x[1].get("what"))):
438
439            wtype = v.get("type", "Symbol")
440            file_ref = v.get("file")
441            names = v.get("what", [""])
442
443            if wtype == "File":
444                if not show_file:
445                    continue
446            else:
447                if not show_symbols:
448                    continue
449
450            if filter_path:
451                if v.get("path") != filter_path:
452                    continue
453
454            msg = ""
455
456            if wtype != "File":
457                cur_part = names[0]
458                if cur_part.find("/") >= 0:
459                    match = self.re_what.match(cur_part)
460                    if match:
461                        symbol = match.group(1).rstrip("/")
462                        cur_part = "Symbols under " + symbol
463
464                if cur_part and cur_part != part:
465                    part = cur_part
466                    msg += f"{part}\n{"-" * len(part)}\n\n"
467
468                msg += f".. _{key}:\n\n"
469
470                max_len = 0
471                for i in range(0, len(names)):           # pylint: disable=C0200
472                    names[i] = "**" + self.re_escape.sub(r"\\\1", names[i]) + "**"
473
474                    max_len = max(max_len, len(names[i]))
475
476                msg += "+-" + "-" * max_len + "-+\n"
477                for name in names:
478                    msg += f"| {name}" + " " * (max_len - len(name)) + " |\n"
479                    msg += "+-" + "-" * max_len + "-+\n"
480                msg += "\n"
481
482            for ref in file_ref:
483                if wtype == "File":
484                    msg += f".. _{ref[1]}:\n\n"
485                else:
486                    base = os.path.basename(ref[0])
487                    msg += f"Defined on file :ref:`{base} <{ref[1]}>`\n\n"
488
489            if wtype == "File":
490                msg += f"{names[0]}\n{"-" * len(names[0])}\n\n"
491
492            desc = v.get("description")
493            if not desc and wtype != "File":
494                msg += f"DESCRIPTION MISSING for {names[0]}\n\n"
495
496            if desc:
497                if output_in_txt:
498                    msg += self.desc_txt(desc)
499                else:
500                    msg += self.desc_rst(desc)
501
502            symbols = v.get("symbols")
503            if symbols:
504                msg += "Has the following ABI:\n\n"
505
506                for w, label in symbols:
507                    # Escape special chars from content
508                    content = self.re_escape.sub(r"\\\1", w)
509
510                    msg += f"- :ref:`{content} <{label}>`\n\n"
511
512            users = v.get("users")
513            if users and users.strip(" \t\n"):
514                msg += f"Users:\n\t{users.strip("\n").replace('\n', '\n\t')}\n\n"
515
516            ln = v.get("line_no", 1)
517
518            yield (msg, file_ref[0][0], ln)
519
520    def check_issues(self):
521        """Warn about duplicated ABI entries"""
522
523        for what, v in self.what_symbols.items():
524            files = v.get("file")
525            if not files:
526                # Should never happen if the parser works properly
527                self.log.warning("%s doesn't have a file associated", what)
528                continue
529
530            if len(files) == 1:
531                continue
532
533            f = []
534            for fname, lines in sorted(files.items()):
535                if not lines:
536                    f.append(f"{fname}")
537                elif len(lines) == 1:
538                    f.append(f"{fname}:{lines[0]}")
539                else:
540                    f.append(f"{fname} lines {", ".join(str(x) for x in lines)}")
541
542            self.log.warning("%s is defined %d times: %s", what, len(f), "; ".join(f))
543
544    def search_symbols(self, expr):
545        """ Searches for ABI symbols """
546
547        regex = re.compile(expr, re.I)
548
549        found_keys = 0
550        for t in sorted(self.data.items(), key=lambda x: [0]):
551            v = t[1]
552
553            wtype = v.get("type", "")
554            if wtype == "File":
555                continue
556
557            for what in v.get("what", [""]):
558                if regex.search(what):
559                    found_keys += 1
560
561                    kernelversion = v.get("kernelversion", "").strip(" \t\n")
562                    date = v.get("date", "").strip(" \t\n")
563                    contact = v.get("contact", "").strip(" \t\n")
564                    users = v.get("users", "").strip(" \t\n")
565                    desc = v.get("description", "").strip(" \t\n")
566
567                    files = []
568                    for f in v.get("file", ()):
569                        files.append(f[0])
570
571                    what = str(found_keys) + ". " + what
572                    title_tag = "-" * len(what)
573
574                    print(f"\n{what}\n{title_tag}\n")
575
576                    if kernelversion:
577                        print(f"Kernel version:\t\t{kernelversion}")
578
579                    if date:
580                        print(f"Date:\t\t\t{date}")
581
582                    if contact:
583                        print(f"Contact:\t\t{contact}")
584
585                    if users:
586                        print(f"Users:\t\t\t{users}")
587
588                    print(f"Defined on file{'s'[:len(files) ^ 1]}:\t{", ".join(files)}")
589
590                    if desc:
591                        print(f"\n{desc.strip("\n")}\n")
592
593        if not found_keys:
594            print(f"Regular expression /{expr}/ not found.")
595