LCOV - code coverage report
Current view: top level - src - cyaml.c (source / functions) Coverage Total Hit
Test: c_collections 2.0.0 Lines: 95.3 % 4889 4661
Test Date: 2026-11-15 18:57:05 Functions: 100.0 % 197 197
Legend: Lines: hit not hit

            Line data    Source code
       1              : /*
       2              : MIT License
       3              : 
       4              : Copyright (c) 2026 - A bunch of nerds
       5              : 
       6              : Permission is hereby granted, free of charge, to any person obtaining a copy
       7              : of this software and associated documentation files (the "Software"), to deal
       8              : in the Software without restriction, including without limitation the rights
       9              : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      10              : copies of the Software, and to permit persons to whom the Software is
      11              : furnished to do so, subject to the following conditions:
      12              : 
      13              : The above copyright notice and this permission notice shall be included in all
      14              : copies or substantial portions of the Software.
      15              : 
      16              : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      17              : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      18              : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      19              : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      20              : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      21              : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      22              : SOFTWARE.
      23              : */
      24              : 
      25              : #include <chashmap.h>
      26              : #include <cvector.h>
      27              : #include <cyaml.h>
      28              : #include <errno.h>
      29              : #include <float.h>
      30              : #include <internal/cascii.h>
      31              : #include <internal/cgrowbuf.h>
      32              : #include <internal/chashinsert.h>
      33              : #include <internal/cnumlocale.h>
      34              : #include <internal/cprocsintern.h>
      35              : #include <internal/cstrutil.h>
      36              : #include <internal/ctlsmodel.h>
      37              : #include <internal/cutf8.h>
      38              : #include <internal/test_helpers/cyaml.h>
      39              : #include <stdarg.h>
      40              : #include <stdatomic.h>
      41              : 
      42              : // The DOM node. The public handle is a pointer to it, but nothing outside this
      43              : // file reads the fields. m_procs is NULL for the default allocator or an
      44              : // interned procs copy, never the caller's own struct. tag is an owned, resolved
      45              : // tag string or NULL, and only cyaml__destroy() frees it (node_clear() keeps
      46              : // it).
      47              : typedef struct cyaml_node {
      48              :   cyaml_node_type type;
      49              :   // attached is set once the node is stored in a list or dictionary and never
      50              :   // cleared; push and set refuse an attached child, so no node gets two owners.
      51              :   // anchored is set while a parse's anchor table points at the node, so
      52              :   // parse_discard() keeps it alive. Both flags sit in padding on LP64.
      53              :   bool attached;
      54              :   bool anchored;
      55              :   ccol_memmgmt_procs *m_procs;
      56              :   char *tag;
      57              :   union {
      58              :     bool boolean;
      59              :     long long integer;
      60              :     double number;
      61              :     char *string;
      62              :     cvec list;
      63              :     chmap dictionary;
      64              :   } value;
      65              : } cyaml_node;
      66              : 
      67              : // The core merge tag. A "<<" key with this tag is a merge key, like an
      68              : // untagged plain "<<".
      69              : #define CYAML_TAG_MERGE "tag:yaml.org,2002:merge"
      70              : // The resolved form of a bare "!". No written tag may resolve to it and no node
      71              : // ever carries it; it only marks the non-specific tag during a parse.
      72              : #define CYAML_TAG_NON_SPECIFIC "!"
      73              : 
      74              : // The serializer's output buffer, a ccol_growbuf. Once oom is set every yb_*
      75              : // call does nothing.
      76              : typedef ccol_growbuf ybuf;
      77              : 
      78              : // Initialize a ybuf and append to it, for every serializer. They're thin
      79              : // wrappers that give each growbuf operation a short local name.
      80       239796 : static inline void yb_init(ybuf *b, ccol_memmgmt_procs *mp) {
      81       239796 :   ccol_growbuf_init(b, mp);
      82         1194 : }
      83              : 
      84       467524 : static inline void yb_append(ybuf *b, const char *data, size_t n) {
      85       275367 :   ccol_growbuf_append(b, data, n);
      86        23323 : }
      87              : 
      88      5144303 : static inline void yb_append_c(ybuf *b, char c) { ccol_growbuf_append_c(b, c); }
      89              : 
      90        37425 : static inline void yb_append_cstr(ybuf *b, const char *s) {
      91        37425 :   ccol_growbuf_append_cstr(b, s);
      92        11192 : }
      93              : 
      94              : // Drops trailing spaces and tabs from b, but never below floor. The
      95              : // quoted-scalar folds and the plain-scalar trim need it, since YAML drops that
      96              : // whitespace before a line break. Like the two helpers after it, it reads the
      97              : // buffer only when oom is clear, because a failed append leaves a store nobody
      98              : // may index.
      99       225822 : static inline void yb_trim_trailing_inline_ws(ybuf *b, size_t floor) {
     100       225822 :   if (b->oom) return;
     101       225910 :   while (b->len > floor &&
     102       185844 :          (b->buf[b->len - 1] == ' ' || b->buf[b->len - 1] == '\t'))
     103          210 :     b->buf[--b->len] = '\0';
     104              : }
     105              : 
     106              : // Appends the content of src to dst, when a scanner joins a temporary buffer
     107              : // into its result. A src in the OOM state adds nothing; the caller reports that
     108              : // failure itself.
     109          314 : static inline void yb_append_buf(ybuf *dst, const ybuf *src) {
     110          314 :   if (src->oom || src->len == 0) return;
     111           49 :   ccol_growbuf_append(dst, src->buf, src->len);
     112              : }
     113              : 
     114              : // True when b has readable content and its last byte is c; the serializers use
     115              : // it to end the output with exactly one newline.
     116          992 : static inline bool yb_ends_with_char(const ybuf *b, char c) {
     117          992 :   return !b->oom && b->len > 0 && b->buf[b->len - 1] == c;
     118              : }
     119              : 
     120              : #ifdef RUNNING_UNIT_TESTS
     121              : // Test hook: Runs the three helpers above on a buffer in the state a failed
     122              : // append leaves (oom set, no store, a stale length). Gives one bit per helper
     123              : // that answered without reading the store, 7 when all three did. The volatile
     124              : // values keep the compiler from folding the calls away.
     125            1 : unsigned cyaml_debug_growbuf_guard_bits(void) {
     126            1 :   char *volatile absent_store = NULL;
     127            1 :   volatile size_t stale_len = 8;
     128            1 :   unsigned bits = 0;
     129              : 
     130            1 :   ybuf hostile = {.buf = absent_store,
     131              :                   .len = stale_len,
     132              :                   .cap = 0,
     133              :                   .oom = true,
     134              :                   .m_procs = NULL};
     135            1 :   yb_trim_trailing_inline_ws(&hostile, 0);
     136            1 :   if (hostile.len == stale_len) bits |= 1u;
     137              : 
     138            1 :   ybuf dst;
     139            1 :   yb_init(&dst, NULL);
     140            1 :   yb_append_buf(&dst, &hostile);
     141            1 :   if (!dst.oom && dst.len == 0) bits |= 2u;
     142            1 :   ccol__mem_free(dst.m_procs, dst.buf);
     143              : 
     144            1 :   if (!yb_ends_with_char(&hostile, '\n')) bits |= 4u;
     145            1 :   return bits;
     146              : }
     147              : #endif
     148              : 
     149              : // Forces a helper inline into the parse driver, which is one very large
     150              : // function whose inlining budget GCC spends elsewhere. Each user was chosen by
     151              : // measuring a whole parse; measure again before adding or removing one.
     152              : #define CYAML_PARSE_HOT static inline __attribute__((always_inline))
     153              : 
     154              : // Reads a child pointer out of a list slot or dictionary value, for every walk
     155              : // over a container. It uses memcpy, the pattern the other modules built on
     156              : // chmap use for their child pointers.
     157      1727596 : static inline cyaml_node *cyaml_read_child(const void *src) {
     158      1727596 :   cyaml_node *p;
     159      1727596 :   memcpy(&p, src, sizeof(p));
     160        54947 :   return p;
     161              : }
     162              : 
     163              : // Gives the oldest member of dictionary n, where every walk in insertion order
     164              : // starts. The map keeps its entries in that order, so serializers, clone and
     165              : // the iterator all see it.
     166        38447 : static inline const ccol_chmap_entry_ref *dict_first_entry(cyaml_node *n) {
     167           41 :   return ccol_chmap_oldest_entry(n->value.dictionary);
     168              : }
     169              : 
     170              : // Each thread keeps a free list of up to CYAML_POOL_CAP default-allocator
     171              : // nodes, so a workload that parses and destroys many documents doesn't pay
     172              : // calloc and free for each node. The key's destructor drains a thread's pool
     173              : // when it exits.
     174              : #define CYAML_POOL_CAP 512U
     175              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     176              : // One thread's pool and error buffer under CCOL__EMULATE_DARWIN_TLS. The block
     177              : // is the value of the pool key, so pool_drain() gets it as its argument and
     178              : // reads no __thread variable (macOS releases those before key destructors).
     179              : typedef struct {
     180              :   cyaml_node *head;
     181              :   unsigned sz;
     182              :   char *err_buf;
     183              : } cyaml_tls;
     184              : #else
     185              : // The calling thread's node pool.
     186              : static __thread cyaml_node *pool_head = NULL;
     187              : static __thread unsigned pool_sz = 0;
     188              : // True once this thread has set its value on the pool key. One set is enough
     189              : // for the destructor to run at exit, so the lock is taken once per thread and
     190              : // not on every refill of the pool.
     191              : static __thread bool pool_key_armed = false;
     192              : #endif
     193              : #ifdef RUNNING_UNIT_TESTS
     194              : // Counts how often any thread took the pool key lock to arm the key.
     195              : atomic_ulong cyaml__pool_key_lock_count_for_tests;
     196              : #endif
     197              : 
     198              : // True while the pool key exists. It goes true at the end of the one-time init
     199              : // and false before the destructor deletes the key.
     200              : static atomic_bool pool_key_live = false;
     201              : 
     202              : // Set first thing in the shared-object destructor. A later first use (from an
     203              : // application destructor, say) then leaves the pool unarmed, because nothing
     204              : // would delete the key or drain the pool.
     205              : static atomic_bool pool_key_finalized = false;
     206              : 
     207              : // The key whose destructor, pool_drain(), frees each thread's pool and error
     208              : // buffer when the thread exits.
     209              : static ccol__thread_ls_key pool_key;
     210              : 
     211              : // Readers hold it across "check pool_key_live, then set the key", and the
     212              : // destructor holds it as writer to clear the flag and delete the key. A plain
     213              : // atomic check isn't enough: The key could be deleted under a
     214              : // pthread_setspecific() that is already running. Initialized lazily under
     215              : // pool_key_once.
     216              : static ccol__rw_lock pool_key_rwlock;
     217              : 
     218              : static void pool_drain(void *);
     219              : 
     220              : // The number of nodes the running parse on this thread may still make;
     221              : // (size_t)-1 when no parse runs, which node_alloc() treats as unlimited. Only
     222              : // parse_node_budget_arm() and _disarm() set it, and parse_common() disarms it
     223              : // on every exit, so a spent budget never leaks into later node creation.
     224              : static __thread size_t parse_node_budget = (size_t)-1;
     225              : 
     226              : // Set when node_alloc() refuses because the node budget ran out (not on a real
     227              : // OOM), so the parser can name the limit in its error.
     228              : static __thread bool parse_node_budget_exhausted = false;
     229              : 
     230              : // The DOM bytes the running parse on this thread may still use; (size_t)-1
     231              : // when no parse runs. It works like parse_node_budget.
     232              : static __thread size_t parse_byte_budget = (size_t)-1;
     233              : 
     234              : // Set when the byte budget refuses a charge, so the parser can name the limit.
     235              : static __thread bool parse_byte_budget_exhausted = false;
     236              : 
     237              : // What the byte budget charges per kind of allocation: A node, the empty
     238              : // backing store of a list or a dictionary, one dictionary entry, and the
     239              : // allocator's own overhead per block. Each figure is at or above the measured
     240              : // cost on LP64, so the budget never understates memory. List slots aren't
     241              : // charged; each one points at a child that costs far more.
     242              : #define CYAML_ALLOC_OVERHEAD ((size_t)16)
     243              : #define CYAML_BYTES_PER_NODE (sizeof(cyaml_node) + CYAML_ALLOC_OVERHEAD)
     244              : #define CYAML_BYTES_PER_LIST_BASE ((size_t)192)
     245              : #define CYAML_BYTES_PER_DICT_BASE ((size_t)320)
     246              : #define CYAML_BYTES_PER_DICT_ENTRY ((size_t)192)
     247              : 
     248              : // Charges bytes to this thread's byte budget, before each DOM allocation of a
     249              : // parse, so a document can't use unbounded memory. True when no parse runs or
     250              : // the budget has room; otherwise it zeroes the budget, sets
     251              : // parse_byte_budget_exhausted and gives false.
     252      7319526 : static inline bool parse_bytes_charge(size_t bytes) {
     253      7319526 :   if (parse_byte_budget == (size_t)-1) return true;
     254      4159385 :   if (bytes > parse_byte_budget) {
     255            9 :     parse_byte_budget = 0;
     256            9 :     parse_byte_budget_exhausted = true;
     257            0 :     return false;
     258              :   }
     259      4159376 :   parse_byte_budget -= bytes;
     260      4159376 :   return true;
     261              : }
     262              : 
     263              : // Tells whether parse_bytes_charge(bytes) would refuse, without changing
     264              : // anything. dictionary_set_impl() needs it, because a key that already exists
     265              : // must not trip the budget.
     266      1608491 : static inline bool parse_bytes_would_refuse(size_t bytes) {
     267        46039 :   return parse_byte_budget != (size_t)-1 && bytes > parse_byte_budget;
     268              : }
     269              : 
     270              : // Gives back bytes to the byte budget when the allocation they were charged for
     271              : // failed. We charge before allocating so an oversized request never reaches the
     272              : // allocator, and the refund keeps the account exact.
     273          567 : static inline void parse_bytes_refund(size_t bytes) {
     274          512 :   if (parse_byte_budget != (size_t)-1) parse_byte_budget += bytes;
     275              : }
     276              : 
     277              : // Copies s with ccol_strdup() after charging the copy to the parse byte budget,
     278              : // for scalar text and tags, so the budget bounds strings as well as nodes. NULL
     279              : // when the budget refuses or the copy fails.
     280       704929 : CYAML_PARSE_HOT char *strdup_charged(ccol_memmgmt_procs *mp, const char *s) {
     281       704929 :   size_t n = strlen(s) + 1 + CYAML_ALLOC_OVERHEAD;
     282            5 :   if (!parse_bytes_charge(n)) return NULL;
     283       704924 :   char *copy = ccol_strdup(mp, s);
     284       686221 :   if (!copy) parse_bytes_refund(n);
     285              :   return copy;
     286              : }
     287              : 
     288              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     289              : // Gives the calling thread's pool block under CCOL__EMULATE_DARWIN_TLS, without
     290              : // making one; node_alloc() and the destructor use it. NULL when the thread has
     291              : // none or the key is gone.
     292              : static cyaml_tls *cyaml_tls_peek(void) {
     293              :   if (!atomic_load_explicit(&pool_key_live, memory_order_acquire)) return NULL;
     294              :   return (cyaml_tls *)ccol__thread_ls_get(pool_key);
     295              : }
     296              : 
     297              : // Gives the calling thread's pool block under CCOL__EMULATE_DARWIN_TLS, made
     298              : // and set on the pool key on first use, for node_free() and the error buffer.
     299              : // NULL when the key is gone, memory runs out or the set fails. It takes
     300              : // pool_key_rwlock as a reader around the set; the caller has run pool_key_once.
     301              : static cyaml_tls *cyaml_tls_get(void) {
     302              :   cyaml_tls *t = cyaml_tls_peek();
     303              :   if (t || !atomic_load(&pool_key_live)) return t;
     304              :   t = (cyaml_tls *)calloc(1, sizeof(*t));
     305              :   if (!t) return NULL;
     306              :   bool set = false;
     307              :   ccol__rw_lock_rdlock(pool_key_rwlock);
     308              : #ifdef RUNNING_UNIT_TESTS
     309              :   atomic_fetch_add_explicit(&cyaml__pool_key_lock_count_for_tests, 1,
     310              :                             memory_order_relaxed);
     311              : #endif
     312              :   if (atomic_load(&pool_key_live) && ccol__thread_ls_set(pool_key, t) == 0)
     313              :     set = true;
     314              :   ccol__rw_lock_unlock(pool_key_rwlock);
     315              :   if (!set) {
     316              :     free(t);
     317              :     return NULL;
     318              :   }
     319              :   return t;
     320              : }
     321              : #else
     322              : // Sets the pool key once per thread, so pool_drain() runs at thread exit and a
     323              : // pooled node is never leaked. node_free() and cyaml_err_storage() call it. It
     324              : // takes pool_key_rwlock as a reader and sets pool_key_armed; the caller has run
     325              : // pool_key_once. Forced inline so node_free() keeps its shape.
     326        29499 : static inline __attribute__((always_inline)) void pool_key_arm(void) {
     327         2823 :   if (!pool_key_armed && atomic_load(&pool_key_live)) {
     328           12 :     ccol__rw_lock_rdlock(pool_key_rwlock);
     329              : #ifdef RUNNING_UNIT_TESTS
     330           12 :     atomic_fetch_add_explicit(&cyaml__pool_key_lock_count_for_tests, 1,
     331              :                               memory_order_relaxed);
     332              : #endif
     333           24 :     if (atomic_load(&pool_key_live) &&
     334           12 :         ccol__thread_ls_set(pool_key, (void *)1) == 0)
     335           12 :       pool_key_armed = true;
     336           12 :     ccol__rw_lock_unlock(pool_key_rwlock);
     337              :   }
     338              : }
     339              : 
     340              : // The thread's buffer for parse error messages (see cyaml_err_storage()). The
     341              : // thread-exit drain frees it with the pool.
     342              : static __thread char *cyaml_err_buf;
     343              : #endif
     344              : 
     345              : // Runs do_pool_key_init() once, on the first node allocation or free, so a
     346              : // process that never uses cyaml pays nothing.
     347              : static ccol__once_flag pool_key_once = CCOL__ONCE_INIT;
     348              : 
     349              : // Creates the rwlock and the pool key, once, through pool_key_once, so the node
     350              : // pool can drain at thread exit. pool_key_live goes true only when both work,
     351              : // so it is the one sign that the rwlock may be used. Does nothing once
     352              : // pool_key_finalized is set.
     353            4 : static void do_pool_key_init(void) {
     354            4 :   if (atomic_load(&pool_key_finalized)) return;
     355            4 :   if (ccol__rw_lock_init(pool_key_rwlock) != 0) return;
     356            4 :   if (ccol__thread_ls_key_create(pool_key, pool_drain) != 0) return;
     357            3 :   atomic_store(&pool_key_live, true);
     358              : }
     359              : 
     360              : // Tears the node pool down when the library unloads or the process exits: Sets
     361              : // pool_key_finalized, drains the calling thread's pool, then clears
     362              : // pool_key_live and deletes the key under the write lock. Without the delete,
     363              : // dlopen and dlclose cycles use up the process's keys.
     364            5 : __attribute__((destructor)) static void pool_key_fini(void) {
     365            5 :   atomic_store(&pool_key_finalized, true);
     366            5 :   if (!atomic_load(&pool_key_live)) return;
     367              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     368              :   cyaml_tls *t = cyaml_tls_peek();
     369              :   if (t) {
     370              :     (void)ccol__thread_ls_set(pool_key, NULL);
     371              :     pool_drain(t);
     372              :   }
     373              : #else
     374            4 :   pool_drain(NULL);
     375              : #endif
     376            4 :   ccol__rw_lock_wrlock(pool_key_rwlock);
     377            4 :   atomic_store(&pool_key_live, false);
     378            4 :   ccol__thread_ls_key_delete(pool_key);
     379            4 :   ccol__rw_lock_unlock(pool_key_rwlock);
     380              : }
     381              : 
     382              : // Allocates a zeroed node of the given type, the one allocation path for every
     383              : // node. mp is the allocator (NULL takes a node from the thread pool first). It
     384              : // charges the byte budget for the node plus the empty container that a list or
     385              : // dictionary gets next, and counts the node against the node budget only once
     386              : // it exists. NULL on OOM or when either budget refuses.
     387      4965712 : CYAML_PARSE_HOT cyaml_node *node_alloc(cyaml_node_type type,
     388              :                                        ccol_memmgmt_procs *mp) {
     389      4965712 :   ccol__call_once(pool_key_once, do_pool_key_init);
     390      4965713 :   if (parse_node_budget != (size_t)-1 && parse_node_budget == 0) {
     391            1 :     parse_node_budget_exhausted = true;
     392            1 :     return NULL;
     393              :   }
     394      4965712 :   size_t node_bytes = CYAML_BYTES_PER_NODE;
     395      4965712 :   if (type == CYAML_LIST)
     396              :     node_bytes += CYAML_BYTES_PER_LIST_BASE;
     397      2902104 :   else if (type == CYAML_DICTIONARY)
     398      1622760 :     node_bytes += CYAML_BYTES_PER_DICT_BASE;
     399      4965715 :   if (!parse_bytes_charge(node_bytes)) return NULL;
     400      4965709 :   cyaml_node *n;
     401              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     402              :   cyaml_tls *t = mp == NULL ? cyaml_tls_peek() : NULL;
     403              :   if (t && t->head) {
     404              :     n = t->head;
     405              :     cyaml_node *next;
     406              :     memcpy(&next, (cyaml_node **)n, sizeof(next));
     407              :     t->head = next;
     408              :     t->sz--;
     409              : #else
     410      4965709 :   if (mp == NULL && pool_head) {
     411       118174 :     n = pool_head;
     412       118174 :     cyaml_node *next;
     413       118174 :     memcpy(&next, (cyaml_node **)n, sizeof(next));
     414       118174 :     pool_head = next;
     415       118174 :     pool_sz--;
     416              : #endif
     417       118174 :     memset(n, 0, sizeof(*n));
     418              :   } else {
     419      4847535 :     n = ccol__mem_calloc(mp, 1, sizeof(*n));
     420      4847532 :     if (!n) {
     421          291 :       parse_bytes_refund(node_bytes);
     422              :       return NULL;
     423              :     }
     424              :   }
     425      4965415 :   if (parse_node_budget != (size_t)-1) parse_node_budget--;
     426      4965415 :   n->type = type;
     427      4965415 :   n->m_procs = mp;
     428        44145 :   return n;
     429              : }
     430              : 
     431              : // Frees a node struct, the one release path for every node: A default-allocator
     432              : // node goes into the thread pool unless it's full, any other node goes back to
     433              : // its own allocator. A thread that can't arm the pool key (no key left, the set
     434              : // fails, or the destructor already ran) frees the node, since nothing would
     435              : // drain its pool. The check of pool_key_live without the lock only skips an
     436              : // rwlock that was never initialized; the check under the lock is the one that
     437              : // matters.
     438      4965414 : CYAML_PARSE_HOT void node_free(cyaml_node *n) {
     439      4965414 :   if (n->m_procs != NULL) {
     440        58090 :     ccol__mem_free(n->m_procs, n);
     441        58090 :     return;
     442              :   }
     443      4907324 :   ccol__call_once(pool_key_once, do_pool_key_init);
     444              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     445              :   cyaml_tls *t = cyaml_tls_get();
     446              :   if (!t || t->sz >= CYAML_POOL_CAP) {
     447              :     free(n);
     448              :     return;
     449              :   }
     450              :   memcpy((cyaml_node **)n, &t->head, sizeof(t->head));
     451              :   t->head = n;
     452              :   t->sz++;
     453              : #else
     454      4907324 :   if (pool_sz >= CYAML_POOL_CAP) {
     455      4783768 :     free(n);
     456      4783768 :     return;
     457              :   }
     458       123556 :   if (pool_sz == 0) {
     459        29445 :     pool_key_arm();
     460        29445 :     if (!pool_key_armed) {
     461         2760 :       free(n);
     462         2760 :       return;
     463              :     }
     464              :   }
     465       120796 :   memcpy((cyaml_node **)n, &pool_head, sizeof(pool_head));
     466       120796 :   pool_head = n;
     467       120796 :   pool_sz++;
     468              : #endif
     469              : }
     470              : 
     471              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     472              : // Frees the pooled nodes and the error buffer of the block arg names; the pool
     473              : // key destructor under CCOL__EMULATE_DARWIN_TLS. A node freed later by another
     474              : // key's destructor makes a new block, and the C library calls this again for
     475              : // it.
     476              : static void pool_drain(void *arg) {
     477              :   cyaml_tls *t = (cyaml_tls *)arg;
     478              :   if (!t) return;
     479              :   cyaml_node *n = t->head;
     480              :   while (n) {
     481              :     cyaml_node *next;
     482              :     memcpy(&next, (cyaml_node **)n, sizeof(next));
     483              :     free(n);
     484              :     n = next;
     485              :   }
     486              :   free(t->err_buf);
     487              :   free(t);
     488              : }
     489              : #else
     490              : // Frees every pooled node and the error buffer of the calling thread; the pool
     491              : // key destructor. It also clears pool_key_armed, since the C library has
     492              : // cleared the key's value; a later free from another key's destructor then sets
     493              : // the key again and gets one more drain round.
     494           13 : static void pool_drain(void *arg) {
     495           13 :   (void)arg;
     496           13 :   cyaml_node *n = pool_head;
     497         3127 :   while (n) {
     498         3114 :     cyaml_node *next;
     499         3114 :     memcpy(&next, (cyaml_node **)n, sizeof(next));
     500         3114 :     free(n);
     501         3114 :     n = next;
     502              :   }
     503           13 :   pool_head = NULL;
     504           13 :   pool_sz = 0;
     505           13 :   free(cyaml_err_buf);
     506           13 :   cyaml_err_buf = NULL;
     507           13 :   pool_key_armed = false;
     508           13 : }
     509              : #endif
     510              : 
     511              : #ifdef RUNNING_UNIT_TESTS
     512              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     513              : // Test hook: Gives the size of the calling thread's pool, so tests can check
     514              : // the cap and that pools stay per thread.
     515              : size_t cyaml_debug_pool_size(void) {
     516              :   cyaml_tls *t = cyaml_tls_peek();
     517              :   return t ? (size_t)t->sz : 0;
     518              : }
     519              : #else
     520           71 : size_t cyaml_debug_pool_size(void) { return (size_t)pool_sz; }
     521              : #endif
     522              : #endif
     523              : 
     524              : // A heap worklist for tearing down a subtree without recursion. A tree built
     525              : // through the public API can be of any depth, and a destroy can't fail, so a
     526              : // depth cap would only turn a crash into a silent leak.
     527              : typedef struct destroy_worklist {
     528              :   cyaml_node **items;
     529              :   size_t cap;
     530              :   size_t len;
     531              :   // true for parse_discard()'s worklist, whose anchored nodes must survive.
     532              :   bool rescue;
     533              : } destroy_worklist;
     534              : 
     535              : static void parse_discard(cyaml_node *n);
     536              : 
     537              : // Pushes child onto the worklist (NULL is ignored), so a teardown never
     538              : // recurses per level. It grows the list with the default allocator. When the
     539              : // list can't grow, the child is destroyed at once by recursion; that needs a
     540              : // deep tree and an OOM at the same time.
     541      4871540 : static void destroy_worklist_push(destroy_worklist *wl, cyaml_node *child) {
     542      4871540 :   if (!child) return;
     543      4871540 :   if (wl->len == wl->cap) {
     544         8764 :     size_t new_cap = wl->cap == 0 ? 32 : wl->cap * 2;
     545         8764 :     cyaml_node **grown =
     546         8764 :         ccol__default_mem_realloc(wl->items, new_cap * sizeof(*wl->items));
     547         8764 :     if (!grown) {
     548            0 :       if (wl->rescue)
     549            0 :         parse_discard(child);
     550              :       else
     551            0 :         cyaml__destroy((cyaml)child);
     552            0 :       return;
     553              :     }
     554         8764 :     wl->items = grown;
     555         8764 :     wl->cap = new_cap;
     556              :   }
     557      4871540 :   wl->items[wl->len++] = child;
     558              : }
     559              : 
     560              : // Pushes the child of one dictionary entry onto the worklist in dtor_ctx; it's
     561              : // the value destructor node_clear_value() gives chashmap_destroy_with_dtor(),
     562              : // so dictionary values drain through the same loop as everything else.
     563      1643400 : static void cyaml_enqueue_dict_child(const cmap_pair *val_pair,
     564              :                                      void *dtor_ctx) {
     565      1643400 :   cyaml_node *child = cyaml_read_child(val_pair->ptr);
     566      1643400 :   destroy_worklist_push((destroy_worklist *)dtor_ctx, child);
     567      1643399 : }
     568              : 
     569              : // Frees the value payload of n (string, list or dictionary storage) and pushes
     570              : // each direct child onto wl, the one step every teardown runs per node. n
     571              : // itself, its type and its tag stay.
     572      4965221 : CYAML_PARSE_HOT void node_clear_value(cyaml_node *n, destroy_worklist *wl) {
     573      4965221 :   switch (n->type) {
     574       691046 :     case CYAML_STRING:
     575       691046 :       ccol__mem_free(n->m_procs, n->value.string);
     576       691046 :       n->value.string = NULL;
     577       691046 :       break;
     578      2063343 :     case CYAML_LIST: {
     579      2063343 :       size_t cnt = cvector_size(n->value.list);
     580      5291484 :       for (size_t i = 0; i < cnt; i++) {
     581      3228141 :         cyaml_node *child = *(cyaml_node **)cvector_at(n->value.list, i);
     582      3228142 :         destroy_worklist_push(wl, child);
     583              :       }
     584      2063342 :       cvector__destroy(n->value.list);
     585      2063343 :       n->value.list = NULL;
     586      2063343 :       break;
     587              :     }
     588      1622642 :     case CYAML_DICTIONARY: {
     589      1622642 :       chashmap_destroy_with_dtor(n->value.dictionary, cyaml_enqueue_dict_child,
     590              :                                  wl);
     591      1622642 :       n->value.dictionary = NULL;
     592      1622642 :       break;
     593              :     }
     594              :     default:
     595              :       break;
     596              :   }
     597              : }
     598              : 
     599              : // Destroys every node on wl, and through node_clear_value() everything below
     600              : // them, in a loop, so destroying a tree of any depth uses constant stack.
     601        88836 : static void destroy_worklist_drain(destroy_worklist *wl) {
     602        88836 :   while (wl->len > 0) {
     603      4851060 :     cyaml_node *n = wl->items[--wl->len];
     604      4851060 :     node_clear_value(n, wl);
     605      4851061 :     ccol__mem_free(n->m_procs, n->tag);
     606      4851060 :     n->tag = NULL;
     607      9790955 :     node_free(n);
     608              :   }
     609        88835 : }
     610              : 
     611              : // Frees the value of n and the whole subtree below it, but not n or its tag, so
     612              : // node_reinit_scalar() can write a new scalar into n in place.
     613          121 : static void node_clear(cyaml_node *n) {
     614          121 :   destroy_worklist wl = {NULL, 0, 0, false};
     615          121 :   node_clear_value(n, &wl);
     616          121 :   destroy_worklist_drain(&wl);
     617          121 :   ccol__default_mem_free(wl.items);
     618          121 : }
     619              : 
     620              : // True when tag is one of the seven core-schema tags, with the one node type it
     621              : // may decorate in *expected; the tag setter and node_drop_stale_core_tag() use
     622              : // it. The tags share an 18-byte prefix, which one strncmp() checks first.
     623         8473 : static bool core_tag_expected_type(const char *tag, cyaml_node_type *expected) {
     624         8473 :   static const char prefix[] = "tag:yaml.org,2002:";
     625         8473 :   if (strncmp(tag, prefix, sizeof(prefix) - 1) != 0) return false;
     626          168 :   const char *suffix = tag + sizeof(prefix) - 1;
     627          168 :   if (strcmp(suffix, "null") == 0)
     628           17 :     *expected = CYAML_NULL;
     629          151 :   else if (strcmp(suffix, "bool") == 0)
     630           17 :     *expected = CYAML_BOOL;
     631          134 :   else if (strcmp(suffix, "int") == 0)
     632           26 :     *expected = CYAML_INTEGER;
     633          108 :   else if (strcmp(suffix, "float") == 0)
     634           17 :     *expected = CYAML_FLOAT;
     635           91 :   else if (strcmp(suffix, "str") == 0)
     636           26 :     *expected = CYAML_STRING;
     637           65 :   else if (strcmp(suffix, "seq") == 0)
     638           19 :     *expected = CYAML_LIST;
     639           46 :   else if (strcmp(suffix, "map") == 0)
     640           18 :     *expected = CYAML_DICTIONARY;
     641              :   else
     642              :     return false;
     643              :   return true;
     644              : }
     645              : 
     646              : // Drops a core tag of n that doesn't name its type; a custom tag stays.
     647              : // Every call that changes the type of a node runs this, so a round trip never
     648              : // writes a tag the parser refuses or reads back as another type.
     649          121 : static void node_drop_stale_core_tag(cyaml_node *n) {
     650          121 :   cyaml_node_type expected;
     651          121 :   if (n->tag && core_tag_expected_type(n->tag, &expected) &&
     652           40 :       expected != n->type) {
     653           32 :     ccol__mem_free(n->m_procs, n->tag);
     654           32 :     n->tag = NULL;
     655              :   }
     656          121 : }
     657              : 
     658              : // True when a string the caller wants to store (a value, a key or a tag) is
     659              : // well-formed UTF-8, so the tree only holds text the serializer can write. NULL
     660              : // passes. Any character is fine, since the serializer can escape every one;
     661              : // only bytes that name no character are refused.
     662      1564089 : static inline bool cyaml_api_string_ok(const char *s) {
     663      1564089 :   return !s || ccol_utf8_is_valid(s, strlen(s));
     664              : }
     665              : 
     666              : // Checks a cyaml__set_typed() payload without touching a node, so a refused
     667              : // cyaml_set() changes nothing: The type must be a scalar one, raw_size must
     668              : // match the width the type needs, raw may be NULL only for CYAML_NULL, a void
     669              : // pointer value must be NULL, and a string must be well-formed UTF-8. Every
     670              : // refusal is ccol_invalid_args. Without these checks a wrong size would read
     671              : // past the caller's object.
     672          170 : static ccol_retval scalar_payload_check(cyaml_node_type type, void *raw,
     673              :                                         size_t raw_size) {
     674          170 :   switch (type) {
     675              :     case CYAML_NULL:
     676              :     case CYAML_BOOL:
     677              :     case CYAML_INTEGER:
     678              :     case CYAML_FLOAT:
     679              :     case CYAML_STRING:
     680          168 :       break;
     681              :     default:
     682              :       return ccol_invalid_args;
     683              :   }
     684              : 
     685          168 :   if (type != CYAML_NULL && !raw) return ccol_invalid_args;
     686              : 
     687          164 :   if (type == CYAML_NULL && raw && raw_size == sizeof(void *)) {
     688           16 :     void *ptr_val;
     689           16 :     memcpy(&ptr_val, raw, sizeof(ptr_val));
     690           16 :     if (ptr_val != NULL) return ccol_invalid_args;
     691              :   }
     692              : 
     693          163 :   if (type == CYAML_BOOL && raw_size != sizeof(bool)) return ccol_invalid_args;
     694              : 
     695          161 :   if (type == CYAML_INTEGER) {
     696           45 :     switch (raw_size) {
     697              :       case 1:
     698              :       case 2:
     699              :       case 4:
     700              :       case 8:
     701              :         break;
     702              :       default:
     703              :         return ccol_invalid_args;
     704              :     }
     705              :   }
     706              : 
     707          161 :   if (type == CYAML_FLOAT && raw_size != sizeof(float) &&
     708              :       raw_size != sizeof(double))
     709              :     return ccol_invalid_args;
     710              : 
     711          161 :   if (type == CYAML_STRING && raw_size != sizeof(const char *))
     712              :     return ccol_invalid_args;
     713          160 :   if (type == CYAML_STRING && !cyaml_api_string_ok(*(const char **)raw))
     714              :     return ccol_invalid_args;
     715              :   return ccol_success;
     716              : }
     717              : 
     718              : // Writes an accepted payload over the existing node n and frees what n held,
     719              : // for a cyaml_set() on a leaf that exists. A string is copied before
     720              : // node_clear(), so ccol_not_enough_memory leaves n unchanged. Integers are read
     721              : // with memcpy into a fixed-width type (the caller's object may be any type of
     722              : // that width), and an unsigned value above LLONG_MAX becomes the nearest
     723              : // double, as its decimal literal would parse.
     724          122 : static ccol_retval node_reinit_scalar_checked(cyaml_node *n,
     725              :                                               cyaml_node_type type, void *raw,
     726              :                                               size_t raw_size, bool is_signed) {
     727          122 :   char *new_str = NULL;
     728          122 :   if (type == CYAML_STRING) {
     729           30 :     const char *s = *(const char **)raw;
     730           30 :     if (s) {
     731           30 :       new_str = strdup_charged(n->m_procs, s);
     732           30 :       if (!new_str) return ccol_not_enough_memory;
     733              :     }
     734              :   }
     735              : 
     736          121 :   node_clear(n);
     737          121 :   memset(&n->value, 0, sizeof(n->value));
     738          121 :   n->type = type;
     739              : 
     740          121 :   switch (type) {
     741              :     case CYAML_NULL:
     742              :       break;
     743           17 :     case CYAML_BOOL:
     744           17 :       n->value.boolean = *(bool *)raw;
     745           17 :       break;
     746           45 :     case CYAML_INTEGER: {
     747           45 :       long long v = 0;
     748           45 :       if (is_signed) {
     749           36 :         switch (raw_size) {
     750              :           case 1: {
     751            3 :             int8_t x;
     752            3 :             memcpy(&x, raw, sizeof(x));
     753            3 :             v = x;
     754            3 :             break;
     755              :           }
     756              :           case 2: {
     757            2 :             int16_t x;
     758            2 :             memcpy(&x, raw, sizeof(x));
     759            2 :             v = x;
     760            2 :             break;
     761              :           }
     762              :           case 4: {
     763           30 :             int32_t x;
     764           30 :             memcpy(&x, raw, sizeof(x));
     765           30 :             v = x;
     766           30 :             break;
     767              :           }
     768              :           case 8: {
     769            1 :             int64_t x;
     770            1 :             memcpy(&x, raw, sizeof(x));
     771            1 :             v = x;
     772            1 :             break;
     773              :           }
     774              :         }
     775              :       } else {
     776            9 :         switch (raw_size) {
     777              :           case 1: {
     778            2 :             uint8_t x;
     779            2 :             memcpy(&x, raw, sizeof(x));
     780            2 :             v = (long long)x;
     781            2 :             break;
     782              :           }
     783              :           case 2: {
     784            2 :             uint16_t x;
     785            2 :             memcpy(&x, raw, sizeof(x));
     786            2 :             v = (long long)x;
     787            2 :             break;
     788              :           }
     789              :           case 4: {
     790            1 :             uint32_t x;
     791            1 :             memcpy(&x, raw, sizeof(x));
     792            1 :             v = (long long)x;
     793            1 :             break;
     794              :           }
     795              :           case 8: {
     796            4 :             unsigned long long u;
     797            4 :             memcpy(&u, raw, sizeof(u));
     798            4 :             if (u > (unsigned long long)LLONG_MAX) {
     799            2 :               n->type = CYAML_FLOAT;
     800            2 :               n->value.number = (double)u;
     801            2 :               node_drop_stale_core_tag(n);
     802            2 :               return ccol_success;
     803              :             }
     804           43 :             v = (long long)u;
     805              :             break;
     806              :           }
     807              :         }
     808              :       }
     809           43 :       n->value.integer = v;
     810           43 :       break;
     811              :     }
     812           14 :     case CYAML_FLOAT:
     813           28 :       n->value.number =
     814           14 :           (raw_size == sizeof(float)) ? (double)*(float *)raw : *(double *)raw;
     815           14 :       break;
     816           29 :     case CYAML_STRING:
     817           29 :       if (!new_str)
     818            0 :         n->type = CYAML_NULL;
     819              :       else
     820           29 :         n->value.string = new_str;
     821              :       break;
     822              :     default:
     823              :       break;
     824              :   }
     825          119 :   node_drop_stale_core_tag(n);
     826          119 :   return ccol_success;
     827              : }
     828              : 
     829              : // Checks a payload, then writes it over n, for cyaml__set_typed() on an
     830              : // existing leaf; a refused call leaves n unchanged.
     831           13 : static ccol_retval node_reinit_scalar(cyaml_node *n, cyaml_node_type type,
     832              :                                       void *raw, size_t raw_size,
     833              :                                       bool is_signed) {
     834           13 :   ccol_retval r = scalar_payload_check(type, raw, raw_size);
     835           13 :   if (r != ccol_success) return r;
     836            4 :   return node_reinit_scalar_checked(n, type, raw, raw_size, is_signed);
     837              : }
     838              : 
     839              : // Makes a new node from an accepted payload with allocator mp, for
     840              : // cyaml__set_typed() on a new key. Fails only with ccol_not_enough_memory, and
     841              : // *out is NULL then.
     842           29 : static ccol_retval node_make_scalar(cyaml_node_type type, void *raw,
     843              :                                     size_t raw_size, bool is_signed,
     844              :                                     ccol_memmgmt_procs *mp, cyaml_node **out) {
     845           29 :   *out = NULL;
     846           29 :   cyaml_node *n = node_alloc(CYAML_NULL, mp);
     847            1 :   if (!n) return ccol_not_enough_memory;
     848           28 :   ccol_retval r = node_reinit_scalar_checked(n, type, raw, raw_size, is_signed);
     849           28 :   if (r != ccol_success) {
     850            1 :     node_free(n);
     851            1 :     return r;
     852              :   }
     853           27 :   *out = n;
     854           27 :   return ccol_success;
     855              : }
     856              : 
     857              : // Replaces *mp with its interned copy, for every public entry point that takes
     858              : // procs, so no node points at the caller's struct. false when the intern table
     859              : // is full.
     860      1578122 : static inline bool cyaml_intern_procs(ccol_memmgmt_procs **mp) {
     861      1578122 :   if (*mp == NULL) return true;
     862         3101 :   return ccol_procs_intern(*mp, mp) == ccol_success;
     863              : }
     864              : 
     865              : // Make a node of each type with allocator mp, which is already interned. The
     866              : // public factories and the parser call them. NULL on OOM or a refused budget.
     867         3682 : static cyaml cyaml_create_null_interned(ccol_memmgmt_procs *mp) {
     868         3682 :   return (cyaml)node_alloc(CYAML_NULL, mp);
     869              : }
     870              : 
     871           16 : static cyaml cyaml_create_bool_interned(bool val, ccol_memmgmt_procs *mp) {
     872           16 :   cyaml_node *n = node_alloc(CYAML_BOOL, mp);
     873           16 :   if (n) n->value.boolean = val;
     874           16 :   return (cyaml)n;
     875              : }
     876              : 
     877       520989 : static cyaml cyaml_create_int_interned(long long val, ccol_memmgmt_procs *mp) {
     878       520989 :   cyaml_node *n = node_alloc(CYAML_INTEGER, mp);
     879       520964 :   if (n) n->value.integer = val;
     880       520989 :   return (cyaml)n;
     881              : }
     882              : 
     883           73 : static cyaml cyaml_create_double_interned(double val, ccol_memmgmt_procs *mp) {
     884           73 :   cyaml_node *n = node_alloc(CYAML_FLOAT, mp);
     885           73 :   if (n) n->value.number = val;
     886           73 :   return (cyaml)n;
     887              : }
     888              : 
     889       525447 : static cyaml cyaml_create_string_interned(const char *val,
     890              :                                           ccol_memmgmt_procs *mp) {
     891       525447 :   if (!val) return cyaml_create_null_interned(mp);
     892       525446 :   cyaml_node *n = node_alloc(CYAML_STRING, mp);
     893            3 :   if (!n) return NULL;
     894       525443 :   n->value.string = strdup_charged(mp, val);
     895       525443 :   if (!n->value.string) {
     896            6 :     node_free(n);
     897            6 :     return NULL;
     898              :   }
     899              :   return (cyaml)n;
     900              : }
     901              : 
     902      2063608 : static cyaml cyaml_create_list_interned(ccol_memmgmt_procs *mp) {
     903      2063608 :   cyaml_node *n = node_alloc(CYAML_LIST, mp);
     904           89 :   if (!n) return NULL;
     905      2063518 :   n->value.list = cvector_create_full(sizeof(cyaml_node *), mp, NULL);
     906      2063516 :   if (!n->value.list) {
     907          176 :     node_free(n);
     908          176 :     return NULL;
     909              :   }
     910              :   return (cyaml)n;
     911              : }
     912              : 
     913      1622760 : static cyaml cyaml_create_dictionary_interned(ccol_memmgmt_procs *mp) {
     914      1622760 :   cyaml_node *n = node_alloc(CYAML_DICTIONARY, mp);
     915           59 :   if (!n) return NULL;
     916      1622701 :   char *err = NULL;
     917      3245402 :   n->value.dictionary =
     918      1622701 :       ccol_chmap_create_compact(ccol_string, ccol_pointer, mp, &err);
     919      1622701 :   if (!n->value.dictionary) {
     920           59 :     node_free(n);
     921           59 :     return NULL;
     922              :   }
     923              :   return (cyaml)n;
     924              : }
     925              : 
     926              : // Make a node of each type with the caller's allocator mp, the public
     927              : // factories. They intern mp first, so a full intern table fails the call before
     928              : // any node exists.
     929         3677 : cyaml cyaml_create_null_mp(ccol_memmgmt_procs *mp) {
     930         3677 :   if (!cyaml_intern_procs(&mp)) return NULL;
     931         3677 :   return cyaml_create_null_interned(mp);
     932              : }
     933              : 
     934           14 : cyaml cyaml_create_bool_mp(bool val, ccol_memmgmt_procs *mp) {
     935           14 :   if (!cyaml_intern_procs(&mp)) return NULL;
     936           14 :   return cyaml_create_bool_interned(val, mp);
     937              : }
     938              : 
     939          130 : cyaml cyaml_create_int_mp(long long val, ccol_memmgmt_procs *mp) {
     940          132 :   if (!cyaml_intern_procs(&mp)) return NULL;
     941          129 :   return cyaml_create_int_interned(val, mp);
     942              : }
     943              : 
     944           71 : cyaml cyaml_create_double_mp(double val, ccol_memmgmt_procs *mp) {
     945           71 :   if (!cyaml_intern_procs(&mp)) return NULL;
     946           71 :   return cyaml_create_double_interned(val, mp);
     947              : }
     948              : 
     949          375 : cyaml cyaml_create_string_mp(const char *val, ccol_memmgmt_procs *mp) {
     950          375 :   if (!cyaml_api_string_ok(val)) return NULL;
     951          360 :   if (!cyaml_intern_procs(&mp)) return NULL;
     952          357 :   return cyaml_create_string_interned(val, mp);
     953              : }
     954              : 
     955         4441 : cyaml cyaml_create_list_mp(ccol_memmgmt_procs *mp) {
     956         4464 :   if (!cyaml_intern_procs(&mp)) return NULL;
     957         4441 :   return cyaml_create_list_interned(mp);
     958              : }
     959              : 
     960      1562433 : cyaml cyaml_create_dictionary_mp(ccol_memmgmt_procs *mp) {
     961      1562456 :   if (!cyaml_intern_procs(&mp)) return NULL;
     962      1562433 :   return cyaml_create_dictionary_interned(mp);
     963              : }
     964              : 
     965              : // Frees node and its whole subtree, the body of cyaml_destroy(). It uses the
     966              : // worklist, so a tree of any depth is fine. node itself is freed directly and
     967              : // never pushed, because the push's OOM fallback would call this function on
     968              : // node again.
     969        88995 : void cyaml__destroy(cyaml node) {
     970        88995 :   if (!node) return;
     971        88717 :   cyaml_node *n = (cyaml_node *)node;
     972              : 
     973        88717 :   destroy_worklist wl = {NULL, 0, 0, false};
     974        88717 :   node_clear_value(n, &wl);
     975        88716 :   ccol__mem_free(n->m_procs, n->tag);
     976        88717 :   n->tag = NULL;
     977        88717 :   node_free(n);
     978              : 
     979        88717 :   destroy_worklist_drain(&wl);
     980        88714 :   ccol__default_mem_free(wl.items);
     981              : }
     982              : 
     983              : // Gives the type of node, so callers can check before an accessor that is fatal
     984              : // on a wrong type. CYAML_NULL for a NULL handle.
     985       102734 : cyaml_node_type cyaml_type(cyaml node) {
     986       102734 :   if (!node) return CYAML_NULL;
     987       102733 :   return ((cyaml_node *)node)->type;
     988              : }
     989              : 
     990              : // Gives the tag of node, or NULL, so callers can read the tags a document
     991              : // carried.
     992        62271 : const char *cyaml_node_tag(cyaml node) {
     993        62271 :   if (!node) return NULL;
     994        62270 :   return ((cyaml_node *)node)->tag;
     995              : }
     996              : 
     997              : // Sets, replaces or (for NULL) clears the tag of node. It refuses "" (it would
     998              : // serialize as "!<>", which the parser refuses), "!", text that isn't UTF-8 and
     999              : // a core tag that doesn't name the node's type, so every tagged tree
    1000              : // round-trips. The copy is made before the old tag is freed.
    1001         1179 : ccol_retval cyaml_node_set_tag(cyaml node, const char *tag) {
    1002         1179 :   if (!node) return ccol_invalid_args;
    1003         1179 :   cyaml_node *n = (cyaml_node *)node;
    1004         1179 :   if (!tag) {
    1005            2 :     ccol__mem_free(n->m_procs, n->tag);
    1006            2 :     n->tag = NULL;
    1007            2 :     return ccol_success;
    1008              :   }
    1009         1177 :   if (tag[0] == '\0') return ccol_invalid_args;
    1010         1176 :   if (strcmp(tag, CYAML_TAG_NON_SPECIFIC) == 0) return ccol_invalid_args;
    1011         1175 :   if (!cyaml_api_string_ok(tag)) return ccol_invalid_args;
    1012         1166 :   cyaml_node_type expected;
    1013         1166 :   if (core_tag_expected_type(tag, &expected) && expected != n->type)
    1014              :     return ccol_invalid_args;
    1015         1120 :   char *copy = strdup_charged(n->m_procs, tag);
    1016            0 :   if (!copy) return ccol_not_enough_memory;
    1017         1120 :   ccol__mem_free(n->m_procs, n->tag);
    1018         1120 :   n->tag = copy;
    1019         1120 :   return ccol_success;
    1020              : }
    1021              : 
    1022              : // Give the value of a scalar node to the caller; each is fatal on NULL or a
    1023              : // wrong type, so check cyaml_type() first when unsure.
    1024          101 : bool cyaml_bool_val(cyaml node) {
    1025          101 :   cyaml_node *n = (cyaml_node *)node;
    1026          101 :   if (!n || n->type != CYAML_BOOL)
    1027            0 :     ccol__fatal_err("cyaml_bool_val: node is %s, expected CYAML_BOOL",
    1028              :                     cyaml_type_str(node));
    1029          101 :   return n->value.boolean;
    1030              : }
    1031              : 
    1032          938 : long long cyaml_int_val(cyaml node) {
    1033          938 :   cyaml_node *n = (cyaml_node *)node;
    1034          938 :   if (!n || n->type != CYAML_INTEGER)
    1035            0 :     ccol__fatal_err("cyaml_int_val: node is %s, expected CYAML_INTEGER",
    1036              :                     cyaml_type_str(node));
    1037          938 :   return n->value.integer;
    1038              : }
    1039              : 
    1040          166 : double cyaml_double_val(cyaml node) {
    1041          166 :   cyaml_node *n = (cyaml_node *)node;
    1042          166 :   if (!n || n->type != CYAML_FLOAT)
    1043            0 :     ccol__fatal_err("cyaml_double_val: node is %s, expected CYAML_FLOAT",
    1044              :                     cyaml_type_str(node));
    1045          166 :   return n->value.number;
    1046              : }
    1047              : 
    1048          772 : const char *cyaml_str_val(cyaml node) {
    1049          772 :   cyaml_node *n = (cyaml_node *)node;
    1050          772 :   if (!n || n->type != CYAML_STRING)
    1051            0 :     ccol__fatal_err("cyaml_str_val: node is %s, expected CYAML_STRING",
    1052              :                     cyaml_type_str(node));
    1053          772 :   return n->value.string;
    1054              : }
    1055              : 
    1056              : // Give the element count of a list and the key count of a dictionary, for
    1057              : // callers that walk them; each is fatal on a wrong type.
    1058        47272 : size_t cyaml_list_size(cyaml node) {
    1059        47272 :   cyaml_node *n = (cyaml_node *)node;
    1060        47272 :   if (!n || n->type != CYAML_LIST)
    1061            0 :     ccol__fatal_err("cyaml_list_size: node is %s, expected CYAML_LIST",
    1062              :                     cyaml_type_str(node));
    1063        47272 :   return cvector_size(n->value.list);
    1064              : }
    1065              : 
    1066        16365 : size_t cyaml_dictionary_size(cyaml node) {
    1067        16365 :   cyaml_node *n = (cyaml_node *)node;
    1068        16365 :   if (!n || n->type != CYAML_DICTIONARY)
    1069            0 :     ccol__fatal_err(
    1070              :         "cyaml_dictionary_size: node is %s, expected CYAML_DICTIONARY",
    1071              :         cyaml_type_str(node));
    1072        16365 :   return chashmap_size(n->value.dictionary);
    1073              : }
    1074              : 
    1075              : // Appends child to seq, which takes ownership of it. Every argument refusal is
    1076              : // ccol_invalid_args and leaves child alone, even when several apply (child ==
    1077              : // seq on a node that isn't a list), so the checks compare against seq itself.
    1078              : // cvector_push_back() can't answer ccol_invalid_args here, so that code stays
    1079              : // reserved for "child untouched"; every other failure destroys child. No cycle
    1080              : // check, as cyaml.h says.
    1081         8062 : ccol_retval cyaml_list_push(cyaml seq, cyaml child) {
    1082         8062 :   if (!child) return ccol_invalid_args;
    1083         8062 :   cyaml_node *c = (cyaml_node *)child;
    1084         8062 :   if (c->attached || (const void *)c == (const void *)seq) {
    1085              :     return ccol_invalid_args;
    1086              :   }
    1087         8057 :   if (!seq) return ccol_invalid_args;
    1088         8055 :   cyaml_node *n = (cyaml_node *)seq;
    1089         8055 :   if (n->type != CYAML_LIST) return ccol_invalid_args;
    1090         8054 :   ccol_retval r = cvector_push_back(n->value.list, &c);
    1091         8054 :   if (r != ccol_success) {
    1092            1 :     cyaml__destroy(child);
    1093            1 :     return r;
    1094              :   }
    1095         8053 :   c->attached = true;
    1096         8053 :   return r;
    1097              : }
    1098              : 
    1099              : // Gives a borrowed reference to the element at index, so callers can read a
    1100              : // list. NULL for a bad index or a node that isn't a list.
    1101        48866 : cyaml cyaml_list_get(cyaml seq, size_t index) {
    1102        48866 :   if (!seq) return NULL;
    1103        48866 :   cyaml_node *n = (cyaml_node *)seq;
    1104        48866 :   if (n->type != CYAML_LIST) return NULL;
    1105        48866 :   void *slot = cvector_at(n->value.list, index);
    1106        48866 :   if (!slot) return NULL;
    1107        48862 :   return *(cyaml *)slot;
    1108              : }
    1109              : 
    1110              : // Puts child into an existing dictionary slot, for a set of a key that already
    1111              : // exists (public set and the parser's repeated keys). The old child goes first
    1112              : // (through parse_discard(), so anchored nodes survive a running parse), then
    1113              : // the pointer is stored. Freeing the old child changes no map, so slot_vp stays
    1114              : // valid. child gets marked attached.
    1115          133 : static void dict_slot_replace_child(const cmap_pair *slot_vp,
    1116              :                                     cyaml_node *child) {
    1117          133 :   cyaml_node *old_child = cyaml_read_child(slot_vp->ptr);
    1118          133 :   parse_discard(old_child);
    1119          133 :   memcpy((void *)slot_vp->ptr, &child, sizeof(child));
    1120          133 :   child->attached = true;
    1121          133 : }
    1122              : 
    1123              : // Inserts or replaces key in map with child; the body of cyaml_dictionary_set()
    1124              : // without the UTF-8 check of the key, which the parser has already done for the
    1125              : // whole stream. Argument refusals give ccol_invalid_args and leave child alone;
    1126              : // the "already attached" refusal sits below the lookup, since setting a key to
    1127              : // the node it already holds is a no-op. A new key is charged to the parse byte
    1128              : // budget before the single-probe insert and refunded when the key turns out to
    1129              : // exist; a key that exists never trips the budget. Every other failure destroys
    1130              : // child.
    1131      1608501 : static ccol_retval dictionary_set_impl(cyaml map, const char *key,
    1132              :                                        cyaml child) {
    1133      1608501 :   if (!child) return ccol_invalid_args;
    1134      1608501 :   cyaml_node *c = (cyaml_node *)child;
    1135      1608501 :   if ((const void *)c == (const void *)map) return ccol_invalid_args;
    1136      1608499 :   if (!map || !key) return ccol_invalid_args;
    1137      1608497 :   cyaml_node *n = (cyaml_node *)map;
    1138      1608497 :   if (n->type != CYAML_DICTIONARY) return ccol_invalid_args;
    1139              : 
    1140      1608496 :   cmap_pair kp = {.ptr = (void *)key, .size = strlen(key) + 1};
    1141              : 
    1142      1608496 :   if (c->attached) {
    1143            5 :     cmap_pair held_vp;
    1144            5 :     if (chashmap_get_elem_ref(n->value.dictionary, &kp, &held_vp) ==
    1145            4 :             ccol_success &&
    1146            4 :         cyaml_read_child(held_vp.ptr) == c)
    1147              :       return ccol_success;
    1148            2 :     return ccol_invalid_args;
    1149              :   }
    1150              : 
    1151      1608491 :   size_t entry_bytes = CYAML_BYTES_PER_DICT_ENTRY + kp.size;
    1152      1608491 :   if (parse_bytes_would_refuse(entry_bytes)) {
    1153            1 :     cmap_pair held_vp;
    1154            1 :     if (chashmap_get_elem_ref(n->value.dictionary, &kp, &held_vp) ==
    1155              :         ccol_success) {
    1156            0 :       dict_slot_replace_child(&held_vp, c);
    1157            0 :       return ccol_success;
    1158              :     }
    1159              :   }
    1160      1608491 :   if (!parse_bytes_charge(entry_bytes)) {
    1161            1 :     cyaml__destroy(child);
    1162            1 :     return ccol_not_enough_memory;
    1163              :   }
    1164              : 
    1165      1608490 :   cmap_pair vp = {.ptr = &c, .size = sizeof(c)};
    1166      1608490 :   cmap_pair old_vp;
    1167      1608490 :   ccol_retval r =
    1168      1608490 :       ccol_chmap_insert_or_get_elem(n->value.dictionary, &kp, &vp, &old_vp);
    1169      1608491 :   if (r == ccol_success) {
    1170      1608290 :     c->attached = true;
    1171      1608290 :     return ccol_success;
    1172              :   }
    1173          201 :   parse_bytes_refund(entry_bytes);
    1174          201 :   if (r == ccol_key_already_present) {
    1175          133 :     dict_slot_replace_child(&old_vp, c);
    1176          133 :     return ccol_success;
    1177              :   }
    1178           68 :   cyaml__destroy((cyaml)child);
    1179           68 :   return r;
    1180              : }
    1181              : 
    1182              : // Inserts or replaces key in map. It refuses a key that isn't UTF-8 with
    1183              : // ccol_invalid_args, then defers to dictionary_set_impl().
    1184      1562471 : ccol_retval cyaml_dictionary_set(cyaml map, const char *key, cyaml child) {
    1185      1562471 :   if (!cyaml_api_string_ok(key)) return ccol_invalid_args;
    1186      1562462 :   return dictionary_set_impl(map, key, child);
    1187              : }
    1188              : 
    1189              : // Gives a borrowed reference to the value of key, so callers can read a
    1190              : // dictionary. NULL when the key is absent or map isn't a dictionary.
    1191        12221 : cyaml cyaml_dictionary_get(cyaml map, const char *key) {
    1192        12221 :   if (!map || !key) return NULL;
    1193        12221 :   cyaml_node *n = (cyaml_node *)map;
    1194        12221 :   if (n->type != CYAML_DICTIONARY) return NULL;
    1195        12221 :   cmap_pair kp = {.ptr = (void *)key, .size = strlen(key) + 1};
    1196        12221 :   cmap_pair vp;
    1197        12221 :   if (chashmap_get_elem_ref(n->value.dictionary, &kp, &vp) != ccol_success)
    1198              :     return NULL;
    1199        10330 :   return cyaml_read_child(vp.ptr);
    1200              : }
    1201              : 
    1202              : // Removes and frees the element at index, for callers that edit a list: It
    1203              : // destroys the element, moves the later ones down and pops the last slot.
    1204              : // ccol_invalid_args for a bad list or index.
    1205            9 : ccol_retval cyaml_list_remove(cyaml seq, size_t index) {
    1206            9 :   if (!seq) return ccol_invalid_args;
    1207            8 :   cyaml_node *n = (cyaml_node *)seq;
    1208            8 :   if (n->type != CYAML_LIST) return ccol_invalid_args;
    1209            8 :   size_t cnt = cvector_size(n->value.list);
    1210            8 :   if (index >= cnt) return ccol_invalid_args;
    1211              : 
    1212            7 :   cyaml_node *child = *(cyaml_node **)cvector_at(n->value.list, index);
    1213            7 :   cyaml__destroy((cyaml)child);
    1214              : 
    1215           14 :   for (size_t i = index; i + 1 < cnt; i++) {
    1216            7 :     cyaml_node **dst = (cyaml_node **)cvector_at(n->value.list, i);
    1217            7 :     cyaml_node **src = (cyaml_node **)cvector_at(n->value.list, i + 1);
    1218            7 :     *dst = *src;
    1219              :   }
    1220            7 :   cyaml_node *tmp = NULL;
    1221            7 :   cvector_pop_back(n->value.list, &tmp);
    1222            7 :   return ccol_success;
    1223              : }
    1224              : 
    1225              : // Steps it onto the next member of a dictionary walk; false at the end. The
    1226              : // cursor reads the successor when it steps onto a member, so removing the
    1227              : // current member leaves it valid.
    1228        15900 : bool cyaml_dictionary_next(cyaml_dictionary_iter *it) {
    1229        15900 :   if (!it) return false;
    1230        15899 :   const ccol_chmap_entry_ref *e = (const ccol_chmap_entry_ref *)it->cyaml__next;
    1231        15899 :   if (!e) {
    1232         7749 :     it->key = NULL;
    1233         7749 :     it->value = NULL;
    1234         7749 :     return false;
    1235              :   }
    1236         8150 :   const cmap_pair *kp, *vp;
    1237         8150 :   it->cyaml__next = ccol_chmap_entry_read(e, &kp, &vp);
    1238         8150 :   it->key = (const char *)kp->ptr;
    1239         8150 :   it->value = (cyaml)cyaml_read_child(vp->ptr);
    1240         8150 :   return true;
    1241              : }
    1242              : 
    1243              : // Starts a dictionary walk: Fills it with the oldest member of dict and reads
    1244              : // its successor. false for an empty, NULL or wrong-type dict, or a NULL it.
    1245         7749 : bool cyaml_dictionary_first(cyaml dict, cyaml_dictionary_iter *it) {
    1246         7749 :   if (!it) return false;
    1247         7748 :   cyaml_node *n = (cyaml_node *)dict;
    1248        15496 :   it->cyaml__next =
    1249         7748 :       (n && n->type == CYAML_DICTIONARY) ? dict_first_entry(n) : NULL;
    1250         7748 :   return cyaml_dictionary_next(it);
    1251              : }
    1252              : 
    1253              : // Removes and frees the entry of key, for callers that edit a dictionary. The
    1254              : // child is taken out of the map first and freed afterwards, so the map never
    1255              : // points at freed memory. ccol_key_not_found when the key is absent.
    1256           16 : ccol_retval cyaml_dictionary_remove(cyaml map, const char *key) {
    1257           16 :   if (!map || !key) return ccol_invalid_args;
    1258           14 :   cyaml_node *n = (cyaml_node *)map;
    1259           14 :   if (n->type != CYAML_DICTIONARY) return ccol_invalid_args;
    1260           14 :   cmap_pair kp = {.ptr = (void *)key, .size = strlen(key) + 1};
    1261           14 :   cmap_pair vp;
    1262           14 :   if (chashmap_get_elem_ref(n->value.dictionary, &kp, &vp) != ccol_success)
    1263              :     return ccol_key_not_found;
    1264           10 :   cyaml_node *child = cyaml_read_child(vp.ptr);
    1265           10 :   ccol_retval r = chashmap_remove_elem(n->value.dictionary, &kp);
    1266           10 :   if (r == ccol_success) cyaml__destroy((cyaml)child);
    1267              :   return r;
    1268              : }
    1269              : 
    1270              : // Copies src_tag onto the finished clone dst, so every cloned node keeps its
    1271              : // tag; clone_shallow() calls it for each node. On OOM it destroys dst and gives
    1272              : // false; it gives false for a NULL dst too. A NULL src_tag is fine.
    1273      3024091 : static bool clone_attach_tag(cyaml dst, const char *src_tag,
    1274              :                              ccol_memmgmt_procs *mp) {
    1275      3024091 :   if (!dst) return false;
    1276      3023946 :   if (!src_tag) return true;
    1277         2537 :   char *t = strdup_charged(mp, src_tag);
    1278            0 :   if (!t) {
    1279            0 :     cyaml__destroy(dst);
    1280            0 :     return false;
    1281              :   }
    1282         2537 :   ((cyaml_node *)dst)->tag = t;
    1283         2537 :   return true;
    1284              : }
    1285              : 
    1286              : // The most containers a tree may nest on any path, the root included when it's
    1287              : // a container. Parse, clone and every serializer share it, so each accepts
    1288              : // exactly what the others accept. All of them walk with explicit stacks, so
    1289              : // this limits work, not native stack.
    1290              : #define CYAML_MAX_NESTING_DEPTH 500
    1291              : 
    1292              : // How many walk frames live in the walker's own locals before the stack moves
    1293              : // to the heap. Ordinary documents never allocate for it.
    1294              : #define CYAML_WALK_INLINE_FRAMES 16
    1295              : 
    1296              : // Grows an explicit walk stack to new_cap frames, for the parser, the clone and
    1297              : // the serializers, which walk without recursion. It gives the new storage: The
    1298              : // first growth copies the inline frames to the heap, later ones realloc. On
    1299              : // failure it gives NULL and leaves *cap alone, so the caller can unwind what it
    1300              : // pushed. The depth caps keep new_cap * elem_size far from overflow.
    1301         2518 : static void *walk_stack_grow_to(void *stack, size_t *cap, size_t new_cap,
    1302              :                                 void *inline_base, size_t elem_size,
    1303              :                                 ccol_memmgmt_procs *mp) {
    1304         2518 :   void *grown;
    1305         2518 :   if (stack == inline_base) {
    1306          773 :     grown = ccol__mem_alloc(mp, new_cap * elem_size);
    1307          773 :     if (!grown) return NULL;
    1308          769 :     memcpy(grown, inline_base, *cap * elem_size);
    1309              :   } else {
    1310         1745 :     grown = ccol__mem_realloc(mp, stack, new_cap * elem_size);
    1311         1745 :     if (!grown) return NULL;
    1312              :   }
    1313         2509 :   *cap = new_cap;
    1314         2509 :   return grown;
    1315              : }
    1316              : 
    1317              : // Grows a walk stack to twice its capacity through walk_stack_grow_to(), for
    1318              : // walkers that grow by doubling.
    1319         1139 : static void *walk_stack_grow(void *stack, size_t *cap, void *inline_base,
    1320              :                              size_t elem_size, ccol_memmgmt_procs *mp) {
    1321           16 :   return walk_stack_grow_to(stack, cap, *cap * 2, inline_base, elem_size, mp);
    1322              : }
    1323              : 
    1324              : // One level of clone_node()'s walk: A source container and its clone. A list
    1325              : // walks by idx up to count; a dictionary walks through next, and idx counts the
    1326              : // entries seen so the caller can tell a walk that stopped early.
    1327              : typedef struct {
    1328              :   cyaml_node *src;
    1329              :   cyaml_node *dst;
    1330              :   size_t idx;
    1331              :   size_t count;
    1332              :   const ccol_chmap_entry_ref *next;
    1333              : } clone_frame;
    1334              : 
    1335              : // Copies src without its children (a container comes back empty) and attaches
    1336              : // its tag; clone_node() makes every node of a copy through it. NULL on OOM,
    1337              : // with nothing left behind.
    1338      3024091 : static cyaml clone_shallow(cyaml_node *src) {
    1339      3024091 :   ccol_memmgmt_procs *mp = src->m_procs;
    1340      3024091 :   cyaml dst;
    1341      3024091 :   switch (src->type) {
    1342            4 :     case CYAML_NULL:
    1343            4 :       dst = cyaml_create_null_interned(mp);
    1344            4 :       break;
    1345            2 :     case CYAML_BOOL:
    1346            2 :       dst = cyaml_create_bool_interned(src->value.boolean, mp);
    1347            2 :       break;
    1348       520860 :     case CYAML_INTEGER:
    1349       520860 :       dst = cyaml_create_int_interned(src->value.integer, mp);
    1350       520860 :       break;
    1351            2 :     case CYAML_FLOAT:
    1352            2 :       dst = cyaml_create_double_interned(src->value.number, mp);
    1353            2 :       break;
    1354       525090 :     case CYAML_STRING:
    1355       525090 :       dst = cyaml_create_string_interned(src->value.string, mp);
    1356       525090 :       break;
    1357      1965565 :     case CYAML_LIST:
    1358      1965565 :       dst = cyaml_create_list_interned(mp);
    1359      1965565 :       break;
    1360        12568 :     case CYAML_DICTIONARY:
    1361        12568 :       dst = cyaml_create_dictionary_interned(mp);
    1362        12568 :       break;
    1363              :     default:
    1364              :       return NULL;
    1365              :   }
    1366      3024091 :   return clone_attach_tag(dst, src->tag, mp) ? dst : NULL;
    1367              : }
    1368              : 
    1369              : // Starts the walk of src's children into the empty clone dst, when clone_node()
    1370              : // enters a container; in insertion order for a dictionary.
    1371      1978001 : static void clone_frame_open(clone_frame *f, cyaml_node *src, cyaml_node *dst) {
    1372      1978001 :   f->src = src;
    1373      1978001 :   f->dst = dst;
    1374      1978001 :   f->idx = 0;
    1375      1978001 :   f->count = 0;
    1376      1978001 :   f->next = NULL;
    1377      1978001 :   if (src->type == CYAML_LIST)
    1378      1965483 :     f->count = cvector_size(src->value.list);
    1379              :   else
    1380        12518 :     f->next = dict_first_entry(src);
    1381      1978001 : }
    1382              : 
    1383              : // Deep-copies src with an explicit frame stack, for cyaml_clone() and every
    1384              : // alias expansion. max_levels caps the nesting of the copy; past it we give
    1385              : // NULL with *too_deep set, and any other NULL is an OOM or a spent parse
    1386              : // budget. On success *height is the nesting of the copy. Each child is attached
    1387              : // to its parent's clone before its own subtree is walked, so one
    1388              : // cyaml__destroy() of the root frees a partial copy. Children go straight into
    1389              : // the containers (no public push or set), but a new dictionary entry is
    1390              : // charged to the byte budget, since alias expansion clones whole mappings.
    1391         5848 : static cyaml clone_node(cyaml_node *src, size_t max_levels, bool *too_deep,
    1392              :                         size_t *height) {
    1393         5848 :   ccol_memmgmt_procs *mp = src->m_procs;
    1394         5848 :   *too_deep = false;
    1395         5848 :   *height = 0;
    1396         5848 :   if ((src->type == CYAML_LIST || src->type == CYAML_DICTIONARY) &&
    1397              :       max_levels == 0) {
    1398            0 :     *too_deep = true;
    1399            0 :     return NULL;
    1400              :   }
    1401         5848 :   cyaml root = clone_shallow(src);
    1402         5848 :   if (!root) return NULL;
    1403         5819 :   if (src->type != CYAML_LIST && src->type != CYAML_DICTIONARY) return root;
    1404              : 
    1405         2561 :   clone_frame inline_frames[CYAML_WALK_INLINE_FRAMES];
    1406         2561 :   clone_frame *stack = inline_frames;
    1407         2561 :   size_t cap = CYAML_WALK_INLINE_FRAMES;
    1408         2561 :   clone_frame_open(&stack[0], src, (cyaml_node *)root);
    1409         2561 :   size_t sp = 1;
    1410         2561 :   size_t max_sp = 1;
    1411         2561 :   bool failed = false;
    1412              : 
    1413      4992822 :   while (!failed && sp > 0) {
    1414      4990418 :     clone_frame *f = &stack[sp - 1];
    1415      4990418 :     cyaml_node *child;
    1416      4990418 :     const cmap_pair *key = NULL;
    1417              : 
    1418      4990418 :     if (f->src->type == CYAML_LIST) {
    1419      4945027 :       if (f->idx >= f->count) {
    1420      1961981 :         sp--;
    1421      1972166 :         continue;
    1422              :       }
    1423      2983046 :       child = *(cyaml_node **)cvector_at(f->src->value.list, f->idx);
    1424      2983046 :       f->idx++;
    1425              :     } else {
    1426        45391 :       if (!f->next) {
    1427        10185 :         sp--;
    1428        10185 :         continue;
    1429              :       }
    1430        35206 :       const cmap_pair *vp;
    1431        35206 :       f->next = ccol_chmap_entry_read(f->next, &key, &vp);
    1432        35206 :       child = cyaml_read_child(vp->ptr);
    1433              :     }
    1434              : 
    1435      3018252 :     if (sp >= max_levels &&
    1436           24 :         (child->type == CYAML_LIST || child->type == CYAML_DICTIONARY)) {
    1437            9 :       *too_deep = true;
    1438            9 :       failed = true;
    1439          157 :       break;
    1440              :     }
    1441              : 
    1442      3018243 :     cyaml_node *cc = (cyaml_node *)clone_shallow(child);
    1443      3018243 :     if (!cc) {
    1444              :       failed = true;
    1445              :       break;
    1446              :     }
    1447      3018127 :     if (key) {
    1448        35133 :       if (!parse_bytes_charge(CYAML_BYTES_PER_DICT_ENTRY + key->size)) {
    1449            0 :         cyaml__destroy((cyaml)cc);
    1450            0 :         failed = true;
    1451           30 :         break;
    1452              :       }
    1453        35133 :       cmap_pair vp = {.ptr = &cc, .size = sizeof(cc)};
    1454        35133 :       if (chashmap_insert_elem(f->dst->value.dictionary, key, &vp) !=
    1455              :           ccol_success) {
    1456           30 :         cyaml__destroy((cyaml)cc);
    1457           30 :         failed = true;
    1458           30 :         break;
    1459              :       }
    1460      2982994 :     } else if (cvector_push_back(f->dst->value.list, &cc) != ccol_success) {
    1461            0 :       cyaml__destroy((cyaml)cc);
    1462            0 :       failed = true;
    1463            0 :       break;
    1464              :     }
    1465      3018097 :     cc->attached = true;
    1466              : 
    1467      3018097 :     if (child->type == CYAML_LIST || child->type == CYAML_DICTIONARY) {
    1468      1975442 :       if (sp == cap) {
    1469          269 :         clone_frame *grown =
    1470          269 :             walk_stack_grow(stack, &cap, inline_frames, sizeof(*stack), mp);
    1471          269 :         if (!grown) {
    1472              :           failed = true;
    1473              :           break;
    1474              :         }
    1475              :         stack = grown;
    1476              :       }
    1477      1975440 :       clone_frame_open(&stack[sp], child, cc);
    1478      1975440 :       sp++;
    1479      1975440 :       if (sp > max_sp) max_sp = sp;
    1480              :     }
    1481              :   }
    1482              : 
    1483         2561 :   if (stack != inline_frames) ccol__mem_free(mp, stack);
    1484         2561 :   if (failed) {
    1485          157 :     cyaml__destroy(root);
    1486          157 :     return NULL;
    1487              :   }
    1488         2404 :   *height = max_sp;
    1489         2404 :   return root;
    1490              : }
    1491              : 
    1492              : // Gives a deep copy of node that the caller owns, the public clone, within the
    1493              : // module's nesting limit; NULL for a NULL node, on OOM or for a tree that is
    1494              : // too deep.
    1495         2307 : cyaml cyaml_clone(cyaml node) {
    1496          359 :   if (!node) return NULL;
    1497         2306 :   bool too_deep;
    1498         2306 :   size_t height;
    1499         2306 :   return clone_node((cyaml_node *)node, CYAML_MAX_NESTING_DEPTH, &too_deep,
    1500              :                     &height);
    1501              : }
    1502              : 
    1503              : // One change a speculative parse made to the anchor table: An owned copy of the
    1504              : // name and the node it named before (NULL when the change added it).
    1505              : typedef struct {
    1506              :   char *name;
    1507              :   cyaml_node *old;
    1508              : } anchor_undo_entry;
    1509              : 
    1510              : // How many undo entries a log keeps inline, so a speculation that stores few
    1511              : // anchors allocates nothing for its log.
    1512              : #define ANCHOR_UNDO_INLINE 4
    1513              : // The changes of one speculative parse to the anchor table, in order, so a
    1514              : // rejection can undo them. entries points at inline_entries until the log
    1515              : // grows.
    1516              : typedef struct {
    1517              :   anchor_undo_entry *entries;
    1518              :   size_t len;
    1519              :   size_t cap;
    1520              :   anchor_undo_entry inline_entries[ANCHOR_UNDO_INLINE];
    1521              : } anchor_undo_log;
    1522              : 
    1523              : // The state of one parse. anchors maps names to anchored nodes without owning
    1524              : // them, and tag_handles maps %TAG handles to prefixes; both are created on
    1525              : // first use and freed at the end of each document. depth counts the containers
    1526              : // around the current node (each collection frame and the one-entry mapping of a
    1527              : // flow pair hold a level); later documents of a stream start at 1 because the
    1528              : // stream list encloses them.
    1529              : typedef struct {
    1530              :   const char *src;
    1531              :   size_t pos;
    1532              :   size_t len;
    1533              :   char error[512];
    1534              :   ccol_memmgmt_procs *mp;
    1535              :   chmap anchors;
    1536              :   chmap tag_handles;
    1537              :   size_t depth;
    1538              :   // The deepest depth of the document, aliases included. A first document at
    1539              :   // the limit is refused once a second document follows.
    1540              :   size_t peak_depth;
    1541              :   // The last answer of line_start_pos(); the text never changes, so a repeat
    1542              :   // question for the same offset is always answered here. SIZE_MAX means none.
    1543              :   size_t memo_pos;
    1544              :   size_t memo_line_start;
    1545              :   // Where the content starts: 0 or the offset past a byte-order mark. Both line
    1546              :   // lookups must use it as the start of the first line.
    1547              :   size_t first_line_start;
    1548              :   // The line-start cache of line_start_pos(). It falls back to a backward scan
    1549              :   // for good once a growth fails.
    1550              :   size_t *line_starts;
    1551              :   size_t line_starts_len;
    1552              :   size_t line_starts_cap;
    1553              :   size_t line_scan_pos;
    1554              :   bool line_cache_disabled;
    1555              :   // The undo log of the running speculation, or NULL.
    1556              :   anchor_undo_log *anchor_undo;
    1557              :   // Anchored nodes that no tree holds any more, owned until anchors_destroy().
    1558              :   // Each anchors_store() reserves a slot, so keeping a node never allocates.
    1559              :   cyaml_node **kept;
    1560              :   size_t kept_len;
    1561              :   size_t kept_cap;
    1562              :   size_t kept_reserved;
    1563              : } parse_ctx;
    1564              : 
    1565              : // The parse running on this thread while it has an anchor table, or NULL.
    1566              : // parse_discard() reads it, since dict_slot_replace_child() has no context.
    1567              : static __thread parse_ctx *parse_discard_ctx;
    1568              : 
    1569              : // Moves n into a slot of ctx's kept list that anchors_store() reserved, so an
    1570              : // anchored node no tree holds stays alive for later aliases.
    1571          354 : static void parse_keep(parse_ctx *ctx, cyaml_node *n) {
    1572          354 :   ccol__assert(ctx->kept_len < ctx->kept_cap);
    1573          354 :   ctx->kept[ctx->kept_len++] = n;
    1574          354 : }
    1575              : 
    1576              : // Frees a subtree that a running parse drops, but moves each anchored node in
    1577              : // it whole to the kept list, since a later alias may copy it. Outside a parse
    1578              : // with an anchor table it's just cyaml__destroy().
    1579        51023 : static void parse_discard(cyaml_node *n) {
    1580        97175 :   if (!n) return;
    1581        51023 :   parse_ctx *ctx = parse_discard_ctx;
    1582        51023 :   if (!ctx) {
    1583        46154 :     cyaml__destroy((cyaml)n);
    1584        46154 :     return;
    1585              :   }
    1586         4869 :   destroy_worklist wl = {NULL, 0, 0, true};
    1587         4869 :   cyaml_node *node = n;
    1588        45833 :   for (;;) {
    1589        25351 :     if (node->anchored) {
    1590           28 :       parse_keep(ctx, node);
    1591              :     } else {
    1592        25323 :       node_clear_value(node, &wl);
    1593        25323 :       ccol__mem_free(node->m_procs, node->tag);
    1594        25323 :       node->tag = NULL;
    1595        25323 :       node_free(node);
    1596              :     }
    1597        25351 :     if (wl.len == 0) break;
    1598        20482 :     node = wl.items[--wl.len];
    1599              :   }
    1600         4869 :   ccol__default_mem_free(wl.items);
    1601              : }
    1602              : 
    1603              : // The most frames one parse's frame stack may hold. Each container holds one
    1604              : // collection frame, and a node holds at most three node frames (itself, its
    1605              : // anchor and its tag), so the nesting limit bounds the stack at this size. The
    1606              : // driver never grows the stack past it.
    1607              : #define CYAML_PARSE_MAX_FRAMES (4 * (CYAML_MAX_NESTING_DEPTH + 1))
    1608              : 
    1609              : // The longest canonical text of a collection used as a key. Each nesting level
    1610              : // of such a key quotes the text of the level below again, so the text grows as
    1611              : // 2^N with the depth; the nesting limit can't stop that. The builder stops at
    1612              : // the first byte past this limit, so a refused key costs at most 64 KiB.
    1613              : #define CYAML_MAX_CANONICAL_KEY_LEN (64 * 1024)
    1614              : 
    1615              : // The fixed floor of the node budget of one parse. Aliases and merge keys make
    1616              : // real deep copies, so nested aliases can grow the node count exponentially
    1617              : // from a small text ("billion laughs"); this caps the nodes, and
    1618              : // CYAML_MAX_PARSE_BYTES caps their bytes.
    1619              : #define CYAML_MAX_PARSE_NODES (4 * 1000 * 1000)
    1620              : 
    1621              : // The node budget grows with the input at this many nodes per byte: 1.5 times
    1622              : // the worst honest shape ("[:,:,:]", 1.5 nodes per byte), rounded up to a power
    1623              : // of two. Copies also count against the fixed amplification budget, so a long
    1624              : // input never raises the limit for its expansion.
    1625              : #define CYAML_PARSE_NODES_PER_INPUT_BYTE 4
    1626              : 
    1627              : // The fixed floor of the byte budget of one parse. A node isn't a fixed amount
    1628              : // of memory (strings, tags, keys, container storage), so a few large anchored
    1629              : // scalars could blow up memory with few nodes. Every DOM allocation site of the
    1630              : // parser charges this budget.
    1631              : #define CYAML_MAX_PARSE_BYTES ((size_t)256 * 1024 * 1024)
    1632              : 
    1633              : // The byte budget grows with the input at this many bytes per byte: The same
    1634              : // "[:,:,:]" shape costs about 331, times 1.5 rounded up. Without the scaling a
    1635              : // large honest document (a big Kubernetes List) would be refused.
    1636              : #define CYAML_PARSE_BYTES_PER_INPUT_BYTE 512
    1637              : 
    1638              : // The two limits of the running parse as parse_node_budget_arm() computed
    1639              : // them, so the error messages can name them.
    1640              : static __thread size_t parse_node_limit = CYAML_MAX_PARSE_NODES;
    1641              : static __thread size_t parse_byte_limit = CYAML_MAX_PARSE_BYTES;
    1642              : 
    1643              : // Gives the budget for an input of input_len bytes, max(floor, per_byte *
    1644              : // input_len), saturated below the (size_t)-1 sentinel (512 times a large input
    1645              : // overflows on ILP32). parse_node_budget_arm() uses it for both budgets.
    1646        14001 : static inline size_t parse_budget_for_input(size_t floor, size_t per_byte,
    1647              :                                             size_t input_len) {
    1648        14001 :   size_t cap = (size_t)-1 - 1;
    1649        14001 :   size_t scaled = input_len > cap / per_byte ? cap : input_len * per_byte;
    1650        14001 :   return scaled > floor ? scaled : floor;
    1651              : }
    1652              : 
    1653              : #ifdef RUNNING_UNIT_TESTS
    1654              : // The floors of the two limits. A test lowers them to show the scaling on a
    1655              : // small document and restores them afterwards.
    1656              : size_t cyaml_test_parse_node_floor = CYAML_MAX_PARSE_NODES;
    1657              : size_t cyaml_test_parse_byte_floor = CYAML_MAX_PARSE_BYTES;
    1658              : // The floors the budgets start from: The test variables above in test builds,
    1659              : // the fixed constants otherwise.
    1660              : #define CYAML_PARSE_NODE_FLOOR cyaml_test_parse_node_floor
    1661              : #define CYAML_PARSE_BYTE_FLOOR cyaml_test_parse_byte_floor
    1662              : 
    1663              : // Test hook: Gives parse_budget_for_input(), so tests can check the scaling and
    1664              : // the saturation.
    1665            5 : size_t cyaml_debug_parse_budget_for_input(size_t floor, size_t per_byte,
    1666              :                                           size_t input_len) {
    1667            5 :   return parse_budget_for_input(floor, per_byte, input_len);
    1668              : }
    1669              : #else
    1670              : #define CYAML_PARSE_NODE_FLOOR ((size_t)CYAML_MAX_PARSE_NODES)
    1671              : #define CYAML_PARSE_BYTE_FLOOR CYAML_MAX_PARSE_BYTES
    1672              : #endif
    1673              : 
    1674              : // The amplification budget of the running parse. Every node and byte made by
    1675              : // copying something already built (an alias, a merged value, a collection key's
    1676              : // text) is charged here as well as to the ordinary budgets, and this one keeps
    1677              : // the fixed floors whatever the input length, so padding a document buys no
    1678              : // expansion. parse_amp_enter() narrows the ordinary budgets to what this one
    1679              : // allows and parse_amp_leave() settles; only the outermost of nested regions
    1680              : // does either.
    1681              : static __thread size_t parse_amp_node_budget;
    1682              : static __thread size_t parse_amp_byte_budget;
    1683              : static __thread size_t parse_amp_saved_node_budget;
    1684              : static __thread size_t parse_amp_saved_byte_budget;
    1685              : static __thread size_t parse_amp_start_node_budget;
    1686              : static __thread size_t parse_amp_start_byte_budget;
    1687              : static __thread unsigned parse_amp_depth;
    1688              : 
    1689              : // Set by parse_amp_leave() when a refused charge happened with this budget as
    1690              : // the binding limit, so the error names it. Cleared by the next arm or disarm.
    1691              : static __thread bool parse_amp_limit_hit;
    1692              : 
    1693              : // Opens an amplification region around a copy (alias, merge, collection key),
    1694              : // so the copy is bounded by the fixed amplification budget. The outermost
    1695              : // region saves the ordinary budgets and narrows them to it.
    1696         5854 : static inline void parse_amp_enter(void) {
    1697         5854 :   if (parse_node_budget == (size_t)-1) return;
    1698         5854 :   if (parse_amp_depth++ != 0) return;
    1699         5854 :   parse_amp_saved_node_budget = parse_node_budget;
    1700         5854 :   parse_amp_saved_byte_budget = parse_byte_budget;
    1701         5854 :   if (parse_amp_node_budget < parse_node_budget)
    1702          116 :     parse_node_budget = parse_amp_node_budget;
    1703         5854 :   if (parse_amp_byte_budget < parse_byte_budget)
    1704         1023 :     parse_byte_budget = parse_amp_byte_budget;
    1705         5854 :   parse_amp_start_node_budget = parse_node_budget;
    1706         5854 :   parse_amp_start_byte_budget = parse_byte_budget;
    1707              : }
    1708              : 
    1709              : // Closes an amplification region: The outermost one charges what the region
    1710              : // used to both budgets and sets parse_amp_limit_hit when the amplification
    1711              : // budget was the binding one. A refund inside the region never lifts the budget
    1712              : // above its start.
    1713         5854 : static inline void parse_amp_leave(void) {
    1714         5854 :   if (parse_node_budget == (size_t)-1) return;
    1715         5854 :   if (--parse_amp_depth != 0) return;
    1716         5854 :   size_t used_nodes = parse_amp_start_node_budget - parse_node_budget;
    1717         5854 :   size_t used_bytes = parse_amp_start_byte_budget - parse_byte_budget;
    1718         5854 :   bool amp_binding_nodes = parse_amp_node_budget <= parse_amp_saved_node_budget;
    1719         5854 :   bool amp_binding_bytes = parse_amp_byte_budget <= parse_amp_saved_byte_budget;
    1720         5854 :   parse_amp_node_budget -= used_nodes;
    1721         5854 :   parse_amp_byte_budget -= used_bytes;
    1722         5854 :   parse_node_budget = parse_amp_saved_node_budget - used_nodes;
    1723         5854 :   parse_byte_budget = parse_amp_saved_byte_budget - used_bytes;
    1724         5854 :   if ((parse_node_budget_exhausted && amp_binding_nodes) ||
    1725         5853 :       (parse_byte_budget_exhausted && amp_binding_bytes))
    1726            6 :     parse_amp_limit_hit = true;
    1727              : }
    1728              : 
    1729              : // Deep-copies src through clone_node() inside an amplification region. Every
    1730              : // alias expansion copies through here, with the levels left below the place
    1731              : // where the copy lands.
    1732         3542 : static cyaml_node *parse_clone_levels(cyaml_node *src, size_t max_levels,
    1733              :                                       bool *too_deep, size_t *height) {
    1734         3542 :   parse_amp_enter();
    1735         3542 :   cyaml_node *copy =
    1736         3542 :       (cyaml_node *)clone_node(src, max_levels, too_deep, height);
    1737         3542 :   parse_amp_leave();
    1738         3542 :   return copy;
    1739              : }
    1740              : 
    1741              : // Arms the node, byte and amplification budgets for a parse of input_len bytes,
    1742              : // at the start of parse_common(), so one document can't use unbounded memory.
    1743              : // They are always armed and disarmed together.
    1744         6998 : static inline void parse_node_budget_arm(size_t input_len) {
    1745         6998 :   parse_node_limit = parse_budget_for_input(
    1746              :       CYAML_PARSE_NODE_FLOOR, CYAML_PARSE_NODES_PER_INPUT_BYTE, input_len);
    1747         6998 :   parse_byte_limit = parse_budget_for_input(
    1748              :       CYAML_PARSE_BYTE_FLOOR, CYAML_PARSE_BYTES_PER_INPUT_BYTE, input_len);
    1749         6998 :   parse_node_budget = parse_node_limit;
    1750         6998 :   parse_node_budget_exhausted = false;
    1751         6998 :   parse_byte_budget = parse_byte_limit;
    1752         6998 :   parse_byte_budget_exhausted = false;
    1753         6998 :   parse_amp_node_budget = CYAML_PARSE_NODE_FLOOR;
    1754         6998 :   parse_amp_byte_budget = CYAML_PARSE_BYTE_FLOOR;
    1755         6998 :   parse_amp_depth = 0;
    1756         6998 :   parse_amp_limit_hit = false;
    1757         6998 : }
    1758              : #ifdef RUNNING_UNIT_TESTS
    1759              : // What the last parse on this thread charged to its two budgets, for the tests
    1760              : // that check the per-byte factors.
    1761              : __thread size_t cyaml_test_last_parse_nodes_charged;
    1762              : __thread size_t cyaml_test_last_parse_bytes_charged;
    1763              : // The largest frame stack capacity a parse reached on this thread.
    1764              : __thread size_t cyaml_test_peak_parse_frame_cap;
    1765              : #endif
    1766              : 
    1767              : // Disarms the budgets at every exit of parse_common(): Sets them back to
    1768              : // unlimited and clears parse_discard_ctx, so nothing a parse left can reach
    1769              : // later calls on this thread.
    1770         6999 : static inline void parse_node_budget_disarm(void) {
    1771              : #ifdef RUNNING_UNIT_TESTS
    1772         6999 :   if (parse_node_budget != (size_t)-1) {
    1773         6999 :     cyaml_test_last_parse_nodes_charged = parse_node_limit - parse_node_budget;
    1774         6999 :     cyaml_test_last_parse_bytes_charged = parse_byte_limit - parse_byte_budget;
    1775              :   }
    1776              : #endif
    1777         6999 :   parse_discard_ctx = NULL;
    1778         6999 :   parse_node_budget = (size_t)-1;
    1779         6999 :   parse_node_budget_exhausted = false;
    1780         6999 :   parse_byte_budget = (size_t)-1;
    1781         6999 :   parse_byte_budget_exhausted = false;
    1782         6999 :   parse_amp_depth = 0;
    1783         6999 :   parse_amp_limit_hit = false;
    1784         6999 : }
    1785              : 
    1786              : static void parse_err(parse_ctx *ctx, const char *fmt, ...)
    1787              :     __attribute__((format(printf, 2, 3)));
    1788              : // Formats a parse error into ctx->error, the one way the parser reports an
    1789              : // error; the last call wins. The printf format attribute on the prototype lets
    1790              : // the compiler check every call site's format string, which also keeps
    1791              : // -Wformat-nonliteral quiet here.
    1792         1737 : static void parse_err(parse_ctx *ctx, const char *fmt, ...) {
    1793         1737 :   va_list ap;
    1794         1737 :   va_start(ap, fmt);
    1795         1737 :   vsnprintf(ctx->error, sizeof(ctx->error), fmt, ap);
    1796         1737 :   va_end(ap);
    1797         1737 : }
    1798              : 
    1799              : // Reports a container past CYAML_MAX_NESTING_DEPTH, so every depth refusal
    1800              : // names the limit in the same words.
    1801           43 : static void parse_depth_err(parse_ctx *ctx) {
    1802           43 :   parse_err(ctx, "maximum nesting depth (%d) exceeded at position %zu",
    1803              :             CYAML_MAX_NESTING_DEPTH, ctx->pos);
    1804              : }
    1805              : 
    1806              : // Takes the nesting level of a flow-sequence pair. A "key: value" pair in a
    1807              : // flow sequence is a one-entry mapping one level down, so it holds a level
    1808              : // while its value is read. false, with the error set, when that level is past
    1809              : // the limit.
    1810        20645 : static inline bool flow_pair_level_take(parse_ctx *ctx) {
    1811        20645 :   if (ctx->depth >= CYAML_MAX_NESTING_DEPTH) {
    1812            0 :     parse_depth_err(ctx);
    1813            0 :     return false;
    1814              :   }
    1815        20645 :   if (++ctx->depth > ctx->peak_depth) ctx->peak_depth = ctx->depth;
    1816              :   return true;
    1817              : }
    1818              : 
    1819              : // Gives the nesting of the tree n (0 for a scalar), for
    1820              : // parse_key_fits_below_mapping(). It walks with a fixed stack of
    1821              : // CYAML_MAX_NESTING_DEPTH frames; a deeper tree gives the limit plus one.
    1822           17 : static size_t parse_tree_height(cyaml_node *n) {
    1823           17 :   if (n->type != CYAML_LIST && n->type != CYAML_DICTIONARY) return 0;
    1824           10 :   struct {
    1825              :     cyaml_node *n;
    1826              :     size_t idx;
    1827              :     const ccol_chmap_entry_ref *next;
    1828              :   } stack[CYAML_MAX_NESTING_DEPTH];
    1829           10 :   size_t sp = 0, height = 0;
    1830           10 :   stack[sp].n = n;
    1831           10 :   stack[sp].idx = 0;
    1832           10 :   stack[sp].next = n->type == CYAML_DICTIONARY ? dict_first_entry(n) : NULL;
    1833           10 :   sp++;
    1834           10 :   height = 1;
    1835           50 :   while (sp > 0) {
    1836           40 :     cyaml_node *child;
    1837           40 :     if (stack[sp - 1].n->type == CYAML_LIST) {
    1838           40 :       cvec list = stack[sp - 1].n->value.list;
    1839           40 :       if (stack[sp - 1].idx >= cvector_size(list)) {
    1840           20 :         sp--;
    1841           20 :         continue;
    1842              :       }
    1843           20 :       child = *(cyaml_node **)cvector_at(list, stack[sp - 1].idx++);
    1844              :     } else {
    1845            0 :       if (!stack[sp - 1].next) {
    1846            0 :         sp--;
    1847            0 :         continue;
    1848              :       }
    1849            0 :       const cmap_pair *kp, *vp;
    1850            0 :       stack[sp - 1].next = ccol_chmap_entry_read(stack[sp - 1].next, &kp, &vp);
    1851            0 :       child = cyaml_read_child(vp->ptr);
    1852              :     }
    1853           20 :     if (child->type != CYAML_LIST && child->type != CYAML_DICTIONARY) continue;
    1854           10 :     if (sp == CYAML_MAX_NESTING_DEPTH) return CYAML_MAX_NESTING_DEPTH + 1;
    1855           10 :     stack[sp].n = child;
    1856           10 :     stack[sp].idx = 0;
    1857           20 :     stack[sp].next =
    1858           10 :         child->type == CYAML_DICTIONARY ? dict_first_entry(child) : NULL;
    1859           10 :     sp++;
    1860           10 :     if (sp > height) height = sp;
    1861              :   }
    1862              :   return height;
    1863              : }
    1864              : 
    1865              : // Checks that a collection used as a key fits below the mapping that holds it.
    1866              : // Such a key is read before its mapping exists, so this adds the mapping's
    1867              : // level once the node is known to be a key, and gives false with the error set
    1868              : // when that passes the limit. It walks the key only when peak_depth is within
    1869              : // one level of the limit.
    1870        20976 : static bool parse_key_fits_below_mapping(parse_ctx *ctx, cyaml_node *key) {
    1871        20976 :   if (ctx->peak_depth + 1 < CYAML_MAX_NESTING_DEPTH) return true;
    1872           17 :   size_t top = ctx->depth + 1 + parse_tree_height(key);
    1873           17 :   if (top > CYAML_MAX_NESTING_DEPTH) {
    1874            8 :     parse_depth_err(ctx);
    1875            8 :     return false;
    1876              :   }
    1877            9 :   if (top > ctx->peak_depth) ctx->peak_depth = top;
    1878              :   return true;
    1879              : }
    1880              : 
    1881              : // Every byte of input that an error message quotes goes through
    1882              : // cyaml_err_echo(), so messages stay printable ASCII: No terminal escapes, no
    1883              : // forged log lines, no invalid UTF-8. Bytes 0x20 to 0x7E stay, any other byte
    1884              : // becomes <0xNN>, and a long text is cut at a whole byte with "...". The macros
    1885              : // give each echo its own compound-literal buffer that lives to the end of the
    1886              : // enclosing block.
    1887              : #define CYAML_ERR_ECHO_BUF 72
    1888              : 
    1889              : // Writes the printable-ASCII echo of the n bytes at s into out and gives out,
    1890              : // so every quoted input in an error message is safe to log.
    1891         1054 : static const char *cyaml_err_echo(const char *s, size_t n, char *out) {
    1892         1054 :   static const char hex[] = "0123456789ABCDEF";
    1893         1054 :   size_t o = 0;
    1894         3114 :   for (size_t i = 0; i < n; i++) {
    1895         2062 :     unsigned char c = (unsigned char)s[i];
    1896         2062 :     bool plain = c >= 0x20 && c <= 0x7E;
    1897         2062 :     size_t need = plain ? 1 : 6;
    1898         2062 :     size_t reserve = i + 1 < n ? 3 : 0;
    1899         2062 :     if (o + need + reserve > CYAML_ERR_ECHO_BUF - 1) {
    1900            2 :       memcpy(out + o, "...", 3);
    1901            2 :       o += 3;
    1902            2 :       break;
    1903              :     }
    1904         2060 :     if (plain) {
    1905         2012 :       out[o++] = (char)c;
    1906              :     } else {
    1907           48 :       out[o++] = '<';
    1908           48 :       out[o++] = '0';
    1909           48 :       out[o++] = 'x';
    1910           48 :       out[o++] = hex[c >> 4];
    1911           48 :       out[o++] = hex[c & 0x0F];
    1912           48 :       out[o++] = '>';
    1913              :     }
    1914              :   }
    1915         1054 :   out[o] = '\0';
    1916         1054 :   return out;
    1917              : }
    1918              : 
    1919              : // Echo input text into an error message: cyaml_echo_n() takes the n bytes at s,
    1920              : // cyaml_echo() a NUL-terminated string (NULL gives ""), cyaml_echo_c() one
    1921              : // character. Each evaluates to the printable-ASCII echo in a compound-literal
    1922              : // buffer that lives to the end of the enclosing block, so it can go straight
    1923              : // into a parse_err() argument list.
    1924              : #define cyaml_echo_n(s, n) \
    1925              :   cyaml_err_echo((s), (n), (char[CYAML_ERR_ECHO_BUF]){0})
    1926              : #define cyaml_echo(s) \
    1927              :   cyaml_echo_n(((s) ? (s) : ""), ((s) ? strlen(s) : (size_t)0))
    1928              : #define cyaml_echo_c(c) cyaml_echo_n(&(const char){(char)(c)}, 1)
    1929              : 
    1930              : // True once the whole input is read; every scanner's end test.
    1931     21645346 : static inline bool at_end(parse_ctx *ctx) { return ctx->pos >= ctx->len; }
    1932              : 
    1933              : // Gives the current character, or '\0' at the end of the input, so scanners
    1934              : // can peek without a bounds test of their own.
    1935     22536443 : static inline char cur(parse_ctx *ctx) {
    1936       207846 :   return at_end(ctx) ? '\0' : ctx->src[ctx->pos];
    1937              : }
    1938              : 
    1939              : #ifdef RUNNING_UNIT_TESTS
    1940              : // Test switch that forces the cache-less line-start path. Memory pressure alone
    1941              : // can't reach the one case where the two paths could differ (a query on the
    1942              : // first line after a byte-order mark).
    1943              : bool cyaml_test_force_line_cache_disabled = false;
    1944              : #endif
    1945              : 
    1946              : // Gives the line start of ctx->pos by scanning back to the last line break,
    1947              : // never below first_line_start. It's the O(column) fallback of line_start_pos()
    1948              : // once the cache is disabled.
    1949          588 : static size_t line_start_pos_backward_scan(parse_ctx *ctx) {
    1950          588 :   size_t p = ctx->pos;
    1951         1738 :   while (p > ctx->first_line_start && ctx->src[p - 1] != '\n' &&
    1952              :          ctx->src[p - 1] != '\r')
    1953              :     p--;
    1954          588 :   return p;
    1955              : }
    1956              : 
    1957              : // Extends the line cache of line_start_pos(): Appends the start of every line
    1958              : // from line_scan_pos up to, not including, up_to. On OOM it frees the cache and
    1959              : // sets line_cache_disabled for good.
    1960       506607 : static void line_starts_extend(parse_ctx *ctx, size_t up_to) {
    1961       506607 :   size_t p = ctx->line_scan_pos;
    1962     16951610 :   while (p < up_to) {
    1963     16445002 :     char c = ctx->src[p];
    1964     16445002 :     p++;
    1965     16445002 :     if (c == '\n' || c == '\r') {
    1966        60049 :       if (ctx->line_starts_len == ctx->line_starts_cap) {
    1967          178 :         size_t new_cap = ctx->line_starts_cap ? ctx->line_starts_cap * 2 : 64;
    1968          178 :         size_t *grown = ccol__mem_realloc(ctx->mp, ctx->line_starts,
    1969              :                                           new_cap * sizeof(size_t));
    1970          179 :         if (!grown) {
    1971            0 :           ccol__mem_free(ctx->mp, ctx->line_starts);
    1972            0 :           ctx->line_starts = NULL;
    1973            0 :           ctx->line_starts_len = 0;
    1974            0 :           ctx->line_starts_cap = 0;
    1975            0 :           ctx->line_cache_disabled = true;
    1976            0 :           return;
    1977              :         }
    1978          179 :         ctx->line_starts = grown;
    1979          179 :         ctx->line_starts_cap = new_cap;
    1980              :       }
    1981        60050 :       ctx->line_starts[ctx->line_starts_len++] = p;
    1982              :     }
    1983              :   }
    1984       506608 :   ctx->line_scan_pos = p;
    1985              : }
    1986              : 
    1987              : static size_t line_start_pos_uncached(parse_ctx *ctx);
    1988              : 
    1989              : // Gives the offset where the line holding ctx->pos starts ('\n' and a lone
    1990              : // '\r' both end a line). A backward scan per call would make long flow lines
    1991              : // quadratic, so a sorted cache of line starts keeps the total work linear. The
    1992              : // memo in ctx answers a repeat question; test builds compare it with a fresh
    1993              : // answer. The first cache allocation happens in parse_common() and its failure
    1994              : // fails the parse; a later growth failure falls back to the scan.
    1995      2915785 : static size_t line_start_pos(parse_ctx *ctx) {
    1996      2915785 :   if (ctx->pos == ctx->memo_pos) {
    1997              : #ifdef RUNNING_UNIT_TESTS
    1998      2243533 :     ccol__assert(ctx->memo_line_start == line_start_pos_uncached(ctx));
    1999              : #endif
    2000      2243545 :     return ctx->memo_line_start;
    2001              :   }
    2002              : 
    2003       672252 :   size_t result = line_start_pos_uncached(ctx);
    2004       672241 :   ctx->memo_pos = ctx->pos;
    2005       672241 :   ctx->memo_line_start = result;
    2006       672241 :   return result;
    2007              : }
    2008              : 
    2009              : // Gives the line start of ctx->pos from the line cache, the real lookup behind
    2010              : // line_start_pos() when the memo misses. After extending to ctx->pos every
    2011              : // entry is at or below it, so the last entry is the answer (test builds check
    2012              : // this against the search). After a rewind the cache holds later entries and we
    2013              : // binary-search instead.
    2014      2915786 : static size_t line_start_pos_uncached(parse_ctx *ctx) {
    2015      2916374 :   if (ctx->line_cache_disabled) return line_start_pos_backward_scan(ctx);
    2016              : 
    2017      2915198 :   if (ctx->pos > ctx->line_scan_pos) {
    2018       506613 :     line_starts_extend(ctx, ctx->pos);
    2019       506603 :     if (ctx->line_cache_disabled) return line_start_pos_backward_scan(ctx);
    2020       506603 :     size_t answer = ctx->line_starts[ctx->line_starts_len - 1];
    2021              : #ifdef RUNNING_UNIT_TESTS
    2022              :     {
    2023       506603 :       size_t vlo = 0, vhi = ctx->line_starts_len;
    2024      2457939 :       while (vlo + 1 < vhi) {
    2025      1444733 :         size_t vmid = vlo + (vhi - vlo) / 2;
    2026      1444733 :         if (ctx->line_starts[vmid] <= ctx->pos)
    2027              :           vlo = vmid;
    2028              :         else
    2029       506603 :           vhi = vmid;
    2030              :       }
    2031       506603 :       ccol__assert(answer == ctx->line_starts[vlo]);
    2032              :     }
    2033              : #endif
    2034              :     return answer;
    2035              :   }
    2036              : 
    2037      2408585 :   size_t lo = 0, hi = ctx->line_starts_len;
    2038      6711495 :   while (lo + 1 < hi) {
    2039      1894325 :     size_t mid = lo + (hi - lo) / 2;
    2040      1894325 :     if (ctx->line_starts[mid] <= ctx->pos)
    2041              :       lo = mid;
    2042              :     else
    2043      2408767 :       hi = mid;
    2044              :   }
    2045      2408585 :   return ctx->line_starts[lo];
    2046              : }
    2047              : 
    2048              : // Gives the 0-based column of ctx->pos, which the block parsers compare with
    2049              : // indents to find structure. It's clamped at INT_MAX, since callers only
    2050              : // compare it with other indents.
    2051       762116 : CYAML_PARSE_HOT int current_col(parse_ctx *ctx) {
    2052            8 :   if (ctx->pos == 0) return 0;
    2053       735306 :   size_t p = line_start_pos(ctx);
    2054       735306 :   size_t col = ctx->pos - p;
    2055       735306 :   return col > (size_t)INT_MAX ? INT_MAX : (int)col;
    2056              : }
    2057              : 
    2058              : // True when a tab sits anywhere between the line start and ctx->pos. Block
    2059              : // entries call it, because a block column can't be measured across a tab. The
    2060              : // whitespace skippers don't refuse tabs themselves: Inside open content a tab
    2061              : // is data, and their callers need them to always move forward.
    2062        51299 : static bool line_indent_has_tab(parse_ctx *ctx) {
    2063        51299 :   size_t p = line_start_pos(ctx);
    2064        51299 :   return memchr(ctx->src + p, '\t', ctx->pos - p) != NULL;
    2065              : }
    2066              : 
    2067              : // Gives the indentation of the current line, for the indent comparisons of flow
    2068              : // continuation lines and block values: The spaces before the first tab when the
    2069              : // leading whitespace holds one, else current_col(). A tab after the indent is
    2070              : // separation.
    2071        28934 : static int line_space_indent(parse_ctx *ctx) {
    2072        28934 :   size_t p = line_start_pos(ctx);
    2073        28934 :   size_t spaces = 0;
    2074        28934 :   bool tab = false;
    2075     12683943 :   for (size_t q = p; q < ctx->pos; q++) {
    2076     12655009 :     char c = ctx->src[q];
    2077     12655009 :     if (c == '\t') {
    2078              :       tab = true;
    2079     12654990 :     } else if (c != ' ') {
    2080            0 :       return current_col(ctx);
    2081     12654990 :     } else if (!tab) {
    2082     12654990 :       spaces++;
    2083              :     }
    2084              :   }
    2085        57849 :   if (!tab) return current_col(ctx);
    2086           19 :   return spaces > (size_t)INT_MAX ? INT_MAX : (int)spaces;
    2087              : }
    2088              : 
    2089              : // Skips spaces and tabs without crossing a newline, where block parsing needs
    2090              : // the column of the next token. It skips tabs on purpose (see
    2091              : // line_indent_has_tab()); stopping at one would hang the fold loops.
    2092        26726 : static void skip_inline_ws(parse_ctx *ctx) {
    2093       388333 :   while (!at_end(ctx)) {
    2094       392812 :     char c = cur(ctx);
    2095       392812 :     if (c == ' ' || c == '\t')
    2096        23318 :       ctx->pos++;
    2097              :     else
    2098              :       break;
    2099              :   }
    2100              : }
    2101              : 
    2102              : // Skips the rest of the line and its line break (LF, CR or CRLF), past a
    2103              : // comment or a header the parser is done with.
    2104          590 : static void skip_to_eol(parse_ctx *ctx) {
    2105      1064376 :   while (!at_end(ctx) && cur(ctx) != '\n' && cur(ctx) != '\r') ctx->pos++;
    2106          590 :   if (!at_end(ctx) && cur(ctx) == '\r') ctx->pos++;
    2107          590 :   if (!at_end(ctx) && cur(ctx) == '\n') ctx->pos++;
    2108          590 : }
    2109              : 
    2110              : // True at a line break or the end of the input, the end test of every line
    2111              : // scan.
    2112         5177 : static inline bool at_eol(parse_ctx *ctx) {
    2113         5172 :   return at_end(ctx) || cur(ctx) == '\n' || cur(ctx) == '\r';
    2114              : }
    2115              : 
    2116              : // True when [start, ctx->pos) holds a line break, for the one-line rule of
    2117              : // implicit keys and the checks of flow continuation lines. It reads no byte:
    2118              : // the line start of ctx->pos lies after start exactly when it does. Test builds
    2119              : // assert the bounds and the equivalence.
    2120      1043899 : static bool span_crosses_newline(parse_ctx *ctx, size_t start) {
    2121              : #ifdef RUNNING_UNIT_TESTS
    2122      1043899 :   ccol__assert(start >= ctx->first_line_start && start <= ctx->pos);
    2123      1044461 :   ccol__assert((line_start_pos(ctx) > start) ==
    2124              :                (memchr(ctx->src + start, '\n', ctx->pos - start) != NULL ||
    2125              :                 memchr(ctx->src + start, '\r', ctx->pos - start) != NULL));
    2126              : #endif
    2127      1043889 :   return line_start_pos(ctx) > start;
    2128              : }
    2129              : 
    2130              : // True when only inline whitespace and maybe a comment remain on the line.
    2131              : // Decides whether a value, anchor or tag starts on this line, which a comment
    2132              : // after the indicator must not fool. ctx->pos doesn't move.
    2133        87710 : static bool rest_of_line_is_blank(parse_ctx *ctx) {
    2134        87710 :   size_t p = ctx->pos;
    2135        87765 :   while (p < ctx->len && (ctx->src[p] == ' ' || ctx->src[p] == '\t')) p++;
    2136        87710 :   if (p < ctx->len && ctx->src[p] == '#' &&
    2137           27 :       (p == ctx->first_line_start || ctx->src[p - 1] == ' ' ||
    2138              :        ctx->src[p - 1] == '\t' || ctx->src[p - 1] == '\n' ||
    2139              :        ctx->src[p - 1] == '\r')) {
    2140          205 :     while (p < ctx->len && ctx->src[p] != '\n' && ctx->src[p] != '\r') p++;
    2141              :   }
    2142        87710 :   return p >= ctx->len || ctx->src[p] == '\n' || ctx->src[p] == '\r';
    2143              : }
    2144              : 
    2145              : // Skips whitespace, newlines and comments between tokens where indentation
    2146              : // doesn't matter. A '#' that touches the token before it isn't a comment, so it
    2147              : // stays for the caller to refuse.
    2148       970824 : static void skip_ws_comments(parse_ctx *ctx) {
    2149     13851733 :   while (!at_end(ctx)) {
    2150     13833264 :     char c = cur(ctx);
    2151     13833264 :     if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
    2152     12880781 :       ctx->pos++;
    2153       952483 :     } else if (c == '#' && (ctx->pos == ctx->first_line_start ||
    2154          113 :                             ctx->src[ctx->pos - 1] == ' ' ||
    2155              :                             ctx->src[ctx->pos - 1] == '\t' ||
    2156              :                             ctx->src[ctx->pos - 1] == '\n' ||
    2157              :                             ctx->src[ctx->pos - 1] == '\r')) {
    2158          124 :       skip_to_eol(ctx);
    2159              :     } else {
    2160              :       break;
    2161              :     }
    2162              :   }
    2163       970828 : }
    2164              : 
    2165              : // Skips whitespace and comments inside flow content like skip_ws_comments().
    2166              : // When it crosses a line, the line it lands on must be indented by more than
    2167              : // indent (the enclosing block indent, -1 at the root), counting the spaces
    2168              : // before the first tab. A line that starts with ']' or '}' may sit exactly at
    2169              : // indent, as libyaml allows, to close the collection under its key. false with
    2170              : // the error set when the check fails.
    2171       790631 : CYAML_PARSE_HOT bool flow_skip_ws(parse_ctx *ctx, int indent) {
    2172       790631 :   size_t start = ctx->pos;
    2173        14516 :   skip_ws_comments(ctx);
    2174       790633 :   if (!at_end(ctx)) {
    2175       790510 :     bool crossed_newline = span_crosses_newline(ctx, start);
    2176       790503 :     int col = crossed_newline ? line_space_indent(ctx) : 0;
    2177       790503 :     if (crossed_newline && col <= indent &&
    2178           46 :         !(col == indent && (cur(ctx) == ']' || cur(ctx) == '}') &&
    2179           14 :           !line_indent_has_tab(ctx))) {
    2180            9 :       parse_err(ctx,
    2181              :                 "flow collection continuation line must be indented "
    2182              :                 "more than %d at position %zu",
    2183              :                 indent, ctx->pos);
    2184           21 :       return false;
    2185              :     }
    2186              :   }
    2187              :   return true;
    2188              : }
    2189              : 
    2190              : // Reads one line break (CR, LF or CRLF), for the scalar scanners that walk line
    2191              : // by line.
    2192         7635 : static void skip_newline(parse_ctx *ctx) {
    2193         7635 :   if (!at_end(ctx) && cur(ctx) == '\r') ctx->pos++;
    2194         7635 :   if (!at_end(ctx) && cur(ctx) == '\n') ctx->pos++;
    2195         7635 : }
    2196              : 
    2197              : // True when the rest of the line holds only spaces and tabs. The quoted-scalar
    2198              : // fold uses it so a blank line with trailing whitespace still folds to a
    2199              : // newline. Reads nothing.
    2200         4147 : static bool at_blank_line(parse_ctx *ctx) {
    2201         4147 :   size_t p = ctx->pos;
    2202         4301 :   while (p < ctx->len && (ctx->src[p] == ' ' || ctx->src[p] == '\t')) p++;
    2203         4147 :   return p >= ctx->len || ctx->src[p] == '\r' || ctx->src[p] == '\n';
    2204              : }
    2205              : 
    2206              : // True for a C0 control other than tab, and for DEL, which no scalar style may
    2207              : // hold raw (PyYAML refuses DEL in every style too). The serializer uses it to
    2208              : // double-quote a string holding one and write it as an escape.
    2209          108 : static inline bool is_disallowed_control_byte(char c) {
    2210          108 :   unsigned char u = (unsigned char)c;
    2211          108 :   return (u < 0x20 && u != '\t') || u == 0x7F;
    2212              : }
    2213              : 
    2214              : // A stream must be UTF-8 made of c-printable characters only. parse_common()
    2215              : // checks the whole input once before parsing, so no scanner checks again, and a
    2216              : // raw NUL never reaches a stored token. The check accepts 16 printable ASCII
    2217              : // bytes with one vector compare and walks any other block one character at a
    2218              : // time (GCC and Clang vector extensions).
    2219              : typedef unsigned char cyaml_u8x16 __attribute__((vector_size(16)));
    2220              : typedef signed char cyaml_s8x16 __attribute__((vector_size(16)));
    2221              : 
    2222              : // True when each of the 16 bytes at p is TAB, LF, CR or 0x20 to 0x7E, the
    2223              : // vector fast path of cyaml_first_refused_char().
    2224      1039186 : static inline bool cyaml_block_is_printable_ascii(const unsigned char *p) {
    2225      1039186 :   cyaml_u8x16 v;
    2226      1039186 :   memcpy(&v, p, sizeof(v));
    2227      1039186 :   cyaml_s8x16 bad =
    2228      1039186 :       ((v < 0x20) & (v != 0x09) & (v != 0x0A) & (v != 0x0D)) | (v >= 0x7F);
    2229      1039186 :   uint64_t lo, hi;
    2230      1039186 :   memcpy(&lo, &bad, sizeof(lo));
    2231      1039186 :   memcpy(&hi, (const char *)&bad + sizeof(lo), sizeof(hi));
    2232      1039186 :   return (lo | hi) == 0;
    2233              : }
    2234              : 
    2235              : // True for an ASCII byte outside c-printable (a C0 control other than TAB, LF
    2236              : // and CR, or DEL), the slow path of the stream check.
    2237       102881 : static inline bool cyaml_is_refused_ascii(unsigned char c) {
    2238       102881 :   return (c < 0x20 && c != 0x09 && c != 0x0A && c != 0x0D) || c == 0x7F;
    2239              : }
    2240              : 
    2241              : // Gives the offset of the first character of p[0..len) that is ill-formed UTF-8
    2242              : // or outside c-printable (C1 controls other than NEL, U+FFFE, U+FFFF included),
    2243              : // or len when there is none. parse_common() runs it on the whole input before
    2244              : // parsing.
    2245        14434 : static size_t cyaml_first_refused_char(const unsigned char *p, size_t len) {
    2246        14434 :   size_t i = 0;
    2247              :   for (;;) {
    2248      1049411 :     while (len - i >= 16 && cyaml_block_is_printable_ascii(p + i)) i += 16;
    2249        14483 :     size_t stop = len - i >= 16 ? i + 16 : len;
    2250       114517 :     while (i < stop) {
    2251       107469 :       unsigned char c = p[i];
    2252       107469 :       if (c < 0x80) {
    2253       110316 :         if (cyaml_is_refused_ascii(c)) return i;
    2254        99877 :         i++;
    2255        99877 :         continue;
    2256              :       }
    2257         4588 :       bool ok;
    2258         4588 :       size_t step = ccol_utf8_step(p + i, len - i, &ok);
    2259         4588 :       if (!ok) return i;
    2260          230 :       if (c == 0xC2 && p[i + 1] <= 0x9F && p[i + 1] != 0x85) return i;
    2261          179 :       if (c == 0xEF && p[i + 1] == 0xBF && p[i + 2] >= 0xBE) return i;
    2262          157 :       i += step;
    2263              :     }
    2264         7048 :     if (i >= len) return len;
    2265              :   }
    2266              : }
    2267              : 
    2268              : // Writes the error for the character at p[at] that cyaml_first_refused_char()
    2269              : // refused into msg, so the caller learns where and what it is: The defect, the
    2270              : // bytes as 0xNN, and the line and column counted from 1. The column counts
    2271              : // characters, and a leading byte-order mark isn't counted. The text comes from
    2272              : // the UTF-8 helper shared with cjson.
    2273         7435 : static void cyaml_describe_refused_char(const unsigned char *p, size_t len,
    2274              :                                         size_t at, char *msg, size_t msg_size) {
    2275         7435 :   size_t line = 1, line_start = 0;
    2276       134042 :   for (size_t i = 0; i < at; i++) {
    2277       126607 :     if (p[i] == '\n' || (p[i] == '\r' && (i + 1 >= len || p[i + 1] != '\n'))) {
    2278           76 :       line++;
    2279           76 :       line_start = i + 1;
    2280              :     }
    2281              :   }
    2282              :   size_t col = 1;
    2283       133645 :   for (size_t i = line_start; i < at; i++)
    2284       126210 :     if ((p[i] & 0xC0) != 0x80) col++;
    2285         7435 :   if (line_start == 0 && at >= 3 && p[0] == 0xEF && p[1] == 0xBB &&
    2286            1 :       p[2] == 0xBF)
    2287            1 :     col--;
    2288              : 
    2289         7435 :   unsigned char c = p[at];
    2290         7435 :   unsigned char c1 = at + 1 < len ? p[at + 1] : 0;
    2291         7435 :   if (c < 0x80) {
    2292         3004 :     snprintf(msg, msg_size,
    2293              :              "raw control character 0x%02x is not allowed in a YAML stream "
    2294              :              "(line %zu, column %zu); write it as an escape sequence in a "
    2295              :              "double-quoted scalar",
    2296              :              c, line, col);
    2297         3077 :     return;
    2298              :   }
    2299         4431 :   bool ok;
    2300         4431 :   (void)ccol_utf8_step(p + at, len - at, &ok);
    2301         4431 :   if (ok) {
    2302           73 :     if (c == 0xC2)
    2303           51 :       snprintf(msg, msg_size,
    2304              :                "C1 control character U+00%02X (bytes 0xc2 0x%02x) is not "
    2305              :                "allowed in a YAML stream (line %zu, column %zu); write it as "
    2306              :                "an escape sequence in a double-quoted scalar",
    2307              :                c1, c1, line, col);
    2308              :     else
    2309           22 :       snprintf(msg, msg_size,
    2310              :                "noncharacter U+FFF%c (bytes 0xef 0xbf 0x%02x) is not allowed "
    2311              :                "in a YAML stream (line %zu, column %zu); write it as an "
    2312              :                "escape sequence in a double-quoted scalar",
    2313           22 :                p[at + 2] == 0xBE ? 'E' : 'F', p[at + 2], line, col);
    2314           73 :     return;
    2315              :   }
    2316              : 
    2317         4358 :   char detail[64];
    2318         4358 :   const char *what =
    2319         4358 :       ccol_utf8_describe_ill_formed(p, len, at, detail, sizeof(detail));
    2320         4358 :   snprintf(msg, msg_size,
    2321              :            "invalid UTF-8 in a YAML stream (line %zu, column %zu): %s (%s)",
    2322              :            line, col, what, detail);
    2323              : }
    2324              : 
    2325              : // True at "---" or "..." in column 0 followed by whitespace or the end, so
    2326              : // block parsers stop at a document boundary and the stream loop finds the next
    2327              : // document. "---#x" is no marker, since a comment needs whitespace before it.
    2328       334653 : CYAML_PARSE_HOT bool at_doc_marker(parse_ctx *ctx) {
    2329       634935 :   if (current_col(ctx) != 0) return false;
    2330        27141 :   if (ctx->pos + 3 > ctx->len) return false;
    2331        22889 :   const char *p = ctx->src + ctx->pos;
    2332        22889 :   if (memcmp(p, "---", 3) != 0 && memcmp(p, "...", 3) != 0) return false;
    2333          873 :   if (ctx->pos + 3 == ctx->len) return true;
    2334          873 :   char nx = ctx->src[ctx->pos + 3];
    2335          873 :   return nx == ' ' || nx == '\t' || nx == '\n' || nx == '\r';
    2336              : }
    2337              : 
    2338              : // True at a byte-order mark in column 0. Inside a document it ends the block
    2339              : // structure like a marker, and the stream loop accepts it only in a document
    2340              : // prefix.
    2341       370744 : static inline bool at_col0_bom(parse_ctx *ctx) {
    2342       739966 :   return ctx->len - ctx->pos >= 3 &&
    2343       369222 :          (unsigned char)ctx->src[ctx->pos] == 0xEF &&
    2344            8 :          (unsigned char)ctx->src[ctx->pos + 1] == 0xBB &&
    2345       370760 :          (unsigned char)ctx->src[ctx->pos + 2] == 0xBF && current_col(ctx) == 0;
    2346              : }
    2347              : 
    2348              : // Creates the anchor table on first use. The table points names at the anchored
    2349              : // nodes, which stay where the document put them, so registering copies nothing;
    2350              : // an alias resolves to a deep clone, charged to the amplification budget. The
    2351              : // table owns no node: Each one lives in a tree or in the kept list until
    2352              : // anchors_destroy(), which runs at the end of every document.
    2353         7123 : static bool anchors_ensure(parse_ctx *ctx) {
    2354         7123 :   if (ctx->anchors) return true;
    2355         1390 :   char *err = NULL;
    2356         1390 :   ctx->anchors = chashmap_create_mp(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE,
    2357              :                                     ccol_string, ccol_pointer, ctx->mp, &err);
    2358         1390 :   if (!ctx->anchors) return false;
    2359         1384 :   parse_discard_ctx = ctx;
    2360         1384 :   return true;
    2361              : }
    2362              : 
    2363              : // Reserves one more kept-list slot for a node anchors_store() registers, so
    2364              : // parse_keep() never allocates. false on OOM.
    2365         7117 : static bool anchors_reserve_kept(parse_ctx *ctx) {
    2366         7117 :   if (ctx->kept_reserved == ctx->kept_cap) {
    2367         1413 :     size_t new_cap = ctx->kept_cap ? ctx->kept_cap * 2 : 16;
    2368         2826 :     cyaml_node **grown =
    2369         1413 :         ccol__mem_realloc(ctx->mp, ctx->kept, new_cap * sizeof(*grown));
    2370         1413 :     if (!grown) return false;
    2371         1407 :     ctx->kept = grown;
    2372         1407 :     ctx->kept_cap = new_cap;
    2373              :   }
    2374         7111 :   ctx->kept_reserved++;
    2375         7111 :   return true;
    2376              : }
    2377              : 
    2378              : // Appends an entry for name (old is NULL) to the running speculation's log, so
    2379              : // anchors_store() can record a change a rejection must undo. The entry stays
    2380              : // valid until the next push; NULL on OOM.
    2381         3516 : static anchor_undo_entry *anchor_undo_push(parse_ctx *ctx, const char *name) {
    2382         3516 :   anchor_undo_log *u = ctx->anchor_undo;
    2383         3516 :   if (u->len == u->cap) {
    2384           49 :     size_t new_cap = u->cap * 2;
    2385           49 :     anchor_undo_entry *grown;
    2386           49 :     if (u->entries == u->inline_entries) {
    2387            7 :       grown = ccol__mem_alloc(ctx->mp, new_cap * sizeof(*grown));
    2388            7 :       if (grown) memcpy(grown, u->entries, u->len * sizeof(*grown));
    2389              :     } else {
    2390           42 :       grown = ccol__mem_realloc(ctx->mp, u->entries, new_cap * sizeof(*grown));
    2391              :     }
    2392           49 :     if (!grown) return NULL;
    2393           49 :     u->entries = grown;
    2394           49 :     u->cap = new_cap;
    2395              :   }
    2396         3516 :   char *copy = ccol_strdup(ctx->mp, name);
    2397            0 :   if (!copy) return NULL;
    2398         3516 :   anchor_undo_entry *e = &u->entries[u->len++];
    2399         3516 :   e->name = copy;
    2400         3516 :   e->old = NULL;
    2401         3516 :   return e;
    2402              : }
    2403              : 
    2404              : // Points name at node with one hash and one probe, marks the node anchored and
    2405              : // reserves a kept slot; a later definition of the name wins. While a
    2406              : // speculation runs, the change and the previous node go into its log. On OOM it
    2407              : // sets a parse error (so a later alias doesn't fail with a misleading "unknown
    2408              : // alias") and gives false, and the caller keeps node.
    2409         7123 : static bool anchors_store(parse_ctx *ctx, const char *name, cyaml_node *node) {
    2410         7123 :   if (!anchors_ensure(ctx) || !anchors_reserve_kept(ctx)) {
    2411           12 :     parse_err(ctx, "out of memory registering anchor '%s' at position %zu",
    2412           12 :               cyaml_echo(name), ctx->pos);
    2413           12 :     return false;
    2414              :   }
    2415         7111 :   anchor_undo_entry *undo = NULL;
    2416         7111 :   if (ctx->anchor_undo) {
    2417         3516 :     undo = anchor_undo_push(ctx, name);
    2418         3516 :     if (!undo) {
    2419            0 :       parse_err(ctx, "out of memory registering anchor '%s' at position %zu",
    2420            0 :                 cyaml_echo(name), ctx->pos);
    2421            0 :       return false;
    2422              :     }
    2423              :   }
    2424         7111 :   cmap_pair kp = {.ptr = (void *)name, .size = strlen(name) + 1};
    2425         7111 :   cmap_pair vp = {.ptr = &node, .size = sizeof(node)};
    2426         7111 :   cmap_pair old_vp;
    2427         7111 :   ccol_retval ins =
    2428         7111 :       ccol_chmap_insert_or_get_elem(ctx->anchors, &kp, &vp, &old_vp);
    2429         7111 :   if (ins == ccol_success) {
    2430         1579 :     node->anchored = true;
    2431         1579 :     return true;
    2432              :   }
    2433         5532 :   if (ins == ccol_key_already_present) {
    2434         5525 :     if (undo) undo->old = cyaml_read_child(old_vp.ptr);
    2435         5525 :     memcpy(old_vp.ptr, &node, sizeof(node));
    2436         5525 :     node->anchored = true;
    2437         5525 :     return true;
    2438              :   }
    2439            7 :   if (undo) {
    2440            0 :     ctx->anchor_undo->len--;
    2441            0 :     ccol__mem_free(ctx->mp, undo->name);
    2442              :   }
    2443           14 :   parse_err(ctx, "out of memory registering anchor '%s' at position %zu",
    2444            7 :             cyaml_echo(name), ctx->pos);
    2445            7 :   return false;
    2446              : }
    2447              : 
    2448              : // The one speculative parse is a flow collection that may be an implicit block
    2449              : // key (see try_parse_scalar_dict_key_body()). Its side effects must vanish when
    2450              : // it's rejected: Stored anchors, kept nodes and budget charges. begin records
    2451              : // the budgets and the kept length and starts an undo log; reject restores all
    2452              : // of it without allocating, accept keeps it. A new side effect in a parse
    2453              : // function needs an undo here too.
    2454              : typedef struct {
    2455              :   anchor_undo_log undo;
    2456              :   anchor_undo_log *outer;
    2457              :   size_t kept_len;
    2458              :   size_t node_budget;
    2459              :   size_t byte_budget;
    2460              :   size_t amp_node_budget;
    2461              :   size_t amp_byte_budget;
    2462              :   bool node_exhausted;
    2463              :   bool byte_exhausted;
    2464              :   bool amp_limit_hit;
    2465              : } anchor_speculation;
    2466              : 
    2467              : // Starts a speculation: Snapshots the budgets and the kept length into sp and
    2468              : // installs a fresh undo log in ctx.
    2469          386 : static void anchor_speculation_begin(parse_ctx *ctx, anchor_speculation *sp) {
    2470          386 :   sp->undo.entries = sp->undo.inline_entries;
    2471          386 :   sp->undo.len = 0;
    2472          386 :   sp->undo.cap = ANCHOR_UNDO_INLINE;
    2473          386 :   sp->outer = ctx->anchor_undo;
    2474          386 :   sp->kept_len = ctx->kept_len;
    2475          386 :   sp->node_budget = parse_node_budget;
    2476          386 :   sp->byte_budget = parse_byte_budget;
    2477          386 :   sp->amp_node_budget = parse_amp_node_budget;
    2478          386 :   sp->amp_byte_budget = parse_amp_byte_budget;
    2479          386 :   sp->node_exhausted = parse_node_budget_exhausted;
    2480          386 :   sp->byte_exhausted = parse_byte_budget_exhausted;
    2481          386 :   sp->amp_limit_hit = parse_amp_limit_hit;
    2482          386 :   ctx->anchor_undo = &sp->undo;
    2483              : }
    2484              : 
    2485              : // Ends a speculation, for both accept and reject: Frees the log's name copies
    2486              : // and puts the outer log back.
    2487          386 : static void anchor_speculation_end(parse_ctx *ctx, anchor_speculation *sp) {
    2488         3902 :   for (size_t i = 0; i < sp->undo.len; i++)
    2489         3516 :     ccol__mem_free(ctx->mp, sp->undo.entries[i].name);
    2490          386 :   if (sp->undo.entries != sp->undo.inline_entries)
    2491            7 :     ccol__mem_free(ctx->mp, sp->undo.entries);
    2492          386 :   ctx->anchor_undo = sp->outer;
    2493          386 : }
    2494              : 
    2495              : // Accepts a speculation: Ends it and keeps its changes, when the flow
    2496              : // collection really was a key or the parse fails anyway.
    2497          332 : static void anchor_speculation_accept(parse_ctx *ctx, anchor_speculation *sp) {
    2498          332 :   anchor_speculation_end(ctx, sp);
    2499              : }
    2500              : 
    2501              : // Rejects a speculation, so the second reading sees no trace of it: Undoes the
    2502              : // stores in reverse order (a name the speculation added keeps a slot with NULL,
    2503              : // so no map delete is needed), frees the nodes it kept and restores the
    2504              : // budgets. The caller has already destroyed the speculative tree, so the
    2505              : // restored slots are written but never read through.
    2506           54 : static void anchor_speculation_reject(parse_ctx *ctx, anchor_speculation *sp) {
    2507         3567 :   for (size_t i = sp->undo.len; i-- > 0;) {
    2508         3513 :     anchor_undo_entry *e = &sp->undo.entries[i];
    2509         3513 :     cmap_pair kp = {.ptr = e->name, .size = strlen(e->name) + 1};
    2510         3513 :     cmap_pair vp;
    2511         3513 :     if (chashmap_get_elem_ref(ctx->anchors, &kp, &vp) == ccol_success)
    2512         3513 :       memcpy(vp.ptr, &e->old, sizeof(e->old));
    2513              :   }
    2514           57 :   while (ctx->kept_len > sp->kept_len)
    2515            3 :     cyaml__destroy((cyaml)ctx->kept[--ctx->kept_len]);
    2516           54 :   parse_node_budget = sp->node_budget;
    2517           54 :   parse_byte_budget = sp->byte_budget;
    2518           54 :   parse_amp_node_budget = sp->amp_node_budget;
    2519           54 :   parse_amp_byte_budget = sp->amp_byte_budget;
    2520           54 :   parse_node_budget_exhausted = sp->node_exhausted;
    2521           54 :   parse_byte_budget_exhausted = sp->byte_exhausted;
    2522           54 :   parse_amp_limit_hit = sp->amp_limit_hit;
    2523           54 :   anchor_speculation_end(ctx, sp);
    2524           54 : }
    2525              : 
    2526              : // Gives the node anchored as name, so an alias can copy it, or NULL; a slot
    2527              : // holding NULL was taken back by a rejected speculation.
    2528         3761 : static cyaml_node *anchors_lookup(parse_ctx *ctx, const char *name) {
    2529         3761 :   if (!ctx->anchors) return NULL;
    2530         3576 :   cmap_pair kp = {.ptr = (void *)name, .size = strlen(name) + 1};
    2531         3576 :   cmap_pair vp;
    2532         3576 :   if (chashmap_get_elem_ref(ctx->anchors, &kp, &vp) != ccol_success)
    2533              :     return NULL;
    2534         3576 :   return cyaml_read_child(vp.ptr);
    2535              : }
    2536              : 
    2537              : // Frees the anchor table and every node of the kept list at the end of each
    2538              : // document, since anchors don't cross documents. After a failed parse the map
    2539              : // may name freed nodes, which nothing reads.
    2540         7038 : static void anchors_destroy(parse_ctx *ctx) {
    2541         7038 :   if (parse_discard_ctx == ctx) parse_discard_ctx = NULL;
    2542         7389 :   for (size_t i = 0; i < ctx->kept_len; i++)
    2543          351 :     cyaml__destroy((cyaml)ctx->kept[i]);
    2544         7038 :   ccol__mem_free(ctx->mp, ctx->kept);
    2545         7039 :   ctx->kept = NULL;
    2546         7039 :   ctx->kept_len = 0;
    2547         7039 :   ctx->kept_cap = 0;
    2548         7039 :   ctx->kept_reserved = 0;
    2549         7039 :   if (!ctx->anchors) return;
    2550         1384 :   chashmap__destroy(ctx->anchors);
    2551         1384 :   ctx->anchors = NULL;
    2552              : }
    2553              : 
    2554              : // Creates the %TAG table on first use. It lives as long as the anchor table and
    2555              : // starts empty, since the lookup falls back to the defaults of "!" and "!!"
    2556              : // itself, so the insert's "already present" answer spots a duplicate %TAG in
    2557              : // one document.
    2558          100 : static bool tag_handles_ensure(parse_ctx *ctx) {
    2559          100 :   if (ctx->tag_handles) return true;
    2560           98 :   char *err = NULL;
    2561          196 :   ctx->tag_handles =
    2562           98 :       chashmap_create_mp(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE, ccol_string,
    2563              :                          ccol_string, ctx->mp, &err);
    2564           98 :   return ctx->tag_handles != NULL;
    2565              : }
    2566              : 
    2567              : // Sets the prefix of a %TAG handle for the directive parser: ccol_success on a
    2568              : // first definition, ccol_key_already_present for a handle the document already
    2569              : // defined, anything else on OOM.
    2570          100 : static ccol_retval tag_handles_set(parse_ctx *ctx, const char *handle,
    2571              :                                    const char *prefix) {
    2572          100 :   if (!tag_handles_ensure(ctx)) return ccol_not_enough_memory;
    2573          100 :   cmap_pair kp = {.ptr = (void *)handle, .size = strlen(handle) + 1};
    2574          100 :   cmap_pair vp = {.ptr = (void *)prefix, .size = strlen(prefix) + 1};
    2575          100 :   return chashmap_insert_elem(ctx->tag_handles, &kp, &vp);
    2576              : }
    2577              : 
    2578              : // Gives the prefix of handle, to resolve a shorthand tag: A %TAG definition,
    2579              : // else the default for "!" or "!!", else NULL.
    2580         9385 : static const char *tag_handles_lookup(parse_ctx *ctx, const char *handle) {
    2581         9385 :   if (ctx->tag_handles) {
    2582           62 :     cmap_pair kp = {.ptr = (void *)handle, .size = strlen(handle) + 1};
    2583           62 :     cmap_pair vp;
    2584           62 :     if (chashmap_get_elem_ref(ctx->tag_handles, &kp, &vp) == ccol_success)
    2585           58 :       return (const char *)vp.ptr;
    2586              :   }
    2587         9327 :   if (strcmp(handle, "!") == 0) return "!";
    2588         3746 :   if (strcmp(handle, "!!") == 0) return "tag:yaml.org,2002:";
    2589              :   return NULL;
    2590              : }
    2591              : 
    2592              : // Frees the %TAG table at the end of each document, since %TAG doesn't cross
    2593              : // documents.
    2594         7038 : static void tag_handles_destroy(parse_ctx *ctx) {
    2595         7038 :   if (!ctx->tag_handles) return;
    2596           98 :   chashmap__destroy(ctx->tag_handles);
    2597           98 :   ctx->tag_handles = NULL;
    2598              : }
    2599              : 
    2600              : // Reads an anchor or alias name after '&' or '*' into *name_out: Everything up
    2601              : // to whitespace, a flow indicator or '#'. A ':' followed by whitespace ends the
    2602              : // name too, so "*x: y" uses alias x as a key. On an empty name or OOM it sets
    2603              : // ctx->error and gives false; the speculative key parse relies on ctx->error to
    2604              : // tell a real error from "not a key".
    2605        18695 : static bool parse_anchor_name(parse_ctx *ctx, char **name_out) {
    2606        18695 :   size_t start = ctx->pos;
    2607        41256 :   while (!at_end(ctx)) {
    2608        41256 :     char c = cur(ctx);
    2609        41256 :     if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',' ||
    2610              :         c == '[' || c == ']' || c == '{' || c == '}' || c == '#')
    2611              :       break;
    2612              :     if (c == ':') {
    2613          285 :       bool stop = (ctx->pos + 1 >= ctx->len) || ctx->src[ctx->pos + 1] == ' ' ||
    2614              :                   ctx->src[ctx->pos + 1] == '\t' ||
    2615          285 :                   ctx->src[ctx->pos + 1] == '\n' ||
    2616              :                   ctx->src[ctx->pos + 1] == '\r';
    2617              :       if (stop) break;
    2618              :     }
    2619        22561 :     ctx->pos++;
    2620              :   }
    2621        18695 :   size_t len = ctx->pos - start;
    2622        18695 :   if (len == 0) {
    2623           27 :     parse_err(ctx, "empty anchor/alias name at position %zu", start);
    2624           27 :     return false;
    2625              :   }
    2626        18668 :   char *name = ccol__mem_alloc(ctx->mp, len + 1);
    2627        18668 :   if (!name) {
    2628           12 :     parse_err(ctx, "out of memory parsing anchor/alias name at position %zu",
    2629              :               start);
    2630           12 :     return false;
    2631              :   }
    2632        18656 :   memcpy(name, ctx->src + start, len);
    2633        18656 :   name[len] = '\0';
    2634        18656 :   *name_out = name;
    2635        18656 :   return true;
    2636              : }
    2637              : 
    2638              : // Tells whether s is a core-schema bool (true/True/TRUE, false/False/FALSE) and
    2639              : // stores it in *out. The type tests are separate functions so an explicit tag
    2640              : // can force one of them. Each dispatches on the first byte before any
    2641              : // comparison, because nearly every scalar must be ruled out and a strcmp chain
    2642              : // costs a call per spelling.
    2643       183497 : static bool try_parse_bool_scalar(const char *s, bool *out) {
    2644       183497 :   switch (s[0]) {
    2645          519 :     case 't':
    2646          519 :       if (strcmp(s, "true") == 0) break;
    2647              :       return false;
    2648           10 :     case 'T':
    2649           10 :       if (strcmp(s, "True") == 0 || strcmp(s, "TRUE") == 0) break;
    2650              :       return false;
    2651          597 :     case 'f':
    2652          597 :       if (strcmp(s, "false") == 0) {
    2653           27 :         *out = false;
    2654           27 :         return true;
    2655              :       }
    2656              :       return false;
    2657            8 :     case 'F':
    2658            8 :       if (strcmp(s, "False") == 0 || strcmp(s, "FALSE") == 0) {
    2659            0 :         *out = false;
    2660            0 :         return true;
    2661              :       }
    2662              :       return false;
    2663              :     default:
    2664              :       return false;
    2665              :   }
    2666          234 :   *out = true;
    2667          234 :   return true;
    2668              : }
    2669              : 
    2670              : // Tells whether s is a core-schema int and stores it in *out, for implicit
    2671              : // typing and !!int: Decimal with an optional sign, or unsigned 0x hex or 0o
    2672              : // octal with a lowercase prefix, at most LLONG_MAX. The first byte must be a
    2673              : // digit or a sign, because strtoll() skips leading whitespace that an escape
    2674              : // can carry. The digits after 0x or 0o are checked by hand, since strtoull()
    2675              : // accepts a sign there.
    2676       183458 : CYAML_PARSE_HOT bool try_parse_int_scalar(const char *s, long long *out) {
    2677       183458 :   const unsigned char first = (unsigned char)s[0];
    2678       160966 :   if (!((unsigned)(first - '0') < 10u || first == '+' || first == '-'))
    2679              :     return false;
    2680              : 
    2681        22564 :   char *endp = NULL;
    2682        22564 :   long long ival = 0;
    2683        22564 :   errno = 0;
    2684              : 
    2685        22564 :   const char *p = s;
    2686        22564 :   if (p[0] == '0' && p[1] == 'x') {
    2687           21 :     const char *digits = p + 2;
    2688           21 :     if (*digits == '\0') return false;
    2689          143 :     for (const char *d = digits; *d; d++) {
    2690          127 :       bool is_hex_digit = (*d >= '0' && *d <= '9') ||
    2691              :                           (*d >= 'a' && *d <= 'f') || (*d >= 'A' && *d <= 'F');
    2692          122 :       if (!is_hex_digit) return false;
    2693              :     }
    2694           16 :     unsigned long long uval = strtoull(digits, &endp, 16);
    2695           16 :     if (endp == digits || *endp != '\0' || errno == ERANGE) return false;
    2696           16 :     if (uval > (unsigned long long)LLONG_MAX) return false;
    2697              :     ival = (long long)uval;
    2698          198 :   } else if (p[0] == '0' && p[1] == 'o') {
    2699            6 :     const char *digits = p + 2;
    2700            6 :     if (*digits == '\0') return false;
    2701           73 :     for (const char *d = digits; *d; d++) {
    2702           69 :       if (*d < '0' || *d > '7') return false;
    2703              :     }
    2704            4 :     unsigned long long uval = strtoull(digits, &endp, 8);
    2705            4 :     if (endp == digits || *endp != '\0' || errno == ERANGE) return false;
    2706            4 :     if (uval > (unsigned long long)LLONG_MAX) return false;
    2707              :     ival = (long long)uval;
    2708              :   } else {
    2709        22537 :     ival = strtoll(s, &endp, 10);
    2710        22537 :     if (endp == s || *endp != '\0' || errno == ERANGE) return false;
    2711              :   }
    2712        22253 :   *out = ival;
    2713        22253 :   return true;
    2714              : }
    2715              : 
    2716              : // Tells whether s is a core-schema float and stores it in *out, for implicit
    2717              : // typing and !!float: .inf, -.inf and .nan included, but not "nan", "inf",
    2718              : // "nan(...)" or any 0x/0o text, which strtod() would accept. The first byte
    2719              : // must be a digit, a sign or '.'. Overflow gives +-inf and underflow a
    2720              : // subnormal or 0, as in PyYAML. Callers run in the C locale.
    2721       161170 : CYAML_PARSE_HOT bool try_parse_float_scalar(const char *s, double *out) {
    2722       161170 :   const unsigned char first = (unsigned char)s[0];
    2723       160928 :   if (!((unsigned)(first - '0') < 10u || first == '+' || first == '-' ||
    2724              :         first == '.'))
    2725              :     return false;
    2726              : 
    2727          319 :   if (s[0] == '.' || s[0] == '+' || s[0] == '-') {
    2728           86 :     if (strcmp(s, ".inf") == 0 || strcmp(s, ".Inf") == 0 ||
    2729           78 :         strcmp(s, ".INF") == 0 || strcmp(s, "+.inf") == 0 ||
    2730           78 :         strcmp(s, "+.Inf") == 0 || strcmp(s, "+.INF") == 0) {
    2731              :       *out = __builtin_inf();
    2732              :       return true;
    2733              :     }
    2734           78 :     if (strcmp(s, "-.inf") == 0 || strcmp(s, "-.Inf") == 0 ||
    2735           71 :         strcmp(s, "-.INF") == 0) {
    2736              :       *out = -__builtin_inf();
    2737              :       return true;
    2738              :     }
    2739           71 :     if (strcmp(s, ".nan") == 0 || strcmp(s, ".NaN") == 0 ||
    2740           64 :         strcmp(s, ".NAN") == 0) {
    2741              :       *out = __builtin_nan("");
    2742              :       return true;
    2743              :     }
    2744              :   }
    2745              : 
    2746          297 :   const char *q = s;
    2747          297 :   if (*q == '+' || *q == '-') q++;
    2748          297 :   const char qc = *q;
    2749          297 :   if (qc == 'n' || qc == 'N' || qc == 'i' || qc == 'I') {
    2750            4 :     if (ccol_ascii_casecmp(q, "nan") == 0 ||
    2751            4 :         ccol_ascii_casecmp(q, "inf") == 0 ||
    2752            1 :         ccol_ascii_casecmp(q, "infinity") == 0)
    2753              :       return false;
    2754            1 :     if (ccol_ascii_ncasecmp(q, "nan(", 4) == 0) return false;
    2755              :   }
    2756              : 
    2757          293 :   if (q[0] == '0' && (q[1] == 'x' || q[1] == 'o' || q[1] == 'X' || q[1] == 'O'))
    2758              :     return false;
    2759              : 
    2760          264 :   char *endp = NULL;
    2761          264 :   double dval = strtod(s, &endp);
    2762          264 :   if (endp == s || *endp != '\0') return false;
    2763              :   *out = dval;
    2764              :   return true;
    2765              : }
    2766              : 
    2767              : // True for "", "~" and the core-schema spellings of null, the first test of
    2768              : // implicit typing.
    2769       223804 : static bool is_null_scalar_text(const char *s) {
    2770       223804 :   switch (s[0]) {
    2771              :     case '\0':
    2772              :       return true;
    2773           52 :     case '~':
    2774           52 :       return s[1] == '\0';
    2775          280 :     case 'n':
    2776          280 :       return strcmp(s, "null") == 0;
    2777           14 :     case 'N':
    2778           16 :       return strcmp(s, "Null") == 0 || strcmp(s, "NULL") == 0;
    2779       183412 :     default:
    2780       183412 :       return false;
    2781              :   }
    2782              : }
    2783              : 
    2784              : // Makes the node of an untagged plain scalar by core-schema typing (null, bool,
    2785              : // int, float, else a string); the parser and every plain key go through it.
    2786              : // NULL on OOM.
    2787       223804 : static cyaml_node *make_typed_scalar(parse_ctx *ctx, const char *s) {
    2788       223804 :   ccol_memmgmt_procs *mp = ctx->mp;
    2789              : 
    2790       264111 :   if (is_null_scalar_text(s)) return node_alloc(CYAML_NULL, mp);
    2791              : 
    2792       183496 :   bool bval;
    2793       183496 :   if (try_parse_bool_scalar(s, &bval)) {
    2794          261 :     cyaml_node *n = node_alloc(CYAML_BOOL, mp);
    2795          261 :     if (n) n->value.boolean = bval;
    2796          261 :     return n;
    2797              :   }
    2798              : 
    2799       183237 :   long long ival;
    2800       183237 :   if (try_parse_int_scalar(s, &ival)) {
    2801        22233 :     cyaml_node *n = node_alloc(CYAML_INTEGER, mp);
    2802        22189 :     if (n) n->value.integer = ival;
    2803        22234 :     return n;
    2804              :   }
    2805              : 
    2806       161004 :   double dval;
    2807       161004 :   if (try_parse_float_scalar(s, &dval)) {
    2808          178 :     cyaml_node *n = node_alloc(CYAML_FLOAT, mp);
    2809          178 :     if (n) n->value.number = dval;
    2810          178 :     return n;
    2811              :   }
    2812              : 
    2813       160826 :   cyaml_node *n = node_alloc(CYAML_STRING, mp);
    2814           72 :   if (!n) return NULL;
    2815       160753 :   n->value.string = strdup_charged(mp, s);
    2816       160753 :   if (!n->value.string) {
    2817           72 :     node_free(n);
    2818           72 :     return NULL;
    2819              :   }
    2820              :   return n;
    2821              : }
    2822              : 
    2823              : // Removes trailing whitespace and newlines before !!int or !!float parses the
    2824              : // text, so chomped block scalars match, as PyYAML accepts them. Leading
    2825              : // whitespace stays and !!bool doesn't trim, again as PyYAML does.
    2826          259 : static void trim_trailing_ws_for_numeric_tag(char *text) {
    2827          259 :   size_t len = strlen(text);
    2828          271 :   while (len > 0 && (text[len - 1] == '\n' || text[len - 1] == '\r' ||
    2829              :                      text[len - 1] == ' ' || text[len - 1] == '\t'))
    2830              :     len--;
    2831          259 :   text[len] = '\0';
    2832          259 : }
    2833              : 
    2834              : // Tells whether s is a word that !!bool accepts and stores it in *out. That's
    2835              : // PyYAML's set: true, false, yes, no, on and off in any case, but not y or n.
    2836          117 : static bool try_parse_bool_scalar_explicit(const char *s, bool *out) {
    2837          342 :   if (ccol_ascii_casecmp(s, "true") == 0 || ccol_ascii_casecmp(s, "yes") == 0 ||
    2838          106 :       ccol_ascii_casecmp(s, "on") == 0) {
    2839           12 :     *out = true;
    2840           12 :     return true;
    2841              :   }
    2842          209 :   if (ccol_ascii_casecmp(s, "false") == 0 || ccol_ascii_casecmp(s, "no") == 0 ||
    2843          103 :       ccol_ascii_casecmp(s, "off") == 0) {
    2844            3 :     *out = false;
    2845            3 :     return true;
    2846              :   }
    2847              :   return false;
    2848              : }
    2849              : 
    2850              : // Makes a string node that takes over *text from a scanner buffer, for quoted
    2851              : // and block scalars (*text is NULL on success). The text is shrunk to its
    2852              : // length and that length is charged to the byte budget, so a short scalar
    2853              : // doesn't keep a 256-byte buffer. NULL on OOM or a refused charge, without
    2854              : // setting ctx->error.
    2855         4897 : static cyaml_node *string_node_adopting_text(parse_ctx *ctx, char **text) {
    2856         4897 :   size_t size = strlen(*text) + 1;
    2857         4897 :   size_t charge = size + CYAML_ALLOC_OVERHEAD;
    2858         4897 :   if (!parse_bytes_charge(charge)) return NULL;
    2859         4897 :   cyaml_node *n = node_alloc(CYAML_STRING, ctx->mp);
    2860         4897 :   if (!n) {
    2861            1 :     parse_bytes_refund(charge);
    2862            1 :     return NULL;
    2863              :   }
    2864         4896 :   char *fit = ccol__mem_realloc(ctx->mp, *text, size);
    2865         4896 :   n->value.string = fit ? fit : *text;
    2866         4896 :   *text = NULL;
    2867         4896 :   return n;
    2868              : }
    2869              : 
    2870              : // Makes the node of a scalar from its text, every scalar style's last step, and
    2871              : // takes ownership of text. resolved_tag (NULL for none) is borrowed; a core tag
    2872              : // forces and checks the type, "!" gives a string with no tag, and a custom tag
    2873              : // is attached to whatever implicit_ok allows (implicit typing for plain scalars
    2874              : // only). NULL on OOM with ctx->error untouched, or with ctx->error set when tag
    2875              : // and text disagree.
    2876       215421 : static cyaml_node *finalize_scalar_node(parse_ctx *ctx, char *text,
    2877              :                                         const char *resolved_tag,
    2878              :                                         bool implicit_ok) {
    2879       215421 :   cyaml_node *n = NULL;
    2880              : 
    2881       215421 :   if (resolved_tag && strcmp(resolved_tag, CYAML_TAG_NON_SPECIFIC) == 0) {
    2882           16 :     n = string_node_adopting_text(ctx, &text);
    2883           16 :     ccol__mem_free(ctx->mp, text);
    2884           16 :     return n;
    2885              :   }
    2886         1729 :   if (resolved_tag && strcmp(resolved_tag, CYAML_TAG_NULL) == 0) {
    2887           12 :     n = node_alloc(CYAML_NULL, ctx->mp);
    2888         1717 :   } else if (resolved_tag && strcmp(resolved_tag, CYAML_TAG_BOOL) == 0) {
    2889          117 :     bool bval;
    2890          117 :     if (!try_parse_bool_scalar_explicit(text, &bval)) {
    2891          204 :       parse_err(ctx, "'%s' is not a valid !!bool value", cyaml_echo(text));
    2892          102 :       ccol__mem_free(ctx->mp, text);
    2893          102 :       return NULL;
    2894              :     }
    2895           30 :     n = node_alloc(CYAML_BOOL, ctx->mp);
    2896           15 :     if (n) n->value.boolean = bval;
    2897         1600 :   } else if (resolved_tag && strcmp(resolved_tag, CYAML_TAG_INT) == 0) {
    2898          147 :     trim_trailing_ws_for_numeric_tag(text);
    2899          147 :     long long ival;
    2900          294 :     if (!try_parse_int_scalar(text, &ival)) {
    2901          214 :       parse_err(ctx, "'%s' is not a valid !!int value", cyaml_echo(text));
    2902          107 :       ccol__mem_free(ctx->mp, text);
    2903          107 :       return NULL;
    2904              :     }
    2905           40 :     n = node_alloc(CYAML_INTEGER, ctx->mp);
    2906           40 :     if (n) n->value.integer = ival;
    2907         1453 :   } else if (resolved_tag && strcmp(resolved_tag, CYAML_TAG_FLOAT) == 0) {
    2908          112 :     trim_trailing_ws_for_numeric_tag(text);
    2909          112 :     double dval;
    2910          224 :     if (!try_parse_float_scalar(text, &dval)) {
    2911           88 :       parse_err(ctx, "'%s' is not a valid !!float value", cyaml_echo(text));
    2912           88 :       ccol__mem_free(ctx->mp, text);
    2913           88 :       return NULL;
    2914              :     }
    2915           24 :     n = node_alloc(CYAML_FLOAT, ctx->mp);
    2916           24 :     if (n) n->value.number = dval;
    2917         1341 :   } else if (resolved_tag && strcmp(resolved_tag, CYAML_TAG_STR) == 0) {
    2918         1079 :     n = string_node_adopting_text(ctx, &text);
    2919          262 :   } else if (resolved_tag && (strcmp(resolved_tag, CYAML_TAG_SEQ) == 0 ||
    2920          260 :                               strcmp(resolved_tag, CYAML_TAG_MAP) == 0)) {
    2921            3 :     parse_err(ctx, "tag '%s' does not match the node it decorates",
    2922            3 :               cyaml_echo(resolved_tag));
    2923            3 :     ccol__mem_free(ctx->mp, text);
    2924            3 :     return NULL;
    2925       213935 :   } else if (implicit_ok) {
    2926       210133 :     n = make_typed_scalar(ctx, text);
    2927              :   } else {
    2928         3802 :     n = string_node_adopting_text(ctx, &text);
    2929              :   }
    2930              : 
    2931       215109 :   ccol__mem_free(ctx->mp, text);
    2932              : 
    2933       215109 :   if (!n) return NULL;
    2934              : 
    2935       214967 :   if (resolved_tag) {
    2936         1429 :     char *tag_copy = strdup_charged(ctx->mp, resolved_tag);
    2937            0 :     if (!tag_copy) {
    2938            0 :       cyaml__destroy((cyaml)n);
    2939            0 :       return NULL;
    2940              :     }
    2941         1429 :     n->tag = tag_copy;
    2942              :   }
    2943              : 
    2944              :   return n;
    2945              : }
    2946              : 
    2947              : // Checks resolved_tag (borrowed) against a finished collection and attaches a
    2948              : // copy, since a collection's type comes from its syntax and a tag can only
    2949              : // agree with it. A scalar core tag, or !!seq/!!map on the wrong kind, is a
    2950              : // parse error. Each builder calls it the moment it builds the collection, so an
    2951              : // anchor above registers the tagged node. Destroys coll and gives NULL on
    2952              : // failure; "!" and NULL attach nothing.
    2953        84007 : static cyaml_node *finalize_collection_node(parse_ctx *ctx, cyaml_node *coll,
    2954              :                                             const char *resolved_tag) {
    2955        84007 :   if (!resolved_tag || !coll) return coll;
    2956        13600 :   if (strcmp(resolved_tag, CYAML_TAG_NON_SPECIFIC) == 0) return coll;
    2957              : 
    2958        13598 :   bool seq_ok = strcmp(resolved_tag, CYAML_TAG_SEQ) == 0;
    2959        13598 :   bool map_ok = strcmp(resolved_tag, CYAML_TAG_MAP) == 0;
    2960        40797 :   bool scalar_core_tag = strcmp(resolved_tag, CYAML_TAG_NULL) == 0 ||
    2961        13597 :                          strcmp(resolved_tag, CYAML_TAG_BOOL) == 0 ||
    2962        13596 :                          strcmp(resolved_tag, CYAML_TAG_INT) == 0 ||
    2963        27193 :                          strcmp(resolved_tag, CYAML_TAG_FLOAT) == 0 ||
    2964        13594 :                          strcmp(resolved_tag, CYAML_TAG_STR) == 0;
    2965        13592 :   if (scalar_core_tag || (seq_ok && coll->type != CYAML_LIST) ||
    2966           23 :       (map_ok && coll->type != CYAML_DICTIONARY)) {
    2967           10 :     parse_err(ctx,
    2968              :               "tag '%s' does not match the node it decorates at "
    2969              :               "position %zu",
    2970           10 :               cyaml_echo(resolved_tag), ctx->pos);
    2971           10 :     cyaml__destroy((cyaml)coll);
    2972           10 :     return NULL;
    2973              :   }
    2974              : 
    2975        13588 :   char *tag_copy = strdup_charged(ctx->mp, resolved_tag);
    2976            0 :   if (!tag_copy) {
    2977            0 :     cyaml__destroy((cyaml)coll);
    2978            0 :     return NULL;
    2979              :   }
    2980        13588 :   coll->tag = tag_copy;
    2981        13588 :   return coll;
    2982              : }
    2983              : 
    2984              : // Appends cp to b as UTF-8, for the \x, \u and \U escapes of double-quoted
    2985              : // scalars.
    2986         9879 : static void encode_utf8(ybuf *b, uint32_t cp) {
    2987         9879 :   char buf[4];
    2988         9879 :   int n;
    2989         9879 :   if (cp <= 0x7F) {
    2990         9783 :     buf[0] = (char)cp;
    2991         9783 :     n = 1;
    2992           96 :   } else if (cp <= 0x7FF) {
    2993           43 :     buf[0] = (char)(0xC0 | (cp >> 6));
    2994           43 :     buf[1] = (char)(0x80 | (cp & 0x3F));
    2995           43 :     n = 2;
    2996           53 :   } else if (cp <= 0xFFFF) {
    2997           47 :     buf[0] = (char)(0xE0 | (cp >> 12));
    2998           47 :     buf[1] = (char)(0x80 | ((cp >> 6) & 0x3F));
    2999           47 :     buf[2] = (char)(0x80 | (cp & 0x3F));
    3000           47 :     n = 3;
    3001              :   } else {
    3002            6 :     buf[0] = (char)(0xF0 | (cp >> 18));
    3003            6 :     buf[1] = (char)(0x80 | ((cp >> 12) & 0x3F));
    3004            6 :     buf[2] = (char)(0x80 | ((cp >> 6) & 0x3F));
    3005            6 :     buf[3] = (char)(0x80 | (cp & 0x3F));
    3006            6 :     n = 4;
    3007              :   }
    3008         9879 :   yb_append(b, buf, (size_t)n);
    3009         9879 : }
    3010              : 
    3011              : // Reads the 4 hex digits of a \u escape into a code point and moves past them;
    3012              : // false on short input or a non-hex digit.
    3013          145 : static bool parse_hex4(parse_ctx *ctx, uint32_t *out) {
    3014          145 :   if (ctx->pos + 4 > ctx->len) {
    3015            1 :     parse_err(ctx, "incomplete \\uXXXX at position %zu", ctx->pos);
    3016            1 :     return false;
    3017              :   }
    3018              :   uint32_t v = 0;
    3019          412 :   for (int i = 0; i < 4; i++) {
    3020          345 :     char c = ctx->src[ctx->pos + i];
    3021          345 :     uint32_t d;
    3022          345 :     if (c >= '0' && c <= '9')
    3023          128 :       d = (uint32_t)(c - '0');
    3024          217 :     else if (c >= 'a' && c <= 'f')
    3025           14 :       d = (uint32_t)(c - 'a' + 10);
    3026          203 :     else if (c >= 'A' && c <= 'F')
    3027          126 :       d = (uint32_t)(c - 'A' + 10);
    3028              :     else {
    3029           77 :       parse_err(ctx, "invalid hex digit '%s' in \\uXXXX at position %zu",
    3030           77 :                 cyaml_echo_c(c), ctx->pos + i);
    3031           77 :       return false;
    3032              :     }
    3033          268 :     v = (v << 4) | d;
    3034              :   }
    3035           67 :   ctx->pos += 4;
    3036           67 :   *out = v;
    3037           67 :   return true;
    3038              : }
    3039              : 
    3040              : // Reads the 8 hex digits of a \U escape into a code point, like parse_hex4().
    3041          109 : static bool parse_hex8(parse_ctx *ctx, uint32_t *out) {
    3042          109 :   if (ctx->pos + 8 > ctx->len) {
    3043            1 :     parse_err(ctx, "incomplete \\UXXXXXXXX at position %zu", ctx->pos);
    3044            1 :     return false;
    3045              :   }
    3046              :   uint32_t v = 0;
    3047          356 :   for (int i = 0; i < 8; i++) {
    3048          325 :     char c = ctx->src[ctx->pos + i];
    3049          325 :     uint32_t d;
    3050          325 :     if (c >= '0' && c <= '9')
    3051          213 :       d = (uint32_t)(c - '0');
    3052          112 :     else if (c >= 'a' && c <= 'f')
    3053            6 :       d = (uint32_t)(c - 'a' + 10);
    3054          106 :     else if (c >= 'A' && c <= 'F')
    3055           29 :       d = (uint32_t)(c - 'A' + 10);
    3056              :     else {
    3057           77 :       parse_err(ctx, "invalid hex digit '%s' in \\UXXXXXXXX at position %zu",
    3058           77 :                 cyaml_echo_c(c), ctx->pos + i);
    3059           77 :       return false;
    3060              :     }
    3061          248 :     v = (v << 4) | d;
    3062              :   }
    3063           31 :   ctx->pos += 8;
    3064           31 :   *out = v;
    3065           31 :   return true;
    3066              : }
    3067              : 
    3068              : // Folds a line break inside a quoted scalar, for both quoted styles. It strips
    3069              : // trailing inline whitespace of b down to strip_floor (the double-quoted style
    3070              : // passes the end of its last escape, since escaped whitespace is content), then
    3071              : // folds the break into a space, or into newlines for blank lines that follow. A
    3072              : // document marker in the fold is an unclosed quote: false with the error set,
    3073              : // and the caller frees b.
    3074          111 : static bool fold_quoted_newline(parse_ctx *ctx, ybuf *b, size_t strip_floor,
    3075              :                                 const char *style_name) {
    3076          111 :   yb_trim_trailing_inline_ws(b, strip_floor);
    3077          111 :   skip_newline(ctx);
    3078          111 :   if (at_doc_marker(ctx)) {
    3079            3 :     parse_err(ctx,
    3080              :               "document marker inside unterminated %s scalar at position %zu",
    3081              :               style_name, ctx->pos);
    3082            3 :     return false;
    3083              :   }
    3084          108 :   if (at_blank_line(ctx)) {
    3085           45 :     while (at_blank_line(ctx)) {
    3086              :       skip_inline_ws(ctx);
    3087           30 :       if (at_end(ctx)) break;
    3088           17 :       yb_append_c(b, '\n');
    3089           17 :       skip_newline(ctx);
    3090              :     }
    3091          255 :     if (at_doc_marker(ctx)) {
    3092            0 :       parse_err(ctx,
    3093              :                 "document marker inside unterminated %s scalar at position "
    3094              :                 "%zu",
    3095              :                 style_name, ctx->pos);
    3096            0 :       return false;
    3097              :     }
    3098              :   } else {
    3099           80 :     yb_append_c(b, ' ');
    3100              :   }
    3101              :   skip_inline_ws(ctx);
    3102              :   return true;
    3103              : }
    3104              : 
    3105              : // Parses a double-quoted scalar from its opening quote into a heap string in
    3106              : // *out, for values and keys. Escapes that decode to U+0000, a lone surrogate or
    3107              : // a value outside Unicode are refused, since a value can't hold a NUL. An
    3108              : // escaped line break adds nothing itself, and each blank line after it adds a
    3109              : // newline. false with ctx->error set on a malformed scalar.
    3110         4058 : static bool parse_double_quoted(parse_ctx *ctx, char **out) {
    3111         4058 :   if (at_end(ctx) || cur(ctx) != '"') {
    3112            0 :     parse_err(ctx, "expected '\"' at position %zu", ctx->pos);
    3113            0 :     return false;
    3114              :   }
    3115         4058 :   ctx->pos++;
    3116              : 
    3117         4058 :   ybuf b;
    3118         4058 :   yb_init(&b, ctx->mp);
    3119              : 
    3120         4058 :   size_t escape_boundary = 0;
    3121              : 
    3122      1166938 :   while (!at_end(ctx)) {
    3123      2330089 :     char c = cur(ctx);
    3124              : 
    3125      1166931 :     if (c == '"') {
    3126         3773 :       ctx->pos++;
    3127         3773 :       goto done;
    3128              :     }
    3129              : 
    3130      1163158 :     if (c == '\\') {
    3131        10616 :       ctx->pos++;
    3132        10616 :       if (at_end(ctx)) break;
    3133        10616 :       char esc = cur(ctx);
    3134        10616 :       ctx->pos++;
    3135        10616 :       switch (esc) {
    3136            2 :         case '0':
    3137            2 :           parse_err(ctx,
    3138              :                     "double-quoted scalar contains a null byte escape "
    3139              :                     "'\\0' at position %zu",
    3140              :                     ctx->pos - 2);
    3141          276 :           goto fail;
    3142              :         case 'a':
    3143            3 :           yb_append_c(&b, '\a');
    3144            3 :           break;
    3145              :         case 'b':
    3146            4 :           yb_append_c(&b, '\b');
    3147            4 :           break;
    3148              :         case 't':
    3149              :         case '\t':
    3150           34 :           yb_append_c(&b, '\t');
    3151           34 :           break;
    3152              :         case 'n':
    3153           18 :           yb_append_c(&b, '\n');
    3154           18 :           break;
    3155              :         case 'v':
    3156           13 :           yb_append_c(&b, '\v');
    3157           13 :           break;
    3158              :         case 'f':
    3159           11 :           yb_append_c(&b, '\f');
    3160           11 :           break;
    3161              :         case 'r':
    3162            7 :           yb_append_c(&b, '\r');
    3163            7 :           break;
    3164              :         case 'e':
    3165          304 :           yb_append_c(&b, 0x1B);
    3166          304 :           break;
    3167              :         case ' ':
    3168            3 :           yb_append_c(&b, ' ');
    3169            3 :           break;
    3170              :         case '"':
    3171            4 :           yb_append_c(&b, '"');
    3172            4 :           break;
    3173              :         case '/':
    3174            3 :           yb_append_c(&b, '/');
    3175            3 :           break;
    3176              :         case '\\':
    3177            4 :           yb_append_c(&b, '\\');
    3178            4 :           break;
    3179              :         case 'N':
    3180           13 :           yb_append(&b, "\xC2\x85", 2);
    3181           13 :           break;
    3182              :         case '_':
    3183            2 :           yb_append(&b, "\xC2\xA0", 2);
    3184            2 :           break;
    3185              :         case 'L':
    3186           18 :           yb_append(&b, "\xE2\x80\xA8", 3);
    3187           18 :           break;
    3188              :         case 'P':
    3189           10 :           yb_append(&b, "\xE2\x80\xA9", 3);
    3190           10 :           break;
    3191         9826 :         case 'x': {
    3192         9826 :           if (ctx->pos + 2 > ctx->len) {
    3193            0 :             parse_err(ctx, "incomplete \\xXX at position %zu", ctx->pos);
    3194            0 :             goto fail;
    3195              :           }
    3196              :           uint32_t v = 0;
    3197        29476 :           for (int i = 0; i < 2; i++) {
    3198        19651 :             char hc = ctx->src[ctx->pos + i];
    3199        19651 :             uint32_t d;
    3200        19651 :             if (hc >= '0' && hc <= '9')
    3201        19608 :               d = (uint32_t)(hc - '0');
    3202           43 :             else if (hc >= 'a' && hc <= 'f')
    3203           42 :               d = (uint32_t)(hc - 'a' + 10);
    3204            1 :             else if (hc >= 'A' && hc <= 'F')
    3205            0 :               d = (uint32_t)(hc - 'A' + 10);
    3206              :             else {
    3207            1 :               parse_err(ctx, "invalid hex digit in \\xXX at position %zu",
    3208              :                         ctx->pos + i);
    3209            1 :               goto fail;
    3210              :             }
    3211        19650 :             v = (v << 4) | d;
    3212              :           }
    3213         9825 :           ctx->pos += 2;
    3214         9825 :           if (v == 0) {
    3215            1 :             parse_err(ctx,
    3216              :                       "double-quoted scalar contains a null byte "
    3217              :                       "escape '\\x00' at position %zu",
    3218              :                       ctx->pos - 4);
    3219            1 :             goto fail;
    3220              :           }
    3221         9824 :           encode_utf8(&b, v);
    3222         9824 :           break;
    3223              :         }
    3224          139 :         case 'u': {
    3225          139 :           uint32_t cp;
    3226          139 :           size_t esc_pos = ctx->pos - 2;
    3227          149 :           if (!parse_hex4(ctx, &cp)) goto fail;
    3228           61 :           if (cp >= 0xD800 && cp <= 0xDBFF) {
    3229            9 :             uint32_t next = 0;
    3230            9 :             if (ctx->pos + 1 < ctx->len && ctx->src[ctx->pos] == '\\' &&
    3231            6 :                 ctx->src[ctx->pos + 1] == 'u') {
    3232            6 :               ctx->pos += 2;
    3233           12 :               if (!parse_hex4(ctx, &next)) goto fail;
    3234              :             }
    3235            9 :             if (next < 0xDC00 || next > 0xDFFF) {
    3236            6 :               parse_err(ctx,
    3237              :                         "\\u escape at position %zu names the high "
    3238              :                         "surrogate U+%04X without a low surrogate escape "
    3239              :                         "after it; a lone surrogate is not a Unicode "
    3240              :                         "character",
    3241              :                         esc_pos, (unsigned)cp);
    3242            6 :               goto fail;
    3243              :             }
    3244            3 :             cp = 0x10000u + ((cp - 0xD800u) << 10) + (next - 0xDC00u);
    3245           52 :           } else if (cp >= 0xDC00 && cp <= 0xDFFF) {
    3246            2 :             parse_err(ctx,
    3247              :                       "\\u escape at position %zu names the low surrogate "
    3248              :                       "U+%04X without a high surrogate before it; a lone "
    3249              :                       "surrogate is not a Unicode character",
    3250              :                       esc_pos, (unsigned)cp);
    3251            2 :             goto fail;
    3252              :           }
    3253           53 :           if (cp == 0) {
    3254            2 :             parse_err(ctx,
    3255              :                       "double-quoted scalar contains a null byte "
    3256              :                       "escape '\\u0000' at position %zu",
    3257              :                       esc_pos);
    3258            2 :             goto fail;
    3259              :           }
    3260           51 :           encode_utf8(&b, cp);
    3261           51 :           break;
    3262              :         }
    3263          109 :         case 'U': {
    3264          109 :           uint32_t cp;
    3265          109 :           size_t esc_pos = ctx->pos - 2;
    3266          136 :           if (!parse_hex8(ctx, &cp)) goto fail;
    3267           31 :           if (cp > 0x10FFFFu || (cp >= 0xD800u && cp <= 0xDFFFu)) {
    3268           25 :             parse_err(ctx,
    3269              :                       "\\U escape at position %zu names 0x%08X, which is "
    3270              :                       "not a Unicode scalar value (a surrogate, or above "
    3271              :                       "U+10FFFF)",
    3272              :                       esc_pos, (unsigned)cp);
    3273           25 :             goto fail;
    3274              :           }
    3275            6 :           if (cp == 0) {
    3276            2 :             parse_err(ctx,
    3277              :                       "double-quoted scalar contains a null byte "
    3278              :                       "escape '\\U00000000' at position %zu",
    3279              :                       esc_pos);
    3280            2 :             goto fail;
    3281              :           }
    3282            4 :           encode_utf8(&b, cp);
    3283            4 :           break;
    3284              :         }
    3285           10 :         case '\n':
    3286              :         case '\r': {
    3287           10 :           if (esc == '\r' && !at_end(ctx) && cur(ctx) == '\n') ctx->pos++;
    3288           13 :           while (at_blank_line(ctx)) {
    3289              :             skip_inline_ws(ctx);
    3290            3 :             if (at_end(ctx)) break;
    3291            3 :             yb_append_c(&b, '\n');
    3292            3 :             skip_newline(ctx);
    3293              :           }
    3294           28 :           if (at_doc_marker(ctx)) {
    3295            0 :             parse_err(ctx,
    3296              :                       "document marker inside unterminated double-quoted "
    3297              :                       "scalar at position %zu",
    3298              :                       ctx->pos);
    3299            0 :             goto fail;
    3300              :           }
    3301              :           skip_inline_ws(ctx);
    3302              :           break;
    3303              :         }
    3304           79 :         default:
    3305           79 :           parse_err(ctx, "unknown escape '\\%s' at position %zu",
    3306           79 :                     cyaml_echo_c(esc), ctx->pos - 1);
    3307           79 :           goto fail;
    3308              :       }
    3309        10340 :       escape_boundary = b.len;
    3310        10340 :       continue;
    3311              :     }
    3312              : 
    3313      1152542 :     if (c == '\r' || c == '\n') {
    3314           76 :       if (!fold_quoted_newline(ctx, &b, escape_boundary, "double-quoted"))
    3315            2 :         goto fail;
    3316           74 :       continue;
    3317              :     }
    3318              : 
    3319      1152466 :     yb_append_c(&b, c);
    3320      1152466 :     ctx->pos++;
    3321              :   }
    3322              : 
    3323            7 :   parse_err(ctx, "unterminated double-quoted scalar");
    3324            7 :   goto fail;
    3325              : 
    3326         3773 : done:
    3327         3773 :   if (b.oom) goto fail;
    3328         3772 :   *out = b.buf;
    3329         3772 :   return true;
    3330              : 
    3331          286 : fail:
    3332          286 :   ccol__mem_free(b.m_procs, b.buf);
    3333              :   return false;
    3334              : }
    3335              : 
    3336              : // Parses a single-quoted scalar ('' is a quote; line breaks fold as in the
    3337              : // double-quoted style) into a heap string in *out, for values and keys. false
    3338              : // with ctx->error set when unterminated.
    3339         1194 : static bool parse_single_quoted(parse_ctx *ctx, char **out) {
    3340         1194 :   if (at_end(ctx) || cur(ctx) != '\'') {
    3341            0 :     parse_err(ctx, "expected \"'\" at position %zu", ctx->pos);
    3342            0 :     return false;
    3343              :   }
    3344         1194 :   ctx->pos++;
    3345              : 
    3346         1194 :   ybuf b;
    3347         1194 :   yb_init(&b, ctx->mp);
    3348              : 
    3349         5986 :   while (!at_end(ctx)) {
    3350         8381 :     char c = cur(ctx);
    3351              : 
    3352         4786 :     if (c == '\'') {
    3353         1191 :       ctx->pos++;
    3354         1191 :       if (!at_end(ctx) && cur(ctx) == '\'') {
    3355            4 :         yb_append_c(&b, '\'');
    3356            4 :         ctx->pos++;
    3357            4 :         continue;
    3358              :       }
    3359         1187 :       goto done;
    3360              :     }
    3361              : 
    3362         3595 :     if (c == '\r' || c == '\n') {
    3363           35 :       if (!fold_quoted_newline(ctx, &b, 0, "single-quoted")) {
    3364            1 :         ccol__mem_free(b.m_procs, b.buf);
    3365            1 :         return false;
    3366              :       }
    3367           34 :       continue;
    3368              :     }
    3369              : 
    3370         3560 :     yb_append_c(&b, c);
    3371         3560 :     ctx->pos++;
    3372              :   }
    3373              : 
    3374            6 :   parse_err(ctx, "unterminated single-quoted scalar");
    3375            6 :   ccol__mem_free(b.m_procs, b.buf);
    3376              :   return false;
    3377              : 
    3378         1187 : done:
    3379         1187 :   if (b.oom) {
    3380            0 :     ccol__mem_free(b.m_procs, b.buf);
    3381            0 :     return false;
    3382              :   }
    3383         1187 :   *out = b.buf;
    3384         1187 :   return true;
    3385              : }
    3386              : 
    3387              : // The chomping of a block scalar: One final newline, none, or every trailing
    3388              : // line.
    3389              : typedef enum { CHOMP_CLIP, CHOMP_STRIP, CHOMP_KEEP } chomp_mode;
    3390              : 
    3391              : // Reads the header of a block scalar after | or >, for both block styles: At
    3392              : // most one chomp indicator and at most one indent digit (1 to 9), in either
    3393              : // order, then an optional comment that needs whitespace before its '#'. Sets
    3394              : // *chomp, and *explicit_indent (0 when no digit is given). false with
    3395              : // ctx->error set when malformed.
    3396          535 : static bool parse_block_scalar_header(parse_ctx *ctx, chomp_mode *chomp,
    3397              :                                       int *explicit_indent) {
    3398          535 :   *chomp = CHOMP_CLIP;
    3399          535 :   *explicit_indent = 0;
    3400              : 
    3401          535 :   bool had_chomp = false, had_indent = false;
    3402          998 :   for (int pass = 0; pass < 2; pass++) {
    3403          989 :     if (at_end(ctx) || at_eol(ctx)) break;
    3404              :     char c = cur(ctx);
    3405              :     if (c == '-' || c == '+') {
    3406          448 :       if (had_chomp) {
    3407            4 :         parse_err(ctx,
    3408              :                   "duplicate chomping indicator in block scalar header "
    3409              :                   "at position %zu",
    3410              :                   ctx->pos);
    3411            4 :         return false;
    3412              :       }
    3413          444 :       *chomp = (c == '-') ? CHOMP_STRIP : CHOMP_KEEP;
    3414          444 :       had_chomp = true;
    3415          444 :       ctx->pos++;
    3416              :     } else if (c >= '1' && c <= '9') {
    3417           20 :       if (had_indent) {
    3418            1 :         parse_err(ctx,
    3419              :                   "duplicate indentation indicator in block scalar header "
    3420              :                   "at position %zu",
    3421              :                   ctx->pos);
    3422            1 :         return false;
    3423              :       }
    3424           19 :       *explicit_indent = c - '0';
    3425           19 :       had_indent = true;
    3426           19 :       ctx->pos++;
    3427              :     } else
    3428              :       break;
    3429              :   }
    3430              : 
    3431              :   bool had_ws = false;
    3432          535 :   while (!at_end(ctx) && (cur(ctx) == ' ' || cur(ctx) == '\t')) {
    3433            5 :     ctx->pos++;
    3434            5 :     had_ws = true;
    3435              :   }
    3436          530 :   if (!at_end(ctx) && cur(ctx) == '#' && had_ws)
    3437            4 :     skip_to_eol(ctx);
    3438          526 :   else if (!at_end(ctx) && at_eol(ctx))
    3439          519 :     skip_newline(ctx);
    3440            7 :   else if (!at_end(ctx)) {
    3441            5 :     parse_err(ctx,
    3442              :               "unexpected character after block scalar header at position %zu",
    3443              :               ctx->pos);
    3444            5 :     return false;
    3445              :   }
    3446              :   return true;
    3447              : }
    3448              : 
    3449              : // What scan_block_scalar_line() found. ERROR: ctx->error is set. END: The
    3450              : // scalar ends before this line, and ctx->pos is back at its start. BLANK: An
    3451              : // empty line, ctx->pos at its end. CONTENT: A content line, *spaces_out holds
    3452              : // its leading spaces (at least block_indent) and ctx->pos sits after them.
    3453              : typedef enum {
    3454              :   SCAN_BLOCK_LINE_ERROR,
    3455              :   SCAN_BLOCK_LINE_END,
    3456              :   SCAN_BLOCK_LINE_BLANK,
    3457              :   SCAN_BLOCK_LINE_CONTENT
    3458              : } scan_block_line;
    3459              : 
    3460              : // Measures and classifies one line of a block scalar for both block styles,
    3461              : // updating indent_determined, block_indent and max_leading_blank_spaces. The
    3462              : // shared rules live here: A tab as indentation while the indent is unknown is
    3463              : // an error, no leading blank line may be indented past the first content line,
    3464              : // the indent is detected from the first content line, and a document marker in
    3465              : // column 0 always ends the scalar (its auto-detected indent may be 0). A line
    3466              : // more indented than block_indent is content even when it holds only spaces.
    3467         1072 : static scan_block_line scan_block_scalar_line(parse_ctx *ctx, int parent_indent,
    3468              :                                               bool *indent_determined,
    3469              :                                               int *block_indent,
    3470              :                                               int *max_leading_blank_spaces,
    3471              :                                               int *spaces_out) {
    3472         1072 :   size_t line_start = ctx->pos;
    3473         1072 :   size_t space_count = 0;
    3474         2305 :   while (!at_end(ctx) && cur(ctx) == ' ') {
    3475         1233 :     space_count++;
    3476         1233 :     ctx->pos++;
    3477              :   }
    3478         1072 :   int spaces = space_count > (size_t)INT_MAX ? INT_MAX : (int)space_count;
    3479              : 
    3480         1072 :   if (!*indent_determined && spaces == 0 && !at_end(ctx) && cur(ctx) == '\t') {
    3481            2 :     parse_err(ctx,
    3482              :               "tab cannot be used as block scalar indentation at "
    3483              :               "position %zu",
    3484              :               ctx->pos);
    3485            2 :     return SCAN_BLOCK_LINE_ERROR;
    3486              :   }
    3487              : 
    3488          564 :   if (spaces == 0 && at_doc_marker(ctx)) {
    3489            8 :     ctx->pos = line_start;
    3490            8 :     return SCAN_BLOCK_LINE_END;
    3491              :   }
    3492              : 
    3493         1062 :   bool is_blank =
    3494           70 :       at_eol(ctx) && (!*indent_determined || spaces <= *block_indent);
    3495              : 
    3496         1001 :   if (is_blank) {
    3497           61 :     if (!*indent_determined && spaces > *max_leading_blank_spaces)
    3498           28 :       *max_leading_blank_spaces = spaces;
    3499           61 :     return SCAN_BLOCK_LINE_BLANK;
    3500              :   }
    3501              : 
    3502         1001 :   if (!*indent_determined) {
    3503          494 :     if (spaces <= parent_indent) {
    3504            2 :       ctx->pos = line_start;
    3505            2 :       return SCAN_BLOCK_LINE_END;
    3506              :     }
    3507          492 :     if (*max_leading_blank_spaces > spaces) {
    3508            6 :       parse_err(ctx,
    3509              :                 "a leading empty line in a block scalar is more "
    3510              :                 "indented than the first non-empty line at position %zu",
    3511              :                 line_start);
    3512            6 :       return SCAN_BLOCK_LINE_ERROR;
    3513              :     }
    3514          486 :     *block_indent = spaces;
    3515          486 :     *indent_determined = true;
    3516          486 :     *spaces_out = spaces;
    3517          486 :     return SCAN_BLOCK_LINE_CONTENT;
    3518              :   }
    3519              : 
    3520          507 :   if (spaces < *block_indent) {
    3521          429 :     ctx->pos = line_start;
    3522          429 :     return SCAN_BLOCK_LINE_END;
    3523              :   }
    3524           78 :   *spaces_out = spaces;
    3525           78 :   return SCAN_BLOCK_LINE_CONTENT;
    3526              : }
    3527              : 
    3528              : // Reads the content of a literal block scalar into a heap string in *out (free
    3529              : // it with ctx->mp). parent_indent (-1 at the root) is the base of an explicit
    3530              : // indent. Trailing lines and the newline of the last content line wait in a
    3531              : // buffer until more content arrives or the scalar ends, so the chomp mode can
    3532              : // decide about them; CLIP and KEEP never add a newline the input didn't have.
    3533          279 : static bool parse_block_scalar_content(parse_ctx *ctx, int parent_indent,
    3534              :                                        chomp_mode chomp, int explicit_indent,
    3535              :                                        char **out) {
    3536          279 :   int block_indent = 0;
    3537          279 :   bool indent_determined = (explicit_indent > 0);
    3538          279 :   if (indent_determined) {
    3539            9 :     int effective_parent = parent_indent < 0 ? 0 : parent_indent;
    3540            9 :     block_indent = effective_parent + explicit_indent;
    3541              :   }
    3542              : 
    3543          279 :   ybuf b;
    3544          279 :   yb_init(&b, ctx->mp);
    3545              : 
    3546          279 :   ybuf pending;
    3547          279 :   yb_init(&pending, ctx->mp);
    3548          279 :   bool have_content = false;
    3549              : 
    3550          279 :   bool had_trailing_newline = false;
    3551              : 
    3552          279 :   bool content_had_trailing_newline = false;
    3553              : 
    3554          279 :   int max_leading_blank_spaces = -1;
    3555              : 
    3556          612 :   while (!at_end(ctx)) {
    3557          566 :     size_t line_start = ctx->pos;
    3558          566 :     int spaces = 0;
    3559          566 :     scan_block_line kind = scan_block_scalar_line(
    3560              :         ctx, parent_indent, &indent_determined, &block_indent,
    3561              :         &max_leading_blank_spaces, &spaces);
    3562              : 
    3563          566 :     if (kind == SCAN_BLOCK_LINE_ERROR) {
    3564            4 :       ccol__mem_free(b.m_procs, b.buf);
    3565            4 :       ccol__mem_free(pending.m_procs, pending.buf);
    3566            4 :       return false;
    3567              :     }
    3568          562 :     if (kind == SCAN_BLOCK_LINE_END) break;
    3569              : 
    3570          333 :     if (kind == SCAN_BLOCK_LINE_BLANK) {
    3571           36 :       had_trailing_newline = !at_end(ctx);
    3572           36 :       if (had_trailing_newline) yb_append_c(&pending, '\n');
    3573           36 :       ctx->pos = line_start;
    3574           36 :       skip_to_eol(ctx);
    3575           36 :       continue;
    3576              :     }
    3577              : 
    3578          297 :     yb_append_buf(&b, &pending);
    3579          297 :     pending.len = 0;
    3580          297 :     have_content = true;
    3581              : 
    3582          297 :     int extra = spaces - block_indent;
    3583              : 
    3584          312 :     for (int i = 0; i < extra; i++) yb_append_c(&b, ' ');
    3585              : 
    3586         2590 :     while (!at_end(ctx) && !at_eol(ctx)) {
    3587         1000 :       yb_append_c(&b, cur(ctx));
    3588         1000 :       ctx->pos++;
    3589              :     }
    3590              : 
    3591          297 :     had_trailing_newline = !at_end(ctx);
    3592          297 :     content_had_trailing_newline = had_trailing_newline;
    3593          297 :     if (had_trailing_newline) yb_append_c(&pending, '\n');
    3594          297 :     skip_newline(ctx);
    3595              :   }
    3596              : 
    3597          275 :   switch (chomp) {
    3598              :     case CHOMP_STRIP:
    3599              :       break;
    3600           45 :     case CHOMP_CLIP:
    3601           45 :       if (have_content && content_had_trailing_newline) yb_append_c(&b, '\n');
    3602              :       break;
    3603              :     case CHOMP_KEEP:
    3604           17 :       yb_append_buf(&b, &pending);
    3605              :       break;
    3606              :   }
    3607              : 
    3608          275 :   bool pending_oom = pending.oom;
    3609          275 :   ccol__mem_free(pending.m_procs, pending.buf);
    3610              : 
    3611          275 :   if (b.oom || pending_oom) {
    3612            0 :     ccol__mem_free(b.m_procs, b.buf);
    3613            0 :     return false;
    3614              :   }
    3615          275 :   *out = b.buf;
    3616          275 :   return true;
    3617              : }
    3618              : 
    3619              : // Reads the content of a folded block scalar: It collects the lines as spans
    3620              : // borrowed from ctx->src (no copy per line), then folds them. A single break
    3621              : // between two lines becomes a space, a blank line a newline, and a break next
    3622              : // to a more indented line (spaces or a tab past block_indent) stays a newline,
    3623              : // plus one more when entering or leaving such a run. Chomping works as in
    3624              : // parse_block_scalar_content().
    3625          246 : static bool parse_folded_scalar_content(parse_ctx *ctx, int parent_indent,
    3626              :                                         chomp_mode chomp, int explicit_indent,
    3627              :                                         char **out) {
    3628          246 :   int block_indent = 0;
    3629          246 :   bool indent_determined = (explicit_indent > 0);
    3630          246 :   if (indent_determined) {
    3631            8 :     int effective_parent = parent_indent < 0 ? 0 : parent_indent;
    3632            8 :     block_indent = effective_parent + explicit_indent;
    3633              :   }
    3634              : 
    3635          246 :   typedef struct {
    3636              :     const char *text;
    3637              :     size_t text_len;
    3638              :     int extra;
    3639              :     bool blank;
    3640              :     bool spaced;
    3641              :   } block_line;
    3642              : 
    3643          246 :   size_t lines_cap = 16, lines_len = 0;
    3644          246 :   block_line *lines = ccol__mem_alloc(ctx->mp, lines_cap * sizeof(block_line));
    3645          246 :   if (!lines) return false;
    3646              : 
    3647          246 :   int max_leading_blank_spaces = -1;
    3648              : 
    3649          246 :   bool had_trailing_newline = false;
    3650              : 
    3651          538 :   while (!at_end(ctx)) {
    3652          506 :     size_t line_start = ctx->pos;
    3653          506 :     int spaces = 0;
    3654          506 :     scan_block_line kind = scan_block_scalar_line(
    3655              :         ctx, parent_indent, &indent_determined, &block_indent,
    3656              :         &max_leading_blank_spaces, &spaces);
    3657              : 
    3658          506 :     if (kind == SCAN_BLOCK_LINE_ERROR) {
    3659            4 :       ccol__mem_free(ctx->mp, lines);
    3660            4 :       return false;
    3661              :     }
    3662          502 :     if (kind == SCAN_BLOCK_LINE_END) break;
    3663              : 
    3664          292 :     bool is_blank = (kind == SCAN_BLOCK_LINE_BLANK);
    3665              : 
    3666          292 :     if (lines_len == lines_cap) {
    3667            0 :       lines_cap *= 2;
    3668            0 :       block_line *tmp =
    3669            0 :           ccol__mem_realloc(ctx->mp, lines, lines_cap * sizeof(block_line));
    3670            0 :       if (!tmp) {
    3671            0 :         ccol__mem_free(ctx->mp, lines);
    3672            0 :         return false;
    3673              :       }
    3674              :       lines = tmp;
    3675              :     }
    3676              : 
    3677          292 :     block_line *ln = &lines[lines_len++];
    3678          292 :     ln->blank = is_blank;
    3679          292 :     ln->extra = is_blank ? 0 : spaces - block_indent;
    3680          584 :     ln->spaced =
    3681          292 :         !is_blank && (ln->extra > 0 || (!at_end(ctx) && cur(ctx) == '\t'));
    3682          292 :     ln->text = NULL;
    3683          292 :     ln->text_len = 0;
    3684              : 
    3685          292 :     if (!is_blank) {
    3686          267 :       const char *span_start = ctx->src + (ctx->pos - (size_t)ln->extra);
    3687         1160 :       while (!at_end(ctx) && !at_eol(ctx)) ctx->pos++;
    3688          267 :       ln->text = span_start;
    3689          267 :       ln->text_len = (size_t)((ctx->src + ctx->pos) - span_start);
    3690              :     }
    3691          292 :     had_trailing_newline = !at_end(ctx);
    3692          292 :     ctx->pos = line_start;
    3693          292 :     skip_to_eol(ctx);
    3694              :   }
    3695              : 
    3696          242 :   ybuf b;
    3697          242 :   yb_init(&b, ctx->mp);
    3698              : 
    3699          242 :   size_t trailing_blanks = 0;
    3700          242 :   bool have_content = false;
    3701          242 :   bool prev_extra = false;
    3702              : 
    3703          522 :   for (size_t i = 0; i < lines_len; i++) {
    3704          280 :     block_line *ln = &lines[i];
    3705          280 :     if (ln->blank) {
    3706           13 :       trailing_blanks++;
    3707           13 :       continue;
    3708              :     }
    3709              : 
    3710          267 :     if (trailing_blanks > 0) {
    3711           16 :       for (size_t j = i - trailing_blanks; j < i; j++) {
    3712            9 :         for (int k = 0; k < lines[j].extra; k++) yb_append_c(&b, ' ');
    3713            9 :         yb_append_c(&b, '\n');
    3714              :       }
    3715            7 :       if (have_content && (ln->spaced || prev_extra)) yb_append_c(&b, '\n');
    3716          260 :     } else if (have_content) {
    3717           27 :       if (ln->spaced || prev_extra)
    3718           12 :         yb_append_c(&b, '\n');
    3719              :       else
    3720           15 :         yb_append_c(&b, ' ');
    3721              :     }
    3722          267 :     trailing_blanks = 0;
    3723          267 :     prev_extra = ln->spaced;
    3724          267 :     yb_append(&b, ln->text, ln->text_len);
    3725          267 :     have_content = true;
    3726              :   }
    3727              : 
    3728          242 :   switch (chomp) {
    3729              :     case CHOMP_STRIP:
    3730              :       break;
    3731           32 :     case CHOMP_CLIP:
    3732           32 :       if (have_content && (trailing_blanks > 0 || had_trailing_newline))
    3733           29 :         yb_append_c(&b, '\n');
    3734              :       break;
    3735            5 :     case CHOMP_KEEP:
    3736            5 :       if (have_content && (trailing_blanks > 0 || had_trailing_newline))
    3737            3 :         yb_append_c(&b, '\n');
    3738            7 :       for (size_t j = lines_len - trailing_blanks; j < lines_len; j++) {
    3739            2 :         for (int k = 0; k < lines[j].extra; k++) yb_append_c(&b, ' ');
    3740            2 :         if (j + 1 < lines_len || had_trailing_newline) yb_append_c(&b, '\n');
    3741              :       }
    3742              :       break;
    3743              :   }
    3744              : 
    3745          242 :   ccol__mem_free(ctx->mp, lines);
    3746              : 
    3747          242 :   if (b.oom) {
    3748            0 :     ccol__mem_free(b.m_procs, b.buf);
    3749            0 :     return false;
    3750              :   }
    3751          242 :   *out = b.buf;
    3752          242 :   return true;
    3753              : }
    3754              : 
    3755              : // Appends the plain-scalar text of the current line to *b, shared by the first
    3756              : // line and every continuation line so both end the same way. true, with
    3757              : // ctx->pos at the stopper, when a real terminator ends the token (" #", ": ", a
    3758              : // ':' at the end, or in flow a ':' before a flow indicator, or any flow
    3759              : // indicator); false at the end of the line or the input. line_start lets a '#'
    3760              : // in the first position stay content.
    3761       225710 : CYAML_PARSE_HOT bool scan_plain_scalar_line(parse_ctx *ctx, bool in_flow,
    3762              :                                             size_t line_start, ybuf *b) {
    3763      1608787 :   while (!at_end(ctx)) {
    3764      1608682 :     char c = cur(ctx);
    3765              : 
    3766      1608682 :     if (c == '\n' || c == '\r') return false;
    3767              : 
    3768      1602006 :     if (c == '#' && ctx->pos > line_start) {
    3769           33 :       char prev = ctx->src[ctx->pos - 1];
    3770           33 :       if (prev == ' ' || prev == '\t') return true;
    3771              :     }
    3772              : 
    3773      1601984 :     if (c == ':') {
    3774        48368 :       if (ctx->pos + 1 >= ctx->len) return true;
    3775        48367 :       char next = ctx->src[ctx->pos + 1];
    3776        48367 :       if (next == ' ' || next == '\t' || next == '\n' || next == '\r')
    3777              :         return true;
    3778        20047 :       if (in_flow) {
    3779        20018 :         char safe = ctx->src[ctx->pos + 1];
    3780        20018 :         if (safe == ',' || safe == ']' || safe == '}' || safe == '[' ||
    3781              :             safe == '{')
    3782              :           return true;
    3783              :       }
    3784              :     }
    3785              : 
    3786      1544724 :     if (in_flow && (c == ',' || c == ']' || c == '}' || c == '[' || c == '{'))
    3787              :       return true;
    3788              : 
    3789      1383076 :     yb_append_c(b, c);
    3790      1383077 :     ctx->pos++;
    3791              :   }
    3792              :   return false;
    3793              : }
    3794              : 
    3795              : // Parses a plain scalar on one line, trailing spaces trimmed. A ':' not
    3796              : // followed by whitespace (or, in flow, by an indicator) is content, as in a
    3797              : // URL. *hit_real_terminator (when not NULL) tells whether a terminator ended
    3798              : // it; only then is no continuation tried. An implicit key never continues.
    3799       225394 : CYAML_PARSE_HOT bool parse_plain_scalar(parse_ctx *ctx, bool in_flow,
    3800              :                                         char **out, bool *hit_real_terminator) {
    3801       225394 :   ybuf b;
    3802       450787 :   yb_init(&b, ctx->mp);
    3803              : 
    3804       225393 :   size_t start = ctx->pos;
    3805       225393 :   bool terminated = scan_plain_scalar_line(ctx, in_flow, start, &b);
    3806       225394 :   if (hit_real_terminator) *hit_real_terminator = terminated;
    3807              : 
    3808       225394 :   yb_trim_trailing_inline_ws(&b, 0);
    3809              : 
    3810       225394 :   if (b.oom) {
    3811          117 :     ccol__mem_free(b.m_procs, b.buf);
    3812              :     return false;
    3813              :   }
    3814       225277 :   *out = b.buf;
    3815       225277 :   return true;
    3816              : }
    3817              : 
    3818              : // Extends the first line of a plain scalar (first_owned, owned from here on)
    3819              : // with continuation lines: Blank lines and lines indented past indent. Each
    3820              : // line step folds to one space and each blank line to a newline. It stops at a
    3821              : // document marker, a line at or below indent, a flow indicator, a comment line,
    3822              : // a ':' at the start of a line (an implicit key's ':' must stay on the key's
    3823              : // line), and a line that hits a terminator. The text accumulates in one buffer,
    3824              : // with a per-line floor for the trailing-space trim.
    3825       211340 : static bool parse_plain_scalar_multiline(parse_ctx *ctx, bool in_flow,
    3826              :                                          int indent, char *first_owned,
    3827              :                                          bool first_terminated, char **out) {
    3828       211340 :   if (first_terminated || at_end(ctx)) {
    3829       205089 :     *out = first_owned;
    3830       205089 :     return true;
    3831              :   }
    3832              : 
    3833         6251 :   ybuf b;
    3834         6251 :   yb_init(&b, ctx->mp);
    3835         6251 :   yb_append_cstr(&b, first_owned);
    3836         6251 :   ccol__mem_free(ctx->mp, first_owned);
    3837              : 
    3838              :   size_t blank_count = 0;
    3839         6452 :   while (!at_end(ctx)) {
    3840         6452 :     size_t save = ctx->pos;
    3841         6452 :     skip_newline(ctx);
    3842              : 
    3843         6452 :     size_t line_start = ctx->pos;
    3844         6452 :     size_t line_space_count = 0;
    3845         7908 :     while (!at_end(ctx) && cur(ctx) == ' ') {
    3846         1456 :       line_space_count++;
    3847         1456 :       ctx->pos++;
    3848              :     }
    3849         6452 :     int spaces =
    3850         6452 :         line_space_count > (size_t)INT_MAX ? INT_MAX : (int)line_space_count;
    3851              : 
    3852         6452 :     if (at_end(ctx)) {
    3853         2471 :       ctx->pos = save;
    3854         2471 :       break;
    3855              :     }
    3856         3981 :     if (at_blank_line(ctx)) {
    3857           19 :       while (!at_end(ctx) && cur(ctx) != '\n' && cur(ctx) != '\r') ctx->pos++;
    3858           16 :       blank_count++;
    3859           16 :       continue;
    3860              :     }
    3861         3965 :     if (at_doc_marker(ctx)) {
    3862           59 :       ctx->pos = save;
    3863           59 :       break;
    3864              :     }
    3865         3906 :     if (spaces <= indent) {
    3866         3563 :       ctx->pos = save;
    3867         3563 :       break;
    3868              :     }
    3869          345 :     while (!at_end(ctx) && (cur(ctx) == ' ' || cur(ctx) == '\t')) ctx->pos++;
    3870          485 :     if (in_flow && (cur(ctx) == ']' || cur(ctx) == '}' || cur(ctx) == ',' ||
    3871          125 :                     cur(ctx) == '[' || cur(ctx) == '{')) {
    3872           19 :       ctx->pos = save;
    3873           19 :       break;
    3874              :     }
    3875          324 :     if (cur(ctx) == ':') {
    3876            6 :       char after = (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    3877            6 :       bool is_value_indicator =
    3878            6 :           after == ' ' || after == '\t' || after == '\n' || after == '\r' ||
    3879            0 :           ctx->pos + 1 >= ctx->len ||
    3880            0 :           (in_flow && (after == ',' || after == ']' || after == '}'));
    3881              :       if (is_value_indicator) {
    3882            6 :         ctx->pos = save;
    3883            6 :         break;
    3884              :       }
    3885              :     }
    3886          318 :     if (cur(ctx) == '#') {
    3887            1 :       ctx->pos = save;
    3888            1 :       break;
    3889              :     }
    3890              : 
    3891          317 :     if (blank_count > 0) {
    3892            6 :       for (size_t i = 0; i < blank_count; i++) yb_append_c(&b, '\n');
    3893              :     } else {
    3894          314 :       yb_append_c(&b, ' ');
    3895              :     }
    3896          317 :     blank_count = 0;
    3897              : 
    3898          317 :     size_t line_floor = b.len;
    3899          317 :     bool cont_terminated = scan_plain_scalar_line(ctx, in_flow, line_start, &b);
    3900          317 :     yb_trim_trailing_inline_ws(&b, line_floor);
    3901              : 
    3902          317 :     if (cont_terminated) break;
    3903              :   }
    3904              : 
    3905         6251 :   if (b.oom) {
    3906           24 :     ccol__mem_free(b.m_procs, b.buf);
    3907           24 :     return false;
    3908              :   }
    3909         6227 :   *out = b.buf;
    3910         6227 :   return true;
    3911              : }
    3912              : 
    3913              : static char *node_to_dict_key_string(parse_ctx *ctx, cyaml_node *key_node,
    3914              :                                      const char *context_label);
    3915              : static char *node_to_dict_key_string_ex(parse_ctx *ctx, cyaml_node *key_node,
    3916              :                                         const char *context_label,
    3917              :                                         bool consume);
    3918              : 
    3919              : static char *serialize_flow_canonical(cyaml_node *n, bool *too_long);
    3920              : 
    3921              : static cyaml_node *parse_flow_list(parse_ctx *ctx, int indent);
    3922              : static cyaml_node *parse_flow_dictionary(parse_ctx *ctx, int indent);
    3923              : 
    3924              : // Tells whether the current position (after the leading whitespace of a line)
    3925              : // continues the value of a block construct at indent: true when it's indented
    3926              : // further. seq_ok_at_indent also allows exactly indent for a "- " entry, the
    3927              : // one exception YAML 1.2 gives the value of a mapping key; pass it only for a
    3928              : // mapping's indent. Spaces after a tab don't count.
    3929        13291 : static bool at_block_value_col(parse_ctx *ctx, int indent,
    3930              :                                bool seq_ok_at_indent) {
    3931        13291 :   int col = line_space_indent(ctx);
    3932        13291 :   if (col > indent) return true;
    3933          143 :   if (col < indent) return false;
    3934          266 :   if (seq_ok_at_indent && cur(ctx) == '-') {
    3935           14 :     char nx = (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    3936           14 :     if (nx == ' ' || nx == '\t' || nx == '\n' || nx == '\r' || nx == '\0')
    3937           13 :       return true;
    3938              :   }
    3939              :   return false;
    3940              : }
    3941              : 
    3942              : // True at a '-' followed by whitespace or the end, so the parser can tell a
    3943              : // block sequence entry from text such as "-1".
    3944         8332 : static bool at_bare_seq_indicator(parse_ctx *ctx) {
    3945         8332 :   if (at_end(ctx) || cur(ctx) != '-') return false;
    3946           13 :   char nx = (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    3947           22 :   return nx == ' ' || nx == '\t' || nx == '\n' || nx == '\r' || nx == '\0';
    3948              : }
    3949              : 
    3950              : // True when the current character may start a flow plain scalar, so a lone "-"
    3951              : // or "?" in flow is refused: Anything but a '-' or '?' that isn't followed by a
    3952              : // character a flow plain scalar may hold. ':' is left out on purpose, so "[:
    3953              : // value]" can still read an empty key.
    3954       205214 : static bool at_valid_flow_plain_scalar_start(parse_ctx *ctx) {
    3955       205214 :   char c = cur(ctx);
    3956       205214 :   if (c != '-' && c != '?') return true;
    3957           18 :   if (ctx->pos + 1 >= ctx->len) return false;
    3958           18 :   char next = ctx->src[ctx->pos + 1];
    3959           18 :   return next != ' ' && next != '\t' && next != '\n' && next != '\r' &&
    3960           43 :          next != ',' && next != '[' && next != ']' && next != '{' &&
    3961              :          next != '}';
    3962              : }
    3963              : 
    3964              : // Skips a tag token at a '!' the caller has seen, for look-aheads that only
    3965              : // need to get past it: A shorthand ends at whitespace or a flow indicator, and
    3966              : // a verbatim "!<...>" runs to its '>', commas included.
    3967         9003 : static void skip_tag_token(parse_ctx *ctx) {
    3968         9003 :   ctx->pos++;
    3969         9003 :   if (!at_end(ctx) && cur(ctx) == '<') {
    3970         2506 :     ctx->pos++;
    3971         7642 :     while (!at_end(ctx) && cur(ctx) != '>' && cur(ctx) != '\n' &&
    3972         5136 :            cur(ctx) != '\r')
    3973         5136 :       ctx->pos++;
    3974         2506 :     if (!at_end(ctx) && cur(ctx) == '>') ctx->pos++;
    3975         2506 :     return;
    3976              :   }
    3977         6497 :   if (!at_end(ctx) && cur(ctx) == '!') ctx->pos++;
    3978        18986 :   while (!at_end(ctx) && cur(ctx) != ' ' && cur(ctx) != '\t' &&
    3979        12493 :          cur(ctx) != '\n' && cur(ctx) != '\r' && cur(ctx) != ',' &&
    3980        31478 :          cur(ctx) != '[' && cur(ctx) != ']' && cur(ctx) != '{' &&
    3981        12489 :          cur(ctx) != '}')
    3982        12489 :     ctx->pos++;
    3983              : }
    3984              : 
    3985              : // True when c may appear unescaped in tag text, so the parser can refuse what
    3986              : // YAML forbids: ns-uri-char (letters, digits and "-#;/?:@&=+$,_.!~*'()[]%") for
    3987              : // verbatim content and %TAG prefixes, and with tag_char set the ns-tag-char
    3988              : // subset (no '!', ',', '[' or ']') for a shorthand suffix. Anything else needs
    3989              : // a percent escape.
    3990        70152 : static inline bool tag_text_char_ok(unsigned char c, bool tag_char) {
    3991        70152 :   if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
    3992        29832 :       (c >= '0' && c <= '9'))
    3993              :     return true;
    3994        21130 :   switch (c) {
    3995              :     case '-':
    3996              :     case '%':
    3997              :     case '#':
    3998              :     case ';':
    3999              :     case '/':
    4000              :     case '?':
    4001              :     case ':':
    4002              :     case '@':
    4003              :     case '&':
    4004              :     case '=':
    4005              :     case '+':
    4006              :     case '$':
    4007              :     case '_':
    4008              :     case '.':
    4009              :     case '~':
    4010              :     case '*':
    4011              :     case '\'':
    4012              :     case '(':
    4013              :     case ')':
    4014              :       return true;
    4015        12349 :     case '!':
    4016              :     case ',':
    4017              :     case '[':
    4018              :     case ']':
    4019        12349 :       return !tag_char;
    4020              :     default:
    4021              :       return false;
    4022              :   }
    4023              : }
    4024              : 
    4025              : // Checks tag text for parse_tag_token_raw() and the %TAG parser: Refuses, as a
    4026              : // parse error naming it, the first byte that tag_text_char_ok() refuses (start
    4027              : // is text's offset in the input). true when every byte is allowed.
    4028        21995 : static bool tag_text_check(parse_ctx *ctx, const char *text, size_t len,
    4029              :                            size_t start, bool tag_char) {
    4030        92110 :   for (size_t i = 0; i < len; i++) {
    4031        70152 :     if (!tag_text_char_ok((unsigned char)text[i], tag_char)) {
    4032           37 :       parse_err(ctx,
    4033              :                 "character '%s' at position %zu is not allowed in a tag; "
    4034              :                 "write it as a percent escape",
    4035           37 :                 cyaml_echo_c(text[i]), start + i);
    4036           37 :       return false;
    4037              :     }
    4038              :   }
    4039              :   return true;
    4040              : }
    4041              : 
    4042              : // Decodes the %XX escapes of tag text in place, for verbatim tags, shorthand
    4043              : // suffixes and %TAG prefixes alike. A malformed escape, %00 (a tag can't hold a
    4044              : // NUL) and escapes that decode to ill-formed UTF-8 are parse errors.
    4045        21891 : static bool percent_decode_tag_inplace(parse_ctx *ctx, char *text,
    4046              :                                        size_t pos_for_err) {
    4047        21891 :   char *w = text;
    4048        21891 :   bool decoded_non_ascii = false;
    4049        75137 :   for (const char *r = text; *r; r++) {
    4050        53253 :     if (*r != '%') {
    4051        44894 :       *w++ = *r;
    4052        44894 :       continue;
    4053              :     }
    4054         8359 :     char h1 = r[1];
    4055         8359 :     char h2 = h1 ? r[2] : '\0';
    4056         8359 :     int hi = -1, lo = -1;
    4057         8359 :     if (h1 >= '0' && h1 <= '9')
    4058         8322 :       hi = h1 - '0';
    4059           37 :     else if (h1 >= 'a' && h1 <= 'f')
    4060            0 :       hi = h1 - 'a' + 10;
    4061           37 :     else if (h1 >= 'A' && h1 <= 'F')
    4062           34 :       hi = h1 - 'A' + 10;
    4063         8359 :     if (h2 >= '0' && h2 <= '9')
    4064           89 :       lo = h2 - '0';
    4065         8270 :     else if (h2 >= 'a' && h2 <= 'f')
    4066            0 :       lo = h2 - 'a' + 10;
    4067         8270 :     else if (h2 >= 'A' && h2 <= 'F')
    4068         8267 :       lo = h2 - 'A' + 10;
    4069         8359 :     if (hi < 0 || lo < 0) {
    4070            3 :       parse_err(ctx, "malformed percent-escape in tag at position %zu",
    4071              :                 pos_for_err);
    4072            3 :       return false;
    4073              :     }
    4074         8356 :     int byte = (hi << 4) | lo;
    4075         8356 :     if (byte == 0) {
    4076            4 :       parse_err(ctx, "tag contains a percent-escaped null byte at position %zu",
    4077              :                 pos_for_err);
    4078            4 :       return false;
    4079              :     }
    4080         8352 :     if (byte >= 0x80) decoded_non_ascii = true;
    4081         8352 :     *w++ = (char)byte;
    4082         8352 :     r += 2;
    4083              :   }
    4084        21884 :   *w = '\0';
    4085        21884 :   if (decoded_non_ascii && !ccol_utf8_is_valid(text, (size_t)(w - text))) {
    4086            5 :     parse_err(ctx,
    4087              :               "tag percent-escapes at position %zu decode to bytes that are "
    4088              :               "not well-formed UTF-8",
    4089              :               pos_for_err);
    4090            5 :     return false;
    4091              :   }
    4092              :   return true;
    4093              : }
    4094              : 
    4095              : // Parses and resolves a tag token at a '!': Verbatim "!<...>", or a shorthand
    4096              : // with the "!", "!!" or "!name!" handle (a named handle is confirmed by a look
    4097              : // ahead for its closing '!'). *resolved_out gets the owned resolved tag, or
    4098              : // NULL for a bare "!". Every failure (bad character, handle with no suffix,
    4099              : // undefined handle, bad escape, OOM) sets ctx->error, which the speculative key
    4100              : // parse relies on. A stored tag is never empty.
    4101        21914 : static bool parse_tag_token_raw(parse_ctx *ctx, char **resolved_out) {
    4102        21914 :   size_t tag_start = ctx->pos;
    4103        21914 :   ctx->pos++;
    4104              : 
    4105        21914 :   if (!at_end(ctx) && cur(ctx) == '<') {
    4106        12473 :     ctx->pos++;
    4107        12473 :     size_t content_start = ctx->pos;
    4108        63850 :     while (!at_end(ctx) && cur(ctx) != '>' && cur(ctx) != '\n' &&
    4109        51377 :            cur(ctx) != '\r') {
    4110        51377 :       ctx->pos++;
    4111              :     }
    4112        12473 :     size_t content_len = ctx->pos - content_start;
    4113        12473 :     if (at_end(ctx) || cur(ctx) != '>') {
    4114            0 :       parse_err(ctx, "unterminated verbatim tag at position %zu", tag_start);
    4115            0 :       return false;
    4116              :     }
    4117        12473 :     ctx->pos++;
    4118        12473 :     if (content_len == 0) {
    4119            0 :       parse_err(ctx, "empty verbatim tag at position %zu", tag_start);
    4120            0 :       return false;
    4121              :     }
    4122        12473 :     if (!tag_text_check(ctx, ctx->src + content_start, content_len,
    4123              :                         content_start, false))
    4124              :       return false;
    4125        12467 :     char *content = ccol__mem_alloc(ctx->mp, content_len + 1);
    4126        12467 :     if (!content) {
    4127            0 :       parse_err(ctx, "out of memory parsing verbatim tag at position %zu",
    4128              :                 tag_start);
    4129            0 :       return false;
    4130              :     }
    4131        12467 :     memcpy(content, ctx->src + content_start, content_len);
    4132        12467 :     content[content_len] = '\0';
    4133        12467 :     if (!percent_decode_tag_inplace(ctx, content, content_start)) {
    4134            6 :       ccol__mem_free(ctx->mp, content);
    4135            6 :       return false;
    4136              :     }
    4137        12461 :     if (content[0] == '\0') {
    4138            0 :       parse_err(ctx, "empty verbatim tag at position %zu", tag_start);
    4139            0 :       ccol__mem_free(ctx->mp, content);
    4140            0 :       return false;
    4141              :     }
    4142        12461 :     *resolved_out = content;
    4143        12461 :     return true;
    4144              :   }
    4145              : 
    4146         9441 :   size_t handle_len = 1;
    4147         9441 :   if (!at_end(ctx) && cur(ctx) == '!') {
    4148         3684 :     handle_len = 2;
    4149         3684 :     ctx->pos++;
    4150              :   } else {
    4151        11771 :     size_t scan = ctx->pos;
    4152        11771 :     while (scan < ctx->len) {
    4153        11771 :       char sc = ctx->src[scan];
    4154        29310 :       bool is_word = (sc >= 'a' && sc <= 'z') || (sc >= 'A' && sc <= 'Z') ||
    4155        11771 :                      (sc >= '0' && sc <= '9') || sc == '-';
    4156        11771 :       if (!is_word) break;
    4157         6014 :       scan++;
    4158              :     }
    4159         5757 :     if (scan > ctx->pos && scan < ctx->len && ctx->src[scan] == '!') {
    4160          113 :       handle_len = (scan - tag_start) + 1;
    4161          113 :       ctx->pos = scan + 1;
    4162              :     }
    4163              :   }
    4164              : 
    4165         9441 :   char *handle = ccol__mem_alloc(ctx->mp, handle_len + 1);
    4166         9441 :   if (!handle) {
    4167            0 :     parse_err(ctx, "out of memory parsing tag handle at position %zu",
    4168              :               tag_start);
    4169            0 :     return false;
    4170              :   }
    4171         9441 :   memcpy(handle, ctx->src + tag_start, handle_len);
    4172         9441 :   handle[handle_len] = '\0';
    4173              : 
    4174         9441 :   size_t suffix_start = ctx->pos;
    4175        36598 :   while (!at_end(ctx) && cur(ctx) != ' ' && cur(ctx) != '\t' &&
    4176        17801 :          cur(ctx) != '\n' && cur(ctx) != '\r' && cur(ctx) != ',' &&
    4177        44884 :          cur(ctx) != '[' && cur(ctx) != ']' && cur(ctx) != '{' &&
    4178        17718 :          cur(ctx) != '}') {
    4179        17716 :     ctx->pos++;
    4180              :   }
    4181         9441 :   size_t suffix_len = ctx->pos - suffix_start;
    4182              : 
    4183         9441 :   if (suffix_len == 0 && handle_len == 1) {
    4184           26 :     ccol__mem_free(ctx->mp, handle);
    4185           26 :     *resolved_out = NULL;
    4186           26 :     return true;
    4187              :   }
    4188         9415 :   if (suffix_len == 0) {
    4189            0 :     parse_err(ctx, "tag handle '%s' with no suffix at position %zu",
    4190            0 :               cyaml_echo(handle), tag_start);
    4191            0 :     ccol__mem_free(ctx->mp, handle);
    4192            0 :     return false;
    4193              :   }
    4194         9415 :   if (!tag_text_check(ctx, ctx->src + suffix_start, suffix_len, suffix_start,
    4195              :                       true)) {
    4196           30 :     ccol__mem_free(ctx->mp, handle);
    4197           30 :     return false;
    4198              :   }
    4199              : 
    4200         9385 :   const char *prefix = tag_handles_lookup(ctx, handle);
    4201         9385 :   if (!prefix) {
    4202           67 :     parse_err(ctx, "undefined tag handle '%s' at position %zu",
    4203           67 :               cyaml_echo(handle), tag_start);
    4204           67 :     ccol__mem_free(ctx->mp, handle);
    4205           67 :     return false;
    4206              :   }
    4207              : 
    4208         9318 :   char *suffix = ccol__mem_alloc(ctx->mp, suffix_len + 1);
    4209         9318 :   if (!suffix) {
    4210            0 :     parse_err(ctx, "out of memory parsing tag suffix at position %zu",
    4211              :               tag_start);
    4212            0 :     ccol__mem_free(ctx->mp, handle);
    4213            0 :     return false;
    4214              :   }
    4215         9318 :   memcpy(suffix, ctx->src + suffix_start, suffix_len);
    4216         9318 :   suffix[suffix_len] = '\0';
    4217         9318 :   if (!percent_decode_tag_inplace(ctx, suffix, suffix_start)) {
    4218            3 :     ccol__mem_free(ctx->mp, handle);
    4219            3 :     ccol__mem_free(ctx->mp, suffix);
    4220            3 :     return false;
    4221              :   }
    4222         9315 :   size_t decoded_suffix_len = strlen(suffix);
    4223              : 
    4224         9315 :   size_t prefix_len = strlen(prefix);
    4225        18630 :   char *resolved =
    4226         9315 :       ccol__mem_alloc(ctx->mp, prefix_len + decoded_suffix_len + 1);
    4227         9315 :   if (!resolved) {
    4228            0 :     parse_err(ctx, "out of memory resolving tag at position %zu", tag_start);
    4229            0 :     ccol__mem_free(ctx->mp, handle);
    4230            0 :     ccol__mem_free(ctx->mp, suffix);
    4231            0 :     return false;
    4232              :   }
    4233         9315 :   memcpy(resolved, prefix, prefix_len);
    4234         9315 :   memcpy(resolved + prefix_len, suffix, decoded_suffix_len);
    4235         9315 :   resolved[prefix_len + decoded_suffix_len] = '\0';
    4236         9315 :   ccol__mem_free(ctx->mp, handle);
    4237         9315 :   ccol__mem_free(ctx->mp, suffix);
    4238         9315 :   *resolved_out = resolved;
    4239         9315 :   return true;
    4240              : }
    4241              : 
    4242              : // Parses a tag token for every place a tag can appear, like
    4243              : // parse_tag_token_raw(), but a bare "!" comes back as an owned
    4244              : // CYAML_TAG_NON_SPECIFIC so node construction sees it, and a written tag that
    4245              : // resolves to "!" (such as "!<!>") is a parse error.
    4246        21914 : static bool parse_tag_token(parse_ctx *ctx, char **resolved_out) {
    4247        21914 :   size_t tag_start = ctx->pos;
    4248        21914 :   char *tag = NULL;
    4249        21914 :   if (!parse_tag_token_raw(ctx, &tag)) return false;
    4250        21802 :   if (tag) {
    4251        21776 :     if (strcmp(tag, CYAML_TAG_NON_SPECIFIC) == 0) {
    4252            1 :       ccol__mem_free(ctx->mp, tag);
    4253            1 :       parse_err(ctx,
    4254              :                 "tag at position %zu resolves to '!', which is reserved for "
    4255              :                 "the non-specific tag",
    4256              :                 tag_start);
    4257            1 :       return false;
    4258              :     }
    4259        21775 :     *resolved_out = tag;
    4260        21775 :     return true;
    4261              :   }
    4262           26 :   tag = strdup_charged(ctx->mp, CYAML_TAG_NON_SPECIFIC);
    4263           26 :   if (!tag) {
    4264            0 :     parse_err(ctx, "out of memory parsing tag at position %zu", tag_start);
    4265            0 :     return false;
    4266              :   }
    4267           26 :   *resolved_out = tag;
    4268           26 :   return true;
    4269              : }
    4270              : 
    4271              : // Registers the anchor of a dictionary key, so a later alias of it resolves;
    4272              : // every place a key can carry an anchor calls it. It points anchor_name (NULL:
    4273              : // nothing to do) at anchor_value when the key has a typed form (a flow
    4274              : // collection, a typed plain scalar, a tagged key), else at a new string node of
    4275              : // key_str. No tree holds that node, so it goes to the kept list. anchor_name is
    4276              : // always freed and anchor_value always consumed. false only on OOM, with the
    4277              : // error set.
    4278         3618 : static bool register_key_anchor(parse_ctx *ctx, char *anchor_name,
    4279              :                                 const char *key_str, cyaml_node *anchor_value) {
    4280         3618 :   if (!anchor_name) {
    4281         3286 :     if (anchor_value) cyaml__destroy((cyaml)anchor_value);
    4282         3286 :     return true;
    4283              :   }
    4284          332 :   cyaml_node *anchor_val = anchor_value;
    4285          332 :   if (!anchor_val) {
    4286            3 :     anchor_val = node_alloc(CYAML_STRING, ctx->mp);
    4287            3 :     if (anchor_val) {
    4288            3 :       anchor_val->value.string = strdup_charged(ctx->mp, key_str);
    4289            3 :       if (!anchor_val->value.string) {
    4290            0 :         node_free(anchor_val);
    4291              :         anchor_val = NULL;
    4292              :       }
    4293              :     }
    4294              :   }
    4295              :   if (!anchor_val) {
    4296            0 :     parse_err(ctx, "out of memory registering key anchor '%s' at position %zu",
    4297            0 :               cyaml_echo(anchor_name), ctx->pos);
    4298            0 :     ccol__mem_free(ctx->mp, anchor_name);
    4299            0 :     return false;
    4300              :   }
    4301          332 :   bool stored = anchors_store(ctx, anchor_name, anchor_val);
    4302          332 :   if (stored)
    4303          326 :     parse_keep(ctx, anchor_val);
    4304              :   else
    4305            6 :     cyaml__destroy((cyaml)anchor_val);
    4306          332 :   ccol__mem_free(ctx->mp, anchor_name);
    4307              :   return stored;
    4308              : }
    4309              : 
    4310              : // True when, after inline whitespace, ctx->pos is at a ':' followed by
    4311              : // whitespace or the end, which makes the token before it an implicit key;
    4312              : // ctx->pos is left on the ':'.
    4313              : static inline __attribute__((always_inline)) bool at_block_value_indicator(
    4314              :     parse_ctx *ctx) {
    4315              :   skip_inline_ws(ctx);
    4316         4003 :   if (at_end(ctx) || cur(ctx) != ':') return false;
    4317         3667 :   char after = (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    4318         3667 :   return after == ' ' || after == '\t' || after == '\n' || after == '\r' ||
    4319              :          after == '\0';
    4320              : }
    4321              : 
    4322              : // Tries to read an implicit block key and its ':': A plain, quoted or flow
    4323              : // collection key, or an alias, with an optional anchor and tag in either order.
    4324              : // The ':' check runs before any key-only work (cloning an alias, typing a
    4325              : // scalar, canonical text), because the same text is usually a value and the
    4326              : // canonical-key limit must never refuse a value. A flow collection is parsed as
    4327              : // a speculation and rejected when no ':' follows. Every implicit key must fit
    4328              : // on one line.
    4329              : //
    4330              : // On a match ctx->pos is past the ':' and the outputs are set: The owned anchor
    4331              : // name (NULL for none or an alias key), the owned key text, whether the key is
    4332              : // a merge key ("<<" plain and untagged, or with the core merge tag; an anchor
    4333              : // doesn't matter), and the typed node an anchor should name. On no match
    4334              : // ctx->pos is restored and ctx->error[0] tells a real error from "not a key";
    4335              : // every OOM sets an error so the caller never mistakes it.
    4336         8363 : static bool try_parse_scalar_dict_key_body(parse_ctx *ctx,
    4337              :                                            char **anchor_name_out,
    4338              :                                            char **key_out,
    4339              :                                            bool *is_merge_candidate_out,
    4340              :                                            cyaml_node **anchor_value_out) {
    4341         8363 :   size_t saved_pos = ctx->pos;
    4342         8363 :   char *anchor_name = NULL;
    4343              : 
    4344         8363 :   if (!at_end(ctx) && cur(ctx) == '*') {
    4345          424 :     const size_t alias_start = ctx->pos;
    4346          424 :     ctx->pos++;
    4347          424 :     char *alias_name = NULL;
    4348          424 :     if (!parse_anchor_name(ctx, &alias_name)) return false;
    4349          413 :     cyaml_node *aliased = anchors_lookup(ctx, alias_name);
    4350          413 :     if (!aliased) {
    4351          180 :       parse_err(ctx, "unknown alias '*%s' at position %zu",
    4352           90 :                 cyaml_echo(alias_name), alias_start);
    4353           90 :       ccol__mem_free(ctx->mp, alias_name);
    4354           90 :       return false;
    4355              :     }
    4356          323 :     ccol__mem_free(ctx->mp, alias_name);
    4357              : 
    4358              :     if (!at_block_value_indicator(ctx)) {
    4359           34 :       ctx->pos = saved_pos;
    4360           34 :       return false;
    4361              :     }
    4362          289 :     ctx->pos++;
    4363              : 
    4364          289 :     bool too_deep = false;
    4365          289 :     size_t height = 0;
    4366          578 :     size_t key_levels = ctx->depth + 1 < CYAML_MAX_NESTING_DEPTH
    4367              :                             ? CYAML_MAX_NESTING_DEPTH - (ctx->depth + 1)
    4368          289 :                             : 0;
    4369          289 :     cyaml_node *clone =
    4370          289 :         parse_clone_levels(aliased, key_levels, &too_deep, &height);
    4371          289 :     if (clone && ctx->depth + 1 + height > ctx->peak_depth)
    4372          284 :       ctx->peak_depth = ctx->depth + 1 + height;
    4373            3 :     if (!clone && too_deep) {
    4374            1 :       parse_depth_err(ctx);
    4375            1 :       return false;
    4376              :     }
    4377            2 :     if (!clone) {
    4378            2 :       parse_err(ctx,
    4379              :                 "out of memory resolving alias as dictionary key at "
    4380              :                 "position %zu",
    4381              :                 saved_pos);
    4382            2 :       return false;
    4383              :     }
    4384              : 
    4385          572 :     char *key_str = node_to_dict_key_string(ctx, clone, "block dictionary");
    4386          286 :     if (!key_str) return false;
    4387              : 
    4388          286 :     *anchor_name_out = NULL;
    4389          286 :     *key_out = key_str;
    4390          286 :     if (is_merge_candidate_out) *is_merge_candidate_out = false;
    4391          286 :     if (anchor_value_out) *anchor_value_out = NULL;
    4392          286 :     return true;
    4393              :   }
    4394              : 
    4395         7939 :   bool had_tag = false;
    4396         7939 :   char *key_tag = NULL;
    4397        12756 :   for (int prop_pass = 0; prop_pass < 2; prop_pass++) {
    4398        12739 :     if (!at_end(ctx) && cur(ctx) == '&' && !anchor_name) {
    4399          430 :       ctx->pos++;
    4400          430 :       if (!parse_anchor_name(ctx, &anchor_name)) {
    4401            3 :         ccol__mem_free(ctx->mp, key_tag);
    4402            3 :         return false;
    4403              :       }
    4404              :       skip_inline_ws(ctx);
    4405        12309 :     } else if (!at_end(ctx) && cur(ctx) == '!' && !had_tag) {
    4406         4501 :       if (!parse_tag_token(ctx, &key_tag)) {
    4407          111 :         ccol__mem_free(ctx->mp, anchor_name);
    4408          111 :         return false;
    4409              :       }
    4410         4639 :       had_tag = true;
    4411              :       skip_inline_ws(ctx);
    4412              :     } else {
    4413              :       break;
    4414              :     }
    4415              :   }
    4416        15650 :   const bool key_has_merge_tag =
    4417         7825 :       key_tag && strcmp(key_tag, CYAML_TAG_MERGE) == 0;
    4418         7825 :   if (!at_end(ctx) && cur(ctx) == '!' && had_tag) {
    4419            6 :     parse_err(ctx, "a node cannot carry two tags at position %zu", ctx->pos);
    4420            6 :     ccol__mem_free(ctx->mp, key_tag);
    4421            6 :     ccol__mem_free(ctx->mp, anchor_name);
    4422            6 :     return false;
    4423              :   }
    4424         7819 :   if (at_end(ctx) || cur(ctx) == '\n' || cur(ctx) == '\r') {
    4425         4046 :     ctx->pos = saved_pos;
    4426         4046 :     ccol__mem_free(ctx->mp, key_tag);
    4427         4046 :     ccol__mem_free(ctx->mp, anchor_name);
    4428         4046 :     return false;
    4429              :   }
    4430         3773 :   char c = cur(ctx);
    4431         3773 :   if (c == '|' || c == '>' || c == '&' || c == '*' || c == '#' || c == '%' ||
    4432              :       c == '@' || c == '`' || c == ']' || c == '}' || c == ',') {
    4433           41 :     ctx->pos = saved_pos;
    4434           41 :     ccol__mem_free(ctx->mp, key_tag);
    4435           41 :     ccol__mem_free(ctx->mp, anchor_name);
    4436           41 :     return false;
    4437              :   }
    4438              : 
    4439         3732 :   char *key_str = NULL;
    4440         3732 :   cyaml_node *coll = NULL;
    4441         3732 :   anchor_speculation spec;
    4442         3732 :   bool parsed;
    4443         3732 :   if (c == '"' || c == '\'') {
    4444           75 :     size_t quote_start = ctx->pos;
    4445           66 :     parsed = (c == '"') ? parse_double_quoted(ctx, &key_str)
    4446           75 :                         : parse_single_quoted(ctx, &key_str);
    4447           75 :     if (parsed && span_crosses_newline(ctx, quote_start)) {
    4448            2 :       ccol__mem_free(ctx->mp, key_str);
    4449            2 :       ctx->pos = saved_pos;
    4450            2 :       ccol__mem_free(ctx->mp, key_tag);
    4451            2 :       ccol__mem_free(ctx->mp, anchor_name);
    4452            2 :       return false;
    4453              :     }
    4454         3657 :   } else if (c == '[' || c == '{') {
    4455          386 :     size_t coll_start = ctx->pos;
    4456          386 :     anchor_speculation_begin(ctx, &spec);
    4457          772 :     coll =
    4458          772 :         (c == '[') ? parse_flow_list(ctx, -1) : parse_flow_dictionary(ctx, -1);
    4459          386 :     if (!coll) {
    4460           31 :       anchor_speculation_accept(ctx, &spec);
    4461           31 :       if (!ctx->error[0]) {
    4462            7 :         if (parse_node_budget_exhausted)
    4463            0 :           parse_err(ctx,
    4464              :                     "document exceeded the %zu node-allocation limit at "
    4465              :                     "position %zu",
    4466              :                     parse_node_limit, coll_start);
    4467            7 :         else if (parse_byte_budget_exhausted)
    4468            0 :           parse_err(ctx,
    4469              :                     "document exceeded the %zu-byte memory limit at "
    4470              :                     "position %zu",
    4471              :                     parse_byte_limit, coll_start);
    4472              :         else
    4473            7 :           parse_err(ctx,
    4474              :                     "out of memory parsing flow collection dictionary key "
    4475              :                     "at position %zu",
    4476              :                     coll_start);
    4477              :       }
    4478           31 :       ccol__mem_free(ctx->mp, key_tag);
    4479           31 :       ccol__mem_free(ctx->mp, anchor_name);
    4480           31 :       return false;
    4481              :     }
    4482          355 :     parsed = !span_crosses_newline(ctx, coll_start);
    4483              :   } else
    4484         6542 :     parsed = parse_plain_scalar(ctx, false, &key_str, NULL);
    4485         3699 :   bool from_plain_branch = (c != '"' && c != '\'' && c != '[' && c != '{');
    4486         3699 :   if (!parsed && !coll) {
    4487           16 :     if (!ctx->error[0])
    4488           14 :       parse_err(ctx, "out of memory parsing dictionary key at position %zu",
    4489              :                 saved_pos);
    4490           16 :     ccol__mem_free(ctx->mp, key_tag);
    4491           16 :     ccol__mem_free(ctx->mp, anchor_name);
    4492           16 :     return false;
    4493              :   }
    4494              : 
    4495         3683 :   if (!parsed || !at_block_value_indicator(ctx)) {
    4496          305 :     ctx->pos = saved_pos;
    4497          305 :     ccol__mem_free(ctx->mp, key_str);
    4498          305 :     if (coll) {
    4499           54 :       cyaml__destroy((cyaml)coll);
    4500           54 :       anchor_speculation_reject(ctx, &spec);
    4501              :     }
    4502          305 :     ccol__mem_free(ctx->mp, key_tag);
    4503          305 :     ccol__mem_free(ctx->mp, anchor_name);
    4504          305 :     return false;
    4505              :   }
    4506         3378 :   if (coll) {
    4507          301 :     anchor_speculation_accept(ctx, &spec);
    4508          301 :     if (!parse_key_fits_below_mapping(ctx, coll)) {
    4509            2 :       cyaml__destroy((cyaml)coll);
    4510            2 :       ccol__mem_free(ctx->mp, key_tag);
    4511            2 :       ccol__mem_free(ctx->mp, anchor_name);
    4512            2 :       return false;
    4513              :     }
    4514              :   }
    4515         3376 :   ctx->pos++;
    4516              : 
    4517         3376 :   cyaml_node *key_node = NULL;
    4518         3376 :   if (!key_tag && from_plain_branch) {
    4519         2999 :     key_node = make_typed_scalar(ctx, key_str);
    4520         2999 :     ccol__mem_free(ctx->mp, key_str);
    4521         2999 :     key_str = NULL;
    4522          377 :   } else if (coll) {
    4523          299 :     key_node = finalize_collection_node(ctx, coll, key_tag);
    4524           78 :   } else if (key_tag || from_plain_branch) {
    4525           42 :     key_node = finalize_scalar_node(ctx, key_str, key_tag, from_plain_branch);
    4526           42 :     key_str = NULL;
    4527              :   }
    4528         3376 :   if (key_tag) ccol__mem_free(ctx->mp, key_tag);
    4529         3376 :   if (!key_node && !key_str) {
    4530           36 :     if (!ctx->error[0])
    4531           28 :       parse_err(ctx, "out of memory typing dictionary key at position %zu",
    4532              :                 saved_pos);
    4533           36 :     ccol__mem_free(ctx->mp, anchor_name);
    4534           36 :     return false;
    4535              :   }
    4536              : 
    4537         3304 :   cyaml_node *anchor_value = NULL;
    4538              :   if (key_node) {
    4539         3304 :     if (anchor_name) {
    4540          662 :       key_str =
    4541          331 :           node_to_dict_key_string_ex(ctx, key_node, "block dictionary", false);
    4542          331 :       if (!key_str) {
    4543            2 :         cyaml__destroy((cyaml)key_node);
    4544            2 :         ccol__mem_free(ctx->mp, anchor_name);
    4545            2 :         return false;
    4546              :       }
    4547              :       anchor_value = key_node;
    4548              :     } else {
    4549         5945 :       key_str = node_to_dict_key_string(ctx, key_node, "block dictionary");
    4550         2972 :       if (!key_str) return false;
    4551              :     }
    4552              :   }
    4553              : 
    4554         3337 :   *anchor_name_out = anchor_name;
    4555         3337 :   *key_out = key_str;
    4556         3337 :   if (is_merge_candidate_out)
    4557         6674 :     *is_merge_candidate_out =
    4558         6674 :         ((from_plain_branch && !had_tag) || key_has_merge_tag) &&
    4559         2978 :         strcmp(key_str, "<<") == 0;
    4560         3337 :   if (anchor_value_out)
    4561         3337 :     *anchor_value_out = anchor_value;
    4562            0 :   else if (anchor_value)
    4563            0 :     cyaml__destroy((cyaml)anchor_value);
    4564              :   return true;
    4565              : }
    4566              : 
    4567              : // Tries to read an implicit block key through the body above, for the node
    4568              : // dispatch and later block-mapping entries. When it declines, ctx->pos and
    4569              : // ctx->depth must be exactly as on entry, because the caller reads the same
    4570              : // text again; test builds assert both.
    4571         8363 : static bool try_parse_scalar_dict_key(parse_ctx *ctx, char **anchor_name_out,
    4572              :                                       char **key_out,
    4573              :                                       bool *is_merge_candidate_out,
    4574              :                                       cyaml_node **anchor_value_out) {
    4575              : #ifdef RUNNING_UNIT_TESTS
    4576         8363 :   const size_t saved_pos = ctx->pos;
    4577         8363 :   const size_t saved_depth = ctx->depth;
    4578              : #endif
    4579         8363 :   bool accepted = try_parse_scalar_dict_key_body(
    4580              :       ctx, anchor_name_out, key_out, is_merge_candidate_out, anchor_value_out);
    4581              : #ifdef RUNNING_UNIT_TESTS
    4582         8362 :   ccol__assert(ctx->depth == saved_depth);
    4583         8362 :   if (!accepted && !ctx->error[0]) ccol__assert(ctx->pos == saved_pos);
    4584              : #endif
    4585         8362 :   return accepted;
    4586              : }
    4587              : 
    4588              : // A parse runs on an explicit stack of frames instead of the C stack, so its
    4589              : // stack needs don't grow with the nesting. Each kind of frame is one construct
    4590              : // that can hold another node. A frame either finishes and hands its node to the
    4591              : // frame below, or asks the driver to push a child and resumes when it's done.
    4592              : typedef enum {
    4593              :   PFK_NODE,
    4594              :   PFK_FLOW_LIST,
    4595              :   PFK_FLOW_DICT,
    4596              :   PFK_BLOCK_LIST,
    4597              :   PFK_BLOCK_DICT
    4598              : } pframe_kind;
    4599              : 
    4600              : // What a frame asks the driver to push: Exactly the arguments of the call it
    4601              : // stands for. resolved_tag and first_key are borrowed.
    4602              : typedef struct {
    4603              :   pframe_kind kind;
    4604              :   int indent;
    4605              :   bool in_flow;
    4606              :   bool seq_ok_at_indent;
    4607              :   bool allow_inline_map;
    4608              :   bool had_anchor;
    4609              :   bool had_tag;
    4610              :   const char *resolved_tag;
    4611              :   const char *first_key;
    4612              :   bool first_key_colon_consumed;
    4613              :   bool first_key_is_merge_candidate;
    4614              : } preq;
    4615              : 
    4616              : // The resume points of each frame kind: Each names the child the frame waits
    4617              : // for.
    4618              : enum {
    4619              :   NS_ENTRY = 0,
    4620              :   NS_AFTER_ANCHOR_VALUE,
    4621              :   NS_AFTER_TAG_VALUE,
    4622              :   NS_AFTER_COLLECTION,
    4623              :   NS_AFTER_FLOW_COLL
    4624              : };
    4625              : enum {
    4626              :   FLS_ENTRY = 0,
    4627              :   FLS_AFTER_PAIR_KEY,
    4628              :   FLS_AFTER_PAIR_VALUE,
    4629              :   FLS_AFTER_ELEM,
    4630              :   FLS_AFTER_SHORTHAND_VALUE
    4631              : };
    4632              : enum { FDS_ENTRY = 0, FDS_AFTER_KEY, FDS_AFTER_VALUE };
    4633              : enum { BLS_ENTRY = 0, BLS_AFTER_ELEM };
    4634              : enum {
    4635              :   BDS_ENTRY = 0,
    4636              :   BDS_AFTER_FIRST_KEY_NODE,
    4637              :   BDS_AFTER_KEY_NODE,
    4638              :   BDS_AFTER_VALUE
    4639              : };
    4640              : 
    4641              : // A "<<" entry of a mapping being read: Its value, owned by the frame until the
    4642              : // mapping ends, and the member count when it appeared, which places the merged
    4643              : // members. It never enters the map, so merge entries never collide.
    4644              : typedef struct {
    4645              :   cyaml_node *val;
    4646              :   size_t pos;
    4647              : } cyaml_merge_entry;
    4648              : 
    4649              : // One suspended parser. child is the node the frame above just finished, owned
    4650              : // here until consumed; result is this frame's finished node. A container under
    4651              : // construction belongs only to its frame, so a failed parse runs
    4652              : // pframe_cleanup() on every frame of the stack.
    4653              : typedef struct {
    4654              :   pframe_kind kind;
    4655              :   int state;
    4656              :   cyaml_node *child;
    4657              :   cyaml_node *result;
    4658              :   union {
    4659              :     struct {
    4660              :       int indent;
    4661              :       bool in_flow, seq_ok_at_indent, allow_inline_map, had_anchor, had_tag;
    4662              :       const char *resolved_tag;
    4663              :       char *name;
    4664              :       char *tag;
    4665              :       char *pending_key;
    4666              :       // The column of the node and where a flow collection started.
    4667              :       int col;
    4668              :       size_t coll_start;
    4669              :     } n;
    4670              :     struct {
    4671              :       int indent;
    4672              :       cyaml_node *seq;
    4673              :       char *key_str;
    4674              :       size_t elem_start;
    4675              :       bool is_merge_candidate;
    4676              :     } fl;
    4677              :     struct {
    4678              :       int indent;
    4679              :       cyaml_node *map;
    4680              :       char *key_str;
    4681              :       cyaml_merge_entry *merges;
    4682              :       size_t merge_count, merge_cap;
    4683              :       bool is_explicit_key_indicator;
    4684              :       bool explicit_key_is_merge_candidate;
    4685              :       bool implicit_key_is_merge_candidate;
    4686              :       bool is_merge_candidate;
    4687              :     } fd;
    4688              :     struct {
    4689              :       int seq_indent;
    4690              :       cyaml_node *seq;
    4691              :     } bl;
    4692              :     struct {
    4693              :       int map_indent;
    4694              :       cyaml_node *map;
    4695              :       const char *key;
    4696              :       char *key_owned;
    4697              :       cyaml_merge_entry *merges;
    4698              :       size_t merge_count, merge_cap;
    4699              :       bool have_colon, is_explicit;
    4700              :       bool entry_is_merge_candidate;
    4701              :     } bd;
    4702              :   } u;
    4703              : } pframe;
    4704              : 
    4705              : // What pbmn_begin() decided about a node in a block mapping: NODE (in
    4706              : // *node_out, NULL meaning OOM), DESCEND (the request is filled in) or ERROR
    4707              : // (ctx->error is set).
    4708              : typedef enum { PBMN_NODE, PBMN_DESCEND, PBMN_ERROR } pbmn;
    4709              : 
    4710              : // What one step of a frame decided: DONE (f->result holds the node), DESCEND
    4711              : // (push the request) or FAIL (ctx->error is set unless it was a bare OOM).
    4712              : typedef enum { PSTEP_DONE, PSTEP_DESCEND, PSTEP_FAIL } pstep;
    4713              : 
    4714              : // How many parse frames the driver keeps in its locals before moving the stack
    4715              : // to the heap. A level opens two frames, plus one per anchor or tag, so this
    4716              : // covers ordinary documents without an allocation.
    4717              : #define CYAML_PARSE_INLINE_FRAMES 24
    4718              : 
    4719              : static cyaml_node *parse_drive(parse_ctx *ctx, const preq *root_req);
    4720              : 
    4721              : // Parses one node by running the frame driver on a node request. The depth
    4722              : // guard lives in the collection frames (see pframe_open()), so every container
    4723              : // counts whatever construct opened it, and every exit gives ctx->depth back.
    4724         6956 : static cyaml_node *parse_node(parse_ctx *ctx, int indent, bool in_flow,
    4725              :                               bool seq_ok_at_indent, bool allow_inline_map,
    4726              :                               bool had_anchor, bool had_tag,
    4727              :                               const char *resolved_tag) {
    4728         6956 :   preq rq = {.kind = PFK_NODE,
    4729              :              .indent = indent,
    4730              :              .in_flow = in_flow,
    4731              :              .seq_ok_at_indent = seq_ok_at_indent,
    4732              :              .allow_inline_map = allow_inline_map,
    4733              :              .had_anchor = had_anchor,
    4734              :              .had_tag = had_tag,
    4735              :              .resolved_tag = resolved_tag,
    4736              :              .first_key = NULL,
    4737              :              .first_key_colon_consumed = false,
    4738              :              .first_key_is_merge_candidate = false};
    4739         6956 :   return parse_drive(ctx, &rq);
    4740              : }
    4741              : 
    4742              : static bool merge_apply(parse_ctx *ctx, cyaml_node *map,
    4743              :                         const cyaml_merge_entry *entries, size_t n);
    4744              : static bool merge_entry_push(parse_ctx *ctx, cyaml_merge_entry **arr,
    4745              :                              size_t *count, size_t *cap, cyaml_node *val,
    4746              :                              size_t pos);
    4747              : static void merge_entries_free(parse_ctx *ctx, cyaml_merge_entry **arr,
    4748              :                                size_t *count, size_t *cap);
    4749              : static bool merge_entries_finish(parse_ctx *ctx, cyaml_node *map,
    4750              :                                  cyaml_merge_entry **arr, size_t *count,
    4751              :                                  size_t *cap);
    4752              : 
    4753              : // Stores the entry of the one-pair mapping that "[key: value]" or
    4754              : // "[? key: value]" makes; a confirmed merge key is expanded into the mapping
    4755              : // instead. It owns key_str and val in every case and destroys pair on failure.
    4756        20622 : static bool flow_pair_store(parse_ctx *ctx, cyaml_node *pair, char *key_str,
    4757              :                             cyaml_node *val, bool is_merge_candidate) {
    4758        20622 :   bool ok;
    4759        20692 :   if (is_merge_candidate && strcmp(key_str, "<<") == 0) {
    4760           70 :     cyaml_merge_entry entry = {.val = val, .pos = 0};
    4761           70 :     ok = merge_apply(ctx, pair, &entry, 1);
    4762           70 :     parse_discard(val);
    4763              :   } else {
    4764        20552 :     ok = dictionary_set_impl((cyaml)pair, key_str, (cyaml)val) == ccol_success;
    4765              :   }
    4766        20622 :   ccol__mem_free(ctx->mp, key_str);
    4767        20622 :   if (!ok) cyaml__destroy((cyaml)pair);
    4768        20622 :   return ok;
    4769              : }
    4770              : 
    4771              : static bool explicit_key_peek_is_merge_candidate(parse_ctx *ctx, int indent,
    4772              :                                                  bool in_flow);
    4773              : // Fills in a request for one node dispatch, with the arguments of the
    4774              : // parse_node() call it stands for. Each preq_* builder writes only the fields
    4775              : // pframe_open() reads for its kind.
    4776       359281 : static void preq_node(preq *rq, int indent, bool in_flow, bool seq_ok_at_indent,
    4777              :                       bool allow_inline_map, bool had_anchor, bool had_tag,
    4778              :                       const char *resolved_tag) {
    4779       359281 :   rq->kind = PFK_NODE;
    4780       359281 :   rq->indent = indent;
    4781       359281 :   rq->in_flow = in_flow;
    4782       359281 :   rq->seq_ok_at_indent = seq_ok_at_indent;
    4783       359281 :   rq->allow_inline_map = allow_inline_map;
    4784       359281 :   rq->had_anchor = had_anchor;
    4785       359281 :   rq->had_tag = had_tag;
    4786       359281 :   rq->resolved_tag = resolved_tag;
    4787        16808 : }
    4788              : 
    4789              : // Fills in a request for a block mapping, for a node that turns out to be its
    4790              : // first key or a "? " entry. first_key is borrowed; the frame below owns it and
    4791              : // outlives the new frame.
    4792        12507 : static void preq_block_dict(preq *rq, int map_indent, const char *first_key,
    4793              :                             bool first_key_colon_consumed,
    4794              :                             bool first_key_is_merge_candidate) {
    4795        12507 :   rq->kind = PFK_BLOCK_DICT;
    4796        12507 :   rq->indent = map_indent;
    4797        12507 :   rq->first_key = first_key;
    4798        12507 :   rq->first_key_colon_consumed = first_key_colon_consumed;
    4799        12507 :   rq->first_key_is_merge_candidate = first_key_is_merge_candidate;
    4800              : }
    4801              : 
    4802              : // Fills in a request for a block sequence at seq_indent, for a node that turns
    4803              : // out to be a "- " entry.
    4804        23374 : static void preq_block_list(preq *rq, int seq_indent) {
    4805        23374 :   rq->kind = PFK_BLOCK_LIST;
    4806        23374 :   rq->indent = seq_indent;
    4807              : }
    4808              : 
    4809              : // Fills in a request for a flow list ('[') or a flow dictionary ('{'), for a
    4810              : // node that starts with one.
    4811        84851 : static void preq_flow(preq *rq, bool is_list, int indent) {
    4812       169316 :   rq->kind = is_list ? PFK_FLOW_LIST : PFK_FLOW_DICT;
    4813        84851 :   rq->indent = indent;
    4814              : }
    4815              : 
    4816              : // Records the finished node of a node frame in f->result, the common exit of
    4817              : // every node dispatch path. A NULL node gives PSTEP_FAIL.
    4818       324087 : static pstep pni_finish(pframe *f, cyaml_node *n) {
    4819       324087 :   f->result = n;
    4820       324087 :   return n ? PSTEP_DONE : PSTEP_FAIL;
    4821              : }
    4822              : 
    4823              : // Frees the anchor name a node frame holds across its descent, once the
    4824              : // resume is done with it. Clearing the field keeps pframe_cleanup()
    4825              : // idempotent.
    4826         6897 : static void pni_release_name(parse_ctx *ctx, pframe *f) {
    4827         6897 :   ccol__mem_free(ctx->mp, f->u.n.name);
    4828         6897 :   f->u.n.name = NULL;
    4829         6897 : }
    4830              : 
    4831              : // Frees the tag text a node frame holds across its descent, once the resume
    4832              : // is done with it, and clears the field as pni_release_name() does.
    4833        15109 : static void pni_release_tag(parse_ctx *ctx, pframe *f) {
    4834        15109 :   ccol__mem_free(ctx->mp, f->u.n.tag);
    4835        15109 :   f->u.n.tag = NULL;
    4836        15109 : }
    4837              : 
    4838              : // What flow_list_expect_comma_or_close() read: ']' (done), ',' (another
    4839              : // entry), or an error with ctx->error set.
    4840              : typedef enum {
    4841              :   FLOW_LIST_TAIL_CLOSE,
    4842              :   FLOW_LIST_TAIL_CONTINUE,
    4843              :   FLOW_LIST_TAIL_ERROR
    4844              : } flow_list_tail;
    4845              : 
    4846              : // Skips whitespace after a flow-list element and reads the ']' or ',' that
    4847              : // must follow. Both entry shapes of pfl_step() share it. Anything else is a
    4848              : // parse error.
    4849       196905 : static flow_list_tail flow_list_expect_comma_or_close(parse_ctx *ctx,
    4850              :                                                       int indent) {
    4851       196905 :   if (!flow_skip_ws(ctx, indent)) return FLOW_LIST_TAIL_ERROR;
    4852       196905 :   if (at_end(ctx)) {
    4853            6 :     parse_err(ctx, "unterminated flow list");
    4854            6 :     return FLOW_LIST_TAIL_ERROR;
    4855              :   }
    4856       196899 :   if (cur(ctx) == ']') {
    4857        26623 :     ctx->pos++;
    4858        26623 :     return FLOW_LIST_TAIL_CLOSE;
    4859              :   }
    4860       170276 :   if (cur(ctx) != ',') {
    4861           17 :     parse_err(ctx, "expected ',' or ']' in flow list at position %zu",
    4862              :               ctx->pos);
    4863           17 :     return FLOW_LIST_TAIL_ERROR;
    4864              :   }
    4865       170259 :   ctx->pos++;
    4866       170259 :   return FLOW_LIST_TAIL_CONTINUE;
    4867              : }
    4868              : 
    4869              : // Runs a flow-list frame, '[' elem (',' elem)* ']', into a CYAML_LIST. The
    4870              : // element, and the key and value of "[? key: value]", are descents. An empty
    4871              : // entry is an error. "[key: value]" is a one-entry mapping whose ':' must be on
    4872              : // the key's line; the merge look-ahead runs before the key is read, and the
    4873              : // pair holds a nesting level while its value is read. Each stored element is
    4874              : // marked attached. f->u.fl.indent is the enclosing block indent, or -1.
    4875       287761 : static pstep pfl_step(parse_ctx *ctx, pframe *f, preq *rq) {
    4876       287761 :   const int indent = f->u.fl.indent;
    4877       287761 :   cyaml_node *key_node;
    4878       287761 :   cyaml_node *val;
    4879       287761 :   cyaml_node *elem;
    4880       287761 :   char *key_str;
    4881              : 
    4882       287761 :   switch (f->state) {
    4883           13 :     case FLS_AFTER_PAIR_KEY:
    4884           13 :       goto after_pair_key;
    4885            7 :     case FLS_AFTER_PAIR_VALUE:
    4886            7 :       goto after_pair_value;
    4887       196934 :     case FLS_AFTER_ELEM:
    4888       196934 :       goto after_elem;
    4889        20620 :     case FLS_AFTER_SHORTHAND_VALUE:
    4890        20620 :       goto after_shorthand_value;
    4891              :     default:
    4892        70187 :       break;
    4893              :   }
    4894              : 
    4895        70187 :   ctx->pos++;
    4896        70191 :   if (!flow_skip_ws(ctx, indent)) return PSTEP_FAIL;
    4897              : 
    4898        70183 :   f->u.fl.seq = (cyaml_node *)cyaml_create_list_interned(ctx->mp);
    4899        70180 :   if (!f->u.fl.seq) return PSTEP_FAIL;
    4900              : 
    4901        69979 :   if (!at_end(ctx) && cur(ctx) == ']') {
    4902        20062 :     ctx->pos++;
    4903        20062 :     goto done;
    4904              :   }
    4905              : 
    4906       220176 :   while (1) {
    4907       220179 :     if (!flow_skip_ws(ctx, indent)) return PSTEP_FAIL;
    4908       220173 :     if (at_end(ctx)) {
    4909           73 :       parse_err(ctx, "unterminated flow list");
    4910           73 :       return PSTEP_FAIL;
    4911              :     }
    4912       220100 :     if (cur(ctx) == ']') {
    4913            9 :       ctx->pos++;
    4914            9 :       goto done;
    4915              :     }
    4916       220091 :     if (cur(ctx) == ',') {
    4917            4 :       parse_err(ctx, "empty flow list entry at position %zu", ctx->pos);
    4918            4 :       return PSTEP_FAIL;
    4919              :     }
    4920              : 
    4921       220087 :     bool is_explicit_pair_indicator = false;
    4922       220087 :     if (cur(ctx) == '?') {
    4923           16 :       char nx = (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    4924           16 :       if (nx == ' ' || nx == '\t' || nx == '\n' || nx == '\r' || nx == '\0')
    4925           13 :         is_explicit_pair_indicator = true;
    4926              :     }
    4927           13 :     if (is_explicit_pair_indicator) {
    4928           13 :       ctx->pos++;
    4929           13 :       if (!flow_skip_ws(ctx, indent)) return PSTEP_FAIL;
    4930           26 :       f->u.fl.is_merge_candidate =
    4931           13 :           explicit_key_peek_is_merge_candidate(ctx, indent, true);
    4932           13 :       preq_node(rq, indent, true, false, false, false, false, NULL);
    4933           13 :       f->state = FLS_AFTER_PAIR_KEY;
    4934           13 :       return PSTEP_DESCEND;
    4935           13 :     after_pair_key:
    4936           13 :       key_node = f->child;
    4937           13 :       f->child = NULL;
    4938           13 :       if (!key_node) return PSTEP_FAIL;
    4939           13 :       if (!parse_key_fits_below_mapping(ctx, key_node)) {
    4940            3 :         cyaml__destroy((cyaml)key_node);
    4941            3 :         return PSTEP_FAIL;
    4942              :       }
    4943           20 :       key_str = node_to_dict_key_string(ctx, key_node, "flow sequence entry");
    4944           10 :       if (!key_str) return PSTEP_FAIL;
    4945              : 
    4946           10 :       if (!flow_skip_ws(ctx, indent)) {
    4947            0 :         ccol__mem_free(ctx->mp, key_str);
    4948            0 :         return PSTEP_FAIL;
    4949              :       }
    4950           10 :       if (!at_end(ctx) && cur(ctx) == ':') {
    4951            7 :         ctx->pos++;
    4952           14 :         if (!flow_skip_ws(ctx, indent) || !flow_pair_level_take(ctx)) {
    4953            0 :           ccol__mem_free(ctx->mp, key_str);
    4954            0 :           return PSTEP_FAIL;
    4955              :         }
    4956            7 :         f->u.fl.key_str = key_str;
    4957            7 :         preq_node(rq, indent, true, false, false, false, false, NULL);
    4958            7 :         f->state = FLS_AFTER_PAIR_VALUE;
    4959            7 :         return PSTEP_DESCEND;
    4960            7 :       after_pair_value:
    4961            7 :         key_str = f->u.fl.key_str;
    4962            7 :         f->u.fl.key_str = NULL;
    4963            7 :         ctx->depth--;
    4964            7 :         val = f->child;
    4965            7 :         f->child = NULL;
    4966            7 :         if (!val) {
    4967            0 :           ccol__mem_free(ctx->mp, key_str);
    4968            0 :           return PSTEP_FAIL;
    4969              :         }
    4970              :       } else {
    4971            3 :         if (ctx->depth >= CYAML_MAX_NESTING_DEPTH) {
    4972            0 :           parse_depth_err(ctx);
    4973            0 :           ccol__mem_free(ctx->mp, key_str);
    4974            0 :           return PSTEP_FAIL;
    4975              :         }
    4976            3 :         if (ctx->depth + 1 > ctx->peak_depth) ctx->peak_depth = ctx->depth + 1;
    4977            3 :         val = node_alloc(CYAML_NULL, ctx->mp);
    4978            3 :         if (!val) {
    4979            0 :           ccol__mem_free(ctx->mp, key_str);
    4980            0 :           return PSTEP_FAIL;
    4981              :         }
    4982              :       }
    4983              : 
    4984              :       {
    4985           10 :         cyaml_node *pair =
    4986           10 :             (cyaml_node *)cyaml_create_dictionary_interned(ctx->mp);
    4987           10 :         if (!pair) {
    4988            0 :           ccol__mem_free(ctx->mp, key_str);
    4989            0 :           cyaml__destroy((cyaml)val);
    4990            0 :           return PSTEP_FAIL;
    4991              :         }
    4992           10 :         if (!flow_pair_store(ctx, pair, key_str, val,
    4993           10 :                              f->u.fl.is_merge_candidate))
    4994              :           return PSTEP_FAIL;
    4995              : 
    4996           10 :         cyaml_node *pep = pair;
    4997           10 :         if (cvector_push_back(f->u.fl.seq->value.list, &pep) != ccol_success) {
    4998            0 :           cyaml__destroy((cyaml)pair);
    4999            0 :           return PSTEP_FAIL;
    5000              :         }
    5001           10 :         pep->attached = true;
    5002              :       }
    5003              : 
    5004           10 :       switch (flow_list_expect_comma_or_close(ctx, indent)) {
    5005            9 :         case FLOW_LIST_TAIL_CLOSE:
    5006            9 :           goto done;
    5007              :         case FLOW_LIST_TAIL_ERROR:
    5008              :           return PSTEP_FAIL;
    5009            1 :         case FLOW_LIST_TAIL_CONTINUE:
    5010            1 :           continue;
    5011              :       }
    5012              :     }
    5013              : 
    5014       220074 :     f->u.fl.elem_start = ctx->pos;
    5015       440150 :     f->u.fl.is_merge_candidate =
    5016       220074 :         explicit_key_peek_is_merge_candidate(ctx, indent, true);
    5017       220076 :     preq_node(rq, indent, true, false, false, false, false, NULL);
    5018       220076 :     f->state = FLS_AFTER_ELEM;
    5019       220076 :     return PSTEP_DESCEND;
    5020       196934 :   after_elem:
    5021       196934 :     elem = f->child;
    5022       196934 :     f->child = NULL;
    5023       196934 :     if (!elem) return PSTEP_FAIL;
    5024              : 
    5025       196934 :     if (!flow_skip_ws(ctx, indent)) {
    5026            5 :       cyaml__destroy((cyaml)elem);
    5027            5 :       return PSTEP_FAIL;
    5028              :     }
    5029       196925 :     if (!span_crosses_newline(ctx, f->u.fl.elem_start) && !at_end(ctx) &&
    5030       196823 :         cur(ctx) == ':') {
    5031        20641 :       if (!parse_key_fits_below_mapping(ctx, elem)) {
    5032            2 :         cyaml__destroy((cyaml)elem);
    5033            2 :         return PSTEP_FAIL;
    5034              :       }
    5035        41278 :       key_str = node_to_dict_key_string(ctx, elem, "flow sequence entry");
    5036        20639 :       if (!key_str) return PSTEP_FAIL;
    5037        20638 :       ctx->pos++;
    5038        20638 :       if (!flow_skip_ws(ctx, indent)) {
    5039            0 :         ccol__mem_free(ctx->mp, key_str);
    5040            0 :         return PSTEP_FAIL;
    5041              :       }
    5042              : 
    5043        20638 :       if (!flow_pair_level_take(ctx)) {
    5044            0 :         ccol__mem_free(ctx->mp, key_str);
    5045            0 :         return PSTEP_FAIL;
    5046              :       }
    5047        20638 :       f->u.fl.key_str = key_str;
    5048        20638 :       preq_node(rq, indent, true, false, false, false, false, NULL);
    5049        20638 :       f->state = FLS_AFTER_SHORTHAND_VALUE;
    5050        20638 :       return PSTEP_DESCEND;
    5051        20620 :     after_shorthand_value:
    5052        20620 :       key_str = f->u.fl.key_str;
    5053        20620 :       f->u.fl.key_str = NULL;
    5054        20620 :       ctx->depth--;
    5055        20620 :       val = f->child;
    5056        20620 :       f->child = NULL;
    5057        20620 :       if (!val) {
    5058            0 :         ccol__mem_free(ctx->mp, key_str);
    5059            0 :         return PSTEP_FAIL;
    5060              :       }
    5061              : 
    5062              :       {
    5063        20620 :         cyaml_node *pair =
    5064        20620 :             (cyaml_node *)cyaml_create_dictionary_interned(ctx->mp);
    5065        20620 :         if (!pair) {
    5066            8 :           ccol__mem_free(ctx->mp, key_str);
    5067            8 :           cyaml__destroy((cyaml)val);
    5068            8 :           return PSTEP_FAIL;
    5069              :         }
    5070        20612 :         if (!flow_pair_store(ctx, pair, key_str, val,
    5071        20612 :                              f->u.fl.is_merge_candidate))
    5072              :           return PSTEP_FAIL;
    5073              :         elem = pair;
    5074              :       }
    5075              :     }
    5076              : 
    5077              :     {
    5078       196895 :       cyaml_node *ep = elem;
    5079       196895 :       if (cvector_push_back(f->u.fl.seq->value.list, &ep) != ccol_success) {
    5080            0 :         cyaml__destroy((cyaml)elem);
    5081            0 :         return PSTEP_FAIL;
    5082              :       }
    5083       196895 :       ep->attached = true;
    5084              :     }
    5085              : 
    5086       196895 :     switch (flow_list_expect_comma_or_close(ctx, indent)) {
    5087        26615 :       case FLOW_LIST_TAIL_CLOSE:
    5088        26615 :         goto done;
    5089              :       case FLOW_LIST_TAIL_ERROR:
    5090              :         return PSTEP_FAIL;
    5091       170258 :       case FLOW_LIST_TAIL_CONTINUE:
    5092       170258 :         continue;
    5093              :     }
    5094              :   }
    5095              : 
    5096        46695 : done:
    5097        46695 :   f->result = f->u.fl.seq;
    5098        46695 :   f->u.fl.seq = NULL;
    5099        46695 :   return PSTEP_DONE;
    5100              : }
    5101              : 
    5102              : // Parses a flow list as an independent walk with its own frame stack. The
    5103              : // speculative read of a flow-collection key needs it, since that read happens
    5104              : // outside any node dispatch. It shares ctx, and so the depth budget, with the
    5105              : // outer parse. Gives the list, or NULL on failure.
    5106          364 : static cyaml_node *parse_flow_list(parse_ctx *ctx, int indent) {
    5107          364 :   preq rq;
    5108          364 :   preq_flow(&rq, true, indent);
    5109          364 :   return parse_drive(ctx, &rq);
    5110              : }
    5111              : 
    5112              : // The buffer size for the canonical text of a float key; the longest text
    5113              : // ("-%.17g" with an exponent) fits.
    5114              : #define CYAML_FLOAT_KEY_BUF_LEN 32
    5115              : 
    5116              : // Writes into buf the shortest "%.Ng" text that reads back as exactly the
    5117              : // finite double v, for float values and float keys: It tries 15, 16 and 17
    5118              : // digits, and 1 to 14 first for a subnormal (5e-324 is "5e-324").
    5119          182 : static void format_shortest_double(double v,
    5120              :                                    char buf[static CYAML_FLOAT_KEY_BUF_LEN]) {
    5121          182 :   if (v > -DBL_MIN && v < DBL_MIN && v != 0.0) {
    5122          246 :     for (int prec = 1; prec < 15; prec++) {
    5123          242 :       snprintf(buf, CYAML_FLOAT_KEY_BUF_LEN, "%.*g", prec, v);
    5124          242 :       if (strtod(buf, NULL) == v) return;
    5125              :     }
    5126              :   }
    5127          144 :   snprintf(buf, CYAML_FLOAT_KEY_BUF_LEN, "%.15g", v);
    5128          144 :   if (strtod(buf, NULL) == v) return;
    5129           12 :   snprintf(buf, CYAML_FLOAT_KEY_BUF_LEN, "%.16g", v);
    5130           12 :   if (strtod(buf, NULL) == v) return;
    5131            8 :   snprintf(buf, CYAML_FLOAT_KEY_BUF_LEN, "%.17g", v);
    5132              : }
    5133              : 
    5134              : // Writes the canonical key text of a float into buf, so equal numbers make the
    5135              : // same dictionary key: The shortest round-trip digits with no ".0" (so the keys
    5136              : // 1.0 and 1 are the same), ".nan", ".inf", "-.inf", and "0" for both zeros.
    5137              : // Every such text parses back to a value with the same text, which lets the
    5138              : // serializer write it unquoted. Runs in the C locale.
    5139           92 : static void format_float_key(double v,
    5140              :                              char buf[static CYAML_FLOAT_KEY_BUF_LEN]) {
    5141           92 :   if (__builtin_isnan(v)) {
    5142            6 :     memcpy(buf, ".nan", sizeof(".nan"));
    5143            6 :     return;
    5144              :   }
    5145           86 :   if (__builtin_isinf(v)) {
    5146           14 :     if (v > 0)
    5147            8 :       memcpy(buf, ".inf", sizeof(".inf"));
    5148              :     else
    5149            6 :       memcpy(buf, "-.inf", sizeof("-.inf"));
    5150           14 :     return;
    5151              :   }
    5152           72 :   if (v == 0.0) {
    5153            4 :     memcpy(buf, "0", sizeof("0"));
    5154            4 :     return;
    5155              :   }
    5156           68 :   format_shortest_double(v, buf);
    5157              : }
    5158              : 
    5159              : // Gives the canonical key text of key_node, since every dictionary key is a
    5160              : // string; every key site of the parser calls it. A scalar gives its canonical
    5161              : // text and a collection its compact canonical flow text, so equal structures
    5162              : // collide whatever their insertion order. With consume it disposes of key_node
    5163              : // through parse_discard() and moves a string out instead of copying it (not
    5164              : // from an anchored node, and only when both use ctx->mp); without consume
    5165              : // key_node stays as it was. Collection text is limited by
    5166              : // CYAML_MAX_CANONICAL_KEY_LEN and charged to the amplification budget. Every
    5167              : // failure sets a parse error.
    5168        50291 : static char *node_to_dict_key_string_ex(parse_ctx *ctx, cyaml_node *key_node,
    5169              :                                         const char *context_label,
    5170              :                                         bool consume) {
    5171        50291 :   char *key_str = NULL;
    5172        50291 :   switch (key_node->type) {
    5173        29647 :     case CYAML_STRING:
    5174        29647 :       if (consume && !key_node->anchored && key_node->m_procs == ctx->mp &&
    5175        29603 :           key_node->value.string) {
    5176        29603 :         key_str = key_node->value.string;
    5177        29603 :         key_node->value.string = NULL;
    5178              :       } else {
    5179           44 :         key_str = ccol_strdup(ctx->mp, key_node->value.string);
    5180              :       }
    5181              :       break;
    5182           72 :     case CYAML_INTEGER: {
    5183           72 :       char tmp[32];
    5184           72 :       snprintf(tmp, sizeof(tmp), "%lld", key_node->value.integer);
    5185           72 :       key_str = ccol_strdup(ctx->mp, tmp);
    5186           72 :       break;
    5187              :     }
    5188           54 :     case CYAML_FLOAT: {
    5189           54 :       char tmp[CYAML_FLOAT_KEY_BUF_LEN];
    5190           54 :       format_float_key(key_node->value.number, tmp);
    5191           54 :       key_str = ccol_strdup(ctx->mp, tmp);
    5192           54 :       break;
    5193              :     }
    5194        20141 :     case CYAML_NULL:
    5195        20141 :       key_str = ccol_strdup(ctx->mp, "null");
    5196        20141 :       break;
    5197            5 :     case CYAML_BOOL:
    5198            5 :       key_str =
    5199            5 :           ccol_strdup(ctx->mp, key_node->value.boolean ? "true" : "false");
    5200            5 :       break;
    5201          372 :     case CYAML_LIST:
    5202              :     case CYAML_DICTIONARY:
    5203              :     default: {
    5204          372 :       bool too_long = false;
    5205          372 :       key_str = serialize_flow_canonical(key_node, &too_long);
    5206          372 :       if (too_long) {
    5207            7 :         parse_err(ctx,
    5208              :                   "canonical form of a non-scalar key in %s exceeds %d "
    5209              :                   "bytes at position %zu",
    5210              :                   context_label, CYAML_MAX_CANONICAL_KEY_LEN, ctx->pos);
    5211          365 :       } else if (!key_str) {
    5212            1 :         parse_err(ctx,
    5213              :                   "out of memory canonicalizing non-scalar key in %s "
    5214              :                   "at position %zu",
    5215              :                   context_label, ctx->pos);
    5216              :       } else {
    5217          364 :         parse_amp_enter();
    5218          364 :         bool charged =
    5219          364 :             parse_bytes_charge(strlen(key_str) + 1 + CYAML_ALLOC_OVERHEAD);
    5220          364 :         parse_amp_leave();
    5221          364 :         if (!charged) {
    5222            0 :           parse_err(ctx,
    5223              :                     "canonical form of a non-scalar key in %s exceeded the "
    5224              :                     "%s memory limit at position %zu",
    5225              :                     context_label,
    5226            0 :                     parse_amp_limit_hit ? "alias expansion" : "document",
    5227              :                     ctx->pos);
    5228            0 :           ccol__mem_free(ctx->mp, key_str);
    5229            0 :           key_str = NULL;
    5230              :         }
    5231              :       }
    5232          372 :       break;
    5233              :     }
    5234              :   }
    5235        50291 :   if (!key_str && !ctx->error[0]) {
    5236            2 :     parse_err(ctx,
    5237              :               "out of memory converting a scalar key to a dictionary "
    5238              :               "key string in %s at position %zu",
    5239              :               context_label, ctx->pos);
    5240              :   }
    5241        50291 :   if (consume) parse_discard(key_node);
    5242        50289 :   return key_str;
    5243              : }
    5244              : 
    5245              : // Gives the key text of key_node and disposes of it,
    5246              : // node_to_dict_key_string_ex() with consume set, for the key sites that don't
    5247              : // keep the node.
    5248        49959 : static char *node_to_dict_key_string(parse_ctx *ctx, cyaml_node *key_node,
    5249              :                                      const char *context_label) {
    5250        23908 :   return node_to_dict_key_string_ex(ctx, key_node, context_label, true);
    5251              : }
    5252              : 
    5253              : // Runs a flow-dictionary frame, '{' key ':' value (',' ...)* '}', into a
    5254              : // CYAML_DICTIONARY. Keys may be any node and are stored as canonical text. The
    5255              : // key and the value are descents. "{? key: value}" is accepted, "{key}" and
    5256              : // "{key:}" give null values, and merge entries wait in f->u.fd.merges until the
    5257              : // mapping ends, so they never replace each other or an ordinary "<<" key.
    5258        39838 : static pstep pfd_step(parse_ctx *ctx, pframe *f, preq *rq) {
    5259        39838 :   const int indent = f->u.fd.indent;
    5260        39838 :   cyaml_node *key_node = NULL;
    5261        39838 :   cyaml_node *val = NULL;
    5262        39838 :   char *key_str = NULL;
    5263              : 
    5264        39838 :   switch (f->state) {
    5265        14688 :     case FDS_AFTER_KEY:
    5266        14688 :       goto after_key;
    5267        10518 :     case FDS_AFTER_VALUE:
    5268        10518 :       goto after_value;
    5269              :     default:
    5270        14632 :       break;
    5271              :   }
    5272              : 
    5273        14632 :   ctx->pos++;
    5274        14637 :   if (!flow_skip_ws(ctx, indent)) return PSTEP_FAIL;
    5275              : 
    5276        14627 :   f->u.fd.map = (cyaml_node *)cyaml_create_dictionary_interned(ctx->mp);
    5277        14627 :   if (!f->u.fd.map) return PSTEP_FAIL;
    5278              : 
    5279        14591 :   if (!at_end(ctx) && cur(ctx) == '}') {
    5280            8 :     ctx->pos++;
    5281            8 :     goto done;
    5282              :   }
    5283              : 
    5284        18825 :   while (1) {
    5285        16704 :     if (!flow_skip_ws(ctx, indent)) return PSTEP_FAIL;
    5286        16704 :     if (at_end(ctx)) {
    5287            6 :       parse_err(ctx, "unterminated flow dictionary");
    5288            6 :       return PSTEP_FAIL;
    5289              :     }
    5290        16698 :     if (cur(ctx) == '}') {
    5291            4 :       ctx->pos++;
    5292            4 :       if (f->u.fd.merge_count &&
    5293            0 :           !merge_entries_finish(ctx, f->u.fd.map, &f->u.fd.merges,
    5294              :                                 &f->u.fd.merge_count, &f->u.fd.merge_cap))
    5295              :         return PSTEP_FAIL;
    5296            4 :       goto done;
    5297              :     }
    5298              : 
    5299        16694 :     f->u.fd.is_explicit_key_indicator = false;
    5300        16694 :     if (cur(ctx) == '?') {
    5301           23 :       char nx = (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    5302           23 :       if (nx == ' ' || nx == '\t' || nx == '\n' || nx == '\r' || nx == '\0')
    5303           22 :         f->u.fd.is_explicit_key_indicator = true;
    5304              :     }
    5305              : 
    5306        16694 :     f->u.fd.implicit_key_is_merge_candidate = false;
    5307        16694 :     f->u.fd.explicit_key_is_merge_candidate = false;
    5308        16694 :     if (f->u.fd.is_explicit_key_indicator) {
    5309           22 :       ctx->pos++;
    5310           22 :       if (!flow_skip_ws(ctx, indent)) return PSTEP_FAIL;
    5311           22 :       if (!at_end(ctx) &&
    5312           22 :           (cur(ctx) == ':' || cur(ctx) == ',' || cur(ctx) == '}')) {
    5313            3 :         key_node = node_alloc(CYAML_NULL, ctx->mp);
    5314            3 :         goto have_key_node;
    5315              :       }
    5316           19 :       f->u.fd.explicit_key_is_merge_candidate =
    5317           19 :           explicit_key_peek_is_merge_candidate(ctx, indent, true);
    5318              :     } else {
    5319        16672 :       f->u.fd.implicit_key_is_merge_candidate =
    5320        16672 :           explicit_key_peek_is_merge_candidate(ctx, indent, true);
    5321              :     }
    5322        16691 :     preq_node(rq, indent, true, false, false, false, false, NULL);
    5323        16691 :     f->state = FDS_AFTER_KEY;
    5324        16691 :     return PSTEP_DESCEND;
    5325        14688 :   after_key:
    5326        14688 :     key_node = f->child;
    5327        14688 :     f->child = NULL;
    5328        14688 :   have_key_node:
    5329        14691 :     if (!key_node) return PSTEP_FAIL;
    5330              : 
    5331        14691 :     key_str = node_to_dict_key_string(ctx, key_node, "flow dictionary");
    5332        14691 :     if (!key_str) return PSTEP_FAIL;
    5333        29382 :     f->u.fd.is_merge_candidate = f->u.fd.is_explicit_key_indicator
    5334           22 :                                      ? f->u.fd.explicit_key_is_merge_candidate
    5335        14691 :                                      : f->u.fd.implicit_key_is_merge_candidate;
    5336              : 
    5337        14691 :     if (!flow_skip_ws(ctx, indent)) {
    5338            0 :       ccol__mem_free(ctx->mp, key_str);
    5339            0 :       return PSTEP_FAIL;
    5340              :     }
    5341        14691 :     if (!at_end(ctx) && cur(ctx) == ':') {
    5342        14678 :       ctx->pos++;
    5343        14678 :       if (!flow_skip_ws(ctx, indent)) {
    5344            0 :         ccol__mem_free(ctx->mp, key_str);
    5345            0 :         return PSTEP_FAIL;
    5346              :       }
    5347        14678 :       if (!at_end(ctx) && (cur(ctx) == ',' || cur(ctx) == '}')) {
    5348            5 :         val = node_alloc(CYAML_NULL, ctx->mp);
    5349              :       } else {
    5350        14673 :         f->u.fd.key_str = key_str;
    5351        14673 :         preq_node(rq, indent, true, false, false, false, false, NULL);
    5352        14673 :         f->state = FDS_AFTER_VALUE;
    5353        14673 :         return PSTEP_DESCEND;
    5354        10518 :       after_value:
    5355        10518 :         key_str = f->u.fd.key_str;
    5356        10518 :         f->u.fd.key_str = NULL;
    5357        10518 :         val = f->child;
    5358        10518 :         f->child = NULL;
    5359              :       }
    5360           13 :     } else if (!at_end(ctx) && (cur(ctx) == ',' || cur(ctx) == '}')) {
    5361           10 :       val = node_alloc(CYAML_NULL, ctx->mp);
    5362              :     } else {
    5363            3 :       parse_err(ctx, "expected ':' after flow dictionary key at position %zu",
    5364              :                 ctx->pos);
    5365            3 :       ccol__mem_free(ctx->mp, key_str);
    5366            3 :       return PSTEP_FAIL;
    5367              :     }
    5368        10533 :     if (!val) {
    5369            0 :       ccol__mem_free(ctx->mp, key_str);
    5370            0 :       return PSTEP_FAIL;
    5371              :     }
    5372              : 
    5373        10533 :     if (f->u.fd.is_merge_candidate && strcmp(key_str, "<<") == 0) {
    5374          517 :       ccol__mem_free(ctx->mp, key_str);
    5375          517 :       if (!merge_entry_push(ctx, &f->u.fd.merges, &f->u.fd.merge_count,
    5376              :                             &f->u.fd.merge_cap, val,
    5377          517 :                             chashmap_size(f->u.fd.map->value.dictionary)))
    5378              :         return PSTEP_FAIL;
    5379              :     } else {
    5380        10016 :       ccol_retval r =
    5381        10016 :           dictionary_set_impl((cyaml)f->u.fd.map, key_str, (cyaml)val);
    5382        10016 :       ccol__mem_free(ctx->mp, key_str);
    5383        10016 :       if (r != ccol_success) return PSTEP_FAIL;
    5384              :     }
    5385              : 
    5386        10502 :     if (!flow_skip_ws(ctx, indent)) return PSTEP_FAIL;
    5387        10501 :     if (at_end(ctx)) {
    5388            0 :       parse_err(ctx, "unterminated flow dictionary");
    5389            0 :       return PSTEP_FAIL;
    5390              :     }
    5391        10501 :     if (cur(ctx) == '}') {
    5392         8377 :       ctx->pos++;
    5393         8716 :       if (f->u.fd.merge_count &&
    5394          339 :           !merge_entries_finish(ctx, f->u.fd.map, &f->u.fd.merges,
    5395              :                                 &f->u.fd.merge_count, &f->u.fd.merge_cap))
    5396              :         return PSTEP_FAIL;
    5397         8346 :       goto done;
    5398              :     }
    5399         2124 :     if (cur(ctx) != ',') {
    5400            3 :       parse_err(ctx, "expected ',' or '}' in flow dictionary at position %zu",
    5401              :                 ctx->pos);
    5402            3 :       return PSTEP_FAIL;
    5403              :     }
    5404         2121 :     ctx->pos++;
    5405              :   }
    5406              : 
    5407         8358 : done:
    5408         8358 :   f->result = f->u.fd.map;
    5409         8358 :   f->u.fd.map = NULL;
    5410         8358 :   return PSTEP_DONE;
    5411              : }
    5412              : 
    5413              : // Parses a flow dictionary as an independent walk, for the same speculative
    5414              : // key read as parse_flow_list(). Gives the dictionary, or NULL on failure.
    5415           22 : static cyaml_node *parse_flow_dictionary(parse_ctx *ctx, int indent) {
    5416           22 :   preq rq;
    5417           22 :   preq_flow(&rq, false, indent);
    5418           22 :   return parse_drive(ctx, &rq);
    5419              : }
    5420              : 
    5421              : // Dispatches one node: The decision tree the parser runs for every node,
    5422              : // suspended at its descents (an anchored value, a tagged value, a collection,
    5423              : // a flow collection that may become a key). It's inlined into the driver, since
    5424              : // half of all parse steps are node dispatches.
    5425              : //
    5426              : // The request carries the context: indent (-1 at the root, in flow, or not
    5427              : // fixed yet), in_flow, seq_ok_at_indent (indent is a mapping's, so a "- " at
    5428              : // exactly indent is its value), allow_inline_map (a scalar followed by ':' may
    5429              : // open a new block mapping here; false only for the same-line value of an
    5430              : // implicit key, so "a: b: c" is an error), had_anchor and had_tag (an enclosing
    5431              : // property already decorates this node, so a second one is an error), and
    5432              : // resolved_tag (the enclosing tag, which decides the type where the content is
    5433              : // built). The '&', '!' and '*' branches pass these on.
    5434              : //
    5435              : // The branches: A document marker or a column-0 BOM is never content. "&a key:"
    5436              : // and "!t key:" decorate only the key, so they try the key reader first. A
    5437              : // property alone on its line takes a value only from a more indented line (or a
    5438              : // "- " at a mapping's indent), else the node is empty and still typed by the
    5439              : // tag. A collection opener right against a property, a "- " after a property
    5440              : // on the same line, two anchors or two tags, and a property on an alias are
    5441              : // errors. An alias is cloned with only the levels left below ctx->depth. A
    5442              : // flow collection or a quoted scalar followed by ':' on the same line becomes
    5443              : // the first key of a block mapping. Anchors are stored on the node itself, and
    5444              : // the tag text is freed here in every case.
    5445       471722 : static pstep pni_step(parse_ctx *ctx, pframe *f, preq *rq) {
    5446       471722 :   const int indent = f->u.n.indent;
    5447       471722 :   const bool in_flow = f->u.n.in_flow;
    5448       471722 :   const bool seq_ok_at_indent = f->u.n.seq_ok_at_indent;
    5449       471722 :   const bool allow_inline_map = f->u.n.allow_inline_map;
    5450       471722 :   const bool had_anchor = f->u.n.had_anchor;
    5451       471722 :   const bool had_tag = f->u.n.had_tag;
    5452       471722 :   const char *const resolved_tag = f->u.n.resolved_tag;
    5453              : 
    5454       471722 :   switch (f->state) {
    5455         6777 :     case NS_AFTER_ANCHOR_VALUE:
    5456         6777 :       goto after_anchor_value;
    5457        14981 :     case NS_AFTER_TAG_VALUE:
    5458        14981 :       goto after_tag_value;
    5459        29034 :     case NS_AFTER_COLLECTION:
    5460        29034 :       goto after_collection;
    5461        54699 :     case NS_AFTER_FLOW_COLL:
    5462        54699 :       goto after_flow_coll;
    5463              :     default:
    5464       366231 :       break;
    5465              :   }
    5466              : 
    5467              :   {
    5468       366231 :     if (!in_flow)
    5469        73794 :       skip_ws_comments(ctx);
    5470              :     else
    5471              :       skip_inline_ws(ctx);
    5472              : 
    5473       366230 :     if (at_end(ctx)) {
    5474            7 :       if (!in_flow) return pni_finish(f, node_alloc(CYAML_NULL, ctx->mp));
    5475            7 :       parse_err(ctx, "unexpected end of input in flow context at position %zu",
    5476              :                 ctx->pos);
    5477            7 :       return PSTEP_FAIL;
    5478              :     }
    5479              : 
    5480       366223 :     if (at_col0_bom(ctx)) {
    5481            2 :       parse_err(ctx,
    5482              :                 "byte order mark inside a document at position %zu; a byte "
    5483              :                 "order mark may only precede a document",
    5484              :                 ctx->pos);
    5485            2 :       return PSTEP_FAIL;
    5486              :     }
    5487              : 
    5488       366224 :     if (in_flow && at_doc_marker(ctx)) {
    5489            2 :       parse_err(ctx,
    5490              :                 "a document marker cannot appear inside an unclosed "
    5491              :                 "flow collection at position %zu",
    5492              :                 ctx->pos);
    5493            2 :       return PSTEP_FAIL;
    5494              :     }
    5495              : 
    5496       366222 :     char c = cur(ctx);
    5497              : 
    5498       366218 :     if (c == '&') {
    5499         9015 :       if (!in_flow && allow_inline_map) {
    5500          123 :         int col = current_col(ctx);
    5501          123 :         char *anchor_name = NULL;
    5502          123 :         char *key_str = NULL;
    5503          123 :         bool is_merge_candidate = false;
    5504          123 :         cyaml_node *anchor_value = NULL;
    5505          123 :         if (try_parse_scalar_dict_key(ctx, &anchor_name, &key_str,
    5506              :                                       &is_merge_candidate, &anchor_value)) {
    5507           41 :           if (!register_key_anchor(ctx, anchor_name, key_str, anchor_value)) {
    5508            3 :             ccol__mem_free(ctx->mp, key_str);
    5509           63 :             return PSTEP_FAIL;
    5510              :           }
    5511           38 :           f->u.n.pending_key = key_str;
    5512           38 :           preq_block_dict(rq, col, key_str, true, is_merge_candidate);
    5513           38 :           f->state = NS_AFTER_COLLECTION;
    5514           38 :           return PSTEP_DESCEND;
    5515              :         }
    5516           82 :         if (ctx->error[0]) return PSTEP_FAIL;
    5517              :       }
    5518              : 
    5519         8955 :       if (had_anchor) {
    5520            2 :         parse_err(ctx, "a node cannot carry two anchors at position %zu",
    5521              :                   ctx->pos);
    5522            2 :         return PSTEP_FAIL;
    5523              :       }
    5524              : 
    5525         8953 :       ctx->pos++;
    5526         8953 :       if (!parse_anchor_name(ctx, &f->u.n.name)) return PSTEP_FAIL;
    5527         8945 :       char *name = f->u.n.name;
    5528         8945 :       size_t after_name_pos = ctx->pos;
    5529         8945 :       skip_inline_ws(ctx);
    5530         8945 :       if (ctx->pos == after_name_pos && !at_end(ctx) &&
    5531          165 :           (cur(ctx) == '[' || cur(ctx) == '{' ||
    5532          154 :            (!in_flow &&
    5533          154 :             (cur(ctx) == ',' || cur(ctx) == ']' || cur(ctx) == '}')))) {
    5534           97 :         parse_err(ctx,
    5535              :                   "unexpected '%s' directly after anchor name at "
    5536              :                   "position %zu",
    5537           97 :                   cyaml_echo_c(cur(ctx)), ctx->pos);
    5538           97 :         pni_release_name(ctx, f);
    5539           97 :         return PSTEP_FAIL;
    5540              :       }
    5541              : 
    5542         8842 :       cyaml_node *n;
    5543         8842 :       if (!in_flow && rest_of_line_is_blank(ctx)) {
    5544           63 :         skip_ws_comments(ctx);
    5545          126 :         bool is_value_col =
    5546           63 :             !at_end(ctx) && at_block_value_col(ctx, indent, seq_ok_at_indent);
    5547           63 :         if (at_end(ctx) || !is_value_col || at_doc_marker(ctx)) {
    5548           14 :           char *empty = ccol_strdup(ctx->mp, "");
    5549           14 :           n = empty ? finalize_scalar_node(ctx, empty, resolved_tag, true)
    5550              :                     : NULL;
    5551              :         } else {
    5552           49 :           preq_node(rq, indent, in_flow, seq_ok_at_indent, true, true, had_tag,
    5553              :                     resolved_tag);
    5554           49 :           f->state = NS_AFTER_ANCHOR_VALUE;
    5555           49 :           return PSTEP_DESCEND;
    5556              :         }
    5557         7770 :       } else if (in_flow && rest_of_line_is_blank(ctx)) {
    5558            9 :         if (!flow_skip_ws(ctx, indent)) {
    5559            2 :           pni_release_name(ctx, f);
    5560            2 :           return PSTEP_FAIL;
    5561              :         }
    5562            7 :         preq_node(rq, indent, in_flow, seq_ok_at_indent, allow_inline_map, true,
    5563              :                   had_tag, resolved_tag);
    5564            7 :         f->state = NS_AFTER_ANCHOR_VALUE;
    5565            7 :         return PSTEP_DESCEND;
    5566         1015 :       } else if (!in_flow && at_bare_seq_indicator(ctx)) {
    5567            2 :         parse_err(ctx,
    5568              :                   "a block sequence cannot start on the same line as an "
    5569              :                   "anchor at position %zu",
    5570              :                   ctx->pos);
    5571            2 :         pni_release_name(ctx, f);
    5572            2 :         return PSTEP_FAIL;
    5573         2026 :       } else if (!in_flow && cur(ctx) == '&') {
    5574            2 :         parse_err(ctx, "a node cannot carry two anchors at position %zu",
    5575              :                   ctx->pos);
    5576            2 :         pni_release_name(ctx, f);
    5577            2 :         return PSTEP_FAIL;
    5578         1011 :       } else if (!in_flow && cur(ctx) == '*') {
    5579            3 :         parse_err(ctx, "an alias cannot carry an anchor or tag at position %zu",
    5580              :                   ctx->pos);
    5581            3 :         pni_release_name(ctx, f);
    5582            3 :         return PSTEP_FAIL;
    5583              :       } else {
    5584         8769 :         preq_node(rq, indent, in_flow, seq_ok_at_indent, allow_inline_map, true,
    5585              :                   had_tag, resolved_tag);
    5586         8769 :         f->state = NS_AFTER_ANCHOR_VALUE;
    5587         8769 :         return PSTEP_DESCEND;
    5588              :       }
    5589           14 :       goto anchor_have_value;
    5590         6777 :     after_anchor_value:
    5591         6777 :       n = f->child;
    5592         6777 :       f->child = NULL;
    5593         6777 :       name = f->u.n.name;
    5594         6791 :     anchor_have_value:
    5595         6791 :       if (!n) {
    5596            0 :         pni_release_name(ctx, f);
    5597            0 :         return PSTEP_FAIL;
    5598              :       }
    5599         6791 :       if (!anchors_store(ctx, name, n)) {
    5600           13 :         cyaml__destroy((cyaml)n);
    5601           13 :         pni_release_name(ctx, f);
    5602           13 :         return PSTEP_FAIL;
    5603              :       }
    5604         6778 :       pni_release_name(ctx, f);
    5605         6778 :       return pni_finish(f, n);
    5606              :     }
    5607              : 
    5608       357207 :     if (c == '*') {
    5609         3471 :       if (!in_flow && allow_inline_map) {
    5610          141 :         int col = current_col(ctx);
    5611          141 :         char *anchor_name = NULL;
    5612          141 :         char *key_str = NULL;
    5613          141 :         if (try_parse_scalar_dict_key(ctx, &anchor_name, &key_str, NULL,
    5614              :                                       NULL)) {
    5615            6 :           ccol__mem_free(ctx->mp, anchor_name);
    5616            6 :           f->u.n.pending_key = key_str;
    5617            6 :           preq_block_dict(rq, col, key_str, true, false);
    5618            6 :           f->state = NS_AFTER_COLLECTION;
    5619          107 :           return PSTEP_DESCEND;
    5620              :         }
    5621          135 :         if (ctx->error[0]) return PSTEP_FAIL;
    5622              :       }
    5623              : 
    5624         3364 :       if (had_anchor || had_tag) {
    5625            0 :         parse_err(ctx, "an alias cannot carry an anchor or tag at position %zu",
    5626              :                   ctx->pos);
    5627            0 :         return PSTEP_FAIL;
    5628              :       }
    5629              : 
    5630         3364 :       const size_t alias_start = ctx->pos;
    5631         3364 :       ctx->pos++;
    5632         3364 :       char *name = NULL;
    5633         3364 :       if (!parse_anchor_name(ctx, &name)) return PSTEP_FAIL;
    5634         3348 :       cyaml_node *anchored = anchors_lookup(ctx, name);
    5635         3348 :       if (!anchored) {
    5636          190 :         parse_err(ctx, "unknown alias '*%s' at position %zu", cyaml_echo(name),
    5637              :                   alias_start);
    5638           95 :         ccol__mem_free(ctx->mp, name);
    5639           95 :         return PSTEP_FAIL;
    5640              :       }
    5641         3253 :       bool too_deep = false;
    5642         3253 :       size_t height = 0;
    5643         6506 :       cyaml_node *clone = parse_clone_levels(
    5644         3253 :           anchored, CYAML_MAX_NESTING_DEPTH - ctx->depth, &too_deep, &height);
    5645         3253 :       if (clone && ctx->depth + height > ctx->peak_depth)
    5646          650 :         ctx->peak_depth = ctx->depth + height;
    5647           36 :       if (!clone && too_deep)
    5648            8 :         parse_err(ctx,
    5649              :                   "alias '*%s' expansion exceeds the maximum nesting depth "
    5650              :                   "(%d) at position %zu",
    5651            4 :                   cyaml_echo(name), CYAML_MAX_NESTING_DEPTH, ctx->pos);
    5652           32 :       else if (!clone && parse_amp_limit_hit)
    5653           10 :         parse_err(ctx,
    5654              :                   "alias '*%s' expansion exceeded the %zu-node, %zu-byte "
    5655              :                   "alias expansion memory limit at position %zu; check for "
    5656              :                   "exponential anchor/alias nesting",
    5657            5 :                   cyaml_echo(name), (size_t)CYAML_PARSE_NODE_FLOOR,
    5658              :                   (size_t)CYAML_PARSE_BYTE_FLOOR, ctx->pos);
    5659           27 :       else if (!clone && parse_node_budget_exhausted)
    5660            0 :         parse_err(ctx,
    5661              :                   "alias '*%s' expansion exceeded the %zu node-allocation "
    5662              :                   "limit at position %zu; check for exponential anchor/alias "
    5663              :                   "nesting",
    5664            0 :                   cyaml_echo(name), parse_node_limit, ctx->pos);
    5665           27 :       else if (!clone && parse_byte_budget_exhausted)
    5666            6 :         parse_err(ctx,
    5667              :                   "alias '*%s' expansion exceeded the %zu-byte document memory "
    5668              :                   "limit at position %zu; check for exponential anchor/alias "
    5669              :                   "nesting",
    5670            3 :                   cyaml_echo(name), parse_byte_limit, ctx->pos);
    5671         3253 :       ccol__mem_free(ctx->mp, name);
    5672         3289 :       return pni_finish(f, clone);
    5673              :     }
    5674              : 
    5675       353736 :     if (c == '!') {
    5676        17575 :       if (!in_flow && allow_inline_map) {
    5677         4482 :         int col = current_col(ctx);
    5678         4482 :         char *anchor_name = NULL;
    5679         4482 :         char *key_str = NULL;
    5680         4482 :         cyaml_node *anchor_value = NULL;
    5681         4482 :         bool is_merge_candidate = false;
    5682         4482 :         if (try_parse_scalar_dict_key(ctx, &anchor_name, &key_str,
    5683              :                                       &is_merge_candidate, &anchor_value)) {
    5684           28 :           if (!register_key_anchor(ctx, anchor_name, key_str, anchor_value)) {
    5685            0 :             ccol__mem_free(ctx->mp, key_str);
    5686          167 :             return PSTEP_FAIL;
    5687              :           }
    5688           28 :           f->u.n.pending_key = key_str;
    5689           28 :           preq_block_dict(rq, col, key_str, true, is_merge_candidate);
    5690           28 :           f->state = NS_AFTER_COLLECTION;
    5691           28 :           return PSTEP_DESCEND;
    5692              :         }
    5693         4454 :         if (ctx->error[0]) return PSTEP_FAIL;
    5694              :       }
    5695              : 
    5696        17408 :       if (had_tag) {
    5697            4 :         parse_err(ctx, "a node cannot carry two tags at position %zu",
    5698              :                   ctx->pos);
    5699            4 :         return PSTEP_FAIL;
    5700              :       }
    5701              : 
    5702        17404 :       if (!parse_tag_token(ctx, &f->u.n.tag)) return PSTEP_FAIL;
    5703        17402 :       char *tag = f->u.n.tag;
    5704        17402 :       size_t after_tag_pos = ctx->pos;
    5705        17402 :       skip_inline_ws(ctx);
    5706        17402 :       if (ctx->pos == after_tag_pos && !at_end(ctx) &&
    5707         4170 :           (cur(ctx) == '[' || cur(ctx) == '{' ||
    5708         4158 :            (!in_flow &&
    5709         4158 :             (cur(ctx) == ',' || cur(ctx) == ']' || cur(ctx) == '}')))) {
    5710           10 :         parse_err(ctx, "unexpected '%s' directly after tag at position %zu",
    5711           10 :                   cyaml_echo_c(cur(ctx)), ctx->pos);
    5712           10 :         pni_release_tag(ctx, f);
    5713           10 :         return PSTEP_FAIL;
    5714              :       }
    5715        17392 :       if (ctx->pos == after_tag_pos && !at_end(ctx) && cur(ctx) != '\n' &&
    5716           94 :           cur(ctx) != '\r' && cur(ctx) != '#' && cur(ctx) != '!' &&
    5717           91 :           cur(ctx) != '&' && cur(ctx) != '*' &&
    5718            4 :           !(in_flow &&
    5719            4 :             (cur(ctx) == ',' || cur(ctx) == ']' || cur(ctx) == '}'))) {
    5720           86 :         parse_err(ctx,
    5721              :                   "tag must be separated from its content by whitespace at "
    5722              :                   "position %zu",
    5723              :                   ctx->pos);
    5724           86 :         pni_release_tag(ctx, f);
    5725           86 :         return PSTEP_FAIL;
    5726              :       }
    5727              : 
    5728        17306 :       cyaml_node *n;
    5729        17306 :       if (!in_flow && rest_of_line_is_blank(ctx)) {
    5730         4069 :         skip_ws_comments(ctx);
    5731         8138 :         bool is_value_col =
    5732         4069 :             !at_end(ctx) && at_block_value_col(ctx, indent, seq_ok_at_indent);
    5733         4069 :         if (at_end(ctx) || !is_value_col || at_doc_marker(ctx)) {
    5734           20 :           char *empty = ccol_strdup(ctx->mp, "");
    5735           20 :           n = empty ? finalize_scalar_node(ctx, empty, tag, true) : NULL;
    5736              :         } else {
    5737         4049 :           preq_node(rq, indent, in_flow, seq_ok_at_indent, true, had_anchor,
    5738              :                     true, tag);
    5739         4049 :           f->state = NS_AFTER_TAG_VALUE;
    5740         4049 :           return PSTEP_DESCEND;
    5741              :         }
    5742        12579 :       } else if (in_flow && rest_of_line_is_blank(ctx)) {
    5743            7 :         if (!flow_skip_ws(ctx, indent)) {
    5744            2 :           pni_release_tag(ctx, f);
    5745            2 :           return PSTEP_FAIL;
    5746              :         }
    5747            5 :         preq_node(rq, indent, in_flow, seq_ok_at_indent, allow_inline_map,
    5748              :                   had_anchor, true, tag);
    5749            5 :         f->state = NS_AFTER_TAG_VALUE;
    5750            5 :         return PSTEP_DESCEND;
    5751          658 :       } else if (!in_flow && at_bare_seq_indicator(ctx)) {
    5752            2 :         parse_err(ctx,
    5753              :                   "a block sequence cannot start on the same line as a "
    5754              :                   "tag at position %zu",
    5755              :                   ctx->pos);
    5756            2 :         pni_release_tag(ctx, f);
    5757            2 :         return PSTEP_FAIL;
    5758         1312 :       } else if (!in_flow && cur(ctx) == '!') {
    5759            1 :         parse_err(ctx, "a node cannot carry two tags at position %zu",
    5760              :                   ctx->pos);
    5761            1 :         pni_release_tag(ctx, f);
    5762            1 :         return PSTEP_FAIL;
    5763          655 :       } else if (!in_flow && cur(ctx) == '*') {
    5764            7 :         parse_err(ctx, "an alias cannot carry an anchor or tag at position %zu",
    5765              :                   ctx->pos);
    5766            7 :         pni_release_tag(ctx, f);
    5767            7 :         return PSTEP_FAIL;
    5768              :       } else {
    5769        13220 :         preq_node(rq, indent, in_flow, seq_ok_at_indent, allow_inline_map,
    5770              :                   had_anchor, true, tag);
    5771        13220 :         f->state = NS_AFTER_TAG_VALUE;
    5772        13220 :         return PSTEP_DESCEND;
    5773              :       }
    5774           20 :       goto tag_have_value;
    5775        14981 :     after_tag_value:
    5776        14981 :       n = f->child;
    5777        14981 :       f->child = NULL;
    5778        15001 :     tag_have_value:
    5779        15001 :       if (!n) {
    5780            5 :         pni_release_tag(ctx, f);
    5781            5 :         return PSTEP_FAIL;
    5782              :       }
    5783              : 
    5784        14996 :       pni_release_tag(ctx, f);
    5785        14996 :       return pni_finish(f, n);
    5786              :     }
    5787              : 
    5788       336161 :     if (c == '[' || c == '{') {
    5789        84464 :       f->u.n.col = current_col(ctx);
    5790        84465 :       f->u.n.coll_start = ctx->pos;
    5791        84465 :       preq_flow(rq, c == '[', indent);
    5792        84465 :       f->state = NS_AFTER_FLOW_COLL;
    5793        84465 :       return PSTEP_DESCEND;
    5794        54699 :     after_flow_coll:;
    5795        54699 :       cyaml_node *coll = f->child;
    5796        54699 :       f->child = NULL;
    5797        54699 :       if (!coll) return PSTEP_FAIL;
    5798              : 
    5799        54699 :       bool spans_multiple_lines = span_crosses_newline(ctx, f->u.n.coll_start);
    5800        54696 :       if (!in_flow && !spans_multiple_lines) {
    5801              :         skip_inline_ws(ctx);
    5802        22493 :         if (!at_end(ctx) && cur(ctx) == ':') {
    5803           66 :           char after =
    5804           22 :               (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    5805           22 :           if (after == ' ' || after == '\t' || after == '\n' || after == '\r' ||
    5806              :               ctx->pos + 1 >= ctx->len) {
    5807           22 :             if (!allow_inline_map) {
    5808            1 :               parse_err(ctx,
    5809              :                         "mapping values are not allowed here "
    5810              :                         "(position %zu)",
    5811              :                         ctx->pos);
    5812            1 :               cyaml__destroy((cyaml)coll);
    5813            1 :               return PSTEP_FAIL;
    5814              :             }
    5815           21 :             if (!parse_key_fits_below_mapping(ctx, coll)) {
    5816            1 :               cyaml__destroy((cyaml)coll);
    5817            1 :               return PSTEP_FAIL;
    5818              :             }
    5819           20 :             char *key_str =
    5820           20 :                 node_to_dict_key_string(ctx, coll, "block dictionary");
    5821           20 :             if (!key_str) return PSTEP_FAIL;
    5822           19 :             f->u.n.pending_key = key_str;
    5823           19 :             preq_block_dict(rq, f->u.n.col, key_str, false, false);
    5824           19 :             f->state = NS_AFTER_COLLECTION;
    5825           19 :             return PSTEP_DESCEND;
    5826              :           }
    5827              :         }
    5828              :       }
    5829        54681 :       return pni_finish(f, finalize_collection_node(ctx, coll, resolved_tag));
    5830              :     }
    5831              : 
    5832       251697 :     if (c == '|' && !in_flow) {
    5833          286 :       ctx->pos++;
    5834          286 :       chomp_mode chomp;
    5835          286 :       int exp_indent;
    5836          286 :       if (!parse_block_scalar_header(ctx, &chomp, &exp_indent))
    5837              :         return PSTEP_FAIL;
    5838          279 :       char *s = NULL;
    5839          279 :       if (!parse_block_scalar_content(ctx, indent, chomp, exp_indent, &s))
    5840              :         return PSTEP_FAIL;
    5841          277 :       return pni_finish(f, finalize_scalar_node(ctx, s, resolved_tag, false));
    5842              :     }
    5843              : 
    5844       251411 :     if (c == '>' && !in_flow) {
    5845          249 :       ctx->pos++;
    5846          249 :       chomp_mode chomp;
    5847          249 :       int exp_indent;
    5848          249 :       if (!parse_block_scalar_header(ctx, &chomp, &exp_indent))
    5849              :         return PSTEP_FAIL;
    5850          246 :       char *s = NULL;
    5851          246 :       if (!parse_folded_scalar_content(ctx, indent, chomp, exp_indent, &s))
    5852              :         return PSTEP_FAIL;
    5853          243 :       return pni_finish(f, finalize_scalar_node(ctx, s, resolved_tag, false));
    5854              :     }
    5855              : 
    5856       251162 :     if (c == '-' && !in_flow) {
    5857        23403 :       if (ctx->pos + 1 < ctx->len) {
    5858        23402 :         char next = ctx->src[ctx->pos + 1];
    5859        23402 :         if (next == ' ' || next == '\t' || next == '\n' || next == '\r') {
    5860        23373 :           preq_block_list(rq, current_col(ctx));
    5861        23373 :           f->state = NS_AFTER_COLLECTION;
    5862        23373 :           return PSTEP_DESCEND;
    5863              :         }
    5864              :       } else {
    5865            1 :         preq_block_list(rq, current_col(ctx));
    5866            1 :         f->state = NS_AFTER_COLLECTION;
    5867            1 :         return PSTEP_DESCEND;
    5868              :       }
    5869              :     }
    5870              : 
    5871       227788 :     if (c == '?' && !in_flow) {
    5872          435 :       bool is_explicit_key = false;
    5873          435 :       if (ctx->pos + 1 < ctx->len) {
    5874          435 :         char next = ctx->src[ctx->pos + 1];
    5875          435 :         if (next == ' ' || next == '\t' || next == '\n' || next == '\r')
    5876              :           is_explicit_key = true;
    5877              :       } else {
    5878              :         is_explicit_key = true;
    5879              :       }
    5880              :       if (is_explicit_key) {
    5881          433 :         if (!allow_inline_map) {
    5882            3 :           parse_err(ctx,
    5883              :                     "mapping values are not allowed here "
    5884              :                     "(position %zu)",
    5885              :                     ctx->pos);
    5886            3 :           return PSTEP_FAIL;
    5887              :         }
    5888          430 :         preq_block_dict(rq, current_col(ctx), NULL, false, false);
    5889          430 :         f->state = NS_AFTER_COLLECTION;
    5890          430 :         return PSTEP_DESCEND;
    5891              :       }
    5892              :     }
    5893              : 
    5894       227355 :     if (c == '"') {
    5895         3992 :       int col = current_col(ctx);
    5896         3992 :       size_t quote_start = ctx->pos;
    5897         3992 :       char *s = NULL;
    5898         3992 :       if (!parse_double_quoted(ctx, &s)) return PSTEP_FAIL;
    5899         3707 :       if (!in_flow) {
    5900              :         skip_inline_ws(ctx);
    5901         1777 :         if (!at_end(ctx) && cur(ctx) == ':') {
    5902         4008 :           char after =
    5903         1336 :               (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    5904         1336 :           if (after == ' ' || after == '\t' || after == '\n' || after == '\r' ||
    5905              :               ctx->pos + 1 >= ctx->len) {
    5906         1336 :             if (span_crosses_newline(ctx, quote_start)) {
    5907           16 :               parse_err(ctx,
    5908              :                         "implicit keys cannot span multiple lines at "
    5909              :                         "position %zu",
    5910              :                         ctx->pos);
    5911           16 :               ccol__mem_free(ctx->mp, s);
    5912           16 :               return PSTEP_FAIL;
    5913              :             }
    5914         1320 :             if (!allow_inline_map) {
    5915            0 :               parse_err(ctx,
    5916              :                         "mapping values are not allowed here "
    5917              :                         "(position %zu)",
    5918              :                         ctx->pos);
    5919            0 :               ccol__mem_free(ctx->mp, s);
    5920            0 :               return PSTEP_FAIL;
    5921              :             }
    5922         1320 :             f->u.n.pending_key = s;
    5923         1320 :             preq_block_dict(rq, col, s, false, false);
    5924         1320 :             f->state = NS_AFTER_COLLECTION;
    5925         1320 :             return PSTEP_DESCEND;
    5926              :           }
    5927              :         }
    5928              :       }
    5929         2487 :       return pni_finish(f, finalize_scalar_node(ctx, s, resolved_tag, false));
    5930              :     }
    5931              : 
    5932              :     if (c == '\'') {
    5933         1184 :       int col = current_col(ctx);
    5934         1184 :       size_t quote_start = ctx->pos;
    5935         1184 :       char *s = NULL;
    5936         1184 :       if (!parse_single_quoted(ctx, &s)) return PSTEP_FAIL;
    5937         1178 :       if (!in_flow) {
    5938              :         skip_inline_ws(ctx);
    5939          174 :         if (!at_end(ctx) && cur(ctx) == ':') {
    5940           99 :           char after =
    5941           33 :               (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    5942           33 :           if (after == ' ' || after == '\t' || after == '\n' || after == '\r' ||
    5943              :               ctx->pos + 1 >= ctx->len) {
    5944           33 :             if (span_crosses_newline(ctx, quote_start)) {
    5945           14 :               parse_err(ctx,
    5946              :                         "implicit keys cannot span multiple lines at "
    5947              :                         "position %zu",
    5948              :                         ctx->pos);
    5949           14 :               ccol__mem_free(ctx->mp, s);
    5950           14 :               return PSTEP_FAIL;
    5951              :             }
    5952           19 :             if (!allow_inline_map) {
    5953            2 :               parse_err(ctx,
    5954              :                         "mapping values are not allowed here "
    5955              :                         "(position %zu)",
    5956              :                         ctx->pos);
    5957            2 :               ccol__mem_free(ctx->mp, s);
    5958            2 :               return PSTEP_FAIL;
    5959              :             }
    5960           17 :             f->u.n.pending_key = s;
    5961           17 :             preq_block_dict(rq, col, s, false, false);
    5962           17 :             f->state = NS_AFTER_COLLECTION;
    5963           17 :             return PSTEP_DESCEND;
    5964              :           }
    5965              :         }
    5966              :       }
    5967         1232 :       return pni_finish(f, finalize_scalar_node(ctx, s, resolved_tag, false));
    5968              :     }
    5969              : 
    5970              :     if (c == '#') {
    5971            5 :       parse_err(ctx,
    5972              :                 "unexpected '#' at position %zu (a comment must be "
    5973              :                 "preceded by whitespace)",
    5974              :                 ctx->pos);
    5975            5 :       return PSTEP_FAIL;
    5976              :     }
    5977              : 
    5978              :     if (c == '%' || c == '@' || c == '`') {
    5979           15 :       parse_err(ctx,
    5980              :                 "unexpected '%s' at position %zu (not a valid plain scalar "
    5981              :                 "start character)",
    5982           15 :                 cyaml_echo_c(c), ctx->pos);
    5983           15 :       return PSTEP_FAIL;
    5984              :     }
    5985              : 
    5986       222159 :     if (!in_flow && (c == ']' || c == '}' || c == ',')) {
    5987           28 :       parse_err(ctx,
    5988              :                 "unexpected '%s' at position %zu (a flow indicator cannot "
    5989              :                 "start a plain scalar)",
    5990           28 :                 cyaml_echo_c(c), ctx->pos);
    5991           28 :       return PSTEP_FAIL;
    5992              :     }
    5993              : 
    5994       205214 :     if (in_flow && !at_valid_flow_plain_scalar_start(ctx)) {
    5995            7 :       parse_err(ctx,
    5996              :                 "unexpected '%s' at position %zu (not a valid plain "
    5997              :                 "scalar in flow context)",
    5998            7 :                 cyaml_echo_c(c), ctx->pos);
    5999            7 :       return PSTEP_FAIL;
    6000              :     }
    6001              : 
    6002              :     {
    6003       222124 :       int col = current_col(ctx);
    6004       222123 :       char *s = NULL;
    6005       222123 :       bool hit_real_terminator = false;
    6006       444246 :       if (!parse_plain_scalar(ctx, in_flow, &s, &hit_real_terminator))
    6007              :         return PSTEP_FAIL;
    6008              : 
    6009       222020 :       if (!in_flow) {
    6010              :         skip_inline_ws(ctx);
    6011        16885 :         if (!at_end(ctx) && cur(ctx) == ':') {
    6012        32042 :           char after =
    6013        10681 :               (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    6014        10681 :           if (after == ' ' || after == '\t' || after == '\n' || after == '\r' ||
    6015              :               ctx->pos + 1 >= ctx->len) {
    6016        10681 :             if (!allow_inline_map) {
    6017           11 :               parse_err(ctx,
    6018              :                         "mapping values are not allowed here "
    6019              :                         "(position %zu)",
    6020              :                         ctx->pos);
    6021           11 :               ccol__mem_free(ctx->mp, s);
    6022           11 :               return PSTEP_FAIL;
    6023              :             }
    6024        10670 :             bool is_merge_candidate = strcmp(s, "<<") == 0;
    6025        10670 :             cyaml_node *typed = make_typed_scalar(ctx, s);
    6026        10669 :             if (!typed) {
    6027           20 :               parse_err(ctx,
    6028              :                         "out of memory typing dictionary key at position %zu",
    6029              :                         ctx->pos);
    6030           20 :               ccol__mem_free(ctx->mp, s);
    6031           20 :               return PSTEP_FAIL;
    6032              :             }
    6033        10649 :             char *canon_key =
    6034        10649 :                 node_to_dict_key_string(ctx, typed, "block dictionary");
    6035        10649 :             ccol__mem_free(ctx->mp, s);
    6036        10649 :             if (!canon_key) return PSTEP_FAIL;
    6037        10649 :             f->u.n.pending_key = canon_key;
    6038        10649 :             preq_block_dict(rq, col, canon_key, false, is_merge_candidate);
    6039        10649 :             f->state = NS_AFTER_COLLECTION;
    6040        10649 :             return PSTEP_DESCEND;
    6041              :           }
    6042              :         }
    6043              :       }
    6044              : 
    6045       211339 :       char *full = NULL;
    6046       211339 :       if (!parse_plain_scalar_multiline(ctx, in_flow, indent, s,
    6047              :                                         hit_real_terminator, &full))
    6048              :         return PSTEP_FAIL;
    6049              : 
    6050       222344 :       return pni_finish(f, finalize_scalar_node(ctx, full, resolved_tag, true));
    6051              :     }
    6052              :   }
    6053              : 
    6054        29034 : after_collection: {
    6055        29034 :   cyaml_node *coll = f->child;
    6056        29034 :   f->child = NULL;
    6057        29034 :   if (f->u.n.pending_key) {
    6058         9558 :     ccol__mem_free(ctx->mp, f->u.n.pending_key);
    6059         9557 :     f->u.n.pending_key = NULL;
    6060              :   }
    6061        29033 :   return pni_finish(f, finalize_collection_node(ctx, coll, resolved_tag));
    6062              : }
    6063              : }
    6064              : 
    6065              : // Runs a block-sequence frame: '-' entries at column f->u.bl.seq_indent, each
    6066              : // value a descent. A '-' followed only by a comment, or whose next content line
    6067              : // isn't more indented, is a null entry. A tab after the '-' is separation, but
    6068              : // a block collection after it fails. The value gets seq_indent as its indent,
    6069              : // so nested block scalars use it as parent_indent, and a compact "- key: value"
    6070              : // mapping is allowed. Each stored element is marked attached.
    6071        63457 : static pstep pbl_step(parse_ctx *ctx, pframe *f, preq *rq) {
    6072        63457 :   const int seq_indent = f->u.bl.seq_indent;
    6073        63457 :   cyaml_node *elem = NULL;
    6074              : 
    6075        63457 :   if (f->state == BLS_AFTER_ELEM) goto after_elem;
    6076              : 
    6077        23373 :   f->u.bl.seq = (cyaml_node *)cyaml_create_list_interned(ctx->mp);
    6078        23373 :   if (!f->u.bl.seq) return PSTEP_FAIL;
    6079              : 
    6080        63462 :   while (!at_end(ctx)) {
    6081        46284 :     skip_ws_comments(ctx);
    6082        46284 :     if (at_end(ctx)) break;
    6083              : 
    6084        46107 :     if (line_indent_has_tab(ctx)) {
    6085           15 :       parse_err(ctx,
    6086              :                 "tab cannot be used as block sequence indentation at "
    6087              :                 "position %zu",
    6088              :                 ctx->pos);
    6089           15 :       return PSTEP_FAIL;
    6090              :     }
    6091        91829 :     if (current_col(ctx) != seq_indent) break;
    6092        44304 :     if (cur(ctx) != '-') break;
    6093              : 
    6094              :     {
    6095        44289 :       bool is_seq_entry = false;
    6096        44289 :       if (ctx->pos + 1 < ctx->len) {
    6097        44288 :         char next = ctx->src[ctx->pos + 1];
    6098        44288 :         if (next == ' ' || next == '\t' || next == '\n' || next == '\r')
    6099              :           is_seq_entry = true;
    6100              :       } else {
    6101              :         is_seq_entry = true;
    6102              :       }
    6103              : 
    6104              :       if (!is_seq_entry) break;
    6105              :     }
    6106              : 
    6107        44284 :     ctx->pos++;
    6108              : 
    6109        44284 :     if (!at_end(ctx) && cur(ctx) == ' ') ctx->pos++;
    6110              : 
    6111        44284 :     if (rest_of_line_is_blank(ctx) || at_end(ctx)) {
    6112        15426 :       skip_ws_comments(ctx);
    6113        15426 :       if (at_end(ctx) || line_space_indent(ctx) <= seq_indent) {
    6114            8 :         elem = node_alloc(CYAML_NULL, ctx->mp);
    6115            8 :         goto have_elem;
    6116              :       }
    6117              :     }
    6118        44276 :     preq_node(rq, seq_indent, false, false, true, false, false, NULL);
    6119        44276 :     f->state = BLS_AFTER_ELEM;
    6120        44276 :     return PSTEP_DESCEND;
    6121        40084 :   after_elem:
    6122        40084 :     elem = f->child;
    6123        40084 :     f->child = NULL;
    6124        40084 :   have_elem:
    6125        40092 :     if (!elem) return PSTEP_FAIL;
    6126              : 
    6127              :     {
    6128        40092 :       cyaml_node *ep = elem;
    6129        40092 :       if (cvector_push_back(f->u.bl.seq->value.list, &ep) != ccol_success) {
    6130            0 :         cyaml__destroy((cyaml)elem);
    6131            0 :         return PSTEP_FAIL;
    6132              :       }
    6133        40092 :       ep->attached = true;
    6134              :     }
    6135              :   }
    6136              : 
    6137        19163 :   f->result = f->u.bl.seq;
    6138        19163 :   f->u.bl.seq = NULL;
    6139        19163 :   return PSTEP_DONE;
    6140              : }
    6141              : 
    6142              : // Starts the node in a block mapping's key or value position, shared by the
    6143              : // explicit '?' key, the explicit ':' value and an implicit value. Content may
    6144              : // follow on the same line or on a more indented later line, else the node is an
    6145              : // implicit null. allow_inline_seq (true only for explicit-style content) lets a
    6146              : // "- " sequence or a chained "k: v" mapping start on the same line, which an
    6147              : // implicit value's grammar doesn't allow. *is_merge_candidate_out (key
    6148              : // position only, may be NULL) gets the merge look-ahead, taken here because
    6149              : // only here is the start of the key's content known in both cases.
    6150        16934 : CYAML_PARSE_HOT pbmn pbmn_begin(parse_ctx *ctx, int map_indent,
    6151              :                                 bool allow_inline_seq,
    6152              :                                 bool *is_merge_candidate_out,
    6153              :                                 cyaml_node **node_out, preq *rq) {
    6154        16934 :   if (is_merge_candidate_out) *is_merge_candidate_out = false;
    6155        16935 :   if (rest_of_line_is_blank(ctx)) {
    6156         9183 :     skip_ws_comments(ctx);
    6157        18366 :     bool is_value_col =
    6158         9183 :         !at_end(ctx) && at_block_value_col(ctx, map_indent, true);
    6159         9183 :     if (at_end(ctx) || !is_value_col || at_doc_marker(ctx)) {
    6160          124 :       *node_out = node_alloc(CYAML_NULL, ctx->mp);
    6161          124 :       return PBMN_NODE;
    6162              :     }
    6163         9059 :     if (is_merge_candidate_out)
    6164            6 :       *is_merge_candidate_out =
    6165            3 :           explicit_key_peek_is_merge_candidate(ctx, map_indent, false);
    6166         9059 :     preq_node(rq, map_indent, false, true, true, false, false, NULL);
    6167         9059 :     return PBMN_DESCEND;
    6168              :   }
    6169         7068 :   if (!allow_inline_seq && at_bare_seq_indicator(ctx)) {
    6170            3 :     parse_err(ctx,
    6171              :               "a block sequence cannot start on the same line as its "
    6172              :               "mapping key at position %zu",
    6173              :               ctx->pos);
    6174            3 :     return PBMN_ERROR;
    6175              :   }
    6176         7749 :   if (is_merge_candidate_out)
    6177         1368 :     *is_merge_candidate_out =
    6178          684 :         explicit_key_peek_is_merge_candidate(ctx, map_indent, false);
    6179         7749 :   preq_node(rq, map_indent, false, true, allow_inline_seq, false, false, NULL);
    6180         7749 :   return PBMN_DESCEND;
    6181              : }
    6182              : 
    6183              : // Looks ahead at the key starting at ctx->pos and tells whether it's a real
    6184              : // merge key, restoring ctx->pos. Every key form (implicit and explicit, block
    6185              : // and flow) uses it before reading the key. It walks the whole anchor and tag
    6186              : // chain, since "&y !!str <<" has a tag after its anchor: An untagged plain "<<"
    6187              : // counts, and so does a plain or quoted "<<" with the core merge tag. in_flow
    6188              : // picks flow_skip_ws() (which reads indent) or skip_inline_ws(). Whitespace
    6189              : // after
    6190              : // "<<" is over-approximated, which is safe because every caller checks the real
    6191              : // key text; the ':' rule matches scan_plain_scalar_line() exactly. A failure in
    6192              : // the look-ahead gives false and clears ctx->error, since the real parse
    6193              : // reports it and a stale message would hide a later one.
    6194       237467 : static bool explicit_key_peek_is_merge_candidate(parse_ctx *ctx, int indent,
    6195              :                                                  bool in_flow) {
    6196       237467 :   size_t saved_pos = ctx->pos;
    6197       237467 :   bool had_tag = false;
    6198       237467 :   size_t tag_pos = 0;
    6199       237467 :   bool had_anchor = false;
    6200       251993 :   for (int prop_pass = 0; prop_pass < 2; prop_pass++) {
    6201       248490 :     if (!at_end(ctx) && cur(ctx) == '&' && !had_anchor) {
    6202         5524 :       ctx->pos++;
    6203         5524 :       char *tmp_anchor = NULL;
    6204         5524 :       if (!parse_anchor_name(ctx, &tmp_anchor)) {
    6205            1 :         ctx->error[0] = '\0';
    6206            1 :         ctx->pos = saved_pos;
    6207            1 :         return false;
    6208              :       }
    6209         5523 :       ccol__mem_free(ctx->mp, tmp_anchor);
    6210         5523 :       had_anchor = true;
    6211       242966 :     } else if (!at_end(ctx) && cur(ctx) == '!' && !had_tag) {
    6212         9003 :       tag_pos = ctx->pos;
    6213         9003 :       skip_tag_token(ctx);
    6214         9003 :       had_tag = true;
    6215              :     } else {
    6216              :       break;
    6217              :     }
    6218        29052 :     bool ws_ok =
    6219        29052 :         in_flow ? flow_skip_ws(ctx, indent) : (skip_inline_ws(ctx), true);
    6220            0 :     if (!ws_ok) {
    6221            0 :       ctx->error[0] = '\0';
    6222            0 :       ctx->pos = saved_pos;
    6223            0 :       return false;
    6224              :     }
    6225              :   }
    6226       237466 :   bool merge_tag = false;
    6227       237466 :   if (had_tag && !at_end(ctx) &&
    6228         9003 :       (cur(ctx) == '<' || cur(ctx) == '"' || cur(ctx) == '\'')) {
    6229            9 :     size_t key_pos = ctx->pos;
    6230            9 :     char *tag = NULL;
    6231            9 :     ctx->pos = tag_pos;
    6232            9 :     if (parse_tag_token(ctx, &tag)) {
    6233            9 :       merge_tag = tag && strcmp(tag, CYAML_TAG_MERGE) == 0;
    6234            9 :       ccol__mem_free(ctx->mp, tag);
    6235              :     } else {
    6236            0 :       ctx->error[0] = '\0';
    6237              :     }
    6238            9 :     ctx->pos = key_pos;
    6239              :   }
    6240       237466 :   bool is_candidate = false;
    6241       237466 :   size_t after = SIZE_MAX;
    6242       237466 :   if ((!had_tag || merge_tag) && !at_end(ctx) && ctx->pos + 1 < ctx->len &&
    6243       228463 :       ctx->src[ctx->pos] == '<' && ctx->src[ctx->pos + 1] == '<') {
    6244          694 :     after = ctx->pos + 2;
    6245       227772 :   } else if (merge_tag && !at_end(ctx) &&
    6246            1 :              (cur(ctx) == '"' || cur(ctx) == '\'')) {
    6247            1 :     char *text = NULL;
    6248            0 :     bool ok = cur(ctx) == '"' ? parse_double_quoted(ctx, &text)
    6249            1 :                               : parse_single_quoted(ctx, &text);
    6250            1 :     is_candidate = ok && strcmp(text, "<<") == 0;
    6251            1 :     if (ok) ccol__mem_free(ctx->mp, text);
    6252            1 :     ctx->error[0] = '\0';
    6253              :   }
    6254          695 :   if (after != SIZE_MAX) {
    6255          694 :     if (after >= ctx->len) {
    6256              :       is_candidate = true;
    6257              :     } else {
    6258          694 :       char c = ctx->src[after];
    6259          694 :       if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
    6260              :         is_candidate = true;
    6261          684 :       } else if (in_flow && (c == ',' || c == ']' || c == '}')) {
    6262              :         is_candidate = true;
    6263          684 :       } else if (c == ':') {
    6264          683 :         if (after + 1 >= ctx->len) {
    6265              :           is_candidate = true;
    6266              :         } else {
    6267          683 :           char c2 = ctx->src[after + 1];
    6268          683 :           if (c2 == ' ' || c2 == '\t' || c2 == '\n' || c2 == '\r')
    6269              :             is_candidate = true;
    6270            1 :           else if (in_flow && (c2 == ',' || c2 == ']' || c2 == '}'))
    6271          692 :             is_candidate = true;
    6272              :         }
    6273              :       }
    6274              :     }
    6275              :   }
    6276       237466 :   ctx->pos = saved_pos;
    6277       237466 :   return is_candidate;
    6278              : }
    6279              : 
    6280              : // Finishes an explicit "? key" entry once its key node is in: Builds the
    6281              : // canonical key text, then looks for the ':' on a later line at exactly
    6282              : // map_indent (no tab before it, and a ':' that isn't followed by whitespace
    6283              : // starts a plain key instead). The key node is a descent, so pode_begin() and
    6284              : // this run on either side of it. Gives 1 on success, -1 on error.
    6285          691 : static int pode_finish(parse_ctx *ctx, int map_indent, cyaml_node *key_node,
    6286              :                        bool is_merge_candidate, char **key_out,
    6287              :                        bool *have_colon_out, bool *is_explicit_out,
    6288              :                        bool *is_merge_candidate_out) {
    6289          691 :   if (!key_node) return -1;
    6290          691 :   char *key_str = node_to_dict_key_string(ctx, key_node, "block dictionary");
    6291          691 :   if (!key_str) return -1;
    6292              : 
    6293          685 :   skip_ws_comments(ctx);
    6294          685 :   bool have_colon = false;
    6295          685 :   if (!at_end(ctx) && !at_doc_marker(ctx)) {
    6296          663 :     if (line_indent_has_tab(ctx)) {
    6297            2 :       parse_err(ctx,
    6298              :                 "tab cannot be used as block mapping indentation at "
    6299              :                 "position %zu",
    6300              :                 ctx->pos);
    6301            2 :       ccol__mem_free(ctx->mp, key_str);
    6302            2 :       return -1;
    6303              :     }
    6304         1981 :     if (current_col(ctx) == map_indent && cur(ctx) == ':') {
    6305          553 :       if (ctx->pos + 1 >= ctx->len) {
    6306              :         have_colon = true;
    6307              :       } else {
    6308          553 :         char after = ctx->src[ctx->pos + 1];
    6309          553 :         have_colon =
    6310          553 :             (after == ' ' || after == '\t' || after == '\n' || after == '\r');
    6311              :       }
    6312              :     }
    6313              :   }
    6314          550 :   if (have_colon) ctx->pos++;
    6315              : 
    6316          683 :   *key_out = key_str;
    6317          683 :   *have_colon_out = have_colon;
    6318          683 :   *is_explicit_out = true;
    6319          683 :   *is_merge_candidate_out = is_merge_candidate;
    6320          683 :   return 1;
    6321              : }
    6322              : 
    6323              : // Reads the key of one block-mapping entry. Gives 1 for a key, 0 when the
    6324              : // position isn't a key (the mapping ends), -1 on error, and 2 for an explicit
    6325              : // "? key" whose node must be read first; the request is filled in and the
    6326              : // caller resumes through pode_finish(). A '?' or '-' followed by text starts a
    6327              : // plain key, and an implicit key may carry an anchor and a tag (read through
    6328              : // try_parse_scalar_dict_key()).
    6329         4406 : static int pode_begin(parse_ctx *ctx, int map_indent, char **key_out,
    6330              :                       bool *have_colon_out, bool *is_explicit_out,
    6331              :                       bool *is_merge_candidate_out, preq *rq) {
    6332         4406 :   char c = cur(ctx);
    6333         4406 :   *is_merge_candidate_out = false;
    6334              : 
    6335         4406 :   bool is_explicit_key_indicator = false;
    6336         4406 :   if (c == '?') {
    6337          790 :     if (ctx->pos + 1 < ctx->len) {
    6338          790 :       char next = ctx->src[ctx->pos + 1];
    6339          790 :       if (next == ' ' || next == '\t' || next == '\n' || next == '\r')
    6340              :         is_explicit_key_indicator = true;
    6341              :     } else {
    6342              :       is_explicit_key_indicator = true;
    6343              :     }
    6344              :   }
    6345              : 
    6346            0 :   if (is_explicit_key_indicator) {
    6347          789 :     ctx->pos++;
    6348              : 
    6349          789 :     if (!at_end(ctx) && cur(ctx) == ' ') ctx->pos++;
    6350              : 
    6351          789 :     cyaml_node *key_node = NULL;
    6352          789 :     switch (pbmn_begin(ctx, map_indent, true, is_merge_candidate_out, &key_node,
    6353              :                        rq)) {
    6354              :       case PBMN_ERROR:
    6355              :         return -1;
    6356              :       case PBMN_DESCEND:
    6357          687 :         return 2;
    6358              :       case PBMN_NODE:
    6359              :         break;
    6360              :     }
    6361          102 :     return pode_finish(ctx, map_indent, key_node, *is_merge_candidate_out,
    6362              :                        key_out, have_colon_out, is_explicit_out,
    6363              :                        is_merge_candidate_out);
    6364              :   }
    6365              : 
    6366         3617 :   if (c == '-') {
    6367           12 :     char nx = (ctx->pos + 1 < ctx->len) ? ctx->src[ctx->pos + 1] : '\0';
    6368           12 :     if (nx == ' ' || nx == '\t' || nx == '\n' || nx == '\r' || nx == '\0')
    6369              :       return 0;
    6370         3605 :   } else if (c == '|' || c == '>' || c == '#') {
    6371              :     return 0;
    6372              :   }
    6373              : 
    6374              :   {
    6375         3617 :     char *anchor_name = NULL;
    6376         3617 :     char *key_str = NULL;
    6377         3617 :     cyaml_node *anchor_value = NULL;
    6378         3617 :     if (!try_parse_scalar_dict_key(ctx, &anchor_name, &key_str,
    6379              :                                    is_merge_candidate_out, &anchor_value))
    6380          139 :       return ctx->error[0] ? -1 : 0;
    6381              : 
    6382         3549 :     if (!register_key_anchor(ctx, anchor_name, key_str, anchor_value)) {
    6383            3 :       ccol__mem_free(ctx->mp, key_str);
    6384            3 :       return -1;
    6385              :     }
    6386              : 
    6387         3546 :     *key_out = key_str;
    6388         3546 :     *have_colon_out = true;
    6389         3546 :     *is_explicit_out = false;
    6390              :   }
    6391         3546 :   return 1;
    6392              : }
    6393              : 
    6394              : // Inserts a copy of val into target under a key target doesn't hold, for a
    6395              : // merged member. The copy and its entry are amplification, so both are charged
    6396              : // to the amplification budget. false with ctx->error set on failure.
    6397         1948 : static bool merge_insert_copy(parse_ctx *ctx, cyaml_node *target,
    6398              :                               const char *key, cyaml_node *val) {
    6399         1948 :   parse_amp_enter();
    6400         1948 :   cyaml clone = cyaml_clone((cyaml)val);
    6401            0 :   bool ok =
    6402         1948 :       clone && dictionary_set_impl((cyaml)target, key, clone) == ccol_success;
    6403         1948 :   parse_amp_leave();
    6404         1948 :   if (ok) return true;
    6405           26 :   if (parse_amp_limit_hit)
    6406            1 :     parse_err(ctx,
    6407              :               "merge key expansion exceeded the %zu-node, %zu-byte alias "
    6408              :               "expansion memory limit at position %zu",
    6409              :               (size_t)CYAML_PARSE_NODE_FLOOR, (size_t)CYAML_PARSE_BYTE_FLOOR,
    6410              :               ctx->pos);
    6411           25 :   else if (parse_node_budget_exhausted)
    6412            0 :     parse_err(ctx,
    6413              :               "merge key expansion exceeded the %zu node-allocation "
    6414              :               "limit at position %zu",
    6415              :               parse_node_limit, ctx->pos);
    6416           25 :   else if (parse_byte_budget_exhausted)
    6417            1 :     parse_err(ctx,
    6418              :               "merge key expansion exceeded the %zu-byte document memory "
    6419              :               "limit at position %zu",
    6420              :               parse_byte_limit, ctx->pos);
    6421              :   else
    6422           24 :     parse_err(ctx, "out of memory expanding merge key at position %zu",
    6423              :               ctx->pos);
    6424              :   return false;
    6425              : }
    6426              : 
    6427              : // Merges the members of one source mapping into target in the source's order,
    6428              : // for merge_apply(), skipping keys target already holds. Values are copied,
    6429              : // since they belong to the source's tree. false with ctx->error set on failure.
    6430          613 : static bool merge_one_source_into(parse_ctx *ctx, cyaml_node *target,
    6431              :                                   cyaml_node *source) {
    6432         2867 :   for (const ccol_chmap_entry_ref *e = dict_first_entry(source); e;) {
    6433         2262 :     const cmap_pair *kp, *vp;
    6434         2262 :     e = ccol_chmap_entry_read(e, &kp, &vp);
    6435         2262 :     const char *key = (const char *)kp->ptr;
    6436         2262 :     if (cyaml_dictionary_get((cyaml)target, key)) continue;
    6437         1854 :     if (!merge_insert_copy(ctx, target, key, cyaml_read_child(vp->ptr)))
    6438            8 :       return false;
    6439              :   }
    6440              :   return true;
    6441              : }
    6442              : 
    6443              : // Moves count members of map, starting at first, to the end of the member order
    6444              : // by deleting and inserting each again; merge_reorder() needs it to place
    6445              : // merged members. The key is copied first (stack buffer, or one allocation for
    6446              : // a long key), since the delete frees it. A member the insert refuses is
    6447              : // destroyed and the parse fails.
    6448          482 : static bool merge_move_to_end(parse_ctx *ctx, cyaml_node *map,
    6449              :                               const ccol_chmap_entry_ref *first, size_t count) {
    6450          482 :   const ccol_chmap_entry_ref *e = first;
    6451          973 :   for (size_t i = 0; i < count && e; i++) {
    6452          501 :     const cmap_pair *kp, *vp;
    6453          501 :     const ccol_chmap_entry_ref *next = ccol_chmap_entry_read(e, &kp, &vp);
    6454          501 :     cyaml_node *child = cyaml_read_child(vp->ptr);
    6455          501 :     char stack_key[256];
    6456          501 :     char *key = stack_key;
    6457          501 :     size_t key_size = kp->size;
    6458          501 :     if (key_size > sizeof(stack_key)) {
    6459            0 :       key = ccol__mem_alloc(ctx->mp, key_size);
    6460            0 :       if (!key) {
    6461            0 :         parse_err(ctx, "out of memory expanding merge key at position %zu",
    6462              :                   ctx->pos);
    6463           10 :         return false;
    6464              :       }
    6465              :     }
    6466          501 :     memcpy(key, kp->ptr, key_size);
    6467          501 :     cmap_pair key_pair = {.ptr = key, .size = key_size};
    6468          501 :     cmap_pair val_pair = {.ptr = &child, .size = sizeof(child)};
    6469          501 :     ccol_retval r = chashmap_remove_elem(map->value.dictionary, &key_pair);
    6470          501 :     if (r == ccol_success)
    6471          501 :       r = chashmap_insert_elem(map->value.dictionary, &key_pair, &val_pair);
    6472          501 :     if (key != stack_key) ccol__mem_free(ctx->mp, key);
    6473          501 :     if (r != ccol_success) {
    6474           10 :       cyaml__destroy((cyaml)child);
    6475           10 :       parse_err(ctx, "out of memory expanding merge key at position %zu",
    6476              :                 ctx->pos);
    6477           10 :       return false;
    6478              :     }
    6479          491 :     e = next;
    6480              :   }
    6481              :   return true;
    6482              : }
    6483              : 
    6484              : // Gives how many sources one merge entry names (the length of its sequence, or
    6485              : // 1 for a single mapping), so merge_apply() can treat both shapes alike.
    6486         1572 : static size_t merge_source_count(const cyaml_node *val) {
    6487           67 :   return val->type == CYAML_LIST ? cvector_size(val->value.list) : 1;
    6488              : }
    6489              : 
    6490              : // Gives source i of one merge entry, the counterpart of merge_source_count().
    6491         1634 : static cyaml_node *merge_source_at(cyaml_node *val, size_t i) {
    6492         1634 :   if (val->type != CYAML_LIST) return val;
    6493          129 :   return *(cyaml_node **)cvector_at(val->value.list, i);
    6494              : }
    6495              : 
    6496              : // One segment that merge_reorder() moves: The first explicit member after a
    6497              : // merge entry, and the first member and count of what that entry placed.
    6498              : typedef struct {
    6499              :   const ccol_chmap_entry_ref *explicit_first;
    6500              :   const ccol_chmap_entry_ref *merged_first;
    6501              :   size_t merged_count;
    6502              : } cyaml_merge_seg;
    6503              : 
    6504              : // Puts the members of map in their final order after merge_apply() placed them.
    6505              : // On entry the explicit members come first, then what each merge entry placed;
    6506              : // afterwards the members of entry i sit between the explicit members before and
    6507              : // after that entry. Only out-of-place segments move, found in one walk (entries
    6508              : // keep their addresses while other members move). false with ctx->error set on
    6509              : // OOM.
    6510          623 : static bool merge_reorder(parse_ctx *ctx, cyaml_node *map,
    6511              :                           const cyaml_merge_entry *entries,
    6512              :                           cyaml_merge_seg *seg, size_t n,
    6513              :                           size_t explicit_count) {
    6514          623 :   size_t k = 0;
    6515          799 :   while (k < n) {
    6516          631 :     size_t end = k + 1 < n ? entries[k + 1].pos : explicit_count;
    6517          631 :     if (end > entries[k].pos) break;
    6518              :     k++;
    6519              :   }
    6520          623 :   if (k == n) return true;
    6521              : 
    6522              :   {
    6523          455 :     size_t idx = 0, ei = k, mi = k + 1, merged_at = explicit_count;
    6524          910 :     for (size_t i = 0; i <= k && i < n; i++) merged_at += seg[i].merged_count;
    6525         1449 :     for (const ccol_chmap_entry_ref *e = dict_first_entry(map); e; idx++) {
    6526          994 :       const cmap_pair *ekp, *evp;
    6527          994 :       const ccol_chmap_entry_ref *cur_e = e;
    6528          994 :       e = ccol_chmap_entry_read(e, &ekp, &evp);
    6529         1467 :       while (ei < n && entries[ei].pos == idx) seg[ei++].explicit_first = cur_e;
    6530         1012 :       while (mi < n && merged_at == idx) {
    6531           18 :         seg[mi].merged_first = cur_e;
    6532           18 :         merged_at += seg[mi++].merged_count;
    6533              :       }
    6534              :     }
    6535              :   }
    6536              : 
    6537          917 :   for (size_t i = k; i < n; i++) {
    6538          472 :     size_t end = i + 1 < n ? entries[i + 1].pos : explicit_count;
    6539          488 :     if (i > k && seg[i].merged_count &&
    6540           16 :         !merge_move_to_end(ctx, map, seg[i].merged_first, seg[i].merged_count))
    6541              :       return false;
    6542          935 :     if (end > entries[i].pos &&
    6543          466 :         !merge_move_to_end(ctx, map, seg[i].explicit_first,
    6544              :                            end - entries[i].pos))
    6545              :       return false;
    6546              :   }
    6547              :   return true;
    6548              : }
    6549              : 
    6550              : // Expands the merge entries of a mapping once it's read; the frames keep every
    6551              : // "<<" entry aside, so map holds only explicit members. The caller keeps the
    6552              : // values. Precedence follows PyYAML: Explicit members win, a later merge entry
    6553              : // beats an earlier one, and inside one entry an earlier source wins. With
    6554              : // several entries, a temporary map of winning values is built first and the
    6555              : // members are placed in document order after. A source mapping's own merges
    6556              : // were expanded when it was read, so nesting needs nothing special. false with
    6557              : // ctx->error set for a source that isn't a mapping, or on OOM.
    6558          669 : static bool merge_apply(parse_ctx *ctx, cyaml_node *map,
    6559              :                         const cyaml_merge_entry *entries, size_t n) {
    6560         1424 :   for (size_t i = 0; i < n; i++) {
    6561          759 :     cyaml_node *val = entries[i].val;
    6562          759 :     size_t cnt = merge_source_count(val);
    6563         1542 :     for (size_t j = 0; j < cnt; j++) {
    6564          787 :       cyaml_node *src = merge_source_at(val, j);
    6565          787 :       if (!src || src->type != CYAML_DICTIONARY) {
    6566            4 :         parse_err(ctx, "merge key source is not a mapping at position %zu",
    6567              :                   ctx->pos);
    6568            4 :         return false;
    6569              :       }
    6570              :     }
    6571              :   }
    6572          665 :   size_t explicit_count = chashmap_size(map->value.dictionary);
    6573              : 
    6574          665 :   if (n == 1) {
    6575          609 :     size_t cnt = merge_source_count(entries[0].val);
    6576         1214 :     for (size_t j = 0; j < cnt; j++)
    6577          621 :       if (!merge_one_source_into(ctx, map, merge_source_at(entries[0].val, j)))
    6578              :         return false;
    6579         1202 :     cyaml_merge_seg seg = {
    6580          601 :         .merged_count = chashmap_size(map->value.dictionary) - explicit_count};
    6581          601 :     return merge_reorder(ctx, map, entries, &seg, 1, explicit_count);
    6582              :   }
    6583              : 
    6584           56 :   char *err = NULL;
    6585           56 :   chmap winners =
    6586           56 :       ccol_chmap_create_compact(ccol_string, ccol_pointer, ctx->mp, &err);
    6587           56 :   cyaml_merge_seg *seg = ccol__mem_alloc(ctx->mp, n * sizeof(*seg));
    6588           56 :   bool ok = winners && seg;
    6589           56 :   if (!ok)
    6590            6 :     parse_err(ctx, "out of memory expanding merge key at position %zu",
    6591              :               ctx->pos);
    6592          174 :   for (size_t i = n; ok && i-- > 0;) {
    6593          118 :     cyaml_node *val = entries[i].val;
    6594          118 :     size_t cnt = merge_source_count(val);
    6595          254 :     for (size_t j = 0; ok && j < cnt; j++) {
    6596          136 :       cyaml_node *src = merge_source_at(val, j);
    6597          312 :       for (const ccol_chmap_entry_ref *e = dict_first_entry(src); e;) {
    6598          185 :         const cmap_pair *kp, *vp;
    6599          185 :         cmap_pair slot;
    6600          185 :         e = ccol_chmap_entry_read(e, &kp, &vp);
    6601          185 :         if (chashmap_get_elem_ref(map->value.dictionary, kp, &slot) ==
    6602              :             ccol_success)
    6603           19 :           continue;
    6604          166 :         cyaml_node *child = cyaml_read_child(vp->ptr);
    6605          166 :         cmap_pair val_pair = {.ptr = &child, .size = sizeof(child)};
    6606          166 :         ccol_retval r =
    6607          166 :             ccol_chmap_insert_or_get_elem(winners, kp, &val_pair, &slot);
    6608          166 :         if (r != ccol_success && r != ccol_key_already_present) {
    6609            9 :           parse_err(ctx, "out of memory expanding merge key at position %zu",
    6610              :                     ctx->pos);
    6611            9 :           ok = false;
    6612            9 :           break;
    6613              :         }
    6614              :       }
    6615              :     }
    6616              :   }
    6617          142 :   for (size_t i = 0; ok && i < n; i++) {
    6618           86 :     cyaml_node *val = entries[i].val;
    6619           86 :     size_t cnt = merge_source_count(val);
    6620           86 :     size_t before = chashmap_size(map->value.dictionary);
    6621          184 :     for (size_t j = 0; ok && j < cnt; j++) {
    6622           98 :       cyaml_node *src = merge_source_at(val, j);
    6623          217 :       for (const ccol_chmap_entry_ref *e = dict_first_entry(src); e;) {
    6624          138 :         const cmap_pair *kp, *vp;
    6625          138 :         cmap_pair slot;
    6626          138 :         e = ccol_chmap_entry_read(e, &kp, &vp);
    6627          138 :         cyaml_node *none = NULL;
    6628          138 :         cmap_pair none_pair = {.ptr = &none, .size = sizeof(none)};
    6629          138 :         ccol_retval r =
    6630          138 :             ccol_chmap_insert_or_get_elem(winners, kp, &none_pair, &slot);
    6631          164 :         if (r == ccol_success) continue;
    6632          121 :         if (r != ccol_key_already_present) {
    6633            1 :           parse_err(ctx, "out of memory expanding merge key at position %zu",
    6634              :                     ctx->pos);
    6635            1 :           ok = false;
    6636           20 :           break;
    6637              :         }
    6638          120 :         cyaml_node *win = cyaml_read_child(slot.ptr);
    6639          120 :         if (!win) continue;
    6640           94 :         memcpy(slot.ptr, &none, sizeof(none));
    6641           94 :         if (!merge_insert_copy(ctx, map, (const char *)kp->ptr, win)) {
    6642              :           ok = false;
    6643              :           break;
    6644              :         }
    6645              :       }
    6646              :     }
    6647           86 :     if (ok) seg[i].merged_count = chashmap_size(map->value.dictionary) - before;
    6648              :   }
    6649           56 :   if (ok) ok = merge_reorder(ctx, map, entries, seg, n, explicit_count);
    6650           56 :   if (winners) chashmap__destroy(winners);
    6651           56 :   ccol__mem_free(ctx->mp, seg);
    6652              :   return ok;
    6653              : }
    6654              : 
    6655              : // Keeps one merge entry of a mapping aside until the mapping ends, so merge
    6656              : // entries never replace each other in the map. It takes ownership of val; a
    6657              : // failure destroys val and sets ctx->error.
    6658          866 : static bool merge_entry_push(parse_ctx *ctx, cyaml_merge_entry **arr,
    6659              :                              size_t *count, size_t *cap, cyaml_node *val,
    6660              :                              size_t pos) {
    6661          866 :   if (*count == *cap) {
    6662          750 :     size_t new_cap = *cap ? *cap * 2 : 2;
    6663         1500 :     cyaml_merge_entry *grown =
    6664          750 :         ccol__mem_realloc(ctx->mp, *arr, new_cap * sizeof(*grown));
    6665          750 :     if (!grown) {
    6666            6 :       cyaml__destroy((cyaml)val);
    6667            6 :       parse_err(ctx, "out of memory parsing merge key at position %zu",
    6668              :                 ctx->pos);
    6669            6 :       return false;
    6670              :     }
    6671          744 :     *arr = grown;
    6672          744 :     *cap = new_cap;
    6673              :   }
    6674          860 :   (*arr)[*count].val = val;
    6675          860 :   (*arr)[*count].pos = pos;
    6676          860 :   (*count)++;
    6677          860 :   return true;
    6678              : }
    6679              : 
    6680              : // Destroys the merge entries a frame kept aside and the array, when the
    6681              : // mapping fails. A value may hold anchored nodes ("<<: &b {x: 1}"), so it goes
    6682              : // through parse_discard().
    6683         9508 : static void merge_entries_free(parse_ctx *ctx, cyaml_merge_entry **arr,
    6684              :                                size_t *count, size_t *cap) {
    6685        10368 :   for (size_t i = 0; i < *count; i++) parse_discard((*arr)[i].val);
    6686         9508 :   ccol__mem_free(ctx->mp, *arr);
    6687         9508 :   *arr = NULL;
    6688         9508 :   *count = 0;
    6689         9508 :   *cap = 0;
    6690         9508 : }
    6691              : 
    6692              : // Expands the merge entries a frame kept aside into map when the mapping ends,
    6693              : // then destroys them whatever the result. Gives what merge_apply() gives.
    6694          599 : static bool merge_entries_finish(parse_ctx *ctx, cyaml_node *map,
    6695              :                                  cyaml_merge_entry **arr, size_t *count,
    6696              :                                  size_t *cap) {
    6697          599 :   bool ok = merge_apply(ctx, map, *arr, *count);
    6698          599 :   merge_entries_free(ctx, arr, count, cap);
    6699          599 :   return ok;
    6700              : }
    6701              : 
    6702              : // Runs a block-mapping frame. The request gives map_indent and maybe a first
    6703              : // key that the requesting frame already read (it owns that key and stays below
    6704              : // this frame); first_key_colon_consumed says whether that key's ':' is read
    6705              : // too, and first_key_is_merge_candidate whether it's a merge key. Without a
    6706              : // first key the mapping starts with a "? key" entry. Explicit keys and every
    6707              : // value are descents. A tab before a key on its line is refused, since the
    6708              : // column would be undefined; an explicit key without ':' has a null value;
    6709              : // merge entries wait in f->u.bd.merges until the mapping ends; each value is
    6710              : // stored with dictionary_set_impl().
    6711        26824 : static pstep pbd_step(parse_ctx *ctx, pframe *f, preq *rq) {
    6712        26824 :   const int map_indent = f->u.bd.map_indent;
    6713        26824 :   cyaml_node *val = NULL;
    6714        26824 :   int r = 0;
    6715              : 
    6716        26824 :   switch (f->state) {
    6717          332 :     case BDS_AFTER_FIRST_KEY_NODE:
    6718          332 :       goto after_first_key_node;
    6719          257 :     case BDS_AFTER_KEY_NODE:
    6720          257 :       goto after_key_node;
    6721        13729 :     case BDS_AFTER_VALUE:
    6722        13729 :       goto after_value;
    6723              :     default:
    6724        12506 :       break;
    6725              :   }
    6726              : 
    6727              :   {
    6728        12506 :     size_t ls = line_start_pos(ctx);
    6729        12506 :     size_t span = ctx->pos - ls;
    6730        12506 :     if (map_indent >= 0 && (size_t)map_indent < span) span = (size_t)map_indent;
    6731        12506 :     if (memchr(ctx->src + ls, '\t', span) != NULL) {
    6732            5 :       parse_err(ctx,
    6733              :                 "tab cannot be used as block mapping indentation at "
    6734              :                 "position %zu",
    6735              :                 ls + span);
    6736            5 :       return PSTEP_FAIL;
    6737              :     }
    6738              :   }
    6739              : 
    6740        12501 :   f->u.bd.map = (cyaml_node *)cyaml_create_dictionary_interned(ctx->mp);
    6741        12502 :   if (!f->u.bd.map) return PSTEP_FAIL;
    6742              : 
    6743        12478 :   if (f->u.bd.key != NULL) {
    6744        12050 :     if (f->u.bd.have_colon) {
    6745        11980 :     } else if (at_end(ctx) || cur(ctx) != ':') {
    6746            0 :       parse_err(ctx, "expected ':' after dictionary key at position %zu",
    6747              :                 ctx->pos);
    6748            0 :       return PSTEP_FAIL;
    6749              :     } else {
    6750        11980 :       ctx->pos++;
    6751        11980 :       f->u.bd.have_colon = true;
    6752              :     }
    6753              :   } else {
    6754          428 :     r = pode_begin(ctx, map_indent, &f->u.bd.key_owned, &f->u.bd.have_colon,
    6755              :                    &f->u.bd.is_explicit, &f->u.bd.entry_is_merge_candidate, rq);
    6756          428 :     if (r == 2) {
    6757          425 :       f->state = BDS_AFTER_FIRST_KEY_NODE;
    6758          425 :       return PSTEP_DESCEND;
    6759              :     }
    6760            3 :     goto first_key_done;
    6761          332 :   after_first_key_node:
    6762          332 :     r = pode_finish(ctx, map_indent, f->child, f->u.bd.entry_is_merge_candidate,
    6763              :                     &f->u.bd.key_owned, &f->u.bd.have_colon,
    6764              :                     &f->u.bd.is_explicit, &f->u.bd.entry_is_merge_candidate);
    6765          332 :     f->child = NULL;
    6766          335 :   first_key_done:
    6767          335 :     if (r <= 0) {
    6768            5 :       if (r == 0)
    6769            0 :         parse_err(ctx, "expected block dictionary key at position %zu",
    6770              :                   ctx->pos);
    6771            5 :       return PSTEP_FAIL;
    6772              :     }
    6773          330 :     f->u.bd.key = f->u.bd.key_owned;
    6774              :   }
    6775              : 
    6776        20176 :   while (1) {
    6777        16278 :     if (f->u.bd.have_colon && !at_end(ctx) && cur(ctx) == ' ') ctx->pos++;
    6778              : 
    6779        16278 :     if (f->u.bd.have_colon) {
    6780        16145 :       switch (
    6781        16145 :           pbmn_begin(ctx, map_indent, f->u.bd.is_explicit, NULL, &val, rq)) {
    6782              :         case PBMN_ERROR:
    6783            3 :           val = NULL;
    6784            3 :           goto have_value;
    6785              :         case PBMN_NODE:
    6786           22 :           goto have_value;
    6787              :         case PBMN_DESCEND:
    6788        16121 :           f->state = BDS_AFTER_VALUE;
    6789        16121 :           return PSTEP_DESCEND;
    6790              :       }
    6791              :     } else {
    6792          133 :       val = node_alloc(CYAML_NULL, ctx->mp);
    6793          133 :       goto have_value;
    6794              :     }
    6795        13729 :   after_value:
    6796        13729 :     val = f->child;
    6797        13729 :     f->child = NULL;
    6798        13751 :   have_value:
    6799        13887 :     if (!val) {
    6800            3 :       if (!ctx->error[0])
    6801            0 :         parse_err(ctx, "out of memory parsing dictionary value at position %zu",
    6802              :                   ctx->pos);
    6803            3 :       return PSTEP_FAIL;
    6804              :     }
    6805              : 
    6806        13884 :     if (f->u.bd.entry_is_merge_candidate && strcmp(f->u.bd.key, "<<") == 0) {
    6807          349 :       if (!merge_entry_push(ctx, &f->u.bd.merges, &f->u.bd.merge_count,
    6808              :                             &f->u.bd.merge_cap, val,
    6809          349 :                             chashmap_size(f->u.bd.map->value.dictionary)))
    6810              :         return PSTEP_FAIL;
    6811        13535 :     } else if (dictionary_set_impl((cyaml)f->u.bd.map, f->u.bd.key,
    6812              :                                    (cyaml)val) != ccol_success) {
    6813              :       return PSTEP_FAIL;
    6814              :     }
    6815        13859 :     ccol__mem_free(ctx->mp, f->u.bd.key_owned);
    6816        13859 :     f->u.bd.key_owned = NULL;
    6817        13859 :     f->u.bd.key = NULL;
    6818              : 
    6819        13859 :     skip_ws_comments(ctx);
    6820        13859 :     if (at_end(ctx)) break;
    6821         4817 :     if (at_doc_marker(ctx)) break;
    6822         4521 :     if (at_col0_bom(ctx)) break;
    6823         4515 :     if (line_indent_has_tab(ctx)) {
    6824            3 :       parse_err(ctx,
    6825              :                 "tab cannot be used as block mapping indentation at "
    6826              :                 "position %zu",
    6827              :                 ctx->pos);
    6828            3 :       return PSTEP_FAIL;
    6829              :     }
    6830         9024 :     if (current_col(ctx) != map_indent) break;
    6831              : 
    6832         3978 :     r = pode_begin(ctx, map_indent, &f->u.bd.key_owned, &f->u.bd.have_colon,
    6833              :                    &f->u.bd.is_explicit, &f->u.bd.entry_is_merge_candidate, rq);
    6834         3978 :     if (r == 2) {
    6835          262 :       f->state = BDS_AFTER_KEY_NODE;
    6836          262 :       return PSTEP_DESCEND;
    6837              :     }
    6838         3716 :     goto next_key_done;
    6839          257 :   after_key_node:
    6840          257 :     r = pode_finish(ctx, map_indent, f->child, f->u.bd.entry_is_merge_candidate,
    6841              :                     &f->u.bd.key_owned, &f->u.bd.have_colon,
    6842              :                     &f->u.bd.is_explicit, &f->u.bd.entry_is_merge_candidate);
    6843          257 :     f->child = NULL;
    6844         3972 :   next_key_done:
    6845         3972 :     if (r < 0) return PSTEP_FAIL;
    6846         3914 :     if (r == 0) break;
    6847         3898 :     f->u.bd.key = f->u.bd.key_owned;
    6848              :   }
    6849              : 
    6850        10154 :   if (f->u.bd.merge_count &&
    6851          260 :       !merge_entries_finish(ctx, f->u.bd.map, &f->u.bd.merges,
    6852              :                             &f->u.bd.merge_count, &f->u.bd.merge_cap))
    6853              :     return PSTEP_FAIL;
    6854              : 
    6855         9871 :   f->result = f->u.bd.map;
    6856         9871 :   f->u.bd.map = NULL;
    6857         9871 :   return PSTEP_DONE;
    6858              : }
    6859              : 
    6860              : // Initializes a frame from the request that asked for it, as the driver pushes
    6861              : // it. A collection frame takes one ctx->depth level for as long as it's on the
    6862              : // stack, which is where the nesting limit is enforced; a node frame takes none.
    6863              : // false, with the error set and nothing pushed, when the level would pass the
    6864              : // limit. Only the fields a kind reads before writing are cleared.
    6865       486962 : static bool pframe_open(parse_ctx *ctx, pframe *f, const preq *rq) {
    6866       486962 :   f->kind = rq->kind;
    6867       486962 :   f->state = 0;
    6868       486962 :   f->child = NULL;
    6869       486962 :   f->result = NULL;
    6870       486962 :   if (rq->kind == PFK_NODE) {
    6871       366230 :     f->u.n.indent = rq->indent;
    6872       366230 :     f->u.n.in_flow = rq->in_flow;
    6873       366230 :     f->u.n.seq_ok_at_indent = rq->seq_ok_at_indent;
    6874       366230 :     f->u.n.allow_inline_map = rq->allow_inline_map;
    6875       366230 :     f->u.n.had_anchor = rq->had_anchor;
    6876       366230 :     f->u.n.had_tag = rq->had_tag;
    6877       366230 :     f->u.n.resolved_tag = rq->resolved_tag;
    6878       366230 :     f->u.n.name = NULL;
    6879       366230 :     f->u.n.tag = NULL;
    6880       366230 :     f->u.n.pending_key = NULL;
    6881       366230 :     return true;
    6882              :   }
    6883       120732 :   if (ctx->depth >= CYAML_MAX_NESTING_DEPTH) {
    6884           34 :     parse_depth_err(ctx);
    6885           34 :     return false;
    6886              :   }
    6887       120698 :   if (++ctx->depth > ctx->peak_depth) ctx->peak_depth = ctx->depth;
    6888       120698 :   switch (rq->kind) {
    6889              :     case PFK_NODE:
    6890              :       break;
    6891        70187 :     case PFK_FLOW_LIST:
    6892        70187 :       f->u.fl.indent = rq->indent;
    6893        70187 :       f->u.fl.seq = NULL;
    6894        70187 :       f->u.fl.key_str = NULL;
    6895        70187 :       break;
    6896        14632 :     case PFK_FLOW_DICT:
    6897        14632 :       f->u.fd.indent = rq->indent;
    6898        14632 :       f->u.fd.map = NULL;
    6899        14632 :       f->u.fd.key_str = NULL;
    6900        14632 :       f->u.fd.merges = NULL;
    6901        14632 :       f->u.fd.merge_count = 0;
    6902        14632 :       f->u.fd.merge_cap = 0;
    6903        14632 :       break;
    6904        23373 :     case PFK_BLOCK_LIST:
    6905        23373 :       f->u.bl.seq_indent = rq->indent;
    6906        23373 :       f->u.bl.seq = NULL;
    6907        23373 :       break;
    6908        12506 :     case PFK_BLOCK_DICT:
    6909        12506 :       f->u.bd.map_indent = rq->indent;
    6910        12506 :       f->u.bd.map = NULL;
    6911        12506 :       f->u.bd.key = rq->first_key;
    6912        12506 :       f->u.bd.key_owned = NULL;
    6913        12506 :       f->u.bd.have_colon = rq->first_key_colon_consumed;
    6914        12506 :       f->u.bd.is_explicit = false;
    6915        12506 :       f->u.bd.merges = NULL;
    6916        12506 :       f->u.bd.merge_count = 0;
    6917        12506 :       f->u.bd.merge_cap = 0;
    6918        12506 :       f->u.bd.entry_is_merge_candidate = rq->first_key_is_merge_candidate;
    6919        12506 :       break;
    6920              :   }
    6921              :   return true;
    6922              : }
    6923              : 
    6924              : // Frees everything a frame still owns, for a failed parse: The driver sweeps
    6925              : // every frame left on the stack, since a container under construction belongs
    6926              : // only to its frame. It gives back the depth level of a collection frame, and
    6927              : // of a flow pair whose value was being read.
    6928        79233 : static void pframe_cleanup(parse_ctx *ctx, pframe *f) {
    6929        79233 :   if (f->child) {
    6930            0 :     cyaml__destroy((cyaml)f->child);
    6931            0 :     f->child = NULL;
    6932              :   }
    6933        79233 :   switch (f->kind) {
    6934        42622 :     case PFK_NODE:
    6935        42622 :       ccol__mem_free(ctx->mp, f->u.n.name);
    6936        42622 :       ccol__mem_free(ctx->mp, f->u.n.tag);
    6937        42622 :       ccol__mem_free(ctx->mp, f->u.n.pending_key);
    6938        42622 :       f->u.n.name = NULL;
    6939        42622 :       f->u.n.tag = NULL;
    6940        42622 :       f->u.n.pending_key = NULL;
    6941        42622 :       return;
    6942        23492 :     case PFK_FLOW_LIST:
    6943        23492 :       cyaml__destroy((cyaml)f->u.fl.seq);
    6944        23492 :       f->u.fl.seq = NULL;
    6945        23492 :       if (f->u.fl.key_str) {
    6946           18 :         ccol__mem_free(ctx->mp, f->u.fl.key_str);
    6947           18 :         f->u.fl.key_str = NULL;
    6948           18 :         ctx->depth--;
    6949              :       }
    6950              :       break;
    6951         6273 :     case PFK_FLOW_DICT:
    6952         6273 :       cyaml__destroy((cyaml)f->u.fd.map);
    6953         6273 :       f->u.fd.map = NULL;
    6954         6273 :       ccol__mem_free(ctx->mp, f->u.fd.key_str);
    6955         6273 :       f->u.fd.key_str = NULL;
    6956         6273 :       merge_entries_free(ctx, &f->u.fd.merges, &f->u.fd.merge_count,
    6957              :                          &f->u.fd.merge_cap);
    6958         6273 :       break;
    6959         4210 :     case PFK_BLOCK_LIST:
    6960         4210 :       cyaml__destroy((cyaml)f->u.bl.seq);
    6961         4210 :       f->u.bl.seq = NULL;
    6962         4210 :       break;
    6963         2636 :     case PFK_BLOCK_DICT:
    6964         2636 :       cyaml__destroy((cyaml)f->u.bd.map);
    6965         2636 :       f->u.bd.map = NULL;
    6966         2636 :       ccol__mem_free(ctx->mp, f->u.bd.key_owned);
    6967         2636 :       f->u.bd.key_owned = NULL;
    6968         2636 :       f->u.bd.key = NULL;
    6969         2636 :       merge_entries_free(ctx, &f->u.bd.merges, &f->u.bd.merge_count,
    6970              :                          &f->u.bd.merge_cap);
    6971         2636 :       break;
    6972              :   }
    6973        36611 :   ctx->depth--;
    6974              : }
    6975              : 
    6976              : // Releases a finished frame, which has handed over its node and owns nothing
    6977              : // else, by giving back a collection frame's depth level. Test builds assert
    6978              : // that the frame holds nothing.
    6979       407696 : static void pframe_release(parse_ctx *ctx, pframe *f) {
    6980              : #ifdef RUNNING_UNIT_TESTS
    6981       407696 :   ccol__assert(f->child == NULL);
    6982       407696 :   switch (f->kind) {
    6983       323610 :     case PFK_NODE:
    6984       323610 :       ccol__assert(f->u.n.name == NULL && f->u.n.tag == NULL &&
    6985              :                    f->u.n.pending_key == NULL);
    6986              :       break;
    6987        46694 :     case PFK_FLOW_LIST:
    6988        46694 :       ccol__assert(f->u.fl.seq == NULL && f->u.fl.key_str == NULL);
    6989              :       break;
    6990         8358 :     case PFK_FLOW_DICT:
    6991         8358 :       ccol__assert(f->u.fd.map == NULL && f->u.fd.key_str == NULL &&
    6992              :                    f->u.fd.merges == NULL);
    6993              :       break;
    6994        19163 :     case PFK_BLOCK_LIST:
    6995        19163 :       ccol__assert(f->u.bl.seq == NULL);
    6996              :       break;
    6997         9871 :     case PFK_BLOCK_DICT:
    6998         9871 :       ccol__assert(f->u.bd.map == NULL && f->u.bd.key_owned == NULL &&
    6999              :                    f->u.bd.merges == NULL);
    7000              :       break;
    7001              :   }
    7002              : #endif
    7003       407696 :   if (f->kind != PFK_NODE) ctx->depth--;
    7004       407696 : }
    7005              : 
    7006              : // Runs one step of the frame's state machine, picked by its kind; node frames
    7007              : // are tested first since they're half of all steps.
    7008       889599 : static pstep pframe_step(parse_ctx *ctx, pframe *f, preq *rq) {
    7009       889599 :   if (f->kind == PFK_NODE) return pni_step(ctx, f, rq);
    7010       417880 :   switch (f->kind) {
    7011              :     case PFK_NODE:
    7012              :       break;
    7013       287761 :     case PFK_FLOW_LIST:
    7014       287761 :       return pfl_step(ctx, f, rq);
    7015        39838 :     case PFK_FLOW_DICT:
    7016        39838 :       return pfd_step(ctx, f, rq);
    7017        63457 :     case PFK_BLOCK_LIST:
    7018        63457 :       return pbl_step(ctx, f, rq);
    7019        26824 :     case PFK_BLOCK_DICT:
    7020        26824 :       return pbd_step(ctx, f, rq);
    7021              :   }
    7022              :   return PSTEP_FAIL;
    7023              : }
    7024              : 
    7025              : // Runs one complete walk from root_req and gives the node it made, or NULL on
    7026              : // failure (ctx->error is set unless it was a bare OOM). Every parse of a node
    7027              : // goes through here. The frame stack starts in locals and moves to the heap
    7028              : // past CYAML_PARSE_INLINE_FRAMES, never past CYAML_PARSE_MAX_FRAMES. A finished
    7029              : // node goes straight into the child slot of the frame below, so on failure only
    7030              : // the frames need sweeping. The walk leaves ctx->depth as it found it, which
    7031              : // lets a speculative key parse run its own walk; test builds check that.
    7032         7341 : static cyaml_node *parse_drive(parse_ctx *ctx, const preq *root_req) {
    7033         7341 :   pframe inline_frames[CYAML_PARSE_INLINE_FRAMES];
    7034         7341 :   pframe *stack = inline_frames;
    7035         7341 :   size_t cap = CYAML_PARSE_INLINE_FRAMES;
    7036         7341 :   size_t sp = 0;
    7037         7341 :   cyaml_node *result = NULL;
    7038         7341 :   bool failed = true;
    7039         7341 :   preq req = *root_req;
    7040              : #ifdef RUNNING_UNIT_TESTS
    7041         7341 :   const size_t entry_depth = ctx->depth;
    7042              : #endif
    7043              : 
    7044         7341 :   if (pframe_open(ctx, &stack[0], &req)) {
    7045              :     sp = 1;
    7046       889596 :     failed = false;
    7047              :     pframe *f = stack;
    7048       889596 :     for (;;) {
    7049       889596 :       pstep r = pframe_step(ctx, f, &req);
    7050       889591 :       if (r == PSTEP_DESCEND) {
    7051       479622 :         if (sp == cap) {
    7052         1379 :           if (cap >= CYAML_PARSE_MAX_FRAMES) {
    7053            0 :             parse_depth_err(ctx);
    7054            0 :             failed = true;
    7055            0 :             break;
    7056              :           }
    7057         1379 :           size_t want = cap * 2 < CYAML_PARSE_MAX_FRAMES
    7058              :                             ? cap * 2
    7059              :                             : (size_t)CYAML_PARSE_MAX_FRAMES;
    7060         1379 :           pframe *grown = walk_stack_grow_to(stack, &cap, want, inline_frames,
    7061              :                                              sizeof(*stack), ctx->mp);
    7062         1379 :           if (!grown) {
    7063              :             failed = true;
    7064              :             break;
    7065              :           }
    7066         1376 :           stack = grown;
    7067         1376 :           f = stack + (sp - 1);
    7068              :         }
    7069       479619 :         if (!pframe_open(ctx, f + 1, &req)) {
    7070              :           failed = true;
    7071              :           break;
    7072              :         }
    7073       479585 :         sp++;
    7074       479585 :         f++;
    7075       479585 :         continue;
    7076              :       }
    7077       409969 :       if (r == PSTEP_FAIL) {
    7078              :         failed = true;
    7079              :         break;
    7080              :       }
    7081              :       {
    7082       407689 :         cyaml_node *done_node = f->result;
    7083       407689 :         f->result = NULL;
    7084       407689 :         pframe_release(ctx, f);
    7085       407694 :         sp--;
    7086       407694 :         if (sp == 0) {
    7087              :           result = done_node;
    7088              :           break;
    7089              :         }
    7090       402669 :         f--;
    7091       402669 :         f->child = done_node;
    7092              :       }
    7093              :     }
    7094              :   }
    7095              : 
    7096         7341 :   if (failed) {
    7097        81551 :     while (sp > 0) {
    7098        79233 :       sp--;
    7099        79233 :       pframe_cleanup(ctx, &stack[sp]);
    7100              :     }
    7101              :     result = NULL;
    7102              :   }
    7103         7342 :   if (stack != inline_frames) ccol__mem_free(ctx->mp, stack);
    7104              : 
    7105              : #ifdef RUNNING_UNIT_TESTS
    7106         7342 :   if (cap > cyaml_test_peak_parse_frame_cap)
    7107           63 :     cyaml_test_peak_parse_frame_cap = cap;
    7108         7342 :   ccol__assert(ctx->depth == entry_depth);
    7109              : #endif
    7110         7342 :   return result;
    7111              : }
    7112              : 
    7113              : // Reads one directive line from its '%'. A directive needs a name; unknown
    7114              : // names are accepted and ignored. "%YAML" needs exactly one MAJOR.MINOR with
    7115              : // major 1, and "%TAG" a valid handle and a prefix of ns-uri-char (a '#' is part
    7116              : // of it, and escapes are decoded); after either only whitespace and a comment
    7117              : // may follow, and a handle defined twice is an error. *is_yaml_directive_out
    7118              : // (may be NULL) tells the caller it was "%YAML", so the caller can refuse a
    7119              : // second one in the same document. false with ctx->error set on a malformed
    7120              : // line.
    7121          191 : static bool parse_directive_line(parse_ctx *ctx, bool *is_yaml_directive_out) {
    7122          191 :   size_t start = ctx->pos;
    7123          191 :   ctx->pos++;
    7124          191 :   size_t name_start = ctx->pos;
    7125          995 :   while (!at_end(ctx) && cur(ctx) != ' ' && cur(ctx) != '\t' &&
    7126         1420 :          cur(ctx) != '\n' && cur(ctx) != '\r')
    7127          613 :     ctx->pos++;
    7128          191 :   size_t name_len = ctx->pos - name_start;
    7129          191 :   if (name_len == 0) {
    7130            2 :     parse_err(ctx, "directive with no name at position %zu", start);
    7131            2 :     return false;
    7132              :   }
    7133          189 :   bool is_yaml = name_len == 4 && memcmp(ctx->src + name_start, "YAML", 4) == 0;
    7134          189 :   bool is_tag = name_len == 3 && memcmp(ctx->src + name_start, "TAG", 3) == 0;
    7135          189 :   if (is_yaml_directive_out) *is_yaml_directive_out = is_yaml;
    7136              : 
    7137          189 :   if (is_tag) {
    7138          144 :     if (at_end(ctx) || (cur(ctx) != ' ' && cur(ctx) != '\t')) {
    7139            0 :       parse_err(ctx, "malformed %%TAG directive at position %zu", start);
    7140            0 :       return false;
    7141              :     }
    7142              :     skip_inline_ws(ctx);
    7143              : 
    7144              :     size_t handle_start = ctx->pos;
    7145          573 :     while (!at_end(ctx) && cur(ctx) != ' ' && cur(ctx) != '\t' &&
    7146         1004 :            cur(ctx) != '\n' && cur(ctx) != '\r')
    7147          429 :       ctx->pos++;
    7148          144 :     size_t handle_len = ctx->pos - handle_start;
    7149          144 :     if (handle_len == 0) {
    7150            0 :       parse_err(ctx, "malformed %%TAG directive at position %zu", start);
    7151            0 :       return false;
    7152              :     }
    7153          144 :     char *handle = ccol__mem_alloc(ctx->mp, handle_len + 1);
    7154          144 :     if (!handle) return false;
    7155          144 :     memcpy(handle, ctx->src + handle_start, handle_len);
    7156          144 :     handle[handle_len] = '\0';
    7157              : 
    7158          144 :     bool handle_valid = false;
    7159          144 :     if (handle_len == 1 && handle[0] == '!') {
    7160              :       handle_valid = true;
    7161          136 :     } else if (handle_len == 2 && handle[0] == '!' && handle[1] == '!') {
    7162              :       handle_valid = true;
    7163          133 :     } else if (handle_len >= 3 && handle[0] == '!' &&
    7164          132 :                handle[handle_len - 1] == '!') {
    7165          240 :       handle_valid = true;
    7166          240 :       for (size_t i = 1; i < handle_len - 1; i++) {
    7167          140 :         char hc = handle[i];
    7168          323 :         bool is_word = (hc >= 'a' && hc <= 'z') || (hc >= 'A' && hc <= 'Z') ||
    7169          140 :                        (hc >= '0' && hc <= '9') || hc == '-';
    7170          140 :         if (!is_word) {
    7171              :           handle_valid = false;
    7172              :           break;
    7173              :         }
    7174              :       }
    7175              :     }
    7176          132 :     if (!handle_valid) {
    7177           33 :       parse_err(ctx, "malformed %%TAG handle '%s' at position %zu",
    7178           33 :                 cyaml_echo(handle), start);
    7179           33 :       ccol__mem_free(ctx->mp, handle);
    7180           33 :       return false;
    7181              :     }
    7182              : 
    7183          111 :     if (at_end(ctx) || (cur(ctx) != ' ' && cur(ctx) != '\t')) {
    7184            2 :       parse_err(ctx, "malformed %%TAG directive at position %zu", start);
    7185            2 :       ccol__mem_free(ctx->mp, handle);
    7186            2 :       return false;
    7187              :     }
    7188              :     skip_inline_ws(ctx);
    7189              : 
    7190              :     size_t prefix_start = ctx->pos;
    7191         1215 :     while (!at_end(ctx) && cur(ctx) != ' ' && cur(ctx) != '\t' &&
    7192         2424 :            cur(ctx) != '\n' && cur(ctx) != '\r') {
    7193         1106 :       ctx->pos++;
    7194              :     }
    7195          109 :     size_t prefix_len = ctx->pos - prefix_start;
    7196          109 :     if (prefix_len == 0) {
    7197            1 :       parse_err(ctx, "malformed %%TAG prefix at position %zu", start);
    7198            1 :       ccol__mem_free(ctx->mp, handle);
    7199            1 :       return false;
    7200              :     }
    7201          108 :     char *prefix = ccol__mem_alloc(ctx->mp, prefix_len + 1);
    7202          108 :     if (!prefix) {
    7203            0 :       ccol__mem_free(ctx->mp, handle);
    7204            0 :       return false;
    7205              :     }
    7206          108 :     memcpy(prefix, ctx->src + prefix_start, prefix_len);
    7207          108 :     prefix[prefix_len] = '\0';
    7208          108 :     if (prefix[0] == ',' || prefix[0] == '[' || prefix[0] == ']') {
    7209            1 :       parse_err(ctx,
    7210              :                 "character '%s' at position %zu cannot start a %%TAG prefix",
    7211            1 :                 cyaml_echo_c(prefix[0]), prefix_start);
    7212            1 :       ccol__mem_free(ctx->mp, handle);
    7213            1 :       ccol__mem_free(ctx->mp, prefix);
    7214            1 :       return false;
    7215              :     }
    7216          213 :     if (!tag_text_check(ctx, prefix, prefix_len, prefix_start, false) ||
    7217          106 :         !percent_decode_tag_inplace(ctx, prefix, prefix_start)) {
    7218            4 :       ccol__mem_free(ctx->mp, handle);
    7219            4 :       ccol__mem_free(ctx->mp, prefix);
    7220            4 :       return false;
    7221              :     }
    7222              : 
    7223          103 :     if (!at_end(ctx) && cur(ctx) != ' ' && cur(ctx) != '\t' &&
    7224           97 :         cur(ctx) != '\n' && cur(ctx) != '\r' && cur(ctx) != '#') {
    7225            0 :       parse_err(ctx, "extra content after %%TAG prefix at position %zu",
    7226              :                 ctx->pos);
    7227            0 :       ccol__mem_free(ctx->mp, handle);
    7228            0 :       ccol__mem_free(ctx->mp, prefix);
    7229            0 :       return false;
    7230              :     }
    7231              :     skip_inline_ws(ctx);
    7232          103 :     if (!at_end(ctx) && cur(ctx) != '\n' && cur(ctx) != '\r' &&
    7233            6 :         cur(ctx) != '#') {
    7234            3 :       parse_err(ctx, "extra content after %%TAG prefix at position %zu",
    7235              :                 ctx->pos);
    7236            3 :       ccol__mem_free(ctx->mp, handle);
    7237            3 :       ccol__mem_free(ctx->mp, prefix);
    7238            3 :       return false;
    7239              :     }
    7240              : 
    7241          100 :     ccol_retval set_rv = tag_handles_set(ctx, handle, prefix);
    7242          100 :     ccol__mem_free(ctx->mp, handle);
    7243          100 :     ccol__mem_free(ctx->mp, prefix);
    7244          100 :     if (set_rv == ccol_key_already_present) {
    7245            1 :       parse_err(ctx, "duplicate %%TAG directive for handle at position %zu",
    7246              :                 start);
    7247            1 :       return false;
    7248              :     }
    7249           99 :     if (set_rv != ccol_success) return false;
    7250              : 
    7251           99 :     skip_to_eol(ctx);
    7252           99 :     return true;
    7253              :   }
    7254              : 
    7255           45 :   if (is_yaml) {
    7256           38 :     if (at_end(ctx) || (cur(ctx) != ' ' && cur(ctx) != '\t')) {
    7257            0 :       parse_err(ctx, "malformed %%YAML directive at position %zu", start);
    7258            0 :       return false;
    7259              :     }
    7260              :     skip_inline_ws(ctx);
    7261              :     size_t ver_start = ctx->pos;
    7262           77 :     while (!at_end(ctx) && cur(ctx) >= '0' && cur(ctx) <= '9') ctx->pos++;
    7263           38 :     bool has_major = ctx->pos > ver_start;
    7264           38 :     bool major_is_one = false;
    7265           38 :     if (has_major) {
    7266              :       size_t m = ver_start;
    7267           38 :       while (m < ctx->pos - 1 && ctx->src[m] == '0') m++;
    7268           40 :       major_is_one = ctx->pos - m == 1 && ctx->src[m] == '1';
    7269              :     }
    7270           38 :     bool ok = has_major && !at_end(ctx) && cur(ctx) == '.';
    7271           37 :     if (ok) {
    7272           37 :       ctx->pos++;
    7273           37 :       size_t minor_start = ctx->pos;
    7274           78 :       while (!at_end(ctx) && cur(ctx) >= '0' && cur(ctx) <= '9') ctx->pos++;
    7275           37 :       ok = ctx->pos > minor_start;
    7276              :     }
    7277           37 :     if (!ok) {
    7278            1 :       parse_err(ctx, "malformed %%YAML version at position %zu", start);
    7279            1 :       return false;
    7280              :     }
    7281           37 :     if (!major_is_one) {
    7282            3 :       parse_err(ctx,
    7283              :                 "unsupported %%YAML version at position %zu (only major "
    7284              :                 "version 1 is supported)",
    7285              :                 start);
    7286            3 :       return false;
    7287              :     }
    7288           34 :     if (!at_end(ctx) && cur(ctx) != ' ' && cur(ctx) != '\t' &&
    7289           25 :         cur(ctx) != '\n' && cur(ctx) != '\r') {
    7290            2 :       parse_err(ctx, "extra content after %%YAML version at position %zu",
    7291              :                 ctx->pos);
    7292            2 :       return false;
    7293              :     }
    7294              :     skip_inline_ws(ctx);
    7295           32 :     if (!at_end(ctx) && cur(ctx) != '\n' && cur(ctx) != '\r' &&
    7296            9 :         cur(ctx) != '#') {
    7297            4 :       parse_err(ctx, "extra content after %%YAML version at position %zu",
    7298              :                 ctx->pos);
    7299            4 :       return false;
    7300              :     }
    7301              :   }
    7302              : 
    7303           35 :   skip_to_eol(ctx);
    7304           35 :   return true;
    7305              : }
    7306              : 
    7307              : // Reads a "---" the caller has confirmed, with the separator whitespace (tabs
    7308              : // allowed) and newline after it, and tells through *same_line_content_out
    7309              : // whether content follows on the same line.
    7310          338 : static void consume_doc_start_marker(parse_ctx *ctx,
    7311              :                                      bool *same_line_content_out) {
    7312          338 :   ctx->pos += 3;
    7313          338 :   skip_inline_ws(ctx);
    7314          338 :   *same_line_content_out = !rest_of_line_is_blank(ctx);
    7315          540 :   if (!at_end(ctx) && at_eol(ctx)) skip_newline(ctx);
    7316          338 :   skip_ws_comments(ctx);
    7317          338 : }
    7318              : 
    7319              : // Skips a byte-order mark at the start of a line between documents, which
    7320              : // YAML 1.2 allows before every document (concatenated files). The mark isn't
    7321              : // content, so first_line_start, the line cache and the memo restart after it;
    7322              : // otherwise every column on the line would be off by 3. Gives true when it
    7323              : // skipped one.
    7324        18708 : static bool skip_document_prefix_bom(parse_ctx *ctx) {
    7325        18708 :   size_t p = ctx->pos;
    7326        18708 :   if (ctx->len - p < 3 || (unsigned char)ctx->src[p] != 0xEF ||
    7327           84 :       (unsigned char)ctx->src[p + 1] != 0xBB ||
    7328           84 :       (unsigned char)ctx->src[p + 2] != 0xBF)
    7329              :     return false;
    7330           84 :   if (p > ctx->first_line_start && ctx->src[p - 1] != '\n' &&
    7331              :       ctx->src[p - 1] != '\r')
    7332              :     return false;
    7333           84 :   p += 3;
    7334           84 :   ctx->pos = p;
    7335           84 :   ctx->first_line_start = p;
    7336           84 :   if (!ctx->line_cache_disabled) {
    7337           84 :     ctx->line_starts[0] = p;
    7338           84 :     ctx->line_starts_len = 1;
    7339           84 :     ctx->line_scan_pos = p;
    7340              :   }
    7341           84 :   ctx->memo_pos = SIZE_MAX;
    7342           84 :   return true;
    7343              : }
    7344              : 
    7345              : // Parses one document: Optional directives (each needs a "---" after it), an
    7346              : // optional "---", one root node, and an optional "...". Content on the same
    7347              : // line as "---" may only be a flow node, and a '%' after this document's own
    7348              : // "---" belongs to the next document. On success ctx->pos is past the document
    7349              : // and *consumed_end_marker tells whether a "..." was read, which the next
    7350              : // document needs to leave out its own "---". The anchor and %TAG tables are
    7351              : // always destroyed before it returns. NULL with ctx->error set on failure.
    7352         7039 : static cyaml_node *parse_one_document(parse_ctx *ctx,
    7353              :                                       bool *consumed_end_marker) {
    7354         7039 :   bool doc_marker_same_line_content = false;
    7355              : 
    7356         7039 :   bool consumed_leading_dashes = false;
    7357              : 
    7358         7254 :   if (at_doc_marker(ctx) && memcmp(ctx->src + ctx->pos, "---", 3) == 0) {
    7359          213 :     consume_doc_start_marker(ctx, &doc_marker_same_line_content);
    7360          213 :     consumed_leading_dashes = true;
    7361              :   }
    7362              : 
    7363         7039 :   bool saw_directive = false;
    7364         7039 :   bool saw_yaml_directive = false;
    7365         7039 :   bool consumed_doc_start_after_directive = false;
    7366         7046 :   while (!consumed_leading_dashes && !at_end(ctx) && cur(ctx) == '%') {
    7367          191 :     saw_directive = true;
    7368          191 :     bool is_yaml_directive = false;
    7369          191 :     if (!parse_directive_line(ctx, &is_yaml_directive)) {
    7370           57 :       anchors_destroy(ctx);
    7371           57 :       tag_handles_destroy(ctx);
    7372           59 :       return NULL;
    7373              :     }
    7374          134 :     if (is_yaml_directive) {
    7375           28 :       if (saw_yaml_directive) {
    7376            2 :         parse_err(ctx,
    7377              :                   "duplicate %%YAML directive for the same document "
    7378              :                   "at position %zu",
    7379              :                   ctx->pos);
    7380            2 :         anchors_destroy(ctx);
    7381            2 :         tag_handles_destroy(ctx);
    7382            2 :         return NULL;
    7383              :       }
    7384              :       saw_yaml_directive = true;
    7385              :     }
    7386          132 :     skip_ws_comments(ctx);
    7387          264 :     if (at_doc_marker(ctx) && memcmp(ctx->src + ctx->pos, "---", 3) == 0) {
    7388          125 :       consume_doc_start_marker(ctx, &doc_marker_same_line_content);
    7389          125 :       consumed_doc_start_after_directive = true;
    7390          125 :       consumed_leading_dashes = true;
    7391          125 :       break;
    7392              :     }
    7393              :   }
    7394         6980 :   if (saw_directive && !consumed_doc_start_after_directive) {
    7395            2 :     parse_err(ctx,
    7396              :               "directive requires an explicit '---' document start at "
    7397              :               "position %zu",
    7398              :               ctx->pos);
    7399            2 :     anchors_destroy(ctx);
    7400            2 :     tag_handles_destroy(ctx);
    7401            2 :     return NULL;
    7402              :   }
    7403              : 
    7404         6978 :   cyaml_node *root;
    7405        13939 :   if (at_end(ctx) || at_doc_marker(ctx) ||
    7406         6961 :       (current_col(ctx) == 0 && cur(ctx) == '%')) {
    7407           20 :     root = node_alloc(CYAML_NULL, ctx->mp);
    7408         6958 :   } else if (doc_marker_same_line_content && at_bare_seq_indicator(ctx)) {
    7409            2 :     parse_err(ctx,
    7410              :               "a block sequence cannot start on the same line as "
    7411              :               "its document start marker at position %zu",
    7412              :               ctx->pos);
    7413            2 :     root = NULL;
    7414              :   } else {
    7415         6956 :     root = parse_node(ctx, -1, false, false, !doc_marker_same_line_content,
    7416         6956 :                       false, false, NULL);
    7417              :   }
    7418              : 
    7419         6978 :   anchors_destroy(ctx);
    7420         6977 :   tag_handles_destroy(ctx);
    7421              : 
    7422         6977 :   if (!root) return NULL;
    7423              : 
    7424         4689 :   skip_ws_comments(ctx);
    7425         4690 :   *consumed_end_marker = false;
    7426         4823 :   while (at_doc_marker(ctx) && memcmp(ctx->src + ctx->pos, "...", 3) == 0) {
    7427           41 :     ctx->pos += 3;
    7428           41 :     skip_inline_ws(ctx);
    7429           82 :     if (!at_end(ctx) && !at_eol(ctx) && cur(ctx) != '#') {
    7430            4 :       parse_err(ctx,
    7431              :                 "unexpected content after '...' document end marker "
    7432              :                 "at position %zu",
    7433              :                 ctx->pos);
    7434            4 :       cyaml__destroy((cyaml)root);
    7435            4 :       return NULL;
    7436              :     }
    7437           71 :     if (!at_end(ctx) && at_eol(ctx)) skip_newline(ctx);
    7438           37 :     *consumed_end_marker = true;
    7439           37 :     skip_ws_comments(ctx);
    7440              :   }
    7441              : 
    7442              :   return root;
    7443              : }
    7444              : 
    7445              : // The size of the per-thread buffer behind err_str. The err out-parameter of
    7446              : // every module has one rule (the library owns the string, the caller never
    7447              : // frees it), and this parser's messages are built at run time, so they live in
    7448              : // a heap buffer per thread instead of being allocated per message. The text
    7449              : // stays valid until the next failing parse on the same thread. A __thread array
    7450              : // would make the TLS block too large for dlopen(). 512 is the size of
    7451              : // parse_ctx.error, where every message is built.
    7452              : #define CYAML_ERR_BUF_LEN 512
    7453              : // The message used when the thread can't keep a buffer (OOM, or the pool key
    7454              : // can't be armed so nothing would free it).
    7455              : static const char cyaml_err_unstored[] =
    7456              :     "parse failed; the error message could not be stored";
    7457              : 
    7458              : // Gives the calling thread's message buffer, allocated on first use, for
    7459              : // cyaml_report_err(). NULL when the allocation fails or the pool key can't be
    7460              : // armed, since only the key's thread-exit drain frees the buffer.
    7461         9909 : static char *cyaml_err_storage(void) {
    7462              : #if defined(CCOL__EMULATE_DARWIN_TLS)
    7463              :   ccol__call_once(pool_key_once, do_pool_key_init);
    7464              :   cyaml_tls *t = cyaml_tls_get();
    7465              :   if (!t) return NULL;
    7466              :   if (!t->err_buf) t->err_buf = malloc(CYAML_ERR_BUF_LEN);
    7467              :   return t->err_buf;
    7468              : #else
    7469         9909 :   if (!cyaml_err_buf) {
    7470           54 :     char *buf = malloc(CYAML_ERR_BUF_LEN);
    7471           54 :     if (!buf) return NULL;
    7472           54 :     ccol__call_once(pool_key_once, do_pool_key_init);
    7473           54 :     pool_key_arm();
    7474           54 :     if (!pool_key_armed) {
    7475           51 :       free(buf);
    7476           51 :       return NULL;
    7477              :     }
    7478            3 :     cyaml_err_buf = buf;
    7479              :   }
    7480         9858 :   return cyaml_err_buf;
    7481              : #endif
    7482              : }
    7483              : 
    7484              : #ifdef RUNNING_UNIT_TESTS
    7485              : // Test builds only: Ends the process when a parse message isn't printable
    7486              : // ASCII, right where the message is reported, so the tests and fuzz targets
    7487              : // catch an echo that was missed.
    7488         9911 : static void cyaml_err_assert_printable(const char *msg) {
    7489       990033 :   for (const unsigned char *p = (const unsigned char *)msg; *p; p++) {
    7490       980122 :     if (*p < 0x20 || *p > 0x7E) {
    7491            0 :       fprintf(stderr, "cyaml error message holds byte 0x%02X: ", *p);
    7492            0 :       for (const unsigned char *q = (const unsigned char *)msg; *q; q++)
    7493            0 :         fprintf(stderr, (*q >= 0x20 && *q <= 0x7E) ? "%c" : "<0x%02X>", *q);
    7494            0 :       fputc('\n', stderr);
    7495            0 :       abort();
    7496              :     }
    7497              :   }
    7498         9911 : }
    7499              : #endif
    7500              : 
    7501              : // Copies msg into the per-thread buffer and points *err_str at it, or at the
    7502              : // fixed message when there is no buffer. Every failing parse reports through
    7503              : // it. Does nothing for a NULL err_str.
    7504         2476 : static void cyaml_report_err(char **err_str, const char *msg) {
    7505              : #ifdef RUNNING_UNIT_TESTS
    7506         2476 :   cyaml_err_assert_printable(msg);
    7507              : #endif
    7508         2476 :   if (!err_str) return;
    7509         2474 :   char *buf = cyaml_err_storage();
    7510         2474 :   if (!buf) {
    7511           51 :     *err_str = (char *)cyaml_err_unstored;
    7512           51 :     return;
    7513              :   }
    7514         2423 :   snprintf(buf, CYAML_ERR_BUF_LEN, "%s", msg);
    7515         2423 :   *err_str = buf;
    7516              : }
    7517              : 
    7518              : // The body of every parse: Checks the whole input for c-printable UTF-8, arms
    7519              : // the budgets, allocates the line cache (its failure fails the parse), skips
    7520              : // BOMs of the first document prefix and parses each document. One document
    7521              : // gives its root; several give a list of roots, where each document after the
    7522              : // first needs "---" unless a "..." ended the previous one, and each starts at
    7523              : // depth 1 (a first document at the limit is refused once a second follows). An
    7524              : // empty input gives a null node. On failure *err_str gets the message (an error
    7525              : // with no message is reported as a named budget limit or as OOM), every
    7526              : // finished document is destroyed and NULL comes back. *err_str is NULL only on
    7527              : // success. The budgets are disarmed on every exit.
    7528        14438 : static cyaml parse_common(const char *src, size_t len, char **err_str,
    7529              :                           ccol_memmgmt_procs *mp) {
    7530        14438 :   if (!src) {
    7531            3 :     cyaml_report_err(err_str, "null input");
    7532            3 :     return NULL;
    7533              :   }
    7534        14435 :   size_t refused_at = cyaml_first_refused_char((const unsigned char *)src, len);
    7535        14434 :   if (refused_at != len) {
    7536         7435 :     if (err_str) {
    7537         7435 :       char *buf = cyaml_err_storage();
    7538         7435 :       if (!buf) {
    7539            0 :         *err_str = (char *)cyaml_err_unstored;
    7540            0 :         return NULL;
    7541              :       }
    7542         7435 :       cyaml_describe_refused_char((const unsigned char *)src, len, refused_at,
    7543              :                                   buf, CYAML_ERR_BUF_LEN);
    7544              : #ifdef RUNNING_UNIT_TESTS
    7545         7435 :       cyaml_err_assert_printable(buf);
    7546              : #endif
    7547         7435 :       *err_str = buf;
    7548              :     }
    7549         7435 :     return NULL;
    7550              :   }
    7551        10049 :   if (!cyaml_intern_procs(&mp)) {
    7552            1 :     cyaml_report_err(err_str,
    7553              :                      "too many distinct allocator procs in this process");
    7554            1 :     return NULL;
    7555              :   }
    7556         6998 :   parse_ctx ctx = {.src = src,
    7557              :                    .pos = 0,
    7558              :                    .len = len,
    7559              :                    .error = "",
    7560              :                    .mp = mp,
    7561              :                    .anchors = NULL,
    7562              :                    .memo_pos = SIZE_MAX};
    7563         6998 :   parse_node_budget_arm(len);
    7564              : 
    7565         6999 :   ctx.line_starts = ccol__mem_alloc(mp, 64 * sizeof(size_t));
    7566         6999 :   if (!ctx.line_starts) {
    7567           20 :     cyaml_report_err(err_str, "out of memory");
    7568           20 :     parse_node_budget_disarm();
    7569           20 :     return NULL;
    7570              :   }
    7571         6979 :   ctx.line_starts_cap = 64;
    7572         6979 :   ctx.line_starts[0] = 0;
    7573         6979 :   ctx.line_starts_len = 1;
    7574              : 
    7575        14032 :   while (skip_document_prefix_bom(&ctx)) {
    7576         7053 :   }
    7577              : 
    7578              : #ifdef RUNNING_UNIT_TESTS
    7579         6979 :   if (cyaml_test_force_line_cache_disabled) ctx.line_cache_disabled = true;
    7580              : #endif
    7581              : 
    7582         6979 :   skip_ws_comments(&ctx);
    7583         6980 :   while (skip_document_prefix_bom(&ctx)) skip_ws_comments(&ctx);
    7584              : 
    7585              :   cyaml_node **docs = NULL;
    7586              :   size_t ndocs = 0;
    7587              :   size_t dcap = 0;
    7588              :   bool prev_consumed_end_marker = false;
    7589              :   size_t bom_pos = SIZE_MAX;
    7590              : 
    7591              :   size_t first_doc_peak = 0;
    7592              : 
    7593        11645 :   while (!at_end(&ctx)) {
    7594         7118 :     if (ndocs > 0 && !prev_consumed_end_marker) {
    7595          180 :       if (!at_doc_marker(&ctx) || memcmp(ctx.src + ctx.pos, "---", 3) != 0) {
    7596           78 :         char buf[128];
    7597           78 :         if (bom_pos != SIZE_MAX)
    7598            3 :           snprintf(buf, sizeof(buf),
    7599              :                    "byte order mark inside a document at position %zu; a "
    7600              :                    "byte order mark may only precede a document",
    7601              :                    bom_pos);
    7602              :         else
    7603           75 :           snprintf(buf, sizeof(buf), "trailing content at position %zu",
    7604              :                    ctx.pos);
    7605           78 :         cyaml_report_err(err_str, buf);
    7606           78 :         goto fail;
    7607              :       }
    7608              :     }
    7609              : 
    7610         7040 :     if (ndocs == 1 && first_doc_peak >= CYAML_MAX_NESTING_DEPTH) {
    7611            1 :       char buf[192];
    7612            1 :       snprintf(buf, sizeof(buf),
    7613              :                "maximum nesting depth (%d) exceeded at position %zu: the "
    7614              :                "first document nests %d containers, and the list of a "
    7615              :                "stream of several documents adds one more",
    7616              :                CYAML_MAX_NESTING_DEPTH, ctx.pos, CYAML_MAX_NESTING_DEPTH);
    7617            1 :       cyaml_report_err(err_str, buf);
    7618            1 :       goto fail;
    7619              :     }
    7620         7039 :     ctx.depth = (ndocs > 0) ? 1 : 0;
    7621         7039 :     ctx.peak_depth = ctx.depth;
    7622         7039 :     bool consumed_end_marker = false;
    7623         7039 :     cyaml_node *root = parse_one_document(&ctx, &consumed_end_marker);
    7624         7039 :     if (ndocs == 0) first_doc_peak = ctx.peak_depth;
    7625         7039 :     if (!root) {
    7626         2353 :       if (ctx.error[0]) {
    7627         1736 :         cyaml_report_err(err_str, ctx.error);
    7628              :       } else {
    7629          617 :         char buf[128];
    7630          617 :         if (parse_node_budget_exhausted)
    7631            0 :           snprintf(buf, sizeof(buf),
    7632              :                    "document exceeded the %zu node-allocation limit at "
    7633              :                    "position %zu",
    7634              :                    parse_node_limit, ctx.pos);
    7635          617 :         else if (parse_byte_budget_exhausted)
    7636            0 :           snprintf(buf, sizeof(buf),
    7637              :                    "document exceeded the %zu-byte memory limit at "
    7638              :                    "position %zu",
    7639              :                    parse_byte_limit, ctx.pos);
    7640              :         else
    7641          617 :           snprintf(buf, sizeof(buf),
    7642              :                    "out of memory (unreported allocation failure) at "
    7643              :                    "position %zu",
    7644              :                    ctx.pos);
    7645          617 :         cyaml_report_err(err_str, buf);
    7646              :       }
    7647         2353 :       goto fail;
    7648              :     }
    7649              : 
    7650         4686 :     if (ndocs == dcap) {
    7651         4626 :       size_t new_cap = dcap ? dcap * 2 : 4;
    7652         9252 :       cyaml_node **nd =
    7653         4626 :           ccol__mem_realloc(mp, docs, new_cap * sizeof(cyaml_node *));
    7654         4626 :       if (!nd) {
    7655           20 :         cyaml__destroy((cyaml)root);
    7656           20 :         cyaml_report_err(err_str, "out of memory");
    7657           20 :         goto fail;
    7658              :       }
    7659              :       docs = nd;
    7660              :       dcap = new_cap;
    7661              :     }
    7662         4666 :     docs[ndocs++] = root;
    7663         4666 :     prev_consumed_end_marker = consumed_end_marker;
    7664              : 
    7665         4666 :     skip_ws_comments(&ctx);
    7666         4666 :     bom_pos = ctx.pos;
    7667         4666 :     if (skip_document_prefix_bom(&ctx)) {
    7668            9 :       skip_ws_comments(&ctx);
    7669            9 :       while (skip_document_prefix_bom(&ctx)) skip_ws_comments(&ctx);
    7670              :     } else {
    7671              :       bom_pos = SIZE_MAX;
    7672              :     }
    7673              :   }
    7674              : 
    7675         4527 :   if (ndocs == 0) {
    7676            6 :     ccol__mem_free(mp, docs);
    7677            6 :     cyaml_node *empty = node_alloc(CYAML_NULL, mp);
    7678            6 :     if (!empty) {
    7679            0 :       cyaml_report_err(err_str, "out of memory");
    7680            0 :       parse_node_budget_disarm();
    7681            0 :       ccol__mem_free(mp, ctx.line_starts);
    7682            0 :       return NULL;
    7683              :     }
    7684            6 :     if (err_str) *err_str = NULL;
    7685            6 :     parse_node_budget_disarm();
    7686            6 :     ccol__mem_free(mp, ctx.line_starts);
    7687            6 :     return (cyaml)empty;
    7688              :   }
    7689              : 
    7690         4521 :   if (ndocs == 1) {
    7691         4475 :     cyaml_node *result = docs[0];
    7692         4475 :     ccol__mem_free(mp, docs);
    7693         4475 :     if (err_str) *err_str = NULL;
    7694         4475 :     parse_node_budget_disarm();
    7695         4475 :     ccol__mem_free(mp, ctx.line_starts);
    7696         4475 :     return (cyaml)result;
    7697              :   }
    7698              : 
    7699           46 :   cyaml_node *list = (cyaml_node *)cyaml_create_list_interned(mp);
    7700           46 :   if (!list) {
    7701            0 :     cyaml_report_err(err_str, "out of memory");
    7702            0 :     goto fail;
    7703              :   }
    7704          154 :   for (size_t i = 0; i < ndocs; i++) {
    7705          108 :     cyaml_node *elem = docs[i];
    7706          108 :     if (cvector_push_back(list->value.list, &elem) != ccol_success) {
    7707            0 :       for (size_t j = i; j < ndocs; j++) cyaml__destroy((cyaml)docs[j]);
    7708            0 :       ccol__mem_free(mp, docs);
    7709            0 :       cyaml__destroy((cyaml)list);
    7710            0 :       cyaml_report_err(err_str, "out of memory");
    7711            0 :       parse_node_budget_disarm();
    7712            0 :       ccol__mem_free(mp, ctx.line_starts);
    7713            0 :       return NULL;
    7714              :     }
    7715          108 :     elem->attached = true;
    7716              :   }
    7717           46 :   ccol__mem_free(mp, docs);
    7718           46 :   if (err_str) *err_str = NULL;
    7719           46 :   parse_node_budget_disarm();
    7720           46 :   ccol__mem_free(mp, ctx.line_starts);
    7721              :   return (cyaml)list;
    7722              : 
    7723         2452 : fail:
    7724         2452 :   parse_node_budget_disarm();
    7725         2535 :   for (size_t i = 0; i < ndocs; i++) cyaml__destroy((cyaml)docs[i]);
    7726         2452 :   ccol__mem_free(mp, docs);
    7727         2452 :   ccol__mem_free(mp, ctx.line_starts);
    7728              :   return NULL;
    7729              : }
    7730              : 
    7731              : // Runs parse_common() inside one C locale scope, so a float always reads with
    7732              : // '.' whatever LC_NUMERIC the thread uses. Two uselocale() calls per parse and
    7733              : // nothing per scalar.
    7734        14436 : static cyaml parse_in_c_locale(const char *src, size_t len, char **err_str,
    7735              :                                ccol_memmgmt_procs *mp) {
    7736        14436 :   ccol_c_locale_scope scope = ccol_c_locale_enter();
    7737        14436 :   cyaml root = parse_common(src, len, err_str, mp);
    7738        14436 :   ccol_c_locale_leave(scope);
    7739        14437 :   return root;
    7740              : }
    7741              : 
    7742              : // Parses a NUL-terminated YAML string with allocator mp (NULL for the default),
    7743              : // the public entry point. mp is interned first. On failure *err_str (when not
    7744              : // NULL) points at the per-thread message, which the caller never frees.
    7745         5132 : cyaml cyaml_parse_mp(const char *yaml_str, char **err_str,
    7746              :                      ccol_memmgmt_procs *mp) {
    7747         5132 :   if (!yaml_str) return parse_common(NULL, 0, err_str, mp);
    7748         5130 :   return parse_in_c_locale(yaml_str, strlen(yaml_str), err_str, mp);
    7749              : }
    7750              : 
    7751              : // Parses exactly len bytes of YAML, so the input needn't end with a NUL. The
    7752              : // rest is as for cyaml_parse_mp().
    7753         9306 : cyaml cyaml_parse_n_mp(const char *yaml_str, size_t len, char **err_str,
    7754              :                        ccol_memmgmt_procs *mp) {
    7755         9306 :   return parse_in_c_locale(yaml_str, len, err_str, mp);
    7756              : }
    7757              : 
    7758              : // True when n's tag is a core tag that names n's type, so the serializer can
    7759              : // leave it out: The output already reads back as that type. A mismatched core
    7760              : // tag, which no public call can make, would go out verbatim instead of
    7761              : // vanishing.
    7762         7247 : static bool tag_matches_node_type(const cyaml_node *n) {
    7763         7247 :   if (!n->tag) return false;
    7764         7247 :   cyaml_node_type expected;
    7765         7247 :   if (!core_tag_expected_type(n->tag, &expected)) return false;
    7766           45 :   return n->type == expected;
    7767              : }
    7768              : 
    7769              : // The bytes needs_quoting() inspects more closely: NUL, the refused controls
    7770              : // and tab, line breaks, the indicators "?,[]{}:#", and the UTF-8 lead bytes
    7771              : // 0xC2, 0xE2 and 0xEF. Every other byte costs one table load.
    7772              : static const unsigned char cyaml_nq_class[256] = {
    7773              :     [0x00] = 1, [0x01] = 1, [0x02] = 1, [0x03] = 1, [0x04] = 1, [0x05] = 1,
    7774              :     [0x06] = 1, [0x07] = 1, [0x08] = 1, [0x09] = 1, [0x0A] = 1, [0x0B] = 1,
    7775              :     [0x0C] = 1, [0x0D] = 1, [0x0E] = 1, [0x0F] = 1, [0x10] = 1, [0x11] = 1,
    7776              :     [0x12] = 1, [0x13] = 1, [0x14] = 1, [0x15] = 1, [0x16] = 1, [0x17] = 1,
    7777              :     [0x18] = 1, [0x19] = 1, [0x1A] = 1, [0x1B] = 1, [0x1C] = 1, [0x1D] = 1,
    7778              :     [0x1E] = 1, [0x1F] = 1, [0x7F] = 1, ['?'] = 1,  [','] = 1,  ['['] = 1,
    7779              :     [']'] = 1,  ['{'] = 1,  ['}'] = 1,  [':'] = 1,  ['#'] = 1,  [0xC2] = 1,
    7780              :     [0xE2] = 1, [0xEF] = 1};
    7781              : 
    7782              : // Tells whether the serializer must quote s instead of writing a plain scalar.
    7783              : // Quoted are: "", a leading U+FEFF (a parse would drop it as a BOM), every
    7784              : // spelling a parse reads as another type (null, bools, special floats, "<<",
    7785              : // "=", and the YAML 1.1 booleans such as "yes" and "no", which 1.1 readers
    7786              : // would misread), a leading indicator, a number-like start ("+.N" included),
    7787              : // and text holding a line break, tab, '?', flow indicator, " #", a C0 or C1
    7788              : // control, NEL/LS/PS, U+FFFE/U+FFFF, or trailing whitespace. The ambiguous
    7789              : // words are matched with a switch on the first byte and constant-size memcmp.
    7790              : // Runs in the C locale.
    7791        26711 : static bool needs_quoting(const char *s) {
    7792        26711 :   if (!s || s[0] == '\0') return true;
    7793              : 
    7794        26709 :   if ((unsigned char)s[0] == 0xEF && (unsigned char)s[1] == 0xBB &&
    7795            3 :       (unsigned char)s[2] == 0xBF)
    7796              :     return true;
    7797              : 
    7798              :   size_t len = 0;
    7799        91387 :   while (len < 6 && s[len] != '\0') len++;
    7800              : #define CYAML_IS(lit) \
    7801              :   (len == sizeof(lit) - 1 && memcmp(s, (lit), sizeof(lit) - 1) == 0)
    7802        26706 :   bool ambiguous = false;
    7803        26706 :   switch (s[0]) {
    7804            3 :     case '~':
    7805            3 :       ambiguous = CYAML_IS("~");
    7806              :       break;
    7807         9099 :     case 'n':
    7808         9099 :       ambiguous = CYAML_IS("null") || CYAML_IS("n") || CYAML_IS("no");
    7809         9099 :       break;
    7810           26 :     case 'N':
    7811           26 :       ambiguous = CYAML_IS("Null") || CYAML_IS("NULL") || CYAML_IS("N") ||
    7812           31 :                   CYAML_IS("No") || CYAML_IS("NO");
    7813           26 :       break;
    7814           18 :     case 't':
    7815           18 :       ambiguous = CYAML_IS("true");
    7816              :       break;
    7817            8 :     case 'T':
    7818            8 :       ambiguous = CYAML_IS("True") || CYAML_IS("TRUE");
    7819              :       break;
    7820           13 :     case 'f':
    7821           13 :       ambiguous = CYAML_IS("false");
    7822              :       break;
    7823            8 :     case 'F':
    7824            8 :       ambiguous = CYAML_IS("False") || CYAML_IS("FALSE");
    7825              :       break;
    7826           17 :     case '.':
    7827           10 :       ambiguous = CYAML_IS(".inf") || CYAML_IS(".Inf") || CYAML_IS(".INF") ||
    7828           23 :                   CYAML_IS(".nan") || CYAML_IS(".NaN") || CYAML_IS(".NAN");
    7829           17 :       break;
    7830           25 :     case '+':
    7831           25 :       ambiguous = CYAML_IS("+.inf") || CYAML_IS("+.Inf") || CYAML_IS("+.INF");
    7832           25 :       break;
    7833           34 :     case '-':
    7834           34 :       ambiguous = CYAML_IS("-.inf") || CYAML_IS("-.Inf") || CYAML_IS("-.INF");
    7835           34 :       break;
    7836           27 :     case 'y':
    7837           27 :       ambiguous = CYAML_IS("y") || CYAML_IS("yes");
    7838              :       break;
    7839           11 :     case 'Y':
    7840           11 :       ambiguous = CYAML_IS("Y") || CYAML_IS("Yes") || CYAML_IS("YES");
    7841           11 :       break;
    7842           15 :     case 'o':
    7843           15 :       ambiguous = CYAML_IS("on") || CYAML_IS("off");
    7844              :       break;
    7845           16 :     case 'O':
    7846           16 :       ambiguous = CYAML_IS("On") || CYAML_IS("ON") || CYAML_IS("Off") ||
    7847            4 :                   CYAML_IS("OFF");
    7848           16 :       break;
    7849            3 :     case '<':
    7850            3 :       ambiguous = CYAML_IS("<<");
    7851              :       break;
    7852            8 :     case '=':
    7853            8 :       ambiguous = len == 1;
    7854            8 :       break;
    7855              :     default:
    7856              :       break;
    7857              :   }
    7858              : #undef CYAML_IS
    7859         9236 :   if (ambiguous) return true;
    7860              : 
    7861        17531 :   const char *p = s;
    7862              : 
    7863        17531 :   char fc = *p;
    7864        17531 :   if (fc == '-' || fc == '?' || fc == ':' || fc == ',' || fc == '[' ||
    7865              :       fc == ']' || fc == '{' || fc == '}' || fc == '#' || fc == '&' ||
    7866              :       fc == '*' || fc == '!' || fc == '|' || fc == '>' || fc == '\'' ||
    7867              :       fc == '"' || fc == '%' || fc == '@' || fc == '`' || fc == ' ' ||
    7868              :       fc == '\t')
    7869              :     return true;
    7870              : 
    7871              :   if (fc >= '0' && fc <= '9') return true;
    7872           19 :   if (fc == '+' && (s[1] >= '0' && s[1] <= '9')) return true;
    7873           11 :   if (fc == '+' && s[1] == '.') {
    7874            9 :     char *endp = NULL;
    7875            9 :     (void)strtod(s, &endp);
    7876            9 :     if (endp != s && *endp == '\0') return true;
    7877              :   }
    7878        17411 :   if (fc == '.') return true;
    7879              : 
    7880       291493 :   for (;; p++) {
    7881       308899 :     char c = *p;
    7882       308899 :     if (__builtin_expect(!cyaml_nq_class[(unsigned char)c], 1)) continue;
    7883        17418 :     if (c == '\0') break;
    7884              :     if (c == '\n' || c == '\r') return true;
    7885              :     if (c == '\t') return true;
    7886              :     if (c == '?') return true;
    7887           21 :     if ((unsigned char)c == 0xE2 && (unsigned char)p[1] == 0x80 &&
    7888           21 :         ((unsigned char)p[2] == 0xA8 || (unsigned char)p[2] == 0xA9))
    7889              :       return true;
    7890          194 :     if ((unsigned char)c == 0xC2 && (unsigned char)p[1] >= 0x80 &&
    7891           59 :         (unsigned char)p[1] <= 0x9F)
    7892              :       return true;
    7893          137 :     if ((unsigned char)c == 0xEF && (unsigned char)p[1] == 0xBF &&
    7894           29 :         ((unsigned char)p[2] == 0xBE || (unsigned char)p[2] == 0xBF))
    7895              :       return true;
    7896         9586 :     if (is_disallowed_control_byte(c)) return true;
    7897              :     if (c == ',' || c == '[' || c == ']' || c == '{' || c == '}') return true;
    7898              :     if (c == ':') {
    7899           16 :       char nx = *(p + 1);
    7900           16 :       if (nx == ' ' || nx == '\t' || nx == '\n' || nx == '\r' || nx == '\0' ||
    7901              :           nx == ',' || nx == ']' || nx == '}')
    7902              :         return true;
    7903              :     }
    7904           13 :     if (c == '#' && (*(p - 1) == ' ' || *(p - 1) == '\t')) return true;
    7905              :   }
    7906        17167 :   if (p > s && (*(p - 1) == ' ' || *(p - 1) == '\t')) return true;
    7907              :   return false;
    7908              : }
    7909              : 
    7910              : static int lltoa_y(char *buf, long long v);
    7911              : 
    7912              : // Tells whether the key s is exactly the canonical text of an int or float key,
    7913              : // which the serializer writes unquoted so readers keep the numeric type; a
    7914              : // parse turns it back into the same key. Other spellings ("010", "0x10") stay
    7915              : // quoted.
    7916        20108 : static bool key_is_canonical_number(const char *s) {
    7917        20108 :   if (!((s[0] >= '0' && s[0] <= '9') || s[0] == '-' || s[0] == '.'))
    7918              :     return false;
    7919           74 :   char canon[CYAML_FLOAT_KEY_BUF_LEN];
    7920           74 :   long long ival;
    7921           74 :   double dval;
    7922           74 :   if (try_parse_int_scalar(s, &ival)) {
    7923           20 :     lltoa_y(canon, ival);
    7924           54 :   } else if (try_parse_float_scalar(s, &dval)) {
    7925           38 :     format_float_key(dval, canon);
    7926              :   } else {
    7927           16 :     return false;
    7928              :   }
    7929           58 :   return strcmp(s, canon) == 0;
    7930              : }
    7931              : 
    7932              : // Tells whether the serializer must quote the dictionary key s: Canonical
    7933              : // numbers go out plain, everything else follows needs_quoting().
    7934        20108 : static bool key_needs_quoting(const char *s) {
    7935        20108 :   if (s && key_is_canonical_number(s)) return false;
    7936        20078 :   return needs_quoting(s);
    7937              : }
    7938              : 
    7939              : // Appends n bytes of d to b, but never lets b grow past limit + 1 bytes; later
    7940              : // calls add nothing. The canonical key builder relies on it to stop at the
    7941              : // first byte past CYAML_MAX_CANONICAL_KEY_LEN. Callers without a limit pass
    7942              : // SIZE_MAX as a constant, so the test folds away.
    7943       325093 : static inline __attribute__((always_inline)) void yb_put(ybuf *b, const char *d,
    7944              :                                                          size_t n,
    7945              :                                                          size_t limit) {
    7946       325093 :   if (limit != SIZE_MAX) {
    7947       209972 :     if (b->oom || b->len > limit) return;
    7948       214776 :     size_t room = limit - b->len;
    7949       208490 :     if (n > room) n = room + 1;
    7950              :   }
    7951       216249 :   yb_append(b, d, n);
    7952              : }
    7953              : 
    7954              : // True once a capped build has gone past its limit, so the canonical key walk
    7955              : // can stop.
    7956       210440 : static inline __attribute__((always_inline)) bool yb_over(const ybuf *b,
    7957              :                                                           size_t limit) {
    7958        30878 :   return limit != SIZE_MAX && b->len > limit;
    7959              : }
    7960              : 
    7961              : // Hex digits for the "\xNN" escapes of the double-quoted writer.
    7962              : static const char cyaml_hex_lower[] = "0123456789abcdef";
    7963              : 
    7964              : // Nonzero for a byte that ends a run a double-quoted scalar holds as it is:
    7965              : // every C0 control (NUL included, so no end test is needed), '"', '\\', DEL,
    7966              : // and the lead bytes 0xC2, 0xE2 and 0xEF of sequences that may need an escape.
    7967              : static const unsigned char cyaml_dq_stop[256] = {
    7968              :     [0x00 ... 0x1F] = 1, ['"'] = 1,  ['\\'] = 1, [0x7F] = 1,
    7969              :     [0xC2] = 1,          [0xE2] = 1, [0xEF] = 1};
    7970              : 
    7971              : // Writes s as a double-quoted scalar into b, within limit + 1 bytes (see
    7972              : // yb_put()). Runs that need no escape go out in one append and escapes come
    7973              : // from tables. NEL, LS and PS become \N, \L and \P (1.1 readers fold them raw),
    7974              : // C1 controls and U+FFFE/U+FFFF get escapes since readers refuse them raw.
    7975         9546 : static inline __attribute__((always_inline)) void yb_dquoted_body(
    7976              :     ybuf *b, const char *s, size_t limit) {
    7977        19092 :   yb_put(b, "\"", 1, limit);
    7978         9546 :   if (!s) {
    7979            0 :     yb_put(b, "\"", 1, limit);
    7980            0 :     return;
    7981              :   }
    7982              :   const unsigned char *p = (const unsigned char *)s;
    7983              :   const unsigned char *run = p;
    7984              :   for (;;) {
    7985       224624 :     while (!cyaml_dq_stop[*p]) p++;
    7986       196539 :     unsigned char c = *p;
    7987       196539 :     if (c == 0xC2 || c == 0xE2 || c == 0xEF) {
    7988       196713 :       bool special = c == 0xC2 ? (p[1] >= 0x80 && p[1] <= 0x9F)
    7989          101 :                      : c == 0xE2
    7990           28 :                          ? (p[1] == 0x80 && (p[2] == 0xA8 || p[2] == 0xA9))
    7991           36 :                          : (p[1] == 0xBF && (p[2] == 0xBE || p[2] == 0xBF));
    7992           73 :       if (!special) {
    7993            7 :         p++;
    7994            7 :         continue;
    7995              :       }
    7996              :     }
    7997       196532 :     if (p > run) yb_put(b, (const char *)run, (size_t)(p - run), limit);
    7998       196532 :     if (c == 0) break;
    7999       186991 :     char esc[6];
    8000       186991 :     const char *out = esc;
    8001       186991 :     size_t out_len = 2;
    8002       186991 :     esc[0] = '\\';
    8003       186991 :     switch (c) {
    8004          355 :       case '"':
    8005          355 :         esc[1] = '"';
    8006          355 :         break;
    8007       130101 :       case '\\':
    8008       130101 :         esc[1] = '\\';
    8009       130101 :         break;
    8010           18 :       case '\n':
    8011           18 :         esc[1] = 'n';
    8012           18 :         break;
    8013            5 :       case '\r':
    8014            5 :         esc[1] = 'r';
    8015            5 :         break;
    8016           16 :       case '\t':
    8017           16 :         esc[1] = 't';
    8018           16 :         break;
    8019            2 :       case '\b':
    8020            2 :         esc[1] = 'b';
    8021            2 :         break;
    8022            2 :       case '\f':
    8023            2 :         esc[1] = 'f';
    8024            2 :         break;
    8025           72 :       case 0xC2:
    8026           72 :         p++;
    8027           72 :         if (*p == 0x85) {
    8028           12 :           esc[1] = 'N';
    8029              :         } else {
    8030           60 :           esc[1] = 'x';
    8031           60 :           esc[2] = cyaml_hex_lower[*p >> 4];
    8032           60 :           esc[3] = cyaml_hex_lower[*p & 0x0F];
    8033           60 :           out_len = 4;
    8034              :         }
    8035              :         break;
    8036           26 :       case 0xE2:
    8037           26 :         p += 2;
    8038           26 :         esc[1] = *p == 0xA8 ? 'L' : 'P';
    8039           26 :         break;
    8040           32 :       case 0xEF:
    8041           32 :         p += 2;
    8042           32 :         out = *p == 0xBE ? "\\uFFFE" : "\\uFFFF";
    8043              :         out_len = 6;
    8044              :         break;
    8045        56362 :       default:
    8046        56362 :         esc[1] = 'x';
    8047        56362 :         esc[2] = cyaml_hex_lower[c >> 4];
    8048        56362 :         esc[3] = cyaml_hex_lower[c & 0x0F];
    8049        56362 :         out_len = 4;
    8050        56362 :         break;
    8051              :     }
    8052       186991 :     yb_put(b, out, out_len, limit);
    8053       179564 :     if (yb_over(b, limit)) return;
    8054       186986 :     run = ++p;
    8055              :   }
    8056         9541 :   yb_put(b, "\"", 1, limit);
    8057              : }
    8058              : 
    8059              : // Appends s as a double-quoted scalar with no limit, for the serializers'
    8060              : // quoted strings and keys.
    8061         9500 : static void yb_append_yaml_dquoted(ybuf *b, const char *s) {
    8062         9500 :   yb_dquoted_body(b, s, SIZE_MAX);
    8063         9500 : }
    8064              : 
    8065              : // Appends s as a double-quoted scalar within yb_put()'s limit, for the
    8066              : // canonical key text.
    8067           46 : static void yb_append_yaml_dquoted_capped(ybuf *b, const char *s,
    8068              :                                           size_t limit) {
    8069           46 :   yb_dquoted_body(b, s, limit);
    8070           46 : }
    8071              : 
    8072              : // The longest rendered key the serializer writes as an implicit "key: value";
    8073              : // YAML 1.2 allows 1024 characters there and PyYAML and libyaml refuse more. A
    8074              : // longer key goes out in the explicit "? key" form. Counting bytes only errs
    8075              : // toward the explicit form.
    8076              : #define CYAML_MAX_IMPLICIT_KEY_LEN 1024
    8077              : 
    8078              : // Appends the text of a dictionary key, plain when that reads back as the same
    8079              : // key and double-quoted otherwise, for both serializers. The quoted form
    8080              : // escapes line breaks, so a key always stays on one line.
    8081        20048 : static inline void yb_append_key_text(ybuf *b, const char *key) {
    8082        20048 :   if (key_needs_quoting(key))
    8083         9190 :     yb_append_yaml_dquoted(b, key);
    8084              :   else
    8085        10858 :     yb_append_cstr(b, key);
    8086        20048 : }
    8087              : 
    8088              : // Appends a key's text like yb_append_key_text(), within yb_put()'s limit, for
    8089              : // the flow writer that builds canonical keys.
    8090         8393 : static inline __attribute__((always_inline)) void yb_append_key_text_lim(
    8091              :     ybuf *b, const char *key, size_t limit) {
    8092         8393 :   if (limit == SIZE_MAX) {
    8093         8333 :     yb_append_key_text(b, key);
    8094           60 :   } else if (key_needs_quoting(key)) {
    8095           42 :     yb_append_yaml_dquoted_capped(b, key, limit);
    8096              :   } else {
    8097           18 :     yb_put(b, key, strlen(key), limit);
    8098              :   }
    8099              : }
    8100              : 
    8101              : // Appends two spaces per level of depth for the block writer, one append per
    8102              : // 128 bytes from a constant block of spaces.
    8103        36239 : static void yb_indent(ybuf *b, int depth) {
    8104        36239 :   static const char spaces[129] =
    8105              :       "                                                                "
    8106              :       "                                                                ";
    8107        36239 :   size_t width = depth > 0 ? (size_t)depth * 2 : 0;
    8108       166225 :   while (width > 0) {
    8109       129986 :     size_t chunk = width < 128 ? width : 128;
    8110       129986 :     yb_append(b, spaces, chunk);
    8111       129986 :     width -= chunk;
    8112              :   }
    8113        36239 : }
    8114              : 
    8115              : // Gives the YAML text of a double for float values, written into buf: ".nan",
    8116              : // ".inf", "-.inf", or the shortest round-trip digits with a '.' in the mantissa
    8117              : // ("1.0", "1.0e+20"), since without it YAML 1.1 readers read "1e+20" as a
    8118              : // string and "1" would come back as an int. Runs in the C locale.
    8119          116 : static const char *yaml_double_text(double v,
    8120              :                                     char buf[CYAML_FLOAT_KEY_BUF_LEN]) {
    8121          116 :   if (__builtin_isnan(v)) return ".nan";
    8122          115 :   if (__builtin_isinf(v)) return v > 0 ? ".inf" : "-.inf";
    8123          114 :   format_shortest_double(v, buf);
    8124          114 :   if (!strchr(buf, '.')) {
    8125           27 :     char *e = strchr(buf, 'e');
    8126           27 :     size_t len = strlen(buf);
    8127           27 :     size_t at = e ? (size_t)(e - buf) : len;
    8128           27 :     memmove(buf + at + 2, buf + at, len - at + 1);
    8129           27 :     buf[at] = '.';
    8130           27 :     buf[at + 1] = '0';
    8131              :   }
    8132              :   return buf;
    8133              : }
    8134              : 
    8135              : // Appends the YAML text of a double, for float scalars in both serializers.
    8136           69 : static void yb_append_double(ybuf *b, double v) {
    8137           69 :   char buf[CYAML_FLOAT_KEY_BUF_LEN];
    8138           69 :   yb_append_cstr(b, yaml_double_text(v, buf));
    8139           69 : }
    8140              : 
    8141              : // Writes v in decimal into buf without snprintf, for integer scalars and the
    8142              : // canonical-number check. Gives the length.
    8143         4524 : static int lltoa_y(char *buf, long long v) {
    8144         4524 :   char tmp[22];
    8145         4524 :   unsigned long long u;
    8146         4524 :   int neg = (v < 0);
    8147         4524 :   int i = 0;
    8148         4524 :   u = neg ? (unsigned long long)(-(v + 1)) + 1ULL : (unsigned long long)v;
    8149         5673 :   do {
    8150         5673 :     tmp[i++] = '0' + (char)(u % 10);
    8151         5673 :     u /= 10;
    8152         5673 :   } while (u);
    8153         4524 :   if (neg) tmp[i++] = '-';
    8154         4524 :   int len = i;
    8155        10200 :   for (int j = 0; j < len; j++) buf[j] = tmp[len - 1 - j];
    8156         4524 :   buf[len] = '\0';
    8157         4524 :   return len;
    8158              : }
    8159              : 
    8160              : static void serialize_block(ybuf *b, cyaml_node *n, int depth, int max_depth);
    8161              : 
    8162              : // Writes a string scalar for the block writer: Double-quoted when a parse would
    8163              : // read it as another type or it holds a character that needs it
    8164              : // (needs_quoting()), plain otherwise.
    8165          387 : static void serialize_block_scalar(ybuf *b, cyaml_node *n) {
    8166          387 :   const char *s = n->value.string;
    8167          387 :   if (needs_quoting(s)) {
    8168          236 :     yb_append_yaml_dquoted(b, s);
    8169              :   } else {
    8170          151 :     yb_append_cstr(b, s);
    8171              :   }
    8172          387 : }
    8173              : 
    8174              : // Tells whether c may appear literally in a written verbatim tag: ns-uri-char
    8175              : // without '%' (it starts an escape) and without '#' (libyaml and PyYAML refuse
    8176              : // it literally; "%23" means the same).
    8177        37333 : static inline bool is_verbatim_tag_literal_char(unsigned char c) {
    8178        37333 :   if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
    8179        29308 :       (c >= '0' && c <= '9'))
    8180              :     return true;
    8181        29224 :   switch (c) {
    8182              :     case '-':
    8183              :     case ';':
    8184              :     case '/':
    8185              :     case '?':
    8186              :     case ':':
    8187              :     case '@':
    8188              :     case '&':
    8189              :     case '=':
    8190              :     case '+':
    8191              :     case '$':
    8192              :     case ',':
    8193              :     case '_':
    8194              :     case '.':
    8195              :     case '!':
    8196              :     case '~':
    8197              :     case '*':
    8198              :     case '\'':
    8199              :     case '(':
    8200              :     case ')':
    8201              :     case '[':
    8202              :     case ']':
    8203              :       return true;
    8204              :     default:
    8205              :       return false;
    8206              :   }
    8207              : }
    8208              : 
    8209              : // Writes tag as "!<...>" within yb_put()'s limit, percent-escaping every byte
    8210              : // that may not appear literally, so any conforming reader accepts the token and
    8211              : // parsing gives back the same tag. The caller writes the separator after it.
    8212         7202 : static inline __attribute__((always_inline)) void yb_verbatim_tag_body(
    8213              :     ybuf *b, const char *tag, size_t limit) {
    8214         7202 :   static const char hex_digits[] = "0123456789ABCDEF";
    8215        36331 :   yb_put(b, "!<", 2, limit);
    8216              :   const unsigned char *p = (const unsigned char *)tag;
    8217        51056 :   for (;;) {
    8218        29129 :     const unsigned char *run = p;
    8219        44534 :     while (*p && is_verbatim_tag_literal_char(*p)) p++;
    8220        29129 :     if (p > run) yb_put(b, (const char *)run, (size_t)(p - run), limit);
    8221        29129 :     if (!*p || yb_over(b, limit)) break;
    8222        21927 :     char esc[3] = {'%', hex_digits[*p >> 4], hex_digits[*p & 0x0F]};
    8223        21927 :     yb_put(b, esc, 3, limit);
    8224        21927 :     p++;
    8225              :   }
    8226         7202 :   yb_put(b, ">", 1, limit);
    8227              : }
    8228              : 
    8229              : // Writes a verbatim tag with no limit, for custom tags in the block and flow
    8230              : // writers.
    8231         7199 : static void yb_append_verbatim_tag(ybuf *b, const char *tag) {
    8232         7199 :   yb_verbatim_tag_body(b, tag, SIZE_MAX);
    8233         7199 : }
    8234              : 
    8235              : // Writes a verbatim tag within yb_put()'s limit, for canonical key text.
    8236            3 : static void yb_append_verbatim_tag_capped(ybuf *b, const char *tag,
    8237              :                                           size_t limit) {
    8238            3 :   yb_verbatim_tag_body(b, tag, limit);
    8239            3 : }
    8240              : 
    8241              : // What a serialize_*_head() call found: The node is fully written, or it's a
    8242              : // non-empty list or dictionary whose children the walk must visit.
    8243              : typedef enum {
    8244              :   CYAML_EMIT_DONE,
    8245              :   CYAML_EMIT_LIST,
    8246              :   CYAML_EMIT_DICT
    8247              : } cyaml_emit_head;
    8248              : 
    8249              : // One level of the block writer's walk: A list walks n by idx up to count, a
    8250              : // dictionary walks through next in insertion order. depth is the indentation
    8251              : // level.
    8252              : typedef struct {
    8253              :   cyaml_node *n;
    8254              :   size_t idx;
    8255              :   size_t count;
    8256              :   const ccol_chmap_entry_ref *next;
    8257              :   int depth;
    8258              : } sblock_frame;
    8259              : 
    8260              : #ifdef RUNNING_UNIT_TESTS
    8261              : // Counts the nodes a serializer visits after its buffer went OOM, so a test can
    8262              : // check that the walk stops at once. CYAML_COUNT_OOM_VISIT() bumps it in test
    8263              : // builds and evaluates to nothing otherwise.
    8264              : __thread size_t cyaml__serialize_oom_visits_for_tests;
    8265              : #define CYAML_COUNT_OOM_VISIT() (cyaml__serialize_oom_visits_for_tests++)
    8266              : #else
    8267              : #define CYAML_COUNT_OOM_VISIT() ((void)0)
    8268              : #endif
    8269              : 
    8270              : // Writes everything about n that comes before its children, for the block
    8271              : // writer: '~' for a NULL pointer, a verbatim tag the type doesn't imply (on its
    8272              : // own line for a collection, as a prefix for a scalar), and the whole of a
    8273              : // scalar or an empty container. depth sets the indentation (2 spaces a level).
    8274              : // A container at max_depth or deeper sets the buffer's oom flag like an
    8275              : // allocation failure, and a set flag writes nothing. Gives what is left to
    8276              : // walk, with the child count in *count_out. Inlined, since it runs per node.
    8277              : static inline __attribute__((always_inline)) cyaml_emit_head
    8278        32570 : serialize_block_head(ybuf *b, cyaml_node *n, int depth, size_t *count_out,
    8279              :                      int max_depth) {
    8280        32570 :   if (b->oom) {
    8281            5 :     CYAML_COUNT_OOM_VISIT();
    8282            5 :     return CYAML_EMIT_DONE;
    8283              :   }
    8284         3400 :   if (!n) {
    8285            2 :     yb_append_cstr(b, "~");
    8286            2 :     return CYAML_EMIT_DONE;
    8287              :   }
    8288              : 
    8289        32563 :   if (n->tag && !tag_matches_node_type(n)) {
    8290         4611 :     if (n->type == CYAML_LIST || n->type == CYAML_DICTIONARY) {
    8291         4518 :       yb_indent(b, depth);
    8292         4518 :       yb_append_verbatim_tag(b, n->tag);
    8293         4518 :       yb_append_c(b, '\n');
    8294              :     } else {
    8295           93 :       yb_append_verbatim_tag(b, n->tag);
    8296           93 :       yb_append_c(b, ' ');
    8297              :     }
    8298              :   }
    8299              : 
    8300        32563 :   switch (n->type) {
    8301              :     case CYAML_NULL:
    8302           24 :       yb_append_cstr(b, "~");
    8303           24 :       break;
    8304           21 :     case CYAML_BOOL:
    8305           21 :       yb_append_cstr(b, n->value.boolean ? "true" : "false");
    8306           21 :       break;
    8307         2220 :     case CYAML_INTEGER: {
    8308         2220 :       char buf[24];
    8309         2220 :       int len = lltoa_y(buf, n->value.integer);
    8310         2220 :       yb_append(b, buf, (size_t)len);
    8311         2220 :       break;
    8312              :     }
    8313           69 :     case CYAML_FLOAT:
    8314           69 :       yb_append_double(b, n->value.number);
    8315           69 :       break;
    8316          387 :     case CYAML_STRING:
    8317          387 :       serialize_block_scalar(b, n);
    8318          387 :       break;
    8319        19876 :     case CYAML_LIST:
    8320        19876 :       if (depth >= max_depth) {
    8321            4 :         CYAML_COUNT_OOM_VISIT();
    8322            4 :         b->oom = true;
    8323            4 :         break;
    8324              :       }
    8325        19872 :       *count_out = cvector_size(n->value.list);
    8326        19872 :       if (*count_out == 0) {
    8327           16 :         yb_indent(b, depth);
    8328           16 :         yb_append_cstr(b, "[]\n");
    8329           16 :         break;
    8330              :       }
    8331              :       return CYAML_EMIT_LIST;
    8332         9966 :     case CYAML_DICTIONARY:
    8333         9966 :       if (depth >= max_depth) {
    8334            2 :         CYAML_COUNT_OOM_VISIT();
    8335            2 :         b->oom = true;
    8336            2 :         break;
    8337              :       }
    8338         9964 :       *count_out = chashmap_size(n->value.dictionary);
    8339         9964 :       if (*count_out == 0) {
    8340          120 :         yb_indent(b, depth);
    8341          120 :         yb_append_cstr(b, "{}\n");
    8342          120 :         break;
    8343              :       }
    8344              :       return CYAML_EMIT_DICT;
    8345              :   }
    8346              :   return CYAML_EMIT_DONE;
    8347              : }
    8348              : 
    8349              : // Starts the walk of the children of the non-empty container n, for
    8350              : // serialize_block(); inlined, since it runs once per container.
    8351        29698 : static inline __attribute__((always_inline)) void sblock_frame_open(
    8352              :     sblock_frame *f, cyaml_node *n, int depth, cyaml_emit_head kind,
    8353              :     size_t count) {
    8354        29698 :   f->n = n;
    8355        29698 :   f->depth = depth;
    8356        29698 :   f->idx = 0;
    8357        29698 :   f->count = count;
    8358         9844 :   f->next = (kind == CYAML_EMIT_DICT) ? dict_first_entry(n) : NULL;
    8359          676 : }
    8360              : 
    8361              : // Writes block-style YAML for the subtree n, the body of cyaml_serialize() and
    8362              : // of each stream document. Each child goes on its own indented line, a key too
    8363              : // long for an implicit key uses the "? key" form, and a container child gets a
    8364              : // bare "-" or "key:" so no line holds only whitespace. An explicit frame stack
    8365              : // drives the walk; it stops as soon as the buffer's oom flag is set, which a
    8366              : // tree nesting past max_depth also sets.
    8367          994 : static void serialize_block(ybuf *b, cyaml_node *n, int depth, int max_depth) {
    8368          994 :   size_t count = 0;
    8369          994 :   cyaml_emit_head kind = serialize_block_head(b, n, depth, &count, max_depth);
    8370          318 :   if (kind == CYAML_EMIT_DONE) return;
    8371              : 
    8372          676 :   sblock_frame inline_frames[CYAML_WALK_INLINE_FRAMES];
    8373          676 :   sblock_frame *stack = inline_frames;
    8374          676 :   size_t cap = CYAML_WALK_INLINE_FRAMES;
    8375          676 :   size_t sp = 1;
    8376          676 :   sblock_frame_open(&stack[0], n, depth, kind, count);
    8377              : 
    8378        58833 :   while (sp > 0 && !b->oom) {
    8379        58159 :     sblock_frame *f = &stack[sp - 1];
    8380        58159 :     cyaml_node *child;
    8381              : 
    8382        58159 :     if (f->n->type == CYAML_LIST) {
    8383        38164 :       if (f->idx >= f->count) {
    8384        18294 :         sp--;
    8385        18294 :         continue;
    8386              :       }
    8387        19870 :       child = *(cyaml_node **)cvector_at(f->n->value.list, f->idx);
    8388        19870 :       f->idx++;
    8389        19870 :       yb_indent(b, f->depth);
    8390        19870 :       if (child &&
    8391        19870 :           (child->type == CYAML_DICTIONARY || child->type == CYAML_LIST)) {
    8392        19802 :         yb_append_cstr(b, "-\n");
    8393        19802 :         kind = serialize_block_head(b, child, f->depth + 1, &count, max_depth);
    8394              :       } else {
    8395           68 :         yb_append_cstr(b, "- ");
    8396           68 :         (void)serialize_block_head(b, child, f->depth, &count, max_depth);
    8397           68 :         yb_append_c(b, '\n');
    8398           68 :         continue;
    8399              :       }
    8400              :     } else {
    8401        19995 :       if (!f->next) {
    8402         8289 :         sp--;
    8403        10629 :         continue;
    8404              :       }
    8405        11706 :       const cmap_pair *kp, *vp;
    8406        11706 :       f->next = ccol_chmap_entry_read(f->next, &kp, &vp);
    8407        11706 :       const char *key = (const char *)kp->ptr;
    8408        11706 :       child = cyaml_read_child(vp->ptr);
    8409              : 
    8410        11706 :       yb_indent(b, f->depth);
    8411        11706 :       size_t key_start = b->len;
    8412        11706 :       yb_append_key_text(b, key);
    8413        11706 :       if (!b->oom && b->len - key_start > CYAML_MAX_IMPLICIT_KEY_LEN) {
    8414            9 :         b->len = key_start;
    8415            9 :         yb_append_cstr(b, "? ");
    8416            9 :         yb_append_key_text(b, key);
    8417            9 :         yb_append_c(b, '\n');
    8418            9 :         yb_indent(b, f->depth);
    8419              :       }
    8420        11706 :       yb_append_c(b, ':');
    8421              : 
    8422        11706 :       if (child &&
    8423        11706 :           (child->type == CYAML_DICTIONARY || child->type == CYAML_LIST)) {
    8424         9366 :         yb_append_c(b, '\n');
    8425        18732 :         kind = serialize_block_head(b, child, f->depth + 1, &count, max_depth);
    8426              :       } else {
    8427         2340 :         yb_append_c(b, ' ');
    8428         2340 :         (void)serialize_block_head(b, child, f->depth, &count, max_depth);
    8429         2340 :         yb_append_c(b, '\n');
    8430         2340 :         continue;
    8431              :       }
    8432              :     }
    8433              : 
    8434        29168 :     if (kind != CYAML_EMIT_DONE) {
    8435        29024 :       int child_depth = f->depth + 1;
    8436        29024 :       if (sp == cap) {
    8437          477 :         sblock_frame *grown = walk_stack_grow(stack, &cap, inline_frames,
    8438              :                                               sizeof(*stack), b->m_procs);
    8439          477 :         if (!grown) {
    8440            2 :           b->oom = true;
    8441            2 :           break;
    8442              :         }
    8443              :         stack = grown;
    8444              :       }
    8445        29022 :       sblock_frame_open(&stack[sp], child, child_depth, kind, count);
    8446        29022 :       sp++;
    8447              :     }
    8448              :   }
    8449              : 
    8450          676 :   if (stack != inline_frames) ccol__mem_free(b->m_procs, stack);
    8451              : }
    8452              : 
    8453              : // Serializes node to block YAML that always ends with a newline, the public
    8454              : // entry point. It runs in one C locale scope, since needs_quoting() and the
    8455              : // float writer follow LC_NUMERIC. Gives a string from the node's allocator, or
    8456              : // NULL on OOM or a tree that is too deep.
    8457          960 : char *cyaml_serialize(cyaml node) {
    8458          960 :   cyaml_node *n = (cyaml_node *)node;
    8459          960 :   ccol_memmgmt_procs *mp = n ? n->m_procs : NULL;
    8460          960 :   ybuf b;
    8461          960 :   yb_init(&b, mp);
    8462          960 :   ccol_c_locale_scope scope = ccol_c_locale_enter();
    8463          960 :   serialize_block(&b, n, 0, CYAML_MAX_NESTING_DEPTH);
    8464          960 :   ccol_c_locale_leave(scope);
    8465         1918 :   if (b.len > 0 && !yb_ends_with_char(&b, '\n')) yb_append_c(&b, '\n');
    8466          960 :   if (b.oom) {
    8467           12 :     ccol__mem_free(b.m_procs, b.buf);
    8468           12 :     return NULL;
    8469              :   }
    8470          948 :   return b.buf;
    8471              : }
    8472              : 
    8473              : // Writes one document of a stream: "---" on its own line, then the block YAML
    8474              : // of root (a root tag goes on the next line). max_depth is one less for an
    8475              : // element of a list of documents, as when parsing a stream.
    8476           34 : static void serialize_stream_document(ybuf *b, cyaml_node *root,
    8477              :                                       int max_depth) {
    8478           34 :   yb_append_cstr(b, "---\n");
    8479           34 :   size_t start = b->len;
    8480           34 :   serialize_block(b, root, 0, max_depth);
    8481           68 :   if (b->len > start && !yb_ends_with_char(b, '\n')) yb_append_c(b, '\n');
    8482           34 : }
    8483              : 
    8484              : // Serializes the elements of a list as a stream of "---" documents, or a node
    8485              : // that isn't a list as one document, in one C locale scope. Gives the string,
    8486              : // "" for an empty list, or NULL on OOM or a tree that is too deep.
    8487           26 : char *cyaml_serialize_stream(cyaml node) {
    8488           26 :   cyaml_node *n = (cyaml_node *)node;
    8489           26 :   ccol_memmgmt_procs *mp = n ? n->m_procs : NULL;
    8490           26 :   ybuf b;
    8491           26 :   yb_init(&b, mp);
    8492           26 :   ccol_c_locale_scope scope = ccol_c_locale_enter();
    8493           26 :   if (n && n->type == CYAML_LIST) {
    8494           19 :     size_t count = cyaml_list_size(node);
    8495           46 :     for (size_t i = 0; i < count && !b.oom; i++)
    8496           27 :       serialize_stream_document(&b, (cyaml_node *)cyaml_list_get(node, i),
    8497              :                                 CYAML_MAX_NESTING_DEPTH - 1);
    8498              :   } else {
    8499            7 :     serialize_stream_document(&b, n, CYAML_MAX_NESTING_DEPTH);
    8500              :   }
    8501           26 :   ccol_c_locale_leave(scope);
    8502           26 :   if (b.oom) {
    8503            1 :     ccol__mem_free(b.m_procs, b.buf);
    8504            1 :     return NULL;
    8505              :   }
    8506           25 :   return b.buf;
    8507              : }
    8508              : 
    8509              : // A key and value pair copied out of a dictionary so canonical mode can sort
    8510              : // it. key is borrowed from the dictionary's storage.
    8511              : typedef struct {
    8512              :   const char *key;
    8513              :   cyaml_node *val;
    8514              : } flow_dict_entry;
    8515              : 
    8516              : // Orders flow_dict_entry items by key with strcmp, for the qsort of canonical
    8517              : // mode.
    8518            4 : static int flow_dict_entry_cmp(const void *a, const void *b) {
    8519            4 :   const flow_dict_entry *ea = (const flow_dict_entry *)a;
    8520            4 :   const flow_dict_entry *eb = (const flow_dict_entry *)b;
    8521            4 :   return strcmp(ea->key, eb->key);
    8522              : }
    8523              : 
    8524              : // One level of the flow writer's walk: A list walks by index, a dictionary
    8525              : // walks through the sorted entries copy of canonical mode or through next in
    8526              : // insertion order.
    8527              : typedef struct {
    8528              :   cyaml_node *n;
    8529              :   flow_dict_entry *entries;
    8530              :   const ccol_chmap_entry_ref *next;
    8531              :   size_t idx;
    8532              :   size_t count;
    8533              :   int depth;
    8534              : } sflow_frame;
    8535              : 
    8536              : // Writes everything about n that comes before its children, for the flow
    8537              : // writer: '~' for NULL, a tag prefix the type doesn't imply, the whole of a
    8538              : // scalar, and the opening bracket of a container (both brackets when empty).
    8539              : // depth is the containers around n; one at the nesting limit or deeper sets the
    8540              : // oom flag, and a set flag writes nothing. All output goes through yb_put()
    8541              : // under limit. Gives what is left to walk.
    8542              : static inline __attribute__((always_inline)) cyaml_emit_head
    8543        29142 : serialize_flow_head(ybuf *b, cyaml_node *n, int depth, size_t *count_out,
    8544              :                     size_t limit) {
    8545        29142 :   if (b->oom) {
    8546            3 :     CYAML_COUNT_OOM_VISIT();
    8547            3 :     return CYAML_EMIT_DONE;
    8548              :   }
    8549        29139 :   if (!n) {
    8550            1 :     yb_put(b, "~", 1, limit);
    8551              :     return CYAML_EMIT_DONE;
    8552              :   }
    8553        29138 :   if (n->tag && !tag_matches_node_type(n)) {
    8554         2591 :     if (limit == SIZE_MAX)
    8555         2588 :       yb_append_verbatim_tag(b, n->tag);
    8556              :     else
    8557            3 :       yb_append_verbatim_tag_capped(b, n->tag, limit);
    8558         2591 :     yb_put(b, " ", 1, limit);
    8559              :   }
    8560        29138 :   switch (n->type) {
    8561              :     case CYAML_NULL:
    8562           43 :       yb_put(b, "~", 1, limit);
    8563              :       break;
    8564           21 :     case CYAML_BOOL:
    8565           21 :       if (n->value.boolean)
    8566           10 :         yb_put(b, "true", 4, limit);
    8567              :       else
    8568           11 :         yb_put(b, "false", 5, limit);
    8569              :       break;
    8570         2284 :     case CYAML_INTEGER: {
    8571         2284 :       char buf[24];
    8572         2284 :       int len = lltoa_y(buf, n->value.integer);
    8573         2284 :       yb_put(b, buf, (size_t)len, limit);
    8574         2284 :       break;
    8575              :     }
    8576           47 :     case CYAML_FLOAT: {
    8577           47 :       char buf[CYAML_FLOAT_KEY_BUF_LEN];
    8578           47 :       const char *text = yaml_double_text(n->value.number, buf);
    8579           47 :       yb_put(b, text, strlen(text), limit);
    8580           47 :       break;
    8581              :     }
    8582         6246 :     case CYAML_STRING:
    8583         6246 :       if (!needs_quoting(n->value.string))
    8584         6168 :         yb_put(b, n->value.string, strlen(n->value.string), limit);
    8585           78 :       else if (limit == SIZE_MAX)
    8586           74 :         yb_append_yaml_dquoted(b, n->value.string);
    8587              :       else
    8588            4 :         yb_append_yaml_dquoted_capped(b, n->value.string, limit);
    8589              :       break;
    8590        12802 :     case CYAML_LIST:
    8591        12802 :       if (depth >= CYAML_MAX_NESTING_DEPTH) {
    8592            4 :         CYAML_COUNT_OOM_VISIT();
    8593            4 :         b->oom = true;
    8594            4 :         break;
    8595              :       }
    8596        13334 :       *count_out = cvector_size(n->value.list);
    8597        13334 :       if (*count_out == 0) {
    8598           11 :         yb_put(b, "[]", 2, limit);
    8599              :         break;
    8600              :       }
    8601        13323 :       yb_put(b, "[", 1, limit);
    8602              :       return CYAML_EMIT_LIST;
    8603         6627 :     case CYAML_DICTIONARY:
    8604         6627 :       if (depth >= CYAML_MAX_NESTING_DEPTH) {
    8605            1 :         CYAML_COUNT_OOM_VISIT();
    8606            1 :         b->oom = true;
    8607            1 :         break;
    8608              :       }
    8609         7158 :       *count_out = chashmap_size(n->value.dictionary);
    8610         7158 :       if (*count_out == 0) {
    8611          121 :         yb_put(b, "{}", 2, limit);
    8612              :         break;
    8613              :       }
    8614         7037 :       yb_put(b, "{", 1, limit);
    8615              :       return CYAML_EMIT_DICT;
    8616              :   }
    8617              :   return CYAML_EMIT_DONE;
    8618              : }
    8619              : 
    8620              : // Frees the sorted entries copy of a flow frame, if canonical mode made one,
    8621              : // when the walk leaves the frame or fails.
    8622        20358 : static void sflow_frame_close(ybuf *b, sflow_frame *f) {
    8623        20358 :   f->next = NULL;
    8624        20358 :   if (f->entries) {
    8625            4 :     ccol__mem_free(b->m_procs, f->entries);
    8626            4 :     f->entries = NULL;
    8627              :   }
    8628        20358 : }
    8629              : 
    8630              : // Starts the walk of the children of the non-empty container n. In canonical
    8631              : // mode a dictionary of two or more entries is copied into an array and sorted
    8632              : // by key, so the text doesn't depend on insertion order. false, with the oom
    8633              : // flag set, when that array can't be allocated.
    8634        20358 : static inline __attribute__((always_inline)) bool sflow_frame_open(
    8635              :     ybuf *b, sflow_frame *f, cyaml_node *n, int depth, bool canonical,
    8636              :     cyaml_emit_head kind, size_t count) {
    8637        20358 :   f->n = n;
    8638        20358 :   f->depth = depth;
    8639        20358 :   f->idx = 0;
    8640        20358 :   f->count = count;
    8641        20358 :   f->next = NULL;
    8642        20358 :   f->entries = NULL;
    8643        20358 :   if (kind == CYAML_EMIT_LIST) return true;
    8644           41 :   if (!canonical || f->count <= 1) {
    8645         7033 :     f->next = dict_first_entry(n);
    8646         7033 :     return true;
    8647              :   }
    8648              : 
    8649            8 :   flow_dict_entry *entries =
    8650            4 :       ccol__mem_calloc(b->m_procs, f->count, sizeof(*entries));
    8651            4 :   if (!entries) {
    8652            0 :     b->oom = true;
    8653            0 :     return false;
    8654              :   }
    8655            4 :   size_t idx = 0;
    8656           12 :   for (const ccol_chmap_entry_ref *e = dict_first_entry(n); e; idx++) {
    8657            8 :     const cmap_pair *kp, *vp;
    8658            8 :     e = ccol_chmap_entry_read(e, &kp, &vp);
    8659            8 :     entries[idx].key = (const char *)kp->ptr;
    8660            8 :     entries[idx].val = cyaml_read_child(vp->ptr);
    8661              :   }
    8662            4 :   qsort(entries, f->count, sizeof(*entries), flow_dict_entry_cmp);
    8663            4 :   f->entries = entries;
    8664            4 :   return true;
    8665              : }
    8666              : 
    8667              : // Writes one flow dictionary key and its ": ", or an explicit "? key: " entry
    8668              : // for a key longer than CYAML_MAX_IMPLICIT_KEY_LEN. Inlined, since it runs per
    8669              : // entry.
    8670         8369 : static inline __attribute__((always_inline)) void sflow_emit_key(
    8671              :     ybuf *b, const char *key, size_t limit) {
    8672         8369 :   size_t key_start = b->len;
    8673        16738 :   yb_append_key_text_lim(b, key, limit);
    8674         8369 :   if (!b->oom && b->len - key_start > CYAML_MAX_IMPLICIT_KEY_LEN) {
    8675           24 :     b->len = key_start;
    8676           24 :     yb_put(b, "? ", 2, limit);
    8677           24 :     yb_append_key_text_lim(b, key, limit);
    8678              :   }
    8679         8369 :   yb_put(b, ": ", 2, limit);
    8680              : }
    8681              : 
    8682              : // Writes compact flow YAML for the subtree n, quoting strings by the same
    8683              : // rules as the block writer, for cyaml_serialize_flow() and the canonical key
    8684              : // builder. canonical sorts the entries of every dictionary by key (lists keep
    8685              : // their order). limit bounds the text at limit + 1 bytes and ends the walk once
    8686              : // it's passed (SIZE_MAX for none). Each caller passes constants, so the public
    8687              : // path carries no limit tests. An explicit frame stack drives the walk, and it
    8688              : // stops as soon as the oom flag is set.
    8689         1112 : static inline __attribute__((always_inline)) void serialize_flow(
    8690              :     ybuf *b, cyaml_node *n, bool canonical, int depth, size_t limit) {
    8691         1112 :   size_t count = 0;
    8692         2224 :   cyaml_emit_head kind = serialize_flow_head(b, n, depth, &count, limit);
    8693           46 :   if (kind == CYAML_EMIT_DONE) return;
    8694              : 
    8695         1066 :   sflow_frame inline_frames[CYAML_WALK_INLINE_FRAMES];
    8696         1066 :   sflow_frame *stack = inline_frames;
    8697         1066 :   size_t cap = CYAML_WALK_INLINE_FRAMES;
    8698         1435 :   size_t sp =
    8699         1066 :       sflow_frame_open(b, &stack[0], n, depth, canonical, kind, count) ? 1 : 0;
    8700              : 
    8701        46213 :   while (sp > 0 && !b->oom && !yb_over(b, limit)) {
    8702        45833 :     sflow_frame *f = &stack[sp - 1];
    8703        45833 :     cyaml_node *child;
    8704              : 
    8705        45833 :     if (f->n->type == CYAML_LIST) {
    8706        31702 :       if (f->idx >= f->count) {
    8707        12041 :         yb_put(b, "]", 1, limit);
    8708        12041 :         sflow_frame_close(b, f);
    8709        12041 :         sp--;
    8710        12041 :         continue;
    8711              :       }
    8712        19661 :       if (f->idx > 0) yb_put(b, ", ", 2, limit);
    8713        19661 :       child = *(cyaml_node **)cvector_at(f->n->value.list, f->idx);
    8714        19661 :       f->idx++;
    8715        14131 :     } else if (f->entries) {
    8716           12 :       if (f->idx >= f->count) {
    8717            4 :         yb_put(b, "}", 1, limit);
    8718            4 :         sflow_frame_close(b, f);
    8719            4 :         sp--;
    8720            4 :         continue;
    8721              :       }
    8722            8 :       if (f->idx > 0) yb_put(b, ", ", 2, limit);
    8723            8 :       sflow_emit_key(b, f->entries[f->idx].key, limit);
    8724            8 :       child = f->entries[f->idx].val;
    8725            8 :       f->idx++;
    8726              :     } else {
    8727        14119 :       if (!f->next) {
    8728         5758 :         yb_put(b, "}", 1, limit);
    8729         5758 :         sflow_frame_close(b, f);
    8730         5758 :         sp--;
    8731         5758 :         continue;
    8732              :       }
    8733         8361 :       if (f->idx > 0) yb_put(b, ", ", 2, limit);
    8734         8361 :       const cmap_pair *kp, *vp;
    8735         8361 :       f->next = ccol_chmap_entry_read(f->next, &kp, &vp);
    8736         8361 :       child = cyaml_read_child(vp->ptr);
    8737         8361 :       f->idx++;
    8738        16722 :       sflow_emit_key(b, (const char *)kp->ptr, limit);
    8739              :     }
    8740              : 
    8741        28030 :     int child_depth = f->depth + 1;
    8742        74927 :     kind = serialize_flow_head(b, child, child_depth, &count, limit);
    8743              :     if (kind != CYAML_EMIT_DONE) {
    8744        19294 :       if (sp == cap) {
    8745          393 :         sflow_frame *grown = walk_stack_grow(stack, &cap, inline_frames,
    8746              :                                              sizeof(*stack), b->m_procs);
    8747          393 :         if (!grown) {
    8748            2 :           b->oom = true;
    8749            2 :           break;
    8750              :         }
    8751              :         stack = grown;
    8752              :       }
    8753        19292 :       if (!sflow_frame_open(b, &stack[sp], child, child_depth, canonical, kind,
    8754              :                             count))
    8755              :         break;
    8756        19292 :       sp++;
    8757              :     }
    8758              :   }
    8759              : 
    8760         3621 :   for (size_t i = 0; i < sp; i++) sflow_frame_close(b, &stack[i]);
    8761         1066 :   if (stack != inline_frames) ccol__mem_free(b->m_procs, stack);
    8762              : }
    8763              : 
    8764              : // Serializes node to one-line flow YAML, the public entry point, in one C
    8765              : // locale scope. Gives a string from the node's allocator, or NULL on OOM or a
    8766              : // tree that is too deep.
    8767          740 : char *cyaml_serialize_flow(cyaml node) {
    8768          740 :   cyaml_node *n = (cyaml_node *)node;
    8769          740 :   ccol_memmgmt_procs *mp = n ? n->m_procs : NULL;
    8770          740 :   ybuf b;
    8771          740 :   yb_init(&b, mp);
    8772          740 :   ccol_c_locale_scope scope = ccol_c_locale_enter();
    8773          740 :   serialize_flow(&b, n, false, 0, SIZE_MAX);
    8774          740 :   ccol_c_locale_leave(scope);
    8775          740 :   if (b.oom) {
    8776            9 :     ccol__mem_free(b.m_procs, b.buf);
    8777            9 :     return NULL;
    8778              :   }
    8779          731 :   return b.buf;
    8780              : }
    8781              : 
    8782              : #ifdef RUNNING_UNIT_TESTS
    8783              : // The largest buffer serialize_flow_canonical() allocated on this thread; a
    8784              : // test resets it and checks it against the key limit.
    8785              : __thread size_t cyaml__canonical_key_peak_bytes_for_tests;
    8786              : #endif
    8787              : // Builds the canonical flow text of a collection used as a key, for
    8788              : // node_to_dict_key_string(): Every dictionary sorted by key, so equal
    8789              : // structures give equal text. It stops at the first byte past
    8790              : // CYAML_MAX_CANONICAL_KEY_LEN, so a refused key costs at most that much work.
    8791              : // NULL with *too_long set when the text is too long, NULL with *too_long false
    8792              : // on OOM.
    8793          372 : static char *serialize_flow_canonical(cyaml_node *n, bool *too_long) {
    8794          372 :   ccol_memmgmt_procs *mp = n ? n->m_procs : NULL;
    8795          372 :   ybuf b;
    8796          372 :   yb_init(&b, mp);
    8797          372 :   serialize_flow(&b, n, true, 0, CYAML_MAX_CANONICAL_KEY_LEN);
    8798              : #ifdef RUNNING_UNIT_TESTS
    8799          372 :   if (b.cap > cyaml__canonical_key_peak_bytes_for_tests)
    8800           15 :     cyaml__canonical_key_peak_bytes_for_tests = b.cap;
    8801              : #endif
    8802          372 :   *too_long = !b.oom && b.len > CYAML_MAX_CANONICAL_KEY_LEN;
    8803          372 :   if (b.oom || *too_long) {
    8804            8 :     ccol__mem_free(b.m_procs, b.buf);
    8805            8 :     return NULL;
    8806              :   }
    8807          364 :   return b.buf;
    8808              : }
    8809              : 
    8810              : // Frees a string from one of the serializers through mp (NULL for the default
    8811              : // allocator); s may be NULL. A parse's *err_str must never come here, since the
    8812              : // library owns it.
    8813         1713 : void cyaml_serialize_free_mp(char *s, ccol_memmgmt_procs *mp) {
    8814         1713 :   ccol__mem_free(mp, s);
    8815         1713 : }
    8816              : 
    8817              : // Gives the first unescaped '.' in s, or NULL; a path splits there. In a path
    8818              : // "\." is a literal dot and "\\" a literal backslash, and any other backslash
    8819              : // passes through.
    8820           22 : static char *path_find_unescaped_dot(char *s) {
    8821           22 :   char *p = s;
    8822         2203 :   while (*p) {
    8823         1746 :     if (*p == '\\' && (*(p + 1) == '.' || *(p + 1) == '\\')) {
    8824           13 :       p += 2;
    8825         1733 :     } else if (*p == '.') {
    8826              :       return p;
    8827              :     } else {
    8828         1580 :       p++;
    8829              :     }
    8830              :   }
    8831              :   return NULL;
    8832              : }
    8833              : 
    8834              : // Gives the last unescaped '.' in s, or NULL, so set and delete can split the
    8835              : // parent path from the leaf.
    8836              : static char *path_find_last_unescaped_dot(char *s) {
    8837              :   char *last = NULL;
    8838              :   char *p = s;
    8839         1390 :   while (*p) {
    8840         1130 :     if (*p == '\\' && (*(p + 1) == '.' || *(p + 1) == '\\')) {
    8841            5 :       p += 2;
    8842         1125 :     } else if (*p == '.') {
    8843          128 :       last = p;
    8844          128 :       p++;
    8845              :     } else {
    8846          997 :       p++;
    8847              :     }
    8848              :   }
    8849          260 :   return last;
    8850              : }
    8851              : 
    8852              : // Resolves the escapes of one path component in place, before it's used as a
    8853              : // key; it never gets longer.
    8854          800 : static void path_unescape_component(char *s) {
    8855          800 :   char *r = s, *w = s;
    8856         2973 :   while (*r) {
    8857         2173 :     if (*r == '\\' && (*(r + 1) == '.' || *(r + 1) == '\\')) {
    8858           18 :       *w++ = *(r + 1);
    8859           18 :       r += 2;
    8860              :     } else {
    8861         2155 :       *w++ = *r++;
    8862              :     }
    8863              :   }
    8864          800 :   *w = '\0';
    8865          800 : }
    8866              : 
    8867              : // Parses the digits of a "#N" component (digits points past the '#'), strictly:
    8868              : // "#", "#+3" and "#3x" are malformed. An index too large for size_t saturates
    8869              : // at SIZE_MAX, so a well-formed index past the list is absent on every width.
    8870              : // false, with *idx_out untouched, when malformed.
    8871           75 : static bool parse_list_index_component(const char *digits, size_t *idx_out) {
    8872           75 :   if (digits[0] == '\0') return false;
    8873              :   size_t idx = 0;
    8874          469 :   for (const char *c = digits; *c; c++) {
    8875          403 :     if (*c < '0' || *c > '9') return false;
    8876          394 :     size_t d = (size_t)(*c - '0');
    8877          394 :     idx = idx > (SIZE_MAX - d) / 10 ? SIZE_MAX : idx * 10 + d;
    8878              :   }
    8879              :   *idx_out = idx;
    8880              :   return true;
    8881              : }
    8882              : 
    8883              : // Why navigate_y() stopped, so set and delete can tell a malformed path
    8884              : // (ccol_invalid_args: Wrong parent type, bad "#N", empty component, bad UTF-8,
    8885              : // at any position) from an absent well-formed component (ccol_key_not_found).
    8886              : // The UTF-8 test runs only from the first component that doesn't resolve.
    8887              : typedef enum {
    8888              :   CYAML_NAV_NOT_FOUND = 0,
    8889              :   CYAML_NAV_WRONG_TYPE,
    8890              :   CYAML_NAV_MALFORMED_INDEX,
    8891              :   CYAML_NAV_EMPTY_COMPONENT,
    8892              :   CYAML_NAV_BAD_UTF8,
    8893              : } cyaml_nav_fail;
    8894              : 
    8895              : // Walks a dot-separated path from root and gives the node at its end, or NULL,
    8896              : // for every path operation. path_copy is writable: Each unescaped dot becomes a
    8897              : // NUL and each component is unescaped in place. "#N" indexes a list. After an
    8898              : // absent component it still scans the rest for an empty or non-UTF-8
    8899              : // component, since that makes the whole path malformed. *fail_reason_out (may
    8900              : // be NULL) is written only when NULL comes back.
    8901          464 : static cyaml navigate_y(cyaml root, char *path_copy,
    8902              :                         cyaml_nav_fail *fail_reason_out) {
    8903          464 :   cyaml node = root;
    8904          464 :   char *p = path_copy;
    8905          464 :   cyaml_nav_fail fail_reason = CYAML_NAV_NOT_FOUND;
    8906          464 :   bool more = false;
    8907              : 
    8908          608 :   while (node) {
    8909          588 :     char *dot = path_find_unescaped_dot(p);
    8910          588 :     more = dot != NULL;
    8911          588 :     if (dot) *dot = '\0';
    8912              : 
    8913          588 :     if (p[0] == '\0') {
    8914              :       fail_reason = CYAML_NAV_EMPTY_COMPONENT;
    8915              :       node = NULL;
    8916              :       break;
    8917              :     }
    8918              : 
    8919          585 :     path_unescape_component(p);
    8920              : 
    8921          585 :     cyaml_node *n = (cyaml_node *)node;
    8922              : 
    8923          585 :     if (n->type == CYAML_LIST && p[0] == '#') {
    8924           46 :       size_t idx;
    8925           92 :       if (!parse_list_index_component(p + 1, &idx)) {
    8926              :         fail_reason = CYAML_NAV_MALFORMED_INDEX;
    8927              :         node = NULL;
    8928          464 :         break;
    8929              :       }
    8930           39 :       void *slot = cvector_at(n->value.list, idx);
    8931           39 :       node = slot ? *(cyaml *)slot : NULL;
    8932           39 :       if (!node) fail_reason = CYAML_NAV_NOT_FOUND;
    8933          539 :     } else if (n->type == CYAML_DICTIONARY) {
    8934          537 :       cmap_pair kp = {.ptr = p, .size = strlen(p) + 1};
    8935          537 :       cmap_pair vp;
    8936          537 :       if (chashmap_get_elem_ref(n->value.dictionary, &kp, &vp) !=
    8937              :           ccol_success) {
    8938           57 :         fail_reason = ccol_utf8_is_valid(p, kp.size - 1) ? CYAML_NAV_NOT_FOUND
    8939           57 :                                                          : CYAML_NAV_BAD_UTF8;
    8940              :         node = NULL;
    8941              :       } else {
    8942          480 :         node = cyaml_read_child(vp.ptr);
    8943              :       }
    8944              :     } else {
    8945              :       fail_reason = CYAML_NAV_WRONG_TYPE;
    8946              :       node = NULL;
    8947              :     }
    8948              : 
    8949          578 :     if (!dot) break;
    8950          144 :     p = dot + 1;
    8951              :   }
    8952          464 :   if (!node && more && fail_reason == CYAML_NAV_NOT_FOUND) {
    8953           26 :     for (;;) {
    8954           22 :       char *dot = path_find_unescaped_dot(p);
    8955           22 :       if (p[0] == '\0' || dot == p) {
    8956              :         fail_reason = CYAML_NAV_EMPTY_COMPONENT;
    8957              :         break;
    8958              :       }
    8959           17 :       if (!ccol_utf8_is_valid(p, dot ? (size_t)(dot - p) : strlen(p))) {
    8960              :         fail_reason = CYAML_NAV_BAD_UTF8;
    8961              :         break;
    8962              :       }
    8963            9 :       if (!dot) break;
    8964            4 :       p = dot + 1;
    8965              :     }
    8966              :   }
    8967          464 :   if (!node && fail_reason_out) *fail_reason_out = fail_reason;
    8968          464 :   return node;
    8969              : }
    8970              : 
    8971              : // Maps a navigate_y() failure to the code set and delete report for a parent
    8972              : // they couldn't reach: ccol_invalid_args for a malformed path (a leaf that
    8973              : // isn't UTF-8 included), ccol_key_not_found for an absent component.
    8974           36 : static ccol_retval nav_fail_to_retval(cyaml_nav_fail reason, const char *leaf) {
    8975           36 :   if (reason == CYAML_NAV_NOT_FOUND && !ccol_utf8_is_valid(leaf, strlen(leaf)))
    8976              :     return ccol_invalid_args;
    8977           32 :   switch (reason) {
    8978              :     case CYAML_NAV_WRONG_TYPE:
    8979              :     case CYAML_NAV_MALFORMED_INDEX:
    8980              :     case CYAML_NAV_EMPTY_COMPONENT:
    8981              :     case CYAML_NAV_BAD_UTF8:
    8982              :       return ccol_invalid_args;
    8983              :     case CYAML_NAV_NOT_FOUND:
    8984              :     default:
    8985              :       return ccol_key_not_found;
    8986              :   }
    8987              : }
    8988              : 
    8989              : // A path shorter than this is copied to the stack, so cyaml__get() allocates
    8990              : // nothing and can't fail for lack of memory.
    8991              : #define CYAML_GET_STACK_PATH 256
    8992              : // Gives the node at path, the body of cyaml_get(). It walks a copy of path, so
    8993              : // the caller's string never changes; only a long path is copied to the heap,
    8994              : // with root's allocator. NULL or "" gives root.
    8995          381 : cyaml cyaml__get(cyaml root, const char *path) {
    8996          381 :   if (!root) return NULL;
    8997          381 :   if (!path || path[0] == '\0') return root;
    8998          380 :   ccol_memmgmt_procs *mp = ((cyaml_node *)root)->m_procs;
    8999          380 :   char stack_copy[CYAML_GET_STACK_PATH];
    9000          380 :   size_t len = strlen(path);
    9001          380 :   char *copy = stack_copy;
    9002          380 :   if (len < sizeof(stack_copy)) {
    9003          380 :     memcpy(stack_copy, path, len + 1);
    9004              :   } else {
    9005            0 :     copy = ccol_strdup(mp, path);
    9006            0 :     if (!copy) return NULL;
    9007              :   }
    9008          380 :   cyaml result = navigate_y(root, copy, NULL);
    9009          380 :   if (copy != stack_copy) ccol__mem_free(mp, copy);
    9010              :   return result;
    9011              : }
    9012              : 
    9013              : // Writes a scalar to the leaf at path, the body of cyaml_set(). The path splits
    9014              : // at its last dot; the leaf is copied before the parent copy is freed, since it
    9015              : // lives inside it. An empty leaf, a bad payload and a key that isn't UTF-8 are
    9016              : // refused before anything changes. An existing scalar leaf is updated in place
    9017              : // (borrowed handles and custom tags survive) and a stale core tag is dropped. A
    9018              : // new dictionary key is inserted with a NULL placeholder in one probe and
    9019              : // removed again if building the child fails. An absent list index is
    9020              : // ccol_key_not_found, since a list doesn't grow to an index; no parent is ever
    9021              : // created.
    9022          224 : ccol_retval cyaml__set_typed(cyaml root, const char *path, cyaml_node_type type,
    9023              :                              void *raw, size_t raw_size, bool is_signed) {
    9024          224 :   if (!root || !path || path[0] == '\0') return ccol_invalid_args;
    9025              : 
    9026          224 :   ccol_memmgmt_procs *mp = ((cyaml_node *)root)->m_procs;
    9027          227 :   char *copy = ccol_strdup(mp, path);
    9028          223 :   if (!copy) return ccol_not_enough_memory;
    9029              : 
    9030          223 :   char *last_dot = path_find_last_unescaped_dot(copy);
    9031          223 :   char *leaf_copy;
    9032          223 :   cyaml parent;
    9033              : 
    9034          223 :   if (!last_dot) {
    9035          165 :     leaf_copy = ccol_strdup(mp, path);
    9036          165 :     parent = root;
    9037          165 :     ccol__mem_free(mp, copy);
    9038              :   } else {
    9039           58 :     *last_dot = '\0';
    9040           58 :     if (last_dot[1] == '\0') {
    9041            3 :       ccol__mem_free(mp, copy);
    9042           22 :       return ccol_invalid_args;
    9043              :     }
    9044           55 :     cyaml_nav_fail fail_reason = CYAML_NAV_NOT_FOUND;
    9045           55 :     leaf_copy = ccol_strdup(mp, last_dot + 1);
    9046           55 :     parent = navigate_y(root, copy, &fail_reason);
    9047           55 :     ccol__mem_free(mp, copy);
    9048           55 :     if (!leaf_copy) return ccol_not_enough_memory;
    9049           55 :     if (!parent) {
    9050           19 :       ccol_retval nav_rv = nav_fail_to_retval(fail_reason, leaf_copy);
    9051           19 :       ccol__mem_free(mp, leaf_copy);
    9052           19 :       return nav_rv;
    9053              :     }
    9054              :   }
    9055              : 
    9056          201 :   if (!leaf_copy) return ccol_not_enough_memory;
    9057          199 :   path_unescape_component(leaf_copy);
    9058          199 :   const char *leaf_comp = leaf_copy;
    9059          199 :   if (leaf_comp[0] == '\0') {
    9060            0 :     ccol__mem_free(mp, leaf_copy);
    9061            0 :     return ccol_invalid_args;
    9062              :   }
    9063              : 
    9064          199 :   cyaml_node *pn = (cyaml_node *)parent;
    9065          199 :   ccol_retval ret;
    9066              : 
    9067          199 :   if (pn->type == CYAML_DICTIONARY) {
    9068          177 :     cmap_pair kp = {.ptr = (void *)leaf_comp, .size = strlen(leaf_comp) + 1};
    9069          177 :     ret = ccol_utf8_is_valid(leaf_comp, kp.size - 1)
    9070          157 :               ? scalar_payload_check(type, raw, raw_size)
    9071          177 :               : ccol_invalid_args;
    9072          157 :     if (ret == ccol_success) {
    9073          120 :       cyaml_node *placeholder = NULL;
    9074          120 :       cmap_pair vp = {.ptr = &placeholder, .size = sizeof(placeholder)};
    9075          120 :       cmap_pair slot;
    9076          120 :       ccol_retval r =
    9077          120 :           ccol_chmap_insert_or_get_elem(pn->value.dictionary, &kp, &vp, &slot);
    9078          120 :       if (r == ccol_key_already_present) {
    9079           90 :         cyaml_node *existing = cyaml_read_child(slot.ptr);
    9080           90 :         ret = node_reinit_scalar_checked(existing, type, raw, raw_size,
    9081              :                                          is_signed);
    9082           30 :       } else if (r == ccol_success) {
    9083           29 :         cyaml_node *new_node = NULL;
    9084           29 :         ret = node_make_scalar(type, raw, raw_size, is_signed, pn->m_procs,
    9085              :                                &new_node);
    9086           29 :         if (ret == ccol_success) {
    9087           27 :           memcpy(slot.ptr, &new_node, sizeof(new_node));
    9088           27 :           new_node->attached = true;
    9089              :         } else {
    9090            2 :           chashmap_remove_elem(pn->value.dictionary, &kp);
    9091              :         }
    9092              :       } else {
    9093              :         ret = r;
    9094              :       }
    9095              :     }
    9096           22 :   } else if (pn->type == CYAML_LIST) {
    9097           20 :     if (leaf_comp[0] != '#') {
    9098              :       ret = ccol_invalid_args;
    9099              :     } else {
    9100           19 :       size_t idx;
    9101           38 :       if (!parse_list_index_component(leaf_comp + 1, &idx)) {
    9102              :         ret = ccol_invalid_args;
    9103              :       } else {
    9104           19 :         void *slot = cvector_at(pn->value.list, idx);
    9105           19 :         if (!slot) {
    9106              :           ret = ccol_key_not_found;
    9107              :         } else {
    9108           13 :           cyaml_node *existing = *(cyaml_node **)slot;
    9109           13 :           ret = node_reinit_scalar(existing, type, raw, raw_size, is_signed);
    9110              :         }
    9111              :       }
    9112              :     }
    9113              :   } else {
    9114              :     ret = ccol_invalid_args;
    9115              :   }
    9116              : 
    9117          199 :   ccol__mem_free(mp, leaf_copy);
    9118              :   return ret;
    9119              : }
    9120              : 
    9121              : // Removes and deep-frees the node at path, the body of cyaml_remove(). The path
    9122              : // splits at its last unescaped dot (no dot: root is the parent), and the leaf
    9123              : // is unescaped. ccol_invalid_args for NULL or "" arguments, an empty or
    9124              : // non-UTF-8 leaf, a malformed component or a parent of the wrong type;
    9125              : // ccol_key_not_found for an absent key or index; ccol_not_enough_memory when a
    9126              : // copy fails.
    9127           38 : ccol_retval cyaml__remove(cyaml root, const char *path) {
    9128           38 :   if (!root || !path || path[0] == '\0') return ccol_invalid_args;
    9129              : 
    9130           37 :   ccol_memmgmt_procs *mp = ((cyaml_node *)root)->m_procs;
    9131           38 :   char *copy = ccol_strdup(mp, path);
    9132           37 :   if (!copy) return ccol_not_enough_memory;
    9133              : 
    9134           37 :   char *last_dot = path_find_last_unescaped_dot(copy);
    9135           37 :   char *leaf_copy;
    9136           37 :   cyaml parent;
    9137              : 
    9138           37 :   if (!last_dot) {
    9139            5 :     leaf_copy = ccol_strdup(mp, path);
    9140            5 :     parent = root;
    9141            5 :     ccol__mem_free(mp, copy);
    9142              :   } else {
    9143           32 :     *last_dot = '\0';
    9144           32 :     if (last_dot[1] == '\0') {
    9145            3 :       ccol__mem_free(mp, copy);
    9146           20 :       return ccol_invalid_args;
    9147              :     }
    9148           29 :     cyaml_nav_fail fail_reason = CYAML_NAV_NOT_FOUND;
    9149           29 :     leaf_copy = ccol_strdup(mp, last_dot + 1);
    9150           29 :     parent = navigate_y(root, copy, &fail_reason);
    9151           29 :     ccol__mem_free(mp, copy);
    9152           29 :     if (!leaf_copy) return ccol_not_enough_memory;
    9153           29 :     if (!parent) {
    9154           17 :       ccol_retval nav_rv = nav_fail_to_retval(fail_reason, leaf_copy);
    9155           17 :       ccol__mem_free(mp, leaf_copy);
    9156           17 :       return nav_rv;
    9157              :     }
    9158              :   }
    9159              : 
    9160           17 :   if (!leaf_copy) return ccol_not_enough_memory;
    9161           16 :   path_unescape_component(leaf_copy);
    9162           16 :   const char *leaf_comp = leaf_copy;
    9163              : 
    9164           16 :   if (leaf_comp[0] == '\0') {
    9165            0 :     ccol__mem_free(mp, leaf_copy);
    9166            0 :     return ccol_invalid_args;
    9167              :   }
    9168              : 
    9169           16 :   cyaml_node *pn = (cyaml_node *)parent;
    9170           16 :   ccol_retval ret;
    9171              : 
    9172           16 :   if (pn->type == CYAML_DICTIONARY) {
    9173            6 :     ret = cyaml_dictionary_remove(parent, leaf_comp);
    9174            9 :     if (ret == ccol_key_not_found &&
    9175            3 :         !ccol_utf8_is_valid(leaf_comp, strlen(leaf_comp)))
    9176            4 :       ret = ccol_invalid_args;
    9177           10 :   } else if (pn->type == CYAML_LIST) {
    9178           10 :     if (leaf_comp[0] != '#') {
    9179              :       ret = ccol_invalid_args;
    9180              :     } else {
    9181           10 :       size_t idx;
    9182           20 :       if (!parse_list_index_component(leaf_comp + 1, &idx)) {
    9183              :         ret = ccol_invalid_args;
    9184            8 :       } else if (idx >= cvector_size(pn->value.list)) {
    9185              :         ret = ccol_key_not_found;
    9186              :       } else {
    9187            2 :         ret = cyaml_list_remove(parent, idx);
    9188              :       }
    9189              :     }
    9190              :   } else {
    9191              :     ret = ccol_invalid_args;
    9192              :   }
    9193              : 
    9194           16 :   ccol__mem_free(mp, leaf_copy);
    9195              :   return ret;
    9196              : }
        

Generated by: LCOV version 2.0-1