/*
 * CFG.h
 *
 * Created on: Sep 27, 2017
 * Author: Jan Travnicek
 */

#ifndef _STRING_CFG_H_
#define _STRING_CFG_H_

#include <grammar/ContextFree/CFG.h>
#include <core/stringApi.hpp>

#include <grammar/GrammarFromStringLexer.h>

#include <grammar/string/common/GrammarFromStringParserCommon.h>
#include <grammar/string/common/GrammarToStringComposerCommon.h>

namespace core {

template < class TerminalSymbolType, class NonterminalSymbolType >
struct stringApi < grammar::CFG < TerminalSymbolType, NonterminalSymbolType > > {
	static grammar::CFG < TerminalSymbolType, NonterminalSymbolType > parse ( std::istream & input );
	static bool first ( std::istream & input );
	static void compose ( std::ostream & output, const grammar::CFG < TerminalSymbolType, NonterminalSymbolType > & grammar );
};

template < class TerminalSymbolType, class NonterminalSymbolType >
grammar::CFG < TerminalSymbolType, NonterminalSymbolType > stringApi < grammar::CFG < TerminalSymbolType, NonterminalSymbolType > >::parse ( std::istream & input ) {
	grammar::GrammarFromStringLexer::Token token = grammar::GrammarFromStringLexer::next(input);
	if(token.type != grammar::GrammarFromStringLexer::TokenType::CFG)
		throw exception::CommonException("Unrecognised CFG token.");

	return grammar::GrammarFromStringParserCommon::parseCFLikeGrammar < grammar::CFG < TerminalSymbolType, NonterminalSymbolType > > ( input );
}

template < class TerminalSymbolType, class NonterminalSymbolType >
bool stringApi < grammar::CFG < TerminalSymbolType, NonterminalSymbolType > >::first ( std::istream & input ) {
	grammar::GrammarFromStringLexer::Token token = grammar::GrammarFromStringLexer::next ( input );
	bool res = token.type == grammar::GrammarFromStringLexer::TokenType::CFG;
	grammar::GrammarFromStringLexer::putback ( input, token );
	return res;
}

template < class TerminalSymbolType, class NonterminalSymbolType >
void stringApi < grammar::CFG < TerminalSymbolType, NonterminalSymbolType > >::compose ( std::ostream & output, const grammar::CFG < TerminalSymbolType, NonterminalSymbolType > & grammar ) {
	output << "CFG";
	grammar::GrammarToStringComposerCommon::composeCFLikeGrammar ( output, grammar );
}

} /* namespace core */

#endif /* _STRING_CFG_H_ */
