forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 1
/
compile.c
6287 lines (5814 loc) · 145 KB
/
compile.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
/* Compile an expression node to intermediate code */
/* XXX TO DO:
XXX add __doc__ attribute == co_doc to code object attributes?
XXX (it's currently the first item of the co_const tuple)
XXX Generate simple jump for break/return outside 'try...finally'
XXX Allow 'continue' inside finally clause of try-finally
XXX New opcode for loading the initial index for a for loop
XXX other JAR tricks?
*/
#include "Python.h"
#include "node.h"
#include "token.h"
#include "graminit.h"
#include "compile.h"
#include "symtable.h"
#include "opcode.h"
#include "structmember.h"
#include <ctype.h>
/* Three symbols from graminit.h are also defined in Python.h, with
Py_ prefixes to their names. Python.h can't include graminit.h
(which defines too many confusing symbols), but we can check here
that they haven't changed (which is very unlikely, but possible). */
#if Py_single_input != single_input
#error "single_input has changed -- update Py_single_input in Python.h"
#endif
#if Py_file_input != file_input
#error "file_input has changed -- update Py_file_input in Python.h"
#endif
#if Py_eval_input != eval_input
#error "eval_input has changed -- update Py_eval_input in Python.h"
#endif
int Py_OptimizeFlag = 0;
#define OP_DELETE 0
#define OP_ASSIGN 1
#define OP_APPLY 2
#define VAR_LOAD 0
#define VAR_STORE 1
#define VAR_DELETE 2
#define DEL_CLOSURE_ERROR \
"can not delete variable '%.400s' referenced in nested scope"
#define DUPLICATE_ARGUMENT \
"duplicate argument '%s' in function definition"
#define GLOBAL_AFTER_ASSIGN \
"name '%.400s' is assigned to before global declaration"
#define GLOBAL_AFTER_USE \
"name '%.400s' is used prior to global declaration"
#define PARAM_GLOBAL \
"name '%.400s' is a function parameter and declared global"
#define LATE_FUTURE \
"from __future__ imports must occur at the beginning of the file"
#define ASSIGN_DEBUG \
"can not assign to __debug__"
#define MANGLE_LEN 256
#define OFF(x) offsetof(PyCodeObject, x)
static PyMemberDef code_memberlist[] = {
{"co_argcount", T_INT, OFF(co_argcount), READONLY},
{"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
{"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
{"co_flags", T_INT, OFF(co_flags), READONLY},
{"co_code", T_OBJECT, OFF(co_code), READONLY},
{"co_consts", T_OBJECT, OFF(co_consts), READONLY},
{"co_names", T_OBJECT, OFF(co_names), READONLY},
{"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
{"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
{"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
{"co_filename", T_OBJECT, OFF(co_filename), READONLY},
{"co_name", T_OBJECT, OFF(co_name), READONLY},
{"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
{"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
{NULL} /* Sentinel */
};
PyDoc_STRVAR(code_doc,
"code(argcount, nlocals, stacksize, flags, codestring, constants, names,\n\
varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])\n\
\n\
Create a code object. Not for the faint of heart.");
static PyObject *
code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
int argcount;
int nlocals;
int stacksize;
int flags;
PyObject *co;
PyObject *empty = NULL;
PyObject *code;
PyObject *consts;
PyObject *names;
PyObject *varnames;
PyObject *freevars = NULL;
PyObject *cellvars = NULL;
PyObject *filename;
PyObject *name;
int firstlineno;
PyObject *lnotab;
if (!PyArg_ParseTuple(args, "iiiiSO!O!O!SSiS|O!O!:code",
&argcount, &nlocals, &stacksize, &flags,
&code,
&PyTuple_Type, &consts,
&PyTuple_Type, &names,
&PyTuple_Type, &varnames,
&filename, &name,
&firstlineno, &lnotab,
&PyTuple_Type, &freevars,
&PyTuple_Type, &cellvars))
return NULL;
if (!PyObject_CheckReadBuffer(code)) {
PyErr_SetString(PyExc_TypeError,
"bytecode object must be a single-segment read-only buffer");
return NULL;
}
if (freevars == NULL || cellvars == NULL) {
empty = PyTuple_New(0);
if (empty == NULL)
return NULL;
if (freevars == NULL)
freevars = empty;
if (cellvars == NULL)
cellvars = empty;
}
co = (PyObject *) PyCode_New(argcount, nlocals, stacksize, flags,
code, consts, names, varnames,
freevars, cellvars, filename, name,
firstlineno, lnotab);
Py_XDECREF(empty);
return co;
}
static void
code_dealloc(PyCodeObject *co)
{
Py_XDECREF(co->co_code);
Py_XDECREF(co->co_consts);
Py_XDECREF(co->co_names);
Py_XDECREF(co->co_varnames);
Py_XDECREF(co->co_freevars);
Py_XDECREF(co->co_cellvars);
Py_XDECREF(co->co_filename);
Py_XDECREF(co->co_name);
Py_XDECREF(co->co_lnotab);
PyObject_DEL(co);
}
static PyObject *
code_repr(PyCodeObject *co)
{
char buf[500];
int lineno = -1;
char *filename = "???";
char *name = "???";
if (co->co_firstlineno != 0)
lineno = co->co_firstlineno;
if (co->co_filename && PyString_Check(co->co_filename))
filename = PyString_AS_STRING(co->co_filename);
if (co->co_name && PyString_Check(co->co_name))
name = PyString_AS_STRING(co->co_name);
PyOS_snprintf(buf, sizeof(buf),
"<code object %.100s at %p, file \"%.300s\", line %d>",
name, co, filename, lineno);
return PyString_FromString(buf);
}
static int
code_compare(PyCodeObject *co, PyCodeObject *cp)
{
int cmp;
cmp = PyObject_Compare(co->co_name, cp->co_name);
if (cmp) return cmp;
cmp = co->co_argcount - cp->co_argcount;
if (cmp) return (cmp<0)?-1:1;
cmp = co->co_nlocals - cp->co_nlocals;
if (cmp) return (cmp<0)?-1:1;
cmp = co->co_flags - cp->co_flags;
if (cmp) return (cmp<0)?-1:1;
cmp = PyObject_Compare(co->co_code, cp->co_code);
if (cmp) return cmp;
cmp = PyObject_Compare(co->co_consts, cp->co_consts);
if (cmp) return cmp;
cmp = PyObject_Compare(co->co_names, cp->co_names);
if (cmp) return cmp;
cmp = PyObject_Compare(co->co_varnames, cp->co_varnames);
if (cmp) return cmp;
cmp = PyObject_Compare(co->co_freevars, cp->co_freevars);
if (cmp) return cmp;
cmp = PyObject_Compare(co->co_cellvars, cp->co_cellvars);
return cmp;
}
static long
code_hash(PyCodeObject *co)
{
long h, h0, h1, h2, h3, h4, h5, h6;
h0 = PyObject_Hash(co->co_name);
if (h0 == -1) return -1;
h1 = PyObject_Hash(co->co_code);
if (h1 == -1) return -1;
h2 = PyObject_Hash(co->co_consts);
if (h2 == -1) return -1;
h3 = PyObject_Hash(co->co_names);
if (h3 == -1) return -1;
h4 = PyObject_Hash(co->co_varnames);
if (h4 == -1) return -1;
h5 = PyObject_Hash(co->co_freevars);
if (h5 == -1) return -1;
h6 = PyObject_Hash(co->co_cellvars);
if (h6 == -1) return -1;
h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
co->co_argcount ^ co->co_nlocals ^ co->co_flags;
if (h == -1) h = -2;
return h;
}
/* XXX code objects need to participate in GC? */
PyTypeObject PyCode_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0,
"code",
sizeof(PyCodeObject),
0,
(destructor)code_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
(cmpfunc)code_compare, /* tp_compare */
(reprfunc)code_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
(hashfunc)code_hash, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
code_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
code_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 */
code_new, /* tp_new */
};
#define NAME_CHARS \
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
/* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */
static int
all_name_chars(unsigned char *s)
{
static char ok_name_char[256];
static unsigned char *name_chars = (unsigned char *)NAME_CHARS;
if (ok_name_char[*name_chars] == 0) {
unsigned char *p;
for (p = name_chars; *p; p++)
ok_name_char[*p] = 1;
}
while (*s) {
if (ok_name_char[*s++] == 0)
return 0;
}
return 1;
}
static int
intern_strings(PyObject *tuple)
{
int i;
for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
PyObject *v = PyTuple_GET_ITEM(tuple, i);
if (v == NULL || !PyString_Check(v)) {
Py_FatalError("non-string found in code slot");
PyErr_BadInternalCall();
return -1;
}
PyString_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
}
return 0;
}
#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
#define ISBASICBLOCK(blocks, start, bytes) (blocks[start]==blocks[start+bytes-1])
static unsigned int *
markblocks(unsigned char *code, int len)
{
unsigned int *blocks = PyMem_Malloc(len*sizeof(int));
int i,j, opcode, oldblock, newblock, blockcnt = 0;
if (blocks == NULL)
return NULL;
memset(blocks, 0, len*sizeof(int));
for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
opcode = code[i];
switch (opcode) {
case FOR_ITER:
case JUMP_FORWARD:
case JUMP_IF_FALSE:
case JUMP_IF_TRUE:
case JUMP_ABSOLUTE:
case CONTINUE_LOOP:
case SETUP_LOOP:
case SETUP_EXCEPT:
case SETUP_FINALLY:
j = GETJUMPTGT(code, i);
oldblock = blocks[j];
newblock = ++blockcnt;
for (; j<len ; j++) {
if (blocks[j] != (unsigned)oldblock)
break;
blocks[j] = newblock;
}
break;
}
}
return blocks;
}
static PyObject *
optimize_code(PyObject *code, PyObject* consts, PyObject *names)
{
int i, j, codelen;
int tgt, tgttgt, opcode;
unsigned char *codestr;
unsigned int *blocks;
char *name;
/* Make a modifiable copy of the code string */
if (!PyString_Check(code))
goto exitUnchanged;
codelen = PyString_Size(code);
codestr = PyMem_Malloc(codelen);
if (codestr == NULL)
goto exitUnchanged;
codestr = memcpy(codestr, PyString_AS_STRING(code), codelen);
/* Avoid situations where jump retargeting could overflow */
if (codelen > 65000)
goto exitUnchanged;
blocks = markblocks(codestr, codelen);
if (blocks == NULL) {
PyMem_Free(codestr);
goto exitUnchanged;
}
assert(PyTuple_Check(consts));
for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
opcode = codestr[i];
switch (opcode) {
/* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
with JUMP_IF_TRUE POP_TOP NOP */
case UNARY_NOT:
if (codestr[i+1] != JUMP_IF_FALSE ||
codestr[i+4] != POP_TOP ||
!ISBASICBLOCK(blocks,i,5))
continue;
tgt = GETJUMPTGT(codestr, (i+1));
if (codestr[tgt] != POP_TOP)
continue;
j = GETARG(codestr, i+1) + 1;
codestr[i] = JUMP_IF_TRUE;
SETARG(codestr, i, j);
codestr[i+3] = POP_TOP;
codestr[i+4] = NOP;
break;
/* not a is b --> a is not b
not a in b --> a not in b
not a is not b --> a is b
not a not in b --> a in b */
case COMPARE_OP:
j = GETARG(codestr, i);
if (j < 6 || j > 9 ||
codestr[i+3] != UNARY_NOT ||
!ISBASICBLOCK(blocks,i,4))
continue;
SETARG(codestr, i, (j^1));
codestr[i+3] = NOP;
break;
/* Replace LOAD_GLOBAL/LOAD_NAME None with LOAD_CONST None */
case LOAD_NAME:
case LOAD_GLOBAL:
j = GETARG(codestr, i);
name = PyString_AsString(PyTuple_GET_ITEM(names, j));
if (name == NULL || strcmp(name, "None") != 0)
continue;
for (j=0 ; j < PyTuple_GET_SIZE(consts) ; j++) {
if (PyTuple_GET_ITEM(consts, j) == Py_None) {
codestr[i] = LOAD_CONST;
SETARG(codestr, i, j);
break;
}
}
break;
/* Skip over LOAD_CONST trueconst JUMP_IF_FALSE xx POP_TOP.
Note, only the first opcode is changed, the others still
perform normally if they happen to be jump targets. */
case LOAD_CONST:
j = GETARG(codestr, i);
if (codestr[i+3] != JUMP_IF_FALSE ||
codestr[i+6] != POP_TOP ||
!PyObject_IsTrue(PyTuple_GET_ITEM(consts, j)))
continue;
codestr[i] = JUMP_FORWARD;
SETARG(codestr, i, 4);
break;
/* Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2 JMP+2 NOP NOP.
Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2 JMP+1 NOP. */
case BUILD_TUPLE:
case BUILD_LIST:
if (codestr[i+3] != UNPACK_SEQUENCE)
continue;
if (!ISBASICBLOCK(blocks,i,6))
continue;
if (GETARG(codestr, i) == 2 &&
GETARG(codestr, i+3) == 2) {
codestr[i] = ROT_TWO;
codestr[i+1] = JUMP_FORWARD;
SETARG(codestr, i+1, 2);
codestr[i+4] = NOP;
codestr[i+5] = NOP;
continue;
}
if (GETARG(codestr, i) == 3 &&
GETARG(codestr, i+3) == 3) {
codestr[i] = ROT_THREE;
codestr[i+1] = ROT_TWO;
codestr[i+2] = JUMP_FORWARD;
SETARG(codestr, i+2, 1);
codestr[i+5] = NOP;
}
break;
/* Replace jumps to unconditional jumps */
case FOR_ITER:
case JUMP_FORWARD:
case JUMP_IF_FALSE:
case JUMP_IF_TRUE:
case JUMP_ABSOLUTE:
case CONTINUE_LOOP:
case SETUP_LOOP:
case SETUP_EXCEPT:
case SETUP_FINALLY:
tgt = GETJUMPTGT(codestr, i);
if (!UNCONDITIONAL_JUMP(codestr[tgt]))
continue;
tgttgt = GETJUMPTGT(codestr, tgt);
if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
opcode = JUMP_ABSOLUTE;
if (!ABSOLUTE_JUMP(opcode))
tgttgt -= i + 3; /* Calc relative jump addr */
if (tgttgt < 0) /* No backward relative jumps */
continue;
codestr[i] = opcode;
SETARG(codestr, i, tgttgt);
break;
case EXTENDED_ARG:
PyMem_Free(codestr);
goto exitUnchanged;
}
}
code = PyString_FromStringAndSize((char *)codestr, codelen);
PyMem_Free(codestr);
PyMem_Free(blocks);
return code;
exitUnchanged:
Py_INCREF(code);
return code;
}
PyCodeObject *
PyCode_New(int argcount, int nlocals, int stacksize, int flags,
PyObject *code, PyObject *consts, PyObject *names,
PyObject *varnames, PyObject *freevars, PyObject *cellvars,
PyObject *filename, PyObject *name, int firstlineno,
PyObject *lnotab)
{
PyCodeObject *co;
int i;
/* Check argument types */
if (argcount < 0 || nlocals < 0 ||
code == NULL ||
consts == NULL || !PyTuple_Check(consts) ||
names == NULL || !PyTuple_Check(names) ||
varnames == NULL || !PyTuple_Check(varnames) ||
freevars == NULL || !PyTuple_Check(freevars) ||
cellvars == NULL || !PyTuple_Check(cellvars) ||
name == NULL || !PyString_Check(name) ||
filename == NULL || !PyString_Check(filename) ||
lnotab == NULL || !PyString_Check(lnotab) ||
!PyObject_CheckReadBuffer(code)) {
PyErr_BadInternalCall();
return NULL;
}
intern_strings(names);
intern_strings(varnames);
intern_strings(freevars);
intern_strings(cellvars);
/* Intern selected string constants */
for (i = PyTuple_Size(consts); --i >= 0; ) {
PyObject *v = PyTuple_GetItem(consts, i);
if (!PyString_Check(v))
continue;
if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
continue;
PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
}
co = PyObject_NEW(PyCodeObject, &PyCode_Type);
if (co != NULL) {
co->co_argcount = argcount;
co->co_nlocals = nlocals;
co->co_stacksize = stacksize;
co->co_flags = flags;
co->co_code = optimize_code(code, consts, names);
Py_INCREF(consts);
co->co_consts = consts;
Py_INCREF(names);
co->co_names = names;
Py_INCREF(varnames);
co->co_varnames = varnames;
Py_INCREF(freevars);
co->co_freevars = freevars;
Py_INCREF(cellvars);
co->co_cellvars = cellvars;
Py_INCREF(filename);
co->co_filename = filename;
Py_INCREF(name);
co->co_name = name;
co->co_firstlineno = firstlineno;
Py_INCREF(lnotab);
co->co_lnotab = lnotab;
if (PyTuple_GET_SIZE(freevars) == 0 &&
PyTuple_GET_SIZE(cellvars) == 0)
co->co_flags |= CO_NOFREE;
}
return co;
}
/* Data structure used internally */
/* The compiler uses two passes to generate bytecodes. The first pass
builds the symbol table. The second pass generates the bytecode.
The first pass uses a single symtable struct. The second pass uses
a compiling struct for each code block. The compiling structs
share a reference to the symtable.
The two passes communicate via symtable_load_symbols() and via
is_local() and is_global(). The former initializes several slots
in the compiling struct: c_varnames, c_locals, c_nlocals,
c_argcount, c_globals, and c_flags.
*/
/* All about c_lnotab.
c_lnotab is an array of unsigned bytes disguised as a Python string. Since
version 2.3, SET_LINENO opcodes are never generated and bytecode offsets are
mapped to source code line #s via c_lnotab instead.
The array is conceptually a list of
(bytecode offset increment, line number increment)
pairs. The details are important and delicate, best illustrated by example:
byte code offset source code line number
0 1
6 2
50 7
350 307
361 308
The first trick is that these numbers aren't stored, only the increments
from one row to the next (this doesn't really work, but it's a start):
0, 1, 6, 1, 44, 5, 300, 300, 11, 1
The second trick is that an unsigned byte can't hold negative values, or
values larger than 255, so (a) there's a deep assumption that byte code
offsets and their corresponding line #s both increase monotonically, and (b)
if at least one column jumps by more than 255 from one row to the next, more
than one pair is written to the table. In case #b, there's no way to know
from looking at the table later how many were written. That's the delicate
part. A user of c_lnotab desiring to find the source line number
corresponding to a bytecode address A should do something like this
lineno = addr = 0
for addr_incr, line_incr in c_lnotab:
addr += addr_incr
if addr > A:
return lineno
lineno += line_incr
In order for this to work, when the addr field increments by more than 255,
the line # increment in each pair generated must be 0 until the remaining addr
increment is < 256. So, in the example above, com_set_lineno should not (as
was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
255, 0, 45, 255, 0, 45.
*/
struct compiling {
PyObject *c_code; /* string */
PyObject *c_consts; /* list of objects */
PyObject *c_const_dict; /* inverse of c_consts */
PyObject *c_names; /* list of strings (names) */
PyObject *c_name_dict; /* inverse of c_names */
PyObject *c_globals; /* dictionary (value=None or True) */
PyObject *c_locals; /* dictionary (value=localID) */
PyObject *c_varnames; /* list (inverse of c_locals) */
PyObject *c_freevars; /* dictionary (value=None) */
PyObject *c_cellvars; /* list */
int c_nlocals; /* index of next local */
int c_argcount; /* number of top-level arguments */
int c_flags; /* same as co_flags */
int c_nexti; /* index into c_code */
int c_errors; /* counts errors occurred */
int c_infunction; /* set when compiling a function */
int c_interactive; /* generating code for interactive command */
int c_loops; /* counts nested loops */
int c_begin; /* begin of current loop, for 'continue' */
int c_block[CO_MAXBLOCKS]; /* stack of block types */
int c_nblocks; /* current block stack level */
const char *c_filename; /* filename of current node */
char *c_name; /* name of object (e.g. function) */
int c_lineno; /* Current line number */
int c_stacklevel; /* Current stack level */
int c_maxstacklevel; /* Maximum stack level */
int c_firstlineno;
PyObject *c_lnotab; /* Table mapping address to line number */
int c_last_addr; /* last op addr seen and recorded in lnotab */
int c_last_line; /* last line seen and recorded in lnotab */
int c_lnotab_next; /* current length of lnotab */
int c_lnotab_last; /* start of last lnotab record added */
char *c_private; /* for private name mangling */
int c_tmpname; /* temporary local name counter */
int c_nested; /* Is block nested funcdef or lamdef? */
int c_closure; /* Is nested w/freevars? */
struct symtable *c_symtable; /* pointer to module symbol table */
PyFutureFeatures *c_future; /* pointer to module's __future__ */
char *c_encoding; /* source encoding (a borrowed reference) */
};
static int
is_free(int v)
{
if ((v & (USE | DEF_FREE))
&& !(v & (DEF_LOCAL | DEF_PARAM | DEF_GLOBAL)))
return 1;
if (v & DEF_FREE_CLASS)
return 1;
return 0;
}
static void
com_error(struct compiling *c, PyObject *exc, char *msg)
{
PyObject *t = NULL, *v = NULL, *w = NULL, *line = NULL;
if (c == NULL) {
/* Error occurred via symtable call to
is_constant_false */
PyErr_SetString(exc, msg);
return;
}
c->c_errors++;
if (c->c_lineno < 1 || c->c_interactive) {
/* Unknown line number or interactive input */
PyErr_SetString(exc, msg);
return;
}
v = PyString_FromString(msg);
if (v == NULL)
return; /* MemoryError, too bad */
line = PyErr_ProgramText(c->c_filename, c->c_lineno);
if (line == NULL) {
Py_INCREF(Py_None);
line = Py_None;
}
if (exc == PyExc_SyntaxError) {
t = Py_BuildValue("(ziOO)", c->c_filename, c->c_lineno,
Py_None, line);
if (t == NULL)
goto exit;
w = PyTuple_Pack(2, v, t);
if (w == NULL)
goto exit;
PyErr_SetObject(exc, w);
} else {
/* Make sure additional exceptions are printed with
file and line, also. */
PyErr_SetObject(exc, v);
PyErr_SyntaxLocation(c->c_filename, c->c_lineno);
}
exit:
Py_XDECREF(t);
Py_XDECREF(v);
Py_XDECREF(w);
Py_XDECREF(line);
}
/* Interface to the block stack */
static void
block_push(struct compiling *c, int type)
{
if (c->c_nblocks >= CO_MAXBLOCKS) {
com_error(c, PyExc_SystemError,
"too many statically nested blocks");
}
else {
c->c_block[c->c_nblocks++] = type;
}
}
static void
block_pop(struct compiling *c, int type)
{
if (c->c_nblocks > 0)
c->c_nblocks--;
if (c->c_block[c->c_nblocks] != type && c->c_errors == 0) {
com_error(c, PyExc_SystemError, "bad block pop");
}
}
/* Prototype forward declarations */
static int issue_warning(const char *, const char *, int);
static int com_init(struct compiling *, const char *);
static void com_free(struct compiling *);
static void com_push(struct compiling *, int);
static void com_pop(struct compiling *, int);
static void com_done(struct compiling *);
static void com_node(struct compiling *, node *);
static void com_factor(struct compiling *, node *);
static void com_addbyte(struct compiling *, int);
static void com_addint(struct compiling *, int);
static void com_addoparg(struct compiling *, int, int);
static void com_addfwref(struct compiling *, int, int *);
static void com_backpatch(struct compiling *, int);
static int com_add(struct compiling *, PyObject *, PyObject *, PyObject *);
static int com_addconst(struct compiling *, PyObject *);
static int com_addname(struct compiling *, PyObject *);
static void com_addopname(struct compiling *, int, node *);
static void com_test(struct compiling *c, node *n);
static void com_list(struct compiling *, node *, int);
static void com_list_iter(struct compiling *, node *, node *, char *);
static void com_gen_iter(struct compiling *, node *, node *);
static int com_argdefs(struct compiling *, node *);
static void com_assign(struct compiling *, node *, int, node *);
static void com_assign_name(struct compiling *, node *, int);
static int com_make_closure(struct compiling *c, PyCodeObject *co);
static PyCodeObject *icompile(node *, struct compiling *);
static PyCodeObject *jcompile(node *, const char *, struct compiling *,
PyCompilerFlags *);
static PyObject *parsestrplus(struct compiling*, node *);
static PyObject *parsestr(struct compiling *, char *);
static node *get_rawdocstring(node *);
static int get_ref_type(struct compiling *, char *);
/* symtable operations */
static int symtable_lookup(struct symtable *st, char *name);
static struct symtable *symtable_build(node *, PyFutureFeatures *,
const char *filename);
static int symtable_load_symbols(struct compiling *);
static struct symtable *symtable_init(void);
static void symtable_enter_scope(struct symtable *, char *, int, int);
static int symtable_exit_scope(struct symtable *);
static int symtable_add_def(struct symtable *, char *, int);
static int symtable_add_def_o(struct symtable *, PyObject *, PyObject *, int);
static void symtable_node(struct symtable *, node *);
static void symtable_funcdef(struct symtable *, node *);
static void symtable_default_args(struct symtable *, node *);
static void symtable_params(struct symtable *, node *);
static void symtable_params_fplist(struct symtable *, node *n);
static void symtable_global(struct symtable *, node *);
static void symtable_import(struct symtable *, node *);
static void symtable_assign(struct symtable *, node *, int);
static void symtable_list_comprehension(struct symtable *, node *);
static void symtable_generator_expression(struct symtable *, node *);
static void symtable_list_for(struct symtable *, node *);
static void symtable_gen_for(struct symtable *, node *, int);
static void symtable_gen_iter(struct symtable *, node *);
static int symtable_update_free_vars(struct symtable *);
static int symtable_undo_free(struct symtable *, PyObject *, PyObject *);
static int symtable_check_global(struct symtable *, PyObject *, PyObject *);
/* helper */
static void
do_pad(int pad)
{
int i;
for (i = 0; i < pad; ++i)
fprintf(stderr, " ");
}
static void
dump(node *n, int pad, int depth)
{
int i;
if (depth == 0)
return;
do_pad(pad);
fprintf(stderr, "%d: %s\n", TYPE(n), STR(n));
if (depth > 0)
depth--;
for (i = 0; i < NCH(n); ++i)
dump(CHILD(n, i), pad + 1, depth);
}
static int
com_init(struct compiling *c, const char *filename)
{
memset((void *)c, '\0', sizeof(struct compiling));
if ((c->c_code = PyString_FromStringAndSize((char *)NULL,
1000)) == NULL)
goto fail;
if ((c->c_consts = PyList_New(0)) == NULL)
goto fail;
if ((c->c_const_dict = PyDict_New()) == NULL)
goto fail;
if ((c->c_names = PyList_New(0)) == NULL)
goto fail;
if ((c->c_name_dict = PyDict_New()) == NULL)
goto fail;
if ((c->c_locals = PyDict_New()) == NULL)
goto fail;
if ((c->c_lnotab = PyString_FromStringAndSize((char *)NULL,
1000)) == NULL)
goto fail;
c->c_globals = NULL;
c->c_varnames = NULL;
c->c_freevars = NULL;
c->c_cellvars = NULL;
c->c_nlocals = 0;
c->c_argcount = 0;
c->c_flags = 0;
c->c_nexti = 0;
c->c_errors = 0;
c->c_infunction = 0;
c->c_interactive = 0;
c->c_loops = 0;
c->c_begin = 0;
c->c_nblocks = 0;
c->c_filename = filename;
c->c_name = "?";
c->c_lineno = 0;
c->c_stacklevel = 0;
c->c_maxstacklevel = 0;
c->c_firstlineno = 0;
c->c_last_addr = 0;
c->c_last_line = 0;
c->c_lnotab_next = 0;
c->c_lnotab_last = 0;
c->c_tmpname = 0;
c->c_nested = 0;
c->c_closure = 0;
c->c_symtable = NULL;
return 1;
fail:
com_free(c);
return 0;
}
static void
com_free(struct compiling *c)
{
Py_XDECREF(c->c_code);
Py_XDECREF(c->c_consts);
Py_XDECREF(c->c_const_dict);
Py_XDECREF(c->c_names);
Py_XDECREF(c->c_name_dict);
Py_XDECREF(c->c_globals);
Py_XDECREF(c->c_locals);
Py_XDECREF(c->c_varnames);
Py_XDECREF(c->c_freevars);
Py_XDECREF(c->c_cellvars);
Py_XDECREF(c->c_lnotab);
if (c->c_future)
PyObject_FREE((void *)c->c_future);
}
static void
com_push(struct compiling *c, int n)
{
c->c_stacklevel += n;
if (c->c_stacklevel > c->c_maxstacklevel) {
c->c_maxstacklevel = c->c_stacklevel;
/*
fprintf(stderr, "%s:%s:%d max stack nexti=%d level=%d n=%d\n",
c->c_filename, c->c_name, c->c_lineno,
c->c_nexti, c->c_stacklevel, n);
*/
}
}
static void
com_pop(struct compiling *c, int n)
{
if (c->c_stacklevel < n)
c->c_stacklevel = 0;
else
c->c_stacklevel -= n;
}
static void
com_done(struct compiling *c)
{
if (c->c_code != NULL)
_PyString_Resize(&c->c_code, c->c_nexti);
if (c->c_lnotab != NULL)
_PyString_Resize(&c->c_lnotab, c->c_lnotab_next);
}
static int
com_check_size(PyObject **s, int offset)
{
int len = PyString_GET_SIZE(*s);
if (offset >= len)
return _PyString_Resize(s, len * 2);
return 0;
}
static void
com_addbyte(struct compiling *c, int byte)
{
/*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
assert(byte >= 0 && byte <= 255);
assert(c->c_code != 0);
if (com_check_size(&c->c_code, c->c_nexti)) {
c->c_errors++;
return;
}
PyString_AS_STRING(c->c_code)[c->c_nexti++] = byte;
}
static void
com_addint(struct compiling *c, int x)
{
com_addbyte(c, x & 0xff);
com_addbyte(c, x >> 8); /* XXX x should be positive */
}