2 * ===============================================================
3 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
4 * ===============================================================
6 * This file is not open source and may not be copied without explicit
7 * written permission of AlliedModders LLC. This file may not be redistributed
8 * in whole or significant part.
9 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
20 #include "TextParsers.h"
23 CTextParsers g_TextParser;
25 static int g_ini_chartable1[255] = {0};
26 static int g_ws_chartable[255] = {0};
28 CTextParsers::CTextParsers()
30 g_ini_chartable1[(unsigned)'_'] = 1;
31 g_ini_chartable1[(unsigned)'-'] = 1;
32 g_ini_chartable1[(unsigned)','] = 1;
33 g_ini_chartable1[(unsigned)'+'] = 1;
34 g_ini_chartable1[(unsigned)'.'] = 1;
35 g_ini_chartable1[(unsigned)'$'] = 1;
36 g_ini_chartable1[(unsigned)'?'] = 1;
37 g_ini_chartable1[(unsigned)'/'] = 1;
38 g_ws_chartable[(unsigned)'\n'] = 1;
39 g_ws_chartable[(unsigned)'\v'] = 1;
40 g_ws_chartable[(unsigned)'\r'] = 1;
41 g_ws_chartable[(unsigned)'\t'] = 1;
42 g_ws_chartable[(unsigned)'\f'] = 1;
43 g_ws_chartable[(unsigned)' '] = 1;
46 void CTextParsers::OnSourceModAllInitialized()
48 g_ShareSys.AddInterface(NULL, this);
51 unsigned int CTextParsers::GetUTF8CharBytes(const char *stream)
53 return _GetUTF8CharBytes(stream);
65 bool CharStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
67 CharStream *srdr = (CharStream *)stream;
69 const char *ptr = srdr->curpos;
70 for (size_t i=0; i<maxlength; i++)
79 *read = ptr - srdr->curpos;
86 SMCParseError CTextParsers::ParseString_SMC(const char *stream,
87 ITextListener_SMC *smc,
91 CharStream srdr = { stream };
93 return ParseStream_SMC(&srdr, CharStreamReader, smc, line, col);
100 bool FileStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
102 size_t num = fread(buffer, 1, maxlength, (FILE *)stream);
104 *read = static_cast<unsigned int>(num);
106 if (num == 0 && feof((FILE *)stream))
111 return (ferror((FILE *)stream) == 0);
114 SMCParseError CTextParsers::ParseFile_SMC(const char *file, ITextListener_SMC *smc, unsigned int *line, unsigned int *col)
116 FILE *fp = fopen(file, "rt");
120 return SMCParse_StreamOpen;
123 SMCParseError result = ParseStream_SMC(fp, FileStreamReader, smc, line, col);
131 * Raw parsing of streams with helper functions
136 StringInfo() : quoted(false), ptr(NULL), end(NULL), special(false) { }
143 const char *FixupString(StringInfo &data)
156 /* A string will never have beginning whitespace because we ignore it in the stream.
157 * Furthermore, if there is trailing whitespace, the end ptr will point to it, so it is valid
158 * to overwrite! Lastly, the last character must be whitespace or a comment/invalid character.
165 //:TODO: this string has special tokens in it, like \, and we must
166 //resolve these before passing the string back to the app
174 const char *rotate(StringInfo info[3])
176 if (info[2].ptr != NULL)
181 if (info[0].ptr != NULL)
185 info[0] = StringInfo();
191 void scrap(StringInfo info[3])
193 info[2] = StringInfo();
194 info[1] = StringInfo();
195 info[0] = StringInfo();
198 void reloc(StringInfo &data, unsigned int bytes)
210 char *lowstring(StringInfo info[3])
212 for (int i=2; i>=0; i--)
223 SMCParseError CTextParsers::ParseStream_SMC(void *stream,
225 ITextListener_SMC *smc,
230 char *reparse_point = NULL;
231 char *parse_point = in_buf;
232 char *line_begin = in_buf;
234 unsigned int curline = 1;
235 unsigned int curtok = 0;
236 unsigned int curlevel = 0;
237 bool in_quote = false;
238 bool ignoring = false;
239 bool eol_comment = false;
240 bool ml_comment = false;
242 SMCParseError err = SMCParse_Okay;
246 StringInfo strings[3];
247 StringInfo emptystring;
249 smc->ReadSMC_ParseStart();
251 while (srdr(stream, parse_point, sizeof(in_buf) - (parse_point - line_begin) - 1, &read))
258 /* :TODO: do this outside of the main loop somehow
259 * This checks for BOM markings
262 in_buf[0] == (char)0xEF &&
263 in_buf[1] == (char)0xBB &&
264 in_buf[2] == (char)0xBF)
266 parse_point = &in_buf[3];
271 read += (parse_point - reparse_point);
272 parse_point = reparse_point;
273 reparse_point = NULL;
276 for (i=0; i<read; i++)
281 /* If we got a newline, there's a lot of things that could have happened in the interim.
282 * First, let's make sure the staged strings are rotated.
286 strings[0].end = &parse_point[i];
287 if (rotate(strings) != NULL)
289 err = SMCParse_InvalidTokens;
294 /* Next, let's clear some line-based values that may no longer have meaning */
297 if (ignoring && !ml_comment)
302 /* Pass the raw line onto the listener */
303 if ((res=smc->ReadSMC_RawLine(line_begin, curline)) != SMCParse_Continue)
305 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
309 /* Now we check the sanity of our staged strings! */
314 err = SMCParse_InvalidProperty1;
317 /* Assume the next string is a property and pass the info on. */
318 if ((res=smc->ReadSMC_KeyValue(
319 FixupString(strings[2]),
320 FixupString(strings[1]),
322 strings[1].quoted)) != SMCParse_Continue)
324 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
330 /* Change the states for the next line */
333 line_begin = &parse_point[i+1]; //Note: safe because this gets relocated later
334 } else if (ignoring) {
337 /* If i was 0, this case is impossible due to reparsing */
338 if ((i != 0) && c == '"' && parse_point[i-1] != '\\')
340 /* If we reached a quote in an ignore phase,
341 * we're staging a string and we must rotate it out.
346 strings[0].end = &parse_point[i];
347 strings[0].quoted = true;
348 if (rotate(strings) != NULL)
350 /* If we rotated too many strings, there was too much crap on one line */
351 err = SMCParse_InvalidTokens;
354 } else if (c == '\\' && i == (read - 1)) {
355 strings[0].special = true;
356 reparse_point = &parse_point[i];
359 } else if (ml_comment) {
362 /* Check if we need to get more input first */
365 reparse_point = &parse_point[i];
368 if (parse_point[i+1] == '/')
372 /* We should not be staging anything right now. */
373 assert(strings[0].ptr == NULL);
374 /* Advance the input stream so we don't choke on this token */
381 /* Check if we're whitespace or not */
382 if (!g_ws_chartable[(unsigned)c])
384 bool restage = false;
385 /* Check various special tokens:
392 if (c == ';' || c == '/')
394 /* If it's a line-based comment (that is, ; or //)
395 * we will need to scrap everything until the end of the line.
401 /* If we reached the end of the look-ahead, we need to re-check our input.
402 * Breaking out will force this to be the new reparse point!
404 reparse_point = &reparse_point[i];
407 if (parse_point[i + 1] == '/')
409 /* standard comment */
413 } else if (parse_point[i+1] == '*') {
414 /* inline comment - start ignoring */
417 /* yes, we restage, meaning that:
418 * STR/ *stuff* /ING (space because ml comments don't nest in C++)
419 * will not generate 'STRING', but rather 'STR' and 'ING'.
420 * This should be a rare occurrence and is done here for convenience.
429 } else if (c == '{') {
430 /* If we are staging a string, we must rotate here */
433 /* We have unacceptable tokens on this line */
434 if (rotate(strings) != NULL)
436 err = SMCParse_InvalidSection1;
440 /* Sections must always be alone */
441 if (strings[2].ptr != NULL)
443 err = SMCParse_InvalidSection1;
445 } else if (strings[1].ptr == NULL) {
446 err = SMCParse_InvalidSection2;
449 if ((res=smc->ReadSMC_NewSection(FixupString(strings[1]), strings[1].quoted))
450 != SMCParse_Continue)
452 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
455 strings[1] = emptystring;
457 } else if (c == '}') {
458 /* Unlike our matching friend, this can be on the same line as something prior */
459 if (rotate(strings) != NULL)
461 err = SMCParse_InvalidSection3;
468 err = SMCParse_InvalidProperty1;
471 if ((res=smc->ReadSMC_KeyValue(
472 FixupString(strings[2]),
473 FixupString(strings[1]),
476 != SMCParse_Continue)
478 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
481 } else if (strings[1].ptr) {
482 err = SMCParse_InvalidSection3;
484 } else if (!curlevel) {
485 err = SMCParse_InvalidSection4;
488 /* Now it's safe to leave the section */
490 if ((res=smc->ReadSMC_LeavingSection()) != SMCParse_Continue)
492 err = (res == SMCParse_HaltFail) ? SMCParse_Custom : SMCParse_Okay;
496 } else if (c == '"') {
497 /* If we get a quote mark, we always restage, but we need to do it beforehand */
500 strings[0].end = &parse_point[i];
501 if (rotate(strings) != NULL)
503 err = SMCParse_InvalidTokens;
507 strings[0].ptr = &parse_point[i];
510 } else if (!strings[0].ptr) {
511 /* If we have no string, we must start one */
512 strings[0].ptr = &parse_point[i];
514 if (restage && strings[0].ptr)
516 strings[0].end = &parse_point[i];
517 if (rotate(strings) != NULL)
519 err = SMCParse_InvalidTokens;
524 /* If we're eating a string and get whitespace, we need to restage.
525 * (Note that if we are quoted, this is being ignored)
530 * The specification says the second string in a pair does not need to be quoted.
531 * Thus, we check if there's already a string on the stack.
532 * If there's a newline, we always rotate so the newline has an empty starter.
536 /* There's no string, so we must move this one down and eat up another */
537 strings[0].end = &parse_point[i];
539 } else if (!strings[1].quoted) {
540 err = SMCParse_InvalidTokens;
547 /* Advance which token we're on */
551 if (line_begin != in_buf)
553 /* The line buffer has advanced, so it's safe to copy N bytes back to the beginning.
554 * What's N? N is the lowest point we're currently relying on.
556 char *stage = lowstring(strings);
557 if (!stage || stage > line_begin)
561 unsigned int bytes = read - (stage - parse_point);
563 /* It is now safe to delete everything before the staged point */
564 memmove(in_buf, stage, bytes);
566 /* Calculate the number of bytes in the new buffer */
567 bytes = stage - in_buf;
568 /* Relocate all the cached pointers to our new base */
570 reloc(strings[0], bytes);
571 reloc(strings[1], bytes);
572 reloc(strings[2], bytes);
575 reparse_point -= bytes;
579 parse_point = &parse_point[read];
580 parse_point -= bytes;
582 } else if (read == sizeof(in_buf) - 1) {
583 err = SMCParse_TokenOverflow;
588 /* If we're done parsing and there are tokens left over... */
591 err = SMCParse_InvalidSection5;
593 } else if (strings[0].ptr || strings[1].ptr) {
594 err = SMCParse_InvalidTokens;
598 smc->ReadSMC_ParseEnd(false, false);
600 return SMCParse_Okay;
608 smc->ReadSMC_ParseEnd(true, (err == SMCParse_Custom));
623 bool CTextParsers::ParseFile_INI(const char *file, ITextListener_INI *ini_listener, unsigned int *line, unsigned int *col)
625 FILE *fp = fopen(file, "rt");
626 unsigned int curline = 0;
641 char *ptr, *save_ptr;
649 if (fgets(buffer, sizeof(buffer), fp) == NULL)
654 //:TODO: this will only run once, so find a nice way to move it out of the while loop
655 /* If this is the first line, check the first three bytes for BOM */
657 buffer[0] == (char)0xEF &&
658 buffer[1] == (char)0xBB &&
659 buffer[2] == (char)0xBF)
661 /* We have a UTF-8 marked file... skip these bytes */
667 /***************************************************
668 * We preprocess the string before parsing tokens! *
669 ***************************************************/
671 /* First strip beginning whitespace */
672 while (*ptr != '\0' && g_ws_chartable[(unsigned)*ptr] != 0)
684 /* Now search for comment characters */
687 for (size_t i=0; i<len; i++,ptr++)
702 /* Terminate the string here */
722 /* Lastly, strip ending whitespace off */
723 for (size_t i=len-1; i>=0 && i<len; i--)
725 if (g_ws_chartable[(unsigned)ptr[i]])
739 if (!ini_listener->ReadINI_RawLine(ptr, &curtok))
746 bool invalid_tokens = false;
747 bool got_bracket = false;
748 bool extra_tokens = false;
753 for (size_t i=1; i<len; i++)
760 if (mbtowc(&wc, &ptr[i], len-i) != -1)
762 alnum = (iswalnum(wc) != 0);
763 i += _GetUTF8CharBytes(&ptr[i]) - 1;
766 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
770 /* First check - is this a bracket? */
775 /* If this isn't the last character... */
784 /* n...No! Continue copying. */
785 invalid_tokens = true;
790 /* Tell the handler */
791 if (!ini_listener->ReadINI_NewSection(&ptr[1], invalid_tokens, got_bracket, extra_tokens, &curtok))
797 char *val_ptr = NULL;
799 size_t first_space = 0;
800 bool invalid_tokens = false;
801 bool equal_token = false;
806 for (size_t i=0; i<len; i++)
810 /* is this an invalid char? */
813 if (mbtowc(&wc, &ptr[i], len-i) != -1)
815 alnum = (iswalnum(wc) != 0);
816 i += _GetUTF8CharBytes(&ptr[i]) - 1;
819 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
824 if (g_ws_chartable[(unsigned)c])
826 /* if it's a space, keep track of the first occurring space */
834 /* if it's an equal sign, we're done with the key */
837 /* remove excess whitespace */
838 key_ptr[first_space] = '\0';
840 /* remove the equal sign */
843 if (ptr[++i] != '\0')
845 /* If this isn't the end, set next pointer */
851 /* Mark that we got something invalid! */
852 invalid_tokens = true;
859 /* Now we need to parse the value, if any */
862 /* eat up spaces! there shouldn't be any h*/
863 while ((*val_ptr != '\0') && g_ws_chartable[(unsigned)*val_ptr] != 0)
867 if (*val_ptr == '\0')
872 /* Do we have an initial quote? If so, the parsing rules change! */
873 if (*val_ptr == '"' && *val_ptr != '\0')
875 len = strlen(val_ptr);
876 if (val_ptr[len-1] == '"')
879 val_ptr[--len] = '\0';
887 curtok = val_ptr - buffer;
888 if (!ini_listener->ReadINI_KeyValue(key_ptr, val_ptr, invalid_tokens, equal_token, quotes, &curtok))
921 const char *CTextParsers::GetSMCErrorString(SMCParseError err)
923 static const char *s_errors[] =
926 "Stream failed to open",
927 "Stream returned read error",
929 "Un-quoted section has invalid tokens",
930 "Section declared without header",
931 "Section declared with unknown tokens",
932 "Section ending without a matching section beginning",
933 "Section beginning without a matching ending",
934 "Line contained too many invalid tokens",
935 "Token buffer overflowed",
936 "A property was declared outside of a section",
939 if (err < SMCParse_Okay || err > SMCParse_InvalidProperty1)
944 return s_errors[err];