Debian Codegraph @

prboom2/src/scanner.cpp

raw
1 // Copyright (c) 2010, Braden "Blzut3" Obrzut <[email protected]>
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are met:
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above copyright
9 // notice, this list of conditions and the following disclaimer in the
10 // documentation and/or other materials provided with the distribution.
11 // * Neither the name of the <organization> nor the
12 // names of its contributors may be used to endorse or promote products
13 // derived from this software without specific prior written permission.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 // ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
19 // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22 // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdarg.h>
30 #include <ctype.h>
31
32 #include "scanner.h"
33
34
35 #ifdef _WIN32
36 # define strcmpnocase stricmp
37 #else
38 # include <strings.h>
39 # define strcmpnocase strcasecmp
40 #endif
41
42
43 const char* const Scanner::TokenNames[TK_NumSpecialTokens] =
44 {
45 "Identifier",
46 "String Constant",
47 "Integer Constant",
48 "Float Constant",
49 "Boolean Constant",
50 "Logical And",
51 "Logical Or",
52 "Equals",
53 "Not Equals",
54 "Greater Than or Equals"
55 "Less Than or Equals",
56 "Left Shift",
57 "Right Shift"
58 };
59
60 static void __ScannerStandardError(const char* message, ...)
61 {
62 va_list list;
63 va_start(list, message);
64 vfprintf(stderr, message, list);
65 va_end(list);
66 }
67 void (*Scanner::error)(const char*, ...) = __ScannerStandardError;
68
69 Scanner::Scanner(const char* data, int length) : line(1), lineStart(0), logicalPosition(0), tokenLine(1), tokenLinePosition(0), scanPos(0), needNext(true)
70 {
71 if(length == -1)
72 length = strlen(data);
73 this->length = length;
74 this->data = new char[length];
75 memcpy(this->data, data, length);
76 string = NULL;
77
78 CheckForWhitespace();
79 }
80
81 Scanner::~Scanner()
82 {
83 if (string != NULL) free(string);
84 delete[] data;
85 }
86
87 void Scanner::SetString(char **ptr, const char *start, unsigned int length)
88 {
89 if (length == -1)
90 length = strlen(start);
91 if (*ptr != NULL) free(*ptr);
92 *ptr = (char*)malloc(length + 1);
93 memcpy(*ptr, start, length);
94 (*ptr)[length] = 0;
95 }
96
97 void Scanner::CheckForWhitespace()
98 {
99 int comment = 0; // 1 = till next new line, 2 = till end block
100 while(scanPos < length)
101 {
102 char cur = data[scanPos];
103 char next = scanPos+1 < length ? data[scanPos+1] : 0;
104 if(comment == 2)
105 {
106 if(cur != '*' || next != '/')
107 {
108 if(cur == '\n' || cur == '\r')
109 {
110 scanPos++;
111 if(comment == 1)
112 comment = 0;
113
114 // Do a quick check for Windows style new line
115 if(cur == '\r' && next == '\n')
116 scanPos++;
117 IncrementLine();
118 }
119 else
120 scanPos++;
121 }
122 else
123 {
124 comment = 0;
125 scanPos += 2;
126 }
127 continue;
128 }
129
130 if(cur == ' ' || cur == '\t' || cur == 0)
131 scanPos++;
132 else if(cur == '\n' || cur == '\r')
133 {
134 scanPos++;
135 if(comment == 1)
136 comment = 0;
137
138 // Do a quick check for Windows style new line
139 if(cur == '\r' && next == '\n')
140 scanPos++;
141 IncrementLine();
142 //CheckForMeta();
143 }
144 else if(cur == '/' && comment == 0)
145 {
146 switch(next)
147 {
148 case '/':
149 comment = 1;
150 break;
151 case '*':
152 comment = 2;
153 break;
154 default:
155 return;
156 }
157 scanPos += 2;
158 }
159 else
160 {
161 if(comment == 0)
162 return;
163 else
164 scanPos++;
165 }
166 }
167 }
168
169 bool Scanner::CheckToken(char token)
170 {
171 if(needNext)
172 {
173 if(!GetNextToken(false))
174 return false;
175 }
176
177 // An int can also be a float.
178 if(nextState.token == token || (nextState.token == TK_IntConst && token == TK_FloatConst))
179 {
180 needNext = true;
181 ExpandState();
182 return true;
183 }
184 needNext = false;
185 return false;
186 }
187
188 void Scanner::ExpandState()
189 {
190 logicalPosition = scanPos;
191 CheckForWhitespace();
192
193 SetString(&string, nextState.string, -1);
194 number = nextState.number;
195 decimal = nextState.decimal;
196 boolean = nextState.boolean;
197 token = nextState.token;
198 tokenLine = nextState.tokenLine;
199 tokenLinePosition = nextState.tokenLinePosition;
200 }
201
202 void Scanner::SaveState(Scanner &savedstate)
203 {
204 // This saves the entire parser state except for the data pointer.
205 if (savedstate.string != NULL) free(savedstate.string);
206 if (savedstate.nextState.string != NULL) free(savedstate.nextState.string);
207 savedstate = *this;
208 savedstate.string = strdup(string);
209 savedstate.nextState.string = strdup(nextState.string);
210 savedstate.data = NULL;
211 }
212
213 void Scanner::RestoreState(Scanner &savedstate)
214 {
215 if (savedstate.data == NULL)
216 {
217 char *saveddata = data;
218 savedstate.SaveState(*this);
219 data = saveddata;
220 }
221 }
222
223 bool Scanner::GetNextToken(bool expandState)
224 {
225 if(!needNext)
226 {
227 needNext = true;
228 if(expandState)
229 ExpandState();
230 return true;
231 }
232
233 nextState.tokenLine = line;
234 nextState.tokenLinePosition = scanPos - lineStart;
235 nextState.token = TK_NoToken;
236 if(scanPos >= length)
237 {
238 if(expandState)
239 ExpandState();
240 return false;
241 }
242
243 int start = scanPos;
244 int end = scanPos;
245 int integerBase = 10;
246 bool floatHasDecimal = false;
247 bool floatHasExponent = false;
248 bool stringFinished = false; // Strings are the only things that can have 0 length tokens.
249
250 char cur = data[scanPos++];
251 // Determine by first character
252 if(cur == '_' || cur == '$' || (cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z'))
253 nextState.token = TK_Identifier;
254 else if(cur >= '0' && cur <= '9')
255 {
256 if(cur == '0')
257 integerBase = 8;
258 nextState.token = TK_IntConst;
259 }
260 else if(cur == '.')
261 {
262 floatHasDecimal = true;
263 nextState.token = TK_FloatConst;
264 }
265 else if(cur == '"')
266 {
267 end = ++start; // Move the start up one character so we don't have to trim it later.
268 nextState.token = TK_StringConst;
269 }
270 else
271 {
272 end = scanPos;
273 nextState.token = cur;
274
275 // Now check for operator tokens
276 if(scanPos < length)
277 {
278 char next = data[scanPos];
279 if(cur == '&' && next == '&')
280 nextState.token = TK_AndAnd;
281 else if(cur == '|' && next == '|')
282 nextState.token = TK_OrOr;
283 else if(cur == '<' && next == '<')
284 nextState.token = TK_ShiftLeft;
285 else if(cur == '>' && next == '>')
286 nextState.token = TK_ShiftRight;
287 //else if(cur == '#' && next == '#')
288 // nextState.token = TK_MacroConcat;
289 else if(next == '=')
290 {
291 switch(cur)
292 {
293 case '=':
294 nextState.token = TK_EqEq;
295 break;
296 case '!':
297 nextState.token = TK_NotEq;
298 break;
299 case '>':
300 nextState.token = TK_GtrEq;
301 break;
302 case '<':
303 nextState.token = TK_LessEq;
304 break;
305 default:
306 break;
307 }
308 }
309
310 if(nextState.token != cur)
311 {
312 scanPos++;
313 end = scanPos;
314 }
315 }
316 }
317
318 if(start == end)
319 {
320 while(scanPos < length)
321 {
322 cur = data[scanPos];
323 switch(nextState.token)
324 {
325 default:
326 break;
327 case TK_Identifier:
328 if(cur != '_' && (cur < 'A' || cur > 'Z') && (cur < 'a' || cur > 'z') && (cur < '0' || cur > '9') && cur != '/' && cur != '\\')
329 end = scanPos;
330 break;
331 case TK_IntConst:
332 if(cur == '.' || (scanPos-1 != start && cur == 'e'))
333 nextState.token = TK_FloatConst;
334 else if((cur == 'x' || cur == 'X') && scanPos-1 == start)
335 {
336 integerBase = 16;
337 break;
338 }
339 else
340 {
341 switch(integerBase)
342 {
343 default:
344 if(cur < '0' || cur > '9')
345 end = scanPos;
346 break;
347 case 8:
348 if(cur < '0' || cur > '7')
349 end = scanPos;
350 break;
351 case 16:
352 if((cur < '0' || cur > '9') && (cur < 'A' || cur > 'F') && (cur < 'a' || cur > 'f'))
353 end = scanPos;
354 break;
355 }
356 break;
357 }
358 case TK_FloatConst:
359 if(cur < '0' || cur > '9')
360 {
361 if(!floatHasDecimal && cur == '.')
362 {
363 floatHasDecimal = true;
364 break;
365 }
366 else if(!floatHasExponent && cur == 'e')
367 {
368 floatHasDecimal = true;
369 floatHasExponent = true;
370 if(scanPos+1 < length)
371 {
372 char next = data[scanPos+1];
373 if((next < '0' || next > '9') && next != '+' && next != '-')
374 end = scanPos;
375 else
376 scanPos++;
377 }
378 break;
379 }
380 end = scanPos;
381 }
382 break;
383 case TK_StringConst:
384 if(cur == '"')
385 {
386 stringFinished = true;
387 end = scanPos;
388 scanPos++;
389 }
390 else if(cur == '\\')
391 scanPos++; // Will add two since the loop automatically adds one
392 break;
393 }
394 if(start == end && !stringFinished)
395 scanPos++;
396 else
397 break;
398 }
399
400 if (start == end && scanPos == length)
401 end = scanPos;
402 }
403
404 if(end-start > 0 || stringFinished)
405 {
406 SetString(&nextState.string, data+start, end-start);
407 if(nextState.token == TK_FloatConst)
408 {
409 nextState.decimal = atof(nextState.string);
410 nextState.number = static_cast<int> (nextState.decimal);
411 nextState.boolean = (nextState.number != 0);
412 }
413 else if(nextState.token == TK_IntConst)
414 {
415 nextState.number = strtol(nextState.string, NULL, integerBase);
416 nextState.decimal = nextState.number;
417 nextState.boolean = (nextState.number != 0);
418 }
419 else if(nextState.token == TK_Identifier)
420 {
421 // Identifiers should be case insensitive.
422 char *p = nextState.string;
423 while (*p)
424 {
425 *p = tolower(*p);
426 p++;
427 }
428 // Check for a boolean constant.
429 if(strcmp(nextState.string, "true") == 0)
430 {
431 nextState.token = TK_BoolConst;
432 nextState.boolean = true;
433 }
434 else if (strcmp(nextState.string, "false") == 0)
435 {
436 nextState.token = TK_BoolConst;
437 nextState.boolean = false;
438 }
439 }
440 else if(nextState.token == TK_StringConst)
441 {
442 Unescape(nextState.string);
443 }
444 if(expandState)
445 ExpandState();
446 return true;
447 }
448 nextState.token = TK_NoToken;
449 if(expandState)
450 ExpandState();
451 return false;
452 }
453
454 void Scanner::IncrementLine()
455 {
456 line++;
457 lineStart = scanPos;
458 }
459
460 void Scanner::SkipLine()
461 {
462 while (tokenLine == line && GetNextToken());
463 }
464
465 void Scanner::Error(int token)
466 {
467 if (token < TK_NumSpecialTokens && this->token >= TK_Identifier && this->token < TK_NumSpecialTokens)
468 error("%d:%d:Expected '%s' but got '%s' instead.", GetLine(), GetLinePos(), TokenNames[token], TokenNames[(unsigned char) this->token]);
469 else if (token < TK_NumSpecialTokens && this->token >= TK_NumSpecialTokens)
470 error("%d:%d:Expected '%s' but got '%c' instead.", GetLine(), GetLinePos(), TokenNames[token], this->token);
471 else if (token < TK_NumSpecialTokens && this->token == TK_NoToken)
472 error("%d:%d:Expected '%s'", GetLine(), GetLinePos(), TokenNames[token]);
473 else if (token >= TK_NumSpecialTokens && this->token >= TK_Identifier && this->token < TK_NumSpecialTokens)
474 error("%d:%d:Expected '%c' but got '%s' instead.", GetLine(), GetLinePos(), token, TokenNames[(unsigned char) this->token]);
475 else
476 error("%d:%d:Expected '%c' but got '%c' instead.", GetLine(), GetLinePos(), token, this->token);
477 }
478
479 void Scanner::Error(const char *mustget)
480 {
481 if (token < TK_NumSpecialTokens && this->token < TK_NumSpecialTokens)
482 error("%d:%d:Expected '%s' but got '%s' instead.", GetLine(), GetLinePos(), mustget, TokenNames[(unsigned char) this->token]);
483 else
484 error("%d:%d:Expected '%s' but got '%c' instead.", GetLine(), GetLinePos(), mustget, this->token);
485 }
486
487 void Scanner::ErrorF(const char *msg, ...)
488 {
489 char buffer[1024];
490 va_list ap;
491 va_start(ap, msg);
492 vsnprintf(buffer, 1024, msg, ap);
493 va_end(ap);
494 error("%d:%d:%s.", GetLine(), GetLinePos(), buffer);
495 }
496
497 void Scanner::MustGetToken(char token)
498 {
499 if(!CheckToken(token))
500 {
501 ExpandState();
502 Error(token);
503 }
504 }
505
506 void Scanner::MustGetIdentifier(const char *ident)
507 {
508 if (!CheckToken(TK_Identifier) || strcmpnocase(string, ident))
509 {
510 Error(ident);
511 return;
512 }
513 }
514
515 // Convenience helpers that parse an entire number including a leading minus or plus sign
516 bool Scanner::ScanInteger()
517 {
518 bool neg = false;
519 if (!GetNextToken())
520 {
521 return false;
522 }
523 if (token == '-')
524 {
525 if (!GetNextToken())
526 {
527 return false;
528 }
529 neg = true;
530 }
531 else if (token == '+')
532 {
533 if (!GetNextToken())
534 {
535 return false;
536 }
537 }
538 if (token != TK_IntConst)
539 {
540 return false;
541 }
542 if (neg)
543 {
544 number = -number;
545 decimal = -decimal;
546 }
547 return true;
548 }
549
550 bool Scanner::ScanFloat()
551 {
552 bool neg = false;
553 if (!GetNextToken())
554 {
555 return false;
556 }
557 if (token == '-')
558 {
559 if (!GetNextToken())
560 {
561 return false;
562 }
563 neg = true;
564 }
565 else if (token == '+')
566 {
567 if (!GetNextToken())
568 {
569 return false;
570 }
571 }
572 if (token != TK_IntConst && token != TK_FloatConst)
573 {
574 return false;
575 }
576 if (neg)
577 {
578 number = -number;
579 decimal = -decimal;
580 }
581 return true;
582 }
583
584 bool Scanner::CheckInteger()
585 {
586 Scanner savedstate;
587 SaveState(savedstate);
588 bool res = ScanInteger();
589 if (!res) RestoreState(savedstate);
590 return res;
591 }
592
593 bool Scanner::CheckFloat()
594 {
595 Scanner savedstate;
596 SaveState(savedstate);
597 bool res = ScanFloat();
598 if (!res) RestoreState(savedstate);
599 return res;
600 }
601
602 bool Scanner::CheckString()
603 {
604 return CheckToken(TK_StringConst) || CheckToken(TK_Identifier);
605 }
606
607 bool Scanner::StringMatch(const char *target)
608 {
609 return !strcmpnocase(string, target);
610 }
611
612 void Scanner::MustGetInteger()
613 {
614 if (!ScanInteger()) Error(TK_IntConst);
615 }
616
617 void Scanner::MustGetFloat()
618 {
619 if (!ScanFloat()) Error(TK_FloatConst);
620 }
621
622 void Scanner::MustGetString()
623 {
624 if (!CheckString())
625 {
626 ErrorF("Expected String Constant or Identifier");
627 return;
628 }
629 }
630
631 bool Scanner::TokensLeft() const
632 {
633 return scanPos < length;
634 }
635
636 // This is taken from ZDoom's strbin function which can do a lot more than just unescaping backslashes and quotation marks.
637 void Scanner::Unescape(char *str)
638 {
639 char *p = str, c;
640 int i;
641
642 while ((c = *p++)) {
643 if (c != '\\') {
644 *str++ = c;
645 }
646 else {
647 switch (*p) {
648 case 'a':
649 *str++ = '\a';
650 break;
651 case 'b':
652 *str++ = '\b';
653 break;
654 case 'f':
655 *str++ = '\f';
656 break;
657 case 'n':
658 *str++ = '\n';
659 break;
660 case 't':
661 *str++ = '\t';
662 break;
663 case 'r':
664 *str++ = '\r';
665 break;
666 case 'v':
667 *str++ = '\v';
668 break;
669 case '?':
670 *str++ = '\?';
671 break;
672 case '\n':
673 break;
674 case 'x':
675 case 'X':
676 c = 0;
677 for (i = 0; i < 2; i++)
678 {
679 p++;
680 if (*p >= '0' && *p <= '9')
681 c = (c << 4) + *p - '0';
682 else if (*p >= 'a' && *p <= 'f')
683 c = (c << 4) + 10 + *p - 'a';
684 else if (*p >= 'A' && *p <= 'F')
685 c = (c << 4) + 10 + *p - 'A';
686 else
687 {
688 p--;
689 break;
690 }
691 }
692 *str++ = c;
693 break;
694 case '0':
695 case '1':
696 case '2':
697 case '3':
698 case '4':
699 case '5':
700 case '6':
701 case '7':
702 c = *p - '0';
703 for (i = 0; i < 2; i++)
704 {
705 p++;
706 if (*p >= '0' && *p <= '7')
707 c = (c << 3) + *p - '0';
708 else
709 {
710 p--;
711 break;
712 }
713 }
714 *str++ = c;
715 break;
716 default:
717 *str++ = *p;
718 break;
719 }
720 p++;
721 }
722 }
723 *str = 0;
724 }