/* Analyze raw symbol information to determine scope of each name.
The next several functions are helpers for PySymtable_Analyze(),
which determines whether a name is local, global, or free. In addition,
it determines which local variables are cell variables; they provide
bindings that are used for free variables in enclosed blocks.
There are also two kinds of free variables, implicit and explicit. An
explicit global is declared with the global statement. An implicit
global is a free variable for which the compiler has found no binding
in an enclosing function scope. The implicit global is either a global
or a builtin. Python's module and class blocks use the xxx_NAME opcodes
to handle these names to implement slightly odd semantics. In such a
block, the name is treated as global until it is assigned to; then it
is treated as a local.
The symbol table requires two passes to determine the scope of each name.
The first pass collects raw facts from the AST: the name is a parameter
here, the name is used by not defined here, etc. The second pass analyzes
these facts during a pass over the PySTEntryObjects created during pass 1.
When a function is entered during the second pass, the parent passes
the set of all name bindings visible to its children. These bindings
are used to determine if the variable is free or an implicit global.
After doing the local analysis, it analyzes each of its child blocks
using an updated set of name bindings.
The children update the free variable set. If a local variable is free
in a child, the variable is marked as a cell. The current function must
provide runtime storage for the variable that may outlive the function's
frame. Cell variables are removed from the free set before the analyze
function returns to its parent.
The sets of bound and free variables are implemented as dictionaries
mapping strings to None.
*/
The dicts passed in as arguments are modified as necessary.
ste is passed so that flags can be updated.
*/
static int
analyze_name(PySTEntryObject *ste, PyObject *dict, PyObject *name, long flags,
PyObject *bound, PyObject *local, PyObject *free,
PyObject *global)
{
if (flags & DEF_GLOBAL) {
if (flags & DEF_PARAM) {
PyErr_Format(PyExc_SyntaxError,
"name '%s' is local and global",
PyString_AS_STRING(name));
return 0;
}
SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
if (PyDict_SetItem(global, name, Py_None) < 0)
return 0;
if (bound && PyDict_GetItem(bound, name)) {
if (PyDict_DelItem(bound, name) < 0)
return 0;
}
return 1;
}
if (flags & DEF_BOUND) {
SET_SCOPE(dict, name, LOCAL);
if (PyDict_SetItem(local, name, Py_None) < 0)
return 0;
if (PyDict_GetItem(global, name)) {
if (PyDict_DelItem(global, name) < 0)
return 0;
}
return 1;
}
/* If an enclosing block has a binding for this name, it
is a free variable rather than a global variable.
Note that having a non-NULL bound implies that the block
is nested.
*/
if (bound && PyDict_GetItem(bound, name)) {
SET_SCOPE(dict, name, FREE);
ste->ste_free = 1;
if (PyDict_SetItem(free, name, Py_None) < 0)
return 0;
return 1;
}
/* If a parent has a global statement, then call it global
explicit? It could also be global implicit.
*/
else if (global && PyDict_GetItem(global, name)) {
SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
return 1;
}
else {
if (ste->ste_nested)
ste->ste_free = 1;
SET_SCOPE(dict, name, GLOBAL_IMPLICIT);
return 1;
}
return 0; /* Can't get here */
}
#undef SET_SCOPE
/* If a name is defined in free and also in locals, then this block
provides the binding for the free variable. The name should be
marked CELL in this block and removed from the free list.
Note that the current block's free variables are included in free.
That's safe because no name can be free and local in the same scope.
*/
static int
analyze_cells(PyObject *scope, PyObject *free)
{
PyObject *name, *v, *w;
int success = 0;
Py_ssize_t pos = 0;
w = PyInt_FromLong(CELL);
if (!w)
return 0;
while (PyDict_Next(scope, &pos, &name, &v)) {
long flags;
assert(PyInt_Check(v));
flags = PyInt_AS_LONG(v);
if (flags != LOCAL)
continue;
if (!PyDict_GetItem(free, name))
continue;
/* Replace LOCAL with CELL for this name, and remove
from free. It is safe to replace the value of name
in the dict, because it will not cause a resize.
*/
if (PyDict_SetItem(scope, name, w) < 0)
goto error;
if (!PyDict_DelItem(free, name) < 0)
goto error;
}
success = 1;
error:
Py_DECREF(w);
return success;
}
/* Check for illegal statements in unoptimized namespaces */
static int
check_unoptimized(const PySTEntryObject* ste) {
char buf[300];
const char* trailer;
trailer = (ste->ste_child_free ?
"contains a nested function with free variables" :
"is a nested function");
switch (ste->ste_unoptimized) {
case OPT_TOPLEVEL: /* exec / import * at top-level is fine */
case OPT_EXEC: /* qualified exec is fine */
return 1;
case OPT_IMPORT_STAR:
PyOS_snprintf(buf, sizeof(buf),
"import * is not allowed in function '%.100s' "
"because it is %s",
PyString_AS_STRING(ste->ste_name), trailer);
break;
case OPT_BARE_EXEC:
PyOS_snprintf(buf, sizeof(buf),
"unqualified exec is not allowed in function "
"'%.100s' it %s",
PyString_AS_STRING(ste->ste_name), trailer);
break;
default:
PyOS_snprintf(buf, sizeof(buf),
"function '%.100s' uses import * and bare exec, "
"which are illegal because it %s",
PyString_AS_STRING(ste->ste_name), trailer);
break;
}
/* Enter the final scope information into the st_symbols dict.
*
* All arguments are dicts. Modifies symbols, others are read-only.
*/
static int
update_symbols(PyObject *symbols, PyObject *scope,
PyObject *bound, PyObject *free, int classflag)
{
PyObject *name, *v, *u, *w, *free_value = NULL;
Py_ssize_t pos = 0;
while (PyDict_Next(symbols, &pos, &name, &v)) {
long i, flags;
assert(PyInt_Check(v));
flags = PyInt_AS_LONG(v);
w = PyDict_GetItem(scope, name);
assert(w && PyInt_Check(w));
i = PyInt_AS_LONG(w);
flags |= (i << SCOPE_OFF);
u = PyInt_FromLong(flags);
if (!u)
return 0;
if (PyDict_SetItem(symbols, name, u) < 0) {
Py_DECREF(u);
return 0;
}
Py_DECREF(u);
}
free_value = PyInt_FromLong(FREE << SCOPE_OFF);
if (!free_value)
return 0;
/* add a free variable when it's only use is for creating a closure */
pos = 0;
while (PyDict_Next(free, &pos, &name, &v)) {
PyObject *o = PyDict_GetItem(symbols, name);
if (o) {
/* It could be a free variable in a method of
the class that has the same name as a local
or global in the class scope.
*/
if (classflag &&
PyInt_AS_LONG(o) & (DEF_BOUND | DEF_GLOBAL)) {
long i = PyInt_AS_LONG(o) | DEF_FREE_CLASS;
o = PyInt_FromLong(i);
if (!o) {
Py_DECREF(free_value);
return 0;
}
if (PyDict_SetItem(symbols, name, o) < 0) {
Py_DECREF(o);
Py_DECREF(free_value);
return 0;
}
Py_DECREF(o);
}
/* else it's not free, probably a cell */
continue;
}
if (!PyDict_GetItem(bound, name))
continue; /* it's a global */
/* Make final symbol table decisions for block of ste.
Arguments:
ste -- current symtable entry (input/output)
bound -- set of variables bound in enclosing scopes (input)
free -- set of free variables in enclosed scopes (output)
globals -- set of declared global variables in enclosing scopes (input)
*/
local = PyDict_New();
if (!local)
goto error;
scope = PyDict_New();
if (!scope)
goto error;
newglobal = PyDict_New();
if (!newglobal)
goto error;
newfree = PyDict_New();
if (!newfree)
goto error;
newbound = PyDict_New();
if (!newbound)
goto error;
if (ste->ste_type == ClassBlock) {
/* make a copy of globals before calling analyze_name(),
because global statements in the class have no effect
on nested functions.
*/
if (PyDict_Update(newglobal, global) < 0)
goto error;
if (bound)
if (PyDict_Update(newbound, bound) < 0)
goto error;
}
assert(PySTEntry_Check(ste));
assert(PyDict_Check(ste->ste_symbols));
while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
long flags = PyInt_AS_LONG(v);
if (!analyze_name(ste, scope, name, flags, bound, local, free,
global))
goto error;
}
if (ste->ste_type != ClassBlock) {
if (ste->ste_type == FunctionBlock) {
if (PyDict_Update(newbound, local) < 0)
goto error;
}
if (bound) {
if (PyDict_Update(newbound, bound) < 0)
goto error;
}
if (PyDict_Update(newglobal, global) < 0)
goto error;
}
/* Recursively call analyze_block() on each child block */
for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
PySTEntryObject* entry;
assert(c && PySTEntry_Check(c));
entry = (PySTEntryObject*)c;
if (!analyze_block(entry, newbound, newfree, newglobal))
goto error;
if (entry->ste_free || entry->ste_child_free)
ste->ste_child_free = 1;
}
if (ste->ste_type == FunctionBlock && !analyze_cells(scope, newfree))
goto error;
if (!update_symbols(ste->ste_symbols, scope, bound, newfree,
ste->ste_type == ClassBlock))
goto error;
if (!check_unoptimized(ste))
goto error;
static int
symtable_analyze(struct symtable *st)
{
PyObject *free, *global;
int r;
free = PyDict_New();
if (!free)
return 0;
global = PyDict_New();
if (!global) {
Py_DECREF(free);
return 0;
}
r = analyze_block(st->st_top, NULL, free, global);
Py_DECREF(free);
Py_DECREF(global);
return r;
}
static int
symtable_warn(struct symtable *st, char *msg, int lineno)
{
if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename,
lineno, NULL, NULL) < 0) {
if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
PyErr_SetString(PyExc_SyntaxError, msg);
PyErr_SyntaxLocation(st->st_filename,
st->st_cur->ste_lineno);
}
return 0;
}
return 1;
}
/* symtable_enter_block() gets a reference via PySTEntry_New().
This reference is released when the block is exited, via the DECREF
in symtable_exit_block().
*/
static int
symtable_exit_block(struct symtable *st, void *ast)
{
Py_ssize_t end;
Py_CLEAR(st->st_cur);
end = PyList_GET_SIZE(st->st_stack) - 1;
if (end >= 0) {
st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack,
end);
if (st->st_cur == NULL)
return 0;
Py_INCREF(st->st_cur);
if (PySequence_DelItem(st->st_stack, end) < 0)
return 0;
}
return 1;
}
static int
symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
void *ast, int lineno)
{
PySTEntryObject *prev = NULL;
if (st->st_cur) {
prev = st->st_cur;
if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) {
return 0;
}
Py_DECREF(st->st_cur);
}
st->st_cur = PySTEntry_New(st, name, block, ast, lineno);
if (st->st_cur == NULL)
return 0;
if (name == GET_IDENTIFIER(top))
st->st_global = st->st_cur->ste_symbols;
if (prev) {
if (PyList_Append(prev->ste_children,
(PyObject *)st->st_cur) < 0) {
return 0;
}
}
return 1;
}
static long
symtable_lookup(struct symtable *st, PyObject *name)
{
PyObject *o;
PyObject *mangled = _Py_Mangle(st->st_private, name);
if (!mangled)
return 0;
o = PyDict_GetItem(st->st_cur->ste_symbols, mangled);
Py_DECREF(mangled);
if (!o)
return 0;
return PyInt_AsLong(o);
}
static int
symtable_add_def(struct symtable *st, PyObject *name, int flag)
{
PyObject *o;
PyObject *dict;
long val;
PyObject *mangled = _Py_Mangle(st->st_private, name);
if (!mangled)
return 0;
dict = st->st_cur->ste_symbols;
if ((o = PyDict_GetItem(dict, mangled))) {
val = PyInt_AS_LONG(o);
if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
/* Is it better to use 'mangled' or 'name' here? */
PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT,
PyString_AsString(name));
PyErr_SyntaxLocation(st->st_filename,
st->st_cur->ste_lineno);
goto error;
}
val |= flag;
} else
val = flag;
o = PyInt_FromLong(val);
if (o == NULL)
goto error;
if (PyDict_SetItem(dict, mangled, o) < 0) {
Py_DECREF(o);
goto error;
}
Py_DECREF(o);
if (flag & DEF_PARAM) {
if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0)
goto error;
} else if (flag & DEF_GLOBAL) {
/* XXX need to update DEF_GLOBAL for other flags too;
perhaps only DEF_FREE_GLOBAL */
val = flag;
if ((o = PyDict_GetItem(st->st_global, mangled))) {
val |= PyInt_AS_LONG(o);
}
o = PyInt_FromLong(val);
if (o == NULL)
goto error;
if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
Py_DECREF(o);
goto error;
}
Py_DECREF(o);
}
Py_DECREF(mangled);
return 1;
error:
Py_DECREF(mangled);
return 0;
}
/* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument.
They use the ASDL name to synthesize the name of the C type and the visit
function.
VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is
useful if the first node in the sequence requires special treatment.
*/