core/TextParsers.cpp
author David Anderson <dvander@alliedmods.net>
Thu Mar 05 02:07:44 2009 -0500 (2009-03-05)
changeset 2654 3a73bbf60f34
parent 2558 178d7954939d
child 2702 e5478415190e
permissions -rw-r--r--
Bumped versions.
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <stdio.h>
    33 #include <ctype.h>
    34 #include <wctype.h>
    35 #include <string.h>
    36 #include <stdlib.h>
    37 #include <assert.h>
    38 #include "TextParsers.h"
    39 #include "ShareSys.h"
    40 #include "sm_stringutil.h"
    41 #include "LibrarySys.h"
    42 
    43 TextParsers g_TextParser;
    44 ITextParsers *textparsers = &g_TextParser;
    45 
    46 static int g_ini_chartable1[255] = {0};
    47 static int g_ws_chartable[255] = {0};
    48 
    49 bool TextParsers::IsWhitespace(const char *stream)
    50 {
    51 	return g_ws_chartable[(unsigned)*stream] == 1;
    52 }
    53 
    54 TextParsers::TextParsers()
    55 {
    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;
    70 }
    71 
    72 void TextParsers::OnSourceModAllInitialized()
    73 {
    74 	g_ShareSys.AddInterface(NULL, this);
    75 }
    76 
    77 unsigned int TextParsers::GetUTF8CharBytes(const char *stream)
    78 {
    79 	return _GetUTF8CharBytes(stream);
    80 }
    81 
    82 /**
    83  * File streams
    84  */
    85 
    86 bool FileStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
    87 {
    88 	size_t num = fread(buffer, 1, maxlength, (FILE *)stream);
    89 
    90 	*read = static_cast<unsigned int>(num);
    91 
    92 	if (num == 0 && feof((FILE *)stream))
    93 	{
    94 		return true;
    95 	}
    96 
    97 	return (ferror((FILE *)stream) == 0);
    98 }
    99 
   100 SMCError TextParsers::ParseFile_SMC(const char *file, ITextListener_SMC *smc, SMCStates *states)
   101 {
   102 	FILE *fp = fopen(file, "rt");
   103 
   104 	if (!fp)
   105 	{
   106 		if (states != NULL)
   107 		{
   108 			states->line = 0;
   109 			states->col = 0;
   110 		}
   111 		return SMCError_StreamOpen;
   112 	}
   113 
   114 	SMCError result = ParseStream_SMC(fp, FileStreamReader, smc, states);
   115 
   116 	fclose(fp);
   117 
   118 	return result;
   119 }
   120 
   121 SMCError TextParsers::ParseSMCFile(const char *file,
   122 								   ITextListener_SMC *smc_listener,
   123 								   SMCStates *states,
   124 								   char *buffer,
   125 								   size_t maxsize)
   126 {
   127 	const char *errstr;
   128 	FILE *fp = fopen(file, "rt");
   129 
   130 	if (fp == NULL)
   131 	{
   132 		char error[256] = "unknown";
   133 		if (states != NULL)
   134 		{
   135 			states->line = 0;
   136 			states->col = 0;
   137 		}
   138 		g_LibSys.GetPlatformError(error, sizeof(error));
   139 		UTIL_Format(buffer, maxsize, "File could not be opened: %s", error);
   140 		return SMCError_StreamOpen;
   141 	}
   142 
   143 	SMCError result = ParseStream_SMC(fp, FileStreamReader, smc_listener, states);
   144 
   145 	fclose(fp);
   146 
   147 	errstr = GetSMCErrorString(result);
   148 	UTIL_Format(buffer, maxsize, "%s", errstr != NULL ? errstr : "Unknown error");
   149 
   150 	return result;
   151 }
   152 
   153 struct RawStream
   154 {
   155 	const char *stream;
   156 	size_t length;
   157 	size_t pos;
   158 };
   159 
   160 bool RawStreamReader(void *stream, char *buffer, size_t maxlength, unsigned int *read)
   161 {
   162 	RawStream *rs = (RawStream *)stream;
   163 
   164 	if (rs->pos >= rs->length)
   165 	{
   166 		return false;
   167 	}
   168 
   169 	size_t remaining = rs->length - rs->pos;
   170 
   171 	/* Use the smaller of the two */
   172 	size_t copy = (remaining > maxlength) ? maxlength : remaining;
   173 
   174 	memcpy(buffer, &rs->stream[rs->pos], copy);
   175 	rs->pos += copy;
   176 	*read = copy;
   177 	assert(rs->pos <= rs->length);
   178 
   179 	return true;
   180 }
   181 
   182 SMCError TextParsers::ParseSMCStream(const char *stream,
   183 									 size_t length,
   184 									 ITextListener_SMC *smc_listener,
   185 									 SMCStates *states,
   186 									 char *buffer,
   187 									 size_t maxsize)
   188 {
   189 	RawStream rs;
   190 	SMCError result;
   191 
   192 	rs.stream = stream;
   193 	rs.length = length;
   194 	rs.pos = 0;
   195 
   196 	result = ParseStream_SMC(&rs, RawStreamReader, smc_listener, states);
   197 
   198 	const char *errstr = GetSMCErrorString(result);
   199 	UTIL_Format(buffer, maxsize, "%s", errstr != NULL ? errstr : "Unknown error");
   200 
   201 	return result;
   202 }
   203 
   204 /** 
   205  * Raw parsing of streams with helper functions
   206  */
   207 
   208 struct StringInfo
   209 {
   210 	StringInfo() : quoted(false), ptr(NULL), end(NULL), special(false) { }
   211 	bool quoted;
   212 	char *ptr;
   213 	char *end;
   214 	bool special;
   215 };
   216 
   217 const char *FixupString(StringInfo &data)
   218 {
   219 	if (!data.ptr)
   220 	{
   221 		return NULL;
   222 	}
   223 
   224 	if (data.quoted)
   225 	{
   226 		data.ptr++;
   227 	}
   228 #if defined _DEBUG
   229 	else {
   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.
   233 		 */
   234  	}
   235 #endif
   236 
   237 	/* Do some extra work on strings that have special quoted characters. */
   238 	if (data.special)
   239 	{
   240 		char *outptr = data.ptr;
   241 		size_t len = data.end - data.ptr;
   242 		if (len >= 2)
   243 		{
   244 			for (size_t i=0; i<len; i++)
   245 			{
   246 				if (data.ptr[i] == '\\' && i < len - 1)
   247 				{
   248 					/* Resolve the next character. */
   249 					i++;
   250 					if (data.ptr[i] == 'n')
   251 					{
   252 						data.ptr[i] = '\n';
   253 					} else if (data.ptr[i] == 't') {
   254 						data.ptr[i] = '\t';
   255 					} else if (data.ptr[i] == 'r') {
   256 						data.ptr[i] = '\r';
   257 					} else if (data.ptr[i] != '\\'
   258 						&& data.ptr[i] != '"') {
   259 						/* This character is invalid, so go back one */
   260 						i--;
   261 					}
   262 				}
   263 				*outptr++ = data.ptr[i];
   264 			}
   265 			*outptr = '\0';
   266 		}
   267 	}
   268 
   269 	if (data.end)
   270 	{
   271 		*(data.end) = '\0';
   272 	}
   273 
   274 	return data.ptr;
   275 }
   276 
   277 const char *rotate(StringInfo info[3])
   278 {
   279 	if (info[2].ptr != NULL)
   280 	{
   281 		return info[2].ptr;
   282 	}
   283 
   284 	if (info[0].ptr != NULL)
   285 	{
   286 		info[2] = info[1];
   287 		info[1] = info[0];
   288 		info[0] = StringInfo();
   289 	}
   290 	
   291 	return NULL;
   292 }
   293 
   294 void scrap(StringInfo info[3])
   295 {
   296 	info[2] = StringInfo();
   297 	info[1] = StringInfo();
   298 	info[0] = StringInfo();
   299 }
   300 
   301 void reloc(StringInfo &data, unsigned int bytes)
   302 {
   303 	if (data.ptr)
   304 	{
   305 		data.ptr -= bytes;
   306 	}
   307 	if (data.end)
   308 	{
   309 		data.end -= bytes;
   310 	}
   311 }
   312 
   313 char *lowstring(StringInfo info[3])
   314 {
   315 	for (int i=2; i>=0; i--)
   316 	{
   317 		if (info[i].ptr)
   318 		{
   319 			return info[i].ptr;
   320 		}
   321 	}
   322 
   323 	return NULL;
   324 }
   325 
   326 SMCError TextParsers::ParseStream_SMC(void *stream, 
   327 								   STREAMREADER srdr, 
   328 								   ITextListener_SMC *smc, 
   329 								   SMCStates *pStates)
   330 {
   331 	char *reparse_point = NULL;
   332 	char in_buf[4096];
   333 	char *parse_point = in_buf;
   334 	char *line_begin = in_buf;
   335 	unsigned int read;
   336 	unsigned int curlevel = 0;
   337 	bool in_quote = false;
   338 	bool ignoring = false;
   339 	bool eol_comment = false;
   340 	bool ml_comment = false;
   341 	unsigned int i;
   342 	SMCError err = SMCError_Okay;
   343 	SMCResult res;
   344 	SMCStates states;
   345 	char c;
   346 
   347 	StringInfo strings[3];
   348 	StringInfo emptystring;
   349 
   350 	states.line = 1;
   351 	states.col = 0;
   352 
   353 	smc->ReadSMC_ParseStart();
   354 
   355 	/**
   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.
   360 	 *
   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.
   363 	 */
   364 	while (srdr(stream, parse_point, sizeof(in_buf) - (parse_point - in_buf) - 1, &read))
   365 	{
   366 		if (!read)
   367 		{
   368 			break;
   369 		}
   370 
   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.
   373 		 */
   374 		if (states.line == 1 && 
   375 			in_buf[0] == (char)0xEF && 
   376 			in_buf[1] == (char)0xBB && 
   377 			in_buf[2] == (char)0xBF)
   378 		{
   379 			/* Move EVERYTHING down :\ */
   380 			memmove(in_buf, &in_buf[3], read - 3);
   381 			read -= 3;
   382 		}
   383 
   384 		if (reparse_point)
   385 		{
   386 			read += (parse_point - reparse_point);
   387 			parse_point = reparse_point;
   388 			reparse_point = NULL;
   389 		}
   390 
   391 		for (i=0; i<read; i++)
   392 		{
   393 			c = parse_point[i];
   394 			if (c == '\n')
   395 			{
   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.
   398 				 */
   399 				if (strings[0].ptr)
   400 				{
   401 					strings[0].end = &parse_point[i];
   402 					if (rotate(strings) != NULL)
   403 					{
   404 						err = SMCError_InvalidTokens;
   405 						goto failed;
   406 					}
   407 				}
   408 
   409 				/* Next, let's clear some line-based values that may no longer have meaning */
   410 				eol_comment = false;
   411 				in_quote = false;
   412 				if (ignoring && !ml_comment)
   413 				{
   414 					ignoring = false;
   415 				}
   416 
   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.
   419 				 */
   420 				parse_point[i] = '\0';
   421 				if ((res=smc->ReadSMC_RawLine(&states, line_begin)) != SMCResult_Continue)
   422 				{
   423 					err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
   424 					goto failed;
   425 				}
   426 				parse_point[i] = '\n';
   427 
   428 				/* Now we check the sanity of our staged strings! */
   429 				if (strings[2].ptr)
   430 				{
   431 					if (!curlevel)
   432 					{
   433 						err = SMCError_InvalidProperty1;
   434 						goto failed;
   435 					}
   436 					/* Assume the next string is a property and pass the info on. */
   437 					if ((res=smc->ReadSMC_KeyValue(
   438 						&states,
   439 						FixupString(strings[2]),
   440 						FixupString(strings[1]))) != SMCResult_Continue)
   441 					{
   442 						err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
   443 						goto failed;
   444 					}
   445 					scrap(strings);
   446 				}
   447 
   448 				/* Change the states for the next line */
   449 				states.col = 0;
   450 				states.line++;
   451 				line_begin = &parse_point[i+1];		//Note: safe because this gets relocated later
   452 			} 
   453 			else if (ignoring) 
   454 			{
   455 				if (in_quote)
   456 				{
   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] != '\\')
   459 					{
   460 						/* If we reached a quote in an ignore phase,
   461 						 * we're staging a string and we must rotate it out.
   462 						 */
   463 						in_quote = false;
   464 						ignoring = false;
   465 						/* Set our info */
   466 						strings[0].end = &parse_point[i];
   467 						strings[0].quoted = true;
   468 						if (rotate(strings) != NULL)
   469 						{
   470 							/* If we rotated too many strings, there was too much crap on one line */
   471 							err = SMCError_InvalidTokens;
   472 							goto failed;
   473 						}
   474 					} 
   475 					else if (c == '\\') 
   476 					{
   477 						strings[0].special = true;
   478 						if (i == (read - 1))
   479 						{
   480 							reparse_point = &parse_point[i];
   481 							break;
   482 						}
   483 					}
   484 				} 
   485 				else if (ml_comment) 
   486 				{
   487 					if (c == '*')
   488 					{
   489 						/* Check if we need to get more input first */
   490 						if (i == read - 1)
   491 						{
   492 							reparse_point = &parse_point[i];
   493 							break;
   494 						}
   495 						if (parse_point[i+1] == '/')
   496 						{
   497 							ml_comment = false;
   498 							ignoring = false;
   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 */
   502 							i++;
   503 							states.col++;
   504 						}
   505 					}
   506 				}
   507 			} 
   508 			else 
   509 			{
   510 				/* Check if we're whitespace or not */
   511 				if (!g_ws_chartable[(unsigned)c])
   512 				{
   513 					bool restage = false;
   514 					/* Check various special tokens:
   515 					 * ;
   516 					 * //
   517 					 * / *
   518 					 * {
   519 					 * }
   520 					 */
   521 					if (c == ';' || c == '/')
   522 					{
   523 						/* If it's a line-based comment (that is, ; or //)
   524 						 * we will need to scrap everything until the end of the line.
   525 						 */
   526 						if (c == '/')
   527 						{
   528 							if (i == read - 1)
   529 							{
   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!
   532 								 */
   533 								reparse_point = &parse_point[i];
   534 								break;
   535 							}
   536 							if (parse_point[i + 1] == '/')
   537 							{
   538 								/* standard comment */
   539 								ignoring = true;
   540 								eol_comment = true;
   541 								restage = true;
   542 							} 
   543 							else if (parse_point[i+1] == '*') 
   544 							{
   545 								/* inline comment - start ignoring */
   546 								ignoring = true;
   547 								ml_comment = true;
   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.
   552 								 */
   553 								restage = true;
   554 							}
   555 						} 
   556 						else 
   557 						{
   558 							ignoring = true;
   559 							eol_comment = true;
   560 							restage = true;
   561 						}
   562 					} 
   563 					else if (c == '{') 
   564 					{
   565 						/* If we are staging a string, we must rotate here */
   566 						if (strings[0].ptr)
   567 						{
   568 							/* We have unacceptable tokens on this line */
   569 							if (rotate(strings) != NULL)
   570 							{
   571 								err = SMCError_InvalidSection1;
   572 								goto failed;
   573 							}
   574 						}
   575 						/* Sections must always be alone */
   576 						if (strings[2].ptr != NULL)
   577 						{
   578 							err = SMCError_InvalidSection1;
   579 							goto failed;
   580 						} 
   581 						else if (strings[1].ptr == NULL)
   582 						{
   583 							err = SMCError_InvalidSection2;
   584 							goto failed;
   585 						}
   586 						if ((res=smc->ReadSMC_NewSection(&states, FixupString(strings[1])))
   587 							!= SMCResult_Continue)
   588 						{
   589 							err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
   590 							goto failed;
   591 						}
   592 						strings[1] = emptystring;
   593 						curlevel++;
   594 					} 
   595 					else if (c == '}') 
   596 					{
   597 						/* Unlike our matching friend, this can be on the same line as something prior */
   598 						if (rotate(strings) != NULL)
   599 						{
   600 							err = SMCError_InvalidSection3;
   601 							goto failed;
   602 						}
   603 						if (strings[2].ptr)
   604 						{
   605 							if (!curlevel)
   606 							{
   607 								err = SMCError_InvalidProperty1;
   608 								goto failed;
   609 							}
   610 							if ((res=smc->ReadSMC_KeyValue(
   611 											&states,
   612 											FixupString(strings[2]),
   613 											FixupString(strings[1])))
   614 								!= SMCResult_Continue)
   615 							{
   616 								err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
   617 								goto failed;
   618 							}
   619 						} 
   620 						else if (strings[1].ptr) 
   621 						{
   622 							err = SMCError_InvalidSection3;
   623 							goto failed;
   624 						} 
   625 						else if (!curlevel) 
   626 						{
   627 							err = SMCError_InvalidSection4;
   628 							goto failed;
   629 						}
   630 						/* Now it's safe to leave the section */
   631 						scrap(strings);
   632 						if ((res=smc->ReadSMC_LeavingSection(&states)) != SMCResult_Continue)
   633 						{
   634 							err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay;
   635 							goto failed;
   636 						}
   637 						curlevel--;
   638 					} 
   639 					else if (c == '"') 
   640 					{
   641 						/* If we get a quote mark, we always restage, but we need to do it beforehand */
   642 						if (strings[0].ptr)
   643 						{
   644 							strings[0].end = &parse_point[i];
   645 							if (rotate(strings) != NULL)
   646 							{
   647 								err = SMCError_InvalidTokens;
   648 								goto failed;
   649 							}
   650 						}
   651 						strings[0].ptr = &parse_point[i];
   652 						in_quote = true;
   653 						ignoring = true;
   654 					} 
   655 					else if (!strings[0].ptr) 
   656 					{
   657 						/* If we have no string, we must start one */
   658 						strings[0].ptr = &parse_point[i];
   659 					}
   660 					if (restage && strings[0].ptr)
   661 					{
   662 						strings[0].end = &parse_point[i];
   663 						if (rotate(strings) != NULL)
   664 						{
   665 							err = SMCError_InvalidTokens;
   666 							goto failed;
   667 						}
   668 					}
   669 				} 
   670 				else 
   671 				{
   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)
   674 					 */
   675 					if (strings[0].ptr)
   676 					{
   677 						/*
   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.
   681 						 */
   682 						if (!strings[1].ptr)
   683 						{
   684 							/* There's no string, so we must move this one down and eat up another */
   685 							strings[0].end = &parse_point[i];
   686 							rotate(strings);
   687 						} 
   688 						else if (!strings[1].quoted) 
   689 						{
   690 							err = SMCError_InvalidTokens;
   691 							goto failed;
   692 						}
   693 					}
   694 				}
   695 			}
   696 
   697 			/* Advance which token we're on */
   698 			states.col++;
   699 		}
   700 
   701 		if (line_begin != in_buf)
   702 		{
   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.
   705 			 */
   706 			char *stage = lowstring(strings);
   707 			if (!stage || stage > line_begin)
   708 			{
   709 				stage = line_begin;
   710 			}
   711 			unsigned int bytes = read - (stage - parse_point);
   712 
   713 			/* It is now safe to delete everything before the staged point */
   714 			memmove(in_buf, stage, bytes);
   715 
   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 */
   719 			line_begin -= bytes;
   720 			reloc(strings[0], bytes);
   721 			reloc(strings[1], bytes);
   722 			reloc(strings[2], bytes);
   723 			if (reparse_point)
   724 			{
   725 				reparse_point -= bytes;
   726 			}
   727 			if (parse_point)
   728 			{
   729 				parse_point = &parse_point[read];
   730 				parse_point -= bytes;
   731 			}
   732 		} 
   733 		else if (read == sizeof(in_buf) - 1) 
   734 		{
   735 			err = SMCError_TokenOverflow;
   736 			goto failed;
   737 		}
   738 	}
   739 
   740 	/* If we're done parsing and there are tokens left over... */
   741 	if (curlevel)
   742 	{
   743 		err = SMCError_InvalidSection5;
   744 		goto failed;
   745 	} 
   746 	else if (strings[0].ptr || strings[1].ptr) 
   747 	{
   748 		err = SMCError_InvalidTokens;
   749 		goto failed;
   750 	}
   751 	
   752 	smc->ReadSMC_ParseEnd(false, false);
   753 	
   754 	if (pStates != NULL)
   755 	{
   756 		*pStates = states;
   757 	}
   758 
   759 	return SMCError_Okay;
   760 
   761 failed:
   762 	if (pStates != NULL)
   763 	{
   764 		*pStates = states;
   765 	}
   766 
   767 	smc->ReadSMC_ParseEnd(true, (err == SMCError_Custom));
   768 
   769 	return err;
   770 }
   771 
   772 
   773 /**
   774  * INI parser 
   775  */
   776 
   777 bool TextParsers::ParseFile_INI(const char *file, ITextListener_INI *ini_listener, unsigned int *line, unsigned int *col)
   778 {
   779 	FILE *fp = fopen(file, "rt");
   780 	unsigned int curline = 0;
   781 	unsigned int curtok;
   782 	size_t len;
   783 
   784 	if (!fp)
   785 	{
   786 		if (line)
   787 		{
   788 			*line = 0;
   789 		}
   790 
   791 		return false;
   792 	}
   793 
   794 	char buffer[2048];
   795 	char *ptr, *save_ptr;
   796 	bool in_quote;
   797 
   798 	while (!feof(fp))
   799 	{
   800 		curline++;
   801 		curtok = 0;
   802 		buffer[0] = '\0';
   803 		if (fgets(buffer, sizeof(buffer), fp) == NULL)
   804 		{
   805 			break;
   806 		}
   807 
   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 */
   810 		if (curline == 1 && 
   811 			buffer[0] == (char)0xEF && 
   812 			buffer[1] == (char)0xBB && 
   813 			buffer[2] == (char)0xBF)
   814 		{
   815 			/* We have a UTF-8 marked file... skip these bytes */
   816 			ptr = &buffer[3];
   817 		} else {
   818 			ptr = buffer;
   819 		}
   820 
   821 		/***************************************************
   822 		 * We preprocess the string before parsing tokens! *
   823 		 ***************************************************/
   824 
   825 		/* First strip beginning whitespace */
   826 		while (*ptr != '\0' && g_ws_chartable[(unsigned)*ptr] != 0)
   827 		{
   828 			ptr++;
   829 		}
   830 
   831 		len = strlen(ptr);
   832 
   833 		if (!len)
   834 		{
   835 			continue;
   836 		}
   837 
   838 		/* Now search for comment characters */
   839 		in_quote = false;
   840 		save_ptr = ptr;
   841 		for (size_t i=0; i<len; i++,ptr++)
   842 		{
   843 			if (!in_quote)
   844 			{
   845 				switch (*ptr)
   846 				{
   847 				case '"':
   848 					{
   849 						in_quote = true;
   850 						break;
   851 					}
   852 				case ';':
   853 					{
   854 						/* Stop the loop */
   855 						len = i;
   856 						/* Terminate the string here */
   857 						*ptr = '\0';
   858 						break;
   859 					}
   860 				}
   861 			} else {
   862 				if (*ptr == '"')
   863 				{
   864 					in_quote = false;
   865 				}
   866 			}
   867 		}
   868 
   869 		if (!len)
   870 		{
   871 			continue;
   872 		}
   873 
   874 		ptr = save_ptr;
   875 
   876 		/* Lastly, strip ending whitespace off */
   877 		for (size_t i=len-1; i>=0 && i<len; i--)
   878 		{
   879 			if (g_ws_chartable[(unsigned)ptr[i]])
   880 			{
   881 				ptr[i] = '\0';
   882 				len--;
   883 			} else {
   884 				break;
   885 			}
   886 		}
   887 
   888 		if (!len)
   889 		{
   890 			continue;
   891 		}
   892 
   893 		if (!ini_listener->ReadINI_RawLine(ptr, &curtok))
   894 		{
   895 			goto event_failed;
   896 		}
   897 
   898 		if (*ptr == '[')
   899 		{
   900 			bool invalid_tokens = false;
   901 			bool got_bracket = false;
   902 			bool extra_tokens = false;
   903 			char c;
   904 			bool alnum;
   905 			wchar_t wc;
   906 
   907 			for (size_t i=1; i<len; i++)
   908 			{
   909 				c = ptr[i];
   910 				alnum = false;
   911 
   912 				if (c & (1<<7))
   913 				{
   914 					if (mbtowc(&wc, &ptr[i], len-i) != -1)
   915 					{
   916 						alnum = (iswalnum(wc) != 0);
   917 						i += _GetUTF8CharBytes(&ptr[i]) - 1;
   918 					}
   919 				} else {
   920 					alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
   921 				}
   922 				if (!alnum)
   923 				{
   924 					/* First check - is this a bracket? */
   925 					if (c == ']')
   926 					{
   927 						/* Yes! */
   928 						got_bracket = true;
   929 						/* If this isn't the last character... */
   930 						if (i != len - 1)
   931 						{
   932 							extra_tokens = true;
   933 						}
   934 						/* terminate */
   935 						ptr[i] = '\0';
   936 						break;
   937 					} else {
   938 						/* n...No! Continue copying. */
   939 						invalid_tokens = true;
   940 					}
   941 				}
   942 			}
   943 
   944 			/* Tell the handler */
   945 			if (!ini_listener->ReadINI_NewSection(&ptr[1], invalid_tokens, got_bracket, extra_tokens, &curtok))
   946 			{
   947 				goto event_failed;
   948 			}
   949 		} else {
   950 			char *key_ptr = ptr;
   951 			char *val_ptr = NULL;
   952 			char c;
   953 			size_t first_space = 0;
   954 			bool invalid_tokens = false;
   955 			bool equal_token = false;
   956 			bool quotes = false;
   957 			bool alnum;
   958 			wchar_t wc;
   959 
   960 			for (size_t i=0; i<len; i++)
   961 			{
   962 				c = ptr[i];
   963 				alnum = false;
   964 				/* is this an invalid char? */
   965 				if (c & (1<<7))
   966 				{
   967 					if (mbtowc(&wc, &ptr[i], len-i) != -1)
   968 					{
   969 						alnum = (iswalnum(wc) != 0);
   970 						i += _GetUTF8CharBytes(&ptr[i]) - 1;
   971 					}
   972 				} else {
   973 					alnum = (isalnum(c) != 0) || (g_ini_chartable1[(unsigned)c] != 0);
   974 				}
   975 
   976 				if (!alnum)
   977 				{
   978 					if (g_ws_chartable[(unsigned)c])
   979 					{
   980 						/* if it's a space, keep track of the first occurring space */
   981 						if (!first_space)
   982 						{
   983 							first_space = i;
   984 						}
   985 					} else {
   986 						if (c == '=')
   987 						{
   988 							/* if it's an equal sign, we're done with the key */
   989 							if (first_space)
   990 							{
   991 								/* remove excess whitespace */
   992 								key_ptr[first_space] = '\0';
   993 							} else {
   994 								/* remove the equal sign */
   995 								key_ptr[i] = '\0';
   996 							}
   997 							if (ptr[++i] != '\0')
   998 							{
   999 								/* If this isn't the end, set next pointer */
  1000 								val_ptr = &ptr[i];
  1001 							}
  1002 							equal_token = true;
  1003 							break;
  1004 						} else {
  1005 							/* Mark that we got something invalid! */
  1006 							invalid_tokens = true;
  1007 							first_space = 0;
  1008 						}
  1009 					}
  1010 				}
  1011 			}
  1012 
  1013 			/* Now we need to parse the value, if any */
  1014 			if (val_ptr)
  1015 			{
  1016 				/* eat up spaces! there shouldn't be any h*/
  1017 				while ((*val_ptr != '\0') && g_ws_chartable[(unsigned)*val_ptr] != 0)
  1018 				{
  1019 					val_ptr++;
  1020 				}
  1021 				if (*val_ptr == '\0')
  1022 				{
  1023 					val_ptr = NULL;
  1024 					goto skip_value;
  1025 				}
  1026 				/* Do we have an initial quote? If so, the parsing rules change! */
  1027 				if (*val_ptr == '"' && *val_ptr != '\0')
  1028 				{
  1029 					len = strlen(val_ptr);
  1030 					if (val_ptr[len-1] == '"')
  1031 					{
  1032 						/* Strip quotes! */
  1033 						val_ptr[--len] = '\0';
  1034 						val_ptr++;
  1035 						quotes = true;
  1036 					}
  1037 				}
  1038 			}
  1039 skip_value:
  1040 			/* We're done! */
  1041 			curtok = val_ptr - buffer;
  1042 			if (!ini_listener->ReadINI_KeyValue(key_ptr, val_ptr, invalid_tokens, equal_token, quotes, &curtok))
  1043 			{
  1044 				curtok = 0;
  1045 				goto event_failed;
  1046 			}
  1047 		}
  1048 	}
  1049 
  1050 	if (line)
  1051 	{
  1052 		*line = curline;
  1053 	}
  1054 
  1055 	fclose(fp);
  1056 
  1057 	return true;
  1058 
  1059 event_failed:
  1060 	if (line)
  1061 	{
  1062 		*line = curline;
  1063 	}
  1064 
  1065 	if (col)
  1066 	{
  1067 		*col = curtok;
  1068 	}
  1069 
  1070 	fclose(fp);
  1071 
  1072 	return false;
  1073 }
  1074 
  1075 const char *TextParsers::GetSMCErrorString(SMCError err)
  1076 {
  1077 	static const char *s_errors[] = 
  1078 	{
  1079 		NULL,
  1080 		"Stream failed to open",
  1081 		"Stream returned read error",
  1082 		NULL,
  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",
  1091 	};
  1092 
  1093 	if (err < SMCError_Okay || err > SMCError_InvalidProperty1)
  1094 	{
  1095 		return NULL;
  1096 	}
  1097 
  1098 	return s_errors[err];
  1099 }