Design of CPython’s Compiler#
Abstract#
In CPython, the compilation from source code to bytecode involves several steps:
Tokenize the source code (
Parser/tokenizer.c)Parse the stream of tokens into an Abstract Syntax Tree (
Parser/parser.c)Transform AST into a Control Flow Graph (
Python/compile.c)Emit bytecode based on the Control Flow Graph (
Python/compile.c)
The purpose of this document is to outline how these steps of the process work.
This document does not touch on how parsing works beyond what is needed to explain what is needed for compilation. It is also not exhaustive in terms of the how the entire system works. You will most likely need to read some source to have an exact understanding of all details.
Parsing#
As of Python 3.9, Python’s parser is a PEG parser of a somewhat unusual design (since its input is a stream of tokens rather than a stream of characters as is more common with PEG parsers).
The grammar file for Python can be found in
Grammar/python.gram. The definitions for literal tokens
(such as :, numbers, etc.) can be found in Grammar/Tokens.
Various C files, including Parser/parser.c are generated from
these (see Changing CPython’s Grammar).
Abstract Syntax Trees (AST)#
The abstract syntax tree (AST) is a high-level representation of the program structure without the necessity of containing the source code; it can be thought of as an abstract representation of the source code. The specification of the AST nodes is specified using the Zephyr Abstract Syntax Definition Language (ASDL) [Wang97].
The definition of the AST nodes for Python is found in the file
Parser/Python.asdl.
Each AST node (representing statements, expressions, and several specialized types, like list comprehensions and exception handlers) is defined by the ASDL. Most definitions in the AST correspond to a particular source construct, such as an ‘if’ statement or an attribute lookup. The definition is independent of its realization in any particular programming language.
The following fragment of the Python ASDL construct demonstrates the approach and syntax:
module Python
{
stmt = FunctionDef(identifier name, arguments args, stmt* body,
expr* decorators)
| Return(expr? value) | Yield(expr? value)
attributes (int lineno)
}
The preceding example describes two different kinds of statements and an
expression: function definitions, return statements, and yield expressions.
All three kinds are considered of type stmt as shown by | separating
the various kinds. They all take arguments of various kinds and amounts.
Modifiers on the argument type specify the number of values needed; ?
means it is optional, * means 0 or more, while no modifier means only one
value for the argument and it is required. FunctionDef, for instance,
takes an identifier for the name, arguments for args, zero or more
stmt arguments for body, and zero or more expr arguments for
decorators.
Do notice that something like ‘arguments’, which is a node type, is represented as a single AST node and not as a sequence of nodes as with stmt as one might expect.
All three kinds also have an ‘attributes’ argument; this is shown by the fact that ‘attributes’ lacks a ‘|’ before it.
The statement definitions above generate the following C structure type:
typedef struct _stmt *stmt_ty;
struct _stmt {
enum { FunctionDef_kind=1, Return_kind=2, Yield_kind=3 } kind;
union {
struct {
identifier name;
arguments_ty args;
asdl_seq *body;
} FunctionDef;
struct {
expr_ty value;
} Return;
struct {
expr_ty value;
} Yield;
} v;
int lineno;
}
Also generated are a series of constructor functions that allocate (in
this case) a stmt_ty struct with the appropriate initialization. The
kind field specifies which component of the union is initialized. The
FunctionDef() constructor function sets ‘kind’ to FunctionDef_kind and
initializes the name, args, body, and attributes fields.
Memory Management#
Before discussing the actual implementation of the compiler, a discussion of how memory is handled is in order. To make memory management simple, an arena is used. This means that a memory is pooled in a single location for easy allocation and removal. What this gives us is the removal of explicit memory deallocation. Because memory allocation for all needed memory in the compiler registers that memory with the arena, a single call to free the arena is all that is needed to completely free all memory used by the compiler.
In general, unless you are working on the critical core of the compiler, memory
management can be completely ignored. But if you are working at either the
very beginning of the compiler or the end, you need to care about how the arena
works. All code relating to the arena is in either
Include/Internal/pycore_pyarena.h or Python/pyarena.c.
PyArena_New() will create a new arena. The returned PyArena structure
will store pointers to all memory given to it. This does the bookkeeping of
what memory needs to be freed when the compiler is finished with the memory it
used. That freeing is done with PyArena_Free(). This only needs to be
called in strategic areas where the compiler exits.
As stated above, in general you should not have to worry about memory management when working on the compiler. The technical details have been designed to be hidden from you for most cases.
The only exception comes about when managing a PyObject. Since the rest
of Python uses reference counting, there is extra support added
to the arena to cleanup each PyObject that was allocated. These cases
are very rare. However, if you’ve allocated a PyObject, you must tell
the arena about it by calling PyArena_AddPyObject().
Source Code to AST#
The AST is generated from source code using the function
_PyParser_ASTFromString() or _PyParser_ASTFromFile()
(from Parser/peg_api.c) depending on the input type.
After some checks, a helper function in Parser/parser.c begins applying
production rules on the source code it receives; converting source code to
tokens and matching these tokens recursively to their corresponding rule. The
rule’s corresponding rule function is called on every match. These rule
functions follow the format xx_rule. Where xx is the grammar rule
that the function handles and is automatically derived from
Grammar/python.gram by Tools/peg_generator/pegen/c_generator.py.
Each rule function in turn creates an AST node as it goes along. It does this by allocating all the new nodes it needs, calling the proper AST node creation functions for any required supporting functions and connecting them as needed. This continues until all nonterminal symbols are replaced with terminals. If an error occurs, the rule functions backtrack and try another rule function. If there are no more rules, an error is set and the parsing ends.
The AST node creation helper functions have the name _PyAST_xx
where xx is the AST node that the function creates. These are defined by the
ASDL grammar and contained in Python/Python-ast.c (which is generated by
Parser/asdl_c.py from Parser/Python.asdl). This all leads to a
sequence of AST nodes stored in asdl_seq structs.
To demonstrate everything explained so far, here’s the
rule function responsible for a simple named import statement such as
import sys. Note that error-checking and debugging code has been
omitted. Removed parts are represented by ....
Furthermore, some comments have been added for explanation. These comments
may not be present in the actual code.
// This is the production rule (from python.gram) the rule function
// corresponds to:
// import_name: 'import' dotted_as_names
static stmt_ty
import_name_rule(Parser *p)
{
...
stmt_ty _res = NULL;
{ // 'import' dotted_as_names
...
Token * _keyword;
asdl_alias_seq* a;
// The tokenizing steps.
if (
(_keyword = _PyPegen_expect_token(p, 513)) // token='import'
&&
(a = dotted_as_names_rule(p)) // dotted_as_names
)
{
...
// Generate an AST for the import statement.
_res = _PyAST_Import ( a , ...);
...
goto done;
}
...
}
_res = NULL;
done:
...
return _res;
}
To improve backtracking performance, some rules (chosen by applying a
(memo) flag in the grammar file) are memoized. Each rule function checks if
a memoized version exists and returns that if so, else it continues in the
manner stated in the previous paragraphs.
There are macros for creating and using asdl_xx_seq * types, where xx is
a type of the ASDL sequence. Three main types are defined
manually – generic, identifier and int. These types are found in
Python/asdl.c and its corresponding header file
Include/Internal/pycore_asdl.h. Functions and macros
for creating asdl_xx_seq * types are as follows:
_Py_asdl_generic_seq_new(Py_ssize_t, PyArena *)Allocate memory for an
asdl_generic_seqof the specified length_Py_asdl_identifier_seq_new(Py_ssize_t, PyArena *)Allocate memory for an
asdl_identifier_seqof the specified length_Py_asdl_int_seq_new(Py_ssize_t, PyArena *)Allocate memory for an
asdl_int_seqof the specified length
In addition to the three types mentioned above, some ASDL sequence types are
automatically generated by Parser/asdl_c.py and found in
Include/Internal/pycore_ast.h. Macros for using both manually defined
and automatically generated ASDL sequence types are as follows:
asdl_seq_GET(asdl_xx_seq *, int)Get item held at a specific position in an
asdl_xx_seqasdl_seq_SET(asdl_xx_seq *, int, stmt_ty)Set a specific index in an
asdl_xx_seqto the specified value
Untyped counterparts exist for some of the typed macros. These are useful when a function needs to manipulate a generic ASDL sequence:
asdl_seq_GET_UNTYPED(asdl_seq *, int)Get item held at a specific position in an
asdl_seqasdl_seq_SET_UNTYPED(asdl_seq *, int, stmt_ty)Set a specific index in an
asdl_seqto the specified valueasdl_seq_LEN(asdl_seq *)Return the length of an
asdl_seqorasdl_xx_seq
Note that typed macros and functions are recommended over their untyped
counterparts. Typed macros carry out checks in debug mode and aid
debugging errors caused by incorrectly casting from void *.
If you are working with statements, you must also worry about keeping
track of what line number generated the statement. Currently the line
number is passed as the last parameter to each stmt_ty function.
Changed in version 3.9: The new PEG parser generates an AST directly without creating a
parse tree. Python/ast.c is now only used to validate the AST for
debugging purposes.
See also
PEP 617 (PEP 617 – New PEG parser for CPython)
Control Flow Graphs#
A control flow graph (often referenced by its acronym, CFG) is a directed graph that models the flow of a program. A node of a CFG is not an individual bytecode instruction, but instead represents a sequence of bytecode instructions that always execute sequentially. Each node is called a basic block and must always execute from start to finish, with a single entry point at the beginning and a single exit point at the end. If some bytecode instruction a needs to jump to some other bytecode instruction