Bumped versions.
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"
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 void TextParsers::OnSourceModAllInitialized()
74 g_ShareSys.AddInterface(NULL, this);
77 unsigned int TextParsers::GetUTF8CharBytes(const char *stream)
79 return _GetUTF8CharBytes(stream);
86 bool FileStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
88 size_t num = fread(buffer, 1, maxlength, (FILE *)stream);
90 *read = static_cast<unsigned int>(num);
92 if (num == 0 && feof((FILE *)stream))
97 return (ferror((FILE *)stream) == 0);
100 SMCError TextParsers::ParseFile_SMC(const char *file, ITextListener_SMC *smc, SMCStates *states)
102 FILE *fp = fopen(file, "rt");
111 return SMCError_StreamOpen;
114 SMCError result = ParseStream_SMC(fp, FileStreamReader, smc, states);
121 SMCError TextParsers::ParseSMCFile(const char *file,
122 ITextListener_SMC *smc_listener,
128 FILE *fp = fopen(file, "rt");
132 char error[256] = "unknown";
138 g_LibSys.GetPlatformError(error, sizeof(error));
139 UTIL_Format(buffer, maxsize, "File could not be opened: %s", error);
140 return SMCError_StreamOpen;
143 SMCError result = ParseStream_SMC(fp, FileStreamReader, smc_listener, states);
147 errstr = GetSMCErrorString(result);
148 UTIL_Format(buffer, maxsize, "%s", errstr != NULL ? errstr : "Unknown error");
160 bool RawStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
162 RawStream *rs = (RawStream *)stream;
164 if (rs->pos >= rs->length)
169 size_t remaining = rs->length - rs->pos;
171 /* Use the smaller of the two */
172 size_t copy = (remaining > maxlength) ? maxlength : remaining;
174 memcpy(buffer, &rs->stream[rs->pos], copy);
177 assert(rs->pos <= rs->length);
182 SMCError TextParsers::ParseSMCStream(const char *stream,
184 ITextListener_SMC *smc_listener,
196 result = ParseStream_SMC(&rs, RawStreamReader, smc_listener, states);
198 const char *errstr = GetSMCErrorString(result);
199 UTIL_Format(buffer, maxsize, "%s", errstr != NULL ? errstr : "Unknown error");
205 * Raw parsing of streams with helper functions
210 StringInfo() : quoted(false), ptr(NULL), end(NULL), special(false) { }
217 const char *FixupString(StringInfo &data)
230 /* A string will never have beginning whitespace because we ignore it in the stream.
231 * Furthermore, if there is trailing whitespace, the end ptr will point to it, so it is valid
232 * to overwrite! Lastly, the last character must be whitespace or a comment/invalid character.
237 /* Do some extra work on strings that have special quoted characters. */
240 char *outptr = data.ptr;
241 size_t len = data.end - data.ptr;
244 for (size_t i=0; i<len; i++)
246 if (data.ptr[i] == '\\' && i < len - 1)
248 /* Resolve the next character. */
250 if (data.ptr[i] == 'n')
253 } else if (data.ptr[i] == 't') {
255 } else if (data.ptr[i] == 'r') {
257 } else if (data.ptr[i] != '\\'
258 && data.ptr[i] != '"') {
259 /* This character is invalid, so go back one */
263 *outptr++ = data.ptr[i];
277 const char *rotate(StringInfo info[3])
279 if (info[2].ptr != NULL)
284 if (info[0].ptr != NULL)
288 info[0] = StringInfo();
294 void scrap(StringInfo info[3])
296 info[2] = StringInfo();
297 info[1] = StringInfo();
298 info[0] = StringInfo();
301 void reloc(StringInfo &data, unsigned int bytes)
313 char *lowstring(StringInfo info[3])
315 for (int i=2; i>=0; i--)
326 SMCError TextParsers::ParseStream_SMC(void *stream,
328 ITextListener_SMC *smc,
331 char *reparse_point = NULL;
333 char *parse_point = in_buf;
334 char *line_begin = in_buf;
336 unsigned int curlevel = 0;
337 bool in_quote = false;
338 bool ignoring = false;
339 bool eol_comment = false;
340 bool ml_comment = false;
342 SMCError err = SMCError_Okay;
347 StringInfo strings[3];
348 StringInfo emptystring;
353 smc->ReadSMC_ParseStart();
356 * The stream reader reads in as much as it can fill the buffer with.
357 * It then processes the buffer. If the buffer cannot be fully processed, for example,
358 * a line is left hanging with no newline, then the contents of the buffer is shifted
359 * down, and the buffer is filled from the stream reader again.
361 * What makes this particularly annoying is that we cache pointers everywhere, so when
362 * the shifting process takes place, all those pointers must be shifted as well.
364 while (srdr(stream, parse_point, sizeof(in_buf) - (parse_point - in_buf) - 1, &read))
371 /* Check for BOM markings, which is only relevant on the first line.
372 * Not worth it, but it could be moved out of the loop.
374 if (states.line == 1 &&
375 in_buf[0] == (char)0xEF &&
376 in_buf[1] == (char)0xBB &&
377 in_buf[2] == (char)0xBF)
379 /* Move EVERYTHING down :\ */
380 memmove(in_buf, &in_buf[3], read - 3);
386 read += (parse_point - reparse_point);
387 parse_point = reparse_point;
388 reparse_point = NULL;
391 for (i=0; i<read; i++)
396 /* If we got a newline, there's a lot of things that could have happened in the interim.
397 * First, let's make sure the staged strings are rotated.
401 strings[0].end = &parse_point[i];
402 if (rotate(strings) != NULL)
404 err = SMCError_InvalidTokens;
409 /* Next, let's clear some line-based values that may no longer have meaning */
412 if (ignoring && !ml_comment)
417 /* Pass the raw line onto the listener. We terminate the line so the receiver
418 * doesn't get tons of useless info. We restore the newline after.
420 parse_point[i] = '\0';
421 if ((res=smc->ReadSMC_RawLine(&states, line_begin)) != SMCResult_Continue)
423 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
426 parse_point[i] = '\n';
428 /* Now we check the sanity of our staged strings! */
433 err = SMCError_InvalidProperty1;
436 /* Assume the next string is a property and pass the info on. */
437 if ((res=smc->ReadSMC_KeyValue(
439 FixupString(strings[2]),
440 FixupString(strings[1]))) != SMCResult_Continue)
442 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
448 /* Change the states for the next line */
451 line_begin = &parse_point[i+1]; //Note: safe because this gets relocated later
457 /* If i was 0, we could have reparsed, so make sure there's no buffer underrun */
458 if ((&parse_point[i] != in_buf) && c == '"' && parse_point[i-1] != '\\')
460 /* If we reached a quote in an ignore phase,
461 * we're staging a string and we must rotate it out.
466 strings[0].end = &parse_point[i];
467 strings[0].quoted = true;
468 if (rotate(strings) != NULL)
470 /* If we rotated too many strings, there was too much crap on one line */
471 err = SMCError_InvalidTokens;
477 strings[0].special = true;
480 reparse_point = &parse_point[i];
489 /* Check if we need to get more input first */
492 reparse_point = &parse_point[i];
495 if (parse_point[i+1] == '/')
499 /* We should not be staging anything right now. */
500 assert(strings[0].ptr == NULL);
501 /* Advance the input stream so we don't choke on this token */
510 /* Check if we're whitespace or not */
511 if (!g_ws_chartable[(unsigned)c])
513 bool restage = false;
514 /* Check various special tokens:
521 if (c == ';' || c == '/')
523 /* If it's a line-based comment (that is, ; or //)
524 * we will need to scrap everything until the end of the line.
530 /* If we reached the end of the look-ahead, we need to re-check our input.
531 * Breaking out will force this to be the new reparse point!
533 reparse_point = &parse_point[i];
536 if (parse_point[i + 1] == '/')
538 /* standard comment */
543 else if (parse_point[i+1] == '*')
545 /* inline comment - start ignoring */
548 /* yes, we restage, meaning that:
549 * STR/ *stuff* /ING (space because ml comments don't nest in C++)
550 * will not generate 'STRING', but rather 'STR' and 'ING'.
551 * This should be a rare occurrence and is done here for convenience.
565 /* If we are staging a string, we must rotate here */
568 /* We have unacceptable tokens on this line */
569 if (rotate(strings) != NULL)
571 err = SMCError_InvalidSection1;
575 /* Sections must always be alone */
576 if (strings[2].ptr != NULL)
578 err = SMCError_InvalidSection1;
581 else if (strings[1].ptr == NULL)
583 err = SMCError_InvalidSection2;
586 if ((res=smc->ReadSMC_NewSection(&states, FixupString(strings[1])))
587 != SMCResult_Continue)
589 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
592 strings[1] = emptystring;
597 /* Unlike our matching friend, this can be on the same line as something prior */
598 if (rotate(strings) != NULL)
600 err = SMCError_InvalidSection3;
607 err = SMCError_InvalidProperty1;
610 if ((res=smc->ReadSMC_KeyValue(
612 FixupString(strings[2]),
613 FixupString(strings[1])))
614 != SMCResult_Continue)
616 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
620 else if (strings[1].ptr)
622 err = SMCError_InvalidSection3;
627 err = SMCError_InvalidSection4;
630 /* Now it's safe to leave the section */
632 if ((res=smc->ReadSMC_LeavingSection(&states)) != SMCResult_Continue)
634 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
641 /* If we get a quote mark, we always restage, but we need to do it beforehand */
644 strings[0].end = &parse_point[i];
645 if (rotate(strings) != NULL)
647 err = SMCError_InvalidTokens;
651 strings[0].ptr = &parse_point[i];
655 else if (!strings[0].ptr)
657 /* If we have no string, we must start one */
658 strings[0].ptr = &parse_point[i];
660 if (restage && strings[0].ptr)
662 strings[0].end = &parse_point[i];
663 if (rotate(strings) != NULL)
665 err = SMCError_InvalidTokens;
672 /* If we're eating a string and get whitespace, we need to restage.
673 * (Note that if we are quoted, this is being ignored)
678 * The specification says the second string in a pair does not need to be quoted.
679 * Thus, we check if there's already a string on the stack.
680 * If there's a newline, we always rotate so the newline has an empty starter.
684 /* There's no string, so we must move this one down and eat up another */
685 strings[0].end = &parse_point[i];
688 else if (!strings[1].quoted)
690 err = SMCError_InvalidTokens;
697 /* Advance which token we're on */
701 if (line_begin != in_buf)
703 /* The line buffer has advanced, so it's safe to copy N bytes back to the beginning.
704 * What's N? N is the lowest point we're currently relying on.
706 char *stage = lowstring(strings);
707 if (!stage || stage > line_begin)
711 unsigned int bytes = read - (stage - parse_point);
713 /* It is now safe to delete everything before the staged point */
714 memmove(in_buf, stage, bytes);
716 /* Calculate the number of bytes in the new buffer */
717 bytes = stage - in_buf;
718 /* Relocate all the cached pointers to our new base */
720 reloc(strings[0], bytes);
721 reloc(strings[1], bytes);
722 reloc(strings[2], bytes);
725 reparse_point -= bytes;
729 parse_point = &parse_point[read];
730 parse_point -= bytes;
733 else if (read == sizeof(in_buf) - 1)
735 err = SMCError_TokenOverflow;
740 /* If we're done parsing and there are tokens left over... */
743 err = SMCError_InvalidSection5;
746 else if (strings[0].ptr || strings[1].ptr)
748 err = SMCError_InvalidTokens;
752 smc->ReadSMC_ParseEnd(false, false);
759 return SMCError_Okay;
767 smc->ReadSMC_ParseEnd(true, (err == SMCError_Custom));
777 bool TextParsers::ParseFile_INI(const char *file, ITextListener_INI *ini_listener, unsigned int *line, unsigned int *col)
779 FILE *fp = fopen(file, "rt");
780 unsigned int curline = 0;
795 char *ptr, *save_ptr;
803 if (fgets(buffer, sizeof(buffer), fp) == NULL)
808 //:TODO: this will only run once, so find a nice way to move it out of the while loop
809 /* If this is the first line, check the first three bytes for BOM */
811 buffer[0] == (char)0xEF &&
812 buffer[1] == (char)0xBB &&
813 buffer[2] == (char)0xBF)
815 /* We have a UTF-8 marked file... skip these bytes */
821 /***************************************************
822 * We preprocess the string before parsing tokens! *
823 ***************************************************/
825 /* First strip beginning whitespace */
826 while (*ptr != '\0' && g_ws_chartable[(unsigned)*ptr] != 0)
838 /* Now search for comment characters */
841 for (size_t i=0; i<len; i++,ptr++)
856 /* Terminate the string here */
876 /* Lastly, strip ending whitespace off */
877 for (size_t i=len-1; i>=0 && i<len; i--)
879 if (g_ws_chartable[(unsigned)ptr[i]])
893 if (!ini_listener->ReadINI_RawLine(ptr, &curtok))
900 bool invalid_tokens = false;
901 bool got_bracket = false;
902 bool extra_tokens = false;
907 for (size_t i=1; i<len; i++)
914 if (mbtowc(&wc, &ptr[i], len-i) != -1)
916 alnum = (iswalnum(wc) != 0);
917 i += _GetUTF8CharBytes(&ptr[i]) - 1;
920 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
924 /* First check - is this a bracket? */
929 /* If this isn't the last character... */
938 /* n...No! Continue copying. */
939 invalid_tokens = true;
944 /* Tell the handler */
945 if (!ini_listener->ReadINI_NewSection(&ptr[1], invalid_tokens, got_bracket, extra_tokens, &curtok))
951 char *val_ptr = NULL;
953 size_t first_space = 0;
954 bool invalid_tokens = false;
955 bool equal_token = false;
960 for (size_t i=0; i<len; i++)
964 /* is this an invalid char? */
967 if (mbtowc(&wc, &ptr[i], len-i) != -1)
969 alnum = (iswalnum(wc) != 0);
970 i += _GetUTF8CharBytes(&ptr[i]) - 1;
973 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
978 if (g_ws_chartable[(unsigned)c])
980 /* if it's a space, keep track of the first occurring space */
988 /* if it's an equal sign, we're done with the key */
991 /* remove excess whitespace */
992 key_ptr[first_space] = '\0';
994 /* remove the equal sign */
997 if (ptr[++i] != '\0')
999 /* If this isn't the end, set next pointer */
1005 /* Mark that we got something invalid! */
1006 invalid_tokens = true;
1013 /* Now we need to parse the value, if any */
1016 /* eat up spaces! there shouldn't be any h*/
1017 while ((*val_ptr != '\0') && g_ws_chartable[(unsigned)*val_ptr] != 0)
1021 if (*val_ptr == '\0')
1026 /* Do we have an initial quote? If so, the parsing rules change! */
1027 if (*val_ptr == '"' && *val_ptr != '\0')
1029 len = strlen(val_ptr);
1030 if (val_ptr[len-1] == '"')
1033 val_ptr[--len] = '\0';
1041 curtok = val_ptr - buffer;
1042 if (!ini_listener->ReadINI_KeyValue(key_ptr, val_ptr, invalid_tokens, equal_token, quotes, &curtok))
1075 const char *TextParsers::GetSMCErrorString(SMCError err)
1077 static const char *s_errors[] =
1080 "Stream failed to open",
1081 "Stream returned read error",
1083 "Un-quoted section has invalid tokens",
1084 "Section declared without header",
1085 "Section declared with unknown tokens",
1086 "Section ending without a matching section beginning",
1087 "Section beginning without a matching ending",
1088 "Line contained too many invalid tokens",
1089 "Token buffer overflowed",
1090 "A property was declared outside of a section",
1093 if (err < SMCError_Okay || err > SMCError_InvalidProperty1)
1098 return s_errors[err];