rapidyaml  0.7.0
parse and emit YAML, and do it fast
parse_engine.hpp
Go to the documentation of this file.
1 #ifndef _C4_YML_PARSE_ENGINE_HPP_
2 #define _C4_YML_PARSE_ENGINE_HPP_
3 
4 #ifndef _C4_YML_DETAIL_PARSER_DBG_HPP_
5 #include "c4/yml/detail/parser_dbg.hpp"
6 #endif
7 
8 #ifndef _C4_YML_PARSER_STATE_HPP_
10 #endif
11 
12 
13 #if defined(_MSC_VER)
14 # pragma warning(push)
15 # pragma warning(disable: 4251/*needs to have dll-interface to be used by clients of struct*/)
16 #endif
17 
18 
19 namespace c4 {
20 namespace yml {
21 
22 /** @addtogroup doc_parse
23  * @{ */
24 
25 /** @defgroup doc_event_handlers Event Handlers
26  *
27  * @brief rapidyaml implements its parsing logic with a two-level
28  * model, where a @ref ParseEngine object reads through the YAML
29  * source, and dispatches events to an EventHandler bound to the @ref
30  * ParseEngine. Because @ref ParseEngine is templated on the event
31  * handler, the binding uses static polymorphism, without any virtual
32  * functions. The actual handler object can be changed at run time,
33  * (but of course needs to be the type of the template parameter).
34  * This is thus a very efficient architecture, and further enables the
35  * user to provide his own custom handler if he wishes to bypass the
36  * rapidyaml @ref Tree.
37  *
38  * There are two handlers implemented in this project:
39  *
40  * - @ref EventHandlerTree is the handler responsible for creating the
41  * ryml @ref Tree
42  *
43  * - @ref EventHandlerYamlStd is the handler responsible for emitting
44  * standardized [YAML test suite
45  * events](https://github.com/yaml/yaml-test-suite), used (only) in
46  * the CI of this project.
47  *
48  *
49  * ### Event model
50  *
51  * The event model used by the parse engine and event handlers follows
52  * very closely the event model in the [YAML test
53  * suite](https://github.com/yaml/yaml-test-suite).
54  *
55  * Consider for example this YAML,
56  * ```yaml
57  * {foo: bar,foo2: bar2}
58  * ```
59  * which would produce these events in the test-suite parlance:
60  * ```
61  * +STR
62  * +DOC
63  * +MAP {}
64  * =VAL :foo
65  * =VAL :bar
66  * =VAL :foo2
67  * =VAL :bar2
68  * -MAP
69  * -DOC
70  * -STR
71  * ```
72  *
73  * For reference, the @ref ParseEngine object will produce this
74  * sequence of calls to its bound EventHandler:
75  * ```cpp
76  * handler.begin_stream();
77  * handler.begin_doc();
78  * handler.begin_map_val_flow();
79  * handler.set_key_scalar_plain("foo");
80  * handler.set_val_scalar_plain("bar");
81  * handler.add_sibling();
82  * handler.set_key_scalar_plain("foo2");
83  * handler.set_val_scalar_plain("bar2");
84  * handler.end_map();
85  * handler.end_doc();
86  * handler.end_stream();
87  * ```
88  *
89  * For many other examples of all areas of YAML and how ryml's parse
90  * model corresponds to the YAML standard model, refer to the [unit
91  * tests for the parse
92  * engine](https://github.com/biojppm/rapidyaml/tree/master/test/test_parse_engine.cpp).
93  *
94  *
95  * ### Special events
96  *
97  * Most of the parsing events adopted by rapidyaml in its event model
98  * are fairly obvious, but there are two less-obvious events requiring
99  * some explanation.
100  *
101  * These events exist to make it easier to parse some special YAML
102  * cases. They are called by the parser when a just-handled
103  * value/container is actually the first key of a new map:
104  *
105  * - `actually_val_is_first_key_of_new_map_flow()` (@ref EventHandlerTree::actually_val_is_first_key_of_new_map_flow() "see implementation in EventHandlerTree" / @ref EventHandlerYamlStd::actually_val_is_first_key_of_new_map_flow() "see implementation in EventHandlerYamlStd")
106  * - `actually_val_is_first_key_of_new_map_block()` (@ref EventHandlerTree::actually_val_is_first_key_of_new_map_block() "see implementation in EventHandlerTree" / @ref EventHandlerYamlStd::actually_val_is_first_key_of_new_map_block() "see implementation in EventHandlerYamlStd")
107  *
108  * For example, consider an implicit map inside a seq: `[a: b, c:
109  * d]` which is parsed as `[{a: b}, {c: d}]`. The standard event
110  * sequence for this YAML would be the following:
111  * ```cpp
112  * handler.begin_seq_val_flow();
113  * handler.begin_map_val_flow();
114  * handler.set_key_scalar_plain("a");
115  * handler.set_val_scalar_plain("b");
116  * handler.end_map();
117  * handler.add_sibling();
118  * handler.begin_map_val_flow();
119  * handler.set_key_scalar_plain("c");
120  * handler.set_val_scalar_plain("d");
121  * handler.end_map();
122  * handler.end_seq();
123  * ```
124  * The problem with this event sequence is that it forces the
125  * parser to delay setting the val scalar (in this case "a" and
126  * "c") until it knows whether the scalar is a key or a val. This
127  * would require the parser to store the scalar until this
128  * time. For instance, in the example above, the parser should
129  * delay setting "a" and "c", because they are in fact keys and
130  * not vals. Until then, the parser would have to store "a" and
131  * "c" in its internal state. The downside is that this complexity
132  * cost would apply even if there is no implicit map -- every val
133  * in a seq would have to be delayed until one of the
134  * disambiguating subsequent tokens `,-]:` is found.
135  * By calling this function, the parser can avoid this complexity,
136  * by preemptively setting the scalar as a val. Then a call to
137  * this function will create the map and rearrange the scalar as
138  * key. Now the cost applies only once: when a seqimap starts. So
139  * the following (easier and cheaper) event sequence below has the
140  * same effect as the event sequence above:
141  * ```cpp
142  * handler.begin_seq_val_flow();
143  * handler.set_val_scalar_plain("notmap");
144  * handler.set_val_scalar_plain("a"); // preemptively set "a" as val!
145  * handler.actually_as_new_map_key(); // create a map, move the "a" val as the key of the first child of the new map
146  * handler.set_val_scalar_plain("b"); // now "a" is a key and "b" the val
147  * handler.end_map();
148  * handler.set_val_scalar_plain("c"); // "c" also as val!
149  * handler.actually_as_block_flow(); // likewise
150  * handler.set_val_scalar_plain("d"); // now "c" is a key and "b" the val
151  * handler.end_map();
152  * handler.end_seq();
153  * ```
154  * This also applies to container keys (although ryml's tree
155  * cannot accomodate these): the parser can preemptively set a
156  * container as a val, and call this event to turn that container
157  * into a key. For example, consider this yaml:
158  * ```yaml
159  * [aa, bb]: [cc, dd]
160  * # ^ ^ ^
161  * # | | |
162  * # (2) (1) (3) <- event sequence
163  * ```
164  * The standard event sequence for this YAML would be the
165  * following:
166  * ```cpp
167  * handler.begin_map_val_block(); // (1)
168  * handler.begin_seq_key_flow(); // (2)
169  * handler.set_val_scalar_plain("aa");
170  * handler.add_sibling();
171  * handler.set_val_scalar_plain("bb");
172  * handler.end_seq();
173  * handler.begin_seq_val_flow(); // (3)
174  * handler.set_val_scalar_plain("cc");
175  * handler.add_sibling();
176  * handler.set_val_scalar_plain("dd");
177  * handler.end_seq();
178  * handler.end_map();
179  * ```
180  * The problem with the sequence above is that, reading from
181  * left-to-right, the parser can only detect the proper calls at
182  * (1) and (2) once it reaches (1) in the YAML source. So, the
183  * parser would have to buffer the entire event sequence starting
184  * from the beginning until it reaches (1). Using this function,
185  * the parser can do instead:
186  * ```cpp
187  * handler.begin_seq_val_flow(); // (2) -- preemptively as val!
188  * handler.set_val_scalar_plain("aa");
189  * handler.add_sibling();
190  * handler.set_val_scalar_plain("bb");
191  * handler.end_seq();
192  * handler.actually_as_new_map_key(); // (1) -- adjust when finding that the prev val was actually a key.
193  * handler.begin_seq_val_flow(); // (3) -- go on as before
194  * handler.set_val_scalar_plain("cc");
195  * handler.add_sibling();
196  * handler.set_val_scalar_plain("dd");
197  * handler.end_seq();
198  * handler.end_map();
199  * ```
200  */
201 
202 class Tree;
203 class NodeRef;
204 class ConstNodeRef;
205 
206 
207 //-----------------------------------------------------------------------------
208 //-----------------------------------------------------------------------------
209 //-----------------------------------------------------------------------------
210 
211 /** Options to give to the parser to control its behavior. */
213 {
214 private:
215 
216  typedef enum : uint32_t {
217  SCALAR_FILTERING = (1u << 0),
218  LOCATIONS = (1u << 1),
219  DEFAULTS = SCALAR_FILTERING,
220  } Flags_e;
221 
222  uint32_t flags = DEFAULTS;
223 
224 public:
225 
226  ParserOptions() = default;
227 
228 public:
229 
230  /** @name source location tracking */
231  /** @{ */
232 
233  /** enable/disable source location tracking */
234  ParserOptions& locations(bool enabled) noexcept
235  {
236  if(enabled)
237  flags |= LOCATIONS;
238  else
239  flags &= ~LOCATIONS;
240  return *this;
241  }
242  /** query source location tracking status */
243  C4_ALWAYS_INLINE bool locations() const noexcept { return (flags & LOCATIONS); }
244 
245  /** @} */
246 
247 public:
248 
249  /** @name scalar filtering status (experimental; disable at your discretion) */
250  /** @{ */
251 
252  /** enable/disable scalar filtering while parsing */
253  ParserOptions& scalar_filtering(bool enabled) noexcept
254  {
255  if(enabled)
256  flags |= SCALAR_FILTERING;
257  else
258  flags &= ~SCALAR_FILTERING;
259  return *this;
260  }
261  /** query scalar filtering status */
262  C4_ALWAYS_INLINE bool scalar_filtering() const noexcept { return (flags & SCALAR_FILTERING); }
263 
264  /** @} */
265 };
266 
267 
268 //-----------------------------------------------------------------------------
269 //-----------------------------------------------------------------------------
270 //-----------------------------------------------------------------------------
271 
272 /** This is the main driver of parsing logic: it scans the YAML or
273  * JSON source for tokens, and emits the appropriate sequence of
274  * parsing events to its event handler. The parse engine itself has no
275  * special limitations, and *can* accomodate containers as keys; it is the
276  * event handler may introduce additional constraints.
277  *
278  * There are two implemented handlers (see @ref doc_event_handlers,
279  * which has important notes about the event model):
280  *
281  * - @ref EventHandlerTree is the handler responsible for creating the
282  * ryml @ref Tree
283  *
284  * - @ref EventHandlerYamlStd is the handler responsible for emitting
285  * standardized [YAML test suite
286  * events](https://github.com/yaml/yaml-test-suite), used (only) in
287  * the CI of this project. This is not part of the library and is
288  * not installed.
289  */
290 template<class EventHandler>
292 {
293 public:
294 
295  using handler_type = EventHandler;
296 
297 public:
298 
299  /** @name construction and assignment */
300  /** @{ */
301 
302  ParseEngine(EventHandler *evt_handler, ParserOptions opts={});
303  ~ParseEngine();
304 
306  ParseEngine(ParseEngine const&);
309 
310  /** @} */
311 
312 public:
313 
314  /** @name modifiers */
315  /** @{ */
316 
317  /** Reserve a certain capacity for the parsing stack.
318  * This should be larger than the expected depth of the parsed
319  * YAML tree.
320  *
321  * The parsing stack is the only (potential) heap memory used
322  * directly by the parser.
323  *
324  * If the requested capacity is below the default
325  * stack size of 16, the memory is used directly in the parser
326  * object; otherwise it will be allocated from the heap.
327  *
328  * @note this reserves memory only for the parser itself; all the
329  * allocations for the parsed tree will go through the tree's
330  * allocator (when different).
331  *
332  * @note for maximum efficiency, the tree and the arena can (and
333  * should) also be reserved. */
334  void reserve_stack(id_type capacity)
335  {
336  m_evt_handler->m_stack.reserve(capacity);
337  }
338 
339  /** Reserve a certain capacity for the array used to track node
340  * locations in the source buffer. */
341  void reserve_locations(size_t num_source_lines)
342  {
343  _resize_locations(num_source_lines);
344  }
345 
346  RYML_DEPRECATED("filter arena no longer needed")
347  void reserve_filter_arena(size_t) {}
348 
349  /** @} */
350 
351 public:
352 
353  /** @name getters */
354  /** @{ */
355 
356  /** Get the options used to build this parser object. */
357  ParserOptions const& options() const { return m_options; }
358 
359  /** Get the current callbacks in the parser. */
360  Callbacks const& callbacks() const { RYML_ASSERT(m_evt_handler); return m_evt_handler->m_stack.m_callbacks; }
361 
362  /** Get the name of the latest file parsed by this object. */
363  csubstr filename() const { return m_file; }
364 
365  /** Get the latest YAML buffer parsed by this object. */
366  csubstr source() const { return m_buf; }
367 
368  id_type stack_capacity() const { RYML_ASSERT(m_evt_handler); return m_evt_handler->m_stack.capacity(); }
369  size_t locations_capacity() const { return m_newline_offsets_capacity; }
370 
371  RYML_DEPRECATED("filter arena no longer needed")
372  size_t filter_arena_capacity() const { return 0u; }
373 
374  /** @} */
375 
376 public:
377 
378  /** @name parse methods */
379  /** @{ */
380 
381  /** parse YAML in place, emitting events to the current handler */
382  void parse_in_place_ev(csubstr filename, substr src);
383 
384  /** parse JSON in place, emitting events to the current handler */
385  void parse_json_in_place_ev(csubstr filename, substr src);
386 
387  /** @} */
388 
389 public:
390 
391  /** @name deprecated parse methods
392  * @{ */
393 
394  /** @cond dev */
395  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_place(csubstr filename, substr yaml, Tree *t, size_t node_id);
396  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_place( substr yaml, Tree *t, size_t node_id);
397  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_place(csubstr filename, substr yaml, Tree *t );
398  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_place( substr yaml, Tree *t );
399  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_place(csubstr filename, substr yaml, NodeRef node );
400  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_place( substr yaml, NodeRef node );
401  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, Tree>::type parse_in_place(csubstr filename, substr yaml );
402  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, Tree>::type parse_in_place( substr yaml );
403  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena(csubstr filename, csubstr yaml, Tree *t, size_t node_id);
404  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena( csubstr yaml, Tree *t, size_t node_id);
405  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena(csubstr filename, csubstr yaml, Tree *t );
406  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena( csubstr yaml, Tree *t );
407  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena(csubstr filename, csubstr yaml, NodeRef node );
408  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena( csubstr yaml, NodeRef node );
409  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, Tree>::type parse_in_arena(csubstr filename, csubstr yaml );
410  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding function in parse.hpp.") typename std::enable_if<U::is_wtree, Tree>::type parse_in_arena( csubstr yaml );
411  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding csubstr version in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena(csubstr filename, substr yaml, Tree *t, size_t node_id);
412  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding csubstr version in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena( substr yaml, Tree *t, size_t node_id);
413  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding csubstr version in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena(csubstr filename, substr yaml, Tree *t );
414  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding csubstr version in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena( substr yaml, Tree *t );
415  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding csubstr version in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena(csubstr filename, substr yaml, NodeRef node );
416  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding csubstr version in parse.hpp.") typename std::enable_if<U::is_wtree, void>::type parse_in_arena( substr yaml, NodeRef node );
417  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding csubstr version in parse.hpp.") typename std::enable_if<U::is_wtree, Tree>::type parse_in_arena(csubstr filename, substr yaml );
418  template<class U=EventHandler> RYML_DEPRECATED("removed, deliberately undefined. use the freestanding csubstr version in parse.hpp.") typename std::enable_if<U::is_wtree, Tree>::type parse_in_arena( substr yaml );
419  /** @endcond */
420 
421  /** @} */
422 
423 public:
424 
425  /** @name locations */
426  /** @{ */
427 
428  /** Get the location of a node of the last tree to be parsed by this parser. */
429  Location location(Tree const& tree, id_type node_id) const;
430  /** Get the location of a node of the last tree to be parsed by this parser. */
431  Location location(ConstNodeRef node) const;
432  /** Get the string starting at a particular location, to the end
433  * of the parsed source buffer. */
434  csubstr location_contents(Location const& loc) const;
435  /** Given a pointer to a buffer position, get the location.
436  * @param[in] val must be pointing to somewhere in the source
437  * buffer that was last parsed by this object. */
438  Location val_location(const char *val) const;
439 
440  /** @} */
441 
442 public:
443 
444  /** @name scalar filtering */
445  /** @{*/
446 
447  /** filter a plain scalar */
448  FilterResult filter_scalar_plain(csubstr scalar, substr dst, size_t indentation);
449  /** filter a plain scalar in place */
450  FilterResult filter_scalar_plain_in_place(substr scalar, size_t cap, size_t indentation);
451 
452  /** filter a single-quoted scalar */
453  FilterResult filter_scalar_squoted(csubstr scalar, substr dst);
454  /** filter a single-quoted scalar in place */
455  FilterResult filter_scalar_squoted_in_place(substr scalar, size_t cap);
456 
457  /** filter a double-quoted scalar */
458  FilterResult filter_scalar_dquoted(csubstr scalar, substr dst);
459  /** filter a double-quoted scalar in place */
460  FilterResultExtending filter_scalar_dquoted_in_place(substr scalar, size_t cap);
461 
462  /** filter a block-literal scalar */
463  FilterResult filter_scalar_block_literal(csubstr scalar, substr dst, size_t indentation, BlockChomp_e chomp);
464  /** filter a block-literal scalar in place */
465  FilterResult filter_scalar_block_literal_in_place(substr scalar, size_t cap, size_t indentation, BlockChomp_e chomp);
466 
467  /** filter a block-folded scalar */
468  FilterResult filter_scalar_block_folded(csubstr scalar, substr dst, size_t indentation, BlockChomp_e chomp);
469  /** filter a block-folded scalar in place */
470  FilterResult filter_scalar_block_folded_in_place(substr scalar, size_t cap, size_t indentation, BlockChomp_e chomp);
471 
472  /** @} */
473 
474 private:
475 
476  struct ScannedScalar
477  {
478  substr scalar;
479  bool needs_filter;
480  };
481 
482  struct ScannedBlock
483  {
484  substr scalar;
485  size_t indentation;
486  BlockChomp_e chomp;
487  };
488 
489  bool _is_doc_begin(csubstr s);
490  bool _is_doc_end(csubstr s);
491 
492  bool _scan_scalar_plain_blck(ScannedScalar *C4_RESTRICT sc, size_t indentation);
493  bool _scan_scalar_plain_seq_flow(ScannedScalar *C4_RESTRICT sc);
494  bool _scan_scalar_plain_seq_blck(ScannedScalar *C4_RESTRICT sc);
495  bool _scan_scalar_plain_map_flow(ScannedScalar *C4_RESTRICT sc);
496  bool _scan_scalar_plain_map_blck(ScannedScalar *C4_RESTRICT sc);
497  bool _scan_scalar_map_json(ScannedScalar *C4_RESTRICT sc);
498  bool _scan_scalar_seq_json(ScannedScalar *C4_RESTRICT sc);
499  bool _scan_scalar_plain_unk(ScannedScalar *C4_RESTRICT sc);
500  bool _is_valid_start_scalar_plain_flow(csubstr s);
501 
502  ScannedScalar _scan_scalar_squot();
503  ScannedScalar _scan_scalar_dquot();
504 
505  void _scan_block(ScannedBlock *C4_RESTRICT sb, size_t indref);
506 
507  csubstr _scan_anchor();
508  csubstr _scan_ref_seq();
509  csubstr _scan_ref_map();
510  csubstr _scan_tag();
511 
512 public: // exposed for testing
513 
514  /** @cond dev */
515  csubstr _filter_scalar_plain(substr s, size_t indentation);
516  csubstr _filter_scalar_squot(substr s);
517  csubstr _filter_scalar_dquot(substr s);
518  csubstr _filter_scalar_literal(substr s, size_t indentation, BlockChomp_e chomp);
519  csubstr _filter_scalar_folded(substr s, size_t indentation, BlockChomp_e chomp);
520 
521  csubstr _maybe_filter_key_scalar_plain(ScannedScalar const& sc, size_t indendation);
522  csubstr _maybe_filter_val_scalar_plain(ScannedScalar const& sc, size_t indendation);
523  csubstr _maybe_filter_key_scalar_squot(ScannedScalar const& sc);
524  csubstr _maybe_filter_val_scalar_squot(ScannedScalar const& sc);
525  csubstr _maybe_filter_key_scalar_dquot(ScannedScalar const& sc);
526  csubstr _maybe_filter_val_scalar_dquot(ScannedScalar const& sc);
527  csubstr _maybe_filter_key_scalar_literal(ScannedBlock const& sb);
528  csubstr _maybe_filter_val_scalar_literal(ScannedBlock const& sb);
529  csubstr _maybe_filter_key_scalar_folded(ScannedBlock const& sb);
530  csubstr _maybe_filter_val_scalar_folded(ScannedBlock const& sb);
531  /** @endcond */
532 
533 private:
534 
535  void _handle_map_block();
536  void _handle_seq_block();
537  void _handle_map_flow();
538  void _handle_seq_flow();
539  void _handle_seq_imap();
540  void _handle_map_json();
541  void _handle_seq_json();
542 
543  void _handle_unk();
544  void _handle_unk_json();
545  void _handle_usty();
546 
547  void _handle_flow_skip_whitespace();
548 
549  void _end_map_blck();
550  void _end_seq_blck();
551  void _end2_map();
552  void _end2_seq();
553 
554  void _begin2_doc();
555  void _begin2_doc_expl();
556  void _end2_doc();
557  void _end2_doc_expl();
558 
559  void _maybe_begin_doc();
560  void _maybe_end_doc();
561 
562  void _start_doc_suddenly();
563  void _end_doc_suddenly();
564  void _end_doc_suddenly__pop();
565  void _end_stream();
566 
567  void _set_indentation(size_t indentation);
568  void _save_indentation();
569  void _handle_indentation_pop_from_block_seq();
570  void _handle_indentation_pop_from_block_map();
571  void _handle_indentation_pop(ParserState const* dst);
572 
573  void _maybe_skip_comment();
574  void _skip_comment();
575  void _maybe_skip_whitespace_tokens();
576  void _maybe_skipchars(char c);
577  #ifdef RYML_NO_COVERAGE__TO_BE_DELETED
578  void _maybe_skipchars_up_to(char c, size_t max_to_skip);
579  #endif
580  template<size_t N>
581  void _skipchars(const char (&chars)[N]);
582  bool _maybe_scan_following_colon() noexcept;
583  bool _maybe_scan_following_comma() noexcept;
584 
585 public:
586 
587  /** @cond dev */
588  template<class FilterProcessor> auto _filter_plain(FilterProcessor &C4_RESTRICT proc, size_t indentation) -> decltype(proc.result());
589  template<class FilterProcessor> auto _filter_squoted(FilterProcessor &C4_RESTRICT proc) -> decltype(proc.result());
590  template<class FilterProcessor> auto _filter_dquoted(FilterProcessor &C4_RESTRICT proc) -> decltype(proc.result());
591  template<class FilterProcessor> auto _filter_block_literal(FilterProcessor &C4_RESTRICT proc, size_t indentation, BlockChomp_e chomp) -> decltype(proc.result());
592  template<class FilterProcessor> auto _filter_block_folded(FilterProcessor &C4_RESTRICT proc, size_t indentation, BlockChomp_e chomp) -> decltype(proc.result());
593  /** @endcond */
594 
595 public:
596 
597  /** @cond dev */
598  template<class FilterProcessor> void _filter_nl_plain(FilterProcessor &C4_RESTRICT proc, size_t indentation);
599  template<class FilterProcessor> void _filter_nl_squoted(FilterProcessor &C4_RESTRICT proc);
600  template<class FilterProcessor> void _filter_nl_dquoted(FilterProcessor &C4_RESTRICT proc);
601 
602  template<class FilterProcessor> bool _filter_ws_handle_to_first_non_space(FilterProcessor &C4_RESTRICT proc);
603  template<class FilterProcessor> void _filter_ws_copy_trailing(FilterProcessor &C4_RESTRICT proc);
604  template<class FilterProcessor> void _filter_ws_skip_trailing(FilterProcessor &C4_RESTRICT proc);
605 
606  template<class FilterProcessor> void _filter_dquoted_backslash(FilterProcessor &C4_RESTRICT proc);
607 
608  template<class FilterProcessor> void _filter_chomp(FilterProcessor &C4_RESTRICT proc, BlockChomp_e chomp, size_t indentation);
609  template<class FilterProcessor> size_t _handle_all_whitespace(FilterProcessor &C4_RESTRICT proc, BlockChomp_e chomp);
610  template<class FilterProcessor> size_t _extend_to_chomp(FilterProcessor &C4_RESTRICT proc, size_t contents_len);
611  template<class FilterProcessor> void _filter_block_indentation(FilterProcessor &C4_RESTRICT proc, size_t indentation);
612  template<class FilterProcessor> void _filter_block_folded_newlines(FilterProcessor &C4_RESTRICT proc, size_t indentation, size_t len);
613  template<class FilterProcessor> size_t _filter_block_folded_newlines_compress(FilterProcessor &C4_RESTRICT proc, size_t num_newl, size_t wpos_at_first_newl);
614  template<class FilterProcessor> void _filter_block_folded_newlines_leading(FilterProcessor &C4_RESTRICT proc, size_t indentation, size_t len);
615  template<class FilterProcessor> void _filter_block_folded_indented_block(FilterProcessor &C4_RESTRICT proc, size_t indentation, size_t len, size_t curr_indentation) noexcept;
616 
617  /** @endcond */
618 
619 private:
620 
621  void _line_progressed(size_t ahead);
622  void _line_ended();
623  void _line_ended_undo();
624 
625  bool _finished_file() const;
626  bool _finished_line() const;
627 
628  void _scan_line();
629  substr _peek_next_line(size_t pos=npos) const;
630 
631  inline bool _at_line_begin() const
632  {
633  return m_evt_handler->m_curr->line_contents.rem.begin() == m_evt_handler->m_curr->line_contents.full.begin();
634  }
635 
636  void _relocate_arena(csubstr prev_arena, substr next_arena);
637  static void _s_relocate_arena(void*, csubstr prev_arena, substr next_arena);
638 
639 private:
640 
641  C4_ALWAYS_INLINE bool has_all(ParserFlag_t f) const noexcept { return (m_evt_handler->m_curr->flags & f) == f; }
642  C4_ALWAYS_INLINE bool has_any(ParserFlag_t f) const noexcept { return (m_evt_handler->m_curr->flags & f) != 0; }
643  C4_ALWAYS_INLINE bool has_none(ParserFlag_t f) const noexcept { return (m_evt_handler->m_curr->flags & f) == 0; }
644  static C4_ALWAYS_INLINE bool has_all(ParserFlag_t f, ParserState const* C4_RESTRICT s) noexcept { return (s->flags & f) == f; }
645  static C4_ALWAYS_INLINE bool has_any(ParserFlag_t f, ParserState const* C4_RESTRICT s) noexcept { return (s->flags & f) != 0; }
646  static C4_ALWAYS_INLINE bool has_none(ParserFlag_t f, ParserState const* C4_RESTRICT s) noexcept { return (s->flags & f) == 0; }
647 
648  #ifndef RYML_DBG
649  C4_ALWAYS_INLINE static void add_flags(ParserFlag_t on, ParserState *C4_RESTRICT s) noexcept { s->flags |= on; }
650  C4_ALWAYS_INLINE static void addrem_flags(ParserFlag_t on, ParserFlag_t off, ParserState *C4_RESTRICT s) noexcept { s->flags &= ~off; s->flags |= on; }
651  C4_ALWAYS_INLINE static void rem_flags(ParserFlag_t off, ParserState *C4_RESTRICT s) noexcept { s->flags &= ~off; }
652  C4_ALWAYS_INLINE void add_flags(ParserFlag_t on) noexcept { m_evt_handler->m_curr->flags |= on; }
653  C4_ALWAYS_INLINE void addrem_flags(ParserFlag_t on, ParserFlag_t off) noexcept { m_evt_handler->m_curr->flags &= ~off; m_evt_handler->m_curr->flags |= on; }
654  C4_ALWAYS_INLINE void rem_flags(ParserFlag_t off) noexcept { m_evt_handler->m_curr->flags &= ~off; }
655  #else
656  static void add_flags(ParserFlag_t on, ParserState *C4_RESTRICT s);
657  static void addrem_flags(ParserFlag_t on, ParserFlag_t off, ParserState *C4_RESTRICT s);
658  static void rem_flags(ParserFlag_t off, ParserState *C4_RESTRICT s);
659  C4_ALWAYS_INLINE void add_flags(ParserFlag_t on) noexcept { add_flags(on, m_evt_handler->m_curr); }
660  C4_ALWAYS_INLINE void addrem_flags(ParserFlag_t on, ParserFlag_t off) noexcept { addrem_flags(on, off, m_evt_handler->m_curr); }
661  C4_ALWAYS_INLINE void rem_flags(ParserFlag_t off) noexcept { rem_flags(off, m_evt_handler->m_curr); }
662  #endif
663 
664 private:
665 
666  void _prepare_locations();
667  void _resize_locations(size_t sz);
668  bool _locations_dirty() const;
669 
670  bool _location_from_cont(Tree const& tree, id_type node, Location *C4_RESTRICT loc) const;
671  bool _location_from_node(Tree const& tree, id_type node, Location *C4_RESTRICT loc, id_type level) const;
672 
673 private:
674 
675  void _reset();
676  void _free();
677  void _clr();
678 
679  #ifdef RYML_DBG
680  template<class ...Args> void _dbg(csubstr fmt, Args const& C4_RESTRICT ...args) const;
681  #endif
682  template<class ...Args> void _err(csubstr fmt, Args const& C4_RESTRICT ...args) const;
683  template<class ...Args> void _errloc(csubstr fmt, Location const& loc, Args const& C4_RESTRICT ...args) const;
684 
685  template<class DumpFn> void _fmt_msg(DumpFn &&dumpfn) const;
686 
687 private:
688 
689  /** store pending tag or anchor/ref annotations */
690  struct Annotation
691  {
692  struct Entry
693  {
694  csubstr str;
695  size_t indentation;
696  size_t line;
697  };
698  Entry annotations[2];
699  size_t num_entries;
700  };
701 
702  void _add_annotation(Annotation *C4_RESTRICT dst, csubstr str, size_t indentation, size_t line);
703  void _clear_annotations(Annotation *C4_RESTRICT dst);
704  bool _has_pending_annotations() const { return m_pending_tags.num_entries || m_pending_anchors.num_entries; }
705  #ifdef RYML_NO_COVERAGE__TO_BE_DELETED
706  bool _handle_indentation_from_annotations();
707  #endif
708  bool _annotations_require_key_container() const;
709  void _handle_annotations_before_blck_key_scalar();
710  void _handle_annotations_before_blck_val_scalar();
711  void _handle_annotations_before_start_mapblck(size_t current_line);
712  void _handle_annotations_before_start_mapblck_as_key();
713  void _handle_annotations_and_indentation_after_start_mapblck(size_t key_indentation, size_t key_line);
714  size_t _select_indentation_from_annotations(size_t val_indentation, size_t val_line);
715  void _handle_directive(csubstr rem);
716 
717  void _check_tag(csubstr tag);
718 
719 private:
720 
721  ParserOptions m_options;
722 
723  csubstr m_file;
724  substr m_buf;
725 
726 public:
727 
728  /** @cond dev */
729  EventHandler *C4_RESTRICT m_evt_handler;
730  /** @endcond */
731 
732 private:
733 
734  Annotation m_pending_anchors;
735  Annotation m_pending_tags;
736 
737  bool m_was_inside_qmrk;
738  bool m_doc_empty = true;
739 
740 private:
741 
742  size_t *m_newline_offsets;
743  size_t m_newline_offsets_size;
744  size_t m_newline_offsets_capacity;
745  csubstr m_newline_offsets_buf;
746 
747 };
748 
749 /** @cond dev */
750 RYML_EXPORT C4_NO_INLINE size_t _find_last_newline_and_larger_indentation(csubstr s, size_t indentation) noexcept;
751 /** @endcond */
752 
753 
754 /** Quickly inspect the source to estimate the number of nodes the
755  * resulting tree is likely have. If a tree is empty before
756  * parsing, considerable time will be spent growing it, so calling
757  * this to reserve the tree size prior to parsing is likely to
758  * result in a time gain. We encourage using this method before
759  * parsing, but as always measure its impact in performance to
760  * obtain a good trade-off.
761  *
762  * @note since this method is meant for optimizing performance, it
763  * is approximate. The result may be actually smaller than the
764  * resulting number of nodes, notably if the YAML uses implicit
765  * maps as flow seq members as in `[these: are, individual:
766  * maps]`. */
768 
769 /** @} */
770 
771 } // namespace yml
772 } // namespace c4
773 
774 #if defined(_MSC_VER)
775 # pragma warning(pop)
776 #endif
777 
778 #endif /* _C4_YML_PARSE_ENGINE_HPP_ */
Holds a pointer to an existing tree, and a node id.
Definition: node.hpp:836
A reference to a node in an existing yaml tree, offering a more convenient API than the index-based A...
Definition: node.hpp:975
This is the main driver of parsing logic: it scans the YAML or JSON source for tokens,...
Location location(Tree const &tree, id_type node_id) const
Get the location of a node of the last tree to be parsed by this parser.
void reserve_stack(id_type capacity)
Reserve a certain capacity for the parsing stack.
FilterResult filter_scalar_plain(csubstr scalar, substr dst, size_t indentation)
filter a plain scalar
csubstr location_contents(Location const &loc) const
Get the string starting at a particular location, to the end of the parsed source buffer.
FilterResult filter_scalar_squoted(csubstr scalar, substr dst)
filter a single-quoted scalar
ParseEngine(EventHandler *evt_handler, ParserOptions opts={})
FilterResult filter_scalar_dquoted(csubstr scalar, substr dst)
filter a double-quoted scalar
void reserve_filter_arena(size_t)
void parse_json_in_place_ev(csubstr filename, substr src)
parse JSON in place, emitting events to the current handler
Location val_location(const char *val) const
Given a pointer to a buffer position, get the location.
FilterResult filter_scalar_plain_in_place(substr scalar, size_t cap, size_t indentation)
filter a plain scalar in place
FilterResult filter_scalar_squoted_in_place(substr scalar, size_t cap)
filter a single-quoted scalar in place
FilterResultExtending filter_scalar_dquoted_in_place(substr scalar, size_t cap)
filter a double-quoted scalar in place
size_t locations_capacity() const
void parse_in_place_ev(csubstr filename, substr src)
parse YAML in place, emitting events to the current handler
csubstr source() const
Get the latest YAML buffer parsed by this object.
FilterResult filter_scalar_block_literal_in_place(substr scalar, size_t cap, size_t indentation, BlockChomp_e chomp)
filter a block-literal scalar in place
ParserOptions const & options() const
Get the options used to build this parser object.
size_t filter_arena_capacity() const
FilterResult filter_scalar_block_literal(csubstr scalar, substr dst, size_t indentation, BlockChomp_e chomp)
filter a block-literal scalar
id_type stack_capacity() const
Callbacks const & callbacks() const
Get the current callbacks in the parser.
EventHandler handler_type
FilterResult filter_scalar_block_folded_in_place(substr scalar, size_t cap, size_t indentation, BlockChomp_e chomp)
filter a block-folded scalar in place
ParseEngine & operator=(ParseEngine &&)
csubstr filename() const
Get the name of the latest file parsed by this object.
void reserve_locations(size_t num_source_lines)
Reserve a certain capacity for the array used to track node locations in the source buffer.
FilterResult filter_scalar_block_folded(csubstr scalar, substr dst, size_t indentation, BlockChomp_e chomp)
filter a block-folded scalar
#define RYML_EXPORT
Definition: export.hpp:15
void parse_in_arena(Parser *parser, csubstr filename, csubstr yaml, Tree *t, id_type node_id)
(1) parse YAML into an existing tree node. The filename will be used in any error messages arising du...
Definition: parse.cpp:91
void parse_in_place(Parser *parser, csubstr filename, substr yaml, Tree *t, id_type node_id)
(1) parse YAML into an existing tree node.
Definition: parse.cpp:37
id_type estimate_tree_capacity(csubstr src)
Quickly inspect the source to estimate the number of nodes the resulting tree is likely have.
Definition: parse.cpp:152
RYML_ID_TYPE id_type
The type of a node id in the YAML tree; to override the default type, define the macro RYML_ID_TYPE t...
Definition: common.hpp:252
@ npos
a null string position
Definition: common.hpp:266
size_t _find_last_newline_and_larger_indentation(csubstr s, size_t indentation) noexcept
Definition: parse.cpp:132
int ParserFlag_t
data type for ParserState_e
Definition: common.cpp:12
a c-style callbacks class.
Definition: common.hpp:375
a source file position
Definition: common.hpp:296
Options to give to the parser to control its behavior.
ParserOptions & scalar_filtering(bool enabled) noexcept
enable/disable scalar filtering while parsing
bool scalar_filtering() const noexcept
query scalar filtering status
bool locations() const noexcept
query source location tracking status
ParserOptions & locations(bool enabled) noexcept
enable/disable source location tracking