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