././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1792676218.855808 pycparser-3.12/0000775000175000017500000000000015266410573013000 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1791207009.659636 pycparser-3.12/LICENSE0000664000175000017500000000300715260723142013776 0ustar00elibenelibenpycparser -- A C parser in Python Copyright (c) 2008-2027, Eli Bendersky All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792675956.5033402 pycparser-3.12/MANIFEST.in0000664000175000017500000000035115266410165014532 0ustar00elibenelibenrecursive-include examples *.c *.h *.py recursive-include tests *.c *.h *.py recursive-include pycparser *.py *.cfg recursive-include utils/fake_libc_include *.h include README.* include LICENSE include OLDER_CHANGES include setup.* ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1769004602.2595415 pycparser-3.12/OLDER_CHANGES0000664000175000017500000002567415134157072014732 0ustar00elibeneliben+ Starting with version 2.22, please use the GitHub UI at https://github.com/eliben/pycparser/tags to compare tags in order to find out what changed. + Version 2.21 (2021.11.06) - Much improved support for C11 (multiple PRs) - Support for parehthesized compount statements (#423) - Support for modern Python versions (3.9 and 3.10) - Fix support for structs with nested enums (#387) - Multiple small bug fixes + Version 2.20 (2020.03.04) - #61: Fix slow backtracking when parsing strings. - #99: Parser for FuncDecl incorrectly sets declname attribute on return type. - #310: Fix crash when file starts with a semicolon. - #313: Fix array type generation. - #314: Fix failed parsing of unnamed function parameters with array dim qualifiers. - #315: Fix pointer type generation. - #324: Fixes for u/l constant integer suffix. - #346: Fix error transforming an empty switch. - #350: Recognize integer multicharacter constants like 'ABCD'. - #363: Fix incorrect AST when parsing offsetof. + Version 2.19 (2018.09.19) - PR #277: Fix parsing of floating point literals - PR #254: Add support for parsing empty structs - PR #240: Fix enum formatting in generated C code (also #216) - PR #222: Add support for #pragma in struct declarations - There are reports that this release doesn't work with Python 2.6 (#281). Please note that the minimal supported version is 2.7; the required versions are listed in the README file. + Version 2.18 (2017.07.04) - PR #161 & #184: Update bundled PLY version to 3.10 - PR #158: Add support for the __int128 type. - PR #169: Handle more tricky TYPEID in declarators. - PR #178: Add columns to the coord of each node + Version 2.17 (2016.10.29) - Again functionality identical to 2.15 and 2.16; the difference is that the tarball now contains Python files with properly set permissions. + Version 2.16 (2016.10.18) - Functionally identical to 2.15, but fixes a packaging problem that caused failed installation (_build_tables wasn't rerun in the pycparser/ dir). + Version 2.15 (2016.10.18) - PR #121: Update bundled PLY version to 3.8 - Issue #117: Fix parsing of extra semi-colons inside structure declarations. - PR #109: Update c_generator to add {} around nested named initializers. - PR #101: Added support for parsing pragmas into the AST. - Additional fake headers and typedefs, manifest fixes (#97, #106, #111). - Testing with Python 3.5 instead of 3.3 now (3.4 and 3.5 are the 3.x versions tested). - PR #145: More complete support for offsetof() - Issue #116: Fix line numbers recorded for empty and compound statements. - Minor performance improvement to the invalid string literal regex. + Version 2.14 (2015.06.09) - Added CParser parameter to specify output directory for generated parsing tables (#84). - Removed lcc's cpp and its license from the distribution. Using lcc's cpp is no longer recommended, now that Clang has binary builds available for Windows. + Version 2.13 (2015.05.12) - Added support for offsetof() the way gcc implements it (special builtin that takes a type as an argument). - Added faked va_* macros (these are expected to come from stdarg.h) - Added a bunch more fake headers and typedefs to support parsing C projects like Git and SQLite without modifications to pycparser. - Added support for empty initializer lists (#79). + Version 2.12 (2015.04.21) - This is a fix release for 2.11; the memory optimization with __slots__ on Coord and AST nodes didn't take weakrefs into account, which broke cffi and its many dependents (issue #76). Fixed by adding __weakref__ to __slots__. + Version 2.11 (2015.04.21) - Add support for C99 6.5.3.7 p7 - qualifiers within array dimensions in function declarations. Started with issue #21 (reported with initial patch by Robin Martinjak). - Issue #27: bug in handling of unified wstring literals. - Issue #28: fix coord reporting for 'for' loops. - Added ``examples/using_gcc_E_libc.py`` to demonstrate how ``gcc -E`` can be used instead of ``cpp`` for preprocessing. - Pull request #64: support keywords like const, volatile, restrict and static in dimensions in array declarations. - Reduce memory usage of AST nodes (issue #72). - Parsing order of nested pointer declarations fixed (issue #68). + Version 2.10 (2013.08.03) - A number of improvements in the handling of typedef-name ambiguities, contributed by Sye van der Veen in GitHub issue #1: * Allow shadowing of types by identifiers in inner scopes. * Allow struct field names to reside in a separate namespace and have the same names as types. * Allow duplicate typedefs in some cases to mimic real compiler behavior. - c_generator error for ExprList in expression context. - Assume default int type for functions whose argument or return types were not specified. - Relax the lexer a bit w.r.t. some integer suffixes and $ in identifier names (which is supported by some other compilers). + Version 2.09.1 (2012.12.29) - No actual functionality changes. - The source distribution was re-packaged to contain the pre-generated Lex and Yacc tables of PLY. + Version 2.09 (2012.12.27) - The pycparser project has moved to Bitbucket. For this version, issue numbers still refer to the old Googlecode project, unless stated otherwise. Starting with the next version all issue numbers will refer to the new Bitbucket project. - pycparser now carries its PLY dependency along. The pycparser/ply directory contains the source of PLY for the currently supported version. This makes distribution and testing easier. - Issue #79: fix generation of new switch/case AST nodes. - Issue #83: fix parsing and C generation to distinguish between initializer lists in declarations and initializing variables with parenthesized comma-separated expressions. - Issue #84: fix C generation for some statements. - Issues #86 and #87: improve location reporting for parse errors. - Issue #89: fix C generation for K&R-style function definitions. + Version 2.08 (2012.08.10) - Issue 73: initial support for #pragma directives. Consume them without errors and ignore (no tokens are returned). Line numbers are preserved. - Issue 68: more correct handling of source files without any actual content. - Issue 69: running all tests will now set appropriate return code. - Better error reporting in case where multiple type specifiers are provided. Also fixes Issue 60. - Issue 63: line endings cleanup for consistent LF ending. - Issues 64 & 65: added some more headers and typedefs to fake includes. - Refactoring the cpp invocation in parse_file into a separate function, which can also be used as a utility. - Issue 74: some Windows include paths were handled incorrectly. + Version 2.07 (2012.06.16) - Issue 54: added an optional parser argument to parse_file - Issue 59: added some more fake headers for C99 - Issue 62: correct coord for Ellipsis nodes - Issue 57: support for C99 hexadecimal float constants - Made running tests that call on 'cpp' a bit more robust. + Version 2.06 (2012.02.04) - Issue 48: gracefully handle parsing of empty files - Issues 49 & 50: handle more escaped chars in paths to #line - "..\..\test.h". - Support for C99 _Complex type. - CGenerator moves from examples/ to pycparser/ as a first-class citizen, and added some fixes to it. examples/c-to-c.py still stays as a convenience wrapper. - Fix problem with parsing a file in which the first statement is just a semicolon. - Improved the AST created for switch statements, making it closer to the semantic meaning than to the grammar. + Version 2.05 (2011.10.16) - Added support for the C99 ``_Bool`` type and ``stdbool.h`` header file - Expanded ``examples/explore_ast.py`` with more details on working with the AST - Relaxed the rules on parsing unnamed struct members (helps parse ``windows.h``) - Bug fixes: * Fixed spacing issue for some type declarations * Issue 47: display empty statements (lone ';') correctly after parsing + Version 2.04 (2011.05.21) - License changed from LGPL to BSD - Bug fixes: * Issue 31: constraining the scope of typedef definitions * Issues 33, 35: fixes for the c-to-c.py example - Added C99 integer types to fake headers - Added unit tests for the c-to-c.py example + Version 2.03 (2011.03.06) - Bug fixes: * Issue 17: empty file-level declarations * Issue 18: empty statements and declarations in functions * Issue 19: anonymous structs & union fields * Issue 23: fix coordinates of Cast nodes - New example added (``examples/c-to-c.py``) for translating ASTs generated by ``pycparser`` back into C code. - ``pycparser`` is now on PyPI (Python Package Index) - Created `FAQ `_ on the ``pycparser`` project page - Removed support for Python 2.5. ``pycparser`` supports Python 2 from 2.6 and on, and Python 3. + Version 2.02 (2010.12.10) * The name of a ``NamedInitializer`` node was turned into a sequence of nodes instead of an attribute, to make it discoverable by the AST node visitor. * Documentation updates + Version 2.01 (04.12.2010) * Removed dependency on YAML. Parsing of the AST node configuration file is done with a simple parser. * Fixed issue 12: installation problems + Version 2.00 (2010.10.31) * Support for C99 (read `this wiki page `_ for more information). + Version 1.08 (2010.10.09) * Bug fixes: + Correct handling of ``do{} ... while`` statements in some cases + Issues 6 & 7: Concatenation of string literals + Issue 9: Support for unnamed bitfields in structs + Version 1.07 (2010.05.18) * Python 3.1 compatibility: ``pycparser`` was modified to run on Python 3.1 as well as 2.6 + Version 1.06 (2010.04.10) * Bug fixes: + coord not propagated to FuncCall nodes + lexing of the ^= token (XOREQUALS) + parsing failed on some abstract declarator rules * Linux compatibility: fixed end-of-line and ``cpp`` path issues to allow all tests and examples run on Linux + Version 1.05 (2009.10.16) * Fixed the ``parse_file`` auxiliary function to handle multiple arguments to ``cpp`` correctly + Version 1.04 (2009.05.22) * Added the ``fake_libc_include`` directory to allow parsing of C code that uses standard C library include files without dependency on a real C library. * Tested with Python 2.6 and PLY 3.2 + Version 1.03 (2009.01.31) * Accept enumeration lists with a comma after the last item (C99 feature). + Version 1.02 (2009.01.16) * Fixed problem of parsing struct/enum/union names that were named similarly to previously defined ``typedef`` types. + Version 1.01 (2009.01.09) * Fixed subprocess invocation in the helper function parse_file - now it's more portable + Version 1.0 (2008.11.15) * Initial release * Support for ANSI C89 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8557947 pycparser-3.12/PKG-INFO0000644000175000017500000002275515266410573014106 0ustar00elibenelibenMetadata-Version: 2.4 Name: pycparser Version: 3.12 Summary: C parser in Python Author-email: Eli Bendersky Maintainer-email: Eli Bendersky License-Expression: BSD-3-Clause Project-URL: Homepage, https://github.com/eliben/pycparser Classifier: Development Status :: 5 - Production/Stable Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 Classifier: Programming Language :: Python :: 3.15 Requires-Python: >=3.11 Description-Content-Type: text/x-rst License-File: LICENSE Dynamic: license-file ========= pycparser ========= .. image:: https://github.com/eliben/pycparser/workflows/pycparser-tests/badge.svg :align: center :target: https://github.com/eliben/pycparser/actions ---- .. contents:: :backlinks: none .. sectnum:: Introduction ============ What is pycparser? ------------------ **pycparser** is a parser for the C language, written in pure Python. It is a module designed to be easily integrated into applications that need to parse C source code. What is it good for? -------------------- Anything that needs C code to be parsed. The following are some uses for **pycparser**, taken from real user reports: * C code obfuscator * Front-end for various specialized C compilers * Static code checker * Automatic unit-test discovery * Adding specialized extensions to the C language One of the most popular uses of **pycparser** is in the `cffi `_ library, which uses it to parse the declarations of C functions and types in order to auto-generate FFIs. **pycparser** is unique in the sense that it's written in pure Python - a very high level language that's easy to experiment with and tweak. To people familiar with Lex and Yacc, **pycparser**'s code will be simple to understand. It also has no external dependencies (except for a Python interpreter), making it very simple to install and deploy. Which version of C does pycparser support? ------------------------------------------ **pycparser** aims to support the full C11 language, including earlier revisions like C99. C23 support is conditional on a ``dialect="c23"`` setting, since this revision introduces new keywords like ``bool`` that would conflict with existing C code if not handled properly. **pycparser** supports very few GCC extensions, but it's fairly easy to set things up so that it parses code with a lot of GCC-isms successfully. See the `FAQ `_ for more details. What grammar does pycparser follow? ----------------------------------- **pycparser** very closely follows the C grammar provided in Annex A of the C99 standard (ISO/IEC 9899). How is pycparser licensed? -------------------------- `BSD license `_. Contact details --------------- For reporting problems with **pycparser** or submitting feature requests, please open an `issue `_, or submit a pull request. Installing ========== Prerequisites ------------- **pycparser** is being tested with modern versions of Python on Linux, macOS and Windows. See `the CI dashboard `__ for details. **pycparser** has no external dependencies. Installation process -------------------- The recommended way to install **pycparser** is with ``pip``:: > pip install pycparser Using ===== Interaction with the C preprocessor ----------------------------------- In order to be compilable, C code must be preprocessed by the C preprocessor - ``cpp``. A compatible ``cpp`` handles preprocessing directives like ``#include`` and ``#define``, removes comments, and performs other minor tasks that prepare the C code for compilation. For all but the most trivial snippets of C code **pycparser**, like a C compiler, must receive preprocessed C code in order to function correctly. If you import the top-level ``parse_file`` function from the **pycparser** package, it will interact with ``cpp`` for you, as long as it's in your PATH, or you provide a path to it. Note also that you can use ``gcc -E`` or ``clang -E`` instead of ``cpp``. See the ``using_gcc_E_libc.py`` example for more details. Windows users can download and install a binary build of Clang for Windows `from this website `_. What about the standard C library headers? ------------------------------------------ C code almost always ``#include``\s various header files from the standard C library, like ``stdio.h``. While (with some effort) **pycparser** can be made to parse the standard headers from any C compiler, it's much simpler to use the provided "fake" standard includes for C11 in ``utils/fake_libc_include``. These are standard C header files that contain only the bare necessities to allow valid parsing of the files that use them. As a bonus, since they're minimal, it can significantly improve the performance of parsing large C files. The key point to understand here is that **pycparser** doesn't really care about the semantics of types. It only needs to know whether some token encountered in the source is a previously defined type. This is essential in order to be able to parse C correctly. See `this blog post `_ for more details. Note that the fake headers are not included in the ``pip`` package nor installed via the package build (`#224 `_). Basic usage ----------- Take a look at the |examples|_ directory of the distribution for a few examples of using **pycparser**. These should be enough to get you started. Please note that most realistic C code samples would require running the C preprocessor before passing the code to **pycparser**; see the previous sections for more details. For example, to parse C23 source with a preprocessor that supports ``-std=c23``:: from pycparser import CParser, parse_file ast = parse_file( "example.c", use_cpp=True, cpp_args=["-std=c23"], parser=CParser(dialect="c23"), ) The parser's dialect does not configure the external preprocessor; select its language mode separately through ``cpp_args``. .. |examples| replace:: ``examples`` .. _examples: examples Advanced usage -------------- The public interface of **pycparser** is well documented with comments in ``pycparser/c_parser.py``. For a detailed overview of the various AST nodes created by the parser, see ``pycparser/_c_ast.cfg``. The root node is a ``FileAST``, whose ``ext`` attribute is a list of top-level declarations and function definitions. Explore nodes through their named fields, and use ``show()`` on a subtree to inspect just that part of the AST:: from pycparser import CParser ast = CParser().parse("int x; int f(void) { return x; }") print(len(ast.ext)) # 2 func = ast.ext[1] func.body.show() For generic exploration, call ``children()`` to get a tuple of ``(field_name, child_node)`` pairs for the immediate children. The tuple supports length and indexing directly:: children = func.children() print(len(children)) # 2: decl and body name, child = children[0] print(name) # decl child.show() Iterating over a node directly (``for child in node``) yields just the child nodes, without their names. For a guided walkthrough, see `examples/explore_ast.py `_; for recursive traversal, see the ``NodeVisitor`` example in `examples/func_defs.py `_. There's also a `FAQ available here `_. In any case, you can always drop me an `email `_ for help. Modifying ========= There are a few points to keep in mind when modifying **pycparser**: * The code for **pycparser**'s AST nodes is automatically generated from a configuration file - ``_c_ast.cfg``, by ``_ast_gen.py``. If you modify the AST configuration or the generator, run ``make regen-ast`` from the repository root to re-generate ``pycparser/c_ast.py`` and run ``make format``. * Read the docstring in the constructor of the ``CParser`` class for details on configuration and compatibility arguments. Package contents ================ Once you unzip the ``pycparser`` package, you'll see the following files and directories: README.rst: This README file. LICENSE: The pycparser license setup.py: Legacy installation script (build metadata lives in ``pyproject.toml``). pyproject.toml: Package metadata and build configuration. examples/: A directory with some examples of using **pycparser** pycparser/: The **pycparser** module source code. tests/: Unit tests. utils/fake_libc_include: Minimal standard C library include files that should allow to parse any C code. Note that these headers now include C11 code, so they may not work when the preprocessor is configured to an earlier C standard (like ``-std=c99``). utils/internal/: Internal utilities for my own use. You probably don't need them. Contributors ============ Some people have contributed to **pycparser** by opening issues on bugs they've found and/or submitting patches. The list of contributors is in the CONTRIBUTORS file in the source distribution. After **pycparser** moved to Github I stopped updating this list because Github does a much better job at tracking contributions. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792674928.0359712 pycparser-3.12/README.rst0000664000175000017500000002141615266406160014470 0ustar00elibeneliben========= pycparser ========= .. image:: https://github.com/eliben/pycparser/workflows/pycparser-tests/badge.svg :align: center :target: https://github.com/eliben/pycparser/actions ---- .. contents:: :backlinks: none .. sectnum:: Introduction ============ What is pycparser? ------------------ **pycparser** is a parser for the C language, written in pure Python. It is a module designed to be easily integrated into applications that need to parse C source code. What is it good for? -------------------- Anything that needs C code to be parsed. The following are some uses for **pycparser**, taken from real user reports: * C code obfuscator * Front-end for various specialized C compilers * Static code checker * Automatic unit-test discovery * Adding specialized extensions to the C language One of the most popular uses of **pycparser** is in the `cffi `_ library, which uses it to parse the declarations of C functions and types in order to auto-generate FFIs. **pycparser** is unique in the sense that it's written in pure Python - a very high level language that's easy to experiment with and tweak. To people familiar with Lex and Yacc, **pycparser**'s code will be simple to understand. It also has no external dependencies (except for a Python interpreter), making it very simple to install and deploy. Which version of C does pycparser support? ------------------------------------------ **pycparser** aims to support the full C11 language, including earlier revisions like C99. C23 support is conditional on a ``dialect="c23"`` setting, since this revision introduces new keywords like ``bool`` that would conflict with existing C code if not handled properly. **pycparser** supports very few GCC extensions, but it's fairly easy to set things up so that it parses code with a lot of GCC-isms successfully. See the `FAQ `_ for more details. What grammar does pycparser follow? ----------------------------------- **pycparser** very closely follows the C grammar provided in Annex A of the C99 standard (ISO/IEC 9899). How is pycparser licensed? -------------------------- `BSD license `_. Contact details --------------- For reporting problems with **pycparser** or submitting feature requests, please open an `issue `_, or submit a pull request. Installing ========== Prerequisites ------------- **pycparser** is being tested with modern versions of Python on Linux, macOS and Windows. See `the CI dashboard `__ for details. **pycparser** has no external dependencies. Installation process -------------------- The recommended way to install **pycparser** is with ``pip``:: > pip install pycparser Using ===== Interaction with the C preprocessor ----------------------------------- In order to be compilable, C code must be preprocessed by the C preprocessor - ``cpp``. A compatible ``cpp`` handles preprocessing directives like ``#include`` and ``#define``, removes comments, and performs other minor tasks that prepare the C code for compilation. For all but the most trivial snippets of C code **pycparser**, like a C compiler, must receive preprocessed C code in order to function correctly. If you import the top-level ``parse_file`` function from the **pycparser** package, it will interact with ``cpp`` for you, as long as it's in your PATH, or you provide a path to it. Note also that you can use ``gcc -E`` or ``clang -E`` instead of ``cpp``. See the ``using_gcc_E_libc.py`` example for more details. Windows users can download and install a binary build of Clang for Windows `from this website `_. What about the standard C library headers? ------------------------------------------ C code almost always ``#include``\s various header files from the standard C library, like ``stdio.h``. While (with some effort) **pycparser** can be made to parse the standard headers from any C compiler, it's much simpler to use the provided "fake" standard includes for C11 in ``utils/fake_libc_include``. These are standard C header files that contain only the bare necessities to allow valid parsing of the files that use them. As a bonus, since they're minimal, it can significantly improve the performance of parsing large C files. The key point to understand here is that **pycparser** doesn't really care about the semantics of types. It only needs to know whether some token encountered in the source is a previously defined type. This is essential in order to be able to parse C correctly. See `this blog post `_ for more details. Note that the fake headers are not included in the ``pip`` package nor installed via the package build (`#224 `_). Basic usage ----------- Take a look at the |examples|_ directory of the distribution for a few examples of using **pycparser**. These should be enough to get you started. Please note that most realistic C code samples would require running the C preprocessor before passing the code to **pycparser**; see the previous sections for more details. For example, to parse C23 source with a preprocessor that supports ``-std=c23``:: from pycparser import CParser, parse_file ast = parse_file( "example.c", use_cpp=True, cpp_args=["-std=c23"], parser=CParser(dialect="c23"), ) The parser's dialect does not configure the external preprocessor; select its language mode separately through ``cpp_args``. .. |examples| replace:: ``examples`` .. _examples: examples Advanced usage -------------- The public interface of **pycparser** is well documented with comments in ``pycparser/c_parser.py``. For a detailed overview of the various AST nodes created by the parser, see ``pycparser/_c_ast.cfg``. The root node is a ``FileAST``, whose ``ext`` attribute is a list of top-level declarations and function definitions. Explore nodes through their named fields, and use ``show()`` on a subtree to inspect just that part of the AST:: from pycparser import CParser ast = CParser().parse("int x; int f(void) { return x; }") print(len(ast.ext)) # 2 func = ast.ext[1] func.body.show() For generic exploration, call ``children()`` to get a tuple of ``(field_name, child_node)`` pairs for the immediate children. The tuple supports length and indexing directly:: children = func.children() print(len(children)) # 2: decl and body name, child = children[0] print(name) # decl child.show() Iterating over a node directly (``for child in node``) yields just the child nodes, without their names. For a guided walkthrough, see `examples/explore_ast.py `_; for recursive traversal, see the ``NodeVisitor`` example in `examples/func_defs.py `_. There's also a `FAQ available here `_. In any case, you can always drop me an `email `_ for help. Modifying ========= There are a few points to keep in mind when modifying **pycparser**: * The code for **pycparser**'s AST nodes is automatically generated from a configuration file - ``_c_ast.cfg``, by ``_ast_gen.py``. If you modify the AST configuration or the generator, run ``make regen-ast`` from the repository root to re-generate ``pycparser/c_ast.py`` and run ``make format``. * Read the docstring in the constructor of the ``CParser`` class for details on configuration and compatibility arguments. Package contents ================ Once you unzip the ``pycparser`` package, you'll see the following files and directories: README.rst: This README file. LICENSE: The pycparser license setup.py: Legacy installation script (build metadata lives in ``pyproject.toml``). pyproject.toml: Package metadata and build configuration. examples/: A directory with some examples of using **pycparser** pycparser/: The **pycparser** module source code. tests/: Unit tests. utils/fake_libc_include: Minimal standard C library include files that should allow to parse any C code. Note that these headers now include C11 code, so they may not work when the preprocessor is configured to an earlier C standard (like ``-std=c99``). utils/internal/: Internal utilities for my own use. You probably don't need them. Contributors ============ Some people have contributed to **pycparser** by opening issues on bugs they've found and/or submitting patches. The list of contributors is in the CONTRIBUTORS file in the source distribution. After **pycparser** moved to Github I stopped updating this list because Github does a much better job at tracking contributions. ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1792676218.850995 pycparser-3.12/examples/0000775000175000017500000000000015266410573014616 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785327145.0291767 pycparser-3.12/examples/c-to-c.py0000664000175000017500000000164015232367051016246 0ustar00elibeneliben# ------------------------------------------------------------------------------ # pycparser: c-to-c.py # # Example of using pycparser.c_generator, serving as a simplistic translator # from C to AST and back to C. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ------------------------------------------------------------------------------ import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import c_generator, parse_file def translate_to_c(filename: str) -> None: """Simply use the c_generator module to emit a parsed AST.""" ast = parse_file(filename, use_cpp=True) generator = c_generator.CGenerator() print(generator.visit(ast)) if __name__ == "__main__": if len(sys.argv) > 1: translate_to_c(sys.argv[1]) else: print("Please provide a filename as argument") ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8511984 pycparser-3.12/examples/c_files/0000775000175000017500000000000015266410573016222 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7866623 pycparser-3.12/examples/c_files/basic.c0000664000175000017500000000006214716121045017435 0ustar00elibenelibenint foo() {} int main() { foo(); return 0; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7866623 pycparser-3.12/examples/c_files/funky.c0000664000175000017500000000030114716121045017504 0ustar00elibenelibenchar foo(void) { return '1'; } int maxout_in(int paste, char** matrix) { char o = foo(); return (int) matrix[1][2] * 5 - paste; } int main() { auto char* multi = "a multi"; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7866623 pycparser-3.12/examples/c_files/hash.c0000664000175000017500000000726514716121045017313 0ustar00elibeneliben/* ** C implementation of a hash table ADT */ typedef enum tagReturnCode {SUCCESS, FAIL} ReturnCode; typedef struct tagEntry { char* key; char* value; } Entry; typedef struct tagNode { Entry* entry; struct tagNode* next; } Node; typedef struct tagHash { unsigned int table_size; Node** heads; } Hash; static unsigned int hash_func(const char* str, unsigned int table_size) { unsigned int hash_value; unsigned int a = 127; for (hash_value = 0; *str != 0; ++str) hash_value = (a*hash_value + *str) % table_size; return hash_value; } ReturnCode HashCreate(Hash** hash, unsigned int table_size) { unsigned int i; if (table_size < 1) return FAIL; // // Allocate space for the Hash // if (((*hash) = malloc(sizeof(**hash))) == NULL) return FAIL; // // Allocate space for the array of list heads // if (((*hash)->heads = malloc(table_size*sizeof(*((*hash)->heads)))) == NULL) return FAIL; // // Initialize Hash info // for (i = 0; i < table_size; ++i) { (*hash)->heads[i] = NULL; } (*hash)->table_size = table_size; return SUCCESS; } ReturnCode HashInsert(Hash* hash, const Entry* entry) { unsigned int index = hash_func(entry->key, hash->table_size); Node* temp = hash->heads[index]; HashRemove(hash, entry->key); if ((hash->heads[index] = malloc(sizeof(Node))) == NULL) return FAIL; hash->heads[index]->entry = malloc(sizeof(Entry)); hash->heads[index]->entry->key = malloc(strlen(entry->key)+1); hash->heads[index]->entry->value = malloc(strlen(entry->value)+1); strcpy(hash->heads[index]->entry->key, entry->key); strcpy(hash->heads[index]->entry->value, entry->value); hash->heads[index]->next = temp; return SUCCESS; } const Entry* HashFind(const Hash* hash, const char* key) { unsigned int index = hash_func(key, hash->table_size); Node* temp = hash->heads[index]; while (temp != NULL) { if (!strcmp(key, temp->entry->key)) return temp->entry; temp = temp->next; } return NULL; } ReturnCode HashRemove(Hash* hash, const char* key) { unsigned int index = hash_func(key, hash->table_size); Node* temp1 = hash->heads[index]; Node* temp2 = temp1; while (temp1 != NULL) { if (!strcmp(key, temp1->entry->key)) { if (temp1 == hash->heads[index]) hash->heads[index] = hash->heads[index]->next; else temp2->next = temp1->next; free(temp1->entry->key); free(temp1->entry->value); free(temp1->entry); free(temp1); temp1 = NULL; return SUCCESS; } temp2 = temp1; temp1 = temp1->next; } return FAIL; } void HashPrint(Hash* hash, void (*PrintFunc)(char*, char*)) { unsigned int i; if (hash == NULL || hash->heads == NULL) return; for (i = 0; i < hash->table_size; ++i) { Node* temp = hash->heads[i]; while (temp != NULL) { PrintFunc(temp->entry->key, temp->entry->value); temp = temp->next; } } } void HashDestroy(Hash* hash) { unsigned int i; if (hash == NULL) return; for (i = 0; i < hash->table_size; ++i) { Node* temp = hash->heads[i]; while (temp != NULL) { Node* temp2 = temp; free(temp->entry->key); free(temp->entry->value); free(temp->entry); temp = temp->next; free(temp2); } } free(hash->heads); hash->heads = NULL; free(hash); } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7866623 pycparser-3.12/examples/c_files/memmgr.c0000664000175000017500000001240314716121045017642 0ustar00elibeneliben//---------------------------------------------------------------- // Statically-allocated memory manager // // by Eli Bendersky (eliben@gmail.com) // // This code is in the public domain. //---------------------------------------------------------------- #include "memmgr.h" typedef ulong Align; union mem_header_union { struct { // Pointer to the next block in the free list // union mem_header_union* next; // Size of the block (in quantas of sizeof(mem_header_t)) // ulong size; } s; // Used to align headers in memory to a boundary // Align align_dummy; }; typedef union mem_header_union mem_header_t; // Initial empty list // static mem_header_t base; // Start of free list // static mem_header_t* freep = 0; // Static pool for new allocations // static byte pool[POOL_SIZE] = {0}; static ulong pool_free_pos = 0; void memmgr_init() { base.s.next = 0; base.s.size = 0; freep = 0; pool_free_pos = 0; } static mem_header_t* get_mem_from_pool(ulong nquantas) { ulong total_req_size; mem_header_t* h; if (nquantas < MIN_POOL_ALLOC_QUANTAS) nquantas = MIN_POOL_ALLOC_QUANTAS; total_req_size = nquantas * sizeof(mem_header_t); if (pool_free_pos + total_req_size <= POOL_SIZE) { h = (mem_header_t*) (pool + pool_free_pos); h->s.size = nquantas; memmgr_free((void*) (h + 1)); pool_free_pos += total_req_size; } else { return 0; } return freep; } // Allocations are done in 'quantas' of header size. // The search for a free block of adequate size begins at the point 'freep' // where the last block was found. // If a too-big block is found, it is split and the tail is returned (this // way the header of the original needs only to have its size adjusted). // The pointer returned to the user points to the free space within the block, // which begins one quanta after the header. // void* memmgr_alloc(ulong nbytes) { mem_header_t* p; mem_header_t* prevp; // Calculate how many quantas are required: we need enough to house all // the requested bytes, plus the header. The -1 and +1 are there to make sure // that if nbytes is a multiple of nquantas, we don't allocate too much // ulong nquantas = (nbytes + sizeof(mem_header_t) - 1) / sizeof(mem_header_t) + 1; // First alloc call, and no free list yet ? Use 'base' for an initial // denegerate block of size 0, which points to itself // if ((prevp = freep) == 0) { base.s.next = freep = prevp = &base; base.s.size = 0; } for (p = prevp->s.next; ; prevp = p, p = p->s.next) { // big enough ? if (p->s.size >= nquantas) { // exactly ? if (p->s.size == nquantas) { // just eliminate this block from the free list by pointing // its prev's next to its next // prevp->s.next = p->s.next; } else // too big { p->s.size -= nquantas; p += p->s.size; p->s.size = nquantas; } freep = prevp; return (void*) (p + 1); } // Reached end of free list ? // Try to allocate the block from the pool. If that succeeds, // get_mem_from_pool adds the new block to the free list and // it will be found in the following iterations. If the call // to get_mem_from_pool doesn't succeed, we've run out of // memory // else if (p == freep) { if ((p = get_mem_from_pool(nquantas)) == 0) { #ifdef DEBUG_MEMMGR_FATAL printf("!! Memory allocation failed !!\n"); #endif return 0; } } } } // Scans the free list, starting at freep, looking the the place to insert the // free block. This is either between two existing blocks or at the end of the // list. In any case, if the block being freed is adjacent to either neighbor, // the adjacent blocks are combined. // void memmgr_free(void* ap) { mem_header_t* block; mem_header_t* p; // acquire pointer to block header block = ((mem_header_t*) ap) - 1; // Find the correct place to place the block in (the free list is sorted by // address, increasing order) // for (p = freep; !(block > p && block < p->s.next); p = p->s.next) { // Since the free list is circular, there is one link where a // higher-addressed block points to a lower-addressed block. // This condition checks if the block should be actually // inserted between them // if (p >= p->s.next && (block > p || block < p->s.next)) break; } // Try to combine with the higher neighbor // if (block + block->s.size == p->s.next) { block->s.size += p->s.next->s.size; block->s.next = p->s.next->s.next; } else { block->s.next = p->s.next; } // Try to combine with the lower neighbor // if (p + p->s.size == block) { p->s.size += block->s.size; p->s.next = block->s.next; } else { p->s.next = block; } freep = p; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7866623 pycparser-3.12/examples/c_files/memmgr.h0000664000175000017500000000550214716121045017651 0ustar00elibeneliben//---------------------------------------------------------------- // Statically-allocated memory manager // // by Eli Bendersky (eliben@gmail.com) // // This code is in the public domain. //---------------------------------------------------------------- #ifndef MEMMGR_H #define MEMMGR_H // // Memory manager: dynamically allocates memory from // a fixed pool that is allocated statically at link-time. // // Usage: after calling memmgr_init() in your // initialization routine, just use memmgr_alloc() instead // of malloc() and memmgr_free() instead of free(). // Naturally, you can use the preprocessor to define // malloc() and free() as aliases to memmgr_alloc() and // memmgr_free(). This way the manager will be a drop-in // replacement for the standard C library allocators, and can // be useful for debugging memory allocation problems and // leaks. // // Preprocessor flags you can define to customize the // memory manager: // // DEBUG_MEMMGR_FATAL // Allow printing out a message when allocations fail // // DEBUG_MEMMGR_SUPPORT_STATS // Allow printing out of stats in function // memmgr_print_stats When this is disabled, // memmgr_print_stats does nothing. // // Note that in production code on an embedded system // you'll probably want to keep those undefined, because // they cause printf to be called. // // POOL_SIZE // Size of the pool for new allocations. This is // effectively the heap size of the application, and can // be changed in accordance with the available memory // resources. // // MIN_POOL_ALLOC_QUANTAS // Internally, the memory manager allocates memory in // quantas roughly the size of two ulong objects. To // minimize pool fragmentation in case of multiple allocations // and deallocations, it is advisable to not allocate // blocks that are too small. // This flag sets the minimal amount of quantas for // an allocation. If the size of a ulong is 4 and you // set this flag to 16, the minimal size of an allocation // will be 4 * 2 * 16 = 128 bytes // If you have a lot of small allocations, keep this value // low to conserve memory. If you have mostly large // allocations, it is best to make it higher, to avoid // fragmentation. // // Notes: // 1. This memory manager is *not thread safe*. Use it only // for single thread/task applications. // #define DEBUG_MEMMGR_SUPPORT_STATS 1 #define POOL_SIZE 8 * 1024 #define MIN_POOL_ALLOC_QUANTAS 16 typedef unsigned char byte; typedef unsigned long ulong; // Initialize the memory manager. This function should be called // only once in the beginning of the program. // void memmgr_init(); // 'malloc' clone // void* memmgr_alloc(ulong nbytes); // 'free' clone // void memmgr_free(void* ap); // Prints statistics about the current state of the memory // manager // void memmgr_print_stats(); #endif // MEMMGR_H ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7866623 pycparser-3.12/examples/c_files/pragmas.c0000664000175000017500000000021414716121045020005 0ustar00elibenelibenint i; #pragma joe int main() { int a = 1; #pragma inmain for (int i = 0; i < 3; i++) { #pragma infor a += i; } return a; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7866623 pycparser-3.12/examples/c_files/year.c0000664000175000017500000000212514716121045017316 0ustar00elibeneliben#include #include #include void convert(int thousands, int hundreds, int tens, int ones) { char *num[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; char *for_ten[] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; char *af_ten[] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Ninteen"}; printf("\nThe year in words is:\n"); printf("%s thousand", num[thousands]); if (hundreds != 0) printf(" %s hundred", num[hundreds]); if (tens != 1) printf(" %s %s", for_ten[tens], num[ones]); else printf(" %s", af_ten[ones]); } int main() { int year; int n1000, n100, n10, n1; printf("\nEnter the year (4 digits): "); scanf("%d", &year); if (year > 9999 || year < 1000) { printf("\nError !! The year must contain 4 digits."); exit(EXIT_FAILURE); } n1000 = year/1000; n100 = ((year)%1000)/100; n10 = (year%100)/10; n1 = ((year%10)%10); convert(n1000, n100, n10, n1); return 0; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785328199.4520743 pycparser-3.12/examples/c_json.py0000664000175000017500000001534515232371107016443 0ustar00elibeneliben# ------------------------------------------------------------------------------ # pycparser: c_json.py # # by Michael White (@mypalmike) # # This example includes functions to serialize and deserialize an ast # to and from json format. Serializing involves walking the ast and converting # each node from a python Node object into a python dict. Deserializing # involves the opposite conversion, walking the tree formed by the # dict and converting each dict into the specific Node object it represents. # The dict itself is serialized and deserialized using the python json module. # # The dict representation is a fairly direct transformation of the object # attributes. Each node in the dict gets one metadata field referring to the # specific node class name, _nodetype. Each local attribute (i.e. not linking # to child nodes) has a string value or array of string values. Each child # attribute is either another dict or an array of dicts, exactly as in the # Node object representation. The "coord" attribute, representing the # node's location within the source code, is serialized/deserialized from # a Coord object into a string of the format "filename:line[:column]". # # Example TypeDecl node, with IdentifierType child node, represented as a dict: # "type": { # "_nodetype": "TypeDecl", # "coord": "c_files/funky.c:8", # "declname": "o", # "quals": [], # "type": { # "_nodetype": "IdentifierType", # "coord": "c_files/funky.c:8", # "names": [ # "char" # ] # } # } # ------------------------------------------------------------------------------ import json import re import sys from collections.abc import Callable from typing import Any, TypeVar # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import c_ast, parse_file from pycparser.c_parser import Coord RE_CHILD_ARRAY = re.compile(r"(.*)\[(.*)\]") RE_INTERNAL_ATTR = re.compile("__.*__") class CJsonError(Exception): pass _T = TypeVar("_T") _R = TypeVar("_R") def memodict(fn: Callable[[_T], _R]) -> Callable[[_T], _R]: """Fast memoization decorator for a function taking a single argument""" cache: dict[_T, _R] = {} def memoized(arg: _T) -> _R: if arg in cache: return cache[arg] result = fn(arg) cache[arg] = result return result return memoized @memodict def child_attrs_of(klass: type[c_ast.Node]) -> set[str]: """ Given a Node class, get a set of child attrs. Memoized to avoid highly repetitive string manipulation """ non_child_attrs = set(klass.attr_names) all_attrs: set[str] = {i for i in klass.__slots__ if not RE_INTERNAL_ATTR.match(i)} return all_attrs - non_child_attrs def to_dict(node: c_ast.Node) -> dict[str, Any]: """Recursively convert an ast into dict representation.""" klass = node.__class__ result: dict[str, Any] = {} # Metadata result["_nodetype"] = klass.__name__ # Local node attributes for attr in klass.attr_names: result[attr] = getattr(node, attr) # Coord object if node.coord: result["coord"] = str(node.coord) else: result["coord"] = None # Child attributes for child_name, child in node.children(): # Child strings are either simple (e.g. 'value') or arrays (e.g. 'block_items[1]') match = RE_CHILD_ARRAY.match(child_name) if match: array_name, array_index = match.groups() array_index = int(array_index) # arrays come in order, so we verify and append. result[array_name] = result.get(array_name, []) if array_index != len(result[array_name]): raise CJsonError( f"Internal ast error. Array {array_name} out of order. " f"Expected index {len(result[array_name])}, got {array_index}" ) result[array_name].append(to_dict(child)) else: result[child_name] = to_dict(child) # Any child attributes that were missing need "None" values in the json. for child_attr in child_attrs_of(klass): if child_attr not in result: result[child_attr] = None return result def to_json(node: c_ast.Node, **kwargs: Any) -> str: """Convert ast node to json string""" return json.dumps(to_dict(node), **kwargs) def file_to_dict(filename: str) -> dict[str, Any]: """Load C file into dict representation of ast""" ast = parse_file(filename, use_cpp=True) return to_dict(ast) def file_to_json(filename: str, **kwargs: Any) -> str: """Load C file into json string representation of ast""" ast = parse_file(filename, use_cpp=True) return to_json(ast, **kwargs) def _parse_coord(coord_str: str | None) -> Coord | None: """Parse coord string (file:line[:column]) into Coord object.""" if coord_str is None: return None vals = coord_str.split(":") vals.extend(["", "", ""]) filename, line, column = vals[:3] line_num = int(line) if line else 0 column_num = int(column) if column else None return Coord(filename, line_num, column_num) def _convert_to_obj(value: Any) -> Any: """ Convert an object in the dict representation into an object. Note: Mutually recursive with from_dict. """ match value: case dict(): return from_dict(value) case list(): return [_convert_to_obj(item) for item in value] case _: # String return value def from_dict(node_dict: dict[str, Any]) -> c_ast.Node: """Recursively build an ast from dict representation""" class_name = node_dict.pop("_nodetype") klass = getattr(c_ast, class_name) # Create a new dict containing the key-value pairs which we can pass # to node constructors. objs = {} for key, value in node_dict.items(): if key == "coord": objs[key] = _parse_coord(value) else: objs[key] = _convert_to_obj(value) # Use keyword parameters, which works thanks to beautifully consistent # ast Node initializers. return klass(**objs) def from_json(ast_json: str) -> c_ast.Node: """Build an ast from json string representation""" return from_dict(json.loads(ast_json)) # ------------------------------------------------------------------------------ if __name__ == "__main__": if len(sys.argv) > 1: # Some test code... # Do trip from C -> ast -> dict -> ast -> json, then print. ast_dict = file_to_dict(sys.argv[1]) ast = from_dict(ast_dict) print(to_json(ast, sort_keys=True, indent=4)) else: print("Please provide a filename as argument") ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785328184.1495535 pycparser-3.12/examples/cdecl.py0000664000175000017500000001530115232371070016231 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: cdecl.py # # Example of the CDECL tool using pycparser. CDECL "explains" C type # declarations in plain English. # # The AST generated by pycparser from the given declaration is traversed # recursively to build the explanation. Note that the declaration must be a # valid external declaration in C. As shown below, typedef can be optionally # expanded. # # For example: # # c_decl = 'typedef int Node; const Node* (*ar)[10];' # # explain_c_declaration(c_decl) # => ar is a pointer to array[10] of pointer to const Node # # struct and typedef can be optionally expanded: # # explain_c_declaration(c_decl, expand_typedef=True) # => ar is a pointer to array[10] of pointer to const int # # c_decl = 'struct P {int x; int y;} p;' # # explain_c_declaration(c_decl) # => p is a struct P # # explain_c_declaration(c_decl, expand_struct=True) # => p is a struct P containing {x is a int, y is a int} # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import copy import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import c_ast, c_parser def explain_c_declaration( c_decl: str, expand_struct: bool = False, expand_typedef: bool = False ) -> str: """Parses the declaration in c_decl and returns a text explanation as a string. The last external node of the string is used, to allow earlier typedefs for used types. expand_struct=True will spell out struct definitions recursively. expand_typedef=True will expand typedef'd types. """ parser = c_parser.CParser() try: node = parser.parse(c_decl, filename="") except c_parser.ParseError: e = sys.exc_info()[1] return "Parse error:" + str(e) if not isinstance(node, c_ast.FileAST) or not isinstance(node.ext[-1], c_ast.Decl): return "Not a valid declaration" try: expanded = expand_struct_typedef( node.ext[-1], node, expand_struct=expand_struct, expand_typedef=expand_typedef, ) except RuntimeError as e: return "Not a valid declaration: " + str(e) return _explain_decl_node(expanded) def _explain_decl_node(decl_node: c_ast.Decl) -> str: """Receives a c_ast.Decl note and returns its explanation in English. """ storage = " ".join(decl_node.storage) + " " if decl_node.storage else "" return decl_node.name + " is a " + storage + _explain_type(decl_node.type) def _explain_type(decl: c_ast.Node) -> str: """Recursively explains a type decl node""" match decl: case c_ast.TypeDecl(): quals = " ".join(decl.quals) + " " if decl.quals else "" return quals + _explain_type(decl.type) case c_ast.Typename() | c_ast.Decl(): return _explain_type(decl.type) case c_ast.IdentifierType(): return " ".join(decl.names) case c_ast.PtrDecl(): quals = " ".join(decl.quals) + " " if decl.quals else "" return quals + "pointer to " + _explain_type(decl.type) case c_ast.ArrayDecl(): arr = "array" if decl.dim is not None: arr += f"[{decl.dim.value}]" return arr + " of " + _explain_type(decl.type) case c_ast.FuncDecl(): if decl.args is not None: params = [_explain_type(param) for param in decl.args.params] args = ", ".join(params) else: args = "" return f"function({args}) returning " + _explain_type(decl.type) case c_ast.Struct(): decls = [_explain_decl_node(mem_decl) for mem_decl in decl.decls] members = ", ".join(decls) struct_name = f" {decl.name}" if decl.name else "" contents = f"containing {{{members}}}" if members else "" return f"struct{struct_name} " + contents case _: return "" def expand_struct_typedef( cdecl: c_ast.Decl, file_ast: c_ast.FileAST, expand_struct: bool = False, expand_typedef: bool = False, ) -> c_ast.Decl: """Expand struct & typedef and return a new expanded node.""" decl_copy = copy.deepcopy(cdecl) _expand_in_place(decl_copy, file_ast, expand_struct, expand_typedef) return decl_copy def _expand_in_place( decl: c_ast.Node, file_ast: c_ast.FileAST, expand_struct: bool = False, expand_typedef: bool = False, ) -> c_ast.Node: """Recursively expand struct & typedef in place, throw RuntimeError if undeclared struct or typedef are used """ match decl: case c_ast.Decl() | c_ast.TypeDecl() | c_ast.PtrDecl() | c_ast.ArrayDecl(): decl.type = _expand_in_place( decl.type, file_ast, expand_struct, expand_typedef ) case c_ast.Struct(): if not decl.decls: struct = _find_struct(decl.name, file_ast) if struct is None: raise RuntimeError(f"using undeclared struct {decl.name}") decl.decls = struct.decls for i, mem_decl in enumerate(decl.decls): decl.decls[i] = _expand_in_place( mem_decl, file_ast, expand_struct, expand_typedef ) if not expand_struct: decl.decls = [] case c_ast.IdentifierType() if decl.names[0] not in ("int", "char"): typedef = _find_typedef(decl.names[0], file_ast) if typedef is None: raise RuntimeError(f"using undeclared type {decl.names[0]}") if expand_typedef: return typedef.type case _: pass return decl def _find_struct(name: str, file_ast: c_ast.FileAST) -> c_ast.Struct | None: """Receives a struct name and return declared struct object in file_ast""" for node in file_ast.ext: if ( isinstance(node, c_ast.Decl) and isinstance(node.type, c_ast.Struct) and node.type.name == name ): return node.type return None def _find_typedef(name: str, file_ast: c_ast.FileAST) -> c_ast.Typedef | None: """Receives a type name and return typedef object in file_ast""" for node in file_ast.ext: if isinstance(node, c_ast.Typedef) and node.name == name: return node return None if __name__ == "__main__": if len(sys.argv) > 1: c_decl = sys.argv[1] else: c_decl = "char *(*(**foo[][8])())[];" print("Explaining the declaration: " + c_decl + "\n") print(explain_c_declaration(c_decl) + "\n") ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1791897874.1034172 pycparser-3.12/examples/construct_ast_from_scratch.py0000664000175000017500000000332515263430422022610 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: construct_ast_from_scratch.py # # Tiny example of writing an AST from scratch to C code. # # Andre Ribeiro [https://github.com/Andree37] # License: BSD # ----------------------------------------------------------------- import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import c_ast, c_generator # target C code: # int main() { # return 0; # } def empty_main_function_ast() -> c_ast.FuncDef: constant_zero = c_ast.Constant(type="int", value="0") return_node = c_ast.Return(expr=constant_zero) compound_node = c_ast.Compound(block_items=[return_node]) type_decl_node = c_ast.TypeDecl( declname="main", quals=[], type=c_ast.IdentifierType(names=["int"]), align=[] ) func_decl_node = c_ast.FuncDecl(args=c_ast.ParamList([]), type=type_decl_node) func_def_node = c_ast.Decl( name="main", quals=[], storage=[], funcspec=[], type=func_decl_node, init=None, bitsize=None, align=[], ) main_func_node = c_ast.FuncDef( decl=func_def_node, param_decls=None, body=compound_node ) return main_func_node def generate_c_code(my_ast: c_ast.Node) -> str: generator = c_generator.CGenerator() return generator.visit(my_ast) if __name__ == "__main__": main_function_ast = empty_main_function_ast() print("|----------------------------------------|") main_function_ast.show(offset=2) print("|----------------------------------------|") main_c_code = generate_c_code(main_function_ast) print(f"C code: \n{main_c_code}") ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1769004602.2595415 pycparser-3.12/examples/dump_ast.py0000664000175000017500000000165615134157072017010 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: dump_ast.py # # Basic example of parsing a file and dumping its parsed AST. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import argparse import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import parse_file if __name__ == "__main__": argparser = argparse.ArgumentParser("Dump AST") argparser.add_argument( "filename", default="examples/c_files/basic.c", nargs="?", help="name of file to parse", ) argparser.add_argument( "--coord", help="show coordinates in the dump", action="store_true" ) args = argparser.parse_args() ast = parse_file(args.filename, use_cpp=False) ast.show(showcoord=args.coord) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1769004602.2595415 pycparser-3.12/examples/explore_ast.py0000664000175000017500000001251115134157072017511 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: explore_ast.py # # This example demonstrates how to "explore" the AST created by # pycparser to understand its structure. The AST is a n-nary tree # of nodes, each node having several children, each with a name. # Just read the code, and let the comments guide you. The lines # beginning with #~ can be uncommented to print out useful # information from the AST. # It helps to have the pycparser/_c_ast.cfg file in front of you. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import c_parser # This is some C source to parse. Note that pycparser must begin # at the top level of the C file, i.e. with either declarations # or function definitions (this is called "external declarations" # in C grammar lingo) # # Also, a C parser must have all the types declared in order to # build the correct AST. It doesn't matter what they're declared # to, so I've inserted the dummy typedef in the code to let the # parser know Hash and Node are types. You don't need to do it # when parsing real, correct C code. text = r""" typedef int Node, Hash; void HashPrint(Hash* hash, void (*PrintFunc)(char*, char*)) { unsigned int i; if (hash == NULL || hash->heads == NULL) return; for (i = 0; i < hash->table_size; ++i) { Node* temp = hash->heads[i]; while (temp != NULL) { PrintFunc(temp->entry->key, temp->entry->value); temp = temp->next; } } } """ # Create the parser and ask to parse the text. parse() will throw # a ParseError if there's an error in the code # parser = c_parser.CParser() ast = parser.parse(text, filename="") # Uncomment the following line to see the AST in a nice, human # readable way. show() is the most useful tool in exploring ASTs # created by pycparser. See the c_ast.py file for the options you # can pass it. # ast.show(showcoord=True) # OK, we've seen that the top node is FileAST. This is always the # top node of the AST. Its children are "external declarations", # and are stored in a list called ext[] (see _c_ast.cfg for the # names and types of Nodes and their children). # As you see from the printout, our AST has two Typedef children # and one FuncDef child. # Let's explore FuncDef more closely. As I've mentioned, the list # ext[] holds the children of FileAST. Since the function # definition is the third child, it's ext[2]. Uncomment the # following line to show it: # ast.ext[2].show() # A FuncDef consists of a declaration, a list of parameter # declarations (for K&R style function definitions), and a body. # First, let's examine the declaration. function_decl = ast.ext[2].decl # function_decl, like any other declaration, is a Decl. Its type child # is a FuncDecl, which has a return type and arguments stored in a # ParamList node # function_decl.type.show() # function_decl.type.args.show() # The following displays the name and type of each argument: # for param_decl in function_decl.type.args.params: # print(f"Arg name: {param_decl.name}") # print('Type:') # param_decl.type.show(offset=6) # The body is of FuncDef is a Compound, which is a placeholder for a block # surrounded by {} (You should be reading _c_ast.cfg parallel to this # explanation and seeing these things with your own eyes). # Let's see the block's declarations: function_body = ast.ext[2].body # The following displays the declarations and statements in the function # body # for decl in function_body.block_items: # decl.show() # We can see a single variable declaration, i, declared to be a simple type # declaration of type 'unsigned int', followed by statements. # block_items is a list, so the third element is the For statement: for_stmt = function_body.block_items[2] # for_stmt.show() # As you can see in _c_ast.cfg, For's children are 'init, cond, # next' for the respective parts of the 'for' loop specifier, # and stmt, which is either a single stmt or a Compound if there's # a block. # # Let's dig deeper, to the while statement inside the for loop: while_stmt = for_stmt.stmt.block_items[1] # while_stmt.show() # While is simpler, it only has a condition node and a stmt node. # The condition: while_cond = while_stmt.cond # while_cond.show() # Note that it's a BinaryOp node - the basic constituent of # expressions in our AST. BinaryOp is the expression tree, with # left and right nodes as children. It also has the op attribute, # which is just the string representation of the operator. # print(while_cond.op) # while_cond.left.show() # while_cond.right.show() # That's it for the example. I hope you now see how easy it is to explore the # AST created by pycparser. Although on the surface it is quite complex and has # a lot of node types, this is the inherent complexity of the C language every # parser/compiler designer has to cope with. # Using the tools provided by the c_ast package it's easy to explore the # structure of AST nodes and write code that processes them. # Specifically, see the cdecl.py example for a non-trivial demonstration of what # you can do by recursively going through the AST. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1769004602.2595415 pycparser-3.12/examples/func_calls.py0000664000175000017500000000257215134157072017303 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: func_calls.py # # Using pycparser for printing out all the calls of some function # in a C file. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import c_ast, parse_file # A visitor with some state information (the funcname it's looking for) class FuncCallVisitor(c_ast.NodeVisitor): def __init__(self, funcname: str) -> None: self.funcname = funcname def visit_FuncCall(self, node: c_ast.FuncCall) -> None: if isinstance(node.name, c_ast.ID) and node.name.name == self.funcname: print(f"{self.funcname} called at {node.name.coord}") # Visit args in case they contain more func calls. if node.args is not None: self.visit(node.args) def show_func_calls(filename: str, funcname: str) -> None: ast = parse_file(filename, use_cpp=True) v = FuncCallVisitor(funcname) v.visit(ast) if __name__ == "__main__": if len(sys.argv) > 2: filename = sys.argv[1] func = sys.argv[2] else: filename = "examples/c_files/basic.c" func = "foo" show_func_calls(filename, func) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1769004602.2595415 pycparser-3.12/examples/func_defs.py0000664000175000017500000000243215134157072017121 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: func_defs.py # # Using pycparser for printing out all the functions defined in a # C file. # # This is a simple example of traversing the AST generated by # pycparser. Call it from the root directory of pycparser. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import c_ast, parse_file # A simple visitor for FuncDef nodes that prints the names and # locations of function definitions. class FuncDefVisitor(c_ast.NodeVisitor): def visit_FuncDef(self, node: c_ast.FuncDef) -> None: print(f"{node.decl.name} at {node.decl.coord}") def show_func_defs(filename: str) -> None: # Note that cpp is used. Provide a path to your own cpp or # make sure one exists in PATH. ast = parse_file(filename, use_cpp=True, cpp_args=r"-Iutils/fake_libc_include") v = FuncDefVisitor() v.visit(ast) if __name__ == "__main__": if len(sys.argv) > 1: filename = sys.argv[1] else: filename = "examples/c_files/memmgr.c" show_func_defs(filename) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1791897874.1314182 pycparser-3.12/examples/func_defs_add_param.py0000664000175000017500000000273215263430422021110 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: func_defs_add_param.py # # Example of rewriting AST nodes to add parameters to function # definitions. Adds an "int _hidden" to every function. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import sys sys.path.extend([".", ".."]) from pycparser import c_ast, c_generator, c_parser text = r""" void foo(int a, int b) { } void bar() { } """ class ParamAdder(c_ast.NodeVisitor): def visit_FuncDecl(self, node: c_ast.FuncDecl) -> None: ty = c_ast.TypeDecl( declname="_hidden", quals=[], align=[], type=c_ast.IdentifierType(["int"]) ) newdecl = c_ast.Decl( name="_hidden", quals=[], align=[], storage=[], funcspec=[], type=ty, init=None, bitsize=None, coord=node.coord, ) if node.args is not None: node.args.params.append(newdecl) else: node.args = c_ast.ParamList(params=[newdecl]) if __name__ == "__main__": parser = c_parser.CParser() ast = parser.parse(text) print("AST before change:") ast.show(offset=2) v = ParamAdder() v.visit(ast) print("\nAST after change:") ast.show(offset=2) print("\nCode after change:") generator = c_generator.CGenerator() print(generator.visit(ast)) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1769004602.2595415 pycparser-3.12/examples/rewrite_ast.py0000664000175000017500000000123415134157072017514 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: rewrite_ast.py # # Tiny example of rewriting a AST node # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import sys sys.path.extend([".", ".."]) from pycparser import c_parser text = r""" void func(void) { x = 1; } """ if __name__ == "__main__": parser = c_parser.CParser() ast = parser.parse(text) print("Before:") ast.show(offset=2) assign = ast.ext[0].body.block_items[0] assign.lvalue.name = "y" assign.rvalue.value = 2 print("After:") ast.show(offset=2) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1769004602.2595415 pycparser-3.12/examples/serialize_ast.py0000664000175000017500000000154415134157072020026 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: serialize_ast.py # # Simple example of serializing AST # # Hart Chu [https://github.com/CtheSky] # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import pickle import sys import tempfile sys.path.extend([".", ".."]) from pycparser import c_parser text = r""" void func(void) { x = 1; } """ if __name__ == "__main__": parser = c_parser.CParser() ast = parser.parse(text) with tempfile.NamedTemporaryFile(delete=False, suffix=".pickle") as f: dump_filename = f.name pickle.dump(ast, f, protocol=pickle.HIGHEST_PROTOCOL) print(f"Dumped to {dump_filename}") # Deserialize. with open(dump_filename, "rb") as f: ast = pickle.load(f) ast.show() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785327145.0301766 pycparser-3.12/examples/typed_usage.py0000664000175000017500000000456315232367051017504 0ustar00elibeneliben# ------------------------------------------------------------------------------ # pycparser: typed_usage.py # # A minimal example of how static type checking helps use pycparser correctly. # # The important parts are the narrowings: # - ast.ext[...] entries start out as generic AST nodes # - Decl.coord is optional and must be checked before use # - Decl.type must be narrowed before accessing node-specific attributes # # Run it from the root directory of pycparser. # ------------------------------------------------------------------------------ import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import c_ast, c_parser SAMPLE_DECL = "const unsigned int *value;" def parse_single_decl(source: str) -> c_ast.Decl: ast = c_parser.CParser().parse(source, filename="") node = ast.ext[-1] # Without this guard, type checkers only know that ext entries are Nodes. if not isinstance(node, c_ast.Decl): raise TypeError("expected a declaration") return node def require_coord(node: c_ast.Node) -> c_parser.Coord: coord = node.coord # Without this guard, `coord.line` is a type error because coord may be None. if coord is None: raise ValueError("node has no source coordinate") return coord def describe_type(type_node: c_ast.Node) -> str: # Without these isinstance checks, attributes such as `.type`, `.quals`, # and `.names` are not safe to access. if isinstance(type_node, c_ast.TypeDecl): quals = " ".join(type_node.quals) base = describe_type(type_node.type) return f"{quals} {base}".strip() if isinstance(type_node, c_ast.PtrDecl): quals = " ".join(type_node.quals) pointer = "pointer" if quals: pointer = f"{quals} {pointer}" return f"{pointer} to {describe_type(type_node.type)}" if isinstance(type_node, c_ast.IdentifierType): return " ".join(type_node.names) raise TypeError(f"unsupported declaration type: {type_node.__class__.__name__}") def show_decl(source: str) -> None: decl = parse_single_decl(source) coord = require_coord(decl) print(f"{decl.name}: {describe_type(decl.type)} at {coord}") if __name__ == "__main__": if len(sys.argv) > 1: show_decl(sys.argv[1]) else: show_decl(SAMPLE_DECL) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785327145.0291767 pycparser-3.12/examples/using_cpp_libc.py0000664000175000017500000000144515232367051020147 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: using_cpp_libc.py # # Shows how to use 'cpp' (the C pre-processor binary) and "fake" libc includes # to parse a file that includes standard C headers. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import parse_file if __name__ == "__main__": if len(sys.argv) > 1: filename = sys.argv[1] else: filename = "examples/c_files/year.c" ast = parse_file( filename, use_cpp=True, cpp_path="cpp", cpp_args=r"-Iutils/fake_libc_include" ) ast.show() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785327145.0291767 pycparser-3.12/examples/using_gcc_E_libc.py0000664000175000017500000000165615232367051020371 0ustar00elibeneliben# ------------------------------------------------------------------------------- # pycparser: using_gcc_E_libc.py # # Similar to the using_cpp_libc.py example, but uses 'gcc -E' instead # of 'cpp'. The same can be achieved with Clang instead of gcc. If you have # Clang installed, simply replace 'gcc' with 'clang' here. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ------------------------------------------------------------------------------- import sys # This is not required if you've installed pycparser into # your site-packages/ with setup.py sys.path.extend([".", ".."]) from pycparser import parse_file if __name__ == "__main__": if len(sys.argv) > 1: filename = sys.argv[1] else: filename = "examples/c_files/year.c" ast = parse_file( filename, use_cpp=True, cpp_path="gcc", cpp_args=["-E", r"-Iutils/fake_libc_include"], ) ast.show() ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1792676218.851459 pycparser-3.12/pycparser/0000775000175000017500000000000015266410573015010 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792675421.7071989 pycparser-3.12/pycparser/__init__.py0000664000175000017500000000540015266407136017121 0ustar00elibeneliben# ----------------------------------------------------------------- # pycparser: __init__.py # # This package file exports some convenience functions for # interacting with pycparser # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- __all__ = ["c_ast", "c_lexer", "c_parser"] __version__ = "3.12" from subprocess import check_output from . import c_parser CParser = c_parser.CParser def preprocess_file(filename, cpp_path="cpp", cpp_args=""): """Preprocess a file using cpp. filename: Name of the file you want to preprocess. cpp_path: cpp_args: Refer to the documentation of parse_file for the meaning of these arguments. When successful, returns the preprocessed file's contents. Errors from cpp will be printed out. """ path_list = [cpp_path] if isinstance(cpp_args, list): path_list += cpp_args elif cpp_args != "": path_list += [cpp_args] path_list += [filename] try: # Note the use of universal_newlines to treat all newlines # as \n for Python's purpose text = check_output(path_list, universal_newlines=True) except OSError as e: raise RuntimeError( "Unable to invoke 'cpp'. " + "Make sure its path was passed correctly\n" + f"Original error: {e}" ) return text def parse_file( filename, use_cpp=False, cpp_path="cpp", cpp_args="", parser=None, encoding=None ): """Parse a C file using pycparser. filename: Name of the file you want to parse. use_cpp: Set to True if you want to execute the C pre-processor on the file prior to parsing it. cpp_path: If use_cpp is True, this is the path to 'cpp' on your system. If no path is provided, it attempts to just execute 'cpp', so it must be in your PATH. cpp_args: If use_cpp is True, set this to the command line arguments strings to cpp. Be careful with quotes - it's best to pass a raw string (r'') here. For example: r'-I../utils/fake_libc_include' If several arguments are required, pass a list of strings. encoding: Encoding to use for the file to parse parser: Optional parser object to be used instead of the default CParser When successful, an AST is returned. ParseError can be thrown if the file doesn't parse successfully. Errors from cpp will be printed out. """ if use_cpp: text = preprocess_file(filename, cpp_path, cpp_args) else: with open(filename, encoding=encoding) as f: text = f.read() if parser is None: parser = CParser() return parser.parse(text, filename) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792674652.4485247 pycparser-3.12/pycparser/_ast_gen.py0000664000175000017500000003111315266405534017141 0ustar00elibeneliben# ----------------------------------------------------------------- # _ast_gen.py # # Generates the AST Node classes from a specification given in # a configuration file. Run 'make regen-ast' from the repository root # to regenerate c_ast.py from _c_ast.cfg and format the code. # This module can also be run as a script (from the repo root or the # pycparser/ directory); then run 'make format' from the repo root. # # The design of this module was inspired by astgen.py from the # Python 2.5 code-base. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import os from string import Template from typing import IO class ASTCodeGenerator: def __init__(self, cfg_filename="_c_ast.cfg"): """Initialize the code generator from a configuration file. """ self.cfg_filename = cfg_filename self.node_cfg = [ NodeCfg(name, contents) for (name, contents) in self.parse_cfgfile(cfg_filename) ] def generate(self, file: IO[str]) -> None: """Generates the code into file, an open file buffer.""" src = Template(_PROLOGUE_COMMENT).substitute(cfg_filename=self.cfg_filename) src += _PROLOGUE_CODE for node_cfg in self.node_cfg: src += node_cfg.generate_source() + "\n\n" file.write(src) def parse_cfgfile(self, filename): """Parse the configuration file and yield pairs of (name, contents) for each node. """ with open(filename, "r") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue colon_i = line.find(":") lbracket_i = line.find("[") # A field's default may contain []; find the outer closing bracket. rbracket_i = line.rfind("]") if colon_i < 1 or lbracket_i <= colon_i or rbracket_i <= lbracket_i: raise RuntimeError(f"Invalid line in {filename}:\n{line}\n") name = line[:colon_i] val = line[lbracket_i + 1 : rbracket_i] vallist = [v.strip() for v in val.split(",")] if val else [] yield name, vallist class NodeCfg: """Node configuration. name: node name contents: a list of contents - attributes and child nodes See comment at the top of the configuration file for details. """ def __init__(self, name, contents): self.name = name self.all_entries = [] self.attr = [] self.child = [] self.seq_child = [] self.defaults = {} for entry in contents: entry, has_default, default = entry.partition("=") entry = entry.strip() clean_entry = entry.rstrip("*") self.all_entries.append(clean_entry) if has_default: default = default.strip() if default not in ("None", "[]"): raise RuntimeError( f"Unsupported default {default!r} for {name}.{clean_entry}; " "expected None or []" ) self.defaults[clean_entry] = default if entry.endswith("**"): self.seq_child.append(clean_entry) elif entry.endswith("*"): self.child.append(clean_entry) else: self.attr.append(entry) def generate_source(self): src = self._gen_init() src += "\n" + self._gen_children() src += "\n" + self._gen_iter() src += "\n" + self._gen_attr_names() return src def _gen_init(self): src = f"class {self.name}(Node):\n" args = ["self"] args.extend(name for name in self.all_entries if name not in self.defaults) args.append("coord=None") # Defaulted fields are keyword-only so adding one doesn't shift coord # in existing positional calls. Both supported defaults use None here; # list defaults are initialized separately for each instance below. if self.defaults: args.append("*") args.extend(f"{name}=None" for name in self.defaults) arglist = f"({', '.join(args)})" # Keep coord and __weakref__ last: Node.__repr__ relies on their # positions when iterating over the node's fields. slots = ", ".join( repr(name) for name in self.all_entries + ["coord", "__weakref__"] ) src += f" __slots__ = ({slots})\n" src += f" def __init__{arglist}:\n" for name in self.all_entries + ["coord"]: if self.defaults.get(name) == "[]": src += f" self.{name} = [] if {name} is None else {name}\n" else: src += f" self.{name} = {name}\n" return src def _gen_children(self): src = " def children(self):\n" if self.all_entries: src += " nodelist = []\n" for child in self.child: src += f" if self.{child} is not None:\n" src += f' nodelist.append(("{child}", self.{child}))\n' for seq_child in self.seq_child: src += f" for i, child in enumerate(self.{seq_child} or []):\n" src += f' nodelist.append((f"{seq_child}[{{i}}]", child))\n' src += " return tuple(nodelist)\n" else: src += " return ()\n" return src def _gen_iter(self): src = " def __iter__(self):\n" if self.all_entries: for child in self.child: src += f" if self.{child} is not None:\n" src += f" yield self.{child}\n" for seq_child in self.seq_child: src += f" yield from self.{seq_child} or []\n" if not (self.child or self.seq_child): # Empty generator src += " return\n" + " yield\n" else: # Empty generator src += " return\n" + " yield\n" return src def _gen_attr_names(self): src = " attr_names = (" + "".join(f"{nm!r}, " for nm in self.attr) + ")" return src _PROLOGUE_COMMENT = r"""#----------------------------------------------------------------- # ** ATTENTION ** # This code was automatically generated from _c_ast.cfg # # Do not modify it directly. Modify the configuration file and # run 'make regen-ast' from the repository root to regenerate and format it. # ** ** *** ** ** # # The order of generated __slots__ is significant to Node.__repr__. # ruff: noqa: RUF023 # # pycparser: c_ast.py # # AST Node classes. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD #----------------------------------------------------------------- """ _PROLOGUE_CODE = r''' import sys from typing import IO, Any, ClassVar def _repr(obj): """ Get the representation of an object, with dedicated pprint-like format for lists. """ if isinstance(obj, list): return '[' + (',\n '.join(_repr(e).replace('\n', '\n ') for e in obj)) + '\n]' else: return repr(obj) class Node: __slots__ = () """ Abstract base class for AST nodes. """ attr_names: ClassVar[tuple[str, ...]] = () coord: Any | None def __repr__(self): """ Generates a python representation of the current node """ result = self.__class__.__name__ + '(' indent = '' separator = '' for name in self.__slots__[:-2]: result += separator result += indent result += name + '=' + (_repr(getattr(self, name)).replace('\n', '\n ' + (' ' * (len(name) + len(self.__class__.__name__))))) separator = ',' indent = '\n ' + (' ' * len(self.__class__.__name__)) result += indent + ')' return result def children(self): """Return a tuple of (name, child) pairs for immediate child nodes. Names identify the field and, for list fields, the index, such as "type" or "ext[0]". Optional children that are None are omitted. The returned tuple supports len() and indexing. Iterating over the node itself yields just the child nodes, without their names. """ def show( self, buf: IO[str] = sys.stdout, offset: int = 0, attrnames: bool = False, showemptyattrs: bool = True, nodenames: bool = False, showcoord: bool = False, _my_node_name: str | None = None, ): """ Pretty print the Node and all its attributes and children (recursively) to a buffer. buf: Open IO buffer into which the Node is printed. offset: Initial offset (amount of leading spaces) attrnames: True if you want to see the attribute names in name=value pairs. False to only see the values. showemptyattrs: False if you want to suppress printing empty attributes. nodenames: True if you want to see the actual node names within their parents. showcoord: Do you want the coordinates of each Node to be displayed. """ lead = ' ' * offset if nodenames and _my_node_name is not None: buf.write(lead + self.__class__.__name__+ ' <' + _my_node_name + '>: ') else: buf.write(lead + self.__class__.__name__+ ': ') if self.attr_names: def is_empty(v): return v is None or (hasattr(v, '__len__') and len(v) == 0) nvlist = [(n, getattr(self,n)) for n in self.attr_names \ if showemptyattrs or not is_empty(getattr(self,n))] if attrnames: attrstr = ', '.join(f'{name}={value}' for name, value in nvlist) else: attrstr = ', '.join(f'{value}' for _, value in nvlist) buf.write(attrstr) if showcoord: buf.write(f' (at {self.coord})') buf.write('\n') for (child_name, child) in self.children(): child.show( buf, offset=offset + 2, attrnames=attrnames, showemptyattrs=showemptyattrs, nodenames=nodenames, showcoord=showcoord, _my_node_name=child_name) class NodeVisitor: """ A base NodeVisitor class for visiting c_ast nodes. Subclass it and define your own visit_XXX methods, where XXX is the class name you want to visit with these methods. For example: class ConstantVisitor(NodeVisitor): def __init__(self): self.values = [] def visit_Constant(self, node): self.values.append(node.value) Creates a list of values of all the constant nodes encountered below the given node. To use it: cv = ConstantVisitor() cv.visit(node) Notes: * generic_visit() will be called for AST nodes for which no visit_XXX method was defined. * The children of nodes for which a visit_XXX was defined will not be visited - if you need this, call generic_visit() on the node. You can use: NodeVisitor.generic_visit(self, node) * Modeled after Python's own AST visiting facilities (the ast module of Python 3.0) """ _method_cache = None def visit(self, node: Node): """ Visit a node. """ if self._method_cache is None: self._method_cache = {} visitor = self._method_cache.get(node.__class__.__name__, None) if visitor is None: method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) self._method_cache[node.__class__.__name__] = visitor return visitor(node) def generic_visit(self, node: Node): """ Called if no explicit visitor function exists for a node. Implements preorder visiting of the node. """ for _, c in node.children(): self.visit(c) ''' if __name__ == "__main__": base_dir = os.path.dirname(os.path.abspath(__file__)) cfg_path = os.path.join(base_dir, "_c_ast.cfg") out_path = os.path.join(base_dir, "c_ast.py") ast_gen = ASTCodeGenerator(cfg_path) with open(out_path, "w") as out: ast_gen.generate(out) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792587002.0920928 pycparser-3.12/pycparser/_c_ast.cfg0000664000175000017500000001733415266132372016727 0ustar00elibeneliben#----------------------------------------------------------------- # pycparser: _c_ast.cfg # # Defines the AST Node classes used in pycparser. # After editing, run 'make regen-ast' from the repository root to # regenerate pycparser/c_ast.py and format the code. # # Each entry is a Node sub-class name, listing the attributes # and child nodes of the class: # * - a child node # ** - a sequence of child nodes # - an attribute # # Append =None or =[] to any field to give it a constructor default, e.g.: # Example: [name, child*=None, items**=[], flags=[]] # Defaulted fields are keyword-only arguments after coord; fields without # defaults remain required positional-or-keyword arguments in the listed order. # A [] default creates a fresh list when omitted or passed None, and otherwise # keeps the supplied value. Defaults do not change slots or child traversal. # # Fields named attributes contain AttributeSpecifier groups. Their owning node # determines placement: declarations/parameters and labels use prefixes, tags # put them after struct/union/enum, and declarators put them after the # identifier, '*', ']', or ')' that the node represents. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD #----------------------------------------------------------------- # ArrayDecl is a nested declaration of an array with the given type. # dim: the dimension (for example, constant 42) # dim_quals: list of dimension qualifiers, to support C99's allowing 'const' # and 'static' within the array dimension in function declarations. ArrayDecl: [type*, dim*, dim_quals, attributes**=[]] # An array designator [expr] in a NamedInitializer. The wrapper distinguishes # an identifier used as an array index from a field designator such as .field. ArrayDesignator: [expr*] ArrayRef: [name*, subscript*] # op: =, +=, /= etc. # Assignment: [op, lvalue*, rvalue*] Alignas: [alignment*] # Generic C23 attribute; arguments is raw text inside parentheses, or None # when no argument clause was written. namespace is None for unprefixed names. Attribute: [name, namespace, arguments] # One [[...]] group; empty attribute-list entries are ignored. AttributeSpecifier: [attributes**] # A standalone attribute declaration, including [[fallthrough]];. AttributeDeclaration: [attributes**] # Attribute prefixes on statements other than labels (which have their own # attributes field to retain the existing switch-case AST structure). AttributedStatement: [attributes**, stmt*] # Attributes following a declaration's type specifiers and qualifiers. AttributedType: [type*, attributes**] BinaryOp: [op, left*, right*] # A C23 bit-precise integer type, used as TypeDecl.type. # width: the constant expression specifying the bit width, left unevaluated # signedness: 'signed', 'unsigned', or None when omitted # BitIntType: [width*, signedness] Break: [] Case: [expr*, stmts**, attributes**=[]] Cast: [to_type*, expr*] # Compound statement in C99 is a list of block items (declarations or # statements). # Compound: [block_items**] # Compound literal (anonymous object), with optional storage specifiers in C23. # (storage-class-specifiers? type-name) {initializer_list} # type: the typename # init: InitList for the initializer list # storage: list of storage-class specifiers, empty when omitted # CompoundLiteral: [type*, init*, storage] # type: int, char, float, string, etc. # value: source spelling. A string may retain adjacent quoted fragments to # preserve escape boundaries, e.g. "\x1" "a". # Constant: [type, value] Continue: [] # name: the variable being declared # quals: list of qualifiers (const, volatile) # funcspec: list function specifiers (i.e. inline in C99) # storage: list of storage specifiers (extern, register, etc.) # type: declaration type (probably nested with all the modifiers) # init: initialization value, or None # bitsize: bit field size, or None # Decl: [name, quals, align, storage, funcspec, type*, init*, bitsize*, attributes**=[]] # Declarations sharing specifiers, optionally followed by Pragma nodes before # the semicolon (in a for initializer). DeclList: [decls**] Default: [stmts**, attributes**=[]] DoWhile: [cond*, stmt*] # Represents the ellipsis (...) parameter in a function # declaration # EllipsisParam: [] # An empty statement (a semicolon ';' on its own) # EmptyStatement: [] # Enumeration type specifier # name: an optional ID # values: an EnumeratorList # underlying_type: an optional Typename for a C23 fixed underlying type # Enum: [name, values*, underlying_type*, attributes**=[]] # A name/value pair for enumeration values # Enumerator: [name, value*, attributes**=[]] # A list of Enumerator and Pragma nodes in source order. # EnumeratorList: [enumerators**] # A list of expressions separated by the comma operator. # ExprList: [exprs**] # This is the top of the AST, representing a single C file (a # translation unit in K&R jargon). It contains a list of # "external-declaration"s, which is either declarations (Decl), # Typedef or function definitions (FuncDef). # FileAST: [ext**] # for (init; cond; next) stmt # For: [init*, cond*, next*, stmt*] # name: Id # args: ExprList # FuncCall: [name*, args*] # type (args) # FuncDecl: [args*, type*, attributes**=[]] # Function definition: a declarator for the function name and # a body, which is a compound statement. # There's an optional list of parameter declarations for old # K&R-style definitions # FuncDef: [decl*, param_decls**, body*] # One association in a C11 generic selection. # type: Typename, or None for the default association # expr: the result expression for this association # GenericAssociation: [type*, expr*] # A C11 _Generic expression. All associations are preserved in source order. # expr: the controlling expression (not evaluated by C) # associations: a nonempty sequence of GenericAssociation nodes # GenericSelection: [expr*, associations**] Goto: [name] ID: [name] # Holder for types that are a simple identifier (e.g. the built # ins void, char etc. and typedef-defined types) # IdentifierType: [names] If: [cond*, iftrue*, iffalse*] # The unresolved type of a C23 auto declaration. Used as TypeDecl.type; # the initializer remains on Decl and "auto" remains in Decl.storage. # InferredType: [] # An initialization list used for compound literals. # InitList: [exprs**] Label: [name, stmt*, attributes**=[]] # A named initializer for C99. # name is a sequence of ID nodes for .field designators and ArrayDesignator # nodes for [expr] designators, allowing combinations such as [i].field[j]. # NamedInitializer: [name**, expr*] # a list of comma separated function parameter declarations # ParamList: [params**] PtrDecl: [quals, type*, attributes**=[]] Return: [expr*] # A static assertion declaration. The condition is preserved without evaluation. # message: a string Constant, or None for the message-less extension # StaticAssert: [cond*, message*] # name: struct tag name # decls: declaration of members # Struct: [name, decls**, attributes**=[]] # type: . or -> # name.field or name->field # StructRef: [name*, type, field*] Switch: [cond*, stmt*] # cond ? iftrue : iffalse # TernaryOp: [cond*, iftrue*, iffalse*] # A base type declaration # TypeDecl: [declname, quals, align, type*, attributes**=[]] # A typedef declaration. # Very similar to Decl, but without some attributes # Typedef: [name, quals, storage, type*, attributes**=[]] Typename: [name, quals, align, type*, attributes**=[]] # A C23 typeof specifier, used as TypeDecl.type without resolving its type. # op: typeof or typeof_unqual # expr: a Typename for a type operand, otherwise an expression # TypeOf: [op, expr*] UnaryOp: [op, expr*] # name: union tag name # decls: declaration of members # Union: [name, decls**, attributes**=[]] While: [cond*, stmt*] Pragma: [string] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1791908798.9795163 pycparser-3.12/pycparser/ast_transforms.py0000664000175000017500000001620715263455677020450 0ustar00elibeneliben# ------------------------------------------------------------------------------ # pycparser: ast_transforms.py # # Some utilities used by the parser to create a friendlier AST. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ------------------------------------------------------------------------------ from copy import deepcopy from typing import Any, cast from . import c_ast def fix_switch_cases(switch_node: c_ast.Switch) -> c_ast.Switch: """The 'case' statements in a 'switch' come out of parsing with one child node, so subsequent statements are just tucked to the parent Compound. Additionally, consecutive (fall-through) case statements come out messy. This is a peculiarity of the C grammar. The following: switch (myvar) { case 10: k = 10; p = k + 1; return 10; case 20: case 30: return 20; default: break; } Creates this tree (pseudo-dump): Switch ID: myvar Compound: Case 10: k = 10 p = k + 1 return 10 Case 20: Case 30: return 20 Default: break The goal of this transform is to fix this mess, turning it into the following: Switch ID: myvar Compound: Case 10: k = 10 p = k + 1 return 10 Case 20: Case 30: return 20 Default: break A fixed AST node is returned. The argument may be modified. """ assert isinstance(switch_node, c_ast.Switch) if isinstance(switch_node.stmt, c_ast.AttributedStatement): attributed = switch_node.stmt switch_node.stmt = attributed.stmt fix_switch_cases(switch_node) attributed.stmt = switch_node.stmt switch_node.stmt = attributed return switch_node if not isinstance(switch_node.stmt, c_ast.Compound): return switch_node # The new Compound child for the Switch, which will collect children in the # correct order new_compound = c_ast.Compound([], switch_node.stmt.coord) # The last Case/Default node last_case: c_ast.Case | c_ast.Default | None = None # Goes over the children of the Compound below the Switch, adding them # either directly below new_compound or below the last Case as appropriate # (for `switch(cond) {}`, block_items would have been None) for child in switch_node.stmt.block_items or []: if isinstance(child, (c_ast.Case, c_ast.Default)): # If it's a Case/Default: # 1. Add it to the Compound and mark as "last case" # 2. If its immediate child is also a Case or Default, promote it # to a sibling. new_compound.block_items.append(child) _extract_nested_case(child, new_compound.block_items) last_case = new_compound.block_items[-1] else: # Other statements are added as children to the last case, if it # exists. if last_case is None: new_compound.block_items.append(child) else: last_case.stmts.append(child) switch_node.stmt = new_compound return switch_node def _extract_nested_case( case_node: c_ast.Case | c_ast.Default, stmts_list: list[c_ast.Node] ) -> None: """Recursively extract consecutive Case statements that are made nested by the parser and add them to the stmts_list. """ if isinstance(case_node.stmts[0], (c_ast.Case, c_ast.Default)): nested = case_node.stmts.pop() stmts_list.append(nested) _extract_nested_case(cast(Any, nested), stmts_list) def fix_atomic_specifiers( decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename, ) -> c_ast.Decl | c_ast.Typedef | c_ast.Typename: """Atomic specifiers like _Atomic(type) are unusually structured, conferring a qualifier upon the contained type. This function fixes a decl with atomic specifiers to have a sane AST structure, by removing spurious Typename->TypeDecl pairs and attaching the _Atomic qualifier in the right place. """ # There can be multiple levels of _Atomic in a decl; fix them until a # fixed point is reached. while True: decl, found = _fix_atomic_specifiers_once(decl) if not found: break # Match the declaration's qualifiers to the innermost TypeDecl, as for # ordinary declarations. Qualifiers moved onto pointers belong only on # those PtrDecl nodes. Also restore the name lost with the wrapper TypeDecl. typ: Any = decl while not isinstance(typ, c_ast.TypeDecl): try: typ = typ.type except AttributeError: return decl decl.quals = typ.quals[:] if typ.declname is None: typ.declname = decl.name return decl def _fix_atomic_specifiers_once( decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename, ) -> tuple[c_ast.Decl | c_ast.Typedef | c_ast.Typename, bool]: """Performs one 'fix' round of atomic specifiers. Returns (modified_decl, found) where found is True iff a fix was made. """ parent: Any = decl grandparent: Any = None node: Any = decl.type while node is not None: if isinstance(node, c_ast.Typename) and "_Atomic" in node.quals: break try: grandparent = parent parent = node node = node.type except AttributeError: # If we've reached a node without a `type` field, it means we won't # find what we're looking for at this point; give up the search # and return the original decl unmodified. return decl, False assert isinstance(parent, c_ast.TypeDecl) assert grandparent is not None # _Atomic(T) cannot wrap an array or function type (C11 6.7.2.4p3). Such a T # has no `quals` to merge below, so report it instead of letting the attach # raise AttributeError out of parse(). if isinstance(node.type, (c_ast.ArrayDecl, c_ast.FuncDecl)): # Imported here to avoid a circular import at module load time. from .c_parser import ParseError raise ParseError( f"{node.coord}: _Atomic cannot be applied to array or function type" ) # Declaration specifiers are shared by comma-separated declarators. Copy # the contained type before attaching qualifiers, coordinates, and a name. typ = deepcopy(node.type) if typ.coord is None: # Preserve the declarator coord for _Atomic(T) so TypeDecl doesn't lose # its location when we replace the wrapper Typename. typ.coord = parent.coord # Qualifiers outside _Atomic(T) apply to T itself. In particular, const in # const _Atomic(int *) qualifies the pointer, not the pointed-to int. typ.quals = parent.quals + typ.quals if "_Atomic" not in typ.quals: typ.quals.append("_Atomic") cast(Any, grandparent).type = typ return decl, True ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792675394.3954527 pycparser-3.12/pycparser/c_ast.py0000664000175000017500000012406615266407102016456 0ustar00elibeneliben# ----------------------------------------------------------------- # ** ATTENTION ** # This code was automatically generated from _c_ast.cfg # # Do not modify it directly. Modify the configuration file and # run 'make regen-ast' from the repository root to regenerate and format it. # ** ** *** ** ** # # The order of generated __slots__ is significant to Node.__repr__. # ruff: noqa: RUF023 # # pycparser: c_ast.py # # AST Node classes. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ----------------------------------------------------------------- import sys from typing import IO, Any, ClassVar def _repr(obj): """ Get the representation of an object, with dedicated pprint-like format for lists. """ if isinstance(obj, list): return "[" + (",\n ".join(_repr(e).replace("\n", "\n ") for e in obj)) + "\n]" else: return repr(obj) class Node: __slots__ = () """ Abstract base class for AST nodes. """ attr_names: ClassVar[tuple[str, ...]] = () coord: Any | None def __repr__(self): """Generates a python representation of the current node""" result = self.__class__.__name__ + "(" indent = "" separator = "" for name in self.__slots__[:-2]: result += separator result += indent result += ( name + "=" + ( _repr(getattr(self, name)).replace( "\n", "\n " + (" " * (len(name) + len(self.__class__.__name__))), ) ) ) separator = "," indent = "\n " + (" " * len(self.__class__.__name__)) result += indent + ")" return result def children(self): """Return a tuple of (name, child) pairs for immediate child nodes. Names identify the field and, for list fields, the index, such as "type" or "ext[0]". Optional children that are None are omitted. The returned tuple supports len() and indexing. Iterating over the node itself yields just the child nodes, without their names. """ def show( self, buf: IO[str] = sys.stdout, offset: int = 0, attrnames: bool = False, showemptyattrs: bool = True, nodenames: bool = False, showcoord: bool = False, _my_node_name: str | None = None, ): """Pretty print the Node and all its attributes and children (recursively) to a buffer. buf: Open IO buffer into which the Node is printed. offset: Initial offset (amount of leading spaces) attrnames: True if you want to see the attribute names in name=value pairs. False to only see the values. showemptyattrs: False if you want to suppress printing empty attributes. nodenames: True if you want to see the actual node names within their parents. showcoord: Do you want the coordinates of each Node to be displayed. """ lead = " " * offset if nodenames and _my_node_name is not None: buf.write(lead + self.__class__.__name__ + " <" + _my_node_name + ">: ") else: buf.write(lead + self.__class__.__name__ + ": ") if self.attr_names: def is_empty(v): return v is None or (hasattr(v, "__len__") and len(v) == 0) nvlist = [ (n, getattr(self, n)) for n in self.attr_names if showemptyattrs or not is_empty(getattr(self, n)) ] if attrnames: attrstr = ", ".join(f"{name}={value}" for name, value in nvlist) else: attrstr = ", ".join(f"{value}" for _, value in nvlist) buf.write(attrstr) if showcoord: buf.write(f" (at {self.coord})") buf.write("\n") for child_name, child in self.children(): child.show( buf, offset=offset + 2, attrnames=attrnames, showemptyattrs=showemptyattrs, nodenames=nodenames, showcoord=showcoord, _my_node_name=child_name, ) class NodeVisitor: """A base NodeVisitor class for visiting c_ast nodes. Subclass it and define your own visit_XXX methods, where XXX is the class name you want to visit with these methods. For example: class ConstantVisitor(NodeVisitor): def __init__(self): self.values = [] def visit_Constant(self, node): self.values.append(node.value) Creates a list of values of all the constant nodes encountered below the given node. To use it: cv = ConstantVisitor() cv.visit(node) Notes: * generic_visit() will be called for AST nodes for which no visit_XXX method was defined. * The children of nodes for which a visit_XXX was defined will not be visited - if you need this, call generic_visit() on the node. You can use: NodeVisitor.generic_visit(self, node) * Modeled after Python's own AST visiting facilities (the ast module of Python 3.0) """ _method_cache = None def visit(self, node: Node): """Visit a node.""" if self._method_cache is None: self._method_cache = {} visitor = self._method_cache.get(node.__class__.__name__, None) if visitor is None: method = "visit_" + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) self._method_cache[node.__class__.__name__] = visitor return visitor(node) def generic_visit(self, node: Node): """Called if no explicit visitor function exists for a node. Implements preorder visiting of the node. """ for _, c in node.children(): self.visit(c) class ArrayDecl(Node): __slots__ = ("type", "dim", "dim_quals", "attributes", "coord", "__weakref__") def __init__(self, type, dim, dim_quals, coord=None, *, attributes=None): self.type = type self.dim = dim self.dim_quals = dim_quals self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.type is not None: nodelist.append(("type", self.type)) if self.dim is not None: nodelist.append(("dim", self.dim)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.type is not None: yield self.type if self.dim is not None: yield self.dim yield from self.attributes or [] attr_names = ("dim_quals",) class ArrayDesignator(Node): __slots__ = ("expr", "coord", "__weakref__") def __init__(self, expr, coord=None): self.expr = expr self.coord = coord def children(self): nodelist = [] if self.expr is not None: nodelist.append(("expr", self.expr)) return tuple(nodelist) def __iter__(self): if self.expr is not None: yield self.expr attr_names = () class ArrayRef(Node): __slots__ = ("name", "subscript", "coord", "__weakref__") def __init__(self, name, subscript, coord=None): self.name = name self.subscript = subscript self.coord = coord def children(self): nodelist = [] if self.name is not None: nodelist.append(("name", self.name)) if self.subscript is not None: nodelist.append(("subscript", self.subscript)) return tuple(nodelist) def __iter__(self): if self.name is not None: yield self.name if self.subscript is not None: yield self.subscript attr_names = () class Assignment(Node): __slots__ = ("op", "lvalue", "rvalue", "coord", "__weakref__") def __init__(self, op, lvalue, rvalue, coord=None): self.op = op self.lvalue = lvalue self.rvalue = rvalue self.coord = coord def children(self): nodelist = [] if self.lvalue is not None: nodelist.append(("lvalue", self.lvalue)) if self.rvalue is not None: nodelist.append(("rvalue", self.rvalue)) return tuple(nodelist) def __iter__(self): if self.lvalue is not None: yield self.lvalue if self.rvalue is not None: yield self.rvalue attr_names = ("op",) class Alignas(Node): __slots__ = ("alignment", "coord", "__weakref__") def __init__(self, alignment, coord=None): self.alignment = alignment self.coord = coord def children(self): nodelist = [] if self.alignment is not None: nodelist.append(("alignment", self.alignment)) return tuple(nodelist) def __iter__(self): if self.alignment is not None: yield self.alignment attr_names = () class Attribute(Node): __slots__ = ("name", "namespace", "arguments", "coord", "__weakref__") def __init__(self, name, namespace, arguments, coord=None): self.name = name self.namespace = namespace self.arguments = arguments self.coord = coord def children(self): nodelist = [] return tuple(nodelist) def __iter__(self): return yield attr_names = ( "name", "namespace", "arguments", ) class AttributeSpecifier(Node): __slots__ = ("attributes", "coord", "__weakref__") def __init__(self, attributes, coord=None): self.attributes = attributes self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.attributes or [] attr_names = () class AttributeDeclaration(Node): __slots__ = ("attributes", "coord", "__weakref__") def __init__(self, attributes, coord=None): self.attributes = attributes self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.attributes or [] attr_names = () class AttributedStatement(Node): __slots__ = ("attributes", "stmt", "coord", "__weakref__") def __init__(self, attributes, stmt, coord=None): self.attributes = attributes self.stmt = stmt self.coord = coord def children(self): nodelist = [] if self.stmt is not None: nodelist.append(("stmt", self.stmt)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.stmt is not None: yield self.stmt yield from self.attributes or [] attr_names = () class AttributedType(Node): __slots__ = ("type", "attributes", "coord", "__weakref__") def __init__(self, type, attributes, coord=None): self.type = type self.attributes = attributes self.coord = coord def children(self): nodelist = [] if self.type is not None: nodelist.append(("type", self.type)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.type is not None: yield self.type yield from self.attributes or [] attr_names = () class BinaryOp(Node): __slots__ = ("op", "left", "right", "coord", "__weakref__") def __init__(self, op, left, right, coord=None): self.op = op self.left = left self.right = right self.coord = coord def children(self): nodelist = [] if self.left is not None: nodelist.append(("left", self.left)) if self.right is not None: nodelist.append(("right", self.right)) return tuple(nodelist) def __iter__(self): if self.left is not None: yield self.left if self.right is not None: yield self.right attr_names = ("op",) class BitIntType(Node): __slots__ = ("width", "signedness", "coord", "__weakref__") def __init__(self, width, signedness, coord=None): self.width = width self.signedness = signedness self.coord = coord def children(self): nodelist = [] if self.width is not None: nodelist.append(("width", self.width)) return tuple(nodelist) def __iter__(self): if self.width is not None: yield self.width attr_names = ("signedness",) class Break(Node): __slots__ = ("coord", "__weakref__") def __init__(self, coord=None): self.coord = coord def children(self): return () def __iter__(self): return yield attr_names = () class Case(Node): __slots__ = ("expr", "stmts", "attributes", "coord", "__weakref__") def __init__(self, expr, stmts, coord=None, *, attributes=None): self.expr = expr self.stmts = stmts self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.expr is not None: nodelist.append(("expr", self.expr)) for i, child in enumerate(self.stmts or []): nodelist.append((f"stmts[{i}]", child)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.expr is not None: yield self.expr yield from self.stmts or [] yield from self.attributes or [] attr_names = () class Cast(Node): __slots__ = ("to_type", "expr", "coord", "__weakref__") def __init__(self, to_type, expr, coord=None): self.to_type = to_type self.expr = expr self.coord = coord def children(self): nodelist = [] if self.to_type is not None: nodelist.append(("to_type", self.to_type)) if self.expr is not None: nodelist.append(("expr", self.expr)) return tuple(nodelist) def __iter__(self): if self.to_type is not None: yield self.to_type if self.expr is not None: yield self.expr attr_names = () class Compound(Node): __slots__ = ("block_items", "coord", "__weakref__") def __init__(self, block_items, coord=None): self.block_items = block_items self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.block_items or []): nodelist.append((f"block_items[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.block_items or [] attr_names = () class CompoundLiteral(Node): __slots__ = ("type", "init", "storage", "coord", "__weakref__") def __init__(self, type, init, storage, coord=None): self.type = type self.init = init self.storage = storage self.coord = coord def children(self): nodelist = [] if self.type is not None: nodelist.append(("type", self.type)) if self.init is not None: nodelist.append(("init", self.init)) return tuple(nodelist) def __iter__(self): if self.type is not None: yield self.type if self.init is not None: yield self.init attr_names = ("storage",) class Constant(Node): __slots__ = ("type", "value", "coord", "__weakref__") def __init__(self, type, value, coord=None): self.type = type self.value = value self.coord = coord def children(self): nodelist = [] return tuple(nodelist) def __iter__(self): return yield attr_names = ( "type", "value", ) class Continue(Node): __slots__ = ("coord", "__weakref__") def __init__(self, coord=None): self.coord = coord def children(self): return () def __iter__(self): return yield attr_names = () class Decl(Node): __slots__ = ( "name", "quals", "align", "storage", "funcspec", "type", "init", "bitsize", "attributes", "coord", "__weakref__", ) def __init__( self, name, quals, align, storage, funcspec, type, init, bitsize, coord=None, *, attributes=None, ): self.name = name self.quals = quals self.align = align self.storage = storage self.funcspec = funcspec self.type = type self.init = init self.bitsize = bitsize self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.type is not None: nodelist.append(("type", self.type)) if self.init is not None: nodelist.append(("init", self.init)) if self.bitsize is not None: nodelist.append(("bitsize", self.bitsize)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.type is not None: yield self.type if self.init is not None: yield self.init if self.bitsize is not None: yield self.bitsize yield from self.attributes or [] attr_names = ( "name", "quals", "align", "storage", "funcspec", ) class DeclList(Node): __slots__ = ("decls", "coord", "__weakref__") def __init__(self, decls, coord=None): self.decls = decls self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.decls or []): nodelist.append((f"decls[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.decls or [] attr_names = () class Default(Node): __slots__ = ("stmts", "attributes", "coord", "__weakref__") def __init__(self, stmts, coord=None, *, attributes=None): self.stmts = stmts self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.stmts or []): nodelist.append((f"stmts[{i}]", child)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.stmts or [] yield from self.attributes or [] attr_names = () class DoWhile(Node): __slots__ = ("cond", "stmt", "coord", "__weakref__") def __init__(self, cond, stmt, coord=None): self.cond = cond self.stmt = stmt self.coord = coord def children(self): nodelist = [] if self.cond is not None: nodelist.append(("cond", self.cond)) if self.stmt is not None: nodelist.append(("stmt", self.stmt)) return tuple(nodelist) def __iter__(self): if self.cond is not None: yield self.cond if self.stmt is not None: yield self.stmt attr_names = () class EllipsisParam(Node): __slots__ = ("coord", "__weakref__") def __init__(self, coord=None): self.coord = coord def children(self): return () def __iter__(self): return yield attr_names = () class EmptyStatement(Node): __slots__ = ("coord", "__weakref__") def __init__(self, coord=None): self.coord = coord def children(self): return () def __iter__(self): return yield attr_names = () class Enum(Node): __slots__ = ( "name", "values", "underlying_type", "attributes", "coord", "__weakref__", ) def __init__(self, name, values, underlying_type, coord=None, *, attributes=None): self.name = name self.values = values self.underlying_type = underlying_type self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.values is not None: nodelist.append(("values", self.values)) if self.underlying_type is not None: nodelist.append(("underlying_type", self.underlying_type)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.values is not None: yield self.values if self.underlying_type is not None: yield self.underlying_type yield from self.attributes or [] attr_names = ("name",) class Enumerator(Node): __slots__ = ("name", "value", "attributes", "coord", "__weakref__") def __init__(self, name, value, coord=None, *, attributes=None): self.name = name self.value = value self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.value is not None: nodelist.append(("value", self.value)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.value is not None: yield self.value yield from self.attributes or [] attr_names = ("name",) class EnumeratorList(Node): __slots__ = ("enumerators", "coord", "__weakref__") def __init__(self, enumerators, coord=None): self.enumerators = enumerators self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.enumerators or []): nodelist.append((f"enumerators[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.enumerators or [] attr_names = () class ExprList(Node): __slots__ = ("exprs", "coord", "__weakref__") def __init__(self, exprs, coord=None): self.exprs = exprs self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.exprs or []): nodelist.append((f"exprs[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.exprs or [] attr_names = () class FileAST(Node): __slots__ = ("ext", "coord", "__weakref__") def __init__(self, ext, coord=None): self.ext = ext self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.ext or []): nodelist.append((f"ext[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.ext or [] attr_names = () class For(Node): __slots__ = ("init", "cond", "next", "stmt", "coord", "__weakref__") def __init__(self, init, cond, next, stmt, coord=None): self.init = init self.cond = cond self.next = next self.stmt = stmt self.coord = coord def children(self): nodelist = [] if self.init is not None: nodelist.append(("init", self.init)) if self.cond is not None: nodelist.append(("cond", self.cond)) if self.next is not None: nodelist.append(("next", self.next)) if self.stmt is not None: nodelist.append(("stmt", self.stmt)) return tuple(nodelist) def __iter__(self): if self.init is not None: yield self.init if self.cond is not None: yield self.cond if self.next is not None: yield self.next if self.stmt is not None: yield self.stmt attr_names = () class FuncCall(Node): __slots__ = ("name", "args", "coord", "__weakref__") def __init__(self, name, args, coord=None): self.name = name self.args = args self.coord = coord def children(self): nodelist = [] if self.name is not None: nodelist.append(("name", self.name)) if self.args is not None: nodelist.append(("args", self.args)) return tuple(nodelist) def __iter__(self): if self.name is not None: yield self.name if self.args is not None: yield self.args attr_names = () class FuncDecl(Node): __slots__ = ("args", "type", "attributes", "coord", "__weakref__") def __init__(self, args, type, coord=None, *, attributes=None): self.args = args self.type = type self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.args is not None: nodelist.append(("args", self.args)) if self.type is not None: nodelist.append(("type", self.type)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.args is not None: yield self.args if self.type is not None: yield self.type yield from self.attributes or [] attr_names = () class FuncDef(Node): __slots__ = ("decl", "param_decls", "body", "coord", "__weakref__") def __init__(self, decl, param_decls, body, coord=None): self.decl = decl self.param_decls = param_decls self.body = body self.coord = coord def children(self): nodelist = [] if self.decl is not None: nodelist.append(("decl", self.decl)) if self.body is not None: nodelist.append(("body", self.body)) for i, child in enumerate(self.param_decls or []): nodelist.append((f"param_decls[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.decl is not None: yield self.decl if self.body is not None: yield self.body yield from self.param_decls or [] attr_names = () class GenericAssociation(Node): __slots__ = ("type", "expr", "coord", "__weakref__") def __init__(self, type, expr, coord=None): self.type = type self.expr = expr self.coord = coord def children(self): nodelist = [] if self.type is not None: nodelist.append(("type", self.type)) if self.expr is not None: nodelist.append(("expr", self.expr)) return tuple(nodelist) def __iter__(self): if self.type is not None: yield self.type if self.expr is not None: yield self.expr attr_names = () class GenericSelection(Node): __slots__ = ("expr", "associations", "coord", "__weakref__") def __init__(self, expr, associations, coord=None): self.expr = expr self.associations = associations self.coord = coord def children(self): nodelist = [] if self.expr is not None: nodelist.append(("expr", self.expr)) for i, child in enumerate(self.associations or []): nodelist.append((f"associations[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.expr is not None: yield self.expr yield from self.associations or [] attr_names = () class Goto(Node): __slots__ = ("name", "coord", "__weakref__") def __init__(self, name, coord=None): self.name = name self.coord = coord def children(self): nodelist = [] return tuple(nodelist) def __iter__(self): return yield attr_names = ("name",) class ID(Node): __slots__ = ("name", "coord", "__weakref__") def __init__(self, name, coord=None): self.name = name self.coord = coord def children(self): nodelist = [] return tuple(nodelist) def __iter__(self): return yield attr_names = ("name",) class IdentifierType(Node): __slots__ = ("names", "coord", "__weakref__") def __init__(self, names, coord=None): self.names = names self.coord = coord def children(self): nodelist = [] return tuple(nodelist) def __iter__(self): return yield attr_names = ("names",) class If(Node): __slots__ = ("cond", "iftrue", "iffalse", "coord", "__weakref__") def __init__(self, cond, iftrue, iffalse, coord=None): self.cond = cond self.iftrue = iftrue self.iffalse = iffalse self.coord = coord def children(self): nodelist = [] if self.cond is not None: nodelist.append(("cond", self.cond)) if self.iftrue is not None: nodelist.append(("iftrue", self.iftrue)) if self.iffalse is not None: nodelist.append(("iffalse", self.iffalse)) return tuple(nodelist) def __iter__(self): if self.cond is not None: yield self.cond if self.iftrue is not None: yield self.iftrue if self.iffalse is not None: yield self.iffalse attr_names = () class InferredType(Node): __slots__ = ("coord", "__weakref__") def __init__(self, coord=None): self.coord = coord def children(self): return () def __iter__(self): return yield attr_names = () class InitList(Node): __slots__ = ("exprs", "coord", "__weakref__") def __init__(self, exprs, coord=None): self.exprs = exprs self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.exprs or []): nodelist.append((f"exprs[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.exprs or [] attr_names = () class Label(Node): __slots__ = ("name", "stmt", "attributes", "coord", "__weakref__") def __init__(self, name, stmt, coord=None, *, attributes=None): self.name = name self.stmt = stmt self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.stmt is not None: nodelist.append(("stmt", self.stmt)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.stmt is not None: yield self.stmt yield from self.attributes or [] attr_names = ("name",) class NamedInitializer(Node): __slots__ = ("name", "expr", "coord", "__weakref__") def __init__(self, name, expr, coord=None): self.name = name self.expr = expr self.coord = coord def children(self): nodelist = [] if self.expr is not None: nodelist.append(("expr", self.expr)) for i, child in enumerate(self.name or []): nodelist.append((f"name[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.expr is not None: yield self.expr yield from self.name or [] attr_names = () class ParamList(Node): __slots__ = ("params", "coord", "__weakref__") def __init__(self, params, coord=None): self.params = params self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.params or []): nodelist.append((f"params[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.params or [] attr_names = () class PtrDecl(Node): __slots__ = ("quals", "type", "attributes", "coord", "__weakref__") def __init__(self, quals, type, coord=None, *, attributes=None): self.quals = quals self.type = type self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.type is not None: nodelist.append(("type", self.type)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.type is not None: yield self.type yield from self.attributes or [] attr_names = ("quals",) class Return(Node): __slots__ = ("expr", "coord", "__weakref__") def __init__(self, expr, coord=None): self.expr = expr self.coord = coord def children(self): nodelist = [] if self.expr is not None: nodelist.append(("expr", self.expr)) return tuple(nodelist) def __iter__(self): if self.expr is not None: yield self.expr attr_names = () class StaticAssert(Node): __slots__ = ("cond", "message", "coord", "__weakref__") def __init__(self, cond, message, coord=None): self.cond = cond self.message = message self.coord = coord def children(self): nodelist = [] if self.cond is not None: nodelist.append(("cond", self.cond)) if self.message is not None: nodelist.append(("message", self.message)) return tuple(nodelist) def __iter__(self): if self.cond is not None: yield self.cond if self.message is not None: yield self.message attr_names = () class Struct(Node): __slots__ = ("name", "decls", "attributes", "coord", "__weakref__") def __init__(self, name, decls, coord=None, *, attributes=None): self.name = name self.decls = decls self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.decls or []): nodelist.append((f"decls[{i}]", child)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.decls or [] yield from self.attributes or [] attr_names = ("name",) class StructRef(Node): __slots__ = ("name", "type", "field", "coord", "__weakref__") def __init__(self, name, type, field, coord=None): self.name = name self.type = type self.field = field self.coord = coord def children(self): nodelist = [] if self.name is not None: nodelist.append(("name", self.name)) if self.field is not None: nodelist.append(("field", self.field)) return tuple(nodelist) def __iter__(self): if self.name is not None: yield self.name if self.field is not None: yield self.field attr_names = ("type",) class Switch(Node): __slots__ = ("cond", "stmt", "coord", "__weakref__") def __init__(self, cond, stmt, coord=None): self.cond = cond self.stmt = stmt self.coord = coord def children(self): nodelist = [] if self.cond is not None: nodelist.append(("cond", self.cond)) if self.stmt is not None: nodelist.append(("stmt", self.stmt)) return tuple(nodelist) def __iter__(self): if self.cond is not None: yield self.cond if self.stmt is not None: yield self.stmt attr_names = () class TernaryOp(Node): __slots__ = ("cond", "iftrue", "iffalse", "coord", "__weakref__") def __init__(self, cond, iftrue, iffalse, coord=None): self.cond = cond self.iftrue = iftrue self.iffalse = iffalse self.coord = coord def children(self): nodelist = [] if self.cond is not None: nodelist.append(("cond", self.cond)) if self.iftrue is not None: nodelist.append(("iftrue", self.iftrue)) if self.iffalse is not None: nodelist.append(("iffalse", self.iffalse)) return tuple(nodelist) def __iter__(self): if self.cond is not None: yield self.cond if self.iftrue is not None: yield self.iftrue if self.iffalse is not None: yield self.iffalse attr_names = () class TypeDecl(Node): __slots__ = ( "declname", "quals", "align", "type", "attributes", "coord", "__weakref__", ) def __init__(self, declname, quals, align, type, coord=None, *, attributes=None): self.declname = declname self.quals = quals self.align = align self.type = type self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.type is not None: nodelist.append(("type", self.type)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.type is not None: yield self.type yield from self.attributes or [] attr_names = ( "declname", "quals", "align", ) class Typedef(Node): __slots__ = ( "name", "quals", "storage", "type", "attributes", "coord", "__weakref__", ) def __init__(self, name, quals, storage, type, coord=None, *, attributes=None): self.name = name self.quals = quals self.storage = storage self.type = type self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.type is not None: nodelist.append(("type", self.type)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.type is not None: yield self.type yield from self.attributes or [] attr_names = ( "name", "quals", "storage", ) class Typename(Node): __slots__ = ("name", "quals", "align", "type", "attributes", "coord", "__weakref__") def __init__(self, name, quals, align, type, coord=None, *, attributes=None): self.name = name self.quals = quals self.align = align self.type = type self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] if self.type is not None: nodelist.append(("type", self.type)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): if self.type is not None: yield self.type yield from self.attributes or [] attr_names = ( "name", "quals", "align", ) class TypeOf(Node): __slots__ = ("op", "expr", "coord", "__weakref__") def __init__(self, op, expr, coord=None): self.op = op self.expr = expr self.coord = coord def children(self): nodelist = [] if self.expr is not None: nodelist.append(("expr", self.expr)) return tuple(nodelist) def __iter__(self): if self.expr is not None: yield self.expr attr_names = ("op",) class UnaryOp(Node): __slots__ = ("op", "expr", "coord", "__weakref__") def __init__(self, op, expr, coord=None): self.op = op self.expr = expr self.coord = coord def children(self): nodelist = [] if self.expr is not None: nodelist.append(("expr", self.expr)) return tuple(nodelist) def __iter__(self): if self.expr is not None: yield self.expr attr_names = ("op",) class Union(Node): __slots__ = ("name", "decls", "attributes", "coord", "__weakref__") def __init__(self, name, decls, coord=None, *, attributes=None): self.name = name self.decls = decls self.attributes = [] if attributes is None else attributes self.coord = coord def children(self): nodelist = [] for i, child in enumerate(self.decls or []): nodelist.append((f"decls[{i}]", child)) for i, child in enumerate(self.attributes or []): nodelist.append((f"attributes[{i}]", child)) return tuple(nodelist) def __iter__(self): yield from self.decls or [] yield from self.attributes or [] attr_names = ("name",) class While(Node): __slots__ = ("cond", "stmt", "coord", "__weakref__") def __init__(self, cond, stmt, coord=None): self.cond = cond self.stmt = stmt self.coord = coord def children(self): nodelist = [] if self.cond is not None: nodelist.append(("cond", self.cond)) if self.stmt is not None: nodelist.append(("stmt", self.stmt)) return tuple(nodelist) def __iter__(self): if self.cond is not None: yield self.cond if self.stmt is not None: yield self.stmt attr_names = () class Pragma(Node): __slots__ = ("string", "coord", "__weakref__") def __init__(self, string, coord=None): self.string = string self.coord = coord def children(self): nodelist = [] return tuple(nodelist) def __iter__(self): return yield attr_names = ("string",) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792587013.8464892 pycparser-3.12/pycparser/c_generator.py0000664000175000017500000010240015266132406017643 0ustar00elibeneliben# ------------------------------------------------------------------------------ # pycparser: c_generator.py # # C code generator from pycparser AST nodes. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ------------------------------------------------------------------------------ from collections.abc import Callable from typing import ClassVar from . import c_ast class CGenerator: """Uses the same visitor pattern as c_ast.NodeVisitor, but modified to return a value from each visit method, using string accumulation in generic_visit. """ indent_level: int reduce_parentheses: bool def __init__(self, reduce_parentheses: bool = False) -> None: """Constructs C-code generator reduce_parentheses: if True, eliminates needless parentheses on binary operators """ # Statements start with indentation of self.indent_level spaces, using # the _make_indent method. self.indent_level = 0 self.reduce_parentheses = reduce_parentheses def _make_indent(self) -> str: return " " * self.indent_level def visit(self, node: c_ast.Node) -> str: method = "visit_" + node.__class__.__name__ return getattr(self, method, self.generic_visit)(node) def generic_visit(self, node: c_ast.Node | None) -> str: if node is None: return "" else: return "".join(self.visit(c) for c_name, c in node.children()) def visit_Constant(self, n: c_ast.Constant) -> str: return n.value def visit_ID(self, n: c_ast.ID) -> str: return n.name def _generate_attributes(self, attributes: list[c_ast.AttributeSpecifier]) -> str: return " ".join(self.visit(attribute) for attribute in attributes) def visit_Attribute(self, n: c_ast.Attribute) -> str: s = (n.namespace + "::" if n.namespace is not None else "") + n.name if n.arguments is not None: s += "(" + n.arguments + ")" return s def visit_AttributeSpecifier(self, n: c_ast.AttributeSpecifier) -> str: return "[[" + ", ".join(self.visit(a) for a in n.attributes) + "]]" def visit_AttributeDeclaration(self, n: c_ast.AttributeDeclaration) -> str: return self._generate_attributes(n.attributes) def visit_AttributedType(self, n: c_ast.AttributedType) -> str: return self.visit(n.type) + " " + self._generate_attributes(n.attributes) def visit_AttributedStatement(self, n: c_ast.AttributedStatement) -> str: return ( self._generate_attributes(n.attributes) + " " + self._generate_stmt(n.stmt).lstrip() ) def visit_Pragma(self, n: c_ast.Pragma) -> str: if isinstance(n.string, c_ast.Constant): return "_Pragma(" + self.visit(n.string) + ")" ret = "#pragma" if n.string: ret += " " + n.string return ret def visit_ArrayRef(self, n: c_ast.ArrayRef) -> str: arrref = self._parenthesize_unless_simple(n.name) return arrref + "[" + self._visit_expr(n.subscript, allow_comma=True) + "]" def visit_StructRef(self, n: c_ast.StructRef) -> str: sref = self._parenthesize_unless_simple(n.name) return sref + n.type + self.visit(n.field) def visit_FuncCall(self, n: c_ast.FuncCall) -> str: fref = self._parenthesize_unless_simple(n.name) # ExprList here separates arguments; visit_ExprList handles each argument. args = self.visit(n.args) if n.args is not None else "" return fref + "(" + args + ")" def visit_GenericSelection(self, n: c_ast.GenericSelection) -> str: # The controlling and association expressions are assignment-expressions: # preserve parentheses around comma expressions with _visit_expr. expr = self._visit_expr(n.expr) associations = ", ".join(self.visit(a) for a in n.associations) return f"_Generic({expr}, {associations})" def visit_GenericAssociation(self, n: c_ast.GenericAssociation) -> str: typ = self.visit(n.type) if n.type is not None else "default" return f"{typ}: {self._visit_expr(n.expr)}" def visit_UnaryOp(self, n: c_ast.UnaryOp) -> str: match n.op: case "sizeof": # Always parenthesize the argument of sizeof since it can be # a name. return f"sizeof({self._visit_expr(n.expr, allow_comma=True)})" case "p++": operand = self._parenthesize_unless_simple(n.expr) return f"{operand}++" case "p--": operand = self._parenthesize_unless_simple(n.expr) return f"{operand}--" case _: operand = self._parenthesize_unless_simple(n.expr) return f"{n.op}{operand}" # Precedence map of binary operators: precedence_map: ClassVar[dict[str, int]] = { # Should be in sync with c_parser.CParser.precedence # Higher numbers are stronger binding "||": 0, # weakest binding "&&": 1, "|": 2, "^": 3, "&": 4, "==": 5, "!=": 5, ">": 6, ">=": 6, "<": 6, "<=": 6, ">>": 7, "<<": 7, "+": 8, "-": 8, "*": 9, "/": 9, "%": 9, # strongest binding } def visit_BinaryOp(self, n: c_ast.BinaryOp) -> str: # Note: all binary operators are left-to-right associative # Unary expressions bind more tightly than every binary operator. # # If `n.left.op` has a stronger or equally binding precedence in # comparison to `n.op`, no parenthesis are needed for the left: # e.g., `(a*b) + c` is equivalent to `a*b + c`, as well as # `(a+b) - c` is equivalent to `a+b - c` (same precedence). # If the left operator is weaker binding than the current, then # parentheses are necessary: # e.g., `(a+b) * c` is NOT equivalent to `a+b * c`. lval_str = self._parenthesize_if( n.left, lambda d: ( not ( self._is_simple_node(d) or self.reduce_parentheses and ( isinstance(d, c_ast.UnaryOp) or isinstance(d, c_ast.BinaryOp) and self.precedence_map[d.op] >= self.precedence_map[n.op] ) ) ), ) # If `n.right.op` has a stronger -but not equal- binding precedence, # parenthesis can be omitted on the right: # e.g., `a + (b*c)` is equivalent to `a + b*c`. # If the right operator is weaker or equally binding, then parentheses # are necessary: # e.g., `a * (b+c)` is NOT equivalent to `a * b+c` and # `a - (b+c)` is NOT equivalent to `a - b+c` (same precedence). rval_str = self._parenthesize_if( n.right, lambda d: ( not ( self._is_simple_node(d) or self.reduce_parentheses and ( isinstance(d, c_ast.UnaryOp) or isinstance(d, c_ast.BinaryOp) and self.precedence_map[d.op] > self.precedence_map[n.op] ) ) ), ) return f"{lval_str} {n.op} {rval_str}" def visit_Assignment(self, n: c_ast.Assignment) -> str: rval_str = self._parenthesize_if( n.rvalue, lambda n: isinstance(n, c_ast.Assignment) ) return f"{self._visit_expr(n.lvalue)} {n.op} {rval_str}" def visit_IdentifierType(self, n: c_ast.IdentifierType) -> str: return " ".join(n.names) def visit_InferredType(self, n: c_ast.InferredType) -> str: # The auto storage specifier is emitted by the enclosing declaration. return "" def visit_TypeOf(self, n: c_ast.TypeOf) -> str: return f"{n.op}({self._visit_expr(n.expr)})" def visit_BitIntType(self, n: c_ast.BitIntType) -> str: sign = n.signedness + " " if n.signedness else "" return f"{sign}_BitInt({self._visit_expr(n.width)})" def _visit_expr(self, n: c_ast.Node, *, allow_comma: bool = False) -> str: """Render an expression or initializer with its required delimiters. Full expression contexts (returns, conditions, subscripts, etc.) allow bare commas. Individual arguments and initializers need comma grouping. Statement expressions always need their own parentheses. """ match n: case c_ast.InitList(): return "{" + self.visit(n) + "}" case c_ast.ExprList() if allow_comma: return self.visit(n) case c_ast.ExprList() | c_ast.Compound(): return "(" + self.visit(n) + ")" case _: return self.visit(n) def visit_Decl(self, n: c_ast.Decl, no_type: bool = False) -> str: # Later declarations in a DeclList omit the shared specifiers, but # still need their own pointer, array, and function declarator parts. s = ( self._generate_type(n.type, emit_base_type=False) if no_type else self._generate_decl(n) ) if n.bitsize: s += " : " + self._visit_expr(n.bitsize) if n.init: s += " = " + self._visit_expr(n.init) return s def visit_DeclList(self, n: c_ast.DeclList) -> str: s = self.visit(n.decls[0]) for decl in n.decls[1:]: if isinstance(decl, c_ast.Pragma): # A for initializer can have pragmas before its semicolon. # Keep directives on their own lines, without a comma. s += "\n" + self._make_indent() + self.visit(decl) else: s += ", " + self.visit_Decl(decl, no_type=True) if isinstance(n.decls[-1], c_ast.Pragma): s += "\n" + self._make_indent() return s def _defined_type( self, n: c_ast.Node ) -> c_ast.Struct | c_ast.Union | c_ast.Enum | None: """Return the struct, union, or enum body this declarator defines. ``union { struct a b; } u, *uu`` both return that same union node. ``struct Foo x`` has no body, so it returns None. Callers compare the result with ``is``: two anonymous structs that only look alike are different nodes. Attribute wrappers are skipped too, since each declarator can have its own wrapper around the shared body. """ if not isinstance(n, (c_ast.Decl, c_ast.Typedef)): return None typ = n.type while isinstance( typ, ( c_ast.PtrDecl, c_ast.ArrayDecl, c_ast.FuncDecl, c_ast.TypeDecl, c_ast.AttributedType, ), ): typ = typ.type if isinstance(typ, (c_ast.Struct, c_ast.Union)) and typ.decls is not None: return typ if isinstance(typ, c_ast.Enum) and typ.values is not None: return typ return None def _same_decl_specs(self, left: c_ast.Node, right: c_ast.Node) -> bool: """Return whether two declarators have the same specifiers. ``static struct { int a; } x, y`` matches: both names are ``static``. ``static struct { int a; } x`` followed by ``struct { int a; } y`` does not, because only ``x`` is ``static``. Qualifiers, alignment, and function specifiers are compared too. """ if type(left) is not type(right): return False if isinstance(left, c_ast.Decl) and isinstance(right, c_ast.Decl): return ( left.quals == right.quals and left.align == right.align and left.storage == right.storage and left.funcspec == right.funcspec ) if isinstance(left, c_ast.Typedef) and isinstance(right, c_ast.Typedef): return left.quals == right.quals and left.storage == right.storage return False def _coalesce_defined_types( self, nodes: list[c_ast.Node] ) -> list[c_ast.Node | list[c_ast.Node]]: """Group consecutive declarators that share one type definition. ``union { struct a b; } u, *uu = &u`` is one group: both names point at that union and their specifiers match. ``struct { int a; } x; struct { int a; } y;`` stays two items, because those are different definition nodes. One name on its own, or a name whose specifiers differ from the next, is left alone. """ grouped: list[c_ast.Node | list[c_ast.Node]] = [] index = 0 while index < len(nodes): node = nodes[index] defined = self._defined_type(node) if defined is None: grouped.append(node) index += 1 continue end = index + 1 while end < len(nodes) and self._same_decl_specs(node, nodes[end]): if self._defined_type(nodes[end]) is not defined: break end += 1 if end == index + 1: grouped.append(node) else: grouped.append(list(nodes[index:end])) index = end return grouped def _visit_decl_group(self, nodes: list[c_ast.Node]) -> str: """Emit a group as one declaration, with the body on the first name. ``typedef struct { int a; } B, C`` keeps a single ``typedef`` and one body. ``struct { int a; } x, *y`` keeps ``*y`` on that same declaration instead of repeating the struct. """ first = nodes[0] if isinstance(first, c_ast.Typedef): extras: list[str] = [] for decl in nodes[1:]: if not isinstance(decl, c_ast.Typedef): raise TypeError("typedef group contains a non-typedef") extras.append(self._generate_type(decl.type, emit_base_type=False)) return self.visit(first) + ", " + ", ".join(extras) decls: list[c_ast.Decl] = [] for decl in nodes: if not isinstance(decl, c_ast.Decl): raise TypeError("declaration group contains a non-declaration") decls.append(decl) return self.visit(c_ast.DeclList(decls)) def visit_Typedef(self, n: c_ast.Typedef) -> str: s = self._generate_attributes(n.attributes) + " " if n.attributes else "" if n.storage: s += " ".join(n.storage) + " " s += self._generate_type(n.type) return s def visit_Cast(self, n: c_ast.Cast) -> str: s = "(" + self._generate_type(n.to_type, emit_declname=False) + ")" return s + " " + self._parenthesize_unless_simple(n.expr) def visit_ExprList(self, n: c_ast.ExprList) -> str: visited_subexprs = [] for expr in n.exprs: visited_subexprs.append(self._visit_expr(expr)) return ", ".join(visited_subexprs) def visit_InitList(self, n: c_ast.InitList) -> str: visited_subexprs = [] for expr in n.exprs: visited_subexprs.append(self._visit_expr(expr)) return ", ".join(visited_subexprs) def visit_Enum(self, n: c_ast.Enum) -> str: return self._generate_struct_union_enum(n, name="enum") def visit_Alignas(self, n: c_ast.Alignas) -> str: return f"_Alignas({self._visit_expr(n.alignment)})" def visit_Enumerator(self, n: c_ast.Enumerator) -> str: name = n.name if n.attributes: name += " " + self._generate_attributes(n.attributes) if not n.value: return f"{self._make_indent()}{name},\n" else: return f"{self._make_indent()}{name} = {self._visit_expr(n.value)},\n" def visit_FuncDef(self, n: c_ast.FuncDef) -> str: decl = self.visit(n.decl) self.indent_level = 0 body = self.visit(n.body) if n.param_decls: knrdecls = "".join(self._generate_stmt(p) for p in n.param_decls) return decl + "\n" + knrdecls + body + "\n" else: return decl + "\n" + body + "\n" def visit_FileAST(self, n: c_ast.FileAST) -> str: s = "" for ext in self._coalesce_defined_types(n.ext): if isinstance(ext, list): s += self._visit_decl_group(ext) + ";\n" continue match ext: case c_ast.FuncDef(): s += self.visit(ext) case c_ast.Pragma(): s += self.visit(ext) + "\n" case _: s += self.visit(ext) + ";\n" return s def visit_Compound(self, n: c_ast.Compound) -> str: s = self._make_indent() + "{\n" self.indent_level += 2 if n.block_items: s += self._generate_body(n.block_items) self.indent_level -= 2 s += self._make_indent() + "}\n" return s def visit_CompoundLiteral(self, n: c_ast.CompoundLiteral) -> str: storage = " ".join(n.storage) + " " if n.storage else "" return "(" + storage + self.visit(n.type) + "){" + self.visit(n.init) + "}" def visit_EmptyStatement(self, n: c_ast.EmptyStatement) -> str: return ";" def visit_ParamList(self, n: c_ast.ParamList) -> str: return ", ".join(self.visit(param) for param in n.params) def visit_Return(self, n: c_ast.Return) -> str: s = "return" if n.expr: s += " " + self._visit_expr(n.expr, allow_comma=True) return s + ";" def visit_Break(self, n: c_ast.Break) -> str: return "break;" def visit_Continue(self, n: c_ast.Continue) -> str: return "continue;" def visit_TernaryOp(self, n: c_ast.TernaryOp) -> str: s = "(" + self._visit_expr(n.cond) + ") ? " s += "(" + self._visit_expr(n.iftrue) + ") : " s += "(" + self._visit_expr(n.iffalse) + ")" return s def visit_If(self, n: c_ast.If) -> str: s = "if (" if n.cond: s += self._visit_expr(n.cond, allow_comma=True) s += ")\n" s += self._generate_stmt(n.iftrue, add_indent=True) if n.iffalse: s += self._make_indent() + "else\n" s += self._generate_stmt(n.iffalse, add_indent=True) return s def visit_For(self, n: c_ast.For) -> str: s = "for (" if n.init: s += self._visit_expr(n.init, allow_comma=True) s += ";" if n.cond: s += " " + self._visit_expr(n.cond, allow_comma=True) s += ";" if n.next: s += " " + self._visit_expr(n.next, allow_comma=True) s += ")\n" s += self._generate_stmt(n.stmt, add_indent=True) return s def visit_While(self, n: c_ast.While) -> str: s = "while (" if n.cond: s += self._visit_expr(n.cond, allow_comma=True) s += ")\n" s += self._generate_stmt(n.stmt, add_indent=True) return s def visit_DoWhile(self, n: c_ast.DoWhile) -> str: s = "do\n" s += self._generate_stmt(n.stmt, add_indent=True) s += self._make_indent() + "while (" if n.cond: s += self._visit_expr(n.cond, allow_comma=True) s += ");" return s def visit_StaticAssert(self, n: c_ast.StaticAssert) -> str: s = "_Static_assert(" s += self._visit_expr(n.cond) if n.message: s += ", " s += self.visit(n.message) s += ")" return s def visit_Switch(self, n: c_ast.Switch) -> str: s = "switch (" + self._visit_expr(n.cond, allow_comma=True) + ")\n" s += self._generate_stmt(n.stmt, add_indent=True) return s def visit_Case(self, n: c_ast.Case) -> str: s = self._generate_attributes(n.attributes) + " " if n.attributes else "" s += "case " + self._visit_expr(n.expr) + ":\n" return s + self._generate_body(n.stmts or [], add_indent=True) def visit_Default(self, n: c_ast.Default) -> str: s = self._generate_attributes(n.attributes) + " " if n.attributes else "" s += "default:\n" return s + self._generate_body(n.stmts or [], add_indent=True) def visit_Label(self, n: c_ast.Label) -> str: s = self._generate_attributes(n.attributes) + " " if n.attributes else "" return s + n.name + ":\n" + self._generate_stmt(n.stmt) def visit_Goto(self, n: c_ast.Goto) -> str: return "goto " + n.name + ";" def visit_EllipsisParam(self, n: c_ast.EllipsisParam) -> str: return "..." def visit_Struct(self, n: c_ast.Struct) -> str: return self._generate_struct_union_enum(n, "struct") def visit_Typename(self, n: c_ast.Typename) -> str: s = self._generate_attributes(n.attributes) + " " if n.attributes else "" return s + self._generate_type(n.type) def visit_Union(self, n: c_ast.Union) -> str: return self._generate_struct_union_enum(n, "union") def visit_ArrayDesignator(self, n: c_ast.ArrayDesignator) -> str: return "[" + self._visit_expr(n.expr) + "]" def visit_NamedInitializer(self, n: c_ast.NamedInitializer) -> str: s = "" for name in n.name: if isinstance(name, c_ast.ID): s += "." + name.name else: s += self.visit(name) s += " = " + self._visit_expr(n.expr) return s def visit_FuncDecl(self, n: c_ast.FuncDecl) -> str: return self._generate_type(n) def visit_ArrayDecl(self, n: c_ast.ArrayDecl) -> str: return self._generate_type(n, emit_declname=False) def visit_TypeDecl(self, n: c_ast.TypeDecl) -> str: return self._generate_type(n, emit_declname=False) def visit_PtrDecl(self, n: c_ast.PtrDecl) -> str: return self._generate_type(n, emit_declname=False) def _generate_struct_union_enum( self, n: c_ast.Struct | c_ast.Union | c_ast.Enum, name: str ) -> str: """Generates code for structs, unions, and enums. name should be 'struct', 'union', or 'enum'. """ if name in ("struct", "union"): assert isinstance(n, (c_ast.Struct, c_ast.Union)) members = n.decls body_function = self._generate_body else: assert name == "enum" assert isinstance(n, c_ast.Enum) members = None if n.values is None else n.values.enumerators body_function = self._generate_enum_body attributes = ( self._generate_attributes(n.attributes) + " " if n.attributes else "" ) s = name + " " + attributes + (n.name or "") if isinstance(n, c_ast.Enum) and n.underlying_type is not None: s = s.rstrip() + " : " + self.visit(n.underlying_type) if members is not None: # None means no members # Empty sequence means an empty list of members s += "\n" s += self._make_indent() self.indent_level += 2 s += "{\n" s += body_function(members) self.indent_level -= 2 s += self._make_indent() + "}" return s def _generate_body(self, nodes: list[c_ast.Node], add_indent: bool = False) -> str: """Emit statements or members, grouping shared type definitions. Callers handle braces and indentation levels; _generate_stmt supplies the punctuation for individual statements, declarations, and pragmas. """ indent = self._make_indent() if add_indent: indent += " " parts: list[str] = [] for item in self._coalesce_defined_types(nodes): if isinstance(item, list): parts.append(indent + self._visit_decl_group(item) + ";\n") else: parts.append(self._generate_stmt(item, add_indent=add_indent)) return "".join(parts) def _generate_enum_body( self, members: list[c_ast.Enumerator | c_ast.Pragma] ) -> str: parts = [] last_enumerator = None for member in members: if isinstance(member, c_ast.Pragma): parts.append(self._generate_stmt(member)) else: last_enumerator = len(parts) parts.append(self.visit(member)) # Remove the comma from the last enumerator, which may be followed by # pragmas whose text and newlines must remain intact. if last_enumerator is not None: parts[last_enumerator] = parts[last_enumerator][:-2] + "\n" return "".join(parts) def _generate_stmt(self, n: c_ast.Node, add_indent: bool = False) -> str: """Generation from a statement node. This method exists as a wrapper for individual visit_* methods to handle different treatment of some statements in this context. """ if add_indent: self.indent_level += 2 indent = self._make_indent() if add_indent: self.indent_level -= 2 match n: case ( c_ast.Decl() | c_ast.Assignment() | c_ast.Cast() | c_ast.UnaryOp() | c_ast.BinaryOp() | c_ast.TernaryOp() | c_ast.FuncCall() | c_ast.ArrayRef() | c_ast.StructRef() | c_ast.Constant() | c_ast.ID() | c_ast.Typedef() | c_ast.ExprList() | c_ast.CompoundLiteral() | c_ast.GenericSelection() | c_ast.StaticAssert() | c_ast.AttributeDeclaration() ): # These visitors leave the semicolon to the enclosing context, # so they can also be used in expressions or for clauses. return indent + self.visit(n) + ";\n" case c_ast.Compound(): # No extra indentation required before the opening brace of a # compound - because it consists of multiple lines it has to # compute its own indentation. # return self.visit(n) case c_ast.AttributedStatement(): return indent + self.visit(n) case c_ast.If(): return indent + self.visit(n) case _: return indent + self.visit(n) + "\n" def _generate_decl(self, n: c_ast.Decl) -> str: """Generation from a Decl node.""" s = self._generate_attributes(n.attributes) + " " if n.attributes else "" if n.funcspec: s += " ".join(n.funcspec) + " " if n.storage: s += " ".join(n.storage) + " " if n.align: s += " ".join(self.visit(align) for align in n.align) + " " if isinstance( n.type, (c_ast.TypeDecl, c_ast.PtrDecl, c_ast.ArrayDecl, c_ast.FuncDecl) ): s += self._generate_type(n.type) else: # Members without declarators carry their specifier directly; # their qualifiers have not been copied onto a TypeDecl. if n.quals: s += " ".join(n.quals) + " " s += self._generate_type_specifier(n.type) return s def _generate_type_specifier(self, n: c_ast.Node) -> str: if isinstance(n, c_ast.AttributedType): return ( self._generate_type_specifier(n.type).rstrip() + " " + self._generate_attributes(n.attributes) ) if isinstance(n, c_ast.Typename) and "_Atomic" in n.quals: # A bare _Atomic(T) still has its Typename wrapper. Preserve the # specifier syntax, which also keeps atomic pointers unambiguous. return "_Atomic(" + self.visit(n) + ")" return self._generate_type(n) def _generate_type( self, n: c_ast.Node, modifiers: list[c_ast.Node] | None = None, emit_declname: bool = True, emit_base_type: bool = True, ) -> str: """Recursive generation from a type node. n is the type node. modifiers collects the PtrDecl, ArrayDecl and FuncDecl modifiers encountered on the way down to a TypeDecl, to allow proper generation from it. emit_base_type controls whether the shared type specifier and its qualifiers are emitted, independently of the declarator parts. """ if modifiers is None: modifiers = [] # ~ print(n, modifiers) match n: case c_ast.TypeDecl(): s = "" if emit_base_type: if n.quals: s += " ".join(n.quals) + " " s += self.visit(n.type) nstr = n.declname if n.declname and emit_declname else "" if n.attributes: nstr += " " + self._generate_attributes(n.attributes) # Resolve modifiers. # Wrap in parens to distinguish pointer to array and pointer to # function syntax. # for i, modifier in enumerate(modifiers): match modifier: case c_ast.ArrayDecl(): if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl): nstr = "(" + nstr + ")" nstr += "[" if modifier.dim_quals: nstr += " ".join(modifier.dim_quals) + " " if modifier.dim is not None: nstr += self._visit_expr(modifier.dim) nstr += "]" if modifier.attributes: nstr += " " + self._generate_attributes( modifier.attributes ) case c_ast.FuncDecl(): if i != 0 and isinstance(modifiers[i - 1], c_ast.PtrDecl): nstr = "(" + nstr + ")" args = ( self.visit(modifier.args) if modifier.args is not None else "" ) nstr += "(" + args + ")" if modifier.attributes: nstr += " " + self._generate_attributes( modifier.attributes ) case c_ast.PtrDecl(): prefix = "*" if modifier.attributes: prefix += " " + self._generate_attributes( modifier.attributes ) if modifier.quals: prefix += " " + " ".join(modifier.quals) separator = ( " " if nstr and (modifier.attributes or modifier.quals) else "" ) nstr = prefix + separator + nstr if not emit_base_type: return nstr if nstr: s = s.rstrip() s += (" " if s else "") + nstr return s case c_ast.Decl(): return self._generate_decl(n.type) case c_ast.Typename(): prefix = ( self._generate_attributes(n.attributes) + " " if n.attributes else "" ) return prefix + self._generate_type( n.type, emit_declname=emit_declname, emit_base_type=emit_base_type, ) case c_ast.IdentifierType(): return " ".join(n.names) + " " case c_ast.ArrayDecl() | c_ast.PtrDecl() | c_ast.FuncDecl(): return self._generate_type( n.type, modifiers + [n], emit_declname=emit_declname, emit_base_type=emit_base_type, ) case _: return self.visit(n) def _parenthesize_if( self, n: c_ast.Node, condition: Callable[[c_ast.Node], bool] ) -> str: """Visits 'n' and returns its string representation, parenthesized if the condition function applied to the node returns True. """ s = self._visit_expr(n) if condition(n): return "(" + s + ")" else: return s def _parenthesize_unless_simple(self, n: c_ast.Node) -> str: """Common use case for _parenthesize_if""" return self._parenthesize_if(n, lambda d: not self._is_simple_node(d)) def _is_simple_node(self, n: c_ast.Node) -> bool: """Returns True for nodes that are "simple" - i.e. nodes that always have higher precedence than operators. """ return isinstance( n, ( c_ast.Constant, c_ast.ID, c_ast.ArrayRef, c_ast.StructRef, c_ast.FuncCall, c_ast.GenericSelection, ), ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792674026.6174889 pycparser-3.12/pycparser/c_lexer.py0000664000175000017500000007612115266404353017011 0ustar00elibeneliben# ------------------------------------------------------------------------------ # pycparser: c_lexer.py # # CLexer class: lexer for the C language # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ------------------------------------------------------------------------------ import re from collections.abc import Callable from dataclasses import dataclass from enum import Enum from typing import Literal, assert_never Dialect = Literal["legacy", "c23"] @dataclass(slots=True) class Token: type: str value: str lineno: int column: int filename: str class CLexer: """A standalone lexer for C. Constructor parameters: error_func: Called with (msg, line, column) on lexing errors. dialect: "legacy" preserves the existing keyword set. "c23" also recognizes C23 keywords and predefined constants. Call input(text) to initialize lexing, and then keep calling token() to get the next token, until it returns None (at end of input). Non-keyword identifiers are emitted as ID tokens. The parser handles scopes and classifies typedef names as TYPEID. """ def __init__( self, error_func: Callable[[str, int, int], None], *, dialect: Dialect = "legacy", ) -> None: if dialect not in ("legacy", "c23"): raise ValueError(f"Unknown dialect {dialect!r}; expected 'legacy' or 'c23'") # Select keywords once per lexer. input() resets the scanning state # without changing this map or affecting lexers using another dialect. self._keyword_map = _keyword_map.copy() if dialect == "c23": self._keyword_map.update(_c23_keywords) self.error_func = error_func self._init_state() def input(self, text: str, filename: str = "") -> None: """Initialize the lexer to the given input text. filename is an optional name identifying the initial file from which the input comes. The lexer may modify it if #line directives are encountered. """ self._init_state() self._lexdata = text self._filename = filename def _init_state(self) -> None: self._lexdata = "" self._filename = "" self._pos = 0 self._line_start = 0 self._pending_tok: Token | None = None self._lineno = 1 self._in_attribute = False @property def filename(self) -> str: return self._filename def token(self) -> Token | None: # Lexing strategy overview: # # - We maintain a current position (self._pos), line number, and the # byte offset of the current line start. The lexer is a simple loop # that skips whitespace/newlines and emits one token per call. # # - A small amount of logic is handled manually before regex matching: # # * Preprocessor-style directives: if we see '#', we check whether # it's a #line or #pragma directive and consume it inline. #line # updates lineno/filename and produces no tokens. #pragma can yield # both PPPRAGMA and PPPRAGMASTR, but token() returns a single token, # so we stash the PPPRAGMASTR as _pending_tok to return on the next # token() call. Otherwise we return PPHASH. # * Newlines update lineno/line-start tracking so tokens can record # accurate columns. # # - The bulk of tokens are recognized in _match_token: # # * _regex_rules: regex patterns for identifiers, literals, and other # complex tokens (including error-producing patterns). The lexer # uses a combined _regex_master to scan options at the same time. # * _fixed_tokens: exact string matches for operators and punctuation, # resolved by longest match. # # - Error patterns call the error callback and advance minimally, which # keeps lexing resilient while reporting useful diagnostics. text = self._lexdata n = len(text) if self._pending_tok is not None: tok = self._pending_tok self._pending_tok = None return tok while self._pos < n: match text[self._pos]: case " " | "\t" | "\f" | "\v": self._pos += 1 case "\n": self._lineno += 1 self._pos += 1 self._line_start = self._pos case "#": if _line_pattern.match(text, self._pos + 1): self._pos += 1 self._handle_ppline() continue if _pragma_pattern.match(text, self._pos + 1): self._pos += 1 toks = self._handle_pppragma() if len(toks) > 1: self._pending_tok = toks[1] if len(toks) > 0: return toks[0] continue tok = self._make_token("PPHASH", "#", self._pos) self._pos += 1 return tok case _: if tok := self._match_token(): return tok else: continue def _match_token(self) -> Token | None: """Match one token at the current position. Returns a Token on success, or None if no token could be matched and an error was reported. This method always advances _pos by the matched length, or by 1 on error/no-match. """ text = self._lexdata pos = self._pos # Attribute arguments are balanced token sequences, not C expressions. # Keep them opaque so the parser does not interpret their contents as # C expressions or declarations. if self._in_attribute: if text[pos] == "(": return self._attribute_arguments() if match := _attribute_end.match(text, pos): self._in_attribute = False return self._attribute_token("ATTRIBUTE_END", match.end()) # Only run regexp check if we are starting an attribute, to avoid # costly regex matching for every token. elif text[pos] == "[" and (match := _attribute_begin.match(text, pos)): self._in_attribute = True return self._attribute_token("ATTRIBUTE_BEGIN", match.end()) # We pick the longest match between: # - the master regex (identifiers, literals, error patterns, etc.) # - fixed operator/punctuator literals from the bucket for text[pos] # # The longest match is required to ensure we properly lex something # like ".123" (a floating-point constant) as a single entity (with # FLOAT_CONST), rather than a PERIOD followed by a number. # # The fixed-literal buckets are already length-sorted, so within that # bucket we can take the first match. However, we still compare its # length to the regex match because the regex may have matched a longer # token that should take precedence. best = None if m := _regex_master.match(text, pos): tok_type = m.lastgroup # All master-regex alternatives are named; lastgroup shouldn't be None. assert tok_type is not None value = m.group(tok_type) length = len(value) action, msg = _regex_actions[tok_type] best = (length, tok_type, value, action, msg) if bucket := _fixed_tokens_by_first.get(text[pos]): for entry in bucket: if text.startswith(entry.literal, pos): length = len(entry.literal) if best is None or length > best[0]: best = ( length, entry.tok_type, entry.literal, _RegexAction.TOKEN, None, ) break if best is None: self._error(f"Illegal character {text[pos]!r}", pos) self._pos += 1 return None length, tok_type, value, action, msg = best match action: case _RegexAction.TOKEN: pass case _RegexAction.ERROR: if tok_type == "BAD_CHAR_CONST": msg = f"Invalid char constant {value}" # All other ERROR rules provide a message. assert msg is not None self._error(msg, pos) self._pos += max(1, length) return None case _RegexAction.ID: tok_type = ( "ID" if self._in_attribute else self._keyword_map.get(value, "ID") ) case _: assert_never(action) tok = self._make_token(tok_type, value, pos) self._pos += length return tok def _attribute_token(self, kind: str, end: int) -> Token: """Emit the text from _pos up to end and advance lexer state. Attribute delimiters can contain whitespace, and argument clauses can span lines. Record the token's starting coordinates before updating line tracking for the entire consumed span. """ value = self._lexdata[self._pos : end] tok = self._make_token(kind, value, self._pos) self._lineno += value.count("\n") if "\n" in value: self._line_start = self._pos + value.rfind("\n") + 1 self._pos = end return tok def _attribute_arguments(self) -> Token | None: """Scan an attribute argument clause with _pos at its opening '('. Return one ATTRIBUTE_ARGUMENTS token containing the raw text inside the outer parentheses. A stack tracks the expected closing delimiters for nested (), [], and {}. Comments and quoted literals are skipped while balancing, but preserved in the token value. This bypasses normal token classification, keeping arbitrary attribute arguments separate from C expressions and scope tracking. Report malformed clauses at the opening parenthesis. If the error callback returns, consume the remaining input and return None. """ text = self._lexdata start = self._pos pos = start + 1 closers = [")"] pairs = {"(": ")", "[": "]", "{": "}"} error = "Unterminated attribute arguments" while pos < len(text): ch = text[pos] if text.startswith("/*", pos): end = text.find("*/", pos + 2) if end < 0: break pos = end + 2 continue if text.startswith("//", pos): end = text.find("\n", pos + 2) pos = len(text) if end < 0 else end continue # Consume whole identifiers and preprocessing numbers first, so # digits in literal prefixes aren't confused with numbers and # digit separators aren't mistaken for character-literal quotes. if match := _attribute_word.match(text, pos): pos = match.end() continue if ch in {"'", '"'}: quote = ch pos += 1 while pos < len(text) and text[pos] not in {quote, "\n"}: pos += 2 if text[pos] == "\\" else 1 if pos >= len(text) or text[pos] != quote: break pos += 1 continue if ch in pairs: closers.append(pairs[ch]) elif ch in ")]}": if ch != closers[-1]: error = "Mismatched delimiter in attribute arguments" break closers.pop() if not closers: tok = self._attribute_token("ATTRIBUTE_ARGUMENTS", pos + 1) tok.value = tok.value[1:-1] return tok pos += 1 self._error(error, start) self._pos = len(text) return None def _make_token(self, tok_type: str, value: str, pos: int) -> Token: """Create a Token at an absolute input position. Expects tok_type/value and the absolute byte offset pos in the current input. Does not advance lexer state; callers manage _pos themselves. Returns a Token with the current filename and line/column coordinates. """ column = pos - self._line_start + 1 tok = Token(tok_type, value, self._lineno, column, self._filename) return tok def _error(self, msg: str, pos: int) -> None: column = pos - self._line_start + 1 self.error_func(msg, self._lineno, column) def _handle_ppline(self) -> None: # Since #line directives aren't supposed to return tokens but should # only affect the lexer's state (update line/filename for coords), this # method does a bit of parsing on its own. It doesn't return anything, # but its side effect is to update self._pos past the directive, and # potentially update self._lineno and self._filename, based on the # directive's contents. # # Accepted #line forms from preprocessors: # - "#line 66 \"kwas\\df.h\"" # - "# 9" # - "#line 10 \"include/me.h\" 1 2 3" (extra numeric flags) # - "# 1 \"file.h\" 3" # Errors we must report: # - "#line \"file.h\"" (filename before line number) # - "#line df" (garbage instead of number/string) # # We scan the directive line once (after an optional 'line' keyword), # validating the order: NUMBER, optional STRING, then any NUMBERs. # The NUMBERs tail is only accepted if a filename STRING was present. text = self._lexdata n = len(text) line_end = text.find("\n", self._pos) if line_end == -1: line_end = n line = text[self._pos : line_end] pos = 0 line_len = len(line) def skip_ws() -> None: nonlocal pos while pos < line_len and line[pos] in " \t": pos += 1 skip_ws() if line.startswith("line", pos): pos += 4 def success(pp_line: str | None, pp_filename: str | None) -> None: if pp_line is None: self._error("line number missing in #line", self._pos + line_len) else: try: self._lineno = int(pp_line.replace("'", "")) except ValueError: self._error("invalid #line directive", self._pos + line_len) return if pp_filename is not None: self._filename = pp_filename self._pos = line_end + 1 self._line_start = self._pos def fail(msg: str, offset: int) -> None: self._error(msg, self._pos + offset) self._pos = line_end + 1 self._line_start = self._pos skip_ws() if pos >= line_len: success(None, None) return if line[pos] == '"': fail("filename before line number in #line", pos) return # Line numbers allow digit separators, but no integer suffixes. m = re.match(_decimal_digits, line[pos:]) if not m: fail("invalid #line directive", pos) return pp_line = m.group(0) pos += len(pp_line) skip_ws() if pos >= line_len: success(pp_line, None) return if line[pos] != '"': fail("invalid #line directive", pos) return m = re.match(_string_literal, line[pos:]) if not m: fail("invalid #line directive", pos) return pp_filename = m.group(0).lstrip('"').rstrip('"') pos += len(m.group(0)) # Consume arbitrary sequence of numeric flags after the directive while True: skip_ws() if pos >= line_len: break m = re.match(_decimal_digits, line[pos:]) if not m: fail("invalid #line directive", pos) return pos += len(m.group(0)) success(pp_line, pp_filename) def _handle_pppragma(self) -> list[Token]: # Parse a full #pragma line; returns a list of tokens with 1 or 2 # tokens - PPPRAGMA and an optional PPPRAGMASTR. If an empty list is # returned, it means an error occurred, or we're at the end of input. # # Examples: # - "#pragma" -> PPPRAGMA only # - "#pragma once" -> PPPRAGMA, PPPRAGMASTR("once") # - "# pragma omp parallel private(th_id)" -> PPPRAGMA, PPPRAGMASTR("omp parallel private(th_id)") # - "#\tpragma {pack: 2, smack: 3}" -> PPPRAGMA, PPPRAGMASTR("{pack: 2, smack: 3}") text = self._lexdata n = len(text) pos = self._pos while pos < n and text[pos] in " \t": pos += 1 if pos >= n: self._pos = pos return [] if not text.startswith("pragma", pos): self._error("invalid #pragma directive", pos) self._pos = pos + 1 return [] pragma_pos = pos pos += len("pragma") toks = [self._make_token("PPPRAGMA", "pragma", pragma_pos)] while pos < n and text[pos] in " \t": pos += 1 start = pos while pos < n and text[pos] != "\n": pos += 1 if pos > start: toks.append(self._make_token("PPPRAGMASTR", text[start:pos], start)) if pos < n and text[pos] == "\n": self._lineno += 1 pos += 1 self._line_start = pos self._pos = pos return toks ## ## Reserved keywords ## _keywords: tuple[str, ...] = ( "AUTO", "BREAK", "CASE", "CHAR", "CONST", "CONTINUE", "DEFAULT", "DO", "DOUBLE", "ELSE", "ENUM", "EXTERN", "FLOAT", "FOR", "GOTO", "IF", "INLINE", "INT", "LONG", "REGISTER", "OFFSETOF", "RESTRICT", "RETURN", "SHORT", "SIGNED", "SIZEOF", "STATIC", "STRUCT", "SWITCH", "TYPEDEF", "UNION", "UNSIGNED", "VOID", "VOLATILE", "WHILE", "__BUILTIN_VA_ARG", "__INT128", "_BOOL", "_COMPLEX", "_GENERIC", "_NORETURN", "_THREAD_LOCAL", "_STATIC_ASSERT", "_ATOMIC", "_ALIGNOF", "_ALIGNAS", "_PRAGMA", ) _keyword_map: dict[str, str] = {} for keyword in _keywords: # Keywords from new C standard are mixed-case, like _Bool, _Alignas, etc. if keyword.startswith("_") and len(keyword) > 1 and keyword[1].isalpha(): _keyword_map[keyword[:2].upper() + keyword[2:].lower()] = keyword else: _keyword_map[keyword.lower()] = keyword # Alternate spellings share token types with the existing grammar. The other # keywords are reserved even where the parser does not yet support their syntax. _c23_keywords = { "alignas": "_ALIGNAS", "alignof": "_ALIGNOF", "bool": "_BOOL", "static_assert": "_STATIC_ASSERT", "thread_local": "_THREAD_LOCAL", "true": "BOOL_CONST", "false": "BOOL_CONST", "nullptr": "NULLPTR", "constexpr": "CONSTEXPR", "typeof": "TYPEOF", "typeof_unqual": "TYPEOF_UNQUAL", "_BitInt": "_BITINT", "_Decimal32": "_DECIMAL32", "_Decimal64": "_DECIMAL64", "_Decimal128": "_DECIMAL128", "_Imaginary": "_IMAGINARY", } ## ## Regexes for use in tokens ## # valid C identifiers (K&R2: A.2.3), plus '$' (supported by some compilers) _identifier = r"[a-zA-Z_$][0-9a-zA-Z_$]*" _attribute_begin = re.compile(r"\[\s*\[") _attribute_end = re.compile(r"\]\s*\]") _attribute_word = re.compile(rf"{_identifier}|(?:[0-9]|\.[0-9])(?:[eEpP][+-]|[\w.'])*") # Accept digit separators in all dialects, retaining them in token values. # A quote must be between two digits of the appropriate base; it cannot # touch a prefix, decimal point, exponent marker/sign, or suffix. _decimal_digits = "[0-9](?:'?[0-9])*" _hex_prefix = "0[xX]" _hex_digits = "[0-9a-fA-F](?:'?[0-9a-fA-F])*" _bin_prefix = "0[bB]" _bin_digits = "[01](?:'?[01])*" # integer constants (K&R2: A.2.5.1) # C23 wb/WB allows u/U before or after it, but no long suffix. Recognize it # in every dialect and let the parser enforce C23. Keep these alternatives # ahead of bare u/U so that an unsigned bit-precise suffix is consumed whole. _integer_suffix_opt = ( r"(([uU](wb|WB))|((wb|WB)[uU]?)|" r"([uU]ll)|([uU]LL)|(ll[uU]?)|(LL[uU]?)|([uU][lL])|([lL][uU]?)|[uU])?" ) _decimal_constant = ( "(0" + _integer_suffix_opt + ")|([1-9](?:'?[0-9])*" + _integer_suffix_opt + ")" ) _octal_constant = "0(?:'?[0-7])*" + _integer_suffix_opt _hex_constant = _hex_prefix + _hex_digits + _integer_suffix_opt _bin_constant = _bin_prefix + _bin_digits + _integer_suffix_opt _bad_octal_constant = "0(?:'?[0-7])*'?[89]" # comments are not supported _unsupported_c_style_comment = r"\/\*" _unsupported_cxx_style_comment = r"\/\/" # Character constants and escape sequences. # # Tokens preserve their source spelling; the lexer does not decode escapes or # validate Unicode code points. Each complete escape must match as one character # in _cconst_char, which is used for both single and multicharacter constants. # Matching is deliberately permissive: simple escapes accept extra letters and # punctuation, and numeric escapes accept decimal digits, not just octal digits. # # _cconst_char is also repeated in the error patterns. If an escape can match in # several ways, long malformed constants can cause exponential backtracking # (https://github.com/eliben/pycparser/issues/61). The lookaheads prevent this: # - Decimal and hexadecimal escapes consume the whole run of digits. For # example, \123 cannot be split into \1 followed by the characters 2 and 3. # - A simple \x escape is allowed only when no hexadecimal digit follows it. # - A complete Unicode escape cannot fall back to a simple \u or \U escape. # _bad_escape also excludes all decimal digits to agree with this permissiveness. # Universal character names consume exactly four hex digits after u or eight # after U. A following hex digit is a separate character, unlike with \x. _unicode_escape = r"(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})" # This lookahead runs immediately after the backslash. If a complete Unicode # escape follows, only _unicode_escape may match it: \u00e9 cannot be read as # \u followed by 0, 0, e, 9. Incomplete forms retain the permissive behavior # of simple escapes. _simple_escape = ( rf"(?!{_unicode_escape})" r"""([a-wyzA-Z._~!=&\^\-\\?'"]|x(?![0-9a-fA-F]))""" ) _decimal_escape = r"""(\d+)(?!\d)""" _hex_escape = r"""(x[0-9a-fA-F]+)(?![0-9a-fA-F])""" _bad_escape = r"""([\\][^a-zA-Z._~^!=&\^\-\\?'"x0-9])""" _escape_sequence = ( r"""(\\(""" + _simple_escape + "|" + _decimal_escape + "|" + _hex_escape + "|" + _unicode_escape + "))" ) # Strings do not need to count the characters represented by escapes. Match # just the backslash and a permitted following character; _string_char consumes # any remaining numeric or Unicode digits as ordinary text. This avoids matching # complete escape sequences repeatedly. The permissive spellings also support # Windows paths in #line filenames, which are matched with _string_literal. _escape_sequence_start_in_string = r"""(\\[0-9a-zA-Z._~!=&\^\-\\?'"])""" _cconst_char = r"""([^'\\\n]|""" + _escape_sequence + ")" _char_const = "'" + _cconst_char + "'" _wchar_const = "L" + _char_const _u8char_const = "u8" + _char_const _u16char_const = "u" + _char_const _u32char_const = "U" + _char_const _multicharacter_constant = "'" + _cconst_char + "{2,4}'" _unmatched_quote = "('" + _cconst_char + "*\\n)|('" + _cconst_char + "*$)" _bad_char_const = ( r"""('""" + _cconst_char + """[^'\n]+')|('')|('""" + _bad_escape + r"""[^'\n]*')""" ) # String literals, including wide and Unicode prefixes. _string_char = r"""([^"\\\n]|""" + _escape_sequence_start_in_string + ")" _string_literal = '"' + _string_char + '*"' _wstring_literal = "L" + _string_literal _u8string_literal = "u8" + _string_literal _u16string_literal = "u" + _string_literal _u32string_literal = "U" + _string_literal _bad_string_literal = '"' + _string_char + "*" + _bad_escape + _string_char + '*"' # floating constants (K&R2: A.2.5.3) _exponent_part = "([eE][-+]?" + _decimal_digits + ")" _fractional_constant = ( "((" + _decimal_digits + r")?\." + _decimal_digits + ")|(" + _decimal_digits + r"\.)" ) _unsuffixed_floating_constant = ( "(((" + _fractional_constant + ")" + _exponent_part + "?)|(" + _decimal_digits + _exponent_part + "))" ) # Recognize C23 decimal suffixes in every dialect; the parser rejects them # outside C23. Each suffix must be entirely lowercase or uppercase. # The hexadecimal float pattern below keeps only f/F/l/L. _floating_constant = _unsuffixed_floating_constant + "(df|dd|dl|DF|DD|DL|[FfLl])?" _binary_exponent_part = "([pP][+-]?" + _decimal_digits + ")" _hex_fractional_constant = ( "(((" + _hex_digits + r""")?\.""" + _hex_digits + ")|(" + _hex_digits + r"""\.))""" ) _hex_floating_constant = ( "(" + _hex_prefix + "(" + _hex_digits + "|" + _hex_fractional_constant + ")" + _binary_exponent_part + "[FfLl]?)" ) class _RegexAction(Enum): TOKEN = 0 ID = 1 ERROR = 2 @dataclass(frozen=True) class _RegexRule: # tok_type: name of the token emitted for a match # regex_pattern: the raw regex (no anchors) to match at the current position # action: TOKEN for normal tokens, ID for identifiers, ERROR to report # error_message: message used for ERROR entries tok_type: str regex_pattern: str action: _RegexAction error_message: str | None _regex_rules: list[_RegexRule] = [ _RegexRule( "UNSUPPORTED_C_STYLE_COMMENT", _unsupported_c_style_comment, _RegexAction.ERROR, "Comments are not supported, see https://github.com/eliben/pycparser#3using.", ), _RegexRule( "UNSUPPORTED_CXX_STYLE_COMMENT", _unsupported_cxx_style_comment, _RegexAction.ERROR, "Comments are not supported, see https://github.com/eliben/pycparser#3using.", ), _RegexRule( "BAD_STRING_LITERAL", _bad_string_literal, _RegexAction.ERROR, "String contains invalid escape code", ), _RegexRule("WSTRING_LITERAL", _wstring_literal, _RegexAction.TOKEN, None), _RegexRule("U8STRING_LITERAL", _u8string_literal, _RegexAction.TOKEN, None), _RegexRule("U16STRING_LITERAL", _u16string_literal, _RegexAction.TOKEN, None), _RegexRule("U32STRING_LITERAL", _u32string_literal, _RegexAction.TOKEN, None), _RegexRule("STRING_LITERAL", _string_literal, _RegexAction.TOKEN, None), _RegexRule("HEX_FLOAT_CONST", _hex_floating_constant, _RegexAction.TOKEN, None), _RegexRule("FLOAT_CONST", _floating_constant, _RegexAction.TOKEN, None), _RegexRule("INT_CONST_HEX", _hex_constant, _RegexAction.TOKEN, None), _RegexRule("INT_CONST_BIN", _bin_constant, _RegexAction.TOKEN, None), _RegexRule( "BAD_CONST_OCT", _bad_octal_constant, _RegexAction.ERROR, "Invalid octal constant", ), _RegexRule("INT_CONST_OCT", _octal_constant, _RegexAction.TOKEN, None), _RegexRule("INT_CONST_DEC", _decimal_constant, _RegexAction.TOKEN, None), _RegexRule("INT_CONST_CHAR", _multicharacter_constant, _RegexAction.TOKEN, None), _RegexRule("CHAR_CONST", _char_const, _RegexAction.TOKEN, None), _RegexRule("WCHAR_CONST", _wchar_const, _RegexAction.TOKEN, None), _RegexRule("U8CHAR_CONST", _u8char_const, _RegexAction.TOKEN, None), _RegexRule("U16CHAR_CONST", _u16char_const, _RegexAction.TOKEN, None), _RegexRule("U32CHAR_CONST", _u32char_const, _RegexAction.TOKEN, None), _RegexRule("UNMATCHED_QUOTE", _unmatched_quote, _RegexAction.ERROR, "Unmatched '"), _RegexRule("BAD_CHAR_CONST", _bad_char_const, _RegexAction.ERROR, None), _RegexRule("ID", _identifier, _RegexAction.ID, None), ] _regex_actions: dict[str, tuple[_RegexAction, str | None]] = {} _regex_pattern_parts: list[str] = [] for _rule in _regex_rules: _regex_actions[_rule.tok_type] = (_rule.action, _rule.error_message) _regex_pattern_parts.append(f"(?P<{_rule.tok_type}>{_rule.regex_pattern})") # The master regex is a single alternation of all token patterns, each wrapped # in a named group. We match once at the current position and then use # `lastgroup` to recover which token kind fired; this avoids iterating over all # regexes on every character while keeping the same token-level semantics. _regex_master: re.Pattern[str] = re.compile("|".join(_regex_pattern_parts)) @dataclass(frozen=True) class _FixedToken: tok_type: str literal: str _fixed_tokens: list[_FixedToken] = [ _FixedToken("ELLIPSIS", "..."), _FixedToken("LSHIFTEQUAL", "<<="), _FixedToken("RSHIFTEQUAL", ">>="), _FixedToken("PLUSPLUS", "++"), _FixedToken("MINUSMINUS", "--"), _FixedToken("ARROW", "->"), _FixedToken("LAND", "&&"), _FixedToken("LOR", "||"), _FixedToken("LSHIFT", "<<"), _FixedToken("RSHIFT", ">>"), _FixedToken("LE", "<="), _FixedToken("GE", ">="), _FixedToken("EQ", "=="), _FixedToken("NE", "!="), _FixedToken("TIMESEQUAL", "*="), _FixedToken("DIVEQUAL", "/="), _FixedToken("MODEQUAL", "%="), _FixedToken("PLUSEQUAL", "+="), _FixedToken("MINUSEQUAL", "-="), _FixedToken("ANDEQUAL", "&="), _FixedToken("OREQUAL", "|="), _FixedToken("XOREQUAL", "^="), _FixedToken("EQUALS", "="), _FixedToken("PLUS", "+"), _FixedToken("MINUS", "-"), _FixedToken("TIMES", "*"), _FixedToken("DIVIDE", "/"), _FixedToken("MOD", "%"), _FixedToken("OR", "|"), _FixedToken("AND", "&"), _FixedToken("NOT", "~"), _FixedToken("XOR", "^"), _FixedToken("LNOT", "!"), _FixedToken("LT", "<"), _FixedToken("GT", ">"), _FixedToken("CONDOP", "?"), _FixedToken("LPAREN", "("), _FixedToken("RPAREN", ")"), _FixedToken("LBRACKET", "["), _FixedToken("RBRACKET", "]"), _FixedToken("LBRACE", "{"), _FixedToken("RBRACE", "}"), _FixedToken("COMMA", ","), _FixedToken("PERIOD", "."), _FixedToken("SEMI", ";"), _FixedToken("COLON", ":"), _FixedToken("COLONCOLON", "::"), ] # To avoid scanning all fixed tokens on every character, we bucket them by the # first character. When matching at position i, we only look at the bucket for # text[i], and we pre-sort that bucket by token length so the first match is # also the longest. This preserves longest-match semantics (e.g. '>>=' before # '>>' before '>') while reducing the number of comparisons. _fixed_tokens_by_first: dict[str, list[_FixedToken]] = {} for _entry in _fixed_tokens: _fixed_tokens_by_first.setdefault(_entry.literal[0], []).append(_entry) for _bucket in _fixed_tokens_by_first.values(): _bucket.sort(key=lambda item: len(item.literal), reverse=True) _line_pattern: re.Pattern[str] = re.compile(r"([ \t]*line\W)|([ \t]*\d+)") _pragma_pattern: re.Pattern[str] = re.compile(r"[ \t]*pragma\W") ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792674026.6474898 pycparser-3.12/pycparser/c_parser.py0000664000175000017500000032650615266404353017173 0ustar00elibeneliben# ------------------------------------------------------------------------------ # pycparser: c_parser.py # # Recursive-descent parser for the C language. # # Eli Bendersky [https://eli.thegreenplace.net/] # License: BSD # ------------------------------------------------------------------------------ from collections.abc import Callable from dataclasses import dataclass from typing import ( Any, Literal, NoReturn, NotRequired, Optional, TypedDict, cast, ) from . import c_ast from .ast_transforms import fix_atomic_specifiers, fix_switch_cases from .c_lexer import CLexer, Dialect, Token # ASTs contain many coordinates, so slots reduce their memory overhead. @dataclass(slots=True) class Coord: """Coordinates of a syntactic element. Consists of: - File name - Line number - Column number """ file: str line: int column: int | None = None def __str__(self) -> str: text = f"{self.file}:{self.line}" if self.column is not None: text += f":{self.column}" return text class ParseError(Exception): pass class CParser: """Recursive-descent C parser. Usage: parser = CParser() ast = parser.parse(text, filename) The `lexer` parameter lets you inject a lexer class (defaults to CLexer). The positional parameters other than `lexer` are accepted for backward compatibility with the old PLY-based parser and are otherwise unused. The keyword-only `dialect` parameter selects keyword recognition: "legacy" preserves existing behavior, while "c23" enables C23 spellings, predefined constants, and other C23-only features. """ def __init__( self, lex_optimize: bool = True, lexer: type[CLexer] = CLexer, lextab: str = "pycparser.lextab", yacc_optimize: bool = True, yacctab: str = "pycparser.yacctab", yacc_debug: bool = False, taboutputdir: str = "", *, dialect: Dialect = "legacy", ) -> None: self.clex: CLexer = lexer( error_func=self._lex_error_func, dialect=dialect, ) self._dialect = dialect # Stack of scopes for keeping track of symbols. _scope_stack[-1] is # the current (topmost) scope. Each scope is a dictionary that # specifies whether a name is a type. If _scope_stack[n][name] is # True, 'name' is currently a type in the scope. If it's False, # 'name' is defined in the scope but not as a type (for instance, if we # saw: int name;) # If 'name' is not a key in _scope_stack[n] then 'name' was not defined # in this scope at all. self._scope_stack: list[dict[str, bool]] = [{}] # Cache the token already checked for typedef-name status to avoid repeated # lookups when peeking or consuming. Cleared when scopes or bindings change. self._typedef_checked_token: Token | None = None self._tokens: _TokenStream = _TokenStream(self.clex.token) def parse( self, text: str, filename: str = "", debug: bool = False ) -> c_ast.FileAST: """Parses C code and returns an AST. text: A string containing the C source code filename: Name of the file being parsed (for meaningful error messages) debug: Deprecated debug flag (unused); for backwards compatibility. """ self._scope_stack = [{}] self._typedef_checked_token = None self.clex.input(text, filename) self._tokens = _TokenStream(self.clex.token) ast = self._parse_translation_unit_or_empty() tok = self._peek() if tok is not None: self._parse_error(f"before: {tok.value}", self._tok_coord(tok)) return ast # ------------------------------------------------------------------ # Scope and declaration helpers # ------------------------------------------------------------------ def _parse_error(self, msg: str, coord: Coord | str | None) -> NoReturn: raise ParseError(f"{coord}: {msg}") def _push_scope(self) -> None: self._scope_stack.append({}) self._typedef_checked_token = None def _pop_scope(self) -> None: assert len(self._scope_stack) > 1, "Cannot pop the global scope" self._scope_stack.pop() self._typedef_checked_token = None def _add_typedef_name(self, name: str, coord: Coord | None) -> None: """Add a new typedef name (ie a TYPEID) to the current scope""" if not self._scope_stack[-1].get(name, True): self._parse_error( f"Typedef {name!r} previously declared as non-typedef in this scope", coord, ) self._scope_stack[-1][name] = True self._typedef_checked_token = None def _add_identifier(self, name: str, coord: Coord | None) -> None: """Add a new object, function, or enum member name (ie an ID) to the current scope """ if self._scope_stack[-1].get(name, False): self._parse_error( f"Non-typedef {name!r} previously declared as typedef in this scope", coord, ) self._scope_stack[-1][name] = False self._typedef_checked_token = None def _is_type_in_scope(self, name: str) -> bool: """Is *name* a typedef-name in the current scope?""" for scope in reversed(self._scope_stack): # If name is an identifier in this scope it shadows typedefs in # higher scopes. if name in scope: return scope[name] return False def _lex_error_func(self, msg: str, line: int, column: int) -> None: self._parse_error(msg, Coord(file=self.clex.filename, line=line, column=column)) # To understand what's going on here, read sections A.8.5 and # A.8.6 of K&R2 very carefully. # # A C type consists of a basic type declaration, with a list # of modifiers. For example: # # int *c[5]; # # The basic declaration here is 'int c', and the pointer and # the array are the modifiers. # # Basic declarations are represented by TypeDecl (from module c_ast) and the # modifiers are FuncDecl, PtrDecl and ArrayDecl. # # The standard states that whenever a new modifier is parsed, it should be # added to the end of the list of modifiers. For example: # # K&R2 A.8.6.2: Array Declarators # # In a declaration T D where D has the form # D1 [constant-expression-opt] # and the type of the identifier in the declaration T D1 is # "type-modifier T", the type of the # identifier of D is "type-modifier array of T" # # This is what this method does. The declarator it receives # can be a list of declarators ending with TypeDecl. It # tacks the modifier to the end of this list, just before # the TypeDecl. # # Additionally, the modifier may be a list itself. This is # useful for pointers, that can come as a chain from the rule # p_pointer. In this case, the whole modifier list is spliced # into the new location. def _type_modify_decl(self, decl: Any, modifier: Any) -> c_ast.Node: """Tacks a type modifier on a declarator, and returns the modified declarator. Note: the declarator and modifier may be modified """ modifier_head = modifier modifier_tail = modifier # The modifier may be a nested list. Reach its tail. while modifier_tail.type: modifier_tail = modifier_tail.type # If the decl is a basic type, just tack the modifier onto it. if isinstance(decl, c_ast.TypeDecl): modifier_tail.type = decl return modifier else: # Otherwise, the decl is a list of modifiers. Reach # its tail and splice the modifier onto the tail, # pointing to the underlying basic type. decl_tail = decl while not isinstance(decl_tail.type, c_ast.TypeDecl): decl_tail = decl_tail.type modifier_tail.type = decl_tail.type decl_tail.type = modifier_head return decl # Due to the order in which declarators are constructed, # they have to be fixed in order to look like a normal AST. # # When a declaration arrives from syntax construction, it has # these problems: # * The innermost TypeDecl has no type (because the basic # type is only known at the uppermost declaration level) # * The declaration has no variable name, since that is saved # in the innermost TypeDecl # * The typename of the declaration is a list of type # specifiers, and not a node. Here, basic identifier types # should be separated from more complex types like enums # and structs. # # This method fixes these problems. def _fix_decl_name_type( self, decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename, typename: list[c_ast.Node], ) -> c_ast.Decl | c_ast.Typedef | c_ast.Typename: """Fixes a declaration. Modifies decl.""" # Reach the underlying basic type typ = decl while not isinstance(typ, c_ast.TypeDecl): typ = typ.type decl.name = typ.declname typ.quals = decl.quals[:] # The typename is a list of types. Except for _BitInt with an # optional signedness, any type that isn't an IdentifierType must # be the only type in the list (it's illegal to declare "int enum .."). # If all the types are basic, they're collected in the # IdentifierType holder. names: list[str] = [] for tn in typename: if isinstance(tn, c_ast.BitIntType): signedness = None for spec in typename: if spec is tn: continue if ( signedness is not None or not isinstance(spec, c_ast.IdentifierType) or spec.names not in (["signed"], ["unsigned"]) ): self._parse_error( "Invalid multiple types specified", spec.coord ) signedness = spec.names[0] # Specifiers are shared by comma-separated declarations; # keep the parsed specifier unchanged when attaching the sign. typ.type = c_ast.BitIntType(tn.width, signedness, tn.coord) return decl if not isinstance(tn, c_ast.IdentifierType): if len(typename) > 1: self._parse_error("Invalid multiple types specified", tn.coord) else: typ.type = tn # Normalize atomic specifiers for declarations and type # names alike (casts, sizeof, unnamed parameters, etc.). return fix_atomic_specifiers(decl) names.extend(tn.names) if not typename: # Functions default to returning int if not isinstance(decl.type, c_ast.FuncDecl): self._parse_error("Missing type in declaration", decl.coord) typ.type = c_ast.IdentifierType(["int"], coord=decl.coord) else: typ.type = c_ast.IdentifierType(names, coord=typename[0].coord) return decl def _add_declaration_specifier( self, declspec: Optional["_DeclSpec"], newspec: str | c_ast.Node, kind: "_DeclSpecKind", ) -> "_DeclSpec": """Append a specifier in source order; see _DeclSpec for the layout.""" if declspec is None: spec: _DeclSpec = { "qual": [], "storage": [], "type": [], "function": [], "alignment": [], "type_attributes": [], } else: spec = declspec if kind == "type": assert isinstance(newspec, c_ast.Node) spec[kind].append(newspec) elif kind == "alignment": assert isinstance(newspec, c_ast.Alignas) spec[kind].append(newspec) else: assert isinstance(newspec, str) spec[kind].append(newspec) return spec def _build_type_name( self, spec: "_DeclSpec", decl: c_ast.Node | None, coord: Coord | None ) -> c_ast.Typename: """Build and normalize an abstract type, including its attributes. Callers select the coordinate according to their grammar context. The name, if any, is taken from the declarator by _fix_decl_name_type. """ typename = c_ast.Typename( name=None, quals=spec["qual"][:], align=None, type=decl or c_ast.TypeDecl(None, None, None, None), coord=coord, ) return cast( c_ast.Typename, self._attach_type_attributes( self._fix_decl_name_type(typename, spec["type"]), spec ), ) def _build_declarations( self, spec: "_DeclSpec", decls: list["_DeclInfo"], typedef_namespace: bool = False, ) -> list[c_ast.Node]: """Builds a list of declarations all sharing the given specifiers. If typedef_namespace is true, each declared name is added to the "typedef namespace", which also includes objects, functions, and enum constants. """ is_typedef = "typedef" in spec["storage"] declarations = [] # Bit-fields are allowed to be unnamed. if decls[0].get("bitsize") is None: # When redeclaring typedef names as identifiers in inner scopes, a # problem can occur where the identifier gets grouped into # spec['type'], leaving decl as None. This can only occur for the # first declarator. if decls[0]["decl"] is None: if ( len(spec["type"]) < 2 or not isinstance(spec["type"][-1], c_ast.IdentifierType) or len(spec["type"][-1].names) != 1 or not self._is_type_in_scope(spec["type"][-1].names[0]) ): coord = "?" for t in spec["type"]: if hasattr(t, "coord"): coord = t.coord break self._parse_error("Invalid declaration", coord) # Make this look as if it came from "direct_declarator:ID" decls[0]["decl"] = c_ast.TypeDecl( declname=spec["type"][-1].names[0], type=None, quals=None, align=spec["alignment"], coord=spec["type"][-1].coord, ) # Remove the "new" type's name from the end of spec['type'] del spec["type"][-1] # A similar problem can occur where the declaration ends up # looking like an abstract declarator. Give it a name if this is # the case. elif isinstance(decls[0]["decl"], _DECLARATOR_NODES): decls_0_tail = cast(Any, decls[0]["decl"]) while not isinstance(decls_0_tail, c_ast.TypeDecl): decls_0_tail = decls_0_tail.type if decls_0_tail.declname is None: type_name = cast(c_ast.IdentifierType, spec["type"][-1]) decls_0_tail.declname = type_name.names[0] del spec["type"][-1] for decl in decls: assert decl["decl"] is not None if is_typedef: declaration = c_ast.Typedef( name=None, quals=spec["qual"], storage=spec["storage"], type=decl["decl"], coord=decl["decl"].coord, ) else: declaration = c_ast.Decl( name=None, quals=spec["qual"], align=spec["alignment"], storage=spec["storage"], funcspec=spec["function"], type=decl["decl"], init=decl.get("init"), bitsize=decl.get("bitsize"), coord=decl["decl"].coord, ) if not isinstance(declaration.type, _DECLARATOR_NODES): fixed_decl = declaration else: fixed_decl = self._fix_decl_name_type(declaration, spec["type"]) # Record the declared name in the current scope so the parser can # distinguish identifiers from typedef names. if typedef_namespace: if is_typedef: self._add_typedef_name(fixed_decl.name, fixed_decl.coord) else: self._add_identifier(fixed_decl.name, fixed_decl.coord) declarations.append(self._attach_type_attributes(fixed_decl, spec)) return declarations def _build_function_definition( self, spec: "_DeclSpec", decl: c_ast.Node, param_decls: list[c_ast.Node] | None, body: c_ast.Node, ) -> c_ast.Node: """Builds a function definition.""" if "typedef" in spec["storage"]: self._parse_error("Invalid typedef", decl.coord) declaration = self._build_declarations( spec=spec, decls=[{"decl": decl}], typedef_namespace=True, )[0] return c_ast.FuncDef( decl=declaration, param_decls=param_decls, body=body, coord=decl.coord ) def _select_struct_union_class(self, token: str) -> type: """Given a token (either STRUCT or UNION), selects the appropriate AST class. """ if token == "struct": return c_ast.Struct else: return c_ast.Union # ------------------------------------------------------------------ # Token helpers # ------------------------------------------------------------------ def _peek(self, k: int = 1) -> Token | None: """Return the k-th next token without consuming it (1-based).""" tok = self._tokens.peek(k) if tok is not self._typedef_checked_token: self._classify_identifier(tok) return tok def _classify_identifier(self, tok: Token | None) -> None: # Buffered identifiers are interpreted in the current scope, including # after backtracking. Peeking and consuming can reuse the classification # until a scope or binding changes. if tok is not None and tok.type in {"ID", "TYPEID"}: tok.type = "TYPEID" if self._is_type_in_scope(tok.value) else "ID" self._typedef_checked_token = tok def _peek_type(self, k: int = 1) -> str | None: """Return the type of the k-th next token, or None if absent (1-based).""" tok = self._peek(k) return tok.type if tok is not None else None def _advance(self) -> Token: tok = self._tokens.next() if tok is None: self._parse_error("At end of input", self.clex.filename) if tok is not self._typedef_checked_token: self._classify_identifier(tok) return tok def _accept(self, token_type: str) -> Token | None: """Conditionally consume next token, only if it's of token_type. If it is of the expected type, consume and return it. Otherwise, leaves the token intact and returns None. """ tok = self._peek() if tok is not None and tok.type == token_type: return self._advance() return None def _expect(self, token_type: str) -> Token: tok = self._advance() if tok.type != token_type: self._parse_error(f"before: {tok.value}", self._tok_coord(tok)) return tok def _mark(self) -> int: return self._tokens.mark() def _reset(self, mark: int) -> None: self._tokens.reset(mark) def _tok_coord(self, tok: Token) -> Coord: return Coord(file=tok.filename, line=tok.lineno, column=tok.column) def _starts_declaration(self, tok: Token | None = None) -> bool: tok = tok or self._peek() if tok is None: return False return tok.type in _DECL_START def _starts_expression(self, tok: Token | None = None) -> bool: tok = tok or self._peek() if tok is None: return False return tok.type in _STARTS_EXPRESSION def _starts_statement(self) -> bool: if self._peek_type() == "ATTRIBUTE_BEGIN": mark = self._mark() self._parse_attribute_specifier_sequence() starts = not self._starts_declaration() self._reset(mark) return starts tok_type = self._peek_type() if tok_type is None: return False if tok_type in _STARTS_STATEMENT: return True return self._starts_expression() def _starts_declarator(self, id_only: bool = False) -> bool: tok_type = self._peek_type() if tok_type is None: return False if tok_type in {"TIMES", "LPAREN"}: return True if id_only: return tok_type == "ID" return tok_type in {"ID", "TYPEID"} def _peek_declarator_name_info(self) -> tuple[str | None, bool]: mark = self._mark() tok_type, saw_paren = self._scan_declarator_name_info() self._reset(mark) return tok_type, saw_paren def _parse_any_declarator( self, allow_abstract: bool = False, typeid_paren_as_abstract: bool = False ) -> tuple[c_ast.Node | None, bool]: # C declarators are ambiguous without lookahead. For example: # int foo(int (aa)); -> aa is a name (ID) # typedef char TT; # int bar(int (TT)); -> TT is a type (TYPEID) in parens name_type, saw_paren = self._peek_declarator_name_info() if name_type is None or ( typeid_paren_as_abstract and name_type == "TYPEID" and saw_paren ): if not allow_abstract: tok = self._peek() coord = self._tok_coord(tok) if tok is not None else self.clex.filename self._parse_error("Invalid declarator", coord) decl = self._parse_abstract_declarator_opt() return decl, False if name_type == "TYPEID": if typeid_paren_as_abstract: decl = self._parse_typeid_noparen_declarator() else: decl = self._parse_typeid_declarator() else: decl = self._parse_id_declarator() return decl, True def _scan_declarator_name_info(self) -> tuple[str | None, bool]: saw_paren = False while self._accept("TIMES"): self._parse_attribute_specifier_sequence() while self._peek_type() in _TYPE_QUALIFIER: self._advance() tok = self._peek() if tok is None: return None, saw_paren if tok.type in {"ID", "TYPEID"}: self._advance() return tok.type, saw_paren if tok.type == "LPAREN": saw_paren = True self._advance() tok_type, nested_paren = self._scan_declarator_name_info() if nested_paren: saw_paren = True depth = 1 while True: tok = self._peek() if tok is None: return None, saw_paren if tok.type == "LPAREN": depth += 1 elif tok.type == "RPAREN": depth -= 1 self._advance() if depth == 0: break continue self._advance() return tok_type, saw_paren return None, saw_paren def _starts_direct_abstract_declarator(self) -> bool: return self._peek_type() in {"LPAREN", "LBRACKET"} def _is_assignment_op(self) -> bool: tok = self._peek() return tok is not None and tok.type in _ASSIGNMENT_OPS def _try_parse_paren_type_name( self, ) -> tuple[c_ast.Typename, int, Token, list[str]] | None: """Parse and return a parenthesized type name if present. Returns (typ, mark, lparen_tok, storage) when the next tokens look like '(' type_name ')', where typ is the parsed type name, mark is the token-stream position before parsing, and lparen_tok is the LPAREN token. C23 storage specifiers may precede the type name, but require a following '{' for a compound literal. Returns None if no parenthesized type name is present. """ lparen_tok = self._peek() # Avoid saving a backtracking position when there's no '(' to parse. if lparen_tok is None or lparen_tok.type != "LPAREN": return None mark = self._mark() self._advance() if not self._starts_declaration(): self._reset(mark) return None storage = [] while self._peek_type() in _STORAGE_CLASS: tok = self._advance() if self._dialect != "c23": self._parse_error( "Storage class specifiers in compound literals require C23", self._tok_coord(tok), ) storage.append(tok.value) typ = self._parse_type_name() if self._accept("RPAREN") is None: self._reset(mark) return None if storage and self._peek_type() != "LBRACE": self._parse_error( "Storage class specifiers require a compound literal initializer", self._tok_coord(lparen_tok), ) return typ, mark, lparen_tok, storage # ------------------------------------------------------------------ # Top-level # ------------------------------------------------------------------ def _parse_attribute_specifier_sequence(self) -> list[c_ast.AttributeSpecifier]: groups = [] while self._peek_type() == "ATTRIBUTE_BEGIN": opening = self._advance() if self._dialect != "c23": self._parse_error("Attributes require C23", self._tok_coord(opening)) attributes = [] while self._peek_type() != "ATTRIBUTE_END": if self._accept("COMMA"): continue name = self._parse_identifier_or_typeid() namespace = None if self._accept("COLONCOLON"): namespace = name.name name = self._parse_identifier_or_typeid() arguments = self._accept("ATTRIBUTE_ARGUMENTS") attributes.append( c_ast.Attribute( name.name, namespace, arguments.value if arguments is not None else None, name.coord, ) ) if not self._accept("COMMA"): break self._expect("ATTRIBUTE_END") groups.append( c_ast.AttributeSpecifier(attributes, self._tok_coord(opening)) ) return groups def _attribute_declarations( self, nodes: list[c_ast.Node], attributes: list[c_ast.AttributeSpecifier] ) -> list[c_ast.Node]: """Attach declaration prefixes, shared by comma-separated declarators.""" if not nodes or isinstance(nodes[0], c_ast.Pragma): self._parse_error( "Expected declaration after attributes", attributes[0].coord ) for node in nodes: # Trailing pragmas belong to the surrounding list, not to the # declaration carrying these attributes. if isinstance(node, c_ast.Pragma): continue decl = node.decl if isinstance(node, c_ast.FuncDef) else node if not isinstance(decl, (c_ast.Decl, c_ast.Typedef)): self._parse_error( "Expected declaration after attributes", attributes[0].coord ) decl.attributes = attributes return nodes def _attribute_statement( self, stmt: c_ast.Node, attributes: list[c_ast.AttributeSpecifier] ) -> c_ast.Node: if isinstance(stmt, (c_ast.Label, c_ast.Case, c_ast.Default)): stmt.attributes = attributes return stmt return c_ast.AttributedStatement(attributes, stmt, attributes[0].coord) def _attach_type_attributes( self, decl: c_ast.Decl | c_ast.Typedef | c_ast.Typename, spec: "_DeclSpec" ) -> c_ast.Decl | c_ast.Typedef | c_ast.Typename: """Keep attributes after the base type, inside pointer/array modifiers.""" if spec["type_attributes"]: target = decl while isinstance( target.type, (c_ast.PtrDecl, c_ast.ArrayDecl, c_ast.FuncDecl, c_ast.TypeDecl), ): target = target.type target.type = c_ast.AttributedType( target.type, spec["type_attributes"], target.type.coord ) return decl # BNF: translation_unit_or_empty : translation_unit | empty def _parse_translation_unit_or_empty(self) -> c_ast.FileAST: if self._peek() is None: return c_ast.FileAST([]) return c_ast.FileAST(self._parse_translation_unit()) # BNF: translation_unit : external_declaration+ def _parse_translation_unit(self) -> list[c_ast.Node]: ext = [] while self._peek() is not None: ext.extend(self._parse_external_declaration()) return ext # BNF: external_declaration : function_definition # | declaration # | pp_directive # | pppragma_directive # | static_assert # | ';' def _parse_external_declaration(self) -> list[c_ast.Node]: if self._peek_type() == "ATTRIBUTE_BEGIN": attributes = self._parse_attribute_specifier_sequence() if self._accept("SEMI"): return [c_ast.AttributeDeclaration(attributes, attributes[0].coord)] return self._attribute_declarations( self._parse_external_declaration(), attributes ) tok = self._peek() if tok is None: return [] if tok.type == "PPHASH": self._parse_pp_directive() return [] if tok.type in {"PPPRAGMA", "_PRAGMA"}: return [self._parse_pppragma_directive()] if self._accept("SEMI"): return [] if tok.type == "_STATIC_ASSERT": return [self._parse_static_assert()] if not self._starts_declaration(tok): # Special handling for old-style function definitions that have an # implicit return type, e.g. # # foo() { # return 5; # } # # These get an implicit 'int' return type. decl = self._parse_id_declarator() if self._peek_type() != "LBRACE": self._parse_error("Invalid function definition", decl.coord) spec: _DeclSpec = { "qual": [], "alignment": [], "storage": [], "type": [c_ast.IdentifierType(["int"], coord=decl.coord)], "function": [], "type_attributes": [], } return [self._parse_function_definition(spec, decl)] # From here on, parsing a standard declatation/definition. spec, saw_type, spec_coord = self._parse_declaration_specifiers( allow_no_type=True ) if self._is_inferred_auto(spec): decls = self._parse_auto_declaration(spec) return self._parse_declaration_end(decls) name_type, _ = self._peek_declarator_name_info() if name_type != "ID": decls = self._parse_decl_body_with_spec(spec, saw_type) return self._parse_declaration_end(decls) decl = self._parse_id_declarator() if self._peek_type() == "LBRACE" or self._starts_declaration(): if not spec["type"]: spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)] return [self._parse_function_definition(spec, decl)] decl_dict: _DeclInfo = {"decl": decl} if self._accept("EQUALS"): decl_dict["init"] = self._parse_initializer() decls = self._parse_init_declarator_list(first=decl_dict) decls = self._build_declarations(spec=spec, decls=decls, typedef_namespace=True) return self._parse_declaration_end(decls) def _parse_function_definition( self, spec: "_DeclSpec", decl: c_ast.Node ) -> c_ast.Node: # Open the scope shared by parameters, old-style parameter declarations, # and the outermost body. self._push_scope() if isinstance(decl, c_ast.FuncDecl) and decl.args is not None: for param in decl.args.params: name = getattr(param, "name", None) if name: self._add_identifier(name, param.coord) param_decls = ( self._parse_declaration_list() if self._starts_declaration() else None ) if self._peek_type() != "LBRACE": self._parse_error("Invalid function definition", decl.coord) body = self._parse_compound_statement(new_scope=False) self._pop_scope() return self._build_function_definition(spec, decl, param_decls, body) # ------------------------------------------------------------------ # Declarations # # Declarations always come as lists (because they can be several in one # line). When returning parsed declarations, a list is always returned - # even if it contains a single element. Pragmas before the final semicolon # follow the declarations in that list. # ------------------------------------------------------------------ # BNF: declaration : decl_body pppragma_directive* ';' | static_assert def _parse_declaration(self) -> list[c_ast.Node]: if self._peek_type() == "ATTRIBUTE_BEGIN": attributes = self._parse_attribute_specifier_sequence() if self._accept("SEMI"): return [c_ast.AttributeDeclaration(attributes, attributes[0].coord)] return self._attribute_declarations(self._parse_declaration(), attributes) if self._peek_type() == "_STATIC_ASSERT": return [self._parse_static_assert()] decls = self._parse_decl_body() return self._parse_declaration_end(decls) def _parse_declaration_end(self, decls: list[c_ast.Node]) -> list[c_ast.Node]: """Consume a declaration's semicolon and retain preceding pragmas. Macro expansions can place diagnostic pragmas just before the final semicolon (issue #478). Represent them after the completed declarations in the surrounding list, just like pragmas following the semicolon. """ pragmas = self._parse_pppragma_directive_list() self._expect("SEMI") return decls + pragmas # BNF: decl_body : declaration_specifiers decl_body_with_spec def _parse_decl_body(self) -> list[c_ast.Node]: spec, saw_type, _ = self._parse_declaration_specifiers(allow_no_type=True) return self._parse_decl_body_with_spec(spec, saw_type) # BNF: decl_body_with_spec : init_declarator_list # | struct_or_union_or_enum_only def _parse_decl_body_with_spec( self, spec: "_DeclSpec", saw_type: bool ) -> list[c_ast.Node]: if self._is_inferred_auto(spec): return self._parse_auto_declaration(spec) # saw_type is True if the specifiers included an actual type (as # opposed to only storage/function/qualifiers). decl_infos: list[_DeclInfo] | None = None if saw_type: if self._starts_declarator(): decl_infos = self._parse_init_declarator_list() else: if self._starts_declarator(id_only=True): decl_infos = self._parse_init_declarator_list(id_only=True) decls: list[c_ast.Node] if decl_infos is None: ty = spec["type"] s_u_or_e = (c_ast.Struct, c_ast.Union, c_ast.Enum) if len(ty) == 1 and isinstance(ty[0], s_u_or_e): decl = c_ast.Decl( name=None, quals=spec["qual"], align=spec["alignment"], storage=spec["storage"], funcspec=spec["function"], type=ty[0], init=None, bitsize=None, coord=ty[0].coord, ) decls = [self._attach_type_attributes(decl, spec)] else: decls = self._build_declarations( spec=spec, decls=[{"decl": None}], typedef_namespace=True, ) else: decls = self._build_declarations( spec=spec, decls=decl_infos, typedef_namespace=True ) return decls def _is_inferred_auto(self, spec: "_DeclSpec") -> bool: return self._dialect == "c23" and "auto" in spec["storage"] and not spec["type"] # C23 type inference uses one plain (possibly parenthesized) name and an # expression initializer. Preserve its syntax without resolving the type. def _parse_auto_declaration(self, spec: "_DeclSpec") -> list[c_ast.Node]: decl = self._parse_id_declarator() if not isinstance(decl, c_ast.TypeDecl): self._parse_error( "Inferred auto declaration requires a plain identifier", decl.coord ) self._expect("EQUALS") init = self._parse_assignment_expression() spec["type"] = [c_ast.InferredType(coord=decl.coord)] # Register the name only after parsing the initializer. return self._build_declarations( spec=spec, decls=[{"decl": decl, "init": init}], typedef_namespace=True, ) # BNF: declaration_list : (declaration pppragma_directive*)+ def _parse_declaration_list(self) -> list[c_ast.Node]: decls = [] while self._starts_declaration(): decls.extend(self._parse_declaration()) # K&R parameter declarations retain pragmas on either side of # their semicolons, including when reparsing generated code. decls.extend(self._parse_pppragma_directive_list()) return decls # BNF: declaration_specifiers : (storage_class_specifier # | type_specifier # | type_qualifier # | function_specifier # | alignment_specifier)+ def _parse_declaration_specifiers( self, allow_no_type: bool = False ) -> tuple["_DeclSpec", bool, Coord | None]: """Parse declaration-specifier sequence. allow_no_type: If True, allow a missing type specifier without error. Returns: (spec, saw_type, first_coord) where spec is a dict with qual/storage/type/function/alignment/type_attributes entries, saw_type is True if a type specifier was consumed, and first_coord is the coord of the first specifier token (used for diagnostics). """ spec, saw_type, first_coord = self._parse_specifiers( allow_storage_and_function=True ) if spec is None: self._parse_error("Invalid declaration", self.clex.filename) if not saw_type and not allow_no_type: self._parse_error("Missing type in declaration", first_coord) return spec, saw_type, first_coord # BNF: specifier_qualifier_list : (type_specifier # | type_qualifier # | alignment_specifier)+ def _parse_specifier_qualifier_list(self) -> "_DeclSpec": spec, saw_type, first_coord = self._parse_specifiers( allow_storage_and_function=False ) if spec is None: self._parse_error("Invalid specifier list", self.clex.filename) if not saw_type and not spec["alignment"]: self._parse_error("Missing type in declaration", first_coord) return spec def _parse_specifiers( self, *, allow_storage_and_function: bool ) -> tuple["_DeclSpec | None", bool, Coord | None]: """Consume specifiers shared by declarations, members, and type names. Storage classes and function specifiers are only accepted in declarations. Callers handle their own missing-specifier diagnostics. """ spec = None saw_type = False first_coord = None while True: tok = self._peek() if tok is None: break if tok.type == "ATTRIBUTE_BEGIN" and spec is not None: spec["type_attributes"] = self._parse_attribute_specifier_sequence() break # Once a type has been seen, a typedef name can be the declarator # (e.g. the second T in "T T"), rather than another type specifier. if tok.type == "TYPEID" and saw_type: break # _Atomic is a type specifier with parentheses, a qualifier without. is_atomic_specifier = ( tok.type == "_ATOMIC" and self._peek_type(2) == "LPAREN" ) if first_coord is None: first_coord = self._tok_coord(tok) kind: _DeclSpecKind = "type" newspec: str | c_ast.Node if tok.type == "_ALIGNAS": kind = "alignment" newspec = self._parse_alignment_specifier() elif is_atomic_specifier: newspec = self._parse_atomic_specifier() elif tok.type in _TYPEOF_SPEC: newspec = self._parse_typeof_specifier() elif tok.type == "_BITINT": newspec = self._parse_bitint_specifier() elif tok.type in _TYPE_QUALIFIER: kind = "qual" newspec = self._advance().value elif allow_storage_and_function and tok.type in _STORAGE_CLASS: kind = "storage" newspec = self._advance().value elif allow_storage_and_function and tok.type in _FUNCTION_SPEC: kind = "function" newspec = self._advance().value elif tok.type in _TYPE_SPEC_SIMPLE or tok.type == "TYPEID": tok = self._advance() newspec = c_ast.IdentifierType([tok.value], coord=self._tok_coord(tok)) elif tok.type in {"STRUCT", "UNION"}: newspec = self._parse_struct_or_union_specifier() elif tok.type == "ENUM": newspec = self._parse_enum_specifier() else: break spec = self._add_declaration_specifier(spec, newspec, kind) if kind == "type": saw_type = True return spec, saw_type, first_coord # BNF: type_qualifier_list : type_qualifier+ def _parse_type_qualifier_list(self) -> list[str]: quals = [] while self._peek_type() in _TYPE_QUALIFIER: quals.append(self._advance().value) return quals # BNF: alignment_specifier : _ALIGNAS '(' type_name | constant_expression ')' def _parse_alignment_specifier(self) -> c_ast.Alignas: tok = self._expect("_ALIGNAS") self._expect("LPAREN") if self._starts_declaration(): typ = self._parse_type_name() self._expect("RPAREN") return c_ast.Alignas(typ, self._tok_coord(tok)) expr = self._parse_constant_expression() self._expect("RPAREN") return c_ast.Alignas(expr, self._tok_coord(tok)) # BNF: atomic_specifier : _ATOMIC '(' type_name ')' def _parse_atomic_specifier(self) -> c_ast.Node: self._expect("_ATOMIC") self._expect("LPAREN") typ = self._parse_type_name() self._expect("RPAREN") typ.quals.append("_Atomic") return typ # BNF: typeof_specifier : (TYPEOF | TYPEOF_UNQUAL) '(' (type_name | expression) ')' def _parse_typeof_specifier(self) -> c_ast.TypeOf: tok = self._advance() self._expect("LPAREN") if self._starts_declaration(): expr = self._parse_type_name() else: expr = self._parse_expression() self._expect("RPAREN") return c_ast.TypeOf(tok.value, expr, self._tok_coord(tok)) # BNF: bitint_specifier : _BITINT '(' constant_expression ')' def _parse_bitint_specifier(self) -> c_ast.BitIntType: tok = self._expect("_BITINT") self._expect("LPAREN") width = self._parse_constant_expression() self._expect("RPAREN") return c_ast.BitIntType(width, None, self._tok_coord(tok)) # BNF: init_declarator_list : init_declarator (',' init_declarator)* def _parse_init_declarator_list( self, first: Optional["_DeclInfo"] = None, id_only: bool = False ) -> list["_DeclInfo"]: decls = ( [first] if first is not None else [self._parse_init_declarator(id_only=id_only)] ) while self._accept("COMMA"): decls.append(self._parse_init_declarator(id_only=id_only)) return decls # BNF: init_declarator : declarator ('=' initializer)? def _parse_init_declarator(self, id_only: bool = False) -> "_DeclInfo": decl = self._parse_id_declarator() if id_only else self._parse_declarator() if self._accept("EQUALS"): return {"decl": decl, "init": self._parse_initializer()} return {"decl": decl} # ------------------------------------------------------------------ # Structs/unions/enums # ------------------------------------------------------------------ # BNF: struct_or_union_specifier : struct_or_union ID? '{' struct_declaration_list? '}' # | struct_or_union ID def _parse_struct_or_union_specifier(self) -> c_ast.Node: tok = self._advance() attributes = self._parse_attribute_specifier_sequence() klass = self._select_struct_union_class(tok.value) if self._peek_type() in {"ID", "TYPEID"}: name_tok = self._advance() if self._peek_type() == "LBRACE": self._advance() if self._accept("RBRACE"): return klass( attributes=attributes, name=name_tok.value, decls=[], coord=self._tok_coord(name_tok), ) decls = self._parse_struct_declaration_list() self._expect("RBRACE") return klass( attributes=attributes, name=name_tok.value, decls=decls, coord=self._tok_coord(name_tok), ) return klass( attributes=attributes, name=name_tok.value, decls=None, coord=self._tok_coord(name_tok), ) if self._peek_type() == "LBRACE": brace_tok = self._advance() if self._accept("RBRACE"): return klass( attributes=attributes, name=None, decls=[], coord=self._tok_coord(brace_tok), ) decls = self._parse_struct_declaration_list() self._expect("RBRACE") return klass( attributes=attributes, name=None, decls=decls, coord=self._tok_coord(brace_tok), ) self._parse_error("Invalid struct/union declaration", self._tok_coord(tok)) # BNF: struct_declaration_list : struct_declaration+ def _parse_struct_declaration_list(self) -> list[c_ast.Node]: decls = [] while self._peek_type() not in {None, "RBRACE"}: items = self._parse_struct_declaration() if items is None: continue decls.extend(items) return decls # BNF: struct_declaration : specifier_qualifier_list struct_declarator_list? # pppragma_directive* ';' # | static_assert # | pppragma_directive def _parse_struct_declaration(self) -> list[c_ast.Node] | None: if self._peek_type() == "ATTRIBUTE_BEGIN": attributes = self._parse_attribute_specifier_sequence() return self._attribute_declarations( self._parse_struct_declaration() or [], attributes ) if self._peek_type() == "_STATIC_ASSERT": return [self._parse_static_assert()] if self._peek_type() == "SEMI": self._advance() return None if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}: return [self._parse_pppragma_directive()] spec = self._parse_specifier_qualifier_list() assert "typedef" not in spec.get("storage", []) decls = None if self._starts_declarator() or self._peek_type() == "COLON": decls = self._parse_struct_declarator_list() if decls is not None: return self._parse_declaration_end( self._build_declarations(spec=spec, decls=decls) ) if len(spec["type"]) == 1: node = spec["type"][0] if isinstance(node, c_ast.Node): decl_type = node else: decl_type = c_ast.IdentifierType(node) return self._parse_declaration_end( self._build_declarations(spec=spec, decls=[{"decl": decl_type}]) ) return self._parse_declaration_end( self._build_declarations(spec=spec, decls=[{"decl": None}]) ) # BNF: struct_declarator_list : struct_declarator (',' struct_declarator)* def _parse_struct_declarator_list(self) -> list["_DeclInfo"]: decls = [self._parse_struct_declarator()] while self._accept("COMMA"): decls.append(self._parse_struct_declarator()) return decls # BNF: struct_declarator : declarator? ':' constant_expression # | declarator (':' constant_expression)? def _parse_struct_declarator(self) -> "_DeclInfo": if self._accept("COLON"): bitsize = self._parse_constant_expression() return { "decl": c_ast.TypeDecl(None, None, None, None), "bitsize": bitsize, } decl = self._parse_declarator() if self._accept("COLON"): bitsize = self._parse_constant_expression() return {"decl": decl, "bitsize": bitsize} return {"decl": decl} # BNF: enum_specifier : ENUM ID? enum_type_specifier? '{' enumerator_list '}' # | ENUM ID enum_type_specifier? def _parse_enum_specifier(self) -> c_ast.Node: tok = self._expect("ENUM") attributes = self._parse_attribute_specifier_sequence() name = None if self._peek_type() in {"ID", "TYPEID"}: name = self._advance().value underlying_type = None # A colon followed by an expression belongs to an unnamed bit-field, # e.g. struct S { enum E : 3; }, rather than a fixed underlying type. if self._peek_type() == "COLON" and self._starts_declaration(self._peek(2)): underlying_type = self._parse_enum_type_specifier() enums = None if name is None or self._peek_type() == "LBRACE": self._expect("LBRACE") enums = self._parse_enumerator_list() self._expect("RBRACE") return c_ast.Enum( name, enums, underlying_type, self._tok_coord(tok), attributes=attributes, ) # BNF: enum_type_specifier : ':' specifier_qualifier_list (C23) def _parse_enum_type_specifier(self) -> c_ast.Typename: colon = self._expect("COLON") if self._dialect != "c23": self._parse_error( "Fixed underlying enum types require C23", self._tok_coord(colon) ) # The base is a specifier-qualifier list, not a full type name: any # following pointer, array, or function declarator belongs to the enum. spec = self._parse_specifier_qualifier_list() coord = spec["type"][0].coord if spec["type"] else self._tok_coord(colon) return self._build_type_name(spec, None, coord) # BNF: enumerator_list : pppragma_directive* enumerator pppragma_directive* # (',' pppragma_directive* enumerator pppragma_directive*)* # (',' pppragma_directive*)? def _parse_enumerator_list(self) -> c_ast.Node: members = self._parse_pppragma_directive_list() # Pragmas do not count as enumerators: even with leading directives, # the list must contain at least one enumerator. enum = self._parse_enumerator() members.append(enum) coord = enum.coord while True: # Directives may appear on either side of a separating comma, or # after the last enumerator. They never replace the comma itself. members.extend(self._parse_pppragma_directive_list()) if not self._accept("COMMA"): break members.extend(self._parse_pppragma_directive_list()) if self._peek_type() == "RBRACE": break members.append(self._parse_enumerator()) return c_ast.EnumeratorList(members, coord) # BNF: enumerator : ID ('=' constant_expression)? def _parse_enumerator(self) -> c_ast.Node: name_tok = self._expect("ID") attributes = self._parse_attribute_specifier_sequence() if self._accept("EQUALS"): value = self._parse_constant_expression() else: value = None enum = c_ast.Enumerator( name_tok.value, value, self._tok_coord(name_tok), attributes=attributes, ) self._add_identifier(enum.name, enum.coord) return enum # ------------------------------------------------------------------ # Declarators # ------------------------------------------------------------------ # BNF: declarator : pointer? direct_declarator def _parse_declarator(self) -> c_ast.Node: decl, _ = self._parse_any_declarator( allow_abstract=False, typeid_paren_as_abstract=False ) assert decl is not None return decl # BNF: id_declarator : declarator with ID name def _parse_id_declarator(self) -> c_ast.Node: return self._parse_declarator_kind(kind="id", allow_paren=True) # BNF: typeid_declarator : declarator with TYPEID name def _parse_typeid_declarator(self) -> c_ast.Node: return self._parse_declarator_kind(kind="typeid", allow_paren=True) # BNF: typeid_noparen_declarator : declarator without parenthesized name def _parse_typeid_noparen_declarator(self) -> c_ast.Node: return self._parse_declarator_kind(kind="typeid", allow_paren=False) # BNF: declarator_kind : pointer? direct_declarator(kind) def _parse_declarator_kind(self, kind: str, allow_paren: bool) -> c_ast.Node: ptr = None if self._peek_type() == "TIMES": ptr = self._parse_pointer() direct = self._parse_direct_declarator(kind, allow_paren=allow_paren) if ptr is not None: return self._type_modify_decl(direct, ptr) return direct # BNF: direct_declarator : ID | TYPEID | '(' declarator ')' # | direct_declarator '[' ... ']' # | direct_declarator '(' ... ')' def _parse_direct_declarator( self, kind: str, allow_paren: bool = True ) -> c_ast.Node: if allow_paren and self._accept("LPAREN"): decl = self._parse_declarator_kind(kind, allow_paren=True) self._expect("RPAREN") else: if kind == "id": name_tok = self._expect("ID") else: name_tok = self._expect("TYPEID") decl = c_ast.TypeDecl( declname=name_tok.value, type=None, quals=None, align=None, coord=self._tok_coord(name_tok), ) decl.attributes = self._parse_attribute_specifier_sequence() return self._parse_decl_suffixes(decl) def _parse_decl_suffixes(self, decl: c_ast.Node) -> c_ast.Node: """Parse a chain of array/function suffixes and attach them to decl.""" while True: if self._peek_type() == "LBRACKET": decl = self._type_modify_decl(decl, self._parse_array_decl(decl)) continue if self._peek_type() == "LPAREN": func = self._parse_function_decl(decl) decl = self._type_modify_decl(decl, func) continue break return decl # BNF: array_decl : '[' array_specifiers? assignment_expression? ']' def _parse_array_decl(self, base_decl: c_ast.Node) -> c_ast.Node: return self._parse_array_decl_common(base_type=None, coord=base_decl.coord) def _parse_array_decl_common( self, base_type: c_ast.Node | None, coord: Coord | None = None ) -> c_ast.Node: """Parse an array declarator suffix and return an ArrayDecl node. base_type: Base declarator node to attach (None for direct-declarator parsing, TypeDecl for abstract declarators). coord: Coordinate to use for the ArrayDecl. If None, uses the '[' token. """ lbrack_tok = self._expect("LBRACKET") if coord is None: coord = self._tok_coord(lbrack_tok) def make_array_decl(dim, dim_quals): return c_ast.ArrayDecl( type=base_type, dim=dim, dim_quals=dim_quals, coord=coord, attributes=self._parse_attribute_specifier_sequence(), ) if self._accept("STATIC"): dim_quals = ["static"] + (self._parse_type_qualifier_list() or []) dim = self._parse_assignment_expression() self._expect("RBRACKET") return make_array_decl(dim, dim_quals) if self._peek_type() in _TYPE_QUALIFIER: dim_quals = self._parse_type_qualifier_list() or [] if self._accept("STATIC"): dim_quals = dim_quals + ["static"] dim = self._parse_assignment_expression() self._expect("RBRACKET") return make_array_decl(dim, dim_quals) times_tok = self._accept("TIMES") if times_tok: self._expect("RBRACKET") dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok)) return make_array_decl(dim, dim_quals) dim = None if self._starts_expression(): dim = self._parse_assignment_expression() self._expect("RBRACKET") return make_array_decl(dim, dim_quals) times_tok = self._accept("TIMES") if times_tok: self._expect("RBRACKET") dim = c_ast.ID(times_tok.value, self._tok_coord(times_tok)) return make_array_decl(dim, []) dim = None if self._starts_expression(): dim = self._parse_assignment_expression() self._expect("RBRACKET") return make_array_decl(dim, []) # BNF: function_decl : '(' parameter_type_list_opt | identifier_list_opt ')' def _parse_function_decl(self, base_decl: c_ast.Node) -> c_ast.Node: self._expect("LPAREN") if self._accept("RPAREN"): args = None else: args = ( self._parse_parameter_type_list() if self._starts_declaration() or self._peek_type() == "ELLIPSIS" else self._parse_identifier_list_opt() ) self._expect("RPAREN") func = c_ast.FuncDecl( args=args, type=None, coord=base_decl.coord, attributes=self._parse_attribute_specifier_sequence(), ) return func # BNF: pointer : '*' type_qualifier_list? pointer? def _parse_pointer(self) -> c_ast.Node | None: stars = [] times_tok = self._accept("TIMES") while times_tok: attributes = self._parse_attribute_specifier_sequence() quals = self._parse_type_qualifier_list() or [] stars.append((quals, self._tok_coord(times_tok), attributes)) times_tok = self._accept("TIMES") if not stars: return None ptr = None for quals, coord, attributes in stars: ptr = c_ast.PtrDecl( quals=quals, type=ptr, coord=coord, attributes=attributes ) return ptr # BNF: parameter_type_list : parameter_list (',' ELLIPSIS)? # | ELLIPSIS (C23) def _parse_parameter_type_list(self) -> c_ast.ParamList: # C23 permits a variadic function with no preceding named parameters. ell_tok = self._accept("ELLIPSIS") if ell_tok: coord = self._tok_coord(ell_tok) if self._dialect != "c23": self._parse_error("Ellipsis-only parameter lists require C23", coord) return c_ast.ParamList([c_ast.EllipsisParam(coord)], coord) params = self._parse_parameter_list() if self._peek_type() == "COMMA" and self._peek_type(2) == "ELLIPSIS": self._advance() ell_tok = self._advance() params.params.append(c_ast.EllipsisParam(self._tok_coord(ell_tok))) return params # BNF: parameter_list : parameter_declaration (',' parameter_declaration)* def _parse_parameter_list(self) -> c_ast.ParamList: first = self._parse_parameter_declaration() params = c_ast.ParamList([first], first.coord) while self._peek_type() == "COMMA" and self._peek_type(2) != "ELLIPSIS": self._advance() params.params.append(self._parse_parameter_declaration()) return params # BNF: parameter_declaration : declaration_specifiers declarator? # | declaration_specifiers abstract_declarator_opt def _parse_parameter_declaration(self) -> c_ast.Node: attributes = self._parse_attribute_specifier_sequence() decl = self._parse_parameter_declaration_body() assert isinstance(decl, (c_ast.Decl, c_ast.Typename)) decl.attributes = attributes return decl def _parse_parameter_declaration_body(self) -> c_ast.Node: spec, _, spec_coord = self._parse_declaration_specifiers(allow_no_type=True) if self._is_inferred_auto(spec): self._parse_error("Cannot infer the type of a parameter", spec_coord) if "typedef" in spec["storage"]: self._parse_error("Invalid storage class for a parameter", spec_coord) if not spec["type"]: spec["type"] = [c_ast.IdentifierType(["int"], coord=spec_coord)] if self._starts_declarator(): decl, is_named = self._parse_any_declarator( allow_abstract=True, typeid_paren_as_abstract=True ) if is_named: return self._build_declarations( spec=spec, decls=[{"decl": decl}], )[0] return self._build_parameter_declaration(spec, decl, spec_coord) decl = self._parse_abstract_declarator_opt() return self._build_parameter_declaration(spec, decl, spec_coord) def _build_parameter_declaration( self, spec: "_DeclSpec", decl: c_ast.Node | None, spec_coord: Coord | None ) -> c_ast.Node: if ( len(spec["type"]) > 1 and isinstance(spec["type"][-1], c_ast.IdentifierType) and len(spec["type"][-1].names) == 1 and self._is_type_in_scope(spec["type"][-1].names[0]) ): return self._build_declarations(spec=spec, decls=[{"decl": decl}])[0] return self._build_type_name(spec, decl, spec_coord) # BNF: identifier_list_opt : identifier_list | empty def _parse_identifier_list_opt(self) -> c_ast.Node | None: if self._peek_type() == "RPAREN": return None return self._parse_identifier_list() # BNF: identifier_list : identifier (',' identifier)* def _parse_identifier_list(self) -> c_ast.Node: first = self._parse_identifier() params = c_ast.ParamList([first], first.coord) while self._accept("COMMA"): params.params.append(self._parse_identifier()) return params # ------------------------------------------------------------------ # Abstract declarators # ------------------------------------------------------------------ # BNF: type_name : specifier_qualifier_list abstract_declarator_opt def _parse_type_name(self) -> c_ast.Typename: spec = self._parse_specifier_qualifier_list() decl = self._parse_abstract_declarator_opt() coord = None if decl is not None: coord = decl.coord elif spec["type"]: coord = spec["type"][0].coord return self._build_type_name(spec, decl, coord) # BNF: abstract_declarator_opt : pointer? direct_abstract_declarator? def _parse_abstract_declarator_opt(self) -> c_ast.Node | None: if self._peek_type() == "TIMES": ptr = self._parse_pointer() if self._starts_direct_abstract_declarator(): decl = self._parse_direct_abstract_declarator() else: decl = c_ast.TypeDecl(None, None, None, None) assert ptr is not None return self._type_modify_decl(decl, ptr) if self._starts_direct_abstract_declarator(): return self._parse_direct_abstract_declarator() return None # BNF: direct_abstract_declarator : '(' parameter_type_list_opt ')' # | '(' abstract_declarator ')' # | '[' ... ']' def _parse_direct_abstract_declarator(self) -> c_ast.Node: lparen_tok = self._accept("LPAREN") if lparen_tok: if self._starts_declaration() or self._peek_type() in { "RPAREN", "ELLIPSIS", }: params = self._parse_parameter_type_list_opt() self._expect("RPAREN") decl = c_ast.FuncDecl( args=params, type=c_ast.TypeDecl(None, None, None, None), coord=self._tok_coord(lparen_tok), attributes=self._parse_attribute_specifier_sequence(), ) else: decl = self._parse_abstract_declarator_opt() self._expect("RPAREN") assert decl is not None elif self._peek_type() == "LBRACKET": decl = self._parse_abstract_array_base() else: self._parse_error("Invalid abstract declarator", self.clex.filename) return self._parse_decl_suffixes(decl) # BNF: parameter_type_list_opt : parameter_type_list | empty def _parse_parameter_type_list_opt(self) -> c_ast.ParamList | None: if self._peek_type() == "RPAREN": return None return self._parse_parameter_type_list() # BNF: abstract_array_base : '[' array_specifiers? assignment_expression? ']' def _parse_abstract_array_base(self) -> c_ast.Node: return self._parse_array_decl_common( base_type=c_ast.TypeDecl(None, None, None, None), coord=None ) # ------------------------------------------------------------------ # Statements # ------------------------------------------------------------------ # BNF: statement : labeled_statement | compound_statement # | selection_statement | iteration_statement # | jump_statement | expression_statement # | pppragma_directive def _parse_statement(self) -> c_ast.Node: if self._peek_type() == "ATTRIBUTE_BEGIN": attributes = self._parse_attribute_specifier_sequence() if self._accept("SEMI"): return c_ast.AttributeDeclaration(attributes, attributes[0].coord) return self._attribute_statement(self._parse_statement(), attributes) tok_type = self._peek_type() match tok_type: case "CASE" | "DEFAULT": return self._parse_labeled_statement() case "ID" if self._peek_type(2) == "COLON": return self._parse_labeled_statement() case "LBRACE": return self._parse_compound_statement() case "IF" | "SWITCH": return self._parse_selection_statement() case "WHILE" | "DO" | "FOR": return self._parse_iteration_statement() case "GOTO" | "BREAK" | "CONTINUE" | "RETURN": return self._parse_jump_statement() case "PPPRAGMA" | "_PRAGMA": return self._parse_pppragma_directive() case _: return self._parse_expression_statement() # BNF: pragmacomp_or_statement : pppragma_directive* statement def _parse_pragmacomp_or_statement(self) -> c_ast.Node: if self._peek_type() in {"PPPRAGMA", "_PRAGMA"}: pragmas = self._parse_pppragma_directive_list() stmt = self._parse_statement() return c_ast.Compound(block_items=pragmas + [stmt], coord=pragmas[0].coord) return self._parse_statement() # BNF: block_item : declaration | statement def _parse_block_item(self) -> c_ast.Node | list[c_ast.Node]: if self._peek_type() == "ATTRIBUTE_BEGIN": attributes = self._parse_attribute_specifier_sequence() if self._accept("SEMI"): return c_ast.AttributeDeclaration(attributes, attributes[0].coord) if self._starts_declaration(): return self._attribute_declarations( self._parse_declaration(), attributes ) return self._attribute_statement(self._parse_statement(), attributes) if self._peek_type() == "_STATIC_ASSERT": return self._parse_static_assert() if self._starts_declaration(): return self._parse_declaration() return self._parse_statement() # BNF: block_item_list : block_item+ def _parse_block_item_list(self) -> list[c_ast.Node]: items: list[c_ast.Node] = [] while self._peek_type() not in {"RBRACE", None}: item = self._parse_block_item() if isinstance(item, c_ast.Node): items.append(item) elif item != [None]: items.extend(item) return items # BNF: compound_statement : '{' block_item_list? '}' def _parse_compound_statement(self, *, new_scope: bool = True) -> c_ast.Node: lbrace_tok = self._expect("LBRACE") if new_scope: self._push_scope() block_items = None if not self._accept("RBRACE"): block_items = self._parse_block_item_list() self._expect("RBRACE") if new_scope: self._pop_scope() return c_ast.Compound( block_items=block_items, coord=self._tok_coord(lbrace_tok) ) # BNF: labeled_statement : ID ':' statement # | CASE constant_expression ':' statement # | DEFAULT ':' statement def _parse_labeled_statement(self) -> c_ast.Node: tok_type = self._peek_type() match tok_type: case "ID": name_tok = self._advance() self._expect("COLON") if self._starts_statement(): stmt = self._parse_pragmacomp_or_statement() else: stmt = c_ast.EmptyStatement(self._tok_coord(name_tok)) return c_ast.Label(name_tok.value, stmt, self._tok_coord(name_tok)) case "CASE": case_tok = self._advance() expr = self._parse_constant_expression() self._expect("COLON") if self._starts_statement(): stmt = self._parse_pragmacomp_or_statement() else: stmt = c_ast.EmptyStatement(self._tok_coord(case_tok)) return c_ast.Case(expr, [stmt], self._tok_coord(case_tok)) case "DEFAULT": def_tok = self._advance() self._expect("COLON") if self._starts_statement(): stmt = self._parse_pragmacomp_or_statement() else: stmt = c_ast.EmptyStatement(self._tok_coord(def_tok)) return c_ast.Default([stmt], self._tok_coord(def_tok)) case _: self._parse_error("Invalid labeled statement", self.clex.filename) # BNF: selection_statement : IF '(' expression ')' statement (ELSE statement)? # | SWITCH '(' expression ')' statement def _parse_selection_statement(self) -> c_ast.Node: tok = self._advance() match tok.type: case "IF": self._expect("LPAREN") cond = self._parse_expression() self._expect("RPAREN") then_stmt = self._parse_pragmacomp_or_statement() if self._accept("ELSE"): else_stmt = self._parse_pragmacomp_or_statement() return c_ast.If(cond, then_stmt, else_stmt, self._tok_coord(tok)) return c_ast.If(cond, then_stmt, None, self._tok_coord(tok)) case "SWITCH": self._expect("LPAREN") expr = self._parse_expression() self._expect("RPAREN") stmt = self._parse_pragmacomp_or_statement() return fix_switch_cases(c_ast.Switch(expr, stmt, self._tok_coord(tok))) case _: self._parse_error("Invalid selection statement", self._tok_coord(tok)) # BNF: iteration_statement : WHILE '(' expression ')' statement # | DO statement WHILE '(' expression ')' ';' # | FOR '(' (declaration | expression_opt) ';' # expression_opt ';' expression_opt ')' statement def _parse_iteration_statement(self) -> c_ast.Node: tok = self._advance() match tok.type: case "WHILE": self._expect("LPAREN") cond = self._parse_expression() self._expect("RPAREN") stmt = self._parse_pragmacomp_or_statement() return c_ast.While(cond, stmt, self._tok_coord(tok)) case "DO": stmt = self._parse_pragmacomp_or_statement() self._expect("WHILE") self._expect("LPAREN") cond = self._parse_expression() self._expect("RPAREN") self._expect("SEMI") return c_ast.DoWhile(cond, stmt, self._tok_coord(tok)) case "FOR": self._expect("LPAREN") if self._peek_type() == "_STATIC_ASSERT" or self._starts_declaration(): # Names declared here are scoped to the loop (C11 6.8.5p5) self._push_scope() decls = self._parse_declaration() init = c_ast.DeclList(decls, self._tok_coord(tok)) cond = self._parse_expression_opt() self._expect("SEMI") next_expr = self._parse_expression_opt() self._expect("RPAREN") stmt = self._parse_pragmacomp_or_statement() self._pop_scope() return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok)) init = self._parse_expression_opt() self._expect("SEMI") cond = self._parse_expression_opt() self._expect("SEMI") next_expr = self._parse_expression_opt() self._expect("RPAREN") stmt = self._parse_pragmacomp_or_statement() return c_ast.For(init, cond, next_expr, stmt, self._tok_coord(tok)) case _: self._parse_error("Invalid iteration statement", self._tok_coord(tok)) # BNF: jump_statement : GOTO ID ';' | BREAK ';' | CONTINUE ';' # | RETURN expression? ';' def _parse_jump_statement(self) -> c_ast.Node: tok = self._advance() match tok.type: case "GOTO": name_tok = self._expect("ID") self._expect("SEMI") return c_ast.Goto(name_tok.value, self._tok_coord(tok)) case "BREAK": self._expect("SEMI") return c_ast.Break(self._tok_coord(tok)) case "CONTINUE": self._expect("SEMI") return c_ast.Continue(self._tok_coord(tok)) case "RETURN": if self._accept("SEMI"): return c_ast.Return(None, self._tok_coord(tok)) expr = self._parse_expression() self._expect("SEMI") return c_ast.Return(expr, self._tok_coord(tok)) case _: self._parse_error("Invalid jump statement", self._tok_coord(tok)) # BNF: expression_statement : expression_opt ';' def _parse_expression_statement(self) -> c_ast.Node: expr = self._parse_expression_opt() semi_tok = self._expect("SEMI") if expr is None: return c_ast.EmptyStatement(self._tok_coord(semi_tok)) return expr # ------------------------------------------------------------------ # Expressions # ------------------------------------------------------------------ # BNF: expression_opt : expression | empty def _parse_expression_opt(self) -> c_ast.Node | None: if self._starts_expression(): return self._parse_expression() return None # BNF: expression : assignment_expression (',' assignment_expression)* def _parse_expression(self) -> c_ast.Node: expr = self._parse_assignment_expression() if not self._accept("COMMA"): return expr exprs = [expr, self._parse_assignment_expression()] while self._accept("COMMA"): exprs.append(self._parse_assignment_expression()) return c_ast.ExprList(exprs, expr.coord) # BNF: assignment_expression : conditional_expression # | unary_expression assignment_op assignment_expression def _parse_assignment_expression(self) -> c_ast.Node: expr = self._parse_conditional_expression() if self._is_assignment_op(): op = self._advance().value rhs = self._parse_assignment_expression() return c_ast.Assignment(op, expr, rhs, expr.coord) return expr # BNF: conditional_expression : binary_expression # | binary_expression '?' expression ':' conditional_expression def _parse_conditional_expression(self) -> c_ast.Node: expr = self._parse_binary_expression() if self._accept("CONDOP"): iftrue = self._parse_expression() self._expect("COLON") iffalse = self._parse_conditional_expression() return c_ast.TernaryOp(expr, iftrue, iffalse, expr.coord) return expr # BNF: binary_expression : cast_expression (binary_op cast_expression)* def _parse_binary_expression( self, min_prec: int = 0, lhs: c_ast.Node | None = None ) -> c_ast.Node: if lhs is None: lhs = self._parse_cast_expression() while True: tok = self._peek() if tok is None or tok.type not in _BINARY_PRECEDENCE: break prec = _BINARY_PRECEDENCE[tok.type] if prec < min_prec: break op = tok.value self._advance() rhs = self._parse_cast_expression() while True: next_tok = self._peek() if next_tok is None or next_tok.type not in _BINARY_PRECEDENCE: break next_prec = _BINARY_PRECEDENCE[next_tok.type] if next_prec > prec: rhs = self._parse_binary_expression(next_prec, rhs) else: break lhs = c_ast.BinaryOp(op, lhs, rhs, lhs.coord) return lhs # BNF: cast_expression : '(' type_name ')' cast_expression # | unary_expression def _parse_cast_expression(self) -> c_ast.Node: result = self._try_parse_paren_type_name() if result is not None: typ, mark, lparen_tok, _ = result if self._peek_type() == "LBRACE": # (type){...} is a compound literal, not a cast. Examples: # (int){1} -> compound literal, handled in postfix # (int) x -> cast, handled below self._reset(mark) else: expr = self._parse_cast_expression() return c_ast.Cast(typ, expr, self._tok_coord(lparen_tok)) return self._parse_unary_expression() # BNF: unary_expression : postfix_expression # | '++' unary_expression # | '--' unary_expression # | unary_op cast_expression # | 'sizeof' unary_expression # | 'sizeof' '(' type_name ')' # | '_Alignof' '(' type_name ')' def _parse_unary_expression(self) -> c_ast.Node: tok_type = self._peek_type() if tok_type in {"PLUSPLUS", "MINUSMINUS"}: tok = self._advance() expr = self._parse_unary_expression() return c_ast.UnaryOp(tok.value, expr, expr.coord) if tok_type in {"AND", "TIMES", "PLUS", "MINUS", "NOT", "LNOT"}: tok = self._advance() expr = self._parse_cast_expression() return c_ast.UnaryOp(tok.value, expr, expr.coord) if tok_type == "SIZEOF": tok = self._advance() result = self._try_parse_paren_type_name() if result is not None: typ, mark, _, _ = result if self._peek_type() != "LBRACE": return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok)) # sizeof (type){...} has an expression operand, including # any postfix operators following the compound literal. self._reset(mark) expr = self._parse_unary_expression() return c_ast.UnaryOp(tok.value, expr, self._tok_coord(tok)) if tok_type == "_ALIGNOF": tok = self._advance() self._expect("LPAREN") typ = self._parse_type_name() self._expect("RPAREN") return c_ast.UnaryOp(tok.value, typ, self._tok_coord(tok)) return self._parse_postfix_expression() # BNF: postfix_expression : primary_expression postfix_suffix* # | compound_literal postfix_suffix* # compound_literal : '(' storage_class_specifiers? type_name ')' # braced_initializer def _parse_postfix_expression(self) -> c_ast.Node: expr = None result = self._try_parse_paren_type_name() if result is not None: typ, mark, lparen_tok, storage = result # Disambiguate between casts and compound literals: # (int) x -> cast # (int) {1} -> compound literal if self._peek_type() == "LBRACE": init = self._parse_initializer() expr = c_ast.CompoundLiteral( typ, init, storage, self._tok_coord(lparen_tok) ) else: self._reset(mark) if expr is None: expr = self._parse_primary_expression() while True: tok_type = self._peek_type() if tok_type == "LBRACKET": self._advance() sub = self._parse_expression() self._expect("RBRACKET") expr = c_ast.ArrayRef(expr, sub, expr.coord) continue if tok_type == "LPAREN": self._advance() if self._peek_type() == "RPAREN": self._advance() args = None else: args = self._parse_argument_expression_list() self._expect("RPAREN") expr = c_ast.FuncCall(expr, args, expr.coord) continue if tok_type in {"PERIOD", "ARROW"}: op_tok = self._advance() name_tok = self._advance() if name_tok.type not in {"ID", "TYPEID"}: self._parse_error( "Invalid struct reference", self._tok_coord(name_tok) ) field = c_ast.ID(name_tok.value, self._tok_coord(name_tok)) expr = c_ast.StructRef(expr, op_tok.value, field, expr.coord) continue if tok_type in {"PLUSPLUS", "MINUSMINUS"}: tok = self._advance() expr = c_ast.UnaryOp("p" + tok.value, expr, expr.coord) continue break return expr # BNF: primary_expression : ID | constant | string_literal # | '(' expression ')' | generic_selection | offsetof # | '(' compound_statement ')' # | '__builtin_va_arg' '(' # assignment_expression ',' type_name ')' def _parse_primary_expression(self) -> c_ast.Node: tok_type = self._peek_type() if tok_type == "ID": return self._parse_identifier() if ( tok_type in _INT_CONST or tok_type in _FLOAT_CONST or tok_type in _CHAR_CONST or tok_type in _PREDEFINED_CONST ): return self._parse_constant() if tok_type in _STRING_LITERAL: return self._parse_unified_string_literal() if tok_type == "LPAREN": self._advance() if self._peek_type() == "LBRACE": # GNU statement expressions participate in all expression # operators, including postfix operators. expr = self._parse_compound_statement() else: expr = self._parse_expression() self._expect("RPAREN") return expr if tok_type == "_GENERIC": return self._parse_generic_selection() if tok_type == "__BUILTIN_VA_ARG": tok = self._advance() self._expect("LPAREN") expr = self._parse_assignment_expression() self._expect("COMMA") typ = self._parse_type_name() self._expect("RPAREN") coord = self._tok_coord(tok) return c_ast.FuncCall( c_ast.ID(tok.value, coord), c_ast.ExprList([expr, typ], coord), coord, ) if tok_type == "OFFSETOF": off_tok = self._advance() self._expect("LPAREN") typ = self._parse_type_name() self._expect("COMMA") designator = self._parse_offsetof_member_designator() self._expect("RPAREN") coord = self._tok_coord(off_tok) return c_ast.FuncCall( c_ast.ID(off_tok.value, coord), c_ast.ExprList([typ, designator], coord), coord, ) self._parse_error("Invalid expression", self.clex.filename) # BNF: generic_selection : _GENERIC '(' assignment_expression ',' # generic_association (',' generic_association)* ')' def _parse_generic_selection(self) -> c_ast.GenericSelection: tok = self._expect("_GENERIC") self._expect("LPAREN") expr = self._parse_assignment_expression() self._expect("COMMA") associations = [self._parse_generic_association()] while self._accept("COMMA"): associations.append(self._parse_generic_association()) self._expect("RPAREN") return c_ast.GenericSelection(expr, associations, self._tok_coord(tok)) # BNF: generic_association : type_name ':' assignment_expression # | DEFAULT ':' assignment_expression def _parse_generic_association(self) -> c_ast.GenericAssociation: tok = self._peek() if tok is None: self._parse_error("At end of input", self.clex.filename) typ = None if self._accept("DEFAULT") else self._parse_type_name() self._expect("COLON") expr = self._parse_assignment_expression() return c_ast.GenericAssociation(typ, expr, self._tok_coord(tok)) # BNF: offsetof_member_designator : identifier_or_typeid # ('.' identifier_or_typeid | '[' expression ']')* def _parse_offsetof_member_designator(self) -> c_ast.Node: node = self._parse_identifier_or_typeid() while True: if self._accept("PERIOD"): field = self._parse_identifier_or_typeid() node = c_ast.StructRef(node, ".", field, node.coord) continue if self._accept("LBRACKET"): expr = self._parse_expression() self._expect("RBRACKET") node = c_ast.ArrayRef(node, expr, node.coord) continue break return node # BNF: argument_expression_list : assignment_expression (',' assignment_expression)* def _parse_argument_expression_list(self) -> c_ast.Node: expr = self._parse_assignment_expression() exprs = [expr] while self._accept("COMMA"): exprs.append(self._parse_assignment_expression()) return c_ast.ExprList(exprs, expr.coord) # BNF: constant_expression : conditional_expression def _parse_constant_expression(self) -> c_ast.Node: return self._parse_conditional_expression() # ------------------------------------------------------------------ # Terminals # ------------------------------------------------------------------ # BNF: identifier : ID def _parse_identifier(self) -> c_ast.Node: tok = self._expect("ID") return c_ast.ID(tok.value, self._tok_coord(tok)) # BNF: identifier_or_typeid : ID | TYPEID def _parse_identifier_or_typeid(self) -> c_ast.ID: tok = self._advance() if tok.type not in {"ID", "TYPEID"}: self._parse_error("Expected identifier", self._tok_coord(tok)) return c_ast.ID(tok.value, self._tok_coord(tok)) # BNF: constant : INT_CONST | FLOAT_CONST | CHAR_CONST | predefined_constant def _parse_constant(self) -> c_ast.Node: tok = self._advance() if tok.type in _PREDEFINED_CONST: return c_ast.Constant( _PREDEFINED_CONST[tok.type], tok.value, self._tok_coord(tok) ) if tok.type in _INT_CONST: # Integer suffixes are at most three characters (e.g. ull, wbu). suffix = tok.value[-3:].lower() if suffix.endswith(("wb", "wbu")): if self._dialect != "c23": self._parse_error( "Bit-precise integer constants require C23", self._tok_coord(tok), ) # Classify by suffix, as with other integer constants; retain # the spelling without computing the value or its bit width. t = "unsigned _BitInt" if "u" in suffix else "_BitInt" return c_ast.Constant(t, tok.value, self._tok_coord(tok)) u_count = 0 l_count = 0 for ch in tok.value[-3:]: if ch in ("l", "L"): l_count += 1 elif ch in ("u", "U"): u_count += 1 if u_count > 1: raise ValueError("Constant cannot have more than one u/U suffix.") if l_count > 2: raise ValueError("Constant cannot have more than two l/L suffix.") prefix = "unsigned " * u_count + "long " * l_count return c_ast.Constant(prefix + "int", tok.value, self._tok_coord(tok)) if tok.type in _FLOAT_CONST: if tok.value[-2:] in {"df", "DF"}: t = "_Decimal32" elif tok.value[-2:] in {"dd", "DD"}: t = "_Decimal64" elif tok.value[-2:] in {"dl", "DL"}: t = "_Decimal128" elif tok.value[-1] in ("f", "F"): t = "float" elif tok.value[-1] in ("l", "L"): t = "long double" else: t = "double" if ( t in {"_Decimal32", "_Decimal64", "_Decimal128"} and self._dialect != "c23" ): self._parse_error( "Decimal floating constants require C23", self._tok_coord(tok) ) return c_ast.Constant(t, tok.value, self._tok_coord(tok)) if tok.type in _CHAR_CONST: return c_ast.Constant("char", tok.value, self._tok_coord(tok)) self._parse_error("Invalid constant", self._tok_coord(tok)) # BNF: unified_string_literal : (STRING_LITERAL | WSTRING_LITERAL # | U8STRING_LITERAL | U16STRING_LITERAL # | U32STRING_LITERAL)+ def _parse_unified_string_literal(self) -> c_ast.Constant: # Represent the whole run of adjacent literals with one Constant. # C interprets escapes before concatenating the character sequences, # whereas Constant.value holds source spelling. Simply removing the # quotes between "\1" "23" would produce "\123", changing three # characters into one (issue #392). tok = self._advance() if tok.type not in _STRING_LITERAL: self._parse_error("Invalid string literal", self._tok_coord(tok)) # Split off the optional encoding prefix and remove the closing quote. # Each part holds unquoted source text that can safely share one literal. prefix, contents = tok.value.split('"', 1) parts = [contents[:-1]] while self._peek_type() in _STRING_LITERAL: tok2 = self._advance() next_prefix, next_contents = tok2.value.split('"', 1) # The first nonempty prefix applies to the whole run, even if it # occurs after ordinary literals. Conflicting prefixes retain the # parser's existing permissive behavior: the first one wins. prefix = prefix or next_prefix next_contents = next_contents[:-1] # Extend the current part when safe; otherwise start a new one so # a quote boundary survives. Empty literals can merge, but do not # end a trailing escape: "\1" "" "23" still needs a boundary. if self._string_literal_needs_separator(parts[-1], next_contents): parts.append(next_contents) else: parts[-1] += next_contents # Re-quote each part, keeping only the necessary literal boundaries. # The prefix on the first literal applies to the adjacent sequence. # The generator can emit this value directly without decoding escapes. value = prefix + '"' + '" "'.join(parts) + '"' return c_ast.Constant("string", value, self._tok_coord(tok)) @staticmethod def _string_literal_needs_separator(left: str, right: str) -> bool: """Whether joining two literal bodies would change their C spelling.""" if not left or not right: return False # A generated trigraph would be replaced before C string processing; # for example, merging "?" "?=" would create the trigraph for '#'. boundary = left[-2:] + right[:2] if any("??" + ch in boundary for ch in "=/'()!<>-"): return True # Only an escape reaching the end of left can absorb characters from # right. The last backslash is the only possible start of that escape. escape_start = left.rfind("\\") if escape_start == -1: return False # An even run of backslashes represents escaped backslashes, not the # start of the numeric escape that the following digits might suggest. run_start = escape_start while run_start > 0 and left[run_start - 1] == "\\": run_start -= 1 if (escape_start - run_start + 1) % 2 == 0: return False escape = left[escape_start + 1 :] if escape.startswith("x"): # Hex escapes have no digit limit: "\x1" "a" must stay separated. hex_digits = "0123456789abcdefABCDEF" return right[0] in hex_digits and all(ch in hex_digits for ch in escape[1:]) # Octal escapes consume at most three digits: "\12" "3" needs a # boundary, but "\123" "4" can become "\1234". Universal character names # have fixed widths and cannot absorb characters from the next literal. return ( 1 <= len(escape) < 3 and all(ch in "01234567" for ch in escape) and right[0] in "01234567" ) # ------------------------------------------------------------------ # Initializers # ------------------------------------------------------------------ # BNF: initializer : assignment_expression # | '{' initializer_list ','? '}' # | '{' '}' def _parse_initializer(self) -> c_ast.Node: lbrace_tok = self._accept("LBRACE") if lbrace_tok: if self._accept("RBRACE"): return c_ast.InitList([], self._tok_coord(lbrace_tok)) init_list = self._parse_initializer_list() self._accept("COMMA") self._expect("RBRACE") return init_list return self._parse_assignment_expression() # BNF: initializer_list : initializer_item (',' initializer_item)* ','? def _parse_initializer_list(self) -> c_ast.Node: items = [self._parse_initializer_item()] while self._accept("COMMA"): if self._peek_type() == "RBRACE": break items.append(self._parse_initializer_item()) return c_ast.InitList(items, items[0].coord) # BNF: initializer_item : designation? initializer def _parse_initializer_item(self) -> c_ast.Node: designation = None if self._peek_type() in {"LBRACKET", "PERIOD"}: designation = self._parse_designation() init = self._parse_initializer() if designation is not None: return c_ast.NamedInitializer(designation, init) return init # BNF: designation : designator_list '=' def _parse_designation(self) -> list[c_ast.Node]: designators = self._parse_designator_list() self._expect("EQUALS") return designators # BNF: designator_list : designator+ def _parse_designator_list(self) -> list[c_ast.Node]: designators = [] while self._peek_type() in {"LBRACKET", "PERIOD"}: designators.append(self._parse_designator()) return designators # BNF: designator : '[' constant_expression ']' # | '.' identifier_or_typeid def _parse_designator(self) -> c_ast.Node: if tok := self._accept("LBRACKET"): expr = self._parse_constant_expression() self._expect("RBRACKET") return c_ast.ArrayDesignator(expr, self._tok_coord(tok)) if self._accept("PERIOD"): return self._parse_identifier_or_typeid() self._parse_error("Invalid designator", self.clex.filename) # ------------------------------------------------------------------ # Preprocessor-like directives # ------------------------------------------------------------------ # BNF: pp_directive : '#' ... (unsupported) def _parse_pp_directive(self) -> NoReturn: tok = self._expect("PPHASH") self._parse_error("Directives not supported yet", self._tok_coord(tok)) # BNF: pppragma_directive : PPPRAGMA PPPRAGMASTR? # | _PRAGMA '(' string_literal ')' def _parse_pppragma_directive(self) -> c_ast.Node: if self._peek_type() == "PPPRAGMA": tok = self._advance() if self._peek_type() == "PPPRAGMASTR": str_tok = self._advance() return c_ast.Pragma(str_tok.value, self._tok_coord(str_tok)) return c_ast.Pragma("", self._tok_coord(tok)) if self._peek_type() == "_PRAGMA": tok = self._advance() lparen = self._expect("LPAREN") literal = self._parse_unified_string_literal() self._expect("RPAREN") return c_ast.Pragma(literal, self._tok_coord(lparen)) self._parse_error("Invalid pragma", self.clex.filename) # BNF: pppragma_directive_list : pppragma_directive+ def _parse_pppragma_directive_list(self) -> list[c_ast.Node]: pragmas = [] while self._peek_type() in {"PPPRAGMA", "_PRAGMA"}: pragmas.append(self._parse_pppragma_directive()) return pragmas # BNF: static_assert : _STATIC_ASSERT '(' constant_expression # (',' unified_string_literal)? ')' ';' # C11 requires a message; omission is supported as an extension. def _parse_static_assert(self) -> c_ast.StaticAssert: tok = self._expect("_STATIC_ASSERT") self._expect("LPAREN") cond = self._parse_constant_expression() msg = None if self._accept("COMMA"): msg = self._parse_unified_string_literal() self._expect("RPAREN") self._expect("SEMI") return c_ast.StaticAssert(cond, msg, self._tok_coord(tok)) _ASSIGNMENT_OPS = { "EQUALS", "XOREQUAL", "TIMESEQUAL", "DIVEQUAL", "MODEQUAL", "PLUSEQUAL", "MINUSEQUAL", "LSHIFTEQUAL", "RSHIFTEQUAL", "ANDEQUAL", "OREQUAL", } # Precedence of operators (lower number = weather binding) # If this changes, c_generator.CGenerator.precedence_map needs to change as # well _BINARY_PRECEDENCE = { "LOR": 0, "LAND": 1, "OR": 2, "XOR": 3, "AND": 4, "EQ": 5, "NE": 5, "GT": 6, "GE": 6, "LT": 6, "LE": 6, "RSHIFT": 7, "LSHIFT": 7, "PLUS": 8, "MINUS": 8, "TIMES": 9, "DIVIDE": 9, "MOD": 9, } _STORAGE_CLASS = { "AUTO", "CONSTEXPR", "REGISTER", "STATIC", "EXTERN", "TYPEDEF", "_THREAD_LOCAL", } _FUNCTION_SPEC = {"INLINE", "_NORETURN"} _TYPE_QUALIFIER = {"CONST", "RESTRICT", "VOLATILE", "_ATOMIC"} _TYPEOF_SPEC = {"TYPEOF", "TYPEOF_UNQUAL"} _TYPE_SPEC_SIMPLE = { "VOID", "_BOOL", "CHAR", "SHORT", "INT", "LONG", "FLOAT", "DOUBLE", "_DECIMAL32", "_DECIMAL64", "_DECIMAL128", "_COMPLEX", "SIGNED", "UNSIGNED", "__INT128", } # Struct members without declarators carry a type specifier directly instead. _DECLARATOR_NODES = (c_ast.TypeDecl, c_ast.PtrDecl, c_ast.ArrayDecl, c_ast.FuncDecl) _DECL_START = ( _STORAGE_CLASS | _FUNCTION_SPEC | _TYPE_QUALIFIER | _TYPE_SPEC_SIMPLE | _TYPEOF_SPEC | { "TYPEID", "STRUCT", "UNION", "ENUM", "_ALIGNAS", "_ATOMIC", "_BITINT", "ATTRIBUTE_BEGIN", } ) _EXPR_START = { "ID", "LPAREN", "PLUSPLUS", "MINUSMINUS", "PLUS", "MINUS", "TIMES", "AND", "NOT", "LNOT", "SIZEOF", "_ALIGNOF", "_GENERIC", "OFFSETOF", "__BUILTIN_VA_ARG", } _INT_CONST = { "INT_CONST_DEC", "INT_CONST_OCT", "INT_CONST_HEX", "INT_CONST_BIN", "INT_CONST_CHAR", } _FLOAT_CONST = {"FLOAT_CONST", "HEX_FLOAT_CONST"} _PREDEFINED_CONST = {"BOOL_CONST": "bool", "NULLPTR": "nullptr_t"} _CHAR_CONST = { "CHAR_CONST", "WCHAR_CONST", "U8CHAR_CONST", "U16CHAR_CONST", "U32CHAR_CONST", } _STRING_LITERAL = { "STRING_LITERAL", "WSTRING_LITERAL", "U8STRING_LITERAL", "U16STRING_LITERAL", "U32STRING_LITERAL", } _STARTS_EXPRESSION = ( _EXPR_START | _INT_CONST | _FLOAT_CONST | _CHAR_CONST | _STRING_LITERAL | _PREDEFINED_CONST.keys() ) _STARTS_STATEMENT = { "LBRACE", "IF", "SWITCH", "WHILE", "DO", "FOR", "GOTO", "BREAK", "CONTINUE", "RETURN", "CASE", "DEFAULT", "PPPRAGMA", "_PRAGMA", "SEMI", } class _TokenStream: """Provides buffered access to tokens supplied by a reader.""" def __init__(self, read_token: Callable[[], Token | None]) -> None: self._read_token = read_token self._buffer: list[Token | None] = [] self._index = 0 def peek(self, k: int = 1) -> Token | None: """Peek at the k-th next token in the stream, without consuming it. Examples: k=1 returns the immediate next token. k=2 returns the token after that. """ if k <= 0: return None pos = self._index + k - 1 if pos >= len(self._buffer): self._fill(k) return self._buffer[pos] def next(self) -> Token | None: """Consume a single token and return it.""" if self._index >= len(self._buffer): self._fill(1) tok = self._buffer[self._index] self._index += 1 return tok # The 'mark' and 'reset' methods are useful for speculative parsing with # backtracking; when the parser needs to examine a sequence of tokens # and potentially decide to try a different path on the same sequence, it # can call 'mark' to obtain the current token position, and if the first # path fails restore the position with `reset(pos)`. def mark(self) -> int: return self._index def reset(self, mark: int) -> None: self._index = mark def _fill(self, n: int) -> None: while len(self._buffer) < self._index + n: tok = self._read_token() self._buffer.append(tok) if tok is None: break # Declaration specifiers are represented by a dictionary with entries: # - qual: a list of type qualifiers # - storage: a list of storage class specifiers # - type: a list of type specifiers # - function: a list of function specifiers # - alignment: a list of alignment specifiers # - type_attributes: attribute groups following the specifier sequence class _DeclSpec(TypedDict): qual: list[str] storage: list[str] type: list[c_ast.Node] function: list[str] alignment: list[c_ast.Alignas] type_attributes: list[c_ast.AttributeSpecifier] _DeclSpecKind = Literal["qual", "storage", "type", "function", "alignment"] class _DeclInfo(TypedDict): # Declarator payloads used by declaration/initializer parsing: # - decl: the declarator node (may be None for abstract/implicit cases) # - init: initializer expression; the key may be omitted when absent # - bitsize: bit-field width expression; the key may be omitted when absent decl: c_ast.Node | None init: NotRequired[c_ast.Node | None] bitsize: NotRequired[c_ast.Node | None] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8516235 pycparser-3.12/pycparser.egg-info/0000775000175000017500000000000015266410573016502 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1792676218.842429 pycparser-3.12/pycparser.egg-info/PKG-INFO0000644000175000017500000002275515266410573017610 0ustar00elibenelibenMetadata-Version: 2.4 Name: pycparser Version: 3.12 Summary: C parser in Python Author-email: Eli Bendersky Maintainer-email: Eli Bendersky License-Expression: BSD-3-Clause Project-URL: Homepage, https://github.com/eliben/pycparser Classifier: Development Status :: 5 - Production/Stable Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 Classifier: Programming Language :: Python :: 3.15 Requires-Python: >=3.11 Description-Content-Type: text/x-rst License-File: LICENSE Dynamic: license-file ========= pycparser ========= .. image:: https://github.com/eliben/pycparser/workflows/pycparser-tests/badge.svg :align: center :target: https://github.com/eliben/pycparser/actions ---- .. contents:: :backlinks: none .. sectnum:: Introduction ============ What is pycparser? ------------------ **pycparser** is a parser for the C language, written in pure Python. It is a module designed to be easily integrated into applications that need to parse C source code. What is it good for? -------------------- Anything that needs C code to be parsed. The following are some uses for **pycparser**, taken from real user reports: * C code obfuscator * Front-end for various specialized C compilers * Static code checker * Automatic unit-test discovery * Adding specialized extensions to the C language One of the most popular uses of **pycparser** is in the `cffi `_ library, which uses it to parse the declarations of C functions and types in order to auto-generate FFIs. **pycparser** is unique in the sense that it's written in pure Python - a very high level language that's easy to experiment with and tweak. To people familiar with Lex and Yacc, **pycparser**'s code will be simple to understand. It also has no external dependencies (except for a Python interpreter), making it very simple to install and deploy. Which version of C does pycparser support? ------------------------------------------ **pycparser** aims to support the full C11 language, including earlier revisions like C99. C23 support is conditional on a ``dialect="c23"`` setting, since this revision introduces new keywords like ``bool`` that would conflict with existing C code if not handled properly. **pycparser** supports very few GCC extensions, but it's fairly easy to set things up so that it parses code with a lot of GCC-isms successfully. See the `FAQ `_ for more details. What grammar does pycparser follow? ----------------------------------- **pycparser** very closely follows the C grammar provided in Annex A of the C99 standard (ISO/IEC 9899). How is pycparser licensed? -------------------------- `BSD license `_. Contact details --------------- For reporting problems with **pycparser** or submitting feature requests, please open an `issue `_, or submit a pull request. Installing ========== Prerequisites ------------- **pycparser** is being tested with modern versions of Python on Linux, macOS and Windows. See `the CI dashboard `__ for details. **pycparser** has no external dependencies. Installation process -------------------- The recommended way to install **pycparser** is with ``pip``:: > pip install pycparser Using ===== Interaction with the C preprocessor ----------------------------------- In order to be compilable, C code must be preprocessed by the C preprocessor - ``cpp``. A compatible ``cpp`` handles preprocessing directives like ``#include`` and ``#define``, removes comments, and performs other minor tasks that prepare the C code for compilation. For all but the most trivial snippets of C code **pycparser**, like a C compiler, must receive preprocessed C code in order to function correctly. If you import the top-level ``parse_file`` function from the **pycparser** package, it will interact with ``cpp`` for you, as long as it's in your PATH, or you provide a path to it. Note also that you can use ``gcc -E`` or ``clang -E`` instead of ``cpp``. See the ``using_gcc_E_libc.py`` example for more details. Windows users can download and install a binary build of Clang for Windows `from this website `_. What about the standard C library headers? ------------------------------------------ C code almost always ``#include``\s various header files from the standard C library, like ``stdio.h``. While (with some effort) **pycparser** can be made to parse the standard headers from any C compiler, it's much simpler to use the provided "fake" standard includes for C11 in ``utils/fake_libc_include``. These are standard C header files that contain only the bare necessities to allow valid parsing of the files that use them. As a bonus, since they're minimal, it can significantly improve the performance of parsing large C files. The key point to understand here is that **pycparser** doesn't really care about the semantics of types. It only needs to know whether some token encountered in the source is a previously defined type. This is essential in order to be able to parse C correctly. See `this blog post `_ for more details. Note that the fake headers are not included in the ``pip`` package nor installed via the package build (`#224 `_). Basic usage ----------- Take a look at the |examples|_ directory of the distribution for a few examples of using **pycparser**. These should be enough to get you started. Please note that most realistic C code samples would require running the C preprocessor before passing the code to **pycparser**; see the previous sections for more details. For example, to parse C23 source with a preprocessor that supports ``-std=c23``:: from pycparser import CParser, parse_file ast = parse_file( "example.c", use_cpp=True, cpp_args=["-std=c23"], parser=CParser(dialect="c23"), ) The parser's dialect does not configure the external preprocessor; select its language mode separately through ``cpp_args``. .. |examples| replace:: ``examples`` .. _examples: examples Advanced usage -------------- The public interface of **pycparser** is well documented with comments in ``pycparser/c_parser.py``. For a detailed overview of the various AST nodes created by the parser, see ``pycparser/_c_ast.cfg``. The root node is a ``FileAST``, whose ``ext`` attribute is a list of top-level declarations and function definitions. Explore nodes through their named fields, and use ``show()`` on a subtree to inspect just that part of the AST:: from pycparser import CParser ast = CParser().parse("int x; int f(void) { return x; }") print(len(ast.ext)) # 2 func = ast.ext[1] func.body.show() For generic exploration, call ``children()`` to get a tuple of ``(field_name, child_node)`` pairs for the immediate children. The tuple supports length and indexing directly:: children = func.children() print(len(children)) # 2: decl and body name, child = children[0] print(name) # decl child.show() Iterating over a node directly (``for child in node``) yields just the child nodes, without their names. For a guided walkthrough, see `examples/explore_ast.py `_; for recursive traversal, see the ``NodeVisitor`` example in `examples/func_defs.py `_. There's also a `FAQ available here `_. In any case, you can always drop me an `email `_ for help. Modifying ========= There are a few points to keep in mind when modifying **pycparser**: * The code for **pycparser**'s AST nodes is automatically generated from a configuration file - ``_c_ast.cfg``, by ``_ast_gen.py``. If you modify the AST configuration or the generator, run ``make regen-ast`` from the repository root to re-generate ``pycparser/c_ast.py`` and run ``make format``. * Read the docstring in the constructor of the ``CParser`` class for details on configuration and compatibility arguments. Package contents ================ Once you unzip the ``pycparser`` package, you'll see the following files and directories: README.rst: This README file. LICENSE: The pycparser license setup.py: Legacy installation script (build metadata lives in ``pyproject.toml``). pyproject.toml: Package metadata and build configuration. examples/: A directory with some examples of using **pycparser** pycparser/: The **pycparser** module source code. tests/: Unit tests. utils/fake_libc_include: Minimal standard C library include files that should allow to parse any C code. Note that these headers now include C11 code, so they may not work when the preprocessor is configured to an earlier C standard (like ``-std=c99``). utils/internal/: Internal utilities for my own use. You probably don't need them. Contributors ============ Some people have contributed to **pycparser** by opening issues on bugs they've found and/or submitting patches. The list of contributors is in the CONTRIBUTORS file in the source distribution. After **pycparser** moved to Github I stopped updating this list because Github does a much better job at tracking contributions. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8481405 pycparser-3.12/pycparser.egg-info/SOURCES.txt0000664000175000017500000001332515266410573020372 0ustar00elibenelibenLICENSE MANIFEST.in OLDER_CHANGES README.rst pyproject.toml setup.cfg setup.py examples/c-to-c.py examples/c_json.py examples/cdecl.py examples/construct_ast_from_scratch.py examples/dump_ast.py examples/explore_ast.py examples/func_calls.py examples/func_defs.py examples/func_defs_add_param.py examples/rewrite_ast.py examples/serialize_ast.py examples/typed_usage.py examples/using_cpp_libc.py examples/using_gcc_E_libc.py examples/c_files/basic.c examples/c_files/funky.c examples/c_files/hash.c examples/c_files/memmgr.c examples/c_files/memmgr.h examples/c_files/pragmas.c examples/c_files/year.c pycparser/__init__.py pycparser/_ast_gen.py pycparser/_c_ast.cfg pycparser/ast_transforms.py pycparser/c_ast.py pycparser/c_generator.py pycparser/c_lexer.py pycparser/c_parser.py pycparser.egg-info/PKG-INFO pycparser.egg-info/SOURCES.txt pycparser.egg-info/dependency_links.txt pycparser.egg-info/top_level.txt tests/__init__.py tests/test_c23_attributes.py tests/test_c_ast.py tests/test_c_generator.py tests/test_c_lexer.py tests/test_c_parser.py tests/test_examples.py tests/test_general.py tests/test_util.py tests/c_files/c11.c tests/c_files/cppd_with_stdio_h.c tests/c_files/empty.h tests/c_files/example_c_file.c tests/c_files/memmgr.c tests/c_files/memmgr.h tests/c_files/memmgr_with_h.c tests/c_files/simplemain.c tests/c_files/year.c tests/c_files/hdir/9/inc.h utils/fake_libc_include/_ansi.h utils/fake_libc_include/_fake_defines.h utils/fake_libc_include/_fake_typedefs.h utils/fake_libc_include/_syslist.h utils/fake_libc_include/aio.h utils/fake_libc_include/alloca.h utils/fake_libc_include/ar.h utils/fake_libc_include/argz.h utils/fake_libc_include/assert.h utils/fake_libc_include/complex.h utils/fake_libc_include/cpio.h utils/fake_libc_include/ctype.h utils/fake_libc_include/dirent.h utils/fake_libc_include/dlfcn.h utils/fake_libc_include/emmintrin.h utils/fake_libc_include/endian.h utils/fake_libc_include/envz.h utils/fake_libc_include/errno.h utils/fake_libc_include/fastmath.h utils/fake_libc_include/fcntl.h utils/fake_libc_include/features.h utils/fake_libc_include/fenv.h utils/fake_libc_include/float.h utils/fake_libc_include/fmtmsg.h utils/fake_libc_include/fnmatch.h utils/fake_libc_include/ftw.h utils/fake_libc_include/getopt.h utils/fake_libc_include/glob.h utils/fake_libc_include/grp.h utils/fake_libc_include/iconv.h utils/fake_libc_include/ieeefp.h utils/fake_libc_include/immintrin.h utils/fake_libc_include/inttypes.h utils/fake_libc_include/iso646.h utils/fake_libc_include/langinfo.h utils/fake_libc_include/libgen.h utils/fake_libc_include/libintl.h utils/fake_libc_include/limits.h utils/fake_libc_include/locale.h utils/fake_libc_include/malloc.h utils/fake_libc_include/math.h utils/fake_libc_include/monetary.h utils/fake_libc_include/mqueue.h utils/fake_libc_include/ndbm.h utils/fake_libc_include/netdb.h utils/fake_libc_include/newlib.h utils/fake_libc_include/nl_types.h utils/fake_libc_include/paths.h utils/fake_libc_include/poll.h utils/fake_libc_include/process.h utils/fake_libc_include/pthread.h utils/fake_libc_include/pwd.h utils/fake_libc_include/reent.h utils/fake_libc_include/regdef.h utils/fake_libc_include/regex.h utils/fake_libc_include/sched.h utils/fake_libc_include/search.h utils/fake_libc_include/semaphore.h utils/fake_libc_include/setjmp.h utils/fake_libc_include/signal.h utils/fake_libc_include/smmintrin.h utils/fake_libc_include/spawn.h utils/fake_libc_include/stdalign.h utils/fake_libc_include/stdarg.h utils/fake_libc_include/stdatomic.h utils/fake_libc_include/stdbool.h utils/fake_libc_include/stddef.h utils/fake_libc_include/stdint.h utils/fake_libc_include/stdio.h utils/fake_libc_include/stdlib.h utils/fake_libc_include/stdnoreturn.h utils/fake_libc_include/string.h utils/fake_libc_include/strings.h utils/fake_libc_include/stropts.h utils/fake_libc_include/syslog.h utils/fake_libc_include/tar.h utils/fake_libc_include/termios.h utils/fake_libc_include/tgmath.h utils/fake_libc_include/threads.h utils/fake_libc_include/time.h utils/fake_libc_include/trace.h utils/fake_libc_include/uchar.h utils/fake_libc_include/ulimit.h utils/fake_libc_include/unctrl.h utils/fake_libc_include/unistd.h utils/fake_libc_include/utime.h utils/fake_libc_include/utmp.h utils/fake_libc_include/utmpx.h utils/fake_libc_include/wchar.h utils/fake_libc_include/wctype.h utils/fake_libc_include/wordexp.h utils/fake_libc_include/zlib.h utils/fake_libc_include/X11/Intrinsic.h utils/fake_libc_include/X11/Xlib.h utils/fake_libc_include/X11/_X11_fake_defines.h utils/fake_libc_include/X11/_X11_fake_typedefs.h utils/fake_libc_include/arpa/inet.h utils/fake_libc_include/asm-generic/int-ll64.h utils/fake_libc_include/linux/socket.h utils/fake_libc_include/linux/version.h utils/fake_libc_include/mir_toolkit/client_types.h utils/fake_libc_include/net/if.h utils/fake_libc_include/netinet/in.h utils/fake_libc_include/netinet/tcp.h utils/fake_libc_include/openssl/err.h utils/fake_libc_include/openssl/evp.h utils/fake_libc_include/openssl/hmac.h utils/fake_libc_include/openssl/ssl.h utils/fake_libc_include/openssl/x509v3.h utils/fake_libc_include/sys/ioctl.h utils/fake_libc_include/sys/ipc.h utils/fake_libc_include/sys/mman.h utils/fake_libc_include/sys/msg.h utils/fake_libc_include/sys/poll.h utils/fake_libc_include/sys/resource.h utils/fake_libc_include/sys/select.h utils/fake_libc_include/sys/sem.h utils/fake_libc_include/sys/shm.h utils/fake_libc_include/sys/socket.h utils/fake_libc_include/sys/stat.h utils/fake_libc_include/sys/statvfs.h utils/fake_libc_include/sys/sysctl.h utils/fake_libc_include/sys/time.h utils/fake_libc_include/sys/times.h utils/fake_libc_include/sys/types.h utils/fake_libc_include/sys/uio.h utils/fake_libc_include/sys/un.h utils/fake_libc_include/sys/utsname.h utils/fake_libc_include/sys/wait.h utils/fake_libc_include/xcb/xcb.h././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8425684 pycparser-3.12/pycparser.egg-info/dependency_links.txt0000664000175000017500000000000115266410573022550 0ustar00elibeneliben ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8426611 pycparser-3.12/pycparser.egg-info/top_level.txt0000664000175000017500000000001215266410573021225 0ustar00elibenelibenpycparser ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1792675956.430338 pycparser-3.12/pyproject.toml0000664000175000017500000000176615266410164015722 0ustar00elibeneliben[build-system] requires = ["setuptools>=77.0.3"] build-backend = "setuptools.build_meta" [project] name = "pycparser" version = "3.12" description = "C parser in Python" readme = "README.rst" license = "BSD-3-Clause" license-files = ["LICENSE"] requires-python = ">=3.11" authors = [{name = "Eli Bendersky", email = "eliben@gmail.com"}] maintainers = [{name = "Eli Bendersky", email = "eliben@gmail.com"}] classifiers = [ "Development Status :: 5 - Production/Stable", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", ] [project.urls] Homepage = "https://github.com/eliben/pycparser" [tool.setuptools] packages = ["pycparser"] [tool.setuptools.package-data] pycparser = ["*.cfg"] [tool.ruff.lint] ignore = ["F403", "F405"] [tool.ty.src] exclude = ["setup.py", "utils/internal/memprofiling.py"] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8559353 pycparser-3.12/setup.cfg0000664000175000017500000000011115266410573014612 0ustar00elibeneliben[metadata] license_file = LICENSE [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1769004602.2605417 pycparser-3.12/setup.py0000664000175000017500000000004615134157072014506 0ustar00elibenelibenfrom setuptools import setup setup() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8519902 pycparser-3.12/tests/0000775000175000017500000000000015266410573014142 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7896626 pycparser-3.12/tests/__init__.py0000664000175000017500000000000014716121045016231 0ustar00elibeneliben././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1792676218.852246 pycparser-3.12/tests/c_files/0000775000175000017500000000000015266410573015546 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1791467011.1988924 pycparser-3.12/tests/c_files/c11.c0000664000175000017500000000372315261717003016274 0ustar00elibeneliben#include #include #include #include #include #include #include #include #include #include #define type_name(x) _Generic((x), int: "int", float: "float", default: "other") /* C11 thread locals */ _Thread_local int flag; thread_local int flag2; /* C11 thread types and macros */ thrd_t worker; mtx_t lock; cnd_t ready; tss_t key; thrd_start_t start; tss_dtor_t destroy; once_flag once = ONCE_FLAG_INIT; int destructor_iterations = TSS_DTOR_ITERATIONS; _Atomic int flag3; _Atomic(int) flag4; _Atomic(_Atomic(int) *) flag5; atomic_bool flag6; _Alignas(32) int q32; _Alignas(long long) int qll; alignas(64) int qqq; max_align_t max_aligned; _Alignas(max_align_t) char aligned_storage[64]; static_assert(sizeof(flag) == sizeof(flag2), "Really unexpected size difference"); struct checked_struct { static_assert(sizeof(int) >= 2, "int size"); int value; }; union checked_union { int value; _Static_assert(sizeof(int) >= 2, "int " u8"size"); }; noreturn void func2(void) { abort(); } _Noreturn void func(void) { func2(); } int main() { _Static_assert(sizeof(flag) == sizeof(flag2), "Unexpected size difference"); _Static_assert(sizeof(flag) == sizeof(flag2)); static_assert(sizeof(flag) == sizeof(flag2), "Unexpected size difference"); static_assert(sizeof(flag) == sizeof(flag3), "Unexpected size difference"); static_assert(sizeof(flag) == sizeof(flag4), "Unexpected size difference"); static_assert(_Alignof(int) == sizeof(int), "Unexpected int alignment"); static_assert(alignof(int) == sizeof(int), "Unexpected int alignment"); wchar_t *w = L"12345"; char16_t *c16 = u"12345"; char32_t *c32 = U"12345"; char *u8 = u8"12345"; wchar_t wc = L'1'; char16_t c16c = u'\u00e9'; char32_t c32c = U'\U0001F600'; char u8c = u8'1'; const char *name = type_name(flag); printf("Flag: %d\n", flag); printf("Flag2: %d\n", flag2); func(); } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7906625 pycparser-3.12/tests/c_files/cppd_with_stdio_h.c0000664000175000017500000010602314716121045021376 0ustar00elibeneliben#line 1 "example_c_file.c" #line 1 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 19 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 25 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 1 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 11 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 1 "D:\eli\cpp_stuff\libc_include/newlib.h" #line 3 "D:\eli\cpp_stuff\libc_include/newlib.h" #line 16 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 1 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 1 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" #line 52 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" #line 58 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" #line 83 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" #line 86 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" #line 89 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" #line 95 "D:\eli\cpp_stuff\libc_include/machine/ieeefp.h" #line 5 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 11 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 143 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 157 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 195 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 207 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 17 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 21 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 30 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 1 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 19 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 26 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 30 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 35 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 39 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 42 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 53 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 56 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 67 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 76 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 98 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 108 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 126 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 131 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 170 "D:\eli\cpp_stuff\libc_include/stddef.h" typedef long unsigned int size_t; #line 243 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 246 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 290 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 302 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 310 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 361 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 365 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 418 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 422 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 427 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 35 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 1 "D:\eli\cpp_stuff\libc_include/stdarg.h" #line 19 "D:\eli\cpp_stuff\libc_include/stdarg.h" #line 26 "D:\eli\cpp_stuff\libc_include/stdarg.h" #line 30 "D:\eli\cpp_stuff\libc_include/stdarg.h" typedef char* __builtin_va_list; typedef __builtin_va_list __gnuc_va_list; #line 50 "D:\eli\cpp_stuff\libc_include/stdarg.h" #line 66 "D:\eli\cpp_stuff\libc_include/stdarg.h" #line 80 "D:\eli\cpp_stuff\libc_include/stdarg.h" #line 98 "D:\eli\cpp_stuff\libc_include/stdarg.h" #line 38 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 44 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 1 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 6 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 1 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 11 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 21 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 14 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 1 "D:\eli\cpp_stuff\libc_include/sys/_types.h" #line 8 "D:\eli\cpp_stuff\libc_include/sys/_types.h" #line 1 "D:\eli\cpp_stuff\libc_include/machine/_types.h" #line 4 "D:\eli\cpp_stuff\libc_include/machine/_types.h" #line 1 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" #line 4 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" #line 15 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" #line 17 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" #line 1 "D:\eli\cpp_stuff\libc_include/limits.h" #line 1 "D:\eli\cpp_stuff\libc_include/newlib.h" #line 3 "D:\eli\cpp_stuff\libc_include/newlib.h" #line 5 "D:\eli\cpp_stuff\libc_include/limits.h" #line 19 "D:\eli\cpp_stuff\libc_include/limits.h" #line 1 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 11 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 143 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 157 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 195 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 207 "D:\eli\cpp_stuff\libc_include/sys/config.h" #line 25 "D:\eli\cpp_stuff\libc_include/limits.h" #line 79 "D:\eli\cpp_stuff\libc_include/limits.h" #line 23 "D:\eli\cpp_stuff\libc_include/machine/_default_types.h" typedef signed char __int8_t ; typedef unsigned char __uint8_t ; typedef signed short __int16_t; typedef unsigned short __uint16_t; typedef __int16_t __int_least16_t; typedef __uint16_t __uint_least16_t; typedef signed int __int32_t; typedef unsigned int __uint32_t; typedef __int32_t __int_least32_t; typedef __uint32_t __uint_least32_t; #line 8 "D:\eli\cpp_stuff\libc_include/machine/_types.h" #line 13 "D:\eli\cpp_stuff\libc_include/sys/_types.h" #line 1 "D:\eli\cpp_stuff\libc_include/sys/lock.h" typedef int _LOCK_T; typedef int _LOCK_RECURSIVE_T; #line 14 "D:\eli\cpp_stuff\libc_include/sys/_types.h" typedef long _off_t; typedef short __dev_t; typedef unsigned short __uid_t; typedef unsigned short __gid_t; typedef long long _off64_t; #line 43 "D:\eli\cpp_stuff\libc_include/sys/_types.h" typedef long _fpos_t; typedef int _ssize_t; #line 1 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 19 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 26 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 30 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 35 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 39 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 42 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 53 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 56 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 67 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 76 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 98 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 108 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 126 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 131 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 170 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 243 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 246 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 290 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 302 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 310 "D:\eli\cpp_stuff\libc_include/stddef.h" typedef unsigned int wint_t; #line 361 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 365 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 418 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 422 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 427 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 64 "D:\eli\cpp_stuff\libc_include/sys/_types.h" typedef struct { int __count; union { wint_t __wch; unsigned char __wchb[4]; } __value; } _mbstate_t; typedef _LOCK_RECURSIVE_T _flock_t; typedef void *_iconv_t; #line 15 "D:\eli\cpp_stuff\libc_include/sys/reent.h" typedef unsigned long __ULong; struct _reent; #line 43 "D:\eli\cpp_stuff\libc_include/sys/reent.h" struct _Bigint { struct _Bigint *_next; int _k, _maxwds, _sign, _wds; __ULong _x[1]; }; struct __tm { int __tm_sec; int __tm_min; int __tm_hour; int __tm_mday; int __tm_mon; int __tm_year; int __tm_wday; int __tm_yday; int __tm_isdst; }; #line 68 "D:\eli\cpp_stuff\libc_include/sys/reent.h" struct _on_exit_args { void * _fnargs[32]; void * _dso_handle[32]; __ULong _fntypes; #line 77 "D:\eli\cpp_stuff\libc_include/sys/reent.h" __ULong _is_cxa; }; struct _atexit { struct _atexit *_next; int _ind; void (*_fns[32])(void); struct _on_exit_args _on_exit_args; }; #line 104 "D:\eli\cpp_stuff\libc_include/sys/reent.h" struct __sbuf { unsigned char *_base; int _size; }; #line 134 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 141 "D:\eli\cpp_stuff\libc_include/sys/reent.h" struct __sFILE { unsigned char *_p; int _r; int _w; short _flags; short _file; struct __sbuf _bf; int _lbfsize; char * _cookie; int(*_read)(); #line 176 "D:\eli\cpp_stuff\libc_include/sys/reent.h" int(*_write)(); #line 178 "D:\eli\cpp_stuff\libc_include/sys/reent.h" _fpos_t(*_seek)(); int(*_close)(); struct __sbuf _ub; unsigned char *_up; int _ur; unsigned char _ubuf[3]; unsigned char _nbuf[1]; struct __sbuf _lb; int _blksize; int _offset; struct _reent *_data; _flock_t _lock; }; typedef struct __sFILE __FILE; struct _glue { struct _glue *_next; int _niobs; __FILE *_iobs; }; #line 284 "D:\eli\cpp_stuff\libc_include/sys/reent.h" struct _rand48 { unsigned short _seed[3]; unsigned short _mult[3]; unsigned short _add; }; #line 313 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 344 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 350 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 420 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 452 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 474 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 478 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 482 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 494 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 496 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 503 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 505 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 508 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 531 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 533 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 536 "D:\eli\cpp_stuff\libc_include/sys/reent.h" struct _reent { int _errno; #line 571 "D:\eli\cpp_stuff\libc_include/sys/reent.h" __FILE *_stdin, *_stdout, *_stderr; int _inc; char _emergency[25]; int _current_category; char *_current_locale; int __sdidinit; void(*__cleanup)(); struct _Bigint *_result; int _result_k; struct _Bigint *_p5s; struct _Bigint **_freelist; int _cvtlen; char *_cvtbuf; union { struct { unsigned int _unused_rand; char * _strtok_last; char _asctime_buf[26]; struct __tm _localtime_buf; int _gamma_signgam; unsigned long long _rand_next; struct _rand48 _r48; _mbstate_t _mblen_state; _mbstate_t _mbtowc_state; _mbstate_t _wctomb_state; char _l64a_buf[8]; char _signal_buf[24]; int _getdate_err; _mbstate_t _mbrlen_state; _mbstate_t _mbrtowc_state; _mbstate_t _mbsrtowcs_state; _mbstate_t _wcrtomb_state; _mbstate_t _wcsrtombs_state; } _reent; #line 619 "D:\eli\cpp_stuff\libc_include/sys/reent.h" struct { unsigned char * _nextf[30]; unsigned int _nmalloc[30]; } _unused; } _new; struct _atexit *_atexit; struct _atexit _atexit0; void (**(_sig_func))(int); #line 637 "D:\eli\cpp_stuff\libc_include/sys/reent.h" struct _glue __sglue; __FILE __sf[3]; }; #line 689 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 751 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 791 "D:\eli\cpp_stuff\libc_include/sys/reent.h" extern struct _reent *_impure_ptr; extern struct _reent * _global_impure_ptr; void _reclaim_reent(); #line 46 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 1 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 17 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 1 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 11 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 21 "D:\eli\cpp_stuff\libc_include/_ansi.h" #line 21 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 1 "D:\eli\cpp_stuff\libc_include/machine/_types.h" #line 4 "D:\eli\cpp_stuff\libc_include/machine/_types.h" #line 26 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 33 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 1 "D:\eli\cpp_stuff\libc_include/sys/_types.h" #line 8 "D:\eli\cpp_stuff\libc_include/sys/_types.h" #line 43 "D:\eli\cpp_stuff\libc_include/sys/_types.h" #line 62 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 1 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 19 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 26 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 30 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 35 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 39 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 42 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 53 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 56 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 67 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 76 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 98 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 108 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 126 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 131 "D:\eli\cpp_stuff\libc_include/stddef.h" typedef long int ptrdiff_t; #line 170 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 243 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 246 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 290 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 302 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 310 "D:\eli\cpp_stuff\libc_include/stddef.h" typedef int wchar_t; #line 361 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 365 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 418 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 422 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 427 "D:\eli\cpp_stuff\libc_include/stddef.h" #line 70 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 1 "D:\eli\cpp_stuff\libc_include/machine/types.h" #line 9 "D:\eli\cpp_stuff\libc_include/machine/types.h" typedef long int __off_t; typedef int __pid_t; typedef long int __loff_t; #line 71 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 79 "D:\eli\cpp_stuff\libc_include/sys/types.h" typedef unsigned char u_char; typedef unsigned short u_short; typedef unsigned int u_int; typedef unsigned long u_long; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long clock_t; typedef long time_t; struct timespec { time_t tv_sec; long tv_nsec; }; struct itimerspec { struct timespec it_interval; struct timespec it_value; }; typedef long daddr_t; typedef char * caddr_t; #line 131 "D:\eli\cpp_stuff\libc_include/sys/types.h" typedef unsigned short ino_t; #line 160 "D:\eli\cpp_stuff\libc_include/sys/types.h" typedef _off_t off_t; typedef __dev_t dev_t; typedef __uid_t uid_t; typedef __gid_t gid_t; typedef int pid_t; typedef long key_t; typedef _ssize_t ssize_t; typedef unsigned int mode_t; typedef unsigned short nlink_t; #line 200 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 209 "D:\eli\cpp_stuff\libc_include/sys/types.h" typedef long fd_mask; #line 221 "D:\eli\cpp_stuff\libc_include/sys/types.h" typedef struct _types_fd_set { fd_mask fds_bits[(((64)+(((sizeof (fd_mask) * 8))-1))/((sizeof (fd_mask) * 8)))]; } _types_fd_set; #line 236 "D:\eli\cpp_stuff\libc_include/sys/types.h" typedef unsigned long clockid_t; typedef unsigned long timer_t; typedef unsigned long useconds_t; typedef long suseconds_t; #line 1 "D:\eli\cpp_stuff\libc_include/sys/features.h" #line 20 "D:\eli\cpp_stuff\libc_include/sys/features.h" #line 257 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 266 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 273 "D:\eli\cpp_stuff\libc_include/sys/types.h" #line 47 "D:\eli\cpp_stuff\libc_include/stdio.h" typedef __FILE FILE; typedef _fpos_t fpos_t; #line 1 "D:\eli\cpp_stuff\libc_include/sys/stdio.h" #line 1 "D:\eli\cpp_stuff\libc_include/sys/lock.h" #line 5 "D:\eli\cpp_stuff\libc_include/sys/stdio.h" #line 1 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 6 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 43 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 68 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 77 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 104 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 134 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 141 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 284 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 313 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 344 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 350 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 420 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 452 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 474 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 478 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 482 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 494 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 496 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 503 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 505 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 508 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 531 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 533 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 536 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 571 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 619 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 637 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 689 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 751 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 791 "D:\eli\cpp_stuff\libc_include/sys/reent.h" #line 6 "D:\eli\cpp_stuff\libc_include/sys/stdio.h" #line 11 "D:\eli\cpp_stuff\libc_include/sys/stdio.h" #line 66 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 96 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 163 "D:\eli\cpp_stuff\libc_include/stdio.h" FILE * tmpfile(); char * tmpnam(); int fclose(); int fflush(); FILE * freopen(); void setbuf(); int setvbuf(); int fprintf(); #line 179 "D:\eli\cpp_stuff\libc_include/stdio.h" int fscanf(); #line 181 "D:\eli\cpp_stuff\libc_include/stdio.h" int printf(); #line 183 "D:\eli\cpp_stuff\libc_include/stdio.h" int scanf(); #line 185 "D:\eli\cpp_stuff\libc_include/stdio.h" int sscanf(); #line 187 "D:\eli\cpp_stuff\libc_include/stdio.h" int vfprintf(); #line 189 "D:\eli\cpp_stuff\libc_include/stdio.h" int vprintf(); #line 191 "D:\eli\cpp_stuff\libc_include/stdio.h" int vsprintf(); #line 193 "D:\eli\cpp_stuff\libc_include/stdio.h" int fgetc(); char * fgets(); int fputc(); int fputs(); int getc(); int getchar(); char * gets(); int putc(); int putchar(); int puts(); int ungetc(); size_t fread(); size_t fwrite(); int fgetpos(); int fseek(); int fsetpos(); long ftell(); void rewind(); void clearerr(); int feof(); int ferror(); void perror(); FILE * fopen(); int sprintf(); #line 227 "D:\eli\cpp_stuff\libc_include/stdio.h" int remove(); int rename(); int fseeko(); off_t ftello(); int asiprintf(); #line 241 "D:\eli\cpp_stuff\libc_include/stdio.h" char * asniprintf(); #line 243 "D:\eli\cpp_stuff\libc_include/stdio.h" char * asnprintf(); #line 245 "D:\eli\cpp_stuff\libc_include/stdio.h" int asprintf(); #line 247 "D:\eli\cpp_stuff\libc_include/stdio.h" int diprintf(); #line 250 "D:\eli\cpp_stuff\libc_include/stdio.h" int fcloseall(); int fiprintf(); #line 254 "D:\eli\cpp_stuff\libc_include/stdio.h" int fiscanf(); #line 256 "D:\eli\cpp_stuff\libc_include/stdio.h" int iprintf(); #line 258 "D:\eli\cpp_stuff\libc_include/stdio.h" int iscanf(); #line 260 "D:\eli\cpp_stuff\libc_include/stdio.h" int siprintf(); #line 262 "D:\eli\cpp_stuff\libc_include/stdio.h" int siscanf(); #line 264 "D:\eli\cpp_stuff\libc_include/stdio.h" int snprintf(); #line 266 "D:\eli\cpp_stuff\libc_include/stdio.h" int sniprintf(); #line 268 "D:\eli\cpp_stuff\libc_include/stdio.h" char * tempnam(); int vasiprintf(); #line 271 "D:\eli\cpp_stuff\libc_include/stdio.h" char * vasniprintf(); #line 273 "D:\eli\cpp_stuff\libc_include/stdio.h" char * vasnprintf(); #line 275 "D:\eli\cpp_stuff\libc_include/stdio.h" int vasprintf(); #line 277 "D:\eli\cpp_stuff\libc_include/stdio.h" int vdiprintf(); #line 279 "D:\eli\cpp_stuff\libc_include/stdio.h" int vfiprintf(); #line 281 "D:\eli\cpp_stuff\libc_include/stdio.h" int vfiscanf(); #line 283 "D:\eli\cpp_stuff\libc_include/stdio.h" int vfscanf(); #line 285 "D:\eli\cpp_stuff\libc_include/stdio.h" int viprintf(); #line 287 "D:\eli\cpp_stuff\libc_include/stdio.h" int viscanf(); #line 289 "D:\eli\cpp_stuff\libc_include/stdio.h" int vscanf(); #line 291 "D:\eli\cpp_stuff\libc_include/stdio.h" int vsiprintf(); #line 293 "D:\eli\cpp_stuff\libc_include/stdio.h" int vsiscanf(); #line 295 "D:\eli\cpp_stuff\libc_include/stdio.h" int vsniprintf(); #line 297 "D:\eli\cpp_stuff\libc_include/stdio.h" int vsnprintf(); #line 299 "D:\eli\cpp_stuff\libc_include/stdio.h" int vsscanf(); #line 301 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 307 "D:\eli\cpp_stuff\libc_include/stdio.h" FILE * fdopen(); int fileno(); int getw(); int pclose(); FILE * popen(); int putw(); void setbuffer(); int setlinebuf(); int getc_unlocked(); int getchar_unlocked(); void flockfile(); int ftrylockfile(); void funlockfile(); int putc_unlocked(); int putchar_unlocked(); #line 331 "D:\eli\cpp_stuff\libc_include/stdio.h" int dprintf(); #line 337 "D:\eli\cpp_stuff\libc_include/stdio.h" FILE * fmemopen(); FILE * open_memstream(); int vdprintf(); #line 345 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 351 "D:\eli\cpp_stuff\libc_include/stdio.h" int _asiprintf_r(); #line 354 "D:\eli\cpp_stuff\libc_include/stdio.h" char * _asniprintf_r(); #line 356 "D:\eli\cpp_stuff\libc_include/stdio.h" char * _asnprintf_r(); #line 358 "D:\eli\cpp_stuff\libc_include/stdio.h" int _asprintf_r(); #line 360 "D:\eli\cpp_stuff\libc_include/stdio.h" int _diprintf_r(); #line 362 "D:\eli\cpp_stuff\libc_include/stdio.h" int _dprintf_r(); #line 364 "D:\eli\cpp_stuff\libc_include/stdio.h" int _fclose_r(); int _fcloseall_r(); FILE * _fdopen_r(); int _fflush_r(); char * _fgets_r(); int _fiprintf_r(); #line 371 "D:\eli\cpp_stuff\libc_include/stdio.h" int _fiscanf_r(); #line 373 "D:\eli\cpp_stuff\libc_include/stdio.h" FILE * _fmemopen_r(); FILE * _fopen_r(); int _fprintf_r(); #line 377 "D:\eli\cpp_stuff\libc_include/stdio.h" int _fputc_r(); int _fputs_r(); size_t _fread_r(); int _fscanf_r(); #line 382 "D:\eli\cpp_stuff\libc_include/stdio.h" int _fseek_r(); long _ftell_r(); size_t _fwrite_r(); int _getc_r(); int _getc_unlocked_r(); int _getchar_r(); int _getchar_unlocked_r(); char * _gets_r(); int _iprintf_r(); #line 392 "D:\eli\cpp_stuff\libc_include/stdio.h" int _iscanf_r(); #line 394 "D:\eli\cpp_stuff\libc_include/stdio.h" int _mkstemp_r(); char * _mktemp_r(); FILE * _open_memstream_r(); void _perror_r(); int _printf_r(); #line 400 "D:\eli\cpp_stuff\libc_include/stdio.h" int _putc_r(); int _putc_unlocked_r(); int _putchar_unlocked_r(); int _putchar_r(); int _puts_r(); int _remove_r(); int _rename_r(); #line 408 "D:\eli\cpp_stuff\libc_include/stdio.h" int _scanf_r(); #line 410 "D:\eli\cpp_stuff\libc_include/stdio.h" int _siprintf_r(); #line 412 "D:\eli\cpp_stuff\libc_include/stdio.h" int _siscanf_r(); #line 414 "D:\eli\cpp_stuff\libc_include/stdio.h" int _sniprintf_r(); #line 416 "D:\eli\cpp_stuff\libc_include/stdio.h" int _snprintf_r(); #line 418 "D:\eli\cpp_stuff\libc_include/stdio.h" int _sprintf_r(); #line 420 "D:\eli\cpp_stuff\libc_include/stdio.h" int _sscanf_r(); #line 422 "D:\eli\cpp_stuff\libc_include/stdio.h" char * _tempnam_r(); FILE * _tmpfile_r(); char * _tmpnam_r(); int _ungetc_r(); int _vasiprintf_r(); #line 428 "D:\eli\cpp_stuff\libc_include/stdio.h" char * _vasniprintf_r(); #line 430 "D:\eli\cpp_stuff\libc_include/stdio.h" char * _vasnprintf_r(); #line 432 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vasprintf_r(); #line 434 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vdiprintf_r(); #line 436 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vdprintf_r(); #line 438 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vfiprintf_r(); #line 440 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vfiscanf_r(); #line 442 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vfprintf_r(); #line 444 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vfscanf_r(); #line 446 "D:\eli\cpp_stuff\libc_include/stdio.h" int _viprintf_r(); #line 448 "D:\eli\cpp_stuff\libc_include/stdio.h" int _viscanf_r(); #line 450 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vprintf_r(); #line 452 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vscanf_r(); #line 454 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vsiprintf_r(); #line 456 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vsiscanf_r(); #line 458 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vsniprintf_r(); #line 460 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vsnprintf_r(); #line 462 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vsprintf_r(); #line 464 "D:\eli\cpp_stuff\libc_include/stdio.h" int _vsscanf_r(); #line 466 "D:\eli\cpp_stuff\libc_include/stdio.h" ssize_t __getdelim(); ssize_t __getline(); #line 493 "D:\eli\cpp_stuff\libc_include/stdio.h" int __srget_r(); int __swbuf_r(); #line 500 "D:\eli\cpp_stuff\libc_include/stdio.h" FILE * funopen(); #line 514 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 518 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 520 "D:\eli\cpp_stuff\libc_include/stdio.h" typedef ssize_t cookie_read_function_t(void *__cookie, char *__buf, size_t __n); typedef ssize_t cookie_write_function_t(void *__cookie, const char *__buf, size_t __n); typedef int cookie_seek_function_t(void *__cookie, off_t *__off, int __whence); typedef int cookie_close_function_t(void *__cookie); typedef struct { #line 535 "D:\eli\cpp_stuff\libc_include/stdio.h" cookie_read_function_t *read; cookie_write_function_t *write; cookie_seek_function_t *seek; cookie_close_function_t *close; } cookie_io_functions_t; FILE * fopencookie(); #line 542 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 549 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 574 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 580 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 603 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 613 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 621 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 626 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 657 "D:\eli\cpp_stuff\libc_include/stdio.h" #line 4 "example_c_file.c" #line 8 "example_c_file.c" char tav = 'b'; char maav = L"'guruguru\n"; char* moral = "ain't I \\\"\\\t\" a nice string?\"\""; char* comment_inside = "but you will /* see it */!!!!"; char* i_have_newlines = "line one\nline two\nline three"; int main() { auto char* multi = "a multi"; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7906625 pycparser-3.12/tests/c_files/empty.h0000664000175000017500000000016214716121045017044 0ustar00elibeneliben#define PERFECTLY #define NORMAL #define TO #define HAVE #define HEADER #define WITH #define ONLY #define DEFINES ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7906625 pycparser-3.12/tests/c_files/example_c_file.c0000664000175000017500000000037214716121045020640 0ustar00elibenelibenchar tav = 'b'; char* moral = "ain't I \\\"\\\t\" a nice string?\"\""; char* comment_inside = "but you will /* see it */!!!!"; char* i_have_newlines = "line one\nline two\nline three"; int main() { auto char* multi = "a multi"; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8497353 pycparser-3.12/tests/c_files/hdir/0000775000175000017500000000000015266410573016474 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1792676218.852276 pycparser-3.12/tests/c_files/hdir/9/0000775000175000017500000000000015266410573016644 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7906625 pycparser-3.12/tests/c_files/hdir/9/inc.h0000664000175000017500000000001714716121045017554 0ustar00elibenelibenextern int ie; ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7906625 pycparser-3.12/tests/c_files/memmgr.c0000664000175000017500000001273514716121045017176 0ustar00elibeneliben//---------------------------------------------------------------- // Statically-allocated memory manager // // by Eli Bendersky (eliben@gmail.com) // // This code is in the public domain. //---------------------------------------------------------------- #include "memmgr.h" typedef ulong Align; union mem_header_union { struct { // Pointer to the next block in the free list // union mem_header_union* next; // Size of the block (in quantas of sizeof(mem_header_t)) // ulong size; } s; // Used to align headers in memory to a boundary // Align align_dummy; }; typedef union mem_header_union mem_header_t; // Initial empty list // static mem_header_t base; // Start of free list // static mem_header_t* freep = 0; // Static pool for new allocations // static byte pool[POOL_SIZE] = {0}; static ulong pool_free_pos = 0; void memmgr_init() { base.s.next = 0; base.s.size = 0; freep = 0; pool_free_pos = 0; } static mem_header_t* get_mem_from_pool(ulong nquantas) { ulong total_req_size; mem_header_t* h; if (nquantas < MIN_POOL_ALLOC_QUANTAS) nquantas = MIN_POOL_ALLOC_QUANTAS; total_req_size = nquantas * sizeof(mem_header_t); if (pool_free_pos + total_req_size <= POOL_SIZE) { h = (mem_header_t*) (pool + pool_free_pos); h->s.size = nquantas; memmgr_free((void*) (h + 1)); pool_free_pos += total_req_size; } else { return 0; } return freep; } // Allocations are done in 'quantas' of header size. // The search for a free block of adequate size begins at the point 'freep' // where the last block was found. // If a too-big block is found, it is split and the tail is returned (this // way the header of the original needs only to have its size adjusted). // The pointer returned to the user points to the free space within the block, // which begins one quanta after the header. // void* memmgr_alloc(ulong nbytes) { mem_header_t* p; mem_header_t* prevp; // Calculate how many quantas are required: we need enough to house all // the requested bytes, plus the header. The -1 and +1 are there to make sure // that if nbytes is a multiple of nquantas, we don't allocate too much // ulong nquantas = (nbytes + sizeof(mem_header_t) - 1) / sizeof(mem_header_t) + 1; // First alloc call, and no free list yet ? Use 'base' for an initial // denegerate block of size 0, which points to itself // if ((prevp = freep) == 0) { base.s.next = freep = prevp = &base; base.s.size = 0; } for (p = prevp->s.next; ; prevp = p, p = p->s.next) { // big enough ? if (p->s.size >= nquantas) { // exactly ? if (p->s.size == nquantas) { // just eliminate this block from the free list by pointing // its prev's next to its next // prevp->s.next = p->s.next; } else // too big { p->s.size -= nquantas; p += p->s.size; p->s.size = nquantas; } freep = prevp; return (void*) (p + 1); } // Reached end of free list ? // Try to allocate the block from the pool. If that succeeds, // get_mem_from_pool adds the new block to the free list and // it will be found in the following iterations. If the call // to get_mem_from_pool doesn't succeed, we've run out of // memory // else if (p == freep) { if ((p = get_mem_from_pool(nquantas)) == 0) { #ifdef DEBUG_MEMMGR_FATAL printf("!! Memory allocation failed !!\n"); #endif return 0; } } } } // Scans the free list, starting at freep, looking the the place to insert the // free block. This is either between two existing blocks or at the end of the // list. In any case, if the block being freed is adjacent to either neighbor, // the adjacent blocks are combined. // void memmgr_free(void* ap) { mem_header_t* block; mem_header_t* p; // acquire pointer to block header block = ((mem_header_t*) ap) - 1; // Find the correct place to place the block in (the free list is sorted by // address, increasing order) // for (p = freep; !(block > p && block < p->s.next); p = p->s.next) { // Since the free list is circular, there is one link where a // higher-addressed block points to a lower-addressed block. // This condition checks if the block should be actually // inserted between them // if (p >= p->s.next && (block > p || block < p->s.next)) break; } // Try to combine with the higher neighbor // if (block + block->s.size == p->s.next) { block->s.size += p->s.next->s.size; block->s.next = p->s.next->s.next; } else { block->s.next = p->s.next; } // Try to combine with the lower neighbor // if (p + p->s.size == block) { p->s.size += block->s.size; p->s.next = block->s.next; } else { p->s.next = block; } freep = p; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7906625 pycparser-3.12/tests/c_files/memmgr.h0000664000175000017500000000566614716121045017210 0ustar00elibeneliben//---------------------------------------------------------------- // Statically-allocated memory manager // // by Eli Bendersky (eliben@gmail.com) // // This code is in the public domain. //---------------------------------------------------------------- #ifndef MEMMGR_H #define MEMMGR_H // // Memory manager: dynamically allocates memory from // a fixed pool that is allocated statically at link-time. // // Usage: after calling memmgr_init() in your // initialization routine, just use memmgr_alloc() instead // of malloc() and memmgr_free() instead of free(). // Naturally, you can use the preprocessor to define // malloc() and free() as aliases to memmgr_alloc() and // memmgr_free(). This way the manager will be a drop-in // replacement for the standard C library allocators, and can // be useful for debugging memory allocation problems and // leaks. // // Preprocessor flags you can define to customize the // memory manager: // // DEBUG_MEMMGR_FATAL // Allow printing out a message when allocations fail // // DEBUG_MEMMGR_SUPPORT_STATS // Allow printing out of stats in function // memmgr_print_stats When this is disabled, // memmgr_print_stats does nothing. // // Note that in production code on an embedded system // you'll probably want to keep those undefined, because // they cause printf to be called. // // POOL_SIZE // Size of the pool for new allocations. This is // effectively the heap size of the application, and can // be changed in accordance with the available memory // resources. // // MIN_POOL_ALLOC_QUANTAS // Internally, the memory manager allocates memory in // quantas roughly the size of two ulong objects. To // minimize pool fragmentation in case of multiple allocations // and deallocations, it is advisable to not allocate // blocks that are too small. // This flag sets the minimal amount of quantas for // an allocation. If the size of a ulong is 4 and you // set this flag to 16, the minimal size of an allocation // will be 4 * 2 * 16 = 128 bytes // If you have a lot of small allocations, keep this value // low to conserve memory. If you have mostly large // allocations, it is best to make it higher, to avoid // fragmentation. // // Notes: // 1. This memory manager is *not thread safe*. Use it only // for single thread/task applications. // #define DEBUG_MEMMGR_SUPPORT_STATS 1 #define POOL_SIZE 8 * 1024 #define MIN_POOL_ALLOC_QUANTAS 16 typedef unsigned char byte; typedef unsigned long ulong; // Initialize the memory manager. This function should be called // only once in the beginning of the program. // void memmgr_init(); // 'malloc' clone // void* memmgr_alloc(ulong nbytes); // 'free' clone // void memmgr_free(void* ap); // Prints statistics about the current state of the memory // manager // void memmgr_print_stats(); #endif // MEMMGR_H ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7906625 pycparser-3.12/tests/c_files/memmgr_with_h.c0000664000175000017500000000770614716121045020542 0ustar00elibeneliben#line 1 "memmgr.c" #line 1 "./memmgr.h" typedef unsigned char byte; typedef unsigned long ulong; void memmgr_init(); void* memmgr_alloc(ulong nbytes); void memmgr_free(void* ap); void memmgr_print_stats(); #line 9 "memmgr.c" typedef ulong Align; union mem_header_union { struct { union mem_header_union* next; ulong size; } s; Align align_dummy; }; typedef union mem_header_union mem_header_t; static mem_header_t base; static mem_header_t* freep = 0; static byte pool[8 * 1024] = {0}; static ulong pool_free_pos = 0; void memmgr_init() { base.s.next = 0; base.s.size = 0; freep = 0; pool_free_pos = 0; } void memmgr_print_stats() { mem_header_t* p; printf("------ Memory manager stats ------\n\n"); printf( "Pool: free_pos = %lu (%lu bytes left)\n\n", pool_free_pos,8 * 1024 - pool_free_pos); p = (mem_header_t*) pool; while (p < (mem_header_t*) (pool + pool_free_pos)) { printf( " * Addr: 0x%8lu; Size: %8lu\n", p, p->s.size); p += p->s.size; } printf("\nFree list:\n\n"); if (freep) { p = freep; while (1) { printf( " * Addr: 0x%8lu; Size: %8lu; Next: 0x%8lu\n", p, p->s.size, p->s.next); p = p->s.next; if (p == freep) break; } } else { printf("Empty\n"); } printf("\n"); } static mem_header_t* get_mem_from_pool(ulong nquantas) { ulong total_req_size; mem_header_t* h; if (nquantas < 16) nquantas = 16; total_req_size = nquantas * sizeof(mem_header_t); if (pool_free_pos + total_req_size <= 8 * 1024) { h = (mem_header_t*) (pool + pool_free_pos); h->s.size = nquantas; memmgr_free((void*) (h + 1)); pool_free_pos += total_req_size; } else { return 0; } return freep; } void* memmgr_alloc(ulong nbytes) { mem_header_t* p; mem_header_t* prevp; ulong nquantas = (nbytes + sizeof(mem_header_t) - 1) / sizeof(mem_header_t) + 1; if ((prevp = freep) == 0) { base.s.next = freep = prevp = &base; base.s.size = 0; } for (p = prevp->s.next; ; prevp = p, p = p->s.next) { if (p->s.size >= nquantas) { if (p->s.size == nquantas) { prevp->s.next = p->s.next; } else { p->s.size -= nquantas; p += p->s.size; p->s.size = nquantas; } freep = prevp; return (void*) (p + 1); } else if (p == freep) { if ((p = get_mem_from_pool(nquantas)) == 0) { return 0; } } } } void memmgr_free(void* ap) { mem_header_t* block; mem_header_t* p; block = ((mem_header_t*) ap) - 1; for (p = freep; !(block > p && block < p->s.next); p = p->s.next) { if (p >= p->s.next && (block > p || block < p->s.next)) break; } if (block + block->s.size == p->s.next) { block->s.size += p->s.next->s.size; block->s.next = p->s.next->s.next; } else { block->s.next = p->s.next; } if (p + p->s.size == block) { p->s.size += block->s.size; p->s.next = block->s.next; } else { p->s.next = block; } freep = p; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7906625 pycparser-3.12/tests/c_files/simplemain.c0000664000175000017500000000010014716121045020027 0ustar00elibeneliben#include "hdir\emptydir\..\9\inc.h" int main() { return 0; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7906625 pycparser-3.12/tests/c_files/year.c0000664000175000017500000000240114716121045016637 0ustar00elibeneliben#include #include #include #include /* C99 bools */ _Bool just_a_flag = false; bool another_flag = true; void convert(int thousands, int hundreds, int tens, int ones) { char *num[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; char *for_ten[] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; char *af_ten[] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Ninteen"}; printf("\nThe year in words is:\n"); printf("%s thousand", num[thousands]); if (hundreds != 0) printf(" %s hundred", num[hundreds]); if (tens != 1) printf(" %s %s", for_ten[tens], num[ones]); else printf(" %s", af_ten[ones]); va_list jajaja; } int main() { int year; int n1000, n100, n10, n1; printf("\nEnter the year (4 digits): "); scanf("%d", &year); if (year > 9999 || year < 1000) { printf("\nError !! The year must contain 4 digits."); exit(EXIT_FAILURE); } n1000 = year/1000; n100 = ((year)%1000)/100; n10 = (year%100)/10; n1 = ((year%10)%10); convert(n1000, n100, n10, n1); return 0; } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792502755.5376382 pycparser-3.12/tests/test_c23_attributes.py0000664000175000017500000005141215265665744020426 0ustar00elibenelibenimport unittest from pycparser import c_ast, c_generator, c_parser from pycparser.c_lexer import CLexer from tests.test_c_generator import compare_asts class TestAttributeLexer(unittest.TestCase): def test_opaque_arguments(self): def error(msg, line, column): self.fail(msg) lexer = CLexer(error, dialect="c23") lexer.input('[[int::return({if (x) [y];}, 1\'000, "[)]")]] {}') tokens = list(iter(lexer.token, None)) self.assertEqual( [t.type for t in tokens], [ "ATTRIBUTE_BEGIN", "ID", "COLONCOLON", "ID", "ATTRIBUTE_ARGUMENTS", "ATTRIBUTE_END", "LBRACE", "RBRACE", ], ) self.assertEqual(tokens[1].value, "int") self.assertEqual(tokens[3].value, "return") self.assertEqual(tokens[4].value, '{if (x) [y];}, 1\'000, "[)]"') def test_multiline_coordinates_and_input_reset(self): lexer = CLexer(lambda msg, line, column: self.fail(msg)) lexer.input('[\n[deprecated(\n"old"\n)]\n] int x;') tokens = list(iter(lexer.token, None)) self.assertEqual((tokens[0].lineno, tokens[0].column), (1, 1)) self.assertEqual((tokens[1].lineno, tokens[1].column), (2, 2)) self.assertEqual((tokens[2].lineno, tokens[2].column), (2, 12)) self.assertEqual(tokens[2].value, '\n"old"\n') self.assertEqual((tokens[4].lineno, tokens[4].column), (5, 3)) lexer.input("[[int") self.assertEqual( [t.type for t in iter(lexer.token, None)], ["ATTRIBUTE_BEGIN", "ID"] ) lexer.input("int x[2];") self.assertEqual( [t.type for t in iter(lexer.token, None)], ["INT", "ID", "LBRACKET", "INT_CONST_DEC", "RBRACKET", "SEMI"], ) class TestAttributeParser(unittest.TestCase): def setUp(self): self.parser = c_parser.CParser(dialect="c23") def test_groups_names_and_arguments(self): decl = self.parser.parse( '[[nodiscard, vendor::flag]] [[deprecated("old")]] int f(void);' ).ext[0] self.assertEqual(len(decl.attributes), 2) first, second = decl.attributes self.assertIsInstance(first, c_ast.AttributeSpecifier) self.assertEqual(first.attributes[0].name, "nodiscard") self.assertIsNone(first.attributes[0].namespace) self.assertIsNone(first.attributes[0].arguments) self.assertEqual(first.attributes[1].name, "flag") self.assertEqual(first.attributes[1].namespace, "vendor") self.assertEqual(second.attributes[0].name, "deprecated") self.assertEqual(second.attributes[0].arguments, '"old"') def test_empty_groups_and_argument_clauses(self): decl = self.parser.parse( "[[]] [[,vendor::plain,,vendor::empty(),]] int x;" ).ext[0] self.assertEqual(decl.attributes[0].attributes, []) plain, empty = decl.attributes[1].attributes self.assertIsNone(plain.arguments) self.assertEqual(empty.arguments, "") def test_keywords_and_typedefs_as_attribute_names(self): ast = self.parser.parse( "typedef int vendor; [[vendor::int, if, constexpr::return]] int x;" ) attrs = ast.ext[1].attributes[0].attributes self.assertEqual((attrs[0].namespace, attrs[0].name), ("vendor", "int")) self.assertEqual(attrs[1].name, "if") self.assertEqual((attrs[2].namespace, attrs[2].name), ("constexpr", "return")) def test_balanced_argument_text(self): source = r"""[[vendor::tokens(if (x) { [y]; }, "[)]", '\'', 1'000, /* ) */ 0xA'B)]] int x;""" decl = self.parser.parse(source).ext[0] self.assertEqual( decl.attributes[0].attributes[0].arguments, r"""if (x) { [y]; }, "[)]", '\'', 1'000, /* ) */ 0xA'B""", ) def test_standalone_attributes(self): ast = self.parser.parse( "[[vendor::global]]; void f(void) { [[fallthrough]]; [[]]; }" ) self.assertIsInstance(ast.ext[0], c_ast.AttributeDeclaration) first, second = ast.ext[1].body.block_items self.assertIsInstance(first, c_ast.AttributeDeclaration) self.assertEqual(first.attributes[0].attributes[0].name, "fallthrough") self.assertEqual(second.attributes[0].attributes, []) def test_prefixed_literals_in_arguments(self): decl = self.parser.parse( """[[vendor::text(u8']', U'}', L')', u8"[(]", token123')')]] int x;""" ).ext[0] self.assertEqual( decl.attributes[0].attributes[0].arguments, """u8']', U'}', L')', u8"[(]", token123')'""", ) def test_comma_declarations_and_typedefs(self): ast = self.parser.parse( "[[maybe_unused]] int a, b; [[deprecated]] typedef int T; T value;" ) self.assertEqual(ast.ext[0].attributes[0].attributes[0].name, "maybe_unused") self.assertEqual(ast.ext[1].attributes[0].attributes[0].name, "maybe_unused") self.assertIsInstance(ast.ext[2], c_ast.Typedef) self.assertEqual(ast.ext[2].attributes[0].attributes[0].name, "deprecated") self.assertEqual(ast.ext[3].type.type.names, ["T"]) def test_type_and_declarator_attributes(self): decl = self.parser.parse( "[[vendor::decl]] const int [[vendor::type]] x [[vendor::name]];" ).ext[0] self.assertEqual(decl.attributes[0].attributes[0].name, "decl") self.assertEqual(decl.type.attributes[0].attributes[0].name, "name") self.assertIsInstance(decl.type.type, c_ast.AttributedType) self.assertEqual(decl.type.type.attributes[0].attributes[0].name, "type") self.assertEqual(decl.type.type.type.names, ["int"]) self.assertEqual(decl.quals, ["const"]) def test_pointer_and_array_attributes(self): ast = self.parser.parse( "int * [[vendor::ptr]] const p [[vendor::id]]; int a[2] [[vendor::outer]][3] [[vendor::inner]];" ) pointer, array = ast.ext self.assertEqual(pointer.type.attributes[0].attributes[0].name, "ptr") self.assertEqual(pointer.type.quals, ["const"]) self.assertEqual(pointer.type.type.attributes[0].attributes[0].name, "id") self.assertEqual(array.type.attributes[0].attributes[0].name, "outer") self.assertEqual(array.type.type.attributes[0].attributes[0].name, "inner") def test_function_and_parameter_attributes(self): func = self.parser.parse( "[[nodiscard]] int f([[maybe_unused]] int x, [[vendor::arg]] int) [[unsequenced]] { return x; }" ).ext[0] self.assertEqual(func.decl.attributes[0].attributes[0].name, "nodiscard") self.assertEqual(func.decl.type.attributes[0].attributes[0].name, "unsequenced") named, unnamed = func.decl.type.args.params self.assertEqual(named.attributes[0].attributes[0].name, "maybe_unused") self.assertIsInstance(unnamed, c_ast.Typename) self.assertEqual(unnamed.attributes[0].attributes[0].name, "arg") def test_abstract_declarator_attributes(self): decl = self.parser.parse( "void f(int (* [[vendor::ptr]])(int) [[vendor::fn]], int [3] [[vendor::arr]], int (int) [[vendor::direct]]);" ).ext[0] pointer, array, function = decl.type.args.params self.assertEqual(pointer.type.attributes[0].attributes[0].name, "ptr") self.assertEqual(pointer.type.type.attributes[0].attributes[0].name, "fn") self.assertEqual(array.type.attributes[0].attributes[0].name, "arr") self.assertEqual(function.type.attributes[0].attributes[0].name, "direct") def test_tags_members_and_enumerators(self): ast = self.parser.parse(""" struct [[deprecated]] S { [[maybe_unused]] int field [[vendor::member]]; }; union [[vendor::union]] U { int x; }; enum [[vendor::enum]] E : unsigned int [[vendor::base]] { A [[deprecated]] = 1, B [[vendor::enumerator()]] }; """) struct, union, enum = ast.ext self.assertEqual(struct.type.attributes[0].attributes[0].name, "deprecated") member = struct.type.decls[0] self.assertEqual(member.attributes[0].attributes[0].name, "maybe_unused") self.assertEqual(member.type.attributes[0].attributes[0].name, "member") self.assertEqual(union.type.attributes[0].attributes[0].name, "union") self.assertEqual(enum.type.attributes[0].attributes[0].name, "enum") self.assertEqual( enum.type.underlying_type.type.type.attributes[0].attributes[0].name, "base" ) a, b = enum.type.values.enumerators self.assertEqual(a.attributes[0].attributes[0].name, "deprecated") self.assertEqual(a.value.value, "1") self.assertEqual(b.attributes[0].attributes[0].arguments, "") def test_statement_attributes(self): func = self.parser.parse(""" void f(int x) { [[vendor::expr]] x++; [[vendor::if]] if (x) [[vendor::return]] return; [[vendor::block]] { [[maybe_unused]] int y; } } """).ext[0] expr, branch, block = func.body.block_items self.assertIsInstance(expr, c_ast.AttributedStatement) self.assertIsInstance(expr.stmt, c_ast.UnaryOp) self.assertEqual(expr.attributes[0].attributes[0].name, "expr") self.assertIsInstance(branch.stmt, c_ast.If) self.assertIsInstance(branch.stmt.iftrue, c_ast.AttributedStatement) self.assertIsInstance(branch.stmt.iftrue.stmt, c_ast.Return) self.assertIsInstance(block.stmt, c_ast.Compound) self.assertEqual( block.stmt.block_items[0].attributes[0].attributes[0].name, "maybe_unused" ) def test_labels_and_switch_cases(self): func = self.parser.parse(""" void f(int x) { switch (x) [[vendor::body]] { [[vendor::first]] case 1: [[vendor::second]] case 2: x++; [[fallthrough]]; [[vendor::default]] default: } [[maybe_unused]] label: [[maybe_unused]] int value; [[maybe_unused]] end: } """).ext[0] switch, label, declaration, end = func.body.block_items self.assertIsInstance(switch.stmt, c_ast.AttributedStatement) first, second, default = switch.stmt.stmt.block_items self.assertIsInstance(first, c_ast.Case) self.assertEqual(first.attributes[0].attributes[0].name, "first") self.assertEqual(first.stmts, []) self.assertEqual(second.attributes[0].attributes[0].name, "second") self.assertIsInstance(second.stmts[1], c_ast.AttributeDeclaration) self.assertEqual(default.attributes[0].attributes[0].name, "default") self.assertEqual(label.attributes[0].attributes[0].name, "maybe_unused") self.assertIsInstance(label.stmt, c_ast.EmptyStatement) self.assertEqual(declaration.name, "value") self.assertIsInstance(end.stmt, c_ast.EmptyStatement) def test_scope_and_parameter_shadowing(self): ast = self.parser.parse(""" typedef int T; int f(int T) [[vendor::tokens({ T; })]] { [[vendor::tokens({ typedef int Other; })]] int value; T = 1; return T; } T outside; """) func = ast.ext[1] self.assertIsInstance(func.body.block_items[1], c_ast.Assignment) self.assertEqual(func.body.block_items[1].lvalue.name, "T") self.assertEqual(ast.ext[2].type.type.names, ["T"]) def test_coordinates_and_parser_reuse(self): decl = self.parser.parse( "[[vendor::attr(\n{ x; }\n)]]\nint x;", "attributes.c" ).ext[0] group = decl.attributes[0] self.assertEqual(str(group.coord), "attributes.c:1:1") self.assertEqual(str(group.attributes[0].coord), "attributes.c:1:11") self.assertEqual(str(decl.coord), "attributes.c:4:5") with self.assertRaises(c_parser.ParseError): self.parser.parse("[[vendor::bad({)]] int x;") plain = self.parser.parse("int x;").ext[0] self.assertEqual(plain.attributes, []) def test_legacy_rejection(self): parser = c_parser.CParser(dialect="legacy") with self.assertRaisesRegex(c_parser.ParseError, "Attributes require C23"): parser.parse("[[maybe_unused]] int x;") with self.assertRaisesRegex(c_parser.ParseError, "Attributes require C23"): parser.parse("int x [[maybe_unused]];") with self.assertRaisesRegex(c_parser.ParseError, "Attributes require C23"): parser.parse("struct [[deprecated]] S;") with self.assertRaisesRegex(c_parser.ParseError, "Attributes require C23"): parser.parse("void f(void) { [[fallthrough]]; }") def test_malformed_attributes(self): self.assertRaises(c_parser.ParseError, self.parser.parse, "[[a b]] int x;") self.assertRaises( c_parser.ParseError, self.parser.parse, "[[vendor:attr]] int x;" ) self.assertRaises( c_parser.ParseError, self.parser.parse, "[[vendor : : attr]] int x;" ) self.assertRaises(c_parser.ParseError, self.parser.parse, "[[vendor::]] int x;") self.assertRaises(c_parser.ParseError, self.parser.parse, "[[a::b::c]] int x;") self.assertRaises(c_parser.ParseError, self.parser.parse, "[[123]] int x;") self.assertRaises(c_parser.ParseError, self.parser.parse, "[[a] int x;") self.assertRaises(c_parser.ParseError, self.parser.parse, "[[a") self.assertRaises(c_parser.ParseError, self.parser.parse, "[[a]]") self.assertRaises(c_parser.ParseError, self.parser.parse, "[[a(()]] int x;") self.assertRaises(c_parser.ParseError, self.parser.parse, "[[a([))]] int x;") self.assertRaises( c_parser.ParseError, self.parser.parse, '[[a("unterminated)]] int x;' ) self.assertRaises( c_parser.ParseError, self.parser.parse, '[[a("line\nbreak")]] int x;' ) self.assertRaises(c_parser.ParseError, self.parser.parse, "int x = [[a]] 1;") self.assertRaises(c_parser.ParseError, self.parser.parse, "int [[a]] const x;") self.assertRaises( c_parser.ParseError, self.parser.parse, "int * const [[a]] x;" ) class TestAttributeGeneration(unittest.TestCase): def round_trip(self, source): parser = c_parser.CParser(dialect="c23") ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated)), generated) return generated def test_declarations_and_declarators(self): generated = self.round_trip(""" [[maybe_unused]] typedef int T; [[vendor::decl]] const T [[vendor::type]] * [[vendor::ptr]] const p [[vendor::id]]; int a [[vendor::name]][2] [[vendor::array]][3] [[vendor::element]]; [[vendor::decl]] int first, second; [[maybe_unused]] auto count [[vendor::name]] = 1; """) self.assertIn( "[[vendor::decl]] const T [[vendor::type]] * [[vendor::ptr]] const p [[vendor::id]];", generated, ) self.assertIn( "int a [[vendor::name]][2] [[vendor::array]][3] [[vendor::element]];", generated, ) self.assertIn("[[maybe_unused]] auto count [[vendor::name]] = 1;", generated) def test_tag_and_member_attributes(self): generated = self.round_trip(""" struct [[deprecated("old")]] S { [[maybe_unused]] int value [[vendor::member]]; }; struct [[vendor::forward]] Forward; union [[vendor::union]] U { int x; }; enum [[vendor::enum]] E : unsigned int [[vendor::base]] { A [[deprecated]], B [[vendor::enumerator()]] }; """) self.assertIn('struct [[deprecated("old")]] S', generated) self.assertIn("[[maybe_unused]] int value [[vendor::member]];", generated) self.assertIn( "enum [[vendor::enum]] E : unsigned int [[vendor::base]]", generated ) self.assertIn("B [[vendor::enumerator()]]", generated) def test_shared_attributed_definition(self): # The shared type's attributes are emitted once; name attributes # still belong to their individual declarators. generated = self.round_trip(""" [[maybe_unused]] struct S { int x; } [[vendor::type]] a [[vendor::first]], b [[vendor::second]]; """) self.assertEqual(generated.count("struct S"), 1) self.assertEqual(generated.count("[[maybe_unused]]"), 1) self.assertEqual(generated.count("[[vendor::type]]"), 1) self.assertIn("a [[vendor::first]], b [[vendor::second]];", generated) first, second = c_parser.CParser(dialect="c23").parse(generated).ext self.assertIs(first.type.type.type, second.type.type.type) def test_shared_attributed_typedef(self): # A pointer typedef must reuse the same union definition and retain # its own pointer attribute when the declarations are grouped. generated = self.round_trip(""" typedef union U { int x; } [[vendor::type]] Value, * [[vendor::ptr]] Pointer; """) self.assertEqual(generated.count("union U"), 1) self.assertEqual(generated.count("[[vendor::type]]"), 1) self.assertIn("Value, * [[vendor::ptr]] Pointer;", generated) value, pointer = c_parser.CParser(dialect="c23").parse(generated).ext self.assertIs(value.type.type.type, pointer.type.type.type.type) def test_separate_attributed_definitions(self): # Identical anonymous definitions remain distinct types, even when # their attributes also match. generated = self.round_trip(""" struct { int x; } [[vendor::type]] a; struct { int x; } [[vendor::type]] b; """) self.assertEqual(generated.count("struct"), 2) self.assertEqual(generated.count("[[vendor::type]]"), 2) first, second = c_parser.CParser(dialect="c23").parse(generated).ext self.assertIsNot(first.type.type.type, second.type.type.type) def test_functions_and_type_operands(self): generated = self.round_trip(""" [[nodiscard]] int f([[maybe_unused]] int x, [[vendor::arg]] int) [[unsequenced]] { return x; } void callback(int (* [[vendor::ptr]])(int) [[vendor::fn]], int [3] [[vendor::array]], int (int) [[vendor::direct]]); int * [[vendor::ptr]] (*factory(void) [[vendor::factory]])(int) [[vendor::result]]; int size = sizeof(int [[vendor::type]] * [[vendor::ptr]]); _Atomic(int [[vendor::inner]]) atomic; typeof(int [[vendor::inner]]) [[vendor::outer]] value; """) self.assertIn( "[[nodiscard]] int f([[maybe_unused]] int x, [[vendor::arg]] int) [[unsequenced]]", generated, ) self.assertIn("sizeof(int [[vendor::type]] * [[vendor::ptr]])", generated) def test_statements_and_labels(self): self.round_trip(""" void f(int x) { [[vendor::expression]] x++; [[vendor::block]] { [[maybe_unused]] int value; } [[vendor::if]] if (x) [[vendor::return]] return; else [[vendor::else]] x--; [[vendor::while]] while (x) [[vendor::body]] x--; [[vendor::do]] do [[vendor::body]] x++; while (x < 1); [[vendor::for]] for ([[maybe_unused]] int i=0, j=1; ifield;", "int v = _Generic(x, default: y)++;", "int v = -_Generic(x, int: 1);", "int v = sizeof(_Generic(x, int: 1));", ] for reduce_parentheses in (False, True): for src in snippets: with self.subTest(src=src, reduce_parentheses=reduce_parentheses): generated = self._assert_ctoc_correct( src, reduce_parentheses=reduce_parentheses ) self.assertEqual(generated, src + "\n") def test_casts(self): self._assert_ctoc_correct(r""" int main() { int b = (int) f; int c = (int*) f; }""") self._assert_ctoc_correct(r""" int main() { int a = (int) b + 8; int t = (int) c; } """) def test_unicode_character_escapes(self): for literal in ( r"'\u00e9'", r"L'\u03A9'", r"u8'\u00e9'", r"u'\u00e9'", r"U'\U0001F600'", r"'\u00e9a'", ): with self.subTest(literal=literal): source = f"int c = {literal};" self.assertEqual(self._assert_ctoc_correct(source), source + "\n") def test_string_literal_escape_boundaries(self): # Round trips alone cannot catch a parser that changes escape meanings. for prefix in ("", "L", "u8", "u", "U"): for literals in (r'"\1" "23"', r'"\x1" "a"', r'"\x12" "3"'): src = f"void *s = {prefix}{literals};" with self.subTest(src=src): self.assertEqual(self._assert_ctoc_correct(src), src + "\n") for src in ( r'_Static_assert(1, "\x1" "a");', r'void f(void) { consume("\1" "23"); }', r'int f(void) { return ("\x1" "a")[1]; }', 'char *s = "?" "?=";', ): with self.subTest(src=src): self._assert_ctoc_correct(src) def test_initlist(self): self._assert_ctoc_correct("int arr[] = {1, 2, 3};") def test_exprs(self): self._assert_ctoc_correct(""" int main(void) { int a; int b = a++; int c = ++a; int d = a--; int e = --a; }""") def test_statements(self): # note two minuses here self._assert_ctoc_correct(r""" int main() { int a; a = 5; ; b = - - a; return a; }""") def test_struct_decl(self): self._assert_ctoc_correct(r""" typedef struct node_t { struct node_t* next; int data; } node; """) def test_krstyle(self): self._assert_ctoc_correct(r""" int main(argc, argv) int argc; char** argv; { return 0; } """) def test_switchcase(self): self._assert_ctoc_correct(r""" int main() { switch (myvar) { case 10: { k = 10; p = k + 1; break; } case 20: case 30: return 20; default: break; } } """) def test_nest_initializer_list(self): self._assert_ctoc_correct(r""" int main() { int i[1][1] = { { 1 } }; }""") def test_nest_named_initializer(self): self._assert_ctoc_correct(r"""struct test { int i; struct test_i_t { int k; } test_i; int j; }; struct test test_var = {.i = 0, .test_i = {.k = 1}, .j = 2}; """) def test_field_and_array_designators(self): # Issue #466: an identifier in brackets is an array index, not a field. self._assert_ctoc_correct(""" enum { x }; struct A { int x; }; struct A a = {.x = 1}; int b[] = {[x] = 2}; struct A c[] = {[x].x = 3}; """) def test_expr_list_in_initializer_list(self): self._assert_ctoc_correct(r""" int main() { int i[1] = { (1, 2) }; }""") def test_issue36(self): self._assert_ctoc_correct(r""" int main() { }""") def test_issue37(self): self._assert_ctoc_correct(r""" int main(void) { unsigned size; size = sizeof(size); return 0; }""") def test_issue66(self): # A non-existing body must not be generated # (previous valid behavior, still working) self._assert_ctoc_correct(r""" struct foo; """) # An empty body must be generated # (added behavior) self._assert_ctoc_correct(r""" struct foo {}; """) def test_issue83(self): self._assert_ctoc_correct(r""" void x(void) { int i = (9, k); } """) def test_issue84(self): self._assert_ctoc_correct(r""" void x(void) { for (int i = 0;;) i; } """) def test_issue246(self): self._assert_ctoc_correct(r""" int array[3] = {[0] = 0, [1] = 1, [1+1] = 2}; """) def test_noreturn(self): self._assert_ctoc_correct(r""" _Noreturn int x(void) { abort(); } """) def test_exprlist_with_semi(self): self._assert_ctoc_correct(r""" void x() { if (i < j) tmp = C[i], C[i] = C[j], C[j] = tmp; if (i <= j) i++, j--; } """) def test_exprlist_with_compound(self): self._assert_ctoc_correct(r""" void test(){ (sizeof (0), ({ if (0) ; else ; })); } """) def test_exprlist_with_subexprlist(self): self._assert_ctoc_correct(r""" void x() { (a = b, (b = c, c = a)); } """) def test_statement_expression_return(self): # A returned block needs the parentheses that make it an expression. self._assert_ctoc_correct("int f(void) { return ({ int x = 1; x; }); }") def test_statement_expression_subscript(self): # Subscript brackets do not replace statement-expression parentheses. self._assert_ctoc_correct("int f(int *a) { return a[({ 1; })]; }") def test_statement_expression_assignment(self): # GNU statement expressions can occur on either side of an assignment. self._assert_ctoc_correct("void f(int x) { ({ x; }) = ({ 2; }); }") def test_statement_expression_conditions(self): # The enclosing condition parentheses must surround the complete ({...}). self._assert_ctoc_correct(""" void f(int n) { if (({ n; })) n--; while (({ n > 0; })) n--; do { n++; } while (({ n < 0; })); switch (({ n; })) { case 0: break; } } """) def test_statement_expression_for_clauses(self): # All three for clauses are expression contexts, including the initializer. source = """ void f(void) { int i; for (({ i = 0; }); ({ i < 2; }); ({ i++; })) {} } """ self._assert_ctoc_correct(source) self._assert_ctoc_correct(source, reduce_parentheses=True) def test_statement_expression_sizeof_and_array_bound(self): # Both array bounds and sizeof operands need expression rendering. self._assert_ctoc_correct(""" void f(void) { int a[({ 3; })]; int size = sizeof(({ a[0]; })); } """) def test_comma_expression_contexts(self): # Bounds, assignment operands, and arguments need comma grouping; # conditions, subscripts, and return expressions allow unwrapped commas. generated = self._assert_ctoc_correct(""" int f(int x, int *p) { int a[(1, 2)]; x = (1, 2); f((1, 2), p); if (x, p[0]) x = 1; return p[x, 1], x; } """) self.assertIn("a[(1, 2)]", generated) self.assertIn("x = (1, 2);", generated) self.assertIn("f((1, 2), p);", generated) self.assertIn("if (x, p[0])", generated) self.assertIn("return p[x, 1], x;", generated) def test_comma_in_constant_expression_contexts(self): # These grammar positions require parentheses around comma expressions, # even though pycparser leaves constant-expression evaluation to callers. self._assert_ctoc_correct(""" void f(void) { _Static_assert((0, 1), "ok"); enum E { A = (1, 2) }; struct S { int bits : (1, 2); }; _Alignas((0, 8)) int x; int a[3] = { [(0, 1)] = 1 }; switch (x) { case (0, 1): break; } } """) def test_comma_operator_funcarg(self): self._assert_ctoc_correct(r""" void f(int x) { return x; } int main(void) { f((1, 2)); return 0; } """) def test_comma_op_in_ternary(self): self._assert_ctoc_correct(r""" void f() { (0, 0) ? (0, 0) : (0, 0); } """) def test_comma_op_assignment(self): self._assert_ctoc_correct(r""" void f() { i = (a, b, c); } """) def test_pragma(self): self._assert_ctoc_correct(r""" #pragma foo void f() { #pragma bar i = (a, b, c); if (d) #pragma qux j = e; if (d) #pragma qux #pragma quux j = e; } typedef struct s { #pragma baz } s; """) def test_pragma_operator_literals(self): literals = [ '""', '"foo"', r'"message(\"hello\")"', r'"message(\"C:\\\\tmp\")"', r'"foo\nbar"', 'L"foo"', 'u8"foo"', 'u"foo"', 'U"foo"', ] for literal in literals: with self.subTest(literal=literal): source = f"_Pragma(\n{literal}\n)\nint x;" generated = self._assert_ctoc_correct(source) self.assertEqual(generated, f"_Pragma({literal})\nint x;\n") def test_pragma_operator_contexts(self): self._assert_ctoc_correct(r""" #pragma foo _Pragma("bar") void f(void) { _Pragma("foo") int x = 0; if (x) _Pragma("bar") _Pragma("baz") x = 1; label: _Pragma("qux") x++; _Pragma("") } struct s { _Pragma("foo") int x; _Pragma("bar") }; union u { _Pragma("baz") int x; }; _Pragma("") #pragma """) def test_pragma_before_declaration_semicolon_issue_478(self): generated = self._assert_ctoc_correct("""struct knote; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wnullability-completeness" struct klist { struct knote *slh_first; } #pragma clang diagnostic pop ; """) self.assertEqual( generated, "struct knote;\n#pragma clang diagnostic push\n" '#pragma clang diagnostic ignored "-Wnullability-completeness"\n' "struct klist\n{\n struct knote *slh_first;\n};\n" "#pragma clang diagnostic pop\n", ) def test_pragma_before_local_declaration_semicolon(self): generated = self._assert_ctoc_correct("""void f(void) { struct S { int x; } a, *b = &a #pragma after ; }""") self.assertIn(" } a, *b = &a;\n #pragma after\n", generated) self.assertEqual(generated.count("struct S"), 1) def test_pragma_before_typedef_and_prototype_semicolons(self): generated = self._assert_ctoc_correct( 'typedef int T _Pragma("type"); T f(void)\n#pragma function\n;' ) self.assertEqual( generated, 'typedef int T;\n_Pragma("type")\nT f(void);\n#pragma function\n' ) def test_pragma_before_struct_member_semicolons(self): generated = self._assert_ctoc_correct("""struct S { int x : 3 #pragma field ; union { int y; } _Pragma("anonymous"); };""") self.assertIn(" int x : 3;\n #pragma field\n", generated) self.assertIn(' };\n _Pragma("anonymous")\n', generated) def test_pragma_before_for_declaration_semicolon(self): generated = self._assert_ctoc_correct("""void f(void) { for (int i = 0, j = 1 _Pragma("first") #pragma second ; i < j; ++i) {} }""") self.assertIn( 'for (int i = 0, j = 1\n _Pragma("first")\n #pragma second\n ; i < j; ++i)', generated, ) def test_pragma_before_knr_declaration_semicolon(self): generated = self._assert_ctoc_correct( 'int f(x, y) int x _Pragma("first"); int y\n#pragma second\n; { return x + y; }' ) self.assertIn('int x;\n_Pragma("first")\nint y;\n#pragma second\n{', generated) def test_c23_attributes_with_trailing_declaration_pragmas(self): parser = c_parser.CParser(dialect="c23") ast = parser.parse("""[[deprecated]] auto x = 1 _Pragma("global"); void f(void) { [[maybe_unused]] auto y = 2 _Pragma("local"); } struct S { [[deprecated]] int z _Pragma("member"); };""") generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn('[[deprecated]] auto x = 1;\n_Pragma("global")\n', generated) self.assertIn('[[maybe_unused]] auto y = 2;\n _Pragma("local")\n', generated) self.assertIn('[[deprecated]] int z;\n _Pragma("member")\n', generated) def test_compound_literal_statement(self): self._assert_ctoc_correct( "struct S { int x; }; void f(void) { (struct S){1}; }" ) def test_compound_literal(self): self._assert_ctoc_correct('char **foo = (char *[]){ "x", "y", "z" };') self._assert_ctoc_correct("int i = ++(int){ 1 };") self._assert_ctoc_correct("struct foo_s foo = (struct foo_s){ 1, 2 };") def test_c23_compound_literal_storage(self): parser = c_parser.CParser(dialect="c23") source = """ typedef int T; int *p = &(static T){1}; int value = (constexpr int){42}; int *array = (static int[]){1, 2}; struct S { int *values; } object = (static struct S){.values = (static int[]){1, 2}}; void f(void) { (register int){2}; (thread_local int){3}; (_Thread_local int){4}; (static thread_local int){}; (thread_local static int){}; (static constexpr const unsigned long){42}; } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("(static T){1}", generated) self.assertIn("(constexpr int){42}", generated) self.assertIn("(register int){2}", generated) self.assertIn("(thread_local int){3}", generated) self.assertIn("(_Thread_local int){4}", generated) self.assertIn("(static thread_local int){}", generated) self.assertIn("(thread_local static int){}", generated) self.assertIn("(static constexpr const unsigned long){42}", generated) def test_c23_compound_literal_postfix(self): parser = c_parser.CParser(dialect="c23") source = """ struct S { int value; } object; int callback(void); void f(void) { (static struct S){.value = 2}.value++; (static struct S){}.value; (static struct S *){&object}->value; (static int[]){1, 2}[0]; (static int[2]){}[0]; (static int (*)(void)){callback}(); (register int){1}++; (register int){2}--; sizeof (static int[3]){}; sizeof (static int[]){1, 2}[0]; (int)(constexpr unsigned int){42}; } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("((static struct S){.value = 2}).value++", generated) self.assertIn("((static int (*)(void)){callback})()", generated) self.assertIn("sizeof((static int [3]){})", generated) def test_legacy_compound_literal_postfix(self): self._assert_ctoc_correct(""" struct S { int value; }; int member = (struct S){1}.value; int empty_member = (struct S){}.value; int element = (int[]){1, 2}[0]; int empty_element = (int[2]){}[0]; int size = sizeof (int[]){1, 2}; """) def test_enum(self): self._assert_ctoc_correct(r""" enum e { a, b = 2, c = 3 }; """) self._assert_ctoc_correct(r""" enum f { g = 4, h, i }; """) def test_enum_leading_pragma(self): generated = self._assert_ctoc_correct("enum E {\n#pragma before\nA, B };") self.assertEqual(generated, "enum E\n{\n #pragma before\n A,\n B\n};\n") def test_enum_pragmas_around_comma(self): generated = self._assert_ctoc_correct( "enum E { A = 1\n#pragma before_comma\n,\n#pragma after_comma\nB };" ) self.assertEqual( generated, "enum E\n{\n A = 1,\n #pragma before_comma\n #pragma after_comma\n B\n};\n", ) def test_enum_trailing_pragmas(self): generated = self._assert_ctoc_correct("enum E { A\n#pragma after\n#pragma\n};") self.assertEqual(generated, "enum E\n{\n A\n #pragma after\n #pragma\n};\n") def test_enum_pragma_after_trailing_comma(self): generated = self._assert_ctoc_correct("enum E { A,\n#pragma after\n};") self.assertEqual(generated, "enum E\n{\n A\n #pragma after\n};\n") def test_enum_pragma_operators(self): generated = self._assert_ctoc_correct( 'enum E { _Pragma("before") A, _Pragma("between") B _Pragma("after") };' ) self.assertEqual( generated, 'enum E\n{\n _Pragma("before")\n A,\n _Pragma("between")\n B\n _Pragma("after")\n};\n', ) def test_c23_enum_pragmas(self): parser = c_parser.CParser(dialect="c23") source = """enum [[deprecated]] E : unsigned int { #pragma before A [[deprecated]] = 1, #pragma between B #pragma after };""" ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertEqual( generated, "enum [[deprecated]] E : unsigned int\n{\n" " #pragma before\n A [[deprecated]] = 1,\n" " #pragma between\n B\n #pragma after\n};\n", ) def test_enum_typedef(self): self._assert_ctoc_correct("typedef enum EnumName EnumTypedefName;") def test_c23_fixed_enums(self): parser = c_parser.CParser(dialect="c23") source = """ typedef unsigned char Byte; enum E : unsigned int; enum E : unsigned int { A = 1, B, }; enum : Byte { C } first, *second; typedef enum Named : unsigned short { D } Alias; enum Wide : unsigned long long { BIG = 1ULL << 40 }; enum E value = B; """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("enum E : unsigned int;", generated) self.assertIn("enum E : unsigned int\n", generated) self.assertIn("enum : Byte\n", generated) self.assertIn("typedef enum Named : unsigned short\n", generated) self.assertIn("BIG = 1ULL << 40", generated) self.assertIn("enum E value = B;", generated) def test_c23_fixed_enum_underlying_types(self): parser = c_parser.CParser(dialect="c23") source = """ enum Qualified : const volatile unsigned int { A }; enum Atomic : _Atomic(unsigned int) { B }; enum Type : typeof(unsigned char) { C }; enum Expr : typeof_unqual(A + 1) { D }; """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("enum Qualified : const volatile unsigned int\n", generated) self.assertIn("enum Atomic : _Atomic unsigned int\n", generated) self.assertIn("enum Type : typeof(unsigned char)\n", generated) self.assertIn("enum Expr : typeof_unqual(A + 1)\n", generated) def test_c23_fixed_enum_contexts(self): parser = c_parser.CParser(dialect="c23") source = """ enum E : unsigned int { A, WIDTH = 3 }; struct S { enum E : 3; enum E : WIDTH; enum E : sizeof(int); enum Member : unsigned char { B } member : 2; }; void f(enum Param : unsigned int { P } p) { enum Local : unsigned short; enum Local : unsigned short { L } local; (enum Cast : unsigned char { C })0; } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("enum E : 3;", generated) self.assertIn("enum E : WIDTH;", generated) self.assertIn("enum E : sizeof(int);", generated) self.assertIn("enum Local : unsigned short;", generated) def test_generate_struct_union_enum_exception(self): generator = c_generator.CGenerator() self.assertRaises( AssertionError, generator._generate_struct_union_enum, n=c_ast.Struct( name="TestStruct", decls=[], ), name="", ) def test_array_decl(self): self._assert_ctoc_correct("int g(const int a[const 20]){}") ast = parse_to_ast("const int a[const 20];") generator = c_generator.CGenerator() self.assertEqual(generator.visit(ast.ext[0].type), "const int [const 20]") self.assertEqual(generator.visit(ast.ext[0].type.type), "const int") def test_ptr_decl(self): src = "const int ** const x;" self._assert_ctoc_correct(src) ast = parse_to_ast(src) generator = c_generator.CGenerator() self.assertEqual(generator.visit(ast.ext[0].type), "const int ** const") self.assertEqual(generator.visit(ast.ext[0].type.type), "const int *") self.assertEqual(generator.visit(ast.ext[0].type.type.type), "const int") def test_atomic_qual(self): self._assert_ctoc_correct("_Atomic int x;") self._assert_ctoc_correct("_Atomic int* x;") self._assert_ctoc_correct("int* _Atomic x;") # _Atomic specifier gets turned into qualifier. s1 = "_Atomic(int) x;" c1 = self._run_c_to_c(s1) self.assertEqual(c1, "_Atomic int x;\n") self._assert_ctoc_correct(s1) s2 = "_Atomic(int*) x;" c2 = self._run_c_to_c(s2) self.assertEqual(c2, "int * _Atomic x;\n") self._assert_ctoc_correct(s2) s3 = "_Atomic(_Atomic(int)*) x;" c3 = self._run_c_to_c(s3) self.assertEqual(c3, "_Atomic int * _Atomic x;\n") self._assert_ctoc_correct(s3) s4 = "typedef _Atomic(int) atomic_int;" c4 = self._run_c_to_c(s4) self.assertEqual(c4, "typedef _Atomic int atomic_int;\n") self._assert_ctoc_correct(s4) s5 = "typedef _Atomic(_Atomic(_Atomic(int (*)(void)) *) *) t;" c5 = self._run_c_to_c(s5) self.assertEqual(c5, "typedef int (* _Atomic * _Atomic * _Atomic t)(void);\n") self._assert_ctoc_correct(s5) self._assert_ctoc_correct(r""" typedef struct node_t { _Atomic(void*) a; _Atomic(void) *b; _Atomic void *c; } node; """) def test_atomic_members_without_declarators(self): parser = c_parser.CParser(dialect="c23") source = """ struct s { _Atomic(int); const _Atomic(volatile int *); _Atomic(int) [[deprecated]]; }; """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue( compare_asts(ast, parser.parse(generated)), f"{source!r} != {generated!r}", ) def test_atomic_specifier_qualifiers(self): # Issue #433: qualifiers outside _Atomic(T) apply to T itself. cases = [ ("const _Atomic(int) x;", "const _Atomic int x;\n"), ("auto const _Atomic(int *) a;", "auto int * const _Atomic a;\n"), ( "const volatile _Atomic(int *) p;", "int * const volatile _Atomic p;\n", ), ("restrict _Atomic(int *) p;", "int * restrict _Atomic p;\n"), ("_Atomic(const int *) p;", "const int * _Atomic p;\n"), ("const _Atomic(const int *) p;", "const int * const _Atomic p;\n"), ("const _Atomic(int *) *p;", "int * const _Atomic *p;\n"), ( "const _Atomic(volatile _Atomic(int) *) p;", "volatile _Atomic int * const _Atomic p;\n", ), ( "typedef const _Atomic(int *) P;", "typedef int * const _Atomic P;\n", ), ( "_Atomic(int) a, b;", "_Atomic int a;\n_Atomic int b;\n", ), ( "const _Atomic(int *) a, *b;", "int * const _Atomic a;\nint * const _Atomic *b;\n", ), ] for src, expected in cases: with self.subTest(src=src): self.assertEqual(self._assert_ctoc_correct(src), expected) def test_atomic_type_names(self): self.assertEqual( self._assert_ctoc_correct("int n = sizeof(const _Atomic(int *));"), "int n = sizeof(int * const _Atomic);\n", ) for src in [ "void f(const _Atomic(int *) p, volatile _Atomic(int *));", "void f(const _Atomic(int *) *, volatile _Atomic(int *)[4]);", "int n = _Alignof(const _Atomic(int *));", "void f(void) { (const _Atomic(int *) *) 0; }", "int x = _Generic(0, const _Atomic(int *): 1, default: 2);", "const _Atomic(int (*)(const _Atomic(int *))) p;", ]: with self.subTest(src=src): self._assert_ctoc_correct(src) def test_nested_sizeof(self): src = "1" for _ in range(30): src = "sizeof(" + src + ")" src = "int x = " + src + ";" self._assert_ctoc_correct(src) def test_static_assert(self): self._assert_ctoc_correct('_Static_assert(sizeof(int) == sizeof(int), "123");') self._assert_ctoc_correct( 'int main() { _Static_assert(sizeof(int) == sizeof(int), "123"); } ' ) self._assert_ctoc_correct("_Static_assert(sizeof(int) == sizeof(int));") def test_c23_keywords(self): parser = c_parser.CParser(dialect="c23") source = """ alignas(16) thread_local bool flag = true; _Thread_local _Bool old_flag = 0; bool flags[2] = {true, false}; void *p = nullptr; static_assert(alignof(bool) == _Alignof(_Bool)); struct S { static_assert(true, "member"); bool value; }; bool f(bool x) { static_assert(!false); return x ? true : false; } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("thread_local _Alignas(16) bool flag = true;", generated) self.assertIn("void *p = nullptr;", generated) self.assertIn('_Static_assert(true, "member");', generated) def test_c23_ellipsis_only_parameter_lists(self): parser = c_parser.CParser(dialect="c23") source = """ void f(...); int definition(...) { return 0; } void (*callback)(...); void function_parameter(int (...)); void pointer_parameter(int (*)(...)); void (*converted)(...) = (void (*)(...))0; """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("void f(...);", generated) self.assertIn("int definition(...)", generated) self.assertIn("void (*callback)(...);", generated) self.assertIn("void function_parameter(int (...));", generated) self.assertIn("void pointer_parameter(int (*)(...));", generated) self.assertIn("(void (*)(...)) 0", generated) def test_c23_empty_initializers(self): parser = c_parser.CParser(dialect="c23") source = """ int scalar = {}; int array[3] = {}; struct S { int value; } object = {}; int literal = (int){}; int *pointer = (int[3]){}; """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("int scalar = {};", generated) self.assertIn("int array[3] = {};", generated) self.assertIn("(int){}", generated) self.assertIn("(int [3]){}", generated) def test_c23_labels_before_declarations_and_at_block_end(self): parser = c_parser.CParser(dialect="c23") source = """ void f(int x) { start: int y = 1; switch (x) { case 1: int z = 2; default: } switch (x) { default: int z = 2; case 1: } end: } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) def test_c23_unnamed_parameters_in_definition(self): parser = c_parser.CParser(dialect="c23") source = "int f(int, const int *, int (*)(int)) { return 0; }" ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("int f(int, const int *, int (*)(int))", generated) def test_c23_constexpr(self): parser = c_parser.CParser(dialect="c23") source = """ typedef int T; constexpr T limit = 16; int constexpr next = limit + 1; static constexpr double scale = 0.5; constexpr int values[] = {1, 2}; struct S { int x; }; constexpr struct S s = {.x = limit}; void f(void) { constexpr bool enabled = true; constexpr void *p = nullptr; constexpr const int local = next; } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("constexpr T limit = 16;", generated) self.assertIn("static constexpr double scale = 0.5;", generated) self.assertIn("constexpr const int local = next;", generated) def test_c23_auto(self): parser = c_parser.CParser(dialect="c23") source = """ typedef int T; auto count = 42; auto (parenthesized) = 1; static auto scale = 0.5; constexpr auto limit = 16; const auto fixed = 1; alignas(16) auto aligned = 0; void f(void) { auto value = (T){1}; auto pointer = &value; auto comma = (value, value + 1); auto _Atomic atomic = value; for (auto i = 0; i < limit; ++i) { auto copy = i; } } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("auto count = 42;", generated) self.assertIn("auto const fixed = 1;", generated) self.assertIn("auto _Alignas(16) aligned = 0;", generated) self.assertIn("for (auto i = 0;", generated) self.assertNotIn("auto auto", generated) def test_c23_typeof(self): parser = c_parser.CParser(dialect="c23") source = """ typedef typeof(1) T; typeof_unqual(const int *) pointer; typeof(int (*)(int)) callback; typeof(int [3]) array; typeof(typeof_unqual(const int)) nested; typeof(_Atomic(int)) inner_atomic; _Atomic(typeof(int)) outer_atomic; const typeof_unqual(volatile int) qualified; struct S { typeof(T) member; }; typeof(int) f(typeof(int) arg, typeof_unqual(const int)) { typeof(T) before; typeof(int) T = 1; typeof(T) after; typeof(arg, f(arg, 2)) comma; typeof(({ int x = 1; x; })) statement_expression; auto cast = (typeof(arg))2; auto literal = (typeof(int)){3}; auto size = sizeof(typeof(int)); auto generic = _Generic(arg, typeof(int): 1, default: 0); for (typeof(arg) i = 0; i < 3; ++i) {} return arg; } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("typeof_unqual(const int *) pointer;", generated) self.assertIn("typeof(int (*)(int)) callback;", generated) self.assertIn("typeof(typeof_unqual(const int)) nested;", generated) self.assertIn("typeof(_Atomic int) inner_atomic;", generated) self.assertIn("_Atomic typeof(int) outer_atomic;", generated) def test_c23_bitint(self): parser = c_parser.CParser(dialect="c23") source = """ constexpr int WIDTH = 17; typedef unsigned _BitInt(WIDTH) T; _BitInt(17) plain; signed _BitInt(17) explicit_signed; _BitInt(17) unsigned reversed; const unsigned _BitInt(8 * sizeof(int)) value = 1, *pointer, array[3]; _BitInt(WIDTH > 8 ? WIDTH : 8) conditional; _Atomic(unsigned _BitInt(17)) atomic; typeof_unqual(const _BitInt(17)) unqualified; struct S { unsigned _BitInt(3) bits : 3; }; _BitInt(17) (*callback)(unsigned _BitInt(8)); _BitInt(17) f(_BitInt(8) arg) { auto cast = (unsigned _BitInt(17))arg; auto literal = (_BitInt(17)){3}; auto size = sizeof(_BitInt(17)); auto selection = _Generic(arg, _BitInt(8): 1, default: 0); for (unsigned _BitInt(8) i = 0, j = 1; i < j; ++i) {} return arg; } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("_BitInt(17) plain;", generated) self.assertIn("signed _BitInt(17) explicit_signed;", generated) self.assertIn("unsigned _BitInt(17) reversed;", generated) self.assertIn("_Atomic unsigned _BitInt(17) atomic;", generated) self.assertIn("for (unsigned _BitInt(8) i = 0, j = 1;", generated) def test_digit_separators(self): generated = self._assert_ctoc_correct(""" unsigned long long count = 1'000'000ULL; int octal = 0'7'7; int hex = 0xAB'CD; int binary = 0b1010'0101; float fraction = 1'234.56'78F; double exponent = 1'2e-3'4; long double hex_float = 0xA'B.C'Dp+1'0L; int values[1'000]; void f(void) { int sum = 1'000 + 2'000; char quote = '\\''; char *text = "1'000"; } """) self.assertIn("unsigned long long count = 1'000'000ULL;", generated) self.assertIn("float fraction = 1'234.56'78F;", generated) self.assertIn("long double hex_float = 0xA'B.C'Dp+1'0L;", generated) self.assertIn("int values[1'000];", generated) def test_c23_digit_separators(self): parser = c_parser.CParser(dialect="c23") source = """ auto count = 1'000wb; auto bits = 0b1010'0101UWB; _Decimal32 price = 1'234.56'78df; _Decimal64 scale = 1'0e-1'0DD; _Decimal128 fraction = .1'25DL; """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("auto count = 1'000wb;", generated) self.assertIn("auto bits = 0b1010'0101UWB;", generated) self.assertIn("_Decimal32 price = 1'234.56'78df;", generated) def test_c23_bitint_literals(self): parser = c_parser.CParser(dialect="c23") source = """ constexpr auto count = 42wb; unsigned _BitInt(8) zero = 0uwb; _BitInt(17) value = 42WB; auto octal = 077uWB; auto hex = 0xffWBu; auto binary = 0B101wbU; auto huge = 340282366920938463463374607431768211456wb; void f(void) { auto negative = -3wb; auto sum = 1Uwb + 2WBU; static_assert(3uwb > 0wb); for (auto i = 0wb; i < 3WB; ++i) {} } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("constexpr auto count = 42wb;", generated) self.assertIn("unsigned _BitInt(8) zero = 0uwb;", generated) self.assertIn("_BitInt(17) value = 42WB;", generated) self.assertIn("auto octal = 077uWB;", generated) self.assertIn("auto hex = 0xffWBu;", generated) self.assertIn("auto binary = 0B101wbU;", generated) def test_c23_decimal_float(self): parser = c_parser.CParser(dialect="c23") source = """ typedef _Decimal64 Money; constexpr _Decimal32 price = 1.25df; const _Decimal64 total = 100.00DD; _Decimal128 precise = .1dl; _Decimal32 values[] = {1.DF, 2e-1df}; _Decimal64 *pointer, array[2]; _Atomic(_Decimal32) atomic; typeof_unqual(const _Decimal128) unqualified; struct S { _Decimal64 amount; }; _Decimal128 f(_Decimal32 input) { auto sum = 1.0df + 2.0DF; Money result = (_Decimal64)input + 1e+2dd; auto literal = (_Decimal128){3.00DL}; auto selection = _Generic(input, _Decimal32: 1, default: 0); auto size = sizeof(_Decimal64); return 0.5DL; } """ ast = parser.parse(source) generated = c_generator.CGenerator().visit(ast) self.assertTrue(compare_asts(ast, parser.parse(generated))) self.assertIn("constexpr _Decimal32 price = 1.25df;", generated) self.assertIn("const _Decimal64 total = 100.00DD;", generated) self.assertIn("_Decimal128 precise = .1dl;", generated) self.assertIn("_Decimal32 values[] = {1.DF, 2e-1df};", generated) self.assertIn("_Atomic _Decimal32 atomic;", generated) def test_static_assert_semicolons(self): self.assertEqual( self._assert_ctoc_correct('_Static_assert(1, "file");'), '_Static_assert(1, "file");\n', ) self.assertEqual( self._assert_ctoc_correct( 'void f(void) { _Static_assert(1, "block"); _Static_assert(2); }' ), 'void f(void)\n{\n _Static_assert(1, "block");\n _Static_assert(2);\n}\n\n', ) def test_static_assert_declaration_contexts(self): src = """ _Static_assert(_Generic(0, int: 1, default: 0), "file"); struct S { _Static_assert(1, "before"); int x; _Static_assert(1, "after"); union { int y; _Static_assert(1, "nested"); } member; }; union U { _Static_assert(1); int x; }; void f(void) { if (1) { _Static_assert(1, "block"); } for (_Static_assert(1, "init"); ; ) { break; } for (_Static_assert(1); ; ) { break; } switch (0) { case 0:; _Static_assert(1, "case"); break; } } """ for reduce_parentheses in (False, True): with self.subTest(reduce_parentheses=reduce_parentheses): self._assert_ctoc_correct(src, reduce_parentheses=reduce_parentheses) def test_static_assert_message_literals(self): for prefix in ("", "L", "u8", "u", "U"): with self.subTest(prefix=prefix): self.assertEqual( self._assert_ctoc_correct( f'_Static_assert(1, "hello" {prefix}" world");' ), f'_Static_assert(1, {prefix}"hello world");\n', ) def test_reduce_parentheses_logical_not(self): # Issue #425: keep the grouping of ||, but omit parentheses around !. src = "void f(void) { if (a && !b && (!c || d)) {} }" generated = self._assert_ctoc_correct(src, reduce_parentheses=True) self.assertIn("if (a && !b && (!c || d))", generated) def test_reduce_parentheses_unary_operands(self): operands = ( "!a", "~a", "+a", "-a", "*p", "&a", "++a", "--a", "a++", "a--", "sizeof(a)", "sizeof(int)", "_Alignof(int)", ) for operand in operands: for left, right in ((operand, "b"), ("b", operand)): with self.subTest(left=left, right=right): src = f"int x = {left} + {right};" generated = self._assert_ctoc_correct(src, reduce_parentheses=True) self.assertEqual(generated, src + "\n") default_left = f"({left})" if left == operand else left default_right = f"({right})" if right == operand else right self.assertEqual( self._run_c_to_c(src), f"int x = {default_left} + {default_right};\n", ) def test_reduce_parentheses_unary_grouping(self): snippets = ( "int x = !(a && b) && c;", "int x = ~(a | b) & c;", "int x = -(a + b) * c;", "int x = a - -b;", "int x = a & &b;", "int x = -(-a);", "int x = +(+a);", "int x = (*p)++;", "int x = (*p)--;", "int x = (*p)[i];", "int x = (*p).field;", "int x = (*fp)();", ) for src in snippets: with self.subTest(src=src): self._assert_ctoc_correct(src) generated = self._assert_ctoc_correct(src, reduce_parentheses=True) self.assertEqual(generated, src + "\n") def test_reduce_parentheses_binaryops(self): c1 = "int x = a + b + c + d;" self.assertEqual(self._run_c_to_c(c1), "int x = ((a + b) + c) + d;\n") self.assertEqual( self._run_c_to_c(c1, reduce_parentheses=True), "int x = a + b + c + d;\n" ) # codes with minimum number of (necessary) parenthesis: test_snippets = [ "int x = a*b*c*d;", "int x = a+b*c*d;", "int x = a*b+c*d;", "int x = a*b*c+d;", "int x = (a+b)*c*d;", "int x = (a+b)*(c+d);", "int x = (a+b)/(c-d);", "int x = a+b-c-d;", "int x = a+(b-c)-d;", ] for src in test_snippets: src2 = self._assert_ctoc_correct(src, reduce_parentheses=True) self.assertTrue( src2.count("(") == src.count("("), msg=f"{src2!r} did not have minimum number of parenthesis, should be like {src!r}.", ) class TestCasttoC(unittest.TestCase): def _find_file(self, name): test_dir = os.path.dirname(__file__) name = os.path.join(test_dir, "c_files", name) assert os.path.exists(name) return name def test_to_type(self): src = "int *x;" generator = c_generator.CGenerator() test_fun = c_ast.FuncCall(c_ast.ID("test_fun"), c_ast.ExprList([])) ast1 = parse_to_ast(src) int_ptr_type = ast1.ext[0].type int_type = int_ptr_type.type self.assertEqual( generator.visit(c_ast.Cast(int_ptr_type, test_fun)), "(int *) test_fun()" ) self.assertEqual( generator.visit(c_ast.Cast(int_type, test_fun)), "(int) test_fun()" ) @unittest.skipUnless(cpp_supported(), "cpp only works on Unix") def test_to_type_with_cpp(self): generator = c_generator.CGenerator() test_fun = c_ast.FuncCall(c_ast.ID("test_fun"), c_ast.ExprList([])) memmgr_path = self._find_file("memmgr.h") ast2 = parse_file( memmgr_path, use_cpp=True, cpp_path=cpp_path(), cpp_args=cpp_args() ) void_ptr_type = ast2.ext[-3].type.type void_type = void_ptr_type.type self.assertEqual( generator.visit(c_ast.Cast(void_ptr_type, test_fun)), "(void *) test_fun()" ) self.assertEqual( generator.visit(c_ast.Cast(void_type, test_fun)), "(void) test_fun()" ) def test_nested_else_if_line_breaks(self): generator = c_generator.CGenerator() test_ast1 = c_ast.If(None, None, None) test_ast2 = c_ast.If(None, None, c_ast.If(None, None, None)) test_ast3 = c_ast.If( None, None, c_ast.If(None, None, c_ast.If(None, None, None)) ) test_ast4 = c_ast.If( None, c_ast.Compound([]), c_ast.If( None, c_ast.Compound([]), c_ast.If(None, c_ast.Compound([]), None) ), ) self.assertEqual(generator.visit(test_ast1), "if ()\n \n") self.assertEqual(generator.visit(test_ast2), "if ()\n \nelse\n if ()\n \n") self.assertEqual( generator.visit(test_ast3), "if ()\n \nelse\n if ()\n \nelse\n if ()\n \n", ) self.assertEqual( generator.visit(test_ast4), "if ()\n{\n}\nelse\n if ()\n{\n}\nelse\n if ()\n{\n}\n", ) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1792585380.210408 pycparser-3.12/tests/test_c_lexer.py0000664000175000017500000007324115266127244017203 0ustar00elibenelibenimport re import sys import unittest sys.path.insert(0, "..") from pycparser.c_lexer import CLexer, Token def require_token(tok: Token | None) -> Token: # In tests we know token() should produce a token here; this helper asserts # that and narrows Optional[Token] to Token, avoiding repeated casts/guards. assert tok is not None return tok def token_list(clex): return list(iter(clex.token, None)) def token_types(clex): return [i.type for i in token_list(clex)] class TestCLexerNoErrors(unittest.TestCase): """Test lexing of strings that are not supposed to cause errors. Therefore, the error_func passed to the lexer raises an exception. """ def error_func(self, msg, line, column): self.fail(msg) def setUp(self): self.clex = CLexer(self.error_func) def assertTokensTypes(self, str, types): self.clex.input(str) self.assertEqual(token_types(self.clex), types) def test_trivial_tokens(self): self.assertTokensTypes("1", ["INT_CONST_DEC"]) self.assertTokensTypes("-", ["MINUS"]) self.assertTokensTypes("volatile", ["VOLATILE"]) self.assertTokensTypes("...", ["ELLIPSIS"]) self.assertTokensTypes("++", ["PLUSPLUS"]) self.assertTokensTypes("case int", ["CASE", "INT"]) self.assertTokensTypes("caseint", ["ID"]) self.assertTokensTypes("$dollar cent$", ["ID", "ID"]) self.assertTokensTypes("i ^= 1;", ["ID", "XOREQUAL", "INT_CONST_DEC", "SEMI"]) def test_form_feed_and_vertical_tab_whitespace(self): self.clex.input("\fint\vx;\n \t\f\vy;") self.assertEqual( [(t.type, t.value, t.lineno, t.column) for t in token_list(self.clex)], [ ("INT", "int", 1, 2), ("ID", "x", 1, 6), ("SEMI", ";", 1, 7), ("ID", "y", 2, 5), ("SEMI", ";", 2, 6), ], ) self.assertTokensTypes(" \t\f\v", []) def test_form_feed_and_vertical_tab_in_literals(self): self.clex.input("\"a\fb\" '\v'") self.assertEqual( [(t.type, t.value, t.lineno, t.column) for t in token_list(self.clex)], [ ("STRING_LITERAL", '"a\fb"', 1, 1), ("CHAR_CONST", "'\v'", 1, 7), ], ) def test_typedef_names_are_identifiers(self): self.assertTokensTypes( "typedef int T; T value;", ["TYPEDEF", "INT", "ID", "SEMI", "ID", "ID", "SEMI"], ) def test_token_filenames(self): self.clex.input( 'int a;\n#line 7 "included.h"\n#pragma once\n#line 1 ""\nint b;', filename="main.c", ) tokens = token_list(self.clex) self.assertEqual( [tok.filename for tok in tokens], ["main.c"] * 3 + ["included.h"] * 2 + [""] * 3, ) self.assertEqual(tokens[3].type, "PPPRAGMA") self.assertEqual(tokens[4].type, "PPPRAGMASTR") self.assertIs(tokens[3].filename, tokens[4].filename) self.clex.input("int c;", filename="next.c") self.assertEqual(require_token(self.clex.token()).filename, "next.c") self.assertEqual(tokens[0].filename, "main.c") def test_integer_constants(self): self.assertTokensTypes("12", ["INT_CONST_DEC"]) self.assertTokensTypes("12u", ["INT_CONST_DEC"]) self.assertTokensTypes("12l", ["INT_CONST_DEC"]) self.assertTokensTypes("199872Ul", ["INT_CONST_DEC"]) self.assertTokensTypes("199872lU", ["INT_CONST_DEC"]) self.assertTokensTypes("199872LL", ["INT_CONST_DEC"]) self.assertTokensTypes("199872ull", ["INT_CONST_DEC"]) self.assertTokensTypes("199872llu", ["INT_CONST_DEC"]) self.assertTokensTypes("1009843200000uLL", ["INT_CONST_DEC"]) self.assertTokensTypes("1009843200000LLu", ["INT_CONST_DEC"]) self.assertTokensTypes("077", ["INT_CONST_OCT"]) self.assertTokensTypes("0123456L", ["INT_CONST_OCT"]) self.assertTokensTypes("0xf7", ["INT_CONST_HEX"]) self.assertTokensTypes("0b110", ["INT_CONST_BIN"]) self.assertTokensTypes("0x01202AAbbf7Ul", ["INT_CONST_HEX"]) self.assertTokensTypes("'12'", ["INT_CONST_CHAR"]) self.assertTokensTypes("'123'", ["INT_CONST_CHAR"]) self.assertTokensTypes("'1AB4'", ["INT_CONST_CHAR"]) self.assertTokensTypes(r"'1A\n4'", ["INT_CONST_CHAR"]) # no 0 before x, so ID catches it self.assertTokensTypes("xf7", ["ID"]) # - is MINUS, the rest a constnant self.assertTokensTypes("-1", ["MINUS", "INT_CONST_DEC"]) def test_integer_digit_separators(self): self.assertTokensTypes("1'000'000", ["INT_CONST_DEC"]) self.assertTokensTypes("0'7'7", ["INT_CONST_OCT"]) self.assertTokensTypes("0xAB'CD", ["INT_CONST_HEX"]) self.assertTokensTypes("0B1010'0101", ["INT_CONST_BIN"]) self.assertTokensTypes("1'000uLL", ["INT_CONST_DEC"]) self.assertTokensTypes("0XFF'FFwbU", ["INT_CONST_HEX"]) self.clex.input("1'000+2'000\n0xAB'CD") self.assertEqual( token_list(self.clex), [ Token("INT_CONST_DEC", "1'000", 1, 1, filename=""), Token("PLUS", "+", 1, 6, filename=""), Token("INT_CONST_DEC", "2'000", 1, 7, filename=""), Token("INT_CONST_HEX", "0xAB'CD", 2, 1, filename=""), ], ) def test_floating_digit_separators(self): self.assertTokensTypes("1'234.56'78", ["FLOAT_CONST"]) self.assertTokensTypes(".1'25", ["FLOAT_CONST"]) self.assertTokensTypes("1'000.", ["FLOAT_CONST"]) self.assertTokensTypes("1'2e+3'4", ["FLOAT_CONST"]) self.assertTokensTypes("0'8.0", ["FLOAT_CONST"]) self.assertTokensTypes("0xAB'CD.EF'01p+1'0", ["HEX_FLOAT_CONST"]) self.assertTokensTypes("0x.A'Bp-1'0", ["HEX_FLOAT_CONST"]) self.assertTokensTypes("0xA'B.p1'0", ["HEX_FLOAT_CONST"]) self.assertTokensTypes("0xA'Bp1'0", ["HEX_FLOAT_CONST"]) self.clex.input("1'2.3'4e-5'6DF") self.assertEqual( token_list(self.clex), [ Token("FLOAT_CONST", "1'2.3'4e-5'6DF", 1, 1, filename=""), ], ) def test_digit_separators_and_quotes(self): self.clex.input("'1'2 1'2 \"1'2\"") self.assertEqual( token_list(self.clex), [ Token("CHAR_CONST", "'1'", 1, 1, filename=""), Token("INT_CONST_DEC", "2", 1, 4, filename=""), Token("INT_CONST_DEC", "1'2", 1, 6, filename=""), Token("STRING_LITERAL", '"1\'2"', 1, 10, filename=""), ], ) def test_line_directive_digit_separators(self): self.clex.input('#line 1\'000 "file.c"\nvalue') self.assertEqual( token_list(self.clex), [Token("ID", "value", 1000, 1, filename="file.c")] ) self.assertEqual(self.clex.filename, "file.c") self.clex.input("#line 0'010\nvalue") self.assertEqual( token_list(self.clex), [Token("ID", "value", 10, 1, filename="")] ) def test_bitint_constants(self): # Numeric regexes are shared, so even the legacy lexer recognizes # these suffixes. The parser enforces C23. self.assertTokensTypes("42wb", ["INT_CONST_DEC"]) self.assertTokensTypes("42WB", ["INT_CONST_DEC"]) self.assertTokensTypes("42uwb", ["INT_CONST_DEC"]) self.assertTokensTypes("42uWB", ["INT_CONST_DEC"]) self.assertTokensTypes("42Uwb", ["INT_CONST_DEC"]) self.assertTokensTypes("42UWB", ["INT_CONST_DEC"]) self.assertTokensTypes("42wbu", ["INT_CONST_DEC"]) self.assertTokensTypes("42wbU", ["INT_CONST_DEC"]) self.assertTokensTypes("42WBu", ["INT_CONST_DEC"]) self.assertTokensTypes("42WBU", ["INT_CONST_DEC"]) self.assertTokensTypes("0wb", ["INT_CONST_OCT"]) self.assertTokensTypes("077uwb", ["INT_CONST_OCT"]) self.assertTokensTypes("0XffWB", ["INT_CONST_HEX"]) self.assertTokensTypes("0b101wbu", ["INT_CONST_BIN"]) self.clex.input("42wb+0xffUWB") self.assertEqual( token_list(self.clex), [ Token("INT_CONST_DEC", "42wb", 1, 1, filename=""), Token("PLUS", "+", 1, 5, filename=""), Token("INT_CONST_HEX", "0xffUWB", 1, 6, filename=""), ], ) def test_special_names(self): self.assertTokensTypes("sizeof offsetof", ["SIZEOF", "OFFSETOF"]) def test_new_keywords(self): self.assertTokensTypes("_Bool", ["_BOOL"]) self.assertTokensTypes("_Atomic", ["_ATOMIC"]) self.assertTokensTypes("_Alignas _Alignof", ["_ALIGNAS", "_ALIGNOF"]) self.assertTokensTypes("_Generic", ["_GENERIC"]) self.assertTokensTypes("_Generic_value _generic", ["ID", "ID"]) def test_c23_keywords(self): source = ( "bool alignas alignof static_assert thread_local true false nullptr " "constexpr typeof typeof_unqual _BitInt _Decimal32 _Decimal64 " "_Decimal128 _Imaginary bool_value True nullptr_t" ) c23 = CLexer(self.error_func, dialect="c23") expected = [ "_BOOL", "_ALIGNAS", "_ALIGNOF", "_STATIC_ASSERT", "_THREAD_LOCAL", "BOOL_CONST", "BOOL_CONST", "NULLPTR", "CONSTEXPR", "TYPEOF", "TYPEOF_UNQUAL", "_BITINT", "_DECIMAL32", "_DECIMAL64", "_DECIMAL128", "_IMAGINARY", "ID", "ID", "ID", ] # input() must preserve the dialect, and selecting it must not affect # another lexer's keyword map. for _ in range(2): self.assertTokensTypes(source, ["ID"] * len(source.split())) c23.input(source) tokens = token_list(c23) self.assertEqual([tok.type for tok in tokens], expected) self.assertEqual([tok.value for tok in tokens], source.split()) def test_invalid_dialect(self): with self.assertRaisesRegex(ValueError, "Unknown dialect"): CLexer( self.error_func, dialect="c99", # ty: ignore[invalid-argument-type] ) def test_floating_constants(self): self.assertTokensTypes("1.5f", ["FLOAT_CONST"]) self.assertTokensTypes("01.5", ["FLOAT_CONST"]) self.assertTokensTypes(".15L", ["FLOAT_CONST"]) self.assertTokensTypes("0.", ["FLOAT_CONST"]) # but just a period is a period self.assertTokensTypes(".", ["PERIOD"]) self.assertTokensTypes("3.3e-3", ["FLOAT_CONST"]) self.assertTokensTypes(".7e25L", ["FLOAT_CONST"]) self.assertTokensTypes("6.e+125f", ["FLOAT_CONST"]) self.assertTokensTypes("666e666", ["FLOAT_CONST"]) self.assertTokensTypes("00666e+3", ["FLOAT_CONST"]) # but this is a hex integer + 3 self.assertTokensTypes("0x0666e+3", ["INT_CONST_HEX", "PLUS", "INT_CONST_DEC"]) def test_c23_decimal_floating_constants(self): c23 = CLexer(self.error_func, dialect="c23") c23.input("1.25df\n2.50dd\n.3dl\n4e+2DF\n5e-1DD\n6.DL") self.assertEqual( token_list(c23), [ Token("FLOAT_CONST", "1.25df", 1, 1, filename=""), Token("FLOAT_CONST", "2.50dd", 2, 1, filename=""), Token("FLOAT_CONST", ".3dl", 3, 1, filename=""), Token("FLOAT_CONST", "4e+2DF", 4, 1, filename=""), Token("FLOAT_CONST", "5e-1DD", 5, 1, filename=""), Token("FLOAT_CONST", "6.DL", 6, 1, filename=""), ], ) c23.input("1.25df+2.50dd") self.assertEqual( token_list(c23), [ Token("FLOAT_CONST", "1.25df", 1, 1, filename=""), Token("PLUS", "+", 1, 7, filename=""), Token("FLOAT_CONST", "2.50dd", 1, 8, filename=""), ], ) def test_decimal_literals_in_legacy_lexer(self): # Literal recognition is shared; the parser enforces the dialect. self.clex.input("1.25df 2.dd 3e1DL") self.assertEqual( token_list(self.clex), [ Token("FLOAT_CONST", "1.25df", 1, 1, filename=""), Token("FLOAT_CONST", "2.dd", 1, 8, filename=""), Token("FLOAT_CONST", "3e1DL", 1, 13, filename=""), ], ) self.clex.input(".5DD") self.assertEqual( token_list(self.clex), [Token("FLOAT_CONST", ".5DD", 1, 1, filename="")] ) def test_c23_binary_floating_constants(self): c23 = CLexer(self.error_func, dialect="c23") c23.input("1.5\n1.5f\n.5L\n0x1.fp+2F\n0x1p0dd") self.assertEqual( token_list(c23), [ Token("FLOAT_CONST", "1.5", 1, 1, filename=""), Token("FLOAT_CONST", "1.5f", 2, 1, filename=""), Token("FLOAT_CONST", ".5L", 3, 1, filename=""), Token("HEX_FLOAT_CONST", "0x1.fp+2F", 4, 1, filename=""), Token("HEX_FLOAT_CONST", "0x1p0", 5, 1, filename=""), Token("ID", "dd", 5, 6, filename=""), ], ) def test_hexadecimal_floating_constants(self): self.assertTokensTypes("0xDE.488641p0", ["HEX_FLOAT_CONST"]) self.assertTokensTypes("0x.488641p0", ["HEX_FLOAT_CONST"]) self.assertTokensTypes("0X12.P0", ["HEX_FLOAT_CONST"]) def test_char_constants(self): self.assertTokensTypes(r"""'x'""", ["CHAR_CONST"]) self.assertTokensTypes(r"""L'x'""", ["WCHAR_CONST"]) self.assertTokensTypes(r"""u8'x'""", ["U8CHAR_CONST"]) self.assertTokensTypes(r"""u'x'""", ["U16CHAR_CONST"]) self.assertTokensTypes(r"""U'x'""", ["U32CHAR_CONST"]) self.assertTokensTypes(r"""'\t'""", ["CHAR_CONST"]) self.assertTokensTypes(r"""'\''""", ["CHAR_CONST"]) self.assertTokensTypes(r"""'\?'""", ["CHAR_CONST"]) self.assertTokensTypes(r"""'\0'""", ["CHAR_CONST"]) self.assertTokensTypes(r"""'\012'""", ["CHAR_CONST"]) self.assertTokensTypes(r"""'\x2f'""", ["CHAR_CONST"]) self.assertTokensTypes(r"""'\x2f12'""", ["CHAR_CONST"]) self.assertTokensTypes(r"""L'\xaf'""", ["WCHAR_CONST"]) def test_unicode_char_constants(self): for prefix, token_type in ( ("", "CHAR_CONST"), ("L", "WCHAR_CONST"), ("u8", "U8CHAR_CONST"), ("u", "U16CHAR_CONST"), ("U", "U32CHAR_CONST"), ): for escape in (r"\u00e9", r"\u03A9", r"\U000000E9", r"\U0001F600"): literal = f"{prefix}'{escape}'" with self.subTest(literal=literal): self.clex.input(f"\n {literal};") self.assertEqual( token_list(self.clex), [ Token(token_type, literal, 2, 3, filename=""), Token("SEMI", ";", 2, 3 + len(literal), filename=""), ], ) def test_unicode_multicharacter_constants(self): # Unicode escapes have fixed width: a following hex digit is a separate # character, unlike the variable-width hexadecimal escape \x. for literal in ( r"'\u00e9a'", r"'\U0001F6000'", r"'a\u00e9'", r"'\u00e9\U0001F600'", r"'\u00e9\u00f1\u03a9\u03b1'", ): with self.subTest(literal=literal): self.assertTokensTypes(literal, ["INT_CONST_CHAR"]) # Keep the lexer's existing permissiveness for other escape spellings. self.assertTokensTypes( r"'\u' '\U' '\u123'", ["CHAR_CONST", "CHAR_CONST", "INT_CONST_CHAR"] ) def test_string_literal(self): self.assertTokensTypes('"a string"', ["STRING_LITERAL"]) self.assertTokensTypes('L"ing"', ["WSTRING_LITERAL"]) self.assertTokensTypes('u8"ing"', ["U8STRING_LITERAL"]) self.assertTokensTypes('u"ing"', ["U16STRING_LITERAL"]) self.assertTokensTypes('U"ing"', ["U32STRING_LITERAL"]) self.assertTokensTypes('"i am a string too \t"', ["STRING_LITERAL"]) self.assertTokensTypes( r'''"esc\ape \"\'\? \0234 chars \rule"''', ["STRING_LITERAL"] ) self.assertTokensTypes( r'''"hello 'joe' wanna give it a \"go\"?"''', ["STRING_LITERAL"] ) self.assertTokensTypes( '"\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123"', ["STRING_LITERAL"], ) # Note: a-zA-Z and '.-~^_!=&;,' are allowed as escape chars to support #line # directives with Windows paths as filenames (..\..\dir\file) self.assertTokensTypes(r'"\x"', ["STRING_LITERAL"]) self.assertTokensTypes( r'"\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z\A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z"', ["STRING_LITERAL"], ) self.assertTokensTypes(r'"C:\x\fa\x1e\xited"', ["STRING_LITERAL"]) # The lexer is permissive and allows decimal escapes (not just octal) self.assertTokensTypes(r'"jx\9"', ["STRING_LITERAL"]) self.assertTokensTypes(r'"fo\9999999"', ["STRING_LITERAL"]) def test_mess(self): self.assertTokensTypes( r"[{}]()", ["LBRACKET", "LBRACE", "RBRACE", "RBRACKET", "LPAREN", "RPAREN"] ) self.assertTokensTypes( r"()||!C&~Z?J", [ "LPAREN", "RPAREN", "LOR", "LNOT", "ID", "AND", "NOT", "ID", "CONDOP", "ID", ], ) self.assertTokensTypes( r"+-*/%|||&&&^><>=<===!=", [ "PLUS", "MINUS", "TIMES", "DIVIDE", "MOD", "LOR", "OR", "LAND", "AND", "XOR", "GT", "LT", "GE", "LE", "EQ", "NE", ], ) self.assertTokensTypes( r"++--->?.,;:", [ "PLUSPLUS", "MINUSMINUS", "ARROW", "CONDOP", "PERIOD", "COMMA", "SEMI", "COLON", ], ) def test_exprs(self): self.assertTokensTypes("bb-cc", ["ID", "MINUS", "ID"]) self.assertTokensTypes("foo & 0xFF", ["ID", "AND", "INT_CONST_HEX"]) self.assertTokensTypes( "(2+k) * 62", [ "LPAREN", "INT_CONST_DEC", "PLUS", "ID", "RPAREN", "TIMES", "INT_CONST_DEC", ], ) self.assertTokensTypes("x | y >> z", ["ID", "OR", "ID", "RSHIFT", "ID"]) self.assertTokensTypes( "x <<= z << 5", ["ID", "LSHIFTEQUAL", "ID", "LSHIFT", "INT_CONST_DEC"] ) self.assertTokensTypes( "x = y > 0 ? y : -6", [ "ID", "EQUALS", "ID", "GT", "INT_CONST_OCT", "CONDOP", "ID", "COLON", "MINUS", "INT_CONST_DEC", ], ) self.assertTokensTypes("a+++b", ["ID", "PLUSPLUS", "PLUS", "ID"]) def test_statements(self): self.assertTokensTypes( "for (int i = 0; i < n; ++i)", [ "FOR", "LPAREN", "INT", "ID", "EQUALS", "INT_CONST_OCT", "SEMI", "ID", "LT", "ID", "SEMI", "PLUSPLUS", "ID", "RPAREN", ], ) self.assertTokensTypes( "self: goto self;", ["ID", "COLON", "GOTO", "ID", "SEMI"] ) self.assertTokensTypes( """ switch (typ) { case TYPE_ID: m = 5; break; default: m = 8; }""", [ "SWITCH", "LPAREN", "ID", "RPAREN", "LBRACE", "CASE", "ID", "COLON", "ID", "EQUALS", "INT_CONST_DEC", "SEMI", "BREAK", "SEMI", "DEFAULT", "COLON", "ID", "EQUALS", "INT_CONST_DEC", "SEMI", "RBRACE", ], ) def test_preprocessor_line(self): self.assertTokensTypes("#abracadabra", ["PPHASH", "ID"]) str = r""" 546 #line 66 "kwas\df.h" id 4 dsf # 9 armo #line 10 "..\~..\test.h" tok1 #line 99999 "include/me.h" tok2 """ # ~ self.clex.filename self.clex.input(str) t1 = require_token(self.clex.token()) self.assertEqual(t1.type, "INT_CONST_DEC") self.assertEqual(t1.lineno, 2) t2 = require_token(self.clex.token()) self.assertEqual(t2.type, "ID") self.assertEqual(t2.value, "id") self.assertEqual(t2.lineno, 66) self.assertEqual(self.clex.filename, r"kwas\df.h") for i in range(3): t = require_token(self.clex.token()) self.assertEqual(t.type, "ID") self.assertEqual(t.value, "armo") self.assertEqual(t.lineno, 9) self.assertEqual(self.clex.filename, r"kwas\df.h") t4 = require_token(self.clex.token()) self.assertEqual(t4.type, "ID") self.assertEqual(t4.value, "tok1") self.assertEqual(t4.lineno, 10) self.assertEqual(self.clex.filename, r"..\~..\test.h") t5 = require_token(self.clex.token()) self.assertEqual(t5.type, "ID") self.assertEqual(t5.value, "tok2") self.assertEqual(t5.lineno, 99999) self.assertEqual(self.clex.filename, r"include/me.h") def test_preprocessor_line_funny(self): str = r""" #line 10 "..\6\joe.h" 10 """ self.clex.input(str) t1 = require_token(self.clex.token()) self.assertEqual(t1.type, "INT_CONST_DEC") self.assertEqual(t1.lineno, 10) self.assertEqual(self.clex.filename, r"..\6\joe.h") def test_preprocessor_pragma(self): str = """ 42 #pragma #pragma helo me #pragma once # pragma omp parallel private(th_id) #\tpragma {pack: 2, smack: 3} #pragma "nowit.h" #pragma "string" #pragma somestring="some_other_string" #pragma id 124124 and numbers 0235495 _Pragma("something else") 59 """ # Check that pragmas are tokenized, including trailing string self.clex.input(str) t1 = require_token(self.clex.token()) self.assertEqual(t1.type, "INT_CONST_DEC") t2 = require_token(self.clex.token()) self.assertEqual(t2.type, "PPPRAGMA") t3 = require_token(self.clex.token()) self.assertEqual(t3.type, "PPPRAGMA") t4 = require_token(self.clex.token()) self.assertEqual(t4.type, "PPPRAGMASTR") self.assertEqual(t4.value, "helo me") for i in range(3): self.clex.token() t5 = require_token(self.clex.token()) self.assertEqual(t5.type, "PPPRAGMASTR") self.assertEqual(t5.value, "omp parallel private(th_id)") for i in range(5): ta = require_token(self.clex.token()) self.assertEqual(ta.type, "PPPRAGMA") tb = require_token(self.clex.token()) self.assertEqual(tb.type, "PPPRAGMASTR") t6a = require_token(self.clex.token()) t6l = require_token(self.clex.token()) t6b = require_token(self.clex.token()) t6r = require_token(self.clex.token()) self.assertEqual(t6a.type, "_PRAGMA") self.assertEqual(t6l.type, "LPAREN") self.assertEqual(t6b.type, "STRING_LITERAL") self.assertEqual(t6b.value, '"something else"') self.assertEqual(t6r.type, "RPAREN") t7 = require_token(self.clex.token()) self.assertEqual(t7.type, "INT_CONST_DEC") self.assertEqual(t7.lineno, 13) # Keeps all the errors the lexer spits in one place, to allow # easier modification if the error syntax changes. # ERR_ILLEGAL_CHAR = "Illegal character" ERR_OCTAL = "Invalid octal constant" ERR_UNMATCHED_QUOTE = "Unmatched '" ERR_INVALID_CCONST = "Invalid char constant" ERR_STRING_ESCAPE = "String contains invalid escape" ERR_FILENAME_BEFORE_LINE = "filename before line" ERR_LINENUM_MISSING = "line number missing" ERR_INVALID_LINE_DIRECTIVE = "invalid #line directive" ERR_COMMENT = "Comments are not supported" class TestCLexerErrors(unittest.TestCase): """Test lexing of erroneous strings. Works by passing an error function that saves the error in an attribute for later perusal. """ def error_func(self, msg, line, column): self.error = msg def setUp(self): self.clex = CLexer(self.error_func) self.error = "" def assertLexerError(self, str, error_like): # feed the string to the lexer self.clex.input(str) # Pulls all tokens from the string. Errors will # be written into self.error by the error_func # callback # token_types(self.clex) # compare the error to the expected self.assertTrue( re.search(error_like, self.error), f"\nExpected error matching: {error_like}\nGot: {self.error}", ) # clear last error, for the sake of subsequent invocations self.error = "" def test_trivial_tokens(self): self.assertLexerError("@", ERR_ILLEGAL_CHAR) self.assertLexerError("`", ERR_ILLEGAL_CHAR) self.assertLexerError("\\", ERR_ILLEGAL_CHAR) def test_integer_constants(self): self.assertLexerError("029", ERR_OCTAL) self.assertLexerError("012345678", ERR_OCTAL) self.assertLexerError("0'8", ERR_OCTAL) self.assertLexerError("0'7'9", ERR_OCTAL) def test_char_constants(self): self.assertLexerError("'", ERR_UNMATCHED_QUOTE) self.assertLexerError("'b\n", ERR_UNMATCHED_QUOTE) self.assertLexerError("'\\xaa\n'", ERR_UNMATCHED_QUOTE) self.assertLexerError(r"'123\12a'", ERR_INVALID_CCONST) self.assertLexerError(r"'123\xabg'", ERR_INVALID_CCONST) self.assertLexerError("''", ERR_INVALID_CCONST) self.assertLexerError("'abcjx'", ERR_INVALID_CCONST) self.assertLexerError(r"'\*'", ERR_INVALID_CCONST) def test_unicode_escape_backtracking(self): # Long malformed constants must not permit exponential backtracking # between Unicode escapes and the permissive simple-escape pattern. escapes = r"\u00e9\U0001F600" * 30 self.assertLexerError("'" + escapes, ERR_UNMATCHED_QUOTE) self.assertLexerError("'" + escapes + "\n", ERR_UNMATCHED_QUOTE) self.assertLexerError("'" + escapes + "'", ERR_INVALID_CCONST) def test_string_literals(self): self.assertLexerError(r'"jx\`"', ERR_STRING_ESCAPE) self.assertLexerError(r'"hekllo\* on ix"', ERR_STRING_ESCAPE) self.assertLexerError(r'L"hekllo\* on ix"', ERR_STRING_ESCAPE) # Should not suffer from slow backtracking self.assertLexerError( r'"\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\`\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123"', ERR_STRING_ESCAPE, ) self.assertLexerError( r'"\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\x23\`\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23\xf1\x23"', ERR_STRING_ESCAPE, ) # Should not suffer from slow backtracking when there's no end quote self.assertLexerError( r'"\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\`\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\123\12\123456', ERR_ILLEGAL_CHAR, ) self.assertLexerError( r'"\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\`\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x23\x2\x23456', ERR_ILLEGAL_CHAR, ) def test_preprocessor(self): self.assertLexerError('#line "ka"', ERR_FILENAME_BEFORE_LINE) self.assertLexerError("#line df", ERR_INVALID_LINE_DIRECTIVE) self.assertLexerError("#line \n", ERR_LINENUM_MISSING) # Integer suffixes are not valid in #line directives (issue #587). self.assertLexerError("#line 0u", ERR_INVALID_LINE_DIRECTIVE) self.assertLexerError("#line 1U", ERR_INVALID_LINE_DIRECTIVE) self.assertLexerError("#line 10uLL", ERR_INVALID_LINE_DIRECTIVE) self.assertLexerError("#line 1'000u", ERR_INVALID_LINE_DIRECTIVE) self.assertLexerError("#line 1''000", ERR_INVALID_LINE_DIRECTIVE) # a compatible preprocessor must remove comments. self.assertLexerError("//", ERR_COMMENT) self.assertLexerError("/*", ERR_COMMENT) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792673999.8435886 pycparser-3.12/tests/test_c_parser.py0000664000175000017500000076246115266404320017362 0ustar00elibenelibenimport os import unittest from pycparser import c_parser from pycparser.c_ast import * ParseError = c_parser.ParseError _c_parser = c_parser.CParser() def expand_decl(decl): """Converts the declaration into a nested list.""" typ = type(decl) if typ == TypeDecl: return ["TypeDecl", expand_decl(decl.type)] elif typ == IdentifierType: return ["IdentifierType", decl.names] elif typ == ID: return ["ID", decl.name] elif typ in [Struct, Union]: decls = [expand_decl(d) for d in decl.decls or []] return [typ.__name__, decl.name, decls] elif typ == Enum: if decl.values is None: values = None else: assert isinstance(decl.values, EnumeratorList) values = [enum.name for enum in decl.values.enumerators] return ["Enum", decl.name, values] elif typ == Alignas: return ["Alignas", expand_init(decl.alignment)] elif typ == StaticAssert: if decl.message: return ["StaticAssert", decl.cond.value, decl.message.value] else: return ["StaticAssert", decl.cond.value] else: nested = expand_decl(decl.type) if typ == Decl: r = ["Decl"] if decl.quals: r.append(decl.quals) if decl.align: r.append(expand_decl(decl.align[0])) r.extend([decl.name, nested]) return r elif typ == Typename: # for function parameters if decl.quals: return ["Typename", decl.quals, nested] else: return ["Typename", nested] elif typ == ArrayDecl: dimval = decl.dim.value if decl.dim else "" return ["ArrayDecl", dimval, decl.dim_quals, nested] elif typ == PtrDecl: if decl.quals: return ["PtrDecl", decl.quals, nested] else: return ["PtrDecl", nested] elif typ == Typedef: return ["Typedef", decl.name, nested] elif typ == FuncDecl: if decl.args: params = [expand_decl(param) for param in decl.args.params] else: params = [] return ["FuncDecl", params, nested] def expand_init(init): """Converts an initialization into a nested list""" typ = type(init) if typ == NamedInitializer: des = [expand_init(dp) for dp in init.name] return (des, expand_init(init.expr)) elif typ == ArrayDesignator: return ["ArrayDesignator", expand_init(init.expr)] elif typ in (InitList, ExprList): return [expand_init(expr) for expr in init.exprs] elif typ == Constant: return ["Constant", init.type, init.value] elif typ == ID: return ["ID", init.name] elif typ == Decl: return ["Decl", init.name] elif typ == UnaryOp: return ["UnaryOp", init.op, expand_decl(init.expr)] elif typ == BinaryOp: return ["BinaryOp", expand_init(init.left), init.op, expand_init(init.right)] elif typ == Compound: blocks = [] if init.block_items: blocks = [expand_init(i) for i in init.block_items] return ["Compound", blocks] elif typ == Typename: return expand_decl(init) else: # Fallback to type name return [typ.__name__] class TestCParser_base(unittest.TestCase): def parse(self, txt, filename=""): return self.cparser.parse(txt, filename) def setUp(self): self.cparser = _c_parser def assert_coord(self, node, line, column=None, file=None): self.assertEqual(node.coord.line, line) if column is not None: self.assertEqual(node.coord.column, column) if file is not None: self.assertEqual(node.coord.file, file) class TestCParser_fundamentals(TestCParser_base): def get_decl(self, txt, index=0): """Given a source and an index returns the expanded declaration at that index. FileAST holds a list of 'external declarations'. index is the offset of the desired declaration in that list. """ t = self.parse(txt).ext[index] return expand_decl(t) def get_decl_init(self, txt, index=0): """Returns the expanded initializer of the declaration at index. """ t = self.parse(txt).ext[index] return expand_init(t.init) def test_FileAST(self): t = self.parse("int a; char c;") self.assertIsInstance(t, FileAST) self.assertEqual(len(t.ext), 2) # empty file t2 = self.parse("") self.assertIsInstance(t2, FileAST) self.assertEqual(len(t2.ext), 0) def test_form_feed_and_vertical_tab_whitespace(self): tree = self.parse("\vint\fx;\nint\vy;\f") self.assertEqual([decl.name for decl in tree.ext], ["x", "y"]) self.assert_coord(tree.ext[0], 1, 6) self.assert_coord(tree.ext[1], 2, 5) self.assertEqual(self.parse(" \t\f\v").ext, []) def test_empty_toplevel_decl(self): code = "int foo;;" t = self.parse(code) self.assertIsInstance(t, FileAST) self.assertEqual(len(t.ext), 1) self.assertEqual( self.get_decl(code), ["Decl", "foo", ["TypeDecl", ["IdentifierType", ["int"]]]], ) def test_initial_semi(self): t = self.parse(";") self.assertEqual(len(t.ext), 0) t = self.parse(";int foo;") self.assertEqual(len(t.ext), 1) self.assertEqual( expand_decl(t.ext[0]), ["Decl", "foo", ["TypeDecl", ["IdentifierType", ["int"]]]], ) def test_line_directive_update_in_errors(self): s1 = """ \t # \t line \t 8 \t "baz.c" \t some syntax error here """ self.assertRaisesRegex(ParseError, "baz.c:9", self.parse, s1) s2 = """ \t # \t 8 \t "baz.c" \t some syntax error here """ self.assertRaisesRegex(ParseError, "baz.c:10", self.parse, s2) s3 = """ #line 5 "foo.c" extern int xx; #line 6 "bar.c" extern int yy; #line 7 "baz.c" some syntax error here #line 8 "yadda.c" extern int zz; """ self.assertRaisesRegex(ParseError, "baz.c:7", self.parse, s3) def test_coords(self): # Tests the "coordinates" of parsed elements - file name, line and # column numbers, with modification inserted by #line directives. self.assert_coord(self.parse("int a;").ext[0], 1, 5) t1 = """ int a; int b;\n\n int c; """ f1 = self.parse(t1, filename="test.c") self.assert_coord(f1.ext[0], 2, 13, "test.c") self.assert_coord(f1.ext[1], 3, 13, "test.c") self.assert_coord(f1.ext[2], 6, 13, "test.c") t1_1 = """ int main() { k = p; printf("%d", b); return 0; }""" f1_1 = self.parse(t1_1, filename="test.c") self.assert_coord(f1_1.ext[0].body.block_items[0], 3, 13, "test.c") self.assert_coord(f1_1.ext[0].body.block_items[1], 4, 13, "test.c") t1_2 = """ int main () { int p = (int) k; }""" f1_2 = self.parse(t1_2, filename="test.c") # make sure that the Cast has a coord (issue 23) self.assert_coord(f1_2.ext[0].body.block_items[0].init, 3, 21, file="test.c") t2 = """ #line 99 int c; """ self.assert_coord(self.parse(t2).ext[0], 99, 13) t3 = """ int dsf; char p; #line 3000 "in.h" char d; """ f3 = self.parse(t3, filename="test.c") self.assert_coord(f3.ext[0], 2, 13, "test.c") self.assert_coord(f3.ext[1], 3, 14, "test.c") self.assert_coord(f3.ext[2], 3000, 14, "in.h") t4 = """ #line 20 "restore.h" int maydler(char); #line 30 "includes/daween.ph" long j, k; #line 50000 char* ro; """ f4 = self.parse(t4, filename="myb.c") self.assert_coord(f4.ext[0], 20, 13, "restore.h") self.assert_coord(f4.ext[1], 30, 14, "includes/daween.ph") self.assert_coord(f4.ext[2], 30, 17, "includes/daween.ph") self.assert_coord(f4.ext[3], 50000, 13, "includes/daween.ph") t5 = """ int #line 99 c; """ self.assert_coord(self.parse(t5).ext[0], 99, 9) # coord for ellipsis t6 = """ int foo(int j, ...) { }""" self.assert_coord(self.parse(t6).ext[0].decl.type.args.params[1], 3, 17) # Coord for _Atomic type decls t7 = """ typedef _Atomic(char) atomic_char; """ self.assert_coord(self.parse(t7).ext[0], 2, 31) self.assert_coord(self.parse(t7).ext[0].type, 2, 31) def test_coords_included_initializers(self): for value in ("1", '"value"', 'L"value"', 'u8"value"', 'u"value"', 'U"value"'): with self.subTest(value=value): declaration = "int a" if value == "1" else "char *a" text = ( f'# 1 "main.c"\n{declaration} =\n' '# 7 "value.h" 1\n' f" {value}\n" '# 3 "main.c" 2\n;\n' ) ast = self.parse(text) self.assert_coord(ast.ext[0].init, 7, 3, "value.h") self.assert_coord(ast.ext[0], 1, 5 if value == "1" else 6, "main.c") def test_coords_adjacent_strings_across_files(self): for filename in ("first.h", "", "main.c"): with self.subTest(filename=filename): text = ( "char *a =\n" f'#line 7 "{filename}"\n "first"\n' '#line 12 "second.h"\n "second"\n' '#line 3 "main.c"\n;\n' ) ast = self.parse(text, filename="main.c") self.assertEqual(ast.ext[0].init.value, '"firstsecond"') self.assert_coord(ast.ext[0].init, 7, 3, filename) def test_coords_declarator_lookahead(self): text = 'int (\n#line 7 "name.h"\n value\n#line 3 "main.c"\n);\n' ast = self.parse(text, filename="main.c") self.assert_coord(ast.ext[0], 7, 3, "name.h") self.assert_coord(ast.ext[0].type, 7, 3, "name.h") def test_coords_error_after_declarator_lookahead(self): text = 'int (\n#line 7 "name.h"\n value unexpected\n#line 3 "main.c"\n);\n' with self.assertRaises(ParseError) as error: self.parse(text, filename="main.c") self.assertEqual(str(error.exception), "name.h:7:9: before: unexpected") def test_coords_compound_across_files(self): text = 'void f(void) {\n#line 7 "body.h"\n return;\n}\n' ast = self.parse(text, filename="main.c") self.assert_coord(ast.ext[0].body, 1, 14, "main.c") self.assert_coord(ast.ext[0].body.block_items[0], 7, 3, "body.h") ast = self.parse("int other;", filename="next.c") self.assert_coord(ast.ext[0], 1, 5, "next.c") def test_forloop_coord(self): t = """\ void foo() { for(int z=0; z<4; z++){} } """ s = self.parse(t, filename="f.c") forloop = s.ext[0].body.block_items[0] self.assert_coord(forloop.init, 2, 13, "f.c") self.assert_coord(forloop.cond, 2, 26, "f.c") self.assert_coord(forloop.next, 3, 17, "f.c") def test_simple_decls(self): self.assertEqual( self.get_decl("int a;"), ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual( self.get_decl("unsigned int a;"), ["Decl", "a", ["TypeDecl", ["IdentifierType", ["unsigned", "int"]]]], ) self.assertEqual( self.get_decl("_Bool a;"), ["Decl", "a", ["TypeDecl", ["IdentifierType", ["_Bool"]]]], ) self.assertEqual( self.get_decl("float _Complex fcc;"), ["Decl", "fcc", ["TypeDecl", ["IdentifierType", ["float", "_Complex"]]]], ) self.assertEqual( self.get_decl("char* string;"), ["Decl", "string", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]], ) self.assertEqual( self.get_decl("long ar[15];"), [ "Decl", "ar", ["ArrayDecl", "15", [], ["TypeDecl", ["IdentifierType", ["long"]]]], ], ) self.assertEqual( self.get_decl("long long ar[15];"), [ "Decl", "ar", [ "ArrayDecl", "15", [], ["TypeDecl", ["IdentifierType", ["long", "long"]]], ], ], ) self.assertEqual( self.get_decl("unsigned ar[];"), [ "Decl", "ar", ["ArrayDecl", "", [], ["TypeDecl", ["IdentifierType", ["unsigned"]]]], ], ) self.assertEqual( self.get_decl("int strlen(char* s);"), [ "Decl", "strlen", [ "FuncDecl", [ [ "Decl", "s", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) self.assertEqual( self.get_decl("int strcmp(char* s1, char* s2);"), [ "Decl", "strcmp", [ "FuncDecl", [ [ "Decl", "s1", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], [ "Decl", "s2", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) # function return values and parameters may not have type information self.assertEqual( self.get_decl("extern foobar(foo, bar);"), [ "Decl", "foobar", [ "FuncDecl", [["ID", "foo"], ["ID", "bar"]], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) def test_int128(self): self.assertEqual( self.get_decl("__int128 a;"), ["Decl", "a", ["TypeDecl", ["IdentifierType", ["__int128"]]]], ) def test_nested_decls(self): # the fun begins self.assertEqual( self.get_decl("char** ar2D;"), [ "Decl", "ar2D", ["PtrDecl", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]], ], ) self.assertEqual( self.get_decl("int (*a)[1][2];"), [ "Decl", "a", [ "PtrDecl", [ "ArrayDecl", "1", [], [ "ArrayDecl", "2", [], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ], ) self.assertEqual( self.get_decl("int *a[1][2];"), [ "Decl", "a", [ "ArrayDecl", "1", [], [ "ArrayDecl", "2", [], ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]], ], ], ], ) self.assertEqual( self.get_decl("char* const* p;"), [ "Decl", "p", [ "PtrDecl", ["PtrDecl", ["const"], ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ) self.assertEqual( self.get_decl("const char* const* p;"), [ "Decl", ["const"], "p", [ "PtrDecl", ["PtrDecl", ["const"], ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ) self.assertEqual( self.get_decl("char* * const p;"), [ "Decl", "p", [ "PtrDecl", ["const"], ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ) self.assertEqual( self.get_decl("char ***ar3D[40];"), [ "Decl", "ar3D", [ "ArrayDecl", "40", [], [ "PtrDecl", [ "PtrDecl", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ], ], ) self.assertEqual( self.get_decl("char (***ar3D)[40];"), [ "Decl", "ar3D", [ "PtrDecl", [ "PtrDecl", [ "PtrDecl", [ "ArrayDecl", "40", [], ["TypeDecl", ["IdentifierType", ["char"]]], ], ], ], ], ], ) self.assertEqual( self.get_decl("int (*const*const x)(char, int);"), [ "Decl", "x", [ "PtrDecl", ["const"], [ "PtrDecl", ["const"], [ "FuncDecl", [ [ "Typename", ["TypeDecl", ["IdentifierType", ["char"]]], ], ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]], ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ], ) self.assertEqual( self.get_decl("int (*x[4])(char, int);"), [ "Decl", "x", [ "ArrayDecl", "4", [], [ "PtrDecl", [ "FuncDecl", [ [ "Typename", ["TypeDecl", ["IdentifierType", ["char"]]], ], ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]], ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ], ) self.assertEqual( self.get_decl("char *(*(**foo [][8])())[];"), [ "Decl", "foo", [ "ArrayDecl", "", [], [ "ArrayDecl", "8", [], [ "PtrDecl", [ "PtrDecl", [ "FuncDecl", [], [ "PtrDecl", [ "ArrayDecl", "", [], [ "PtrDecl", [ "TypeDecl", ["IdentifierType", ["char"]], ], ], ], ], ], ], ], ], ], ], ) # explore named and unnamed function pointer parameters, # with and without qualifiers # unnamed w/o quals self.assertEqual( self.get_decl("int (*k)(int);"), [ "Decl", "k", [ "PtrDecl", [ "FuncDecl", [["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ) # unnamed w/ quals self.assertEqual( self.get_decl("int (*k)(const int);"), [ "Decl", "k", [ "PtrDecl", [ "FuncDecl", [ [ "Typename", ["const"], ["TypeDecl", ["IdentifierType", ["int"]]], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ) # named w/o quals self.assertEqual( self.get_decl("int (*k)(int q);"), [ "Decl", "k", [ "PtrDecl", [ "FuncDecl", [["Decl", "q", ["TypeDecl", ["IdentifierType", ["int"]]]]], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ) # named w/ quals self.assertEqual( self.get_decl("int (*k)(const volatile int q);"), [ "Decl", "k", [ "PtrDecl", [ "FuncDecl", [ [ "Decl", ["const", "volatile"], "q", ["TypeDecl", ["IdentifierType", ["int"]]], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ) self.assertEqual( self.get_decl("int (*k)(_Atomic volatile int q);"), [ "Decl", "k", [ "PtrDecl", [ "FuncDecl", [ [ "Decl", ["_Atomic", "volatile"], "q", ["TypeDecl", ["IdentifierType", ["int"]]], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ) self.assertEqual( self.get_decl("int (*k)(const volatile int* q);"), [ "Decl", "k", [ "PtrDecl", [ "FuncDecl", [ [ "Decl", ["const", "volatile"], "q", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ) # restrict qualifier self.assertEqual( self.get_decl("int (*k)(restrict int* q);"), [ "Decl", "k", [ "PtrDecl", [ "FuncDecl", [ [ "Decl", ["restrict"], "q", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ) def test_func_decls_with_array_dim_qualifiers(self): # named function parameter self.assertEqual( self.get_decl("int zz(int p[static 10]);"), [ "Decl", "zz", [ "FuncDecl", [ [ "Decl", "p", [ "ArrayDecl", "10", ["static"], ["TypeDecl", ["IdentifierType", ["int"]]], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) # anonymous function parameter self.assertEqual( self.get_decl("int zz(int [static 10]);"), [ "Decl", "zz", [ "FuncDecl", [ [ "Typename", [ "ArrayDecl", "10", ["static"], ["TypeDecl", ["IdentifierType", ["int"]]], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) self.assertEqual( self.get_decl("int zz(int [static const restrict 10]);"), [ "Decl", "zz", [ "FuncDecl", [ [ "Typename", [ "ArrayDecl", "10", ["static", "const", "restrict"], ["TypeDecl", ["IdentifierType", ["int"]]], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) self.assertEqual( self.get_decl("int zz(int p[const 10]);"), [ "Decl", "zz", [ "FuncDecl", [ [ "Decl", "p", [ "ArrayDecl", "10", ["const"], ["TypeDecl", ["IdentifierType", ["int"]]], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) self.assertEqual( self.get_decl("int zz(int p[restrict][5]);"), [ "Decl", "zz", [ "FuncDecl", [ [ "Decl", "p", [ "ArrayDecl", "", ["restrict"], [ "ArrayDecl", "5", [], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) self.assertEqual( self.get_decl("int zz(int p[const restrict static 10][5]);"), [ "Decl", "zz", [ "FuncDecl", [ [ "Decl", "p", [ "ArrayDecl", "10", ["const", "restrict", "static"], [ "ArrayDecl", "5", [], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) # unnamed function parameter self.assertEqual( self.get_decl("int zz(int [const 10]);"), [ "Decl", "zz", [ "FuncDecl", [ [ "Typename", [ "ArrayDecl", "10", ["const"], ["TypeDecl", ["IdentifierType", ["int"]]], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) self.assertEqual( self.get_decl("int zz(int [restrict][5]);"), [ "Decl", "zz", [ "FuncDecl", [ [ "Typename", [ "ArrayDecl", "", ["restrict"], [ "ArrayDecl", "5", [], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) self.assertEqual( self.get_decl("int zz(int [const restrict volatile 10][5]);"), [ "Decl", "zz", [ "FuncDecl", [ [ "Typename", [ "ArrayDecl", "10", ["const", "restrict", "volatile"], [ "ArrayDecl", "5", [], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) def test_qualifiers_storage_specifiers(self): def assert_qs(txt, index, quals, storage): d = self.parse(txt).ext[index] self.assertEqual(d.quals, quals) self.assertEqual(d.storage, storage) assert_qs("extern int p;", 0, [], ["extern"]) assert_qs("_Thread_local int p;", 0, [], ["_Thread_local"]) assert_qs("const long p = 6;", 0, ["const"], []) assert_qs("_Atomic int p;", 0, ["_Atomic"], []) assert_qs("_Atomic restrict int* p;", 0, ["_Atomic", "restrict"], []) d1 = "static const int p, q, r;" for i in range(3): assert_qs(d1, i, ["const"], ["static"]) d2 = "static char * const p;" assert_qs(d2, 0, [], ["static"]) pdecl = self.parse(d2).ext[0].type self.assertIsInstance(pdecl, PtrDecl) self.assertEqual(pdecl.quals, ["const"]) def test_restricted_specifier_lists(self): # Sharing specifier parsing must not admit storage classes or function # specifiers in member declarations and type names. with self.assertRaisesRegex(ParseError, "Invalid specifier list"): self.parse("struct S { static int x; };") with self.assertRaisesRegex(ParseError, "Invalid specifier list"): self.parse("struct S { inline int x; };") with self.assertRaisesRegex(ParseError, "Invalid specifier list"): self.parse("int n = sizeof(inline int);") def test_specifier_list_missing_type(self): # Qualifiers alone do not supply a type; report the first qualifier's # position in both member declarations and type names. with self.assertRaisesRegex( ParseError, r"^types.c:1:12: Missing type in declaration$" ): self.parse("struct S { const x; };", filename="types.c") with self.assertRaisesRegex( ParseError, r"^types.c:1:16: Missing type in declaration$" ): self.parse("int n = sizeof(const);", filename="types.c") def test_atomic_specifier(self): self.assertEqual( self.get_decl("_Atomic(int) ai;"), ["Decl", ["_Atomic"], "ai", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual( self.get_decl("_Atomic(int*) ai;"), [ "Decl", "ai", ["PtrDecl", ["_Atomic"], ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) self.assertEqual( self.get_decl("_Atomic(_Atomic(int)*) aai;"), [ "Decl", ["_Atomic"], "aai", ["PtrDecl", ["_Atomic"], ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) # Multiple declarations with _Atomic(...) s = "_Atomic(int) foo, bar;" self.assertEqual( self.get_decl(s, 0), ["Decl", ["_Atomic"], "foo", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual( self.get_decl(s, 1), ["Decl", ["_Atomic"], "bar", ["TypeDecl", ["IdentifierType", ["int"]]]], ) # typedefs with _Atomic specifiers. s = "typedef _Atomic(int) atomic_int;" self.assertEqual( self.get_decl(s, 0), ["Typedef", "atomic_int", ["TypeDecl", ["IdentifierType", ["int"]]]], ) s = "typedef _Atomic(_Bool) atomic_bool;" self.assertEqual( self.get_decl(s, 0), ["Typedef", "atomic_bool", ["TypeDecl", ["IdentifierType", ["_Bool"]]]], ) s = "typedef _Atomic(_Atomic(_Atomic(int (*)(void)) *) *) t;" self.assertEqual( self.get_decl(s, 0), [ "Typedef", "t", [ "PtrDecl", ["_Atomic"], [ "PtrDecl", ["_Atomic"], [ "PtrDecl", ["_Atomic"], [ "FuncDecl", [ [ "Typename", ["TypeDecl", ["IdentifierType", ["void"]]], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ], ], ) def test_atomic_specifier_rejects_array_and_function(self): # _Atomic cannot wrap an array or function type (C11 6.7.2.4p3). These # must raise ParseError rather than crash with AttributeError. for s in ( "_Atomic(char[3]) a;", "_Atomic(int[]) a;", "_Atomic(char*[3]) a;", "_Atomic(void(int)) f;", "typedef _Atomic(char[3]) t;", "void g(_Atomic(char[3]));", ): with self.assertRaises(ParseError): self.parse(s) def test_atomic_specifier_rejects_array_in_sizeof(self): with self.assertRaisesRegex( ParseError, "_Atomic cannot be applied to array or function type" ): self.parse("int n = sizeof(_Atomic(char[3]));") def test_atomic_specifier_rejects_function_in_sizeof(self): with self.assertRaisesRegex( ParseError, "_Atomic cannot be applied to array or function type" ): self.parse("int n = sizeof(_Atomic(void(int)));") def test_atomic_specifier_rejects_array_in_cast(self): with self.assertRaisesRegex( ParseError, "_Atomic cannot be applied to array or function type" ): self.parse("void f(void) { (_Atomic(char[3]))0; }") def test_atomic_specifier_rejects_function_in_cast(self): with self.assertRaisesRegex( ParseError, "_Atomic cannot be applied to array or function type" ): self.parse("void f(void) { (_Atomic(void(int)))0; }") def test_typedef_parameter_declaration(self): self.assertRaises(ParseError, self.parse, "void f(typedef int x);") self.assertRaises(ParseError, self.parse, "void f(typedef int);") self.assertRaises(ParseError, self.parse, "void f(int a, typedef int *p);") def test_atomic_specifier_qualifiers(self): decl = self.parse("const _Atomic(volatile int *) p;").ext[0] # The outer const qualifies the atomic pointer, while volatile stays # on the pointed-to int and in the declaration's base qualifiers. self.assertEqual(decl.quals, ["volatile"]) self.assertIsInstance(decl.type, PtrDecl) self.assertEqual(decl.type.quals, ["const", "_Atomic"]) self.assertIsInstance(decl.type.type, TypeDecl) self.assertEqual(decl.type.type.quals, ["volatile"]) self.assertEqual(decl.type.type.declname, "p") typ = self.parse("int n = sizeof(const _Atomic(int *));").ext[0].init.expr self.assertIsInstance(typ, Typename) self.assertEqual(typ.quals, []) self.assertIsInstance(typ.type, PtrDecl) self.assertEqual(typ.type.quals, ["const", "_Atomic"]) self.assertEqual(typ.type.type.quals, []) self.assertIsNone(typ.type.type.declname) def test_atomic_specifier_multiple_declarators(self): decls = self.parse("const _Atomic(int) a, b;").ext for decl, name, column in zip(decls, ("a", "b"), (20, 23)): self.assertEqual(decl.name, name) self.assertEqual(decl.type.declname, name) self.assertEqual(decl.quals, ["const", "_Atomic"]) self.assertEqual(decl.type.quals, ["const", "_Atomic"]) self.assert_coord(decl.type, 1, column) self.assertIsNot(decls[0].type, decls[1].type) def test_sizeof(self): e = """ void foo() { int a = sizeof k; int b = sizeof(int); int c = sizeof(int**);; char* p = "just to make sure this parses w/o error..."; int d = sizeof(int()); } """ compound = self.parse(e).ext[0].body s1 = compound.block_items[0].init self.assertIsInstance(s1, UnaryOp) self.assertEqual(s1.op, "sizeof") self.assertIsInstance(s1.expr, ID) self.assertEqual(s1.expr.name, "k") s2 = compound.block_items[1].init self.assertEqual( expand_decl(s2.expr), ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]], ) s3 = compound.block_items[2].init self.assertEqual( expand_decl(s3.expr), [ "Typename", ["PtrDecl", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]]], ], ) def test_alignof(self): r = self.parse("int a = _Alignof(int);") self.assertEqual( expand_decl(r.ext[0]), ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual( expand_init(r.ext[0].init), [ "UnaryOp", "_Alignof", ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) self.assertEqual( expand_decl(self.parse("_Alignas(_Alignof(int)) char a;").ext[0]), [ "Decl", [ "Alignas", [ "UnaryOp", "_Alignof", ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]], ], ], "a", ["TypeDecl", ["IdentifierType", ["char"]]], ], ) self.assertEqual( expand_decl(self.parse("_Alignas(4) char a;").ext[0]), [ "Decl", ["Alignas", ["Constant", "int", "4"]], "a", ["TypeDecl", ["IdentifierType", ["char"]]], ], ) self.assertEqual( expand_decl(self.parse("_Alignas(int) char a;").ext[0]), [ "Decl", ["Alignas", ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]], "a", ["TypeDecl", ["IdentifierType", ["char"]]], ], ) def test_alignas_with_typedef_in_struct(self): # Issue #472 s = """ typedef int test_int; typedef struct { _Alignas(int) test_int a1; } test_struct; """ ast = self.parse(s) field = ast.ext[1].type.type.decls[0] self.assertEqual(field.name, "a1") self.assertTrue(hasattr(field, "align") and field.align is not None) self.assertEqual( expand_decl(field), [ "Decl", ["Alignas", ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]], "a1", ["TypeDecl", ["IdentifierType", ["test_int"]]], ], ) def test_builtin_va_arg(self): # Issue #533: the second argument is a type, including typedef names. ast = self.parse(""" typedef void *va_list; typedef int T; void f(va_list ap) { __builtin_va_arg(ap, int); __builtin_va_arg(ap, const T *); } """) scalar, pointer = ast.ext[2].body.block_items self.assertIsInstance(scalar, FuncCall) self.assertEqual(scalar.name.name, "__builtin_va_arg") self.assertIsInstance(scalar.args.exprs[0], ID) self.assertEqual(scalar.args.exprs[0].name, "ap") self.assertIsInstance(scalar.args.exprs[1], Typename) self.assertEqual(scalar.args.exprs[1].type.type.names, ["int"]) typ = pointer.args.exprs[1] self.assertIsInstance(typ, Typename) self.assertIsInstance(typ.type, PtrDecl) self.assertEqual(typ.type.type.quals, ["const"]) self.assertEqual(typ.type.type.type.names, ["T"]) def test_function_call_rejects_type_argument(self): with self.assertRaises(ParseError): self.parse("void f(void) { foo(int); }") def test_offsetof(self): def expand_ref(n): if isinstance(n, StructRef): return ["StructRef", expand_ref(n.name), expand_ref(n.field)] elif isinstance(n, ArrayRef): return ["ArrayRef", expand_ref(n.name), expand_ref(n.subscript)] elif isinstance(n, ID): return ["ID", n.name] elif isinstance(n, Constant): return ["Constant", n.type, n.value] else: raise TypeError("Unexpected type " + n.__class__.__name__) e = """ void foo() { int a = offsetof(struct S, p); a.b = offsetof(struct sockaddr, sp) + strlen(bar); int a = offsetof(struct S, p.q.r); int a = offsetof(struct S, p[5].q[4][5]); } """ compound = self.parse(e).ext[0].body s1 = compound.block_items[0].init self.assertIsInstance(s1, FuncCall) self.assertIsInstance(s1.name, ID) self.assertEqual(s1.name.name, "offsetof") self.assertIsInstance(s1.args.exprs[0], Typename) self.assertIsInstance(s1.args.exprs[1], ID) s3 = compound.block_items[2].init self.assertIsInstance(s3.args.exprs[1], StructRef) self.assertEqual( expand_ref(s3.args.exprs[1]), ["StructRef", ["StructRef", ["ID", "p"], ["ID", "q"]], ["ID", "r"]], ) s4 = compound.block_items[3].init self.assertIsInstance(s4.args.exprs[1], ArrayRef) self.assertEqual( expand_ref(s4.args.exprs[1]), [ "ArrayRef", [ "ArrayRef", [ "StructRef", ["ArrayRef", ["ID", "p"], ["Constant", "int", "5"]], ["ID", "q"], ], ["Constant", "int", "4"], ], ["Constant", "int", "5"], ], ) def test_compound_statement(self): e = """ void foo() { } """ compound = self.parse(e).ext[0].body self.assertIsInstance(compound, Compound) self.assert_coord(compound, 2) # The C99 compound literal feature # def test_compound_literals(self): ps1 = self.parse(r""" void foo() { p = (long long){k}; tc = (struct jk){.a = {1, 2}, .b[0] = t}; }""") compound = ps1.ext[0].body.block_items[0].rvalue self.assertEqual( expand_decl(compound.type), ["Typename", ["TypeDecl", ["IdentifierType", ["long", "long"]]]], ) self.assertEqual(expand_init(compound.init), [["ID", "k"]]) compound = ps1.ext[0].body.block_items[1].rvalue self.assertEqual( expand_decl(compound.type), ["Typename", ["TypeDecl", ["Struct", "jk", []]]] ) self.assertEqual( expand_init(compound.init), [ ([["ID", "a"]], [["Constant", "int", "1"], ["Constant", "int", "2"]]), ( [["ID", "b"], ["ArrayDesignator", ["Constant", "int", "0"]]], ["ID", "t"], ), ], ) def test_empty_compound_literal(self): # C23 allows empty initializer braces in compound literals, e.g. (int){}. # Also accepted in legacy mode. Regression test for #503. ps = self.parse(r""" void foo() { x = (int){}; y = (struct jk){}; }""") compound = ps.ext[0].body.block_items[0].rvalue self.assertIsInstance(compound, CompoundLiteral) self.assertEqual( expand_decl(compound.type), ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual(expand_init(compound.init), []) compound = ps.ext[0].body.block_items[1].rvalue self.assertIsInstance(compound, CompoundLiteral) self.assertEqual( expand_decl(compound.type), ["Typename", ["TypeDecl", ["Struct", "jk", []]]], ) self.assertEqual(expand_init(compound.init), []) def test_parenthesized_compounds(self): e = self.parse(r""" void foo() { int a; ({}); ({ 1; }); ({ 1; 2; }); int b = ({ 1; }); int c, d = ({ int x = 1; x + 2; }); a = ({ int x = 1; 2 * x; }); }""") body = e.ext[0].body.block_items self.assertIsInstance(body[1], Compound) self.assertEqual(body[1].block_items, None) self.assertIsInstance(body[2], Compound) self.assertEqual(len(body[2].block_items), 1) self.assertIsInstance(body[2].block_items[0], Constant) self.assertIsInstance(body[3], Compound) self.assertEqual(len(body[3].block_items), 2) self.assertIsInstance(body[3].block_items[0], Constant) self.assertIsInstance(body[3].block_items[1], Constant) self.assertIsInstance(body[4], Decl) self.assertEqual( expand_init(body[4].init), ["Compound", [["Constant", "int", "1"]]] ) self.assertIsInstance(body[5], Decl) self.assertEqual(body[5].init, None) self.assertIsInstance(body[6], Decl) self.assertEqual( expand_init(body[6].init), [ "Compound", [ ["Decl", "x"], ["BinaryOp", ["ID", "x"], "+", ["Constant", "int", "2"]], ], ], ) self.assertIsInstance(body[7], Assignment) self.assertIsInstance(body[7].rvalue, Compound) self.assertEqual( expand_init(body[7].rvalue), [ "Compound", [ ["Decl", "x"], ["BinaryOp", ["Constant", "int", "2"], "*", ["ID", "x"]], ], ], ) def test_parenthesized_compounds_binary_operands(self): # Regression for #538: the compound is a binary operand, rather than # the entire right-hand side of an assignment. e = self.parse(""" float f(float z) { return z / ({ float a = 1.0; a * 2; }); } """) expr = e.ext[0].body.block_items[0].expr self.assertIsInstance(expr, BinaryOp) self.assertEqual(expr.op, "/") self.assertEqual(expr.left.name, "z") self.assertIsInstance(expr.right, Compound) decl, value = expr.right.block_items self.assertEqual(decl.name, "a") self.assertEqual(decl.init.value, "1.0") self.assertEqual( expand_init(value), ["BinaryOp", ["ID", "a"], "*", ["Constant", "int", "2"]], ) def test_parenthesized_compounds_precedence(self): # Multiplication still binds tighter than addition when statement # expressions appear as operands on either side. e = self.parse("void f() { ({ 1; }) + 2 * ({ 3; }); }") expr = e.ext[0].body.block_items[0] self.assertEqual(expr.op, "+") self.assertIsInstance(expr.left, Compound) self.assertEqual(expr.left.block_items[0].value, "1") self.assertEqual(expr.right.op, "*") self.assertEqual(expr.right.left.value, "2") self.assertIsInstance(expr.right.right, Compound) self.assertEqual(expr.right.right.block_items[0].value, "3") def test_parenthesized_compounds_unary_and_cast(self): # Unary minus applies to the statement expression before the cast. e = self.parse("void f() { (int) -({ 1.0; }); }") expr = e.ext[0].body.block_items[0] self.assertIsInstance(expr, Cast) self.assertIsInstance(expr.expr, UnaryOp) self.assertEqual(expr.expr.op, "-") self.assertIsInstance(expr.expr.expr, Compound) self.assertEqual(expr.expr.expr.block_items[0].value, "1.0") def test_parenthesized_compounds_postfix(self): # A statement expression can be the base of an array subscript. e = self.parse("void f(int *p) { ({ p; })[0]; }") expr = e.ext[0].body.block_items[0] self.assertIsInstance(expr, ArrayRef) self.assertIsInstance(expr.name, Compound) self.assertEqual(expr.name.block_items[0].name, "p") self.assertEqual(expr.subscript.value, "0") def test_parenthesized_compounds_nested_scope(self): # The inner expression sees T as a variable; after the outer # expression, T is again a typedef. e = self.parse(""" typedef int T; void f() { int x = 1 + ({ int T = 2; ({ T + 3; }); }); T y; } """) decl, after = e.ext[1].body.block_items outer = decl.init.right self.assertIsInstance(outer, Compound) self.assertEqual(outer.block_items[0].name, "T") # The final nested statement expression retains its Compound node. inner = outer.block_items[1] self.assertIsInstance(inner, Compound) self.assertEqual(inner.block_items[0].left.name, "T") self.assertEqual(inner.block_items[0].op, "+") self.assertEqual(inner.block_items[0].right.value, "3") self.assertEqual(after.type.type.names, ["T"]) def test_parenthesized_compounds_invalid_syntax(self): # Missing closing parenthesis. with self.assertRaises(ParseError): self.parse("int f() { return 1 + ({ 2; }; }") # Missing expression-statement semicolon. with self.assertRaises(ParseError): self.parse("int f() { return 1 + ({ 2 }); }") def test_enums(self): e1 = "enum mycolor op;" e1_type = self.parse(e1).ext[0].type.type self.assertIsInstance(e1_type, Enum) self.assertEqual(e1_type.name, "mycolor") self.assertEqual(e1_type.values, None) e2 = "enum mysize {large=20, small, medium} shoes;" e2_type = self.parse(e2).ext[0].type.type self.assertIsInstance(e2_type, Enum) self.assertEqual(e2_type.name, "mysize") e2_elist = e2_type.values self.assertIsInstance(e2_elist, EnumeratorList) for e2_eval in e2_elist.enumerators: self.assertIsInstance(e2_eval, Enumerator) self.assertEqual(e2_elist.enumerators[0].name, "large") self.assertEqual(e2_elist.enumerators[0].value.value, "20") self.assertEqual(e2_elist.enumerators[2].name, "medium") self.assertEqual(e2_elist.enumerators[2].value, None) # enum with trailing comma (C99 feature) e3 = """ enum { red, blue, green, } color; """ e3_type = self.parse(e3).ext[0].type.type self.assertIsInstance(e3_type, Enum) e3_elist = e3_type.values self.assertIsInstance(e3_elist, EnumeratorList) for e3_eval in e3_elist.enumerators: self.assertIsInstance(e3_eval, Enumerator) self.assertEqual(e3_elist.enumerators[0].name, "red") self.assertEqual(e3_elist.enumerators[0].value, None) self.assertEqual(e3_elist.enumerators[1].name, "blue") self.assertEqual(e3_elist.enumerators[2].name, "green") def test_enum_leading_pragma(self): enum = self.parse("enum E {\n#pragma before\nA, B };", "enum.c").ext[0].type pragma, a, b = enum.values.enumerators self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string, "before") self.assertEqual(pragma.coord.file, "enum.c") self.assertEqual(pragma.coord.line, 2) self.assertEqual(a.name, "A") self.assertEqual(b.name, "B") self.assertEqual(enum.values.coord, a.coord) def test_enum_intervening_pragma(self): enum = self.parse("enum E { A,\n#pragma between\nB = A + 1 };").ext[0].type a, pragma, b = enum.values.enumerators self.assertEqual(a.name, "A") self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string, "between") self.assertEqual(b.name, "B") self.assertIsInstance(b.value, BinaryOp) self.assertEqual(b.value.left.name, "A") def test_enum_pragma_before_comma(self): enum = self.parse("enum E { A\n#pragma between\n, B };").ext[0].type a, pragma, b = enum.values.enumerators self.assertEqual(a.name, "A") self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string, "between") self.assertEqual(b.name, "B") def test_enum_trailing_pragma(self): enum = self.parse("enum E { A\n#pragma after\n};").ext[0].type a, pragma = enum.values.enumerators self.assertEqual(a.name, "A") self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string, "after") def test_enum_pragma_after_trailing_comma(self): enum = self.parse("enum E { A,\n#pragma after\n};").ext[0].type a, pragma = enum.values.enumerators self.assertEqual(a.name, "A") self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string, "after") def test_enum_pragma_operator(self): enum = ( self.parse('enum E { _Pragma("before") A _Pragma("after") };').ext[0].type ) before, a, after = enum.values.enumerators self.assertIsInstance(before, Pragma) self.assertIsInstance(before.string, Constant) self.assertEqual(before.string.value, '"before"') self.assertEqual(a.name, "A") self.assertIsInstance(after, Pragma) self.assertEqual(after.string.value, '"after"') def test_enum_pragmas_require_enumerator(self): with self.assertRaises(ParseError): self.parse('enum E {\n#pragma foo\n_Pragma("bar") };') def test_enum_pragma_does_not_replace_comma(self): with self.assertRaises(ParseError): self.parse("enum E { A\n#pragma between\nB };") def test_enum_pragma_does_not_allow_duplicate_comma(self): with self.assertRaises(ParseError): self.parse("enum E { A,\n#pragma between\n, B };") def test_enum_pragma_does_not_allow_leading_comma(self): with self.assertRaises(ParseError): self.parse("enum E {\n#pragma before\n, A };") def test_typedef(self): # without typedef, error s1 = """ node k; """ self.assertRaises(ParseError, self.parse, s1) # now with typedef, works s2 = """ typedef void* node; node k; """ ps2 = self.parse(s2) self.assertEqual( expand_decl(ps2.ext[0]), [ "Typedef", "node", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["void"]]]], ], ) self.assertEqual( expand_decl(ps2.ext[1]), ["Decl", "k", ["TypeDecl", ["IdentifierType", ["node"]]]], ) s3 = """ typedef int T; typedef T *pT; pT aa, bb; """ ps3 = self.parse(s3) self.assertEqual( expand_decl(ps3.ext[3]), ["Decl", "bb", ["TypeDecl", ["IdentifierType", ["pT"]]]], ) s4 = """ typedef char* __builtin_va_list; typedef __builtin_va_list __gnuc_va_list; """ ps4 = self.parse(s4) self.assertEqual( expand_decl(ps4.ext[1]), [ "Typedef", "__gnuc_va_list", ["TypeDecl", ["IdentifierType", ["__builtin_va_list"]]], ], ) s5 = """typedef struct tagHash Hash;""" ps5 = self.parse(s5) self.assertEqual( expand_decl(ps5.ext[0]), ["Typedef", "Hash", ["TypeDecl", ["Struct", "tagHash", []]]], ) s6 = """typedef int (* const * const T)(void);""" ps6 = self.parse(s6) self.assertEqual( expand_decl(ps6.ext[0]), [ "Typedef", "T", [ "PtrDecl", ["const"], [ "PtrDecl", ["const"], [ "FuncDecl", [["Typename", ["TypeDecl", ["IdentifierType", ["void"]]]]], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ], ) def test_struct_union(self): s1 = """ struct { int id; char* name; } joe; """ self.assertEqual( expand_decl(self.parse(s1).ext[0]), [ "Decl", "joe", [ "TypeDecl", [ "Struct", None, [ ["Decl", "id", ["TypeDecl", ["IdentifierType", ["int"]]]], [ "Decl", "name", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ], ], ], ) s2 = """ struct node p; """ self.assertEqual( expand_decl(self.parse(s2).ext[0]), ["Decl", "p", ["TypeDecl", ["Struct", "node", []]]], ) s21 = """ union pri ra; """ self.assertEqual( expand_decl(self.parse(s21).ext[0]), ["Decl", "ra", ["TypeDecl", ["Union", "pri", []]]], ) s3 = """ struct node* p; """ self.assertEqual( expand_decl(self.parse(s3).ext[0]), ["Decl", "p", ["PtrDecl", ["TypeDecl", ["Struct", "node", []]]]], ) s4 = """ struct node; """ self.assertEqual( expand_decl(self.parse(s4).ext[0]), ["Decl", None, ["Struct", "node", []]] ) s5 = """ union { struct { int type; } n; struct { int type; int intnode; } ni; } u; """ self.assertEqual( expand_decl(self.parse(s5).ext[0]), [ "Decl", "u", [ "TypeDecl", [ "Union", None, [ [ "Decl", "n", [ "TypeDecl", [ "Struct", None, [ [ "Decl", "type", [ "TypeDecl", ["IdentifierType", ["int"]], ], ] ], ], ], ], [ "Decl", "ni", [ "TypeDecl", [ "Struct", None, [ [ "Decl", "type", [ "TypeDecl", ["IdentifierType", ["int"]], ], ], [ "Decl", "intnode", [ "TypeDecl", ["IdentifierType", ["int"]], ], ], ], ], ], ], ], ], ], ], ) s6 = """ typedef struct foo_tag { void* data; } foo, *pfoo; """ s6_ast = self.parse(s6) self.assertEqual( expand_decl(s6_ast.ext[0]), [ "Typedef", "foo", [ "TypeDecl", [ "Struct", "foo_tag", [ [ "Decl", "data", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["void"]]]], ] ], ], ], ], ) self.assertEqual( expand_decl(s6_ast.ext[1]), [ "Typedef", "pfoo", [ "PtrDecl", [ "TypeDecl", [ "Struct", "foo_tag", [ [ "Decl", "data", [ "PtrDecl", ["TypeDecl", ["IdentifierType", ["void"]]], ], ] ], ], ], ], ], ) s7 = r""" struct _on_exit_args { void * _fnargs[32]; void * _dso_handle[32]; long _fntypes; #line 77 "D:\eli\cpp_stuff\libc_include/sys/reent.h" long _is_cxa; }; """ s7_ast = self.parse(s7, filename="test.c") self.assert_coord(s7_ast.ext[0].type.decls[2], 6, 22, "test.c") self.assert_coord( s7_ast.ext[0].type.decls[3], 78, 22, r"D:\eli\cpp_stuff\libc_include/sys/reent.h", ) s8 = """ typedef enum tagReturnCode {SUCCESS, FAIL} ReturnCode; typedef struct tagEntry { char* key; char* value; } Entry; typedef struct tagNode { Entry* entry; struct tagNode* next; } Node; typedef struct tagHash { unsigned int table_size; Node** heads; } Hash; """ s8_ast = self.parse(s8) self.assertEqual( expand_decl(s8_ast.ext[3]), [ "Typedef", "Hash", [ "TypeDecl", [ "Struct", "tagHash", [ [ "Decl", "table_size", ["TypeDecl", ["IdentifierType", ["unsigned", "int"]]], ], [ "Decl", "heads", [ "PtrDecl", [ "PtrDecl", ["TypeDecl", ["IdentifierType", ["Node"]]], ], ], ], ], ], ], ], ) def test_struct_enum(self): s1 = """ struct Foo { enum Bar { A = 1 }; }; """ self.assertEqual( expand_decl(self.parse(s1).ext[0]), ["Decl", None, ["Struct", "Foo", [["Decl", None, ["Enum", "Bar", ["A"]]]]]], ) s2 = """ struct Foo { enum Bar { A = 1, B, C } bar; enum Baz { D = A } baz; } foo; """ self.assertEqual( expand_decl(self.parse(s2).ext[0]), [ "Decl", "foo", [ "TypeDecl", [ "Struct", "Foo", [ [ "Decl", "bar", ["TypeDecl", ["Enum", "Bar", ["A", "B", "C"]]], ], ["Decl", "baz", ["TypeDecl", ["Enum", "Baz", ["D"]]]], ], ], ], ], ) def test_struct_with_extra_semis_inside(self): s1 = """ struct { int a;; } foo; """ s1_ast = self.parse(s1) self.assertEqual( expand_decl(s1_ast.ext[0]), [ "Decl", "foo", [ "TypeDecl", [ "Struct", None, [["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]]], ], ], ], ) s2 = """ struct { int a;;;; float b, c; ;; char d; } foo; """ s2_ast = self.parse(s2) self.assertEqual( expand_decl(s2_ast.ext[0]), [ "Decl", "foo", [ "TypeDecl", [ "Struct", None, [ ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]], ["Decl", "b", ["TypeDecl", ["IdentifierType", ["float"]]]], ["Decl", "c", ["TypeDecl", ["IdentifierType", ["float"]]]], ["Decl", "d", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ], ], ) def test_struct_with_initial_semi(self): s1 = """ struct { ;int a; } foo; """ s1_ast = self.parse(s1) self.assertEqual( expand_decl(s1_ast.ext[0]), [ "Decl", "foo", [ "TypeDecl", [ "Struct", None, [["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]]], ], ], ], ) def test_anonymous_struct_union(self): s1 = """ union { union { int i; long l; }; struct { int type; int intnode; }; } u; """ self.assertEqual( expand_decl(self.parse(s1).ext[0]), [ "Decl", "u", [ "TypeDecl", [ "Union", None, [ [ "Decl", None, [ "Union", None, [ [ "Decl", "i", ["TypeDecl", ["IdentifierType", ["int"]]], ], [ "Decl", "l", ["TypeDecl", ["IdentifierType", ["long"]]], ], ], ], ], [ "Decl", None, [ "Struct", None, [ [ "Decl", "type", ["TypeDecl", ["IdentifierType", ["int"]]], ], [ "Decl", "intnode", ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ], ], ], ], ], ) s2 = """ struct { int i; union { int id; char* name; }; float f; } joe; """ self.assertEqual( expand_decl(self.parse(s2).ext[0]), [ "Decl", "joe", [ "TypeDecl", [ "Struct", None, [ ["Decl", "i", ["TypeDecl", ["IdentifierType", ["int"]]]], [ "Decl", None, [ "Union", None, [ [ "Decl", "id", ["TypeDecl", ["IdentifierType", ["int"]]], ], [ "Decl", "name", [ "PtrDecl", [ "TypeDecl", ["IdentifierType", ["char"]], ], ], ], ], ], ], ["Decl", "f", ["TypeDecl", ["IdentifierType", ["float"]]]], ], ], ], ], ) # ISO/IEC 9899:201x Committee Draft 2010-11-16, N1539 # section 6.7.2.1, par. 19, example 1 s3 = """ struct v { union { struct { int i, j; }; struct { long k, l; } w; }; int m; } v1; """ self.assertEqual( expand_decl(self.parse(s3).ext[0]), [ "Decl", "v1", [ "TypeDecl", [ "Struct", "v", [ [ "Decl", None, [ "Union", None, [ [ "Decl", None, [ "Struct", None, [ [ "Decl", "i", [ "TypeDecl", ["IdentifierType", ["int"]], ], ], [ "Decl", "j", [ "TypeDecl", ["IdentifierType", ["int"]], ], ], ], ], ], [ "Decl", "w", [ "TypeDecl", [ "Struct", None, [ [ "Decl", "k", [ "TypeDecl", [ "IdentifierType", ["long"], ], ], ], [ "Decl", "l", [ "TypeDecl", [ "IdentifierType", ["long"], ], ], ], ], ], ], ], ], ], ], ["Decl", "m", ["TypeDecl", ["IdentifierType", ["int"]]]], ], ], ], ], ) s4 = """ struct v { int i; float; } v2;""" # just make sure this doesn't raise ParseError self.parse(s4) def test_struct_member_without_declarator(self): # Issue #633: lone atomic, _BitInt, and typeof specifiers must not # be traversed as declarators. decl = self.parse("struct s { _Atomic(int); };").ext[0] (member,) = decl.type.decls self.assertIsNone(member.name) self.assertIsInstance(member.type, Typename) self.assertEqual(member.type.quals, ["_Atomic"]) c23 = c_parser.CParser(dialect="c23") decl = c23.parse("struct s { _BitInt(8); typeof(int); };").ext[0] bitint, typeof = decl.type.decls self.assertIsNone(bitint.name) self.assertIsInstance(bitint.type, BitIntType) self.assertIsNone(typeof.name) self.assertIsInstance(typeof.type, TypeOf) def test_struct_members_namespace(self): """Tests that structure/union member names reside in a separate namespace and can be named after existing types. """ s1 = """ typedef int Name; typedef Name NameArray[10]; struct { Name Name; Name NameArray[3]; } sye; void main(void) { sye.Name = 1; } """ s1_ast = self.parse(s1) self.assertEqual( expand_decl(s1_ast.ext[2]), [ "Decl", "sye", [ "TypeDecl", [ "Struct", None, [ [ "Decl", "Name", ["TypeDecl", ["IdentifierType", ["Name"]]], ], [ "Decl", "NameArray", [ "ArrayDecl", "3", [], ["TypeDecl", ["IdentifierType", ["Name"]]], ], ], ], ], ], ], ) self.assertEqual(s1_ast.ext[3].body.block_items[0].lvalue.field.name, "Name") def test_struct_bitfields(self): # a struct with two bitfields, one unnamed s1 = """ struct { int k:6; int :2; } joe; """ parsed_struct = self.parse(s1).ext[0] # We can see here the name of the decl for the unnamed bitfield is # None, but expand_decl doesn't show bitfield widths # ... self.assertEqual( expand_decl(parsed_struct), [ "Decl", "joe", [ "TypeDecl", [ "Struct", None, [ ["Decl", "k", ["TypeDecl", ["IdentifierType", ["int"]]]], ["Decl", None, ["TypeDecl", ["IdentifierType", ["int"]]]], ], ], ], ], ) # ... # so we test them manually self.assertEqual(parsed_struct.type.type.decls[0].bitsize.value, "6") self.assertEqual(parsed_struct.type.type.decls[1].bitsize.value, "2") def test_struct_empty(self): """ Tests that parsing an empty struct works. Empty structs do NOT follow C99 (See 6.2.5-20 of the C99 standard). This is nevertheless supported by some compilers (clang, gcc), especially when using FORTIFY code. Some compilers (visual) will fail to compile with an error. """ # an empty struct. This is NOT C99 compliant s1 = """ struct foo { }; """ parsed_struct = self.parse(s1).ext[0] self.assertEqual( expand_decl(parsed_struct), ["Decl", None, ["Struct", "foo", []]] ) s2 = """struct { } foo;""" parsed_struct = self.parse(s2).ext[0] self.assertEqual( expand_decl(parsed_struct), ["Decl", "foo", ["TypeDecl", ["Struct", None, []]]], ) s3 = """union { } foo;""" parsed_struct = self.parse(s3).ext[0] self.assertEqual( expand_decl(parsed_struct), ["Decl", "foo", ["TypeDecl", ["Union", None, []]]], ) def test_tags_namespace(self): """Tests that the tags of structs/unions/enums reside in a separate namespace and can be named after existing types. """ s1 = """ typedef int tagEntry; struct tagEntry { char* key; char* value; } Entry; """ s1_ast = self.parse(s1) self.assertEqual( expand_decl(s1_ast.ext[1]), [ "Decl", "Entry", [ "TypeDecl", [ "Struct", "tagEntry", [ [ "Decl", "key", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], [ "Decl", "value", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ], ], ], ) s2 = """ struct tagEntry; typedef struct tagEntry tagEntry; struct tagEntry { char* key; char* value; } Entry; """ s2_ast = self.parse(s2) self.assertEqual( expand_decl(s2_ast.ext[2]), [ "Decl", "Entry", [ "TypeDecl", [ "Struct", "tagEntry", [ [ "Decl", "key", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], [ "Decl", "value", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ], ], ], ) s3 = """ typedef int mytag; enum mytag {ABC, CDE}; enum mytag joe; """ s3_type = self.parse(s3).ext[1].type self.assertIsInstance(s3_type, Enum) self.assertEqual(s3_type.name, "mytag") def test_multi_decls(self): d1 = "int a, b;" self.assertEqual( self.get_decl(d1, 0), ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual( self.get_decl(d1, 1), ["Decl", "b", ["TypeDecl", ["IdentifierType", ["int"]]]], ) d2 = "char* p, notp, ar[4];" self.assertEqual( self.get_decl(d2, 0), ["Decl", "p", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]], ) self.assertEqual( self.get_decl(d2, 1), ["Decl", "notp", ["TypeDecl", ["IdentifierType", ["char"]]]], ) self.assertEqual( self.get_decl(d2, 2), [ "Decl", "ar", ["ArrayDecl", "4", [], ["TypeDecl", ["IdentifierType", ["char"]]]], ], ) def test_invalid_multiple_types_error(self): bad = ["int enum {ab, cd} fubr;", "enum kid char brbr;"] for b in bad: self.assertRaises(ParseError, self.parse, b) def test_invalid_typedef_storage_qual_error(self): """Tests that using typedef as a storage qualifier is correctly flagged as an error. """ bad = "typedef const int foo(int a) { return 0; }" self.assertRaises(ParseError, self.parse, bad) def test_duplicate_typedef(self): """Tests that redeclarations of existing types are parsed correctly. This is non-standard, but allowed by many compilers. """ d1 = """ typedef int numbertype; typedef int numbertype; """ self.assertEqual( self.get_decl(d1, 0), ["Typedef", "numbertype", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual( self.get_decl(d1, 1), ["Typedef", "numbertype", ["TypeDecl", ["IdentifierType", ["int"]]]], ) d2 = """ typedef int (*funcptr)(int x); typedef int (*funcptr)(int x); """ self.assertEqual( self.get_decl(d2, 0), [ "Typedef", "funcptr", [ "PtrDecl", [ "FuncDecl", [["Decl", "x", ["TypeDecl", ["IdentifierType", ["int"]]]]], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ) self.assertEqual( self.get_decl(d2, 1), [ "Typedef", "funcptr", [ "PtrDecl", [ "FuncDecl", [["Decl", "x", ["TypeDecl", ["IdentifierType", ["int"]]]]], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ], ) d3 = """ typedef int numberarray[5]; typedef int numberarray[5]; """ self.assertEqual( self.get_decl(d3, 0), [ "Typedef", "numberarray", ["ArrayDecl", "5", [], ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) self.assertEqual( self.get_decl(d3, 1), [ "Typedef", "numberarray", ["ArrayDecl", "5", [], ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) def test_decl_inits(self): d1 = "int a = 16;" # ~ self.parse(d1).show() self.assertEqual( self.get_decl(d1), ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]] ) self.assertEqual(self.get_decl_init(d1), ["Constant", "int", "16"]) d1_1 = "float f = 0xEF.56p1;" self.assertEqual(self.get_decl_init(d1_1), ["Constant", "double", "0xEF.56p1"]) d1_2 = "int bitmask = 0b1001010;" self.assertEqual(self.get_decl_init(d1_2), ["Constant", "int", "0b1001010"]) d2 = "long ar[] = {7, 8, 9};" self.assertEqual( self.get_decl(d2), [ "Decl", "ar", ["ArrayDecl", "", [], ["TypeDecl", ["IdentifierType", ["long"]]]], ], ) self.assertEqual( self.get_decl_init(d2), [ ["Constant", "int", "7"], ["Constant", "int", "8"], ["Constant", "int", "9"], ], ) d21 = "long ar[4] = {};" self.assertEqual(self.get_decl_init(d21), []) d3 = "char p = j;" self.assertEqual( self.get_decl(d3), ["Decl", "p", ["TypeDecl", ["IdentifierType", ["char"]]]] ) self.assertEqual(self.get_decl_init(d3), ["ID", "j"]) d4 = "char x = 'c', *p = {0, 1, 2, {4, 5}, 6};" self.assertEqual( self.get_decl(d4, 0), ["Decl", "x", ["TypeDecl", ["IdentifierType", ["char"]]]], ) self.assertEqual(self.get_decl_init(d4, 0), ["Constant", "char", "'c'"]) self.assertEqual( self.get_decl(d4, 1), ["Decl", "p", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]], ) self.assertEqual( self.get_decl_init(d4, 1), [ ["Constant", "int", "0"], ["Constant", "int", "1"], ["Constant", "int", "2"], [["Constant", "int", "4"], ["Constant", "int", "5"]], ["Constant", "int", "6"], ], ) d5 = "float d = 1.0;" self.assertEqual(self.get_decl_init(d5), ["Constant", "double", "1.0"]) d51 = "float ld = 1.0l;" self.assertEqual(self.get_decl_init(d51), ["Constant", "long double", "1.0l"]) d52 = "float ld = 1.0L;" self.assertEqual(self.get_decl_init(d52), ["Constant", "long double", "1.0L"]) d53 = "float ld = 1.0f;" self.assertEqual(self.get_decl_init(d53), ["Constant", "float", "1.0f"]) d54 = "float ld = 1.0F;" self.assertEqual(self.get_decl_init(d54), ["Constant", "float", "1.0F"]) d55 = "float ld = 0xDE.38p0;" self.assertEqual(self.get_decl_init(d55), ["Constant", "double", "0xDE.38p0"]) d56 = "float ld = 0xDE.38p0f;" self.assertEqual(self.get_decl_init(d56), ["Constant", "float", "0xDE.38p0f"]) d57 = "float ld = 0xDE.38p0F;" self.assertEqual(self.get_decl_init(d57), ["Constant", "float", "0xDE.38p0F"]) d58 = "float ld = 0xDE.38p0l;" self.assertEqual( self.get_decl_init(d58), ["Constant", "long double", "0xDE.38p0l"] ) d59 = "float ld = 0xDE.38p0L;" self.assertEqual( self.get_decl_init(d59), ["Constant", "long double", "0xDE.38p0L"] ) d6 = "int i = 1;" self.assertEqual(self.get_decl_init(d6), ["Constant", "int", "1"]) d61 = "long int li = 1l;" self.assertEqual(self.get_decl_init(d61), ["Constant", "long int", "1l"]) d62 = "unsigned int ui = 1u;" self.assertEqual(self.get_decl_init(d62), ["Constant", "unsigned int", "1u"]) d63 = "unsigned long long int ulli = 1LLU;" self.assertEqual( self.get_decl_init(d63), ["Constant", "unsigned long long int", "1LLU"] ) def test_decl_named_inits(self): d1 = "int a = {.k = 16};" self.assertEqual( self.get_decl_init(d1), [([["ID", "k"]], ["Constant", "int", "16"])] ) d2 = "int a = { [0].a = {1}, [1].a[0] = 2 };" self.assertEqual( self.get_decl_init(d2), [ ( [["ArrayDesignator", ["Constant", "int", "0"]], ["ID", "a"]], [["Constant", "int", "1"]], ), ( [ ["ArrayDesignator", ["Constant", "int", "1"]], ["ID", "a"], ["ArrayDesignator", ["Constant", "int", "0"]], ], ["Constant", "int", "2"], ), ], ) d3 = "int a = { .a = 1, .c = 3, 4, .b = 5};" self.assertEqual( self.get_decl_init(d3), [ ([["ID", "a"]], ["Constant", "int", "1"]), ([["ID", "c"]], ["Constant", "int", "3"]), ["Constant", "int", "4"], ([["ID", "b"]], ["Constant", "int", "5"]), ], ) def test_field_and_array_designators(self): # Issue #466: .x and [x] must have distinct AST representations. tree = self.parse(""" enum { x }; struct A { int x; }; struct A a = {.x = 1}; int b[] = {[x] = 2}; """) field = tree.ext[2].init.exprs[0].name[0] index = tree.ext[3].init.exprs[0].name[0] self.assertIsInstance(field, ID) self.assertEqual(field.name, "x") self.assertIsInstance(index, ArrayDesignator) self.assertIsInstance(index.expr, ID) self.assertEqual(index.expr.name, "x") def test_designated_initializer_with_typedef_name(self): # Issue #215: a field designator can have the same name as a typedef. tree = self.parse(""" typedef int Foo; struct Bar { char Foo; }; void f(void) { struct Bar bar = {.Foo = 'C'}; } """) init = tree.ext[2].body.block_items[0].init self.assertEqual( expand_init(init), [([["ID", "Foo"]], ["Constant", "char", "'C'"])] ) def test_function_definitions(self): def parse_fdef(str): return self.parse(str).ext[0] def fdef_decl(fdef): return expand_decl(fdef.decl) f1 = parse_fdef(""" int factorial(int p) { return 3; } """) self.assertEqual( fdef_decl(f1), [ "Decl", "factorial", [ "FuncDecl", [["Decl", "p", ["TypeDecl", ["IdentifierType", ["int"]]]]], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) self.assertEqual(type(f1.body.block_items[0]), Return) f2 = parse_fdef(""" char* zzz(int p, char* c) { int a; char b; a = b + 2; return 3; } """) self.assertEqual( fdef_decl(f2), [ "Decl", "zzz", [ "FuncDecl", [ ["Decl", "p", ["TypeDecl", ["IdentifierType", ["int"]]]], [ "Decl", "c", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ) self.assertEqual( list(map(type, f2.body.block_items)), [Decl, Decl, Assignment, Return] ) f3 = parse_fdef(""" char* zzz(p, c) long p, *c; { int a; char b; a = b + 2; return 3; } """) self.assertEqual( fdef_decl(f3), [ "Decl", "zzz", [ "FuncDecl", [["ID", "p"], ["ID", "c"]], ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]], ], ], ) self.assertEqual( list(map(type, f3.body.block_items)), [Decl, Decl, Assignment, Return] ) self.assertEqual( expand_decl(f3.param_decls[0]), ["Decl", "p", ["TypeDecl", ["IdentifierType", ["long"]]]], ) self.assertEqual( expand_decl(f3.param_decls[1]), ["Decl", "c", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["long"]]]]], ) # function return values and parameters may not have type information f4 = parse_fdef(""" que(p) { return 3; } """) self.assertEqual( fdef_decl(f4), [ "Decl", "que", ["FuncDecl", [["ID", "p"]], ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) def test_static_assert(self): f1 = self.parse(""" _Static_assert(1, "123"); int factorial(int p) { _Static_assert(2, "456"); _Static_assert(3); } """) self.assertEqual(expand_decl(f1.ext[0]), ["StaticAssert", "1", '"123"']) self.assertEqual( expand_decl(f1.ext[1].body.block_items[0]), ["StaticAssert", "2", '"456"'] ) self.assertEqual( expand_decl(f1.ext[1].body.block_items[1]), ["StaticAssert", "3"] ) self.assertEqual(len(f1.ext[1].body.block_items), 2) def test_unicode_character_escapes(self): for prefix in ("", "L", "u8", "u", "U"): for escape in (r"\u00e9", r"\U0001F600"): literal = f"{prefix}'{escape}'" with self.subTest(literal=literal): self.assertEqual( self.get_decl_init(f"int c = {literal};"), ["Constant", "char", literal], ) self.assertEqual( self.get_decl_init(r"int c = '\u00e9a';"), ["Constant", "int", r"'\u00e9a'"], ) def test_unified_string_literals(self): # simple string, for reference d1 = self.get_decl_init('char* s = "hello";') self.assertEqual(d1, ["Constant", "string", '"hello"']) d2 = self.get_decl_init('char* s = "hello" " world";') self.assertEqual(d2, ["Constant", "string", '"hello world"']) # the test case from issue 6 d3 = self.parse(r""" int main() { fprintf(stderr, "Wrong Params?\n" "Usage:\n" "%s \n", argv[0] ); } """) self.assertEqual( d3.ext[0].body.block_items[0].args.exprs[1].value, r'"Wrong Params?\nUsage:\n%s \n"', ) d4 = self.get_decl_init('char* s = "" "foobar";') self.assertEqual(d4, ["Constant", "string", '"foobar"']) d5 = self.get_decl_init(r'char* s = "foo\"" "bar";') self.assertEqual(d5, ["Constant", "string", r'"foo\"bar"']) # Issue #392: concatenation must not turn two characters into an escape. d6 = self.get_decl_init(r'char* s = "\1" "23";') self.assertEqual(d6, ["Constant", "string", r'"\1" "23"']) def test_unified_wstring_literals(self): d1 = self.get_decl_init('char* s = L"hello" L"world";') self.assertEqual(d1, ["Constant", "string", 'L"helloworld"']) d2 = self.get_decl_init('char* s = L"hello " L"world" L" and I";') self.assertEqual(d2, ["Constant", "string", 'L"hello world and I"']) d3 = self.get_decl_init('char* s = u8"hello" u8"world";') self.assertEqual(d3, ["Constant", "string", 'u8"helloworld"']) d4 = self.get_decl_init('char* s = u8"a" u8"b" u8"c";') self.assertEqual(d4, ["Constant", "string", 'u8"abc"']) d5 = self.get_decl_init('char* s = u"hello" u"world";') self.assertEqual(d5, ["Constant", "string", 'u"helloworld"']) def test_unified_string_literals_whitespace(self): for prefix in ("", "L", "u8", "u", "U"): for separator in ("", " ", "\t", "\n "): with self.subTest(prefix=prefix, separator=separator): literals = separator.join( f'{prefix}"{part}"' for part in ("hello ", "world", "!") ) self.assertEqual( self.get_decl_init(f"char* s = {literals};"), ["Constant", "string", f'{prefix}"hello world!"'], ) def test_unified_string_literals_empty(self): cases = [ (("", "", ""), ""), (("", "hello"), "hello"), (("hello", ""), "hello"), (("hello", "", " world"), "hello world"), (("", "hello", "", " world", ""), "hello world"), ] for prefix in ("", "L", "u8", "u", "U"): for parts, expected in cases: with self.subTest(prefix=prefix, parts=parts): literals = " ".join(f'{prefix}"{part}"' for part in parts) self.assertEqual( self.get_decl_init(f"char* s = {literals};"), ["Constant", "string", f'{prefix}"{expected}"'], ) def test_unified_string_literals_escapes(self): cases = [ ((r'"foo\""', r'"\"bar"'), r'"foo\"\"bar"'), ((r'"\\"', r'"\n\t"', r'"\0end"'), r'"\\\n\t\0end"'), ] for prefix in ("", "L", "u8", "u", "U"): for parts, expected in cases: with self.subTest(prefix=prefix, parts=parts): literals = " ".join(prefix + part for part in parts) self.assertEqual( self.get_decl_init(f"char* s = {literals};"), ["Constant", "string", prefix + expected], ) def test_unified_string_literals_escape_boundaries(self): cases = [ (r'"\1" "23"', r'"\1" "23"'), (r'"\12" "3"', r'"\12" "3"'), (r'"\123" "4"', r'"\1234"'), (r'"\1" "89"', r'"\189"'), (r'"\x1" "aF"', r'"\x1" "aF"'), (r'"\x0012" "3"', r'"\x0012" "3"'), (r'"\x1" "g"', r'"\x1g"'), (r'"\\x1" "a"', r'"\\x1a"'), (r'"\\1" "23"', r'"\\123"'), (r'"\\\x1" "a"', r'"\\\x1" "a"'), (r'"\u00e9" "a"', r'"\u00e9a"'), (r'"\U0001F600" "a"', r'"\U0001F600a"'), (r'"\1" "" "2" "3"', r'"\1" "23"'), (r'"\x1" "a\2" "3" "end"', r'"\x1" "a\2" "3end"'), ] for prefix in ("", "L", "u8", "u", "U"): for literals, expected in cases: with self.subTest(prefix=prefix, literals=literals): ast = self.parse(f"void *s = {prefix}{literals};") self.assertEqual( expand_init(ast.ext[0].init), ["Constant", "string", prefix + expected], ) self.assert_coord(ast.ext[0].init, 1, 11) # A later encoding prefix still applies to the entire string. for prefix in ("L", "u8", "u", "U"): with self.subTest(prefix=prefix): self.assertEqual( self.get_decl_init(r'void *s = "\x1" ' + prefix + '"a";'), ["Constant", "string", prefix + r'"\x1" "a"'], ) def test_unified_string_literals_trigraph_boundaries(self): for last in "=/'()!<>-": for literals in (f'"?" "?{last}"', f'"??" "{last}"'): with self.subTest(literals=literals): self.assertEqual( self.get_decl_init(f"char *s = {literals};"), ["Constant", "string", literals], ) self.assertEqual( self.get_decl_init('char *s = "?" "?" "=";'), ["Constant", "string", '"??" "="'], ) def test_unified_string_literals_expression_boundaries(self): ast = self.parse(""" int f(void) { consume("a" "b", "c" "d"); char *s[] = {"e" "f", "g" "h"}; return ("i" "j")[1]; } """) call, decl, ret = ast.ext[0].body.block_items self.assertIsInstance(call, FuncCall) self.assertEqual( expand_init(call.args), [["Constant", "string", '"ab"'], ["Constant", "string", '"cd"']], ) self.assertEqual( expand_init(decl.init), [["Constant", "string", '"ef"'], ["Constant", "string", '"gh"']], ) self.assertIsInstance(ret, Return) self.assertIsInstance(ret.expr, ArrayRef) self.assertEqual(expand_init(ret.expr.name), ["Constant", "string", '"ij"']) self.assertEqual(expand_init(ret.expr.subscript), ["Constant", "int", "1"]) def test_unified_string_literals_static_assert(self): ast = self.parse('_Static_assert(1, "hello" " " "world");') self.assertEqual( expand_decl(ast.ext[0]), ["StaticAssert", "1", '"hello world"'] ) def test_unified_string_literals_mixed_prefix(self): for prefix in ("L", "u8", "u", "U"): for parts in ( f'{prefix}"hello" " world"', f'"hello" {prefix}" world"', f'"hello" {prefix}" " "world"', ): with self.subTest(prefix=prefix, parts=parts): self.assertEqual( self.get_decl_init(f"void *s = {parts};"), ["Constant", "string", f'{prefix}"hello world"'], ) def test_unified_string_literals_coord(self): for prefix in ("", "L", "u8", "u", "U"): with self.subTest(prefix=prefix): ast = self.parse( f'char* s =\n {prefix}"hello "\n {prefix}"world";', filename="strings.c", ) self.assertEqual( expand_init(ast.ext[0].init), ["Constant", "string", f'{prefix}"hello world"'], ) self.assert_coord(ast.ext[0].init, 2, 5, "strings.c") def test_inline_specifier(self): ps2 = self.parse("static inline void inlinefoo(void);") self.assertEqual(ps2.ext[0].funcspec, ["inline"]) def test_noreturn_specifier(self): ps2 = self.parse("static _Noreturn void noreturnfoo(void);") self.assertEqual(ps2.ext[0].funcspec, ["_Noreturn"]) # variable length array def test_vla(self): ps2 = self.parse(r""" int main() { int size; int var[size = 5]; int var2[*]; } """) self.assertIsInstance(ps2.ext[0].body.block_items[1].type.dim, Assignment) self.assertIsInstance(ps2.ext[0].body.block_items[2].type.dim, ID) def test_pragma(self): s1 = r""" #pragma bar void main() { #pragma foo for(;;) {} #pragma baz { int i = 0; } #pragma } struct s { #pragma baz } s; _Pragma("other \"string\"") """ s1_ast = self.parse(s1) self.assertIsInstance(s1_ast.ext[0], Pragma) self.assertEqual(s1_ast.ext[0].string, "bar") self.assertEqual(s1_ast.ext[0].coord.line, 2) self.assertIsInstance(s1_ast.ext[1].body.block_items[0], Pragma) self.assertEqual(s1_ast.ext[1].body.block_items[0].string, "foo") self.assertEqual(s1_ast.ext[1].body.block_items[0].coord.line, 4) self.assertIsInstance(s1_ast.ext[1].body.block_items[2], Pragma) self.assertEqual(s1_ast.ext[1].body.block_items[2].string, "baz") self.assertEqual(s1_ast.ext[1].body.block_items[2].coord.line, 6) self.assertIsInstance(s1_ast.ext[1].body.block_items[4], Pragma) self.assertEqual(s1_ast.ext[1].body.block_items[4].string, "") self.assertEqual(s1_ast.ext[1].body.block_items[4].coord.line, 10) self.assertIsInstance(s1_ast.ext[2].type.type.decls[0], Pragma) self.assertEqual(s1_ast.ext[2].type.type.decls[0].string, "baz") self.assertEqual(s1_ast.ext[2].type.type.decls[0].coord.line, 13) self.assertIsInstance(s1_ast.ext[3], Pragma) self.assertEqual(s1_ast.ext[3].string.value, r'"other \"string\""') self.assertEqual(s1_ast.ext[3].coord.line, 15) def test_pragma_before_declaration_semicolon_issue_478(self): ast = self.parse( """struct knote; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wnullability-completeness" struct klist { struct knote *slh_first; } #pragma clang diagnostic pop ; """, "event.h", ) forward, push, ignored, decl, pop = ast.ext self.assertEqual(forward.type.name, "knote") self.assertIsInstance(push, Pragma) self.assertEqual(push.string, "clang diagnostic push") self.assertEqual( ignored.string, 'clang diagnostic ignored "-Wnullability-completeness"' ) self.assertIsInstance(decl.type, Struct) self.assertEqual(decl.type.name, "klist") self.assertEqual(decl.type.decls[0].name, "slh_first") self.assertIsInstance(pop, Pragma) self.assertEqual(pop.string, "clang diagnostic pop") self.assertEqual(pop.coord.file, "event.h") self.assertEqual(pop.coord.line, 5) def test_pragma_before_initialized_declaration_semicolon(self): ast = self.parse('int a = 1, b = 2 _Pragma("first")\n#pragma second\n; int c;') a, b, first, second, c = ast.ext self.assertEqual(a.init.value, "1") self.assertEqual(b.init.value, "2") self.assertIsInstance(first, Pragma) self.assertEqual(first.string.value, '"first"') self.assertIsInstance(second, Pragma) self.assertEqual(second.string, "second") self.assertEqual(c.name, "c") def test_pragma_before_local_declaration_semicolon(self): ast = self.parse('void f(void) { int x _Pragma("after"); x = 1; }') decl, pragma, assignment = ast.ext[0].body.block_items self.assertEqual(decl.name, "x") self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string.value, '"after"') self.assertIsInstance(assignment, Assignment) def test_pragma_before_typedef_semicolon(self): ast = self.parse("typedef int T\n#pragma after\n; T value;") typedef, pragma, decl = ast.ext self.assertIsInstance(typedef, Typedef) self.assertEqual(typedef.name, "T") self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string, "after") self.assertEqual(decl.type.type.names, ["T"]) def test_pragma_before_struct_member_semicolon(self): ast = self.parse('struct S { int x : 3 _Pragma("after"); int y; };') x, pragma, y = ast.ext[0].type.decls self.assertEqual(x.bitsize.value, "3") self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string.value, '"after"') self.assertEqual(y.name, "y") def test_pragma_before_anonymous_union_member_semicolon(self): ast = self.parse('struct S { union { int x; } _Pragma("after"); int y; };') anonymous, pragma, y = ast.ext[0].type.decls self.assertIsNone(anonymous.name) self.assertIsInstance(anonymous.type, Union) self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string.value, '"after"') self.assertEqual(y.name, "y") def test_pragma_before_for_declaration_semicolon(self): ast = self.parse( 'void f(void) { for (int i = 0 _Pragma("after"); i < 2; ++i) {} }' ) loop = ast.ext[0].body.block_items[0] decl, pragma = loop.init.decls self.assertEqual(decl.name, "i") self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string.value, '"after"') self.assertIsInstance(loop.cond, BinaryOp) self.assertEqual(loop.next.op, "++") def test_pragma_before_knr_declaration_semicolon(self): ast = self.parse('int f(x, y) int x _Pragma("after"); int y; { return x + y; }') x, pragma, y = ast.ext[0].param_decls self.assertEqual(x.name, "x") self.assertIsInstance(pragma, Pragma) self.assertEqual(pragma.string.value, '"after"') self.assertEqual(y.name, "y") def test_declaration_pragma_requires_semicolon(self): with self.assertRaises(ParseError): self.parse('struct S { int x; } _Pragma("after")') def test_declaration_pragma_does_not_end_declaration(self): with self.assertRaises(ParseError): self.parse('int x _Pragma("after") int y;') def test_c23_attributes_with_trailing_declaration_pragma(self): ast = c_parser.CParser(dialect="c23").parse( '[[deprecated]] auto x = 1 _Pragma("global"); ' 'void f(void) { [[maybe_unused]] auto y = 2 _Pragma("local"); }' ) x, global_pragma, func = ast.ext self.assertEqual(x.attributes[0].attributes[0].name, "deprecated") self.assertEqual(global_pragma.string.value, '"global"') y, local_pragma = func.body.block_items self.assertEqual(y.attributes[0].attributes[0].name, "maybe_unused") self.assertEqual(local_pragma.string.value, '"local"') def test_c23_attributes_cannot_prefix_pragma(self): with self.assertRaises(ParseError): c_parser.CParser(dialect="c23").parse('[[deprecated]] _Pragma("after")') def test_pragmacomp_or_statement(self): s1 = r""" void main() { int sum = 0; for (int i; i < 3; i++) #pragma omp critical sum += 1; while(sum < 10) #pragma omp critical sum += 1; mylabel: #pragma foo sum += 10; if (sum > 10) #pragma bar #pragma baz sum = 10; switch (sum) case 10: #pragma foo sum = 20; } """ s1_ast = self.parse(s1) self.assertIsInstance(s1_ast.ext[0].body.block_items[1], For) self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, Compound) self.assertIsInstance( s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Pragma ) self.assertIsInstance( s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Assignment ) self.assertIsInstance(s1_ast.ext[0].body.block_items[2], While) self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, Compound) self.assertIsInstance( s1_ast.ext[0].body.block_items[2].stmt.block_items[0], Pragma ) self.assertIsInstance( s1_ast.ext[0].body.block_items[2].stmt.block_items[1], Assignment ) self.assertIsInstance(s1_ast.ext[0].body.block_items[3], Label) self.assertIsInstance(s1_ast.ext[0].body.block_items[3].stmt, Compound) self.assertIsInstance( s1_ast.ext[0].body.block_items[3].stmt.block_items[0], Pragma ) self.assertIsInstance( s1_ast.ext[0].body.block_items[3].stmt.block_items[1], Assignment ) self.assertIsInstance(s1_ast.ext[0].body.block_items[4], If) self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue, Compound) self.assertIsInstance( s1_ast.ext[0].body.block_items[4].iftrue.block_items[0], Pragma ) self.assertIsInstance( s1_ast.ext[0].body.block_items[4].iftrue.block_items[1], Pragma ) self.assertIsInstance( s1_ast.ext[0].body.block_items[4].iftrue.block_items[2], Assignment ) self.assertIsInstance(s1_ast.ext[0].body.block_items[5], Switch) self.assertIsInstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0], Compound) self.assertIsInstance( s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[0], Pragma ) self.assertIsInstance( s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[1], Assignment ) class TestCParser_static_assert(TestCParser_base): def test_aggregate_members(self): for kind in ("struct", "union"): with self.subTest(kind=kind): ast = self.parse(f""" {kind} S {{ _Static_assert(1, "before"); int x; _Static_assert(2); struct {{ int y; _Static_assert(3, "nested"); }} member; }}; """) members = ast.ext[0].type.decls self.assertEqual( [type(n) for n in members], [StaticAssert, Decl, StaticAssert, Decl] ) self.assertEqual( expand_decl(members[0]), ["StaticAssert", "1", '"before"'] ) self.assertEqual(expand_decl(members[2]), ["StaticAssert", "2"]) nested = members[3].type.type.decls self.assertEqual([type(n) for n in nested], [Decl, StaticAssert]) self.assertEqual( expand_decl(nested[1]), ["StaticAssert", "3", '"nested"'] ) def test_semicolon_consumption(self): ast = self.parse(""" _Static_assert(1, "file"); _Static_assert(2); void f(void) { _Static_assert(3, "block"); _Static_assert(4);; int x; } """) self.assertEqual( [type(n) for n in ast.ext], [StaticAssert, StaticAssert, FuncDef] ) self.assertEqual( [type(n) for n in ast.ext[2].body.block_items], [StaticAssert, StaticAssert, EmptyStatement, Decl], ) def test_for_initializer(self): for args in ('1, "init"', "1"): with self.subTest(args=args): ast = self.parse( f"void f(void) {{ for (_Static_assert({args}); ; ) {{}} }}" ) loop = ast.ext[0].body.block_items[0] self.assertIsInstance(loop, For) self.assertIsInstance(loop.init, DeclList) self.assertEqual(len(loop.init.decls), 1) self.assertIsInstance(loop.init.decls[0], StaticAssert) self.assertIsNone(loop.cond) self.assertIsNone(loop.next) def test_message_literals(self): for prefix in ("", "L", "u8", "u", "U"): for message, expected in ( (f'{prefix}""', f'{prefix}""'), (f'{prefix}"hello"', f'{prefix}"hello"'), (f'{prefix}"hello" {prefix}" world"', f'{prefix}"hello world"'), (f'"hello" {prefix}" " "world"', f'{prefix}"hello world"'), ): with self.subTest(message=message): ast = self.parse(f"_Static_assert(1, {message});") self.assertEqual( expand_decl(ast.ext[0]), ["StaticAssert", "1", expected] ) def test_coordinates(self): ast = self.parse( '\n_Static_assert(\n 1,\n u8"hello" " world"\n);\n', filename="assert.c", ) assertion = ast.ext[0] self.assert_coord(assertion, 2, 1, "assert.c") self.assert_coord(assertion.cond, 3, 3, "assert.c") self.assert_coord(assertion.message, 4, 3, "assert.c") def test_missing_semicolon(self): for assertion in ('_Static_assert(1, "ok")', "_Static_assert(1)"): for source in ( assertion, f"{assertion} int x;", f"{assertion} _Static_assert(1);", f"void f(void) {{ {assertion} }}", f"struct S {{ int x; {assertion} }};", f"union U {{ {assertion} int x; }};", ): with self.subTest(source=source): self.assertRaises(ParseError, self.parse, source) def test_invalid_syntax(self): for args in ( "", ', "message"', '1 "message"', "1,", "1, 2", "1, message", '1, ("message")', '1, "message",', '1, "message", "extra"', 'x = 1, "message"', ): with self.subTest(args=args): self.assertRaises(ParseError, self.parse, f"_Static_assert({args});") def test_invalid_statement_positions(self): for statement in ( 'if (1) _Static_assert(1, "if");', 'if (1) {} else _Static_assert(1, "else");', 'while (1) _Static_assert(1, "while");', 'do _Static_assert(1, "do"); while (0);', 'for (;;) _Static_assert(1, "for");', ): with self.subTest(statement=statement): self.assertRaises( ParseError, self.parse, f"void f(void) {{ {statement} }}" ) class TestCParser_generic_selection(TestCParser_base): def test_associations(self): selection = ( self.parse("int v = _Generic(x, int: 1, default: 2, float: 3);").ext[0].init ) self.assertIsInstance(selection, GenericSelection) self.assertEqual(expand_init(selection.expr), ["ID", "x"]) self.assertEqual(len(selection.associations), 3) for association in selection.associations: self.assertIsInstance(association, GenericAssociation) first, default, last = selection.associations self.assertEqual( expand_decl(first.type), ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertIsNone(default.type) self.assertEqual( expand_decl(last.type), ["Typename", ["TypeDecl", ["IdentifierType", ["float"]]]], ) self.assertEqual( [a.expr.value for a in selection.associations], ["1", "2", "3"] ) def test_single_association(self): for association in ("int: 1", "default: 1"): with self.subTest(association=association): ast = self.parse(f"int v = _Generic(x, {association});") selection = ast.ext[0].init self.assertEqual(len(selection.associations), 1) self.assertEqual(selection.associations[0].expr.value, "1") def test_association_type_names(self): ast = self.parse(""" typedef int T; int v = _Generic(x, T: 1, const T *: 2, int (*)(int, int): 3, int[3]: 4, struct S: 5); """) types = [a.type for a in ast.ext[1].init.associations] for typ in types: self.assertIsInstance(typ, Typename) self.assertEqual(types[0].type.type.names, ["T"]) self.assertEqual( expand_decl(types[1]), [ "Typename", ["const"], ["PtrDecl", ["TypeDecl", ["IdentifierType", ["T"]]]], ], ) self.assertIsInstance(types[2].type, PtrDecl) self.assertIsInstance(types[2].type.type, FuncDecl) self.assertEqual(len(types[2].type.type.args.params), 2) self.assertIsInstance(types[3].type, ArrayDecl) self.assertEqual(types[3].type.dim.value, "3") self.assertIsInstance(types[4].type.type, Struct) self.assertEqual(types[4].type.type.name, "S") def test_typedef_scope(self): ast = self.parse(""" typedef int T; int f(void) { int T; return _Generic(T, int: 1); } int v = _Generic(0, T: 2); """) selection = ast.ext[1].body.block_items[1].expr self.assertEqual(expand_init(selection.expr), ["ID", "T"]) self.assertEqual(ast.ext[2].init.associations[0].type.type.type.names, ["T"]) def test_assignment_and_conditional_expressions(self): selection = ( self.parse("int v = _Generic(x = y, int: a = b, default: flag ? c : d);") .ext[0] .init ) self.assertIsInstance(selection.expr, Assignment) self.assertEqual(selection.expr.lvalue.name, "x") self.assertEqual(selection.expr.rvalue.name, "y") assignment, conditional = [a.expr for a in selection.associations] self.assertIsInstance(assignment, Assignment) self.assertEqual(assignment.lvalue.name, "a") self.assertEqual(assignment.rvalue.name, "b") self.assertIsInstance(conditional, TernaryOp) self.assertEqual(conditional.iftrue.name, "c") self.assertEqual(conditional.iffalse.name, "d") def test_comma_boundaries(self): ast = self.parse( "int v = _Generic((a, b), int: (c, d), default: f(e, g)), w = 1;" ) self.assertEqual([decl.name for decl in ast.ext], ["v", "w"]) selection = ast.ext[0].init self.assertIsInstance(selection.expr, ExprList) self.assertEqual([n.name for n in selection.expr.exprs], ["a", "b"]) self.assertEqual(len(selection.associations), 2) first, second = selection.associations self.assertIsInstance(first.expr, ExprList) self.assertEqual([n.name for n in first.expr.exprs], ["c", "d"]) self.assertIsInstance(second.expr, FuncCall) self.assertEqual([n.name for n in second.expr.args.exprs], ["e", "g"]) def test_nested_selections(self): selection = ( self.parse(""" int v = _Generic(_Generic(x, int: 0, default: 1), int: _Generic(y, float: 2, default: 3), default: 4); """) .ext[0] .init ) self.assertIsInstance(selection.expr, GenericSelection) self.assertEqual(selection.expr.expr.name, "x") self.assertEqual(len(selection.expr.associations), 2) inner = selection.associations[0].expr self.assertIsInstance(inner, GenericSelection) self.assertEqual(inner.expr.name, "y") self.assertEqual(len(inner.associations), 2) self.assertEqual(selection.associations[1].expr.value, "4") def test_expression_contexts(self): body = ( self.parse(""" int f(int x) { _Generic(x, int: 0); if (x) _Generic(x, default: 1); for (_Generic(x, default: 2); _Generic(x, default: 3); _Generic(x, default: 4)) ; int a[_Generic(x, int: 5)]; return _Generic(x, int: 6); } """) .ext[0] .body.block_items ) expressions = [ body[0], body[1].iftrue, body[2].init, body[2].cond, body[2].next, body[3].type.dim, body[4].expr, ] for i, expr in enumerate(expressions): self.assertIsInstance(expr, GenericSelection) self.assertEqual(expr.associations[0].expr.value, str(i)) def test_postfix_and_precedence(self): for suffix, klass, attr in ( ("(x)", FuncCall, "name"), ("[0]", ArrayRef, "name"), (".field", StructRef, "name"), ("->field", StructRef, "name"), ("++", UnaryOp, "expr"), ): with self.subTest(suffix=suffix): ast = self.parse(f"int v = _Generic(x, default: y){suffix};") expr = ast.ext[0].init self.assertIsInstance(expr, klass) self.assertIsInstance(getattr(expr, attr), GenericSelection) expr = self.parse("int v = 1 + _Generic(x, int: 2) * 3;").ext[0].init self.assertEqual(expr.op, "+") self.assertEqual(expr.right.op, "*") self.assertIsInstance(expr.right.left, GenericSelection) def test_coordinates(self): selection = ( self.parse( "int v =\n _Generic(x,\n const int *: 1,\n default: 2);\n", filename="generic.c", ) .ext[0] .init ) self.assert_coord(selection, 2, 3, "generic.c") self.assert_coord(selection.expr, 2, 12, "generic.c") self.assert_coord(selection.associations[0], 3, 5, "generic.c") self.assert_coord(selection.associations[0].expr, 3, 18, "generic.c") self.assert_coord(selection.associations[1], 4, 5, "generic.c") def test_invalid_syntax(self): for expr in ( "_Generic()", "_Generic(x)", "_Generic(x,)", "_Generic(, int: 1)", "_Generic(x int: 1)", "_Generic(x, int 1)", "_Generic(x, int:)", "_Generic(x, int: 1,)", "_Generic(x, default 1)", "_Generic(x, default:)", "_Generic(x, unknown_type: 1)", "_Generic(x, int value: 1)", "_Generic(x, int: 1, 2)", "_Generic x, int: 1", ): with self.subTest(expr=expr): self.assertRaises(ParseError, self.parse, f"int v = {expr};") for source in ( "int v = _Generic(", "int v = _Generic(x,", "int v = _Generic(x, int:", "int v = _Generic(x, int: 1", ): with self.subTest(source=source): self.assertRaises(ParseError, self.parse, source) class TestCParser_dialects(unittest.TestCase): def test_legacy_identifiers(self): source = """ typedef int bool; bool true = 1, false = 0; int alignas, alignof, static_assert, thread_local; int constexpr, typeof, typeof_unqual; void *nullptr; _Bool b = true; void *p = nullptr; """ for parser in (c_parser.CParser(), c_parser.CParser(dialect="legacy")): ast = parser.parse(source) self.assertIsInstance(ast.ext[0], Typedef) self.assertEqual(ast.ext[1].type.type.names, ["bool"]) self.assertIsInstance(ast.ext[-2].init, ID) self.assertEqual(ast.ext[-2].init.name, "true") self.assertIsInstance(ast.ext[-1].init, ID) self.assertEqual(ast.ext[-1].init.name, "nullptr") def test_c23_keyword_aliases(self): parser = c_parser.CParser(dialect="c23") ast = parser.parse(""" alignas(16) thread_local bool flag = false; int alignment = alignof(bool); _Alignas(16) _Thread_local _Bool old_flag = 0; int old_alignment = _Alignof(_Bool); """) flag, alignment, old_flag, old_alignment = ast.ext self.assertEqual(flag.type.type.names, ["bool"]) self.assertEqual(flag.storage, ["thread_local"]) self.assertEqual(flag.align[0].alignment.value, "16") self.assertEqual(alignment.init.op, "alignof") self.assertEqual(alignment.init.expr.type.type.names, ["bool"]) self.assertEqual(old_flag.type.type.names, ["_Bool"]) self.assertEqual(old_flag.storage, ["_Thread_local"]) self.assertEqual(old_alignment.init.op, "_Alignof") def test_c23_constexpr(self): parser = c_parser.CParser(dialect="c23") declarations = """ constexpr T limit = 16; int constexpr next = limit + 1; static constexpr double scale = 0.5; constexpr bool enabled = true; constexpr int values[] = {1, 2}; """ for block_scope in (False, True): with self.subTest(block_scope=block_scope): source = declarations if block_scope: source = "void f(void) {" + declarations + "}" ast = parser.parse("typedef int T;" + source) decls = ast.ext[1].body.block_items if block_scope else ast.ext[1:] limit, next_value, scale, enabled, values = decls for decl in (limit, next_value, enabled, values): self.assertEqual(decl.storage, ["constexpr"]) self.assertEqual(scale.storage, ["static", "constexpr"]) self.assertEqual(limit.type.type.names, ["T"]) self.assertEqual(expand_init(limit.init), ["Constant", "int", "16"]) self.assertIsInstance(next_value.init, BinaryOp) self.assertEqual(next_value.init.left.name, "limit") self.assertEqual(scale.init.value, "0.5") self.assertEqual( expand_init(enabled.init), ["Constant", "bool", "true"] ) self.assertIsInstance(values.type, ArrayDecl) self.assertEqual([expr.value for expr in values.init.exprs], ["1", "2"]) def test_constexpr_dialect(self): for parser in (c_parser.CParser(), c_parser.CParser(dialect="legacy")): ast = parser.parse("int constexpr = 1; int x = constexpr;") self.assertEqual(ast.ext[0].name, "constexpr") self.assertIsInstance(ast.ext[1].init, ID) self.assertEqual(ast.ext[1].init.name, "constexpr") self.assertRaises(ParseError, parser.parse, "constexpr int x = 1;") def test_c23_static_assert_contexts(self): parser = c_parser.CParser(dialect="c23") ast = parser.parse(""" static_assert(true); struct S { static_assert(true, "member"); bool value; }; void f(void) { static_assert(!false); _Static_assert(true); } """) assertions = [ ast.ext[0], ast.ext[1].type.decls[0], *ast.ext[2].body.block_items, ] for node in assertions: self.assertIsInstance(node, StaticAssert) self.assertIsNone(assertions[0].message) self.assertEqual(assertions[1].message.value, '"member"') def test_c23_predefined_constants(self): parser = c_parser.CParser(dialect="c23") ast = parser.parse( "bool t = true;\nbool f = false;\nvoid *p = nullptr;", "c23.c" ) expected = [ ("bool", "true", 10), ("bool", "false", 10), ("nullptr_t", "nullptr", 11), ] for line, (decl, (typ, value, column)) in enumerate( zip(ast.ext, expected), start=1 ): node = decl.init self.assertIsInstance(node, Constant) self.assertEqual((node.type, node.value), (typ, value)) self.assertEqual(str(node.coord), f"c23.c:{line}:{column}") def test_c23_constants_start_statements(self): parser = c_parser.CParser(dialect="c23") ast = parser.parse(""" void f(void) { true; false; nullptr; label: true; if (true) false; while (false) nullptr; } """) stmts = ast.ext[0].body.block_items for node, value in zip(stmts[:3], ("true", "false", "nullptr")): self.assertIsInstance(node, Constant) self.assertEqual(node.value, value) self.assertIsInstance(stmts[3].stmt, Constant) self.assertIsInstance(stmts[4].iftrue, Constant) self.assertIsInstance(stmts[5].stmt, Constant) def test_c23_reserved_identifiers(self): parser = c_parser.CParser(dialect="c23") for source in ( "typedef int bool; bool x;", "int true;", "int false;", "void *nullptr;", "int *alignas;", "int *alignof;", "int *static_assert;", "int *thread_local;", "int *constexpr;", "int *typeof;", "int *typeof_unqual;", "int *_BitInt;", "int *_Decimal32;", "int *_Decimal64;", "int *_Decimal128;", ): with self.subTest(source=source): self.assertRaises(ParseError, parser.parse, source) def test_c23_unsupported_keywords_are_reserved(self): parser = c_parser.CParser(dialect="c23") legacy = c_parser.CParser() self.assertEqual(legacy.parse("int _Imaginary;").ext[0].name, "_Imaginary") self.assertRaises(ParseError, parser.parse, "int _Imaginary;") self.assertRaises(ParseError, parser.parse, "_Imaginary double x;") def test_dialect_isolation_and_parser_reuse(self): legacy = c_parser.CParser() c23 = c_parser.CParser(dialect="c23") another_legacy = c_parser.CParser(dialect="legacy") for _ in range(2): for parser, expected_type in ( (legacy, ID), (c23, Constant), (another_legacy, ID), ): with self.subTest(expected_type=expected_type): ast = parser.parse("_Bool b = true; void *p = nullptr;") for decl in ast.ext: self.assertIsInstance(decl.init, expected_type) legacy.parse("typedef int bool; bool x;") self.assertRaises(ParseError, c23.parse, "typedef int bool;") def test_invalid_dialect(self): with self.assertRaisesRegex(ValueError, "Unknown dialect"): c_parser.CParser(dialect="c99") # ty: ignore[invalid-argument-type] class TestCParser_c23_grammar(TestCParser_base): def setUp(self): self.cparser = c_parser.CParser(dialect="c23") def test_ellipsis_only_declaration(self): decl = self.parse("void f(...);", filename="variadic.c").ext[0] self.assertIsInstance(decl.type, FuncDecl) self.assertIsInstance(decl.type.args, ParamList) self.assertEqual(len(decl.type.args.params), 1) self.assertIsInstance(decl.type.args.params[0], EllipsisParam) self.assert_coord(decl.type.args, 1, 8, "variadic.c") self.assert_coord(decl.type.args.params[0], 1, 8, "variadic.c") def test_ellipsis_only_definition(self): ast = self.parse("typedef int T; int f(...) { T value = 0; return value; }") func = ast.ext[1] self.assertIsInstance(func, FuncDef) self.assertEqual(len(func.decl.type.args.params), 1) self.assertIsInstance(func.decl.type.args.params[0], EllipsisParam) self.assertEqual(func.body.block_items[0].type.type.names, ["T"]) self.assertIsInstance(func.body.block_items[1], Return) def test_ellipsis_only_function_pointer(self): decl = self.parse("void (*callback)(...);").ext[0] self.assertIsInstance(decl.type, PtrDecl) self.assertIsInstance(decl.type.type, FuncDecl) self.assertEqual(len(decl.type.type.args.params), 1) self.assertIsInstance(decl.type.type.args.params[0], EllipsisParam) def test_ellipsis_only_abstract_function_parameter(self): decl = self.parse("void f(int (...));").ext[0] param = decl.type.args.params[0] self.assertIsInstance(param, Typename) self.assertIsInstance(param.type, FuncDecl) self.assertEqual(len(param.type.args.params), 1) self.assertIsInstance(param.type.args.params[0], EllipsisParam) def test_ellipsis_only_abstract_function_pointer_parameter(self): decl = self.parse("void f(int (*)(...));").ext[0] param = decl.type.args.params[0] self.assertIsInstance(param, Typename) self.assertIsInstance(param.type, PtrDecl) self.assertIsInstance(param.type.type, FuncDecl) self.assertEqual(len(param.type.type.args.params), 1) self.assertIsInstance(param.type.type.args.params[0], EllipsisParam) def test_ellipsis_only_function_pointer_cast(self): decl = self.parse("void (*callback)(...) = (void (*)(...))0;").ext[0] self.assertIsInstance(decl.init, Cast) pointer = decl.init.to_type.type self.assertIsInstance(pointer, PtrDecl) self.assertIsInstance(pointer.type, FuncDecl) self.assertEqual(len(pointer.type.args.params), 1) self.assertIsInstance(pointer.type.args.params[0], EllipsisParam) def test_ellipsis_only_rejected_in_legacy(self): parser = c_parser.CParser(dialect="legacy") with self.assertRaisesRegex( ParseError, "Ellipsis-only parameter lists require C23" ): parser.parse("void f(...);") with self.assertRaisesRegex( ParseError, "Ellipsis-only parameter lists require C23" ): parser.parse("void f(...) {}") with self.assertRaisesRegex( ParseError, "Ellipsis-only parameter lists require C23" ): parser.parse("void (*callback)(...);") with self.assertRaisesRegex( ParseError, "Ellipsis-only parameter lists require C23" ): parser.parse("void f(int (...));") with self.assertRaisesRegex( ParseError, "Ellipsis-only parameter lists require C23" ): parser.parse("void f(int (*)(...));") with self.assertRaisesRegex( ParseError, "Ellipsis-only parameter lists require C23" ): parser.parse("void f(void) { (void (*)(...))0; }") def test_invalid_ellipsis_parameter_lists(self): self.assertRaises(ParseError, self.parse, "void f(, ...);") self.assertRaises(ParseError, self.parse, "void f(...,);") self.assertRaises(ParseError, self.parse, "void f(..., int x);") self.assertRaises(ParseError, self.parse, "void f(... ...);") self.assertRaises(ParseError, self.parse, "void f(int x ...);") self.assertRaises(ParseError, self.parse, "void f(...") self.assertRaises(ParseError, self.parse, "void f(int (...,));") self.assertRaises(ParseError, self.parse, "void f(int (*)(..., int));") def test_named_variadic_parameter_list(self): decl = self.parse("void f(int x, ...);").ext[0] self.assertEqual(len(decl.type.args.params), 2) self.assertEqual(decl.type.args.params[0].name, "x") self.assertIsInstance(decl.type.args.params[1], EllipsisParam) parser = c_parser.CParser(dialect="legacy") decl = parser.parse("void f(int x, ...);").ext[0] self.assertEqual(len(decl.type.args.params), 2) self.assertEqual(decl.type.args.params[0].name, "x") self.assertIsInstance(decl.type.args.params[1], EllipsisParam) def test_empty_initializers(self): ast = self.parse(""" int scalar = {}; int array[3] = {}; struct S { int value; } object = {}; """) scalar, array, obj = ast.ext self.assertIsInstance(scalar.init, InitList) self.assertEqual(scalar.init.exprs, []) self.assertIsInstance(array.init, InitList) self.assertEqual(array.init.exprs, []) self.assertIsInstance(obj.init, InitList) self.assertEqual(obj.init.exprs, []) def test_empty_compound_literals(self): ast = self.parse("int scalar = (int){}; int *array = (int[3]){};") scalar, array = ast.ext self.assertIsInstance(scalar.init, CompoundLiteral) self.assertEqual(scalar.init.type.type.type.names, ["int"]) self.assertEqual(scalar.init.init.exprs, []) self.assertIsInstance(array.init, CompoundLiteral) self.assertIsInstance(array.init.type.type, ArrayDecl) self.assertEqual(array.init.init.exprs, []) def test_labels_before_declarations_and_at_block_end(self): func = self.parse("void f(void) { start: int x = 1; end: }").ext[0] start, decl, end = func.body.block_items self.assertIsInstance(start, Label) self.assertEqual(start.name, "start") self.assertIsInstance(start.stmt, EmptyStatement) self.assertIsInstance(decl, Decl) self.assertEqual(decl.name, "x") self.assertIsInstance(end, Label) self.assertEqual(end.name, "end") self.assertIsInstance(end.stmt, EmptyStatement) def test_case_before_declaration_and_trailing_default(self): func = self.parse(""" void f(int x) { switch (x) { case 1: int y = 2; default: } } """).ext[0] case, default = func.body.block_items[0].stmt.block_items self.assertIsInstance(case, Case) self.assertEqual(case.expr.value, "1") self.assertIsInstance(case.stmts[0], EmptyStatement) self.assertIsInstance(case.stmts[1], Decl) self.assertEqual(case.stmts[1].name, "y") self.assertIsInstance(default, Default) self.assertIsInstance(default.stmts[0], EmptyStatement) def test_default_before_declaration_and_trailing_case(self): func = self.parse(""" void f(int x) { switch (x) { default: int y = 2; case 1: } } """).ext[0] default, case = func.body.block_items[0].stmt.block_items self.assertIsInstance(default, Default) self.assertIsInstance(default.stmts[0], EmptyStatement) self.assertIsInstance(default.stmts[1], Decl) self.assertEqual(default.stmts[1].name, "y") self.assertIsInstance(case, Case) self.assertEqual(case.expr.value, "1") self.assertIsInstance(case.stmts[0], EmptyStatement) def test_unnamed_parameters_in_definition(self): func = self.parse("int f(int, const int *, int (*)(int)) { return 0; }").ext[0] scalar, pointer, callback = func.decl.type.args.params self.assertIsInstance(scalar, Typename) self.assertEqual(scalar.type.type.names, ["int"]) self.assertIsNone(scalar.type.declname) self.assertIsInstance(pointer, Typename) self.assertIsInstance(pointer.type, PtrDecl) self.assertEqual(pointer.type.type.quals, ["const"]) self.assertIsNone(pointer.type.type.declname) self.assertIsInstance(callback, Typename) self.assertIsInstance(callback.type, PtrDecl) self.assertIsInstance(callback.type.type, FuncDecl) self.assertIsNone(callback.type.type.type.declname) self.assertIsInstance(func.body.block_items[0], Return) class TestCParser_c23_compound_literals(TestCParser_base): def setUp(self): self.cparser = c_parser.CParser(dialect="c23") def test_storage_specifiers(self): ast = self.parse(""" int *p = &(static int){1}; int value = (constexpr int){42}; void f(void) { (register int){2}; } """) static = ast.ext[0].init.expr self.assertIsInstance(static, CompoundLiteral) self.assertEqual(static.storage, ["static"]) self.assertEqual(static.type.type.type.names, ["int"]) self.assertEqual(static.init.exprs[0].value, "1") constexpr = ast.ext[1].init self.assertEqual(constexpr.storage, ["constexpr"]) self.assertEqual(constexpr.init.exprs[0].value, "42") register = ast.ext[2].body.block_items[0] self.assertIsInstance(register, CompoundLiteral) self.assertEqual(register.storage, ["register"]) def test_thread_local_storage(self): func = self.parse(""" void f(void) { (thread_local int){1}; (_Thread_local int){2}; (static thread_local int){3}; (thread_local static int){4}; } """).ext[0] thread, old_spelling, static_first, thread_first = func.body.block_items self.assertEqual(thread.storage, ["thread_local"]) self.assertEqual(old_spelling.storage, ["_Thread_local"]) self.assertEqual(static_first.storage, ["static", "thread_local"]) self.assertEqual(thread_first.storage, ["thread_local", "static"]) def test_storage_and_type_qualifiers(self): literal = ( self.parse("int x = (static constexpr const unsigned long){42};") .ext[0] .init ) self.assertEqual(literal.storage, ["static", "constexpr"]) self.assertEqual(literal.type.quals, ["const"]) self.assertEqual(literal.type.type.quals, ["const"]) self.assertEqual(literal.type.type.type.names, ["unsigned", "long"]) def test_typedef_and_abstract_types(self): ast = self.parse(""" typedef int T; T *array = (static T[]){1, 2}; T *pointer = (static T *){0}; """) array = ast.ext[1].init self.assertEqual(array.storage, ["static"]) self.assertIsInstance(array.type.type, ArrayDecl) self.assertIsNone(array.type.type.dim) self.assertEqual(array.type.type.type.type.names, ["T"]) pointer = ast.ext[2].init self.assertEqual(pointer.storage, ["static"]) self.assertIsInstance(pointer.type.type, PtrDecl) self.assertEqual(pointer.type.type.type.type.names, ["T"]) def test_empty_and_designated_initializers(self): ast = self.parse(""" struct S { int value; }; struct S empty = (static struct S){}; struct S designated = (static struct S){.value = 1,}; """) empty = ast.ext[1].init self.assertEqual(empty.storage, ["static"]) self.assertIsInstance(empty.init, InitList) self.assertEqual(empty.init.exprs, []) designated = ast.ext[2].init.init.exprs[0] self.assertIsInstance(designated, NamedInitializer) self.assertEqual(designated.name[0].name, "value") self.assertEqual(designated.expr.value, "1") def test_member_access(self): ast = self.parse(""" struct S { int value; }; int value = (static struct S){.value = 2}.value; int zero = (static struct S){}.value; """) member = ast.ext[1].init self.assertIsInstance(member, StructRef) self.assertEqual(member.type, ".") self.assertEqual(member.field.name, "value") self.assertIsInstance(member.name, CompoundLiteral) self.assertEqual(member.name.storage, ["static"]) empty_member = ast.ext[2].init self.assertIsInstance(empty_member, StructRef) self.assertEqual(empty_member.name.init.exprs, []) def test_array_indexing(self): ast = self.parse(""" int value = (static int[]){1, 2}[1]; int zero = (static int[2]){}[0]; """) indexed = ast.ext[0].init self.assertIsInstance(indexed, ArrayRef) self.assertEqual(indexed.subscript.value, "1") self.assertIsInstance(indexed.name, CompoundLiteral) self.assertEqual(indexed.name.storage, ["static"]) self.assertEqual(len(indexed.name.init.exprs), 2) empty_indexed = ast.ext[1].init self.assertIsInstance(empty_indexed, ArrayRef) self.assertEqual(empty_indexed.name.init.exprs, []) def test_other_postfix_operators(self): ast = self.parse(""" struct S { int value; } object; int callback(void); void f(void) { (static struct S *){&object}->value; (static int (*)(void)){callback}(); (register int){1}++; (register int){2}--; } """) arrow, call, increment, decrement = ast.ext[2].body.block_items self.assertIsInstance(arrow, StructRef) self.assertEqual(arrow.type, "->") self.assertIsInstance(arrow.name, CompoundLiteral) self.assertIsInstance(call, FuncCall) self.assertIsInstance(call.name, CompoundLiteral) self.assertEqual(call.name.storage, ["static"]) self.assertEqual(increment.op, "p++") self.assertEqual(increment.expr.storage, ["register"]) self.assertEqual(decrement.op, "p--") self.assertEqual(decrement.expr.storage, ["register"]) def test_sizeof_compound_literal(self): ast = self.parse(""" int array_size = sizeof (static int[3]){}; int element_size = sizeof (static int[]){1, 2}[0]; int ordinary = sizeof (int){1}; int type_size = sizeof(int); """) array_size = ast.ext[0].init self.assertEqual(array_size.op, "sizeof") self.assertIsInstance(array_size.expr, CompoundLiteral) self.assertEqual(array_size.expr.storage, ["static"]) self.assertEqual(array_size.expr.init.exprs, []) element_size = ast.ext[1].init self.assertIsInstance(element_size.expr, ArrayRef) self.assertIsInstance(element_size.expr.name, CompoundLiteral) self.assertIsInstance(ast.ext[2].init.expr, CompoundLiteral) self.assertEqual(ast.ext[2].init.expr.storage, []) self.assertIsInstance(ast.ext[3].init.expr, Typename) def test_nested_initializer(self): literal = ( self.parse(""" struct S { int *values; } object = (static struct S){.values = (static int[]){1, 2}}; """) .ext[0] .init ) self.assertEqual(literal.storage, ["static"]) nested = literal.init.exprs[0].expr self.assertIsInstance(nested, CompoundLiteral) self.assertEqual(nested.storage, ["static"]) self.assertIsInstance(nested.type.type, ArrayDecl) self.assertEqual(len(nested.init.exprs), 2) def test_cast_of_compound_literal(self): expr = self.parse("int value = (int)(constexpr unsigned int){42};").ext[0].init self.assertIsInstance(expr, Cast) self.assertEqual(expr.to_type.type.type.names, ["int"]) self.assertIsInstance(expr.expr, CompoundLiteral) self.assertEqual(expr.expr.storage, ["constexpr"]) def test_storage_rejected_in_legacy(self): parser = c_parser.CParser(dialect="legacy") with self.assertRaisesRegex(ParseError, "compound literals require C23"): parser.parse("int value = (static int){1};") with self.assertRaisesRegex(ParseError, "compound literals require C23"): parser.parse("void f(void) { (register int){1}; }") with self.assertRaisesRegex(ParseError, "compound literals require C23"): parser.parse("void f(void) { (_Thread_local int){1}; }") def test_storage_requires_braced_initializer(self): with self.assertRaisesRegex( ParseError, "require a compound literal initializer" ): self.parse("int value = (static int)1;") with self.assertRaisesRegex( ParseError, "require a compound literal initializer" ): self.parse("int value = sizeof(static int);") with self.assertRaisesRegex( ParseError, "require a compound literal initializer" ): self.parse("int value = (constexpr int);") self.assertRaises(ParseError, self.parse, "int value = alignof(static int);") self.assertRaises(ParseError, self.parse, "typeof(static int) value;") def test_invalid_syntax(self): self.assertRaises(ParseError, self.parse, "int value = (static){1};") self.assertRaises(ParseError, self.parse, "int value = (static unknown){1};") self.assertRaises(ParseError, self.parse, "int value = (const static int){1};") self.assertRaises(ParseError, self.parse, "int value = (int static){1};") self.assertRaises(ParseError, self.parse, "int value = (static int name){1};") self.assertRaises(ParseError, self.parse, "int value = (static int){,};") self.assertRaises(ParseError, self.parse, "int value = (static int){1;") def test_legacy_compound_literal_postfix(self): parser = c_parser.CParser(dialect="legacy") ast = parser.parse(""" struct S { int value; }; int member = (struct S){1}.value; int empty_member = (struct S){}.value; int element = (int[]){1, 2}[0]; int empty_element = (int[2]){}[0]; int size = sizeof (int[]){1, 2}; """) member = ast.ext[1].init self.assertIsInstance(member, StructRef) self.assertEqual(member.name.storage, []) self.assertIsInstance(ast.ext[2].init, StructRef) self.assertEqual(ast.ext[2].init.name.init.exprs, []) self.assertIsInstance(ast.ext[3].init, ArrayRef) self.assertEqual(ast.ext[3].init.name.storage, []) self.assertIsInstance(ast.ext[4].init, ArrayRef) self.assertEqual(ast.ext[4].init.name.init.exprs, []) self.assertIsInstance(ast.ext[5].init.expr, CompoundLiteral) class TestCParser_fixed_enum(TestCParser_base): def setUp(self): self.cparser = c_parser.CParser(dialect="c23") def test_named_definition(self): enum = self.parse("enum E : unsigned char { A = 1, B, };").ext[0].type self.assertIsInstance(enum, Enum) self.assertEqual(enum.name, "E") self.assertIsInstance(enum.underlying_type, Typename) self.assertIsNone(enum.underlying_type.name) self.assertIsInstance(enum.underlying_type.type, TypeDecl) self.assertEqual(enum.underlying_type.type.type.names, ["unsigned", "char"]) self.assertEqual(enum.values.enumerators[0].name, "A") self.assertEqual(enum.values.enumerators[0].value.value, "1") self.assertEqual(enum.values.enumerators[1].name, "B") self.assertIsNone(enum.values.enumerators[1].value) def test_forward_declaration_and_reference(self): ast = self.parse(""" enum E : unsigned int; enum E : unsigned int { A }; enum E value = A; """) forward, definition, variable = ast.ext self.assertIsNone(forward.type.values) self.assertEqual(forward.type.name, "E") self.assertEqual( forward.type.underlying_type.type.type.names, ["unsigned", "int"] ) self.assertIsInstance(definition.type.values, EnumeratorList) self.assertEqual( definition.type.underlying_type.type.type.names, ["unsigned", "int"] ) self.assertIsNone(variable.type.type.underlying_type) self.assertEqual(variable.type.type.name, "E") self.assertIsInstance(variable.init, ID) self.assertEqual(variable.init.name, "A") def test_anonymous_definition_with_declarators(self): ast = self.parse("enum : unsigned short { A } first = A, *second;") first, second = ast.ext enum = first.type.type self.assertIsInstance(enum, Enum) self.assertIsNone(enum.name) self.assertEqual(enum.underlying_type.type.type.names, ["unsigned", "short"]) self.assertEqual(first.init.name, "A") self.assertIsInstance(second.type, PtrDecl) self.assertIs(second.type.type.type, enum) def test_typedef_underlying_type_and_tag(self): ast = self.parse(""" typedef unsigned char Byte; enum Byte : Byte { A }; Byte value; """) enum = ast.ext[1].type self.assertEqual(enum.name, "Byte") self.assertEqual(enum.underlying_type.type.type.names, ["Byte"]) self.assertEqual(ast.ext[2].type.type.names, ["Byte"]) def test_typedef_of_fixed_enum(self): ast = self.parse("typedef enum : unsigned short { A } E; E value;") typedef = ast.ext[0] self.assertIsInstance(typedef, Typedef) self.assertEqual(typedef.name, "E") self.assertIsNone(typedef.type.type.name) self.assertEqual( typedef.type.type.underlying_type.type.type.names, ["unsigned", "short"] ) self.assertEqual(ast.ext[1].type.type.names, ["E"]) def test_qualified_underlying_type(self): decl = self.parse( "const enum E : volatile unsigned int const { A } value;" ).ext[0] self.assertEqual(decl.quals, ["const"]) underlying = decl.type.type.underlying_type self.assertEqual(underlying.quals, ["volatile", "const"]) self.assertEqual(underlying.type.quals, ["volatile", "const"]) self.assertEqual(underlying.type.type.names, ["unsigned", "int"]) def test_typeof_underlying_types(self): ast = self.parse(""" enum E : typeof(unsigned int) { A }; enum F : typeof_unqual(A + 1) { B }; """) first = ast.ext[0].type.underlying_type.type.type self.assertIsInstance(first, TypeOf) self.assertEqual(first.op, "typeof") self.assertIsInstance(first.expr, Typename) self.assertEqual(first.expr.type.type.names, ["unsigned", "int"]) second = ast.ext[1].type.underlying_type.type.type self.assertEqual(second.op, "typeof_unqual") self.assertIsInstance(second.expr, BinaryOp) self.assertEqual(second.expr.left.name, "A") def test_atomic_underlying_type(self): enum = self.parse("enum E : _Atomic(unsigned int) { A };").ext[0].type self.assertEqual(enum.underlying_type.quals, ["_Atomic"]) self.assertEqual(enum.underlying_type.type.quals, ["_Atomic"]) self.assertEqual(enum.underlying_type.type.type.names, ["unsigned", "int"]) def test_enumerator_expressions_are_preserved(self): enum = ( self.parse(""" enum E : unsigned long long { A = 1ULL << 40, B = 0xffffffffffffffffULL, C }; """) .ext[0] .type ) a, b, c = enum.values.enumerators self.assertIsInstance(a.value, BinaryOp) self.assertEqual(a.value.op, "<<") self.assertEqual(a.value.left.value, "1ULL") self.assertEqual(a.value.right.value, "40") self.assertEqual(b.value.value, "0xffffffffffffffffULL") self.assertIsNone(c.value) def test_definition_in_struct_member(self): struct = ( self.parse("struct S { enum E : unsigned char { A } member : 2; };") .ext[0] .type ) member = struct.decls[0] self.assertEqual(member.name, "member") self.assertEqual(member.bitsize.value, "2") self.assertEqual( member.type.type.underlying_type.type.type.names, ["unsigned", "char"] ) def test_definition_in_parameter(self): func = self.parse("void f(enum E : unsigned int { A } value);").ext[0] param = func.type.args.params[0] self.assertEqual(param.name, "value") self.assertEqual(param.type.type.name, "E") self.assertEqual( param.type.type.underlying_type.type.type.names, ["unsigned", "int"] ) def test_definition_in_type_name(self): func = self.parse("void f(void) { (enum E : unsigned char { A })0; }").ext[0] expr = func.body.block_items[0] self.assertIsInstance(expr, Cast) enum = expr.to_type.type.type self.assertEqual(enum.name, "E") self.assertEqual(enum.underlying_type.type.type.names, ["unsigned", "char"]) def test_unnamed_enum_bitfields(self): ast = self.parse(""" enum E : unsigned int { A, WIDTH = 3 }; struct S { enum E : 3; enum E : WIDTH; enum E : sizeof(int); }; """) literal, identifier, size = ast.ext[1].type.decls self.assertIsNone(literal.name) self.assertIsNone(literal.type.type.underlying_type) self.assertEqual(literal.bitsize.value, "3") self.assertIsNone(identifier.name) self.assertIsNone(identifier.type.type.underlying_type) self.assertEqual(identifier.bitsize.name, "WIDTH") self.assertIsNone(size.type.type.underlying_type) self.assertEqual(size.bitsize.op, "sizeof") def test_legacy_enum_bitfields(self): parser = c_parser.CParser(dialect="legacy") ast = parser.parse(""" enum E { A, WIDTH = 3 }; struct S { enum E : 3; enum E : WIDTH; enum E member : sizeof(int); }; """) self.assertIsNone(ast.ext[0].type.underlying_type) literal, identifier, size = ast.ext[1].type.decls self.assertIsNone(literal.type.type.underlying_type) self.assertEqual(literal.bitsize.value, "3") self.assertEqual(identifier.bitsize.name, "WIDTH") self.assertEqual(size.name, "member") self.assertEqual(size.bitsize.op, "sizeof") def test_fixed_enum_rejected_in_legacy(self): parser = c_parser.CParser(dialect="legacy") with self.assertRaisesRegex( ParseError, "Fixed underlying enum types require C23" ): parser.parse("enum E : unsigned int { A };") with self.assertRaisesRegex( ParseError, "Fixed underlying enum types require C23" ): parser.parse("enum E : unsigned int;") with self.assertRaisesRegex( ParseError, "Fixed underlying enum types require C23" ): parser.parse("enum : unsigned int { A } value;") with self.assertRaisesRegex( ParseError, "Fixed underlying enum types require C23" ): parser.parse("typedef int T; enum E : T { A };") def test_invalid_underlying_type_syntax(self): self.assertRaises(ParseError, self.parse, "enum E : { A };") self.assertRaises(ParseError, self.parse, "enum E :;") self.assertRaises(ParseError, self.parse, "enum E :") self.assertRaises(ParseError, self.parse, "enum E : unknown { A };") self.assertRaises(ParseError, self.parse, "enum E : const { A };") self.assertRaises(ParseError, self.parse, "enum E : static int { A };") self.assertRaises(ParseError, self.parse, "enum E : int * { A };") self.assertRaises(ParseError, self.parse, "enum E : int [3] { A };") self.assertRaises(ParseError, self.parse, "enum E : int () { A };") self.assertRaises(ParseError, self.parse, "enum E : (int) { A };") self.assertRaises(ParseError, self.parse, "enum E : int { A;") self.assertRaises(ParseError, self.parse, "enum E : int {};") self.assertRaises(ParseError, self.parse, "enum : int;") self.assertRaises(ParseError, self.parse, "enum : int value;") self.assertRaises( ParseError, self.parse, "typedef int T; void f(void) { int T; enum E : T { A }; }", ) def test_coordinates_and_traversal(self): enum = ( self.parse("enum E :\n unsigned char { A };", filename="enum.c") .ext[0] .type ) underlying = enum.underlying_type self.assert_coord(enum, 1, 1, "enum.c") self.assert_coord(underlying, 2, 3, "enum.c") self.assert_coord(underlying.type.type, 2, 3, "enum.c") self.assertEqual( enum.children(), (("values", enum.values), ("underlying_type", underlying)) ) self.assertEqual(list(enum), [enum.values, underlying]) class TypeVisitor(NodeVisitor): def __init__(self): self.names = [] def visit_IdentifierType(self, node): self.names.append(node.names) visitor = TypeVisitor() visitor.visit(enum) self.assertEqual(visitor.names, [["unsigned", "char"]]) class TestCParser_auto(TestCParser_base): def setUp(self): self.cparser = c_parser.CParser(dialect="c23") def test_inferred_declarations(self): declarations = """ auto count = 42; const auto scale = 0.5; static auto enabled = true; constexpr auto limit = 16; auto pointer = &count; auto ((parenthesized)) = 1; alignas(16) auto aligned = 0; """ for block_scope in (False, True): with self.subTest(block_scope=block_scope): source = declarations if block_scope: source = "void f(void) {" + declarations + "}" ast = self.parse(source, filename="auto.c") decls = ast.ext[0].body.block_items if block_scope else ast.ext self.assertEqual(len(decls), 7) for decl in decls: self.assertIsInstance(decl.type, TypeDecl) self.assertIsInstance(decl.type.type, InferredType) self.assertIn("auto", decl.storage) self.assertEqual(expand_init(decls[0].init), ["Constant", "int", "42"]) self.assertEqual(decls[1].quals, ["const"]) self.assertEqual(decls[1].type.quals, ["const"]) self.assertEqual(decls[2].storage, ["static", "auto"]) self.assertEqual(decls[3].storage, ["constexpr", "auto"]) self.assertIsInstance(decls[4].init, UnaryOp) self.assertEqual(decls[4].init.op, "&") self.assertEqual(decls[5].name, "parenthesized") self.assertEqual(decls[6].align[0].alignment.value, "16") def test_expression_initializers(self): ast = self.parse(""" typedef int T; int compute(void); void f(void) { int values[3]; auto p = values; auto q = &values; auto cast = (T)3; auto literal = (T){4}; auto call = compute(); auto comma = (compute(), 5); auto string = "text"; auto null = nullptr; T after = cast; } """) decls = ast.ext[2].body.block_items expected = ( ID, UnaryOp, Cast, CompoundLiteral, FuncCall, ExprList, Constant, Constant, ) for decl, init_type in zip(decls[1:-1], expected): self.assertIsInstance(decl.type.type, InferredType) self.assertIsInstance(decl.init, init_type) self.assertEqual(decls[-1].type.type.names, ["T"]) def test_for_loop_and_typedef_scopes(self): ast = self.parse(""" typedef int T; void f(void) { auto start = 0; for (auto i = start; i < 3; ++i) { auto j = i; } { auto int T = 2; auto value = T; } T after; } """) body = ast.ext[1].body.block_items loop = body[1] self.assertIsInstance(loop.init.decls[0].type.type, InferredType) self.assertEqual(loop.init.decls[0].init.name, "start") self.assertIsInstance(loop.stmt.block_items[0].type.type, InferredType) self.assertEqual(body[2].block_items[1].init.name, "T") self.assertEqual(body[3].type.type.names, ["T"]) def test_explicit_types_and_legacy_mode(self): source = "typedef int T; void f(void) { auto int x; auto T y = 3; }" parsers = (self.cparser, c_parser.CParser(), c_parser.CParser(dialect="legacy")) for _ in range(2): for parser in parsers: ast = parser.parse(source) x, y = ast.ext[1].body.block_items self.assertEqual(x.storage, ["auto"]) self.assertEqual(x.type.type.names, ["int"]) self.assertEqual(y.type.type.names, ["T"]) self.assertIsInstance( self.parse("auto x = 1;").ext[0].type.type, InferredType ) for parser in parsers[1:]: for source_without_type in ( "auto x = 1;", "void f(void) { auto x = 1; }", ): self.assertRaises(ParseError, parser.parse, source_without_type) def test_invalid_inferred_declarations(self): for source in ( "auto x;", "auto x = {};", "auto x = {1};", "auto x = 1, y = 2;", "auto *p = &x;", "auto a[3] = x;", "auto f(void) = 0;", "auto f(void) { return 0; }", "auto;", "auto = 1;", "auto x =;", "const x = 1;", ): for block_scope in (False, True): with self.subTest(source=source, block_scope=block_scope): wrapped = "void f(void) {" + source + "}" if block_scope else source self.assertRaises(ParseError, self.parse, wrapped) for source in ( "void f(auto x);", "void f(const auto);", "typedef int T; void f(void) { auto T = 1; }", ): with self.subTest(source=source): self.assertRaises(ParseError, self.parse, source) def test_coordinates_and_visitor(self): ast = self.parse("auto count = 42;", filename="auto.c") decl = ast.ext[0] self.assert_coord(decl.type.type, 1, 6, "auto.c") self.assert_coord(decl.init, 1, 14, "auto.c") class InferredVisitor(NodeVisitor): def __init__(self): self.types = [] def visit_InferredType(self, node): self.types.append(node) visitor = InferredVisitor() visitor.visit(ast) self.assertEqual(visitor.types, [decl.type.type]) class TestCParser_typeof(TestCParser_base): def setUp(self): self.cparser = c_parser.CParser(dialect="c23") def test_typeof_type_operands(self): typ = self.parse("typeof(int) value;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertEqual( expand_decl(typ.expr), ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]], ) typ = self.parse("typeof(const int *) value;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertEqual( expand_decl(typ.expr), [ "Typename", ["const"], ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) typ = self.parse("typeof(int [3]) value;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertEqual( expand_decl(typ.expr), [ "Typename", ["ArrayDecl", "3", [], ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) typ = self.parse("typeof(int (*)(int)) callback;").ext[0].type.type self.assertIsInstance(typ.expr.type, PtrDecl) self.assertIsInstance(typ.expr.type.type, FuncDecl) self.assertEqual(typ.expr.type.type.args.params[0].type.type.names, ["int"]) def test_typeof_unqual_type_operands(self): typ = self.parse("typeof_unqual(int) value;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertEqual( expand_decl(typ.expr), ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]], ) typ = self.parse("typeof_unqual(const int *) value;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertEqual( expand_decl(typ.expr), [ "Typename", ["const"], ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) typ = self.parse("typeof_unqual(int [3]) value;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertEqual( expand_decl(typ.expr), [ "Typename", ["ArrayDecl", "3", [], ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) typ = self.parse("typeof_unqual(int (*)(int)) callback;").ext[0].type.type self.assertIsInstance(typ.expr.type, PtrDecl) self.assertIsInstance(typ.expr.type.type, FuncDecl) self.assertEqual(typ.expr.type.type.args.params[0].type.type.names, ["int"]) def test_typeof_expression_operands(self): typ = self.parse("typeof(value) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertIsInstance(typ.expr, ID) typ = self.parse("typeof(value + 1) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertIsInstance(typ.expr, BinaryOp) typ = self.parse("typeof(value++) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertIsInstance(typ.expr, UnaryOp) typ = self.parse("typeof(f(value)) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertIsInstance(typ.expr, FuncCall) typ = self.parse("typeof((int)value) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertIsInstance(typ.expr, Cast) typ = self.parse("typeof((int){1}) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertIsInstance(typ.expr, CompoundLiteral) typ = self.parse("typeof(value, f()) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof") self.assertIsInstance(typ.expr, ExprList) def test_typeof_unqual_expression_operands(self): typ = self.parse("typeof_unqual(value) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertIsInstance(typ.expr, ID) typ = self.parse("typeof_unqual(value + 1) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertIsInstance(typ.expr, BinaryOp) typ = self.parse("typeof_unqual(value++) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertIsInstance(typ.expr, UnaryOp) typ = self.parse("typeof_unqual(f(value)) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertIsInstance(typ.expr, FuncCall) typ = self.parse("typeof_unqual((int)value) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertIsInstance(typ.expr, Cast) typ = self.parse("typeof_unqual((int){1}) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertIsInstance(typ.expr, CompoundLiteral) typ = self.parse("typeof_unqual(value, f()) copy;").ext[0].type.type self.assertIsInstance(typ, TypeOf) self.assertEqual(typ.op, "typeof_unqual") self.assertIsInstance(typ.expr, ExprList) def test_typedef_scopes(self): ast = self.parse(""" typedef int T; typeof(T) outer; void f(void) { typeof(T) before; typeof(int) T = 0; typeof(T) after; { typedef char T; typeof_unqual(T) inner; } typeof(T) last; } typeof(T) restored; """) before, shadow, after, block, last = ast.ext[2].body.block_items for decl in (ast.ext[1], before, block.block_items[1], ast.ext[3]): self.assertIsInstance(decl.type.type.expr, Typename) self.assertEqual(decl.type.type.expr.type.type.names, ["T"]) self.assertEqual(shadow.name, "T") for decl in (after, last): self.assertIsInstance(decl.type.type.expr, ID) self.assertEqual(decl.type.type.expr.name, "T") def test_nested_types_and_qualifiers(self): ast = self.parse(""" typeof(typeof_unqual(const int)) nested; typeof(_Atomic(int)) inner_atomic; _Atomic(typeof(int)) outer_atomic; const typeof_unqual(volatile int) qualified; """) nested, inner, outer, qualified = ast.ext self.assertEqual(nested.type.type.expr.type.type.op, "typeof_unqual") self.assertEqual(nested.type.type.expr.type.type.expr.quals, ["const"]) self.assertEqual(inner.quals, []) self.assertEqual(inner.type.type.expr.quals, ["_Atomic"]) self.assertEqual(outer.quals, ["_Atomic"]) self.assertEqual(outer.type.type.expr.quals, []) self.assertEqual(qualified.quals, ["const"]) self.assertEqual(qualified.type.type.expr.quals, ["volatile"]) def test_declaration_contexts(self): ast = self.parse(""" typedef typeof(1) T; struct S { typeof(T) member; typeof_unqual(unsigned int) bits : 3; }; typeof(int) f(typeof(int) arg, typeof_unqual(const int)) { typeof(arg) local = arg; for (typeof(arg) i = 0; i < 3; ++i) {} return local; } """) typedef, struct, func = ast.ext self.assertIsInstance(typedef.type.type, TypeOf) for member in struct.type.decls: self.assertIsInstance(member.type.type, TypeOf) self.assertEqual(struct.type.decls[1].bitsize.value, "3") self.assertIsInstance(func.decl.type.type.type, TypeOf) for param in func.decl.type.args.params: self.assertIsInstance(param.type.type, TypeOf) local, loop, _ = func.body.block_items self.assertIsInstance(local.type.type, TypeOf) self.assertIsInstance(loop.init.decls[0].type.type, TypeOf) def test_type_name_contexts(self): ast = self.parse(""" alignas(typeof(int)) int aligned; void f(void) { sizeof(typeof(int)); alignof(typeof_unqual(const int)); (typeof(1))2; (typeof(int)){3}; _Generic(1, typeof(int): 1, default: 0); } """) self.assertIsInstance(ast.ext[0].align[0].alignment.type.type, TypeOf) size, align, cast, literal, generic = ast.ext[1].body.block_items for expr in (size, align): self.assertIsInstance(expr.expr.type.type, TypeOf) self.assertIsInstance(cast.to_type.type.type, TypeOf) self.assertIsInstance(literal.type.type.type, TypeOf) self.assertIsInstance(generic.associations[0].type.type.type, TypeOf) def test_invalid_typeof_specifiers(self): self.assertRaises(ParseError, self.parse, "typeof() x;") self.assertRaises(ParseError, self.parse, "typeof int x;") self.assertRaises(ParseError, self.parse, "typeof(int x;") self.assertRaises(ParseError, self.parse, "typeof(int x) y;") self.assertRaises(ParseError, self.parse, "typeof(value,) x;") self.assertRaises(ParseError, self.parse, "typeof(int);") self.assertRaises(ParseError, self.parse, "int typeof(int);") self.assertRaises(ParseError, self.parse, "int typeof(int) x;") self.assertRaises(ParseError, self.parse, "typeof(int) int x;") self.assertRaises(ParseError, self.parse, "typeof(int) typeof(int) x;") self.assertRaises(ParseError, self.parse, "void f(int typeof(int));") self.assertRaises(ParseError, self.parse, "void f(void) { int x = typeof(1); }") def test_invalid_typeof_unqual_specifiers(self): self.assertRaises(ParseError, self.parse, "typeof_unqual() x;") self.assertRaises(ParseError, self.parse, "typeof_unqual int x;") self.assertRaises(ParseError, self.parse, "typeof_unqual(int x;") self.assertRaises(ParseError, self.parse, "typeof_unqual(int x) y;") self.assertRaises(ParseError, self.parse, "typeof_unqual(value,) x;") self.assertRaises(ParseError, self.parse, "typeof_unqual(int);") self.assertRaises(ParseError, self.parse, "int typeof_unqual(int);") self.assertRaises(ParseError, self.parse, "int typeof_unqual(int) x;") self.assertRaises(ParseError, self.parse, "typeof_unqual(int) int x;") self.assertRaises( ParseError, self.parse, "typeof_unqual(int) typeof_unqual(int) x;" ) self.assertRaises(ParseError, self.parse, "void f(int typeof_unqual(int));") self.assertRaises( ParseError, self.parse, "void f(void) { int x = typeof_unqual(1); }" ) def test_legacy_mode(self): for parser in (c_parser.CParser(), c_parser.CParser(dialect="legacy")): ast = parser.parse(""" int typeof(int x) { return x; } int typeof_unqual(int x) { return typeof(x); } """) self.assertEqual(ast.ext[0].decl.name, "typeof") self.assertEqual(ast.ext[1].decl.name, "typeof_unqual") self.assertEqual(ast.ext[1].body.block_items[0].expr.name.name, "typeof") self.assertRaises(ParseError, parser.parse, "typeof(int) x;") self.assertRaises(ParseError, parser.parse, "typeof_unqual(const int) x;") def test_coordinates_and_visitor(self): ast = self.parse("typeof(x + 1) y;", filename="typeof.c") typ = ast.ext[0].type.type self.assert_coord(typ, 1, 1, "typeof.c") self.assert_coord(typ.expr, 1, 8, "typeof.c") class TypeOfVisitor(NodeVisitor): def __init__(self): self.operators = [] self.ids = [] def visit_TypeOf(self, node): self.operators.append(node.op) self.generic_visit(node) def visit_ID(self, node): self.ids.append(node.name) visitor = TypeOfVisitor() visitor.visit(ast) self.assertEqual(visitor.operators, ["typeof"]) self.assertEqual(visitor.ids, ["x"]) class TestCParser_bitint(TestCParser_base): def setUp(self): self.cparser = c_parser.CParser(dialect="c23") def test_plain_type(self): decl = self.parse("_BitInt(17) value;").ext[0] self.assertEqual(decl.name, "value") self.assertIsInstance(decl.type.type, BitIntType) self.assertIsNone(decl.type.type.signedness) self.assertEqual(expand_init(decl.type.type.width), ["Constant", "int", "17"]) def test_signed_type(self): typ = self.parse("signed _BitInt(17) value;").ext[0].type.type self.assertIsInstance(typ, BitIntType) self.assertEqual(typ.signedness, "signed") self.assertEqual(typ.width.value, "17") typ = self.parse("_BitInt(17) signed value;").ext[0].type.type self.assertIsInstance(typ, BitIntType) self.assertEqual(typ.signedness, "signed") self.assertEqual(typ.width.value, "17") def test_unsigned_type(self): typ = self.parse("unsigned _BitInt(1) flag;").ext[0].type.type self.assertIsInstance(typ, BitIntType) self.assertEqual(typ.signedness, "unsigned") self.assertEqual(typ.width.value, "1") typ = self.parse("_BitInt(17) unsigned value;").ext[0].type.type self.assertIsInstance(typ, BitIntType) self.assertEqual(typ.signedness, "unsigned") self.assertEqual(typ.width.value, "17") def test_width_expressions(self): width = self.parse("_BitInt(WIDTH) value;").ext[0].type.type.width self.assertIsInstance(width, ID) self.assertEqual(width.name, "WIDTH") width = self.parse("_BitInt(8 * sizeof(int)) value;").ext[0].type.type.width self.assertIsInstance(width, BinaryOp) self.assertEqual(width.op, "*") self.assertEqual(width.left.value, "8") self.assertIsInstance(width.right, UnaryOp) self.assertEqual(width.right.op, "sizeof") self.assertEqual(width.right.expr.type.type.names, ["int"]) width = ( self.parse("_BitInt(WIDTH > 8 ? WIDTH : 8) value;").ext[0].type.type.width ) self.assertIsInstance(width, TernaryOp) self.assertEqual(width.cond.op, ">") self.assertEqual(width.iftrue.name, "WIDTH") self.assertEqual(width.iffalse.value, "8") def test_qualifiers_and_declarators(self): value, pointer, array = self.parse( "static const unsigned _BitInt(17) value = 1, *pointer, array[3];" ).ext self.assertEqual(value.storage, ["static"]) self.assertEqual(value.quals, ["const"]) self.assertEqual(value.type.quals, ["const"]) self.assertEqual(value.type.type.signedness, "unsigned") self.assertEqual(value.type.type.width.value, "17") self.assertEqual(value.init.value, "1") self.assertIsInstance(pointer.type, PtrDecl) self.assertEqual(pointer.type.type.quals, ["const"]) self.assertEqual(pointer.type.type.type.signedness, "unsigned") self.assertEqual(pointer.type.type.type.width.value, "17") self.assertIsInstance(array.type, ArrayDecl) self.assertEqual(array.type.dim.value, "3") self.assertEqual(array.type.type.type.signedness, "unsigned") self.assertEqual(array.type.type.type.width.value, "17") def test_atomic_and_typeof(self): atomic, qualified, typeof = self.parse(""" _Atomic(unsigned _BitInt(17)) atomic; _Atomic _BitInt(17) qualified; typeof_unqual(const unsigned _BitInt(17)) value; """).ext self.assertEqual(atomic.quals, ["_Atomic"]) self.assertIsInstance(atomic.type.type, BitIntType) self.assertEqual(atomic.type.type.signedness, "unsigned") self.assertEqual(qualified.quals, ["_Atomic"]) self.assertIsInstance(qualified.type.type, BitIntType) self.assertIsNone(qualified.type.type.signedness) self.assertEqual(typeof.type.type.op, "typeof_unqual") self.assertEqual(typeof.type.type.expr.quals, ["const"]) self.assertIsInstance(typeof.type.type.expr.type.type, BitIntType) self.assertEqual(typeof.type.type.expr.type.type.signedness, "unsigned") def test_declaration_contexts(self): ast = self.parse(""" typedef unsigned _BitInt(17) T; struct S { _BitInt(8) member; unsigned _BitInt(3) bits : 3; }; _BitInt(17) f(unsigned _BitInt(8) arg, _BitInt(17)) { T from_typedef; _BitInt(8) T = 0; for (unsigned _BitInt(8) i = 0; i < 3; ++i) {} return T; } T after; """) typedef, struct, func, after = ast.ext self.assertIsInstance(typedef, Typedef) self.assertIsInstance(typedef.type.type, BitIntType) self.assertEqual(typedef.type.type.signedness, "unsigned") member, bits = struct.type.decls self.assertIsInstance(member.type.type, BitIntType) self.assertIsInstance(bits.type.type, BitIntType) self.assertEqual(bits.type.type.signedness, "unsigned") self.assertEqual(bits.bitsize.value, "3") self.assertIsInstance(func.decl.type.type.type, BitIntType) named, unnamed = func.decl.type.args.params self.assertEqual(named.name, "arg") self.assertIsInstance(named.type.type, BitIntType) self.assertIsInstance(unnamed, Typename) self.assertIsInstance(unnamed.type.type, BitIntType) from_typedef, shadow, loop, _ = func.body.block_items self.assertEqual(from_typedef.type.type.names, ["T"]) self.assertEqual(shadow.name, "T") self.assertIsInstance(shadow.type.type, BitIntType) self.assertEqual(loop.init.decls[0].type.type.signedness, "unsigned") self.assertEqual(after.type.type.names, ["T"]) def test_type_name_contexts(self): ast = self.parse(""" alignas(_BitInt(8)) int aligned; void f(void) { sizeof(_BitInt(17)); alignof(unsigned _BitInt(8)); (_BitInt(17))2; (unsigned _BitInt(8)){3}; _Generic(1, _BitInt(17): 1, default: 0); } """) self.assertIsInstance(ast.ext[0].align[0].alignment.type.type, BitIntType) size, align, cast, literal, generic = ast.ext[1].body.block_items self.assertIsInstance(size.expr.type.type, BitIntType) self.assertEqual(align.expr.type.type.signedness, "unsigned") self.assertIsInstance(cast.to_type.type.type, BitIntType) self.assertEqual(literal.type.type.type.signedness, "unsigned") self.assertIsInstance(generic.associations[0].type.type.type, BitIntType) def test_invalid_width_syntax(self): self.assertRaises(ParseError, self.parse, "_BitInt() x;") self.assertRaises(ParseError, self.parse, "_BitInt 17 x;") self.assertRaises(ParseError, self.parse, "_BitInt(17 x;") self.assertRaises(ParseError, self.parse, "_BitInt(int) x;") self.assertRaises(ParseError, self.parse, "_BitInt(8, 17) x;") self.assertRaises(ParseError, self.parse, "_BitInt(WIDTH = 17) x;") def test_invalid_type_combinations(self): self.assertRaises(ParseError, self.parse, "int _BitInt(17) x;") self.assertRaises(ParseError, self.parse, "_BitInt(17) int x;") self.assertRaises(ParseError, self.parse, "long _BitInt(17) x;") self.assertRaises(ParseError, self.parse, "unsigned signed _BitInt(17) x;") self.assertRaises(ParseError, self.parse, "_BitInt(17) unsigned unsigned x;") self.assertRaises(ParseError, self.parse, "_BitInt(8) _BitInt(17) x;") self.assertRaises(ParseError, self.parse, "_BitInt(17) typeof(int) x;") self.assertRaises(ParseError, self.parse, "typeof(int) _BitInt(17) x;") self.assertRaises(ParseError, self.parse, "int _BitInt(17);") self.assertRaises(ParseError, self.parse, "void f(int _BitInt(17));") def test_legacy_mode(self): parser = c_parser.CParser() ast = parser.parse("int _BitInt = 1; int f(void) { return _BitInt; }") self.assertEqual(ast.ext[0].name, "_BitInt") self.assertEqual(ast.ext[1].body.block_items[0].expr.name, "_BitInt") self.assertRaises(ParseError, parser.parse, "_BitInt(17) x;") self.assertRaises(ParseError, parser.parse, "unsigned _BitInt(17) x;") def test_coordinates_and_visitor(self): ast = self.parse("unsigned _BitInt(WIDTH + 1) x;", filename="bitint.c") typ = ast.ext[0].type.type self.assert_coord(typ, 1, 10, "bitint.c") self.assert_coord(typ.width, 1, 18, "bitint.c") class BitIntVisitor(NodeVisitor): def __init__(self): self.types = [] self.ids = [] def visit_BitIntType(self, node): self.types.append(node) self.generic_visit(node) def visit_ID(self, node): self.ids.append(node.name) visitor = BitIntVisitor() visitor.visit(ast) self.assertEqual(visitor.types, [typ]) self.assertEqual(visitor.ids, ["WIDTH"]) class TestCParser_digit_separators(TestCParser_base): def test_integer_constants_in_default_mode(self): init = self.parse("int x = 1'000'000;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "int", "1'000'000"]) init = self.parse("int x = 0'7'7;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "int", "0'7'7"]) init = self.parse("int x = 0xAB'CD;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "int", "0xAB'CD"]) init = self.parse("int x = 0b1010'0101;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "int", "0b1010'0101"]) def test_floating_constants_in_default_mode(self): init = self.parse("double x = 1'234.56'78;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "double", "1'234.56'78"]) init = self.parse("double x = .1'25;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "double", ".1'25"]) init = self.parse("double x = 1'000.;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "double", "1'000."]) init = self.parse("double x = 1'2e-3'4;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "double", "1'2e-3'4"]) init = self.parse("double x = 0xAB'CD.EF'01p+1'0;").ext[0].init self.assertEqual( expand_init(init), ["Constant", "double", "0xAB'CD.EF'01p+1'0"] ) def test_suffixes(self): init = self.parse("unsigned x = 1'000U;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned int", "1'000U"]) init = self.parse("long x = 1'000L;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "long int", "1'000L"]) init = self.parse("unsigned long long x = 0xFF'FFuLL;").ext[0].init self.assertEqual( expand_init(init), ["Constant", "unsigned long long int", "0xFF'FFuLL"] ) init = self.parse("float x = 1.2'5F;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "float", "1.2'5F"]) init = self.parse("long double x = 0xA'B.p1'0L;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "long double", "0xA'B.p1'0L"]) def test_c23_constants(self): parser = c_parser.CParser(dialect="c23") init = parser.parse("auto x = 1'000;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "int", "1'000"]) init = parser.parse("auto x = 1'000wb;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_BitInt", "1'000wb"]) init = parser.parse("auto x = 0b1010'0101UWB;").ext[0].init self.assertEqual( expand_init(init), ["Constant", "unsigned _BitInt", "0b1010'0101UWB"] ) init = parser.parse("_Decimal32 x = 1'2.3'4e+1'0DF;").ext[0].init self.assertEqual( expand_init(init), ["Constant", "_Decimal32", "1'2.3'4e+1'0DF"] ) init = parser.parse("_Decimal64 x = 1'000.00dd;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_Decimal64", "1'000.00dd"]) init = parser.parse("_Decimal128 x = .1'25DL;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_Decimal128", ".1'25DL"]) def test_separators_do_not_enable_c23_suffixes_in_legacy_mode(self): self.assertRaises(ParseError, self.parse, "int x = 1'000wb;") self.assertRaises(ParseError, self.parse, "int x = 1'000uwb;") self.assertRaises(ParseError, self.parse, "double x = 1'000.0df;") self.assertRaises(ParseError, self.parse, "double x = 1'000.0dd;") self.assertRaises(ParseError, self.parse, "double x = 1'000.0dl;") def test_invalid_separator_positions(self): self.assertRaises(ParseError, self.parse, "int x = 1''000;") self.assertRaises(ParseError, self.parse, "int x = 1'000';") self.assertRaises(ParseError, self.parse, "int x = 0x'FF;") self.assertRaises(ParseError, self.parse, "int x = 0b'10;") self.assertRaises(ParseError, self.parse, "int x = 1'U;") self.assertRaises(ParseError, self.parse, "int x = 0'8;") self.assertRaises(ParseError, self.parse, "double x = 1'.0;") self.assertRaises(ParseError, self.parse, "double x = 1.'0;") self.assertRaises(ParseError, self.parse, "double x = 1'e2;") self.assertRaises(ParseError, self.parse, "double x = 1e'2;") self.assertRaises(ParseError, self.parse, "double x = 1e+'2;") self.assertRaises(ParseError, self.parse, "double x = 0x1'p2;") self.assertRaises(ParseError, self.parse, "double x = 0x1p'2;") def test_coordinates_and_line_directives(self): ast = self.parse("int x = 1'000, y = 2'000;", filename="digits.c") self.assert_coord(ast.ext[0].init, 1, 9, "digits.c") self.assert_coord(ast.ext[1].init, 1, 20, "digits.c") ast = self.parse("#line 1'000\nint x = 2'000;", filename="digits.c") self.assert_coord(ast.ext[0].init, 1000, 9, "digits.c") class TestCParser_bitint_literals(TestCParser_base): def setUp(self): self.cparser = c_parser.CParser(dialect="c23") def test_signed_suffixes(self): init = self.parse("auto x = 42wb;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_BitInt", "42wb"]) init = self.parse("auto x = 42WB;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_BitInt", "42WB"]) def test_unsigned_prefixes(self): init = self.parse("auto x = 42uwb;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "42uwb"]) init = self.parse("auto x = 42uWB;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "42uWB"]) init = self.parse("auto x = 42Uwb;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "42Uwb"]) init = self.parse("auto x = 42UWB;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "42UWB"]) def test_unsigned_suffixes(self): init = self.parse("auto x = 42wbu;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "42wbu"]) init = self.parse("auto x = 42wbU;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "42wbU"]) init = self.parse("auto x = 42WBu;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "42WBu"]) init = self.parse("auto x = 42WBU;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "42WBU"]) def test_integer_bases(self): init = self.parse("auto x = 0wb;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_BitInt", "0wb"]) init = self.parse("auto x = 077uwb;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "077uwb"]) init = self.parse("auto x = 0x1bwb;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_BitInt", "0x1bwb"]) init = self.parse("auto x = 0XffUWB;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned _BitInt", "0XffUWB"]) init = self.parse("auto x = 0b101wbu;").ext[0].init self.assertEqual( expand_init(init), ["Constant", "unsigned _BitInt", "0b101wbu"] ) init = self.parse("auto x = 0B101WB;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_BitInt", "0B101WB"]) def test_large_value_and_negation(self): init = ( self.parse("auto x = 340282366920938463463374607431768211456wb;") .ext[0] .init ) self.assertEqual(init.type, "_BitInt") self.assertEqual(init.value, "340282366920938463463374607431768211456wb") init = self.parse("auto x = -3wb;").ext[0].init self.assertIsInstance(init, UnaryOp) self.assertEqual(init.op, "-") self.assertEqual(expand_init(init.expr), ["Constant", "_BitInt", "3wb"]) def test_expression_contexts(self): ast = self.parse(""" _BitInt(8wb) value = 42wb; void f(void) { 1wb; auto sum = 1uwb + 2WBU; consume(3WB); if (1wb) 2uwb; else 3WB; _Generic(1wb, _BitInt(2): 1, default: 0); } """) self.assertEqual(ast.ext[0].type.type.width.type, "_BitInt") self.assertEqual(ast.ext[0].init.type, "_BitInt") constant, sum_decl, call, conditional, generic = ast.ext[1].body.block_items self.assertEqual(expand_init(constant), ["Constant", "_BitInt", "1wb"]) self.assertEqual(sum_decl.init.op, "+") self.assertEqual(sum_decl.init.left.type, "unsigned _BitInt") self.assertEqual(sum_decl.init.right.type, "unsigned _BitInt") self.assertEqual(call.args.exprs[0].type, "_BitInt") self.assertEqual(conditional.cond.type, "_BitInt") self.assertEqual(conditional.iftrue.type, "unsigned _BitInt") self.assertEqual(conditional.iffalse.type, "_BitInt") self.assertEqual(generic.expr.type, "_BitInt") def test_invalid_suffixes(self): self.assertRaises(ParseError, self.parse, "auto x = 42wB;") self.assertRaises(ParseError, self.parse, "auto x = 42Wb;") self.assertRaises(ParseError, self.parse, "auto x = 42uwB;") self.assertRaises(ParseError, self.parse, "auto x = 42Wbu;") self.assertRaises(ParseError, self.parse, "auto x = 42uwbu;") self.assertRaises(ParseError, self.parse, "auto x = 42wbwb;") self.assertRaises(ParseError, self.parse, "auto x = 42wbl;") self.assertRaises(ParseError, self.parse, "auto x = 42Lwb;") self.assertRaises(ParseError, self.parse, "auto x = 42llwb;") self.assertRaises(ParseError, self.parse, "auto x = 42WBUL;") self.assertRaises(ParseError, self.parse, "auto x = 1.0wb;") self.assertRaises(ParseError, self.parse, "auto x = 1e2wb;") self.assertRaises(ParseError, self.parse, "auto x = 0x1p0wb;") def test_ordinary_integer_and_character_constants(self): init = self.parse("auto x = 42U;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "unsigned int", "42U"]) init = self.parse("auto x = 42uLL;").ext[0].init self.assertEqual( expand_init(init), ["Constant", "unsigned long long int", "42uLL"] ) init = self.parse("auto x = 'wb';").ext[0].init self.assertEqual(expand_init(init), ["Constant", "int", "'wb'"]) def test_legacy_mode_and_reuse(self): parser = c_parser.CParser() with self.assertRaisesRegex( ParseError, "Bit-precise integer constants require C23" ): parser.parse("int x = 42wb;") self.assertRaises(ParseError, parser.parse, "int x = 42WB;") self.assertRaises(ParseError, parser.parse, "int x = 42uwb;") self.assertRaises(ParseError, parser.parse, "int x = 42UWB;") self.assertRaises(ParseError, parser.parse, "int x = 42wbu;") self.assertRaises(ParseError, parser.parse, "int x = 42WBU;") self.assertEqual(self.parse("auto x = 42wb;").ext[0].init.type, "_BitInt") self.assertEqual(parser.parse("int x = 42;").ext[0].init.type, "int") self.assertEqual( self.parse("auto x = 42uwb;").ext[0].init.type, "unsigned _BitInt" ) self.assertRaises(ParseError, parser.parse, "int x = 42uwb;") def test_coordinates(self): init = self.parse("auto x = 42uwb;", filename="bitint.c").ext[0].init self.assert_coord(init, 1, 10, "bitint.c") class TestCParser_decimal_float(TestCParser_base): def setUp(self): self.cparser = c_parser.CParser(dialect="c23") def test_decimal32(self): decl = self.parse("_Decimal32 price = 1.25df;").ext[0] self.assertEqual(decl.type.type.names, ["_Decimal32"]) self.assertEqual(expand_init(decl.init), ["Constant", "_Decimal32", "1.25df"]) def test_decimal64(self): decl = self.parse("_Decimal64 total = 100.00dd;").ext[0] self.assertEqual(decl.type.type.names, ["_Decimal64"]) self.assertEqual(expand_init(decl.init), ["Constant", "_Decimal64", "100.00dd"]) def test_decimal128(self): decl = self.parse("_Decimal128 precise = 0.1dl;").ext[0] self.assertEqual(decl.type.type.names, ["_Decimal128"]) self.assertEqual(expand_init(decl.init), ["Constant", "_Decimal128", "0.1dl"]) def test_uppercase_suffixes(self): init = self.parse("_Decimal32 x = 1.25DF;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_Decimal32", "1.25DF"]) init = self.parse("_Decimal64 x = 100.00DD;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_Decimal64", "100.00DD"]) init = self.parse("_Decimal128 x = 0.1DL;").ext[0].init self.assertEqual(expand_init(init), ["Constant", "_Decimal128", "0.1DL"]) def test_fractional_and_exponent_forms(self): zero, fraction, exponent, combined = self.parse(""" auto zero = 0.dd; auto fraction = .5df; auto exponent = 12e-2dl; auto combined = 1.5e+2DF; """).ext self.assertEqual(expand_init(zero.init), ["Constant", "_Decimal64", "0.dd"]) self.assertEqual(expand_init(fraction.init), ["Constant", "_Decimal32", ".5df"]) self.assertEqual( expand_init(exponent.init), ["Constant", "_Decimal128", "12e-2dl"] ) self.assertEqual( expand_init(combined.init), ["Constant", "_Decimal32", "1.5e+2DF"] ) def test_declaration_contexts(self): ast = self.parse(""" typedef _Decimal64 Money; const _Decimal32 *pointer; _Decimal128 array[2]; struct S { _Decimal64 amount; }; _Decimal64 f(_Decimal32 arg, _Decimal128) { constexpr _Decimal64 rate = 0.05dd; Money result = rate; return result; } """) typedef, pointer, array, struct, func = ast.ext self.assertEqual(typedef.type.type.names, ["_Decimal64"]) self.assertIsInstance(pointer.type, PtrDecl) self.assertEqual(pointer.type.type.quals, ["const"]) self.assertEqual(pointer.type.type.type.names, ["_Decimal32"]) self.assertIsInstance(array.type, ArrayDecl) self.assertEqual(array.type.type.type.names, ["_Decimal128"]) self.assertEqual(struct.type.decls[0].type.type.names, ["_Decimal64"]) self.assertEqual(func.decl.type.type.type.names, ["_Decimal64"]) named, unnamed = func.decl.type.args.params self.assertEqual(named.type.type.names, ["_Decimal32"]) self.assertEqual(unnamed.type.type.names, ["_Decimal128"]) rate, result, _ = func.body.block_items self.assertEqual(rate.storage, ["constexpr"]) self.assertEqual(rate.init.type, "_Decimal64") self.assertEqual(result.type.type.names, ["Money"]) def test_type_name_contexts(self): ast = self.parse(""" alignas(_Decimal64) int aligned; _Atomic(_Decimal32) atomic; typeof_unqual(const _Decimal128) value; void f(void) { sizeof(_Decimal32); alignof(_Decimal64); (_Decimal128)1; (_Decimal64){2.dd}; _Generic(1.df, _Decimal32: 1, default: 0); } """) self.assertEqual(ast.ext[0].align[0].alignment.type.type.names, ["_Decimal64"]) self.assertEqual(ast.ext[1].quals, ["_Atomic"]) self.assertEqual(ast.ext[1].type.type.names, ["_Decimal32"]) self.assertEqual(ast.ext[2].type.type.expr.type.type.names, ["_Decimal128"]) size, align, cast, literal, generic = ast.ext[3].body.block_items self.assertEqual(size.expr.type.type.names, ["_Decimal32"]) self.assertEqual(align.expr.type.type.names, ["_Decimal64"]) self.assertEqual(cast.to_type.type.type.names, ["_Decimal128"]) self.assertEqual(literal.type.type.type.names, ["_Decimal64"]) self.assertEqual(generic.associations[0].type.type.type.names, ["_Decimal32"]) def test_literals_in_expressions_and_statements(self): ast = self.parse(""" void f(void) { 1.25df; -2.5dd; auto sum = 1.df + 2.df; consume(3.dl); if (1.DF) 2.DD; else 3.DL; } """) constant, negative, sum_decl, call, conditional = ast.ext[0].body.block_items self.assertEqual(expand_init(constant), ["Constant", "_Decimal32", "1.25df"]) self.assertEqual(negative.op, "-") self.assertEqual( expand_init(negative.expr), ["Constant", "_Decimal64", "2.5dd"] ) self.assertEqual(sum_decl.init.op, "+") self.assertEqual(sum_decl.init.left.type, "_Decimal32") self.assertEqual(sum_decl.init.right.type, "_Decimal32") self.assertEqual(call.args.exprs[0].type, "_Decimal128") self.assertEqual(conditional.cond.type, "_Decimal32") self.assertEqual(conditional.iftrue.type, "_Decimal64") self.assertEqual(conditional.iffalse.type, "_Decimal128") def test_binary_floating_constants(self): double, float_decl, long_double, hex_float = self.parse(""" double x = 1.25; float y = 1.25f; long double z = 1.25L; float h = 0x1.fp2F; """).ext self.assertEqual(double.init.type, "double") self.assertEqual(float_decl.init.type, "float") self.assertEqual(long_double.init.type, "long double") self.assertEqual(hex_float.init.type, "float") def test_invalid_suffixes(self): self.assertRaises(ParseError, self.parse, "auto x = 1.0dF;") self.assertRaises(ParseError, self.parse, "auto x = 1.0Df;") self.assertRaises(ParseError, self.parse, "auto x = 1.0dD;") self.assertRaises(ParseError, self.parse, "auto x = 1.0Dd;") self.assertRaises(ParseError, self.parse, "auto x = 1.0dL;") self.assertRaises(ParseError, self.parse, "auto x = 1.0Dl;") self.assertRaises(ParseError, self.parse, "auto x = 1.0fdf;") self.assertRaises(ParseError, self.parse, "auto x = 1.0ddL;") self.assertRaises(ParseError, self.parse, "auto x = 1.0ddextra;") self.assertRaises(ParseError, self.parse, "auto x = 1df;") self.assertRaises(ParseError, self.parse, "auto x = 1dd;") self.assertRaises(ParseError, self.parse, "auto x = 1dl;") def test_hexadecimal_decimal_suffixes(self): self.assertRaises(ParseError, self.parse, "auto x = 0x1p0df;") self.assertRaises(ParseError, self.parse, "auto x = 0x1p0dd;") self.assertRaises(ParseError, self.parse, "auto x = 0x1p0dl;") self.assertRaises(ParseError, self.parse, "auto x = 0x1.fp+2DF;") self.assertRaises(ParseError, self.parse, "auto x = 0x1.fp+2DD;") self.assertRaises(ParseError, self.parse, "auto x = 0x1.fp+2DL;") def test_legacy_mode_and_reuse(self): parser = c_parser.CParser() names = parser.parse("int _Decimal32, _Decimal64, _Decimal128;").ext self.assertEqual(names[0].name, "_Decimal32") self.assertEqual(names[1].name, "_Decimal64") self.assertEqual(names[2].name, "_Decimal128") self.assertRaises(ParseError, parser.parse, "_Decimal32 x;") self.assertRaises(ParseError, parser.parse, "_Decimal64 x;") self.assertRaises(ParseError, parser.parse, "_Decimal128 x;") self.assertRaises(ParseError, parser.parse, "double x = 1.25df;") self.assertRaises(ParseError, parser.parse, "double x = 1.25dd;") self.assertRaises(ParseError, parser.parse, "double x = 1.25dl;") self.assertRaises(ParseError, parser.parse, "double x = 1.25DF;") self.assertRaises(ParseError, parser.parse, "double x = 1.25DD;") self.assertRaises(ParseError, parser.parse, "double x = 1.25DL;") self.assertEqual( self.parse("_Decimal32 x = 1.df;").ext[0].init.type, "_Decimal32" ) self.assertEqual(parser.parse("double x = 1.;").ext[0].init.type, "double") self.assertEqual( self.parse("_Decimal64 x = 1.dd;").ext[0].init.type, "_Decimal64" ) self.assertRaises(ParseError, parser.parse, "double x = 1.dd;") def test_coordinates(self): ast = self.parse("_Decimal64 x = 1.25dd;", filename="decimal.c") self.assert_coord(ast.ext[0].type.type, 1, 1, "decimal.c") self.assert_coord(ast.ext[0].init, 1, 16, "decimal.c") def test_legacy_literal_diagnostic(self): parser = c_parser.CParser(dialect="legacy") with self.assertRaisesRegex( ParseError, "decimal.c:1:12: Decimal floating constants require C23" ): parser.parse("double x = 1.25dd;", filename="decimal.c") class TestUnmatchedRbrace(unittest.TestCase): """Regression for #603: unmatched '}' raises ParseError, not AssertionError.""" def test_unmatched_rbrace_raises_parse_error(self): parser = c_parser.CParser() with self.assertRaises(ParseError): parser.parse("}", filename="test.c") class TestCParser_whole_code(TestCParser_base): """Testing of parsing whole chunks of code. Since I don't want to rely on the structure of ASTs too much, most of these tests are implemented with visitors. """ # A simple helper visitor that lists the values of all the # Constant nodes it sees. # class ConstantVisitor(NodeVisitor): def __init__(self): self.values = [] def visit_Constant(self, node): self.values.append(node.value) # This visitor counts the amount of references to the ID # with the name provided to it in the constructor. # class IDNameCounter(NodeVisitor): def __init__(self, name): self.name = name self.nrefs = 0 def visit_ID(self, node): if node.name == self.name: self.nrefs += 1 # Counts the amount of nodes of a given class # class NodeKlassCounter(NodeVisitor): def __init__(self, node_klass): self.klass = node_klass self.n = 0 def generic_visit(self, node): if node.__class__ == self.klass: self.n += 1 NodeVisitor.generic_visit(self, node) def assert_all_Constants(self, code, constants): """Asserts that the list of all Constant values (by 'preorder' appearance) in the chunk of code is as given. """ if isinstance(code, str): parsed = self.parse(code) else: parsed = code cv = self.ConstantVisitor() cv.visit(parsed) self.assertEqual(cv.values, constants) def assert_num_ID_refs(self, code, name, num): """Asserts the number of references to the ID with the given name. """ if isinstance(code, str): parsed = self.parse(code) else: parsed = code iv = self.IDNameCounter(name) iv.visit(parsed) self.assertEqual(iv.nrefs, num) def assert_num_klass_nodes(self, code, klass, num): """Asserts the amount of klass nodes in the code.""" if isinstance(code, str): parsed = self.parse(code) else: parsed = code cv = self.NodeKlassCounter(klass) cv.visit(parsed) self.assertEqual(cv.n, num) def test_generic_selection_visitors(self): ast = self.parse("int v = _Generic(0, int[1]: 2, default: 3);") self.assert_all_Constants(ast, ["0", "1", "2", "3"]) self.assert_num_klass_nodes(ast, GenericSelection, 1) self.assert_num_klass_nodes(ast, GenericAssociation, 2) self.assert_num_klass_nodes(ast, Typename, 1) def test_expressions(self): e1 = """int k = (r + 10.0) >> 6 + 8 << (3 & 0x14);""" self.assert_all_Constants(e1, ["10.0", "6", "8", "3", "0x14"]) e2 = r"""char n = '\n', *prefix = "st_";""" self.assert_all_Constants(e2, [r"'\n'", '"st_"']) s1 = r"""int main() { int i = 5, j = 6, k = 1; if ((i=j && k == 1) || k > j) printf("Hello, world\n"); return 0; }""" ps1 = self.parse(s1) self.assert_all_Constants(ps1, ["5", "6", "1", "1", '"Hello, world\\n"', "0"]) self.assert_num_ID_refs(ps1, "i", 1) self.assert_num_ID_refs(ps1, "j", 2) def test_statements(self): s1 = r""" void foo(){ if (sp == 1) if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0') return -1; else if (strcmp(argv[optind], "--") == 0) { optind++; return -1; } } """ self.assert_all_Constants( s1, ["1", "0", r"'-'", "1", r"'\0'", "1", r'"--"', "0", "1"] ) ps1 = self.parse(s1) self.assert_num_ID_refs(ps1, "argv", 3) self.assert_num_ID_refs(ps1, "optind", 5) self.assert_num_klass_nodes(ps1, If, 3) self.assert_num_klass_nodes(ps1, Return, 2) self.assert_num_klass_nodes(ps1, FuncCall, 1) # strcmp self.assert_num_klass_nodes(ps1, BinaryOp, 7) # In the following code, Hash and Node were defined as # int to pacify the parser that sees they're used as # types # s2 = r""" typedef int Hash, Node; void HashDestroy(Hash* hash) { unsigned int i; if (hash == NULL) return; for (i = 0; i < hash->table_size; ++i) { Node* temp = hash->heads[i]; while (temp != NULL) { Node* temp2 = temp; free(temp->entry->key); free(temp->entry->value); free(temp->entry); temp = temp->next; free(temp2); } } free(hash->heads); hash->heads = NULL; free(hash); } """ ps2 = self.parse(s2) self.assert_num_klass_nodes(ps2, FuncCall, 6) self.assert_num_klass_nodes(ps2, FuncDef, 1) self.assert_num_klass_nodes(ps2, For, 1) self.assert_num_klass_nodes(ps2, While, 1) self.assert_num_klass_nodes(ps2, StructRef, 10) # declarations don't count self.assert_num_ID_refs(ps2, "hash", 6) self.assert_num_ID_refs(ps2, "i", 4) s3 = r""" void x(void) { int a, b; if (a < b) do { a = 0; } while (0); else if (a == b) { a = 1; } } """ ps3 = self.parse(s3) self.assert_num_klass_nodes(ps3, DoWhile, 1) self.assert_num_ID_refs(ps3, "a", 4) self.assert_all_Constants(ps3, ["0", "0", "1"]) def test_empty_statements(self): s1 = r""" void foo(void){ ; return;; ; } """ ps1 = self.parse(s1) self.assert_num_klass_nodes(ps1, EmptyStatement, 3) self.assert_num_klass_nodes(ps1, Return, 1) self.assert_coord(ps1.ext[0].body.block_items[0], 3) self.assert_coord(ps1.ext[0].body.block_items[1], 4) self.assert_coord(ps1.ext[0].body.block_items[2], 4) self.assert_coord(ps1.ext[0].body.block_items[3], 6) def test_switch_statement(self): def assert_case_node(node, const_value): self.assertIsInstance(node, Case) self.assertIsInstance(node.expr, Constant) self.assertEqual(node.expr.value, const_value) def assert_default_node(node): self.assertIsInstance(node, Default) s1 = r""" int foo(void) { switch (myvar) { case 10: k = 10; p = k + 1; return 10; case 20: case 30: return 20; default: break; } return 0; } """ ps1 = self.parse(s1) switch = ps1.ext[0].body.block_items[0] block = switch.stmt.block_items self.assertEqual(len(block), 4) assert_case_node(block[0], "10") self.assertEqual(len(block[0].stmts), 3) assert_case_node(block[1], "20") self.assertEqual(len(block[1].stmts), 0) assert_case_node(block[2], "30") self.assertEqual(len(block[2].stmts), 1) assert_default_node(block[3]) s2 = r""" int foo(void) { switch (myvar) { default: joe = moe; return 10; case 10: case 20: case 30: case 40: break; } return 0; } """ ps2 = self.parse(s2) switch = ps2.ext[0].body.block_items[0] block = switch.stmt.block_items self.assertEqual(len(block), 5) assert_default_node(block[0]) self.assertEqual(len(block[0].stmts), 2) assert_case_node(block[1], "10") self.assertEqual(len(block[1].stmts), 0) assert_case_node(block[2], "20") self.assertEqual(len(block[1].stmts), 0) assert_case_node(block[3], "30") self.assertEqual(len(block[1].stmts), 0) assert_case_node(block[4], "40") self.assertEqual(len(block[4].stmts), 1) s3 = r""" int foo(void) { switch (myvar) { } return 0; } """ ps3 = self.parse(s3) switch = ps3.ext[0].body.block_items[0] self.assertEqual(switch.stmt.block_items, []) def test_for_statement(self): s2 = r""" void x(void) { int i; for (i = 0; i < 5; ++i) { x = 50; } } """ ps2 = self.parse(s2) self.assert_num_klass_nodes(ps2, For, 1) # here there are 3 refs to 'i' since the declaration doesn't count as # a ref in the visitor # self.assert_num_ID_refs(ps2, "i", 3) s3 = r""" void x(void) { for (int i = 0; i < 5; ++i) { x = 50; } } """ ps3 = self.parse(s3) self.assert_num_klass_nodes(ps3, For, 1) # here there are 2 refs to 'i' since the declaration doesn't count as # a ref in the visitor # self.assert_num_ID_refs(ps3, "i", 2) s4 = r""" void x(void) { for (int i = 0;;) i; } """ ps4 = self.parse(s4) self.assert_num_ID_refs(ps4, "i", 1) def _open_c_file(self, name): """Find a c file by name, taking into account the current dir can be in a couple of typical places """ testdir = os.path.dirname(__file__) name = os.path.join(testdir, "c_files", name) assert os.path.exists(name) return open(name) def test_whole_file(self): # See how pycparser handles a whole, real C file. # with self._open_c_file("memmgr_with_h.c") as f: code = f.read() p = self.parse(code) self.assert_num_klass_nodes(p, FuncDef, 5) # each FuncDef also has a FuncDecl. 4 declarations # + 5 definitions, overall 9 self.assert_num_klass_nodes(p, FuncDecl, 9) self.assert_num_klass_nodes(p, Typedef, 4) self.assertEqual(p.ext[4].coord.line, 88) self.assertEqual(p.ext[4].coord.file, "./memmgr.h") self.assertEqual(p.ext[6].coord.line, 10) self.assertEqual(p.ext[6].coord.file, "memmgr.c") def test_whole_file_with_stdio(self): # Parse a whole file with stdio.h included by cpp # with self._open_c_file("cppd_with_stdio_h.c") as f: code = f.read() p = self.parse(code) self.assertIsInstance(p.ext[0], Typedef) self.assertEqual(p.ext[0].coord.line, 213) self.assertEqual(p.ext[0].coord.file, r"D:\eli\cpp_stuff\libc_include/stddef.h") self.assertIsInstance(p.ext[-1], FuncDef) self.assertEqual(p.ext[-1].coord.line, 15) self.assertEqual(p.ext[-1].coord.file, "example_c_file.c") self.assertIsInstance(p.ext[-8], Typedef) self.assertIsInstance(p.ext[-8].type, TypeDecl) self.assertEqual(p.ext[-8].name, "cookie_io_functions_t") class TestCParser_typenames(TestCParser_base): """Test issues related to the typedef-name problem.""" def test_innerscope_typedef(self): # should fail since TT is not a type in bar s1 = r""" void foo() { typedef char TT; TT x; } void bar() { TT y; } """ self.assertRaises(ParseError, self.parse, s1) # should succeed since TT is not a type in bar s2 = r""" void foo() { typedef char TT; TT x; } void bar() { unsigned TT; } """ self.assertIsInstance(self.parse(s2), FileAST) def test_ambiguous_parameters(self): # From ISO/IEC 9899:TC2, 6.7.5.3.11: # "If, in a parameter declaration, an identifier can be treated either # as a typedef name or as a parameter name, it shall be taken as a # typedef name." # foo takes an int named aa # bar takes a function taking a TT s1 = r""" typedef char TT; int foo(int (aa)); int bar(int (TT)); """ s1_ast = self.parse(s1) self.assertEqual( expand_decl(s1_ast.ext[1].type.args.params[0]), ["Decl", "aa", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual( expand_decl(s1_ast.ext[2].type.args.params[0]), [ "Typename", [ "FuncDecl", [["Typename", ["TypeDecl", ["IdentifierType", ["TT"]]]]], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) # foo takes a function taking a char # bar takes a function taking a function taking a char s2 = r""" typedef char TT; int foo(int (aa (char))); int bar(int (TT (char))); """ s2_ast = self.parse(s2) self.assertEqual( expand_decl(s2_ast.ext[1].type.args.params[0]), [ "Decl", "aa", [ "FuncDecl", [["Typename", ["TypeDecl", ["IdentifierType", ["char"]]]]], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) self.assertEqual( expand_decl(s2_ast.ext[2].type.args.params[0]), [ "Typename", [ "FuncDecl", [ [ "Typename", [ "FuncDecl", [ [ "Typename", ["TypeDecl", ["IdentifierType", ["char"]]], ] ], ["TypeDecl", ["IdentifierType", ["TT"]]], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) # foo takes an int array named aa # bar takes a function taking a TT array s3 = r""" typedef char TT; int foo(int (aa[])); int bar(int (TT[])); """ s3_ast = self.parse(s3) self.assertEqual( expand_decl(s3_ast.ext[1].type.args.params[0]), [ "Decl", "aa", ["ArrayDecl", "", [], ["TypeDecl", ["IdentifierType", ["int"]]]], ], ) self.assertEqual( expand_decl(s3_ast.ext[2].type.args.params[0]), [ "Typename", [ "FuncDecl", [ [ "Typename", [ "ArrayDecl", "", [], ["TypeDecl", ["IdentifierType", ["TT"]]], ], ] ], ["TypeDecl", ["IdentifierType", ["int"]]], ], ], ) def test_innerscope_reuse_typedef_name(self): # identifiers can be reused in inner scopes; the original should be # restored at the end of the block s1 = r""" typedef char TT; void foo(void) { unsigned TT; TT = 10; } TT x = 5; """ s1_ast = self.parse(s1) self.assertEqual( expand_decl(s1_ast.ext[1].body.block_items[0]), ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], ) self.assertEqual( expand_decl(s1_ast.ext[2]), ["Decl", "x", ["TypeDecl", ["IdentifierType", ["TT"]]]], ) # this should be recognized even with an initializer s2 = r""" typedef char TT; void foo(void) { unsigned TT = 10; } """ s2_ast = self.parse(s2) self.assertEqual( expand_decl(s2_ast.ext[1].body.block_items[0]), ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], ) # before the second local variable, TT is a type; after, it's a # variable s3 = r""" typedef char TT; void foo(void) { TT tt = sizeof(TT); unsigned TT = 10; } """ s3_ast = self.parse(s3) self.assertEqual( expand_decl(s3_ast.ext[1].body.block_items[0]), ["Decl", "tt", ["TypeDecl", ["IdentifierType", ["TT"]]]], ) self.assertEqual( expand_decl(s3_ast.ext[1].body.block_items[1]), ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], ) # a variable and its type can even share the same name s4 = r""" typedef char TT; void foo(void) { TT TT = sizeof(TT); unsigned uu = TT * 2; } """ s4_ast = self.parse(s4) self.assertEqual( expand_decl(s4_ast.ext[1].body.block_items[0]), ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["TT"]]]], ) self.assertEqual( expand_decl(s4_ast.ext[1].body.block_items[1]), ["Decl", "uu", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], ) # ensure an error is raised if a type, redeclared as a variable, is # used as a type s5 = r""" typedef char TT; void foo(void) { unsigned TT = 10; TT erroneous = 20; } """ self.assertRaises(ParseError, self.parse, s5) # reusing a type name should work with multiple declarators s6 = r""" typedef char TT; void foo(void) { unsigned TT, uu; } """ s6_ast = self.parse(s6) items = s6_ast.ext[1].body.block_items self.assertEqual( expand_decl(items[0]), ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], ) self.assertEqual( expand_decl(items[1]), ["Decl", "uu", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], ) # reusing a type name should work after a pointer s7 = r""" typedef char TT; void foo(void) { unsigned * TT; } """ s7_ast = self.parse(s7) items = s7_ast.ext[1].body.block_items self.assertEqual( expand_decl(items[0]), ["Decl", "TT", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["unsigned"]]]]], ) # redefine a name in the middle of a multi-declarator declaration s8 = r""" typedef char TT; void foo(void) { int tt = sizeof(TT), TT, uu = sizeof(TT); int uu = sizeof(tt); } """ s8_ast = self.parse(s8) items = s8_ast.ext[1].body.block_items self.assertEqual( expand_decl(items[0]), ["Decl", "tt", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual( expand_decl(items[1]), ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["int"]]]], ) self.assertEqual( expand_decl(items[2]), ["Decl", "uu", ["TypeDecl", ["IdentifierType", ["int"]]]], ) # Don't test this until we have support for it # self.assertEqual(expand_init(items[0].init), # ['UnaryOp', 'sizeof', ['Typename', ['TypeDecl', ['IdentifierType', ['TT']]]]]) # self.assertEqual(expand_init(items[2].init), # ['UnaryOp', 'sizeof', ['ID', 'TT']]) def test_parameter_reuse_typedef_name(self): # Parameter names shadow typedef names inside the body; the outer # typedef is visible again immediately after the function. s1 = r""" typedef char TT; void foo(unsigned TT, TT bar) { TT = 10; } TT x = 5; """ s1_ast = self.parse(s1) self.assertEqual( expand_decl(s1_ast.ext[1].decl), [ "Decl", "foo", [ "FuncDecl", [ ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], ["Decl", "bar", ["TypeDecl", ["IdentifierType", ["TT"]]]], ], ["TypeDecl", ["IdentifierType", ["void"]]], ], ], ) # Parameter names in a prototype must not hide typedef names in # subsequent declarations. s2 = r""" typedef char TT; void foo(unsigned TT, TT bar); TT x = 5; """ s2_ast = self.parse(s2) self.assertEqual( expand_decl(s2_ast.ext[1]), [ "Decl", "foo", [ "FuncDecl", [ ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]], ["Decl", "bar", ["TypeDecl", ["IdentifierType", ["TT"]]]], ], ["TypeDecl", ["IdentifierType", ["void"]]], ], ], ) # ensure an error is raised if a type, redeclared as a parameter, is # used as a type s3 = r""" typedef char TT; void foo(unsigned TT, TT bar) { TT erroneous = 20; } """ self.assertRaises(ParseError, self.parse, s3) def test_nested_function_decls(self): # parameter names of nested function declarations must not escape into # the top-level function _definition's_ scope; the following must # succeed because TT is still a typedef inside foo's body s1 = r""" typedef char TT; void foo(unsigned bar(int TT)) { TT x = 10; } """ self.assertIsInstance(self.parse(s1), FileAST) def test_for_loop_reuse_typedef_name(self): # Looking for an else peeks at TT while the loop's TT is still visible. s = """ typedef char TT; void foo(void) { for (unsigned TT = 0; TT < 3; TT++) if (TT) TT++; TT *x; } """ items = self.parse(s).ext[1].body.block_items self.assertEqual( expand_decl(items[-1]), ["Decl", "x", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["TT"]]]]], ) def test_buffered_identifiers_across_statement_expression_scope(self): # Scanning the parenthesized declarator reads through the inner block # before parsing it. Its T must still be interpreted in the right scope. tree = self.parse(""" typedef char T; void f(void) { int (a[sizeof(({ int T = 0; T++; T; }))]); T *x; } """) array, pointer = tree.ext[1].body.block_items inner = array.type.dim.expr.block_items self.assertEqual(inner[1].expr.name, "T") self.assertEqual( expand_decl(pointer), ["Decl", "x", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["T"]]]]], ) def test_function_returning_function_pointer_parameter_scope(self): tree = self.parse(""" typedef int T; typedef int U; int (*f(int T))(int U) { T++; U value = 0; return 0; } T x; """) body = tree.ext[2].body.block_items self.assertEqual(body[0].expr.name, "T") self.assertEqual(body[1].type.type.names, ["U"]) self.assertEqual(tree.ext[-1].type.type.names, ["T"]) def test_old_style_parameter_scope(self): tree = self.parse(""" int f(x) int x; { return x; } typedef int x; """) self.assertEqual(tree.ext[0].param_decls[0].name, "x") self.assertIsInstance(tree.ext[1], Typedef) self.assertEqual(tree.ext[1].name, "x") def test_for_loop_scope_before_closing_brace(self): # Looking for an else peeks at the function's closing brace. Both the # loop's TT and the function's TT must go out of scope. s = """ typedef char TT; void foo(void) { int TT; for (unsigned TT = 0; TT < 3; TT++) if (TT) TT++; } TT x; """ tree = self.parse(s) self.assertEqual( expand_decl(tree.ext[-1]), ["Decl", "x", ["TypeDecl", ["IdentifierType", ["TT"]]]], ) def test_samescope_reuse_name(self): # a typedef name cannot be reused as an object name in the same scope s1 = r""" typedef char TT; char TT = 5; """ self.assertRaises(ParseError, self.parse, s1) # ...and vice-versa s2 = r""" char TT = 5; typedef char TT; """ self.assertRaises(ParseError, self.parse, s2) def test_label_empty_statement(self): # Labels with empty statements and no semicolon should be parsed correctly s1 = r""" int main() { int i = 0; label0: i++; label1: } """ s1_ast: FileAST = self.parse(s1) self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Label) self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, UnaryOp) self.assertIsInstance(s1_ast.ext[0].body.block_items[2], Label) self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, EmptyStatement) def test_case_empty_statement(self): # Labels with empty statements and no semicolon should be parsed correctly s1 = r""" int main() { int i = 0; switch (i) { case 0: i = 1; case 1: } return i; } """ s2 = r""" int main() { int i = 0; switch (i) { case 0: i = 1; default: } return i; } """ s1_ast: FileAST = self.parse(s1) s2_ast: FileAST = self.parse(s2) self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Switch) self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, Compound) self.assertIsInstance( s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Case ) self.assertIsInstance( s1_ast.ext[0].body.block_items[1].stmt.block_items[0].stmts[0], Assignment ) self.assertIsInstance( s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Case ) self.assertIsInstance( s1_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0], EmptyStatement, ) self.assertIsInstance( s2_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0], EmptyStatement, ) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785327145.0291767 pycparser-3.12/tests/test_examples.py0000664000175000017500000000171415232367051017367 0ustar00elibenelibenimport os import sys import unittest sys.path.insert(0, ".") from tests.test_util import cpp_supported, run_exe # Runs all pycparser examples with no command-line arguments and makes sure they # run successfully (return code = 0), without actually verifying their output. class TestExamplesSucceed(unittest.TestCase): @unittest.skipUnless(cpp_supported(), "cpp only works on Unix") def test_all_examples(self): root = "./examples" for filename in os.listdir(root): if os.path.splitext(filename)[1] == ".py": with self.subTest(name=filename): path = os.path.join(root, filename) rc, stdout, stderr = run_exe(path) self.assertEqual( rc, 0, f'example "{filename}" failed with stdout =\n{stdout}\nstderr =\n{stderr}', ) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792673999.9655926 pycparser-3.12/tests/test_general.py0000664000175000017500000001236115266404320017164 0ustar00elibenelibenimport os import sys import tempfile import unittest sys.path.insert(0, "..") from pycparser import CParser, c_ast, parse_file from tests.test_util import cpp_args, cpp_path, cpp_supported # Test successful parsing # class TestParsing(unittest.TestCase): def _find_file(self, name): """Find a c file by name, taking into account the current dir can be in a couple of typical places """ testdir = os.path.dirname(__file__) name = os.path.join(testdir, "c_files", name) assert os.path.exists(name) return name def test_without_cpp(self): ast = parse_file(self._find_file("example_c_file.c")) self.assertIsInstance(ast, c_ast.FileAST) def test_c23_parser(self): with tempfile.TemporaryDirectory() as directory: filename = os.path.join(directory, "c23.c") with open(filename, "w", encoding="utf-8") as source: source.write("bool flag = true; void *p = nullptr;") ast = parse_file(filename, parser=CParser(dialect="c23")) self.assertEqual(ast.ext[0].type.type.names, ["bool"]) for decl, typ in zip(ast.ext, ("bool", "nullptr_t")): self.assertIsInstance(decl.init, c_ast.Constant) self.assertEqual(decl.init.type, typ) @unittest.skipUnless(cpp_supported(), "cpp only works on Unix") def test_with_cpp(self): memmgr_path = self._find_file("memmgr.c") c_files_path = os.path.dirname(memmgr_path) ast = parse_file( memmgr_path, use_cpp=True, cpp_path=cpp_path(), cpp_args=cpp_args(f"-I{c_files_path}"), ) self.assertIsInstance(ast, c_ast.FileAST) fake_libc = os.path.join(c_files_path, "..", "..", "utils", "fake_libc_include") ast2 = parse_file( self._find_file("year.c"), use_cpp=True, cpp_path=cpp_path(), cpp_args=cpp_args(f"-I{fake_libc}"), ) self.assertIsInstance(ast2, c_ast.FileAST) @unittest.skipUnless(cpp_supported(), "cpp only works on Unix") def test_va_arg_preserves_type(self): # Issue #533: preprocessing with the fake headers must retain the type. fake_libc = os.path.join( os.path.dirname(__file__), "..", "utils", "fake_libc_include" ) with tempfile.TemporaryDirectory() as directory: filename = os.path.join(directory, "va_arg.c") with open(filename, "w", encoding="utf-8") as source: source.write(""" #include int f(int first, ...) { va_list ap; va_start(ap, first); int value = va_arg(ap, int); va_end(ap); return value; } """) ast = parse_file( filename, use_cpp=True, cpp_path=cpp_path(), cpp_args=cpp_args(["-nostdinc", f"-I{fake_libc}"]), ) call = ast.ext[-1].body.block_items[2].init self.assertEqual(call.name.name, "__builtin_va_arg") self.assertEqual(len(call.args.exprs), 2) self.assertIsInstance(call.args.exprs[1], c_ast.Typename) self.assertEqual(call.args.exprs[1].type.type.names, ["int"]) @unittest.skipUnless(cpp_supported(), "cpp only works on Unix") def test_cpp_funkydir(self): # This test contains Windows specific path escapes if sys.platform != "win32": return c_files_path = os.path.join("tests", "c_files") ast = parse_file( self._find_file("simplemain.c"), use_cpp=True, cpp_path=cpp_path(), cpp_args=cpp_args(f"-I{c_files_path}"), ) self.assertIsInstance(ast, c_ast.FileAST) @unittest.skipUnless(cpp_supported(), "cpp only works on Unix") def test_no_real_content_after_cpp(self): ast = parse_file( self._find_file("empty.h"), use_cpp=True, cpp_path=cpp_path(), cpp_args=cpp_args(), ) self.assertIsInstance(ast, c_ast.FileAST) @unittest.skipUnless(cpp_supported(), "cpp only works on Unix") def test_c11_with_cpp(self): c_files_path = os.path.join("tests", "c_files") fake_libc = os.path.join(c_files_path, "..", "..", "utils", "fake_libc_include") ast = parse_file( self._find_file("c11.c"), use_cpp=True, cpp_path=cpp_path(), # Missing fake headers must not fall back to the host's libc headers. cpp_args=cpp_args(["-std=c11", "-nostdinc", f"-I{fake_libc}"]), ) self.assertIsInstance(ast, c_ast.FileAST) decls = {node.name: node for node in ast.ext if isinstance(node, c_ast.Decl)} self.assertEqual(decls["flag2"].storage, ["_Thread_local"]) # Unexpanded macro names would also parse, so check their expansion. for name in ("once", "destructor_iterations"): with self.subTest(name=name): self.assertIsInstance(decls[name].init, c_ast.Constant) self.assertEqual(decls[name].init.type, "int") if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785328185.0175831 pycparser-3.12/tests/test_util.py0000664000175000017500000000311115232371071016514 0ustar00elibeneliben# ------------------------------------------------------------------------------ # pycparser: test_util.py # # Utility code for tests. # # Eli Bendersky [https://eli.thegreenplace.net/] # This file contributed by vit9696@users.noreply.github.com # License: BSD # ------------------------------------------------------------------------------ import os import platform import subprocess import sys def cpp_supported(): """Is cpp (the C preprocessor) supported as a native command?""" return platform.system() == "Linux" def cpp_path(): """Path to cpp command.""" if platform.system() == "Darwin": return "gcc" return "cpp" def cpp_args(args=None): """Turn args into a suitable format for passing to cpp.""" if args is None: args = [] if isinstance(args, str): args = [args] if platform.system() == "Darwin": return ["-E"] + args return args def _bytes2str(b): return b.decode("latin-1") def run_exe(exe_path, args=None, echo=False): """Runs the given executable as a subprocess, given the list of arguments. Captures its return code (rc) and stdout and returns a tuple: rc, stdout, stderr """ if args is None: args = [] popen_cmd = [exe_path] + args if os.path.splitext(exe_path)[1] == ".py": popen_cmd.insert(0, sys.executable) if echo: print("[cmd]", " ".join(popen_cmd)) proc = subprocess.Popen(popen_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() return proc.returncode, _bytes2str(stdout), _bytes2str(stderr) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8497353 pycparser-3.12/utils/0000775000175000017500000000000015266410573014140 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8547246 pycparser-3.12/utils/fake_libc_include/0000775000175000017500000000000015266410573017542 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8548284 pycparser-3.12/utils/fake_libc_include/X11/0000775000175000017500000000000015266410573020113 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/X11/Intrinsic.h0000664000175000017500000000016614716121045022221 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" #include "_X11_fake_defines.h" #include "_X11_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/X11/Xlib.h0000664000175000017500000000016614716121045021155 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" #include "_X11_fake_defines.h" #include "_X11_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/X11/_X11_fake_defines.h0000664000175000017500000000046714716121045023456 0ustar00elibeneliben#ifndef _X11_FAKE_DEFINES_H #define _X11_FAKE_DEFINES_H #define Atom CARD32 #define Bool int #define KeySym CARD32 #define Pixmap CARD32 #define Time CARD32 #define _XFUNCPROTOBEGIN #define _XFUNCPROTOEND #define _Xconst const #define _X_RESTRICT_KYWD #define Cardinal unsigned int #define Boolean int #endif ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/X11/_X11_fake_typedefs.h0000664000175000017500000000212714716121045023657 0ustar00elibeneliben#ifndef _X11_FAKE_TYPEDEFS_H #define _X11_FAKE_TYPEDEFS_H typedef char* XPointer; typedef unsigned char KeyCode; typedef unsigned int CARD32; typedef unsigned long VisualID; typedef unsigned long XIMResetState; typedef unsigned long XID; typedef XID Window; typedef XID Colormap; typedef XID Cursor; typedef XID Drawable; typedef void* XtPointer; typedef XtPointer XtRequestId; typedef struct Display Display; typedef struct Screen Screen; typedef struct Status Status; typedef struct Visual Visual; typedef struct Widget *Widget; typedef struct XColor XColor; typedef struct XClassHint XClassHint; typedef struct XEvent XEvent; typedef struct XFontStruct XFontStruct; typedef struct XGCValues XGCValues; typedef struct XKeyEvent XKeyEvent; typedef struct XKeyPressedEvent XKeyPressedEvent; typedef struct XPoint XPoint; typedef struct XRectangle XRectangle; typedef struct XSelectionRequestEvent XSelectionRequestEvent; typedef struct XWindowChanges XWindowChanges; typedef struct _XGC _XCG; typedef struct _XGC *GC; typedef struct _XIC *XIC; typedef struct _XIM *XIM; typedef struct _XImage XImage; #endif ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/_ansi.h0000664000175000017500000000006714716121045020777 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792674026.6944914 pycparser-3.12/utils/fake_libc_include/_fake_defines.h0000664000175000017500000001353715266404353022465 0ustar00elibeneliben#ifndef _FAKE_DEFINES_H #define _FAKE_DEFINES_H #define NULL 0 #define BUFSIZ 1024 #define FOPEN_MAX 20 #define FILENAME_MAX 1024 #ifndef SEEK_SET #define SEEK_SET 0 /* set file offset to offset */ #endif #ifndef SEEK_CUR #define SEEK_CUR 1 /* set file offset to current plus offset */ #endif #ifndef SEEK_END #define SEEK_END 2 /* set file offset to EOF plus offset */ #endif #define __LITTLE_ENDIAN 1234 #define LITTLE_ENDIAN __LITTLE_ENDIAN #define __BIG_ENDIAN 4321 #define BIG_ENDIAN __BIG_ENDIAN #define __BYTE_ORDER __LITTLE_ENDIAN #define BYTE_ORDER __BYTE_ORDER #define EXIT_FAILURE 1 #define EXIT_SUCCESS 0 #define SCHAR_MIN -128 #define SCHAR_MAX 127 #define CHAR_MIN -128 #define CHAR_MAX 127 #define UCHAR_MAX 255 #define SHRT_MIN -32768 #define SHRT_MAX 32767 #define USHRT_MAX 65535 #define INT_MIN -2147483648 #define INT_MAX 2147483647 #define UINT_MAX 4294967295U #define LONG_MIN -9223372036854775808L #define LONG_MAX 9223372036854775807L #define ULONG_MAX 18446744073709551615UL #define RAND_MAX 32767 /* C99 inttypes.h defines */ #define PRId8 "d" #define PRIi8 "i" #define PRIo8 "o" #define PRIu8 "u" #define PRIx8 "x" #define PRIX8 "X" #define PRId16 "d" #define PRIi16 "i" #define PRIo16 "o" #define PRIu16 "u" #define PRIx16 "x" #define PRIX16 "X" #define PRId32 "d" #define PRIi32 "i" #define PRIo32 "o" #define PRIu32 "u" #define PRIx32 "x" #define PRIX32 "X" #define PRId64 "d" #define PRIi64 "i" #define PRIo64 "o" #define PRIu64 "u" #define PRIx64 "x" #define PRIX64 "X" #define PRIdLEAST8 "d" #define PRIiLEAST8 "i" #define PRIoLEAST8 "o" #define PRIuLEAST8 "u" #define PRIxLEAST8 "x" #define PRIXLEAST8 "X" #define PRIdLEAST16 "d" #define PRIiLEAST16 "i" #define PRIoLEAST16 "o" #define PRIuLEAST16 "u" #define PRIxLEAST16 "x" #define PRIXLEAST16 "X" #define PRIdLEAST32 "d" #define PRIiLEAST32 "i" #define PRIoLEAST32 "o" #define PRIuLEAST32 "u" #define PRIxLEAST32 "x" #define PRIXLEAST32 "X" #define PRIdLEAST64 "d" #define PRIiLEAST64 "i" #define PRIoLEAST64 "o" #define PRIuLEAST64 "u" #define PRIxLEAST64 "x" #define PRIXLEAST64 "X" #define PRIdFAST8 "d" #define PRIiFAST8 "i" #define PRIoFAST8 "o" #define PRIuFAST8 "u" #define PRIxFAST8 "x" #define PRIXFAST8 "X" #define PRIdFAST16 "d" #define PRIiFAST16 "i" #define PRIoFAST16 "o" #define PRIuFAST16 "u" #define PRIxFAST16 "x" #define PRIXFAST16 "X" #define PRIdFAST32 "d" #define PRIiFAST32 "i" #define PRIoFAST32 "o" #define PRIuFAST32 "u" #define PRIxFAST32 "x" #define PRIXFAST32 "X" #define PRIdFAST64 "d" #define PRIiFAST64 "i" #define PRIoFAST64 "o" #define PRIuFAST64 "u" #define PRIxFAST64 "x" #define PRIXFAST64 "X" #define PRIdPTR "d" #define PRIiPTR "i" #define PRIoPTR "o" #define PRIuPTR "u" #define PRIxPTR "x" #define PRIXPTR "X" #define PRIdMAX "d" #define PRIiMAX "i" #define PRIoMAX "o" #define PRIuMAX "u" #define PRIxMAX "x" #define PRIXMAX "X" #define SCNd8 "d" #define SCNi8 "i" #define SCNo8 "o" #define SCNu8 "u" #define SCNx8 "x" #define SCNd16 "d" #define SCNi16 "i" #define SCNo16 "o" #define SCNu16 "u" #define SCNx16 "x" #define SCNd32 "d" #define SCNi32 "i" #define SCNo32 "o" #define SCNu32 "u" #define SCNx32 "x" #define SCNd64 "d" #define SCNi64 "i" #define SCNo64 "o" #define SCNu64 "u" #define SCNx64 "x" #define SCNdLEAST8 "d" #define SCNiLEAST8 "i" #define SCNoLEAST8 "o" #define SCNuLEAST8 "u" #define SCNxLEAST8 "x" #define SCNdLEAST16 "d" #define SCNiLEAST16 "i" #define SCNoLEAST16 "o" #define SCNuLEAST16 "u" #define SCNxLEAST16 "x" #define SCNdLEAST32 "d" #define SCNiLEAST32 "i" #define SCNoLEAST32 "o" #define SCNuLEAST32 "u" #define SCNxLEAST32 "x" #define SCNdLEAST64 "d" #define SCNiLEAST64 "i" #define SCNoLEAST64 "o" #define SCNuLEAST64 "u" #define SCNxLEAST64 "x" #define SCNdFAST8 "d" #define SCNiFAST8 "i" #define SCNoFAST8 "o" #define SCNuFAST8 "u" #define SCNxFAST8 "x" #define SCNdFAST16 "d" #define SCNiFAST16 "i" #define SCNoFAST16 "o" #define SCNuFAST16 "u" #define SCNxFAST16 "x" #define SCNdFAST32 "d" #define SCNiFAST32 "i" #define SCNoFAST32 "o" #define SCNuFAST32 "u" #define SCNxFAST32 "x" #define SCNdFAST64 "d" #define SCNiFAST64 "i" #define SCNoFAST64 "o" #define SCNuFAST64 "u" #define SCNxFAST64 "x" #define SCNdPTR "d" #define SCNiPTR "i" #define SCNoPTR "o" #define SCNuPTR "u" #define SCNxPTR "x" #define SCNdMAX "d" #define SCNiMAX "i" #define SCNoMAX "o" #define SCNuMAX "u" #define SCNxMAX "x" /* C99 stdbool.h defines */ #define __bool_true_false_are_defined 1 #define false 0 #define true 1 /* va_arg macros and type*/ #define va_start(_ap, _type) __builtin_va_start((_ap)) #define va_arg(_ap, _type) __builtin_va_arg((_ap), _type) #define va_end(_list) /* Vectors */ #define __m128 int #define __m128_u int #define __m128d int #define __m128d_u int #define __m128i int #define __m128i_u int #define __m256 int #define __m256_u int #define __m256d int #define __m256d_u int #define __m256i int #define __m256i_u int #define __m512 int #define __m512_u int #define __m512d int #define __m512d_u int #define __m512i int #define __m512i_u int /* C11 stdnoreturn.h defines */ #define __noreturn_is_defined 1 #define noreturn _Noreturn /* C11 threads.h defines */ #define thread_local _Thread_local #define ONCE_FLAG_INIT 0 #define TSS_DTOR_ITERATIONS 1 /* C11 assert.h defines */ #define static_assert _Static_assert /* C11 stdatomic.h defines */ #define ATOMIC_BOOL_LOCK_FREE 0 #define ATOMIC_CHAR_LOCK_FREE 0 #define ATOMIC_CHAR16_T_LOCK_FREE 0 #define ATOMIC_CHAR32_T_LOCK_FREE 0 #define ATOMIC_WCHAR_T_LOCK_FREE 0 #define ATOMIC_SHORT_LOCK_FREE 0 #define ATOMIC_INT_LOCK_FREE 0 #define ATOMIC_LONG_LOCK_FREE 0 #define ATOMIC_LLONG_LOCK_FREE 0 #define ATOMIC_POINTER_LOCK_FREE 0 #define ATOMIC_VAR_INIT(value) (value) #define ATOMIC_FLAG_INIT { 0 } #define kill_dependency(y) (y) /* C11 stdalign.h defines */ #define alignas _Alignas #define alignof _Alignof #define __alignas_is_defined 1 #define __alignof_is_defined 1 #endif ././@PaxHeader0000000000000000000000000000003200000000000010210 xustar0026 mtime=1791467015.30603 pycparser-3.12/utils/fake_libc_include/_fake_typedefs.h0000664000175000017500000001563315261717007022670 0ustar00elibeneliben#ifndef _FAKE_TYPEDEFS_H #define _FAKE_TYPEDEFS_H typedef int size_t; typedef int __builtin_va_list; typedef int __gnuc_va_list; typedef int va_list; typedef int __int8_t; typedef int __uint8_t; typedef int __int16_t; typedef int __uint16_t; typedef int __int_least16_t; typedef int __uint_least16_t; typedef int __int32_t; typedef int __uint32_t; typedef int __int64_t; typedef int __uint64_t; typedef int __int_least32_t; typedef int __uint_least32_t; typedef int __s8; typedef int __u8; typedef int __s16; typedef int __u16; typedef int __s32; typedef int __u32; typedef int __s64; typedef int __u64; typedef int _LOCK_T; typedef int _LOCK_RECURSIVE_T; typedef int _off_t; typedef int __dev_t; typedef int __uid_t; typedef int __gid_t; typedef int _off64_t; typedef int _fpos_t; typedef int _ssize_t; typedef int wint_t; typedef int _mbstate_t; typedef int _flock_t; typedef int _iconv_t; typedef int __ULong; typedef int __FILE; typedef int ptrdiff_t; typedef int max_align_t; typedef int wchar_t; typedef int char16_t; typedef int char32_t; typedef int __off_t; typedef int __pid_t; typedef int __loff_t; typedef int u_char; typedef int u_short; typedef int u_int; typedef int u_long; typedef int ushort; typedef int uint; typedef int clock_t; typedef int time_t; typedef int daddr_t; typedef int caddr_t; typedef int ino_t; typedef int off_t; typedef int dev_t; typedef int uid_t; typedef int gid_t; typedef int pid_t; typedef int key_t; typedef int ssize_t; typedef int mode_t; typedef int nlink_t; typedef int fd_mask; typedef int _types_fd_set; typedef int clockid_t; typedef int timer_t; typedef int useconds_t; typedef int suseconds_t; typedef int FILE; typedef int fpos_t; typedef int cookie_read_function_t; typedef int cookie_write_function_t; typedef int cookie_seek_function_t; typedef int cookie_close_function_t; typedef int cookie_io_functions_t; typedef int div_t; typedef int ldiv_t; typedef int lldiv_t; typedef int sigset_t; typedef int __sigset_t; typedef int _sig_func_ptr; typedef int sig_atomic_t; typedef int __tzrule_type; typedef int __tzinfo_type; typedef int mbstate_t; typedef int sem_t; typedef int pthread_t; typedef int pthread_attr_t; typedef int pthread_mutex_t; typedef int pthread_mutexattr_t; typedef int pthread_cond_t; typedef int pthread_condattr_t; typedef int pthread_key_t; typedef int pthread_once_t; typedef int pthread_rwlock_t; typedef int pthread_rwlockattr_t; typedef int pthread_spinlock_t; typedef int pthread_barrier_t; typedef int pthread_barrierattr_t; typedef int jmp_buf; typedef int rlim_t; typedef int sa_family_t; typedef int sigjmp_buf; typedef int stack_t; typedef int siginfo_t; typedef int z_stream; /* C99 exact-width integer types */ typedef int int8_t; typedef int uint8_t; typedef int int16_t; typedef int uint16_t; typedef int int32_t; typedef int uint32_t; typedef int int64_t; typedef int uint64_t; /* C99 minimum-width integer types */ typedef int int_least8_t; typedef int uint_least8_t; typedef int int_least16_t; typedef int uint_least16_t; typedef int int_least32_t; typedef int uint_least32_t; typedef int int_least64_t; typedef int uint_least64_t; /* C99 fastest minimum-width integer types */ typedef int int_fast8_t; typedef int uint_fast8_t; typedef int int_fast16_t; typedef int uint_fast16_t; typedef int int_fast32_t; typedef int uint_fast32_t; typedef int int_fast64_t; typedef int uint_fast64_t; /* C99 integer types capable of holding object pointers */ typedef int intptr_t; typedef int uintptr_t; /* C99 greatest-width integer types */ typedef int intmax_t; typedef int uintmax_t; /* C99 stdbool.h bool type. _Bool is built-in in C99 */ typedef _Bool bool; /* GNU Extension for 64-bit targets */ #ifdef __SIZEOF_INT128__ typedef int __int128_t; typedef int __uint128_t; #endif /* __SIZEOF_INT128__ */ /* Mir typedefs */ typedef void* MirEGLNativeWindowType; typedef void* MirEGLNativeDisplayType; typedef struct MirConnection MirConnection; typedef struct MirSurface MirSurface; typedef struct MirSurfaceSpec MirSurfaceSpec; typedef struct MirScreencast MirScreencast; typedef struct MirPromptSession MirPromptSession; typedef struct MirBufferStream MirBufferStream; typedef struct MirPersistentId MirPersistentId; typedef struct MirBlob MirBlob; typedef struct MirDisplayConfig MirDisplayConfig; /* xcb typedefs */ typedef struct xcb_connection_t xcb_connection_t; typedef uint32_t xcb_window_t; typedef uint32_t xcb_visualid_t; /* dirent typedef */ typedef void* DIR; /* socket typedefs */ typedef __uint32_t __socklen_t; typedef __socklen_t socklen_t; typedef unsigned short __kernel_sa_family_t; /* C11 threads.h types */ typedef int cnd_t; typedef int thrd_t; typedef int tss_t; typedef int mtx_t; typedef int tss_dtor_t; typedef int thrd_start_t; typedef int once_flag; /* C11 stdatomic.h types */ typedef _Atomic(_Bool) atomic_bool; typedef _Atomic(char) atomic_char; typedef _Atomic(signed char) atomic_schar; typedef _Atomic(unsigned char) atomic_uchar; typedef _Atomic(short) atomic_short; typedef _Atomic(unsigned short) atomic_ushort; typedef _Atomic(int) atomic_int; typedef _Atomic(unsigned int) atomic_uint; typedef _Atomic(long) atomic_long; typedef _Atomic(unsigned long) atomic_ulong; typedef _Atomic(long long) atomic_llong; typedef _Atomic(unsigned long long) atomic_ullong; typedef _Atomic(uint_least16_t) atomic_char16_t; typedef _Atomic(uint_least32_t) atomic_char32_t; typedef _Atomic(wchar_t) atomic_wchar_t; typedef _Atomic(int_least8_t) atomic_int_least8_t; typedef _Atomic(uint_least8_t) atomic_uint_least8_t; typedef _Atomic(int_least16_t) atomic_int_least16_t; typedef _Atomic(uint_least16_t) atomic_uint_least16_t; typedef _Atomic(int_least32_t) atomic_int_least32_t; typedef _Atomic(uint_least32_t) atomic_uint_least32_t; typedef _Atomic(int_least64_t) atomic_int_least64_t; typedef _Atomic(uint_least64_t) atomic_uint_least64_t; typedef _Atomic(int_fast8_t) atomic_int_fast8_t; typedef _Atomic(uint_fast8_t) atomic_uint_fast8_t; typedef _Atomic(int_fast16_t) atomic_int_fast16_t; typedef _Atomic(uint_fast16_t) atomic_uint_fast16_t; typedef _Atomic(int_fast32_t) atomic_int_fast32_t; typedef _Atomic(uint_fast32_t) atomic_uint_fast32_t; typedef _Atomic(int_fast64_t) atomic_int_fast64_t; typedef _Atomic(uint_fast64_t) atomic_uint_fast64_t; typedef _Atomic(intptr_t) atomic_intptr_t; typedef _Atomic(uintptr_t) atomic_uintptr_t; typedef _Atomic(size_t) atomic_size_t; typedef _Atomic(ptrdiff_t) atomic_ptrdiff_t; typedef _Atomic(intmax_t) atomic_intmax_t; typedef _Atomic(uintmax_t) atomic_uintmax_t; typedef struct atomic_flag { atomic_bool _Value; } atomic_flag; typedef enum memory_order { memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst } memory_order; #endif ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/_syslist.h0000664000175000017500000000006714716121045021557 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/aio.h0000664000175000017500000000006714716121045020456 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/alloca.h0000664000175000017500000000006714716121045021141 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/ar.h0000664000175000017500000000006714716121045020310 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/argz.h0000664000175000017500000000006714716121045020651 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8548532 pycparser-3.12/utils/fake_libc_include/arpa/0000775000175000017500000000000015266410573020465 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/arpa/inet.h0000664000175000017500000000006714716121045021570 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8548787 pycparser-3.12/utils/fake_libc_include/asm-generic/0000775000175000017500000000000015266410573021734 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/asm-generic/int-ll64.h0000664000175000017500000000006714716121045023451 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/assert.h0000664000175000017500000000006714716121045021207 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/complex.h0000664000175000017500000000006714716121045021355 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/cpio.h0000664000175000017500000000006714716121045020640 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/ctype.h0000664000175000017500000000006714716121045021032 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/dirent.h0000664000175000017500000000006714716121045021173 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/dlfcn.h0000664000175000017500000000006714716121045020774 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/emmintrin.h0000664000175000017500000000006714716121045021710 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/endian.h0000664000175000017500000000006714716121045021144 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/envz.h0000664000175000017500000000006714716121045020670 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/errno.h0000664000175000017500000000006714716121045021033 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/fastmath.h0000664000175000017500000000006714716121045021515 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/fcntl.h0000664000175000017500000000006714716121045021014 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/features.h0000664000175000017500000000006714716121045021524 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/fenv.h0000664000175000017500000000006714716121045020644 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/float.h0000664000175000017500000000006714716121045021013 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/fmtmsg.h0000664000175000017500000000006714716121045021203 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/fnmatch.h0000664000175000017500000000006714716121045021326 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/ftw.h0000664000175000017500000000006714716121045020506 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/getopt.h0000664000175000017500000000006714716121045021210 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/glob.h0000664000175000017500000000006714716121045020631 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/grp.h0000664000175000017500000000006714716121045020476 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/iconv.h0000664000175000017500000000006714716121045021024 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/ieeefp.h0000664000175000017500000000006714716121045021143 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/immintrin.h0000664000175000017500000000006714716121045021714 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/inttypes.h0000664000175000017500000000006714716121045021565 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/iso646.h0000664000175000017500000000006714716121045020740 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/langinfo.h0000664000175000017500000000006714716121045021503 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/libgen.h0000664000175000017500000000006714716121045021146 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7956626 pycparser-3.12/utils/fake_libc_include/libintl.h0000664000175000017500000000006714716121045021343 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/limits.h0000664000175000017500000000006714716121045021207 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8549297 pycparser-3.12/utils/fake_libc_include/linux/0000775000175000017500000000000015266410573020701 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/linux/socket.h0000664000175000017500000000006714716121045022335 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/linux/version.h0000664000175000017500000000006714716121045022532 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/locale.h0000664000175000017500000000006714716121045021145 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/malloc.h0000664000175000017500000000006714716121045021155 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/math.h0000664000175000017500000000006714716121045020637 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8549542 pycparser-3.12/utils/fake_libc_include/mir_toolkit/0000775000175000017500000000000015266410573022076 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/mir_toolkit/client_types.h0000664000175000017500000000006714716121045024744 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/monetary.h0000664000175000017500000000006714716121045021544 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/mqueue.h0000664000175000017500000000006714716121045021207 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/ndbm.h0000664000175000017500000000006714716121045020626 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8549917 pycparser-3.12/utils/fake_libc_include/net/0000775000175000017500000000000015266410573020330 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/net/if.h0000664000175000017500000000006714716121045021072 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/netdb.h0000664000175000017500000000006714716121045021002 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8550425 pycparser-3.12/utils/fake_libc_include/netinet/0000775000175000017500000000000015266410573021210 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/netinet/in.h0000664000175000017500000000006714716121045021762 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/netinet/tcp.h0000664000175000017500000000006714716121045022142 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/newlib.h0000664000175000017500000000006714716121045021166 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/nl_types.h0000664000175000017500000000006714716121045021543 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8551693 pycparser-3.12/utils/fake_libc_include/openssl/0000775000175000017500000000000015266410573021225 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/openssl/err.h0000664000175000017500000000006714716121045022161 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/openssl/evp.h0000664000175000017500000000006714716121045022163 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/openssl/hmac.h0000664000175000017500000000006714716121045022301 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/openssl/ssl.h0000664000175000017500000000006714716121045022172 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/openssl/x509v3.h0000664000175000017500000000006714716121045022347 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/paths.h0000664000175000017500000000006714716121045021025 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/poll.h0000664000175000017500000000006714716121045020654 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/process.h0000664000175000017500000000006714716121045021364 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/pthread.h0000664000175000017500000000006714716121045021335 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/pwd.h0000664000175000017500000000006714716121045020500 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/reent.h0000664000175000017500000000006714716121045021023 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/regdef.h0000664000175000017500000000006714716121045021142 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/regex.h0000664000175000017500000000006714716121045021020 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sched.h0000664000175000017500000000006714716121045020774 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/search.h0000664000175000017500000000006714716121045021153 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/semaphore.h0000664000175000017500000000006714716121045021671 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/setjmp.h0000664000175000017500000000006714716121045021210 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/signal.h0000664000175000017500000000006714716121045021163 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/smmintrin.h0000664000175000017500000000006714716121045021726 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/spawn.h0000664000175000017500000000006714716121045021036 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stdalign.h0000664000175000017500000000006714716121045021513 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stdarg.h0000664000175000017500000000006714716121045021172 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stdatomic.h0000664000175000017500000000006714716121045021675 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stdbool.h0000664000175000017500000000006714716121045021354 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stddef.h0000664000175000017500000000006714716121045021157 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stdint.h0000664000175000017500000000006714716121045021213 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stdio.h0000664000175000017500000000006714716121045021030 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stdlib.h0000664000175000017500000000006714716121045021167 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stdnoreturn.h0000664000175000017500000000006714716121045022275 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/string.h0000664000175000017500000000006714716121045021214 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/strings.h0000664000175000017500000000006714716121045021377 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/stropts.h0000664000175000017500000000006714716121045021424 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8556595 pycparser-3.12/utils/fake_libc_include/sys/0000775000175000017500000000000015266410573020360 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/ioctl.h0000664000175000017500000000006714716121045021636 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/ipc.h0000664000175000017500000000006714716121045021277 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/mman.h0000664000175000017500000000006714716121045021454 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/msg.h0000664000175000017500000000006714716121045021312 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/poll.h0000664000175000017500000000006714716121045021472 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/resource.h0000664000175000017500000000006714716121045022353 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/select.h0000664000175000017500000000006714716121045022003 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/sem.h0000664000175000017500000000006714716121045021310 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/shm.h0000664000175000017500000000006714716121045021313 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/socket.h0000664000175000017500000000006714716121045022014 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/stat.h0000664000175000017500000000006714716121045021477 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/statvfs.h0000664000175000017500000000006714716121045022216 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/sysctl.h0000664000175000017500000000006714716121045022045 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/time.h0000664000175000017500000000006714716121045021462 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/times.h0000664000175000017500000000006714716121045021645 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/types.h0000664000175000017500000000006714716121045021670 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/uio.h0000664000175000017500000000006714716121045021320 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/un.h0000664000175000017500000000006714716121045021146 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/utsname.h0000664000175000017500000000006714716121045022200 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/sys/wait.h0000664000175000017500000000006714716121045021470 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/syslog.h0000664000175000017500000000006714716121045021226 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/tar.h0000664000175000017500000000006714716121045020474 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/termios.h0000664000175000017500000000006714716121045021370 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/tgmath.h0000664000175000017500000000006714716121045021172 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7966628 pycparser-3.12/utils/fake_libc_include/threads.h0000664000175000017500000000006714716121045021340 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/time.h0000664000175000017500000000006714716121045020644 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/trace.h0000664000175000017500000000006714716121045021004 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1791465774.598431 pycparser-3.12/utils/fake_libc_include/uchar.h0000664000175000017500000000006715261714457021023 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/ulimit.h0000664000175000017500000000006714716121045021211 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/unctrl.h0000664000175000017500000000006714716121045021215 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/unistd.h0000664000175000017500000000006714716121045021214 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/utime.h0000664000175000017500000000006714716121045021031 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/utmp.h0000664000175000017500000000006714716121045020673 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/utmpx.h0000664000175000017500000000006714716121045021063 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/wchar.h0000664000175000017500000000006714716121045021012 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/wctype.h0000664000175000017500000000006714716121045021221 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/wordexp.h0000664000175000017500000000006714716121045021376 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1792676218.8556843 pycparser-3.12/utils/fake_libc_include/xcb/0000775000175000017500000000000015266410573020316 5ustar00elibeneliben././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/xcb/xcb.h0000664000175000017500000000006714716121045021236 0ustar00elibeneliben#include "_fake_defines.h" #include "_fake_typedefs.h" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1731764772.7976627 pycparser-3.12/utils/fake_libc_include/zlib.h0000664000175000017500000000100214716121045020634 0ustar00elibeneliben#ifndef ZLIB_H #define ZLIB_H #include "_fake_defines.h" #include "_fake_typedefs.h" typedef int uInt; typedef int uLong; #if !defined(__MACTYPES__) typedef int Byte; #endif typedef int Bytef; typedef int charf; typedef int intf; typedef int uIntf; typedef int uLongf; typedef int voidpc; typedef int voidpf; typedef int voidp; #if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) typedef int Z_U4; #endif typedef int z_crc_t; typedef int z_size_t; typedef int alloc_func; typedef int free_func; #endif