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