/*=============================================================================
    Symbol Tables

    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_SYMBOLS_IPP
#define SPIRIT_SYMBOLS_IPP

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

#include "boost/spirit/symbols.hpp"
#include <memory>

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

///////////////////////////////////////////////////////////////////////////////
//
//  tst class
//
//      Ternary Search Tree implementation. This is the default
//      implementation for string sets. The data structure is faster
//      than hashing for many typical search problems especially when
//      the search interface is iterator based. Searching for a string
//      of length k in a ternary search tree with n strings will require
//      at most O(log n+k) character comparisons. TSTs are many times
//      faster than hash tables for unsuccessful searches since
//      mismatches are discovered earlier after examining only a few
//      characters. Hash tables always examine an entire key when
//      searching.
//
//      For details see http://www.cs.princeton.edu/~rs/strings/.
//
///////////////////////////////////////////////////////////////////////////////
template <typename T, typename CharT>
class tst {

public:

    struct search_info {

        T*          data;
        unsigned    length;
    };

    tst();
    tst(tst const& other);
    ~tst();

    tst&
    operator=(tst const& other);

    template <typename IteratorT>
    T*
    add(IteratorT first, IteratorT const& last, T const& data);

    template <typename IteratorT>
    search_info
    find(IteratorT& first, IteratorT const& last) const;

private:

    struct node;
    node* root;
};

//////////////////////////////////
template <typename T, typename CharT>
struct tst<T, CharT>::node {

    node(CharT value);

    #ifndef __MWERKS__
    ~node();
    #else
    //////////////////////////////////
    ~node()
    {
        delete left;
        delete right;
        if (value)
            delete middle.link;
        else
            delete middle.data;
    }
    #endif

    node*
    clone() const;

    union center {

        node*   link;
        T*      data;
    };

    CharT   value;
    node*   left;
    center  middle;
    node*   right;
};

///////////////////////////////////////////////////////////////////////////////
//
//  tst class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename T, typename CharT>
inline tst<T, CharT>::node::node(CharT value_)
:   value(value_),
    left(0),
    right(0)
{
    middle.link = 0;
}

#ifndef __MWERKS__
//////////////////////////////////
template <typename T, typename CharT>
inline tst<T, CharT>::node::~node()
{
    delete left;
    delete right;
    if (value)
        delete middle.link;
    else
        delete middle.data;
}
#endif

//////////////////////////////////
template <typename T, typename CharT>
inline typename tst<T, CharT>::node*
tst<T, CharT>::node::clone() const
{
    std::auto_ptr<node> copy(new node(value));

    if (left)
        copy->left = left->clone();
    if (right)
        copy->right = right->clone();
    if (value && middle.link)
        copy->middle.link = middle.link->clone();
    else
        copy->middle.data = new T(*middle.data);

    return copy.release();
 }

//////////////////////////////////
template <typename T, typename CharT>
inline tst<T, CharT>::tst()
:   root(0)
{
}

//////////////////////////////////
template <typename T, typename CharT>
inline tst<T, CharT>::tst(tst const& other)
:   root(other.root->clone())
{
}

//////////////////////////////////
template <typename T, typename CharT>
inline tst<T, CharT>::~tst()
{
    delete root;
}

//////////////////////////////////
template <typename T, typename CharT>
inline tst<T, CharT>&
tst<T, CharT>::operator=(tst const& other)
{
    if (this != &other)
    {
        node* new_root = other.root->clone();
        delete root;
        root = new_root;
    }
    return *this;
}

//////////////////////////////////
template <typename T, typename CharT>
template <typename IteratorT>
T*
tst<T, CharT>::add(
    IteratorT           first,
    IteratorT const&    last,
    T const&            data)
{
    if (first == last)
        return 0;

    node**  np = &root;
    CharT   ch = *first;

    while (true)
    {
        if (*np == 0 || ch == 0)
        {
            node* right = 0;
            if (np != 0)
                right = *np;
            *np = new node(ch);
            if (right)
                (**np).right = right;
        }

        if (ch < (**np).value)
        {
            np = &(**np).left;
        }
        else
        {
            if (ch == (**np).value)
            {
                if (ch == 0)
                {
                    if ((**np).middle.data == 0)
                    {
                        (**np).middle.data = new T(data);
                        return (**np).middle.data;
                    }
                    else
                    {
                        //  re-addition is disallowed
                        return 0;
                    }
               }
                ++first;
                ch = (first == last) ? 0 : *first;
                np = &(**np).middle.link;
            }
            else
            {
                np = &(**np).right;
            }
        }
    }
}

//////////////////////////////////
template <typename T, typename CharT>
template <typename IteratorT>
typename tst<T, CharT>::search_info
tst<T, CharT>::find(IteratorT& first, IteratorT const& last) const
{
    node*       np = root;
    CharT       ch = *first;
    IteratorT   save = first;
    IteratorT   latest = first;
    unsigned    latest_len = 0;
    search_info result = { 0, 0 };

    while (np)
    {
        if (ch < np->value)
        {
            if (np->value == 0)
            {
                result.data = np->middle.data;
                if (result.data)
                {
                    latest = first;
                    latest_len = result.length;
                }
            }
            np = np->left;
        }
        else
        {
            if (ch == np->value)
            {
                if (first == last)
                {
                    result.data = np->middle.data;
                    if (result.data)
                    {
                        latest = first;
                        latest_len = result.length;
                    }
                    break;
                }
                ch = *(++first);
                np = np->middle.link;
                ++result.length;
            }
            else
            {
                if (np->value == 0)
                {
                    result.data = np->middle.data;
                    if (result.data)
                    {
                        latest = first;
                        latest_len = result.length;
                    }
                }
                np = np->right;
             }
        }
    }

    if (result.data == 0)
    {
        first = save;
    }
    else
    {
        first = latest;
        result.length = latest_len;
    }
    return result;
}

///////////////////////////////////////////////////////////////////////////////
//
//  symbol_match class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename T>
inline symbol_match<T>::symbol_match()
:   match(),
    info(0)
{
}

//////////////////////////////////
template <typename T>
inline symbol_match<T>::symbol_match(unsigned length, T* info_)
:   match(length),
    info(info_)
{
}

//////////////////////////////////
template <typename T>
inline T*
symbol_match<T>::data() const
{
    return info;
}

///////////////////////////////////////////////////////////////////////////////
//
//  symbol_inserter class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename T, typename SetT>
symbol_inserter<T, SetT>::symbol_inserter(SetT& set_)
:   set(set_)
{
}

//////////////////////////////////
template <typename T, typename SetT>
template <typename IteratorT>
inline T*
symbol_inserter<T, SetT>::operator()(
    IteratorT           first,
    IteratorT const&    last,
    T const&            data) const
{
    return set.add(first, last, data);
}

template <typename T, typename SetT>
template <typename CharT>
inline symbol_inserter<T, SetT> const&
symbol_inserter<T, SetT>::operator,(CharT const* str) const
{
    CharT const* last = str;
    while (*last)
        last++;
    set.add(str, last, T());
    return *this;
}

///////////////////////////////////////////////////////////////////////////////
//
//  symbol_action class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename ParserT, typename ActionT>
inline symbol_action<ParserT, ActionT>::symbol_action(
    ParserT const&  parser,
    ActionT const&   actor_)
:   unary<ParserT>(parser),
    actor(actor_)
{
}

//////////////////////////////////
template <typename ParserT, typename ActionT>
template <typename IteratorT>
inline match
symbol_action<ParserT, ActionT>::parse(
    IteratorT&          first,
    IteratorT const&    last) const
{
    typedef impl::strip_scanner<IteratorT> strip_scanner;
    typename strip_scanner::iterator_type
        begin = strip_scanner::get(first);

    typename ParserT::symbol_match hit = this->subject().parse(first, last);

    if (hit)
        actor(begin, strip_scanner::get(first), *hit.data());

    return hit;
}

///////////////////////////////////////////////////////////////////////////////
//
//  symbols class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename T, typename CharT, typename SetT>
inline symbols<T, CharT, SetT>::symbols()
:   tst<T, CharT>(),
    add(*this)
{
}

//////////////////////////////////
template <typename T, typename CharT, typename SetT>
symbols<T, CharT, SetT>::symbols(symbols const& other)
:   tst<T, CharT>(other)
,   parser<symbols<T, CharT, SetT> >()
,   add(*this)
{
}

//////////////////////////////////
template <typename T, typename CharT, typename SetT>
inline symbols<T, CharT, SetT>::~symbols()
{
}

//////////////////////////////////
template <typename T, typename CharT, typename SetT>
inline symbols<T, CharT, SetT>&
symbols<T, CharT, SetT>::operator=(symbols const& other)
{
    tst<T, CharT>::operator=(other);
    return *this;
}

//////////////////////////////////
template <typename T, typename CharT, typename SetT>
inline symbol_inserter<T, SetT> const&
symbols<T, CharT, SetT>::operator=(CharT const* str)
{
    return add, str;
}

//////////////////////////////////
template <typename T, typename CharT, typename SetT>
template <typename IteratorT>
inline symbol_match<T>
symbols<T, CharT, SetT>::parse(
    IteratorT&          first,
    IteratorT const&    last) const
{
    typename SetT::search_info result = tst<T, CharT>::find(first, last);

    if (result.data)
        return symbol_match(result.length, result.data);
    else
        return symbol_match();
}

///////////////////////////////////////////////////////////////////////////////
//
//  Symbol table utilities
//
///////////////////////////////////////////////////////////////////////////////
template <typename T, typename CharT, typename SetT>
inline T*
find(symbols<T, CharT, SetT>& table, CharT const* sym)
{
    CharT const* last = sym;
    while (*last)
        last++;
    return table.parse(sym, last).info();
}

//////////////////////////////////
template <typename T, typename CharT, typename SetT>
inline T*
add(symbols<T, CharT, SetT>& table, CharT const* sym, T const& data)
{
    CharT const* last = sym;
    while (*last)
        last++;
    return table.add(sym, last, data);
}

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

#endif
