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