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