/*
 * NonContractingGrammar.h
 *
 * This file is part of Algorithms library toolkit.
 * Copyright (C) 2017 Jan Travnicek (jan.travnicek@fit.cvut.cz)

 * Algorithms library toolkit 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 3 of the License, or
 * (at your option) any later version.

 * Algorithms library toolkit 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 Algorithms library toolkit.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  Created on: Nov 17, 2013
 *      Author: Jan Travnicek
 */

#ifndef NON_CONTRACTING_GRAMMAR_H_
#define NON_CONTRACTING_GRAMMAR_H_

#include <sstream>

#include <alib/map>
#include <alib/set>
#include <alib/vector>
#include <alib/algorithm>
#include <alib/compare>

#include <core/components.hpp>

#include <common/DefaultSymbolType.h>

#include <grammar/GrammarException.h>

#include <core/normalize.hpp>
#include <alphabet/common/SymbolNormalize.h>
#include <grammar/common/GrammarNormalize.h>

namespace grammar {

class TerminalAlphabet;
class NonterminalAlphabet;
class InitialSymbol;

/**
 * \brief
 * Noncontracting grammar in Chomsky hierarchy or type 1 in Chomsky hierarchy. Generates context sensitive languages.

 * \details
 * Definition is similar to all common definitions of context sensitive grammars.
 * G = (N, T, P, S),
 * N (NonterminalAlphabet) = nonempty finite set of nonterminal symbols,
 * T (TerminalAlphabet) = finite set of terminal symbols - having this empty won't let grammar do much though,
 * P = set of production rules of the form A -> B, where A, B \in ( N \cup T )+ and |A| <= |B|,
 * S (InitialSymbol) = initial nonterminal symbol,
 *
 * \tparam SymbolType used for the terminal alphabet, the nonterminal alphabet, and the initial symbol of the grammar.
 */
template < class SymbolType = DefaultSymbolType >
class NonContractingGrammar final : public ext::CompareOperators < NonContractingGrammar < SymbolType > >, public core::Components < NonContractingGrammar < SymbolType >, ext::set < SymbolType >, component::Set, std::tuple < TerminalAlphabet, NonterminalAlphabet >, SymbolType, component::Value, InitialSymbol > {
	/**
	 * Rules function as mapping from nonterminal symbol on the left hand side to a set of sequences of terminal and nonterminal symbols.
	 */
	ext::map < ext::vector < SymbolType >, ext::set < ext::vector < SymbolType > > > rules;

	/**
	 * Boolean signaling whether grammar generates empty string or don't.
	 */
	bool generatesEpsilon;

public:
	/**
	 * \brief Creates a new instance of the grammar with a concrete initial symbol.
	 *
	 * \param initialSymbol the initial symbol of the grammar
	 */
	explicit NonContractingGrammar ( SymbolType initialSymbol );

	/**
	 * \brief Creates a new instance of the grammar with a concrete nonterminal alphabet, terminal alphabet and initial symbol.
	 *
	 * \param nonTerminalSymbols the initial nonterminal alphabet
	 * \param terminalSymbols the initial terminal alphabet
	 * \param initialSymbol the initial symbol of the grammar
	 */
	explicit NonContractingGrammar ( ext::set < SymbolType > nonterminalAlphabet, ext::set < SymbolType > terminalAlphabet, SymbolType initialSymbol );

	/**
	 * \brief Add a new rule of a grammar.
	 *
	 * \details The rule is in a form of A -> B, where A, B \in ( N \cup T )+, and |A| <= |B|.
	 *
	 * \param leftHandSide the left hand side of the rule
	 * \param rightHandSide the right hand side of the rule
	 *
	 * \returns true if the rule was indeed added, false othervise
	 */
	bool addRule ( ext::vector < SymbolType > leftHandSide, ext::vector < SymbolType > rightHandSide );

	/**
	 * \brief Add new rules of a grammar.
	 *
	 * \details The rules are in form of A -> B | C | ..., where A, B, C ... \in ( N \cup T )+, and |A| <= |B|.
	 *
	 * \param leftHandSide the left hand side of the rule
	 * \param rightHandSide a set of right hand sides of the rule
	 */
	void addRules ( ext::vector < SymbolType > leftHandSide, ext::set < ext::vector < SymbolType > > rightHandSide );

	/**
	 * Get rules of the grammar.
	 *
	 * \returns rules of the grammar
	 */
	const ext::map < ext::vector < SymbolType >, ext::set < ext::vector < SymbolType > > > & getRules ( ) const &;

	/**
	 * Get rules of the grammar.
	 *
	 * \returns rules of the grammar
	 */
	ext::map < ext::vector < SymbolType >, ext::set < ext::vector < SymbolType > > > && getRules ( ) &&;

	/**
	 * Remove a rule of a grammar in form of A -> B, where A, B \in ( N \cup T )+, and |A| <= |B|.
	 *
	 * \param leftHandSide the left hand side of the rule
	 * \param rightHandSide the right hand side of the rule
	 *
	 * \returns true if the rule was indeed removed, false othervise
	 */
	bool removeRule ( const ext::vector < SymbolType > & leftHandSide, const ext::vector < SymbolType > & rightHandSide );

	/**
	 * Getter of initial symbol.
	 *
	 * \returns the initial symbol of the grammar
	 */
	const SymbolType & getInitialSymbol ( ) const & {
		return this->template accessComponent < InitialSymbol > ( ).get ( );
	}

	/**
	 * Getter of initial symbol.
	 *
	 * \returns the initial symbol of the grammar
	 */
	SymbolType && getInitialSymbol ( ) && {
		return std::move ( this->template accessComponent < InitialSymbol > ( ).get ( ) );
	}

	/**
	 * Setter of initial symbol.
	 *
	 * \param symbol new initial symbol of the grammar
	 *
	 * \returns true if the initial symbol was indeed changed
	 */
	bool setInitialSymbol ( SymbolType symbol ) {
		return this->template accessComponent < InitialSymbol > ( ).set ( std::move ( symbol ) );
	}

	/**
	 * Getter of nonterminal alphabet.
	 *
	 * \returns the nonterminal alphabet of the grammar
	 */
	const ext::set < SymbolType > & getNonterminalAlphabet ( ) const & {
		return this->template accessComponent < NonterminalAlphabet > ( ).get ( );
	}

	/**
	 * Getter of nonterminal alphabet.
	 *
	 * \returns the nonterminal alphabet of the grammar
	 */
	ext::set < SymbolType > && getNonterminalAlphabet ( ) && {
		return std::move ( this->template accessComponent < NonterminalAlphabet > ( ).get ( ) );
	}

	/**
	 * Adder of nonterminal symbol.
	 *
	 * \param symbol the new symbol to be added to nonterminal alphabet
	 *
	 * \returns true if the symbol was indeed added
	 */
	bool addNonterminalSymbol ( SymbolType symbol ) {
		return this->template accessComponent < NonterminalAlphabet > ( ).add ( std::move ( symbol ) );
	}

	/**
	 * Setter of nonterminal alphabet.
	 *
	 * \param symbols completely new nonterminal alphabet
	 */
	void setNonterminalAlphabet ( ext::set < SymbolType > symbols ) {
		this->template accessComponent < NonterminalAlphabet > ( ).set ( std::move ( symbols ) );
	}

	/**
	 * Getter of terminal alphabet.
	 *
	 * \returns the terminal alphabet of the grammar
	 */
	const ext::set < SymbolType > & getTerminalAlphabet ( ) const & {
		return this->template accessComponent < TerminalAlphabet > ( ).get ( );
	}

	/**
	 * Getter of terminal alphabet.
	 *
	 * \returns the terminal alphabet of the grammar
	 */
	ext::set < SymbolType > && getTerminalAlphabet ( ) && {
		return std::move ( this->template accessComponent < TerminalAlphabet > ( ).get ( ) );
	}

	/**
	 * Adder of terminal symbol.
	 *
	 * \param symbol the new symbol tuo be added to nonterminal alphabet
	 *
	 * \returns true if the symbol was indeed added
	 */
	bool addTerminalSymbol ( SymbolType symbol ) {
		return this->template accessComponent < TerminalAlphabet > ( ).add ( std::move ( symbol ) );
	}

	/**
	 * Setter of terminal alphabet.
	 *
	 * \param symbol completely new nontemrinal alphabet
	 */
	void setTerminalAlphabet ( ext::set < SymbolType > symbols ) {
		this->template accessComponent < TerminalAlphabet > ( ).set ( std::move ( symbols ) );
	}

	/**
	 * Sets sign representing that grammar generates or doesn't generate empty word.
	 *
	 * \param genEps sign representing the posibility of generating empty string from the grammar
	 */
	void setGeneratesEpsilon ( bool genEps );

	/**
	 * Gets sign representing that grammar generates or doesn't generate empty word.
	 *
	 * \returns sign representing the posibility of generating empty string from the grammar
	 */
	bool getGeneratesEpsilon ( ) const;

	/**
	 * Actual compare method
	 *
	 * \param other the other instance
	 *
	 * \returns actual relation between two by type same grammar instances
	 */
	int compare ( const NonContractingGrammar & other ) const;

	/**
	 * Print this object as raw representation to ostream.
	 *
	 * \param out ostream where to print
	 * \param instance object to print
	 *
	 * \returns modified output stream
	 */
	friend std::ostream & operator << ( std::ostream & out, const NonContractingGrammar & instance ) {
		return out << "(NonContractingGrammar "
			   << "nonterminalAlphabet = " << instance.getNonterminalAlphabet ( )
			   << "terminalAlphabet = " << instance.getTerminalAlphabet ( )
			   << "initialSymbol = " << instance.getInitialSymbol ( )
			   << "rules = " << instance.getRules ( )
			   << "generatesEpsilon = " << instance.getGeneratesEpsilon ( )
			   << ")";
	}

	/**
	 * Casts this instance to as compact as possible string representation.
	 *
	 * \returns string representation of the object
	 */
	explicit operator std::string ( ) const;
};

template < class SymbolType >
NonContractingGrammar < SymbolType >::NonContractingGrammar ( SymbolType initialSymbol ) : NonContractingGrammar ( ext::set < SymbolType > { initialSymbol }, ext::set < SymbolType > ( ), initialSymbol ) {
}

template < class SymbolType >
NonContractingGrammar < SymbolType >::NonContractingGrammar ( ext::set < SymbolType > nonterminalAlphabet, ext::set < SymbolType > terminalAlphabet, SymbolType initialSymbol ) : core::Components < NonContractingGrammar, ext::set < SymbolType >, component::Set, std::tuple < TerminalAlphabet, NonterminalAlphabet >, SymbolType, component::Value, InitialSymbol > ( std::move ( terminalAlphabet), std::move ( nonterminalAlphabet ), std::move ( initialSymbol ) ), generatesEpsilon ( false ) {
}

template < class SymbolType >
bool NonContractingGrammar < SymbolType >::addRule ( ext::vector < SymbolType > leftHandSide, ext::vector < SymbolType > rightHandSide ) {
	int lSize = leftHandSide.size ( );

	if ( std::all_of ( leftHandSide.begin ( ), leftHandSide.end ( ), [this] ( const SymbolType symbol ) {
			return !getNonterminalAlphabet ( ).count ( symbol );
		} ) )
		throw GrammarException ( "Rule must rewrite nonterminal symbol" );

	for ( const SymbolType & symbol : leftHandSide )
		if ( !getTerminalAlphabet ( ).count ( symbol ) && !getNonterminalAlphabet ( ).count ( symbol ) )
			throw GrammarException ( "Symbol \"" + ext::to_string ( symbol ) + "\" is not neither terminal nor nonterminal symbol" );

	int rSize = rightHandSide.size ( );

	if ( lSize > rSize )
		throw GrammarException ( "Invalid size of right hand side of a rule" );

	for ( const SymbolType & symbol : rightHandSide )
		if ( !getTerminalAlphabet ( ).count ( symbol ) && !getNonterminalAlphabet ( ).count ( symbol ) )
			throw GrammarException ( "Symbol \"" + ext::to_string ( symbol ) + "\" is not neither terminal nor nonterminal symbol" );

	return rules[std::move ( leftHandSide )].insert ( std::move ( rightHandSide ) ).second;
}

template < class SymbolType >
void NonContractingGrammar < SymbolType >::addRules ( ext::vector < SymbolType > leftHandSide, ext::set < ext::vector < SymbolType > > rightHandSide ) {
	int lSize = leftHandSide.size ( );

	if ( std::all_of ( leftHandSide.begin ( ), leftHandSide.end ( ), [this] ( const SymbolType symbol ) {
			return !getNonterminalAlphabet ( ).count ( symbol );
		} ) )
		throw GrammarException ( "Rule must rewrite nonterminal symbol" );

	for ( const SymbolType & symbol : leftHandSide )
		if ( !getTerminalAlphabet ( ).count ( symbol ) && !getNonterminalAlphabet ( ).count ( symbol ) )
			throw GrammarException ( "Symbol \"" + ext::to_string ( symbol ) + "\" is not neither terminal nor nonterminal symbol" );

	for ( const ext::vector < SymbolType > & rhs : rightHandSide ) {

		int rSize = rightHandSide.size ( );

		if ( lSize > rSize )
			throw GrammarException ( "Invalid size of right hand side of a rule" );

		for ( const SymbolType & symbol : rhs )
			if ( !getTerminalAlphabet ( ).count ( symbol ) && !getNonterminalAlphabet ( ).count ( symbol ) )
				throw GrammarException ( "Symbol \"" + ext::to_string ( symbol ) + "\" is not neither terminal nor nonterminal symbol" );
	}

	rules [ std::move ( leftHandSide ) ].insert ( ext::make_mover ( rightHandSide ).begin ( ), ext::make_mover ( rightHandSide ).end ( ) );
}

template < class SymbolType >
const ext::map < ext::vector < SymbolType >, ext::set < ext::vector < SymbolType > > > & NonContractingGrammar < SymbolType >::getRules ( ) const & {
	return rules;
}

template < class SymbolType >
ext::map < ext::vector < SymbolType >, ext::set < ext::vector < SymbolType > > > && NonContractingGrammar < SymbolType >::getRules ( ) && {
	return std::move ( rules );
}

template < class SymbolType >
bool NonContractingGrammar < SymbolType >::removeRule ( const ext::vector < SymbolType > & leftHandSide, const ext::vector < SymbolType > & rightHandSide ) {
	return rules[leftHandSide].erase ( rightHandSide );
}

template < class SymbolType >
void NonContractingGrammar < SymbolType >::setGeneratesEpsilon ( bool genEps ) {
	generatesEpsilon = genEps;
}

template < class SymbolType >
bool NonContractingGrammar < SymbolType >::getGeneratesEpsilon ( ) const {
	return generatesEpsilon;
}

template < class SymbolType >
int NonContractingGrammar < SymbolType >::compare ( const NonContractingGrammar & other ) const {
	auto first = ext::tie ( getTerminalAlphabet ( ), getNonterminalAlphabet ( ), getInitialSymbol ( ), rules );
	auto second = ext::tie ( other.getTerminalAlphabet ( ), other.getNonterminalAlphabet ( ), other.getInitialSymbol ( ), other.rules );

	static ext::compare < decltype ( first ) > comp;

	return comp ( first, second );
}

template < class SymbolType >
NonContractingGrammar < SymbolType >::operator std::string ( ) const {
	std::stringstream ss;
	ss << * this;
	return ss.str ( );
}

} /* namespace grammar */

namespace core {

/**
 * Helper class specifying constraints for the grammar's internal terminal alphabet component.
 *
 * \tparam SymbolType used for the terminal alphabet of the grammar.
 */
template < class SymbolType >
class SetConstraint< grammar::NonContractingGrammar < SymbolType >, SymbolType, grammar::TerminalAlphabet > {
public:
	/**
	 * Returns true if the terminal symbol is still used in some rule of the grammar.
	 *
	 * \param grammar the tested grammar
	 * \param symbol the tested symbol
	 *
	 * \returns true if the symbol is used, false othervise
	 */
	static bool used ( const grammar::NonContractingGrammar < SymbolType > & grammar, const SymbolType & symbol ) {
		for ( const std::pair < const ext::vector < SymbolType >, ext::set < ext::vector < SymbolType > > > & rule : grammar.getRules ( ) ) {
			if ( std::find ( rule.first.begin ( ), rule.first.end ( ), symbol ) != rule.first.end ( ) )
				return true;

			for ( const ext::vector < SymbolType > & rhs : rule.second )
				if ( std::find ( rhs.begin ( ), rhs.end ( ), symbol ) != rhs.end ( ) )
					return true;

		}

		return false;
	}

	/**
	 * Returns true as all terminal symbols are possibly available to be terminal symbols.
	 *
	 * \param grammar the tested grammar
	 * \param symbol the tested symbol
	 *
	 * \returns true
	 */
	static bool available ( const grammar::NonContractingGrammar < SymbolType > &, const SymbolType & ) {
		return true;
	}

	/**
	 * Throws runtime exception if the symbol requested to be terminal symbol is already in nonterminal alphabet.
	 *
	 * \param grammar the tested grammar
	 * \param symbol the tested symbol
	 *
	 * \throws grammar::GrammarException of the tested symbol is in nonterminal alphabet
	 */
	static void valid ( const grammar::NonContractingGrammar < SymbolType > & grammar, const SymbolType & symbol ) {
		if ( grammar.template accessComponent < grammar::NonterminalAlphabet > ( ).get ( ).count ( symbol ) )
			throw grammar::GrammarException ( "Symbol " + ext::to_string ( symbol ) + " cannot be in the terminal alphabet since it is already in the nonterminal alphabet." );
	}
};

/**
 * Helper class specifying constraints for the grammar's internal nonterminal alphabet component.
 *
 * \tparam SymbolType used for the nonterminal alphabet of the grammar.
 */
template < class SymbolType >
class SetConstraint< grammar::NonContractingGrammar < SymbolType >, SymbolType, grammar::NonterminalAlphabet > {
public:
	/**
	 * Returns true if the nonterminal symbol is still used in some rule of the grammar or if it is the initial symbol of the grammar.
	 *
	 * \param grammar the tested grammar
	 * \param symbol the tested symbol
	 *
	 * \returns true if the symbol is used, false othervise
	 */
	static bool used ( const grammar::NonContractingGrammar < SymbolType > & grammar, const SymbolType & symbol ) {
		for ( const std::pair < const ext::vector < SymbolType >, ext::set < ext::vector < SymbolType > > > & rule : grammar.getRules ( ) ) {
			if ( std::find ( rule.first.begin ( ), rule.first.end ( ), symbol ) != rule.first.end ( ) )
				return true;

			for ( const ext::vector < SymbolType > & rhs : rule.second )
				if ( std::find ( rhs.begin ( ), rhs.end ( ), symbol ) != rhs.end ( ) )
					return true;

		}

		return grammar.template accessComponent < grammar::InitialSymbol > ( ).get ( ) == symbol;
	}

	/**
	 * Returns true as all terminal symbols are possibly available to be nonterminal symbols.
	 *
	 * \param grammar the tested grammar
	 * \param symbol the tested symbol
	 *
	 * \returns true
	 */
	static bool available ( const grammar::NonContractingGrammar < SymbolType > &, const SymbolType & ) {
		return true;
	}

	/**
	 * Throws runtime exception if the symbol requested to be nonterminal symbol is already in terminal alphabet.
	 *
	 * \param grammar the tested grammar
	 * \param symbol the tested symbol
	 *
	 * \throws grammar::GrammarException of the tested symbol is in nonterminal alphabet
	 */
	static void valid ( const grammar::NonContractingGrammar < SymbolType > & grammar, const SymbolType & symbol ) {
		if ( grammar.template accessComponent < grammar::TerminalAlphabet > ( ).get ( ).count ( symbol ) )
			throw grammar::GrammarException ( "Symbol " + ext::to_string ( symbol ) + " cannot be in the nonterminal alphabet since it is already in the terminal alphabet." );
	}
};

/**
 * Helper class specifying constraints for the grammar's internal initial symbol element.
 *
 * \tparam SymbolType used for the initial symbol of the grammar.
 */
template < class SymbolType >
class ElementConstraint< grammar::NonContractingGrammar < SymbolType >, SymbolType, grammar::InitialSymbol > {
public:
	/**
	 * Returns true if the symbol requested to be initial is available in nonterminal alphabet.
	 *
	 * \param grammar the tested grammar
	 * \param symbol the tested symbol
	 *
	 * \returns true if the tested symbol is in nonterminal alphabet
	 */
	static bool available ( const grammar::NonContractingGrammar < SymbolType > & grammar, const SymbolType & symbol ) {
		return grammar.template accessComponent < grammar::NonterminalAlphabet > ( ).get ( ).count ( symbol );
	}

	/**
	 * All symbols are valid as initial symbols.
	 *
	 * \param grammar the tested grammar
	 * \param symbol the tested symbol
	 */
	static void valid ( const grammar::NonContractingGrammar < SymbolType > &, const SymbolType & ) {
	}
};

/**
 * Helper for normalisation of types specified by templates used as internal datatypes of symbols.
 *
 * \returns new instance of the grammar with default template parameters or unmodified instance if the template parameters were already default ones
 */
template < class SymbolType >
struct normalize < grammar::NonContractingGrammar < SymbolType > > {
	static grammar::NonContractingGrammar < > eval ( grammar::NonContractingGrammar < SymbolType > && value ) {
		ext::set < DefaultSymbolType > nonterminals = alphabet::SymbolNormalize::normalizeAlphabet ( std::move ( value ).getNonterminalAlphabet ( ) );
		ext::set < DefaultSymbolType > terminals = alphabet::SymbolNormalize::normalizeAlphabet ( std::move ( value ).getTerminalAlphabet ( ) );
		DefaultSymbolType initialSymbol = alphabet::SymbolNormalize::normalizeSymbol ( std::move ( value ).getInitialSymbol ( ) );

		grammar::NonContractingGrammar < > res ( std::move ( nonterminals ), std::move ( terminals ), std::move ( initialSymbol ) );

		for ( std::pair < ext::vector < SymbolType >, ext::set < ext::vector < SymbolType > > > && rule : ext::make_mover ( std::move ( value ).getRules ( ) ) ) {

			ext::set < ext::vector < DefaultSymbolType > > rhs;
			for ( ext::vector < SymbolType > && target : ext::make_mover ( rule.second ) )
				rhs.insert ( alphabet::SymbolNormalize::normalizeSymbols ( std::move ( target ) ) );

			ext::vector < DefaultSymbolType > lhs = alphabet::SymbolNormalize::normalizeSymbols ( std::move ( rule.first ) );

			res.addRules ( std::move ( lhs ), std::move ( rhs ) );
		}

		res.setGeneratesEpsilon ( value.getGeneratesEpsilon ( ) );

		return res;
	}
};

} /* namespace core */

extern template class grammar::NonContractingGrammar < >;

#endif /* NON_CONTRACTING_GRAMMAR_H_ */
