]> git.xonotic.org Git - xonotic/gmqcc.git/blob - lexer.c
Perliminary restructuring / implementation of the diagnostics system.
[xonotic/gmqcc.git] / lexer.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <stdarg.h>
27
28 #include "gmqcc.h"
29 #include "lexer.h"
30
31 /*
32  * List of Keywords
33  */
34
35 /* original */
36 static const char *keywords_qc[] = {
37     "for", "do", "while",
38     "if", "else",
39     "local",
40     "return",
41     "const"
42 };
43 static size_t num_keywords_qc = sizeof(keywords_qc) / sizeof(keywords_qc[0]);
44
45 /* For fte/gmgqcc */
46 static const char *keywords_fg[] = {
47     "switch", "case", "default",
48     "struct", "union",
49     "break", "continue",
50     "typedef",
51     "goto",
52
53     "__builtin_debug_printtype"
54 };
55 static size_t num_keywords_fg = sizeof(keywords_fg) / sizeof(keywords_fg[0]);
56
57 /*
58  * Lexer code
59  */
60
61 static char* *lex_filenames;
62
63 static void lexerror(lex_file *lex, const char *fmt, ...)
64 {
65     va_list ap;
66
67     va_start(ap, fmt);
68     if (lex)
69         con_vprintmsg(LVL_ERROR, lex->name, lex->sline, "parse error", fmt, ap);
70     else
71         con_vprintmsg(LVL_ERROR, "", 0, "parse error", fmt, ap);
72     va_end(ap);
73 }
74
75 static bool lexwarn(lex_file *lex, int warntype, const char *fmt, ...)
76 {
77     bool    r;
78     lex_ctx ctx;
79     va_list ap;
80
81     ctx.file = lex->name;
82     ctx.line = lex->sline;
83
84     va_start(ap, fmt);
85     r = vcompile_warning(ctx, warntype, fmt, ap);
86     va_end(ap);
87     return r;
88 }
89
90
91 #if 0
92 token* token_new()
93 {
94     token *tok = (token*)mem_a(sizeof(token));
95     if (!tok)
96         return NULL;
97     memset(tok, 0, sizeof(*tok));
98     return tok;
99 }
100
101 void token_delete(token *self)
102 {
103     if (self->next && self->next->prev == self)
104         self->next->prev = self->prev;
105     if (self->prev && self->prev->next == self)
106         self->prev->next = self->next;
107     MEM_VECTOR_CLEAR(self, value);
108     mem_d(self);
109 }
110
111 token* token_copy(const token *cp)
112 {
113     token* self = token_new();
114     if (!self)
115         return NULL;
116     /* copy the value */
117     self->value_alloc = cp->value_count + 1;
118     self->value_count = cp->value_count;
119     self->value = (char*)mem_a(self->value_alloc);
120     if (!self->value) {
121         mem_d(self);
122         return NULL;
123     }
124     memcpy(self->value, cp->value, cp->value_count);
125     self->value[self->value_alloc-1] = 0;
126
127     /* rest */
128     self->ctx = cp->ctx;
129     self->ttype = cp->ttype;
130     memcpy(&self->constval, &cp->constval, sizeof(self->constval));
131     return self;
132 }
133
134 void token_delete_all(token *t)
135 {
136     token *n;
137
138     do {
139         n = t->next;
140         token_delete(t);
141         t = n;
142     } while(t);
143 }
144
145 token* token_copy_all(const token *cp)
146 {
147     token *cur;
148     token *out;
149
150     out = cur = token_copy(cp);
151     if (!out)
152         return NULL;
153
154     while (cp->next) {
155         cp = cp->next;
156         cur->next = token_copy(cp);
157         if (!cur->next) {
158             token_delete_all(out);
159             return NULL;
160         }
161         cur->next->prev = cur;
162         cur = cur->next;
163     }
164
165     return out;
166 }
167 #else
168 static void lex_token_new(lex_file *lex)
169 {
170 #if 0
171     if (lex->tok)
172         token_delete(lex->tok);
173     lex->tok = token_new();
174 #else
175     if (lex->tok.value)
176         vec_shrinkto(lex->tok.value, 0);
177         
178     lex->tok.constval.t = 0;
179     lex->tok.ctx.line   = lex->sline;
180     lex->tok.ctx.file   = lex->name;
181 #endif
182 }
183 #endif
184
185 lex_file* lex_open(const char *file)
186 {
187     lex_file *lex;
188     FILE *in = fs_file_open(file, "rb");
189
190     if (!in) {
191         lexerror(NULL, "open failed: '%s'\n", file);
192         return NULL;
193     }
194
195     lex = (lex_file*)mem_a(sizeof(*lex));
196     if (!lex) {
197         fs_file_close(in);
198         lexerror(NULL, "out of memory\n");
199         return NULL;
200     }
201
202     memset(lex, 0, sizeof(*lex));
203
204     lex->file = in;
205     lex->name = util_strdup(file);
206     lex->line = 1; /* we start counting at 1 */
207
208     lex->peekpos = 0;
209     lex->eof = false;
210
211     vec_push(lex_filenames, lex->name);
212     return lex;
213 }
214
215 lex_file* lex_open_string(const char *str, size_t len, const char *name)
216 {
217     lex_file *lex;
218
219     lex = (lex_file*)mem_a(sizeof(*lex));
220     if (!lex) {
221         lexerror(NULL, "out of memory\n");
222         return NULL;
223     }
224
225     memset(lex, 0, sizeof(*lex));
226
227     lex->file = NULL;
228     lex->open_string        = str;
229     lex->open_string_length = len;
230     lex->open_string_pos    = 0;
231
232     lex->name = util_strdup(name ? name : "<string-source>");
233     lex->line = 1; /* we start counting at 1 */
234
235     lex->peekpos = 0;
236     lex->eof = false;
237
238     vec_push(lex_filenames, lex->name);
239
240     return lex;
241 }
242
243 void lex_cleanup(void)
244 {
245     size_t i;
246     for (i = 0; i < vec_size(lex_filenames); ++i)
247         mem_d(lex_filenames[i]);
248     vec_free(lex_filenames);
249 }
250
251 void lex_close(lex_file *lex)
252 {
253     size_t i;
254     for (i = 0; i < vec_size(lex->frames); ++i)
255         mem_d(lex->frames[i].name);
256     vec_free(lex->frames);
257
258     if (lex->modelname)
259         vec_free(lex->modelname);
260
261     if (lex->file)
262         fs_file_close(lex->file);
263 #if 0
264     if (lex->tok)
265         token_delete(lex->tok);
266 #else
267     vec_free(lex->tok.value);
268 #endif
269     /* mem_d(lex->name); collected in lex_filenames */
270     mem_d(lex);
271 }
272
273 static int lex_fgetc(lex_file *lex)
274 {
275     if (lex->file) {
276         return fs_file_getc(lex->file);
277     }
278     if (lex->open_string) {
279         if (lex->open_string_pos >= lex->open_string_length)
280             return EOF;
281         return lex->open_string[lex->open_string_pos++];
282     }
283     return EOF;
284 }
285
286 /* Get or put-back data
287  * The following to functions do NOT understand what kind of data they
288  * are working on.
289  * The are merely wrapping get/put in order to count line numbers.
290  */
291 static void lex_ungetch(lex_file *lex, int ch);
292 static int lex_try_trigraph(lex_file *lex, int old)
293 {
294     int c2, c3;
295     c2 = lex_fgetc(lex);
296     if (!lex->push_line && c2 == '\n')
297         lex->line++;
298     if (c2 != '?') {
299         lex_ungetch(lex, c2);
300         return old;
301     }
302
303     c3 = lex_fgetc(lex);
304     if (!lex->push_line && c3 == '\n')
305         lex->line++;
306     switch (c3) {
307         case '=': return '#';
308         case '/': return '\\';
309         case '\'': return '^';
310         case '(': return '[';
311         case ')': return ']';
312         case '!': return '|';
313         case '<': return '{';
314         case '>': return '}';
315         case '-': return '~';
316         default:
317             lex_ungetch(lex, c3);
318             lex_ungetch(lex, c2);
319             return old;
320     }
321 }
322
323 static int lex_try_digraph(lex_file *lex, int ch)
324 {
325     int c2;
326     c2 = lex_fgetc(lex);
327     /* we just used fgetc() so count lines
328      * need to offset a \n the ungetch would recognize
329      */
330     if (!lex->push_line && c2 == '\n')
331         lex->line++;
332     if      (ch == '<' && c2 == ':')
333         return '[';
334     else if (ch == ':' && c2 == '>')
335         return ']';
336     else if (ch == '<' && c2 == '%')
337         return '{';
338     else if (ch == '%' && c2 == '>')
339         return '}';
340     else if (ch == '%' && c2 == ':')
341         return '#';
342     lex_ungetch(lex, c2);
343     return ch;
344 }
345
346 static int lex_getch(lex_file *lex)
347 {
348     int ch;
349
350     if (lex->peekpos) {
351         lex->peekpos--;
352         if (!lex->push_line && lex->peek[lex->peekpos] == '\n')
353             lex->line++;
354         return lex->peek[lex->peekpos];
355     }
356
357     ch = lex_fgetc(lex);
358     if (!lex->push_line && ch == '\n')
359         lex->line++;
360     else if (ch == '?')
361         return lex_try_trigraph(lex, ch);
362     else if (!lex->flags.nodigraphs && (ch == '<' || ch == ':' || ch == '%'))
363         return lex_try_digraph(lex, ch);
364     return ch;
365 }
366
367 static void lex_ungetch(lex_file *lex, int ch)
368 {
369     lex->peek[lex->peekpos++] = ch;
370     if (!lex->push_line && ch == '\n')
371         lex->line--;
372 }
373
374 /* classify characters
375  * some additions to the is*() functions of ctype.h
376  */
377
378 /* Idents are alphanumberic, but they start with alpha or _ */
379 static bool isident_start(int ch)
380 {
381     return isalpha(ch) || ch == '_';
382 }
383
384 static bool isident(int ch)
385 {
386     return isident_start(ch) || isdigit(ch);
387 }
388
389 /* isxdigit_only is used when we already know it's not a digit
390  * and want to see if it's a hex digit anyway.
391  */
392 static bool isxdigit_only(int ch)
393 {
394     return (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
395 }
396
397 /* Append a character to the token buffer */
398 static void lex_tokench(lex_file *lex, int ch)
399 {
400     vec_push(lex->tok.value, ch);
401 }
402
403 /* Append a trailing null-byte */
404 static void lex_endtoken(lex_file *lex)
405 {
406     vec_push(lex->tok.value, 0);
407     vec_shrinkby(lex->tok.value, 1);
408 }
409
410 static bool lex_try_pragma(lex_file *lex)
411 {
412     int ch;
413     char *pragma  = NULL;
414     char *command = NULL;
415     char *param   = NULL;
416     size_t line;
417
418     if (lex->flags.preprocessing)
419         return false;
420
421     line = lex->line;
422
423     ch = lex_getch(lex);
424     if (ch != '#') {
425         lex_ungetch(lex, ch);
426         return false;
427     }
428
429     for (ch = lex_getch(lex); vec_size(pragma) < 8 && ch >= 'a' && ch <= 'z'; ch = lex_getch(lex))
430         vec_push(pragma, ch);
431     vec_push(pragma, 0);
432
433     if (ch != ' ' || strcmp(pragma, "pragma")) {
434         lex_ungetch(lex, ch);
435         goto unroll;
436     }
437
438     for (ch = lex_getch(lex); vec_size(command) < 32 && ch >= 'a' && ch <= 'z'; ch = lex_getch(lex))
439         vec_push(command, ch);
440     vec_push(command, 0);
441
442     if (ch != '(') {
443         lex_ungetch(lex, ch);
444         goto unroll;
445     }
446
447     for (ch = lex_getch(lex); vec_size(param) < 1024 && ch != ')' && ch != '\n'; ch = lex_getch(lex))
448         vec_push(param, ch);
449     vec_push(param, 0);
450
451     if (ch != ')') {
452         lex_ungetch(lex, ch);
453         goto unroll;
454     }
455
456     if (!strcmp(command, "push")) {
457         if (!strcmp(param, "line")) {
458             lex->push_line++;
459             if (lex->push_line == 1)
460                 --line;
461         }
462         else
463             goto unroll;
464     }
465     else if (!strcmp(command, "pop")) {
466         if (!strcmp(param, "line")) {
467             if (lex->push_line)
468                 lex->push_line--;
469             if (lex->push_line == 0)
470                 --line;
471         }
472         else
473             goto unroll;
474     }
475     else if (!strcmp(command, "file")) {
476         lex->name = util_strdup(param);
477         vec_push(lex_filenames, lex->name);
478     }
479     else if (!strcmp(command, "line")) {
480         line = strtol(param, NULL, 0)-1;
481     }
482     else
483         goto unroll;
484
485     lex->line = line;
486     while (ch != '\n' && ch != EOF)
487         ch = lex_getch(lex);
488     vec_free(command);
489     vec_free(param);
490     vec_free(pragma);
491     return true;
492
493 unroll:
494     if (command) {
495         vec_pop(command);
496         while (vec_size(command)) {
497             lex_ungetch(lex, (unsigned char)vec_last(command));
498             vec_pop(command);
499         }
500         vec_free(command);
501         lex_ungetch(lex, ' ');
502     }
503     if (param) {
504         vec_pop(param);
505         while (vec_size(param)) {
506             lex_ungetch(lex, (unsigned char)vec_last(param));
507             vec_pop(param);
508         }
509         vec_free(param);
510         lex_ungetch(lex, ' ');
511     }
512     if (pragma) {
513         vec_pop(pragma);
514         while (vec_size(pragma)) {
515             lex_ungetch(lex, (unsigned char)vec_last(pragma));
516             vec_pop(pragma);
517         }
518         vec_free(pragma);
519     }
520     lex_ungetch(lex, '#');
521
522     lex->line = line;
523     return false;
524 }
525
526 /* Skip whitespace and comments and return the first
527  * non-white character.
528  * As this makes use of the above getch() ungetch() functions,
529  * we don't need to care at all about line numbering anymore.
530  *
531  * In theory, this function should only be used at the beginning
532  * of lexing, or when we *know* the next character is part of the token.
533  * Otherwise, if the parser throws an error, the linenumber may not be
534  * the line of the error, but the line of the next token AFTER the error.
535  *
536  * This is currently only problematic when using c-like string-continuation,
537  * since comments and whitespaces are allowed between 2 such strings.
538  * Example:
539 printf(   "line one\n"
540 // A comment
541           "A continuation of the previous string"
542 // This line is skipped
543       , foo);
544
545  * In this case, if the parse decides it didn't actually want a string,
546  * and uses lex->line to print an error, it will show the ', foo);' line's
547  * linenumber.
548  *
549  * On the other hand, the parser is supposed to remember the line of the next
550  * token's beginning. In this case we would want skipwhite() to be called
551  * AFTER reading a token, so that the parser, before reading the NEXT token,
552  * doesn't store teh *comment's* linenumber, but the actual token's linenumber.
553  *
554  * THIS SOLUTION
555  *    here is to store the line of the first character after skipping
556  *    the initial whitespace in lex->sline, this happens in lex_do.
557  */
558 static int lex_skipwhite(lex_file *lex, bool hadwhite)
559 {
560     int ch = 0;
561     bool haswhite = hadwhite;
562
563     do
564     {
565         ch = lex_getch(lex);
566         while (ch != EOF && isspace(ch)) {
567             if (ch == '\n') {
568                 if (lex_try_pragma(lex))
569                     continue;
570             }
571             if (lex->flags.preprocessing) {
572                 if (ch == '\n') {
573                     /* end-of-line */
574                     /* see if there was whitespace first */
575                     if (haswhite) { /* (vec_size(lex->tok.value)) { */
576                         lex_ungetch(lex, ch);
577                         lex_endtoken(lex);
578                         return TOKEN_WHITE;
579                     }
580                     /* otherwise return EOL */
581                     return TOKEN_EOL;
582                 }
583                 haswhite = true;
584                 lex_tokench(lex, ch);
585             }
586             ch = lex_getch(lex);
587         }
588
589         if (ch == '/') {
590             ch = lex_getch(lex);
591             if (ch == '/')
592             {
593                 /* one line comment */
594                 ch = lex_getch(lex);
595
596                 if (lex->flags.preprocessing) {
597                     haswhite = true;
598                     /*
599                     lex_tokench(lex, '/');
600                     lex_tokench(lex, '/');
601                     */
602                     lex_tokench(lex, ' ');
603                     lex_tokench(lex, ' ');
604                 }
605
606                 while (ch != EOF && ch != '\n') {
607                     if (lex->flags.preprocessing)
608                         lex_tokench(lex, ' '); /* ch); */
609                     ch = lex_getch(lex);
610                 }
611                 if (lex->flags.preprocessing) {
612                     lex_ungetch(lex, '\n');
613                     lex_endtoken(lex);
614                     return TOKEN_WHITE;
615                 }
616                 continue;
617             }
618             if (ch == '*')
619             {
620                 /* multiline comment */
621                 if (lex->flags.preprocessing) {
622                     haswhite = true;
623                     /*
624                     lex_tokench(lex, '/');
625                     lex_tokench(lex, '*');
626                     */
627                     lex_tokench(lex, ' ');
628                     lex_tokench(lex, ' ');
629                 }
630
631                 while (ch != EOF)
632                 {
633                     ch = lex_getch(lex);
634                     if (ch == '*') {
635                         ch = lex_getch(lex);
636                         if (ch == '/') {
637                             if (lex->flags.preprocessing) {
638                                 /*
639                                 lex_tokench(lex, '*');
640                                 lex_tokench(lex, '/');
641                                 */
642                                 lex_tokench(lex, ' ');
643                                 lex_tokench(lex, ' ');
644                             }
645                             break;
646                         }
647                         lex_ungetch(lex, ch);
648                     }
649                     if (lex->flags.preprocessing) {
650                         if (ch == '\n')
651                             lex_tokench(lex, '\n');
652                         else
653                             lex_tokench(lex, ' '); /* ch); */
654                     }
655                 }
656                 ch = ' '; /* cause TRUE in the isspace check */
657                 continue;
658             }
659             /* Otherwise roll back to the slash and break out of the loop */
660             lex_ungetch(lex, ch);
661             ch = '/';
662             break;
663         }
664     } while (ch != EOF && isspace(ch));
665
666     if (haswhite) {
667         lex_endtoken(lex);
668         lex_ungetch(lex, ch);
669         return TOKEN_WHITE;
670     }
671     return ch;
672 }
673
674 /* Get a token */
675 static bool GMQCC_WARN lex_finish_ident(lex_file *lex)
676 {
677     int ch;
678
679     ch = lex_getch(lex);
680     while (ch != EOF && isident(ch))
681     {
682         lex_tokench(lex, ch);
683         ch = lex_getch(lex);
684     }
685
686     /* last ch was not an ident ch: */
687     lex_ungetch(lex, ch);
688
689     return true;
690 }
691
692 /* read one ident for the frame list */
693 static int lex_parse_frame(lex_file *lex)
694 {
695     int ch;
696
697     lex_token_new(lex);
698
699     ch = lex_getch(lex);
700     while (ch != EOF && ch != '\n' && isspace(ch))
701         ch = lex_getch(lex);
702
703     if (ch == '\n')
704         return 1;
705
706     if (!isident_start(ch)) {
707         lexerror(lex, "invalid framename, must start with one of a-z or _, got %c", ch);
708         return -1;
709     }
710
711     lex_tokench(lex, ch);
712     if (!lex_finish_ident(lex))
713         return -1;
714     lex_endtoken(lex);
715     return 0;
716 }
717
718 /* read a list of $frames */
719 static bool lex_finish_frames(lex_file *lex)
720 {
721     do {
722         size_t i;
723         int    rc;
724         frame_macro m;
725
726         rc = lex_parse_frame(lex);
727         if (rc > 0) /* end of line */
728             return true;
729         if (rc < 0) /* error */
730             return false;
731
732         for (i = 0; i < vec_size(lex->frames); ++i) {
733             if (!strcmp(lex->tok.value, lex->frames[i].name)) {
734                 lex->frames[i].value = lex->framevalue++;
735                 if (lexwarn(lex, WARN_FRAME_MACROS, "duplicate frame macro defined: `%s`", lex->tok.value))
736                     return false;
737                 break;
738             }
739         }
740         if (i < vec_size(lex->frames))
741             continue;
742
743         m.value = lex->framevalue++;
744         m.name = util_strdup(lex->tok.value);
745         vec_shrinkto(lex->tok.value, 0);
746         vec_push(lex->frames, m);
747     } while (true);
748
749     return false;
750 }
751
752 static int GMQCC_WARN lex_finish_string(lex_file *lex, int quote)
753 {
754     uchar_t chr;
755     int ch = 0;
756     int nextch;
757     bool hex;
758     char u8buf[8]; /* way more than enough */
759     int  u8len, uc;
760
761     while (ch != EOF)
762     {
763         ch = lex_getch(lex);
764         if (ch == quote)
765             return TOKEN_STRINGCONST;
766
767         if (lex->flags.preprocessing && ch == '\\') {
768             lex_tokench(lex, ch);
769             ch = lex_getch(lex);
770             if (ch == EOF) {
771                 lexerror(lex, "unexpected end of file");
772                 lex_ungetch(lex, EOF); /* next token to be TOKEN_EOF */
773                 return (lex->tok.ttype = TOKEN_ERROR);
774             }
775             lex_tokench(lex, ch);
776         }
777         else if (ch == '\\') {
778             ch = lex_getch(lex);
779             if (ch == EOF) {
780                 lexerror(lex, "unexpected end of file");
781                 lex_ungetch(lex, EOF); /* next token to be TOKEN_EOF */
782                 return (lex->tok.ttype = TOKEN_ERROR);
783             }
784
785             switch (ch) {
786             case '\\': break;
787             case '\'': break;
788             case '"':  break;
789             case 'a':  ch = '\a'; break;
790             case 'b':  ch = '\b'; break;
791             case 'r':  ch = '\r'; break;
792             case 'n':  ch = '\n'; break;
793             case 't':  ch = '\t'; break;
794             case 'f':  ch = '\f'; break;
795             case 'v':  ch = '\v'; break;
796             case 'x':
797             case 'X':
798                 /* same procedure as in fteqcc */
799                 ch = 0;
800                 nextch = lex_getch(lex);
801                 if      (nextch >= '0' && nextch <= '9')
802                     ch += nextch - '0';
803                 else if (nextch >= 'a' && nextch <= 'f')
804                     ch += nextch - 'a' + 10;
805                 else if (nextch >= 'A' && nextch <= 'F')
806                     ch += nextch - 'A' + 10;
807                 else {
808                     lexerror(lex, "bad character code");
809                     lex_ungetch(lex, nextch);
810                     return (lex->tok.ttype = TOKEN_ERROR);
811                 }
812
813                 ch *= 0x10;
814                 nextch = lex_getch(lex);
815                 if      (nextch >= '0' && nextch <= '9')
816                     ch += nextch - '0';
817                 else if (nextch >= 'a' && nextch <= 'f')
818                     ch += nextch - 'a' + 10;
819                 else if (nextch >= 'A' && nextch <= 'F')
820                     ch += nextch - 'A' + 10;
821                 else {
822                     lexerror(lex, "bad character code");
823                     lex_ungetch(lex, nextch);
824                     return (lex->tok.ttype = TOKEN_ERROR);
825                 }
826                 break;
827
828             /* fteqcc support */
829             case '0': case '1': case '2': case '3':
830             case '4': case '5': case '6': case '7':
831             case '8': case '9':
832                 ch = 18 + ch - '0';
833                 break;
834             case '<':  ch = 29; break;
835             case '-':  ch = 30; break;
836             case '>':  ch = 31; break;
837             case '[':  ch = 16; break;
838             case ']':  ch = 17; break;
839             case '{':
840                 chr = 0;
841                 nextch = lex_getch(lex);
842                 hex = (nextch == 'x');
843                 if (!hex)
844                     lex_ungetch(lex, nextch);
845                 for (nextch = lex_getch(lex); nextch != '}'; nextch = lex_getch(lex)) {
846                     if (!hex) {
847                         if (nextch >= '0' && nextch <= '9')
848                             chr = chr * 10 + nextch - '0';
849                         else {
850                             lexerror(lex, "bad character code");
851                             return (lex->tok.ttype = TOKEN_ERROR);
852                         }
853                     } else {
854                         if (nextch >= '0' && nextch <= '9')
855                             chr = chr * 0x10 + nextch - '0';
856                         else if (nextch >= 'a' && nextch <= 'f')
857                             chr = chr * 0x10 + nextch - 'a' + 10;
858                         else if (nextch >= 'A' && nextch <= 'F')
859                             chr = chr * 0x10 + nextch - 'A' + 10;
860                         else {
861                             lexerror(lex, "bad character code");
862                             return (lex->tok.ttype = TOKEN_ERROR);
863                         }
864                     }
865                     if (chr > 0x10FFFF || (!OPTS_FLAG(UTF8) && chr > 255))
866                     {
867                         lexerror(lex, "character code out of range");
868                         return (lex->tok.ttype = TOKEN_ERROR);
869                     }
870                 }
871                 if (OPTS_FLAG(UTF8) && chr >= 128) {
872                     u8len = u8_fromchar(chr, u8buf, sizeof(u8buf));
873                     if (!u8len)
874                         ch = 0;
875                     else {
876                         --u8len;
877                         for (uc = 0; uc < u8len; ++uc)
878                             lex_tokench(lex, u8buf[uc]);
879                         /* the last character will be inserted with the tokench() call
880                          * below the switch
881                          */
882                         ch = u8buf[uc];
883                     }
884                 }
885                 else
886                     ch = chr;
887                 break;
888             case '\n':  ch = '\n'; break;
889
890             default:
891                 lexwarn(lex, WARN_UNKNOWN_CONTROL_SEQUENCE, "unrecognized control sequence: \\%c", ch);
892                 /* so we just add the character plus backslash no matter what it actually is */
893                 lex_tokench(lex, '\\');
894             }
895             /* add the character finally */
896             lex_tokench(lex, ch);
897         }
898         else
899             lex_tokench(lex, ch);
900     }
901     lexerror(lex, "unexpected end of file within string constant");
902     lex_ungetch(lex, EOF); /* next token to be TOKEN_EOF */
903     return (lex->tok.ttype = TOKEN_ERROR);
904 }
905
906 static int GMQCC_WARN lex_finish_digit(lex_file *lex, int lastch)
907 {
908     bool ishex = false;
909
910     int  ch = lastch;
911
912     /* parse a number... */
913     if (ch == '.')
914         lex->tok.ttype = TOKEN_FLOATCONST;
915     else
916         lex->tok.ttype = TOKEN_INTCONST;
917
918     lex_tokench(lex, ch);
919
920     ch = lex_getch(lex);
921     if (ch != '.' && !isdigit(ch))
922     {
923         if (lastch != '0' || ch != 'x')
924         {
925             /* end of the number or EOF */
926             lex_ungetch(lex, ch);
927             lex_endtoken(lex);
928
929             lex->tok.constval.i = lastch - '0';
930             return lex->tok.ttype;
931         }
932
933         ishex = true;
934     }
935
936     /* EOF would have been caught above */
937
938     if (ch != '.')
939     {
940         lex_tokench(lex, ch);
941         ch = lex_getch(lex);
942         while (isdigit(ch) || (ishex && isxdigit_only(ch)))
943         {
944             lex_tokench(lex, ch);
945             ch = lex_getch(lex);
946         }
947     }
948     /* NOT else, '.' can come from above as well */
949     if (lex->tok.ttype != TOKEN_FLOATCONST && ch == '.' && !ishex)
950     {
951         /* Allow floating comma in non-hex mode */
952         lex->tok.ttype = TOKEN_FLOATCONST;
953         lex_tokench(lex, ch);
954
955         /* continue digits-only */
956         ch = lex_getch(lex);
957         while (isdigit(ch))
958         {
959             lex_tokench(lex, ch);
960             ch = lex_getch(lex);
961         }
962     }
963     /* put back the last character */
964     /* but do not put back the trailing 'f' or a float */
965     if (lex->tok.ttype == TOKEN_FLOATCONST && ch == 'f')
966         ch = lex_getch(lex);
967
968     /* generally we don't want words to follow numbers: */
969     if (isident(ch)) {
970         lexerror(lex, "unexpected trailing characters after number");
971         return (lex->tok.ttype = TOKEN_ERROR);
972     }
973     lex_ungetch(lex, ch);
974
975     lex_endtoken(lex);
976     if (lex->tok.ttype == TOKEN_FLOATCONST)
977         lex->tok.constval.f = strtod(lex->tok.value, NULL);
978     else
979         lex->tok.constval.i = strtol(lex->tok.value, NULL, 0);
980     return lex->tok.ttype;
981 }
982
983 int lex_do(lex_file *lex)
984 {
985     int ch, nextch, thirdch;
986     bool hadwhite = false;
987
988     lex_token_new(lex);
989 #if 0
990     if (!lex->tok)
991         return TOKEN_FATAL;
992 #endif
993
994     while (true) {
995         ch = lex_skipwhite(lex, hadwhite);
996         hadwhite = true;
997         if (!lex->flags.mergelines || ch != '\\')
998             break;
999         ch = lex_getch(lex);
1000         if (ch == '\r')
1001             ch = lex_getch(lex);
1002         if (ch != '\n') {
1003             lex_ungetch(lex, ch);
1004             ch = '\\';
1005             break;
1006         }
1007         /* we reached a linemerge */
1008         lex_tokench(lex, '\n');
1009         continue;
1010     }
1011
1012     if (lex->flags.preprocessing && (ch == TOKEN_WHITE || ch == TOKEN_EOL || ch == TOKEN_FATAL)) {
1013         return (lex->tok.ttype = ch);
1014     }
1015
1016     lex->sline = lex->line;
1017     lex->tok.ctx.line = lex->sline;
1018     lex->tok.ctx.file = lex->name;
1019
1020     if (lex->eof)
1021         return (lex->tok.ttype = TOKEN_FATAL);
1022
1023     if (ch == EOF) {
1024         lex->eof = true;
1025         return (lex->tok.ttype = TOKEN_EOF);
1026     }
1027
1028     /* modelgen / spiritgen commands */
1029     if (ch == '$' && !lex->flags.preprocessing) {
1030         const char *v;
1031         size_t frame;
1032
1033         ch = lex_getch(lex);
1034         if (!isident_start(ch)) {
1035             lexerror(lex, "hanging '$' modelgen/spritegen command line");
1036             return lex_do(lex);
1037         }
1038         lex_tokench(lex, ch);
1039         if (!lex_finish_ident(lex))
1040             return (lex->tok.ttype = TOKEN_ERROR);
1041         lex_endtoken(lex);
1042         /* skip the known commands */
1043         v = lex->tok.value;
1044
1045         if (!strcmp(v, "frame") || !strcmp(v, "framesave"))
1046         {
1047             /* frame/framesave command works like an enum
1048              * similar to fteqcc we handle this in the lexer.
1049              * The reason for this is that it is sensitive to newlines,
1050              * which the parser is unaware of
1051              */
1052             if (!lex_finish_frames(lex))
1053                  return (lex->tok.ttype = TOKEN_ERROR);
1054             return lex_do(lex);
1055         }
1056
1057         if (!strcmp(v, "framevalue"))
1058         {
1059             ch = lex_getch(lex);
1060             while (ch != EOF && isspace(ch) && ch != '\n')
1061                 ch = lex_getch(lex);
1062
1063             if (!isdigit(ch)) {
1064                 lexerror(lex, "$framevalue requires an integer parameter");
1065                 return lex_do(lex);
1066             }
1067
1068             lex_token_new(lex);
1069             lex->tok.ttype = lex_finish_digit(lex, ch);
1070             lex_endtoken(lex);
1071             if (lex->tok.ttype != TOKEN_INTCONST) {
1072                 lexerror(lex, "$framevalue requires an integer parameter");
1073                 return lex_do(lex);
1074             }
1075             lex->framevalue = lex->tok.constval.i;
1076             return lex_do(lex);
1077         }
1078
1079         if (!strcmp(v, "framerestore"))
1080         {
1081             int rc;
1082
1083             lex_token_new(lex);
1084
1085             rc = lex_parse_frame(lex);
1086
1087             if (rc > 0) {
1088                 lexerror(lex, "$framerestore requires a framename parameter");
1089                 return lex_do(lex);
1090             }
1091             if (rc < 0)
1092                 return (lex->tok.ttype = TOKEN_FATAL);
1093
1094             v = lex->tok.value;
1095             for (frame = 0; frame < vec_size(lex->frames); ++frame) {
1096                 if (!strcmp(v, lex->frames[frame].name)) {
1097                     lex->framevalue = lex->frames[frame].value;
1098                     return lex_do(lex);
1099                 }
1100             }
1101             lexerror(lex, "unknown framename `%s`", v);
1102             return lex_do(lex);
1103         }
1104
1105         if (!strcmp(v, "modelname"))
1106         {
1107             int rc;
1108
1109             lex_token_new(lex);
1110
1111             rc = lex_parse_frame(lex);
1112
1113             if (rc > 0) {
1114                 lexerror(lex, "$modelname requires a parameter");
1115                 return lex_do(lex);
1116             }
1117             if (rc < 0)
1118                 return (lex->tok.ttype = TOKEN_FATAL);
1119
1120             if (lex->modelname) {
1121                 frame_macro m;
1122                 m.value = lex->framevalue;
1123                 m.name = lex->modelname;
1124                 lex->modelname = NULL;
1125                 vec_push(lex->frames, m);
1126             }
1127             lex->modelname = lex->tok.value;
1128             lex->tok.value = NULL;
1129             return lex_do(lex);
1130         }
1131
1132         if (!strcmp(v, "flush"))
1133         {
1134             size_t fi;
1135             for (fi = 0; fi < vec_size(lex->frames); ++fi)
1136                 mem_d(lex->frames[fi].name);
1137             vec_free(lex->frames);
1138             /* skip line (fteqcc does it too) */
1139             ch = lex_getch(lex);
1140             while (ch != EOF && ch != '\n')
1141                 ch = lex_getch(lex);
1142             return lex_do(lex);
1143         }
1144
1145         if (!strcmp(v, "cd") ||
1146             !strcmp(v, "origin") ||
1147             !strcmp(v, "base") ||
1148             !strcmp(v, "flags") ||
1149             !strcmp(v, "scale") ||
1150             !strcmp(v, "skin"))
1151         {
1152             /* skip line */
1153             ch = lex_getch(lex);
1154             while (ch != EOF && ch != '\n')
1155                 ch = lex_getch(lex);
1156             return lex_do(lex);
1157         }
1158
1159         for (frame = 0; frame < vec_size(lex->frames); ++frame) {
1160             if (!strcmp(v, lex->frames[frame].name)) {
1161                 lex->tok.constval.i = lex->frames[frame].value;
1162                 return (lex->tok.ttype = TOKEN_INTCONST);
1163             }
1164         }
1165
1166         lexerror(lex, "invalid frame macro");
1167         return lex_do(lex);
1168     }
1169
1170     /* single-character tokens */
1171     switch (ch)
1172     {
1173         case '[':
1174             nextch = lex_getch(lex);
1175             if (nextch == '[') {
1176                 lex_tokench(lex, ch);
1177                 lex_tokench(lex, nextch);
1178                 lex_endtoken(lex);
1179                 return (lex->tok.ttype = TOKEN_ATTRIBUTE_OPEN);
1180             }
1181             lex_ungetch(lex, nextch);
1182             /* FALL THROUGH */
1183         case '(':
1184         case ':':
1185         case '?':
1186             lex_tokench(lex, ch);
1187             lex_endtoken(lex);
1188             if (lex->flags.noops)
1189                 return (lex->tok.ttype = ch);
1190             else
1191                 return (lex->tok.ttype = TOKEN_OPERATOR);
1192
1193         case ']':
1194             if (lex->flags.noops) {
1195                 nextch = lex_getch(lex);
1196                 if (nextch == ']') {
1197                     lex_tokench(lex, ch);
1198                     lex_tokench(lex, nextch);
1199                     lex_endtoken(lex);
1200                     return (lex->tok.ttype = TOKEN_ATTRIBUTE_CLOSE);
1201                 }
1202                 lex_ungetch(lex, nextch);
1203             }
1204             /* FALL THROUGH */
1205         case ')':
1206         case ';':
1207         case '{':
1208         case '}':
1209
1210         case '#':
1211             lex_tokench(lex, ch);
1212             lex_endtoken(lex);
1213             return (lex->tok.ttype = ch);
1214         default:
1215             break;
1216     }
1217
1218     if (ch == '.') {
1219         nextch = lex_getch(lex);
1220         /* digits starting with a dot */
1221         if (isdigit(nextch)) {
1222             lex_ungetch(lex, nextch);
1223             lex->tok.ttype = lex_finish_digit(lex, ch);
1224             lex_endtoken(lex);
1225             return lex->tok.ttype;
1226         }
1227         lex_ungetch(lex, nextch);
1228     }
1229
1230     if (lex->flags.noops)
1231     {
1232         /* Detect characters early which are normally
1233          * operators OR PART of an operator.
1234          */
1235         switch (ch)
1236         {
1237             /*
1238             case '+':
1239             case '-':
1240             */
1241             case '*':
1242             case '/':
1243             case '<':
1244             case '>':
1245             case '=':
1246             case '&':
1247             case '|':
1248             case '^':
1249             case '~':
1250             case ',':
1251             case '!':
1252                 lex_tokench(lex, ch);
1253                 lex_endtoken(lex);
1254                 return (lex->tok.ttype = ch);
1255             default:
1256                 break;
1257         }
1258     }
1259
1260     if (ch == '.')
1261     {
1262         lex_tokench(lex, ch);
1263         /* peak ahead once */
1264         nextch = lex_getch(lex);
1265         if (nextch != '.') {
1266             lex_ungetch(lex, nextch);
1267             lex_endtoken(lex);
1268             if (lex->flags.noops)
1269                 return (lex->tok.ttype = ch);
1270             else
1271                 return (lex->tok.ttype = TOKEN_OPERATOR);
1272         }
1273         /* peak ahead again */
1274         nextch = lex_getch(lex);
1275         if (nextch != '.') {
1276             lex_ungetch(lex, nextch);
1277             lex_ungetch(lex, '.');
1278             lex_endtoken(lex);
1279             if (lex->flags.noops)
1280                 return (lex->tok.ttype = ch);
1281             else
1282                 return (lex->tok.ttype = TOKEN_OPERATOR);
1283         }
1284         /* fill the token to be "..." */
1285         lex_tokench(lex, ch);
1286         lex_tokench(lex, ch);
1287         lex_endtoken(lex);
1288         return (lex->tok.ttype = TOKEN_DOTS);
1289     }
1290
1291     if (ch == ',' || ch == '.') {
1292         lex_tokench(lex, ch);
1293         lex_endtoken(lex);
1294         return (lex->tok.ttype = TOKEN_OPERATOR);
1295     }
1296
1297     if (ch == '+' || ch == '-' || /* ++, --, +=, -=  and -> as well! */
1298         ch == '>' || ch == '<' || /* <<, >>, <=, >=                  */
1299         ch == '=' || ch == '!' || /* <=>, ==, !=                     */
1300         ch == '&' || ch == '|' || /* &&, ||, &=, |=                  */
1301         ch == '~'                 /* ~=, ~                           */
1302     )  {
1303         lex_tokench(lex, ch);
1304
1305         nextch = lex_getch(lex);
1306         if ((nextch == '=' && ch != '<') || (nextch == ch && ch != '!')) {
1307             lex_tokench(lex, nextch);
1308         } else if (ch == '<' && nextch == '=') {
1309             lex_tokench(lex, nextch);
1310             if ((thirdch = lex_getch(lex)) == '>')
1311                 lex_tokench(lex, thirdch);
1312             else
1313                 lex_ungetch(lex, thirdch);
1314
1315         } else if (ch == '-' && nextch == '>') {
1316             lex_tokench(lex, nextch);
1317         } else if (ch == '&' && nextch == '~') {
1318             thirdch = lex_getch(lex);
1319             if (thirdch != '=') {
1320                 lex_ungetch(lex, thirdch);
1321                 lex_ungetch(lex, nextch);
1322             }
1323             else {
1324                 lex_tokench(lex, nextch);
1325                 lex_tokench(lex, thirdch);
1326             }
1327         }
1328         else if (lex->flags.preprocessing &&
1329                  ch == '-' && isdigit(nextch))
1330         {
1331             lex->tok.ttype = lex_finish_digit(lex, nextch);
1332             if (lex->tok.ttype == TOKEN_INTCONST)
1333                 lex->tok.constval.i = -lex->tok.constval.i;
1334             else
1335                 lex->tok.constval.f = -lex->tok.constval.f;
1336             lex_endtoken(lex);
1337             return lex->tok.ttype;
1338         } else {
1339             lex_ungetch(lex, nextch);
1340         }
1341
1342         lex_endtoken(lex);
1343         return (lex->tok.ttype = TOKEN_OPERATOR);
1344     }
1345
1346     /*
1347     if (ch == '^' || ch == '~' || ch == '!')
1348     {
1349         lex_tokench(lex, ch);
1350         lex_endtoken(lex);
1351         return (lex->tok.ttype = TOKEN_OPERATOR);
1352     }
1353     */
1354
1355     if (ch == '*' || ch == '/') /* *=, /= */
1356     {
1357         lex_tokench(lex, ch);
1358
1359         nextch = lex_getch(lex);
1360         if (nextch == '=' || nextch == '*') {
1361             lex_tokench(lex, nextch);
1362         } else
1363             lex_ungetch(lex, nextch);
1364
1365         lex_endtoken(lex);
1366         return (lex->tok.ttype = TOKEN_OPERATOR);
1367     }
1368
1369     if (ch == '%') {
1370         lex_tokench(lex, ch);
1371         lex_endtoken(lex);
1372         return (lex->tok.ttype = TOKEN_OPERATOR);
1373     }
1374
1375     if (isident_start(ch))
1376     {
1377         const char *v;
1378
1379         lex_tokench(lex, ch);
1380         if (!lex_finish_ident(lex)) {
1381             /* error? */
1382             return (lex->tok.ttype = TOKEN_ERROR);
1383         }
1384         lex_endtoken(lex);
1385         lex->tok.ttype = TOKEN_IDENT;
1386
1387         v = lex->tok.value;
1388         if (!strcmp(v, "void")) {
1389             lex->tok.ttype = TOKEN_TYPENAME;
1390             lex->tok.constval.t = TYPE_VOID;
1391         } else if (!strcmp(v, "int")) {
1392             lex->tok.ttype = TOKEN_TYPENAME;
1393             lex->tok.constval.t = TYPE_INTEGER;
1394         } else if (!strcmp(v, "float")) {
1395             lex->tok.ttype = TOKEN_TYPENAME;
1396             lex->tok.constval.t = TYPE_FLOAT;
1397         } else if (!strcmp(v, "string")) {
1398             lex->tok.ttype = TOKEN_TYPENAME;
1399             lex->tok.constval.t = TYPE_STRING;
1400         } else if (!strcmp(v, "entity")) {
1401             lex->tok.ttype = TOKEN_TYPENAME;
1402             lex->tok.constval.t = TYPE_ENTITY;
1403         } else if (!strcmp(v, "vector")) {
1404             lex->tok.ttype = TOKEN_TYPENAME;
1405             lex->tok.constval.t = TYPE_VECTOR;
1406         } else {
1407             size_t kw;
1408             for (kw = 0; kw < num_keywords_qc; ++kw) {
1409                 if (!strcmp(v, keywords_qc[kw]))
1410                     return (lex->tok.ttype = TOKEN_KEYWORD);
1411             }
1412             if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC) {
1413                 for (kw = 0; kw < num_keywords_fg; ++kw) {
1414                     if (!strcmp(v, keywords_fg[kw]))
1415                         return (lex->tok.ttype = TOKEN_KEYWORD);
1416                 }
1417             }
1418         }
1419
1420         return lex->tok.ttype;
1421     }
1422
1423     if (ch == '"')
1424     {
1425         lex->flags.nodigraphs = true;
1426         if (lex->flags.preprocessing)
1427             lex_tokench(lex, ch);
1428         lex->tok.ttype = lex_finish_string(lex, '"');
1429         if (lex->flags.preprocessing)
1430             lex_tokench(lex, ch);
1431         while (!lex->flags.preprocessing && lex->tok.ttype == TOKEN_STRINGCONST)
1432         {
1433             /* Allow c style "string" "continuation" */
1434             ch = lex_skipwhite(lex, false);
1435             if (ch != '"') {
1436                 lex_ungetch(lex, ch);
1437                 break;
1438             }
1439
1440             lex->tok.ttype = lex_finish_string(lex, '"');
1441         }
1442         lex->flags.nodigraphs = false;
1443         lex_endtoken(lex);
1444         return lex->tok.ttype;
1445     }
1446
1447     if (ch == '\'')
1448     {
1449         /* we parse character constants like string,
1450          * but return TOKEN_CHARCONST, or a vector type if it fits...
1451          * Likewise actual unescaping has to be done by the parser.
1452          * The difference is we don't allow 'char' 'continuation'.
1453          */
1454         if (lex->flags.preprocessing)
1455             lex_tokench(lex, ch);
1456         lex->tok.ttype = lex_finish_string(lex, '\'');
1457         if (lex->flags.preprocessing)
1458             lex_tokench(lex, ch);
1459         lex_endtoken(lex);
1460
1461         lex->tok.ttype = TOKEN_CHARCONST;
1462          /* It's a vector if we can successfully scan 3 floats */
1463 #ifdef _MSC_VER
1464         if (sscanf_s(lex->tok.value, " %f %f %f ",
1465                    &lex->tok.constval.v.x, &lex->tok.constval.v.y, &lex->tok.constval.v.z) == 3)
1466 #else
1467         if (sscanf(lex->tok.value, " %f %f %f ",
1468                    &lex->tok.constval.v.x, &lex->tok.constval.v.y, &lex->tok.constval.v.z) == 3)
1469 #endif
1470
1471         {
1472              lex->tok.ttype = TOKEN_VECTORCONST;
1473         }
1474         else
1475         {
1476             if (!lex->flags.preprocessing && strlen(lex->tok.value) > 1) {
1477                 uchar_t u8char;
1478                 /* check for a valid utf8 character */
1479                 if (!OPTS_FLAG(UTF8) || !u8_analyze(lex->tok.value, NULL, NULL, &u8char, 8)) {
1480                     if (lexwarn(lex, WARN_MULTIBYTE_CHARACTER,
1481                                 ( OPTS_FLAG(UTF8) ? "invalid multibyte character sequence `%s`"
1482                                                   : "multibyte character: `%s`" ),
1483                                 lex->tok.value))
1484                         return (lex->tok.ttype = TOKEN_ERROR);
1485                 }
1486                 else
1487                     lex->tok.constval.i = u8char;
1488             }
1489             else
1490                 lex->tok.constval.i = lex->tok.value[0];
1491         }
1492
1493         return lex->tok.ttype;
1494     }
1495
1496     if (isdigit(ch))
1497     {
1498         lex->tok.ttype = lex_finish_digit(lex, ch);
1499         lex_endtoken(lex);
1500         return lex->tok.ttype;
1501     }
1502
1503     if (lex->flags.preprocessing) {
1504         lex_tokench(lex, ch);
1505         lex_endtoken(lex);
1506         return (lex->tok.ttype = ch);
1507     }
1508
1509     lexerror(lex, "unknown token: `%s`", lex->tok.value);
1510     return (lex->tok.ttype = TOKEN_ERROR);
1511 }