compile.c 50.2 KB
Newer Older
1
/***********************************************************
2 3
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

******************************************************************/

Guido van Rossum's avatar
Guido van Rossum committed
25 26
/* Compile an expression node to intermediate code */

Guido van Rossum's avatar
Guido van Rossum committed
27 28 29 30 31 32 33
/* XXX TO DO:
   XXX Compute maximum needed stack sizes while compiling
   XXX Generate simple jump for break/return outside 'try...finally'
*/

#include "allobjects.h"

Guido van Rossum's avatar
Guido van Rossum committed
34 35 36 37 38
#include "node.h"
#include "token.h"
#include "graminit.h"
#include "compile.h"
#include "opcode.h"
Guido van Rossum's avatar
Guido van Rossum committed
39 40 41
#include "structmember.h"

#include <ctype.h>
42
#include <errno.h>
43

Guido van Rossum's avatar
Guido van Rossum committed
44 45 46
#define OFF(x) offsetof(codeobject, x)

static struct memberlist code_memberlist[] = {
47 48 49 50
	{"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_filename",	T_OBJECT,	OFF(co_filename),	READONLY},
51
	{"co_name",	T_OBJECT,	OFF(co_name),		READONLY},
Guido van Rossum's avatar
Guido van Rossum committed
52 53 54 55 56 57 58 59 60 61
	{NULL}	/* Sentinel */
};

static object *
code_getattr(co, name)
	codeobject *co;
	char *name;
{
	return getmember((char *)co, code_memberlist, name);
}
Guido van Rossum's avatar
Guido van Rossum committed
62 63

static void
Guido van Rossum's avatar
Guido van Rossum committed
64 65
code_dealloc(co)
	codeobject *co;
Guido van Rossum's avatar
Guido van Rossum committed
66
{
Guido van Rossum's avatar
Guido van Rossum committed
67 68 69 70
	XDECREF(co->co_code);
	XDECREF(co->co_consts);
	XDECREF(co->co_names);
	XDECREF(co->co_filename);
71
	XDECREF(co->co_name);
Guido van Rossum's avatar
Guido van Rossum committed
72
	DEL(co);
Guido van Rossum's avatar
Guido van Rossum committed
73 74
}

75 76 77 78 79 80 81 82
static object *
code_repr(co)
	codeobject *co;
{
	char buf[500];
	int lineno = -1;
	char *p = GETSTRINGVALUE(co->co_code);
	char *filename = "???";
83
	char *name = "???";
84 85 86 87
	if (*p == SET_LINENO)
		lineno = (p[1] & 0xff) | ((p[2] & 0xff) << 8);
	if (co->co_filename && is_stringobject(co->co_filename))
		filename = getstringvalue(co->co_filename);
88 89 90 91
	if (co->co_name && is_stringobject(co->co_name))
		name = getstringvalue(co->co_name);
	sprintf(buf, "<code object %.100s at %lx, file \"%.300s\", line %d>",
		name, (long)co, filename, lineno);
92 93 94
	return newstringobject(buf);
}

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
static int
code_compare(co, cp)
	codeobject *co, *cp;
{
	int cmp;
	cmp = cmpobject((object *)co->co_code, (object *)cp->co_code);
	if (cmp) return cmp;
	cmp = cmpobject(co->co_consts, cp->co_consts);
	if (cmp) return cmp;
	cmp = cmpobject(co->co_names, cp->co_names);
	return cmp;
}

static long
code_hash(co)
	codeobject *co;
{
	long h, h1, h2, h3;
	h1 = hashobject((object *)co->co_code);
	if (h1 == -1) return -1;
	h2 = hashobject(co->co_consts);
	if (h2 == -1) return -1;
	h3 = hashobject(co->co_names);
	if (h3 == -1) return -1;
	h = h1 ^ h2 ^ h3;
	if (h == -1) h = -2;
	return h;
}

Guido van Rossum's avatar
Guido van Rossum committed
124 125 126 127 128 129 130 131
typeobject Codetype = {
	OB_HEAD_INIT(&Typetype)
	0,
	"code",
	sizeof(codeobject),
	0,
	code_dealloc,	/*tp_dealloc*/
	0,		/*tp_print*/
Guido van Rossum's avatar
Guido van Rossum committed
132
	code_getattr,	/*tp_getattr*/
Guido van Rossum's avatar
Guido van Rossum committed
133
	0,		/*tp_setattr*/
134
	code_compare,	/*tp_compare*/
135
	code_repr,	/*tp_repr*/
Guido van Rossum's avatar
Guido van Rossum committed
136 137 138
	0,		/*tp_as_number*/
	0,		/*tp_as_sequence*/
	0,		/*tp_as_mapping*/
139
	code_hash,	/*tp_hash*/
Guido van Rossum's avatar
Guido van Rossum committed
140 141
};

142
codeobject *
143
newcodeobject(code, consts, names, filename, name)
Guido van Rossum's avatar
Guido van Rossum committed
144 145 146
	object *code;
	object *consts;
	object *names;
147
	object *filename;
148
	object *name;
Guido van Rossum's avatar
Guido van Rossum committed
149 150 151 152 153 154
{
	codeobject *co;
	int i;
	/* Check argument types */
	if (code == NULL || !is_stringobject(code) ||
		consts == NULL || !is_listobject(consts) ||
155 156
		names == NULL || !is_listobject(names) ||
		name == NULL || !is_stringobject(name)) {
Guido van Rossum's avatar
Guido van Rossum committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
		err_badcall();
		return NULL;
	}
	/* Make sure the list of names contains only strings */
	for (i = getlistsize(names); --i >= 0; ) {
		object *v = getlistitem(names, i);
		if (v == NULL || !is_stringobject(v)) {
			err_badcall();
			return NULL;
		}
	}
	co = NEWOBJ(codeobject, &Codetype);
	if (co != NULL) {
		INCREF(code);
		co->co_code = (stringobject *)code;
		INCREF(consts);
		co->co_consts = consts;
		INCREF(names);
		co->co_names = names;
176 177
		INCREF(filename);
		co->co_filename = filename;
178 179
		INCREF(name);
		co->co_name = name;
Guido van Rossum's avatar
Guido van Rossum committed
180 181 182 183 184 185
	}
	return co;
}


/* Data structure used internally */
186 187 188

#define MAXBLOCKS 20 /* Max static block nesting within a function */

Guido van Rossum's avatar
Guido van Rossum committed
189 190 191 192
struct compiling {
	object *c_code;		/* string */
	object *c_consts;	/* list of objects */
	object *c_names;	/* list of strings (names) */
193
	object *c_globals;	/* dictionary */
Guido van Rossum's avatar
Guido van Rossum committed
194 195
	int c_nexti;		/* index into c_code */
	int c_errors;		/* counts errors occurred */
Guido van Rossum's avatar
Guido van Rossum committed
196
	int c_infunction;	/* set when compiling a function */
197
	int c_inlambda;		/* set when compiling an expression */
Guido van Rossum's avatar
Guido van Rossum committed
198
	int c_loops;		/* counts nested loops */
199 200 201
	int c_begin;		/* begin of current loop, for 'continue' */
	int c_block[MAXBLOCKS];	/* stack of block types */
	int c_nblocks;		/* current block stack level */
Guido van Rossum's avatar
Guido van Rossum committed
202
	char *c_filename;	/* filename of current node */
203
	char *c_name;		/* name of object (e.g. function) */
Guido van Rossum's avatar
Guido van Rossum committed
204 205
};

206 207 208 209 210 211 212 213 214

/* Interface to the block stack */

static void
block_push(c, type)
	struct compiling *c;
	int type;
{
	if (c->c_nblocks >= MAXBLOCKS) {
215
		err_setstr(SystemError, "too many statically nested blocks");
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
		c->c_errors++;
	}
	else {
		c->c_block[c->c_nblocks++] = type;
	}
}

static void
block_pop(c, type)
	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) {
		err_setstr(SystemError, "bad block pop");
		c->c_errors++;
	}
}


Guido van Rossum's avatar
Guido van Rossum committed
237
/* Prototypes */
238

239
static int com_init PROTO((struct compiling *, char *, int));
Guido van Rossum's avatar
Guido van Rossum committed
240 241 242 243 244 245 246 247 248 249 250 251
static void com_free PROTO((struct compiling *));
static void com_done PROTO((struct compiling *));
static void com_node PROTO((struct compiling *, struct _node *));
static void com_addbyte PROTO((struct compiling *, int));
static void com_addint PROTO((struct compiling *, int));
static void com_addoparg PROTO((struct compiling *, int, int));
static void com_addfwref PROTO((struct compiling *, int, int *));
static void com_backpatch PROTO((struct compiling *, int));
static int com_add PROTO((struct compiling *, object *, object *));
static int com_addconst PROTO((struct compiling *, object *));
static int com_addname PROTO((struct compiling *, object *));
static void com_addopname PROTO((struct compiling *, int, node *));
Guido van Rossum's avatar
Guido van Rossum committed
252
static void com_list PROTO((struct compiling *, node *, int));
Guido van Rossum's avatar
Guido van Rossum committed
253 254

static int
255
com_init(c, filename, inlambda)
Guido van Rossum's avatar
Guido van Rossum committed
256
	struct compiling *c;
Guido van Rossum's avatar
Guido van Rossum committed
257
	char *filename;
258
	int inlambda;
Guido van Rossum's avatar
Guido van Rossum committed
259
{
260
	if ((c->c_code = newsizedstringobject((char *)NULL, 1000)) == NULL)
Guido van Rossum's avatar
Guido van Rossum committed
261 262 263 264 265
		goto fail_3;
	if ((c->c_consts = newlistobject(0)) == NULL)
		goto fail_2;
	if ((c->c_names = newlistobject(0)) == NULL)
		goto fail_1;
266 267
	if ((c->c_globals = newdictobject()) == NULL)
		goto fail_0;
Guido van Rossum's avatar
Guido van Rossum committed
268 269
	c->c_nexti = 0;
	c->c_errors = 0;
Guido van Rossum's avatar
Guido van Rossum committed
270
	c->c_infunction = 0;
271
	c->c_inlambda = inlambda;
Guido van Rossum's avatar
Guido van Rossum committed
272
	c->c_loops = 0;
273 274
	c->c_begin = 0;
	c->c_nblocks = 0;
Guido van Rossum's avatar
Guido van Rossum committed
275
	c->c_filename = filename;
276
	c->c_name = "?";
Guido van Rossum's avatar
Guido van Rossum committed
277 278
	return 1;
	
279 280
  fail_0:
  	DECREF(c->c_names);
Guido van Rossum's avatar
Guido van Rossum committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
  fail_1:
	DECREF(c->c_consts);
  fail_2:
	DECREF(c->c_code);
  fail_3:
 	return 0;
}

static void
com_free(c)
	struct compiling *c;
{
	XDECREF(c->c_code);
	XDECREF(c->c_consts);
	XDECREF(c->c_names);
296
	XDECREF(c->c_globals);
Guido van Rossum's avatar
Guido van Rossum committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
}

static void
com_done(c)
	struct compiling *c;
{
	if (c->c_code != NULL)
		resizestring(&c->c_code, c->c_nexti);
}

static void
com_addbyte(c, byte)
	struct compiling *c;
	int byte;
{
	int len;
	if (byte < 0 || byte > 255) {
314
		/*
Guido van Rossum's avatar
Guido van Rossum committed
315 316
		fprintf(stderr, "XXX compiling bad byte: %d\n", byte);
		abort();
317
		*/
Guido van Rossum's avatar
Guido van Rossum committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
		err_setstr(SystemError, "com_addbyte: byte out of range");
		c->c_errors++;
	}
	if (c->c_code == NULL)
		return;
	len = getstringsize(c->c_code);
	if (c->c_nexti >= len) {
		if (resizestring(&c->c_code, len+1000) != 0) {
			c->c_errors++;
			return;
		}
	}
	getstringvalue(c->c_code)[c->c_nexti++] = byte;
}

static void
com_addint(c, x)
	struct compiling *c;
	int x;
{
338 339
	com_addbyte(c, x & 0xff);
	com_addbyte(c, x >> 8); /* XXX x should be positive */
Guido van Rossum's avatar
Guido van Rossum committed
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
}

static void
com_addoparg(c, op, arg)
	struct compiling *c;
	int op;
	int arg;
{
	com_addbyte(c, op);
	com_addint(c, arg);
}

static void
com_addfwref(c, op, p_anchor)
	struct compiling *c;
	int op;
	int *p_anchor;
{
	/* Compile a forward reference for backpatching */
	int here;
	int anchor;
	com_addbyte(c, op);
	here = c->c_nexti;
	anchor = *p_anchor;
	*p_anchor = here;
	com_addint(c, anchor == 0 ? 0 : here - anchor);
}

static void
com_backpatch(c, anchor)
	struct compiling *c;
	int anchor; /* Must be nonzero */
{
	unsigned char *code = (unsigned char *) getstringvalue(c->c_code);
	int target = c->c_nexti;
	int dist;
	int prev;
	for (;;) {
		/* Make the JUMP instruction at anchor point to target */
379 380 381 382
		prev = code[anchor] + (code[anchor+1] << 8);
		dist = target - (anchor+2);
		code[anchor] = dist & 0xff;
		code[anchor+1] = dist >> 8;
Guido van Rossum's avatar
Guido van Rossum committed
383 384 385 386 387 388
		if (!prev)
			break;
		anchor -= prev;
	}
}

Guido van Rossum's avatar
Guido van Rossum committed
389
/* Handle literals and names uniformly */
Guido van Rossum's avatar
Guido van Rossum committed
390 391 392 393 394 395 396

static int
com_add(c, list, v)
	struct compiling *c;
	object *list;
	object *v;
{
397 398 399 400
	int n = getlistsize(list);
	int i;
	for (i = n; --i >= 0; ) {
		object *w = getlistitem(list, i);
401
		if (v->ob_type == w->ob_type && cmpobject(v, w) == 0)
402 403
			return i;
	}
Guido van Rossum's avatar
Guido van Rossum committed
404 405
	if (addlistitem(list, v) != 0)
		c->c_errors++;
406
	return n;
Guido van Rossum's avatar
Guido van Rossum committed
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
}

static int
com_addconst(c, v)
	struct compiling *c;
	object *v;
{
	return com_add(c, c->c_consts, v);
}

static int
com_addname(c, v)
	struct compiling *c;
	object *v;
{
	return com_add(c, c->c_names, v);
}

static void
com_addopname(c, op, n)
	struct compiling *c;
	int op;
	node *n;
{
	object *v;
	int i;
	char *name;
	if (TYPE(n) == STAR)
		name = "*";
	else {
		REQ(n, NAME);
		name = STR(n);
	}
	if ((v = newstringobject(name)) == NULL) {
		c->c_errors++;
		i = 255;
	}
	else {
		i = com_addname(c, v);
		DECREF(v);
	}
448 449 450 451 452 453 454 455 456 457 458 459 460
	/* Hack to replace *_NAME opcodes by *_GLOBAL if necessary */
	switch (op) {
	case LOAD_NAME:
	case STORE_NAME:
	case DELETE_NAME:
		if (dictlookup(c->c_globals, name) != NULL) {
			switch (op) {
			case LOAD_NAME:   op = LOAD_GLOBAL;   break;
			case STORE_NAME:  op = STORE_GLOBAL;  break;
			case DELETE_NAME: op = DELETE_GLOBAL; break;
			}
		}
	}
Guido van Rossum's avatar
Guido van Rossum committed
461 462 463 464 465 466 467
	com_addoparg(c, op, i);
}

static object *
parsenumber(s)
	char *s;
{
Guido van Rossum's avatar
Guido van Rossum committed
468 469 470
	extern long strtol PROTO((const char *, char **, int));
	extern unsigned long strtoul PROTO((const char *, char **, int));
	extern double strtod PROTO((const char *, char **));
471
	char *end;
Guido van Rossum's avatar
Guido van Rossum committed
472
	long x;
473 474
	double xx;
	errno = 0;
475
	end = s + strlen(s) - 1;
Guido van Rossum's avatar
Guido van Rossum committed
476
	if (*end == 'l' || *end == 'L')
477
		return long_scan(s, 0);
478 479 480 481
	if (s[0] == '0')
		x = (long) strtoul(s, &end, 0);
	else
		x = strtol(s, &end, 0);
482 483
	if (*end == '\0') {
		if (errno != 0) {
484
			err_setstr(OverflowError,
Guido van Rossum's avatar
Guido van Rossum committed
485
				   "integer literal too large");
486 487
			return NULL;
		}
Guido van Rossum's avatar
Guido van Rossum committed
488
		return newintobject(x);
489 490 491 492
	}
	errno = 0;
	xx = strtod(s, &end);
	if (*end == '\0') {
Guido van Rossum's avatar
Guido van Rossum committed
493 494 495 496
#ifndef BROKEN_STRTOD
		/* Some strtod() versions (e.g., in older SunOS systems)
		   set errno incorrectly; better to ignore overflows
		   than not to be able to use float literals at all! */
497
		if (errno != 0) {
Guido van Rossum's avatar
Guido van Rossum committed
498
			err_setstr(OverflowError, "float literal too large");
499 500
			return NULL;
		}
Guido van Rossum's avatar
Guido van Rossum committed
501
#endif
502 503
		return newfloatobject(xx);
	}
504
	err_setstr(SystemError, "bad number syntax?!?!");
Guido van Rossum's avatar
Guido van Rossum committed
505 506 507 508 509 510 511 512 513 514 515 516
	return NULL;
}

static object *
parsestr(s)
	char *s;
{
	object *v;
	int len;
	char *buf;
	char *p;
	int c;
517 518
	int quote = *s;
	if (quote != '\'' && quote != '\"') {
Guido van Rossum's avatar
Guido van Rossum committed
519 520 521 522 523
		err_badcall();
		return NULL;
	}
	s++;
	len = strlen(s);
524
	if (s[--len] != quote) {
Guido van Rossum's avatar
Guido van Rossum committed
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
		err_badcall();
		return NULL;
	}
	if (strchr(s, '\\') == NULL)
		return newsizedstringobject(s, len);
	v = newsizedstringobject((char *)NULL, len);
	p = buf = getstringvalue(v);
	while (*s != '\0' && *s != '\'') {
		if (*s != '\\') {
			*p++ = *s++;
			continue;
		}
		s++;
		switch (*s++) {
		/* XXX This assumes ASCII! */
		case '\\': *p++ = '\\'; break;
		case '\'': *p++ = '\''; break;
542
		case '\"': *p++ = '\"'; break;
Guido van Rossum's avatar
Guido van Rossum committed
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
		case 'b': *p++ = '\b'; break;
		case 'f': *p++ = '\014'; break; /* FF */
		case 't': *p++ = '\t'; break;
		case 'n': *p++ = '\n'; break;
		case 'r': *p++ = '\r'; break;
		case 'v': *p++ = '\013'; break; /* VT */
		case 'a': *p++ = '\007'; break; /* BEL, not classic C */
		case '0': case '1': case '2': case '3':
		case '4': case '5': case '6': case '7':
			c = s[-1] - '0';
			if ('0' <= *s && *s <= '7') {
				c = (c<<3) + *s++ - '0';
				if ('0' <= *s && *s <= '7')
					c = (c<<3) + *s++ - '0';
			}
			*p++ = c;
			break;
		case 'x':
			if (isxdigit(*s)) {
				sscanf(s, "%x", &c);
				*p++ = c;
				do {
					s++;
				} while (isxdigit(*s));
				break;
			}
		/* FALLTHROUGH */
		default: *p++ = '\\'; *p++ = s[-1]; break;
		}
	}
	resizestring(&v, (int)(p - buf));
	return v;
}

static void
com_list_constructor(c, n)
	struct compiling *c;
	node *n;
{
	int len;
	int i;
	if (TYPE(n) != testlist)
		REQ(n, exprlist);
	/* exprlist: expr (',' expr)* [',']; likewise for testlist */
	len = (NCH(n) + 1) / 2;
	for (i = 0; i < NCH(n); i += 2)
		com_node(c, CHILD(n, i));
	com_addoparg(c, BUILD_LIST, len);
}

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
static void
com_dictmaker(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	/* dictmaker: test ':' test (',' test ':' value)* [','] */
	for (i = 0; i+2 < NCH(n); i += 4) {
		/* We must arrange things just right for STORE_SUBSCR.
		   It wants the stack to look like (value) (dict) (key) */
		com_addbyte(c, DUP_TOP);
		com_node(c, CHILD(n, i+2)); /* value */
		com_addbyte(c, ROT_TWO);
		com_node(c, CHILD(n, i)); /* key */
		com_addbyte(c, STORE_SUBSCR);
	}
}

Guido van Rossum's avatar
Guido van Rossum committed
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
static void
com_atom(c, n)
	struct compiling *c;
	node *n;
{
	node *ch;
	object *v;
	int i;
	REQ(n, atom);
	ch = CHILD(n, 0);
	switch (TYPE(ch)) {
	case LPAR:
		if (TYPE(CHILD(n, 1)) == RPAR)
			com_addoparg(c, BUILD_TUPLE, 0);
		else
			com_node(c, CHILD(n, 1));
		break;
	case LSQB:
		if (TYPE(CHILD(n, 1)) == RSQB)
			com_addoparg(c, BUILD_LIST, 0);
		else
			com_list_constructor(c, CHILD(n, 1));
		break;
634
	case LBRACE: /* '{' [dictmaker] '}' */
Guido van Rossum's avatar
Guido van Rossum committed
635
		com_addoparg(c, BUILD_MAP, 0);
636 637
		if (TYPE(CHILD(n, 1)) != RBRACE)
			com_dictmaker(c, CHILD(n, 1));
Guido van Rossum's avatar
Guido van Rossum committed
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
		break;
	case BACKQUOTE:
		com_node(c, CHILD(n, 1));
		com_addbyte(c, UNARY_CONVERT);
		break;
	case NUMBER:
		if ((v = parsenumber(STR(ch))) == NULL) {
			c->c_errors++;
			i = 255;
		}
		else {
			i = com_addconst(c, v);
			DECREF(v);
		}
		com_addoparg(c, LOAD_CONST, i);
		break;
	case STRING:
		if ((v = parsestr(STR(ch))) == NULL) {
			c->c_errors++;
			i = 255;
		}
		else {
			i = com_addconst(c, v);
			DECREF(v);
		}
		com_addoparg(c, LOAD_CONST, i);
		break;
	case NAME:
		com_addopname(c, LOAD_NAME, ch);
		break;
	default:
		fprintf(stderr, "node type %d\n", TYPE(ch));
		err_setstr(SystemError, "com_atom: unexpected node type");
		c->c_errors++;
	}
}

static void
com_slice(c, n, op)
	struct compiling *c;
	node *n;
	int op;
{
	if (NCH(n) == 1) {
		com_addbyte(c, op);
	}
	else if (NCH(n) == 2) {
		if (TYPE(CHILD(n, 0)) != COLON) {
			com_node(c, CHILD(n, 0));
			com_addbyte(c, op+1);
		}
		else {
			com_node(c, CHILD(n, 1));
			com_addbyte(c, op+2);
		}
	}
	else {
		com_node(c, CHILD(n, 0));
		com_node(c, CHILD(n, 2));
		com_addbyte(c, op+3);
	}
}

static void
com_apply_subscript(c, n)
	struct compiling *c;
	node *n;
{
	REQ(n, subscript);
	if (NCH(n) == 1 && TYPE(CHILD(n, 0)) != COLON) {
		/* It's a single subscript */
		com_node(c, CHILD(n, 0));
		com_addbyte(c, BINARY_SUBSCR);
	}
	else {
		/* It's a slice: [expr] ':' [expr] */
		com_slice(c, n, SLICE);
	}
}

static void
com_call_function(c, n)
	struct compiling *c;
	node *n; /* EITHER testlist OR ')' */
{
	if (TYPE(n) == RPAR) {
Guido van Rossum's avatar
Guido van Rossum committed
724 725
		com_addoparg(c, BUILD_TUPLE, 0);
		com_addbyte(c, BINARY_CALL);
Guido van Rossum's avatar
Guido van Rossum committed
726 727
	}
	else {
Guido van Rossum's avatar
Guido van Rossum committed
728 729
		REQ(n, testlist);
		com_list(c, n, 1);
Guido van Rossum's avatar
Guido van Rossum committed
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
		com_addbyte(c, BINARY_CALL);
	}
}

static void
com_select_member(c, n)
	struct compiling *c;
	node *n;
{
	com_addopname(c, LOAD_ATTR, n);
}

static void
com_apply_trailer(c, n)
	struct compiling *c;
	node *n;
{
	REQ(n, trailer);
	switch (TYPE(CHILD(n, 0))) {
	case LPAR:
		com_call_function(c, CHILD(n, 1));
		break;
	case DOT:
		com_select_member(c, CHILD(n, 1));
		break;
	case LSQB:
		com_apply_subscript(c, CHILD(n, 1));
		break;
	default:
		err_setstr(SystemError,
			"com_apply_trailer: unknown trailer type");
		c->c_errors++;
	}
}

static void
com_factor(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	REQ(n, factor);
	if (TYPE(CHILD(n, 0)) == PLUS) {
		com_factor(c, CHILD(n, 1));
		com_addbyte(c, UNARY_POSITIVE);
	}
	else if (TYPE(CHILD(n, 0)) == MINUS) {
		com_factor(c, CHILD(n, 1));
		com_addbyte(c, UNARY_NEGATIVE);
	}
780 781 782 783
	else if (TYPE(CHILD(n, 0)) == TILDE) {
		com_factor(c, CHILD(n, 1));
		com_addbyte(c, UNARY_INVERT);
	}
Guido van Rossum's avatar
Guido van Rossum committed
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
	else {
		com_atom(c, CHILD(n, 0));
		for (i = 1; i < NCH(n); i++)
			com_apply_trailer(c, CHILD(n, i));
	}
}

static void
com_term(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	int op;
	REQ(n, term);
	com_factor(c, CHILD(n, 0));
	for (i = 2; i < NCH(n); i += 2) {
		com_factor(c, CHILD(n, i));
		switch (TYPE(CHILD(n, i-1))) {
		case STAR:
			op = BINARY_MULTIPLY;
			break;
		case SLASH:
			op = BINARY_DIVIDE;
			break;
		case PERCENT:
			op = BINARY_MODULO;
			break;
		default:
			err_setstr(SystemError,
814
				"com_term: operator not *, / or %");
Guido van Rossum's avatar
Guido van Rossum committed
815 816 817 818 819 820 821 822
			c->c_errors++;
			op = 255;
		}
		com_addbyte(c, op);
	}
}

static void
823
com_arith_expr(c, n)
Guido van Rossum's avatar
Guido van Rossum committed
824 825 826 827 828
	struct compiling *c;
	node *n;
{
	int i;
	int op;
829
	REQ(n, arith_expr);
Guido van Rossum's avatar
Guido van Rossum committed
830 831 832 833 834 835 836 837 838 839 840 841
	com_term(c, CHILD(n, 0));
	for (i = 2; i < NCH(n); i += 2) {
		com_term(c, CHILD(n, i));
		switch (TYPE(CHILD(n, i-1))) {
		case PLUS:
			op = BINARY_ADD;
			break;
		case MINUS:
			op = BINARY_SUBTRACT;
			break;
		default:
			err_setstr(SystemError,
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
				"com_arith_expr: operator not + or -");
			c->c_errors++;
			op = 255;
		}
		com_addbyte(c, op);
	}
}

static void
com_shift_expr(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	int op;
	REQ(n, shift_expr);
	com_arith_expr(c, CHILD(n, 0));
	for (i = 2; i < NCH(n); i += 2) {
		com_arith_expr(c, CHILD(n, i));
		switch (TYPE(CHILD(n, i-1))) {
		case LEFTSHIFT:
			op = BINARY_LSHIFT;
			break;
		case RIGHTSHIFT:
			op = BINARY_RSHIFT;
			break;
		default:
			err_setstr(SystemError,
				"com_shift_expr: operator not << or >>");
			c->c_errors++;
			op = 255;
		}
		com_addbyte(c, op);
	}
}

static void
com_and_expr(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	int op;
	REQ(n, and_expr);
	com_shift_expr(c, CHILD(n, 0));
	for (i = 2; i < NCH(n); i += 2) {
		com_shift_expr(c, CHILD(n, i));
		if (TYPE(CHILD(n, i-1)) == AMPER) {
			op = BINARY_AND;
		}
		else {
			err_setstr(SystemError,
				"com_and_expr: operator not &");
			c->c_errors++;
			op = 255;
		}
		com_addbyte(c, op);
	}
}

static void
com_xor_expr(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	int op;
	REQ(n, xor_expr);
	com_and_expr(c, CHILD(n, 0));
	for (i = 2; i < NCH(n); i += 2) {
		com_and_expr(c, CHILD(n, i));
		if (TYPE(CHILD(n, i-1)) == CIRCUMFLEX) {
			op = BINARY_XOR;
		}
		else {
			err_setstr(SystemError,
				"com_xor_expr: operator not ^");
			c->c_errors++;
			op = 255;
		}
		com_addbyte(c, op);
	}
}

static void
com_expr(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	int op;
	REQ(n, expr);
	com_xor_expr(c, CHILD(n, 0));
	for (i = 2; i < NCH(n); i += 2) {
		com_xor_expr(c, CHILD(n, i));
		if (TYPE(CHILD(n, i-1)) == VBAR) {
			op = BINARY_OR;
		}
		else {
			err_setstr(SystemError,
				"com_expr: expr operator not |");
Guido van Rossum's avatar
Guido van Rossum committed
943 944 945 946 947 948 949 950 951 952 953 954
			c->c_errors++;
			op = 255;
		}
		com_addbyte(c, op);
	}
}

static enum cmp_op
cmp_type(n)
	node *n;
{
	REQ(n, comp_op);
955
	/* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
Guido van Rossum's avatar
Guido van Rossum committed
956 957 958 959 960 961
	          | 'in' | 'not' 'in' | 'is' | 'is' not' */
	if (NCH(n) == 1) {
		n = CHILD(n, 0);
		switch (TYPE(n)) {
		case LESS:	return LT;
		case GREATER:	return GT;
962
		case EQEQUAL:			/* == */
Guido van Rossum's avatar
Guido van Rossum committed
963
		case EQUAL:	return EQ;
964 965 966
		case LESSEQUAL:	return LE;
		case GREATEREQUAL: return GE;
		case NOTEQUAL:	return NE;	/* <> or != */
Guido van Rossum's avatar
Guido van Rossum committed
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
		case NAME:	if (strcmp(STR(n), "in") == 0) return IN;
				if (strcmp(STR(n), "is") == 0) return IS;
		}
	}
	else if (NCH(n) == 2) {
		switch (TYPE(CHILD(n, 0))) {
		case NAME:	if (strcmp(STR(CHILD(n, 1)), "in") == 0)
					return NOT_IN;
				if (strcmp(STR(CHILD(n, 0)), "is") == 0)
					return IS_NOT;
		}
	}
	return BAD;
}

static void
com_comparison(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	enum cmp_op op;
	int anchor;
	REQ(n, comparison); /* comparison: expr (comp_op expr)* */
	com_expr(c, CHILD(n, 0));
	if (NCH(n) == 1)
		return;
	
	/****************************************************************
	   The following code is generated for all but the last
	   comparison in a chain:
	   
	   label:	on stack:	opcode:		jump to:
	   
			a		<code to load b>
			a, b		DUP_TOP
			a, b, b		ROT_THREE
			b, a, b		COMPARE_OP
			b, 0-or-1	JUMP_IF_FALSE	L1
			b, 1		POP_TOP
			b		
	
	   We are now ready to repeat this sequence for the next
	   comparison in the chain.
	   
	   For the last we generate:
	   
	   		b		<code to load c>
	   		b, c		COMPARE_OP
	   		0-or-1		
	   
	   If there were any jumps to L1 (i.e., there was more than one
	   comparison), we generate:
	   
	   		0-or-1		JUMP_FORWARD	L2
	   L1:		b, 0		ROT_TWO
	   		0, b		POP_TOP
	   		0
	   L2:
	****************************************************************/
	
	anchor = 0;
	
	for (i = 2; i < NCH(n); i += 2) {
		com_expr(c, CHILD(n, i));
		if (i+2 < NCH(n)) {
			com_addbyte(c, DUP_TOP);
			com_addbyte(c, ROT_THREE);
		}
		op = cmp_type(CHILD(n, i-1));
		if (op == BAD) {
			err_setstr(SystemError,
				"com_comparison: unknown comparison op");
			c->c_errors++;
		}
		com_addoparg(c, COMPARE_OP, op);
		if (i+2 < NCH(n)) {
			com_addfwref(c, JUMP_IF_FALSE, &anchor);
			com_addbyte(c, POP_TOP);
		}
	}
	
	if (anchor) {
		int anchor2 = 0;
		com_addfwref(c, JUMP_FORWARD, &anchor2);
		com_backpatch(c, anchor);
		com_addbyte(c, ROT_TWO);
		com_addbyte(c, POP_TOP);
		com_backpatch(c, anchor2);
	}
}

static void
com_not_test(c, n)
	struct compiling *c;
	node *n;
{
	REQ(n, not_test); /* 'not' not_test | comparison */
	if (NCH(n) == 1) {
		com_comparison(c, CHILD(n, 0));
	}
	else {
		com_not_test(c, CHILD(n, 1));
		com_addbyte(c, UNARY_NOT);
	}
}

static void
com_and_test(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	int anchor;
	REQ(n, and_test); /* not_test ('and' not_test)* */
	anchor = 0;
	i = 0;
	for (;;) {
		com_not_test(c, CHILD(n, i));
		if ((i += 2) >= NCH(n))
			break;
		com_addfwref(c, JUMP_IF_FALSE, &anchor);
		com_addbyte(c, POP_TOP);
	}
	if (anchor)
		com_backpatch(c, anchor);
}

static void
com_test(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	int anchor;
	REQ(n, test); /* and_test ('and' and_test)* */
	anchor = 0;
	i = 0;
	for (;;) {
		com_and_test(c, CHILD(n, i));
		if ((i += 2) >= NCH(n))
			break;
		com_addfwref(c, JUMP_IF_TRUE, &anchor);
		com_addbyte(c, POP_TOP);
	}
	if (anchor)
		com_backpatch(c, anchor);
}

static void
Guido van Rossum's avatar
Guido van Rossum committed
1117
com_list(c, n, toplevel)
Guido van Rossum's avatar
Guido van Rossum committed
1118 1119
	struct compiling *c;
	node *n;
Guido van Rossum's avatar
Guido van Rossum committed
1120
	int toplevel; /* If nonzero, *always* build a tuple */
Guido van Rossum's avatar
Guido van Rossum committed
1121 1122
{
	/* exprlist: expr (',' expr)* [',']; likewise for testlist */
Guido van Rossum's avatar
Guido van Rossum committed
1123
	if (NCH(n) == 1 && !toplevel) {
Guido van Rossum's avatar
Guido van Rossum committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
		com_node(c, CHILD(n, 0));
	}
	else {
		int i;
		int len;
		len = (NCH(n) + 1) / 2;
		for (i = 0; i < NCH(n); i += 2)
			com_node(c, CHILD(n, i));
		com_addoparg(c, BUILD_TUPLE, len);
	}
}


/* Begin of assignment compilation */

static void com_assign_name PROTO((struct compiling *, node *, int));
static void com_assign PROTO((struct compiling *, node *, int));

static void
com_assign_attr(c, n, assigning)
	struct compiling *c;
	node *n;
	int assigning;
{
	com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n);
}

static void
com_assign_slice(c, n, assigning)
	struct compiling *c;
	node *n;
	int assigning;
{
	com_slice(c, n, assigning ? STORE_SLICE : DELETE_SLICE);
}

static void
com_assign_subscript(c, n, assigning)
	struct compiling *c;
	node *n;
	int assigning;
{
	com_node(c, n);
	com_addbyte(c, assigning ? STORE_SUBSCR : DELETE_SUBSCR);
}

static void
com_assign_trailer(c, n, assigning)
	struct compiling *c;
	node *n;
	int assigning;
{
	REQ(n, trailer);
	switch (TYPE(CHILD(n, 0))) {
	case LPAR: /* '(' [exprlist] ')' */
1179
		err_setstr(SyntaxError, "can't assign to function call");
Guido van Rossum's avatar
Guido van Rossum committed
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
		c->c_errors++;
		break;
	case DOT: /* '.' NAME */
		com_assign_attr(c, CHILD(n, 1), assigning);
		break;
	case LSQB: /* '[' subscript ']' */
		n = CHILD(n, 1);
		REQ(n, subscript); /* subscript: expr | [expr] ':' [expr] */
		if (NCH(n) > 1 || TYPE(CHILD(n, 0)) == COLON)
			com_assign_slice(c, n, assigning);
		else
			com_assign_subscript(c, CHILD(n, 0), assigning);
		break;
	default:
1194
		err_setstr(SystemError, "unknown trailer type");
Guido van Rossum's avatar
Guido van Rossum committed
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
		c->c_errors++;
	}
}

static void
com_assign_tuple(c, n, assigning)
	struct compiling *c;
	node *n;
	int assigning;
{
	int i;
	if (TYPE(n) != testlist)
		REQ(n, exprlist);
	if (assigning)
		com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2);
	for (i = 0; i < NCH(n); i += 2)
		com_assign(c, CHILD(n, i), assigning);
}

static void
com_assign_list(c, n, assigning)
	struct compiling *c;
	node *n;
	int assigning;
{
	int i;
	if (assigning)
		com_addoparg(c, UNPACK_LIST, (NCH(n)+1)/2);
	for (i = 0; i < NCH(n); i += 2)
		com_assign(c, CHILD(n, i), assigning);
}

static void
com_assign_name(c, n, assigning)
	struct compiling *c;
	node *n;
	int assigning;
{
	REQ(n, NAME);
	com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n);
}

static void
com_assign(c, n, assigning)
	struct compiling *c;
	node *n;
	int assigning;
{
	/* Loop to avoid trivial recursion */
	for (;;) {
		switch (TYPE(n)) {
1246
		
Guido van Rossum's avatar
Guido van Rossum committed
1247 1248 1249 1250 1251 1252 1253 1254
		case exprlist:
		case testlist:
			if (NCH(n) > 1) {
				com_assign_tuple(c, n, assigning);
				return;
			}
			n = CHILD(n, 0);
			break;
1255
		
Guido van Rossum's avatar
Guido van Rossum committed
1256 1257 1258 1259 1260
		case test:
		case and_test:
		case not_test:
		case comparison:
		case expr:
1261 1262 1263 1264
		case xor_expr:
		case and_expr:
		case shift_expr:
		case arith_expr:
Guido van Rossum's avatar
Guido van Rossum committed
1265 1266
		case term:
			if (NCH(n) > 1) {
1267
				err_setstr(SyntaxError,
Guido van Rossum's avatar
Guido van Rossum committed
1268 1269 1270 1271 1272 1273
					"can't assign to operator");
				c->c_errors++;
				return;
			}
			n = CHILD(n, 0);
			break;
1274
		
1275 1276
		case factor: /* ('+'|'-'|'~') factor | atom trailer* */
			if (TYPE(CHILD(n, 0)) != atom) { /* '+'|'-'|'~' */
1277
				err_setstr(SyntaxError,
Guido van Rossum's avatar
Guido van Rossum committed
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
					"can't assign to operator");
				c->c_errors++;
				return;
			}
			if (NCH(n) > 1) { /* trailer present */
				int i;
				com_node(c, CHILD(n, 0));
				for (i = 1; i+1 < NCH(n); i++) {
					com_apply_trailer(c, CHILD(n, i));
				} /* NB i is still alive */
				com_assign_trailer(c,
						CHILD(n, i), assigning);
				return;
			}
			n = CHILD(n, 0);
			break;
1294
		
Guido van Rossum's avatar
Guido van Rossum committed
1295 1296 1297 1298 1299 1300
		case atom:
			switch (TYPE(CHILD(n, 0))) {
			case LPAR:
				n = CHILD(n, 1);
				if (TYPE(n) == RPAR) {
					/* XXX Should allow () = () ??? */
1301
					err_setstr(SyntaxError,
Guido van Rossum's avatar
Guido van Rossum committed
1302 1303 1304 1305 1306 1307 1308 1309
						"can't assign to ()");
					c->c_errors++;
					return;
				}
				break;
			case LSQB:
				n = CHILD(n, 1);
				if (TYPE(n) == RSQB) {
1310
					err_setstr(SyntaxError,
Guido van Rossum's avatar
Guido van Rossum committed
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
						"can't assign to []");
					c->c_errors++;
					return;
				}
				com_assign_list(c, n, assigning);
				return;
			case NAME:
				com_assign_name(c, CHILD(n, 0), assigning);
				return;
			default:
1321
				err_setstr(SyntaxError,
Guido van Rossum's avatar
Guido van Rossum committed
1322
						"can't assign to literal");
Guido van Rossum's avatar
Guido van Rossum committed
1323 1324 1325 1326
				c->c_errors++;
				return;
			}
			break;
1327
		
Guido van Rossum's avatar
Guido van Rossum committed
1328 1329 1330 1331 1332
		default:
			fprintf(stderr, "node type %d\n", TYPE(n));
			err_setstr(SystemError, "com_assign: bad node");
			c->c_errors++;
			return;
1333
		
Guido van Rossum's avatar
Guido van Rossum committed
1334 1335 1336 1337 1338 1339 1340 1341 1342
		}
	}
}

static void
com_expr_stmt(c, n)
	struct compiling *c;
	node *n;
{
1343
	REQ(n, expr_stmt); /* testlist ('=' testlist)* */
1344 1345
	com_node(c, CHILD(n, NCH(n)-1));
	if (NCH(n) == 1) {
Guido van Rossum's avatar
Guido van Rossum committed
1346 1347 1348 1349
		com_addbyte(c, PRINT_EXPR);
	}
	else {
		int i;
1350 1351
		for (i = 0; i < NCH(n)-2; i+=2) {
			if (i+2 < NCH(n)-2)
Guido van Rossum's avatar
Guido van Rossum committed
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
				com_addbyte(c, DUP_TOP);
			com_assign(c, CHILD(n, i), 1/*assign*/);
		}
	}
}

static void
com_print_stmt(c, n)
	struct compiling *c;
	node *n;
{
	int i;
1364 1365
	REQ(n, print_stmt); /* 'print' (test ',')* [test] */
	for (i = 1; i < NCH(n); i += 2) {
Guido van Rossum's avatar
Guido van Rossum committed
1366 1367 1368
		com_node(c, CHILD(n, i));
		com_addbyte(c, PRINT_ITEM);
	}
1369
	if (TYPE(CHILD(n, NCH(n)-1)) != COMMA)
Guido van Rossum's avatar
Guido van Rossum committed
1370
		com_addbyte(c, PRINT_NEWLINE);
1371
		/* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
Guido van Rossum's avatar
Guido van Rossum committed
1372 1373 1374 1375 1376 1377 1378
}

static void
com_return_stmt(c, n)
	struct compiling *c;
	node *n;
{
1379
	REQ(n, return_stmt); /* 'return' [testlist] */
Guido van Rossum's avatar
Guido van Rossum committed
1380
	if (!c->c_infunction) {
1381
		err_setstr(SyntaxError, "'return' outside function");
Guido van Rossum's avatar
Guido van Rossum committed
1382 1383
		c->c_errors++;
	}
1384
	if (NCH(n) < 2)
Guido van Rossum's avatar
Guido van Rossum committed
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
		com_addoparg(c, LOAD_CONST, com_addconst(c, None));
	else
		com_node(c, CHILD(n, 1));
	com_addbyte(c, RETURN_VALUE);
}

static void
com_raise_stmt(c, n)
	struct compiling *c;
	node *n;
{
1396
	REQ(n, raise_stmt); /* 'raise' test [',' test] */
Guido van Rossum's avatar
Guido van Rossum committed
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
	com_node(c, CHILD(n, 1));
	if (NCH(n) > 3)
		com_node(c, CHILD(n, 3));
	else
		com_addoparg(c, LOAD_CONST, com_addconst(c, None));
	com_addbyte(c, RAISE_EXCEPTION);
}

static void
com_import_stmt(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	REQ(n, import_stmt);
1412 1413
	/* 'import' NAME (',' NAME)* |
	   'from' NAME 'import' ('*' | NAME (',' NAME)*) */
Guido van Rossum's avatar
Guido van Rossum committed
1414 1415 1416 1417 1418 1419 1420 1421 1422
	if (STR(CHILD(n, 0))[0] == 'f') {
		/* 'from' NAME 'import' ... */
		REQ(CHILD(n, 1), NAME);
		com_addopname(c, IMPORT_NAME, CHILD(n, 1));
		for (i = 3; i < NCH(n); i += 2)
			com_addopname(c, IMPORT_FROM, CHILD(n, i));
		com_addbyte(c, POP_TOP);
	}
	else {
1423
		/* 'import' ... */
Guido van Rossum's avatar
Guido van Rossum committed
1424 1425 1426 1427 1428 1429 1430
		for (i = 1; i < NCH(n); i += 2) {
			com_addopname(c, IMPORT_NAME, CHILD(n, i));
			com_addopname(c, STORE_NAME, CHILD(n, i));
		}
	}
}

1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
static void
com_global_stmt(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	REQ(n, global_stmt);
	/* 'global' NAME (',' NAME)* */
	for (i = 1; i < NCH(n); i += 2) {
		if (dictinsert(c->c_globals, STR(CHILD(n, i)), None) != 0)
			c->c_errors++;
	}
}

1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
#define strequ(a, b) (strcmp((a), (b)) == 0)

static void
com_access_stmt(c, n)
	struct compiling *c;
	node *n;
{
	int i, j, k, mode, imode;
	object *vmode;
	REQ(n, access_stmt);
	/* 'access' NAME (',' NAME)* ':' accesstype (',' accesstype)*
	   accesstype: NAME+ */

	/* Find where the colon is */
	i = 1;
	while (TYPE(CHILD(n,i-1)) != COLON)
		i += 1;

	/* Calculate the mode mask */
	mode = 0;
	for (j = i; j < NCH(n); j += 2) {
1466 1467
		int r = 0, w = 0, p = 0;
		for (k = 0; k < NCH(CHILD(n,j)); k++) {
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
			if (strequ(STR(CHILD(CHILD(n,j),k)), "public"))
				p = 0;
			else if (strequ(STR(CHILD(CHILD(n,j),k)), "protected"))
				p = 1;
			else if (strequ(STR(CHILD(CHILD(n,j),k)), "private"))
				p = 2;
			else if (strequ(STR(CHILD(CHILD(n,j),k)), "read"))
				r = 1;
			else if (strequ(STR(CHILD(CHILD(n,j),k)), "write"))
				w = 1;
			else /* XXX should make this an exception */
				fprintf(stderr, "bad access type %s\n",
					STR(CHILD(CHILD(n,j),k)));
		}
		if (r == 0 && w == 0)
1483
			r = w = 1;
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
		if (p == 0) {
			if (r == 1) mode |= AC_R_PUBLIC;
			if (w == 1) mode |= AC_W_PUBLIC;
		} else if (p == 1) {
			if (r == 1) mode |= AC_R_PROTECTED;
			if (w == 1) mode |= AC_W_PROTECTED;
		} else {
			if (r == 1) mode |= AC_R_PRIVATE;
			if (w == 1) mode |= AC_W_PRIVATE;
		}
	}
	vmode = newintobject((long)mode);
	imode = com_addconst(c, vmode);
	XDECREF(vmode);
	for (i = 1; TYPE(CHILD(n,i-1)) != COLON; i+=2) {
		com_addoparg(c, LOAD_CONST, imode);
		com_addopname(c, ACCESS_MODE, CHILD(n, i));
	}
}

1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
static void
com_exec_stmt(c, n)
	struct compiling *c;
	node *n;
{
	REQ(n, exec_stmt);
	/* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
	com_node(c, CHILD(n, 1));
	if (NCH(n) >= 4)
		com_node(c, CHILD(n, 3));
	else
		com_addoparg(c, LOAD_CONST, com_addconst(c, None));
	if (NCH(n) >= 6)
		com_node(c, CHILD(n, 5));
	else
		com_addbyte(c, DUP_TOP);
	com_addbyte(c, EXEC_STMT);
}

Guido van Rossum's avatar
Guido van Rossum committed
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
static void
com_if_stmt(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	int anchor = 0;
	REQ(n, if_stmt);
	/*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
	for (i = 0; i+3 < NCH(n); i+=4) {
		int a = 0;
Guido van Rossum's avatar
Guido van Rossum committed
1534 1535 1536
		node *ch = CHILD(n, i+1);
		if (i > 0)
			com_addoparg(c, SET_LINENO, ch->n_lineno);
Guido van Rossum's avatar
Guido van Rossum committed
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
		com_node(c, CHILD(n, i+1));
		com_addfwref(c, JUMP_IF_FALSE, &a);
		com_addbyte(c, POP_TOP);
		com_node(c, CHILD(n, i+3));
		com_addfwref(c, JUMP_FORWARD, &anchor);
		com_backpatch(c, a);
		com_addbyte(c, POP_TOP);
	}
	if (i+2 < NCH(n))
		com_node(c, CHILD(n, i+2));
	com_backpatch(c, anchor);
}

static void
com_while_stmt(c, n)
	struct compiling *c;
	node *n;
{
	int break_anchor = 0;
	int anchor = 0;
1557
	int save_begin = c->c_begin;
Guido van Rossum's avatar
Guido van Rossum committed
1558 1559
	REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */
	com_addfwref(c, SETUP_LOOP, &break_anchor);
1560 1561
	block_push(c, SETUP_LOOP);
	c->c_begin = c->c_nexti;
Guido van Rossum's avatar
Guido van Rossum committed
1562
	com_addoparg(c, SET_LINENO, n->n_lineno);
Guido van Rossum's avatar
Guido van Rossum committed
1563 1564 1565
	com_node(c, CHILD(n, 1));
	com_addfwref(c, JUMP_IF_FALSE, &anchor);
	com_addbyte(c, POP_TOP);
Guido van Rossum's avatar
Guido van Rossum committed
1566
	c->c_loops++;
Guido van Rossum's avatar
Guido van Rossum committed
1567
	com_node(c, CHILD(n, 3));
Guido van Rossum's avatar
Guido van Rossum committed
1568
	c->c_loops--;
1569 1570
	com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
	c->c_begin = save_begin;
Guido van Rossum's avatar
Guido van Rossum committed
1571 1572 1573
	com_backpatch(c, anchor);
	com_addbyte(c, POP_TOP);
	com_addbyte(c, POP_BLOCK);
1574
	block_pop(c, SETUP_LOOP);
Guido van Rossum's avatar
Guido van Rossum committed
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
	if (NCH(n) > 4)
		com_node(c, CHILD(n, 6));
	com_backpatch(c, break_anchor);
}

static void
com_for_stmt(c, n)
	struct compiling *c;
	node *n;
{
	object *v;
	int break_anchor = 0;
	int anchor = 0;
1588
	int save_begin = c->c_begin;
Guido van Rossum's avatar
Guido van Rossum committed
1589 1590 1591
	REQ(n, for_stmt);
	/* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
	com_addfwref(c, SETUP_LOOP, &break_anchor);
1592
	block_push(c, SETUP_LOOP);
Guido van Rossum's avatar
Guido van Rossum committed
1593 1594 1595 1596 1597 1598
	com_node(c, CHILD(n, 3));
	v = newintobject(0L);
	if (v == NULL)
		c->c_errors++;
	com_addoparg(c, LOAD_CONST, com_addconst(c, v));
	XDECREF(v);
1599
	c->c_begin = c->c_nexti;
Guido van Rossum's avatar
Guido van Rossum committed
1600
	com_addoparg(c, SET_LINENO, n->n_lineno);
Guido van Rossum's avatar
Guido van Rossum committed
1601 1602
	com_addfwref(c, FOR_LOOP, &anchor);
	com_assign(c, CHILD(n, 1), 1/*assigning*/);
Guido van Rossum's avatar
Guido van Rossum committed
1603
	c->c_loops++;
Guido van Rossum's avatar
Guido van Rossum committed
1604
	com_node(c, CHILD(n, 5));
Guido van Rossum's avatar
Guido van Rossum committed
1605
	c->c_loops--;
1606 1607
	com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
	c->c_begin = save_begin;
Guido van Rossum's avatar
Guido van Rossum committed
1608 1609
	com_backpatch(c, anchor);
	com_addbyte(c, POP_BLOCK);
1610
	block_pop(c, SETUP_LOOP);
Guido van Rossum's avatar
Guido van Rossum committed
1611 1612 1613 1614 1615
	if (NCH(n) > 8)
		com_node(c, CHILD(n, 8));
	com_backpatch(c, break_anchor);
}

1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
/* Although 'execpt' and 'finally' clauses can be combined
   syntactically, they are compiled separately.  In fact,
	try: S
	except E1: S1
	except E2: S2
	...
	finally: Sf
   is equivalent to
	try:
	    try: S
	    except E1: S1
	    except E2: S2
	    ...
	finally: Sf
   meaning that the 'finally' clause is entered even if things
   go wrong again in an exception handler.  Note that this is
   not the case for exception handlers: at most one is entered.
   
   Code generated for "try: S finally: Sf" is as follows:
   
		SETUP_FINALLY	L
		<code for S>
		POP_BLOCK
		LOAD_CONST	<nil>
	L:	<code for Sf>
		END_FINALLY
   
   The special instructions use the block stack.  Each block
   stack entry contains the instruction that created it (here
   SETUP_FINALLY), the level of the value stack at the time the
   block stack entry was created, and a label (here L).
   
   SETUP_FINALLY:
	Pushes the current value stack level and the label
	onto the block stack.
   POP_BLOCK:
	Pops en entry from the block stack, and pops the value
	stack until its level is the same as indicated on the
	block stack.  (The label is ignored.)
   END_FINALLY:
Guido van Rossum's avatar
Guido van Rossum committed
1656 1657 1658
	Pops a variable number of entries from the *value* stack
	and re-raises the exception they specify.  The number of
	entries popped depends on the (pseudo) exception type.
1659 1660 1661 1662 1663 1664 1665 1666
   
   The block stack is unwound when an exception is raised:
   when a SETUP_FINALLY entry is found, the exception is pushed
   onto the value stack (and the exception condition is cleared),
   and the interpreter jumps to the label gotten from the block
   stack.
   
   Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
Guido van Rossum's avatar
Guido van Rossum committed
1667 1668 1669
   (The contents of the value stack is shown in [], with the top
   at the right; 'tb' is trace-back info, 'val' the exception's
   associated value, and 'exc' the exception.)
1670 1671 1672 1673 1674 1675 1676
   
   Value stack		Label	Instruction	Argument
   []				SETUP_EXCEPT	L1
   []				<code for S>
   []				POP_BLOCK
   []				JUMP_FORWARD	L0
   
Guido van Rossum's avatar
Guido van Rossum committed
1677 1678 1679 1680 1681 1682 1683 1684
   [tb, val, exc]	L1:	DUP				)
   [tb, val, exc, exc]		<evaluate E1>			)
   [tb, val, exc, exc, E1]	COMPARE_OP	EXC_MATCH	) only if E1
   [tb, val, exc, 1-or-0]	JUMP_IF_FALSE	L2		)
   [tb, val, exc, 1]		POP				)
   [tb, val, exc]		POP
   [tb, val]			<assign to V1>	(or POP if no V1)
   [tb]				POP
1685 1686 1687
   []				<code for S1>
   				JUMP_FORWARD	L0
   
Guido van Rossum's avatar
Guido van Rossum committed
1688 1689
   [tb, val, exc, 0]	L2:	POP
   [tb, val, exc]		DUP
1690 1691
   .............................etc.......................

Guido van Rossum's avatar
Guido van Rossum committed
1692 1693
   [tb, val, exc, 0]	Ln+1:	POP
   [tb, val, exc]	   	END_FINALLY	# re-raise exception
1694 1695 1696 1697 1698 1699
   
   []			L0:	<next statement>
   
   Of course, parts are not generated if Vi or Ei is not present.
*/

Guido van Rossum's avatar
Guido van Rossum committed
1700 1701 1702 1703 1704 1705 1706 1707
static void
com_try_stmt(c, n)
	struct compiling *c;
	node *n;
{
	int finally_anchor = 0;
	int except_anchor = 0;
	REQ(n, try_stmt);
1708 1709 1710 1711 1712
	/* 'try' ':' suite (except_clause ':' suite)*
	 | 'try' ':' 'finally' ':' suite */

	/* XXX This can be simplified because except and finally can
	   no longer be mixed in a single try statement */
1713
	
Guido van Rossum's avatar
Guido van Rossum committed
1714 1715 1716
	if (NCH(n) > 3 && TYPE(CHILD(n, NCH(n)-3)) != except_clause) {
		/* Have a 'finally' clause */
		com_addfwref(c, SETUP_FINALLY, &finally_anchor);
1717
		block_push(c, SETUP_FINALLY);
Guido van Rossum's avatar
Guido van Rossum committed
1718 1719 1720 1721
	}
	if (NCH(n) > 3 && TYPE(CHILD(n, 3)) == except_clause) {
		/* Have an 'except' clause */
		com_addfwref(c, SETUP_EXCEPT, &except_anchor);
1722
		block_push(c, SETUP_EXCEPT);
Guido van Rossum's avatar
Guido van Rossum committed
1723 1724 1725 1726 1727 1728 1729
	}
	com_node(c, CHILD(n, 2));
	if (except_anchor) {
		int end_anchor = 0;
		int i;
		node *ch;
		com_addbyte(c, POP_BLOCK);
1730
		block_pop(c, SETUP_EXCEPT);
Guido van Rossum's avatar
Guido van Rossum committed
1731 1732 1733 1734 1735 1736
		com_addfwref(c, JUMP_FORWARD, &end_anchor);
		com_backpatch(c, except_anchor);
		for (i = 3;
			i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause;
								i += 3) {
			/* except_clause: 'except' [expr [',' expr]] */
1737
			if (except_anchor == 0) {
1738
				err_setstr(SyntaxError,
1739 1740 1741 1742 1743
					"default 'except:' must be last");
				c->c_errors++;
				break;
			}
			except_anchor = 0;
Guido van Rossum's avatar
Guido van Rossum committed
1744
			com_addoparg(c, SET_LINENO, ch->n_lineno);
Guido van Rossum's avatar
Guido van Rossum committed
1745 1746 1747 1748
			if (NCH(ch) > 1) {
				com_addbyte(c, DUP_TOP);
				com_node(c, CHILD(ch, 1));
				com_addoparg(c, COMPARE_OP, EXC_MATCH);
1749
				com_addfwref(c, JUMP_IF_FALSE, &except_anchor);
Guido van Rossum's avatar
Guido van Rossum committed
1750 1751 1752 1753 1754 1755 1756
				com_addbyte(c, POP_TOP);
			}
			com_addbyte(c, POP_TOP);
			if (NCH(ch) > 3)
				com_assign(c, CHILD(ch, 3), 1/*assigning*/);
			else
				com_addbyte(c, POP_TOP);
Guido van Rossum's avatar
Guido van Rossum committed
1757
			com_addbyte(c, POP_TOP);
Guido van Rossum's avatar
Guido van Rossum committed
1758 1759
			com_node(c, CHILD(n, i+2));
			com_addfwref(c, JUMP_FORWARD, &end_anchor);
1760 1761 1762 1763
			if (except_anchor) {
				com_backpatch(c, except_anchor);
				com_addbyte(c, POP_TOP);
			}
Guido van Rossum's avatar
Guido van Rossum committed
1764 1765 1766 1767 1768
		}
		com_addbyte(c, END_FINALLY);
		com_backpatch(c, end_anchor);
	}
	if (finally_anchor) {
Guido van Rossum's avatar
Guido van Rossum committed
1769
		node *ch;
Guido van Rossum's avatar
Guido van Rossum committed
1770
		com_addbyte(c, POP_BLOCK);
1771 1772
		block_pop(c, SETUP_FINALLY);
		block_push(c, END_FINALLY);
Guido van Rossum's avatar
Guido van Rossum committed
1773 1774
		com_addoparg(c, LOAD_CONST, com_addconst(c, None));
		com_backpatch(c, finally_anchor);
Guido van Rossum's avatar
Guido van Rossum committed
1775 1776 1777
		ch = CHILD(n, NCH(n)-1);
		com_addoparg(c, SET_LINENO, ch->n_lineno);
		com_node(c, ch);
Guido van Rossum's avatar
Guido van Rossum committed
1778
		com_addbyte(c, END_FINALLY);
1779
		block_pop(c, END_FINALLY);
Guido van Rossum's avatar
Guido van Rossum committed
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
	}
}

static void
com_suite(c, n)
	struct compiling *c;
	node *n;
{
	REQ(n, suite);
	/* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
	if (NCH(n) == 1) {
		com_node(c, CHILD(n, 0));
	}
	else {
		int i;
		for (i = 0; i < NCH(n); i++) {
			node *ch = CHILD(n, i);
			if (TYPE(ch) == stmt)
				com_node(c, ch);
		}
	}
}

Guido van Rossum's avatar
Guido van Rossum committed
1803
/* ARGSUSED */
1804 1805 1806
static void
com_continue_stmt(c, n)
	struct compiling *c;
Guido van Rossum's avatar
Guido van Rossum committed
1807
	node *n; /* Not used, but passed for consistency */
1808 1809 1810 1811 1812 1813
{
	int i = c->c_nblocks;
	if (i-- > 0 && c->c_block[i] == SETUP_LOOP) {
		com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
	}
	else {
1814
		err_setstr(SyntaxError, "'continue' not properly in loop");
1815 1816 1817 1818 1819 1820
		c->c_errors++;
	}
	/* XXX Could allow it inside a 'finally' clause
	   XXX if we could pop the exception still on the stack */
}

Guido van Rossum's avatar
Guido van Rossum committed
1821 1822 1823 1824 1825 1826 1827
static void
com_funcdef(c, n)
	struct compiling *c;
	node *n;
{
	object *v;
	REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
1828
	v = (object *)_compile(n, c->c_filename, 0);
Guido van Rossum's avatar
Guido van Rossum committed
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
	if (v == NULL)
		c->c_errors++;
	else {
		int i = com_addconst(c, v);
		com_addoparg(c, LOAD_CONST, i);
		com_addbyte(c, BUILD_FUNCTION);
		com_addopname(c, STORE_NAME, CHILD(n, 1));
		DECREF(v);
	}
}

1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
static void
com_lambda(c, n)
	struct compiling *c;
	node *n;
{
	object *v;
	REQ(n, lambda_input);
	v = (object *)_compile(n, c->c_filename, 1);
	if (v == NULL)
		c->c_errors++;
	else {
		int i = com_addconst(c, v);
		DECREF(v);
		com_addoparg(c, LOAD_CONST, i);
		com_addbyte(c, BUILD_FUNCTION);
		com_addbyte(c, RETURN_VALUE);
	}
}

1859
static void
1860
com_bases(c, n)
1861 1862 1863
	struct compiling *c;
	node *n;
{
Guido van Rossum's avatar
Guido van Rossum committed
1864
	int i;
1865 1866 1867 1868 1869 1870 1871
	REQ(n, testlist);
	/* testlist: test (',' test)* [','] */
	for (i = 0; i < NCH(n); i += 2)
		com_node(c, CHILD(n, i));
	com_addoparg(c, BUILD_TUPLE, (NCH(n)+1) / 2);
}

Guido van Rossum's avatar
Guido van Rossum committed
1872 1873 1874 1875 1876
static void
com_classdef(c, n)
	struct compiling *c;
	node *n;
{
1877
	int i;
1878
	object *v;
Guido van Rossum's avatar
Guido van Rossum committed
1879
	REQ(n, classdef);
1880 1881 1882 1883
	/* classdef: class NAME ['(' testlist ')'] ':' suite */
	if ((v = newstringobject(STR(CHILD(n, 1)))) == NULL) {
		c->c_errors++;
		return;
1884
	}
1885 1886 1887 1888 1889 1890 1891 1892 1893
	/* Push the class name on the stack */
	i = com_addconst(c, v);
	com_addoparg(c, LOAD_CONST, i);
	DECREF(v);
	/* Push the tuple of base classes on the stack */
	if (TYPE(CHILD(n, 2)) != LPAR)
		com_addoparg(c, BUILD_TUPLE, 0);
	else
		com_bases(c, CHILD(n, 3));
1894
	v = (object *)_compile(n, c->c_filename, 0);
1895 1896 1897
	if (v == NULL)
		c->c_errors++;
	else {
1898
		i = com_addconst(c, v);
1899 1900 1901 1902 1903 1904 1905
		com_addoparg(c, LOAD_CONST, i);
		com_addbyte(c, BUILD_FUNCTION);
		com_addbyte(c, UNARY_CALL);
		com_addbyte(c, BUILD_CLASS);
		com_addopname(c, STORE_NAME, CHILD(n, 1));
		DECREF(v);
	}
Guido van Rossum's avatar
Guido van Rossum committed
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
}

static void
com_node(c, n)
	struct compiling *c;
	node *n;
{
	switch (TYPE(n)) {
	
	/* Definition nodes */
	
	case funcdef:
		com_funcdef(c, n);
		break;
	case classdef:
		com_classdef(c, n);
		break;
	
	/* Trivial parse tree nodes */
	
	case stmt:
1927
	case small_stmt:
Guido van Rossum's avatar
Guido van Rossum committed
1928
	case flow_stmt:
Guido van Rossum's avatar
Guido van Rossum committed
1929 1930 1931 1932
		com_node(c, CHILD(n, 0));
		break;

	case simple_stmt:
1933 1934 1935 1936 1937 1938 1939 1940 1941
		/* small_stmt (';' small_stmt)* [';'] NEWLINE */
		com_addoparg(c, SET_LINENO, n->n_lineno);
		{
			int i;
			for (i = 0; i < NCH(n)-1; i += 2)
				com_node(c, CHILD(n, i));
		}
		break;
	
Guido van Rossum's avatar
Guido van Rossum committed
1942
	case compound_stmt:
Guido van Rossum's avatar
Guido van Rossum committed
1943
		com_addoparg(c, SET_LINENO, n->n_lineno);
Guido van Rossum's avatar
Guido van Rossum committed
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
		com_node(c, CHILD(n, 0));
		break;

	/* Statement nodes */
	
	case expr_stmt:
		com_expr_stmt(c, n);
		break;
	case print_stmt:
		com_print_stmt(c, n);
		break;
1955
	case del_stmt: /* 'del' exprlist */
Guido van Rossum's avatar
Guido van Rossum committed
1956 1957 1958 1959 1960
		com_assign(c, CHILD(n, 1), 0/*delete*/);
		break;
	case pass_stmt:
		break;
	case break_stmt:
Guido van Rossum's avatar
Guido van Rossum committed
1961
		if (c->c_loops == 0) {
1962
			err_setstr(SyntaxError, "'break' outside loop");
Guido van Rossum's avatar
Guido van Rossum committed
1963 1964
			c->c_errors++;
		}
Guido van Rossum's avatar
Guido van Rossum committed
1965 1966
		com_addbyte(c, BREAK_LOOP);
		break;
1967 1968 1969
	case continue_stmt:
		com_continue_stmt(c, n);
		break;
Guido van Rossum's avatar
Guido van Rossum committed
1970 1971 1972 1973 1974 1975 1976 1977 1978
	case return_stmt:
		com_return_stmt(c, n);
		break;
	case raise_stmt:
		com_raise_stmt(c, n);
		break;
	case import_stmt:
		com_import_stmt(c, n);
		break;
1979 1980 1981
	case global_stmt:
		com_global_stmt(c, n);
		break;
1982 1983 1984
	case access_stmt:
		com_access_stmt(c, n);
		break;
1985 1986 1987
	case exec_stmt:
		com_exec_stmt(c, n);
		break;
Guido van Rossum's avatar
Guido van Rossum committed
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
	case if_stmt:
		com_if_stmt(c, n);
		break;
	case while_stmt:
		com_while_stmt(c, n);
		break;
	case for_stmt:
		com_for_stmt(c, n);
		break;
	case try_stmt:
		com_try_stmt(c, n);
		break;
	case suite:
		com_suite(c, n);
		break;
	
	/* Expression nodes */
	
	case testlist:
Guido van Rossum's avatar
Guido van Rossum committed
2007
		com_list(c, n, 0);
Guido van Rossum's avatar
Guido van Rossum committed
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
		break;
	case test:
		com_test(c, n);
		break;
	case and_test:
		com_and_test(c, n);
		break;
	case not_test:
		com_not_test(c, n);
		break;
	case comparison:
		com_comparison(c, n);
		break;
	case exprlist:
Guido van Rossum's avatar
Guido van Rossum committed
2022
		com_list(c, n, 0);
Guido van Rossum's avatar
Guido van Rossum committed
2023 2024 2025 2026
		break;
	case expr:
		com_expr(c, n);
		break;
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
	case xor_expr:
		com_xor_expr(c, n);
		break;
	case and_expr:
		com_and_expr(c, n);
		break;
	case shift_expr:
		com_shift_expr(c, n);
		break;
	case arith_expr:
		com_arith_expr(c, n);
		break;
Guido van Rossum's avatar
Guido van Rossum committed
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
	case term:
		com_term(c, n);
		break;
	case factor:
		com_factor(c, n);
		break;
	case atom:
		com_atom(c, n);
		break;
	
	default:
		fprintf(stderr, "node type %d\n", TYPE(n));
		err_setstr(SystemError, "com_node: unexpected node type");
		c->c_errors++;
	}
}

static void com_fplist PROTO((struct compiling *, node *));

static void
com_fpdef(c, n)
	struct compiling *c;
	node *n;
{
	REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */
	if (TYPE(CHILD(n, 0)) == LPAR)
		com_fplist(c, CHILD(n, 1));
	else
		com_addopname(c, STORE_NAME, CHILD(n, 0));
}

static void
com_fplist(c, n)
	struct compiling *c;
	node *n;
{
Guido van Rossum's avatar
Guido van Rossum committed
2075
	REQ(n, fplist); /* fplist: fpdef (',' fpdef)* [','] */
Guido van Rossum's avatar
Guido van Rossum committed
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
	if (NCH(n) == 1) {
		com_fpdef(c, CHILD(n, 0));
	}
	else {
		int i;
		com_addoparg(c, UNPACK_TUPLE, (NCH(n)+1)/2);
		for (i = 0; i < NCH(n); i += 2)
			com_fpdef(c, CHILD(n, i));
	}
}

Guido van Rossum's avatar
Guido van Rossum committed
2087 2088 2089 2090 2091 2092 2093
static void
com_arglist(c, n)
	struct compiling *c;
	node *n;
{
	int i, nargs, op;
	REQ(n, varargslist);
2094
	/* varargslist:
2095
	   (fpdef ',')* '*' NAME | fpdef (',' fpdef)* [','] */
Guido van Rossum's avatar
Guido van Rossum committed
2096 2097 2098
	op = UNPACK_ARG;
	nargs = (NCH(n) + 1) / 2;
	for (i = 0; i < NCH(n); i += 2) {
2099
		int t = TYPE(CHILD(n, i));
2100
		if (t == STAR) {
Guido van Rossum's avatar
Guido van Rossum committed
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
			op = UNPACK_VARARG;
			nargs = i/2;
			break;
		}
	}
	com_addoparg(c, op, nargs);
	for (i = 0; i < 2*nargs; i += 2)
		com_fpdef(c, CHILD(n, i));
	if (op == UNPACK_VARARG)
		com_addopname(c, STORE_NAME, CHILD(n, 2*nargs+1));
}

Guido van Rossum's avatar
Guido van Rossum committed
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
static void
com_file_input(c, n)
	struct compiling *c;
	node *n;
{
	int i;
	REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */
	for (i = 0; i < NCH(n); i++) {
		node *ch = CHILD(n, i);
		if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE)
			com_node(c, ch);
	}
}

/* Top-level compile-node interface */

static void
compile_funcdef(c, n)
	struct compiling *c;
	node *n;
{
	node *ch;
	REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
2136
	c->c_name = STR(CHILD(n, 1));
2137
	com_addoparg(c, RESERVE_FAST, com_addconst(c, None)); /* Patched! */
Guido van Rossum's avatar
Guido van Rossum committed
2138 2139
	ch = CHILD(n, 2); /* parameters: '(' [varargslist] ')' */
	ch = CHILD(ch, 1); /* ')' | varargslist */
Guido van Rossum's avatar
Guido van Rossum committed
2140
	if (TYPE(ch) == RPAR)
Guido van Rossum's avatar
Guido van Rossum committed
2141
		com_addoparg(c, UNPACK_ARG, 0);
Guido van Rossum's avatar
Guido van Rossum committed
2142 2143
	else
		com_arglist(c, ch);
Guido van Rossum's avatar
Guido van Rossum committed
2144
	c->c_infunction = 1;
Guido van Rossum's avatar
Guido van Rossum committed
2145
	com_node(c, CHILD(n, 4));
Guido van Rossum's avatar
Guido van Rossum committed
2146
	c->c_infunction = 0;
Guido van Rossum's avatar
Guido van Rossum committed
2147 2148 2149 2150
	com_addoparg(c, LOAD_CONST, com_addconst(c, None));
	com_addbyte(c, RETURN_VALUE);
}

2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
static void
compile_lambda(c, n)
	struct compiling *c;
	node *n;
{
	REQ(n, lambda_input)
	com_arglist(c, CHILD(n, 0));
	com_node(c, CHILD(n, 2));
	com_addbyte(c, RETURN_VALUE);
}

Guido van Rossum's avatar
Guido van Rossum committed
2162 2163 2164 2165 2166
static void
compile_node(c, n)
	struct compiling *c;
	node *n;
{
Guido van Rossum's avatar
Guido van Rossum committed
2167 2168
	com_addoparg(c, SET_LINENO, n->n_lineno);
	
Guido van Rossum's avatar
Guido van Rossum committed
2169 2170
	switch (TYPE(n)) {
	
2171
	case single_input: /* One interactive command */
Guido van Rossum's avatar
Guido van Rossum committed
2172 2173 2174 2175
		/* NEWLINE | simple_stmt | compound_stmt NEWLINE */
		n = CHILD(n, 0);
		if (TYPE(n) != NEWLINE)
			com_node(c, n);
Guido van Rossum's avatar
Guido van Rossum committed
2176 2177
		com_addoparg(c, LOAD_CONST, com_addconst(c, None));
		com_addbyte(c, RETURN_VALUE);
Guido van Rossum's avatar
Guido van Rossum committed
2178 2179
		break;
	
2180
	case file_input: /* A whole file, or built-in function exec() */
Guido van Rossum's avatar
Guido van Rossum committed
2181
		com_file_input(c, n);
Guido van Rossum's avatar
Guido van Rossum committed
2182 2183
		com_addoparg(c, LOAD_CONST, com_addconst(c, None));
		com_addbyte(c, RETURN_VALUE);
Guido van Rossum's avatar
Guido van Rossum committed
2184 2185
		break;
	
2186 2187
	case lambda_input: /* Built-in function lambda() */
		(c->c_inlambda ? compile_lambda : com_lambda)(c, n);
Guido van Rossum's avatar
Guido van Rossum committed
2188 2189
		break;
	
2190
	case eval_input: /* Built-in functions eval() and input() */
Guido van Rossum's avatar
Guido van Rossum committed
2191
		com_node(c, CHILD(n, 0));
Guido van Rossum's avatar
Guido van Rossum committed
2192
		com_addbyte(c, RETURN_VALUE);
Guido van Rossum's avatar
Guido van Rossum committed
2193 2194
		break;
	
2195
	case funcdef: /* A function definition */
Guido van Rossum's avatar
Guido van Rossum committed
2196 2197 2198
		compile_funcdef(c, n);
		break;
	
2199
	case classdef: /* A class definition */
2200 2201
		/* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
		c->c_name = STR(CHILD(n, 1));
2202
		com_node(c, CHILD(n, NCH(n)-1)); /* The suite */
Guido van Rossum's avatar
Guido van Rossum committed
2203 2204
		com_addbyte(c, LOAD_LOCALS);
		com_addbyte(c, RETURN_VALUE);
2205 2206
		break;
	
Guido van Rossum's avatar
Guido van Rossum committed
2207 2208 2209 2210 2211 2212 2213
	default:
		fprintf(stderr, "node type %d\n", TYPE(n));
		err_setstr(SystemError, "compile_node: unexpected node type");
		c->c_errors++;
	}
}

2214
/* Optimization for local variables in functions (and *only* functions).
2215

2216 2217 2218 2219
   This replaces all LOAD_NAME, STORE_NAME and DELETE_NAME
   instructions that refer to local variables with LOAD_FAST etc.
   The latter instructions are much faster because they don't need to
   look up the variable name in a dictionary.
2220 2221 2222 2223
   
   To find all local variables, we check all STORE_NAME and IMPORT_FROM
   instructions.  This yields all local variables, including arguments,
   function definitions, class definitions and import statements.
2224 2225
   (We don't check DELETE_NAME instructions, since if there's no
   STORE_NAME the DELETE_NAME will surely fail.)
2226
   
2227 2228
   There is one problem: 'from foo import *' introduces local variables
   that we can't know while compiling.  If this is the case, wo don't
2229 2230
   optimize at all (this rarely happens, since this form of import
   statement is mostly used at the module level).
2231 2232 2233 2234 2235

   Note that, because of this optimization, code like the following
   won't work:
	eval('x = 1')
	print x
2236 2237 2238 2239 2240
   
   NB: this modifies the string object co->co_code!
*/

static void
2241 2242
optimize(c)
	struct compiling *c;
2243
{
2244
	unsigned char *next_instr, *cur_instr;
2245
	object *locals;
2246
	int nlocals;
2247 2248 2249
	int opcode;
	int oparg;
	object *name;
2250 2251 2252
	int fast_reserved;
	object *error_type, *error_value;
	
2253 2254 2255
#define NEXTOP()	(*next_instr++)
#define NEXTARG()	(next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
#define GETITEM(v, i)	(getlistitem((v), (i)))
2256 2257
#define GETNAMEOBJ(i)	(GETITEM(c->c_names, (i)))
	
2258 2259
	locals = newdictobject();
	if (locals == NULL) {
2260 2261
		c->c_errors++;
		return;
2262
	}
2263 2264 2265
	nlocals = 0;

	err_get(&error_type, &error_value);
2266
	
2267
	next_instr = (unsigned char *) getstringvalue(c->c_code);
2268 2269 2270 2271
	for (;;) {
		opcode = NEXTOP();
		if (opcode == STOP_CODE)
			break;
2272 2273
		if (opcode == EXEC_STMT)
			goto end; /* Don't optimize if exec present */
2274 2275
		if (HAS_ARG(opcode))
			oparg = NEXTARG();
2276 2277 2278
		if (opcode == STORE_NAME || opcode == DELETE_NAME ||
		    opcode == IMPORT_FROM) {
			object *v;
2279
			name = GETNAMEOBJ(oparg);
2280 2281 2282 2283 2284 2285 2286
			if (dict2lookup(locals, name) != NULL)
				continue;
			err_clear();
			v = newintobject(nlocals);
			if (v == NULL) {
				c->c_errors++;
				goto err;
2287
			}
2288 2289 2290 2291 2292 2293 2294
			nlocals++;
			if (dict2insert(locals, name, v) != 0) {
				DECREF(v);
				c->c_errors++;
				goto err;
			}
			DECREF(v);
2295 2296 2297
		}
	}
	
2298 2299 2300 2301 2302 2303 2304
	if (nlocals == 0 || dictlookup(locals, "*") != NULL) {
		/* Don't optimize anything */
		goto end;
	}
	
	next_instr = (unsigned char *) getstringvalue(c->c_code);
	fast_reserved = 0;
2305 2306 2307 2308 2309 2310 2311
	for (;;) {
		cur_instr = next_instr;
		opcode = NEXTOP();
		if (opcode == STOP_CODE)
			break;
		if (HAS_ARG(opcode))
			oparg = NEXTARG();
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
		if (opcode == RESERVE_FAST) {
			int i = com_addconst(c, locals);
			cur_instr[1] = i & 0xff;
			cur_instr[2] = (i>>8) & 0xff;
			fast_reserved = 1;
			continue;
		}
		if (!fast_reserved)
			continue;
		if (opcode == LOAD_NAME ||
		    opcode == STORE_NAME ||
		    opcode == DELETE_NAME) {
			object *v;
			int i;
2326
			name = GETNAMEOBJ(oparg);
2327 2328
			v = dict2lookup(locals, name);
			if (v == NULL) {
2329
				err_clear();
2330
				continue;
2331
			}
2332 2333 2334 2335 2336 2337 2338 2339
			i = getintvalue(v);
			switch (opcode) {
			case LOAD_NAME: cur_instr[0] = LOAD_FAST; break;
			case STORE_NAME: cur_instr[0] = STORE_FAST; break;
			case DELETE_NAME: cur_instr[0] = DELETE_FAST; break;
			}
			cur_instr[1] = i & 0xff;
			cur_instr[2] = (i>>8) & 0xff;
2340 2341
		}
	}
2342 2343 2344 2345

 end:
	err_setval(error_type, error_value);
 err:
2346 2347 2348
	DECREF(locals);
}

Guido van Rossum's avatar
Guido van Rossum committed
2349
codeobject *
2350
_compile(n, filename, inlambda)
Guido van Rossum's avatar
Guido van Rossum committed
2351
	node *n;
Guido van Rossum's avatar
Guido van Rossum committed
2352
	char *filename;
2353
	int inlambda;
Guido van Rossum's avatar
Guido van Rossum committed
2354 2355 2356
{
	struct compiling sc;
	codeobject *co;
2357
	if (!com_init(&sc, filename, inlambda))
Guido van Rossum's avatar
Guido van Rossum committed
2358 2359 2360
		return NULL;
	compile_node(&sc, n);
	com_done(&sc);
2361 2362
	if (TYPE(n) == funcdef && sc.c_errors == 0)
		optimize(&sc);
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
	co = NULL;
	if (sc.c_errors == 0) {
		object *v, *w;
		v = newstringobject(sc.c_filename);
		w = newstringobject(sc.c_name);
		if (v != NULL && w != NULL)
			co = newcodeobject(sc.c_code, sc.c_consts,
					   sc.c_names, v, w);
		XDECREF(v);
		XDECREF(w);
2373
	}
Guido van Rossum's avatar
Guido van Rossum committed
2374 2375 2376
	com_free(&sc);
	return co;
}