2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 * Copyright (c) 2015, Facebook, Inc.
18 * All rights reserved.
20 * This source code is licensed under the BSD-style license found in the
21 * LICENSE file in the root directory of this source tree. An additional grant
22 * of patent rights can be found in the PATENTS file in the same directory.
27 #include <folly/ScopeGuard.h>
28 #include <folly/dynamic.h>
33 * DynamicParser provides a tiny DSL for easily, correctly, and losslessly
34 * parsing a folly::dynamic into any other representation.
36 * To make this concrete, this lets you take a JSON config that potentially
37 * contains user errors, and parse __all__ of its valid parts, while
38 * automatically and __reversibly__ recording any parts that cause errors:
41 * "an int": "THIS WILL BE RECORDED AS AN ERROR, BUT WE'LL PARSE THE REST",
44 * "the sky is blue": true,
45 * "THIS WILL ALSO BE RECORDED AS AN ERROR": "cheese",
50 * To parse this JSON, you need no exception handling, it is as easy as:
52 * folly::dynamic d = ...; // Input
53 * int64_t integer; // Three outputs
55 * std::map<std::string, bool> enabled_widgets;
56 * DynamicParser p(DynamicParser::OnError::RECORD, &d);
57 * p.required("my values", [&]() {
58 * p.optional("an int", [&](int64_t v) { integer = v; });
59 * p.required("a double", [&](double v) { real = v; });
60 * p.optional("keys & values", [&]() {
61 * p.objectItems([&](std::string widget, bool enabled) {
62 * enabled_widgets.emplace(widget, enabled);
67 * Your code in the lambdas can throw, and this will be reported just like
68 * missing key and type conversion errors, with precise context on what part
69 * of the folly::dynamic caused the error. No need to throw:
70 * std::runtime_error("Value X at key Y caused a flux capacitor overload")
72 * std::runtime_error("Flux capacitor overload")
74 * == Keys and values are auto-converted to match your callback ==
76 * DynamicParser's optional(), required(), objectItems(), and
77 * arrayItems() automatically convert the current key and value to match the
78 * signature of the provided callback. parser.key() and parser.value() can
79 * be used to access the same data without conversion.
81 * The following types are supported -- you should generally take arguments
82 * by-value, or by-const-reference for dynamics & strings you do not copy.
84 * Key: folly::dynamic (no conversion), std::string, int64_t
85 * Value: folly::dynamic (no conversion), int64_t, bool, double, std::string
87 * There are 21 supported callback signatures, of three kinds:
89 * 1: No arguments -- useful if you will just call more parser methods.
91 * 5: The value alone -- the common case for optional() and required().
92 * [&](whatever_t value) {}
94 * 15: Both the key and the value converted according to the rules above:
95 * [&](whatever_t key, whatever_t) {}
97 * NB: The key alone should be rarely needed, but these callback styles
98 * provide it with no conversion overhead, and only minimal verbosity:
99 * [&](const std::string& k, const folly::dynamic&) {}
100 * [&]() { auto k = p.key().asString(); }
102 * == How `releaseErrors()` can make your parse lossless ==
104 * If you write parsing code by hand, you usually end up with error-handling
105 * resembling that of OnError::THROW -- the first error you hit aborts the
106 * whole parse, and you report it.
108 * OnError::RECORD offers a more user-friendly alternative for "parse,
109 * serialize, re-parse" pipelines, akin to what web-forms do. All
110 * exception-causing parts are losslessly recorded in a parallel
111 * folly::dynamic, available via releaseErrors() at the end of the parse.
113 * Suppose we fail to look up "key1" at the root, and hit a value error in
114 * "key2": {"subkey2": ...}. The error report will have the form:
117 * "key_errors": {"key1": "explanatory message"},
118 * "value": <whole input>,
119 * "nested": { "key2": { "nested": {
120 * "subkey2": {"value": <original value>, "error": "message"}
124 * Errors in array items are handled just the same, but using integer keys.
126 * The advantage of this approach is that your parsing can throw wherever,
127 * and DynamicParser isolates it, allowing the good parts to parse.
129 * Put another way, this makes it easy to implement a transformation that
130 * splits a `folly::dynamic` into a "parsed" part (which might be your
131 * struct meant for runtime use), and a matching "errors" part. As long as
132 * your successful parses are lossless, you can always reconstruct the
133 * original input from the parse output and the recorded "errors".
137 * - The input dynamic should be an object or array. wrapError() could be
138 * exposed to allow parsing single scalars, but this would not be a
139 * significant usability improvement over try-catch.
141 * - Do NOT try to parse the same part of the input dynamic twice. You
142 * might report multiple value errors, which is currently unsupported.
144 * - optional() does not support defaulting. This is unavoidable, since
145 * DynamicParser does not dictate how you record parsed data. If your
146 * parse writes into an output struct, then it ought to be initialized at
147 * construction time. If your output is initialized to default values,
148 * then you need no "default" feature. If it is not initialized, you are
149 * in trouble anyway. Suppose your optional() parse hits an error. What
150 * does your output contain?
151 * - Uninitialized data :(
152 * - You rely on an optional() feature to fall back to parsing some
153 * default dynamic. Sadly, the default hits a parse error. Now what?
154 * Since there is no good way to default, DynamicParser leaves it out.
156 * == Future: un-parsed items ==
158 * DynamicParser could support erroring on un-parsed items -- the parts of
159 * the folly::dynamic, which were never asked for. Here is an ok design:
161 * (i) At the start of parsing any value, the user may call:
162 * parser.recursivelyForbidUnparsed();
163 * parser.recursivelyAllowUnparsed();
164 * parser.locallyForbidUnparsed();
165 * parser.locallyAllowUnparsed();
167 * (ii) At the end of the parse, any unparsed items are dumped to "errors".
168 * For example, failing to parse index 1 out of ["v1", "v2", "v3"] yields:
169 * "nested": {1: {"unparsed": "v2"}}
170 * or perhaps more verbosely:
171 * "nested": {1: {"error": "unparsed value", "value": "v2"}}
173 * By default, unparsed items are allowed. Calling a "forbid" function after
174 * some keys have already been parsed is allowed to fail (this permits a
175 * lazy implementation, which has minimal overhead when "forbid" is not
178 * == Future: multiple value errors ==
180 * The present contract is that exactly one value error is reported per
181 * location in the input (multiple key lookup errors are, of course,
182 * supported). If the need arises, multiple value errors could easily be
183 * supported by replacing the "error" string with an "errors" array.
187 // Why do DynamicParser error messages use folly::dynamic pseudo-JSON?
188 // Firstly, the input dynamic need not correspond to valid JSON. Secondly,
189 // wrapError() uses integer-keyed objects to report arrary-indexing errors.
190 std::string toPseudoJson(const folly::dynamic& d);
191 } // namespace detail
194 * With DynamicParser::OnError::THROW, reports the first error.
195 * It is forbidden to call releaseErrors() if you catch this.
197 struct DynamicParserParseError : public std::runtime_error {
198 explicit DynamicParserParseError(folly::dynamic error)
199 : std::runtime_error(folly::to<std::string>(
200 "DynamicParserParseError: ", detail::toPseudoJson(error)
202 error_(std::move(error)) {}
204 * Structured just like releaseErrors(), but with only 1 error inside:
205 * {"nested": {"key1": {"nested": {"key2": {"error": "err", "value": 5}}}}}
207 * {"nested": {"key1": {"key_errors": {"key3": "err"}, "value": 7}}}
209 const folly::dynamic& error() const { return error_; }
212 folly::dynamic error_;
216 * When DynamicParser is used incorrectly, it will throw this exception
217 * instead of reporting an error via releaseErrors(). It is unsafe to call
218 * any parser methods after catching a LogicError.
220 struct DynamicParserLogicError : public std::logic_error {
221 template <typename... Args>
222 explicit DynamicParserLogicError(Args&&... args)
223 : std::logic_error(folly::to<std::string>(std::forward<Args>(args)...)) {}
226 class DynamicParser {
229 // After parsing, releaseErrors() reports all parse errors.
230 // Throws DynamicParserLogicError on programmer errors.
232 // Throws DynamicParserParseError on the first parse error, or
233 // DynamicParserLogicError on programmer errors.
237 // You MUST NOT destroy `d` before the parser.
238 DynamicParser(OnError on_error, const folly::dynamic* d)
239 : onError_(on_error), stack_(d) {} // Always access input through stack_
242 * Once you finished the entire parse, returns a structured description of
243 * all parse errors (see top-of-file docblock). May ONLY be called once.
244 * May NOT be called if the parse threw any kind of exception. Returns an
245 * empty object for successful OnError::THROW parsers.
247 folly::dynamic releaseErrors() { return stack_.releaseErrors(); }
250 * Error-wraps fn(auto-converted key & value) if d[key] is set. The
251 * top-of-file docblock explains the auto-conversion.
253 template <typename Fn>
254 void optional(const folly::dynamic& key, Fn);
256 // Like optional(), but reports an error if d[key] does not exist.
257 template <typename Fn>
258 void required(const folly::dynamic& key, Fn);
261 * Iterate over the current object's keys and values. Report each item's
262 * errors under its own key in a matching sub-object of "errors".
264 template <typename Fn>
265 void objectItems(Fn);
268 * Like objectItems() -- arrays are treated identically to objects with
269 * integer keys from 0 to size() - 1.
271 template <typename Fn>
275 * The key currently being parsed (integer if inside an array). Throws if
276 * called outside of a parser callback.
278 inline const folly::dynamic& key() const { return stack_.key(); }
280 * The value currently being parsed (initially, the input dynamic).
281 * Throws if parsing nullptr, or parsing after releaseErrors().
283 inline const folly::dynamic& value() const { return stack_.value(); }
286 * By default, DynamicParser's "nested" object coerces all keys to
287 * strings, whether from arrayItems() or from p.optional(some_int, ...),
288 * to allow errors be serialized to JSON. If you are parsing non-JSON
289 * dynamic objects with non-string keys, this is problematic. When set to
290 * true, "nested" objects will report integer keys for errors coming from
291 * inside arrays, or the original key type from inside values of objects.
293 DynamicParser& setAllowNonStringKeyErrors(bool b) {
294 allowNonStringKeyErrors_ = b;
300 * If `fn` throws an exception, wrapError() catches it and inserts an
301 * enriched description into stack_.errors_. If lookup_key is non-null,
302 * reports a key lookup error in "key_errors", otherwise reportse a value
305 * Not public because that would encourage users to report multiple errors
306 * per input part, which is currently unsupported. It does not currently
307 * seem like normal user code should need this.
309 template <typename Fn>
310 void wrapError(const folly::dynamic* lookup_key, Fn);
312 void reportError(const folly::dynamic* lookup_k, const std::exception& ex);
314 template <typename Fn>
315 void parse(const folly::dynamic& key, const folly::dynamic& value, Fn fn);
317 // All of the above business logic obtains the part of the folly::dynamic
318 // it is examining (and the location for reporting errors) via this class,
319 // which lets it correctly handle nesting.
322 explicit Pop(ParserStack* sp)
323 : key_(sp->key_), value_(sp->value_), stackPtr_(sp) {}
324 void operator()() noexcept; // ScopeGuard requires noexcept
326 const folly::dynamic* key_;
327 const folly::dynamic* value_;
328 ParserStack* stackPtr_;
331 explicit ParserStack(const folly::dynamic* input)
333 errors_(folly::dynamic::object()),
334 subErrors_({&errors_}) {}
336 // Not copiable or movable due to numerous internal pointers
337 ParserStack(const ParserStack&) = delete;
338 ParserStack& operator=(const ParserStack&) = delete;
339 ParserStack(ParserStack&&) = delete;
340 ParserStack& operator=(ParserStack&&) = delete;
342 // Lets user code nest parser calls by recording current key+value and
343 // returning an RAII guard to restore the old one. `noexcept` since it
344 // is used unwrapped.
345 folly::ScopeGuardImpl<Pop> push(
346 const folly::dynamic& k, const folly::dynamic& v
349 // Throws DynamicParserLogicError if used outside of a parsing function.
350 inline const folly::dynamic& key() const;
351 // Throws DynamicParserLogicError if used after releaseErrors().
352 inline const folly::dynamic& value() const;
354 // Lazily creates new "nested" sub-objects in errors_.
355 folly::dynamic& errors(bool allow_non_string_keys) noexcept;
357 // The user invokes this at most once after the parse is done.
358 folly::dynamic releaseErrors();
360 // Invoked on error when using OnError::THROW.
361 [[noreturn]] void throwErrors();
366 folly::dynamic releaseErrorsImpl(); // for releaseErrors() & throwErrors()
368 // Null outside of a parsing function.
369 const folly::dynamic* key_{nullptr};
370 // Null on errors: when the input was nullptr, or after releaseErrors().
371 const folly::dynamic* value_;
373 // An object containing some of these keys:
374 // "key_errors" -- {"key": "description of error looking up said key"}
375 // "error" -- why did we fail to parse this value?
376 // "value" -- a copy of the input causing the error, and
377 // "nested" -- {"key" or integer for arrays: <another errors_ object>}
379 // "nested" will contain identically structured objects with keys (array
380 // indices) identifying the origin of the errors. Of course, "input"
381 // would no longer refer to the whole input, but to a part.
382 folly::dynamic errors_;
383 // We only materialize errors_ sub-objects when needed. This stores keys
384 // for unmaterialized errors, from outermost to innermost.
385 std::vector<const folly::dynamic*> unmaterializedSubErrorKeys_;
386 // Materialized errors, from outermost to innermost
387 std::vector<folly::dynamic*> subErrors_; // Point into errors_
392 bool allowNonStringKeyErrors_{false}; // See the setter's docblock.
397 #include <folly/experimental/DynamicParser-inl.h>