Files
compiler-explorer/etc/scripts/ast_dump.py
Sirui Mu 7a6af91bc9 Enable AST output for Python (#8858)
This patch adds support for viewing the abstract syntax tree (AST) of
Python source code in Compiler Explorer, matching the existing AST
viewer feature for C/C++ (Clang AST).

- This patch adds a helper script `ast_dump.py` that parses and dumps
the AST for a Python source code file. `python -m ast` should also work,
but it's not available in old versions of Python.
- This patch adds an AST parser for Python which mimics the structure of
the C/C++ AST parser. It also updates the Python compiler to enable AST
output.
- All existing and new tests pass.

Assisted-by: GitHub Copilot / DeepSeek v4 Flash
Assisted-by: GitHub Copilot / DeepSeek v4 Pro

<!-- THIS COMMENT IS INVISIBLE IN THE FINAL PR, BUT FEEL FREE TO REMOVE
IT
Thanks for taking the time to improve CE. We really appreciate it.
Before opening the PR, please make sure that the tests & linter pass
their checks,
  by running `make check`.
In the best case scenario, you are also adding tests to back up your
changes,
  but don't sweat it if you don't. We can discuss them at a later date.
Feel free to append your name to the CONTRIBUTORS.md file
Thanks again, we really appreciate this!
-->

Co-authored-by: Matt Godbolt <matt@godbolt.org>
2026-07-14 08:46:10 +01:00

46 lines
1.1 KiB
Python

"""Dumps the AST of a Python source file."""
import argparse
import ast
import sys
def main():
parser = argparse.ArgumentParser(
description="Parse and dump the AST of an Python source file"
)
parser.add_argument(
"input",
help="Path to input Python source code file",
)
args = parser.parse_args()
try:
with open(args.input, "r", encoding="utf-8") as f:
source = f.read()
except IOError as err:
# Log error and output empty array so CE handles it gracefully
print("Error reading file: %s" % err)
sys.exit(1)
try:
tree = compile(
source,
filename="<source>",
mode="exec",
flags=ast.PyCF_ONLY_AST,
dont_inherit=True,
optimize=0,
)
except SyntaxError as err:
# Output the syntax error as a single entry so CE can display it
print("SyntaxError: %s" % err)
sys.exit(1)
# The "ident" parameter is introduced in Python 3.9
print(ast.dump(tree, indent=2))
if __name__ == "__main__":
main()