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;
43 static int g_ini_chartable1[255] = {0};
44 static int g_ws_chartable[255] = {0};
46 bool IsWhitespace(const char *stream)
48 return g_ws_chartable[(unsigned)*stream] == 1;
51 TextParsers::TextParsers()
53 g_ini_chartable1[(unsigned)'_'] = 1;
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_ws_chartable[(unsigned)'\n'] = 1;
62 g_ws_chartable[(unsigned)'\v'] = 1;
63 g_ws_chartable[(unsigned)'\r'] = 1;
64 g_ws_chartable[(unsigned)'\t'] = 1;
65 g_ws_chartable[(unsigned)'\f'] = 1;
66 g_ws_chartable[(unsigned)' '] = 1;
69 void TextParsers::OnSourceModAllInitialized()
71 g_ShareSys.AddInterface(NULL, this);
74 unsigned int TextParsers::GetUTF8CharBytes(const char *stream)
76 return _GetUTF8CharBytes(stream);
88 bool CharStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
90 CharStream *srdr = (CharStream *)stream;
92 const char *ptr = srdr->curpos;
93 for (size_t i=0; i<maxlength; i++)
102 *read = ptr - srdr->curpos;
109 SMCParseError TextParsers::ParseString_SMC(const char *stream,
110 ITextListener_SMC *smc,
114 CharStream srdr = { stream };
116 return ParseStream_SMC(&srdr, CharStreamReader, smc, line, col);
123 bool FileStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
125 size_t num = fread(buffer, 1, maxlength, (FILE *)stream);
127 *read = static_cast<unsigned int>(num);
129 if (num == 0 && feof((FILE *)stream))
134 return (ferror((FILE *)stream) == 0);
137 SMCParseError TextParsers::ParseFile_SMC(const char *file, ITextListener_SMC *smc, unsigned int *line, unsigned int *col)
139 FILE *fp = fopen(file, "rt");
143 return SMCParse_StreamOpen;
146 SMCParseError result = ParseStream_SMC(fp, FileStreamReader, smc, line, col);
154 * Raw parsing of streams with helper functions
159 StringInfo() : quoted(false), ptr(NULL), end(NULL), special(false) { }
166 const char *FixupString(StringInfo &data)
179 /* A string will never have beginning whitespace because we ignore it in the stream.
180 * Furthermore, if there is trailing whitespace, the end ptr will point to it, so it is valid
181 * to overwrite! Lastly, the last character must be whitespace or a comment/invalid character.
186 /* Do some extra work on strings that have special quoted characters. */
189 char *outptr = data.ptr;
190 size_t len = data.end - data.ptr;
193 for (size_t i=0; i<len; i++)
195 if (data.ptr[i] == '\\' && i < len - 1)
197 /* Resolve the next character. */
199 if (data.ptr[i] == 'n')
202 } else if (data.ptr[i] == 't') {
204 } else if (data.ptr[i] == 'r') {
206 } else if (data.ptr[i] != '\\'
207 && data.ptr[i] != '"') {
208 /* This character is invalid, so go back one */
212 *outptr++ = data.ptr[i];
226 const char *rotate(StringInfo info[3])
228 if (info[2].ptr != NULL)
233 if (info[0].ptr != NULL)
237 info[0] = StringInfo();
243 void scrap(StringInfo info[3])
245 info[2] = StringInfo();
246 info[1] = StringInfo();
247 info[0] = StringInfo();
250 void reloc(StringInfo &data, unsigned int bytes)
262 char *lowstring(StringInfo info[3])
264 for (int i=2; i>=0; i--)
275 SMCParseError TextParsers::ParseStream_SMC(void *stream,
277 ITextListener_SMC *smc,
282 char *reparse_point = NULL;
283 char *parse_point = in_buf;
284 char *line_begin = in_buf;
286 unsigned int curline = 1;
287 unsigned int curtok = 0;
288 unsigned int curlevel = 0;
289 bool in_quote = false;
290 bool ignoring = false;
291 bool eol_comment = false;
292 bool ml_comment = false;
294 SMCParseError err = SMCParse_Okay;
298 StringInfo strings[3];
299 StringInfo emptystring;
301 smc->ReadSMC_ParseStart();
303 while (srdr(stream, parse_point, sizeof(in_buf) - (parse_point - line_begin) - 1, &read))
310 /* :TODO: do this outside of the main loop somehow
311 * This checks for BOM markings
314 in_buf[0] == (char)0xEF &&
315 in_buf[1] == (char)0xBB &&
316 in_buf[2] == (char)0xBF)
318 /* Move EVERYTHING down :\ */
319 memmove(in_buf, &in_buf[3], read - 3);
325 read += (parse_point - reparse_point);
326 parse_point = reparse_point;
327 reparse_point = NULL;
330 for (i=0; i<read; i++)
335 /* If we got a newline, there's a lot of things that could have happened in the interim.
336 * First, let's make sure the staged strings are rotated.
340 strings[0].end = &parse_point[i];
341 if (rotate(strings) != NULL)
343 err = SMCParse_InvalidTokens;
348 /* Next, let's clear some line-based values that may no longer have meaning */
351 if (ignoring && !ml_comment)
356 /* Pass the raw line onto the listener */
357 if ((res=smc->ReadSMC_RawLine(line_begin, curline)) != SMCParse_Continue)
359 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
363 /* Now we check the sanity of our staged strings! */
368 err = SMCParse_InvalidProperty1;
371 /* Assume the next string is a property and pass the info on. */
372 if ((res=smc->ReadSMC_KeyValue(
373 FixupString(strings[2]),
374 FixupString(strings[1]),
376 strings[1].quoted)) != SMCParse_Continue)
378 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
384 /* Change the states for the next line */
387 line_begin = &parse_point[i+1]; //Note: safe because this gets relocated later
388 } else if (ignoring) {
391 /* If i was 0, this case is impossible due to reparsing */
392 if ((i != 0) && c == '"' && parse_point[i-1] != '\\')
394 /* If we reached a quote in an ignore phase,
395 * we're staging a string and we must rotate it out.
400 strings[0].end = &parse_point[i];
401 strings[0].quoted = true;
402 if (rotate(strings) != NULL)
404 /* If we rotated too many strings, there was too much crap on one line */
405 err = SMCParse_InvalidTokens;
408 } else if (c == '\\') {
409 strings[0].special = true;
412 reparse_point = &parse_point[i];
416 } else if (ml_comment) {
419 /* Check if we need to get more input first */
422 reparse_point = &parse_point[i];
425 if (parse_point[i+1] == '/')
429 /* We should not be staging anything right now. */
430 assert(strings[0].ptr == NULL);
431 /* Advance the input stream so we don't choke on this token */
438 /* Check if we're whitespace or not */
439 if (!g_ws_chartable[(unsigned)c])
441 bool restage = false;
442 /* Check various special tokens:
449 if (c == ';' || c == '/')
451 /* If it's a line-based comment (that is, ; or //)
452 * we will need to scrap everything until the end of the line.
458 /* If we reached the end of the look-ahead, we need to re-check our input.
459 * Breaking out will force this to be the new reparse point!
461 reparse_point = &parse_point[i];
464 if (parse_point[i + 1] == '/')
466 /* standard comment */
470 } else if (parse_point[i+1] == '*') {
471 /* inline comment - start ignoring */
474 /* yes, we restage, meaning that:
475 * STR/ *stuff* /ING (space because ml comments don't nest in C++)
476 * will not generate 'STRING', but rather 'STR' and 'ING'.
477 * This should be a rare occurrence and is done here for convenience.
486 } else if (c == '{') {
487 /* If we are staging a string, we must rotate here */
490 /* We have unacceptable tokens on this line */
491 if (rotate(strings) != NULL)
493 err = SMCParse_InvalidSection1;
497 /* Sections must always be alone */
498 if (strings[2].ptr != NULL)
500 err = SMCParse_InvalidSection1;
502 } else if (strings[1].ptr == NULL) {
503 err = SMCParse_InvalidSection2;
506 if ((res=smc->ReadSMC_NewSection(FixupString(strings[1]), strings[1].quoted))
507 != SMCParse_Continue)
509 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
512 strings[1] = emptystring;
514 } else if (c == '}') {
515 /* Unlike our matching friend, this can be on the same line as something prior */
516 if (rotate(strings) != NULL)
518 err = SMCParse_InvalidSection3;
525 err = SMCParse_InvalidProperty1;
528 if ((res=smc->ReadSMC_KeyValue(
529 FixupString(strings[2]),
530 FixupString(strings[1]),
533 != SMCParse_Continue)
535 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
538 } else if (strings[1].ptr) {
539 err = SMCParse_InvalidSection3;
541 } else if (!curlevel) {
542 err = SMCParse_InvalidSection4;
545 /* Now it's safe to leave the section */
547 if ((res=smc->ReadSMC_LeavingSection()) != SMCParse_Continue)
549 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
553 } else if (c == '"') {
554 /* If we get a quote mark, we always restage, but we need to do it beforehand */
557 strings[0].end = &parse_point[i];
558 if (rotate(strings) != NULL)
560 err = SMCParse_InvalidTokens;
564 strings[0].ptr = &parse_point[i];
567 } else if (!strings[0].ptr) {
568 /* If we have no string, we must start one */
569 strings[0].ptr = &parse_point[i];
571 if (restage && strings[0].ptr)
573 strings[0].end = &parse_point[i];
574 if (rotate(strings) != NULL)
576 err = SMCParse_InvalidTokens;
581 /* If we're eating a string and get whitespace, we need to restage.
582 * (Note that if we are quoted, this is being ignored)
587 * The specification says the second string in a pair does not need to be quoted.
588 * Thus, we check if there's already a string on the stack.
589 * If there's a newline, we always rotate so the newline has an empty starter.
593 /* There's no string, so we must move this one down and eat up another */
594 strings[0].end = &parse_point[i];
596 } else if (!strings[1].quoted) {
597 err = SMCParse_InvalidTokens;
604 /* Advance which token we're on */
608 if (line_begin != in_buf)
610 /* The line buffer has advanced, so it's safe to copy N bytes back to the beginning.
611 * What's N? N is the lowest point we're currently relying on.
613 char *stage = lowstring(strings);
614 if (!stage || stage > line_begin)
618 unsigned int bytes = read - (stage - parse_point);
620 /* It is now safe to delete everything before the staged point */
621 memmove(in_buf, stage, bytes);
623 /* Calculate the number of bytes in the new buffer */
624 bytes = stage - in_buf;
625 /* Relocate all the cached pointers to our new base */
627 reloc(strings[0], bytes);
628 reloc(strings[1], bytes);
629 reloc(strings[2], bytes);
632 reparse_point -= bytes;
636 parse_point = &parse_point[read];
637 parse_point -= bytes;
639 } else if (read == sizeof(in_buf) - 1) {
640 err = SMCParse_TokenOverflow;
645 /* If we're done parsing and there are tokens left over... */
648 err = SMCParse_InvalidSection5;
650 } else if (strings[0].ptr || strings[1].ptr) {
651 err = SMCParse_InvalidTokens;
655 smc->ReadSMC_ParseEnd(false, false);
657 return SMCParse_Okay;
665 smc->ReadSMC_ParseEnd(true, (err == SMCParse_Custom));
680 bool TextParsers::ParseFile_INI(const char *file, ITextListener_INI *ini_listener, unsigned int *line, unsigned int *col)
682 FILE *fp = fopen(file, "rt");
683 unsigned int curline = 0;
698 char *ptr, *save_ptr;
706 if (fgets(buffer, sizeof(buffer), fp) == NULL)
711 //:TODO: this will only run once, so find a nice way to move it out of the while loop
712 /* If this is the first line, check the first three bytes for BOM */
714 buffer[0] == (char)0xEF &&
715 buffer[1] == (char)0xBB &&
716 buffer[2] == (char)0xBF)
718 /* We have a UTF-8 marked file... skip these bytes */
724 /***************************************************
725 * We preprocess the string before parsing tokens! *
726 ***************************************************/
728 /* First strip beginning whitespace */
729 while (*ptr != '\0' && g_ws_chartable[(unsigned)*ptr] != 0)
741 /* Now search for comment characters */
744 for (size_t i=0; i<len; i++,ptr++)
759 /* Terminate the string here */
779 /* Lastly, strip ending whitespace off */
780 for (size_t i=len-1; i>=0 && i<len; i--)
782 if (g_ws_chartable[(unsigned)ptr[i]])
796 if (!ini_listener->ReadINI_RawLine(ptr, &curtok))
803 bool invalid_tokens = false;
804 bool got_bracket = false;
805 bool extra_tokens = false;
810 for (size_t i=1; i<len; i++)
817 if (mbtowc(&wc, &ptr[i], len-i) != -1)
819 alnum = (iswalnum(wc) != 0);
820 i += _GetUTF8CharBytes(&ptr[i]) - 1;
823 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
827 /* First check - is this a bracket? */
832 /* If this isn't the last character... */
841 /* n...No! Continue copying. */
842 invalid_tokens = true;
847 /* Tell the handler */
848 if (!ini_listener->ReadINI_NewSection(&ptr[1], invalid_tokens, got_bracket, extra_tokens, &curtok))
854 char *val_ptr = NULL;
856 size_t first_space = 0;
857 bool invalid_tokens = false;
858 bool equal_token = false;
863 for (size_t i=0; i<len; i++)
867 /* is this an invalid char? */
870 if (mbtowc(&wc, &ptr[i], len-i) != -1)
872 alnum = (iswalnum(wc) != 0);
873 i += _GetUTF8CharBytes(&ptr[i]) - 1;
876 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
881 if (g_ws_chartable[(unsigned)c])
883 /* if it's a space, keep track of the first occurring space */
891 /* if it's an equal sign, we're done with the key */
894 /* remove excess whitespace */
895 key_ptr[first_space] = '\0';
897 /* remove the equal sign */
900 if (ptr[++i] != '\0')
902 /* If this isn't the end, set next pointer */
908 /* Mark that we got something invalid! */
909 invalid_tokens = true;
916 /* Now we need to parse the value, if any */
919 /* eat up spaces! there shouldn't be any h*/
920 while ((*val_ptr != '\0') && g_ws_chartable[(unsigned)*val_ptr] != 0)
924 if (*val_ptr == '\0')
929 /* Do we have an initial quote? If so, the parsing rules change! */
930 if (*val_ptr == '"' && *val_ptr != '\0')
932 len = strlen(val_ptr);
933 if (val_ptr[len-1] == '"')
936 val_ptr[--len] = '\0';
944 curtok = val_ptr - buffer;
945 if (!ini_listener->ReadINI_KeyValue(key_ptr, val_ptr, invalid_tokens, equal_token, quotes, &curtok))
978 const char *TextParsers::GetSMCErrorString(SMCParseError err)
980 static const char *s_errors[] =
983 "Stream failed to open",
984 "Stream returned read error",
986 "Un-quoted section has invalid tokens",
987 "Section declared without header",
988 "Section declared with unknown tokens",
989 "Section ending without a matching section beginning",
990 "Section beginning without a matching ending",
991 "Line contained too many invalid tokens",
992 "Token buffer overflowed",
993 "A property was declared outside of a section",
996 if (err < SMCParse_Okay || err > SMCParse_InvalidProperty1)
1001 return s_errors[err];