#include "stdafx.h"
#include "Unless.h"
#include "Compiler/Exception.h"

namespace storm {
	namespace bs {

		Unless::Unless(Block *parent, Condition *cond, Expr *fail)
			: Expr(cond->pos()), cond(cond), fail(fail) {

			// Make sure that 'fail' does not return:
			if (fail->result() != noReturn())
				throw new (this) SyntaxError(pos, S("The statement inside 'until' must always do a 'return', 'throw', 'break' or 'continue'."));

			// Add the variable to 'parent'. Note that we may have to replace existing variables to
			// not get any multiply defined variables!
			if (LocalVar *var = cond->result()) {
				parent->addReplace(var);
			}
		}

		ExprResult Unless::result() {
			// Noting: We are a statement.
			return ExprResult();
		}

		void Unless::code(CodeGen *state, CodeResult *r) {
			using namespace code;

			Value boolType = StormInfo<Bool>::type(engine());
			CodeResult *ok = new (this) CodeResult(boolType, state->block);
			cond->code(state, ok);

			Label skipLbl = state->l->label();

			*state->l << cmp(ok->location(state), byteConst(0));
			*state->l << jmp(skipLbl, ifNotEqual);

			CodeResult *failResult = new (this) CodeResult();
			fail->code(state, failResult);
			// We have verified that 'failStmt' never returns, no worry about extra jumps!

			// If we skipped 'fail', then we can initialize any new variables and continue.
			*state->l << skipLbl;
			cond->trueCode(state);
		}

		void Unless::toS(StrBuf *to) const {
			*to << S("unless (") << cond << S(") ") << fail << S(";\n");
		}


	}
}
