aboutsummaryrefslogtreecommitdiff
path: root/libbutl/regex.txx
blob: 96b1f54c8388fec59f5b74a01b88742ea40081b7 (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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// file      : libbutl/regex.txx -*- C++ -*-
// copyright : Copyright (c) 2014-2019 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

LIBBUTL_MODEXPORT namespace butl //@@ MOD Clang needs this for some reason.
{
  // Replace the regex match results using the format string.
  //
  template <typename C>
  std::basic_string<C>
  regex_replace_match_results (
    const std::match_results<typename std::basic_string<C>::const_iterator>& m,
    const std::basic_string<C>& fmt)
  {
    using namespace std;

    using string_type = basic_string<C>;
    using str_it      = typename string_type::const_iterator;

    string_type r;

    // Note that we are using char type literals with the assumption that
    // being ASCII characters they will be properly "widened" to the
    // corresponding literals of the C template parameter type.
    //
    auto digit = [] (C c) -> int
    {
      return c >= '0' && c <= '9' ? c - '0' : -1;
    };

    enum class case_conv {none, upper, lower, upper_once, lower_once}
    mode (case_conv::none);

    locale cl; // Copy of the global C++ locale.

    auto conv_chr = [&mode, &cl] (C c) -> C
    {
      switch (mode)
      {
      case case_conv::upper_once: mode = case_conv::none; // Fall through.
      case case_conv::upper:      c = toupper (c, cl); break;
      case case_conv::lower_once: mode = case_conv::none; // Fall through.
      case case_conv::lower:      c = tolower (c, cl); break;
      case case_conv::none:       break;
      }
      return c;
    };

    auto append_chr = [&r, &conv_chr] (C c) {r.push_back (conv_chr (c));};

    auto append_str = [&r, &mode, &conv_chr] (str_it b, str_it e)
    {
      // Optimize for the common case.
      //
      if (mode == case_conv::none)
        r.append (b, e);
      else
      {
        for (str_it i (b); i != e; ++i)
          r.push_back (conv_chr (*i));
      }
    };

    size_t n (fmt.size ());
    for (size_t i (0); i < n; ++i)
    {
      C c (fmt[i]);

      switch (c)
      {
      case '$':
        {
          // Check if this is a $-based escape sequence. Interpret it
          // accordingly if that's the case, treat '$' as a regular character
          // otherwise.
          //
          c = fmt[++i]; // '\0' if last.

          switch (c)
          {
          case '$': append_chr (c); break;
          case '&': append_str (m[0].first, m[0].second); break;
          case '`':
            {
              append_str (m.prefix ().first, m.prefix ().second);
              break;
            }
          case '\'':
            {
              append_str (m.suffix ().first, m.suffix ().second);
              break;
            }
          default:
            {
              // Check if this is a sub-expression 1-based index ($n or $nn).
              // Append the matching substring if that's the case. Treat '$'
              // as a regular character otherwise. Index greater than the
              // sub-expression count is silently ignored.
              //
              int si (digit (c));
              if (si >= 0)
              {
                int d;
                if ((d = digit (fmt[i + 1])) >= 0) // '\0' if last.
                {
                  si = si * 10 + d;
                  ++i;
                }
              }

              if (si > 0)
              {
                // m[0] refers to the matched substring. Note that we ignore
                // unmatched sub-expression references.
                //
                if (static_cast<size_t> (si) < m.size () && m[si].matched)
                  append_str (m[si].first, m[si].second);
              }
              else
              {
                // Not a $-based escape sequence so treat '$' as a regular
                // character.
                //
                --i;
                append_chr ('$');
              }

              break;
            }
          }

          break;
        }
      case '\\':
        {
          c = fmt[++i]; // '\0' if last.

          switch (c)
          {
          case '\\': append_chr (c);    break;
          case 'n':  append_chr ('\n'); break;

          case 'u': mode = case_conv::upper_once; break;
          case 'l': mode = case_conv::lower_once; break;
          case 'U': mode = case_conv::upper;      break;
          case 'L': mode = case_conv::lower;      break;
          case 'E': mode = case_conv::none;       break;
          default:
            {
              // Check if this is a sub-expression 1-based index. Append the
              // matching substring if that's the case, Skip '\\' otherwise.
              // Index greater than the sub-expression count is silently
              // ignored.
              //
              int si (digit (c));
              if (si > 0)
              {
                // m[0] refers to the matched substring. Note that we ignore
                // unmatched sub-expression references.
                //
                if (static_cast<size_t> (si) < m.size () && m[si].matched)
                  append_str (m[si].first, m[si].second);
              }
              else
                --i;

              break;
            }
          }

          break;
        }
      default:
        {
          // Append a regular character.
          //
          append_chr (c);
          break;
        }
      }
    }

    return r;
  }

  template <typename C>
  std::pair<std::basic_string<C>, bool>
  regex_replace_match (const std::basic_string<C>& s,
                       const std::basic_regex<C>& re,
                       const std::basic_string<C>& fmt)
  {
    using namespace std;

    using string_type = basic_string<C>;
    using str_it      = typename string_type::const_iterator;

    match_results<str_it> m;
    bool match (regex_match (s, m, re));

    return make_pair (match ? regex_replace_match_results (m, fmt) : string (),
                      match);
  }

  template <typename C, typename F>
  bool
  regex_replace_search (const std::basic_string<C>& s,
                        const std::basic_regex<C>& re,
                        const std::basic_string<C>& fmt,
                        F&& append,
                        std::regex_constants::match_flag_type flags)
  {
    using namespace std;

    using string_type = basic_string<C>;
    using str_it      = typename string_type::const_iterator;
    using regex_it    = regex_iterator<str_it>;

    bool first_only ((flags & regex_constants::format_first_only) != 0);
    bool no_copy ((flags & regex_constants::format_no_copy) != 0);

    // Beginning of the last unmatched substring.
    //
    str_it ub (s.begin ());

    regex_it b (s.begin (), s.end (), re, flags);
    regex_it e;
    bool match (b != e);

    // For libc++, the end-of-sequence regex iterator can never be reached
    // for some regular expressions (LLVM bug #33681). We will check if the
    // matching sequence start is the same as the one for the previous match
    // and bail out if that's the case.
    //
#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 4000
    str_it pm;
#endif

    for (regex_it i (b); i != e; ++i)
    {
      const match_results<str_it>& m (*i);

#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 4000
      if (i != b && m[0].first == pm)
        break;

      pm = m[0].first;
#endif

      // Copy the preceeding unmatched substring, save the beginning of the
      // one that follows.
      //
      if (!no_copy)
      {
        append (ub, m.prefix ().second);
        ub = m.suffix ().first;
      }

      if (first_only && i != b)
      {
        // Append matched substring.
        //
        if (!no_copy)
          append (m[0].first, m[0].second);
      }
      else
      {
        // The standard implementation calls m.format() here. We perform our
        // own formatting.
        //
        string_type r (regex_replace_match_results (m, fmt));
        append (r.begin (), r.end ());
      }
    }

    // Append the rightmost non-matched substring.
    //
    if (!no_copy)
      append (ub, s.end ());

    return match;
  }
}