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

#ifndef _STRING_CNF_H_
#define _STRING_CNF_H_

#include <grammar/ContextFree/CNF.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::CNF < TerminalSymbolType, NonterminalSymbolType > > {
	static grammar::CNF < TerminalSymbolType, NonterminalSymbolType > parse ( std::istream & input );
	static bool first ( std::istream & input );
	static void compose ( std::ostream & output, const grammar::CNF < TerminalSymbolType, NonterminalSymbolType > & grammar );
};

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

	grammar::CNF < TerminalSymbolType, NonterminalSymbolType > grammar = grammar::GrammarFromStringParserCommon::parseCFLikeGrammar < grammar::CNF < 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::CNF < TerminalSymbolType, NonterminalSymbolType > >::first ( std::istream & input ) {
	grammar::GrammarFromStringLexer::Token token = grammar::GrammarFromStringLexer::next ( input );
	bool res = token.type == grammar::GrammarFromStringLexer::TokenType::CNF;
	grammar::GrammarFromStringLexer::putback ( input, token );
	return res;
}

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

} /* namespace core */

#endif /* _STRING_CNF_H_ */
