Orcus
parser_base.hpp
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
6  */
7 
8 #ifndef INCLUDED_ORCUS_PARSER_BASE_HPP
9 #define INCLUDED_ORCUS_PARSER_BASE_HPP
10 
11 #include "orcus/env.hpp"
12 #include "orcus/exception.hpp"
13 
14 #include <string>
15 #include <cstdlib>
16 #include <cstddef>
17 #include <cassert>
18 #include <functional>
19 
20 namespace orcus {
21 
26 class ORCUS_PSR_DLLPUBLIC parse_error : public general_error
27 {
28  std::ptrdiff_t m_offset;
29 protected:
30  parse_error(const std::string& msg, std::ptrdiff_t offset);
31  parse_error(const std::string& cls, const std::string& msg, std::ptrdiff_t offset);
32 
33  static std::string build_message(const char* msg_before, char c, const char* msg_after);
34  static std::string build_message(const char* msg_before, const char* p, size_t n, const char* msg_after);
35 
36 public:
37  std::ptrdiff_t offset() const;
38 };
39 
40 class ORCUS_PSR_DLLPUBLIC parser_base
41 {
42 protected:
43  using numeric_parser_type = std::function<double(const char*&, size_t)>;
44 
45  const char* const mp_begin;
46  const char* mp_char;
47  const char* mp_end;
48  const bool m_transient_stream;
49 
50 private:
51  std::function<double(const char*&, size_t)> m_func_parse_numeric;
52 
53 protected:
54  parser_base(const char* p, size_t n, bool transient_stream);
55 
56  void set_numeric_parser(const numeric_parser_type& func)
57  {
58  m_func_parse_numeric = func;
59  }
60 
61  bool transient_stream() const { return m_transient_stream; }
62 
63  bool has_char() const
64  {
65  assert(mp_char <= mp_end);
66  return mp_char != mp_end;
67  }
68 
69  bool has_next() const
70  {
71  assert((mp_char+1) <= mp_end);
72  return (mp_char+1) != mp_end;
73  }
74 
75  void next(size_t inc=1) { mp_char += inc; }
76 
77  void prev(size_t dec=1);
78 
79  char cur_char() const { return *mp_char; }
80 
81  char next_char() const;
82 
83  void skip(const char* chars_to_skip, size_t n_chars_to_skip);
84 
89 
100  bool parse_expected(const char* expected, size_t n_expected);
101 
108  double parse_double();
109 
118  size_t remaining_size() const;
119 
126  size_t available_size() const
127  {
128  return std::distance(mp_char, mp_end);
129  }
130 
136  std::ptrdiff_t offset() const;
137 };
138 
139 }
140 
141 #endif
142 
143 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Definition: exception.hpp:19
Definition: parser_base.hpp:27
parse_error(const std::string &msg, std::ptrdiff_t offset)
offset in the stream where the error occurred.
Definition: parser_base.hpp:41
size_t available_size() const
Definition: parser_base.hpp:126
void skip_space_and_control()
size_t remaining_size() const
std::ptrdiff_t offset() const
bool parse_expected(const char *expected, size_t n_expected)