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