1 #ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_PARSER_H_
2 #define ABSL_STRINGS_INTERNAL_STR_FORMAT_PARSER_H_
3
4 #include <limits.h>
5 #include <stddef.h>
6 #include <stdlib.h>
7
8 #include <cassert>
9 #include <cstdint>
10 #include <initializer_list>
11 #include <iosfwd>
12 #include <iterator>
13 #include <memory>
14 #include <string>
15 #include <vector>
16
17 #include "absl/strings/internal/str_format/checker.h"
18 #include "absl/strings/internal/str_format/extension.h"
19
20 namespace absl {
21 ABSL_NAMESPACE_BEGIN
22 namespace str_format_internal {
23
24 enum class LengthMod : std::uint8_t { h, hh, l, ll, L, j, z, t, q, none };
25
26 std::string LengthModToString(LengthMod v);
27
28 // The analyzed properties of a single specified conversion.
29 struct UnboundConversion {
UnboundConversionUnboundConversion30 UnboundConversion()
31 : flags() /* This is required to zero all the fields of flags. */ {
32 flags.basic = true;
33 }
34
35 class InputValue {
36 public:
set_valueUnboundConversion37 void set_value(int value) {
38 assert(value >= 0);
39 value_ = value;
40 }
valueUnboundConversion41 int value() const { return value_; }
42
43 // Marks the value as "from arg". aka the '*' format.
44 // Requires `value >= 1`.
45 // When set, is_from_arg() return true and get_from_arg() returns the
46 // original value.
47 // `value()`'s return value is unspecfied in this state.
set_from_argUnboundConversion48 void set_from_arg(int value) {
49 assert(value > 0);
50 value_ = -value - 1;
51 }
is_from_argUnboundConversion52 bool is_from_arg() const { return value_ < -1; }
get_from_argUnboundConversion53 int get_from_arg() const {
54 assert(is_from_arg());
55 return -value_ - 1;
56 }
57
58 private:
59 int value_ = -1;
60 };
61
62 // No need to initialize. It will always be set in the parser.
63 int arg_position;
64
65 InputValue width;
66 InputValue precision;
67
68 Flags flags;
69 LengthMod length_mod = LengthMod::none;
70 ConversionChar conv = FormatConversionChar::kNone;
71 };
72
73 // Consume conversion spec prefix (not including '%') of [p, end) if valid.
74 // Examples of valid specs would be e.g.: "s", "d", "-12.6f".
75 // If valid, it returns the first character following the conversion spec,
76 // and the spec part is broken down and returned in 'conv'.
77 // If invalid, returns nullptr.
78 const char* ConsumeUnboundConversion(const char* p, const char* end,
79 UnboundConversion* conv, int* next_arg);
80
81 // Helper tag class for the table below.
82 // It allows fast `char -> ConversionChar/LengthMod` checking and
83 // conversions.
84 class ConvTag {
85 public:
ConvTag(ConversionChar conversion_char)86 constexpr ConvTag(ConversionChar conversion_char) // NOLINT
87 : tag_(static_cast<int8_t>(conversion_char)) {}
88 // We invert the length modifiers to make them negative so that we can easily
89 // test for them.
ConvTag(LengthMod length_mod)90 constexpr ConvTag(LengthMod length_mod) // NOLINT
91 : tag_(~static_cast<std::int8_t>(length_mod)) {}
92 // Everything else is -128, which is negative to make is_conv() simpler.
ConvTag()93 constexpr ConvTag() : tag_(-128) {}
94
is_conv()95 bool is_conv() const { return tag_ >= 0; }
is_length()96 bool is_length() const { return tag_ < 0 && tag_ != -128; }
as_conv()97 ConversionChar as_conv() const {
98 assert(is_conv());
99 return static_cast<ConversionChar>(tag_);
100 }
as_length()101 LengthMod as_length() const {
102 assert(is_length());
103 return static_cast<LengthMod>(~tag_);
104 }
105
106 private:
107 std::int8_t tag_;
108 };
109
110 extern const ConvTag kTags[256];
111 // Keep a single table for all the conversion chars and length modifiers.
GetTagForChar(char c)112 inline ConvTag GetTagForChar(char c) {
113 return kTags[static_cast<unsigned char>(c)];
114 }
115
116 // Parse the format string provided in 'src' and pass the identified items into
117 // 'consumer'.
118 // Text runs will be passed by calling
119 // Consumer::Append(string_view);
120 // ConversionItems will be passed by calling
121 // Consumer::ConvertOne(UnboundConversion, string_view);
122 // In the case of ConvertOne, the string_view that is passed is the
123 // portion of the format string corresponding to the conversion, not including
124 // the leading %. On success, it returns true. On failure, it stops and returns
125 // false.
126 template <typename Consumer>
ParseFormatString(string_view src,Consumer consumer)127 bool ParseFormatString(string_view src, Consumer consumer) {
128 int next_arg = 0;
129 const char* p = src.data();
130 const char* const end = p + src.size();
131 while (p != end) {
132 const char* percent = static_cast<const char*>(memchr(p, '%', end - p));
133 if (!percent) {
134 // We found the last substring.
135 return consumer.Append(string_view(p, end - p));
136 }
137 // We found a percent, so push the text run then process the percent.
138 if (ABSL_PREDICT_FALSE(!consumer.Append(string_view(p, percent - p)))) {
139 return false;
140 }
141 if (ABSL_PREDICT_FALSE(percent + 1 >= end)) return false;
142
143 auto tag = GetTagForChar(percent[1]);
144 if (tag.is_conv()) {
145 if (ABSL_PREDICT_FALSE(next_arg < 0)) {
146 // This indicates an error in the format std::string.
147 // The only way to get `next_arg < 0` here is to have a positional
148 // argument first which sets next_arg to -1 and then a non-positional
149 // argument.
150 return false;
151 }
152 p = percent + 2;
153
154 // Keep this case separate from the one below.
155 // ConvertOne is more efficient when the compiler can see that the `basic`
156 // flag is set.
157 UnboundConversion conv;
158 conv.conv = tag.as_conv();
159 conv.arg_position = ++next_arg;
160 if (ABSL_PREDICT_FALSE(
161 !consumer.ConvertOne(conv, string_view(percent + 1, 1)))) {
162 return false;
163 }
164 } else if (percent[1] != '%') {
165 UnboundConversion conv;
166 p = ConsumeUnboundConversion(percent + 1, end, &conv, &next_arg);
167 if (ABSL_PREDICT_FALSE(p == nullptr)) return false;
168 if (ABSL_PREDICT_FALSE(!consumer.ConvertOne(
169 conv, string_view(percent + 1, p - (percent + 1))))) {
170 return false;
171 }
172 } else {
173 if (ABSL_PREDICT_FALSE(!consumer.Append("%"))) return false;
174 p = percent + 2;
175 continue;
176 }
177 }
178 return true;
179 }
180
181 // Always returns true, or fails to compile in a constexpr context if s does not
182 // point to a constexpr char array.
EnsureConstexpr(string_view s)183 constexpr bool EnsureConstexpr(string_view s) {
184 return s.empty() || s[0] == s[0];
185 }
186
187 class ParsedFormatBase {
188 public:
189 explicit ParsedFormatBase(string_view format, bool allow_ignored,
190 std::initializer_list<Conv> convs);
191
ParsedFormatBase(const ParsedFormatBase & other)192 ParsedFormatBase(const ParsedFormatBase& other) { *this = other; }
193
ParsedFormatBase(ParsedFormatBase && other)194 ParsedFormatBase(ParsedFormatBase&& other) { *this = std::move(other); }
195
196 ParsedFormatBase& operator=(const ParsedFormatBase& other) {
197 if (this == &other) return *this;
198 has_error_ = other.has_error_;
199 items_ = other.items_;
200 size_t text_size = items_.empty() ? 0 : items_.back().text_end;
201 data_.reset(new char[text_size]);
202 memcpy(data_.get(), other.data_.get(), text_size);
203 return *this;
204 }
205
206 ParsedFormatBase& operator=(ParsedFormatBase&& other) {
207 if (this == &other) return *this;
208 has_error_ = other.has_error_;
209 data_ = std::move(other.data_);
210 items_ = std::move(other.items_);
211 // Reset the vector to make sure the invariants hold.
212 other.items_.clear();
213 return *this;
214 }
215
216 template <typename Consumer>
ProcessFormat(Consumer consumer)217 bool ProcessFormat(Consumer consumer) const {
218 const char* const base = data_.get();
219 string_view text(base, 0);
220 for (const auto& item : items_) {
221 const char* const end = text.data() + text.size();
222 text = string_view(end, (base + item.text_end) - end);
223 if (item.is_conversion) {
224 if (!consumer.ConvertOne(item.conv, text)) return false;
225 } else {
226 if (!consumer.Append(text)) return false;
227 }
228 }
229 return !has_error_;
230 }
231
has_error()232 bool has_error() const { return has_error_; }
233
234 private:
235 // Returns whether the conversions match and if !allow_ignored it verifies
236 // that all conversions are used by the format.
237 bool MatchesConversions(bool allow_ignored,
238 std::initializer_list<Conv> convs) const;
239
240 struct ParsedFormatConsumer;
241
242 struct ConversionItem {
243 bool is_conversion;
244 // Points to the past-the-end location of this element in the data_ array.
245 size_t text_end;
246 UnboundConversion conv;
247 };
248
249 bool has_error_;
250 std::unique_ptr<char[]> data_;
251 std::vector<ConversionItem> items_;
252 };
253
254
255 // A value type representing a preparsed format. These can be created, copied
256 // around, and reused to speed up formatting loops.
257 // The user must specify through the template arguments the conversion
258 // characters used in the format. This will be checked at compile time.
259 //
260 // This class uses Conv enum values to specify each argument.
261 // This allows for more flexibility as you can specify multiple possible
262 // conversion characters for each argument.
263 // ParsedFormat<char...> is a simplified alias for when the user only
264 // needs to specify a single conversion character for each argument.
265 //
266 // Example:
267 // // Extended format supports multiple characters per argument:
268 // using MyFormat = ExtendedParsedFormat<Conv::d | Conv::x>;
269 // MyFormat GetFormat(bool use_hex) {
270 // if (use_hex) return MyFormat("foo %x bar");
271 // return MyFormat("foo %d bar");
272 // }
273 // // 'format' can be used with any value that supports 'd' and 'x',
274 // // like `int`.
275 // auto format = GetFormat(use_hex);
276 // value = StringF(format, i);
277 //
278 // This class also supports runtime format checking with the ::New() and
279 // ::NewAllowIgnored() factory functions.
280 // This is the only API that allows the user to pass a runtime specified format
281 // string. These factory functions will return NULL if the format does not match
282 // the conversions requested by the user.
283 template <str_format_internal::Conv... C>
284 class ExtendedParsedFormat : public str_format_internal::ParsedFormatBase {
285 public:
ExtendedParsedFormat(string_view format)286 explicit ExtendedParsedFormat(string_view format)
287 #ifdef ABSL_INTERNAL_ENABLE_FORMAT_CHECKER
288 __attribute__((
289 enable_if(str_format_internal::EnsureConstexpr(format),
290 "Format std::string is not constexpr."),
291 enable_if(str_format_internal::ValidFormatImpl<C...>(format),
292 "Format specified does not match the template arguments.")))
293 #endif // ABSL_INTERNAL_ENABLE_FORMAT_CHECKER
294 : ExtendedParsedFormat(format, false) {
295 }
296
297 // ExtendedParsedFormat factory function.
298 // The user still has to specify the conversion characters, but they will not
299 // be checked at compile time. Instead, it will be checked at runtime.
300 // This delays the checking to runtime, but allows the user to pass
301 // dynamically sourced formats.
302 // It returns NULL if the format does not match the conversion characters.
303 // The user is responsible for checking the return value before using it.
304 //
305 // The 'New' variant will check that all the specified arguments are being
306 // consumed by the format and return NULL if any argument is being ignored.
307 // The 'NewAllowIgnored' variant will not verify this and will allow formats
308 // that ignore arguments.
New(string_view format)309 static std::unique_ptr<ExtendedParsedFormat> New(string_view format) {
310 return New(format, false);
311 }
NewAllowIgnored(string_view format)312 static std::unique_ptr<ExtendedParsedFormat> NewAllowIgnored(
313 string_view format) {
314 return New(format, true);
315 }
316
317 private:
New(string_view format,bool allow_ignored)318 static std::unique_ptr<ExtendedParsedFormat> New(string_view format,
319 bool allow_ignored) {
320 std::unique_ptr<ExtendedParsedFormat> conv(
321 new ExtendedParsedFormat(format, allow_ignored));
322 if (conv->has_error()) return nullptr;
323 return conv;
324 }
325
ExtendedParsedFormat(string_view s,bool allow_ignored)326 ExtendedParsedFormat(string_view s, bool allow_ignored)
327 : ParsedFormatBase(s, allow_ignored, {C...}) {}
328 };
329 } // namespace str_format_internal
330 ABSL_NAMESPACE_END
331 } // namespace absl
332
333 #endif // ABSL_STRINGS_INTERNAL_STR_FORMAT_PARSER_H_
334