aboutsummaryrefslogtreecommitdiff
path: root/libbutl/tab-parser.cxx
blob: cca2792baa6b690f18998085ff77c064c8d49270 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// file      : libbutl/tab-parser.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#ifndef __cpp_modules_ts
#include <libbutl/tab-parser.mxx>
#endif

#include <cassert>

#ifndef __cpp_lib_modules_ts
#include <string>
#include <vector>
#include <cstdint>
#include <stdexcept>

#include <istream>
#include <sstream>
#endif

// Other includes.

#ifdef __cpp_modules_ts
module butl.tab_parser;

// Only imports additional to interface.
#ifdef __clang__
#ifdef __cpp_lib_modules_ts
import std.core;
import std.io;
#endif
#endif

import butl.string_parser;
#else
#include <libbutl/string-parser.mxx>
#endif

using namespace std;

namespace butl
{
  using parsing = tab_parsing;

  // tab_parser
  //
  tab_fields tab_parser::
  next ()
  {
    tab_fields r;

    // Read lines until a non-empty one or EOF is encountered. In the first
    // case parse the line and bail out.
    //
    // Note that we check for character presence in the stream prior to the
    // getline() call, to prevent it from setting the failbit.
    //
    while (!is_.eof () && is_.peek () != istream::traits_type::eof ())
    {
      string s;
      getline (is_, s);

      ++line_;

      // Skip empty line.
      //
      auto i (s.begin ());
      auto e (s.end ());
      for (; i != e && (*i == ' ' || *i == '\t'); ++i) ; // Skip spaces.

      if (i == e || *i == '#')
        continue;

      r.line = line_;
      r.end_column = s.size () + 1; // Newline position.

      vector<std::pair<string, size_t>> sp;

      try
      {
        sp = string_parser::parse_quoted_position (s, false);
      }
      catch (const string_parser::invalid_string& e)
      {
        throw parsing (name_, line_, e.position + 1, e.what ());
      }

      for (auto& s: sp)
        r.emplace_back (tab_field ({move (s.first), s.second + 1}));

      break;
    }

    return r;
  }

  // tab_parsing
  //
  static inline string
  format (const string& n, uint64_t l, uint64_t c, const string& d)
  {
    ostringstream os;
    if (!n.empty ())
      os << n << ':';
    os << l << ':' << c << ": error: " << d;
    return os.str ();
  }

  tab_parsing::
  tab_parsing (const string& n, uint64_t l, uint64_t c, const string& d)
      : runtime_error (format (n, l, c, d)),
        name (n), line (l), column (c), description (d)
  {
  }
}