Exemplo n.º 1
0
Value StringParser::expression(SymbolTable* scope, EvalContext& context)
{
	// Create a parser on just this section of the string
	size_t n = str.find('}', pos);

	if(n == string::npos) {
		Error(string("unterminated expression block"),0,0);
		pos = n;
		next();
		return Value();
	}

	string exstr = str.substr(pos, (n-pos));

	Parser parser(exstr);
	parser.SetErrorHandler(this);

	// Parse one expression and evaluate it
	Expression* e = parser.ParseExpression();
	Value result = e->Evaluate(scope, context);

	// Skip the expression block
	pos = n+1;
	next();

	return result;
}
Exemplo n.º 2
0
// Read defintion and graph data, parse and evaluate it
bool AppWindow::UpdateGraph() {
int i;
StringReader *r;
Parser p(new Scanner(r = new StringReader()));
Expression *defs = view->graph->GetDefinitions();
	defs->SetText(program->view->Text());

	ColorMenuItem *c = (ColorMenuItem*)bg_color->FindMarked();
	if (c != NULL) view->graph->bg_color = c->GetColor();
	c = (ColorMenuItem*)axes_color->FindMarked();
	if (c != NULL) view->graph->axes_color = c->GetColor();

	if (!defs->ParseDefs(&p, r)) {
		statusLine->SetText("Syntax error in definitions");
		ShowErrorPosition(program->view, p.GetPos());
		return false;
	}
	
	view->ip->Reset();
	if (!defs->Evaluate(view->ip)) {
		statusLine->SetText("Error interpreting definitions");
		ShowErrorPosition(program->view, 0);
		return false;
	}

	ExprList *g = view->graph->GetGraphExprs();	
	for (i = 0; i <= 5; i++) {
		g->SetText(i, data->gCtrls[i]->Text());
	}

	if (!g->ParseExpr(&p, r, i)) {
		statusLine->SetText("Error parsing expression");
		ShowErrorPosition(data->gCtrls[i]->TextView(), p.GetPos());
		return false;
	}

	if (!g->Evaluate(view->ip, i)) {
		statusLine->SetText("Error evaluating expression");
		ShowErrorPosition(data->gCtrls[i]->TextView(), 0);
		return false;
	}
	return true;
}
Exemplo n.º 3
0
void MethodCallStatement::ExecuteStatement()
{
	if (name=="print"){
			ExpressionList::iterator it = arguments->begin();
			while (it!=arguments->end()){
					Expression* n = *it;
					ResultValue nr = n->Evaluate();
					//Revisar si exite la variable para evitar
					// imprimir muchos errores
					switch (nr.type){
						case Int: cout << nr.value.int_value; break;
						case String: cout << nr.value.string_value; break;
						case Boolean: cout << nr.value.bool_value; break;
						default: cout << "("<<line<<","<<column<<"): Tipo de dato no reconocido." << endl;
					}
					it++;
			}
			cout << endl;
	}
	else
			cout << " Test MethodCallStatement: "<<name<<endl;
	// Valor de retorno lo tiene que guardar en methods[name]

}
Exemplo n.º 4
0
/// For if- and elsif- statements.
void Script::HandleConditional(String line)
{
	// Remove first part until (
	int index = line.Find('(');
	line = line.Part(index);
	/// Use expressions from the MathLib. First parse for functions to provide their values? Or...
	Expression exp;
	List<Variable> allVars = GameVars.GetAllExpressionVariables() + variables;
	exp.functionEvaluators = functionEvaluators; // Set evaluators.
	bool parseOK = exp.ParseExpression(line);
	if (!parseOK)
	{
		std::cout<<"\nParse error in expression "<<line;
		return;
	}
	ExpressionResult res = exp.Evaluate(allVars);
	bool statementTrue = res.GetBool();
	/// If statement is true, sign this row as finished.
	if (statementTrue)
	{
		// Set line finished to true so the actual content will be processed.
		lineFinished = true;
		// Set if-Processed to true so that no elsif- or else- clause will be handled.
		ScriptLevel & latest = stack.Last();
		latest.evaluatedAtLine = currentLine;
	}
	else 
	{
		// Check stuff.
		ScriptLevel & sl = stack.Last();
		int newRow = -1;
		int ifStack = 0;
		// If the statement is not true, find an else or endif block..!
		for (int i = currentLine+1; i < lines.Size(); ++i)
		{
			String l = lines[i];
			if (sl.type == ScriptLevel::WHILE_LOOP)
			{
				if (l.Contains("endwhile"))
				{
					// Jump to next after, as regular stopping on endwhile will reboot the loop
					newRow = i + 1;
					stack.RemoveLast();
					break; 
				}
			}
			if (sl.type == ScriptLevel::IF_CLAUSE)
			{
				if (l.Contains("elsif") || l.Contains("else") || l.Contains("endif"))
				{
					if (ifStack == 0)
					{
						newRow = i; 
						break;
					}
					if (l.Contains("endif"))
						--ifStack;
				}
				else if (l.Contains("if"))
					++ifStack;
			}
		}
		assert(newRow > 0);
		// Process it next iteration.
		currentLine = newRow;
		lineProcessed = false;
		lineFinished = false;
		return;

	}
	if (lineFinished == false)
		assert(false && "Line not finished? Something is missing in the if/else/endif block!");	
}
Exemplo n.º 5
0
void Script::EvaluateLine(String & line)
{
	/// Default line processed once?
	lineProcessed = true;

	line.SetComparisonMode(String::NOT_CASE_SENSITIVE);
	// "80Gray50Alpha.png"
#define DEFAULT_TEXTURE_SOURCE	"black50Alpha.png"
#define DEFAULT_TEXT_SIZE_RATIO	0.3f
	
	/// Some state began, take not of it?
	if (line.Contains("Wait("))
	{
		WaitScript * wait = new WaitScript(line, this);
		wait->SetDeleteOnEnd(true);
		ScriptMan.PlayScript(wait);
	}
	else if (line.StartsWith("Key:"))
	{
		String keyStr = line.Tokenize(":")[1];
		keyStr.RemoveSurroundingWhitespaces();
		int keyCode = GetKeyForString(keyStr);
		assert(keyCode != 0);
		InputMan.KeyDown(MainWindow(), keyCode, false);
		InputMan.KeyUp(MainWindow(), keyCode);
		lineFinished = true;
	}
	else if (line.Contains("PlayScript("))
	{
		List<String> tokens = line.Tokenize("(),");
		// Source of script within the parenthesis.
		String source = tokens[1];
		bool wait = true;
		Script * scriptParent = this;
		if (tokens.Size() >= 3)
		{
			wait = tokens[2].ParseBool();
			if (!wait)
			{
				scriptParent = NULL;
				this->lineFinished = true;
			}
		}
		Script * script = new Script(source, scriptParent);
		script->source = source;
		bool loaded = script->Load();
		assert(loaded);
		ScriptMan.PlayScript(script);
	}
	else if (line == "DisableActiveUI")
	{
		InputMan.DisableActiveUI();
		lineFinished = true;
		uiDisabled = true;
	}
	else if (line == "EnableActiveUI")
	{
		InputMan.EnableActiveUI();
		lineFinished = true;
	}
	else if (line.Contains("PreloadTexturesInDirectory("))
	{
		// Fetch the stuff, do the buff
		String dir = line.Tokenize("()")[1];
		List<String> files;
		int num = GetFilesInDirectory(dir, files);
		for (int i = 0; i < files.Size(); ++i)
		{
			String path = dir + "/" + files[i];
			Texture * tex = TexMan.LoadTexture(path);
			Graphics.QueueMessage(new GMBufferTexture(tex));
		}
		lineFinished = true;
	}
	else if (line.Contains("Begin("))
	{
		String stateBeginning = line.Tokenize("()")[1];
		if (stateBeginning == "Cutscene")
		{
			BeginCutscene();
		}
		lineFinished = true;
	}
	else if (line.Contains("End("))
	{
		String stateEnding = line.Tokenize("()")[1];
		if (stateEnding == "Cutscene")
		{
			EndCutscene();
		}
		lineFinished = true;
	}
	else if (line.Contains("EndScript"))
	{
		// End it.
		scriptState = ENDING;
	}
	else if (line.Contains("EnterGameState("))
	{
		String name = line.Tokenize("()")[1];		
		StateChanger * changer = new StateChanger(line, this);
		ScriptMan.PlayScript(changer);
	}
	else if (line.Contains("FadeTo(") || line.Contains("FadeIn("))
	{
		FadeInEffect * fade = new FadeInEffect(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeInBackground("))
	{
		FadeInBackground * fade = new FadeInBackground(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeOutBackground("))
	{
		FadeOutBackground * fade = new FadeOutBackground(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeOut"))
	{
		FadeOutEffect * fade = new FadeOutEffect(line, this);
		ScriptMan.PlayScript(fade);
	}
	else if (line.Contains("FadeText("))
	{
		FadeTextEffect * text = new FadeTextEffect(line, this);
		ScriptMan.PlayScript(text);
		lineFinished = true;
	}
	else if (line.Contains("PlaySong("))
	{
		// Just play it.
		String song = line.Tokenize("()")[1];
		TrackMan.PlayTrack(song);
		// Line finished straight away.
		lineFinished = true;
	}
	else if (line.Contains("Dialogue")){
		/// If raw string, output it straight away! (should later be queued to some kind of dialogue-manager?)
		if (line.Contains("\"")){
			/// Create dialogue UI and append it to the current UI!
			String text = line.Tokenize("\"")[1];
			std::cout<<"\n"<<text;
			UIButton * dialogue = new UIButton("Dialogue");
			dialogue->exitable = false;
			dialogue->text = text;
			dialogue->activationMessage = "PopFromStack(this)&Remove(this)&ContinueEvent("+this->name+")";
			dialogue->textureSource = DEFAULT_TEXTURE_SOURCE;
			dialogue->textSizeRatio = DEFAULT_TEXT_SIZE_RATIO;
			dialogue->sizeRatioY = 0.3f;
			dialogue->alignmentY = 0.15f;
			dialogue->state |= UIState::DIALOGUE;  // Flag the dialogue-state flag to signify importance!
			Graphics.QueueMessage(new GMAddUI(dialogue, "root"));
			Graphics.QueueMessage(GMPushUI::ToUI("Dialogue", ActiveUI()));
		}
		/// If no quotes, load the specified dialogue-file and begin processing that instead, waiting until it is finished.!
		else {
			/// Give the npc a dialogue?
		//	assert(false);
			// Send it tot he state too, to attach to the appropriate thingymajig.
			Message * message = new Message(line);
			/// Set this event as
			message->scriptOrigin = this;
			MesMan.QueueMessage(message);
			/// Instant thingies.
			lineFinished = true;
		}
	}
	else if (line.Contains("Answer")){
		///  Go to EndAnswers..!
		lineFinished = true;
		for (int i = currentLine; i < lines.Size(); ++i){
			String line = lines[i];
			if (line.Contains("EndAnswers")){
				currentLine = i;
				lineFinished = true;
				return;
			}
		}
		assert(false && "No EndAnswers found? No good, jaow ;___;");
	}
	else if (line.Contains("BeginAlternatives") || line.Contains("BeginQuestion")){
		/// Create dialogue UI and append it to the current UI!
		String text = line.Tokenize("\"")[1];
		std::cout<<"\n"<<text;
		UIElement * dialogue = new UIElement();
		dialogue->exitable = false;
		dialogue->name = "AlternativesDialogue";
	//	dialogue->activationMessage = "Remove(this)&ContinueEvent("+this->name+")";
		dialogue->textureSource = DEFAULT_TEXTURE_SOURCE;
		dialogue->sizeRatioY = 0.3f;
		dialogue->alignmentY = 0.15f;
		dialogue->state |= UIState::DIALOGUE;  // Flag the dialogue-state flag to signify importance!

		UILabel * dialogueText = new UILabel();
		dialogueText->text = text;
		dialogueText->textSizeRatio = DEFAULT_TEXT_SIZE_RATIO;
		dialogueText->sizeRatioX = 0.5f;
		dialogueText->alignmentX = 0.25f;
		dialogue->AddChild(dialogueText);

		UIList * dialogueAnswerList = new UIList();
		dialogueAnswerList->sizeRatioX = 0.5f;
		dialogueAnswerList->alignmentX = 0.75f;
		dialogue->AddChild(dialogueAnswerList);

		int answers = 0;
		List<UIElement*> answerList;
		// Parse and add answers
		for (int i = currentLine+1; i < lines.Size(); ++i){
			String l = lines[i];
			l.SetComparisonMode(String::NOT_CASE_SENSITIVE);
			List<String> tokens = l.Tokenize(" ");
			String token1 = tokens[0];
			token1.SetComparisonMode(String::NOT_CASE_SENSITIVE);

			if (token1 == "text"){
				l.Remove(token1);
				dialogueText->text = l;
				dialogueText->text.RemoveInitialWhitespaces();
				dialogueText->text.Remove("\"");
				dialogueText->text.Remove("\"");
			}
			else if (l.Contains("Answer")){
				++answers;
				UIButton * answerButton = new UIButton();
				answerButton->name = token1;
				l.Remove("Answer");
				l.RemoveInitialWhitespaces();
				l.Remove("\"");
				l.Remove("\"");
				answerButton->textureSource = DEFAULT_TEXTURE_SOURCE;
				answerButton->text = l;
				answerButton->sizeRatioY = 0.2f;
				answerButton->activationMessage = "ActivateDialogueAlternative("+name+","+answerButton->name+")&PopFromStack("+dialogue->name+")&Remove("+dialogue->name+")";
				answerList.Add(answerButton);
			}
			else if (l.Contains("EndAlternatives")){
				// Donelir. o-o
				break;
			}
			else {
				assert(false && "Bad line! Should only be Answer before EndAlternatives!");
			}
		}
		assert(answers);
		float sizeRatioY = 0.95f / answers;
		for (int i = 0; i < answers; ++i){
			UIElement * ans = answerList[i];
		//	ans->sizeRatioY = sizeRatioY; // Stupid to set the sizeRatioY to be this dynamic, yo.
			dialogueAnswerList->AddChild(ans);
		}
		isInAlternativeDialogue = true;
		Graphics.QueueMessage(new GMAddUI(dialogue, "root"));
		Graphics.QueueMessage(GMPushUI::ToUI(dialogue, ActiveUI()));
	}
	else if (line.Contains("elsif") || line.Contains("elseif") || line.Contains("else if"))
	{
		/// Should be in an if-stack, check if we already evaluated.
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::IF_CLAUSE);
		/// If already evaluated, jump to endif.
		if (sl.evaluatedAtLine > 0)
		{
			// Jump to endif.
			JumpToEndif();
			return;
		}
		/// If not, handle the conditional first.
		HandleConditional(line);
	}
	else if (line.Contains("if(") || line.Contains("if ("))
	{
		// Add to stack.
		stack.AddItem(ScriptLevel(ScriptLevel::IF_CLAUSE, currentLine));
		HandleConditional(line);
	}
	else if (line.Contains("else"))
	{
//		if (ifProcessed)
		//	JumpToEndif();
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::IF_CLAUSE);
		if (sl.evaluatedAtLine > 0)
		{
			JumpToEndif();
			return;
		}
		lineFinished = true;
		return;
	}
	else if (line.Contains("endif"))
	{
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::IF_CLAUSE);
		stack.RemoveLast();
		lineFinished = true;
	}
	else if (line.Contains("endwhile"))
	{
		// Go to start!
		ScriptLevel sl = stack.Last();
		assert(sl.type == ScriptLevel::WHILE_LOOP);
		currentLine = sl.evaluatedAtLine;
		String startLine = lines[currentLine];
		HandleConditional(startLine);
//		lineFinished = true;
		// Evaluate?
//		stack.RemoveLast();
	}
	else if (line.Contains("while"))
	{
		stack.AddItem(ScriptLevel(ScriptLevel::WHILE_LOOP, currentLine));
		HandleConditional(line);
	}
/*	else if (line.Contains("CreateInt")){
		List<String> tokens = line.Tokenize(" \t");
		String varName = tokens[1];
		int initialValue = 0;
		if (tokens.Size() >= 3)
			initialValue = tokens[2].ParseInt();
		if (!GameVars.Get(varName)){
			GameVars.CreateInt(varName, initialValue);
		}
		lineFinished = true;
	}
	/*
	else if (line.Contains("SetInt ")){
		List<String> tokens = line.Tokenize(" \t");
		String varName = tokens[1];
		int value = tokens[2].ParseInt();
		GameVars.SetInt(varName, value);
		lineFinished = true;
	}*/
	else if (line.Contains("Repeatable")){
		/// Flag the event as repeatable.
		repeatable = true;
		lineFinished = true;
	}
	// Consider just making an else-clause for all remaining events to be processed by the specific game instead?
	else if (
		line.Contains("SpawnEntity") ||
		line.Contains("OnApproach") ||
		line.Contains("OnInteract") ||
		line.Contains("DisableMovement") ||
		line.Contains("EnableMovement") ||
		line.Contains("Zone(") ||
		line.Contains("PlacePlayer(") ||
		line.Contains("TrackPlayer")
		)
	{
		Message * message = new Message(line);
		/// Set this event as
		message->scriptOrigin = this;
		MesMan.QueueMessage(message);
		/// Instant thingies.
		lineFinished = true;
	}
	else {
		/// Try evaluate it as an expression.
		Expression exp;
		List<Variable> allVars = GameVars.GetAllExpressionVariables() + variables;
		exp.functionEvaluators = functionEvaluators; // Set evaluators.
		bool parseOK = exp.ParseExpression(line);
		if (line.Contains("SetMovementPattern"))
			int p = 4;;
		if (parseOK)
		{
			ExpressionResult res = exp.Evaluate(allVars);
			/// Continue until it returns true! o.o
			if (res.type != DataType::NO_TYPE)
			{
				if (res.GetBool() == true)
				{
					lineFinished = true;
					return;
				}
			}
		}


//		std::cout<<"\nUndefined event command: "<<line;
//		std::cout<<"\nPassing it as a custom command to the game states for further processing.";
		Message * message = new Message(line);
		/// Set this event as source of it.
		message->scriptOrigin = this;
		MesMan.QueueMessage(message);
		lineFinished = true;
	//	assert(false && "Undefined event command!");
	};
}
Exemplo n.º 6
0
bool ConsoleHandler::ExecuteScriptHelper(HttpRequest& request, HttpResponse& response,
    const String& command, const String& session, bool sandboxed)
{
	Log(LogInformation, "Console")
	    << "Executing expression: " << command;

	ApiScriptFrame& lsf = l_ApiScriptFrames[session];
	lsf.Seen = Utility::GetTime();

	if (!lsf.Locals)
		lsf.Locals = new Dictionary();

	String fileName = "<" + Convert::ToString(lsf.NextLine) + ">";
	lsf.NextLine++;

	lsf.Lines[fileName] = command;

	Array::Ptr results = new Array();
	Dictionary::Ptr resultInfo = new Dictionary();
	Expression *expr = NULL;
	Value exprResult;

	try {
		expr = ConfigCompiler::CompileText(fileName, command);

		ScriptFrame frame;
		frame.Locals = lsf.Locals;
		frame.Self = lsf.Locals;
		frame.Sandboxed = sandboxed;

		exprResult = expr->Evaluate(frame);

		resultInfo->Set("code", 200);
		resultInfo->Set("status", "Executed successfully.");
		resultInfo->Set("result", Serialize(exprResult, 0));
	} catch (const ScriptError& ex) {
		DebugInfo di = ex.GetDebugInfo();

		std::ostringstream msgbuf;

		msgbuf << di.Path << ": " << lsf.Lines[di.Path] << "\n"
		    << String(di.Path.GetLength() + 2, ' ')
		    << String(di.FirstColumn, ' ') << String(di.LastColumn - di.FirstColumn + 1, '^') << "\n"
		    << ex.what() << "\n";

		resultInfo->Set("code", 500);
		resultInfo->Set("status", String(msgbuf.str()));
		resultInfo->Set("incomplete_expression", ex.IsIncompleteExpression());

		Dictionary::Ptr debugInfo = new Dictionary();
		debugInfo->Set("path", di.Path);
		debugInfo->Set("first_line", di.FirstLine);
		debugInfo->Set("first_column", di.FirstColumn);
		debugInfo->Set("last_line", di.LastLine);
		debugInfo->Set("last_column", di.LastColumn);
		resultInfo->Set("debug_info", debugInfo);
	} catch (...) {
		delete expr;
		throw;
	}
	delete expr;

	results->Add(resultInfo);

	Dictionary::Ptr result = new Dictionary();
	result->Set("results", results);

	response.SetStatus(200, "OK");
	HttpUtility::SendJsonBody(response, result);

	return true;
}
Exemplo n.º 7
0
bool ConfigObjectUtility::CreateObject(const Type::Ptr& type, const String& fullName,
    const String& config, const Array::Ptr& errors)
{
	if (!ConfigPackageUtility::PackageExists("_api")) {
		ConfigPackageUtility::CreatePackage("_api");

		String stage = ConfigPackageUtility::CreateStage("_api");
		ConfigPackageUtility::ActivateStage("_api", stage);
	}

	String path = GetObjectConfigPath(type, fullName);
	Utility::MkDirP(Utility::DirName(path), 0700);

	if (Utility::PathExists(path)) {
		errors->Add("Configuration file '" + path + "' already exists.");
		return false;
	}

	std::ofstream fp(path.CStr(), std::ofstream::out | std::ostream::trunc);
	fp << config;
	fp.close();

	Expression *expr = ConfigCompiler::CompileFile(path, String(), "_api");

	try {
		ActivationScope ascope;

		ScriptFrame frame;
		expr->Evaluate(frame);
		delete expr;
		expr = NULL;

		WorkQueue upq;
		std::vector<ConfigItem::Ptr> newItems;

		if (!ConfigItem::CommitItems(ascope.GetContext(), upq, newItems) || !ConfigItem::ActivateItems(upq, newItems, true)) {
			if (errors) {
				if (unlink(path.CStr()) < 0 && errno != ENOENT) {
					BOOST_THROW_EXCEPTION(posix_error()
					    << boost::errinfo_api_function("unlink")
					    << boost::errinfo_errno(errno)
					    << boost::errinfo_file_name(path));
				}

				for (const boost::exception_ptr& ex : upq.GetExceptions()) {
					errors->Add(DiagnosticInformation(ex));
				}
			}

			return false;
		}

		ApiListener::UpdateObjectAuthority();
	} catch (const std::exception& ex) {
		delete expr;

		if (unlink(path.CStr()) < 0 && errno != ENOENT) {
			BOOST_THROW_EXCEPTION(posix_error()
			    << boost::errinfo_api_function("unlink")
			    << boost::errinfo_errno(errno)
			    << boost::errinfo_file_name(path));
		}

		if (errors)
			errors->Add(DiagnosticInformation(ex));

		return false;
	}

	return true;
}
Exemplo n.º 8
0
ExpressionResult IncludeExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	if (frame.Sandboxed)
		BOOST_THROW_EXCEPTION(ScriptError("Includes are not allowed in sandbox mode.", m_DebugInfo));

	Expression *expr;
	String name, path, pattern;

	switch (m_Type) {
		case IncludeRegular:
			{
				ExpressionResult pathres = m_Path->Evaluate(frame, dhint);
				CHECK_RESULT(pathres);
				path = pathres.GetValue();
			}

			expr = ConfigCompiler::HandleInclude(m_RelativeBase, path, m_SearchIncludes, m_Zone, m_Package, m_DebugInfo);
			break;

		case IncludeRecursive:
			{
				ExpressionResult pathres = m_Path->Evaluate(frame, dhint);
				CHECK_RESULT(pathres);
				path = pathres.GetValue();
			}

			{
				ExpressionResult patternres = m_Pattern->Evaluate(frame, dhint);
				CHECK_RESULT(patternres);
				pattern = patternres.GetValue();
			}

			expr = ConfigCompiler::HandleIncludeRecursive(m_RelativeBase, path, pattern, m_Zone, m_Package, m_DebugInfo);
			break;

		case IncludeZones:
			{
				ExpressionResult nameres = m_Name->Evaluate(frame, dhint);
				CHECK_RESULT(nameres);
				name = nameres.GetValue();
			}

			{
				ExpressionResult pathres = m_Path->Evaluate(frame, dhint);
				CHECK_RESULT(pathres);
				path = pathres.GetValue();
			}

			{
				ExpressionResult patternres = m_Pattern->Evaluate(frame, dhint);
				CHECK_RESULT(patternres);
				pattern = patternres.GetValue();
			}

			expr = ConfigCompiler::HandleIncludeZones(m_RelativeBase, name, path, pattern, m_Package, m_DebugInfo);
			break;
	}

	ExpressionResult res(Empty);

	try {
		res = expr->Evaluate(frame, dhint);
	} catch (const std::exception&) {
		delete expr;
		throw;
	}

	delete expr;

	return res;
}
Exemplo n.º 9
0
int Main(void)
{
	int argc = Application::GetArgC();
	char **argv = Application::GetArgV();

	bool autocomplete = false;
	int autoindex = 0;

	if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
		autocomplete = true;

		try {
			autoindex = Convert::ToLong(argv[2]);
		} catch (const std::invalid_argument& ex) {
			Log(LogCritical, "icinga-app")
			    << "Invalid index for --autocomplete: " << argv[2];
			return EXIT_FAILURE;
		}

		argc -= 3;
		argv += 3;
	}

	Application::SetStartTime(Utility::GetTime());

	if (!autocomplete)
		Application::SetResourceLimits();

	/* Set thread title. */
	Utility::SetThreadName("Main Thread", false);

	/* Install exception handlers to make debugging easier. */
	Application::InstallExceptionHandlers();

#ifdef _WIN32
	bool builtinPaths = true;

	HKEY hKey;
	if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Icinga Development Team\\ICINGA2", 0,
	    KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
		BYTE pvData[MAX_PATH];
		DWORD cbData = sizeof(pvData)-1;
		DWORD lType;
		if (RegQueryValueEx(hKey, NULL, NULL, &lType, pvData, &cbData) == ERROR_SUCCESS && lType == REG_SZ) {
			pvData[cbData] = '\0';

			String prefix = (char *)pvData;
			Application::DeclarePrefixDir(prefix);
			Application::DeclareSysconfDir(prefix + "\\etc");
			Application::DeclareRunDir(prefix + "\\var\\run");
			Application::DeclareLocalStateDir(prefix + "\\var");
			Application::DeclarePkgDataDir(prefix + "\\share\\icinga2");
			Application::DeclareIncludeConfDir(prefix + "\\share\\icinga2\\include");

			builtinPaths = false;
		}

		RegCloseKey(hKey);
	}

	if (builtinPaths) {
		Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");

#endif /* _WIN32 */
		Application::DeclarePrefixDir(ICINGA_PREFIX);
		Application::DeclareSysconfDir(ICINGA_SYSCONFDIR);
		Application::DeclareRunDir(ICINGA_RUNDIR);
		Application::DeclareLocalStateDir(ICINGA_LOCALSTATEDIR);
		Application::DeclarePkgDataDir(ICINGA_PKGDATADIR);
		Application::DeclareIncludeConfDir(ICINGA_INCLUDECONFDIR);
#ifdef _WIN32
	}
#endif /* _WIN32 */

	Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
	Application::DeclareRunAsUser(ICINGA_USER);
	Application::DeclareRunAsGroup(ICINGA_GROUP);
	Application::DeclareConcurrency(boost::thread::hardware_concurrency());

	if (!ScriptGlobal::Exists("UseVfork"))
#ifdef __APPLE__
		ScriptGlobal::Set("UseVfork", false);
#else /* __APPLE__ */
		ScriptGlobal::Set("UseVfork", true);
#endif /* __APPLE__ */

	ScriptGlobal::Set("AttachDebugger", false);

	LogSeverity logLevel = Logger::GetConsoleLogSeverity();
	Logger::SetConsoleLogSeverity(LogWarning);

	Loader::LoadExtensionLibrary("cli");

	po::options_description visibleDesc("Global options");

	visibleDesc.add_options()
		("help,h", "show this help message")
		("version,V", "show version information")
#ifndef _WIN32
		("color", "use VT100 color codes even when stdout is not a terminal")
#endif /* _WIN32 */
		("define,D", po::value<std::vector<std::string> >(), "define a constant")
		("app,a", po::value<std::string>(), "application library name (default: icinga)")
		("library,l", po::value<std::vector<std::string> >(), "load a library")
		("include,I", po::value<std::vector<std::string> >(), "add include search directory")
		("log-level,x", po::value<std::string>(), "specify the log level for the console log");

	po::options_description hiddenDesc("Hidden options");

	hiddenDesc.add_options()
#ifndef _WIN32
		("no-stack-rlimit", "used internally, do not specify manually")
#else /* _WIN32 */
		("no-stack-rlimit", "used internally, do not specify manually")
#endif /* _WIN32 */
		("arg", po::value<std::vector<std::string> >(), "positional argument");

	po::positional_options_description positionalDesc;
	positionalDesc.add("arg", -1);

	String cmdname;
	CLICommand::Ptr command;
	po::variables_map vm;

	try {
		CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
		    vm, cmdname, command, autocomplete);
	} catch (const std::exception& ex) {
		Log(LogCritical, "icinga-app")
		    << "Error while parsing command-line options: " << ex.what();
		return EXIT_FAILURE;
	}

	String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";

	if (Utility::PathExists(initconfig)) {
		Expression *expression;
		try {
			expression = ConfigCompiler::CompileFile(initconfig);

			ScriptFrame frame;
			expression->Evaluate(frame);
		} catch (const std::exception& ex) {
			delete expression;

			Log(LogCritical, "config", DiagnosticInformation(ex));
			return EXIT_FAILURE;
		}

		delete expression;
	}

#ifndef _WIN32
	if (vm.count("color")) {
		Console::SetType(std::cout, Console_VT100);
		Console::SetType(std::cerr, Console_VT100);
	}
#endif /* _WIN32 */

	if (vm.count("define")) {
		BOOST_FOREACH(const String& define, vm["define"].as<std::vector<std::string> >()) {
			String key, value;
			size_t pos = define.FindFirstOf('=');
			if (pos != String::NPos) {
				key = define.SubStr(0, pos);
				value = define.SubStr(pos + 1);
			} else {
				key = define;
				value = "1";
			}
			ScriptGlobal::Set(key, value);
		}
	}