3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
38 #include "TextParsers.h"
41 TextParsers g_TextParser;
42 ITextParsers *textparsers = &g_TextParser;
44 static int g_ini_chartable1[255] = {0};
45 static int g_ws_chartable[255] = {0};
47 bool TextParsers::IsWhitespace(const char *stream)
49 return g_ws_chartable[(unsigned)*stream] == 1;
52 TextParsers::TextParsers()
54 g_ini_chartable1[(unsigned)'_'] = 1;
55 g_ini_chartable1[(unsigned)'-'] = 1;
56 g_ini_chartable1[(unsigned)','] = 1;
57 g_ini_chartable1[(unsigned)'+'] = 1;
58 g_ini_chartable1[(unsigned)'.'] = 1;
59 g_ini_chartable1[(unsigned)'$'] = 1;
60 g_ini_chartable1[(unsigned)'?'] = 1;
61 g_ini_chartable1[(unsigned)'/'] = 1;
62 g_ws_chartable[(unsigned)'\n'] = 1;
63 g_ws_chartable[(unsigned)'\v'] = 1;
64 g_ws_chartable[(unsigned)'\r'] = 1;
65 g_ws_chartable[(unsigned)'\t'] = 1;
66 g_ws_chartable[(unsigned)'\f'] = 1;
67 g_ws_chartable[(unsigned)' '] = 1;
70 void TextParsers::OnSourceModAllInitialized()
72 g_ShareSys.AddInterface(NULL, this);
75 unsigned int TextParsers::GetUTF8CharBytes(const char *stream)
77 return _GetUTF8CharBytes(stream);
89 bool CharStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
91 CharStream *srdr = (CharStream *)stream;
93 const char *ptr = srdr->curpos;
94 for (size_t i=0; i<maxlength; i++)
103 *read = ptr - srdr->curpos;
110 SMCParseError TextParsers::ParseString_SMC(const char *stream,
111 ITextListener_SMC *smc,
115 CharStream srdr = { stream };
117 return ParseStream_SMC(&srdr, CharStreamReader, smc, line, col);
124 bool FileStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
126 size_t num = fread(buffer, 1, maxlength, (FILE *)stream);
128 *read = static_cast<unsigned int>(num);
130 if (num == 0 && feof((FILE *)stream))
135 return (ferror((FILE *)stream) == 0);
138 SMCParseError TextParsers::ParseFile_SMC(const char *file, ITextListener_SMC *smc, unsigned int *line, unsigned int *col)
140 FILE *fp = fopen(file, "rt");
144 return SMCParse_StreamOpen;
147 SMCParseError result = ParseStream_SMC(fp, FileStreamReader, smc, line, col);
155 * Raw parsing of streams with helper functions
160 StringInfo() : quoted(false), ptr(NULL), end(NULL), special(false) { }
167 const char *FixupString(StringInfo &data)
180 /* A string will never have beginning whitespace because we ignore it in the stream.
181 * Furthermore, if there is trailing whitespace, the end ptr will point to it, so it is valid
182 * to overwrite! Lastly, the last character must be whitespace or a comment/invalid character.
187 /* Do some extra work on strings that have special quoted characters. */
190 char *outptr = data.ptr;
191 size_t len = data.end - data.ptr;
194 for (size_t i=0; i<len; i++)
196 if (data.ptr[i] == '\\' && i < len - 1)
198 /* Resolve the next character. */
200 if (data.ptr[i] == 'n')
203 } else if (data.ptr[i] == 't') {
205 } else if (data.ptr[i] == 'r') {
207 } else if (data.ptr[i] != '\\'
208 && data.ptr[i] != '"') {
209 /* This character is invalid, so go back one */
213 *outptr++ = data.ptr[i];
227 const char *rotate(StringInfo info[3])
229 if (info[2].ptr != NULL)
234 if (info[0].ptr != NULL)
238 info[0] = StringInfo();
244 void scrap(StringInfo info[3])
246 info[2] = StringInfo();
247 info[1] = StringInfo();
248 info[0] = StringInfo();
251 void reloc(StringInfo &data, unsigned int bytes)
263 char *lowstring(StringInfo info[3])
265 for (int i=2; i>=0; i--)
276 SMCParseError TextParsers::ParseStream_SMC(void *stream,
278 ITextListener_SMC *smc,
283 char *reparse_point = NULL;
284 char *parse_point = in_buf;
285 char *line_begin = in_buf;
287 unsigned int curline = 1;
288 unsigned int curtok = 0;
289 unsigned int curlevel = 0;
290 bool in_quote = false;
291 bool ignoring = false;
292 bool eol_comment = false;
293 bool ml_comment = false;
295 SMCParseError err = SMCParse_Okay;
299 StringInfo strings[3];
300 StringInfo emptystring;
302 smc->ReadSMC_ParseStart();
304 while (srdr(stream, parse_point, sizeof(in_buf) - (parse_point - line_begin) - 1, &read))
311 /* :TODO: do this outside of the main loop somehow
312 * This checks for BOM markings
315 in_buf[0] == (char)0xEF &&
316 in_buf[1] == (char)0xBB &&
317 in_buf[2] == (char)0xBF)
319 /* Move EVERYTHING down :\ */
320 memmove(in_buf, &in_buf[3], read - 3);
326 read += (parse_point - reparse_point);
327 parse_point = reparse_point;
328 reparse_point = NULL;
331 for (i=0; i<read; i++)
336 /* If we got a newline, there's a lot of things that could have happened in the interim.
337 * First, let's make sure the staged strings are rotated.
341 strings[0].end = &parse_point[i];
342 if (rotate(strings) != NULL)
344 err = SMCParse_InvalidTokens;
349 /* Next, let's clear some line-based values that may no longer have meaning */
352 if (ignoring && !ml_comment)
357 /* Pass the raw line onto the listener */
358 if ((res=smc->ReadSMC_RawLine(line_begin, curline)) != SMCParse_Continue)
360 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
364 /* Now we check the sanity of our staged strings! */
369 err = SMCParse_InvalidProperty1;
372 /* Assume the next string is a property and pass the info on. */
373 if ((res=smc->ReadSMC_KeyValue(
374 FixupString(strings[2]),
375 FixupString(strings[1]),
377 strings[1].quoted)) != SMCParse_Continue)
379 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
385 /* Change the states for the next line */
388 line_begin = &parse_point[i+1]; //Note: safe because this gets relocated later
389 } else if (ignoring) {
392 /* If i was 0, this case is impossible due to reparsing */
393 if ((i != 0) && c == '"' && parse_point[i-1] != '\\')
395 /* If we reached a quote in an ignore phase,
396 * we're staging a string and we must rotate it out.
401 strings[0].end = &parse_point[i];
402 strings[0].quoted = true;
403 if (rotate(strings) != NULL)
405 /* If we rotated too many strings, there was too much crap on one line */
406 err = SMCParse_InvalidTokens;
409 } else if (c == '\\') {
410 strings[0].special = true;
413 reparse_point = &parse_point[i];
417 } else if (ml_comment) {
420 /* Check if we need to get more input first */
423 reparse_point = &parse_point[i];
426 if (parse_point[i+1] == '/')
430 /* We should not be staging anything right now. */
431 assert(strings[0].ptr == NULL);
432 /* Advance the input stream so we don't choke on this token */
439 /* Check if we're whitespace or not */
440 if (!g_ws_chartable[(unsigned)c])
442 bool restage = false;
443 /* Check various special tokens:
450 if (c == ';' || c == '/')
452 /* If it's a line-based comment (that is, ; or //)
453 * we will need to scrap everything until the end of the line.
459 /* If we reached the end of the look-ahead, we need to re-check our input.
460 * Breaking out will force this to be the new reparse point!
462 reparse_point = &parse_point[i];
465 if (parse_point[i + 1] == '/')
467 /* standard comment */
471 } else if (parse_point[i+1] == '*') {
472 /* inline comment - start ignoring */
475 /* yes, we restage, meaning that:
476 * STR/ *stuff* /ING (space because ml comments don't nest in C++)
477 * will not generate 'STRING', but rather 'STR' and 'ING'.
478 * This should be a rare occurrence and is done here for convenience.
487 } else if (c == '{') {
488 /* If we are staging a string, we must rotate here */
491 /* We have unacceptable tokens on this line */
492 if (rotate(strings) != NULL)
494 err = SMCParse_InvalidSection1;
498 /* Sections must always be alone */
499 if (strings[2].ptr != NULL)
501 err = SMCParse_InvalidSection1;
503 } else if (strings[1].ptr == NULL) {
504 err = SMCParse_InvalidSection2;
507 if ((res=smc->ReadSMC_NewSection(FixupString(strings[1]), strings[1].quoted))
508 != SMCParse_Continue)
510 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
513 strings[1] = emptystring;
515 } else if (c == '}') {
516 /* Unlike our matching friend, this can be on the same line as something prior */
517 if (rotate(strings) != NULL)
519 err = SMCParse_InvalidSection3;
526 err = SMCParse_InvalidProperty1;
529 if ((res=smc->ReadSMC_KeyValue(
530 FixupString(strings[2]),
531 FixupString(strings[1]),
534 != SMCParse_Continue)
536 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
539 } else if (strings[1].ptr) {
540 err = SMCParse_InvalidSection3;
542 } else if (!curlevel) {
543 err = SMCParse_InvalidSection4;
546 /* Now it's safe to leave the section */
548 if ((res=smc->ReadSMC_LeavingSection()) != SMCParse_Continue)
550 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
554 } else if (c == '"') {
555 /* If we get a quote mark, we always restage, but we need to do it beforehand */
558 strings[0].end = &parse_point[i];
559 if (rotate(strings) != NULL)
561 err = SMCParse_InvalidTokens;
565 strings[0].ptr = &parse_point[i];
568 } else if (!strings[0].ptr) {
569 /* If we have no string, we must start one */
570 strings[0].ptr = &parse_point[i];
572 if (restage && strings[0].ptr)
574 strings[0].end = &parse_point[i];
575 if (rotate(strings) != NULL)
577 err = SMCParse_InvalidTokens;
582 /* If we're eating a string and get whitespace, we need to restage.
583 * (Note that if we are quoted, this is being ignored)
588 * The specification says the second string in a pair does not need to be quoted.
589 * Thus, we check if there's already a string on the stack.
590 * If there's a newline, we always rotate so the newline has an empty starter.
594 /* There's no string, so we must move this one down and eat up another */
595 strings[0].end = &parse_point[i];
597 } else if (!strings[1].quoted) {
598 err = SMCParse_InvalidTokens;
605 /* Advance which token we're on */
609 if (line_begin != in_buf)
611 /* The line buffer has advanced, so it's safe to copy N bytes back to the beginning.
612 * What's N? N is the lowest point we're currently relying on.
614 char *stage = lowstring(strings);
615 if (!stage || stage > line_begin)
619 unsigned int bytes = read - (stage - parse_point);
621 /* It is now safe to delete everything before the staged point */
622 memmove(in_buf, stage, bytes);
624 /* Calculate the number of bytes in the new buffer */
625 bytes = stage - in_buf;
626 /* Relocate all the cached pointers to our new base */
628 reloc(strings[0], bytes);
629 reloc(strings[1], bytes);
630 reloc(strings[2], bytes);
633 reparse_point -= bytes;
637 parse_point = &parse_point[read];
638 parse_point -= bytes;
640 } else if (read == sizeof(in_buf) - 1) {
641 err = SMCParse_TokenOverflow;
646 /* If we're done parsing and there are tokens left over... */
649 err = SMCParse_InvalidSection5;
651 } else if (strings[0].ptr || strings[1].ptr) {
652 err = SMCParse_InvalidTokens;
656 smc->ReadSMC_ParseEnd(false, false);
658 return SMCParse_Okay;
666 smc->ReadSMC_ParseEnd(true, (err == SMCParse_Custom));
681 bool TextParsers::ParseFile_INI(const char *file, ITextListener_INI *ini_listener, unsigned int *line, unsigned int *col)
683 FILE *fp = fopen(file, "rt");
684 unsigned int curline = 0;
699 char *ptr, *save_ptr;
707 if (fgets(buffer, sizeof(buffer), fp) == NULL)
712 //:TODO: this will only run once, so find a nice way to move it out of the while loop
713 /* If this is the first line, check the first three bytes for BOM */
715 buffer[0] == (char)0xEF &&
716 buffer[1] == (char)0xBB &&
717 buffer[2] == (char)0xBF)
719 /* We have a UTF-8 marked file... skip these bytes */
725 /***************************************************
726 * We preprocess the string before parsing tokens! *
727 ***************************************************/
729 /* First strip beginning whitespace */
730 while (*ptr != '\0' && g_ws_chartable[(unsigned)*ptr] != 0)
742 /* Now search for comment characters */
745 for (size_t i=0; i<len; i++,ptr++)
760 /* Terminate the string here */
780 /* Lastly, strip ending whitespace off */
781 for (size_t i=len-1; i>=0 && i<len; i--)
783 if (g_ws_chartable[(unsigned)ptr[i]])
797 if (!ini_listener->ReadINI_RawLine(ptr, &curtok))
804 bool invalid_tokens = false;
805 bool got_bracket = false;
806 bool extra_tokens = false;
811 for (size_t i=1; i<len; i++)
818 if (mbtowc(&wc, &ptr[i], len-i) != -1)
820 alnum = (iswalnum(wc) != 0);
821 i += _GetUTF8CharBytes(&ptr[i]) - 1;
824 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
828 /* First check - is this a bracket? */
833 /* If this isn't the last character... */
842 /* n...No! Continue copying. */
843 invalid_tokens = true;
848 /* Tell the handler */
849 if (!ini_listener->ReadINI_NewSection(&ptr[1], invalid_tokens, got_bracket, extra_tokens, &curtok))
855 char *val_ptr = NULL;
857 size_t first_space = 0;
858 bool invalid_tokens = false;
859 bool equal_token = false;
864 for (size_t i=0; i<len; i++)
868 /* is this an invalid char? */
871 if (mbtowc(&wc, &ptr[i], len-i) != -1)
873 alnum = (iswalnum(wc) != 0);
874 i += _GetUTF8CharBytes(&ptr[i]) - 1;
877 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
882 if (g_ws_chartable[(unsigned)c])
884 /* if it's a space, keep track of the first occurring space */
892 /* if it's an equal sign, we're done with the key */
895 /* remove excess whitespace */
896 key_ptr[first_space] = '\0';
898 /* remove the equal sign */
901 if (ptr[++i] != '\0')
903 /* If this isn't the end, set next pointer */
909 /* Mark that we got something invalid! */
910 invalid_tokens = true;
917 /* Now we need to parse the value, if any */
920 /* eat up spaces! there shouldn't be any h*/
921 while ((*val_ptr != '\0') && g_ws_chartable[(unsigned)*val_ptr] != 0)
925 if (*val_ptr == '\0')
930 /* Do we have an initial quote? If so, the parsing rules change! */
931 if (*val_ptr == '"' && *val_ptr != '\0')
933 len = strlen(val_ptr);
934 if (val_ptr[len-1] == '"')
937 val_ptr[--len] = '\0';
945 curtok = val_ptr - buffer;
946 if (!ini_listener->ReadINI_KeyValue(key_ptr, val_ptr, invalid_tokens, equal_token, quotes, &curtok))
979 const char *TextParsers::GetSMCErrorString(SMCParseError err)
981 static const char *s_errors[] =
984 "Stream failed to open",
985 "Stream returned read error",
987 "Un-quoted section has invalid tokens",
988 "Section declared without header",
989 "Section declared with unknown tokens",
990 "Section ending without a matching section beginning",
991 "Section beginning without a matching ending",
992 "Line contained too many invalid tokens",
993 "Token buffer overflowed",
994 "A property was declared outside of a section",
997 if (err < SMCParse_Okay || err > SMCParse_InvalidProperty1)
1002 return s_errors[err];