]> git.xonotic.org Git - xonotic/gmqcc.git/blob - lexer.c
Merge branch 'master' of github.com:graphitemaster/gmqcc
[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 <ctype.h>
24 #include <string.h>
25 #include <stdlib.h>
26
27 #include "gmqcc.h"
28 #include "lexer.h"
29 /*
30  * List of Keywords
31  */
32
33 /* original */
34 static const char *keywords_qc[] = {
35     "for", "do", "while",
36     "if", "else",
37     "local",
38     "return",
39     "const"
40 };
41 static size_t num_keywords_qc = sizeof(keywords_qc) / sizeof(keywords_qc[0]);
42
43 /* For fte/gmgqcc */
44 static const char *keywords_fg[] = {
45     "switch", "case", "default",
46     "struct", "union",
47     "break", "continue",
48     "typedef",
49     "goto",
50
51     "__builtin_debug_printtype"
52 };
53 static size_t num_keywords_fg = sizeof(keywords_fg) / sizeof(keywords_fg[0]);
54
55 /*
56  * Lexer code
57  */
58
59 static char* *lex_filenames;
60
61 static void lexerror(lex_file *lex, const char *fmt, ...)
62 {
63     va_list ap;
64
65     va_start(ap, fmt);
66     if (lex)
67         con_vprintmsg(LVL_ERROR, lex->name, lex->sline, lex->column, "parse error", fmt, ap);
68     else
69         con_vprintmsg(LVL_ERROR, "", 0, 0, "parse error", fmt, ap);
70     va_end(ap);
71 }
72
73 static bool lexwarn(lex_file *lex, int warntype, const char *fmt, ...)
74 {
75     bool    r;
76     lex_ctx ctx;
77     va_list ap;
78
79     ctx.file = lex->name;
80     ctx.line = lex->sline;
81
82     va_start(ap, fmt);
83     r = vcompile_warning(ctx, warntype, fmt, ap);
84     va_end(ap);
85     return r;
86 }
87
88
89 #if 0
90 token* token_new()
91 {
92     token *tok = (token*)mem_a(sizeof(token));
93     if (!tok)
94         return NULL;
95     memset(tok, 0, sizeof(*tok));
96     return tok;
97 }
98
99 void token_delete(token *self)
100 {
101     if (self->next && self->next->prev == self)
102         self->next->prev = self->prev;
103     if (self->prev && self->prev->next == self)
104         self->prev->next = self->next;
105     MEM_VECTOR_CLEAR(self, value);
106     mem_d(self);
107 }
108
109 token* token_copy(const token *cp)
110 {
111     token* self = token_new();
112     if (!self)
113         return NULL;
114     /* copy the value */
115     self->value_alloc = cp->value_count + 1;
116     self->value_count = cp->value_count;
117     self->value = (char*)mem_a(self->value_alloc);
118     if (!self->value) {
119         mem_d(self);
120         return NULL;
121     }
122     memcpy(self->value, cp->value, cp->value_count);
123     self->value[self->value_alloc-1] = 0;
124
125     /* rest */
126     self->ctx = cp->ctx;
127     self->ttype = cp->ttype;
128     memcpy(&self->constval, &cp->constval, sizeof(self->constval));
129     return self;
130 }
131
132 void token_delete_all(token *t)
133 {
134     token *n;
135
136     do {
137         n = t->next;
138         token_delete(t);
139         t = n;
140     } while(t);
141 }
142
143 token* token_copy_all(const token *cp)
144 {
145     token *cur;
146     token *out;
147
148     out = cur = token_copy(cp);
149     if (!out)
150         return NULL;
151
152     while (cp->next) {
153         cp = cp->next;
154         cur->next = token_copy(cp);
155         if (!cur->next) {
156             token_delete_all(out);
157             return NULL;
158         }
159         cur->next->prev = cur;
160         cur = cur->next;
161     }
162
163     return out;
164 }
165 #else
166 static void lex_token_new(lex_file *lex)
167 {
168 #if 0
169     if (lex->tok)
170         token_delete(lex->tok);
171     lex->tok = token_new();
172 #else
173     if (lex->tok.value)
174         vec_shrinkto(lex->tok.value, 0);
175         
176     lex->tok.constval.t  = 0;
177     lex->tok.ctx.line    = lex->sline;
178     lex->tok.ctx.file    = lex->name;
179     lex->tok.ctx.column  = lex->column;
180 #endif
181 }
182 #endif
183
184 lex_file* lex_open(const char *file)
185 {
186     lex_file *lex;
187     FILE *in = fs_file_open(file, "rb");
188
189     if (!in) {
190         lexerror(NULL, "open failed: '%s'\n", file);
191         return NULL;
192     }
193
194     lex = (lex_file*)mem_a(sizeof(*lex));
195     if (!lex) {
196         fs_file_close(in);
197         lexerror(NULL, "out of memory\n");
198         return NULL;
199     }
200
201     memset(lex, 0, sizeof(*lex));
202
203     lex->file    = in;
204     lex->name    = util_strdup(file);
205     lex->line    = 1; /* we start counting at 1 */
206     lex->column  = 0;
207     lex->peekpos = 0;
208     lex->eof     = false;
209
210     vec_push(lex_filenames, lex->name);
211     return lex;
212 }
213
214 lex_file* lex_open_string(const char *str, size_t len, const char *name)
215 {
216     lex_file *lex;
217
218     lex = (lex_file*)mem_a(sizeof(*lex));
219     if (!lex) {
220         lexerror(NULL, "out of memory\n");
221         return NULL;
222     }
223
224     memset(lex, 0, sizeof(*lex));
225
226     lex->file = NULL;
227     lex->open_string        = str;
228     lex->open_string_length = len;
229     lex->open_string_pos    = 0;
230
231     lex->name    = util_strdup(name ? name : "<string-source>");
232     lex->line    = 1; /* we start counting at 1 */
233     lex->peekpos = 0;
234     lex->eof     = false;
235     lex->column  = 0;
236
237     vec_push(lex_filenames, lex->name);
238
239     return lex;
240 }
241
242 void lex_cleanup(void)
243 {
244     size_t i;
245     for (i = 0; i < vec_size(lex_filenames); ++i)
246         mem_d(lex_filenames[i]);
247     vec_free(lex_filenames);
248 }
249
250 void lex_close(lex_file *lex)
251 {
252     size_t i;
253     for (i = 0; i < vec_size(lex->frames); ++i)
254         mem_d(lex->frames[i].name);
255     vec_free(lex->frames);
256
257     if (lex->modelname)
258         vec_free(lex->modelname);
259
260     if (lex->file)
261         fs_file_close(lex->file);
262 #if 0
263     if (lex->tok)
264         token_delete(lex->tok);
265 #else
266     vec_free(lex->tok.value);
267 #endif
268     /* mem_d(lex->name); collected in lex_filenames */
269     mem_d(lex);
270 }
271
272 static int lex_fgetc(lex_file *lex)
273 {
274     if (lex->file) {
275         lex->column++;
276         return fs_file_getc(lex->file);
277     }
278     if (lex->open_string) {
279         if (lex->open_string_pos >= lex->open_string_length)
280             return EOF;
281         lex->column++;
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 (!lex->push_line && c2 == '\n') {
298         lex->line++;
299         lex->column = 0;
300     }
301     
302     if (c2 != '?') {
303         lex_ungetch(lex, c2);
304         return old;
305     }
306
307     c3 = lex_fgetc(lex);
308     if (!lex->push_line && c3 == '\n') {
309         lex->line++;
310         lex->column = 0;
311     }
312     
313     switch (c3) {
314         case '=': return '#';
315         case '/': return '\\';
316         case '\'': return '^';
317         case '(': return '[';
318         case ')': return ']';
319         case '!': return '|';
320         case '<': return '{';
321         case '>': return '}';
322         case '-': return '~';
323         default:
324             lex_ungetch(lex, c3);
325             lex_ungetch(lex, c2);
326             return old;
327     }
328 }
329
330 static int lex_try_digraph(lex_file *lex, int ch)
331 {
332     int c2;
333     c2 = lex_fgetc(lex);
334     /* we just used fgetc() so count lines
335      * need to offset a \n the ungetch would recognize
336      */
337     if (!lex->push_line && c2 == '\n')
338         lex->line++;
339     if      (ch == '<' && c2 == ':')
340         return '[';
341     else if (ch == ':' && c2 == '>')
342         return ']';
343     else if (ch == '<' && c2 == '%')
344         return '{';
345     else if (ch == '%' && c2 == '>')
346         return '}';
347     else if (ch == '%' && c2 == ':')
348         return '#';
349     lex_ungetch(lex, c2);
350     return ch;
351 }
352
353 static int lex_getch(lex_file *lex)
354 {
355     int ch;
356
357     if (lex->peekpos) {
358         lex->peekpos--;
359         if (!lex->push_line && lex->peek[lex->peekpos] == '\n')
360             lex->line++;
361         return lex->peek[lex->peekpos];
362     }
363
364     ch = lex_fgetc(lex);
365     if (!lex->push_line && ch == '\n')
366         lex->line++;
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 isalpha(ch) || ch == '_';
392 }
393
394 static bool isident(int ch)
395 {
396     return isident_start(ch) || 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 && 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 && 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' && 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     uchar_t chr;
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 = u8_fromchar(chr, u8buf, sizeof(u8buf));
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                         /* the last character will be inserted with the tokench() call
891                          * below the switch
892                          */
893                         ch = u8buf[uc];
894                     }
895                 }
896                 else
897                     ch = chr;
898                 break;
899             case '\n':  ch = '\n'; break;
900
901             default:
902                 lexwarn(lex, WARN_UNKNOWN_CONTROL_SEQUENCE, "unrecognized control sequence: \\%c", ch);
903                 /* so we just add the character plus backslash no matter what it actually is */
904                 lex_tokench(lex, '\\');
905             }
906             /* add the character finally */
907             lex_tokench(lex, ch);
908         }
909         else
910             lex_tokench(lex, ch);
911     }
912     lexerror(lex, "unexpected end of file within string constant");
913     lex_ungetch(lex, EOF); /* next token to be TOKEN_EOF */
914     return (lex->tok.ttype = TOKEN_ERROR);
915 }
916
917 static int GMQCC_WARN lex_finish_digit(lex_file *lex, int lastch)
918 {
919     bool ishex = false;
920
921     int  ch = lastch;
922
923     /* parse a number... */
924     if (ch == '.')
925         lex->tok.ttype = TOKEN_FLOATCONST;
926     else
927         lex->tok.ttype = TOKEN_INTCONST;
928
929     lex_tokench(lex, ch);
930
931     ch = lex_getch(lex);
932     if (ch != '.' && !isdigit(ch))
933     {
934         if (lastch != '0' || ch != 'x')
935         {
936             /* end of the number or EOF */
937             lex_ungetch(lex, ch);
938             lex_endtoken(lex);
939
940             lex->tok.constval.i = lastch - '0';
941             return lex->tok.ttype;
942         }
943
944         ishex = true;
945     }
946
947     /* EOF would have been caught above */
948
949     if (ch != '.')
950     {
951         lex_tokench(lex, ch);
952         ch = lex_getch(lex);
953         while (isdigit(ch) || (ishex && isxdigit_only(ch)))
954         {
955             lex_tokench(lex, ch);
956             ch = lex_getch(lex);
957         }
958     }
959     /* NOT else, '.' can come from above as well */
960     if (lex->tok.ttype != TOKEN_FLOATCONST && ch == '.' && !ishex)
961     {
962         /* Allow floating comma in non-hex mode */
963         lex->tok.ttype = TOKEN_FLOATCONST;
964         lex_tokench(lex, ch);
965
966         /* continue digits-only */
967         ch = lex_getch(lex);
968         while (isdigit(ch))
969         {
970             lex_tokench(lex, ch);
971             ch = lex_getch(lex);
972         }
973     }
974     /* put back the last character */
975     /* but do not put back the trailing 'f' or a float */
976     if (lex->tok.ttype == TOKEN_FLOATCONST && ch == 'f')
977         ch = lex_getch(lex);
978
979     /* generally we don't want words to follow numbers: */
980     if (isident(ch)) {
981         lexerror(lex, "unexpected trailing characters after number");
982         return (lex->tok.ttype = TOKEN_ERROR);
983     }
984     lex_ungetch(lex, ch);
985
986     lex_endtoken(lex);
987     if (lex->tok.ttype == TOKEN_FLOATCONST)
988         lex->tok.constval.f = strtod(lex->tok.value, NULL);
989     else
990         lex->tok.constval.i = strtol(lex->tok.value, NULL, 0);
991     return lex->tok.ttype;
992 }
993
994 int lex_do(lex_file *lex)
995 {
996     int ch, nextch, thirdch;
997     bool hadwhite = false;
998
999     lex_token_new(lex);
1000 #if 0
1001     if (!lex->tok)
1002         return TOKEN_FATAL;
1003 #endif
1004
1005     while (true) {
1006         ch = lex_skipwhite(lex, hadwhite);
1007         hadwhite = true;
1008         if (!lex->flags.mergelines || ch != '\\')
1009             break;
1010         ch = lex_getch(lex);
1011         if (ch == '\r')
1012             ch = lex_getch(lex);
1013         if (ch != '\n') {
1014             lex_ungetch(lex, ch);
1015             ch = '\\';
1016             break;
1017         }
1018         /* we reached a linemerge */
1019         lex_tokench(lex, '\n');
1020         continue;
1021     }
1022
1023     if (lex->flags.preprocessing && (ch == TOKEN_WHITE || ch == TOKEN_EOL || ch == TOKEN_FATAL)) {
1024         return (lex->tok.ttype = ch);
1025     }
1026
1027     lex->sline = lex->line;
1028     lex->tok.ctx.line = lex->sline;
1029     lex->tok.ctx.file = lex->name;
1030
1031     if (lex->eof)
1032         return (lex->tok.ttype = TOKEN_FATAL);
1033
1034     if (ch == EOF) {
1035         lex->eof = true;
1036         return (lex->tok.ttype = TOKEN_EOF);
1037     }
1038
1039     /* modelgen / spiritgen commands */
1040     if (ch == '$' && !lex->flags.preprocessing) {
1041         const char *v;
1042         size_t frame;
1043
1044         ch = lex_getch(lex);
1045         if (!isident_start(ch)) {
1046             lexerror(lex, "hanging '$' modelgen/spritegen command line");
1047             return lex_do(lex);
1048         }
1049         lex_tokench(lex, ch);
1050         if (!lex_finish_ident(lex))
1051             return (lex->tok.ttype = TOKEN_ERROR);
1052         lex_endtoken(lex);
1053         /* skip the known commands */
1054         v = lex->tok.value;
1055
1056         if (!strcmp(v, "frame") || !strcmp(v, "framesave"))
1057         {
1058             /* frame/framesave command works like an enum
1059              * similar to fteqcc we handle this in the lexer.
1060              * The reason for this is that it is sensitive to newlines,
1061              * which the parser is unaware of
1062              */
1063             if (!lex_finish_frames(lex))
1064                  return (lex->tok.ttype = TOKEN_ERROR);
1065             return lex_do(lex);
1066         }
1067
1068         if (!strcmp(v, "framevalue"))
1069         {
1070             ch = lex_getch(lex);
1071             while (ch != EOF && isspace(ch) && ch != '\n')
1072                 ch = lex_getch(lex);
1073
1074             if (!isdigit(ch)) {
1075                 lexerror(lex, "$framevalue requires an integer parameter");
1076                 return lex_do(lex);
1077             }
1078
1079             lex_token_new(lex);
1080             lex->tok.ttype = lex_finish_digit(lex, ch);
1081             lex_endtoken(lex);
1082             if (lex->tok.ttype != TOKEN_INTCONST) {
1083                 lexerror(lex, "$framevalue requires an integer parameter");
1084                 return lex_do(lex);
1085             }
1086             lex->framevalue = lex->tok.constval.i;
1087             return lex_do(lex);
1088         }
1089
1090         if (!strcmp(v, "framerestore"))
1091         {
1092             int rc;
1093
1094             lex_token_new(lex);
1095
1096             rc = lex_parse_frame(lex);
1097
1098             if (rc > 0) {
1099                 lexerror(lex, "$framerestore requires a framename parameter");
1100                 return lex_do(lex);
1101             }
1102             if (rc < 0)
1103                 return (lex->tok.ttype = TOKEN_FATAL);
1104
1105             v = lex->tok.value;
1106             for (frame = 0; frame < vec_size(lex->frames); ++frame) {
1107                 if (!strcmp(v, lex->frames[frame].name)) {
1108                     lex->framevalue = lex->frames[frame].value;
1109                     return lex_do(lex);
1110                 }
1111             }
1112             lexerror(lex, "unknown framename `%s`", v);
1113             return lex_do(lex);
1114         }
1115
1116         if (!strcmp(v, "modelname"))
1117         {
1118             int rc;
1119
1120             lex_token_new(lex);
1121
1122             rc = lex_parse_frame(lex);
1123
1124             if (rc > 0) {
1125                 lexerror(lex, "$modelname requires a parameter");
1126                 return lex_do(lex);
1127             }
1128             if (rc < 0)
1129                 return (lex->tok.ttype = TOKEN_FATAL);
1130
1131             if (lex->modelname) {
1132                 frame_macro m;
1133                 m.value = lex->framevalue;
1134                 m.name = lex->modelname;
1135                 lex->modelname = NULL;
1136                 vec_push(lex->frames, m);
1137             }
1138             lex->modelname = lex->tok.value;
1139             lex->tok.value = NULL;
1140             return lex_do(lex);
1141         }
1142
1143         if (!strcmp(v, "flush"))
1144         {
1145             size_t fi;
1146             for (fi = 0; fi < vec_size(lex->frames); ++fi)
1147                 mem_d(lex->frames[fi].name);
1148             vec_free(lex->frames);
1149             /* skip line (fteqcc does it too) */
1150             ch = lex_getch(lex);
1151             while (ch != EOF && ch != '\n')
1152                 ch = lex_getch(lex);
1153             return lex_do(lex);
1154         }
1155
1156         if (!strcmp(v, "cd") ||
1157             !strcmp(v, "origin") ||
1158             !strcmp(v, "base") ||
1159             !strcmp(v, "flags") ||
1160             !strcmp(v, "scale") ||
1161             !strcmp(v, "skin"))
1162         {
1163             /* skip line */
1164             ch = lex_getch(lex);
1165             while (ch != EOF && ch != '\n')
1166                 ch = lex_getch(lex);
1167             return lex_do(lex);
1168         }
1169
1170         for (frame = 0; frame < vec_size(lex->frames); ++frame) {
1171             if (!strcmp(v, lex->frames[frame].name)) {
1172                 lex->tok.constval.i = lex->frames[frame].value;
1173                 return (lex->tok.ttype = TOKEN_INTCONST);
1174             }
1175         }
1176
1177         lexerror(lex, "invalid frame macro");
1178         return lex_do(lex);
1179     }
1180
1181     /* single-character tokens */
1182     switch (ch)
1183     {
1184         case '[':
1185             nextch = lex_getch(lex);
1186             if (nextch == '[') {
1187                 lex_tokench(lex, ch);
1188                 lex_tokench(lex, nextch);
1189                 lex_endtoken(lex);
1190                 return (lex->tok.ttype = TOKEN_ATTRIBUTE_OPEN);
1191             }
1192             lex_ungetch(lex, nextch);
1193             /* FALL THROUGH */
1194         case '(':
1195         case ':':
1196         case '?':
1197             lex_tokench(lex, ch);
1198             lex_endtoken(lex);
1199             if (lex->flags.noops)
1200                 return (lex->tok.ttype = ch);
1201             else
1202                 return (lex->tok.ttype = TOKEN_OPERATOR);
1203
1204         case ']':
1205             if (lex->flags.noops) {
1206                 nextch = lex_getch(lex);
1207                 if (nextch == ']') {
1208                     lex_tokench(lex, ch);
1209                     lex_tokench(lex, nextch);
1210                     lex_endtoken(lex);
1211                     return (lex->tok.ttype = TOKEN_ATTRIBUTE_CLOSE);
1212                 }
1213                 lex_ungetch(lex, nextch);
1214             }
1215             /* FALL THROUGH */
1216         case ')':
1217         case ';':
1218         case '{':
1219         case '}':
1220
1221         case '#':
1222             lex_tokench(lex, ch);
1223             lex_endtoken(lex);
1224             return (lex->tok.ttype = ch);
1225         default:
1226             break;
1227     }
1228
1229     if (ch == '.') {
1230         nextch = lex_getch(lex);
1231         /* digits starting with a dot */
1232         if (isdigit(nextch)) {
1233             lex_ungetch(lex, nextch);
1234             lex->tok.ttype = lex_finish_digit(lex, ch);
1235             lex_endtoken(lex);
1236             return lex->tok.ttype;
1237         }
1238         lex_ungetch(lex, nextch);
1239     }
1240
1241     if (lex->flags.noops)
1242     {
1243         /* Detect characters early which are normally
1244          * operators OR PART of an operator.
1245          */
1246         switch (ch)
1247         {
1248             /*
1249             case '+':
1250             case '-':
1251             */
1252             case '*':
1253             case '/':
1254             case '<':
1255             case '>':
1256             case '=':
1257             case '&':
1258             case '|':
1259             case '^':
1260             case '~':
1261             case ',':
1262             case '!':
1263                 lex_tokench(lex, ch);
1264                 lex_endtoken(lex);
1265                 return (lex->tok.ttype = ch);
1266             default:
1267                 break;
1268         }
1269     }
1270
1271     if (ch == '.')
1272     {
1273         lex_tokench(lex, ch);
1274         /* peak ahead once */
1275         nextch = lex_getch(lex);
1276         if (nextch != '.') {
1277             lex_ungetch(lex, nextch);
1278             lex_endtoken(lex);
1279             if (lex->flags.noops)
1280                 return (lex->tok.ttype = ch);
1281             else
1282                 return (lex->tok.ttype = TOKEN_OPERATOR);
1283         }
1284         /* peak ahead again */
1285         nextch = lex_getch(lex);
1286         if (nextch != '.') {
1287             lex_ungetch(lex, nextch);
1288             lex_ungetch(lex, '.');
1289             lex_endtoken(lex);
1290             if (lex->flags.noops)
1291                 return (lex->tok.ttype = ch);
1292             else
1293                 return (lex->tok.ttype = TOKEN_OPERATOR);
1294         }
1295         /* fill the token to be "..." */
1296         lex_tokench(lex, ch);
1297         lex_tokench(lex, ch);
1298         lex_endtoken(lex);
1299         return (lex->tok.ttype = TOKEN_DOTS);
1300     }
1301
1302     if (ch == ',' || ch == '.') {
1303         lex_tokench(lex, ch);
1304         lex_endtoken(lex);
1305         return (lex->tok.ttype = TOKEN_OPERATOR);
1306     }
1307
1308     if (ch == '+' || ch == '-' || /* ++, --, +=, -=  and -> as well! */
1309         ch == '>' || ch == '<' || /* <<, >>, <=, >=                  */
1310         ch == '=' || ch == '!' || /* <=>, ==, !=                     */
1311         ch == '&' || ch == '|' || /* &&, ||, &=, |=                  */
1312         ch == '~'                 /* ~=, ~                           */
1313     )  {
1314         lex_tokench(lex, ch);
1315
1316         nextch = lex_getch(lex);
1317         if ((nextch == '=' && ch != '<') || (nextch == ch && ch != '!')) {
1318             lex_tokench(lex, nextch);
1319         } else if (ch == '<' && nextch == '=') {
1320             lex_tokench(lex, nextch);
1321             if ((thirdch = lex_getch(lex)) == '>')
1322                 lex_tokench(lex, thirdch);
1323             else
1324                 lex_ungetch(lex, thirdch);
1325
1326         } else if (ch == '-' && nextch == '>') {
1327             lex_tokench(lex, nextch);
1328         } else if (ch == '&' && nextch == '~') {
1329             thirdch = lex_getch(lex);
1330             if (thirdch != '=') {
1331                 lex_ungetch(lex, thirdch);
1332                 lex_ungetch(lex, nextch);
1333             }
1334             else {
1335                 lex_tokench(lex, nextch);
1336                 lex_tokench(lex, thirdch);
1337             }
1338         }
1339         else if (lex->flags.preprocessing &&
1340                  ch == '-' && isdigit(nextch))
1341         {
1342             lex->tok.ttype = lex_finish_digit(lex, nextch);
1343             if (lex->tok.ttype == TOKEN_INTCONST)
1344                 lex->tok.constval.i = -lex->tok.constval.i;
1345             else
1346                 lex->tok.constval.f = -lex->tok.constval.f;
1347             lex_endtoken(lex);
1348             return lex->tok.ttype;
1349         } else {
1350             lex_ungetch(lex, nextch);
1351         }
1352
1353         lex_endtoken(lex);
1354         return (lex->tok.ttype = TOKEN_OPERATOR);
1355     }
1356
1357     /*
1358     if (ch == '^' || ch == '~' || ch == '!')
1359     {
1360         lex_tokench(lex, ch);
1361         lex_endtoken(lex);
1362         return (lex->tok.ttype = TOKEN_OPERATOR);
1363     }
1364     */
1365
1366     if (ch == '*' || ch == '/') /* *=, /= */
1367     {
1368         lex_tokench(lex, ch);
1369
1370         nextch = lex_getch(lex);
1371         if (nextch == '=' || nextch == '*') {
1372             lex_tokench(lex, nextch);
1373         } else
1374             lex_ungetch(lex, nextch);
1375
1376         lex_endtoken(lex);
1377         return (lex->tok.ttype = TOKEN_OPERATOR);
1378     }
1379
1380     if (ch == '%') {
1381         lex_tokench(lex, ch);
1382         lex_endtoken(lex);
1383         return (lex->tok.ttype = TOKEN_OPERATOR);
1384     }
1385
1386     if (isident_start(ch))
1387     {
1388         const char *v;
1389
1390         lex_tokench(lex, ch);
1391         if (!lex_finish_ident(lex)) {
1392             /* error? */
1393             return (lex->tok.ttype = TOKEN_ERROR);
1394         }
1395         lex_endtoken(lex);
1396         lex->tok.ttype = TOKEN_IDENT;
1397
1398         v = lex->tok.value;
1399         if (!strcmp(v, "void")) {
1400             lex->tok.ttype = TOKEN_TYPENAME;
1401             lex->tok.constval.t = TYPE_VOID;
1402         } else if (!strcmp(v, "int")) {
1403             lex->tok.ttype = TOKEN_TYPENAME;
1404             lex->tok.constval.t = TYPE_INTEGER;
1405         } else if (!strcmp(v, "float")) {
1406             lex->tok.ttype = TOKEN_TYPENAME;
1407             lex->tok.constval.t = TYPE_FLOAT;
1408         } else if (!strcmp(v, "string")) {
1409             lex->tok.ttype = TOKEN_TYPENAME;
1410             lex->tok.constval.t = TYPE_STRING;
1411         } else if (!strcmp(v, "entity")) {
1412             lex->tok.ttype = TOKEN_TYPENAME;
1413             lex->tok.constval.t = TYPE_ENTITY;
1414         } else if (!strcmp(v, "vector")) {
1415             lex->tok.ttype = TOKEN_TYPENAME;
1416             lex->tok.constval.t = TYPE_VECTOR;
1417         } else {
1418             size_t kw;
1419             for (kw = 0; kw < num_keywords_qc; ++kw) {
1420                 if (!strcmp(v, keywords_qc[kw]))
1421                     return (lex->tok.ttype = TOKEN_KEYWORD);
1422             }
1423             if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC) {
1424                 for (kw = 0; kw < num_keywords_fg; ++kw) {
1425                     if (!strcmp(v, keywords_fg[kw]))
1426                         return (lex->tok.ttype = TOKEN_KEYWORD);
1427                 }
1428             }
1429         }
1430
1431         return lex->tok.ttype;
1432     }
1433
1434     if (ch == '"')
1435     {
1436         lex->flags.nodigraphs = true;
1437         if (lex->flags.preprocessing)
1438             lex_tokench(lex, ch);
1439         lex->tok.ttype = lex_finish_string(lex, '"');
1440         if (lex->flags.preprocessing)
1441             lex_tokench(lex, ch);
1442         while (!lex->flags.preprocessing && lex->tok.ttype == TOKEN_STRINGCONST)
1443         {
1444             /* Allow c style "string" "continuation" */
1445             ch = lex_skipwhite(lex, false);
1446             if (ch != '"') {
1447                 lex_ungetch(lex, ch);
1448                 break;
1449             }
1450
1451             lex->tok.ttype = lex_finish_string(lex, '"');
1452         }
1453         lex->flags.nodigraphs = false;
1454         lex_endtoken(lex);
1455         return lex->tok.ttype;
1456     }
1457
1458     if (ch == '\'')
1459     {
1460         /* we parse character constants like string,
1461          * but return TOKEN_CHARCONST, or a vector type if it fits...
1462          * Likewise actual unescaping has to be done by the parser.
1463          * The difference is we don't allow 'char' 'continuation'.
1464          */
1465         if (lex->flags.preprocessing)
1466             lex_tokench(lex, ch);
1467         lex->tok.ttype = lex_finish_string(lex, '\'');
1468         if (lex->flags.preprocessing)
1469             lex_tokench(lex, ch);
1470         lex_endtoken(lex);
1471
1472         lex->tok.ttype = TOKEN_CHARCONST;
1473          /* It's a vector if we can successfully scan 3 floats */
1474 #ifdef _MSC_VER
1475         if (sscanf_s(lex->tok.value, " %f %f %f ",
1476                    &lex->tok.constval.v.x, &lex->tok.constval.v.y, &lex->tok.constval.v.z) == 3)
1477 #else
1478         if (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 #endif
1481
1482         {
1483              lex->tok.ttype = TOKEN_VECTORCONST;
1484         }
1485         else
1486         {
1487             if (!lex->flags.preprocessing && strlen(lex->tok.value) > 1) {
1488                 uchar_t u8char;
1489                 /* check for a valid utf8 character */
1490                 if (!OPTS_FLAG(UTF8) || !u8_analyze(lex->tok.value, NULL, NULL, &u8char, 8)) {
1491                     if (lexwarn(lex, WARN_MULTIBYTE_CHARACTER,
1492                                 ( OPTS_FLAG(UTF8) ? "invalid multibyte character sequence `%s`"
1493                                                   : "multibyte character: `%s`" ),
1494                                 lex->tok.value))
1495                         return (lex->tok.ttype = TOKEN_ERROR);
1496                 }
1497                 else
1498                     lex->tok.constval.i = u8char;
1499             }
1500             else
1501                 lex->tok.constval.i = lex->tok.value[0];
1502         }
1503
1504         return lex->tok.ttype;
1505     }
1506
1507     if (isdigit(ch))
1508     {
1509         lex->tok.ttype = lex_finish_digit(lex, ch);
1510         lex_endtoken(lex);
1511         return lex->tok.ttype;
1512     }
1513
1514     if (lex->flags.preprocessing) {
1515         lex_tokench(lex, ch);
1516         lex_endtoken(lex);
1517         return (lex->tok.ttype = ch);
1518     }
1519
1520     lexerror(lex, "unknown token: `%s`", lex->tok.value);
1521     return (lex->tok.ttype = TOKEN_ERROR);
1522 }