/*=============================================================================
    Numeric parsers

    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_NUMERICS_IPP
#define SPIRIT_NUMERICS_IPP

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

#include <cmath>
#include "boost/spirit/primitives.hpp"
#include "boost/spirit/iterators.hpp"

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

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

    //////////////////////////////////
    template <typename IteratorT>
    bool
    extract_sign(IteratorT& iter, unsigned& count)
    {
        //  Extract the sign

        count = 0;
        bool neg = *iter == '-';
        if (neg || (*iter == '+'))
        {
            ++iter;
            ++count;
            return neg;
        }

        return false;
    }

    //////////////////////////////////
    template <typename IteratorT, typename T>
    void
    extract_uint(IteratorT& first, IteratorT const& last, T& n, unsigned& count)
    {
        //  Extract an unsigned integer

        while ((first != last) && isdigit(*first))
        {
            n *= 10;
            n += *first - '0';
            ++first;
            ++count;
        }
    }

} // namespace impl

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

//////////////////////////////////
template <typename ParserT, typename ActionT>
template <typename IteratorT>
inline match
numeric_action<ParserT, ActionT>::
    parse(IteratorT& first, IteratorT const& last) const
{
    match hit = this->subject().parse(first, last);
    if (hit)
        actor(this->subject().n);
    return hit;
}

///////////////////////////////////////////////////////////////////////////////
//
//  uint_parser class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename T>
inline uint_parser<T>::uint_parser(T n_)
:   n(n_) {}

//////////////////////////////////
template <typename T>
template <typename IteratorT>
inline match
uint_parser<T>::parse(IteratorT& first, IteratorT const& last) const
{
    n = 0;
    if (first == last)
        return match();

    typedef typename impl::strip_scanner<IteratorT>
        ::iterator_type plain_iter;
    plain_iter  i1 = impl::strip_scanner<IteratorT>::get(first);
    plain_iter  i2 = impl::strip_scanner<IteratorT>::get(last);

    unsigned count = 0;
    if (!isdigit(*i1))
        return match();

    impl::extract_uint(i1, i2, n, count);
    first = i1;
    return match(count);
}

///////////////////////////////////////////////////////////////////////////////
//
//  int_parser class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename T>
inline int_parser<T>::int_parser(T n_)
:   n(n_) {}

//////////////////////////////////
template <typename T>
template <typename IteratorT>
inline match
int_parser<T>::parse(IteratorT& first, IteratorT const& last) const
{
    n = 0;
    if (first == last)
        return match();

    typedef typename impl::strip_scanner<IteratorT>
        ::iterator_type plain_iter;
    plain_iter  i1 = impl::strip_scanner<IteratorT>::get(first);
    plain_iter  i2 = impl::strip_scanner<IteratorT>::get(last);

    unsigned    count;
    bool        neg = impl::extract_sign(i1, count);

    if (match hit = uint_p[ref(n)].parse(i1, i2))
    {
        if (neg) n = -n;
        first = i1;
        return match(hit.length() + count);
    }
    return match();
}

///////////////////////////////////////////////////////////////////////////////
template <typename T> struct real_traits {};
template <typename T> struct real_traits<T&> : public real_traits<T> {};

#ifdef __MWERKS__

//////////////////////////////////
template <> struct real_traits<float> {

    static float pow(float x, float y)
    { return std::powf(x, y); }
};

//////////////////////////////////
template <> struct real_traits<double> {

    static double pow(double x, double y)
    { return std::pow(x, y); }
};

//////////////////////////////////
template <> struct real_traits<long double> {

    static double pow(long double x, long double y)
    { return std::powl(x, y); }
};

#else

//////////////////////////////////
template <> struct real_traits<float> {

    static float pow(float x, float y)
    { return static_cast<float>(std::pow(x, y)); }
};

//////////////////////////////////
template <> struct real_traits<double> {

    static double pow(double x, double y)
    { return std::pow(x, y); }
};

//////////////////////////////////
template <> struct real_traits<long double> {

    static double pow(long double x, long double y)
    { return std::pow(x, y); }
};

#endif

///////////////////////////////////////////////////////////////////////////////
//
//  ureal_parser class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename T>
inline ureal_parser<T>::ureal_parser(T n_)
:   n(n_) {}

//////////////////////////////////
template <typename T>
template <typename IteratorT>
match
ureal_parser<T>::parse(IteratorT& first, IteratorT const& last) const
{
    n = 0;
    if (first == last)
        return match();

    typedef typename impl::strip_scanner<IteratorT>
        ::iterator_type plain_iter;
    plain_iter  i1 = impl::strip_scanner<IteratorT>::get(first);
    plain_iter  i2 = impl::strip_scanner<IteratorT>::get(last);

    if (!(isdigit(*i1) || *i1 == '.'))
        return match();

    unsigned    count = 0;
    unsigned    frac = 0;

    if (*i1 != '.')
    {
        //  Extract the digits before the decimal point: nnn.
        impl::extract_uint(i1, i2, n, count);
        if (i1 == i2)
        {
            first = i1;
            return match(count);
        }
    }

    if (*i1 == '.')
    {
        //  Extract the digits after the decimal point .nnn
        impl::extract_uint(++i1, i2, n, frac);
        count += frac + 1;
    }

    match   hit(count);
    int     exp = 0;

    //  Extract the exponent
    if (match mexp = (nocase['e'] >> int_p[ref(exp)]).parse(i1, i2))
        hit += mexp;

    n *= real_traits<T>::pow(10, exp - int(frac));
    first = i1;
    return hit;
}

///////////////////////////////////////////////////////////////////////////////
//
//  real_parser class implementation
//
///////////////////////////////////////////////////////////////////////////////
template <typename T>
inline real_parser<T>::real_parser(T n_)
:   n(n_) {}

//////////////////////////////////
template <typename T>
template <typename IteratorT>
inline match
real_parser<T>::parse(IteratorT& first, IteratorT const& last) const
{
    n = 0;
    if (first == last)
        return match();

    typedef typename impl::strip_scanner<IteratorT>
        ::iterator_type plain_iter;
    plain_iter  i1 = impl::strip_scanner<IteratorT>::get(first);
    plain_iter  i2 = impl::strip_scanner<IteratorT>::get(last);

    unsigned    count;
    bool        neg = impl::extract_sign(i1, count);

    if (match hit = ureal_p[ref(n)].parse(i1, i2))
    {
        if (neg) n = -n;
        first = i1;
        return match(hit.length() + count);
    }
    return match();
}

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

#endif
