520cc8
commit f40c7887d3cc9bb0b56576ed9edbe505ff8058c0
520cc8
Author: Florian Weimer <fweimer@redhat.com>
520cc8
Date:   Thu Sep 22 12:10:41 2022 +0200
520cc8
520cc8
    scripts: Extract glibcpp.py from check-obsolete-constructs.py
520cc8
    
520cc8
    The C tokenizer is useful separately.
520cc8
    
520cc8
    Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
520cc8
520cc8
diff --git a/scripts/check-obsolete-constructs.py b/scripts/check-obsolete-constructs.py
520cc8
index 89d21dea6e788783..7c7a092e440a3258 100755
520cc8
--- a/scripts/check-obsolete-constructs.py
520cc8
+++ b/scripts/check-obsolete-constructs.py
520cc8
@@ -24,193 +24,14 @@
520cc8
 """
520cc8
 
520cc8
 import argparse
520cc8
-import collections
520cc8
+import os
520cc8
 import re
520cc8
 import sys
520cc8
 
520cc8
-# Simplified lexical analyzer for C preprocessing tokens.
520cc8
-# Does not implement trigraphs.
520cc8
-# Does not implement backslash-newline in the middle of any lexical
520cc8
-#   item other than a string literal.
520cc8
-# Does not implement universal-character-names in identifiers.
520cc8
-# Treats prefixed strings (e.g. L"...") as two tokens (L and "...")
520cc8
-# Accepts non-ASCII characters only within comments and strings.
520cc8
-
520cc8
-# Caution: The order of the outermost alternation matters.
520cc8
-# STRING must be before BAD_STRING, CHARCONST before BAD_CHARCONST,
520cc8
-# BLOCK_COMMENT before BAD_BLOCK_COM before PUNCTUATOR, and OTHER must
520cc8
-# be last.
520cc8
-# Caution: There should be no capturing groups other than the named
520cc8
-# captures in the outermost alternation.
520cc8
-
520cc8
-# For reference, these are all of the C punctuators as of C11:
520cc8
-#   [ ] ( ) { } , ; ? ~
520cc8
-#   ! != * *= / /= ^ ^= = ==
520cc8
-#   # ##
520cc8
-#   % %= %> %: %:%:
520cc8
-#   & &= &&
520cc8
-#   | |= ||
520cc8
-#   + += ++
520cc8
-#   - -= -- ->
520cc8
-#   . ...
520cc8
-#   : :>
520cc8
-#   < <% <: << <<= <=
520cc8
-#   > >= >> >>=
520cc8
-
520cc8
-# The BAD_* tokens are not part of the official definition of pp-tokens;
520cc8
-# they match unclosed strings, character constants, and block comments,
520cc8
-# so that the regex engine doesn't have to backtrack all the way to the
520cc8
-# beginning of a broken construct and then emit dozens of junk tokens.
520cc8
-
520cc8
-PP_TOKEN_RE_ = re.compile(r"""
520cc8
-    (?P<STRING>        \"(?:[^\"\\\r\n]|\\(?:[\r\n -~]|\r\n))*\")
520cc8
-   |(?P<BAD_STRING>    \"(?:[^\"\\\r\n]|\\[ -~])*)
520cc8
-   |(?P<CHARCONST>     \'(?:[^\'\\\r\n]|\\(?:[\r\n -~]|\r\n))*\')
520cc8
-   |(?P<BAD_CHARCONST> \'(?:[^\'\\\r\n]|\\[ -~])*)
520cc8
-   |(?P<BLOCK_COMMENT> /\*(?:\*(?!/)|[^*])*\*/)
520cc8
-   |(?P<BAD_BLOCK_COM> /\*(?:\*(?!/)|[^*])*\*?)
520cc8
-   |(?P<LINE_COMMENT>  //[^\r\n]*)
520cc8
-   |(?P<IDENT>         [_a-zA-Z][_a-zA-Z0-9]*)
520cc8
-   |(?P<PP_NUMBER>     \.?[0-9](?:[0-9a-df-oq-zA-DF-OQ-Z_.]|[eEpP][+-]?)*)
520cc8
-   |(?P<PUNCTUATOR>
520cc8
-       [,;?~(){}\[\]]
520cc8
-     | [!*/^=]=?
520cc8
-     | \#\#?
520cc8
-     | %(?:[=>]|:(?:%:)?)?
520cc8
-     | &[=&]?
520cc8
-     |\|[=|]?
520cc8
-     |\+[=+]?
520cc8
-     | -[=->]?
520cc8
-     |\.(?:\.\.)?
520cc8
-     | :>?
520cc8
-     | <(?:[%:]|<(?:=|<=?)?)?
520cc8
-     | >(?:=|>=?)?)
520cc8
-   |(?P<ESCNL>         \\(?:\r|\n|\r\n))
520cc8
-   |(?P<WHITESPACE>    [ \t\n\r\v\f]+)
520cc8
-   |(?P<OTHER>         .)
520cc8
-""", re.DOTALL | re.VERBOSE)
520cc8
-
520cc8
-HEADER_NAME_RE_ = re.compile(r"""
520cc8
-    < [^>\r\n]+ >
520cc8
-  | " [^"\r\n]+ "
520cc8
-""", re.DOTALL | re.VERBOSE)
520cc8
-
520cc8
-ENDLINE_RE_ = re.compile(r"""\r|\n|\r\n""")
520cc8
-
520cc8
-# based on the sample code in the Python re documentation
520cc8
-Token_ = collections.namedtuple("Token", (
520cc8
-    "kind", "text", "line", "column", "context"))
520cc8
-Token_.__doc__ = """
520cc8
-   One C preprocessing token, comment, or chunk of whitespace.
520cc8
-   'kind' identifies the token type, which will be one of:
520cc8
-       STRING, CHARCONST, BLOCK_COMMENT, LINE_COMMENT, IDENT,
520cc8
-       PP_NUMBER, PUNCTUATOR, ESCNL, WHITESPACE, HEADER_NAME,
520cc8
-       or OTHER.  The BAD_* alternatives in PP_TOKEN_RE_ are
520cc8
-       handled within tokenize_c, below.
520cc8
-
520cc8
-   'text' is the sequence of source characters making up the token;
520cc8
-       no decoding whatsoever is performed.
520cc8
-
520cc8
-   'line' and 'column' give the position of the first character of the
520cc8
-      token within the source file.  They are both 1-based.
520cc8
-
520cc8
-   'context' indicates whether or not this token occurred within a
520cc8
-      preprocessing directive; it will be None for running text,
520cc8
-      '<null>' for the leading '#' of a directive line (because '#'
520cc8
-      all by itself on a line is a "null directive"), or the name of
520cc8
-      the directive for tokens within a directive line, starting with
520cc8
-      the IDENT for the name itself.
520cc8
-"""
520cc8
-
520cc8
-def tokenize_c(file_contents, reporter):
520cc8
-    """Yield a series of Token objects, one for each preprocessing
520cc8
-       token, comment, or chunk of whitespace within FILE_CONTENTS.
520cc8
-       The REPORTER object is expected to have one method,
520cc8
-       reporter.error(token, message), which will be called to
520cc8
-       indicate a lexical error at the position of TOKEN.
520cc8
-       If MESSAGE contains the four-character sequence '{!r}', that
520cc8
-       is expected to be replaced by repr(token.text).
520cc8
-    """
520cc8
+# Make available glibc Python modules.
520cc8
+sys.path.append(os.path.dirname(os.path.realpath(__file__)))
520cc8
 
520cc8
-    Token = Token_
520cc8
-    PP_TOKEN_RE = PP_TOKEN_RE_
520cc8
-    ENDLINE_RE = ENDLINE_RE_
520cc8
-    HEADER_NAME_RE = HEADER_NAME_RE_
520cc8
-
520cc8
-    line_num = 1
520cc8
-    line_start = 0
520cc8
-    pos = 0
520cc8
-    limit = len(file_contents)
520cc8
-    directive = None
520cc8
-    at_bol = True
520cc8
-    while pos < limit:
520cc8
-        if directive == "include":
520cc8
-            mo = HEADER_NAME_RE.match(file_contents, pos)
520cc8
-            if mo:
520cc8
-                kind = "HEADER_NAME"
520cc8
-                directive = "after_include"
520cc8
-            else:
520cc8
-                mo = PP_TOKEN_RE.match(file_contents, pos)
520cc8
-                kind = mo.lastgroup
520cc8
-                if kind != "WHITESPACE":
520cc8
-                    directive = "after_include"
520cc8
-        else:
520cc8
-            mo = PP_TOKEN_RE.match(file_contents, pos)
520cc8
-            kind = mo.lastgroup
520cc8
-
520cc8
-        text = mo.group()
520cc8
-        line = line_num
520cc8
-        column = mo.start() - line_start
520cc8
-        adj_line_start = 0
520cc8
-        # only these kinds can contain a newline
520cc8
-        if kind in ("WHITESPACE", "BLOCK_COMMENT", "LINE_COMMENT",
520cc8
-                    "STRING", "CHARCONST", "BAD_BLOCK_COM", "ESCNL"):
520cc8
-            for tmo in ENDLINE_RE.finditer(text):
520cc8
-                line_num += 1
520cc8
-                adj_line_start = tmo.end()
520cc8
-            if adj_line_start:
520cc8
-                line_start = mo.start() + adj_line_start
520cc8
-
520cc8
-        # Track whether or not we are scanning a preprocessing directive.
520cc8
-        if kind == "LINE_COMMENT" or (kind == "WHITESPACE" and adj_line_start):
520cc8
-            at_bol = True
520cc8
-            directive = None
520cc8
-        else:
520cc8
-            if kind == "PUNCTUATOR" and text == "#" and at_bol:
520cc8
-                directive = "<null>"
520cc8
-            elif kind == "IDENT" and directive == "<null>":
520cc8
-                directive = text
520cc8
-            at_bol = False
520cc8
-
520cc8
-        # Report ill-formed tokens and rewrite them as their well-formed
520cc8
-        # equivalents, so downstream processing doesn't have to know about them.
520cc8
-        # (Rewriting instead of discarding provides better error recovery.)
520cc8
-        if kind == "BAD_BLOCK_COM":
520cc8
-            reporter.error(Token("BAD_BLOCK_COM", "", line, column+1, ""),
520cc8
-                           "unclosed block comment")
520cc8
-            text += "*/"
520cc8
-            kind = "BLOCK_COMMENT"
520cc8
-        elif kind == "BAD_STRING":
520cc8
-            reporter.error(Token("BAD_STRING", "", line, column+1, ""),
520cc8
-                           "unclosed string")
520cc8
-            text += "\""
520cc8
-            kind = "STRING"
520cc8
-        elif kind == "BAD_CHARCONST":
520cc8
-            reporter.error(Token("BAD_CHARCONST", "", line, column+1, ""),
520cc8
-                           "unclosed char constant")
520cc8
-            text += "'"
520cc8
-            kind = "CHARCONST"
520cc8
-
520cc8
-        tok = Token(kind, text, line, column+1,
520cc8
-                    "include" if directive == "after_include" else directive)
520cc8
-        # Do not complain about OTHER tokens inside macro definitions.
520cc8
-        # $ and @ appear in macros defined by headers intended to be
520cc8
-        # included from assembly language, e.g. sysdeps/mips/sys/asm.h.
520cc8
-        if kind == "OTHER" and directive != "define":
520cc8
-            self.error(tok, "stray {!r} in program")
520cc8
-
520cc8
-        yield tok
520cc8
-        pos = mo.end()
520cc8
+import glibcpp
520cc8
 
520cc8
 #
520cc8
 # Base and generic classes for individual checks.
520cc8
@@ -446,7 +267,7 @@ class HeaderChecker:
520cc8
 
520cc8
         typedef_checker = ObsoleteTypedefChecker(self, self.fname)
520cc8
 
520cc8
-        for tok in tokenize_c(contents, self):
520cc8
+        for tok in glibcpp.tokenize_c(contents, self):
520cc8
             typedef_checker.examine(tok)
520cc8
 
520cc8
 def main():
520cc8
diff --git a/scripts/glibcpp.py b/scripts/glibcpp.py
520cc8
new file mode 100644
520cc8
index 0000000000000000..b44c6a4392dde8ce
520cc8
--- /dev/null
520cc8
+++ b/scripts/glibcpp.py
520cc8
@@ -0,0 +1,212 @@
520cc8
+#! /usr/bin/python3
520cc8
+# Approximation to C preprocessing.
520cc8
+# Copyright (C) 2019-2022 Free Software Foundation, Inc.
520cc8
+# This file is part of the GNU C Library.
520cc8
+#
520cc8
+# The GNU C Library is free software; you can redistribute it and/or
520cc8
+# modify it under the terms of the GNU Lesser General Public
520cc8
+# License as published by the Free Software Foundation; either
520cc8
+# version 2.1 of the License, or (at your option) any later version.
520cc8
+#
520cc8
+# The GNU C Library is distributed in the hope that it will be useful,
520cc8
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
520cc8
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
520cc8
+# Lesser General Public License for more details.
520cc8
+#
520cc8
+# You should have received a copy of the GNU Lesser General Public
520cc8
+# License along with the GNU C Library; if not, see
520cc8
+# <https://www.gnu.org/licenses/>.
520cc8
+
520cc8
+"""
520cc8
+Simplified lexical analyzer for C preprocessing tokens.
520cc8
+
520cc8
+Does not implement trigraphs.
520cc8
+
520cc8
+Does not implement backslash-newline in the middle of any lexical
520cc8
+item other than a string literal.
520cc8
+
520cc8
+Does not implement universal-character-names in identifiers.
520cc8
+
520cc8
+Treats prefixed strings (e.g. L"...") as two tokens (L and "...").
520cc8
+
520cc8
+Accepts non-ASCII characters only within comments and strings.
520cc8
+"""
520cc8
+
520cc8
+import collections
520cc8
+import re
520cc8
+
520cc8
+# Caution: The order of the outermost alternation matters.
520cc8
+# STRING must be before BAD_STRING, CHARCONST before BAD_CHARCONST,
520cc8
+# BLOCK_COMMENT before BAD_BLOCK_COM before PUNCTUATOR, and OTHER must
520cc8
+# be last.
520cc8
+# Caution: There should be no capturing groups other than the named
520cc8
+# captures in the outermost alternation.
520cc8
+
520cc8
+# For reference, these are all of the C punctuators as of C11:
520cc8
+#   [ ] ( ) { } , ; ? ~
520cc8
+#   ! != * *= / /= ^ ^= = ==
520cc8
+#   # ##
520cc8
+#   % %= %> %: %:%:
520cc8
+#   & &= &&
520cc8
+#   | |= ||
520cc8
+#   + += ++
520cc8
+#   - -= -- ->
520cc8
+#   . ...
520cc8
+#   : :>
520cc8
+#   < <% <: << <<= <=
520cc8
+#   > >= >> >>=
520cc8
+
520cc8
+# The BAD_* tokens are not part of the official definition of pp-tokens;
520cc8
+# they match unclosed strings, character constants, and block comments,
520cc8
+# so that the regex engine doesn't have to backtrack all the way to the
520cc8
+# beginning of a broken construct and then emit dozens of junk tokens.
520cc8
+
520cc8
+PP_TOKEN_RE_ = re.compile(r"""
520cc8
+    (?P<STRING>        \"(?:[^\"\\\r\n]|\\(?:[\r\n -~]|\r\n))*\")
520cc8
+   |(?P<BAD_STRING>    \"(?:[^\"\\\r\n]|\\[ -~])*)
520cc8
+   |(?P<CHARCONST>     \'(?:[^\'\\\r\n]|\\(?:[\r\n -~]|\r\n))*\')
520cc8
+   |(?P<BAD_CHARCONST> \'(?:[^\'\\\r\n]|\\[ -~])*)
520cc8
+   |(?P<BLOCK_COMMENT> /\*(?:\*(?!/)|[^*])*\*/)
520cc8
+   |(?P<BAD_BLOCK_COM> /\*(?:\*(?!/)|[^*])*\*?)
520cc8
+   |(?P<LINE_COMMENT>  //[^\r\n]*)
520cc8
+   |(?P<IDENT>         [_a-zA-Z][_a-zA-Z0-9]*)
520cc8
+   |(?P<PP_NUMBER>     \.?[0-9](?:[0-9a-df-oq-zA-DF-OQ-Z_.]|[eEpP][+-]?)*)
520cc8
+   |(?P<PUNCTUATOR>
520cc8
+       [,;?~(){}\[\]]
520cc8
+     | [!*/^=]=?
520cc8
+     | \#\#?
520cc8
+     | %(?:[=>]|:(?:%:)?)?
520cc8
+     | &[=&]?
520cc8
+     |\|[=|]?
520cc8
+     |\+[=+]?
520cc8
+     | -[=->]?
520cc8
+     |\.(?:\.\.)?
520cc8
+     | :>?
520cc8
+     | <(?:[%:]|<(?:=|<=?)?)?
520cc8
+     | >(?:=|>=?)?)
520cc8
+   |(?P<ESCNL>         \\(?:\r|\n|\r\n))
520cc8
+   |(?P<WHITESPACE>    [ \t\n\r\v\f]+)
520cc8
+   |(?P<OTHER>         .)
520cc8
+""", re.DOTALL | re.VERBOSE)
520cc8
+
520cc8
+HEADER_NAME_RE_ = re.compile(r"""
520cc8
+    < [^>\r\n]+ >
520cc8
+  | " [^"\r\n]+ "
520cc8
+""", re.DOTALL | re.VERBOSE)
520cc8
+
520cc8
+ENDLINE_RE_ = re.compile(r"""\r|\n|\r\n""")
520cc8
+
520cc8
+# based on the sample code in the Python re documentation
520cc8
+Token_ = collections.namedtuple("Token", (
520cc8
+    "kind", "text", "line", "column", "context"))
520cc8
+Token_.__doc__ = """
520cc8
+   One C preprocessing token, comment, or chunk of whitespace.
520cc8
+   'kind' identifies the token type, which will be one of:
520cc8
+       STRING, CHARCONST, BLOCK_COMMENT, LINE_COMMENT, IDENT,
520cc8
+       PP_NUMBER, PUNCTUATOR, ESCNL, WHITESPACE, HEADER_NAME,
520cc8
+       or OTHER.  The BAD_* alternatives in PP_TOKEN_RE_ are
520cc8
+       handled within tokenize_c, below.
520cc8
+
520cc8
+   'text' is the sequence of source characters making up the token;
520cc8
+       no decoding whatsoever is performed.
520cc8
+
520cc8
+   'line' and 'column' give the position of the first character of the
520cc8
+      token within the source file.  They are both 1-based.
520cc8
+
520cc8
+   'context' indicates whether or not this token occurred within a
520cc8
+      preprocessing directive; it will be None for running text,
520cc8
+      '<null>' for the leading '#' of a directive line (because '#'
520cc8
+      all by itself on a line is a "null directive"), or the name of
520cc8
+      the directive for tokens within a directive line, starting with
520cc8
+      the IDENT for the name itself.
520cc8
+"""
520cc8
+
520cc8
+def tokenize_c(file_contents, reporter):
520cc8
+    """Yield a series of Token objects, one for each preprocessing
520cc8
+       token, comment, or chunk of whitespace within FILE_CONTENTS.
520cc8
+       The REPORTER object is expected to have one method,
520cc8
+       reporter.error(token, message), which will be called to
520cc8
+       indicate a lexical error at the position of TOKEN.
520cc8
+       If MESSAGE contains the four-character sequence '{!r}', that
520cc8
+       is expected to be replaced by repr(token.text).
520cc8
+    """
520cc8
+
520cc8
+    Token = Token_
520cc8
+    PP_TOKEN_RE = PP_TOKEN_RE_
520cc8
+    ENDLINE_RE = ENDLINE_RE_
520cc8
+    HEADER_NAME_RE = HEADER_NAME_RE_
520cc8
+
520cc8
+    line_num = 1
520cc8
+    line_start = 0
520cc8
+    pos = 0
520cc8
+    limit = len(file_contents)
520cc8
+    directive = None
520cc8
+    at_bol = True
520cc8
+    while pos < limit:
520cc8
+        if directive == "include":
520cc8
+            mo = HEADER_NAME_RE.match(file_contents, pos)
520cc8
+            if mo:
520cc8
+                kind = "HEADER_NAME"
520cc8
+                directive = "after_include"
520cc8
+            else:
520cc8
+                mo = PP_TOKEN_RE.match(file_contents, pos)
520cc8
+                kind = mo.lastgroup
520cc8
+                if kind != "WHITESPACE":
520cc8
+                    directive = "after_include"
520cc8
+        else:
520cc8
+            mo = PP_TOKEN_RE.match(file_contents, pos)
520cc8
+            kind = mo.lastgroup
520cc8
+
520cc8
+        text = mo.group()
520cc8
+        line = line_num
520cc8
+        column = mo.start() - line_start
520cc8
+        adj_line_start = 0
520cc8
+        # only these kinds can contain a newline
520cc8
+        if kind in ("WHITESPACE", "BLOCK_COMMENT", "LINE_COMMENT",
520cc8
+                    "STRING", "CHARCONST", "BAD_BLOCK_COM", "ESCNL"):
520cc8
+            for tmo in ENDLINE_RE.finditer(text):
520cc8
+                line_num += 1
520cc8
+                adj_line_start = tmo.end()
520cc8
+            if adj_line_start:
520cc8
+                line_start = mo.start() + adj_line_start
520cc8
+
520cc8
+        # Track whether or not we are scanning a preprocessing directive.
520cc8
+        if kind == "LINE_COMMENT" or (kind == "WHITESPACE" and adj_line_start):
520cc8
+            at_bol = True
520cc8
+            directive = None
520cc8
+        else:
520cc8
+            if kind == "PUNCTUATOR" and text == "#" and at_bol:
520cc8
+                directive = "<null>"
520cc8
+            elif kind == "IDENT" and directive == "<null>":
520cc8
+                directive = text
520cc8
+            at_bol = False
520cc8
+
520cc8
+        # Report ill-formed tokens and rewrite them as their well-formed
520cc8
+        # equivalents, so downstream processing doesn't have to know about them.
520cc8
+        # (Rewriting instead of discarding provides better error recovery.)
520cc8
+        if kind == "BAD_BLOCK_COM":
520cc8
+            reporter.error(Token("BAD_BLOCK_COM", "", line, column+1, ""),
520cc8
+                           "unclosed block comment")
520cc8
+            text += "*/"
520cc8
+            kind = "BLOCK_COMMENT"
520cc8
+        elif kind == "BAD_STRING":
520cc8
+            reporter.error(Token("BAD_STRING", "", line, column+1, ""),
520cc8
+                           "unclosed string")
520cc8
+            text += "\""
520cc8
+            kind = "STRING"
520cc8
+        elif kind == "BAD_CHARCONST":
520cc8
+            reporter.error(Token("BAD_CHARCONST", "", line, column+1, ""),
520cc8
+                           "unclosed char constant")
520cc8
+            text += "'"
520cc8
+            kind = "CHARCONST"
520cc8
+
520cc8
+        tok = Token(kind, text, line, column+1,
520cc8
+                    "include" if directive == "after_include" else directive)
520cc8
+        # Do not complain about OTHER tokens inside macro definitions.
520cc8
+        # $ and @ appear in macros defined by headers intended to be
520cc8
+        # included from assembly language, e.g. sysdeps/mips/sys/asm.h.
520cc8
+        if kind == "OTHER" and directive != "define":
520cc8
+            self.error(tok, "stray {!r} in program")
520cc8
+
520cc8
+        yield tok
520cc8
+        pos = mo.end()