1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Compile an expression node to intermediate code */
35 XXX add __doc__ attribute == co_doc to code object attributes?
36 XXX (it's currently the first item of the co_const tuple)
37 XXX Generate simple jump for break/return outside 'try...finally'
38 XXX Allow 'continue' inside try-finally
39 XXX New opcode for loading the initial index for a for loop
43 #ifndef NO_PRIVATE_NAME_MANGLING
44 #define PRIVATE_NAME_MANGLING
54 #include "structmember.h"
58 /* Three symbols from graminit.h are also defined in Python.h, with
59 Py_ prefixes to their names. Python.h can't include graminit.h
60 (which defines too many confusing symbols), but we can check here
61 that they haven't changed (which is very unlikely, but possible). */
62 #if Py_single_input != single_input
63 #error "single_input has changed -- update Py_single_input in Python.h"
65 #if Py_file_input != file_input
66 #error "file_input has changed -- update Py_file_input in Python.h"
68 #if Py_eval_input != eval_input
69 #error "eval_input has changed -- update Py_eval_input in Python.h"
72 int Py_OptimizeFlag
= 0;
78 #define OFF(x) offsetof(PyCodeObject, x)
80 static struct memberlist code_memberlist
[] = {
81 {"co_argcount", T_INT
, OFF(co_argcount
), READONLY
},
82 {"co_nlocals", T_INT
, OFF(co_nlocals
), READONLY
},
83 {"co_stacksize",T_INT
, OFF(co_stacksize
), READONLY
},
84 {"co_flags", T_INT
, OFF(co_flags
), READONLY
},
85 {"co_code", T_OBJECT
, OFF(co_code
), READONLY
},
86 {"co_consts", T_OBJECT
, OFF(co_consts
), READONLY
},
87 {"co_names", T_OBJECT
, OFF(co_names
), READONLY
},
88 {"co_varnames", T_OBJECT
, OFF(co_varnames
), READONLY
},
89 {"co_filename", T_OBJECT
, OFF(co_filename
), READONLY
},
90 {"co_name", T_OBJECT
, OFF(co_name
), READONLY
},
91 {"co_firstlineno", T_INT
, OFF(co_firstlineno
), READONLY
},
92 {"co_lnotab", T_OBJECT
, OFF(co_lnotab
), READONLY
},
97 code_getattr(co
, name
)
101 return PyMember_Get((char *)co
, code_memberlist
, name
);
108 Py_XDECREF(co
->co_code
);
109 Py_XDECREF(co
->co_consts
);
110 Py_XDECREF(co
->co_names
);
111 Py_XDECREF(co
->co_varnames
);
112 Py_XDECREF(co
->co_filename
);
113 Py_XDECREF(co
->co_name
);
114 Py_XDECREF(co
->co_lnotab
);
125 char *filename
= "???";
128 _PyCode_GETCODEPTR(co
, &p
);
129 if (*p
== SET_LINENO
)
130 lineno
= (p
[1] & 0xff) | ((p
[2] & 0xff) << 8);
131 if (co
->co_filename
&& PyString_Check(co
->co_filename
))
132 filename
= PyString_AsString(co
->co_filename
);
133 if (co
->co_name
&& PyString_Check(co
->co_name
))
134 name
= PyString_AsString(co
->co_name
);
135 sprintf(buf
, "<code object %.100s at %lx, file \"%.300s\", line %d>",
136 name
, (long)co
, filename
, lineno
);
137 return PyString_FromString(buf
);
142 PyCodeObject
*co
, *cp
;
145 cmp
= co
->co_argcount
- cp
->co_argcount
;
147 cmp
= co
->co_nlocals
- cp
->co_nlocals
;
149 cmp
= co
->co_flags
- cp
->co_flags
;
151 cmp
= PyObject_Compare(co
->co_code
, cp
->co_code
);
153 cmp
= PyObject_Compare(co
->co_consts
, cp
->co_consts
);
155 cmp
= PyObject_Compare(co
->co_names
, cp
->co_names
);
157 cmp
= PyObject_Compare(co
->co_varnames
, cp
->co_varnames
);
165 long h
, h1
, h2
, h3
, h4
;
166 h1
= PyObject_Hash(co
->co_code
);
167 if (h1
== -1) return -1;
168 h2
= PyObject_Hash(co
->co_consts
);
169 if (h2
== -1) return -1;
170 h3
= PyObject_Hash(co
->co_names
);
171 if (h3
== -1) return -1;
172 h4
= PyObject_Hash(co
->co_varnames
);
173 if (h4
== -1) return -1;
174 h
= h1
^ h2
^ h3
^ h4
^
175 co
->co_argcount
^ co
->co_nlocals
^ co
->co_flags
;
180 PyTypeObject PyCode_Type
= {
181 PyObject_HEAD_INIT(&PyType_Type
)
184 sizeof(PyCodeObject
),
186 (destructor
)code_dealloc
, /*tp_dealloc*/
188 (getattrfunc
)code_getattr
, /*tp_getattr*/
190 (cmpfunc
)code_compare
, /*tp_compare*/
191 (reprfunc
)code_repr
, /*tp_repr*/
193 0, /*tp_as_sequence*/
195 (hashfunc
)code_hash
, /*tp_hash*/
199 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
202 PyCode_New(argcount
, nlocals
, stacksize
, flags
,
203 code
, consts
, names
, varnames
, filename
, name
,
221 /* Check argument types */
222 if (argcount
< 0 || nlocals
< 0 ||
224 consts
== NULL
|| !PyTuple_Check(consts
) ||
225 names
== NULL
|| !PyTuple_Check(names
) ||
226 varnames
== NULL
|| !PyTuple_Check(varnames
) ||
227 name
== NULL
|| !PyString_Check(name
) ||
228 filename
== NULL
|| !PyString_Check(filename
) ||
229 lnotab
== NULL
|| !PyString_Check(lnotab
)) {
230 PyErr_BadInternalCall();
233 pb
= code
->ob_type
->tp_as_buffer
;
235 pb
->bf_getreadbuffer
== NULL
||
236 pb
->bf_getsegcount
== NULL
||
237 (*pb
->bf_getsegcount
)(code
, NULL
) != 1)
239 PyErr_BadInternalCall();
242 /* Make sure names and varnames are all strings, & intern them */
243 for (i
= PyTuple_Size(names
); --i
>= 0; ) {
244 PyObject
*v
= PyTuple_GetItem(names
, i
);
245 if (v
== NULL
|| !PyString_Check(v
)) {
246 PyErr_BadInternalCall();
249 PyString_InternInPlace(&PyTuple_GET_ITEM(names
, i
));
251 for (i
= PyTuple_Size(varnames
); --i
>= 0; ) {
252 PyObject
*v
= PyTuple_GetItem(varnames
, i
);
253 if (v
== NULL
|| !PyString_Check(v
)) {
254 PyErr_BadInternalCall();
257 PyString_InternInPlace(&PyTuple_GET_ITEM(varnames
, i
));
259 /* Intern selected string constants */
260 for (i
= PyTuple_Size(consts
); --i
>= 0; ) {
261 PyObject
*v
= PyTuple_GetItem(consts
, i
);
263 if (!PyString_Check(v
))
265 p
= PyString_AsString(v
);
266 if ((int)strspn(p
, NAME_CHARS
)
269 PyString_InternInPlace(&PyTuple_GET_ITEM(consts
, i
));
271 co
= PyObject_NEW(PyCodeObject
, &PyCode_Type
);
273 co
->co_argcount
= argcount
;
274 co
->co_nlocals
= nlocals
;
275 co
->co_stacksize
= stacksize
;
276 co
->co_flags
= flags
;
280 co
->co_consts
= consts
;
282 co
->co_names
= names
;
284 co
->co_varnames
= varnames
;
286 co
->co_filename
= filename
;
289 co
->co_firstlineno
= firstlineno
;
291 co
->co_lnotab
= lnotab
;
297 /* Data structure used internally */
300 PyObject
*c_code
; /* string */
301 PyObject
*c_consts
; /* list of objects */
302 PyObject
*c_names
; /* list of strings (names) */
303 PyObject
*c_globals
; /* dictionary (value=None) */
304 PyObject
*c_locals
; /* dictionary (value=localID) */
305 PyObject
*c_varnames
; /* list (inverse of c_locals) */
306 int c_nlocals
; /* index of next local */
307 int c_argcount
; /* number of top-level arguments */
308 int c_flags
; /* same as co_flags */
309 int c_nexti
; /* index into c_code */
310 int c_errors
; /* counts errors occurred */
311 int c_infunction
; /* set when compiling a function */
312 int c_interactive
; /* generating code for interactive command */
313 int c_loops
; /* counts nested loops */
314 int c_begin
; /* begin of current loop, for 'continue' */
315 int c_block
[CO_MAXBLOCKS
]; /* stack of block types */
316 int c_nblocks
; /* current block stack level */
317 char *c_filename
; /* filename of current node */
318 char *c_name
; /* name of object (e.g. function) */
319 int c_lineno
; /* Current line number */
320 int c_stacklevel
; /* Current stack level */
321 int c_maxstacklevel
; /* Maximum stack level */
323 PyObject
*c_lnotab
; /* Table mapping address to line number */
324 int c_last_addr
, c_last_line
, c_lnotab_next
;
325 #ifdef PRIVATE_NAME_MANGLING
326 char *c_private
; /* for private name mangling */
331 /* Error message including line number */
334 com_error(c
, exc
, msg
)
344 if (c
->c_lineno
<= 1) {
345 /* Unknown line number or single interactive command */
346 PyErr_SetString(exc
, msg
);
349 sprintf(buffer
, " (line %d)", c
->c_lineno
);
350 v
= PyString_FromStringAndSize((char *)NULL
, n
+ strlen(buffer
));
352 return; /* MemoryError, too bad */
353 s
= PyString_AS_STRING((PyStringObject
*)v
);
356 PyErr_SetObject(exc
, v
);
361 /* Interface to the block stack */
368 if (c
->c_nblocks
>= CO_MAXBLOCKS
) {
369 com_error(c
, PyExc_SystemError
,
370 "too many statically nested blocks");
373 c
->c_block
[c
->c_nblocks
++] = type
;
382 if (c
->c_nblocks
> 0)
384 if (c
->c_block
[c
->c_nblocks
] != type
&& c
->c_errors
== 0) {
385 com_error(c
, PyExc_SystemError
, "bad block pop");
390 /* Prototype forward declarations */
392 static int com_init
Py_PROTO((struct compiling
*, char *));
393 static void com_free
Py_PROTO((struct compiling
*));
394 static void com_push
Py_PROTO((struct compiling
*, int));
395 static void com_pop
Py_PROTO((struct compiling
*, int));
396 static void com_done
Py_PROTO((struct compiling
*));
397 static void com_node
Py_PROTO((struct compiling
*, struct _node
*));
398 static void com_factor
Py_PROTO((struct compiling
*, struct _node
*));
399 static void com_addbyte
Py_PROTO((struct compiling
*, int));
400 static void com_addint
Py_PROTO((struct compiling
*, int));
401 static void com_addoparg
Py_PROTO((struct compiling
*, int, int));
402 static void com_addfwref
Py_PROTO((struct compiling
*, int, int *));
403 static void com_backpatch
Py_PROTO((struct compiling
*, int));
404 static int com_add
Py_PROTO((struct compiling
*, PyObject
*, PyObject
*));
405 static int com_addconst
Py_PROTO((struct compiling
*, PyObject
*));
406 static int com_addname
Py_PROTO((struct compiling
*, PyObject
*));
407 static void com_addopname
Py_PROTO((struct compiling
*, int, node
*));
408 static void com_list
Py_PROTO((struct compiling
*, node
*, int));
409 static int com_argdefs
Py_PROTO((struct compiling
*, node
*));
410 static int com_newlocal
Py_PROTO((struct compiling
*, char *));
411 static PyCodeObject
*icompile
Py_PROTO((struct _node
*, struct compiling
*));
412 static PyCodeObject
*jcompile
Py_PROTO((struct _node
*, char *,
413 struct compiling
*));
414 static PyObject
*parsestrplus
Py_PROTO((node
*));
415 static PyObject
*parsestr
Py_PROTO((char *));
418 com_init(c
, filename
)
422 if ((c
->c_code
= PyString_FromStringAndSize((char *)NULL
,
425 if ((c
->c_consts
= PyList_New(0)) == NULL
)
427 if ((c
->c_names
= PyList_New(0)) == NULL
)
429 if ((c
->c_globals
= PyDict_New()) == NULL
)
431 if ((c
->c_locals
= PyDict_New()) == NULL
)
433 if ((c
->c_varnames
= PyList_New(0)) == NULL
)
435 if ((c
->c_lnotab
= PyString_FromStringAndSize((char *)NULL
,
444 c
->c_interactive
= 0;
448 c
->c_filename
= filename
;
452 c
->c_maxstacklevel
= 0;
453 c
->c_firstlineno
= 0;
456 c
-> c_lnotab_next
= 0;
460 Py_DECREF(c
->c_lnotab
);
462 Py_DECREF(c
->c_locals
);
464 Py_DECREF(c
->c_globals
);
466 Py_DECREF(c
->c_names
);
468 Py_DECREF(c
->c_consts
);
470 Py_DECREF(c
->c_code
);
479 Py_XDECREF(c
->c_code
);
480 Py_XDECREF(c
->c_consts
);
481 Py_XDECREF(c
->c_names
);
482 Py_XDECREF(c
->c_globals
);
483 Py_XDECREF(c
->c_locals
);
484 Py_XDECREF(c
->c_varnames
);
485 Py_XDECREF(c
->c_lnotab
);
493 c
->c_stacklevel
+= n
;
494 if (c
->c_stacklevel
> c
->c_maxstacklevel
)
495 c
->c_maxstacklevel
= c
->c_stacklevel
;
503 if (c
->c_stacklevel
< n
) {
505 "%s:%d: underflow! nexti=%d, level=%d, n=%d\n",
506 c->c_filename, c->c_lineno,
507 c->c_nexti, c->c_stacklevel, n); */
511 c
->c_stacklevel
-= n
;
518 if (c
->c_code
!= NULL
)
519 _PyString_Resize(&c
->c_code
, c
->c_nexti
);
520 if (c
->c_lnotab
!= NULL
)
521 _PyString_Resize(&c
->c_lnotab
, c
->c_lnotab_next
);
530 /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
531 if (byte
< 0 || byte
> 255) {
533 fprintf(stderr, "XXX compiling bad byte: %d\n", byte);
534 fatal("com_addbyte: byte out of range");
536 com_error(c
, PyExc_SystemError
,
537 "com_addbyte: byte out of range");
539 if (c
->c_code
== NULL
)
541 len
= PyString_Size(c
->c_code
);
542 if (c
->c_nexti
>= len
) {
543 if (_PyString_Resize(&c
->c_code
, len
+1000) != 0) {
548 PyString_AsString(c
->c_code
)[c
->c_nexti
++] = byte
;
556 com_addbyte(c
, x
& 0xff);
557 com_addbyte(c
, x
>> 8); /* XXX x should be positive */
561 com_add_lnotab(c
, addr
, line
)
568 if (c
->c_lnotab
== NULL
)
570 size
= PyString_Size(c
->c_lnotab
);
571 if (c
->c_lnotab_next
+2 > size
) {
572 if (_PyString_Resize(&c
->c_lnotab
, size
+ 1000) < 0) {
577 p
= PyString_AsString(c
->c_lnotab
) + c
->c_lnotab_next
;
580 c
->c_lnotab_next
+= 2;
584 com_set_lineno(c
, lineno
)
588 c
->c_lineno
= lineno
;
589 if (c
->c_firstlineno
== 0) {
590 c
->c_firstlineno
= c
->c_last_line
= lineno
;
593 int incr_addr
= c
->c_nexti
- c
->c_last_addr
;
594 int incr_line
= lineno
- c
->c_last_line
;
595 while (incr_addr
> 0 || incr_line
> 0) {
596 int trunc_addr
= incr_addr
;
597 int trunc_line
= incr_line
;
598 if (trunc_addr
> 255)
600 if (trunc_line
> 255)
602 com_add_lnotab(c
, trunc_addr
, trunc_line
);
603 incr_addr
-= trunc_addr
;
604 incr_line
-= trunc_line
;
606 c
->c_last_addr
= c
->c_nexti
;
607 c
->c_last_line
= lineno
;
612 com_addoparg(c
, op
, arg
)
617 if (op
== SET_LINENO
) {
618 com_set_lineno(c
, arg
);
627 com_addfwref(c
, op
, p_anchor
)
632 /* Compile a forward reference for backpatching */
639 com_addint(c
, anchor
== 0 ? 0 : here
- anchor
);
643 com_backpatch(c
, anchor
)
645 int anchor
; /* Must be nonzero */
647 unsigned char *code
= (unsigned char *) PyString_AsString(c
->c_code
);
648 int target
= c
->c_nexti
;
652 /* Make the JUMP instruction at anchor point to target */
653 prev
= code
[anchor
] + (code
[anchor
+1] << 8);
654 dist
= target
- (anchor
+2);
655 code
[anchor
] = dist
& 0xff;
656 code
[anchor
+1] = dist
>> 8;
663 /* Handle literals and names uniformly */
671 int n
= PyList_Size(list
);
673 /* XXX This is quadratic in the number of names per compilation unit.
674 XXX Should use a dictionary. */
675 for (i
= n
; --i
>= 0; ) {
676 PyObject
*w
= PyList_GetItem(list
, i
);
677 if (v
->ob_type
== w
->ob_type
&& PyObject_Compare(v
, w
) == 0)
680 /* Check for error from PyObject_Compare */
681 if (PyErr_Occurred() || PyList_Append(list
, v
) != 0)
691 return com_add(c
, c
->c_consts
, v
);
699 return com_add(c
, c
->c_names
, v
);
702 #ifdef PRIVATE_NAME_MANGLING
704 com_mangle(c
, name
, buffer
, maxlen
)
710 /* Name mangling: __private becomes _classname__private.
711 This is independent from how the name is used. */
715 if (nlen
+2 >= maxlen
)
716 return 0; /* Don't mangle __extremely_long_names */
717 if (name
[nlen
-1] == '_' && name
[nlen
-2] == '_')
718 return 0; /* Don't mangle __whatever__ */
720 /* Strip leading underscores from class name */
724 return 0; /* Don't mangle if class is just underscores */
726 if (plen
+ nlen
>= maxlen
)
727 plen
= maxlen
-nlen
-2; /* Truncate class name if too long */
728 /* buffer = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
730 strncpy(buffer
+1, p
, plen
);
731 strcpy(buffer
+1+plen
, name
);
732 /* fprintf(stderr, "mangle %s -> %s\n", name, buffer); */
738 com_addopnamestr(c
, op
, name
)
745 #ifdef PRIVATE_NAME_MANGLING
747 if (name
!= NULL
&& name
[0] == '_' && name
[1] == '_' &&
748 c
->c_private
!= NULL
&&
749 com_mangle(c
, name
, buffer
, (int)sizeof(buffer
)))
752 if (name
== NULL
|| (v
= PyString_InternFromString(name
)) == NULL
) {
757 i
= com_addname(c
, v
);
760 /* Hack to replace *_NAME opcodes by *_GLOBAL if necessary */
765 if (PyDict_GetItemString(c
->c_globals
, name
) != NULL
) {
767 case LOAD_NAME
: op
= LOAD_GLOBAL
; break;
768 case STORE_NAME
: op
= STORE_GLOBAL
; break;
769 case DELETE_NAME
: op
= DELETE_GLOBAL
; break;
773 com_addoparg(c
, op
, i
);
777 com_addopname(c
, op
, n
)
784 /* XXX it is possible to write this code without the 1000
785 chars on the total length of dotted names, I just can't be
786 bothered right now */
789 else if (TYPE(n
) == dotted_name
) {
793 for (i
= 0; i
< NCH(n
); i
+= 2) {
794 char *s
= STR(CHILD(n
, i
));
795 if (p
+ strlen(s
) > buffer
+ (sizeof buffer
) - 2) {
796 com_error(c
, PyExc_MemoryError
,
797 "dotted_name too long");
811 com_addopnamestr(c
, op
, name
);
816 struct compiling
*co
;
819 extern long PyOS_strtol
Py_PROTO((const char *, char **, int));
820 extern unsigned long PyOS_strtoul
Py_PROTO((const char *,
822 extern double atof
Py_PROTO((const char *));
826 #ifndef WITHOUT_COMPLEX
832 end
= s
+ strlen(s
) - 1;
833 #ifndef WITHOUT_COMPLEX
834 imflag
= *end
== 'j' || *end
== 'J';
836 if (*end
== 'l' || *end
== 'L')
837 return PyLong_FromString(s
, (char **)0, 0);
839 x
= (long) PyOS_strtoul(s
, &end
, 0);
841 x
= PyOS_strtol(s
, &end
, 0);
844 com_error(co
, PyExc_OverflowError
,
845 "integer literal too large");
848 return PyInt_FromLong(x
);
850 /* XXX Huge floats may silently fail */
851 #ifndef WITHOUT_COMPLEX
854 PyFPE_START_PROTECT("atof", return 0)
857 return PyComplex_FromCComplex(c
);
862 PyFPE_START_PROTECT("atof", return 0)
864 PyFPE_END_PROTECT(dx
)
865 return PyFloat_FromDouble(dx
);
881 if (isalpha(quote
) || quote
== '_')
883 if (quote
!= '\'' && quote
!= '\"') {
884 PyErr_BadInternalCall();
889 if (s
[--len
] != quote
) {
890 PyErr_BadInternalCall();
893 if (len
>= 4 && s
[0] == quote
&& s
[1] == quote
) {
896 if (s
[--len
] != quote
|| s
[--len
] != quote
) {
897 PyErr_BadInternalCall();
901 if (first
!= quote
|| strchr(s
, '\\') == NULL
)
902 return PyString_FromStringAndSize(s
, len
);
903 v
= PyString_FromStringAndSize((char *)NULL
, len
);
904 p
= buf
= PyString_AsString(v
);
913 /* XXX This assumes ASCII! */
915 case '\\': *p
++ = '\\'; break;
916 case '\'': *p
++ = '\''; break;
917 case '\"': *p
++ = '\"'; break;
918 case 'b': *p
++ = '\b'; break;
919 case 'f': *p
++ = '\014'; break; /* FF */
920 case 't': *p
++ = '\t'; break;
921 case 'n': *p
++ = '\n'; break;
922 case 'r': *p
++ = '\r'; break;
923 case 'v': *p
++ = '\013'; break; /* VT */
924 case 'a': *p
++ = '\007'; break; /* BEL, not classic C */
925 case '0': case '1': case '2': case '3':
926 case '4': case '5': case '6': case '7':
928 if ('0' <= *s
&& *s
<= '7') {
929 c
= (c
<<3) + *s
++ - '0';
930 if ('0' <= *s
&& *s
<= '7')
931 c
= (c
<<3) + *s
++ - '0';
936 if (isxdigit(Py_CHARMASK(*s
))) {
948 } while (isxdigit(Py_CHARMASK(*s
)));
953 default: *p
++ = '\\'; *p
++ = s
[-1]; break;
956 _PyString_Resize(&v
, (int)(p
- buf
));
966 REQ(CHILD(n
, 0), STRING
);
967 if ((v
= parsestr(STR(CHILD(n
, 0)))) != NULL
) {
968 /* String literal concatenation */
969 for (i
= 1; i
< NCH(n
) && v
!= NULL
; i
++) {
970 PyString_ConcatAndDel(&v
, parsestr(STR(CHILD(n
, i
))));
977 com_list_constructor(c
, n
)
983 if (TYPE(n
) != testlist
)
985 /* exprlist: expr (',' expr)* [',']; likewise for testlist */
986 len
= (NCH(n
) + 1) / 2;
987 for (i
= 0; i
< NCH(n
); i
+= 2)
988 com_node(c
, CHILD(n
, i
));
989 com_addoparg(c
, BUILD_LIST
, len
);
999 /* dictmaker: test ':' test (',' test ':' value)* [','] */
1000 for (i
= 0; i
+2 < NCH(n
); i
+= 4) {
1001 /* We must arrange things just right for STORE_SUBSCR.
1002 It wants the stack to look like (value) (dict) (key) */
1003 com_addbyte(c
, DUP_TOP
);
1005 com_node(c
, CHILD(n
, i
+2)); /* value */
1006 com_addbyte(c
, ROT_TWO
);
1007 com_node(c
, CHILD(n
, i
)); /* key */
1008 com_addbyte(c
, STORE_SUBSCR
);
1015 struct compiling
*c
;
1025 if (TYPE(CHILD(n
, 1)) == RPAR
) {
1026 com_addoparg(c
, BUILD_TUPLE
, 0);
1030 com_node(c
, CHILD(n
, 1));
1033 if (TYPE(CHILD(n
, 1)) == RSQB
) {
1034 com_addoparg(c
, BUILD_LIST
, 0);
1038 com_list_constructor(c
, CHILD(n
, 1));
1040 case LBRACE
: /* '{' [dictmaker] '}' */
1041 com_addoparg(c
, BUILD_MAP
, 0);
1043 if (TYPE(CHILD(n
, 1)) != RBRACE
)
1044 com_dictmaker(c
, CHILD(n
, 1));
1047 com_node(c
, CHILD(n
, 1));
1048 com_addbyte(c
, UNARY_CONVERT
);
1051 if ((v
= parsenumber(c
, STR(ch
))) == NULL
) {
1055 i
= com_addconst(c
, v
);
1058 com_addoparg(c
, LOAD_CONST
, i
);
1062 v
= parsestrplus(n
);
1068 i
= com_addconst(c
, v
);
1071 com_addoparg(c
, LOAD_CONST
, i
);
1075 com_addopname(c
, LOAD_NAME
, ch
);
1079 /* XXX fprintf(stderr, "node type %d\n", TYPE(ch)); */
1080 com_error(c
, PyExc_SystemError
,
1081 "com_atom: unexpected node type");
1087 struct compiling
*c
;
1094 else if (NCH(n
) == 2) {
1095 if (TYPE(CHILD(n
, 0)) != COLON
) {
1096 com_node(c
, CHILD(n
, 0));
1097 com_addbyte(c
, op
+1);
1100 com_node(c
, CHILD(n
, 1));
1101 com_addbyte(c
, op
+2);
1106 com_node(c
, CHILD(n
, 0));
1107 com_node(c
, CHILD(n
, 2));
1108 com_addbyte(c
, op
+3);
1114 com_argument(c
, n
, pkeywords
)
1115 struct compiling
*c
;
1116 node
*n
; /* argument */
1117 PyObject
**pkeywords
;
1120 REQ(n
, argument
); /* [test '='] test; really [keyword '='] test */
1122 if (*pkeywords
!= NULL
) {
1123 com_error(c
, PyExc_SyntaxError
,
1124 "non-keyword arg after keyword arg");
1127 com_node(c
, CHILD(n
, 0));
1134 } while (NCH(m
) == 1);
1135 if (TYPE(m
) != NAME
) {
1136 com_error(c
, PyExc_SyntaxError
,
1137 "keyword can't be an expression");
1140 PyObject
*v
= PyString_InternFromString(STR(m
));
1141 if (v
!= NULL
&& *pkeywords
== NULL
)
1142 *pkeywords
= PyDict_New();
1143 if (v
== NULL
|| *pkeywords
== NULL
)
1146 if (PyDict_GetItem(*pkeywords
, v
) != NULL
)
1147 com_error(c
, PyExc_SyntaxError
,
1148 "duplicate keyword argument");
1150 if (PyDict_SetItem(*pkeywords
, v
, v
) != 0)
1152 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, v
));
1157 com_node(c
, CHILD(n
, 2));
1161 com_call_function(c
, n
)
1162 struct compiling
*c
;
1163 node
*n
; /* EITHER arglist OR ')' */
1165 if (TYPE(n
) == RPAR
) {
1166 com_addoparg(c
, CALL_FUNCTION
, 0);
1169 PyObject
*keywords
= NULL
;
1174 for (i
= 0; i
< NCH(n
); i
+= 2) {
1175 com_argument(c
, CHILD(n
, i
), &keywords
);
1176 if (keywords
== NULL
)
1181 Py_XDECREF(keywords
);
1182 if (na
> 255 || nk
> 255) {
1183 com_error(c
, PyExc_SyntaxError
,
1184 "more than 255 arguments");
1186 com_addoparg(c
, CALL_FUNCTION
, na
| (nk
<< 8));
1187 com_pop(c
, na
+ 2*nk
);
1192 com_select_member(c
, n
)
1193 struct compiling
*c
;
1196 com_addopname(c
, LOAD_ATTR
, n
);
1201 struct compiling
*c
;
1205 int ns
=2; /* number of slice arguments */
1208 /* first argument */
1209 if (TYPE(CHILD(n
,i
)) == COLON
) {
1210 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1215 com_node(c
, CHILD(n
,i
));
1217 REQ(CHILD(n
,i
),COLON
);
1220 /* second argument */
1221 if (i
< NCH(n
) && TYPE(CHILD(n
,i
)) == test
) {
1222 com_node(c
, CHILD(n
,i
));
1226 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1229 /* remaining arguments */
1230 for (; i
< NCH(n
); i
++) {
1235 /* right argument of ':' missing */
1236 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
1240 com_node(c
, CHILD(ch
,1));
1242 com_addoparg(c
, BUILD_SLICE
, ns
);
1243 com_pop(c
, 1 + (ns
== 3));
1248 struct compiling
*c
;
1254 /* check for rubber index */
1255 if (TYPE(ch
) == DOT
&& TYPE(CHILD(n
,1)) == DOT
) {
1256 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_Ellipsis
));
1260 /* check for slice */
1261 if ((TYPE(ch
) == COLON
|| NCH(n
) > 1))
1271 com_subscriptlist(c
, n
, assigning
)
1272 struct compiling
*c
;
1277 REQ(n
, subscriptlist
);
1278 /* Check to make backward compatible slice behavior for '[i:j]' */
1280 node
*sub
= CHILD(n
, 0); /* subscript */
1281 /* Make it is a simple slice.
1282 Should have exactly one colon. */
1283 if ((TYPE(CHILD(sub
, 0)) == COLON
1284 || (NCH(sub
) > 1 && TYPE(CHILD(sub
, 1)) == COLON
))
1285 && (TYPE(CHILD(sub
,NCH(sub
)-1)) != sliceop
))
1287 if (assigning
== OP_APPLY
)
1290 op
= ((assigning
== OP_ASSIGN
) ?
1291 STORE_SLICE
: DELETE_SLICE
);
1292 com_slice(c
, sub
, op
);
1293 if (op
== STORE_SLICE
)
1295 else if (op
== DELETE_SLICE
)
1300 /* Else normal subscriptlist. Compile each subscript. */
1301 for (i
= 0; i
< NCH(n
); i
+= 2)
1302 com_subscript(c
, CHILD(n
, i
));
1303 /* Put multiple subscripts into a tuple */
1306 com_addoparg(c
, BUILD_TUPLE
, i
);
1309 if (assigning
== OP_APPLY
) {
1313 else if (assigning
== OP_ASSIGN
) {
1326 com_apply_trailer(c
, n
)
1327 struct compiling
*c
;
1331 switch (TYPE(CHILD(n
, 0))) {
1333 com_call_function(c
, CHILD(n
, 1));
1336 com_select_member(c
, CHILD(n
, 1));
1339 com_subscriptlist(c
, CHILD(n
, 1), OP_APPLY
);
1342 com_error(c
, PyExc_SystemError
,
1343 "com_apply_trailer: unknown trailer type");
1349 struct compiling
*c
;
1354 com_atom(c
, CHILD(n
, 0));
1355 for (i
= 1; i
< NCH(n
); i
++) {
1356 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
1357 com_factor(c
, CHILD(n
, i
+1));
1358 com_addbyte(c
, BINARY_POWER
);
1363 com_apply_trailer(c
, CHILD(n
, i
));
1369 struct compiling
*c
;
1373 if (TYPE(CHILD(n
, 0)) == PLUS
) {
1374 com_factor(c
, CHILD(n
, 1));
1375 com_addbyte(c
, UNARY_POSITIVE
);
1377 else if (TYPE(CHILD(n
, 0)) == MINUS
) {
1378 com_factor(c
, CHILD(n
, 1));
1379 com_addbyte(c
, UNARY_NEGATIVE
);
1381 else if (TYPE(CHILD(n
, 0)) == TILDE
) {
1382 com_factor(c
, CHILD(n
, 1));
1383 com_addbyte(c
, UNARY_INVERT
);
1386 com_power(c
, CHILD(n
, 0));
1392 struct compiling
*c
;
1398 com_factor(c
, CHILD(n
, 0));
1399 for (i
= 2; i
< NCH(n
); i
+= 2) {
1400 com_factor(c
, CHILD(n
, i
));
1401 switch (TYPE(CHILD(n
, i
-1))) {
1403 op
= BINARY_MULTIPLY
;
1412 com_error(c
, PyExc_SystemError
,
1413 "com_term: operator not *, / or %");
1422 com_arith_expr(c
, n
)
1423 struct compiling
*c
;
1429 com_term(c
, CHILD(n
, 0));
1430 for (i
= 2; i
< NCH(n
); i
+= 2) {
1431 com_term(c
, CHILD(n
, i
));
1432 switch (TYPE(CHILD(n
, i
-1))) {
1437 op
= BINARY_SUBTRACT
;
1440 com_error(c
, PyExc_SystemError
,
1441 "com_arith_expr: operator not + or -");
1450 com_shift_expr(c
, n
)
1451 struct compiling
*c
;
1457 com_arith_expr(c
, CHILD(n
, 0));
1458 for (i
= 2; i
< NCH(n
); i
+= 2) {
1459 com_arith_expr(c
, CHILD(n
, i
));
1460 switch (TYPE(CHILD(n
, i
-1))) {
1468 com_error(c
, PyExc_SystemError
,
1469 "com_shift_expr: operator not << or >>");
1479 struct compiling
*c
;
1485 com_shift_expr(c
, CHILD(n
, 0));
1486 for (i
= 2; i
< NCH(n
); i
+= 2) {
1487 com_shift_expr(c
, CHILD(n
, i
));
1488 if (TYPE(CHILD(n
, i
-1)) == AMPER
) {
1492 com_error(c
, PyExc_SystemError
,
1493 "com_and_expr: operator not &");
1503 struct compiling
*c
;
1509 com_and_expr(c
, CHILD(n
, 0));
1510 for (i
= 2; i
< NCH(n
); i
+= 2) {
1511 com_and_expr(c
, CHILD(n
, i
));
1512 if (TYPE(CHILD(n
, i
-1)) == CIRCUMFLEX
) {
1516 com_error(c
, PyExc_SystemError
,
1517 "com_xor_expr: operator not ^");
1527 struct compiling
*c
;
1533 com_xor_expr(c
, CHILD(n
, 0));
1534 for (i
= 2; i
< NCH(n
); i
+= 2) {
1535 com_xor_expr(c
, CHILD(n
, i
));
1536 if (TYPE(CHILD(n
, i
-1)) == VBAR
) {
1540 com_error(c
, PyExc_SystemError
,
1541 "com_expr: expr operator not |");
1554 /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
1555 | 'in' | 'not' 'in' | 'is' | 'is' not' */
1559 case LESS
: return LT
;
1560 case GREATER
: return GT
;
1561 case EQEQUAL
: /* == */
1562 case EQUAL
: return EQ
;
1563 case LESSEQUAL
: return LE
;
1564 case GREATEREQUAL
: return GE
;
1565 case NOTEQUAL
: return NE
; /* <> or != */
1566 case NAME
: if (strcmp(STR(n
), "in") == 0) return IN
;
1567 if (strcmp(STR(n
), "is") == 0) return IS
;
1570 else if (NCH(n
) == 2) {
1571 switch (TYPE(CHILD(n
, 0))) {
1572 case NAME
: if (strcmp(STR(CHILD(n
, 1)), "in") == 0)
1574 if (strcmp(STR(CHILD(n
, 0)), "is") == 0)
1582 com_comparison(c
, n
)
1583 struct compiling
*c
;
1589 REQ(n
, comparison
); /* comparison: expr (comp_op expr)* */
1590 com_expr(c
, CHILD(n
, 0));
1594 /****************************************************************
1595 The following code is generated for all but the last
1596 comparison in a chain:
1598 label: on stack: opcode: jump to:
1604 b, 0-or-1 JUMP_IF_FALSE L1
1608 We are now ready to repeat this sequence for the next
1609 comparison in the chain.
1611 For the last we generate:
1617 If there were any jumps to L1 (i.e., there was more than one
1618 comparison), we generate:
1620 0-or-1 JUMP_FORWARD L2
1625 ****************************************************************/
1629 for (i
= 2; i
< NCH(n
); i
+= 2) {
1630 com_expr(c
, CHILD(n
, i
));
1632 com_addbyte(c
, DUP_TOP
);
1634 com_addbyte(c
, ROT_THREE
);
1636 op
= cmp_type(CHILD(n
, i
-1));
1638 com_error(c
, PyExc_SystemError
,
1639 "com_comparison: unknown comparison op");
1641 com_addoparg(c
, COMPARE_OP
, op
);
1644 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
1645 com_addbyte(c
, POP_TOP
);
1652 com_addfwref(c
, JUMP_FORWARD
, &anchor2
);
1653 com_backpatch(c
, anchor
);
1654 com_addbyte(c
, ROT_TWO
);
1655 com_addbyte(c
, POP_TOP
);
1656 com_backpatch(c
, anchor2
);
1662 struct compiling
*c
;
1665 REQ(n
, not_test
); /* 'not' not_test | comparison */
1667 com_comparison(c
, CHILD(n
, 0));
1670 com_not_test(c
, CHILD(n
, 1));
1671 com_addbyte(c
, UNARY_NOT
);
1677 struct compiling
*c
;
1682 REQ(n
, and_test
); /* not_test ('and' not_test)* */
1686 com_not_test(c
, CHILD(n
, i
));
1687 if ((i
+= 2) >= NCH(n
))
1689 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
1690 com_addbyte(c
, POP_TOP
);
1694 com_backpatch(c
, anchor
);
1699 struct compiling
*c
;
1702 REQ(n
, test
); /* and_test ('or' and_test)* | lambdef */
1703 if (NCH(n
) == 1 && TYPE(CHILD(n
, 0)) == lambdef
) {
1706 int ndefs
= com_argdefs(c
, CHILD(n
, 0));
1707 v
= (PyObject
*) icompile(CHILD(n
, 0), c
);
1713 i
= com_addconst(c
, v
);
1716 com_addoparg(c
, LOAD_CONST
, i
);
1718 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
1725 com_and_test(c
, CHILD(n
, i
));
1726 if ((i
+= 2) >= NCH(n
))
1728 com_addfwref(c
, JUMP_IF_TRUE
, &anchor
);
1729 com_addbyte(c
, POP_TOP
);
1733 com_backpatch(c
, anchor
);
1738 com_list(c
, n
, toplevel
)
1739 struct compiling
*c
;
1741 int toplevel
; /* If nonzero, *always* build a tuple */
1743 /* exprlist: expr (',' expr)* [',']; likewise for testlist */
1744 if (NCH(n
) == 1 && !toplevel
) {
1745 com_node(c
, CHILD(n
, 0));
1750 len
= (NCH(n
) + 1) / 2;
1751 for (i
= 0; i
< NCH(n
); i
+= 2)
1752 com_node(c
, CHILD(n
, i
));
1753 com_addoparg(c
, BUILD_TUPLE
, len
);
1759 /* Begin of assignment compilation */
1761 static void com_assign_name
Py_PROTO((struct compiling
*, node
*, int));
1762 static void com_assign
Py_PROTO((struct compiling
*, node
*, int));
1765 com_assign_attr(c
, n
, assigning
)
1766 struct compiling
*c
;
1770 com_addopname(c
, assigning
? STORE_ATTR
: DELETE_ATTR
, n
);
1771 com_pop(c
, assigning
? 2 : 1);
1775 com_assign_trailer(c
, n
, assigning
)
1776 struct compiling
*c
;
1781 switch (TYPE(CHILD(n
, 0))) {
1782 case LPAR
: /* '(' [exprlist] ')' */
1783 com_error(c
, PyExc_SyntaxError
,
1784 "can't assign to function call");
1786 case DOT
: /* '.' NAME */
1787 com_assign_attr(c
, CHILD(n
, 1), assigning
);
1789 case LSQB
: /* '[' subscriptlist ']' */
1790 com_subscriptlist(c
, CHILD(n
, 1), assigning
);
1793 com_error(c
, PyExc_SystemError
, "unknown trailer type");
1798 com_assign_tuple(c
, n
, assigning
)
1799 struct compiling
*c
;
1804 if (TYPE(n
) != testlist
)
1808 com_addoparg(c
, UNPACK_TUPLE
, i
);
1811 for (i
= 0; i
< NCH(n
); i
+= 2)
1812 com_assign(c
, CHILD(n
, i
), assigning
);
1816 com_assign_list(c
, n
, assigning
)
1817 struct compiling
*c
;
1824 com_addoparg(c
, UNPACK_LIST
, i
);
1827 for (i
= 0; i
< NCH(n
); i
+= 2)
1828 com_assign(c
, CHILD(n
, i
), assigning
);
1832 com_assign_name(c
, n
, assigning
)
1833 struct compiling
*c
;
1838 com_addopname(c
, assigning
? STORE_NAME
: DELETE_NAME
, n
);
1844 com_assign(c
, n
, assigning
)
1845 struct compiling
*c
;
1849 /* Loop to avoid trivial recursion */
1856 com_assign_tuple(c
, n
, assigning
);
1874 com_error(c
, PyExc_SyntaxError
,
1875 "can't assign to operator");
1881 case power
: /* atom trailer* ('**' power)* */
1882 /* ('+'|'-'|'~') factor | atom trailer* */
1883 if (TYPE(CHILD(n
, 0)) != atom
) {
1884 com_error(c
, PyExc_SyntaxError
,
1885 "can't assign to operator");
1888 if (NCH(n
) > 1) { /* trailer or exponent present */
1890 com_node(c
, CHILD(n
, 0));
1891 for (i
= 1; i
+1 < NCH(n
); i
++) {
1892 if (TYPE(CHILD(n
, i
)) == DOUBLESTAR
) {
1893 com_error(c
, PyExc_SyntaxError
,
1894 "can't assign to operator");
1897 com_apply_trailer(c
, CHILD(n
, i
));
1898 } /* NB i is still alive */
1899 com_assign_trailer(c
,
1900 CHILD(n
, i
), assigning
);
1907 switch (TYPE(CHILD(n
, 0))) {
1910 if (TYPE(n
) == RPAR
) {
1911 /* XXX Should allow () = () ??? */
1912 com_error(c
, PyExc_SyntaxError
,
1913 "can't assign to ()");
1919 if (TYPE(n
) == RSQB
) {
1920 com_error(c
, PyExc_SyntaxError
,
1921 "can't assign to []");
1924 com_assign_list(c
, n
, assigning
);
1927 com_assign_name(c
, CHILD(n
, 0), assigning
);
1930 com_error(c
, PyExc_SyntaxError
,
1931 "can't assign to literal");
1937 com_error(c
, PyExc_SyntaxError
,
1938 "can't assign to lambda");
1942 /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
1943 com_error(c
, PyExc_SystemError
,
1944 "com_assign: bad node");
1951 /* Forward */ static node
*get_rawdocstring
Py_PROTO((node
*));
1955 struct compiling
*c
;
1958 REQ(n
, expr_stmt
); /* testlist ('=' testlist)* */
1959 /* Forget it if we have just a doc string here */
1960 if (!c
->c_interactive
&& NCH(n
) == 1 && get_rawdocstring(n
) != NULL
)
1962 com_node(c
, CHILD(n
, NCH(n
)-1));
1964 if (c
->c_interactive
)
1965 com_addbyte(c
, PRINT_EXPR
);
1967 com_addbyte(c
, POP_TOP
);
1972 for (i
= 0; i
< NCH(n
)-2; i
+=2) {
1973 if (i
+2 < NCH(n
)-2) {
1974 com_addbyte(c
, DUP_TOP
);
1977 com_assign(c
, CHILD(n
, i
), OP_ASSIGN
);
1983 com_assert_stmt(c
, n
)
1984 struct compiling
*c
;
1989 REQ(n
, assert_stmt
); /* 'assert' test [',' test] */
1990 /* Generate code like for
1994 raise AssertionError [, <message>]
1996 where <message> is the second test, if present.
1998 if (Py_OptimizeFlag
)
2000 com_addopnamestr(c
, LOAD_GLOBAL
, "__debug__");
2002 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
2003 com_addbyte(c
, POP_TOP
);
2005 com_node(c
, CHILD(n
, 1));
2006 com_addfwref(c
, JUMP_IF_TRUE
, &b
);
2007 com_addbyte(c
, POP_TOP
);
2009 /* Raise that exception! */
2010 com_addopnamestr(c
, LOAD_GLOBAL
, "AssertionError");
2012 i
= NCH(n
)/2; /* Either 2 or 4 */
2014 com_node(c
, CHILD(n
, 3));
2015 com_addoparg(c
, RAISE_VARARGS
, i
);
2017 /* The interpreter does not fall through */
2018 /* All jumps converge here */
2019 com_backpatch(c
, a
);
2020 com_backpatch(c
, b
);
2021 com_addbyte(c
, POP_TOP
);
2025 com_print_stmt(c
, n
)
2026 struct compiling
*c
;
2030 REQ(n
, print_stmt
); /* 'print' (test ',')* [test] */
2031 for (i
= 1; i
< NCH(n
); i
+= 2) {
2032 com_node(c
, CHILD(n
, i
));
2033 com_addbyte(c
, PRINT_ITEM
);
2036 if (TYPE(CHILD(n
, NCH(n
)-1)) != COMMA
)
2037 com_addbyte(c
, PRINT_NEWLINE
);
2038 /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
2042 com_return_stmt(c
, n
)
2043 struct compiling
*c
;
2046 REQ(n
, return_stmt
); /* 'return' [testlist] */
2047 if (!c
->c_infunction
) {
2048 com_error(c
, PyExc_SyntaxError
, "'return' outside function");
2051 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2055 com_node(c
, CHILD(n
, 1));
2056 com_addbyte(c
, RETURN_VALUE
);
2061 com_raise_stmt(c
, n
)
2062 struct compiling
*c
;
2066 REQ(n
, raise_stmt
); /* 'raise' [test [',' test [',' test]]] */
2068 com_node(c
, CHILD(n
, 1));
2070 com_node(c
, CHILD(n
, 3));
2072 com_node(c
, CHILD(n
, 5));
2076 com_addoparg(c
, RAISE_VARARGS
, i
);
2081 com_import_stmt(c
, n
)
2082 struct compiling
*c
;
2086 REQ(n
, import_stmt
);
2087 /* 'import' dotted_name (',' dotted_name)* |
2088 'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
2089 if (STR(CHILD(n
, 0))[0] == 'f') {
2090 /* 'from' dotted_name 'import' ... */
2091 REQ(CHILD(n
, 1), dotted_name
);
2092 com_addopname(c
, IMPORT_NAME
, CHILD(n
, 1));
2094 for (i
= 3; i
< NCH(n
); i
+= 2)
2095 com_addopname(c
, IMPORT_FROM
, CHILD(n
, i
));
2096 com_addbyte(c
, POP_TOP
);
2101 for (i
= 1; i
< NCH(n
); i
+= 2) {
2102 REQ(CHILD(n
, i
), dotted_name
);
2103 com_addopname(c
, IMPORT_NAME
, CHILD(n
, i
));
2105 com_addopname(c
, STORE_NAME
, CHILD(CHILD(n
, i
), 0));
2112 com_global_stmt(c
, n
)
2113 struct compiling
*c
;
2117 REQ(n
, global_stmt
);
2118 /* 'global' NAME (',' NAME)* */
2119 for (i
= 1; i
< NCH(n
); i
+= 2) {
2120 char *s
= STR(CHILD(n
, i
));
2121 #ifdef PRIVATE_NAME_MANGLING
2123 if (s
!= NULL
&& s
[0] == '_' && s
[1] == '_' &&
2124 c
->c_private
!= NULL
&&
2125 com_mangle(c
, s
, buffer
, (int)sizeof(buffer
)))
2128 if (PyDict_GetItemString(c
->c_locals
, s
) != NULL
) {
2129 com_error(c
, PyExc_SyntaxError
,
2130 "name is local and global");
2132 else if (PyDict_SetItemString(c
->c_globals
, s
, Py_None
) != 0)
2138 com_newlocal_o(c
, nameval
)
2139 struct compiling
*c
;
2144 if (PyList_Size(c
->c_varnames
) != c
->c_nlocals
) {
2145 /* This is usually caused by an error on a previous call */
2146 if (c
->c_errors
== 0) {
2147 com_error(c
, PyExc_SystemError
,
2148 "mixed up var name/index");
2152 ival
= PyInt_FromLong(i
= c
->c_nlocals
++);
2155 else if (PyDict_SetItem(c
->c_locals
, nameval
, ival
) != 0)
2157 else if (PyList_Append(c
->c_varnames
, nameval
) != 0)
2164 com_addlocal_o(c
, nameval
)
2165 struct compiling
*c
;
2168 PyObject
*ival
= PyDict_GetItem(c
->c_locals
, nameval
);
2170 return PyInt_AsLong(ival
);
2171 return com_newlocal_o(c
, nameval
);
2175 com_newlocal(c
, name
)
2176 struct compiling
*c
;
2179 PyObject
*nameval
= PyString_InternFromString(name
);
2181 if (nameval
== NULL
) {
2185 i
= com_newlocal_o(c
, nameval
);
2192 struct compiling
*c
;
2196 /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
2197 com_node(c
, CHILD(n
, 1));
2199 com_node(c
, CHILD(n
, 3));
2201 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2205 com_node(c
, CHILD(n
, 5));
2207 com_addbyte(c
, DUP_TOP
);
2210 com_addbyte(c
, EXEC_STMT
);
2215 is_constant_false(c
, n
)
2216 struct compiling
*c
;
2222 /* Label to avoid tail recursion */
2233 for (i
= 0; i
< NCH(n
); i
++) {
2234 node
*ch
= CHILD(n
, i
);
2235 if (TYPE(ch
) == stmt
) {
2270 if (Py_OptimizeFlag
&& strcmp(STR(n
), "__debug__") == 0)
2275 v
= parsenumber(c
, STR(n
));
2280 i
= PyObject_IsTrue(v
);
2285 v
= parsestr(STR(n
));
2290 i
= PyObject_IsTrue(v
);
2300 struct compiling
*c
;
2306 /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
2307 for (i
= 0; i
+3 < NCH(n
); i
+=4) {
2309 node
*ch
= CHILD(n
, i
+1);
2310 if (is_constant_false(c
, ch
))
2313 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
2315 com_addfwref(c
, JUMP_IF_FALSE
, &a
);
2316 com_addbyte(c
, POP_TOP
);
2318 com_node(c
, CHILD(n
, i
+3));
2319 com_addfwref(c
, JUMP_FORWARD
, &anchor
);
2320 com_backpatch(c
, a
);
2321 /* We jump here with an extra entry which we now pop */
2322 com_addbyte(c
, POP_TOP
);
2325 com_node(c
, CHILD(n
, i
+2));
2327 com_backpatch(c
, anchor
);
2331 com_while_stmt(c
, n
)
2332 struct compiling
*c
;
2335 int break_anchor
= 0;
2337 int save_begin
= c
->c_begin
;
2338 REQ(n
, while_stmt
); /* 'while' test ':' suite ['else' ':' suite] */
2339 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
2340 block_push(c
, SETUP_LOOP
);
2341 c
->c_begin
= c
->c_nexti
;
2342 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
2343 com_node(c
, CHILD(n
, 1));
2344 com_addfwref(c
, JUMP_IF_FALSE
, &anchor
);
2345 com_addbyte(c
, POP_TOP
);
2348 com_node(c
, CHILD(n
, 3));
2350 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
2351 c
->c_begin
= save_begin
;
2352 com_backpatch(c
, anchor
);
2353 /* We jump here with one entry more on the stack */
2354 com_addbyte(c
, POP_TOP
);
2355 com_addbyte(c
, POP_BLOCK
);
2356 block_pop(c
, SETUP_LOOP
);
2358 com_node(c
, CHILD(n
, 6));
2359 com_backpatch(c
, break_anchor
);
2364 struct compiling
*c
;
2368 int break_anchor
= 0;
2370 int save_begin
= c
->c_begin
;
2372 /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
2373 com_addfwref(c
, SETUP_LOOP
, &break_anchor
);
2374 block_push(c
, SETUP_LOOP
);
2375 com_node(c
, CHILD(n
, 3));
2376 v
= PyInt_FromLong(0L);
2379 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, v
));
2382 c
->c_begin
= c
->c_nexti
;
2383 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
2384 com_addfwref(c
, FOR_LOOP
, &anchor
);
2386 com_assign(c
, CHILD(n
, 1), OP_ASSIGN
);
2388 com_node(c
, CHILD(n
, 5));
2390 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
2391 c
->c_begin
= save_begin
;
2392 com_backpatch(c
, anchor
);
2393 com_pop(c
, 2); /* FOR_LOOP has popped these */
2394 com_addbyte(c
, POP_BLOCK
);
2395 block_pop(c
, SETUP_LOOP
);
2397 com_node(c
, CHILD(n
, 8));
2398 com_backpatch(c
, break_anchor
);
2401 /* Code generated for "try: S finally: Sf" is as follows:
2410 The special instructions use the block stack. Each block
2411 stack entry contains the instruction that created it (here
2412 SETUP_FINALLY), the level of the value stack at the time the
2413 block stack entry was created, and a label (here L).
2416 Pushes the current value stack level and the label
2417 onto the block stack.
2419 Pops en entry from the block stack, and pops the value
2420 stack until its level is the same as indicated on the
2421 block stack. (The label is ignored.)
2423 Pops a variable number of entries from the *value* stack
2424 and re-raises the exception they specify. The number of
2425 entries popped depends on the (pseudo) exception type.
2427 The block stack is unwound when an exception is raised:
2428 when a SETUP_FINALLY entry is found, the exception is pushed
2429 onto the value stack (and the exception condition is cleared),
2430 and the interpreter jumps to the label gotten from the block
2433 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2434 (The contents of the value stack is shown in [], with the top
2435 at the right; 'tb' is trace-back info, 'val' the exception's
2436 associated value, and 'exc' the exception.)
2438 Value stack Label Instruction Argument
2444 [tb, val, exc] L1: DUP )
2445 [tb, val, exc, exc] <evaluate E1> )
2446 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2447 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2448 [tb, val, exc, 1] POP )
2450 [tb, val] <assign to V1> (or POP if no V1)
2455 [tb, val, exc, 0] L2: POP
2457 .............................etc.......................
2459 [tb, val, exc, 0] Ln+1: POP
2460 [tb, val, exc] END_FINALLY # re-raise exception
2462 [] L0: <next statement>
2464 Of course, parts are not generated if Vi or Ei is not present.
2468 com_try_except(c
, n
)
2469 struct compiling
*c
;
2472 int except_anchor
= 0;
2474 int else_anchor
= 0;
2478 com_addfwref(c
, SETUP_EXCEPT
, &except_anchor
);
2479 block_push(c
, SETUP_EXCEPT
);
2480 com_node(c
, CHILD(n
, 2));
2481 com_addbyte(c
, POP_BLOCK
);
2482 block_pop(c
, SETUP_EXCEPT
);
2483 com_addfwref(c
, JUMP_FORWARD
, &else_anchor
);
2484 com_backpatch(c
, except_anchor
);
2486 i
< NCH(n
) && TYPE(ch
= CHILD(n
, i
)) == except_clause
;
2488 /* except_clause: 'except' [expr [',' var]] */
2489 if (except_anchor
== 0) {
2490 com_error(c
, PyExc_SyntaxError
,
2491 "default 'except:' must be last");
2495 com_push(c
, 3); /* tb, val, exc pushed by exception */
2496 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
2498 com_addbyte(c
, DUP_TOP
);
2500 com_node(c
, CHILD(ch
, 1));
2501 com_addoparg(c
, COMPARE_OP
, EXC_MATCH
);
2503 com_addfwref(c
, JUMP_IF_FALSE
, &except_anchor
);
2504 com_addbyte(c
, POP_TOP
);
2507 com_addbyte(c
, POP_TOP
);
2510 com_assign(c
, CHILD(ch
, 3), OP_ASSIGN
);
2512 com_addbyte(c
, POP_TOP
);
2515 com_addbyte(c
, POP_TOP
);
2517 com_node(c
, CHILD(n
, i
+2));
2518 com_addfwref(c
, JUMP_FORWARD
, &end_anchor
);
2519 if (except_anchor
) {
2520 com_backpatch(c
, except_anchor
);
2521 /* We come in with [tb, val, exc, 0] on the
2522 stack; one pop and it's the same as
2523 expected at the start of the loop */
2524 com_addbyte(c
, POP_TOP
);
2527 /* We actually come in here with [tb, val, exc] but the
2528 END_FINALLY will zap those and jump around.
2529 The c_stacklevel does not reflect them so we need not pop
2531 com_addbyte(c
, END_FINALLY
);
2532 com_backpatch(c
, else_anchor
);
2534 com_node(c
, CHILD(n
, i
+2));
2535 com_backpatch(c
, end_anchor
);
2539 com_try_finally(c
, n
)
2540 struct compiling
*c
;
2543 int finally_anchor
= 0;
2546 com_addfwref(c
, SETUP_FINALLY
, &finally_anchor
);
2547 block_push(c
, SETUP_FINALLY
);
2548 com_node(c
, CHILD(n
, 2));
2549 com_addbyte(c
, POP_BLOCK
);
2550 block_pop(c
, SETUP_FINALLY
);
2551 block_push(c
, END_FINALLY
);
2552 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
2553 /* While the generated code pushes only one item,
2554 the try-finally handling can enter here with
2555 up to three items. OK, here are the details:
2556 3 for an exception, 2 for RETURN, 1 for BREAK. */
2558 com_backpatch(c
, finally_anchor
);
2559 ch
= CHILD(n
, NCH(n
)-1);
2560 com_addoparg(c
, SET_LINENO
, ch
->n_lineno
);
2562 com_addbyte(c
, END_FINALLY
);
2563 block_pop(c
, END_FINALLY
);
2564 com_pop(c
, 3); /* Matches the com_push above */
2569 struct compiling
*c
;
2573 /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
2574 | 'try' ':' suite 'finally' ':' suite */
2575 if (TYPE(CHILD(n
, 3)) != except_clause
)
2576 com_try_finally(c
, n
);
2578 com_try_except(c
, n
);
2587 /* Label to avoid tail recursion */
2598 for (i
= 0; i
< NCH(n
); i
++) {
2599 node
*ch
= CHILD(n
, i
);
2600 if (TYPE(ch
) == stmt
) {
2634 if (TYPE(CHILD(n
, 0)) == STRING
)
2646 n
= get_rawdocstring(n
);
2649 return parsestrplus(n
);
2654 struct compiling
*c
;
2658 /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
2660 com_node(c
, CHILD(n
, 0));
2664 for (i
= 0; i
< NCH(n
); i
++) {
2665 node
*ch
= CHILD(n
, i
);
2666 if (TYPE(ch
) == stmt
)
2674 com_continue_stmt(c
, n
)
2675 struct compiling
*c
;
2676 node
*n
; /* Not used, but passed for consistency */
2678 int i
= c
->c_nblocks
;
2679 if (i
-- > 0 && c
->c_block
[i
] == SETUP_LOOP
) {
2680 com_addoparg(c
, JUMP_ABSOLUTE
, c
->c_begin
);
2683 com_error(c
, PyExc_SyntaxError
,
2684 "'continue' not properly in loop");
2686 /* XXX Could allow it inside a 'finally' clause
2687 XXX if we could pop the exception still on the stack */
2692 struct compiling
*c
;
2695 int i
, nch
, nargs
, ndefs
;
2696 if (TYPE(n
) == lambdef
) {
2697 /* lambdef: 'lambda' [varargslist] ':' test */
2701 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ... */
2703 REQ(n
, parameters
); /* parameters: '(' [varargslist] ')' */
2706 if (TYPE(n
) != varargslist
)
2709 (fpdef ['=' test] ',')* '*' ....... |
2710 fpdef ['=' test] (',' fpdef ['=' test])* [','] */
2714 for (i
= 0; i
< nch
; i
++) {
2716 if (TYPE(CHILD(n
, i
)) == STAR
||
2717 TYPE(CHILD(n
, i
)) == DOUBLESTAR
)
2722 t
= RPAR
; /* Anything except EQUAL or COMMA */
2724 t
= TYPE(CHILD(n
, i
));
2728 com_node(c
, CHILD(n
, i
));
2732 t
= TYPE(CHILD(n
, i
));
2735 /* Treat "(a=1, b)" as an error */
2737 com_error(c
, PyExc_SyntaxError
,
2738 "non-default argument follows default argument");
2748 struct compiling
*c
;
2752 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
2753 v
= (PyObject
*)icompile(n
, c
);
2757 int i
= com_addconst(c
, v
);
2758 int ndefs
= com_argdefs(c
, n
);
2759 com_addoparg(c
, LOAD_CONST
, i
);
2761 com_addoparg(c
, MAKE_FUNCTION
, ndefs
);
2763 com_addopname(c
, STORE_NAME
, CHILD(n
, 1));
2771 struct compiling
*c
;
2776 /* testlist: test (',' test)* [','] */
2777 for (i
= 0; i
< NCH(n
); i
+= 2)
2778 com_node(c
, CHILD(n
, i
));
2780 com_addoparg(c
, BUILD_TUPLE
, i
);
2786 struct compiling
*c
;
2792 /* classdef: class NAME ['(' testlist ')'] ':' suite */
2793 if ((v
= PyString_InternFromString(STR(CHILD(n
, 1)))) == NULL
) {
2797 /* Push the class name on the stack */
2798 i
= com_addconst(c
, v
);
2799 com_addoparg(c
, LOAD_CONST
, i
);
2802 /* Push the tuple of base classes on the stack */
2803 if (TYPE(CHILD(n
, 2)) != LPAR
) {
2804 com_addoparg(c
, BUILD_TUPLE
, 0);
2808 com_bases(c
, CHILD(n
, 3));
2809 v
= (PyObject
*)icompile(n
, c
);
2813 i
= com_addconst(c
, v
);
2814 com_addoparg(c
, LOAD_CONST
, i
);
2816 com_addoparg(c
, MAKE_FUNCTION
, 0);
2817 com_addoparg(c
, CALL_FUNCTION
, 0);
2818 com_addbyte(c
, BUILD_CLASS
);
2820 com_addopname(c
, STORE_NAME
, CHILD(n
, 1));
2827 struct compiling
*c
;
2832 /* Definition nodes */
2841 /* Trivial parse tree nodes */
2846 com_node(c
, CHILD(n
, 0));
2850 /* small_stmt (';' small_stmt)* [';'] NEWLINE */
2851 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
2854 for (i
= 0; i
< NCH(n
)-1; i
+= 2)
2855 com_node(c
, CHILD(n
, i
));
2860 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
2861 com_node(c
, CHILD(n
, 0));
2864 /* Statement nodes */
2867 com_expr_stmt(c
, n
);
2870 com_print_stmt(c
, n
);
2872 case del_stmt
: /* 'del' exprlist */
2873 com_assign(c
, CHILD(n
, 1), OP_DELETE
);
2878 if (c
->c_loops
== 0) {
2879 com_error(c
, PyExc_SyntaxError
,
2880 "'break' outside loop");
2882 com_addbyte(c
, BREAK_LOOP
);
2885 com_continue_stmt(c
, n
);
2888 com_return_stmt(c
, n
);
2891 com_raise_stmt(c
, n
);
2894 com_import_stmt(c
, n
);
2897 com_global_stmt(c
, n
);
2900 com_exec_stmt(c
, n
);
2903 com_assert_stmt(c
, n
);
2909 com_while_stmt(c
, n
);
2921 /* Expression nodes */
2936 com_comparison(c
, n
);
2951 com_shift_expr(c
, n
);
2954 com_arith_expr(c
, n
);
2970 /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
2971 com_error(c
, PyExc_SystemError
,
2972 "com_node: unexpected node type");
2976 static void com_fplist
Py_PROTO((struct compiling
*, node
*));
2980 struct compiling
*c
;
2983 REQ(n
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
2984 if (TYPE(CHILD(n
, 0)) == LPAR
)
2985 com_fplist(c
, CHILD(n
, 1));
2987 com_addoparg(c
, STORE_FAST
, com_newlocal(c
, STR(CHILD(n
, 0))));
2994 struct compiling
*c
;
2997 REQ(n
, fplist
); /* fplist: fpdef (',' fpdef)* [','] */
2999 com_fpdef(c
, CHILD(n
, 0));
3002 int i
= (NCH(n
)+1)/2;
3003 com_addoparg(c
, UNPACK_TUPLE
, i
);
3005 for (i
= 0; i
< NCH(n
); i
+= 2)
3006 com_fpdef(c
, CHILD(n
, i
));
3012 struct compiling
*c
;
3018 REQ(n
, varargslist
);
3020 (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
3022 /* Enter all arguments in table of locals */
3023 for (i
= 0; i
< nch
; i
++) {
3024 node
*ch
= CHILD(n
, i
);
3027 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
3029 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3031 if (TYPE(fp
) == NAME
)
3035 sprintf(nbuf
, ".%d", i
);
3038 com_newlocal(c
, name
);
3043 if (TYPE(ch
) == EQUAL
)
3048 /* Handle *arguments */
3052 if (TYPE(ch
) != DOUBLESTAR
) {
3055 if (TYPE(ch
) == NAME
) {
3056 c
->c_flags
|= CO_VARARGS
;
3058 com_newlocal(c
, STR(ch
));
3062 /* Handle **keywords */
3066 if (TYPE(ch
) != DOUBLESTAR
) {
3075 c
->c_flags
|= CO_VARKEYWORDS
;
3076 com_newlocal(c
, STR(ch
));
3079 /* Generate code for complex arguments only after
3080 having counted the simple arguments */
3082 for (i
= 0; i
< nch
; i
++) {
3083 node
*ch
= CHILD(n
, i
);
3085 if (TYPE(ch
) == STAR
|| TYPE(ch
) == DOUBLESTAR
)
3087 REQ(ch
, fpdef
); /* fpdef: NAME | '(' fplist ')' */
3089 if (TYPE(fp
) != NAME
) {
3090 com_addoparg(c
, LOAD_FAST
, ilocal
);
3098 if (TYPE(ch
) == EQUAL
)
3107 com_file_input(c
, n
)
3108 struct compiling
*c
;
3113 REQ(n
, file_input
); /* (NEWLINE | stmt)* ENDMARKER */
3114 doc
= get_docstring(n
);
3116 int i
= com_addconst(c
, doc
);
3118 com_addoparg(c
, LOAD_CONST
, i
);
3120 com_addopnamestr(c
, STORE_NAME
, "__doc__");
3123 for (i
= 0; i
< NCH(n
); i
++) {
3124 node
*ch
= CHILD(n
, i
);
3125 if (TYPE(ch
) != ENDMARKER
&& TYPE(ch
) != NEWLINE
)
3130 /* Top-level compile-node interface */
3133 compile_funcdef(c
, n
)
3134 struct compiling
*c
;
3139 REQ(n
, funcdef
); /* funcdef: 'def' NAME parameters ':' suite */
3140 c
->c_name
= STR(CHILD(n
, 1));
3141 doc
= get_docstring(CHILD(n
, 4));
3143 (void) com_addconst(c
, doc
);
3147 (void) com_addconst(c
, Py_None
); /* No docstring */
3148 ch
= CHILD(n
, 2); /* parameters: '(' [varargslist] ')' */
3149 ch
= CHILD(ch
, 1); /* ')' | varargslist */
3150 if (TYPE(ch
) == varargslist
)
3152 c
->c_infunction
= 1;
3153 com_node(c
, CHILD(n
, 4));
3154 c
->c_infunction
= 0;
3155 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3157 com_addbyte(c
, RETURN_VALUE
);
3162 compile_lambdef(c
, n
)
3163 struct compiling
*c
;
3167 REQ(n
, lambdef
); /* lambdef: 'lambda' [varargslist] ':' test */
3168 c
->c_name
= "<lambda>";
3171 (void) com_addconst(c
, Py_None
); /* No docstring */
3172 if (TYPE(ch
) == varargslist
) {
3179 com_addbyte(c
, RETURN_VALUE
);
3184 compile_classdef(c
, n
)
3185 struct compiling
*c
;
3191 /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
3192 c
->c_name
= STR(CHILD(n
, 1));
3193 #ifdef PRIVATE_NAME_MANGLING
3194 c
->c_private
= c
->c_name
;
3196 ch
= CHILD(n
, NCH(n
)-1); /* The suite */
3197 doc
= get_docstring(ch
);
3199 int i
= com_addconst(c
, doc
);
3201 com_addoparg(c
, LOAD_CONST
, i
);
3203 com_addopnamestr(c
, STORE_NAME
, "__doc__");
3207 (void) com_addconst(c
, Py_None
);
3209 com_addbyte(c
, LOAD_LOCALS
);
3211 com_addbyte(c
, RETURN_VALUE
);
3217 struct compiling
*c
;
3220 com_addoparg(c
, SET_LINENO
, n
->n_lineno
);
3224 case single_input
: /* One interactive command */
3225 /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
3228 if (TYPE(n
) != NEWLINE
)
3230 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3232 com_addbyte(c
, RETURN_VALUE
);
3237 case file_input
: /* A whole file, or built-in function exec() */
3238 com_file_input(c
, n
);
3239 com_addoparg(c
, LOAD_CONST
, com_addconst(c
, Py_None
));
3241 com_addbyte(c
, RETURN_VALUE
);
3245 case eval_input
: /* Built-in function input() */
3246 com_node(c
, CHILD(n
, 0));
3247 com_addbyte(c
, RETURN_VALUE
);
3251 case lambdef
: /* anonymous function definition */
3252 compile_lambdef(c
, n
);
3255 case funcdef
: /* A function definition */
3256 compile_funcdef(c
, n
);
3259 case classdef
: /* A class definition */
3260 compile_classdef(c
, n
);
3264 /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
3265 com_error(c
, PyExc_SystemError
,
3266 "compile_node: unexpected node type");
3270 /* Optimization for local variables in functions (and *only* functions).
3272 This replaces all LOAD_NAME, STORE_NAME and DELETE_NAME
3273 instructions that refer to local variables with LOAD_FAST etc.
3274 The latter instructions are much faster because they don't need to
3275 look up the variable name in a dictionary.
3277 To find all local variables, we check all STORE_NAME, IMPORT_FROM
3278 and DELETE_NAME instructions. This yields all local variables,
3279 function definitions, class definitions and import statements.
3280 Argument names have already been entered into the list by the
3281 special processing for the argument list.
3283 All remaining LOAD_NAME instructions must refer to non-local (global
3284 or builtin) variables, so are replaced by LOAD_GLOBAL.
3286 There are two problems: 'from foo import *' and 'exec' may introduce
3287 local variables that we can't know while compiling. If this is the
3288 case, we can still optimize bona fide locals (since those
3289 statements will be surrounded by fast_2_locals() and
3290 locals_2_fast()), but we can't change LOAD_NAME to LOAD_GLOBAL.
3292 NB: this modifies the string object c->c_code! */
3296 struct compiling
*c
;
3298 unsigned char *next_instr
, *cur_instr
;
3302 PyObject
*error_type
, *error_value
, *error_traceback
;
3304 #define NEXTOP() (*next_instr++)
3305 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
3306 #define GETITEM(v, i) (PyList_GetItem((v), (i)))
3307 #define GETNAMEOBJ(i) (GETITEM(c->c_names, (i)))
3309 PyErr_Fetch(&error_type
, &error_value
, &error_traceback
);
3311 c
->c_flags
|= CO_OPTIMIZED
;
3313 next_instr
= (unsigned char *) PyString_AsString(c
->c_code
);
3316 if (opcode
== STOP_CODE
)
3318 if (HAS_ARG(opcode
))
3324 com_addlocal_o(c
, GETNAMEOBJ(oparg
));
3327 c
->c_flags
&= ~CO_OPTIMIZED
;
3332 if (PyDict_GetItemString(c
->c_locals
, "*") != NULL
)
3333 c
->c_flags
&= ~CO_OPTIMIZED
;
3335 next_instr
= (unsigned char *) PyString_AsString(c
->c_code
);
3337 cur_instr
= next_instr
;
3339 if (opcode
== STOP_CODE
)
3341 if (HAS_ARG(opcode
))
3343 if (opcode
== LOAD_NAME
||
3344 opcode
== STORE_NAME
||
3345 opcode
== DELETE_NAME
) {
3348 name
= GETNAMEOBJ(oparg
);
3349 v
= PyDict_GetItem(c
->c_locals
, name
);
3351 if (opcode
== LOAD_NAME
&&
3352 (c
->c_flags
&CO_OPTIMIZED
))
3353 cur_instr
[0] = LOAD_GLOBAL
;
3356 i
= PyInt_AsLong(v
);
3358 case LOAD_NAME
: cur_instr
[0] = LOAD_FAST
; break;
3359 case STORE_NAME
: cur_instr
[0] = STORE_FAST
; break;
3360 case DELETE_NAME
: cur_instr
[0] = DELETE_FAST
; break;
3362 cur_instr
[1] = i
& 0xff;
3363 cur_instr
[2] = (i
>>8) & 0xff;
3367 if (c
->c_errors
== 0)
3368 PyErr_Restore(error_type
, error_value
, error_traceback
);
3372 PyNode_Compile(n
, filename
)
3376 return jcompile(n
, filename
, NULL
);
3379 static PyCodeObject
*
3382 struct compiling
*base
;
3384 return jcompile(n
, base
->c_filename
, base
);
3387 static PyCodeObject
*
3388 jcompile(n
, filename
, base
)
3391 struct compiling
*base
;
3393 struct compiling sc
;
3395 if (!com_init(&sc
, filename
))
3397 #ifdef PRIVATE_NAME_MANGLING
3399 sc
.c_private
= base
->c_private
;
3401 sc
.c_private
= NULL
;
3403 compile_node(&sc
, n
);
3405 if ((TYPE(n
) == funcdef
|| TYPE(n
) == lambdef
) && sc
.c_errors
== 0) {
3407 sc
.c_flags
|= CO_NEWLOCALS
;
3409 else if (TYPE(n
) == classdef
)
3410 sc
.c_flags
|= CO_NEWLOCALS
;
3412 if (sc
.c_errors
== 0) {
3413 PyObject
*consts
, *names
, *varnames
, *filename
, *name
;
3414 consts
= PyList_AsTuple(sc
.c_consts
);
3415 names
= PyList_AsTuple(sc
.c_names
);
3416 varnames
= PyList_AsTuple(sc
.c_varnames
);
3417 filename
= PyString_InternFromString(sc
.c_filename
);
3418 name
= PyString_InternFromString(sc
.c_name
);
3419 if (!PyErr_Occurred())
3420 co
= PyCode_New(sc
.c_argcount
,
3434 Py_XDECREF(varnames
);
3435 Py_XDECREF(filename
);
3443 PyCode_Addr2Line(co
, addrq
)
3447 int size
= PyString_Size(co
->co_lnotab
) / 2;
3448 char *p
= PyString_AsString(co
->co_lnotab
);
3449 int line
= co
->co_firstlineno
;
3451 while (--size
>= 0) {