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