// file      : xsde/cxx/parser/non-validating/nmtokens.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2005-2008 Code Synthesis Tools CC
// license   : GNU GPL v2 + exceptions; see accompanying LICENSE file

#include <xsde/cxx/config.hxx>

#include <xsde/cxx/parser/non-validating/nmtokens.hxx>

namespace xsde
{
  namespace cxx
  {
    namespace parser
    {
      namespace non_validating
      {
        nmtokens_pimpl::
        ~nmtokens_pimpl ()
        {
          delete seq_;
        }

        nmtokens_pimpl::
        nmtokens_pimpl ()
            : seq_ (0)
        {
        }

        void nmtokens_pimpl::
        _pre ()
        {
          delete seq_;
          seq_ = new string_sequence ();

#ifndef XSDE_EXCEPTIONS
          if (seq_ == 0)
          {
            _sys_error (sys_error::no_memory);
            return;
          }
#endif
          nmtokens_pskel::_pre ();
        }

        string_sequence* nmtokens_pimpl::
        post_nmtokens ()
        {
          string_sequence* r = seq_;
          seq_ = 0;
          return r;
        }

        void nmtokens_pimpl::
        _reset ()
        {
          nmtokens_pskel::_reset ();
          parser_._reset ();
        }

#ifdef XSDE_EXCEPTIONS
        struct string_guard
        {
          ~string_guard () { delete[] p_; }
          string_guard (char* p) : p_ (p) {}

          void
          release () { p_ = 0; }

        private:
          char* p_;
        };

        void nmtokens_pimpl::
        _xsde_parse_item (const ro_string& s)
        {
          parser_.pre ();
          parser_._pre_impl (_context ());
          parser_._characters (s);
          parser_._post_impl ();
          char* x = parser_.post_nmtoken ();
          string_guard guard (x);
          seq_->push_back_attach (x);
          guard.release ();
        }
#else
        void nmtokens_pimpl::
        _xsde_parse_item (const ro_string& s)
        {
          context& ctx = _context ();

          parser_.pre ();

          if (!parser_._error_type ())
            parser_._pre_impl (ctx);
          else
            parser_._copy_error (ctx);

          if (!ctx.error_type ())
            parser_._characters (s);

          if (!ctx.error_type ())
            parser_._post_impl ();

          if (!ctx.error_type ())
          {
            char* x = parser_.post_nmtoken ();

            if (!parser_._error_type ())
            {
              if (seq_->push_back_attach (x))
              {
                delete[] x;
                _sys_error (sys_error::no_memory);
              }
            }
            else
              parser_._copy_error (ctx);
          }
        }
#endif
      }
    }
  }
}
