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

#pragma once

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

#include <grammar/GrammarFromStringLexer.h>

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

#include <grammar/properties/IsFITDefinition.h>
#include <grammar/simplify/MakeFITDefinition.h>

namespace core {

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

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

	grammar::EpsilonFreeCFG < TerminalSymbolType, NonterminalSymbolType > grammar = grammar::GrammarFromStringParserCommon::parseCFLikeGrammar < grammar::EpsilonFreeCFG < TerminalSymbolType, NonterminalSymbolType > > ( input );

	if ( ! grammar::properties::IsFITDefinition::isFITDefinition ( grammar ) )
		throw exception::CommonException("Init on RHS when generate eps");

	return grammar;
}

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

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

} /* namespace core */

