aboutsummaryrefslogtreecommitdiff
path: root/bbot/variable.cxx
blob: a25b007fb92a6bcdd4d31e03697e665498595bfb (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
// file      : bbot/variable.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2017 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <bbot/variable>

#include <utility> // move()

using namespace std;

namespace bbot
{
  variable::
  variable (string v): string (move (v))
  {
    // Scan the string untill the end to check that the quoting is terminated.
    // We will also make sure that the name doesn't contain spaces and the
    // value is provided.
    //
    char quoting ('\0'); // Current quoting mode, can be used as bool.
    bool name (true);    // True while we are parsing the variable name.

    auto b (cbegin ());
    auto i (b);

    auto bad_variable = [&b, &i] (const string& d)
    {
      throw invalid_variable (i - b, d);
    };

    for (auto e (cend ()); i != e; ++i)
    {
      char c (*i);

      if (!quoting)
      {
        if (c == '"' || c == '\'') // Begin of quoted string,
        {
          quoting = c;
          continue;
        }
      }
      else if (c == quoting)       // End of quoted string,
      {
        quoting = '\0';
        continue;
      }

      if (name)
      {
        if (c == ' ' || c == '\t')
          bad_variable ("expected variable assignment");
        else if (c == '=')
          name = false;
      }
    }

    if (quoting)
      bad_variable ("unterminated quoted string");

    if (name)
      bad_variable ("no variable value");
  }

  string variable::
  unquoted () const
  {
    string r;
    char quoting ('\0');  // Current quoting mode, can be used as bool.

    for (auto i (cbegin ()), e (cend ()); i != e; ++i)
    {
      char c (*i);

      if (!quoting)
      {
        if (c == '"' || c == '\'') // Begin of quoted string.
        {
          quoting = c;
          continue;
        }
      }
      else if (c == quoting)       // End of quoted string.
      {
        quoting = '\0';
        continue;
      }

      r += c;
    }

    return r;
  }
}