/*----------------------------------------------------------------------
Compiler Generator Coco/R,
Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz
extended by M. Loeberbauer & A. Woess, Univ. of Linz
ported to C++ by Csaba Balazs, University of Szeged
with improvements by Pat Terry, Rhodes University

This program is free software; you can redistribute it and/or modify it 
under the terms of the GNU General Public License as published by the 
Free Software Foundation; either version 2, or (at your option) any 
later version.

This program 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.  See the GNU General Public License 
for more details.

You should have received a copy of the GNU General Public License along 
with this program; if not, write to the Free Software Foundation, Inc., 
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

As an exception, it is allowed to write an extension of Coco/R that is
used as a plugin in non-free software.

If not otherwise stated, any source code generated by Coco/R (other than 
Coco/R itself) does not fall under the GNU General Public License.
-----------------------------------------------------------------------*/


#include <wchar.h>
#include "Parser.h"
#include "Scanner.h"




void Parser::SynErr(int n) {
	if (errDist >= minErrDist) errors->SynErr(la->line, la->col, n);
	errDist = 0;
}

void Parser::SemErr(const wchar_t* msg) {
	if (errDist >= minErrDist) errors->Error(t->line, t->col, msg);
	errDist = 0;
}

void Parser::Get() {
	for (;;) {
		t = la;
		la = scanner->Scan();
		if (la->kind <= maxT) { ++errDist; break; }

		if (dummyToken != t) {
			dummyToken->kind = t->kind;
			dummyToken->pos = t->pos;
			dummyToken->col = t->col;
			dummyToken->line = t->line;
			dummyToken->next = NULL;
			coco_string_delete(dummyToken->val);
			dummyToken->val = coco_string_create(t->val);
			t = dummyToken;
		}
		la = t;
	}
}

void Parser::Expect(int n) {
	if (la->kind==n) Get(); else { SynErr(n); }
}

void Parser::ExpectWeak(int n, int follow) {
	if (la->kind == n) Get();
	else {
		SynErr(n);
		while (!StartOf(follow)) Get();
	}
}

bool Parser::WeakSeparator(int n, int syFol, int repFol) {
	if (la->kind == n) {Get(); return true;}
	else if (StartOf(repFol)) {return false;}
	else {
		SynErr(n);
		while (!(StartOf(syFol) || StartOf(repFol) || StartOf(0))) {
			Get();
		}
		return StartOf(syFol);
	}
}

void Parser::Xreate() {
		while (la->kind == 1) {
			FDecl();
		}
}

void Parser::FDecl() {
		std::wstring fname; Expression fbody; std::wstring varname; TypeAnnotation typIn; TypeAnnotation typOut; 
		Ident(fname);
		Expect(4);
		Expect(5);
		Expect(6);
		Function f = Function(fname); 
		if (StartOf(1)) {
			Type(typOut);
			f.setReturnType(typOut); 
		} else if (la->kind == 7) {
			Get();
			Ident(varname);
			Expect(6);
			Type(typIn);
			f.addArg(varname, typIn); 
			while (la->kind == 8) {
				Get();
				Ident(varname);
				Expect(6);
				Type(typIn);
				f.addArg(varname, typIn);
			}
			Expect(9);
		} else SynErr(28);
		Expect(10);
		while (la->kind == 1) {
			VDecl(f);
			Expect(11);
		}
		Expr(fbody);
		Expect(12);
		f.setBody(fbody); 
}

void Parser::Ident(std::wstring& name) {
		Expect(1);
		name = t->val; 
}

void Parser::Type(TypeAnnotation& typ) {
		TypeAnnotation typ2; TypeAtom typ3; 
		if (la->kind == 18) {
			Get();
			Type(typ2);
			Expect(19);
			typ = TypeAnnotation(TypeOperator::LIST, typ2); 
		} else if (StartOf(2)) {
			TypeTerm(typ3);
			typ = TypeAnnotation(typ3); 
		} else SynErr(29);
}

void Parser::VDecl(Function& f) {
		std::wstring vname; Expression e; TypeAnnotation typ; 
		Ident(vname);
		Expect(4);
		if (la->kind == 1 || la->kind == 2 || la->kind == 20) {
			Expr(e);
			Expect(6);
			Type(typ);
			f.addDeclaration(vname, typ, e); 
		} else if (la->kind == 18) {
			ListLiteral(e);
			Expect(6);
			Type(typ);
			f.addListDeclaration(vname, typ, e); 
		} else SynErr(30);
		Expect(11);
}

void Parser::Expr(Expression& e) {
		Operator op; Expression e2; 
		SimExpr(e);
		if (la->kind == 24 || la->kind == 25 || la->kind == 26) {
			RelOp(op);
			SimExpr(e2);
			Expression e (op, e);
			e.addArg(e2);
			
		}
}

void Parser::TypeTerm(TypeAtom& typ) {
		if (la->kind == 13) {
			Get();
		} else if (la->kind == 14) {
			Get();
		} else if (la->kind == 15) {
			Get();
		} else if (la->kind == 16) {
			Get();
		} else if (la->kind == 17) {
			Get();
		} else SynErr(31);
		typ = Atom<Type_t>(t->val); 
}

void Parser::ListLiteral(Expression& e) {
		Expression e2; 
		Expect(18);
		if (la->kind == 19) {
			Get();
			Expect(11);
			e = Expression(Operator::LIST, Expression()); 
		} else if (la->kind == 1 || la->kind == 2 || la->kind == 20) {
			Expr(e2);
			e = Expression(Operator::LIST, e2); 
			while (la->kind == 8) {
				Get();
				Expr(e2);
				e.addArg(e2); 
			}
			Expect(19);
			Expect(11);
		} else SynErr(32);
}

void Parser::SimExpr(Expression& e) {
		Operator op; Expression e2; 
		Term(e);
		while (la->kind == 20 || la->kind == 21) {
			AddOp(op);
			Term(e2);
			e = Expression(op, e);
			e.addArg(e2);
			
		}
}

void Parser::RelOp(Operator& op) {
		op = Operator::EQU; 
		if (la->kind == 24) {
			Get();
		} else if (la->kind == 25) {
			Get();
			op = Operator::LSS; 
		} else if (la->kind == 26) {
			Get();
			op = Operator::GTR; 
		} else SynErr(33);
}

void Parser::Term(Expression& e) {
		Operator op; Expression e2; 
		Factor(e);
		while (la->kind == 22 || la->kind == 23) {
			MulOp(op);
			Factor(e2);
			e = Expression(op, e);
			e.addArg(e2);
			
		}
}

void Parser::AddOp(Operator& op) {
		op = Operator::ADD; 
		if (la->kind == 21) {
			Get();
		} else if (la->kind == 20) {
			Get();
			op = Operator::SUB; 
		} else SynErr(34);
}

void Parser::Factor(Expression& e) {
		std::wstring name; 
		if (la->kind == 1) {
			Ident(name);
			e = Expression(Atom<Identifier_t>(name)); 
		} else if (la->kind == 2) {
			Get();
			e = Expression(Atom<Number_t>(t->val)); 
		} else if (la->kind == 20) {
			Get();
			Factor(e);
			e = Expression(Operator::NEG, e); 
		} else SynErr(35);
}

void Parser::MulOp(Operator& op) {
		op = Operator::MUL; 
		if (la->kind == 22) {
			Get();
		} else if (la->kind == 23) {
			Get();
			op = Operator::DIV; 
		} else SynErr(36);
}




// If the user declared a method Init and a mehtod Destroy they should
// be called in the contructur and the destructor respctively.
//
// The following templates are used to recognize if the user declared
// the methods Init and Destroy.

template<typename T>
struct ParserInitExistsRecognizer {
	template<typename U, void (U::*)() = &U::Init>
	struct ExistsIfInitIsDefinedMarker{};

	struct InitIsMissingType {
		char dummy1;
	};
	
	struct InitExistsType {
		char dummy1; char dummy2;
	};

	// exists always
	template<typename U>
	static InitIsMissingType is_here(...);

	// exist only if ExistsIfInitIsDefinedMarker is defined
	template<typename U>
	static InitExistsType is_here(ExistsIfInitIsDefinedMarker<U>*);

	enum { InitExists = (sizeof(is_here<T>(NULL)) == sizeof(InitExistsType)) };
};

template<typename T>
struct ParserDestroyExistsRecognizer {
	template<typename U, void (U::*)() = &U::Destroy>
	struct ExistsIfDestroyIsDefinedMarker{};

	struct DestroyIsMissingType {
		char dummy1;
	};
	
	struct DestroyExistsType {
		char dummy1; char dummy2;
	};

	// exists always
	template<typename U>
	static DestroyIsMissingType is_here(...);

	// exist only if ExistsIfDestroyIsDefinedMarker is defined
	template<typename U>
	static DestroyExistsType is_here(ExistsIfDestroyIsDefinedMarker<U>*);

	enum { DestroyExists = (sizeof(is_here<T>(NULL)) == sizeof(DestroyExistsType)) };
};

// The folloing templates are used to call the Init and Destroy methods if they exist.

// Generic case of the ParserInitCaller, gets used if the Init method is missing
template<typename T, bool = ParserInitExistsRecognizer<T>::InitExists>
struct ParserInitCaller {
	static void CallInit(T *t) {
		// nothing to do
	}
};

// True case of the ParserInitCaller, gets used if the Init method exists
template<typename T>
struct ParserInitCaller<T, true> {
	static void CallInit(T *t) {
		t->Init();
	}
};

// Generic case of the ParserDestroyCaller, gets used if the Destroy method is missing
template<typename T, bool = ParserDestroyExistsRecognizer<T>::DestroyExists>
struct ParserDestroyCaller {
	static void CallDestroy(T *t) {
		// nothing to do
	}
};

// True case of the ParserDestroyCaller, gets used if the Destroy method exists
template<typename T>
struct ParserDestroyCaller<T, true> {
	static void CallDestroy(T *t) {
		t->Destroy();
	}
};

void Parser::Parse() {
	t = NULL;
	la = dummyToken = new Token();
	la->val = coco_string_create(L"Dummy Token");
	Get();
	Xreate();
	Expect(0);
}

Parser::Parser(Scanner *scanner) {
	maxT = 27;

	ParserInitCaller<Parser>::CallInit(this);
	dummyToken = NULL;
	t = la = NULL;
	minErrDist = 2;
	errDist = minErrDist;
	this->scanner = scanner;
	errors = new Errors();
}

bool Parser::StartOf(int s) {
	const bool T = true;
	const bool x = false;

	static bool set[3][29] = {
		{T,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x,x,x,x, x},
		{x,x,x,x, x,x,x,x, x,x,x,x, x,T,T,T, T,T,T,x, x,x,x,x, x,x,x,x, x},
		{x,x,x,x, x,x,x,x, x,x,x,x, x,T,T,T, T,T,x,x, x,x,x,x, x,x,x,x, x}
	};



	return set[s][la->kind];
}

Parser::~Parser() {
	ParserDestroyCaller<Parser>::CallDestroy(this);
	delete errors;
	delete dummyToken;
}

Errors::Errors() {
	count = 0;
}

void Errors::SynErr(int line, int col, int n) {
	wchar_t* s;
	switch (n) {
			case 0: s = coco_string_create(L"EOF expected"); break;
			case 1: s = coco_string_create(L"ident expected"); break;
			case 2: s = coco_string_create(L"number expected"); break;
			case 3: s = coco_string_create(L"string expected"); break;
			case 4: s = coco_string_create(L"\"=\" expected"); break;
			case 5: s = coco_string_create(L"\"function\" expected"); break;
			case 6: s = coco_string_create(L"\":\" expected"); break;
			case 7: s = coco_string_create(L"\"(\" expected"); break;
			case 8: s = coco_string_create(L"\",\" expected"); break;
			case 9: s = coco_string_create(L"\")\" expected"); break;
			case 10: s = coco_string_create(L"\"{\" expected"); break;
			case 11: s = coco_string_create(L"\";\" expected"); break;
			case 12: s = coco_string_create(L"\"}\" expected"); break;
			case 13: s = coco_string_create(L"\"string\" expected"); break;
			case 14: s = coco_string_create(L"\"int\" expected"); break;
			case 15: s = coco_string_create(L"\"num\" expected"); break;
			case 16: s = coco_string_create(L"\"float\" expected"); break;
			case 17: s = coco_string_create(L"\"bool\" expected"); break;
			case 18: s = coco_string_create(L"\"[\" expected"); break;
			case 19: s = coco_string_create(L"\"]\" expected"); break;
			case 20: s = coco_string_create(L"\"-\" expected"); break;
			case 21: s = coco_string_create(L"\"+\" expected"); break;
			case 22: s = coco_string_create(L"\"*\" expected"); break;
			case 23: s = coco_string_create(L"\"/\" expected"); break;
			case 24: s = coco_string_create(L"\"==\" expected"); break;
			case 25: s = coco_string_create(L"\"<\" expected"); break;
			case 26: s = coco_string_create(L"\">\" expected"); break;
			case 27: s = coco_string_create(L"??? expected"); break;
			case 28: s = coco_string_create(L"invalid FDecl"); break;
			case 29: s = coco_string_create(L"invalid Type"); break;
			case 30: s = coco_string_create(L"invalid VDecl"); break;
			case 31: s = coco_string_create(L"invalid TypeTerm"); break;
			case 32: s = coco_string_create(L"invalid ListLiteral"); break;
			case 33: s = coco_string_create(L"invalid RelOp"); break;
			case 34: s = coco_string_create(L"invalid AddOp"); break;
			case 35: s = coco_string_create(L"invalid Factor"); break;
			case 36: s = coco_string_create(L"invalid MulOp"); break;

		default:
		{
			wchar_t format[20];
			coco_swprintf(format, 20, L"error %d", n);
			s = coco_string_create(format);
		}
		break;
	}
	wprintf(L"-- line %d col %d: %ls\n", line, col, s);
	coco_string_delete(s);
	count++;
}

void Errors::Error(int line, int col, const wchar_t *s) {
	wprintf(L"-- line %d col %d: %ls\n", line, col, s);
	count++;
}

void Errors::Warning(int line, int col, const wchar_t *s) {
	wprintf(L"-- line %d col %d: %ls\n", line, col, s);
}

void Errors::Warning(const wchar_t *s) {
	wprintf(L"%ls\n", s);
}

void Errors::Exception(const wchar_t* s) {
	wprintf(L"%ls", s); 
	exit(1);
}


