e3caf0c9138c4dc963a0550157c606cbfa5a7658
[folly.git] / folly / experimental / DynamicParser.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 /*
17  *  Copyright (c) 2015, Facebook, Inc.
18  *  All rights reserved.
19  *
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.
23  *
24  */
25 #pragma once
26
27 #include <folly/dynamic.h>
28 #include <folly/ScopeGuard.h>
29
30 namespace folly {
31
32 /**
33  * DynamicParser provides a tiny DSL for easily, correctly, and losslessly
34  * parsing a folly::dynamic into any other representation.
35  *
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:
39  *
40  *   {"my values": {
41  *     "an int": "THIS WILL BE RECORDED AS AN ERROR, BUT WE'LL PARSE THE REST",
42  *     "a double": 3.1415,
43  *     "keys & values": {
44  *       "the sky is blue": true,
45  *       "THIS WILL ALSO BE RECORDED AS AN ERROR": "cheese",
46  *       "2+2=5": false,
47  *     }
48  *   }}
49  *
50  * To parse this JSON, you need no exception handling, it is as easy as:
51  *
52  *   folly::dynamic d = ...;  // Input
53  *   int64_t integer;  // Three outputs
54  *   double real;
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);
63  *       });
64  *     });
65  *   });
66  *
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")
71  * This will do:
72  *   std::runtime_error("Flux capacitor overload")
73  *
74  * == Keys and values are auto-converted to match your callback ==
75  *
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.
80  *
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.
83  *
84  *   Key: folly::dynamic (no conversion), std::string, int64_t
85  *   Value: folly::dynamic (no conversion), int64_t, bool, double, std::string
86  *
87  * There are 21 supported callback signatures, of three kinds:
88  *
89  *   1: No arguments -- useful if you will just call more parser methods.
90  *
91  *   5: The value alone -- the common case for optional() and required().
92  *        [&](whatever_t value) {}
93  *
94  *   15: Both the key and the value converted according to the rules above:
95  *        [&](whatever_t key, whatever_t) {}
96  *
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(); }
101  *
102  * == How `releaseErrors()` can make your parse lossless ==
103  *
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.
107  *
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.
112  *
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:
115  *
116  *   {"nested": {
117  *     "key_errors": {"key1": "explanatory message"},
118  *     "value": <whole input>,
119  *     "nested": { "key2": { "nested": {
120  *       "subkey2": {"value": <original value>, "error": "message"}
121  *     } } }
122  *   }}
123  *
124  * Errors in array items are handled just the same, but using integer keys.
125  *
126  * The advantage of this approach is that your parsing can throw wherever,
127  * and DynamicParser isolates it, allowing the good parts to parse.
128  *
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".
134  *
135  * == Limitations ==
136  *
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.
140  *
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.
143  *
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.
155  *
156  * == Future: un-parsed items ==
157  *
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:
160  *
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();
166  *
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"}}
172  *
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
176  * requested).
177  *
178  * == Future: multiple value errors ==
179  *
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.
184  */
185
186 namespace detail {
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
192
193 /**
194  * With DynamicParser::OnError::THROW, reports the first error.
195  * It is forbidden to call releaseErrors() if you catch this.
196  */
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)
201       )),
202       error_(std::move(error)) {}
203   /**
204    * Structured just like releaseErrors(), but with only 1 error inside:
205    *   {"nested": {"key1": {"nested": {"key2": {"error": "err", "value": 5}}}}}
206    * or:
207    *   {"nested": {"key1": {"key_errors": {"key3": "err"}, "value": 7}}}
208    */
209   const folly::dynamic& error() const { return error_; }
210 private:
211   folly::dynamic error_;
212 };
213
214 /**
215  * When DynamicParser is used incorrectly, it will throw this exception
216  * instead of reporting an error via releaseErrors().  It is unsafe to call
217  * any parser methods after catching a LogicError.
218  */
219 struct DynamicParserLogicError : public std::logic_error {
220   template <typename... Args>
221   explicit DynamicParserLogicError(Args&&... args)
222     : std::logic_error(folly::to<std::string>(std::forward<Args>(args)...)) {}
223 };
224
225 class DynamicParser {
226 public:
227   enum class OnError {
228     // After parsing, releaseErrors() reports all parse errors.
229     // Throws DynamicParserLogicError on programmer errors.
230     RECORD,
231     // Throws DynamicParserParseError on the first parse error, or
232     // DynamicParserLogicError on programmer errors.
233     THROW,
234   };
235
236   // You MUST NOT destroy `d` before the parser.
237   DynamicParser(OnError on_error, const folly::dynamic* d)
238     : onError_(on_error), stack_(d) {}  // Always access input through stack_
239
240   /**
241    * Once you finished the entire parse, returns a structured description of
242    * all parse errors (see top-of-file docblock).  May ONLY be called once.
243    * May NOT be called if the parse threw any kind of exception.  Returns an
244    * empty object for successful OnError::THROW parsers.
245    */
246   folly::dynamic releaseErrors() { return stack_.releaseErrors(); }
247
248   /**
249    * Error-wraps fn(auto-converted key & value) if d[key] is set. The
250    * top-of-file docblock explains the auto-conversion.
251    */
252   template <typename Fn>
253   void optional(const folly::dynamic& key, Fn);
254
255   // Like optional(), but reports an error if d[key] does not exist.
256   template <typename Fn>
257   void required(const folly::dynamic& key, Fn);
258
259   /**
260    * Iterate over the current object's keys and values. Report each item's
261    * errors under its own key in a matching sub-object of "errors".
262    */
263   template <typename Fn>
264   void objectItems(Fn);
265
266   /**
267    * Like objectItems() -- arrays are treated identically to objects with
268    * integer keys from 0 to size() - 1.
269    */
270   template <typename Fn>
271   void arrayItems(Fn);
272
273   /**
274    * The key currently being parsed (integer if inside an array). Throws if
275    * called outside of a parser callback.
276    */
277   inline const folly::dynamic& key() const { return stack_.key(); }
278   /**
279    * The value currently being parsed (initially, the input dynamic).
280    * Throws if parsing nullptr, or parsing after releaseErrors().
281    */
282   inline const folly::dynamic& value() const { return stack_.value(); }
283
284   /**
285    * By default, DynamicParser's "nested" object coerces all keys to
286    * strings, whether from arrayItems() or from p.optional(some_int, ...),
287    * to allow errors be serialized to JSON.  If you are parsing non-JSON
288    * dynamic objects with non-string keys, this is problematic.  When set to
289    * true, "nested" objects will report integer keys for errors coming from
290    * inside arrays, or the original key type from inside values of objects.
291    */
292   DynamicParser& setAllowNonStringKeyErrors(bool b) {
293     allowNonStringKeyErrors_ = b;
294     return *this;
295   }
296
297 private:
298   /**
299    * If `fn` throws an exception, wrapError() catches it and inserts an
300    * enriched description into stack_.errors_.  If lookup_key is non-null,
301    * reports a key lookup error in "key_errors", otherwise reportse a value
302    * error in "error".
303    *
304    * Not public because that would encourage users to report multiple errors
305    * per input part, which is currently unsupported.  It does not currently
306    * seem like normal user code should need this.
307    */
308   template <typename Fn>
309   void wrapError(const folly::dynamic* lookup_key, Fn);
310
311   void reportError(const folly::dynamic* lookup_k, const std::exception& ex);
312
313   template <typename Fn>
314   void parse(const folly::dynamic& key, const folly::dynamic& value, Fn fn);
315
316   // All of the above business logic obtains the part of the folly::dynamic
317   // it is examining (and the location for reporting errors) via this class,
318   // which lets it correctly handle nesting.
319   struct ParserStack {
320     struct Pop {
321       explicit Pop(ParserStack* sp)
322         : key_(sp->key_), value_(sp->value_), stackPtr_(sp) {}
323       void operator()() noexcept;  // ScopeGuard requires noexcept
324     private:
325       const folly::dynamic* key_;
326       const folly::dynamic* value_;
327       ParserStack* stackPtr_;
328     };
329
330     explicit ParserStack(const folly::dynamic* input)
331       : value_(input),
332         errors_(folly::dynamic::object()),
333         subErrors_({&errors_}) {}
334
335     // Not copiable or movable due to numerous internal pointers
336     ParserStack(const ParserStack&) = delete;
337     ParserStack& operator=(const ParserStack&) = delete;
338     ParserStack(ParserStack&&) = delete;
339     ParserStack& operator=(ParserStack&&) = delete;
340
341     // Lets user code nest parser calls by recording current key+value and
342     // returning an RAII guard to restore the old one.  `noexcept` since it
343     // is used unwrapped.
344     folly::ScopeGuardImpl<Pop> push(
345       const folly::dynamic& k, const folly::dynamic& v
346     ) noexcept;
347
348     // Throws DynamicParserLogicError if used outside of a parsing function.
349     inline const folly::dynamic& key() const;
350     // Throws DynamicParserLogicError if used after releaseErrors().
351     inline const folly::dynamic& value() const;
352
353     // Lazily creates new "nested" sub-objects in errors_.
354     folly::dynamic& errors(bool allow_non_string_keys) noexcept;
355
356     // The user invokes this at most once after the parse is done.
357     folly::dynamic releaseErrors();
358
359     // Invoked on error when using OnError::THROW.
360     [[noreturn]] void throwErrors();
361
362    private:
363     friend struct Pop;
364
365     folly::dynamic releaseErrorsImpl();  // for releaseErrors() & throwErrors()
366
367     // Null outside of a parsing function.
368     const folly::dynamic* key_{nullptr};
369     // Null on errors: when the input was nullptr, or after releaseErrors().
370     const folly::dynamic* value_;
371
372     // An object containing some of these keys:
373     //   "key_errors" -- {"key": "description of error looking up said key"}
374     //   "error" -- why did we fail to parse this value?
375     //   "value" -- a copy of the input causing the error, and
376     //   "nested" -- {"key" or integer for arrays: <another errors_ object>}
377     //
378     // "nested" will contain identically structured objects with keys (array
379     // indices) identifying the origin of the errors.  Of course, "input"
380     // would no longer refer to the whole input, but to a part.
381     folly::dynamic errors_;
382     // We only materialize errors_ sub-objects when needed. This stores keys
383     // for unmaterialized errors, from outermost to innermost.
384     std::vector<const folly::dynamic*> unmaterializedSubErrorKeys_;
385     // Materialized errors, from outermost to innermost
386     std::vector<folly::dynamic*> subErrors_;  // Point into errors_
387   };
388
389   OnError onError_;
390   ParserStack stack_;
391   bool allowNonStringKeyErrors_{false};  // See the setter's docblock.
392 };
393
394 }  // namespace folly
395
396 #include <folly/experimental/DynamicParser-inl.h>