More Windows build fix.
3 * =============================================================================
5 * Copyright (C) 2004-2008 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"
39 //#include "ShareSys.h"
40 //#include "sm_stringutil.h"
41 //#include "LibrarySys.h"
43 TextParsers g_TextParser;
44 ITextParsers *textparsers = &g_TextParser;
46 static int g_ini_chartable1[255] = {0};
47 static int g_ws_chartable[255] = {0};
49 bool TextParsers::IsWhitespace(const char *stream)
51 return g_ws_chartable[(unsigned)*stream] == 1;
54 TextParsers::TextParsers()
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_ini_chartable1[(unsigned)'?'] = 1;
63 g_ini_chartable1[(unsigned)'/'] = 1;
64 g_ws_chartable[(unsigned)'\n'] = 1;
65 g_ws_chartable[(unsigned)'\v'] = 1;
66 g_ws_chartable[(unsigned)'\r'] = 1;
67 g_ws_chartable[(unsigned)'\t'] = 1;
68 g_ws_chartable[(unsigned)'\f'] = 1;
69 g_ws_chartable[(unsigned)' '] = 1;
72 unsigned int TextParsers::GetUTF8CharBytes(const char *stream)
74 return _GetUTF8CharBytes(stream);
81 bool FileStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
83 size_t num = fread(buffer, 1, maxlength, (FILE *)stream);
85 *read = static_cast<unsigned int>(num);
87 if (num == 0 && feof((FILE *)stream))
92 return (ferror((FILE *)stream) == 0);
95 SMCError TextParsers::ParseFile_SMC(const char *file, ITextListener_SMC *smc, SMCStates *states)
97 FILE *fp = fopen(file, "rt");
106 return SMCError_StreamOpen;
109 SMCError result = ParseStream_SMC(fp, FileStreamReader, smc, states);
116 SMCError TextParsers::ParseSMCFile(const char *file,
117 ITextListener_SMC *smc_listener,
123 FILE *fp = fopen(file, "rt");
127 char error[256] = "unknown";
133 //g_LibSys.GetPlatformError(error, sizeof(error));
134 UTIL_Format(buffer, maxsize, "File could not be opened: %s", error);
135 return SMCError_StreamOpen;
138 SMCError result = ParseStream_SMC(fp, FileStreamReader, smc_listener, states);
142 errstr = GetSMCErrorString(result);
143 UTIL_Format(buffer, maxsize, "%s", errstr != NULL ? errstr : "Unknown error");
155 bool RawStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
157 RawStream *rs = (RawStream *)stream;
159 if (rs->pos >= rs->length)
164 size_t remaining = rs->length - rs->pos;
166 /* Use the smaller of the two */
167 size_t copy = (remaining > maxlength) ? maxlength : remaining;
169 memcpy(buffer, &rs->stream[rs->pos], copy);
172 assert(rs->pos <= rs->length);
177 SMCError TextParsers::ParseSMCStream(const char *stream,
179 ITextListener_SMC *smc_listener,
191 result = ParseStream_SMC(&rs, RawStreamReader, smc_listener, states);
193 const char *errstr = GetSMCErrorString(result);
194 UTIL_Format(buffer, maxsize, "%s", errstr != NULL ? errstr : "Unknown error");
200 * Raw parsing of streams with helper functions
205 StringInfo() : quoted(false), ptr(NULL), end(NULL), special(false) { }
212 const char *FixupString(StringInfo &data)
225 /* A string will never have beginning whitespace because we ignore it in the stream.
226 * Furthermore, if there is trailing whitespace, the end ptr will point to it, so it is valid
227 * to overwrite! Lastly, the last character must be whitespace or a comment/invalid character.
232 /* Do some extra work on strings that have special quoted characters. */
235 char *outptr = data.ptr;
236 size_t len = data.end - data.ptr;
239 for (size_t i=0; i<len; i++)
241 if (data.ptr[i] == '\\' && i < len - 1)
243 /* Resolve the next character. */
245 if (data.ptr[i] == 'n')
248 } else if (data.ptr[i] == 't') {
250 } else if (data.ptr[i] == 'r') {
252 } else if (data.ptr[i] != '\\'
253 && data.ptr[i] != '"') {
254 /* This character is invalid, so go back one */
258 *outptr++ = data.ptr[i];
272 const char *rotate(StringInfo info[3])
274 if (info[2].ptr != NULL)
279 if (info[0].ptr != NULL)
283 info[0] = StringInfo();
289 void scrap(StringInfo info[3])
291 info[2] = StringInfo();
292 info[1] = StringInfo();
293 info[0] = StringInfo();
296 void reloc(StringInfo &data, unsigned int bytes)
308 char *lowstring(StringInfo info[3])
310 for (int i=2; i>=0; i--)
321 SMCError TextParsers::ParseStream_SMC(void *stream,
323 ITextListener_SMC *smc,
326 char *reparse_point = NULL;
328 char *parse_point = in_buf;
329 char *line_begin = in_buf;
331 unsigned int curlevel = 0;
332 bool in_quote = false;
333 bool ignoring = false;
334 bool eol_comment = false;
335 bool ml_comment = false;
337 SMCError err = SMCError_Okay;
342 StringInfo strings[3];
343 StringInfo emptystring;
348 smc->ReadSMC_ParseStart();
351 * The stream reader reads in as much as it can fill the buffer with.
352 * It then processes the buffer. If the buffer cannot be fully processed, for example,
353 * a line is left hanging with no newline, then the contents of the buffer is shifted
354 * down, and the buffer is filled from the stream reader again.
356 * What makes this particularly annoying is that we cache pointers everywhere, so when
357 * the shifting process takes place, all those pointers must be shifted as well.
359 while (srdr(stream, parse_point, sizeof(in_buf) - (parse_point - in_buf) - 1, &read))
366 /* Check for BOM markings, which is only relevant on the first line.
367 * Not worth it, but it could be moved out of the loop.
369 if (states.line == 1 &&
370 in_buf[0] == (char)0xEF &&
371 in_buf[1] == (char)0xBB &&
372 in_buf[2] == (char)0xBF)
374 /* Move EVERYTHING down :\ */
375 memmove(in_buf, &in_buf[3], read - 3);
381 read += (parse_point - reparse_point);
382 parse_point = reparse_point;
383 reparse_point = NULL;
386 for (i=0; i<read; i++)
391 /* If we got a newline, there's a lot of things that could have happened in the interim.
392 * First, let's make sure the staged strings are rotated.
396 strings[0].end = &parse_point[i];
397 if (rotate(strings) != NULL)
399 err = SMCError_InvalidTokens;
404 /* Next, let's clear some line-based values that may no longer have meaning */
407 if (ignoring && !ml_comment)
412 /* Pass the raw line onto the listener. We terminate the line so the receiver
413 * doesn't get tons of useless info. We restore the newline after.
415 parse_point[i] = '\0';
416 if ((res=smc->ReadSMC_RawLine(&states, line_begin)) != SMCResult_Continue)
418 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
421 parse_point[i] = '\n';
423 /* Now we check the sanity of our staged strings! */
428 err = SMCError_InvalidProperty1;
431 /* Assume the next string is a property and pass the info on. */
432 if ((res=smc->ReadSMC_KeyValue(
434 FixupString(strings[2]),
435 FixupString(strings[1]))) != SMCResult_Continue)
437 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
443 /* Change the states for the next line */
446 line_begin = &parse_point[i+1]; //Note: safe because this gets relocated later
452 /* If i was 0, we could have reparsed, so make sure there's no buffer underrun */
453 if ((&parse_point[i] != in_buf) && c == '"' && parse_point[i-1] != '\\')
455 /* If we reached a quote in an ignore phase,
456 * we're staging a string and we must rotate it out.
461 strings[0].end = &parse_point[i];
462 strings[0].quoted = true;
463 if (rotate(strings) != NULL)
465 /* If we rotated too many strings, there was too much crap on one line */
466 err = SMCError_InvalidTokens;
472 strings[0].special = true;
475 reparse_point = &parse_point[i];
484 /* Check if we need to get more input first */
487 reparse_point = &parse_point[i];
490 if (parse_point[i+1] == '/')
494 /* We should not be staging anything right now. */
495 assert(strings[0].ptr == NULL);
496 /* Advance the input stream so we don't choke on this token */
505 /* Check if we're whitespace or not */
506 if (!g_ws_chartable[(unsigned)c])
508 bool restage = false;
509 /* Check various special tokens:
516 if (c == ';' || c == '/')
518 /* If it's a line-based comment (that is, ; or //)
519 * we will need to scrap everything until the end of the line.
525 /* If we reached the end of the look-ahead, we need to re-check our input.
526 * Breaking out will force this to be the new reparse point!
528 reparse_point = &parse_point[i];
531 if (parse_point[i + 1] == '/')
533 /* standard comment */
538 else if (parse_point[i+1] == '*')
540 /* inline comment - start ignoring */
543 /* yes, we restage, meaning that:
544 * STR/ *stuff* /ING (space because ml comments don't nest in C++)
545 * will not generate 'STRING', but rather 'STR' and 'ING'.
546 * This should be a rare occurrence and is done here for convenience.
560 /* If we are staging a string, we must rotate here */
563 /* We have unacceptable tokens on this line */
564 if (rotate(strings) != NULL)
566 err = SMCError_InvalidSection1;
570 /* Sections must always be alone */
571 if (strings[2].ptr != NULL)
573 err = SMCError_InvalidSection1;
576 else if (strings[1].ptr == NULL)
578 err = SMCError_InvalidSection2;
581 if ((res=smc->ReadSMC_NewSection(&states, FixupString(strings[1])))
582 != SMCResult_Continue)
584 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
587 strings[1] = emptystring;
592 /* Unlike our matching friend, this can be on the same line as something prior */
593 if (rotate(strings) != NULL)
595 err = SMCError_InvalidSection3;
602 err = SMCError_InvalidProperty1;
605 if ((res=smc->ReadSMC_KeyValue(
607 FixupString(strings[2]),
608 FixupString(strings[1])))
609 != SMCResult_Continue)
611 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
615 else if (strings[1].ptr)
617 err = SMCError_InvalidSection3;
622 err = SMCError_InvalidSection4;
625 /* Now it's safe to leave the section */
627 if ((res=smc->ReadSMC_LeavingSection(&states)) != SMCResult_Continue)
629 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
636 /* If we get a quote mark, we always restage, but we need to do it beforehand */
639 strings[0].end = &parse_point[i];
640 if (rotate(strings) != NULL)
642 err = SMCError_InvalidTokens;
646 strings[0].ptr = &parse_point[i];
650 else if (!strings[0].ptr)
652 /* If we have no string, we must start one */
653 strings[0].ptr = &parse_point[i];
655 if (restage && strings[0].ptr)
657 strings[0].end = &parse_point[i];
658 if (rotate(strings) != NULL)
660 err = SMCError_InvalidTokens;
667 /* If we're eating a string and get whitespace, we need to restage.
668 * (Note that if we are quoted, this is being ignored)
673 * The specification says the second string in a pair does not need to be quoted.
674 * Thus, we check if there's already a string on the stack.
675 * If there's a newline, we always rotate so the newline has an empty starter.
679 /* There's no string, so we must move this one down and eat up another */
680 strings[0].end = &parse_point[i];
683 else if (!strings[1].quoted)
685 err = SMCError_InvalidTokens;
692 /* Advance which token we're on */
696 if (line_begin != in_buf)
698 /* The line buffer has advanced, so it's safe to copy N bytes back to the beginning.
699 * What's N? N is the lowest point we're currently relying on.
701 char *stage = lowstring(strings);
702 if (!stage || stage > line_begin)
706 unsigned int bytes = read - (stage - parse_point);
708 /* It is now safe to delete everything before the staged point */
709 memmove(in_buf, stage, bytes);
711 /* Calculate the number of bytes in the new buffer */
712 bytes = stage - in_buf;
713 /* Relocate all the cached pointers to our new base */
715 reloc(strings[0], bytes);
716 reloc(strings[1], bytes);
717 reloc(strings[2], bytes);
720 reparse_point -= bytes;
724 parse_point = &parse_point[read];
725 parse_point -= bytes;
728 else if (read == sizeof(in_buf) - 1)
730 err = SMCError_TokenOverflow;
735 /* If we're done parsing and there are tokens left over... */
738 err = SMCError_InvalidSection5;
741 else if (strings[0].ptr || strings[1].ptr)
743 err = SMCError_InvalidTokens;
747 smc->ReadSMC_ParseEnd(false, false);
754 return SMCError_Okay;
762 smc->ReadSMC_ParseEnd(true, (err == SMCError_Custom));
772 bool TextParsers::ParseFile_INI(const char *file, ITextListener_INI *ini_listener, unsigned int *line, unsigned int *col)
774 FILE *fp = fopen(file, "rt");
775 unsigned int curline = 0;
790 char *ptr, *save_ptr;
798 if (fgets(buffer, sizeof(buffer), fp) == NULL)
803 //:TODO: this will only run once, so find a nice way to move it out of the while loop
804 /* If this is the first line, check the first three bytes for BOM */
806 buffer[0] == (char)0xEF &&
807 buffer[1] == (char)0xBB &&
808 buffer[2] == (char)0xBF)
810 /* We have a UTF-8 marked file... skip these bytes */
816 /***************************************************
817 * We preprocess the string before parsing tokens! *
818 ***************************************************/
820 /* First strip beginning whitespace */
821 while (*ptr != '\0' && g_ws_chartable[(unsigned)*ptr] != 0)
833 /* Now search for comment characters */
836 for (size_t i=0; i<len; i++,ptr++)
851 /* Terminate the string here */
871 /* Lastly, strip ending whitespace off */
872 for (size_t i=len-1; i>=0 && i<len; i--)
874 if (g_ws_chartable[(unsigned)ptr[i]])
888 if (!ini_listener->ReadINI_RawLine(ptr, &curtok))
895 bool invalid_tokens = false;
896 bool got_bracket = false;
897 bool extra_tokens = false;
902 for (size_t i=1; i<len; i++)
909 if (mbtowc(&wc, &ptr[i], len-i) != -1)
911 alnum = (iswalnum(wc) != 0);
912 i += _GetUTF8CharBytes(&ptr[i]) - 1;
915 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
919 /* First check - is this a bracket? */
924 /* If this isn't the last character... */
933 /* n...No! Continue copying. */
934 invalid_tokens = true;
939 /* Tell the handler */
940 if (!ini_listener->ReadINI_NewSection(&ptr[1], invalid_tokens, got_bracket, extra_tokens, &curtok))
946 char *val_ptr = NULL;
948 size_t first_space = 0;
949 bool invalid_tokens = false;
950 bool equal_token = false;
955 for (size_t i=0; i<len; i++)
959 /* is this an invalid char? */
962 if (mbtowc(&wc, &ptr[i], len-i) != -1)
964 alnum = (iswalnum(wc) != 0);
965 i += _GetUTF8CharBytes(&ptr[i]) - 1;
968 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
973 if (g_ws_chartable[(unsigned)c])
975 /* if it's a space, keep track of the first occurring space */
983 /* if it's an equal sign, we're done with the key */
986 /* remove excess whitespace */
987 key_ptr[first_space] = '\0';
989 /* remove the equal sign */
992 if (ptr[++i] != '\0')
994 /* If this isn't the end, set next pointer */
1000 /* Mark that we got something invalid! */
1001 invalid_tokens = true;
1008 /* Now we need to parse the value, if any */
1011 /* eat up spaces! there shouldn't be any h*/
1012 while ((*val_ptr != '\0') && g_ws_chartable[(unsigned)*val_ptr] != 0)
1016 if (*val_ptr == '\0')
1021 /* Do we have an initial quote? If so, the parsing rules change! */
1022 if (*val_ptr == '"' && *val_ptr != '\0')
1024 len = strlen(val_ptr);
1025 if (val_ptr[len-1] == '"')
1028 val_ptr[--len] = '\0';
1036 curtok = val_ptr - buffer;
1037 if (!ini_listener->ReadINI_KeyValue(key_ptr, val_ptr, invalid_tokens, equal_token, quotes, &curtok))
1070 const char *TextParsers::GetSMCErrorString(SMCError err)
1072 static const char *s_errors[] =
1075 "Stream failed to open",
1076 "Stream returned read error",
1078 "Un-quoted section has invalid tokens",
1079 "Section declared without header",
1080 "Section declared with unknown tokens",
1081 "Section ending without a matching section beginning",
1082 "Section beginning without a matching ending",
1083 "Line contained too many invalid tokens",
1084 "Token buffer overflowed",
1085 "A property was declared outside of a section",
1088 if (err < SMCError_Okay || err > SMCError_InvalidProperty1)
1093 return s_errors[err];