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