scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | README | LICENSE

lex.c (14078B)


      1 static char sccsid[] = "@(#) ./cc1/lex.c";
      2 #include <assert.h>
      3 #include <ctype.h>
      4 #include <errno.h>
      5 #include <limits.h>
      6 #include <setjmp.h>
      7 #include <stdio.h>
      8 #include <stdlib.h>
      9 #include <string.h>
     10 
     11 #include <scc/cstd.h>
     12 #include <scc/scc.h>
     13 #include "cc1.h"
     14 
     15 int yytoken;
     16 struct yystype yylval;
     17 char yytext[STRINGSIZ+3];
     18 unsigned short yylen;
     19 int lexmode = CCMODE;
     20 unsigned lineno;
     21 char filenam[FILENAME_MAX];
     22 
     23 int namespace = NS_IDEN;
     24 static int safe;
     25 Input *input;
     26 
     27 void
     28 ilex(void)
     29 {
     30 	static struct keyword keys[] = {
     31 		{"auto", SCLASS, AUTO},
     32 		{"break", BREAK, BREAK},
     33 		{"_Bool", TYPE, BOOL},
     34 		{"__builtin_va_list", TYPE, VA_LIST},
     35 		{"case", CASE, CASE},
     36 		{"char", TYPE, CHAR},
     37 		{"const", TQUALIFIER, CONST},
     38 		{"continue", CONTINUE, CONTINUE},
     39 		{"default", DEFAULT, DEFAULT},
     40 		{"do", DO, DO},
     41 		{"double", TYPE, DOUBLE},
     42 		{"else", ELSE, ELSE},
     43 		{"enum", TYPE, ENUM},
     44 		{"extern", SCLASS, EXTERN},
     45 		{"float", TYPE, FLOAT},
     46 		{"for", FOR, FOR},
     47 		{"goto", GOTO, GOTO},
     48 		{"if", IF, IF},
     49 		{"inline", TQUALIFIER, INLINE},
     50 		{"int", TYPE, INT},
     51 		{"long", TYPE, LONG},
     52 		{"register", SCLASS, REGISTER},
     53 		{"restrict", TQUALIFIER, RESTRICT},
     54 		{"return", RETURN, RETURN},
     55 		{"short", TYPE, SHORT},
     56 		{"signed", TYPE, SIGNED},
     57 		{"sizeof", SIZEOF, SIZEOF},
     58 		{"static", SCLASS, STATIC},
     59 		{"struct", TYPE, STRUCT},
     60 		{"switch", SWITCH, SWITCH},
     61 		{"typedef", SCLASS, TYPEDEF},
     62 		{"union", TYPE, UNION},
     63 		{"unsigned", TYPE, UNSIGNED},
     64 		{"void", TYPE, VOID},
     65 		{"volatile", TQUALIFIER, VOLATILE},
     66 		{"while", WHILE, WHILE},
     67 		{NULL, 0, 0},
     68 	};
     69 	keywords(keys, NS_KEYWORD);
     70 }
     71 
     72 void
     73 setloc(char *fname, unsigned line)
     74 {
     75 	size_t len;
     76 
     77 	if ((len = strlen(fname)) >= FILENAME_MAX)
     78 		die("cc1: %s: file name too long", fname);
     79 	memmove(filenam, fname, len);
     80 	filenam[len] = '\0';
     81 
     82 	free(input->filenam);
     83 	input->filenam = xstrdup(fname);
     84 	lineno = input->lineno = line;
     85 }
     86 
     87 void
     88 addinput(char *fname, Symbol *hide, char *buffer)
     89 {
     90 	FILE *fp;
     91 	char *extp;
     92 	unsigned flags;
     93 	int infileln;
     94 	Input *newip, *curip = input;
     95 
     96 	if (hide) {
     97 		/* this is a macro expansion */
     98 		fp = NULL;
     99 		if (hide->hide == UCHAR_MAX)
    100 			die("cc1: too many macro expansions");
    101 		++hide->hide;
    102 		flags = IMACRO;
    103 	} else  if (fname) {
    104 		/* a new file */
    105 		if ((fp = fopen(fname, "r")) == NULL)
    106 			die("cc1: %s: %s", fname, strerror(errno));
    107 		flags = IFILE;
    108 		if (curip && onlyheader) {
    109 			infileln = strlen(infile);
    110 			if (extp = strrchr(infile, '.'))
    111 				infileln -= strlen(extp);
    112 			printf("%.*s.o: %s %s\n",
    113 			       infileln, infile, infile, fname);
    114 		}
    115 	} else {
    116 		/* reading from stdin */
    117 		fp = stdin;
    118 		fname = "<stdin>";
    119 		flags = ISTDIN;
    120 	}
    121 
    122 	newip = xmalloc(sizeof(*newip));
    123 
    124 	if (!buffer) {
    125 		buffer = xmalloc(INPUTSIZ);
    126 		buffer[0] = '\0';
    127 	}
    128 
    129 	if (curip)
    130 		curip->lineno = lineno;
    131 
    132 	newip->p = newip->begin = newip->line = buffer;
    133 	newip->filenam = NULL;
    134 	newip->lineno = 0;
    135 	newip->next = curip;
    136 	newip->fp = fp;
    137 	newip->hide = hide;
    138 	newip->flags = flags;
    139 	input = newip;
    140 
    141 	setloc(fname, (curip) ? curip->lineno : newip->lineno);
    142 }
    143 
    144 void
    145 delinput(void)
    146 {
    147 	Input *ip = input;
    148 	Symbol *hide = ip->hide;
    149 
    150 	switch (ip->flags & ITYPE) {
    151 	case IFILE:
    152 		if (fclose(ip->fp))
    153 			die("cc1: %s: %s", ip->filenam, strerror(errno));
    154 		break;
    155 	case IMACRO:
    156 		assert(hide->hide == 1);
    157 		--hide->hide;
    158 		break;
    159 	}
    160 	input = ip->next;
    161 	free(ip->filenam);
    162 	free(ip->line);
    163 	if (input) {
    164 		lineno = input->lineno;
    165 		strcpy(filenam, input->filenam);
    166 	}
    167 }
    168 
    169 static void
    170 newline(void)
    171 {
    172 	if (++lineno == 0)
    173 		die("cc1: %s: file too long", filenam);
    174 }
    175 
    176 /*
    177  * Read the next character from the input file, counting number of lines
    178  * and joining lines escaped with \
    179  */
    180 static int
    181 readchar(void)
    182 {
    183 	FILE *fp = input->fp;
    184 	int c;
    185 
    186 repeat:
    187 	switch (c = getc(fp)) {
    188 	case '\\':
    189 		if ((c = getc(fp)) == '\n') {
    190 			newline();
    191 			goto repeat;
    192 		}
    193 		ungetc(c, fp);
    194 		c = '\\';
    195 		break;
    196 	case '\n':
    197 		newline();
    198 		break;
    199 	default:
    200 		if (!isprint(c) && !ispunct(c) && !isspace(c))
    201 			warn("invalid input character. The shame of UB is yours");
    202 		break;
    203 	}
    204 
    205 	return c;
    206 }
    207 
    208 /*
    209  * discard a C comment. This function is only called from readline
    210  * because it is impossible to have a comment in a macro, because
    211  * comments are always discarded before processing any cpp directive
    212  */
    213 static void
    214 comment(int type)
    215 {
    216 	int c;
    217 
    218 repeat:
    219 	while ((c = readchar()) != EOF && c != type)
    220 		;
    221 
    222 	if (c == EOF) {
    223 		errorp("unterminated comment");
    224 		return;
    225 	}
    226 
    227 	if (type == '*' && (c = readchar()) != '/')
    228 		goto repeat;
    229 }
    230 
    231 /*
    232  * readline is used to read a full logic line from a file.
    233  * It discards comments and check that the line fits in
    234  * the input buffer
    235  */
    236 static int
    237 readline(void)
    238 {
    239 	char *bp, *lim;
    240 	int c, peekc = 0;
    241 
    242 	if (feof(input->fp)) {
    243 		input->flags |= IEOF;
    244 		return 0;
    245 	}
    246 
    247 	*input->line = '\0';
    248 	lim = &input->line[INPUTSIZ-1];
    249 	for (bp = input->line; bp < lim-1; *bp++ = c) {
    250 		c = (peekc) ? peekc : readchar();
    251 		peekc = 0;
    252 		if (c == '\n' || c == EOF)
    253 			break;
    254 		if (c != '/')
    255 			continue;
    256 
    257 		/* check for /* or // */
    258 		peekc = readchar();
    259 		if (peekc != '*' && peekc != '/')
    260 			continue;
    261 		comment((peekc == '/') ? '\n' : '*');
    262 		peekc = 0;
    263 		c = ' ';
    264 	}
    265 
    266 	input->begin = input->p = input->line;
    267 	if (bp == lim-1) {
    268 		errorp("line too long");
    269 		--bp;
    270 	}
    271 	*bp++ = '\n';
    272 	*bp = '\0';
    273 
    274 	return 1;
    275 }
    276 
    277 /*
    278  * moreinput gets more bytes to be passed to the lexer.
    279  * It can take more bytes from macro expansions or
    280  * directly reading from files. When a cpp directive
    281  * is processed the line is discarded because it must not
    282  * be passed to the lexer
    283  */
    284 static int
    285 moreinput(void)
    286 {
    287 	int wasexpand = 0;
    288 
    289 repeat:
    290 	if (!input)
    291 		return 0;
    292 
    293 	if (*input->p == '\0') {
    294 		if ((input->flags&ITYPE) == IMACRO) {
    295 			wasexpand = 1;
    296 			input->flags |= IEOF;
    297 		}
    298 		if (input->flags & IEOF) {
    299 			delinput();
    300 			goto repeat;
    301 		}
    302 		if (!readline() || cpp()) {
    303 			*input->p = '\0';
    304 			goto repeat;
    305 		}
    306 	}
    307 
    308 	if (onlycpp && !wasexpand)
    309 		ppragmaln();
    310 	return 1;
    311 }
    312 
    313 static void
    314 tok2str(void)
    315 {
    316 	if ((yylen = input->p - input->begin) > INTIDENTSIZ)
    317 		error("token too big");
    318 	memcpy(yytext, input->begin, yylen);
    319 	yytext[yylen] = '\0';
    320 	input->begin = input->p;
    321 }
    322 
    323 static Symbol *
    324 readint(char *s, int base, int sign, Symbol *sym)
    325 {
    326 	Type *tp = sym->type;
    327 	struct limits *lim;
    328 	TUINT u, val, max;
    329 	int c;
    330 
    331 	lim = getlimits(tp);
    332 	max = lim->max.i;
    333 	if (*s == '0')
    334 		++s;
    335 	if (toupper(*s) == 'X')
    336 		++s;
    337 
    338 	for (u = 0; isxdigit(c = *s++); u = u*base + val) {
    339 		static char letters[] = "0123456789ABCDEF";
    340 		val = strchr(letters, toupper(c)) - letters;
    341 	repeat:
    342 		if (u <= max/base && u*base <= max - val)
    343 			continue;
    344 		if (tp->prop & TSIGNED) {
    345 			if (tp == inttype)
    346 				tp = (base==10) ? longtype : uinttype;
    347 			else if (tp == longtype)
    348 				tp = (base==10) ? llongtype : ulongtype;
    349 			else
    350 				goto overflow;
    351 		} else {
    352 			if (tp == uinttype)
    353 				tp = (sign==UNSIGNED) ? ulongtype : longtype;
    354 			else if (tp == ulongtype)
    355 				tp = (sign==UNSIGNED) ? ullongtype : llongtype;
    356 			else
    357 				goto overflow;
    358 		}
    359 		sym->type = tp;
    360 		lim = getlimits(tp);
    361 		max = lim->max.i;
    362 		goto repeat;
    363 	}
    364 
    365 	if (tp->prop & TSIGNED)
    366 		sym->u.i = u;
    367 	else
    368 		sym->u.u = u;
    369 
    370 	return sym;
    371 
    372 overflow:
    373 	errorp("overflow in integer constant");
    374 	return sym;
    375 }
    376 
    377 static int
    378 integer(char *s, int base)
    379 {
    380 	Type *tp;
    381 	Symbol *sym;
    382 	unsigned size, sign;
    383 
    384 	for (size = sign = 0; ; ++input->p) {
    385 		switch (toupper(*input->p)) {
    386 		case 'L':
    387 			if (size == LLONG)
    388 				goto wrong_type;
    389 			size = (size == LONG) ? LLONG : LONG;
    390 			continue;
    391 		case 'U':
    392 			if (sign == UNSIGNED)
    393 				goto wrong_type;
    394 			sign = UNSIGNED;
    395 			continue;
    396 		default:
    397 			goto convert;
    398 		wrong_type:
    399 			error("invalid suffix in integer constant");
    400 		}
    401 	}
    402 
    403 convert:
    404 	tp = ctype(INT, sign, size);
    405 	sym = newsym(NS_IDEN, NULL);
    406 	sym->type = tp;
    407 	sym->flags |= SCONSTANT;
    408 	yylval.sym = readint(s, base, sign, sym);
    409 	return CONSTANT;
    410 }
    411 
    412 static char *
    413 digits(int base)
    414 {
    415 	char *p;
    416 	int c;
    417 
    418 	for (p = input->p; c = *p; ++p) {
    419 		switch (base) {
    420 		case 8:
    421 			if (!strchr("01234567", c))
    422 				goto end;
    423 			break;
    424 		case 10:
    425 			if (!isdigit(c))
    426 				goto end;
    427 			break;
    428 		case 16:
    429 			if (!isxdigit(c))
    430 				goto end;
    431 			break;
    432 		}
    433 	}
    434 end:
    435 	input->p = p;
    436 	tok2str();
    437 	return yytext;
    438 }
    439 
    440 static int
    441 number(void)
    442 {
    443 	int base;
    444 
    445 	if (*input->p != '0') {
    446 		base = 10;
    447 	} else {
    448 		if (toupper(*++input->p) == 'X') {
    449 			++input->p;
    450 			base = 16;
    451 		} else {
    452 			base = 8;
    453 		}
    454 	}
    455 
    456 	return integer(digits(base), base);
    457 }
    458 
    459 static int
    460 escape(void)
    461 {
    462 	int c, base;
    463 
    464 	switch (*++input->p) {
    465 	case 'a':  return '\a';
    466 	case 'f':  return '\f';
    467 	case 'n':  return '\n';
    468 	case 'r':  return '\r';
    469 	case 't':  return '\t';
    470 	case 'v':  return '\v';
    471 	case '"':  return '"';
    472 	case '\'': return '\'';
    473 	case '\\': return '\\';
    474 	case '\?': return '\?';
    475 	case 'u':
    476 		/*
    477 		 * FIXME: universal constants are not correctly handled
    478 		 */
    479 		if (!isdigit(*++input->p))
    480 			warn("incorrect digit for numerical character constant");
    481 		base = 10;
    482 		break;
    483 	case 'x':
    484 		if (!isxdigit(*++input->p))
    485 			warn("\\x used with no following hex digits");
    486 		base = 16;
    487 		break;
    488 	case '0':
    489 		if (!strchr("01234567", *++input->p))
    490 			warn("\\0 used with no following octal digits");
    491 		base = 8;
    492 		break;
    493 	default:
    494 		warn("unknown escape sequence");
    495 		return ' ';
    496 	}
    497 	errno = 0;
    498 	c = strtoul(input->p, &input->p, base);
    499 	if (errno || c > 255)
    500 		warn("character constant out of range");
    501 	--input->p;
    502 	return c;
    503 }
    504 
    505 static int
    506 character(void)
    507 {
    508 	int c;
    509 	Symbol *sym;
    510 
    511 	if ((c = *++input->p) == '\\')
    512 		c = escape();
    513 	else
    514 		c = *input->p;
    515 	++input->p;
    516 	if (*input->p != '\'')
    517 		errorp("invalid character constant");
    518 	else
    519 		++input->p;
    520 
    521 	sym = newsym(NS_IDEN, NULL);
    522 	sym->u.i = c;
    523 	sym->type = inttype;
    524 	yylval.sym = sym;
    525 	tok2str();
    526 	return CONSTANT;
    527 }
    528 
    529 static int
    530 string(void)
    531 {
    532 	char *bp = yytext;
    533 	int c;
    534 
    535 	*bp++ = '"';
    536 	for (++input->p; (c = *input->p) != '"'; ++input->p) {
    537 		if (c == '\0') {
    538 			errorp("missing terminating '\"' character");
    539 			break;
    540 		}
    541 		if (c == '\\')
    542 			c = escape();
    543 		if (bp == &yytext[STRINGSIZ+1]) {
    544 			/* TODO: proper error handling here */
    545 			error("string too long");
    546 		}
    547 		*bp++ = c;
    548 	}
    549 
    550 	input->begin = ++input->p;
    551 	*bp = '\0';
    552 
    553 	yylen = bp - yytext + 1;
    554 	yylval.sym = newstring(yytext+1, yylen-1);
    555 	*bp++ = '"';
    556 	*bp = '\0';
    557 	return STRING;
    558 }
    559 
    560 static int
    561 iden(void)
    562 {
    563 	Symbol *sym;
    564 	char *p, *begin;
    565 
    566 	begin = input->p;
    567 	for (p = begin; isalnum(*p) || *p == '_'; ++p)
    568 		;
    569 	input->p = p;
    570 	tok2str();
    571 	if ((sym = lookup(NS_CPP, yytext, NOALLOC)) != NULL) {
    572 		if (!disexpand && !sym->hide && expand(begin, sym))
    573 			return next();
    574 	}
    575 	sym = lookup(namespace, yytext, ALLOC);
    576 	yylval.sym = sym;
    577 	if (sym->flags & SCONSTANT)
    578 		return CONSTANT;
    579 	if (sym->token != IDEN)
    580 		yylval.token = sym->u.token;
    581 	return sym->token;
    582 }
    583 
    584 static int
    585 follow(int expect, int ifyes, int ifno)
    586 {
    587 	if (*input->p++ == expect)
    588 		return ifyes;
    589 	--input->p;
    590 	return ifno;
    591 }
    592 
    593 static int
    594 minus(void)
    595 {
    596 	switch (*input->p++) {
    597 	case '-': return DEC;
    598 	case '>': return INDIR;
    599 	case '=': return SUB_EQ;
    600 	default: --input->p; return '-';
    601 	}
    602 }
    603 
    604 static int
    605 plus(void)
    606 {
    607 	switch (*input->p++) {
    608 	case '+': return INC;
    609 	case '=': return ADD_EQ;
    610 	default: --input->p; return '+';
    611 	}
    612 }
    613 
    614 static int
    615 relational(int op, int equal, int shift, int assig)
    616 {
    617 	int c;
    618 
    619 	if ((c = *input->p++) == '=')
    620 		return equal;
    621 	if (c == op)
    622 		return follow('=', assig, shift);
    623 	--input->p;
    624 	return op;
    625 }
    626 
    627 static int
    628 logic(int op, int equal, int logic)
    629 {
    630 	int c;
    631 
    632 	if ((c = *input->p++) == '=')
    633 		return equal;
    634 	if (c == op)
    635 		return logic;
    636 	--input->p;
    637 	return op;
    638 }
    639 
    640 static int
    641 dot(void)
    642 {
    643 	int c;
    644 
    645 	if ((c = *input->p) != '.')
    646 		return '.';
    647 	if ((c = *++input->p) != '.')
    648 		error("incorrect token '..'");
    649 	++input->p;
    650 	return ELLIPSIS;
    651 }
    652 
    653 static int
    654 operator(void)
    655 {
    656 	int t;
    657 
    658 	switch (t = *input->p++) {
    659 	case '<': t = relational('<', LE, SHL, SHL_EQ); break;
    660 	case '>': t = relational('>', GE, SHR, SHR_EQ); break;
    661 	case '&': t = logic('&', AND_EQ, AND); break;
    662 	case '|': t = logic('|', OR_EQ, OR); break;
    663 	case '=': t = follow('=', EQ, '='); break;
    664 	case '^': t = follow('=', XOR_EQ, '^'); break;
    665 	case '*': t = follow('=', MUL_EQ, '*'); break;
    666 	case '/': t = follow('=', DIV_EQ, '/'); break;
    667 	case '!': t = follow('=', NE, '!'); break;
    668 	case '#': t = follow('#', '$', '#'); break;
    669 	case '-': t = minus(); break;
    670 	case '+': t = plus(); break;
    671 	case '.': t = dot(); break;
    672 	}
    673 	tok2str();
    674 	return t;
    675 }
    676 
    677 /* TODO: Ensure that namespace is NS_IDEN after a recovery */
    678 
    679 /*
    680  * skip all the spaces until the next token. When we are in
    681  * CPPMODE \n is not considered a whitespace
    682  */
    683 static int
    684 skipspaces(void)
    685 {
    686 	int c;
    687 
    688 	for (;;) {
    689 		switch (c = *input->p) {
    690 		case '\n':
    691 			if (lexmode == CPPMODE)
    692 				goto return_byte;
    693 			++input->p;
    694 		case '\0':
    695 			if (!moreinput())
    696 				return EOF;
    697 			break;
    698 		case ' ':
    699 		case '\t':
    700 		case '\v':
    701 		case '\r':
    702 		case '\f':
    703 			++input->p;
    704 			break;
    705 		default:
    706 			goto return_byte;
    707 		}
    708 	}
    709 
    710 return_byte:
    711 	input->begin = input->p;
    712 	return c;
    713 }
    714 
    715 int
    716 next(void)
    717 {
    718 	int c;
    719 
    720 	if ((c = skipspaces()) == EOF)
    721 		yytoken = EOFTOK;
    722 	else if (isalpha(c) || c == '_')
    723 		yytoken = iden();
    724 	else if (isdigit(c))
    725 		yytoken = number();
    726 	else if (c == '"')
    727 		yytoken = string();
    728 	else if (c == '\'')
    729 		yytoken = character();
    730 	else
    731 		yytoken = operator();
    732 
    733 	if (yytoken == EOF) {
    734 		strcpy(yytext, "<EOF>");
    735 		if (cppctx)
    736 			errorp("#endif expected");
    737 	}
    738 
    739 	DBG("TOKEN %s", yytext);
    740 	return yytoken;
    741 }
    742 
    743 void
    744 expect(int tok)
    745 {
    746 	if (yytoken != tok) {
    747 		if (isgraph(tok))
    748 			errorp("expected '%c' before '%s'", tok, yytext);
    749 		else
    750 			errorp("unexpected '%s'", yytext);
    751 	} else {
    752 		next();
    753 	}
    754 }
    755 
    756 int
    757 ahead(void)
    758 {
    759 	skipspaces();
    760 	return *input->begin;
    761 }
    762 
    763 void
    764 setsafe(int type)
    765 {
    766 	safe = type;
    767 }
    768 
    769 void
    770 discard(void)
    771 {
    772 	extern jmp_buf recover;
    773 	int c;
    774 
    775 	input->begin = input->p;
    776 	for (c = yytoken; ; c = *input->begin++) {
    777 		switch (safe) {
    778 		case END_COMP:
    779 			if (c == '}')
    780 				goto jump;
    781 			goto semicolon;
    782 		case END_COND:
    783 			if (c == ')')
    784 				goto jump;
    785 			break;
    786 		case END_LDECL:
    787 			if (c == ',')
    788 				goto jump;
    789 		case END_DECL:
    790 		semicolon:
    791 			if (c == ';')
    792 				goto jump;
    793 			break;
    794 		}
    795 		if (c == '\0' && !moreinput())
    796 			exit(1);
    797 	}
    798 jump:
    799 	yytoken = c;
    800 	longjmp(recover, 1);
    801 }