/*=============================================================================
    The Production rule

    Spirit V1.2
    Copyright (c) 2001, Joel de Guzman

    This software is provided 'as-is', without any express or implied
    warranty. In no event will the copyright holder be held liable for
    any damages arising from the use of this software.

    Permission is granted to anyone to use this software for any purpose,
    including commercial applications, and to alter it and redistribute
    it freely, subject to the following restrictions:

    1.  The origin of this software must not be misrepresented; you must
        not claim that you wrote the original software. If you use this
        software in a product, an acknowledgment in the product documentation
        would be appreciated but is not required.

    2.  Altered source versions must be plainly marked as such, and must
        not be misrepresented as being the original software.

    3.  This notice may not be removed or altered from any source
        distribution.

    Acknowledgements:

        Special thanks to Dan Nuffer, John (EBo) David, Chris Uzdavinis,
        and Doug Gregor. These people are most instrumental in steering
        Spirit in the right direction.

        Special thanks also to people who have contributed to the code base
        and sample code, ported Spirit to various platforms and compilers,
        gave suggestions, reported and provided bug fixes. Alexander
        Hirner, Andy Elvey, Bogdan Kushnir, Brett Calcott, Bruce Florman,
        Changzhe Han, Colin McPhail, Hakki Dogusan, Jan Bares, Joseph
        Smith, Martijn W. van der Lee, Raghavendra Satish, Remi Delcos, Tom
        Spilman, Vladimir Prus, W. Scott Dillman, David A. Greene, Bob
        Bailey, Hartmut Kaiser.

        Finally special thanks also to people who gave feedback and
        valuable comments, particularly members of Spirit's Source Forge
        mailing list and boost.org.

    URL: http://spirit.sourceforge.net/

======================================================================================*/
#ifndef SPIRIT_RULE_IPP
#define SPIRIT_RULE_IPP

///////////////////////////////////////////////////////////////////////////////

#include <cassert>
#include "boost/spirit/rule.hpp"
#include "boost/spirit/primitives.hpp"

///////////////////////////////////////////////////////////////////////////////
namespace spirit {

///////////////////////////////////////////////////////////////////////////////
namespace impl {

    ///////////////////////////////////////////////////////////////////////////////
    //
    //  abstract_parser class
    //
    ///////////////////////////////////////////////////////////////////////////////
    template <typename IteratorT>
    class abstract_parser {

    public:

        abstract_parser();
        virtual ~abstract_parser();

        virtual match
        parse(IteratorT& first, IteratorT const& last) const = 0;
    };

    //////////////////////////////////
    template <typename IteratorT>
    inline abstract_parser<IteratorT>::abstract_parser() {}

    //////////////////////////////////
    template <typename IteratorT>
    abstract_parser<IteratorT>::~abstract_parser() {}

    ///////////////////////////////////////////////////////////////////////////////
    //
    //  concrete_parser class
    //
    ///////////////////////////////////////////////////////////////////////////////
    template <typename ParserT, typename IteratorT>
    class concrete_parser
    :   public ParserT,
        public abstract_parser<IteratorT> {

    public:

        concrete_parser(ParserT const& parser);
        virtual ~concrete_parser();

        virtual match
        parse(IteratorT& first, IteratorT const& last) const;
    };

    //////////////////////////////////
    template <typename ParserT, typename IteratorT>
    inline concrete_parser<ParserT, IteratorT>::concrete_parser(
        ParserT const& parser)
    :   ParserT(parser) {}

    //////////////////////////////////
    template <typename ParserT, typename IteratorT>
    concrete_parser<ParserT, IteratorT>::~concrete_parser() {}

    //////////////////////////////////
    template <typename ParserT, typename IteratorT>
    match
    concrete_parser<ParserT, IteratorT>::
        parse(IteratorT& first, IteratorT const& last) const
    {
        return ParserT::parse(first, last);
    }

    ///////////////////////////////////////////////////////////////////////////////
    //
    //  rule_alias class
    //
    ///////////////////////////////////////////////////////////////////////////////
    template <typename IteratorT>
    class rule_alias : public abstract_parser<IteratorT> {

    public:

        rule_alias(rule<IteratorT> const& alias);
        virtual ~rule_alias();

        virtual match
        parse(IteratorT& first, IteratorT const& last) const;

    private:

        rule<IteratorT> const& alias;
    };

    //////////////////////////////////
    template <typename IteratorT>
    inline rule_alias<IteratorT>::rule_alias(
        rule<IteratorT> const& alias_)
    :   alias(alias_) {}

    //////////////////////////////////
    template <typename IteratorT>
    rule_alias<IteratorT>::~rule_alias() {}

    //////////////////////////////////
    template <typename IteratorT>
    match
    rule_alias<IteratorT>::
        parse(IteratorT& first, IteratorT const& last) const
    {
        return alias.parse(first, last);
    }

    ///////////////////////////////////////////////////////////////////////////////
    //
    //  alt_parser class
    //
    ///////////////////////////////////////////////////////////////////////////////
    template <typename ParserT, typename IteratorT>
    class alt_parser : public abstract_parser<IteratorT> {

    public:

        alt_parser(abstract_parser<IteratorT>* left, ParserT const& right);
        virtual ~alt_parser();

        virtual match
        parse(IteratorT& first, IteratorT const& last) const;

    private:

        abstract_parser<IteratorT>* left;
        ParserT right;
    };

    //////////////////////////////////
    template <typename ParserT, typename IteratorT>
    inline alt_parser<ParserT, IteratorT>::alt_parser(
        abstract_parser<IteratorT>* left_, ParserT const& right_)
    :   left(left_),
        right(right_) {}

    //////////////////////////////////
    template <typename ParserT, typename IteratorT>
    alt_parser<ParserT, IteratorT>::~alt_parser()
    {
        delete left;
    }

    //////////////////////////////////
    template <typename ParserT, typename IteratorT>
    match
    alt_parser<ParserT, IteratorT>::
        parse(IteratorT& first, IteratorT const& last) const
    {
        if (match hit = left->parse(first, last))
            return hit;
        return right.parse(first, last);
    }

} // namespace impl

///////////////////////////////////////////////////////////////////////////////
//
//  rule class implementation.
//
///////////////////////////////////////////////////////////////////////////////
template <typename IteratorT>
inline rule<IteratorT>::rule()
:   meta(0) {}

//////////////////////////////////
#ifdef SPIRIT_DEBUG
template <typename IteratorT>
inline void
rule<IteratorT>::debug_name(char const* name_)
{
    name = name_;
}
#endif

//////////////////////////////////
template <typename IteratorT>
inline rule<IteratorT>::~rule()
{
    delete meta;
}

//////////////////////////////////
template <typename IteratorT>
inline rule<IteratorT>::rule(rule const& other)
:   parser<rule<IteratorT> >()
,   meta(new impl::rule_alias<IteratorT>(other))
{
}

//////////////////////////////////
template <typename IteratorT>
template <typename ParserT>
inline rule<IteratorT>::rule(ParserT const& parser)
:   meta(new impl::concrete_parser<ParserT, IteratorT>(parser))
{
}

//////////////////////////////////
template <typename IteratorT>
inline rule<IteratorT>&
rule<IteratorT>::operator = (rule const& other)
{
    if (this != &other)
    {
        if (meta == 0)
            meta = new impl::rule_alias<IteratorT>(other);
        else
            meta = new impl::alt_parser<rule, IteratorT>(meta, other);
    }
    return *this;
}

//////////////////////////////////
template <typename IteratorT>
template <typename ParserT>
inline rule<IteratorT>&
rule<IteratorT>::operator = (ParserT const& parser)
{
    if (meta == 0)
        meta = new impl::concrete_parser<ParserT, IteratorT>(parser);
    else
        meta = new impl::alt_parser<ParserT, IteratorT>(meta, parser);
    return *this;
}

//////////////////////////////////
#ifdef SPIRIT_DEBUG
template <typename IteratorT>
void
print_info(
    bool                hit,
    int                 level,
    bool                close,
    std::string const&  name,
    IteratorT           first,
    IteratorT           last)
{
    if (!name.empty())
    {
        for (int i = 0; i < level; ++i)
            SPIRIT_DEBUG_OUT << "  ";
        if (close)
        {
            if (hit)
                SPIRIT_DEBUG_OUT << "/";
            else
                SPIRIT_DEBUG_OUT << "#";
        }
        SPIRIT_DEBUG_OUT << name << ":\t\"";
        typedef impl::strip_scanner<IteratorT> strip_scanner;
        typename strip_scanner::iterator_type
            iter = strip_scanner::get(first);
        typename strip_scanner::iterator_type
            ilast = strip_scanner::get(last);
        for (int j = 0; j < 20; ++j)
        {
            if (iter == ilast)
                break;

            switch (*iter) {

                case '\r': SPIRIT_DEBUG_OUT << "\\r";  break;
                case '\n': SPIRIT_DEBUG_OUT << "\\n";  break;
                default: SPIRIT_DEBUG_OUT << *iter;    break;
            }
            ++iter;
        }
        SPIRIT_DEBUG_OUT << " \"\n";
    }
}
#endif

template <typename IteratorT>
inline match
rule<IteratorT>::parse(IteratorT& first, IteratorT const& last) const
{
#ifdef SPIRIT_DEBUG

    static int      level = 0;
    print_info(false, level, false, name, first, last);

    int save_level = level;
    level++;
    match hit = meta ? meta->parse(first, last) : match();
    level = save_level;

    print_info(hit, level, true, name, first, last);
    return hit;

#else
    return meta ? meta->parse(first, last) : match();
#endif
}

///////////////////////////////////////////////////////////////////////////////
//
//  skipper class implementation.
//
///////////////////////////////////////////////////////////////////////////////
template <typename IteratorT>
template <typename ParserT>
inline skipper<IteratorT>::skipper(
    ParserT const&      skip_rule_,
    IteratorT const&    last_)
:
    last(last_),
    skip_rule(skip_rule_)
{
}

//////////////////////////////////
template <typename IteratorT>
inline skipper<IteratorT>::skipper(IteratorT const& last_)
:
    last(last_),
    skip_rule(space)
{
}

//////////////////////////////////
template <typename IteratorT>
inline void
skipper<IteratorT>::skip(IteratorT& current) const
{
    while (skip_rule.parse(current, last))
    {}
}

///////////////////////////////////////////////////////////////////////////////
}   //  namespace Spirit

#endif
