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