Add "stream_name()" helper function, and use it.
[smatch.git] / tokenize.c
blobad52189723960a921d79d50052ebd99c4e5c46e4
1 /*
2 * This is a really stupid C tokenizer. It doesn't do any include
3 * files or anything complex at all. That's the pre-processor.
5 * Copyright (C) 2003 Transmeta Corp.
6 * 2003 Linus Torvalds
8 * Licensed under the Open Software License version 1.1
9 */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <stdarg.h>
13 #include <stddef.h>
14 #include <string.h>
15 #include <ctype.h>
16 #include <unistd.h>
18 #include "lib.h"
19 #include "allocate.h"
20 #include "token.h"
21 #include "symbol.h"
23 #define EOF (-1)
25 int input_stream_nr = 0;
26 struct stream *input_streams;
27 static int input_streams_allocated;
29 #define BUFSIZE (8192)
31 typedef struct {
32 int fd, offset, size;
33 int pos, line, nr;
34 int newline, whitespace;
35 struct token **tokenlist;
36 struct token *token;
37 unsigned char *buffer;
38 } stream_t;
40 const char *stream_name(int stream)
42 if (stream < 0 || stream > input_stream_nr)
43 return "<bad stream>";
44 return input_streams[stream].name;
47 struct position stream_pos(stream_t *stream)
49 struct position pos;
50 pos.type = 0;
51 pos.stream = stream->nr;
52 pos.newline = stream->newline;
53 pos.whitespace = stream->whitespace;
54 pos.pos = stream->pos;
55 pos.line = stream->line;
56 pos.noexpand = 0;
57 return pos;
60 const char *show_special(int val)
62 static const char *combinations[] = COMBINATION_STRINGS;
63 static char buffer[4];
65 buffer[0] = val;
66 buffer[1] = 0;
67 if (val >= SPECIAL_BASE)
68 strcpy(buffer, combinations[val - SPECIAL_BASE]);
69 return buffer;
72 const char *show_ident(const struct ident *ident)
74 static char buffer[256];
75 if (!ident)
76 return "<noident>";
77 sprintf(buffer, "%.*s", ident->len, ident->name);
78 return buffer;
81 char *charstr(char *ptr, unsigned char c, unsigned char escape, unsigned char next)
83 if (isprint(c)) {
84 if (c == escape || c == '\\')
85 *ptr++ = '\\';
86 *ptr++ = c;
87 return ptr;
89 *ptr++ = '\\';
90 switch (c) {
91 case '\n':
92 *ptr++ = 'n';
93 return ptr;
94 case '\t':
95 *ptr++ = 't';
96 return ptr;
98 if (!isdigit(next))
99 return ptr + sprintf(ptr, "%o", c);
101 return ptr + sprintf(ptr, "%03o", c);
104 const char *show_string(const struct string *string)
106 static char buffer[4 * MAX_STRING + 3];
107 char *ptr;
108 int i;
110 if (!string->length)
111 return "<bad_string>";
112 ptr = buffer;
113 *ptr++ = '"';
114 for (i = 0; i < string->length-1; i++) {
115 const unsigned char *p = string->data + i;
116 ptr = charstr(ptr, p[0], '"', p[1]);
118 *ptr++ = '"';
119 *ptr = '\0';
120 return buffer;
123 const char *show_token(const struct token *token)
125 static char buffer[256];
127 if (!token)
128 return "<no token>";
129 switch (token_type(token)) {
130 case TOKEN_ERROR:
131 return "syntax error";
133 case TOKEN_EOF:
134 return "end-of-input";
136 case TOKEN_IDENT:
137 return show_ident(token->ident);
139 case TOKEN_STRING:
140 return show_string(token->string);
142 case TOKEN_NUMBER:
143 return token->number;
145 case TOKEN_SPECIAL:
146 return show_special(token->special);
148 case TOKEN_CHAR: {
149 char *ptr = buffer;
150 int c = token->character;
151 *ptr++ = '\'';
152 ptr = charstr(ptr, c, '\'', 0);
153 *ptr++ = '\'';
154 *ptr++ = '\0';
155 return buffer;
158 case TOKEN_STREAMBEGIN:
159 sprintf(buffer, "<beginning of '%s'>", stream_name(token->pos.stream));
160 return buffer;
162 case TOKEN_STREAMEND:
163 sprintf(buffer, "<end of '%s'>", stream_name(token->pos.stream));
164 return buffer;
166 default:
167 return "WTF???";
171 int init_stream(const char *name, int fd, const char **next_path)
173 int stream = input_stream_nr;
174 struct stream *current;
176 if (stream >= input_streams_allocated) {
177 int newalloc = stream * 4 / 3 + 10;
178 input_streams = realloc(input_streams, newalloc * sizeof(struct stream));
179 if (!input_streams)
180 die("Unable to allocate more streams space");
181 input_streams_allocated = newalloc;
183 current = input_streams + stream;
184 memset(current, 0, sizeof(*current));
185 current->name = name;
186 current->fd = fd;
187 current->next_path = next_path;
188 current->constant = CONSTANT_FILE_MAYBE;
189 input_stream_nr = stream+1;
190 return stream;
193 static struct token * alloc_token(stream_t *stream)
195 struct token *token = __alloc_token(0);
196 token->pos = stream_pos(stream);
197 return token;
201 * Argh... That was surprisingly messy - handling '\r' complicates the
202 * things a _lot_.
204 static int nextchar_slow(stream_t *stream)
206 int offset = stream->offset;
207 int size = stream->size;
208 int c;
209 int spliced = 0, had_cr, had_backslash, complain;
211 restart:
212 had_cr = had_backslash = complain = 0;
214 repeat:
215 if (offset >= size) {
216 size = read(stream->fd, stream->buffer, BUFSIZE);
217 if (size <= 0)
218 goto got_eof;
219 stream->size = size;
220 stream->offset = offset = 0;
223 c = stream->buffer[offset++];
225 if (had_cr && c != '\n')
226 complain = 1;
228 if (c == '\r') {
229 had_cr = 1;
230 goto repeat;
233 stream->pos++;
235 if (c == '\n') {
236 stream->line++;
237 stream->pos = 0;
240 if (!had_backslash) {
241 if (c == '\\') {
242 had_backslash = 1;
243 goto repeat;
245 if (c == '\n')
246 stream->newline = 1;
247 } else {
248 if (c == '\n') {
249 if (complain)
250 warning(stream_pos(stream), "non-ASCII data stream");
251 spliced = 1;
252 goto restart;
254 stream->pos--;
255 offset--;
256 c = '\\';
259 out:
260 stream->offset = offset;
261 if (complain)
262 warning(stream_pos(stream), "non-ASCII data stream");
264 return c;
266 got_eof:
267 if (had_backslash) {
268 c = '\\';
269 goto out;
271 if (stream->pos)
272 warning(stream_pos(stream), "no newline at end of file");
273 else if (had_cr)
274 warning(stream_pos(stream), "non-ASCII data stream");
275 else if (spliced)
276 warning(stream_pos(stream), "backslash-newline at end of file");
277 return EOF;
281 * We want that as light as possible while covering all normal cases.
282 * Slow path (including the logics with line-splicing and EOF sanity
283 * checks) is in nextchar_slow().
285 static int nextchar(stream_t *stream)
287 int offset = stream->offset;
289 if (offset < stream->size) {
290 int c = stream->buffer[offset++];
291 static const char special[256] = {
292 ['\r'] = 1, ['\n'] = 1, ['\\'] = 1
294 if (!special[c]) {
295 stream->offset = offset;
296 stream->pos++;
297 return c;
300 return nextchar_slow(stream);
303 struct token eof_token_entry;
305 static void mark_eof(stream_t *stream, struct token *end_token)
307 struct token *end;
309 end = alloc_token(stream);
310 token_type(end) = TOKEN_STREAMEND;
311 end->pos.newline = 1;
313 eof_token_entry.next = &eof_token_entry;
314 eof_token_entry.pos.newline = 1;
316 if (!end_token)
317 end_token = &eof_token_entry;
318 end->next = end_token;
319 *stream->tokenlist = end;
320 stream->tokenlist = NULL;
323 static void add_token(stream_t *stream)
325 struct token *token = stream->token;
327 stream->token = NULL;
328 token->next = NULL;
329 *stream->tokenlist = token;
330 stream->tokenlist = &token->next;
333 static void drop_token(stream_t *stream)
335 stream->newline |= stream->token->pos.newline;
336 stream->whitespace |= stream->token->pos.whitespace;
337 stream->token = NULL;
340 enum {
341 Letter = 1,
342 Digit = 2,
343 Hex = 4,
344 Exp = 8,
345 Dot = 16,
346 ValidSecond = 32,
349 static const long cclass[257] = {
350 ['0' + 1 ... '9' + 1] = Digit | Hex,
351 ['A' + 1 ... 'D' + 1] = Letter | Hex,
352 ['E' + 1] = Letter | Hex | Exp,
353 ['F' + 1] = Letter | Hex,
354 ['G' + 1 ... 'O' + 1] = Letter,
355 ['P' + 1] = Letter | Exp,
356 ['Q' + 1 ... 'Z' + 1] = Letter,
357 ['a' + 1 ... 'd' + 1] = Letter | Hex,
358 ['e' + 1] = Letter | Hex | Exp,
359 ['f' + 1] = Letter | Hex,
360 ['g' + 1 ... 'o' + 1] = Letter,
361 ['p' + 1] = Letter | Exp,
362 ['q' + 1 ... 'z' + 1] = Letter,
363 ['_' + 1] = Letter,
364 ['.' + 1] = Dot | ValidSecond,
365 ['=' + 1] = ValidSecond,
366 ['+' + 1] = ValidSecond,
367 ['-' + 1] = ValidSecond,
368 ['>' + 1] = ValidSecond,
369 ['<' + 1] = ValidSecond,
370 ['&' + 1] = ValidSecond,
371 ['|' + 1] = ValidSecond,
372 ['#' + 1] = ValidSecond,
376 * pp-number:
377 * digit
378 * . digit
379 * pp-number digit
380 * pp-number identifier-nodigit
381 * pp-number e sign
382 * pp-number E sign
383 * pp-number p sign
384 * pp-number P sign
385 * pp-number .
387 static int get_one_number(int c, int next, stream_t *stream)
389 struct token *token;
390 static char buffer[4095];
391 char *p = buffer, *buf, *buffer_end = buffer + sizeof (buffer);
392 int len;
394 *p++ = c;
395 for (;;) {
396 long class = cclass[next + 1];
397 if (!(class & (Dot | Digit | Letter)))
398 break;
399 if (p != buffer_end)
400 *p++ = next;
401 next = nextchar(stream);
402 if (class & Exp) {
403 if (next == '-' || next == '+') {
404 if (p != buffer_end)
405 *p++ = next;
406 next = nextchar(stream);
411 if (p == buffer_end) {
412 error(stream_pos(stream), "number token exceeds %td characters",
413 buffer_end - buffer);
414 // Pretend we saw just "1".
415 buffer[0] = '1';
416 p = buffer + 1;
419 *p++ = 0;
420 len = p - buffer;
421 buf = __alloc_bytes(len);
422 memcpy(buf, buffer, len);
424 token = stream->token;
425 token_type(token) = TOKEN_NUMBER;
426 token->number = buf;
427 add_token(stream);
429 return next;
432 static int escapechar(int first, int type, stream_t *stream, int *valp)
434 int next, value;
436 next = nextchar(stream);
437 value = first;
439 if (first == '\n')
440 warning(stream_pos(stream), "Newline in string or character constant");
442 if (first == '\\' && next != EOF) {
443 value = next;
444 next = nextchar(stream);
445 if (value != type) {
446 switch (value) {
447 case 'a':
448 value = '\a';
449 break;
450 case 'b':
451 value = '\b';
452 break;
453 case 't':
454 value = '\t';
455 break;
456 case 'n':
457 value = '\n';
458 break;
459 case 'v':
460 value = '\v';
461 break;
462 case 'f':
463 value = '\f';
464 break;
465 case 'r':
466 value = '\r';
467 break;
468 case 'e':
469 value = '\e';
470 break;
471 case '\\':
472 break;
473 case '\'':
474 break;
475 case '"':
476 break;
477 case '\n':
478 warning(stream_pos(stream), "Newline in string or character constant");
479 break;
480 case '0'...'7': {
481 int nr = 2;
482 value -= '0';
483 while (next >= '0' && next <= '9') {
484 value = (value << 3) + (next-'0');
485 next = nextchar(stream);
486 if (!--nr)
487 break;
489 value &= 0xff;
490 break;
492 case 'x': {
493 int hex = hexval(next);
494 if (hex < 16) {
495 value = hex;
496 next = nextchar(stream);
497 while ((hex = hexval(next)) < 16) {
498 value = (value << 4) + hex;
499 next = nextchar(stream);
501 value &= 0xff;
502 break;
505 /* Fallthrough */
506 default:
507 warning(stream_pos(stream), "Unknown escape '%c'", value);
510 /* Mark it as escaped */
511 value |= 0x100;
513 *valp = value;
514 return next;
517 static int get_char_token(int next, stream_t *stream)
519 int value;
520 struct token *token;
522 next = escapechar(next, '\'', stream, &value);
523 if (value == '\'' || next != '\'') {
524 warning(stream_pos(stream), "Bad character constant");
525 drop_token(stream);
526 return next;
529 token = stream->token;
530 token_type(token) = TOKEN_CHAR;
531 token->character = value & 0xff;
533 add_token(stream);
534 return nextchar(stream);
537 static int get_string_token(int next, stream_t *stream)
539 static char buffer[MAX_STRING];
540 struct string *string;
541 struct token *token;
542 int len = 0;
544 for (;;) {
545 int val;
546 next = escapechar(next, '"', stream, &val);
547 if (val == '"')
548 break;
549 if (next == EOF) {
550 warning(stream_pos(stream), "End of file in middle of string");
551 return next;
553 if (len < MAX_STRING)
554 buffer[len] = val;
555 len++;
558 if (len > MAX_STRING) {
559 warning(stream_pos(stream), "string too long (%d bytes, %d bytes max)", len, MAX_STRING);
560 len = MAX_STRING;
563 string = __alloc_string(len+1);
564 memcpy(string->data, buffer, len);
565 string->data[len] = '\0';
566 string->length = len+1;
568 /* Pass it on.. */
569 token = stream->token;
570 token_type(token) = TOKEN_STRING;
571 token->string = string;
572 add_token(stream);
574 return next;
577 static int drop_stream_eoln(stream_t *stream)
579 int next = nextchar(stream);
580 drop_token(stream);
581 for (;;) {
582 int curr = next;
583 if (curr == EOF)
584 return next;
585 next = nextchar(stream);
586 if (curr == '\n')
587 return next;
591 static int drop_stream_comment(stream_t *stream)
593 int newline;
594 int next;
595 drop_token(stream);
596 newline = stream->newline;
598 next = nextchar(stream);
599 for (;;) {
600 int curr = next;
601 if (curr == EOF) {
602 warning(stream_pos(stream), "End of file in the middle of a comment");
603 return curr;
605 next = nextchar(stream);
606 if (curr == '*' && next == '/')
607 break;
609 stream->newline = newline;
610 return nextchar(stream);
613 unsigned char combinations[][3] = COMBINATION_STRINGS;
615 #define NR_COMBINATIONS (SPECIAL_ARG_SEPARATOR - SPECIAL_BASE)
617 static int get_one_special(int c, stream_t *stream)
619 struct token *token;
620 unsigned char c1, c2, c3;
621 int next, value, i;
622 char *comb;
624 next = nextchar(stream);
627 * Check for numbers, strings, character constants, and comments
629 switch (c) {
630 case '.':
631 if (next >= '0' && next <= '9')
632 return get_one_number(c, next, stream);
633 break;
634 case '"':
635 return get_string_token(next, stream);
636 case '\'':
637 return get_char_token(next, stream);
638 case '/':
639 if (next == '/')
640 return drop_stream_eoln(stream);
641 if (next == '*')
642 return drop_stream_comment(stream);
646 * Check for combinations
648 value = c;
649 if (cclass[next + 1] & ValidSecond) {
650 comb = combinations[0];
651 c1 = c; c2 = next; c3 = 0;
652 for (i = 0; i < NR_COMBINATIONS; i++) {
653 if (comb[0] == c1 && comb[1] == c2 && comb[2] == c3) {
654 value = i + SPECIAL_BASE;
655 next = nextchar(stream);
656 if (c3)
657 break;
658 c3 = next;
660 comb += 3;
664 /* Pass it on.. */
665 token = stream->token;
666 token_type(token) = TOKEN_SPECIAL;
667 token->special = value;
668 add_token(stream);
669 return next;
672 #define IDENT_HASH_BITS (13)
673 #define IDENT_HASH_SIZE (1<<IDENT_HASH_BITS)
674 #define IDENT_HASH_MASK (IDENT_HASH_SIZE-1)
676 #define ident_hash_init(c) (c)
677 #define ident_hash_add(oldhash,c) ((oldhash)*11 + (c))
678 #define ident_hash_end(hash) ((((hash) >> IDENT_HASH_BITS) + (hash)) & IDENT_HASH_MASK)
680 static struct ident *hash_table[IDENT_HASH_SIZE];
681 int ident_hit, ident_miss, idents;
683 void show_identifier_stats(void)
685 int i;
686 int distribution[100];
688 fprintf(stderr, "identifiers: %d hits, %d misses\n",
689 ident_hit, ident_miss);
691 for (i = 0; i < 100; i++)
692 distribution[i] = 0;
694 for (i = 0; i < IDENT_HASH_SIZE; i++) {
695 struct ident * ident = hash_table[i];
696 int count = 0;
698 while (ident) {
699 count++;
700 ident = ident->next;
702 if (count > 99)
703 count = 99;
704 distribution[count]++;
707 for (i = 0; i < 100; i++) {
708 if (distribution[i])
709 fprintf(stderr, "%2d: %d buckets\n", i, distribution[i]);
713 static struct ident *alloc_ident(const char *name, int len)
715 struct ident *ident = __alloc_ident(len);
716 ident->symbols = NULL;
717 ident->len = len;
718 ident->tainted = 0;
719 memcpy(ident->name, name, len);
720 return ident;
723 static struct ident * insert_hash(struct ident *ident, unsigned long hash)
725 ident->next = hash_table[hash];
726 hash_table[hash] = ident;
727 ident_miss++;
728 return ident;
731 static struct ident *create_hashed_ident(const char *name, int len, unsigned long hash)
733 struct ident *ident;
734 struct ident **p;
736 p = &hash_table[hash];
737 while ((ident = *p) != NULL) {
738 if (ident->len == (unsigned char) len) {
739 const char *n = name;
740 const char *m = ident->name;
741 int l = len;
742 do {
743 if (*n != *m)
744 goto next;
745 n++;
746 m++;
747 } while (--l);
749 ident_hit++;
750 return ident;
752 next:
753 //misses++;
754 p = &ident->next;
756 ident = alloc_ident(name, len);
757 *p = ident;
758 ident->next = NULL;
759 ident_miss++;
760 idents++;
761 return ident;
764 static unsigned long hash_name(const char *name, int len)
766 unsigned long hash;
767 const unsigned char *p = (const unsigned char *)name;
769 hash = ident_hash_init(*p++);
770 while (--len) {
771 unsigned int i = *p++;
772 hash = ident_hash_add(hash, i);
774 return ident_hash_end(hash);
777 struct ident *hash_ident(struct ident *ident)
779 return insert_hash(ident, hash_name(ident->name, ident->len));
782 struct ident *built_in_ident(const char *name)
784 int len = strlen(name);
785 return create_hashed_ident(name, len, hash_name(name, len));
788 struct token *built_in_token(int stream, const char *name)
790 struct token *token;
792 token = __alloc_token(0);
793 token->pos.stream = stream;
794 token_type(token) = TOKEN_IDENT;
795 token->ident = built_in_ident(name);
796 return token;
799 static int get_one_identifier(int c, stream_t *stream)
801 struct token *token;
802 struct ident *ident;
803 unsigned long hash;
804 char buf[256];
805 int len = 1;
806 int next;
808 hash = ident_hash_init(c);
809 buf[0] = c;
810 for (;;) {
811 next = nextchar(stream);
812 if (!(cclass[next + 1] & (Letter | Digit)))
813 break;
814 if (len >= sizeof(buf))
815 break;
816 hash = ident_hash_add(hash, next);
817 buf[len] = next;
818 len++;
820 hash = ident_hash_end(hash);
822 ident = create_hashed_ident(buf, len, hash);
824 /* Pass it on.. */
825 token = stream->token;
826 token_type(token) = TOKEN_IDENT;
827 token->ident = ident;
828 add_token(stream);
829 return next;
832 static int get_one_token(int c, stream_t *stream)
834 long class = cclass[c + 1];
835 if (class & Digit)
836 return get_one_number(c, nextchar(stream), stream);
837 if (class & Letter)
838 return get_one_identifier(c, stream);
839 return get_one_special(c, stream);
842 static struct token *setup_stream(stream_t *stream, int idx, int fd,
843 unsigned char *buf, unsigned int buf_size)
845 struct token *begin;
847 stream->nr = idx;
848 stream->line = 1;
849 stream->newline = 1;
850 stream->whitespace = 0;
851 stream->pos = 0;
853 stream->token = NULL;
854 stream->fd = fd;
855 stream->offset = 0;
856 stream->size = buf_size;
857 stream->buffer = buf;
859 begin = alloc_token(stream);
860 token_type(begin) = TOKEN_STREAMBEGIN;
861 stream->tokenlist = &begin->next;
862 return begin;
865 static void tokenize_stream(stream_t *stream, struct token *endtoken)
867 int c = nextchar(stream);
868 while (c != EOF) {
869 if (!isspace(c)) {
870 struct token *token = alloc_token(stream);
871 stream->token = token;
872 stream->newline = 0;
873 stream->whitespace = 0;
874 c = get_one_token(c, stream);
875 continue;
877 stream->whitespace = 1;
878 c = nextchar(stream);
880 mark_eof(stream, endtoken);
883 struct token * tokenize_buffer(unsigned char *buffer, unsigned long size, struct token *endtoken)
885 stream_t stream;
886 struct token *begin;
888 begin = setup_stream(&stream, 0, -1, buffer, size);
889 tokenize_stream(&stream, endtoken);
890 return begin;
893 struct token * tokenize(const char *name, int fd, struct token *endtoken, const char **next_path)
895 struct token *begin;
896 stream_t stream;
897 unsigned char buffer[BUFSIZE];
898 int idx;
900 idx = init_stream(name, fd, next_path);
901 if (idx < 0) {
902 // info(endtoken->pos, "File %s is const", name);
903 return endtoken;
906 begin = setup_stream(&stream, idx, fd, buffer, 0);
907 tokenize_stream(&stream, endtoken);
908 return begin;