Fixed build for real.
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 <ILibrarySys.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 char)*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 sharesys->AddInterface(NULL, this);
75 unsigned int TextParsers::GetUTF8CharBytes(const char *stream)
77 return _GetUTF8CharBytes(stream);
84 bool FileStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
86 size_t num = fread(buffer, 1, maxlength, (FILE *)stream);
88 *read = static_cast<unsigned int>(num);
90 if (num == 0 && feof((FILE *)stream))
95 return (ferror((FILE *)stream) == 0);
98 SMCError TextParsers::ParseFile_SMC(const char *file, ITextListener_SMC *smc, SMCStates *states)
100 FILE *fp = fopen(file, "rt");
109 return SMCError_StreamOpen;
112 SMCError result = ParseStream_SMC(fp, FileStreamReader, smc, states);
119 SMCError TextParsers::ParseSMCFile(const char *file,
120 ITextListener_SMC *smc_listener,
126 FILE *fp = fopen(file, "rt");
130 char error[256] = "unknown";
136 libsys->GetPlatformError(error, sizeof(error));
137 smcore.Format(buffer, maxsize, "File could not be opened: %s", error);
138 return SMCError_StreamOpen;
141 SMCError result = ParseStream_SMC(fp, FileStreamReader, smc_listener, states);
145 errstr = GetSMCErrorString(result);
146 smcore.Format(buffer, maxsize, "%s", errstr != NULL ? errstr : "Unknown error");
158 bool RawStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
160 RawStream *rs = (RawStream *)stream;
162 if (rs->pos >= rs->length)
167 size_t remaining = rs->length - rs->pos;
169 /* Use the smaller of the two */
170 size_t copy = (remaining > maxlength) ? maxlength : remaining;
172 memcpy(buffer, &rs->stream[rs->pos], copy);
175 assert(rs->pos <= rs->length);
180 SMCError TextParsers::ParseSMCStream(const char *stream,
182 ITextListener_SMC *smc_listener,
194 result = ParseStream_SMC(&rs, RawStreamReader, smc_listener, states);
196 const char *errstr = GetSMCErrorString(result);
197 smcore.Format(buffer, maxsize, "%s", errstr != NULL ? errstr : "Unknown error");
203 * Raw parsing of streams with helper functions
208 StringInfo() : quoted(false), ptr(NULL), end(NULL), special(false) { }
215 const char *FixupString(StringInfo &data)
228 /* A string will never have beginning whitespace because we ignore it in the stream.
229 * Furthermore, if there is trailing whitespace, the end ptr will point to it, so it is valid
230 * to overwrite! Lastly, the last character must be whitespace or a comment/invalid character.
235 /* Do some extra work on strings that have special quoted characters. */
238 char *outptr = data.ptr;
239 size_t len = data.end - data.ptr;
242 for (size_t i=0; i<len; i++)
244 if (data.ptr[i] == '\\' && i < len - 1)
246 /* Resolve the next character. */
248 if (data.ptr[i] == 'n')
251 } else if (data.ptr[i] == 't') {
253 } else if (data.ptr[i] == 'r') {
255 } else if (data.ptr[i] != '\\'
256 && data.ptr[i] != '"') {
257 /* This character is invalid, so go back one */
261 *outptr++ = data.ptr[i];
275 const char *rotate(StringInfo info[3])
277 if (info[2].ptr != NULL)
282 if (info[0].ptr != NULL)
286 info[0] = StringInfo();
292 void scrap(StringInfo info[3])
294 info[2] = StringInfo();
295 info[1] = StringInfo();
296 info[0] = StringInfo();
299 void reloc(StringInfo &data, unsigned int bytes)
311 char *lowstring(StringInfo info[3])
313 for (int i=2; i>=0; i--)
324 SMCError TextParsers::ParseStream_SMC(void *stream,
326 ITextListener_SMC *smc,
329 char *reparse_point = NULL;
331 char *parse_point = in_buf;
332 char *line_begin = in_buf;
334 unsigned int curlevel = 0;
335 bool in_quote = false;
336 bool ignoring = false;
337 bool eol_comment = false;
338 bool ml_comment = false;
340 SMCError err = SMCError_Okay;
345 StringInfo strings[3];
346 StringInfo emptystring;
351 smc->ReadSMC_ParseStart();
354 * The stream reader reads in as much as it can fill the buffer with.
355 * It then processes the buffer. If the buffer cannot be fully processed, for example,
356 * a line is left hanging with no newline, then the contents of the buffer is shifted
357 * down, and the buffer is filled from the stream reader again.
359 * What makes this particularly annoying is that we cache pointers everywhere, so when
360 * the shifting process takes place, all those pointers must be shifted as well.
362 while (srdr(stream, parse_point, sizeof(in_buf) - (parse_point - in_buf) - 1, &read))
369 /* Check for BOM markings, which is only relevant on the first line.
370 * Not worth it, but it could be moved out of the loop.
372 if (states.line == 1 &&
373 in_buf[0] == (char)0xEF &&
374 in_buf[1] == (char)0xBB &&
375 in_buf[2] == (char)0xBF)
377 /* Move EVERYTHING down :\ */
378 memmove(in_buf, &in_buf[3], read - 3);
384 read += (parse_point - reparse_point);
385 parse_point = reparse_point;
386 reparse_point = NULL;
389 for (i=0; i<read; i++)
394 /* If we got a newline, there's a lot of things that could have happened in the interim.
395 * First, let's make sure the staged strings are rotated.
399 strings[0].end = &parse_point[i];
400 if (rotate(strings) != NULL)
402 err = SMCError_InvalidTokens;
407 /* Next, let's clear some line-based values that may no longer have meaning */
410 if (ignoring && !ml_comment)
415 /* Pass the raw line onto the listener. We terminate the line so the receiver
416 * doesn't get tons of useless info. We restore the newline after.
418 parse_point[i] = '\0';
419 if ((res=smc->ReadSMC_RawLine(&states, line_begin)) != SMCResult_Continue)
421 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
424 parse_point[i] = '\n';
426 /* Now we check the sanity of our staged strings! */
431 err = SMCError_InvalidProperty1;
434 /* Assume the next string is a property and pass the info on. */
435 if ((res=smc->ReadSMC_KeyValue(
437 FixupString(strings[2]),
438 FixupString(strings[1]))) != SMCResult_Continue)
440 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
446 /* Change the states for the next line */
449 line_begin = &parse_point[i+1]; //Note: safe because this gets relocated later
455 /* If i was 0, we could have reparsed, so make sure there's no buffer underrun */
456 if ((&parse_point[i] != in_buf) && c == '"' && parse_point[i-1] != '\\')
458 /* If we reached a quote in an ignore phase,
459 * we're staging a string and we must rotate it out.
464 strings[0].end = &parse_point[i];
465 strings[0].quoted = true;
466 if (rotate(strings) != NULL)
468 /* If we rotated too many strings, there was too much crap on one line */
469 err = SMCError_InvalidTokens;
475 strings[0].special = true;
478 reparse_point = &parse_point[i];
487 /* Check if we need to get more input first */
490 reparse_point = &parse_point[i];
493 if (parse_point[i+1] == '/')
497 /* We should not be staging anything right now. */
498 assert(strings[0].ptr == NULL);
499 /* Advance the input stream so we don't choke on this token */
508 /* Check if we're whitespace or not */
509 if (!g_ws_chartable[(unsigned char)c])
511 bool restage = false;
512 /* Check various special tokens:
519 if (c == ';' || c == '/')
521 /* If it's a line-based comment (that is, ; or //)
522 * we will need to scrap everything until the end of the line.
528 /* If we reached the end of the look-ahead, we need to re-check our input.
529 * Breaking out will force this to be the new reparse point!
531 reparse_point = &parse_point[i];
534 if (parse_point[i + 1] == '/')
536 /* standard comment */
541 else if (parse_point[i+1] == '*')
543 /* inline comment - start ignoring */
546 /* yes, we restage, meaning that:
547 * STR/ *stuff* /ING (space because ml comments don't nest in C++)
548 * will not generate 'STRING', but rather 'STR' and 'ING'.
549 * This should be a rare occurrence and is done here for convenience.
563 /* If we are staging a string, we must rotate here */
566 /* We have unacceptable tokens on this line */
567 if (rotate(strings) != NULL)
569 err = SMCError_InvalidSection1;
573 /* Sections must always be alone */
574 if (strings[2].ptr != NULL)
576 err = SMCError_InvalidSection1;
579 else if (strings[1].ptr == NULL)
581 err = SMCError_InvalidSection2;
584 if ((res=smc->ReadSMC_NewSection(&states, FixupString(strings[1])))
585 != SMCResult_Continue)
587 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
590 strings[1] = emptystring;
595 /* Unlike our matching friend, this can be on the same line as something prior */
596 if (rotate(strings) != NULL)
598 err = SMCError_InvalidSection3;
605 err = SMCError_InvalidProperty1;
608 if ((res=smc->ReadSMC_KeyValue(
610 FixupString(strings[2]),
611 FixupString(strings[1])))
612 != SMCResult_Continue)
614 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
618 else if (strings[1].ptr)
620 err = SMCError_InvalidSection3;
625 err = SMCError_InvalidSection4;
628 /* Now it's safe to leave the section */
630 if ((res=smc->ReadSMC_LeavingSection(&states)) != SMCResult_Continue)
632 err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
639 /* If we get a quote mark, we always restage, but we need to do it beforehand */
642 strings[0].end = &parse_point[i];
643 if (rotate(strings) != NULL)
645 err = SMCError_InvalidTokens;
649 strings[0].ptr = &parse_point[i];
653 else if (!strings[0].ptr)
655 /* If we have no string, we must start one */
656 strings[0].ptr = &parse_point[i];
658 if (restage && strings[0].ptr)
660 strings[0].end = &parse_point[i];
661 if (rotate(strings) != NULL)
663 err = SMCError_InvalidTokens;
670 /* If we're eating a string and get whitespace, we need to restage.
671 * (Note that if we are quoted, this is being ignored)
676 * The specification says the second string in a pair does not need to be quoted.
677 * Thus, we check if there's already a string on the stack.
678 * If there's a newline, we always rotate so the newline has an empty starter.
682 /* There's no string, so we must move this one down and eat up another */
683 strings[0].end = &parse_point[i];
686 else if (!strings[1].quoted)
688 err = SMCError_InvalidTokens;
695 /* Advance which token we're on */
699 if (line_begin != in_buf)
701 /* The line buffer has advanced, so it's safe to copy N bytes back to the beginning.
702 * What's N? N is the lowest point we're currently relying on.
704 char *stage = lowstring(strings);
705 if (!stage || stage > line_begin)
709 unsigned int bytes = read - (stage - parse_point);
711 /* It is now safe to delete everything before the staged point */
712 memmove(in_buf, stage, bytes);
714 /* Calculate the number of bytes in the new buffer */
715 bytes = stage - in_buf;
716 /* Relocate all the cached pointers to our new base */
718 reloc(strings[0], bytes);
719 reloc(strings[1], bytes);
720 reloc(strings[2], bytes);
723 reparse_point -= bytes;
727 parse_point = &parse_point[read];
728 parse_point -= bytes;
731 else if (read == sizeof(in_buf) - 1)
733 err = SMCError_TokenOverflow;
738 /* If we're done parsing and there are tokens left over... */
741 err = SMCError_InvalidSection5;
744 else if (strings[0].ptr || strings[1].ptr)
746 err = SMCError_InvalidTokens;
750 smc->ReadSMC_ParseEnd(false, false);
757 return SMCError_Okay;
765 smc->ReadSMC_ParseEnd(true, (err == SMCError_Custom));
775 bool TextParsers::ParseFile_INI(const char *file, ITextListener_INI *ini_listener, unsigned int *line, unsigned int *col)
777 FILE *fp = fopen(file, "rt");
778 unsigned int curline = 0;
793 char *ptr, *save_ptr;
801 if (fgets(buffer, sizeof(buffer), fp) == NULL)
806 //:TODO: this will only run once, so find a nice way to move it out of the while loop
807 /* If this is the first line, check the first three bytes for BOM */
809 buffer[0] == (char)0xEF &&
810 buffer[1] == (char)0xBB &&
811 buffer[2] == (char)0xBF)
813 /* We have a UTF-8 marked file... skip these bytes */
819 /***************************************************
820 * We preprocess the string before parsing tokens! *
821 ***************************************************/
823 /* First strip beginning whitespace */
824 while (*ptr != '\0' && g_ws_chartable[(unsigned char)*ptr] != 0)
836 /* Now search for comment characters */
839 for (size_t i=0; i<len; i++,ptr++)
854 /* Terminate the string here */
874 /* Lastly, strip ending whitespace off */
875 for (size_t i=len-1; i<len; i--)
877 if (g_ws_chartable[(unsigned char)ptr[i]])
891 if (!ini_listener->ReadINI_RawLine(ptr, &curtok))
898 bool invalid_tokens = false;
899 bool got_bracket = false;
900 bool extra_tokens = false;
905 for (size_t i=1; i<len; i++)
912 if (mbtowc(&wc, &ptr[i], len-i) != -1)
914 alnum = (iswalnum(wc) != 0);
915 i += _GetUTF8CharBytes(&ptr[i]) - 1;
918 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned char)c] != 0);
922 /* First check - is this a bracket? */
927 /* If this isn't the last character... */
936 /* n...No! Continue copying. */
937 invalid_tokens = true;
942 /* Tell the handler */
943 if (!ini_listener->ReadINI_NewSection(&ptr[1], invalid_tokens, got_bracket, extra_tokens, &curtok))
949 char *val_ptr = NULL;
951 size_t first_space = 0;
952 bool invalid_tokens = false;
953 bool equal_token = false;
958 for (size_t i=0; i<len; i++)
962 /* is this an invalid char? */
965 if (mbtowc(&wc, &ptr[i], len-i) != -1)
967 alnum = (iswalnum(wc) != 0);
968 i += _GetUTF8CharBytes(&ptr[i]) - 1;
971 alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned char)c] != 0);
976 if (g_ws_chartable[(unsigned char)c])
978 /* if it's a space, keep track of the first occurring space */
986 /* if it's an equal sign, we're done with the key */
989 /* remove excess whitespace */
990 key_ptr[first_space] = '\0';
992 /* remove the equal sign */
995 if (ptr[++i] != '\0')
997 /* If this isn't the end, set next pointer */
1003 /* Mark that we got something invalid! */
1004 invalid_tokens = true;
1011 /* Now we need to parse the value, if any */
1014 /* eat up spaces! there shouldn't be any h*/
1015 while ((*val_ptr != '\0') && g_ws_chartable[(unsigned char)*val_ptr] != 0)
1019 if (*val_ptr == '\0')
1024 /* Do we have an initial quote? If so, the parsing rules change! */
1025 if (*val_ptr == '"' && *val_ptr != '\0')
1027 len = strlen(val_ptr);
1028 if (val_ptr[len-1] == '"')
1031 val_ptr[--len] = '\0';
1039 curtok = val_ptr - buffer;
1040 if (!ini_listener->ReadINI_KeyValue(key_ptr, val_ptr, invalid_tokens, equal_token, quotes, &curtok))
1073 const char *TextParsers::GetSMCErrorString(SMCError err)
1075 static const char *s_errors[] =
1078 "Stream failed to open",
1079 "Stream returned read error",
1081 "Un-quoted section has invalid tokens",
1082 "Section declared without header",
1083 "Section declared with unknown tokens",
1084 "Section ending without a matching section beginning",
1085 "Section beginning without a matching ending",
1086 "Line contained too many invalid tokens",
1087 "Token buffer overflowed",
1088 "A property was declared outside of a section",
1091 if (err < SMCError_Okay || err > SMCError_InvalidProperty1)
1096 return s_errors[err];