<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "ssvm_pre.h"
#include "sslang_vm.h"
#include "ssvm.h"

extern Script g_Script;

int LoadScript(char* filename)
{
	FILE* pScriptFile = fopen(filename, "rb");
	if (pScriptFile == NULL)
		return LOAD_ERROR_FAIL_FILE_OPEN;

	char* magicNumStr = (char*) malloc(5);
	fread(magicNumStr, 4, 1, pScriptFile);
	magicNumStr[strlen(SSE_ID_STRING)] = '\0';

	if (strcmp(magicNumStr, SSE_ID_STRING) != 0)
		return LOAD_ERROR_INVALID_SSE;

	free(magicNumStr);

	int majorVersion = 0;
	int minorVersion = 0;

	fread(&majorVersion, 1, 1, pScriptFile);
	fread(&minorVersion, 1, 1, pScriptFile);

	if (majorVersion != VERSION_MAJOR || minorVersion != VERSION_MINOR)
		return LOAD_ERROR_UNSOPPORTED_VERSION;

	fread(&g_Script.stack.iSize, 4, 1, pScriptFile);
	if (g_Script.stack.iSize == 0)
		g_Script.stack.iSize = DEFAULT_STACK_SIZE;

	g_Script.stack.pElement = (Value*) malloc(g_Script.stack.iSize * sizeof(Value));

	fread(&g_Script.iGlobalDataSize, 4, 1, pScriptFile);
	fread(&g_Script.iIsMainFuncExist, 1, 1, pScriptFile);
	fread(&g_Script.iMainFuncIndex, 4, 1, pScriptFile);

	fread(&g_Script.instrStream.iSize, 4, 1, pScriptFile);
	g_Script.instrStream.pInstr = (Instr*) malloc(g_Script.instrStream.iSize * sizeof(Instr));

	for (int i = 0; i < g_Script.instrStream.iSize; i++)
	{
		g_Script.instrStream.pInstr[i].iOpcode  = 0;
		fread(&g_Script.instrStream.pInstr[i].iOpcode,  2, 1, pScriptFile);
		g_Script.instrStream.pInstr[i].iOpCount = 0;
		fread(&g_Script.instrStream.pInstr[i].iOpCount, 1, 1, pScriptFile);

		int opCount = g_Script.instrStream.pInstr[i].iOpCount;

		Value* pOplist = (Value*) malloc(opCount * sizeof(Value));

		for (int j = 0; j < opCount; j++)
		{
			pOplist[j].iType = 0;
			fread(&pOplist[j].iType, 1, 1, pScriptFile);

			switch (pOplist[j].iType)
			{
			case OP_TYPE_INT:
				fread(&pOplist[j].iIntLiteral, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_FLOAT:
				fread(&pOplist[j].fFloatLiteral, sizeof(float), 1, pScriptFile);
				break;
			case OP_TYPE_STRING_INDEX:
				fread(&pOplist[j].iIntLiteral, sizeof(int), 1, pScriptFile);
				pOplist[j].iType = OP_TYPE_STRING_INDEX;
				break;
			case OP_TYPE_INSTR_INDEX:
				fread(&pOplist[j].iInstrIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_ABS_STACK_INDEX:
				fread(&pOplist[j].iStackIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_REL_STACK_INDEX:
				fread(&pOplist[j].iStackIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_FUNC_INDEX:
				fread(&pOplist[j].iOffsetIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_HOST_API_CALL_INDEX:
				fread(&pOplist[j].iHostAPICallIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_REG:
				fread(&pOplist[j].iReg, sizeof(int), 1, pScriptFile);
				break;
			default:
				break;
			}
		}

		g_Script.instrStream.pInstr[i].pOplist = pOplist;
	}

	int stringTableSize;
	fread(&stringTableSize, 4, 1, pScriptFile);
	if (stringTableSize)
	{
		char** ppStringTable = (char**) malloc(stringTableSize * sizeof(char*));
		for (int i = 0; i < stringTableSize; i++)
		{
			int stringLen = 0;
			fread(&stringLen, sizeof(int), 1, pScriptFile);

			char* pString = (char*) malloc((stringLen + 1) * sizeof(char));
			fread(pString, stringLen, 1, pScriptFile);
			pString[stringLen] = '\0';

			ppStringTable[i] = pString;
		}

		for (int i = 0; i < g_Script.instrStream.iSize; i++)
		{
			int opCount = g_Script.instrStream.pInstr[i].iOpCount;
			Value* opList = g_Script.instrStream.pInstr[i].pOplist;
			for (int j = 0; j < opCount; j++)
			{
				if (opList[j].iType == OP_TYPE_STRING_INDEX)
				{
					int stringIndex = opList[j].iIntLiteral;
					char* temp = (char*) malloc(strlen(ppStringTable[stringIndex] + 1));
					strcpy(temp, ppStringTable[stringIndex]);

					opList[j].strStringLiteral = temp;
				}
			}
		}

		for (int i = 0; i < stringTableSize; i++)
			free(ppStringTable[i]);
		free(ppStringTable);
	}

	int functionTableSize;
	fread(&functionTableSize, 4, 1, pScriptFile);
	g_Script.pFuncTable = (Func*) malloc(functionTableSize * sizeof(Func));
	for (int i = 0; i < functionTableSize; i++)
	{
		int entryPoint;
		fread(&entryPoint, 4, 1, pScriptFile);

		int paramCount = 0;
		fread(&paramCount, 1, 1, pScriptFile);

		int localDataSize;
		fread(&localDataSize, 4, 1, pScriptFile);

		int stackFrameSize = paramCount + 1 + localDataSize;

		g_Script.pFuncTable[i].iEntryPoint     = entryPoint;
		g_Script.pFuncTable[i].iParamCount     = paramCount;
		g_Script.pFuncTable[i].iLocalDataSize  = localDataSize;
		g_Script.pFuncTable[i].iStackFrameSize = stackFrameSize;
	}

	fread(&g_Script.hostAPICallTable.iSize, 4, 1, pScriptFile);
	g_Script.hostAPICallTable.ppStrCalls = (char**) malloc(g_Script.hostAPICallTable.iSize * sizeof(char*));
	for (int i = 0; i < g_Script.hostAPICallTable.iSize; i++)
	{
		int callLength = 0;
		fread(&callLength, 1, 1, pScriptFile);

		char* pAPICall = (char*) malloc(callLength + 1);
		fread(pAPICall, callLength, 1, pScriptFile);
		pAPICall[callLength] = '\0';

		g_Script.hostAPICallTable.ppStrCalls[i] = pAPICall;
	}

	fclose(pScriptFile);

	return LOAD_OK;
}

void ResetScript()
{

}

void RunScript()
{
	int isExitExeLoop = FALSE;
	while (TRUE)
	{
		if (g_Script.iIsPaused)
		{
			/*if (GetCurrentTime() >= g_Script.iPauseEndTime)
			g_Script.iIsPaused = FALSE;
			else
			continue;*/
		}

		int currentInstr = g_Script.instrStream.iCurrentInstr;
		int opCode = g_Script.instrStream.pInstr[currentInstr].iOpcode;

		printf("\t");
		if (opCode < 10)
			printf(" %d", opCode);
		else
			printf("%d", opCode);
		printf(" %s", "dd");

		switch (opCode)
		{
		case INSTR_MOV:

		case INSTR_ADD:
		case INSTR_SUB:
		case INSTR_MUL:
		case INSTR_DIV:
		case INSTR_MOD:
		case INSTR_EXP:

		case INSTR_AND:
		case INSTR_OR:
		case INSTR_XOR:
		case INSTR_SHL:
		case INSTR_SHR:
			{
				Value dest = GetOpValue(0);
				Value source = GetOpValue(1);

				switch (opCode)
				{
				case INSTR_MOV:
					if (GetOpValuePointer(0) == GetOpValuePointer(1))
						break;

					CopyValue(&dest, source);
					break;

				case INSTR_ADD:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral += GetOpValueAsInt(1);
					else
						dest.fFloatLiteral += GetOpValueAsFloat(1);
					break;

				case INSTR_SUB:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral -= GetOpValueAsInt(1);
					else
						dest.fFloatLiteral -= GetOpValueAsFloat(1);
					break;
				case INSTR_MUL:
				case INSTR_DIV:
				case INSTR_MOD:
				case INSTR_EXP:

				case INSTR_AND:
				case INSTR_OR:
				case INSTR_XOR:
				case INSTR_SHL:
				case INSTR_SHR:
				default:
					break;
				}
			}

		default:
			break;
		}

		printf("\n");

		if (currentInstr == g_Script.instrStream.iCurrentInstr)
			g_Script.instrStream.iCurrentInstr++;

		if (isExitExeLoop)
			break;
	}

}

void CopyValue(Value* dest, Value value)
{
	*dest = value;
}

int ValueToInt(Value value)
{
	switch (value.iType)
	{
	case OP_TYPE_INT:
		return value.iIntLiteral;
	case OP_TYPE_FLOAT:
		return (int)value.fFloatLiteral;
	case OP_TYPE_STRING_INDEX:
		return atoi(value.strStringLiteral);
	default:
		return 0;
	}
}

float ValueToFloat(Value value)
{
	switch (value.iType)
	{
	case OP_TYPE_INT:
		return (float) value.iIntLiteral;
	case OP_TYPE_FLOAT:
		return value.fFloatLiteral;
	case OP_TYPE_STRING_INDEX:
		return atof(value.strStringLiteral);
	default:
		return 0;
	}
}

char* ValueToString(Value value)
{
	char* str = NULL;
	if (value.iType != OP_TYPE_STRING_INDEX)
		str = (char*) malloc(MAX_VALUE_STRING_SIZE + 1);

	switch (value.iType)
	{
	case OP_TYPE_INT:
		_itoa(value.iIntLiteral, str, 10);
		return str;
	case OP_TYPE_FLOAT:
		sprintf(str, "%f", value.fFloatLiteral);
		return str;
	case OP_TYPE_STRING_INDEX:
		return value.strStringLiteral;
	default:
		return NULL;
	}
}

Value GetStackValue(int index)
{
	return g_Script.stack.pElement[GET_STACK_INDEX(index)];
}

int GetOpType(int opIndex);
Value GetOpValue(int opIndex)
{
	int currentInstr = g_Script.instrStream.iCurrentInstr;
	Value opValue = g_Script.instrStream.pInstr[currentInstr].pOplist[opIndex];

	switch (opValue.iType)
	{

	}
	return opValue;
}
Value* GetOpValuePointer(int opIndex)
{
	return NULL;
}
int GetOpValueAsInt(int opIndex)
{
	return 0;
}
float GetOpValueAsFloat(int opIndex)
{
	return 0;
}
char* GetOpValueAsString(int opIndex)
{
	return 0;
}
int GetOpValueAsStackIndex(int opIndex)
{
	int currentInstr = g_Script.instrStream.iCurrentInstr;
	Value opValue = g_Script.instrStream.pInstr[currentInstr].pOplist[opIndex];

	switch (opValue.iType)
	{
	case OP_TYPE_ABS_STACK_INDEX:
		return opValue.iStackIndex;
	case OP_TYPE_REL_STACK_INDEX:
		break;

	}
	return 0;
}
int GetOpValueAsInstrIndex(int opIndex)
{
	return 0;
}
int GetOpValueAsFuncIndex(int opIndex)
{
	return 0;
}
char* GetOpValueASHostAPI(int opIndex)
{
	return NULL;
}<commit_msg>instr resolve<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "ssvm_pre.h"
#include "sslang_vm.h"
#include "ssvm.h"

extern Script g_Script;

int LoadScript(char* filename)
{
	FILE* pScriptFile = fopen(filename, "rb");
	if (pScriptFile == NULL)
		return LOAD_ERROR_FAIL_FILE_OPEN;

	char* magicNumStr = (char*) malloc(5);
	fread(magicNumStr, 4, 1, pScriptFile);
	magicNumStr[strlen(SSE_ID_STRING)] = '\0';

	if (strcmp(magicNumStr, SSE_ID_STRING) != 0)
		return LOAD_ERROR_INVALID_SSE;

	free(magicNumStr);

	int majorVersion = 0;
	int minorVersion = 0;

	fread(&majorVersion, 1, 1, pScriptFile);
	fread(&minorVersion, 1, 1, pScriptFile);

	if (majorVersion != VERSION_MAJOR || minorVersion != VERSION_MINOR)
		return LOAD_ERROR_UNSOPPORTED_VERSION;

	fread(&g_Script.stack.iSize, 4, 1, pScriptFile);
	if (g_Script.stack.iSize == 0)
		g_Script.stack.iSize = DEFAULT_STACK_SIZE;

	g_Script.stack.pElement = (Value*) malloc(g_Script.stack.iSize * sizeof(Value));

	fread(&g_Script.iGlobalDataSize, 4, 1, pScriptFile);
	fread(&g_Script.iIsMainFuncExist, 1, 1, pScriptFile);
	fread(&g_Script.iMainFuncIndex, 4, 1, pScriptFile);

	fread(&g_Script.instrStream.iSize, 4, 1, pScriptFile);
	g_Script.instrStream.pInstr = (Instr*) malloc(g_Script.instrStream.iSize * sizeof(Instr));

	for (int i = 0; i < g_Script.instrStream.iSize; i++)
	{
		g_Script.instrStream.pInstr[i].iOpcode  = 0;
		fread(&g_Script.instrStream.pInstr[i].iOpcode,  2, 1, pScriptFile);
		g_Script.instrStream.pInstr[i].iOpCount = 0;
		fread(&g_Script.instrStream.pInstr[i].iOpCount, 1, 1, pScriptFile);

		int opCount = g_Script.instrStream.pInstr[i].iOpCount;

		Value* pOplist = (Value*) malloc(opCount * sizeof(Value));

		for (int j = 0; j < opCount; j++)
		{
			pOplist[j].iType = 0;
			fread(&pOplist[j].iType, 1, 1, pScriptFile);

			switch (pOplist[j].iType)
			{
			case OP_TYPE_INT:
				fread(&pOplist[j].iIntLiteral, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_FLOAT:
				fread(&pOplist[j].fFloatLiteral, sizeof(float), 1, pScriptFile);
				break;
			case OP_TYPE_STRING_INDEX:
				fread(&pOplist[j].iIntLiteral, sizeof(int), 1, pScriptFile);
				pOplist[j].iType = OP_TYPE_STRING_INDEX;
				break;
			case OP_TYPE_INSTR_INDEX:
				fread(&pOplist[j].iInstrIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_ABS_STACK_INDEX:
				fread(&pOplist[j].iStackIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_REL_STACK_INDEX:
				fread(&pOplist[j].iStackIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_FUNC_INDEX:
				fread(&pOplist[j].iOffsetIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_HOST_API_CALL_INDEX:
				fread(&pOplist[j].iHostAPICallIndex, sizeof(int), 1, pScriptFile);
				break;
			case OP_TYPE_REG:
				fread(&pOplist[j].iReg, sizeof(int), 1, pScriptFile);
				break;
			default:
				break;
			}
		}

		g_Script.instrStream.pInstr[i].pOplist = pOplist;
	}

	int stringTableSize;
	fread(&stringTableSize, 4, 1, pScriptFile);
	if (stringTableSize)
	{
		char** ppStringTable = (char**) malloc(stringTableSize * sizeof(char*));
		for (int i = 0; i < stringTableSize; i++)
		{
			int stringLen = 0;
			fread(&stringLen, sizeof(int), 1, pScriptFile);

			char* pString = (char*) malloc((stringLen + 1) * sizeof(char));
			fread(pString, stringLen, 1, pScriptFile);
			pString[stringLen] = '\0';

			ppStringTable[i] = pString;
		}

		for (int i = 0; i < g_Script.instrStream.iSize; i++)
		{
			int opCount = g_Script.instrStream.pInstr[i].iOpCount;
			Value* opList = g_Script.instrStream.pInstr[i].pOplist;
			for (int j = 0; j < opCount; j++)
			{
				if (opList[j].iType == OP_TYPE_STRING_INDEX)
				{
					int stringIndex = opList[j].iIntLiteral;
					char* temp = (char*) malloc(strlen(ppStringTable[stringIndex] + 1));
					strcpy(temp, ppStringTable[stringIndex]);

					opList[j].strStringLiteral = temp;
				}
			}
		}

		for (int i = 0; i < stringTableSize; i++)
			free(ppStringTable[i]);
		free(ppStringTable);
	}

	int functionTableSize;
	fread(&functionTableSize, 4, 1, pScriptFile);
	g_Script.pFuncTable = (Func*) malloc(functionTableSize * sizeof(Func));
	for (int i = 0; i < functionTableSize; i++)
	{
		int entryPoint;
		fread(&entryPoint, 4, 1, pScriptFile);

		int paramCount = 0;
		fread(&paramCount, 1, 1, pScriptFile);

		int localDataSize;
		fread(&localDataSize, 4, 1, pScriptFile);

		int stackFrameSize = paramCount + 1 + localDataSize;

		g_Script.pFuncTable[i].iEntryPoint     = entryPoint;
		g_Script.pFuncTable[i].iParamCount     = paramCount;
		g_Script.pFuncTable[i].iLocalDataSize  = localDataSize;
		g_Script.pFuncTable[i].iStackFrameSize = stackFrameSize;
	}

	fread(&g_Script.hostAPICallTable.iSize, 4, 1, pScriptFile);
	g_Script.hostAPICallTable.ppStrCalls = (char**) malloc(g_Script.hostAPICallTable.iSize * sizeof(char*));
	for (int i = 0; i < g_Script.hostAPICallTable.iSize; i++)
	{
		int callLength = 0;
		fread(&callLength, 1, 1, pScriptFile);

		char* pAPICall = (char*) malloc(callLength + 1);
		fread(pAPICall, callLength, 1, pScriptFile);
		pAPICall[callLength] = '\0';

		g_Script.hostAPICallTable.ppStrCalls[i] = pAPICall;
	}

	fclose(pScriptFile);

	return LOAD_OK;
}

void ResetScript()
{

}

void RunScript()
{
	int isExitExeLoop = FALSE;
	while (TRUE)
	{
		if (g_Script.iIsPaused)
		{
			/*if (GetCurrentTime() >= g_Script.iPauseEndTime)
			g_Script.iIsPaused = FALSE;
			else
			continue;*/
		}

		int currentInstr = g_Script.instrStream.iCurrentInstr;
		int opCode = g_Script.instrStream.pInstr[currentInstr].iOpcode;

		printf("\t");
		if (opCode < 10)
			printf(" %d", opCode);
		else
			printf("%d", opCode);
		printf(" %s", "dd");

		switch (opCode)
		{
		case INSTR_MOV:

		case INSTR_ADD:
		case INSTR_SUB:
		case INSTR_MUL:
		case INSTR_DIV:
		case INSTR_MOD:
		case INSTR_EXP:

		case INSTR_AND:
		case INSTR_OR:
		case INSTR_XOR:
		case INSTR_SHL:
		case INSTR_SHR:
			{
				Value dest = GetOpValue(0);
				Value source = GetOpValue(1);

				switch (opCode)
				{
				case INSTR_MOV:
					if (GetOpValuePointer(0) == GetOpValuePointer(1))
						break;

					CopyValue(&dest, source);
					break;
				case INSTR_ADD:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral += GetOpValueAsInt(1);
					else
						dest.fFloatLiteral += GetOpValueAsFloat(1);
					break;
				case INSTR_SUB:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral -= GetOpValueAsInt(1);
					else
						dest.fFloatLiteral -= GetOpValueAsFloat(1);
					break;
				case INSTR_MUL:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral *= GetOpValueAsInt(1);
					else
						dest.fFloatLiteral *= GetOpValueAsFloat(1);
					break;
				case INSTR_DIV:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral /= GetOpValueAsInt(1);
					else
						dest.fFloatLiteral /= GetOpValueAsFloat(1);
					break;
				case INSTR_MOD:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral %= GetOpValueAsInt(1);
					break;
				case INSTR_EXP:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral = (int) pow((float)dest.iIntLiteral, GetOpValueAsInt(1));
					else
						dest.fFloatLiteral = (float) pow((float)dest.iIntLiteral, GetOpValueAsFloat(1));
					break;

				case INSTR_AND:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral &= GetOpValueAsInt(1);
					break;
				case INSTR_OR:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral |= GetOpValueAsInt(1);
					break;
				case INSTR_XOR:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral ^= GetOpValueAsInt(1);
					break;
				case INSTR_SHL:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral <<= GetOpValueAsInt(1);
					break;
				case INSTR_SHR:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral >>= GetOpValueAsInt(1);
					break;
				default:
					break;
				}

				*GetOpValuePointer(0) = dest;
			}

		case INSTR_NEG:
		case INSTR_NOT:
		case INSTR_INC:
		case INSTR_DEC:
			{
				Value dest = GetOpValue(0);

				switch (opCode)
				{
				case INSTR_NEG:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral = -dest.iIntLiteral;
					else
						dest.fFloatLiteral = -dest.fFloatLiteral;
					break;
				case INSTR_NOT:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral = ~dest.iIntLiteral;
				case INSTR_INC:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral++;
					else
						dest.fFloatLiteral++;
					break;
				case INSTR_DEC:
					if (dest.iType == OP_TYPE_INT)
						dest.iIntLiteral--;
					else
						dest.fFloatLiteral--;
					break;
				default:
					break;
				}

				*GetOpValuePointer(0) = dest;
			}

		case INSTR_CONCAT:
			{
				Value dest = GetOpValue(0);

				if (dest.iType != OP_TYPE_STRING_INDEX)
					break;

				char* appendString = GetOpValueAsString(1);
				int newStringLength = strlen(dest.strStringLiteral) + strlen(appendString);
				char* newString = (char*) malloc(newStringLength + 1);

				strcpy(newString, dest.strStringLiteral);
				strcat(newString, appendString);

				//newString[newStringLength] = '\0';
				free(dest.strStringLiteral);
				dest.strStringLiteral = newString;

				*GetOpValuePointer(0) = dest;
				break;
			}

		case INSTR_GETCHAR:
			{

			}

		case INSTR_SETCHAR:
			{

			}

		case INSTR_JMP:
		case INSTR_JE:
		case INSTR_JNE:
		case INSTR_JG:
		case INSTR_JGE:
		case INSTR_JL:
		case INSTR_JLE:

		case INSTR_PUSH:
		case INSTR_POP:

		case INSTR_CALL:
		case INSTR_RET:
		case INSTR_CALLHOST:

		case INSTR_PAUSE:
		case INSTR_EXIT:

		default:
			break;
		}

		printf("\n");

		if (currentInstr == g_Script.instrStream.iCurrentInstr)
			g_Script.instrStream.iCurrentInstr++;

		if (isExitExeLoop)
			break;
	}

}

void CopyValue(Value* dest, Value value)
{
	*dest = value;
}

int ValueToInt(Value value)
{
	switch (value.iType)
	{
	case OP_TYPE_INT:
		return value.iIntLiteral;
	case OP_TYPE_FLOAT:
		return (int)value.fFloatLiteral;
	case OP_TYPE_STRING_INDEX:
		return atoi(value.strStringLiteral);
	default:
		return 0;
	}
}

float ValueToFloat(Value value)
{
	switch (value.iType)
	{
	case OP_TYPE_INT:
		return (float) value.iIntLiteral;
	case OP_TYPE_FLOAT:
		return value.fFloatLiteral;
	case OP_TYPE_STRING_INDEX:
		return atof(value.strStringLiteral);
	default:
		return 0;
	}
}

char* ValueToString(Value value)
{
	char* str = NULL;
	if (value.iType != OP_TYPE_STRING_INDEX)
		str = (char*) malloc(MAX_VALUE_STRING_SIZE + 1);

	switch (value.iType)
	{
	case OP_TYPE_INT:
		_itoa(value.iIntLiteral, str, 10);
		return str;
	case OP_TYPE_FLOAT:
		sprintf(str, "%f", value.fFloatLiteral);
		return str;
	case OP_TYPE_STRING_INDEX:
		return value.strStringLiteral;
	default:
		return NULL;
	}
}

Value GetStackValue(int index)
{
	return g_Script.stack.pElement[GET_STACK_INDEX(index)];
}

int GetOpType(int opIndex);
Value GetOpValue(int opIndex)
{
	int currentInstr = g_Script.instrStream.iCurrentInstr;
	Value opValue = g_Script.instrStream.pInstr[currentInstr].pOplist[opIndex];

	switch (opValue.iType)
	{

	}
	return opValue;
}
Value* GetOpValuePointer(int opIndex)
{
	return NULL;
}
int GetOpValueAsInt(int opIndex)
{
	return 0;
}
float GetOpValueAsFloat(int opIndex)
{
	return 0;
}
char* GetOpValueAsString(int opIndex)
{
	return 0;
}
int GetOpValueAsStackIndex(int opIndex)
{
	int currentInstr = g_Script.instrStream.iCurrentInstr;
	Value opValue = g_Script.instrStream.pInstr[currentInstr].pOplist[opIndex];

	switch (opValue.iType)
	{
	case OP_TYPE_ABS_STACK_INDEX:
		return opValue.iStackIndex;
	case OP_TYPE_REL_STACK_INDEX:
		break;

	}
	return 0;
}
int GetOpValueAsInstrIndex(int opIndex)
{
	return 0;
}
int GetOpValueAsFuncIndex(int opIndex)
{
	return 0;
}
char* GetOpValueASHostAPI(int opIndex)
{
	return NULL;
}<|endoftext|>


<commit_before>#ifndef PARTIAL_FP_LIST_HPP
#define PARTIAL_FP_LIST_HPP

#include <string>
#include <cstdio>
#include <ir/dup_det/integer_dyn_array.hpp>

NS_IZENELIB_IR_BEGIN

template<
  typename UNIT_TYPE = uint64_t,
  uint8_t  FP_LENGTH = 6,
  uint64_t CACHE_SIZE = 600
  >
class PartialFpList
{

public:
  typedef izenelib::am::IntegerDynArray<UNIT_TYPE> FpVector;

  typedef izenelib::am::IntegerDynArray<uint32_t> DocIDVector;

  typedef DocIDVector::size_t size_t;

private:

  enum CACHE_STATUS
    {
      ADD_DOCS, UNIFORM_ACCESS
    }
    ;

  std::string file_name_;
  size_t doc_num_;        //<! Total amount of documents.
  size_t in_mem_doc_num_; //!< Amount of documents in memory.
  size_t start_doc_i_;    //!< start index of document in memory.
  CACHE_STATUS cache_status_; //!< Cache status is adding docs and reading docs.

  const size_t ALL_INFO_IN_MEM_LENGTH;
  const uint8_t  UNIT_LEN;       //!< how many units do pre-clustering use.
  const uint8_t PARTIALS_SIZE;

  FILE** fhandlers_;
  FpVector**    fp_ptrs_;
  DocIDVector   docids_;

protected:
  inline void clean_fp_ptr()
  {
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
      fp_ptrs_[i] = NULL;
  }

  inline void swith_cache_status(CACHE_STATUS sta)
  {
    if (cache_status_ == UNIFORM_ACCESS)
    {
      cache_status_ = ADD_DOCS;
      for (uint8_t i =0; i<PARTIALS_SIZE; i++)
      {
        if (fp_ptrs_[i]!=NULL)
          fp_ptrs_[i]->reset();
      }
      in_mem_doc_num_ = 0;
      start_doc_i_ = doc_num_;
    }
    else
    {
      cache_status_ = UNIFORM_ACCESS;
      unload_fps();
      // for (uint8_t i =0; i<FP_LENGTH; i++)
//       {
//         start_fps_[i] = start_doc_i_;
//       }

    }
  }

  inline void set_cache_status(CACHE_STATUS sta)
  {
    if (sta == cache_status_)
      return;
    swith_cache_status(sta);
  }

  /**
     This function is to indicate if the cache is full when adding docs.
   **/
  inline bool cache_full()
  {
    assert (cache_status_ == ADD_DOCS);

    return in_mem_doc_num_ >= ALL_INFO_IN_MEM_LENGTH;
  }

  inline void unload_fps()
  {
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      if (fp_ptrs_[i]==NULL || fp_ptrs_[i]->length()==0)
        continue;

      //std::cout<<"unload seeking: "<<start_doc_i_<<std::endl;

      fseek(fhandlers_[i], start_doc_i_*sizeof(UNIT_TYPE)*UNIT_LEN, SEEK_SET);
      assert(fwrite(fp_ptrs_[i]->data(), fp_ptrs_[i]->size(), 1, fhandlers_[i])==1);
      fp_ptrs_[i]->compact();
      fp_ptrs_[i]->reset();
    }
  }

  inline void clean_fp()
  {
    //std::cout<<"clean_fp....\n";
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      if (fp_ptrs_[i]==NULL)
        continue;
      delete (fp_ptrs_[i]);
      fp_ptrs_[i] = NULL;
    }
  }

  inline void load_fp(uint8_t fpi, size_t n)
  {
    assert(fpi < PARTIALS_SIZE);

    static size_t max_fps_size = 0;
    max_fps_size = (CACHE_SIZE*1000000 - docids_.size())/sizeof(UNIT_TYPE);
    max_fps_size += max_fps_size % UNIT_LEN;

    start_doc_i_ = n;
    size_t size = (doc_num_ - n)*UNIT_LEN;
    size = size > max_fps_size? max_fps_size: size;

    std::cout<<size<<" "<<max_fps_size<<" "<<doc_num_<<"  loaded fp size\n";

//     for (uint8_t i =0; i<PARTIALS_SIZE; i++)
//     {
//       if (fpi == i || fp_ptrs_[i]==NULL)
//         continue;
//       delete fp_ptrs_[i];
//       fp_ptrs_[i] = NULL;
//     }

    if (fp_ptrs_[fpi] == NULL)
      fp_ptrs_[fpi] = new FpVector();

    fseek(fhandlers_[fpi], n*sizeof (UNIT_TYPE)*UNIT_LEN, SEEK_SET);
    assert(fread(fp_ptrs_[fpi]->array(size), size*sizeof(UNIT_TYPE), 1, fhandlers_[fpi])==1);
  }

  inline bool is_in_mem(uint8_t fpi, size_t n)
  {
    if (fp_ptrs_[fpi]!=NULL && n>=start_doc_i_ && n < start_doc_i_+fp_ptrs_[fpi]->length()/UNIT_LEN)
      return true;

    return false;
  }

public:
  explicit PartialFpList(const char* file_name, uint8_t unit_len=2, size_t doc_num = 0)
    :file_name_(file_name),doc_num_(doc_num), in_mem_doc_num_(0),start_doc_i_(0),cache_status_(ADD_DOCS),
     ALL_INFO_IN_MEM_LENGTH(CACHE_SIZE*1000000/(FP_LENGTH*sizeof(UNIT_TYPE))),
     UNIT_LEN(unit_len)
    , PARTIALS_SIZE((uint8_t)((double)FP_LENGTH/UNIT_LEN+0.5))
  {
    fp_ptrs_ = new FpVector*[PARTIALS_SIZE];
    fhandlers_ = new FILE*[PARTIALS_SIZE+1];
    clean_fp_ptr();

    static char num[8];

    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      sprintf(num, ".fp.%d", i);
      std::string s = file_name_;
      s += num;
      fhandlers_[i] = fopen(s.c_str(), "r+");
      if (fhandlers_[i] == NULL)
        fhandlers_[i] = fopen(s.c_str(), "w+");
      if (fhandlers_[i] == NULL)
      {
        std::cout<<"Can't create file: "<<s<<std::endl;
        return;
      }
    }

    std::string s = file_name_;
    s += ".id";
    fhandlers_[PARTIALS_SIZE] = fopen(s.c_str(), "r+");
    if (fhandlers_[PARTIALS_SIZE] != NULL)
    {
      fread(&doc_num_, sizeof(size_t), 1, fhandlers_[PARTIALS_SIZE]);
      if (doc_num_!= 0)
        fread(docids_.array(doc_num_), doc_num_*sizeof(uint32_t), 1, fhandlers_[PARTIALS_SIZE]);
    }
    else{
      fhandlers_[PARTIALS_SIZE] = fopen(s.c_str(), "w+");
      if (fhandlers_[PARTIALS_SIZE] == NULL)
      {
        std::cout<<"Can't create file: "<<s<<std::endl;
        return;
      }
      fwrite(&doc_num_, sizeof(size_t), 1, fhandlers_[PARTIALS_SIZE]);
    }

    start_doc_i_ = doc_num_;
    std::cout<<"ALL_INFO_IN_MEM_LENGTH: "<<ALL_INFO_IN_MEM_LENGTH<<std::endl;
  }

  inline ~PartialFpList()
  {
    flush();
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
      fclose(fhandlers_[i]);
    clean_fp();

    delete fhandlers_;
  }

  size_t add_doc(uint32_t docid, const FpVector& fp)
  {
    //std::cout<<"*** "<<fp<<std::endl;

    set_cache_status(ADD_DOCS);

    if (cache_full())
    {
      unload_fps();
      in_mem_doc_num_ = 0;
      start_doc_i_ = doc_num_;
    }

    assert(FP_LENGTH == fp.length());
    docids_.push_back(docid);

    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      if (fp_ptrs_[i]==NULL)
        fp_ptrs_[i] = new FpVector(10);

      for (uint8_t j=0; j<UNIT_LEN; j++)
      {
        size_t ii = i*UNIT_LEN+j;
        fp_ptrs_[i]->push_back(ii<fp.length()?fp[ii]: 0);
      }
    }

    ++in_mem_doc_num_;
    return ++doc_num_;
  }

  inline void ready_for_uniform_access(uint8_t fpi)
  {
    set_cache_status(UNIFORM_ACCESS);
    clean_fp();
    load_fp(fpi, 0);
  }

  inline UNIT_TYPE get_fp(uint8_t fpi, size_t n, uint8_t i=0)
  {
    assert(fpi<PARTIALS_SIZE);
    if (!is_in_mem(fpi, n))
      load_fp(fpi, n);

    return (*fp_ptrs_[fpi]).at((n-start_doc_i_)*UNIT_LEN+i);
  }

  inline void flush()
  {
    if (cache_status_ == ADD_DOCS)
    {
      unload_fps();
    }

    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
      fflush(fhandlers_[i]);

    fseek(fhandlers_[PARTIALS_SIZE], 0, SEEK_SET);
    fwrite(&doc_num_, sizeof (size_t), 1, fhandlers_[PARTIALS_SIZE]);
    fwrite(docids_.data(), docids_.size(), 1, fhandlers_[PARTIALS_SIZE]);
    fflush(fhandlers_[PARTIALS_SIZE]);

    //std::cout<<docids_.length()<<" "<<docids_.size()<<std::endl;
  }

  inline size_t doc_num() const
  {
    return doc_num_;
  }

  void reset()
  {
    static char num[8];
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      sprintf(num, ".fp.%d", i);
      std::string s = file_name_;
      s += num;
      fclose(fhandlers_[i]);
      fhandlers_[i] = fopen(s.c_str(), "w+");
      if (fhandlers_[i] == NULL)
      {
        std::cout<<"Can't create file: "<<s<<std::endl;
        return;
      }
    }

    std::string s = file_name_;
    s += ".id";
    fclose(fhandlers_[PARTIALS_SIZE]);
    fhandlers_[PARTIALS_SIZE] = fopen(s.c_str(), "w+");
    if (fhandlers_[PARTIALS_SIZE] == NULL)
    {
      std::cout<<"Can't create file: "<<s<<std::endl;
      return;
    }

    doc_num_ = 0;
    fwrite(&doc_num_, sizeof(size_t), 1, fhandlers_[PARTIALS_SIZE]);

    in_mem_doc_num_ = 0;
    start_doc_i_ = 0;
    clean_fp();
  }

  inline uint8_t unit_len()const
  {
    return UNIT_LEN;
  }

  inline void free()
  {
    clean_fp();
    docids_.compact();
    start_doc_i_ = doc_num_;
    in_mem_doc_num_ = 0;
  }

  inline uint32_t& operator[] (size_t i)
  {
    assert(i < docids_.length());
    return docids_[i];
  }

  void print()const
  {
    //std::cout<<docids_<<std::endl;

    if (cache_status_ == ADD_DOCS)
    {
      std::cout<<"Adding docs...\n";
      for (size_t i=0; i<in_mem_doc_num_; i++)
      {
        std::cout<<(*this)[i]<<"# ";//std::cout<<docids_.at(i+start_doc_i_)<<"# ";
        for (uint8_t j=0; j<PARTIALS_SIZE; j++)
          if (fp_ptrs_[j]!= NULL)
          { //std::cout<<(*fp_ptrs_[j]).length()<<" "<<(int)j<<std::endl;
            for (uint8_t k=0; k<UNIT_LEN; k++)
              std::cout<<(*fp_ptrs_[j])[i*UNIT_LEN+k]<<" ";
            std::cout<<"| ";
          }

        std::cout<<std::endl;
      }
    }
    else
    {
      std::cout<<"Uniform access to docs...\n";
      for (uint8_t i = 0; i<PARTIALS_SIZE; i++)
      {
        if (fp_ptrs_[i] == NULL)
          continue;
        std::cout<<"------------- #"<<(int)i<<"  fingerprinting("<<fp_ptrs_[i]->length()/UNIT_LEN<<") ------------------\n";
        for (size_t j=0; j<fp_ptrs_[i]->length(); j++)
        {
          std::cout<<j/UNIT_LEN+start_doc_i_<<": "<<(*fp_ptrs_[i])[j]<<" ";
          if ((j+1)%UNIT_LEN==0)
            std::cout<<"\n";
        }
      }
    }
  }

}
  ;

NS_IZENELIB_IR_END
#endif

<commit_msg>dupd memory leaking problem<commit_after>#ifndef PARTIAL_FP_LIST_HPP
#define PARTIAL_FP_LIST_HPP

#include <string>
#include <cstdio>
#include <ir/dup_det/integer_dyn_array.hpp>

NS_IZENELIB_IR_BEGIN

template<
  typename UNIT_TYPE = uint64_t,
  uint8_t  FP_LENGTH = 6,
  uint64_t CACHE_SIZE = 600
  >
class PartialFpList
{

public:
  typedef izenelib::am::IntegerDynArray<UNIT_TYPE> FpVector;

  typedef izenelib::am::IntegerDynArray<uint32_t> DocIDVector;

  typedef DocIDVector::size_t size_t;

private:

  enum CACHE_STATUS
    {
      ADD_DOCS, UNIFORM_ACCESS
    }
    ;

  std::string file_name_;
  size_t doc_num_;        //<! Total amount of documents.
  size_t in_mem_doc_num_; //!< Amount of documents in memory.
  size_t start_doc_i_;    //!< start index of document in memory.
  CACHE_STATUS cache_status_; //!< Cache status is adding docs and reading docs.

  const size_t ALL_INFO_IN_MEM_LENGTH;
  const uint8_t  UNIT_LEN;       //!< how many units do pre-clustering use.
  const uint8_t PARTIALS_SIZE;

  FILE** fhandlers_;
  FpVector**    fp_ptrs_;
  DocIDVector   docids_;

protected:
  inline void clean_fp_ptr()
  {
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
      fp_ptrs_[i] = NULL;
  }

  inline void swith_cache_status(CACHE_STATUS sta)
  {
    if (cache_status_ == UNIFORM_ACCESS)
    {
      cache_status_ = ADD_DOCS;
      for (uint8_t i =0; i<PARTIALS_SIZE; i++)
      {
        if (fp_ptrs_[i]!=NULL)
          fp_ptrs_[i]->reset();
      }
      in_mem_doc_num_ = 0;
      start_doc_i_ = doc_num_;
    }
    else
    {
      cache_status_ = UNIFORM_ACCESS;
      unload_fps();
      // for (uint8_t i =0; i<FP_LENGTH; i++)
//       {
//         start_fps_[i] = start_doc_i_;
//       }

    }
  }

  inline void set_cache_status(CACHE_STATUS sta)
  {
    if (sta == cache_status_)
      return;
    swith_cache_status(sta);
  }

  /**
     This function is to indicate if the cache is full when adding docs.
   **/
  inline bool cache_full()
  {
    assert (cache_status_ == ADD_DOCS);

    return in_mem_doc_num_ >= ALL_INFO_IN_MEM_LENGTH;
  }

  inline void unload_fps()
  {
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      if (fp_ptrs_[i]==NULL || fp_ptrs_[i]->length()==0)
        continue;

      //std::cout<<"unload seeking: "<<start_doc_i_<<std::endl;

      fseek(fhandlers_[i], start_doc_i_*sizeof(UNIT_TYPE)*UNIT_LEN, SEEK_SET);
      assert(fwrite(fp_ptrs_[i]->data(), fp_ptrs_[i]->size(), 1, fhandlers_[i])==1);
      fp_ptrs_[i]->compact();
      fp_ptrs_[i]->reset();
    }
  }

  inline void clean_fp()
  {
    //std::cout<<"clean_fp....\n";
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      if (fp_ptrs_[i]==NULL)
        continue;
      delete (fp_ptrs_[i]);
      fp_ptrs_[i] = NULL;
    }
  }

  inline void load_fp(uint8_t fpi, size_t n)
  {
    assert(fpi < PARTIALS_SIZE);

    static size_t max_fps_size = 0;
    max_fps_size = (CACHE_SIZE*1000000 - docids_.size())/sizeof(UNIT_TYPE);
    max_fps_size += max_fps_size % UNIT_LEN;

    start_doc_i_ = n;
    size_t size = (doc_num_ - n)*UNIT_LEN;
    size = size > max_fps_size? max_fps_size: size;

    std::cout<<size<<" "<<max_fps_size<<" "<<doc_num_<<"  loaded fp size\n";

//     for (uint8_t i =0; i<PARTIALS_SIZE; i++)
//     {
//       if (fpi == i || fp_ptrs_[i]==NULL)
//         continue;
//       delete fp_ptrs_[i];
//       fp_ptrs_[i] = NULL;
//     }

    if (fp_ptrs_[fpi] == NULL)
      fp_ptrs_[fpi] = new FpVector();

    fseek(fhandlers_[fpi], n*sizeof (UNIT_TYPE)*UNIT_LEN, SEEK_SET);
    assert(fread(fp_ptrs_[fpi]->array(size), size*sizeof(UNIT_TYPE), 1, fhandlers_[fpi])==1);
  }

  inline bool is_in_mem(uint8_t fpi, size_t n)
  {
    if (fp_ptrs_[fpi]!=NULL && n>=start_doc_i_ && n < start_doc_i_+fp_ptrs_[fpi]->length()/UNIT_LEN)
      return true;

    return false;
  }

public:
  explicit PartialFpList(const char* file_name, uint8_t unit_len=2, size_t doc_num = 0)
    :file_name_(file_name),doc_num_(doc_num), in_mem_doc_num_(0),start_doc_i_(0),cache_status_(ADD_DOCS),
     ALL_INFO_IN_MEM_LENGTH(CACHE_SIZE*1000000/(FP_LENGTH*sizeof(UNIT_TYPE))),
     UNIT_LEN(unit_len)
    , PARTIALS_SIZE((uint8_t)((double)FP_LENGTH/UNIT_LEN+0.5))
  {
    fp_ptrs_ = new FpVector*[PARTIALS_SIZE];
    fhandlers_ = new FILE*[PARTIALS_SIZE+1];
    clean_fp_ptr();

    static char num[8];

    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      sprintf(num, ".fp.%d", i);
      std::string s = file_name_;
      s += num;
      fhandlers_[i] = fopen(s.c_str(), "r+");
      if (fhandlers_[i] == NULL)
        fhandlers_[i] = fopen(s.c_str(), "w+");
      if (fhandlers_[i] == NULL)
      {
        std::cout<<"Can't create file: "<<s<<std::endl;
        return;
      }
    }

    std::string s = file_name_;
    s += ".id";
    fhandlers_[PARTIALS_SIZE] = fopen(s.c_str(), "r+");
    if (fhandlers_[PARTIALS_SIZE] != NULL)
    {
      fread(&doc_num_, sizeof(size_t), 1, fhandlers_[PARTIALS_SIZE]);
      if (doc_num_!= 0)
        fread(docids_.array(doc_num_), doc_num_*sizeof(uint32_t), 1, fhandlers_[PARTIALS_SIZE]);
    }
    else{
      fhandlers_[PARTIALS_SIZE] = fopen(s.c_str(), "w+");
      if (fhandlers_[PARTIALS_SIZE] == NULL)
      {
        std::cout<<"Can't create file: "<<s<<std::endl;
        return;
      }
      fwrite(&doc_num_, sizeof(size_t), 1, fhandlers_[PARTIALS_SIZE]);
    }

    start_doc_i_ = doc_num_;
    std::cout<<"ALL_INFO_IN_MEM_LENGTH: "<<ALL_INFO_IN_MEM_LENGTH<<std::endl;
  }

  inline ~PartialFpList()
  {
    flush();
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
      fclose(fhandlers_[i]);
    clean_fp();

    delete fhandlers_;
    delete fp_ptrs_;
  }

  size_t add_doc(uint32_t docid, const FpVector& fp)
  {
    //std::cout<<"*** "<<fp<<std::endl;

    set_cache_status(ADD_DOCS);

    if (cache_full())
    {
      unload_fps();
      in_mem_doc_num_ = 0;
      start_doc_i_ = doc_num_;
    }

    assert(FP_LENGTH == fp.length());
    docids_.push_back(docid);

    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      if (fp_ptrs_[i]==NULL)
        fp_ptrs_[i] = new FpVector(10);

      for (uint8_t j=0; j<UNIT_LEN; j++)
      {
        size_t ii = i*UNIT_LEN+j;
        fp_ptrs_[i]->push_back(ii<fp.length()?fp[ii]: 0);
      }
    }

    ++in_mem_doc_num_;
    return ++doc_num_;
  }

  inline void ready_for_uniform_access(uint8_t fpi)
  {
    set_cache_status(UNIFORM_ACCESS);
    clean_fp();
    load_fp(fpi, 0);
  }

  inline UNIT_TYPE get_fp(uint8_t fpi, size_t n, uint8_t i=0)
  {
    assert(fpi<PARTIALS_SIZE);
    if (!is_in_mem(fpi, n))
      load_fp(fpi, n);

    return (*fp_ptrs_[fpi]).at((n-start_doc_i_)*UNIT_LEN+i);
  }

  inline void flush()
  {
    if (cache_status_ == ADD_DOCS)
    {
      unload_fps();
    }

    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
      fflush(fhandlers_[i]);

    fseek(fhandlers_[PARTIALS_SIZE], 0, SEEK_SET);
    fwrite(&doc_num_, sizeof (size_t), 1, fhandlers_[PARTIALS_SIZE]);
    fwrite(docids_.data(), docids_.size(), 1, fhandlers_[PARTIALS_SIZE]);
    fflush(fhandlers_[PARTIALS_SIZE]);

    //std::cout<<docids_.length()<<" "<<docids_.size()<<std::endl;
  }

  inline size_t doc_num() const
  {
    return doc_num_;
  }

  void reset()
  {
    static char num[8];
    for (uint8_t i =0; i<PARTIALS_SIZE; i++)
    {
      sprintf(num, ".fp.%d", i);
      std::string s = file_name_;
      s += num;
      fclose(fhandlers_[i]);
      fhandlers_[i] = fopen(s.c_str(), "w+");
      if (fhandlers_[i] == NULL)
      {
        std::cout<<"Can't create file: "<<s<<std::endl;
        return;
      }
    }

    std::string s = file_name_;
    s += ".id";
    fclose(fhandlers_[PARTIALS_SIZE]);
    fhandlers_[PARTIALS_SIZE] = fopen(s.c_str(), "w+");
    if (fhandlers_[PARTIALS_SIZE] == NULL)
    {
      std::cout<<"Can't create file: "<<s<<std::endl;
      return;
    }

    doc_num_ = 0;
    fwrite(&doc_num_, sizeof(size_t), 1, fhandlers_[PARTIALS_SIZE]);

    in_mem_doc_num_ = 0;
    start_doc_i_ = 0;
    clean_fp();
  }

  inline uint8_t unit_len()const
  {
    return UNIT_LEN;
  }

  inline void free()
  {
    clean_fp();
    docids_.compact();
    start_doc_i_ = doc_num_;
    in_mem_doc_num_ = 0;
  }

  inline uint32_t& operator[] (size_t i)
  {
    assert(i < docids_.length());
    return docids_[i];
  }

  void print()const
  {
    //std::cout<<docids_<<std::endl;

    if (cache_status_ == ADD_DOCS)
    {
      std::cout<<"Adding docs...\n";
      for (size_t i=0; i<in_mem_doc_num_; i++)
      {
        std::cout<<(*this)[i]<<"# ";//std::cout<<docids_.at(i+start_doc_i_)<<"# ";
        for (uint8_t j=0; j<PARTIALS_SIZE; j++)
          if (fp_ptrs_[j]!= NULL)
          { //std::cout<<(*fp_ptrs_[j]).length()<<" "<<(int)j<<std::endl;
            for (uint8_t k=0; k<UNIT_LEN; k++)
              std::cout<<(*fp_ptrs_[j])[i*UNIT_LEN+k]<<" ";
            std::cout<<"| ";
          }

        std::cout<<std::endl;
      }
    }
    else
    {
      std::cout<<"Uniform access to docs...\n";
      for (uint8_t i = 0; i<PARTIALS_SIZE; i++)
      {
        if (fp_ptrs_[i] == NULL)
          continue;
        std::cout<<"------------- #"<<(int)i<<"  fingerprinting("<<fp_ptrs_[i]->length()/UNIT_LEN<<") ------------------\n";
        for (size_t j=0; j<fp_ptrs_[i]->length(); j++)
        {
          std::cout<<j/UNIT_LEN+start_doc_i_<<": "<<(*fp_ptrs_[i])[j]<<" ";
          if ((j+1)%UNIT_LEN==0)
            std::cout<<"\n";
        }
      }
    }
  }

}
  ;

NS_IZENELIB_IR_END
#endif

<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <algorithm>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"

#if defined(_MSC_VER)
namespace std
{
	using ::isprint;
}
#define for if (false) {} else for
#endif

namespace
{
	template <class T>
	void call_destructor(T* o)
	{
		TORRENT_ASSERT(o);
		o->~T();
	}

	struct compare_string
	{
		compare_string(char const* s): m_str(s)  {}

		bool operator()(
			std::pair<std::string
			, libtorrent::entry> const& e) const
		{
			return m_str && e.first == m_str;
		}
		char const* m_str;
	};
}

namespace libtorrent
{
	namespace detail
	{
		TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
		{
			int sign = 0;
			if (val < 0)
			{
				sign = 1;
				val = -val;
			}
			buf[--size] = '\0';
			if (val == 0) buf[--size] = '0';
			for (; size > sign && val != 0;)
			{
				buf[--size] = '0' + char(val % 10);
				val /= 10;
			}
			if (sign) buf[--size] = '-';
			return buf + size;
		}
	}

	entry& entry::operator[](char const* key)
	{
		dictionary_type::iterator i = dict().find(key);
		if (i != dict().end()) return i->second;
		dictionary_type::iterator ret = dict().insert(
			dict().begin()
			, std::make_pair(std::string(key), entry()));
		return ret->second;
	}

	entry& entry::operator[](std::string const& key)
	{
		return (*this)[key.c_str()];
	}

	entry* entry::find_key(char const* key)
	{
		dictionary_type::iterator i = std::find_if(
			dict().begin()
			, dict().end()
			, compare_string(key));
		if (i == dict().end()) return 0;
		return &i->second;

	}

	entry const* entry::find_key(char const* key) const
	{
		dictionary_type::const_iterator i = dict().find(key);
		if (i == dict().end()) return 0;
		return &i->second;
	}

#ifndef BOOST_NO_EXCEPTIONS
	const entry& entry::operator[](char const* key) const
	{
		dictionary_type::const_iterator i = dict().find(key);
		if (i == dict().end()) throw type_error(
			(std::string("key not found: ") + key).c_str());
		return i->second;
	}

	const entry& entry::operator[](std::string const& key) const
	{
		return (*this)[key.c_str()];
	}
#endif

	entry::entry(dictionary_type const& v)
	{
		new(data) dictionary_type(v);
		m_type = dictionary_t;
	}

	entry::entry(string_type const& v)
	{
		new(data) string_type(v);
		m_type = string_t;
	}

	entry::entry(list_type const& v)
	{
		new(data) list_type(v);
		m_type = list_t;
	}

	entry::entry(integer_type const& v)
	{
		new(data) integer_type(v);
		m_type = int_t;
	}

	void entry::operator=(dictionary_type const& v)
	{
		destruct();
		new(data) dictionary_type(v);
		m_type = dictionary_t;
	}

	void entry::operator=(string_type const& v)
	{
		destruct();
		new(data) string_type(v);
		m_type = string_t;
	}

	void entry::operator=(list_type const& v)
	{
		destruct();
		new(data) list_type(v);
		m_type = list_t;
	}

	void entry::operator=(integer_type const& v)
	{
		destruct();
		new(data) integer_type(v);
		m_type = int_t;
	}

	bool entry::operator==(entry const& e) const
	{
		if (m_type != e.m_type) return false;

		switch(m_type)
		{
		case int_t:
			return integer() == e.integer();
		case string_t:
			return string() == e.string();
		case list_t:
			return list() == e.list();
		case dictionary_t:
			return dict() == e.dict();
		default:
			TORRENT_ASSERT(m_type == undefined_t);
			return true;
		}
	}

	void entry::construct(data_type t)
	{
		m_type = t;
		switch(m_type)
		{
		case int_t:
			new(data) integer_type;
			break;
		case string_t:
			new(data) string_type;
			break;
		case list_t:
			new(data) list_type;
			break;
		case dictionary_t:
			new (data) dictionary_type;
			break;
		default:
			TORRENT_ASSERT(m_type == undefined_t);
			m_type = undefined_t;
		}
	}

	void entry::copy(entry const& e)
	{
		m_type = e.m_type;
		switch(m_type)
		{
		case int_t:
			new(data) integer_type(e.integer());
			break;
		case string_t:
			new(data) string_type(e.string());
			break;
		case list_t:
			new(data) list_type(e.list());
			break;
		case dictionary_t:
			new (data) dictionary_type(e.dict());
			break;
		default:
			m_type = undefined_t;
		}
	}

	void entry::destruct()
	{
		switch(m_type)
		{
		case int_t:
			call_destructor(reinterpret_cast<integer_type*>(data));
			break;
		case string_t:
			call_destructor(reinterpret_cast<string_type*>(data));
			break;
		case list_t:
			call_destructor(reinterpret_cast<list_type*>(data));
			break;
		case dictionary_t:
			call_destructor(reinterpret_cast<dictionary_type*>(data));
			break;
		default:
			TORRENT_ASSERT(m_type == undefined_t);
			break;
		}
	}

	void entry::swap(entry& e)
	{
		// not implemented
		TORRENT_ASSERT(false);
	}

	void entry::print(std::ostream& os, int indent) const
	{
		TORRENT_ASSERT(indent >= 0);
		for (int i = 0; i < indent; ++i) os << " ";
		switch (m_type)
		{
		case int_t:
			os << integer() << "\n";
			break;
		case string_t:
			{
				bool binary_string = false;
				for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
				{
					if (!std::isprint(static_cast<unsigned char>(*i)))
					{
						binary_string = true;
						break;
					}
				}
				if (binary_string)
				{
					os.unsetf(std::ios_base::dec);
					os.setf(std::ios_base::hex);
					for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
						os << std::setfill('0') << std::setw(2)
							<< static_cast<unsigned int>((unsigned char)*i);
					os.unsetf(std::ios_base::hex);
					os.setf(std::ios_base::dec);
					os << "\n";
				}
				else
				{
					os << string() << "\n";
				}
			} break;
		case list_t:
			{
				os << "list\n";
				for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
				{
					i->print(os, indent+1);
				}
			} break;
		case dictionary_t:
			{
				os << "dictionary\n";
				for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
				{
					for (int j = 0; j < indent+1; ++j) os << " ";
					os << "[" << i->first << "]";
					if (i->second.type() != entry::string_t
						&& i->second.type() != entry::int_t)
						os << "\n";
					else os << " ";
					i->second.print(os, indent+2);
				}
			} break;
		default:
			os << "<uninitialized>\n";
		}
	}
}

<commit_msg>fixed missing include in entry.cpp<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include <algorithm>
#include <iostream>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"

#if defined(_MSC_VER)
namespace std
{
	using ::isprint;
}
#define for if (false) {} else for
#endif

namespace
{
	template <class T>
	void call_destructor(T* o)
	{
		TORRENT_ASSERT(o);
		o->~T();
	}

	struct compare_string
	{
		compare_string(char const* s): m_str(s)  {}

		bool operator()(
			std::pair<std::string
			, libtorrent::entry> const& e) const
		{
			return m_str && e.first == m_str;
		}
		char const* m_str;
	};
}

namespace libtorrent
{
	namespace detail
	{
		TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
		{
			int sign = 0;
			if (val < 0)
			{
				sign = 1;
				val = -val;
			}
			buf[--size] = '\0';
			if (val == 0) buf[--size] = '0';
			for (; size > sign && val != 0;)
			{
				buf[--size] = '0' + char(val % 10);
				val /= 10;
			}
			if (sign) buf[--size] = '-';
			return buf + size;
		}
	}

	entry& entry::operator[](char const* key)
	{
		dictionary_type::iterator i = dict().find(key);
		if (i != dict().end()) return i->second;
		dictionary_type::iterator ret = dict().insert(
			dict().begin()
			, std::make_pair(std::string(key), entry()));
		return ret->second;
	}

	entry& entry::operator[](std::string const& key)
	{
		return (*this)[key.c_str()];
	}

	entry* entry::find_key(char const* key)
	{
		dictionary_type::iterator i = std::find_if(
			dict().begin()
			, dict().end()
			, compare_string(key));
		if (i == dict().end()) return 0;
		return &i->second;

	}

	entry const* entry::find_key(char const* key) const
	{
		dictionary_type::const_iterator i = dict().find(key);
		if (i == dict().end()) return 0;
		return &i->second;
	}

#ifndef BOOST_NO_EXCEPTIONS
	const entry& entry::operator[](char const* key) const
	{
		dictionary_type::const_iterator i = dict().find(key);
		if (i == dict().end()) throw type_error(
			(std::string("key not found: ") + key).c_str());
		return i->second;
	}

	const entry& entry::operator[](std::string const& key) const
	{
		return (*this)[key.c_str()];
	}
#endif

	entry::entry(dictionary_type const& v)
	{
		new(data) dictionary_type(v);
		m_type = dictionary_t;
	}

	entry::entry(string_type const& v)
	{
		new(data) string_type(v);
		m_type = string_t;
	}

	entry::entry(list_type const& v)
	{
		new(data) list_type(v);
		m_type = list_t;
	}

	entry::entry(integer_type const& v)
	{
		new(data) integer_type(v);
		m_type = int_t;
	}

	void entry::operator=(dictionary_type const& v)
	{
		destruct();
		new(data) dictionary_type(v);
		m_type = dictionary_t;
	}

	void entry::operator=(string_type const& v)
	{
		destruct();
		new(data) string_type(v);
		m_type = string_t;
	}

	void entry::operator=(list_type const& v)
	{
		destruct();
		new(data) list_type(v);
		m_type = list_t;
	}

	void entry::operator=(integer_type const& v)
	{
		destruct();
		new(data) integer_type(v);
		m_type = int_t;
	}

	bool entry::operator==(entry const& e) const
	{
		if (m_type != e.m_type) return false;

		switch(m_type)
		{
		case int_t:
			return integer() == e.integer();
		case string_t:
			return string() == e.string();
		case list_t:
			return list() == e.list();
		case dictionary_t:
			return dict() == e.dict();
		default:
			TORRENT_ASSERT(m_type == undefined_t);
			return true;
		}
	}

	void entry::construct(data_type t)
	{
		m_type = t;
		switch(m_type)
		{
		case int_t:
			new(data) integer_type;
			break;
		case string_t:
			new(data) string_type;
			break;
		case list_t:
			new(data) list_type;
			break;
		case dictionary_t:
			new (data) dictionary_type;
			break;
		default:
			TORRENT_ASSERT(m_type == undefined_t);
			m_type = undefined_t;
		}
	}

	void entry::copy(entry const& e)
	{
		m_type = e.m_type;
		switch(m_type)
		{
		case int_t:
			new(data) integer_type(e.integer());
			break;
		case string_t:
			new(data) string_type(e.string());
			break;
		case list_t:
			new(data) list_type(e.list());
			break;
		case dictionary_t:
			new (data) dictionary_type(e.dict());
			break;
		default:
			m_type = undefined_t;
		}
	}

	void entry::destruct()
	{
		switch(m_type)
		{
		case int_t:
			call_destructor(reinterpret_cast<integer_type*>(data));
			break;
		case string_t:
			call_destructor(reinterpret_cast<string_type*>(data));
			break;
		case list_t:
			call_destructor(reinterpret_cast<list_type*>(data));
			break;
		case dictionary_t:
			call_destructor(reinterpret_cast<dictionary_type*>(data));
			break;
		default:
			TORRENT_ASSERT(m_type == undefined_t);
			break;
		}
	}

	void entry::swap(entry& e)
	{
		// not implemented
		TORRENT_ASSERT(false);
	}

	void entry::print(std::ostream& os, int indent) const
	{
		TORRENT_ASSERT(indent >= 0);
		for (int i = 0; i < indent; ++i) os << " ";
		switch (m_type)
		{
		case int_t:
			os << integer() << "\n";
			break;
		case string_t:
			{
				bool binary_string = false;
				for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
				{
					if (!std::isprint(static_cast<unsigned char>(*i)))
					{
						binary_string = true;
						break;
					}
				}
				if (binary_string)
				{
					os.unsetf(std::ios_base::dec);
					os.setf(std::ios_base::hex);
					for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
						os << std::setfill('0') << std::setw(2)
							<< static_cast<unsigned int>((unsigned char)*i);
					os.unsetf(std::ios_base::hex);
					os.setf(std::ios_base::dec);
					os << "\n";
				}
				else
				{
					os << string() << "\n";
				}
			} break;
		case list_t:
			{
				os << "list\n";
				for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
				{
					i->print(os, indent+1);
				}
			} break;
		case dictionary_t:
			{
				os << "dictionary\n";
				for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
				{
					for (int j = 0; j < indent+1; ++j) os << " ";
					os << "[" << i->first << "]";
					if (i->second.type() != entry::string_t
						&& i->second.type() != entry::int_t)
						os << "\n";
					else os << " ";
					i->second.print(os, indent+2);
				}
			} break;
		default:
			os << "<uninitialized>\n";
		}
	}
}

<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <sstream>

#include "analyzer.h"
#include "ast.h"
#include "cell.h"
#include "compiler.h"
#include "debuginfo.h"
#include "disassembler.h"
#include "exec.h"
#include "lexer.h"
#include "parser.h"
#include "pt_dump.h"
#include "repl.h"
#include "support.h"

bool dump_tokens = false;
bool dump_parse = false;
bool dump_ast = false;
bool dump_listing = false;
bool enable_assert = true;
bool enable_trace = false;
bool error_json = false;
unsigned short debug_port = 0;
bool repl_no_prompt = false;
bool repl_stop_on_any_error = false;

static bool has_suffix(const std::string &str, const std::string &suffix)
{
    return str.size() >= suffix.size() && str.substr(str.size() - suffix.size()) == suffix;
}

static TokenizedSource dump(const TokenizedSource &tokens)
{
    for (auto t: tokens.tokens) {
        std::cerr << t.tostring() << "\n";
    }
    return tokens;
}

static const pt::Program *dump(const pt::Program *parsetree)
{
    pt::dump(std::cerr, parsetree);
    return parsetree;
}

static const ast::Program *dump(const ast::Program *program)
{
    program->dump(std::cerr);
    return program;
}

static void repl(int argc, char *argv[])
{
    Repl repl(argc, argv, repl_no_prompt, repl_stop_on_any_error, dump_listing);
    for (;;) {
        if (not repl_no_prompt) {
            std::cout << "> ";
        }
        std::string s;
        if (not std::getline(std::cin, s)) {
            if (not repl_no_prompt) {
                std::cout << std::endl;
            }
            break;
        }
        repl.handle(s);
    }
    exit(0);
}

int main(int argc, char *argv[])
{
    if (argc < 1) {
        fprintf(stderr, "Usage: %s filename.neon\n", argv[0]);
        exit(1);
    }

    int a = 1;
    while (a < argc && argv[a][0] == '-' && argv[a][1] != '\0') {
        std::string arg = argv[a];
        if (arg == "-c") {
            if (argv[a+1] == NULL) {
                fprintf(stderr, "%s: -c requires argument\n", argv[0]);
                exit(1);
            }
            break;
        } else if (arg == "-d") {
            a++;
            try {
                debug_port = static_cast<unsigned short>(std::stoul(argv[a]));
            } catch(std::invalid_argument) {
                fprintf(stderr, "%s: -d requires integer argument\n", argv[0]);
                exit(1);
            }
        } else if (arg == "--json") {
            error_json = true;
        } else if (arg == "-l") {
            dump_listing = true;
        } else if (arg == "-n") {
            enable_assert = false;
        } else if (arg == "--repl-no-prompt") {
            repl_no_prompt = true;
        } else if (arg == "--repl-stop-on-any-error") {
            repl_stop_on_any_error = true;
        } else if (arg == "-t") {
            enable_trace = true;
        } else {
            fprintf(stderr, "Unknown option: %s\n", arg.c_str());
            exit(1);
        }
        a++;
    }

    if (a >= argc) {
        repl(argc, argv);
    }

    const std::string name = argv[a];
    auto i = name.find_last_of("/:\\");
    const std::string source_path { i != std::string::npos ? name.substr(0, i+1) : "" };

    CompilerSupport compiler_support(source_path, nullptr);
    RuntimeSupport runtime_support(source_path);
    std::unique_ptr<DebugInfo> debug;

    std::vector<unsigned char> bytecode;
    if (not has_suffix(name, ".neonx")) {

        std::stringstream source;
        if (name == "-") {
            source << std::cin.rdbuf();
        } else if (name == "-c") {
            source << argv[a+1];
        } else {
            std::ifstream inf(name);
            if (not inf) {
                fprintf(stderr, "Source file not found: %s\n", name.c_str());
                exit(1);
            }
            source << inf.rdbuf();
        }

        // TODO - Allow reading debug information from file.
        debug.reset(new DebugInfo(name, source.str()));

        try {
            auto tokens = tokenize(name, source.str());
            if (dump_tokens) {
                dump(*tokens);
            }

            auto parsetree = parse(*tokens);
            if (dump_parse) {
                dump(parsetree.get());
            }

            auto program = analyze(&compiler_support, parsetree.get());
            if (dump_ast) {
                dump(program);
            }

            bytecode = compile(program, debug.get());
            if (dump_listing) {
                disassemble(bytecode, std::cerr, debug.get());
            }

        } catch (CompilerError *error) {
            if (error_json) {
                error->write_json(std::cerr);
            } else {
                error->write(std::cerr);
            }
            exit(1);
        }

    } else {

        std::ifstream inf(name, std::ios::binary);
        if (not inf) {
            fprintf(stderr, "Source file not found: %s\n", name.c_str());
            exit(1);
        }
        std::stringstream object;
        object << inf.rdbuf();
        std::string s = object.str();
        std::copy(s.begin(), s.end(), std::back_inserter(bytecode));

    }

    struct ExecOptions options;
    options.enable_assert = enable_assert;
    options.enable_trace = enable_trace;
    exit(exec(name, bytecode, debug.get(), &runtime_support, &options, debug_port, argc-a, argv+a));
}
<commit_msg>Catch polymorphic exception by reference, not value<commit_after>#include <fstream>
#include <iostream>
#include <sstream>

#include "analyzer.h"
#include "ast.h"
#include "cell.h"
#include "compiler.h"
#include "debuginfo.h"
#include "disassembler.h"
#include "exec.h"
#include "lexer.h"
#include "parser.h"
#include "pt_dump.h"
#include "repl.h"
#include "support.h"

bool dump_tokens = false;
bool dump_parse = false;
bool dump_ast = false;
bool dump_listing = false;
bool enable_assert = true;
bool enable_trace = false;
bool error_json = false;
unsigned short debug_port = 0;
bool repl_no_prompt = false;
bool repl_stop_on_any_error = false;

static bool has_suffix(const std::string &str, const std::string &suffix)
{
    return str.size() >= suffix.size() && str.substr(str.size() - suffix.size()) == suffix;
}

static TokenizedSource dump(const TokenizedSource &tokens)
{
    for (auto t: tokens.tokens) {
        std::cerr << t.tostring() << "\n";
    }
    return tokens;
}

static const pt::Program *dump(const pt::Program *parsetree)
{
    pt::dump(std::cerr, parsetree);
    return parsetree;
}

static const ast::Program *dump(const ast::Program *program)
{
    program->dump(std::cerr);
    return program;
}

static void repl(int argc, char *argv[])
{
    Repl repl(argc, argv, repl_no_prompt, repl_stop_on_any_error, dump_listing);
    for (;;) {
        if (not repl_no_prompt) {
            std::cout << "> ";
        }
        std::string s;
        if (not std::getline(std::cin, s)) {
            if (not repl_no_prompt) {
                std::cout << std::endl;
            }
            break;
        }
        repl.handle(s);
    }
    exit(0);
}

int main(int argc, char *argv[])
{
    if (argc < 1) {
        fprintf(stderr, "Usage: %s filename.neon\n", argv[0]);
        exit(1);
    }

    int a = 1;
    while (a < argc && argv[a][0] == '-' && argv[a][1] != '\0') {
        std::string arg = argv[a];
        if (arg == "-c") {
            if (argv[a+1] == NULL) {
                fprintf(stderr, "%s: -c requires argument\n", argv[0]);
                exit(1);
            }
            break;
        } else if (arg == "-d") {
            a++;
            try {
                debug_port = static_cast<unsigned short>(std::stoul(argv[a]));
            } catch (std::invalid_argument &) {
                fprintf(stderr, "%s: -d requires integer argument\n", argv[0]);
                exit(1);
            }
        } else if (arg == "--json") {
            error_json = true;
        } else if (arg == "-l") {
            dump_listing = true;
        } else if (arg == "-n") {
            enable_assert = false;
        } else if (arg == "--repl-no-prompt") {
            repl_no_prompt = true;
        } else if (arg == "--repl-stop-on-any-error") {
            repl_stop_on_any_error = true;
        } else if (arg == "-t") {
            enable_trace = true;
        } else {
            fprintf(stderr, "Unknown option: %s\n", arg.c_str());
            exit(1);
        }
        a++;
    }

    if (a >= argc) {
        repl(argc, argv);
    }

    const std::string name = argv[a];
    auto i = name.find_last_of("/:\\");
    const std::string source_path { i != std::string::npos ? name.substr(0, i+1) : "" };

    CompilerSupport compiler_support(source_path, nullptr);
    RuntimeSupport runtime_support(source_path);
    std::unique_ptr<DebugInfo> debug;

    std::vector<unsigned char> bytecode;
    if (not has_suffix(name, ".neonx")) {

        std::stringstream source;
        if (name == "-") {
            source << std::cin.rdbuf();
        } else if (name == "-c") {
            source << argv[a+1];
        } else {
            std::ifstream inf(name);
            if (not inf) {
                fprintf(stderr, "Source file not found: %s\n", name.c_str());
                exit(1);
            }
            source << inf.rdbuf();
        }

        // TODO - Allow reading debug information from file.
        debug.reset(new DebugInfo(name, source.str()));

        try {
            auto tokens = tokenize(name, source.str());
            if (dump_tokens) {
                dump(*tokens);
            }

            auto parsetree = parse(*tokens);
            if (dump_parse) {
                dump(parsetree.get());
            }

            auto program = analyze(&compiler_support, parsetree.get());
            if (dump_ast) {
                dump(program);
            }

            bytecode = compile(program, debug.get());
            if (dump_listing) {
                disassemble(bytecode, std::cerr, debug.get());
            }

        } catch (CompilerError *error) {
            if (error_json) {
                error->write_json(std::cerr);
            } else {
                error->write(std::cerr);
            }
            exit(1);
        }

    } else {

        std::ifstream inf(name, std::ios::binary);
        if (not inf) {
            fprintf(stderr, "Source file not found: %s\n", name.c_str());
            exit(1);
        }
        std::stringstream object;
        object << inf.rdbuf();
        std::string s = object.str();
        std::copy(s.begin(), s.end(), std::back_inserter(bytecode));

    }

    struct ExecOptions options;
    options.enable_assert = enable_assert;
    options.enable_trace = enable_trace;
    exit(exec(name, bytecode, debug.get(), &runtime_support, &options, debug_port, argc-a, argv+a));
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2012, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/config.hpp"
#include "libtorrent/rss.hpp"
#include "libtorrent/fingerprint.hpp"
#include "libtorrent/aux_/session_impl.hpp"
#include "libtorrent/http_parser.hpp"

#include "test.hpp"

using namespace libtorrent;

void print_feed(feed_status const& f)
{
	fprintf(stderr, "FEED: %s\n",f.url.c_str());
	if (f.error)
		fprintf(stderr, "ERROR: %s\n", f.error.message().c_str());

	fprintf(stderr, "   %s\n   %s\n", f.title.c_str(), f.description.c_str());
	fprintf(stderr, "   ttl: %d minutes\n", f.ttl);
	fprintf(stderr, "   num items: %d\n", int(f.items.size()));

	for (std::vector<feed_item>::const_iterator i = f.items.begin()
		, end(f.items.end()); i != end; ++i)
	{
		fprintf(stderr, "\033[32m%s\033[0m\n------------------------------------------------------\n"
			"   url: %s\n   size: %"PRId64"\n   info-hash: %s\n   uuid: %s\n   description: %s\n"
			"   comment: %s\n   category: %s\n"
			, i->title.c_str(), i->url.c_str(), i->size
			, i->info_hash.is_all_zeros() ? "" : to_hex(i->info_hash.to_string()).c_str()
			, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());
	}
}

struct rss_expect
{
	rss_expect(int nitems, std::string url, std::string title, size_type size)
		: num_items(nitems), first_url(url), first_title(title), first_size(size)
	{}

	int num_items;
	std::string first_url;
	std::string first_title;
	size_type first_size;
};

void test_feed(std::string const& filename, rss_expect const& expect)
{
	std::vector<char> buffer;
	error_code ec;
	load_file(filename, buffer, ec);
	if (ec)
	{
		fprintf(stderr, "failed to load file \"%s\": %s\n", filename.c_str(), ec.message().c_str());
	}
	TEST_CHECK(!ec);

	char* buf = buffer.size() ? &buffer[0] : NULL;
	int len = buffer.size();

	char const header[] = "HTTP/1.1 200 OK\r\n"
		"\r\n";

	boost::shared_ptr<aux::session_impl> s = boost::shared_ptr<aux::session_impl>(new aux::session_impl(
		std::make_pair(100, 200), fingerprint("TT", 0, 0, 0 ,0), NULL, 0));
	s->start_session();

	feed_settings sett;
	sett.auto_download = false;
	sett.auto_map_handles = false;
	boost::shared_ptr<feed> f = boost::shared_ptr<feed>(new feed(*s, sett));
	http_parser parser;
	bool err = false;
	parser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err);
	TEST_CHECK(err == false);

	f->on_feed(error_code(), parser, buf, len);

	feed_status st;
	f->get_feed_status(&st);
	TEST_CHECK(!st.error);

	print_feed(st);

	TEST_CHECK(st.items.size() == expect.num_items);
	if (st.items.size() > 0)
	{
		TEST_CHECK(st.items[0].url == expect.first_url);
		TEST_CHECK(st.items[0].size == expect.first_size);
		TEST_CHECK(st.items[0].title == expect.first_title);
	}

	entry state;
	f->save_state(state);

	fprintf(stderr, "feed_state:\n");
#ifdef TORRENT_DEBUG
	state.print(std::cerr);
#endif

	// TODO: verify some key state is saved in 'state'
}

int test_main()
{
	test_feed(combine_path("..", "eztv.xml"), rss_expect(30, "http://torrent.zoink.it/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent", "The Daily Show 2012-02-16 [HDTV - LMAO]", 183442338));
	test_feed(combine_path("..", "cb.xml"), rss_expect(50, "http://www.clearbits.net/get/1911-norbergfestival-2011.torrent", "Norbergfestival 2011", 1160773632));
	test_feed(combine_path("..", "kat.xml"), rss_expect(25, "http://kat.ph/torrents/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897/", "Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]", 168773863));
	test_feed(combine_path("..", "mn.xml"), rss_expect(20, "http://www.mininova.org/get/13203100", "Dexcell - January TwentyTwelve Mix", 137311179));
	test_feed(combine_path("..", "pb.xml"), rss_expect(60, "magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D", "Thompson Twins - 1989 - Big Trash [MP3]", 100160904));
	return 0;
}

<commit_msg>fix test_rss for windows<commit_after>/*

Copyright (c) 2012, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/config.hpp"
#include "libtorrent/rss.hpp"
#include "libtorrent/fingerprint.hpp"
#include "libtorrent/aux_/session_impl.hpp"
#include "libtorrent/http_parser.hpp"

#include "test.hpp"

using namespace libtorrent;

void print_feed(feed_status const& f)
{
	fprintf(stderr, "FEED: %s\n",f.url.c_str());
	if (f.error)
		fprintf(stderr, "ERROR: %s\n", f.error.message().c_str());

	fprintf(stderr, "   %s\n   %s\n", f.title.c_str(), f.description.c_str());
	fprintf(stderr, "   ttl: %d minutes\n", f.ttl);
	fprintf(stderr, "   num items: %d\n", int(f.items.size()));

	for (std::vector<feed_item>::const_iterator i = f.items.begin()
		, end(f.items.end()); i != end; ++i)
	{
		fprintf(stderr, "\033[32m%s\033[0m\n------------------------------------------------------\n"
			"   url: %s\n   size: %"PRId64"\n   info-hash: %s\n   uuid: %s\n   description: %s\n"
			"   comment: %s\n   category: %s\n"
			, i->title.c_str(), i->url.c_str(), i->size
			, i->info_hash.is_all_zeros() ? "" : to_hex(i->info_hash.to_string()).c_str()
			, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());
	}
}

struct rss_expect
{
	rss_expect(int nitems, std::string url, std::string title, size_type size)
		: num_items(nitems), first_url(url), first_title(title), first_size(size)
	{}

	int num_items;
	std::string first_url;
	std::string first_title;
	size_type first_size;
};

void test_feed(std::string const& filename, rss_expect const& expect)
{
	std::vector<char> buffer;
	error_code ec;
	load_file(filename, buffer, ec);
	if (ec)
	{
		fprintf(stderr, "failed to load file \"%s\": %s\n", filename.c_str(), ec.message().c_str());
	}
	TEST_CHECK(!ec);

	char* buf = buffer.size() ? &buffer[0] : NULL;
	int len = buffer.size();

	char const header[] = "HTTP/1.1 200 OK\r\n"
		"\r\n";

	boost::shared_ptr<aux::session_impl> s = boost::shared_ptr<aux::session_impl>(new aux::session_impl(
		std::make_pair(100, 200), fingerprint("TT", 0, 0, 0 ,0), NULL, 0));
	s->start_session();

	feed_settings sett;
	sett.auto_download = false;
	sett.auto_map_handles = false;
	boost::shared_ptr<feed> f = boost::shared_ptr<feed>(new feed(*s, sett));
	http_parser parser;
	bool err = false;
	parser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err);
	TEST_CHECK(err == false);

	f->on_feed(error_code(), parser, buf, len);

	feed_status st;
	f->get_feed_status(&st);
	TEST_CHECK(!st.error);

	print_feed(st);

	TEST_CHECK(st.items.size() == expect.num_items);
	if (st.items.size() > 0)
	{
		TEST_CHECK(st.items[0].url == expect.first_url);
		TEST_CHECK(st.items[0].size == expect.first_size);
		TEST_CHECK(st.items[0].title == expect.first_title);
	}

	entry state;
	f->save_state(state);

	fprintf(stderr, "feed_state:\n");
#ifdef TORRENT_DEBUG
	state.print(std::cerr);
#endif

	// TODO: verify some key state is saved in 'state'
}

int test_main()
{
	std::string root_dir = parent_path(current_working_directory());

	test_feed(combine_path(root_dir, "eztv.xml"), rss_expect(30, "http://torrent.zoink.it/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent", "The Daily Show 2012-02-16 [HDTV - LMAO]", 183442338));
	test_feed(combine_path(root_dir, "cb.xml"), rss_expect(50, "http://www.clearbits.net/get/1911-norbergfestival-2011.torrent", "Norbergfestival 2011", 1160773632));
	test_feed(combine_path(root_dir, "kat.xml"), rss_expect(25, "http://kat.ph/torrents/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897/", "Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]", 168773863));
	test_feed(combine_path(root_dir, "mn.xml"), rss_expect(20, "http://www.mininova.org/get/13203100", "Dexcell - January TwentyTwelve Mix", 137311179));
	test_feed(combine_path(root_dir, "pb.xml"), rss_expect(60, "magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D", "Thompson Twins - 1989 - Big Trash [MP3]", 100160904));
	return 0;
}

<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commericial and non commericial applications,
 * as long as this copyright notice is maintained.
 *
 * This application is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/

#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osgProducer/Viewer>
#include <osg/CoordinateSystemNode>

int main( int argc, char **argv )
{

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");

    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // if user request help write it out to cout.
    bool helpAll = arguments.read("--help-all");
    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
    if (helpType)
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    osg::Timer_t start_tick = osg::Timer::instance()->tick();

    // read the scene from the list of file specified command line args.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

    // if no model has been successfully loaded report failure.
    if (!loadedModel)
    {
        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
    }

    osg::Timer_t end_tick = osg::Timer::instance()->tick();

    std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl;

    // optimize the scene graph, remove redundant nodes and state etc.
    osgUtil::Optimizer optimizer;
    optimizer.optimize(loadedModel.get());

    // pass the loaded scene graph to the viewer.
    viewer.setSceneData(loadedModel.get());

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    // run a clean up frame to delete all OpenGL objects.
    viewer.cleanup_frame();

    // wait for all the clean up frame to complete.
    viewer.sync();

    return 0;
}

<commit_msg>tweaked comment.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commericial and non commericial applications,
 * as long as this copyright notice is maintained.
 *
 * This application is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/

#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osgProducer/Viewer>
#include <osg/CoordinateSystemNode>

int main( int argc, char **argv )
{

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");

    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // if user request help write it out to cout.
    bool helpAll = arguments.read("--help-all");
    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
    if (helpType)
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    osg::Timer_t start_tick = osg::Timer::instance()->tick();

    // read the scene from the list of file specified command line args.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

    // if no model has been successfully loaded report failure.
    if (!loadedModel)
    {
        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
    }

    osg::Timer_t end_tick = osg::Timer::instance()->tick();

    std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl;

    // optimize the scene graph, remove redundant nodes and state etc.
    osgUtil::Optimizer optimizer;
    optimizer.optimize(loadedModel.get());

    // pass the loaded scene graph to the viewer.
    viewer.setSceneData(loadedModel.get());

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete.
    viewer.sync();

    // run a clean up frame to delete all OpenGL objects.
    viewer.cleanup_frame();

    // wait for all the clean up frame to complete.
    viewer.sync();

    return 0;
}

<|endoftext|>