/*
 * UnrestrictedGrammar.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
 */

#pragma once

#include <sstream>

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

#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
 * Unrestricted grammar. Type 0 in Chomsky hierarchy. Generates recursively enumerable languages.

 * \details
 * Definition is similar to all common definitions of unrestricted 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 \alpha A \beta -> B, where A \in N, B, \alpha, and \beta \in ( N \cup T )*,
 * 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 UnrestrictedGrammar final : public core::Components < UnrestrictedGrammar < SymbolType >, ext::set < SymbolType >, component::Set, std::tuple < TerminalAlphabet, NonterminalAlphabet >, SymbolType, component::Value, InitialSymbol > {
	/**
	 * Rules function as mapping from nonterminal symbol and contexts 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;

public:
	/**
	 * \brief Creates a new instance of the grammar with a concrete initial symbol.
	 *
	 * \param initialSymbol the initial symbol of the grammar
	 */
	explicit UnrestrictedGrammar ( 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 UnrestrictedGrammar ( 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 \alpha A \beta -> B, where A \in N, B, \alpha, and \beta \in ( N \cup T )*.
	 *
	 * \param lContext the left context of the rule
	 * \param leftHandSide the left hand side of the rule
	 * \param rContext the right context 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 \alpha A \beta -> B | C | ..., where A \in N, B, C ..., \alpha, and \beta \in ( N \cup T )*.
	 *
	 * \param lContext the left context of the rule
	 * \param leftHandSide the left hand side of the rule
	 * \param rContext the right context 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 \alpha A \beta -> B, where A \in N, B, \alpha, and \beta \in ( N \cup T )*.
	 *
	 * \param lContext the left context of the rule
	 * \param leftHandSide the left hand side of the rule
	 * \param rContext the right context 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 ) );
	}

	/**
	 * The three way comparison implementation
	 *
	 * \param other the other instance
	 *
	 * \returns the ordering between this object and the @p other.
	 */
	auto operator <=> ( const UnrestrictedGrammar & other ) const {
		return std::tie ( getTerminalAlphabet ( ), getNonterminalAlphabet ( ), getInitialSymbol ( ), rules ) <=> std::tie ( other.getTerminalAlphabet ( ), other.getNonterminalAlphabet ( ), other.getInitialSymbol ( ), other.rules );
	}

	/**
	 * The equality comparison implementation.
	 *
	 * \param other the other object to compare with.
	 *
	 * \returns true if this and other objects are equal, false othervise
	 */
	bool operator == ( const UnrestrictedGrammar & other ) const {
		return std::tie ( getTerminalAlphabet ( ), getNonterminalAlphabet ( ), getInitialSymbol ( ), rules ) == std::tie ( other.getTerminalAlphabet ( ), other.getNonterminalAlphabet ( ), other.getInitialSymbol ( ), other.rules );
	}

	/**
	 * 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 UnrestrictedGrammar & instance ) {
		return out << "(UnrestrictedGrammar "
			   << "nonterminalAlphabet = " << instance.getNonterminalAlphabet ( )
			   << "terminalAlphabet = " << instance.getTerminalAlphabet ( )
			   << "initialSymbol = " << instance.getInitialSymbol ( )
			   << "rules = " << instance.getRules ( )
			   << ")";
	}

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

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

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

template < class SymbolType >
bool UnrestrictedGrammar < SymbolType >::addRule ( ext::vector < SymbolType > leftHandSide, ext::vector < SymbolType > rightHandSide ) {
	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 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 UnrestrictedGrammar < SymbolType >::addRules ( ext::vector < SymbolType > leftHandSide, ext::set < ext::vector < SymbolType > > rightHandSide ) {
	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 )
		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 > > > & UnrestrictedGrammar < SymbolType >::getRules ( ) const & {
	return rules;
}

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

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

template < class SymbolType >
UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < 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::UnrestrictedGrammar < SymbolType > > {
	static grammar::UnrestrictedGrammar < > eval ( grammar::UnrestrictedGrammar < 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::UnrestrictedGrammar < > 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 ) );
		}

		return res;
	}
};

} /* namespace core */

extern template class grammar::UnrestrictedGrammar < >;

