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