forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymtable.c
2154 lines (1977 loc) · 71.9 KB
/
symtable.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Python.h"
#include "pycore_ast.h" // identifier, stmt_ty
#include "pycore_compile.h" // _Py_Mangle(), _PyFuture_FromAST()
#include "pycore_parser.h" // _PyParser_ASTFromString()
#include "pycore_pystate.h" // _PyThreadState_GET()
#include "pycore_symtable.h" // PySTEntryObject
#include "structmember.h" // PyMemberDef
/* error strings used for warnings */
#define GLOBAL_PARAM \
"name '%U' is parameter and global"
#define NONLOCAL_PARAM \
"name '%U' is parameter and nonlocal"
#define GLOBAL_AFTER_ASSIGN \
"name '%U' is assigned to before global declaration"
#define NONLOCAL_AFTER_ASSIGN \
"name '%U' is assigned to before nonlocal declaration"
#define GLOBAL_AFTER_USE \
"name '%U' is used prior to global declaration"
#define NONLOCAL_AFTER_USE \
"name '%U' is used prior to nonlocal declaration"
#define GLOBAL_ANNOT \
"annotated name '%U' can't be global"
#define NONLOCAL_ANNOT \
"annotated name '%U' can't be nonlocal"
#define IMPORT_STAR_WARNING "import * only allowed at module level"
#define NAMED_EXPR_COMP_IN_CLASS \
"assignment expression within a comprehension cannot be used in a class body"
#define NAMED_EXPR_COMP_CONFLICT \
"assignment expression cannot rebind comprehension iteration variable '%U'"
#define NAMED_EXPR_COMP_INNER_LOOP_CONFLICT \
"comprehension inner loop cannot rebind assignment expression target '%U'"
#define NAMED_EXPR_COMP_ITER_EXPR \
"assignment expression cannot be used in a comprehension iterable expression"
#define ANNOTATION_NOT_ALLOWED \
"'%s' can not be used within an annotation"
#define LOCATION(x) \
(x)->lineno, (x)->col_offset, (x)->end_lineno, (x)->end_col_offset
#define ST_LOCATION(x) \
(x)->ste_lineno, (x)->ste_col_offset, (x)->ste_end_lineno, (x)->ste_end_col_offset
static PySTEntryObject *
ste_new(struct symtable *st, identifier name, _Py_block_ty block,
void *key, int lineno, int col_offset,
int end_lineno, int end_col_offset)
{
PySTEntryObject *ste = NULL;
PyObject *k = NULL;
k = PyLong_FromVoidPtr(key);
if (k == NULL)
goto fail;
ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
if (ste == NULL) {
Py_DECREF(k);
goto fail;
}
ste->ste_table = st;
ste->ste_id = k; /* ste owns reference to k */
ste->ste_name = Py_NewRef(name);
ste->ste_symbols = NULL;
ste->ste_varnames = NULL;
ste->ste_children = NULL;
ste->ste_directives = NULL;
ste->ste_type = block;
ste->ste_nested = 0;
ste->ste_free = 0;
ste->ste_varargs = 0;
ste->ste_varkeywords = 0;
ste->ste_opt_lineno = 0;
ste->ste_opt_col_offset = 0;
ste->ste_lineno = lineno;
ste->ste_col_offset = col_offset;
ste->ste_end_lineno = end_lineno;
ste->ste_end_col_offset = end_col_offset;
if (st->st_cur != NULL &&
(st->st_cur->ste_nested ||
st->st_cur->ste_type == FunctionBlock))
ste->ste_nested = 1;
ste->ste_child_free = 0;
ste->ste_generator = 0;
ste->ste_coroutine = 0;
ste->ste_comprehension = NoComprehension;
ste->ste_returns_value = 0;
ste->ste_needs_class_closure = 0;
ste->ste_comp_iter_target = 0;
ste->ste_comp_iter_expr = 0;
ste->ste_symbols = PyDict_New();
ste->ste_varnames = PyList_New(0);
ste->ste_children = PyList_New(0);
if (ste->ste_symbols == NULL
|| ste->ste_varnames == NULL
|| ste->ste_children == NULL)
goto fail;
if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0)
goto fail;
return ste;
fail:
Py_XDECREF(ste);
return NULL;
}
static PyObject *
ste_repr(PySTEntryObject *ste)
{
return PyUnicode_FromFormat("<symtable entry %U(%ld), line %d>",
ste->ste_name,
PyLong_AS_LONG(ste->ste_id), ste->ste_lineno);
}
static void
ste_dealloc(PySTEntryObject *ste)
{
ste->ste_table = NULL;
Py_XDECREF(ste->ste_id);
Py_XDECREF(ste->ste_name);
Py_XDECREF(ste->ste_symbols);
Py_XDECREF(ste->ste_varnames);
Py_XDECREF(ste->ste_children);
Py_XDECREF(ste->ste_directives);
PyObject_Free(ste);
}
#define OFF(x) offsetof(PySTEntryObject, x)
static PyMemberDef ste_memberlist[] = {
{"id", T_OBJECT, OFF(ste_id), READONLY},
{"name", T_OBJECT, OFF(ste_name), READONLY},
{"symbols", T_OBJECT, OFF(ste_symbols), READONLY},
{"varnames", T_OBJECT, OFF(ste_varnames), READONLY},
{"children", T_OBJECT, OFF(ste_children), READONLY},
{"nested", T_INT, OFF(ste_nested), READONLY},
{"type", T_INT, OFF(ste_type), READONLY},
{"lineno", T_INT, OFF(ste_lineno), READONLY},
{NULL}
};
PyTypeObject PySTEntry_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"symtable entry",
sizeof(PySTEntryObject),
0,
(destructor)ste_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
(reprfunc)ste_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
ste_memberlist, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
static int symtable_analyze(struct symtable *st);
static int symtable_enter_block(struct symtable *st, identifier name,
_Py_block_ty block, void *ast,
int lineno, int col_offset,
int end_lineno, int end_col_offset);
static int symtable_exit_block(struct symtable *st);
static int symtable_visit_stmt(struct symtable *st, stmt_ty s);
static int symtable_visit_expr(struct symtable *st, expr_ty s);
static int symtable_visit_genexp(struct symtable *st, expr_ty s);
static int symtable_visit_listcomp(struct symtable *st, expr_ty s);
static int symtable_visit_setcomp(struct symtable *st, expr_ty s);
static int symtable_visit_dictcomp(struct symtable *st, expr_ty s);
static int symtable_visit_arguments(struct symtable *st, arguments_ty);
static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty);
static int symtable_visit_alias(struct symtable *st, alias_ty);
static int symtable_visit_comprehension(struct symtable *st, comprehension_ty);
static int symtable_visit_keyword(struct symtable *st, keyword_ty);
static int symtable_visit_params(struct symtable *st, asdl_arg_seq *args);
static int symtable_visit_annotation(struct symtable *st, expr_ty annotation);
static int symtable_visit_argannotations(struct symtable *st, asdl_arg_seq *args);
static int symtable_implicit_arg(struct symtable *st, int pos);
static int symtable_visit_annotations(struct symtable *st, stmt_ty, arguments_ty, expr_ty);
static int symtable_visit_withitem(struct symtable *st, withitem_ty item);
static int symtable_visit_match_case(struct symtable *st, match_case_ty m);
static int symtable_visit_pattern(struct symtable *st, pattern_ty s);
static int symtable_raise_if_annotation_block(struct symtable *st, const char *, expr_ty);
static int symtable_raise_if_comprehension_block(struct symtable *st, expr_ty);
#define DUPLICATE_ARGUMENT \
"duplicate argument '%U' in function definition"
static struct symtable *
symtable_new(void)
{
struct symtable *st;
st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
if (st == NULL) {
PyErr_NoMemory();
return NULL;
}
st->st_filename = NULL;
st->st_blocks = NULL;
if ((st->st_stack = PyList_New(0)) == NULL)
goto fail;
if ((st->st_blocks = PyDict_New()) == NULL)
goto fail;
st->st_cur = NULL;
st->st_private = NULL;
return st;
fail:
_PySymtable_Free(st);
return NULL;
}
/* When compiling the use of C stack is probably going to be a lot
lighter than when executing Python code but still can overflow
and causing a Python crash if not checked (e.g. eval("()"*300000)).
Using the current recursion limit for the compiler seems too
restrictive (it caused at least one test to fail) so a factor is
used to allow deeper recursion when compiling an expression.
Using a scaling factor means this should automatically adjust when
the recursion limit is adjusted for small or large C stack allocations.
*/
#define COMPILER_STACK_FRAME_SCALE 3
struct symtable *
_PySymtable_Build(mod_ty mod, PyObject *filename, PyFutureFeatures *future)
{
struct symtable *st = symtable_new();
asdl_stmt_seq *seq;
int i;
PyThreadState *tstate;
int starting_recursion_depth;
if (st == NULL)
return NULL;
if (filename == NULL) {
_PySymtable_Free(st);
return NULL;
}
st->st_filename = Py_NewRef(filename);
st->st_future = future;
/* Setup recursion depth check counters */
tstate = _PyThreadState_GET();
if (!tstate) {
_PySymtable_Free(st);
return NULL;
}
/* Be careful here to prevent overflow. */
int recursion_depth = C_RECURSION_LIMIT - tstate->c_recursion_remaining;
starting_recursion_depth = recursion_depth * COMPILER_STACK_FRAME_SCALE;
st->recursion_depth = starting_recursion_depth;
st->recursion_limit = C_RECURSION_LIMIT * COMPILER_STACK_FRAME_SCALE;
/* Make the initial symbol information gathering pass */
if (!symtable_enter_block(st, &_Py_ID(top), ModuleBlock, (void *)mod, 0, 0, 0, 0)) {
_PySymtable_Free(st);
return NULL;
}
st->st_top = st->st_cur;
switch (mod->kind) {
case Module_kind:
seq = mod->v.Module.body;
for (i = 0; i < asdl_seq_LEN(seq); i++)
if (!symtable_visit_stmt(st,
(stmt_ty)asdl_seq_GET(seq, i)))
goto error;
break;
case Expression_kind:
if (!symtable_visit_expr(st, mod->v.Expression.body))
goto error;
break;
case Interactive_kind:
seq = mod->v.Interactive.body;
for (i = 0; i < asdl_seq_LEN(seq); i++)
if (!symtable_visit_stmt(st,
(stmt_ty)asdl_seq_GET(seq, i)))
goto error;
break;
case FunctionType_kind:
PyErr_SetString(PyExc_RuntimeError,
"this compiler does not handle FunctionTypes");
goto error;
}
if (!symtable_exit_block(st)) {
_PySymtable_Free(st);
return NULL;
}
/* Check that the recursion depth counting balanced correctly */
if (st->recursion_depth != starting_recursion_depth) {
PyErr_Format(PyExc_SystemError,
"symtable analysis recursion depth mismatch (before=%d, after=%d)",
starting_recursion_depth, st->recursion_depth);
_PySymtable_Free(st);
return NULL;
}
/* Make the second symbol analysis pass */
if (symtable_analyze(st))
return st;
_PySymtable_Free(st);
return NULL;
error:
(void) symtable_exit_block(st);
_PySymtable_Free(st);
return NULL;
}
void
_PySymtable_Free(struct symtable *st)
{
Py_XDECREF(st->st_filename);
Py_XDECREF(st->st_blocks);
Py_XDECREF(st->st_stack);
PyMem_Free((void *)st);
}
PySTEntryObject *
PySymtable_Lookup(struct symtable *st, void *key)
{
PyObject *k, *v;
k = PyLong_FromVoidPtr(key);
if (k == NULL)
return NULL;
v = PyDict_GetItemWithError(st->st_blocks, k);
Py_DECREF(k);
if (v) {
assert(PySTEntry_Check(v));
}
else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_KeyError,
"unknown symbol table entry");
}
return (PySTEntryObject *)Py_XNewRef(v);
}
long
_PyST_GetSymbol(PySTEntryObject *ste, PyObject *name)
{
PyObject *v = PyDict_GetItemWithError(ste->ste_symbols, name);
if (!v)
return 0;
assert(PyLong_Check(v));
return PyLong_AS_LONG(v);
}
int
_PyST_GetScope(PySTEntryObject *ste, PyObject *name)
{
long symbol = _PyST_GetSymbol(ste, name);
return (symbol >> SCOPE_OFFSET) & SCOPE_MASK;
}
static int
error_at_directive(PySTEntryObject *ste, PyObject *name)
{
Py_ssize_t i;
PyObject *data;
assert(ste->ste_directives);
for (i = 0; i < PyList_GET_SIZE(ste->ste_directives); i++) {
data = PyList_GET_ITEM(ste->ste_directives, i);
assert(PyTuple_CheckExact(data));
assert(PyUnicode_CheckExact(PyTuple_GET_ITEM(data, 0)));
if (PyUnicode_Compare(PyTuple_GET_ITEM(data, 0), name) == 0) {
PyErr_RangedSyntaxLocationObject(ste->ste_table->st_filename,
PyLong_AsLong(PyTuple_GET_ITEM(data, 1)),
PyLong_AsLong(PyTuple_GET_ITEM(data, 2)) + 1,
PyLong_AsLong(PyTuple_GET_ITEM(data, 3)),
PyLong_AsLong(PyTuple_GET_ITEM(data, 4)) + 1);
return 0;
}
}
PyErr_SetString(PyExc_RuntimeError,
"BUG: internal directive bookkeeping broken");
return 0;
}
/* Analyze raw symbol information to determine scope of each name.
The next several functions are helpers for symtable_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 global 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 via the symtable_visit_*
functions: the name is a parameter here, the name is used but 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 non-local variables are free or implicit globals.
Names which are explicitly declared nonlocal must exist in this set of
visible names - if they do not, a syntax error is raised. 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 added to
the free variable set by the child, the variable is marked as a cell. The
function object being defined 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.
During analysis, the names are:
symbols: dict mapping from symbol names to flag values (including offset scope values)
scopes: dict mapping from symbol names to scope values (no offset)
local: set of all symbol names local to the current scope
bound: set of all symbol names local to a containing function scope
free: set of all symbol names referenced but not bound in child scopes
global: set of all symbol names explicitly declared as global
*/
#define SET_SCOPE(DICT, NAME, I) { \
PyObject *o = PyLong_FromLong(I); \
if (!o) \
return 0; \
if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
Py_DECREF(o); \
return 0; \
} \
Py_DECREF(o); \
}
/* Decide on scope of name, given flags.
The namespace dictionaries may be modified to record information
about the new name. For example, a new global will add an entry to
global. A name that was global can be changed to local.
*/
static int
analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags,
PyObject *bound, PyObject *local, PyObject *free,
PyObject *global)
{
if (flags & DEF_GLOBAL) {
if (flags & DEF_NONLOCAL) {
PyErr_Format(PyExc_SyntaxError,
"name '%U' is nonlocal and global",
name);
return error_at_directive(ste, name);
}
SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
if (PySet_Add(global, name) < 0)
return 0;
if (bound && (PySet_Discard(bound, name) < 0))
return 0;
return 1;
}
if (flags & DEF_NONLOCAL) {
if (!bound) {
PyErr_Format(PyExc_SyntaxError,
"nonlocal declaration not allowed at module level");
return error_at_directive(ste, name);
}
if (!PySet_Contains(bound, name)) {
PyErr_Format(PyExc_SyntaxError,
"no binding for nonlocal '%U' found",
name);
return error_at_directive(ste, name);
}
SET_SCOPE(scopes, name, FREE);
ste->ste_free = 1;
return PySet_Add(free, name) >= 0;
}
if (flags & DEF_BOUND) {
SET_SCOPE(scopes, name, LOCAL);
if (PySet_Add(local, name) < 0)
return 0;
if (PySet_Discard(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 && PySet_Contains(bound, name)) {
SET_SCOPE(scopes, name, FREE);
ste->ste_free = 1;
return PySet_Add(free, name) >= 0;
}
/* If a parent has a global statement, then call it global
explicit? It could also be global implicit.
*/
if (global && PySet_Contains(global, name)) {
SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
return 1;
}
if (ste->ste_nested)
ste->ste_free = 1;
SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
return 1;
}
#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 *scopes, PyObject *free)
{
PyObject *name, *v, *v_cell;
int success = 0;
Py_ssize_t pos = 0;
v_cell = PyLong_FromLong(CELL);
if (!v_cell)
return 0;
while (PyDict_Next(scopes, &pos, &name, &v)) {
long scope;
assert(PyLong_Check(v));
scope = PyLong_AS_LONG(v);
if (scope != LOCAL)
continue;
if (!PySet_Contains(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(scopes, name, v_cell) < 0)
goto error;
if (PySet_Discard(free, name) < 0)
goto error;
}
success = 1;
error:
Py_DECREF(v_cell);
return success;
}
static int
drop_class_free(PySTEntryObject *ste, PyObject *free)
{
int res;
res = PySet_Discard(free, &_Py_ID(__class__));
if (res < 0)
return 0;
if (res)
ste->ste_needs_class_closure = 1;
return 1;
}
/* Enter the final scope information into the ste_symbols dict.
*
* All arguments are dicts. Modifies symbols, others are read-only.
*/
static int
update_symbols(PyObject *symbols, PyObject *scopes,
PyObject *bound, PyObject *free, int classflag)
{
PyObject *name = NULL, *itr = NULL;
PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL;
Py_ssize_t pos = 0;
/* Update scope information for all symbols in this scope */
while (PyDict_Next(symbols, &pos, &name, &v)) {
long scope, flags;
assert(PyLong_Check(v));
flags = PyLong_AS_LONG(v);
v_scope = PyDict_GetItemWithError(scopes, name);
assert(v_scope && PyLong_Check(v_scope));
scope = PyLong_AS_LONG(v_scope);
flags |= (scope << SCOPE_OFFSET);
v_new = PyLong_FromLong(flags);
if (!v_new)
return 0;
if (PyDict_SetItem(symbols, name, v_new) < 0) {
Py_DECREF(v_new);
return 0;
}
Py_DECREF(v_new);
}
/* Record not yet resolved free variables from children (if any) */
v_free = PyLong_FromLong(FREE << SCOPE_OFFSET);
if (!v_free)
return 0;
itr = PyObject_GetIter(free);
if (itr == NULL) {
Py_DECREF(v_free);
return 0;
}
while ((name = PyIter_Next(itr))) {
v = PyDict_GetItemWithError(symbols, name);
/* Handle symbol that already exists in this scope */
if (v) {
/* Handle 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 &&
PyLong_AS_LONG(v) & (DEF_BOUND | DEF_GLOBAL)) {
long flags = PyLong_AS_LONG(v) | DEF_FREE_CLASS;
v_new = PyLong_FromLong(flags);
if (!v_new) {
goto error;
}
if (PyDict_SetItem(symbols, name, v_new) < 0) {
Py_DECREF(v_new);
goto error;
}
Py_DECREF(v_new);
}
/* It's a cell, or already free in this scope */
Py_DECREF(name);
continue;
}
else if (PyErr_Occurred()) {
goto error;
}
/* Handle global symbol */
if (bound && !PySet_Contains(bound, name)) {
Py_DECREF(name);
continue; /* it's a global */
}
/* Propagate new free symbol up the lexical stack */
if (PyDict_SetItem(symbols, name, v_free) < 0) {
goto error;
}
Py_DECREF(name);
}
Py_DECREF(itr);
Py_DECREF(v_free);
return 1;
error:
Py_XDECREF(v_free);
Py_XDECREF(itr);
Py_XDECREF(name);
return 0;
}
/* 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). bound
is NULL for module blocks.
free -- set of free variables in enclosed scopes (output)
globals -- set of declared global variables in enclosing scopes (input)
The implementation uses two mutually recursive functions,
analyze_block() and analyze_child_block(). analyze_block() is
responsible for analyzing the individual names defined in a block.
analyze_child_block() prepares temporary namespace dictionaries
used to evaluated nested blocks.
The two functions exist because a child block should see the name
bindings of its enclosing blocks, but those bindings should not
propagate back to a parent block.
*/
static int
analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
PyObject *global, PyObject* child_free);
static int
analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free,
PyObject *global)
{
PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL;
PyObject *newglobal = NULL, *newfree = NULL, *allfree = NULL;
PyObject *temp;
int i, success = 0;
Py_ssize_t pos = 0;
local = PySet_New(NULL); /* collect new names bound in block */
if (!local)
goto error;
scopes = PyDict_New(); /* collect scopes defined for each name */
if (!scopes)
goto error;
/* Allocate new global and bound variable dictionaries. These
dictionaries hold the names visible in nested blocks. For
ClassBlocks, the bound and global names are initialized
before analyzing names, because class bindings aren't
visible in methods. For other blocks, they are initialized
after names are analyzed.
*/
/* TODO(jhylton): Package these dicts in a struct so that we
can write reasonable helper functions?
*/
newglobal = PySet_New(NULL);
if (!newglobal)
goto error;
newfree = PySet_New(NULL);
if (!newfree)
goto error;
newbound = PySet_New(NULL);
if (!newbound)
goto error;
/* Class namespace has no effect on names visible in
nested functions, so populate the global and bound
sets to be passed to child blocks before analyzing
this one.
*/
if (ste->ste_type == ClassBlock) {
/* Pass down known globals */
temp = PyNumber_InPlaceOr(newglobal, global);
if (!temp)
goto error;
Py_DECREF(temp);
/* Pass down previously bound symbols */
if (bound) {
temp = PyNumber_InPlaceOr(newbound, bound);
if (!temp)
goto error;
Py_DECREF(temp);
}
}
while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
long flags = PyLong_AS_LONG(v);
if (!analyze_name(ste, scopes, name, flags,
bound, local, free, global))
goto error;
}
/* Populate global and bound sets to be passed to children. */
if (ste->ste_type != ClassBlock) {
/* Add function locals to bound set */
if (ste->ste_type == FunctionBlock) {
temp = PyNumber_InPlaceOr(newbound, local);
if (!temp)
goto error;
Py_DECREF(temp);
}
/* Pass down previously bound symbols */
if (bound) {
temp = PyNumber_InPlaceOr(newbound, bound);
if (!temp)
goto error;
Py_DECREF(temp);
}
/* Pass down known globals */
temp = PyNumber_InPlaceOr(newglobal, global);
if (!temp)
goto error;
Py_DECREF(temp);
}
else {
/* Special-case __class__ */
if (PySet_Add(newbound, &_Py_ID(__class__)) < 0)
goto error;
}
/* Recursively call analyze_child_block() on each child block.
newbound, newglobal now contain the names visible in
nested blocks. The free variables in the children will
be collected in allfree.
*/
allfree = PySet_New(NULL);
if (!allfree)
goto error;
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_child_block(entry, newbound, newfree, newglobal,
allfree))
goto error;
/* Check if any children have free variables */
if (entry->ste_free || entry->ste_child_free)
ste->ste_child_free = 1;
}
temp = PyNumber_InPlaceOr(newfree, allfree);
if (!temp)
goto error;
Py_DECREF(temp);
/* Check if any local variables must be converted to cell variables */
if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree))
goto error;
else if (ste->ste_type == ClassBlock && !drop_class_free(ste, newfree))
goto error;
/* Records the results of the analysis in the symbol table entry */
if (!update_symbols(ste->ste_symbols, scopes, bound, newfree,
ste->ste_type == ClassBlock))
goto error;
temp = PyNumber_InPlaceOr(free, newfree);
if (!temp)
goto error;
Py_DECREF(temp);
success = 1;
error:
Py_XDECREF(scopes);
Py_XDECREF(local);
Py_XDECREF(newbound);
Py_XDECREF(newglobal);
Py_XDECREF(newfree);
Py_XDECREF(allfree);
if (!success)
assert(PyErr_Occurred());
return success;
}
static int
analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
PyObject *global, PyObject* child_free)
{
PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
PyObject *temp;
/* Copy the bound and global dictionaries.
These dictionaries are used by all blocks enclosed by the
current block. The analyze_block() call modifies these
dictionaries.
*/
temp_bound = PySet_New(bound);
if (!temp_bound)
goto error;
temp_free = PySet_New(free);
if (!temp_free)
goto error;
temp_global = PySet_New(global);
if (!temp_global)
goto error;
if (!analyze_block(entry, temp_bound, temp_free, temp_global))
goto error;
temp = PyNumber_InPlaceOr(child_free, temp_free);
if (!temp)
goto error;
Py_DECREF(temp);
Py_DECREF(temp_bound);
Py_DECREF(temp_free);
Py_DECREF(temp_global);
return 1;
error:
Py_XDECREF(temp_bound);
Py_XDECREF(temp_free);
Py_XDECREF(temp_global);
return 0;
}
static int
symtable_analyze(struct symtable *st)
{
PyObject *free, *global;
int r;
free = PySet_New(NULL);
if (!free)
return 0;
global = PySet_New(NULL);
if (!global) {
Py_DECREF(free);
return 0;
}
r = analyze_block(st->st_top, NULL, free, global);
Py_DECREF(free);
Py_DECREF(global);
return r;
}
/* symtable_enter_block() gets a reference via ste_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)
{
Py_ssize_t size;
st->st_cur = NULL;
size = PyList_GET_SIZE(st->st_stack);
if (size) {
if (PyList_SetSlice(st->st_stack, size - 1, size, NULL) < 0)
return 0;
if (--size)
st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, size - 1);
}
return 1;
}
static int
symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
void *ast, int lineno, int col_offset,
int end_lineno, int end_col_offset)
{
PySTEntryObject *prev = NULL, *ste;
ste = ste_new(st, name, block, ast, lineno, col_offset, end_lineno, end_col_offset);
if (ste == NULL)
return 0;
if (PyList_Append(st->st_stack, (PyObject *)ste) < 0) {
Py_DECREF(ste);
return 0;
}
prev = st->st_cur;
/* bpo-37757: For now, disallow *all* assignment expressions in the
* outermost iterator expression of a comprehension, even those inside
* a nested comprehension or a lambda expression.
*/
if (prev) {
ste->ste_comp_iter_expr = prev->ste_comp_iter_expr;
}
/* The entry is owned by the stack. Borrow it for st_cur. */
Py_DECREF(ste);
st->st_cur = ste;
/* Annotation blocks shouldn't have any affect on the symbol table since in
* the compilation stage, they will all be transformed to strings. They are
* only created if future 'annotations' feature is activated. */
if (block == AnnotationBlock) {
return 1;
}
if (block == ModuleBlock)
st->st_global = st->st_cur->ste_symbols;
if (prev) {
if (PyList_Append(prev->ste_children, (PyObject *)ste) < 0) {
return 0;