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