]> git.xonotic.org Git - xonotic/gmqcc.git/blob - lexer.c
Work in progress specification LaTeX document for "The GMQCC QuakeC Programming Language"
[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 (!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 != '\n') {
996             lex_ungetch(lex, ch);
997             ch = '\\';
998             break;
999         }
1000         /* we reached a linemerge */
1001         lex_tokench(lex, '\n');
1002         continue;
1003     }
1004
1005     if (lex->flags.preprocessing && (ch == TOKEN_WHITE || ch == TOKEN_EOL || ch == TOKEN_FATAL)) {
1006         return (lex->tok.ttype = ch);
1007     }
1008
1009     lex->sline = lex->line;
1010     lex->tok.ctx.line = lex->sline;
1011     lex->tok.ctx.file = lex->name;
1012
1013     if (lex->eof)
1014         return (lex->tok.ttype = TOKEN_FATAL);
1015
1016     if (ch == EOF) {
1017         lex->eof = true;
1018         return (lex->tok.ttype = TOKEN_EOF);
1019     }
1020
1021     /* modelgen / spiritgen commands */
1022     if (ch == '$' && !lex->flags.preprocessing) {
1023         const char *v;
1024         size_t frame;
1025
1026         ch = lex_getch(lex);
1027         if (!isident_start(ch)) {
1028             lexerror(lex, "hanging '$' modelgen/spritegen command line");
1029             return lex_do(lex);
1030         }
1031         lex_tokench(lex, ch);
1032         if (!lex_finish_ident(lex))
1033             return (lex->tok.ttype = TOKEN_ERROR);
1034         lex_endtoken(lex);
1035         /* skip the known commands */
1036         v = lex->tok.value;
1037
1038         if (!strcmp(v, "frame") || !strcmp(v, "framesave"))
1039         {
1040             /* frame/framesave command works like an enum
1041              * similar to fteqcc we handle this in the lexer.
1042              * The reason for this is that it is sensitive to newlines,
1043              * which the parser is unaware of
1044              */
1045             if (!lex_finish_frames(lex))
1046                  return (lex->tok.ttype = TOKEN_ERROR);
1047             return lex_do(lex);
1048         }
1049
1050         if (!strcmp(v, "framevalue"))
1051         {
1052             ch = lex_getch(lex);
1053             while (ch != EOF && isspace(ch) && ch != '\n')
1054                 ch = lex_getch(lex);
1055
1056             if (!isdigit(ch)) {
1057                 lexerror(lex, "$framevalue requires an integer parameter");
1058                 return lex_do(lex);
1059             }
1060
1061             lex_token_new(lex);
1062             lex->tok.ttype = lex_finish_digit(lex, ch);
1063             lex_endtoken(lex);
1064             if (lex->tok.ttype != TOKEN_INTCONST) {
1065                 lexerror(lex, "$framevalue requires an integer parameter");
1066                 return lex_do(lex);
1067             }
1068             lex->framevalue = lex->tok.constval.i;
1069             return lex_do(lex);
1070         }
1071
1072         if (!strcmp(v, "framerestore"))
1073         {
1074             int rc;
1075
1076             lex_token_new(lex);
1077
1078             rc = lex_parse_frame(lex);
1079
1080             if (rc > 0) {
1081                 lexerror(lex, "$framerestore requires a framename parameter");
1082                 return lex_do(lex);
1083             }
1084             if (rc < 0)
1085                 return (lex->tok.ttype = TOKEN_FATAL);
1086
1087             v = lex->tok.value;
1088             for (frame = 0; frame < vec_size(lex->frames); ++frame) {
1089                 if (!strcmp(v, lex->frames[frame].name)) {
1090                     lex->framevalue = lex->frames[frame].value;
1091                     return lex_do(lex);
1092                 }
1093             }
1094             lexerror(lex, "unknown framename `%s`", v);
1095             return lex_do(lex);
1096         }
1097
1098         if (!strcmp(v, "modelname"))
1099         {
1100             int rc;
1101
1102             lex_token_new(lex);
1103
1104             rc = lex_parse_frame(lex);
1105
1106             if (rc > 0) {
1107                 lexerror(lex, "$modelname requires a parameter");
1108                 return lex_do(lex);
1109             }
1110             if (rc < 0)
1111                 return (lex->tok.ttype = TOKEN_FATAL);
1112
1113             if (lex->modelname) {
1114                 frame_macro m;
1115                 m.value = lex->framevalue;
1116                 m.name = lex->modelname;
1117                 lex->modelname = NULL;
1118                 vec_push(lex->frames, m);
1119             }
1120             lex->modelname = lex->tok.value;
1121             lex->tok.value = NULL;
1122             return lex_do(lex);
1123         }
1124
1125         if (!strcmp(v, "flush"))
1126         {
1127             size_t fi;
1128             for (fi = 0; fi < vec_size(lex->frames); ++fi)
1129                 mem_d(lex->frames[fi].name);
1130             vec_free(lex->frames);
1131             /* skip line (fteqcc does it too) */
1132             ch = lex_getch(lex);
1133             while (ch != EOF && ch != '\n')
1134                 ch = lex_getch(lex);
1135             return lex_do(lex);
1136         }
1137
1138         if (!strcmp(v, "cd") ||
1139             !strcmp(v, "origin") ||
1140             !strcmp(v, "base") ||
1141             !strcmp(v, "flags") ||
1142             !strcmp(v, "scale") ||
1143             !strcmp(v, "skin"))
1144         {
1145             /* skip line */
1146             ch = lex_getch(lex);
1147             while (ch != EOF && ch != '\n')
1148                 ch = lex_getch(lex);
1149             return lex_do(lex);
1150         }
1151
1152         for (frame = 0; frame < vec_size(lex->frames); ++frame) {
1153             if (!strcmp(v, lex->frames[frame].name)) {
1154                 lex->tok.constval.i = lex->frames[frame].value;
1155                 return (lex->tok.ttype = TOKEN_INTCONST);
1156             }
1157         }
1158
1159         lexerror(lex, "invalid frame macro");
1160         return lex_do(lex);
1161     }
1162
1163     /* single-character tokens */
1164     switch (ch)
1165     {
1166         case '[':
1167             nextch = lex_getch(lex);
1168             if (nextch == '[') {
1169                 lex_tokench(lex, ch);
1170                 lex_tokench(lex, nextch);
1171                 lex_endtoken(lex);
1172                 return (lex->tok.ttype = TOKEN_ATTRIBUTE_OPEN);
1173             }
1174             lex_ungetch(lex, nextch);
1175             /* FALL THROUGH */
1176         case '(':
1177         case ':':
1178         case '?':
1179             lex_tokench(lex, ch);
1180             lex_endtoken(lex);
1181             if (lex->flags.noops)
1182                 return (lex->tok.ttype = ch);
1183             else
1184                 return (lex->tok.ttype = TOKEN_OPERATOR);
1185
1186         case ']':
1187             if (lex->flags.noops) {
1188                 nextch = lex_getch(lex);
1189                 if (nextch == ']') {
1190                     lex_tokench(lex, ch);
1191                     lex_tokench(lex, nextch);
1192                     lex_endtoken(lex);
1193                     return (lex->tok.ttype = TOKEN_ATTRIBUTE_CLOSE);
1194                 }
1195                 lex_ungetch(lex, nextch);
1196             }
1197             /* FALL THROUGH */
1198         case ')':
1199         case ';':
1200         case '{':
1201         case '}':
1202
1203         case '#':
1204             lex_tokench(lex, ch);
1205             lex_endtoken(lex);
1206             return (lex->tok.ttype = ch);
1207         default:
1208             break;
1209     }
1210
1211     if (ch == '.') {
1212         nextch = lex_getch(lex);
1213         /* digits starting with a dot */
1214         if (isdigit(nextch)) {
1215             lex_ungetch(lex, nextch);
1216             lex->tok.ttype = lex_finish_digit(lex, ch);
1217             lex_endtoken(lex);
1218             return lex->tok.ttype;
1219         }
1220         lex_ungetch(lex, nextch);
1221     }
1222
1223     if (lex->flags.noops)
1224     {
1225         /* Detect characters early which are normally
1226          * operators OR PART of an operator.
1227          */
1228         switch (ch)
1229         {
1230             /*
1231             case '+':
1232             case '-':
1233             */
1234             case '*':
1235             case '/':
1236             case '<':
1237             case '>':
1238             case '=':
1239             case '&':
1240             case '|':
1241             case '^':
1242             case '~':
1243             case ',':
1244             case '!':
1245                 lex_tokench(lex, ch);
1246                 lex_endtoken(lex);
1247                 return (lex->tok.ttype = ch);
1248             default:
1249                 break;
1250         }
1251     }
1252
1253     if (ch == '.')
1254     {
1255         lex_tokench(lex, ch);
1256         /* peak ahead once */
1257         nextch = lex_getch(lex);
1258         if (nextch != '.') {
1259             lex_ungetch(lex, nextch);
1260             lex_endtoken(lex);
1261             if (lex->flags.noops)
1262                 return (lex->tok.ttype = ch);
1263             else
1264                 return (lex->tok.ttype = TOKEN_OPERATOR);
1265         }
1266         /* peak ahead again */
1267         nextch = lex_getch(lex);
1268         if (nextch != '.') {
1269             lex_ungetch(lex, nextch);
1270             lex_ungetch(lex, '.');
1271             lex_endtoken(lex);
1272             if (lex->flags.noops)
1273                 return (lex->tok.ttype = ch);
1274             else
1275                 return (lex->tok.ttype = TOKEN_OPERATOR);
1276         }
1277         /* fill the token to be "..." */
1278         lex_tokench(lex, ch);
1279         lex_tokench(lex, ch);
1280         lex_endtoken(lex);
1281         return (lex->tok.ttype = TOKEN_DOTS);
1282     }
1283
1284     if (ch == ',' || ch == '.') {
1285         lex_tokench(lex, ch);
1286         lex_endtoken(lex);
1287         return (lex->tok.ttype = TOKEN_OPERATOR);
1288     }
1289
1290     if (ch == '+' || ch == '-' || /* ++, --, +=, -=  and -> as well! */
1291         ch == '>' || ch == '<' || /* <<, >>, <=, >=                  */
1292         ch == '=' || ch == '!' || /* ==, !=                          */
1293         ch == '&' || ch == '|' || /* &&, ||, &=, |=                  */
1294         ch == '~'                 /* ~=, ~                           */
1295     )  {
1296         lex_tokench(lex, ch);
1297
1298         nextch = lex_getch(lex);
1299         if (nextch == '=' || (nextch == ch && ch != '!')) {
1300             lex_tokench(lex, nextch);
1301         } else if (ch == '-' && nextch == '>') {
1302             lex_tokench(lex, nextch);
1303         } else if (ch == '&' && nextch == '~') {
1304             thirdch = lex_getch(lex);
1305             if (thirdch != '=') {
1306                 lex_ungetch(lex, thirdch);
1307                 lex_ungetch(lex, nextch);
1308             }
1309             else {
1310                 lex_tokench(lex, nextch);
1311                 lex_tokench(lex, thirdch);
1312             }
1313         }
1314         else if (lex->flags.preprocessing &&
1315                  ch == '-' && isdigit(nextch))
1316         {
1317             lex->tok.ttype = lex_finish_digit(lex, nextch);
1318             if (lex->tok.ttype == TOKEN_INTCONST)
1319                 lex->tok.constval.i = -lex->tok.constval.i;
1320             else
1321                 lex->tok.constval.f = -lex->tok.constval.f;
1322             lex_endtoken(lex);
1323             return lex->tok.ttype;
1324         } else
1325             lex_ungetch(lex, nextch);
1326
1327         lex_endtoken(lex);
1328         return (lex->tok.ttype = TOKEN_OPERATOR);
1329     }
1330
1331     /*
1332     if (ch == '^' || ch == '~' || ch == '!')
1333     {
1334         lex_tokench(lex, ch);
1335         lex_endtoken(lex);
1336         return (lex->tok.ttype = TOKEN_OPERATOR);
1337     }
1338     */
1339
1340     if (ch == '*' || ch == '/') /* *=, /= */
1341     {
1342         lex_tokench(lex, ch);
1343
1344         nextch = lex_getch(lex);
1345         if (nextch == '=') {
1346             lex_tokench(lex, nextch);
1347         } else
1348             lex_ungetch(lex, nextch);
1349
1350         lex_endtoken(lex);
1351         return (lex->tok.ttype = TOKEN_OPERATOR);
1352     }
1353
1354     if (isident_start(ch))
1355     {
1356         const char *v;
1357
1358         lex_tokench(lex, ch);
1359         if (!lex_finish_ident(lex)) {
1360             /* error? */
1361             return (lex->tok.ttype = TOKEN_ERROR);
1362         }
1363         lex_endtoken(lex);
1364         lex->tok.ttype = TOKEN_IDENT;
1365
1366         v = lex->tok.value;
1367         if (!strcmp(v, "void")) {
1368             lex->tok.ttype = TOKEN_TYPENAME;
1369             lex->tok.constval.t = TYPE_VOID;
1370         } else if (!strcmp(v, "int")) {
1371             lex->tok.ttype = TOKEN_TYPENAME;
1372             lex->tok.constval.t = TYPE_INTEGER;
1373         } else if (!strcmp(v, "float")) {
1374             lex->tok.ttype = TOKEN_TYPENAME;
1375             lex->tok.constval.t = TYPE_FLOAT;
1376         } else if (!strcmp(v, "string")) {
1377             lex->tok.ttype = TOKEN_TYPENAME;
1378             lex->tok.constval.t = TYPE_STRING;
1379         } else if (!strcmp(v, "entity")) {
1380             lex->tok.ttype = TOKEN_TYPENAME;
1381             lex->tok.constval.t = TYPE_ENTITY;
1382         } else if (!strcmp(v, "vector")) {
1383             lex->tok.ttype = TOKEN_TYPENAME;
1384             lex->tok.constval.t = TYPE_VECTOR;
1385         } else {
1386             size_t kw;
1387             for (kw = 0; kw < num_keywords_qc; ++kw) {
1388                 if (!strcmp(v, keywords_qc[kw]))
1389                     return (lex->tok.ttype = TOKEN_KEYWORD);
1390             }
1391             if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC) {
1392                 for (kw = 0; kw < num_keywords_fg; ++kw) {
1393                     if (!strcmp(v, keywords_fg[kw]))
1394                         return (lex->tok.ttype = TOKEN_KEYWORD);
1395                 }
1396             }
1397         }
1398
1399         return lex->tok.ttype;
1400     }
1401
1402     if (ch == '"')
1403     {
1404         lex->flags.nodigraphs = true;
1405         if (lex->flags.preprocessing)
1406             lex_tokench(lex, ch);
1407         lex->tok.ttype = lex_finish_string(lex, '"');
1408         if (lex->flags.preprocessing)
1409             lex_tokench(lex, ch);
1410         while (!lex->flags.preprocessing && lex->tok.ttype == TOKEN_STRINGCONST)
1411         {
1412             /* Allow c style "string" "continuation" */
1413             ch = lex_skipwhite(lex, false);
1414             if (ch != '"') {
1415                 lex_ungetch(lex, ch);
1416                 break;
1417             }
1418
1419             lex->tok.ttype = lex_finish_string(lex, '"');
1420         }
1421         lex->flags.nodigraphs = false;
1422         lex_endtoken(lex);
1423         return lex->tok.ttype;
1424     }
1425
1426     if (ch == '\'')
1427     {
1428         /* we parse character constants like string,
1429          * but return TOKEN_CHARCONST, or a vector type if it fits...
1430          * Likewise actual unescaping has to be done by the parser.
1431          * The difference is we don't allow 'char' 'continuation'.
1432          */
1433         if (lex->flags.preprocessing)
1434             lex_tokench(lex, ch);
1435         lex->tok.ttype = lex_finish_string(lex, '\'');
1436         if (lex->flags.preprocessing)
1437             lex_tokench(lex, ch);
1438         lex_endtoken(lex);
1439
1440         lex->tok.ttype = TOKEN_CHARCONST;
1441          /* It's a vector if we can successfully scan 3 floats */
1442 #ifdef _MSC_VER
1443         if (sscanf_s(lex->tok.value, " %f %f %f ",
1444                    &lex->tok.constval.v.x, &lex->tok.constval.v.y, &lex->tok.constval.v.z) == 3)
1445 #else
1446         if (sscanf(lex->tok.value, " %f %f %f ",
1447                    &lex->tok.constval.v.x, &lex->tok.constval.v.y, &lex->tok.constval.v.z) == 3)
1448 #endif
1449
1450         {
1451              lex->tok.ttype = TOKEN_VECTORCONST;
1452         }
1453         else
1454         {
1455             if (!lex->flags.preprocessing && strlen(lex->tok.value) > 1) {
1456                 uchar_t u8char;
1457                 /* check for a valid utf8 character */
1458                 if (!OPTS_FLAG(UTF8) || !u8_analyze(lex->tok.value, NULL, NULL, &u8char, 8)) {
1459                     if (lexwarn(lex, WARN_MULTIBYTE_CHARACTER,
1460                                 ( OPTS_FLAG(UTF8) ? "invalid multibyte character sequence `%s`"
1461                                                   : "multibyte character: `%s`" ),
1462                                 lex->tok.value))
1463                         return (lex->tok.ttype = TOKEN_ERROR);
1464                 }
1465                 else
1466                     lex->tok.constval.i = u8char;
1467             }
1468             else
1469                 lex->tok.constval.i = lex->tok.value[0];
1470         }
1471
1472         return lex->tok.ttype;
1473     }
1474
1475     if (isdigit(ch))
1476     {
1477         lex->tok.ttype = lex_finish_digit(lex, ch);
1478         lex_endtoken(lex);
1479         return lex->tok.ttype;
1480     }
1481
1482     if (lex->flags.preprocessing) {
1483         lex_tokench(lex, ch);
1484         lex_endtoken(lex);
1485         return (lex->tok.ttype = ch);
1486     }
1487
1488     lexerror(lex, "unknown token: `%s`", lex->tok.value);
1489     return (lex->tok.ttype = TOKEN_ERROR);
1490 }