aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/lib/strings/scanner.h
blob: c82e771368c1c2b8a945e070cfcd45f72f91f0a3 (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
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#ifndef TENSORFLOW_LIB_STRINGS_SCANNER_H_
#define TENSORFLOW_LIB_STRINGS_SCANNER_H_

#include <string>
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/macros.h"

namespace tensorflow {
namespace strings {

// Scanner provides simplified string parsing, in which a string is parsed as a
// series of scanning calls (e.g. One, Any, Many, OneLiteral, Eos), and then
// finally GetResult is called. If GetResult returns true, then it also returns
// the remaining characters and any captured substring.
//
// The range to capture can be controlled with RestartCapture and StopCapture;
// by default, all processed characters are captured.
class Scanner {
 public:
  // Classes of characters. Each enum name is to be read as the union of the
  // parts - e.g., class LETTER_DIGIT means the class includes all letters and
  // all digits.
  //
  // LETTER means ascii letter a-zA-Z.
  // DIGIT means ascii digit: 0-9.
  enum CharClass {
    // NOTE: When adding a new CharClass, update the AllCharClasses ScannerTest
    // in scanner_test.cc
    ALL,
    DIGIT,
    LETTER,
    LETTER_DIGIT,
    LETTER_DIGIT_DASH_UNDERSCORE,
    LETTER_DIGIT_DASH_DOT_SLASH,             // SLASH is / only, not backslash
    LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE,  // SLASH is / only, not backslash
    LETTER_DIGIT_DOT,
    LETTER_DIGIT_DOT_PLUS_MINUS,
    LETTER_DIGIT_DOT_UNDERSCORE,
    LETTER_DIGIT_UNDERSCORE,
    LOWERLETTER,
    LOWERLETTER_DIGIT,
    LOWERLETTER_DIGIT_UNDERSCORE,
    NON_ZERO_DIGIT,
    SPACE,
    UPPERLETTER,
  };

  explicit Scanner(StringPiece source) : cur_(source) { RestartCapture(); }

  // Consume the next character of the given class from input. If the next
  // character is not in the class, then GetResult will ultimately return false.
  Scanner& One(CharClass clz) {
    if (cur_.empty() || !Matches(clz, cur_[0])) {
      return Error();
    }
    cur_.remove_prefix(1);
    return *this;
  }

  // Consume the next s.size() characters of the input, if they match <s>. If
  // they don't match <s>, this is a no-op.
  Scanner& ZeroOrOneLiteral(StringPiece s) {
    str_util::ConsumePrefix(&cur_, s);
    return *this;
  }

  // Consume the next s.size() characters of the input, if they match <s>. If
  // they don't match <s>, then GetResult will ultimately return false.
  Scanner& OneLiteral(StringPiece s) {
    if (!str_util::ConsumePrefix(&cur_, s)) {
      error_ = true;
    }
    return *this;
  }

  // Consume characters from the input as long as they match <clz>. Zero
  // characters is still considered a match, so it will never cause GetResult to
  // return false.
  Scanner& Any(CharClass clz) {
    while (!cur_.empty() && Matches(clz, cur_[0])) {
      cur_.remove_prefix(1);
    }
    return *this;
  }

  // Shorthand for One(clz).Any(clz).
  Scanner& Many(CharClass clz) { return One(clz).Any(clz); }

  // Reset the capture start point.
  //
  // Later, when GetResult is called and if it returns true, the capture
  // returned will start at the position at the time this was called.
  Scanner& RestartCapture() {
    capture_start_ = cur_.data();
    capture_end_ = nullptr;
    return *this;
  }

  // Stop capturing input.
  //
  // Later, when GetResult is called and if it returns true, the capture
  // returned will end at the position at the time this was called.
  Scanner& StopCapture() {
    capture_end_ = cur_.data();
    return *this;
  }

  // If not at the input of input, then GetResult will ultimately return false.
  Scanner& Eos() {
    if (!cur_.empty()) error_ = true;
    return *this;
  }

  // Shorthand for Any(SPACE).
  Scanner& AnySpace() { return Any(SPACE); }

  // This scans input until <end_ch> is reached. <end_ch> is NOT consumed.
  Scanner& ScanUntil(char end_ch) {
    ScanUntilImpl(end_ch, false);
    return *this;
  }

  // This scans input until <end_ch> is reached. <end_ch> is NOT consumed.
  // Backslash escape sequences are skipped.
  // Used for implementing quoted string scanning.
  Scanner& ScanEscapedUntil(char end_ch) {
    ScanUntilImpl(end_ch, true);
    return *this;
  }

  // Return the next character that will be scanned, or <default_value> if there
  // are no more characters to scan.
  // Note that if a scan operation has failed (so GetResult() returns false),
  // then the value of Peek may or may not have advanced since the scan
  // operation that failed.
  char Peek(char default_value = '\0') const {
    return cur_.empty() ? default_value : cur_[0];
  }

  // Returns false if there are no remaining characters to consume.
  int empty() const { return cur_.empty(); }

  // Returns true if the input string successfully matched. When true is
  // returned, the remaining string is returned in <remaining> and the captured
  // string returned in <capture>, if non-NULL.
  bool GetResult(StringPiece* remaining = nullptr,
                 StringPiece* capture = nullptr);

 private:
  void ScanUntilImpl(char end_ch, bool escaped);

  Scanner& Error() {
    error_ = true;
    return *this;
  }

  static bool IsLetter(char ch) {
    return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
  }

  static bool IsLowerLetter(char ch) { return ch >= 'a' && ch <= 'z'; }

  static bool IsDigit(char ch) { return ch >= '0' && ch <= '9'; }

  static bool IsSpace(char ch) {
    return (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\f' ||
            ch == '\r');
  }

  static bool Matches(CharClass clz, char ch) {
    switch (clz) {
      case ALL:
        return true;
      case DIGIT:
        return IsDigit(ch);
      case LETTER:
        return IsLetter(ch);
      case LETTER_DIGIT:
        return IsLetter(ch) || IsDigit(ch);
      case LETTER_DIGIT_DASH_UNDERSCORE:
        return (IsLetter(ch) || IsDigit(ch) || ch == '-' || ch == '_');
      case LETTER_DIGIT_DASH_DOT_SLASH:
        return IsLetter(ch) || IsDigit(ch) || ch == '-' || ch == '.' ||
               ch == '/';
      case LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE:
        return (IsLetter(ch) || IsDigit(ch) || ch == '-' || ch == '.' ||
                ch == '/' || ch == '_');
      case LETTER_DIGIT_DOT:
        return IsLetter(ch) || IsDigit(ch) || ch == '.';
      case LETTER_DIGIT_DOT_PLUS_MINUS:
        return IsLetter(ch) || IsDigit(ch) || ch == '+' || ch == '-' ||
               ch == '.';
      case LETTER_DIGIT_DOT_UNDERSCORE:
        return IsLetter(ch) || IsDigit(ch) || ch == '.' || ch == '_';
      case LETTER_DIGIT_UNDERSCORE:
        return IsLetter(ch) || IsDigit(ch) || ch == '_';
      case LOWERLETTER:
        return ch >= 'a' && ch <= 'z';
      case LOWERLETTER_DIGIT:
        return IsLowerLetter(ch) || IsDigit(ch);
      case LOWERLETTER_DIGIT_UNDERSCORE:
        return IsLowerLetter(ch) || IsDigit(ch) || ch == '_';
      case NON_ZERO_DIGIT:
        return IsDigit(ch) && ch != '0';
      case SPACE:
        return IsSpace(ch);
      case UPPERLETTER:
        return ch >= 'A' && ch <= 'Z';
    }
    return false;
  }

  StringPiece cur_;
  const char* capture_start_ = nullptr;
  const char* capture_end_ = nullptr;
  bool error_ = false;

  friend class ScannerTest;
  TF_DISALLOW_COPY_AND_ASSIGN(Scanner);
};

}  // namespace strings
}  // namespace tensorflow

#endif  // TENSORFLOW_LIB_STRINGS_SCANNER_H_