diff --git a/.github/workflows/tools.yml b/.github/workflows/tools.yml index d1db2a68229..659aba58347 100644 --- a/.github/workflows/tools.yml +++ b/.github/workflows/tools.yml @@ -25,6 +25,7 @@ on: - gyp-next - histogram - icu + - igname - inspector_protocol - libffi - libuv @@ -159,6 +160,14 @@ jobs: cat temp-output tail -n1 temp-output | grep "NEW_VERSION=" >> "$GITHUB_ENV" || true rm temp-output + - id: igname + subsystem: deps + label: dependencies + run: | + ./tools/dep_updaters/update-igname.sh > temp-output + cat temp-output + tail -n1 temp-output | grep "NEW_VERSION=" >> "$GITHUB_ENV" || true + rm temp-output - id: inspector_protocol subsystem: deps label: dependencies, inspector diff --git a/LICENSE b/LICENSE index 9ade32efb25..2d7aaf98efb 100644 --- a/LICENSE +++ b/LICENSE @@ -126,6 +126,31 @@ The externally maintained libraries used by Node.js are: CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ +- igname, located at deps/igname, is licensed as follows: + """ + MIT License + + Copyright (c) 2026 James M Snell and igname contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + """ + - ittapi, located at deps/v8/third_party/ittapi, is licensed as follows: """ Copyright (c) 2019 Intel Corporation. All rights reserved. diff --git a/deps/igname/BUILD.gn b/deps/igname/BUILD.gn new file mode 100644 index 00000000000..bb973f5979f --- /dev/null +++ b/deps/igname/BUILD.gn @@ -0,0 +1,14 @@ +############################################################################## +# # +# DO NOT EDIT THIS FILE! # +# # +############################################################################## + +# This file is used by GN for building, which is NOT the build system used for +# building official binaries. +# Please modify the gyp files if you are making changes to build system. + +import("unofficial.gni") + +igname_gn_build("igname") { +} diff --git a/deps/igname/LICENSE b/deps/igname/LICENSE new file mode 100644 index 00000000000..fb83639a972 --- /dev/null +++ b/deps/igname/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 James M Snell and igname contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/deps/igname/README.md b/deps/igname/README.md new file mode 100644 index 00000000000..b2568645154 --- /dev/null +++ b/deps/igname/README.md @@ -0,0 +1,473 @@ +# igname + +*Igname* is Italian for "yam", a nod to YAML. It is pronounced +**EE-nyah-meh** (IPA /ˈiɲ.ɲa.me/): the stress falls on the first syllable, +and "gn" sounds like the "ny" in "canyon" (or the Spanish "ñ"). + +A small, fast, exception-free YAML 1.2 parser and emitter for C++20, in two +headers, written to be vendored into Node.js (and anything else with the same +constraints). + +* **Event based.** igname reports the document as a stream of events to a + handler passed as a template parameter. It never builds a tree of its own, + so a binding can create its native values (for example V8 objects) directly + from the events, without an intermediate copy of the document. +* **Spec compliant.** Passes all 402 cases of the official + [YAML test suite](https://github.com/yaml/yaml-test-suite) (event streams + and error cases), and all 279 JSON cases using the bundled core schema + resolver. +* **Fast.** Parses at roughly 350-1400 MiB/s on typical inputs (see + [Benchmarks](#benchmarks)), using portable word-at-a-time scanning and + zero-copy scalars. +* **Emitter included.** A streaming emitter writes YAML from calls such as + `BeginMapping()` and `String()`, choosing quoting and styles so that the + output reads back as the same values (see [Emitting](#emitting)). +* **Embeddable.** No exceptions, no RTTI, no allocations per event, no global + state, no platform-specific code. Optional use of + [simdutf](https://github.com/simdutf/simdutf) and + [fast_float](https://github.com/fastfloat/fast_float). + +## Usage + +```cpp +#include + +struct Handler : igname::BaseHandler { + bool OnMappingStart(igname::CollectionStyle, const igname::NodeInfo&); + bool OnMappingEnd(); + bool OnSequenceStart(igname::CollectionStyle, const igname::NodeInfo&); + bool OnSequenceEnd(); + bool OnScalar(std::string_view value, igname::ScalarStyle style, + const igname::NodeInfo& info); + bool OnAlias(std::string_view anchor, const igname::Mark& mark); +}; + +Handler handler; +igname::Result result = igname::Parse(input, handler); +if (!result) { + // result.error, result.message, result.line, result.column +} +``` + +Handlers derive from `igname::BaseHandler` and shadow the methods they need +(dispatch is static). The full set of events is: + +| Method | Event | +| --- | --- | +| `OnStreamStart()` / `OnStreamEnd()` | start and end of input | +| `OnDocumentStart(bool explicit_start)` / `OnDocumentEnd(bool explicit_end)` | each document (`---` / `...` present) | +| `OnMappingStart(style, info)` / `OnMappingEnd()` | a mapping; its children alternate key, value | +| `OnSequenceStart(style, info)` / `OnSequenceEnd()` | a sequence | +| `OnScalar(value, style, info)` | a scalar | +| `OnAlias(name, mark)` | an alias (`*name`) | + +`NodeInfo` carries the node's anchor, its fully resolved tag (for example +`tag:yaml.org,2002:str`, or `!` for the non-specific tag; empty when the node +is untagged) and its position. Every method returns `bool`; returning `false` +stops parsing immediately with `Error::kAborted`, which is how an embedder +bails out when, say, a JavaScript exception is pending. + +### Lifetimes + +String views passed to the handler are valid only during the call. Scalars +are slices of the input whenever possible (plain single-line scalars and +quoted scalars without escapes or line folding); otherwise they point into a +scratch buffer that is reused for the next scalar. + +### Input + +`Parse()` accepts UTF-8 (with or without a byte order mark), UTF-16 and +UTF-32, detected as described in YAML 1.2 section 5.2. Malformed input +produces `Error::kInvalidEncoding`; C0 control characters other than tab and +line breaks produce `Error::kInvalidCharacter`. CRLF and CR line breaks are +normalized to LF. An input copy is made only when transcoding or normalizing +line breaks. + +### Errors + +`Result` holds an `Error` code, a static message, and the 1-based line and +column (in code points) of the error. `ParseOptions::max_depth` (default 512) +bounds collection nesting, and with it the parser's recursion; exceeding it +produces `Error::kDepthExceeded`. + +### Core schema + +igname reports scalars as text. `igname::ResolveScalar()` applies the YAML +1.2 core schema: untagged plain scalars are matched against the null, bool, +int and float patterns, other untagged scalars are strings, and the core +schema tags (`!!null`, `!!bool`, `!!int`, `!!float`, `!!str`) force a type +(returning `ResolveStatus::kInvalid` when the value does not match, for +example `!!int abc`). Integers that do not fit in `int64_t` are reported with +`overflow` set, so a binding can create a big integer from the source text. + +```cpp +igname::ScalarValue v; +switch (igname::ResolveScalar(value, style, info.tag, &v)) { + case igname::ResolveStatus::kOk: /* use v.kind, v.integer, ... */ + case igname::ResolveStatus::kInvalid: /* e.g. !!int abc */ + case igname::ResolveStatus::kUnknownTag: /* application-specific tag */ +} +``` + +## Emitting + +`include/igname/emitter.hpp` provides `igname::Emitter`, which writes YAML +from a sequence of calls. Like the parser, it builds no tree and does not +throw: misuse (a value without a key, unbalanced `End` calls, invalid UTF-8) +sets an error, after which every call returns `false` and nothing more is +written. + +```cpp +#include + +std::string out; +igname::Emitter<> e(&out); +e.BeginMapping(); +e.String("name"); e.String("app"); +e.String("ports"); e.BeginSequence(); e.Int(80); e.Int(443); e.EndSequence(); +e.String("debug"); e.Bool(false); +e.EndMapping(); +if (!e.Finish()) { + // e.result().error, e.result().message +} +``` + +```yaml +name: app +ports: + - 80 + - 443 +debug: false +``` + +| Method | Writes | +| --- | --- | +| `BeginMapping(style, props)` / `EndMapping()` | a mapping; children alternate key, value | +| `BeginSequence(style, props)` / `EndSequence()` | a sequence | +| `String(value, props)` | a string | +| `Key(prepared)` | a string prepared with `PrepareKey()` (see below) | +| `Null()`, `Bool()`, `Int()`, `Double()` | core schema values | +| `RawScalar(text, props)` | text written as a plain scalar (for example a big integer) | +| `Alias(name)` | an alias | +| `BeginDocument()` / `EndDocument()` | optional; each top-level node otherwise starts a new document | +| `Finish()` | ends the stream and flushes the output | +| `Reset()` | nothing; starts a new stream (see below) | + +`props` (`igname::Properties`) carries an optional anchor and a full tag +(`tag:yaml.org,2002:str`, `!local`, ...), written in shorthand where +possible. + +The output is UTF-8. Strings are written as plain scalars when that is +unambiguous; otherwise single-quoted, as a literal block scalar (`|`) when +they span lines, or double-quoted when they need escapes. A string that a +YAML parser would read as another type (`true`, `null`, `12`, `0x1F`) is +always quoted, so `String()` values read back as strings. By default the +emitter also quotes strings that YAML 1.1 parsers (still common) would read +as other types, such as `yes`, `off`, `0755` and `2001-12-14`. Doubles are +written in the shortest form that reads back as the same value. +Collections use block style unless flow style is requested; empty +collections are written as `[]` and `{}`. Long lines are not folded. + +`EmitOptions` sets the indentation (default 2), whether block sequences under +a key are indented (default yes), whether to escape all non-ASCII characters +for ASCII-only output, whether to quote the YAML 1.1 types, and explicit +`---` / `...` markers. + +The emitter writes to a `std::string`, or to any type with a +`bool Write(const char* data, size_t size)` method (`Emitter`). It +buffers the output and writes it in chunks of up to 64 KiB; a piece of text +longer than 32 KiB (a long scalar or literal line) is passed through in a +call of its own. `ascii_only()` reports whether the output so far is pure +ASCII, which lets a binding create a one-byte string without scanning it. + +A `std::string` that grows while it is written to is the most expensive +part of emitting: in the benchmarks, emitting into a new, empty string each +time was 15-41% slower than emitting into one that was reserved beforehand +(`out.reserve(...)`) or reused, and the +growth also raises the peak memory (see [Memory use](#memory-use)). When +the output size can be estimated (when reformatting, about the input size), +reserve it; otherwise reuse the string. + +To emit many small documents, keep one emitter and call `Reset()` before +each one (clearing or replacing the output string too). It makes the +emitter behave as a new one with the same sink and options, and keeps its +memory and its remembered keys (see below). Output that `Finish()` has not +yet written to the sink is discarded. Setting up a new emitter is +noticeable for small documents: a 48-byte mapping took 270 ns with a new +emitter and 100 ns with `Reset()`, and a 313-byte one 930 and 630 ns. + +Mapping keys usually repeat: a binding that serializes many objects of the +same shape writes the same property names again and again. Two things make +repeated keys cheaper, and neither changes the output: + +* `PrepareKey(text)` checks and formats a key once; `Key(prepared)` then + writes exactly what `String(text)` would, without examining the string + again (in a value position it is simply `String(text)`). A binding can + keep prepared keys per object shape. In the benchmarks, this made emitting + 10-18% faster than `String()` keys (the `keys` column below). +* Short keys (up to 32 bytes, ASCII, without properties) that were written + plain are also remembered automatically, in a table of 256 entries matched + by content. If most keys do not repeat, the emitter stops looking for a + while, so documents with unique keys are not slowed down. + +The emitter is also a parser handler, so `igname::Parse(input, emitter)` +reformats a YAML stream. Plain scalars stay plain, and so keep their type. +Comments and the original layout are not preserved. `igname_format` is a +command-line tool that does this. + +## Building + +The library is the two headers `include/igname/igname.hpp` and (for +emitting) `include/igname/emitter.hpp`. Optional +dependencies, enabled by defining a macro before including it: + +| Macro | Effect | +| --- | --- | +| `IGNAME_USE_SIMDUTF` | validate UTF-8 with simdutf (`simdutf.h`) | +| `IGNAME_USE_FAST_FLOAT` | parse floats with fast_float (`fast_float/fast_float.h`) | + +Without fast_float, floats are parsed with `std::from_chars` where the +standard library provides it for floating point, and with `strtod` otherwise +(note that `strtod` honors `LC_NUMERIC`). + +Tests, tools and benchmarks build with CMake: + +```sh +test/fetch-suite.sh # downloads the YAML test suite data +cmake -B build -G Ninja && ninja -C build +ctest --test-dir build # suite, unit, emitter and JSON tests +``` + +CMake options: `-DIGNAME_SIMDUTF_DIR=...`, `-DIGNAME_FAST_FLOAT_DIR=...`, +`-DIGNAME_SANITIZE=ON` (ASan and UBSan). The libFuzzer harnesses (clang +only) are `test/fuzz.cc` (target `igname_fuzz`), which fuzzes the parser and +the parse, emit, parse round trip, and `test/fuzz_emit.cc` +(`igname_fuzz_emit`), which fuzzes sequences of emitter calls. +`igname_events` prints the event stream of a file in the test suite's +notation, `igname_json` converts YAML to JSON using the core schema, and +`igname_format` reformats YAML. + +The emitter tests (`test/emit.cc`) also round-trip every valid case of the +YAML test suite with several option sets. Each output must parse to the same +events (styles aside) and must reformat to itself. + +## Benchmarks + +`igname_bench` measures generated 8 MiB corpora. Three parser handlers: +parsing only (`events`), parsing and resolving every scalar with the core +schema (`resolve`), and additionally building a heap-allocated tree (`tree`, +a stand-in for the work a binding does). Two emitter measurements: +reformatting, that is parsing with the emitter as the handler (`format`, +MiB/s of input), and emitting the tree built by `tree` through `Null()`, +`Bool()`, `Int()`, `Double()` and `String()` calls, the way a binding +serializes values (`emit`, MiB/s of output), and the same with mapping keys +written with `Key()` from keys prepared beforehand (`keys`, see +[Emitting](#emitting)). Clang 22, `-O2`, x86-64, no +optional dependencies, MiB/s, best of 10 (run to run variation is about +5-10%): + +| Input | events | resolve | tree | format | emit | keys | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Kubernetes manifests | 542 | 460 | 200 | 293 | 519 | 571 | +| CI workflows | 567 | 479 | 202 | 277 | 541 | 640 | +| JSON-like flow data | 325 | 250 | 89 | 199 | 263 | 290 | +| Text (quoted, folded and literal scalars) | 1430 | 1342 | 566 | 628 | 1220 | 1376 | + +Building values costs more than parsing: in an embedding such as a +JavaScript binding, object creation is likely to dominate. Emitting costs +more than parsing too, mainly because every string is checked to choose +its style and quoting. `igname_bench --write-corpora DIR` writes the +corpora as files, for measuring other libraries. + +### Optional dependencies + +* **simdutf** matters for non-ASCII input. On ASCII the built-in input check, + which examines eight bytes at a time, never needs to validate UTF-8, so + simdutf makes no difference. On a 5 MB document of mostly CJK, Cyrillic and + Greek text, parsing went from 336 to 1058 MiB/s with simdutf, because the + built-in validator handles multi-byte characters one at a time. The same + holds for emitting, which validates every non-ASCII string: on 8 MiB of + locale files (ASCII keys, values in Japanese, Russian, German and French), + emitting went from 472 to 859 MiB/s with simdutf. +* **fast_float** makes no measurable difference where the standard library + implements `std::from_chars` for floating point (libstdc++ 12 and later use + a comparable algorithm). It matters where igname falls back to `strtod`, such + as older libc++ versions: core schema resolution of the JSON-like corpus + was 9% slower with `strtod` (249 vs. 274 MiB/s), and `strtod` depends on + the process locale. Enabling it gives the same behavior on every platform. + +### Compared with other libraries + +For context, two other C and C++ libraries were measured on the same machine +and corpora: [libyaml](https://github.com/yaml/libyaml) 0.2.5, the most +widely used C implementation, and +[rapidyaml](https://github.com/biojppm/rapidyaml) 0.16.0, a C++ library +designed for speed. All were built with Clang 22 at `-O2`. For every corpus, +the output of each library's emitter was checked to parse to the same +events as the input (scalar styles aside). MiB/s, best of 10 runs. + +**Parsing.** libyaml pulls each event with `yaml_parser_parse()` and frees +it, the least work its API allows. rapidyaml parses in place into its tree, +either a new tree for each parse or a tree (and parser) reused across +parses, which keeps their memory. The igname columns are the `events` +handler (no tree) and the `tree` handler (resolves every scalar and builds +a tree of heap-allocated nodes, more work than rapidyaml's flat tree): + +| Input | libyaml | rapidyaml, new tree | rapidyaml, reused tree | igname, events | igname, tree | +| --- | ---: | ---: | ---: | ---: | ---: | +| Kubernetes manifests | 87 | 112 | 324 | 542 | 200 | +| CI workflows | 87 | 116 | 354 | 567 | 202 | +| JSON-like flow data | 62 | 61 | 287 | 325 | 89 | +| Text (quoted, folded and literal scalars) | 158 | 268 | 425 | 1430 | 566 | +| Non-ASCII text (5 MiB) | 96 | | | 343 (983 with simdutf) | | + +**Emitting** (MiB/s of output). libyaml emits events that were parsed +beforehand (outside the timed region). rapidyaml emits its tree with +`emitrs_yaml()`. igname is the `emit` and `keys` columns above. All three +write to a `std::string` whose memory is reused across runs: + +| Input | libyaml | rapidyaml | igname | igname, prepared keys | +| --- | ---: | ---: | ---: | ---: | +| Kubernetes manifests | 129 | 744 | 519 | 571 | +| CI workflows | 135 | 775 | 541 | 640 | +| JSON-like flow data | 101 | 469 | 263 | 290 | +| Text (quoted, folded and literal scalars) | 123 | 1389 | 1220 | 1376 | + +**Reformatting** (parse and emit, MiB/s of input). libyaml passes each +parsed event to `yaml_emitter_emit()`; rapidyaml parses into a reused tree +and emits it; igname parses with the emitter as the handler (`format`): + +| Input | libyaml | rapidyaml | igname | +| --- | ---: | ---: | ---: | +| Kubernetes manifests | 52 | 216 | 293 | +| CI workflows | 53 | 233 | 277 | +| JSON-like flow data | 38 | 176 | 199 | +| Text (quoted, folded and literal scalars) | 66 | 309 | 628 | + +The output sizes are similar: within about 10% of each other and of the +input, except for the JSON-like corpus (8.4 MB of input). igname writes it +in 7.0 MB, without the quotes that keys and words do not need, and with the +whole top-level flow sequence on one line, since it does not break flow +collections across lines. rapidyaml keeps the quotes and the line breaks +(8.0 MB), and libyaml writes 8.7 MB. + +How to read these numbers: + +* **The libraries do different amounts of work.** libyaml hands out + self-contained events: it allocates and copies every scalar, anchor and + tag, so events can be kept after the call returns. igname passes slices of + the input that are valid only during the callback. rapidyaml builds a tree + whose strings point into the (modified) input buffer. Much of the + difference in parsing comes from these design choices. +* **rapidyaml's emitter writes what the tree already knows.** It keeps the + style each node was parsed with (quotes, block or flow), so emitting is + mostly copying. igname's emitter is given values, not styles: it checks + every string to decide whether it can be plain and how to quote it, so that + the output reads back as the same values. That check is most of the + difference in the emitting table, and it is work a binding that serializes + JavaScript values needs anyway. libyaml also analyzes every scalar, and + tracks the column to fold long lines (turning folding off made a + difference of 8% at most). +* **Memory reuse matters for rapidyaml.** A new tree starts small and grows + by reallocation; reusing a tree made parsing 1.6 to 4 times faster here. + Its reformatting row uses a reused tree. +* **They target different specifications and have different scope.** libyaml + implements YAML 1.1 (recent releases accept `%YAML 1.2` documents); igname + and rapidyaml implement YAML 1.2. libyaml also provides a token API, and + rapidyaml a full tree API with C++ type conversions, JSON output and alias + resolution. Both preserve the input's styles when reformatting more closely + than igname, which chooses styles itself. +* **libyaml and rapidyaml are mature.** Both have been in wide use for years: + libyaml as the parser behind PyYAML and Ruby's Psych, rapidyaml in + performance-sensitive C++ projects. igname is new. +* **The corpora are synthetic** and come from igname's own benchmark. Real + documents vary, and so will the ratios. The numbers come from a single + x86-64 machine. +* **Parsing is rarely the bottleneck.** As the `tree` column shows, building + values typically costs more than parsing, so the end-to-end difference in + an application is much smaller than these ratios suggest. + +### Memory use + +Heap use was measured for the same libraries and corpora by replacing +`malloc`, `free` and related functions with versions that count live bytes, +the peak and the number of allocations. Measurements start after the input +is loaded, so they show what each library needs beyond holding the input. +*Peak* is the most memory in use at any point, *live* what is still +allocated at the end. Sizes are for the 8 MiB corpora. + +**Parsing.** igname's parser does not allocate per event: parsing used at +most 1 KiB and 5 allocations for any corpus. Its only allocations are a few +buffers that are reused for the whole parse (for scalars that are not slices +of the input, resolved tags and `%TAG` handles), and a copy of the input +when it has to be transcoded from UTF-16 or UTF-32 or its CRLF line breaks +normalized. libyaml also parses in constant memory (about 67 KiB) but +allocates a copy of every scalar, anchor and tag: 2.6 to 4.2 allocations per +event, 2.4 million for the Kubernetes corpus. + +**Trees.** rapidyaml parses into its own tree; igname builds none, so the +igname row is the benchmark's `tree` handler, a stand-in for the values a +binding creates (for a JavaScript binding, these live on the JavaScript +heap rather than in igname). Memory as a multiple of the input size: + +| Input | rapidyaml, new tree (live / peak) | rapidyaml, reserved tree | benchmark `tree` handler | +| --- | ---: | ---: | ---: | +| Kubernetes manifests | 9.0x / 13.5x | 11.6x / 17.4x | 10.8x | +| JSON-like flow data | 18.0x / 27.0x | 12.1x | 15.9x | +| Text | 2.3x / 3.4x | 3.2x | 2.9x | + +rapidyaml's peak exceeds its live size because its node array grows by +reallocation. Reserving the tree with `estimate_tree_capacity()` avoids the +growth, but the estimate can exceed what is needed (as for the Kubernetes +corpus). rapidyaml also parses in place, so it needs a writable copy of the +input unless the caller already has one; that copy is not counted here. + +**Emitting.** With the output discarded, the emitters' own working memory +is small and does not grow with the document: about 105 KiB for igname +(its output buffer, at most 64 KiB, scratch space for scalars and the +8.5 KiB table of recent keys; 13 KiB for a 3 KB document), about 120 KiB for +libyaml (which also makes 2.4 to 3.7 million allocations for the events it +consumes), and 4 KiB for rapidyaml writing to a `FILE*`. + +When the output is a `std::string`, the string dominates. rapidyaml sizes +it exactly (it measures the output, then emits into one allocation), so its +peak equals the output size. igname appends to the string in chunks of up +to 64 KiB, and the string grows by doubling, so the old and new buffers +briefly coexist. The peak therefore depends on where the output size falls +between powers of two: 12 MiB for 8.3 MB of output (1.5 times), but 24 MiB +for the CI workflow corpus, whose 8.4 MB of output just exceeds 8 MiB (2.9 +times). Reserving the string, or a sink that writes the output elsewhere in +chunks (for example a binding that creates the JavaScript string from +them), avoids this. + +**Reformatting** (parse and emit into a `std::string`), peak as a multiple +of the input: + +| Input | libyaml | rapidyaml | igname | +| --- | ---: | ---: | ---: | +| Kubernetes manifests | 2.4x | 13.5x | 1.5x | +| JSON-like flow data | 3.0x | 27.0x | 1.5x | +| Text | 1.5x | 3.4x | 1.5x | + +libyaml and igname stream, so their peak is mostly the output string (and, +as above, depends on how its growth falls; for the CI workflow corpus +igname's peak was 3.0x); rapidyaml holds the whole tree before it emits. + +## Behavior notes + +* igname is an event parser: it does not detect duplicate mapping keys or + resolve aliases. Both are the handler's job, since the right behavior + depends on the target representation. +* The explicit indentation indicator of a block scalar at document level is + interpreted relative to column 0 (`--- |2` means two spaces), as libyaml + does. +* Implicit keys are limited to 1024 characters by the specification; igname + looks for the `:` of an implicit key within 4096 bytes. +* Characters that YAML excludes from streams but that are harmless to + process (C1 controls, DEL, U+FFFE and U+FFFF) are accepted. +* `%YAML 1.x` directives are accepted for any minor version; other major + versions are rejected. + +## License + +MIT diff --git a/deps/igname/igname.gyp b/deps/igname/igname.gyp new file mode 100644 index 00000000000..92b4a43a537 --- /dev/null +++ b/deps/igname/igname.gyp @@ -0,0 +1,13 @@ +{ + # Header-only. Dependents may additionally define IGNAME_USE_SIMDUTF and/or + # IGNAME_USE_FAST_FLOAT and add the corresponding include directories. + 'targets': [ + { + 'target_name': 'igname', + 'type': 'none', + 'direct_dependent_settings': { + 'include_dirs': ['include'], + }, + }, + ] +} diff --git a/deps/igname/include/igname/emitter.hpp b/deps/igname/include/igname/emitter.hpp new file mode 100644 index 00000000000..1862c96df7f --- /dev/null +++ b/deps/igname/include/igname/emitter.hpp @@ -0,0 +1,1541 @@ +// igname -- YAML 1.2 emitter. +// +// SPDX-License-Identifier: MIT +// +// The emitter is the counterpart of the event parser: the caller pushes +// events (begin/end collection, scalars, aliases) and the emitter writes YAML +// text, choosing quoting, scalar styles and layout. No tree is built. +// +// std::string out; +// igname::Emitter<> e(&out); // or Emitter e(MySink(...)) +// e.BeginMapping(); +// e.String("name"); e.String("app"); +// e.String("ports"); e.BeginSequence(); e.Int(80); e.EndSequence(); +// e.EndMapping(); +// if (!e.Finish()) { /* e.result().message */ } +// +// Guarantees: +// * The output is UTF-8 and parses back (with any YAML 1.2 parser) to the +// same structure. Scalars written with String() read back as strings under +// the core schema; Null/Bool/Int/Double read back as those types. +// * No exceptions. Misuse (a value without a key, unbalanced End calls, +// invalid UTF-8, ...) sets an error, after which every call returns false +// and nothing more is written. +// * The emitter is also a parser handler, so igname::Parse(input, emitter) +// reformats a YAML stream. Plain scalars from the parser stay plain, so +// their core schema type is preserved. +// +// Style rules: strings are written plain when that is unambiguous, otherwise +// single-quoted, as a literal block scalar (|) when they span lines, or +// double-quoted when they need escapes. Collections are block style unless +// flow style is requested (or they are empty, or nested in a flow +// collection). Long lines are never folded. + +#ifndef IGNAME_EMITTER_HPP_ +#define IGNAME_EMITTER_HPP_ + +#include "igname.hpp" + +#include +#include +#include +#include +#include +#include + +// Forces inlining of small functions on hot paths (with GCC and Clang; with +// MSVC, __forceinline warns (C4714) where it cannot be honored). +#if defined(__GNUC__) || defined(__clang__) +#define IGNAME_INLINE inline __attribute__((always_inline)) +#else +#define IGNAME_INLINE inline +#endif + +namespace igname { + +struct EmitOptions { + // Spaces per indentation level, 1 to 9. + int indent = 2; + // Indent block sequences that are mapping values ("key:\n - a") rather + // than aligning them with the key ("key:\n- a"). + bool indent_sequences = true; + // Write non-ASCII characters in scalars as escapes (in double quotes), so + // that the output is pure ASCII. Anchors are not affected. + bool escape_non_ascii = false; + // Also quote strings that a YAML 1.1 parser would read as another type + // (yes, no, on, off, 0755, 1:20, 2001-12-14, ...). Recommended for + // interoperability; it only adds quotes. + bool quote_yaml11 = true; + // Always start documents with "---" / end them with "...". + bool explicit_document_start = false; + bool explicit_document_end = false; + // Maximum nesting depth of collections. + uint32_t max_depth = 512; +}; + +enum class EmitError : uint8_t { + kNone = 0, + kInvalidState, // the call is not valid here (e.g. EndMapping after a key) + kInvalidUtf8, // a string or anchor is not valid UTF-8 + kInvalidArgument, // e.g. an empty anchor, or RawScalar text that is unsafe + kDepthExceeded, // nesting exceeded EmitOptions::max_depth + kSinkFailed, // the sink's Write() returned false +}; + +struct EmitResult { + EmitError error = EmitError::kNone; + const char* message = ""; // static string, never null + explicit operator bool() const { return error == EmitError::kNone; } +}; + +// Node properties for emitting. `tag` is a full tag ("tag:yaml.org,2002:str", +// "!local", "!" for the non-specific tag); it is written in shorthand form +// where possible. +struct Properties { + std::string_view anchor; + std::string_view tag; +}; + +// Appends the output to a std::string. +class StringSink { + public: + explicit StringSink(std::string* out) : out_(out) {} + bool Write(const char* data, size_t size) { + out_->append(data, size); + return true; + } + + private: + std::string* out_; +}; + +namespace detail { + +// What a string looks like, for choosing a scalar style. +struct StringAnalysis { + bool plain_block = true; // may be a plain scalar in block context + bool plain_flow = true; // may be a plain scalar in flow context + bool newline = false; // contains a line break + bool escape = false; // contains characters that must be escaped + bool non_ascii = false; +}; + +// Bytes that need a closer look when analyzing a string: controls, line +// breaks, ':', '#', flow indicators, DEL, and the lead bytes of the +// non-ASCII characters that are escaped (C1 controls, LS/PS, BOM, U+FFFE/F). +inline constexpr struct SpecialTable { + bool v[256] = {}; + constexpr SpecialTable() { + for (int c = 0; c < 0x20; ++c) v[c] = c != '\t'; + for (int c : {0x7F, 0xC2, 0xE2, 0xEF}) v[c] = true; + for (char c : {':', '#', ',', '[', ']', '{', '}'}) { + v[static_cast(c)] = true; + } + } +} kSpecial; + +// High bit set in (at least) the first byte of `w` that may be special (see +// kSpecial), and in no byte unless some byte may be special. It may flag +// extra bytes (tab, controls); callers look at flagged bytes one at a time. +inline uint64_t SpecialMask(uint64_t w) { + // Setting bit 5 maps '[' to '{' and ']' to '}'; the other bytes it maps + // onto ':', '#', ',', '{' or '}' are controls, special anyway. + const uint64_t v = w | (kOnes * 0x20); + uint64_t m = ((w - kOnes * 0x20) & ~w & kHighs) | MatchByte(w, '\x7F') | + MatchByte(v, ':') | MatchByte(v, '#') | MatchByte(v, ',') | + MatchByte(v, '{') | MatchByte(v, '}'); + if (w & kHighs) { // rare in most documents + m |= MatchByte(w, '\xC2') | MatchByte(w, '\xE2') | MatchByte(w, '\xEF'); + } + return m; +} + +// kSkip = false examines every byte (for testing the skipping). With kCopy, +// the string is also copied to `copy` (s.size() bytes) as it is examined. +template +inline StringAnalysis AnalyzeString(std::string_view s, + char* copy = nullptr) { + StringAnalysis a; + const size_t n = s.size(); + if (n == 0) { + a.plain_block = a.plain_flow = false; + return a; + } + const char first = s[0]; + if (IsWhite(first) || IsWhite(s[n - 1]) || s[n - 1] == ':') { + a.plain_block = a.plain_flow = false; + } else if (Has(first, kIndicator)) { + // '-', '?' and ':' may start a plain scalar if a non-space follows. + if ((first == '-' || first == '?' || first == ':') && n > 1 && + !IsWhite(s[1]) && s[1] != '\n') { + if (IsFlowIndicator(s[1])) a.plain_flow = false; + } else { + a.plain_block = a.plain_flow = false; + } + } + // Document markers, and the YAML 1.1 merge key "<<". + if ((first == '-' || first == '.') && n >= 3 && s[1] == first && + s[2] == first) { + a.plain_block = a.plain_flow = false; + } + if (n == 2 && first == '<' && s[1] == '<') { + a.plain_block = a.plain_flow = false; + } + const auto* p = reinterpret_cast(s.data()); + // Every byte is ORed into `seen` (as part of a word or on its own), to + // tell whether the string is ASCII. + uint64_t seen = 0; + for (size_t i = 0; i < n; ++i) { + // Skip 8 bytes at a time while none can be special. + while (kSkip && n - i >= 8) { + if constexpr (kCopy) memcpy(copy + i, s.data() + i, 8); + const uint64_t w = LoadWord(s.data() + i); + seen |= w; + const uint64_t m = SpecialMask(w); + if (m) { + i += static_cast(FirstByte(m)); + break; + } + i += 8; + } + if (kSkip && n - i < 8 && n >= 4) { + // Fewer than 8 bytes left: if no byte of a word covering them (the + // last 8 bytes, or for a short string two overlapping halves) may be + // special, there is nothing more to find. + uint64_t w; + if (n >= 8) { + w = LoadWord(s.data() + n - 8); + if constexpr (kCopy) memcpy(copy + n - 8, s.data() + n - 8, 8); + } else { + uint32_t lo, hi; + memcpy(&lo, s.data(), 4); + memcpy(&hi, s.data() + n - 4, 4); + if constexpr (kCopy) { + memcpy(copy, &lo, 4); + memcpy(copy + n - 4, &hi, 4); + } + w = uint64_t{hi} << 32 | lo; + } + seen |= w; + if (SpecialMask(w) == 0) break; + } + // Every byte is copied either as part of a word above, or here. + while (i < n && !kSpecial.v[p[i]]) { + if constexpr (kCopy) copy[i] = s[i]; + seen |= p[i]; + ++i; + } + if (i == n) break; + const uint8_t c = p[i]; + if constexpr (kCopy) copy[i] = s[i]; + seen |= c; + if (c < 0x80) { + if (c == '\n') { + a.newline = true; + a.plain_block = a.plain_flow = false; + } else if (c < 0x20 || c == 0x7F) { + a.escape = true; + a.plain_block = a.plain_flow = false; + } else if (c == ':') { + const char next = i + 1 < n ? s[i + 1] : '\0'; + if (next == ' ' || next == '\t') { + a.plain_block = a.plain_flow = false; + } else if (IsFlowIndicator(next)) { + a.plain_flow = false; + } + } else if (c == '#') { + if (i > 0 && IsWhite(s[i - 1])) a.plain_block = a.plain_flow = false; + } else { // a flow indicator + a.plain_flow = false; + } + continue; + } + const uint8_t c1 = i + 1 < n ? p[i + 1] : 0; + const uint8_t c2 = i + 2 < n ? p[i + 2] : 0; + // C1 controls (including NEL), LS/PS (line breaks in YAML 1.1), BOM and + // the noncharacters U+FFFE/U+FFFF. + if ((c == 0xC2 && c1 <= 0x9F) || + (c == 0xE2 && c1 == 0x80 && (c2 == 0xA8 || c2 == 0xA9)) || + (c == 0xEF && ((c1 == 0xBB && c2 == 0xBF) || + (c1 == 0xBF && (c2 == 0xBE || c2 == 0xBF))))) { + a.escape = true; + a.plain_block = a.plain_flow = false; + } + } + a.non_ascii = (seen & kHighs) != 0; + return a; +} + +// True if a YAML 1.1 parser would resolve `s` to something other than a +// string (booleans like yes/on, and number- or date-like text). Errs on the +// side of quoting. +inline bool IsYaml11Ambiguous(std::string_view s) { + if (s.empty()) return false; + // YAML 1.1 booleans: y, yes, n, no, on, off in lower, title and upper case. + if (s.size() <= 3) { + const auto is = [&](std::string_view w) { + return s == w; + }; + switch (s[0]) { + case 'y': + case 'Y': + if (s.size() == 1 || is("yes") || is("Yes") || is("YES")) return true; + break; + case 'n': + case 'N': + if (s.size() == 1 || is("no") || is("No") || is("NO")) return true; + break; + case 'o': + case 'O': + if (is("on") || is("On") || is("ON") || is("off") || is("Off") || + is("OFF")) { + return true; + } + break; + default: + break; + } + } + const auto digit = [](char c) { return c >= '0' && c <= '9'; }; + const char c0 = s[0]; + if (!(digit(c0) || + ((c0 == '-' || c0 == '+' || c0 == '.') && s.size() > 1 && + (digit(s[1]) || s[1] == '.')))) { + return false; + } + // Timestamps may contain spaces ("2001-12-14 21:59:43.10 -5"). + if (s.size() >= 5 && digit(s[0]) && digit(s[1]) && digit(s[2]) && + digit(s[3]) && s[4] == '-') { + return true; + } + for (char c : s) { + if (!(Has(c, kWordChar) || c == '_' || c == '.' || c == ':' || + c == '+')) { + return false; + } + } + return true; +} + +// Remembers recently written short keys that were written plain, so that a +// key repeated in many mappings (the property names of many objects of the +// same shape) is examined only once. Entries are found by a hash and matched +// by length and content, so the result never depends on where the caller's +// string lives. `context` is a bit for what was checked (block or flow +// mapping, string or parser scalar); the options do not change during an +// emitter's lifetime. +class KeyCache { + public: + static constexpr size_t kMaxKey = 32; + + // True if `key` was remembered for `context`. Otherwise, Remember() may + // store it next. + IGNAME_INLINE bool Find(std::string_view key, uint8_t context) { + pending_ = nullptr; + const size_t n = key.size(); + if (n == 0 || n > kMaxKey) return false; + if (skip_ > 0) { + --skip_; + return false; + } + if (++window_ == kWindow) { + // Mostly misses (keys that do not repeat): stop looking for a while. + if (hits_ < kWindow / 8) skip_ = kBackOff; + window_ = hits_ = 0; + } + if (!entries_) entries_.reset(new Entry[kEntries]()); + Entry& e = entries_[Hash(key)]; + if (e.len == n && (e.contexts & context) && Equal(e.text, key.data(), n)) { + ++hits_; + return true; + } + pending_ = &e; + return false; + } + + // Remembers the key just looked up with Find() for `context`. + void Remember(std::string_view key, uint8_t context) { + Entry* e = pending_; + if (e == nullptr) return; + pending_ = nullptr; + const size_t n = key.size(); + if (e->len != n || !Equal(e->text, key.data(), n)) { + e->len = static_cast(n); + e->contexts = 0; + Copy(e->text, key.data(), n); + } + e->contexts |= context; + } + + private: + static constexpr size_t kEntries = 256; + static constexpr uint32_t kWindow = 256; + static constexpr uint32_t kBackOff = 8192; // lookups skipped + + struct Entry { + uint8_t len; + uint8_t contexts; + char text[kMaxKey]; + }; + + static uint64_t Load8(const char* p) { + uint64_t v; + memcpy(&v, p, 8); + return v; + } + static uint64_t Load4(const char* p) { + uint32_t v; + memcpy(&v, p, 4); + return v; + } + static void Store8(char* p, uint64_t v) { memcpy(p, &v, 8); } + static void Store4(char* p, uint64_t v) { + const auto w = static_cast(v); + memcpy(p, &w, 4); + } + + // 1 <= n <= kMaxKey for the functions below. They use overlapping loads + // within the n bytes. + IGNAME_INLINE static size_t Hash(std::string_view s) { + const char* p = s.data(); + const size_t n = s.size(); + uint64_t h; + if (n >= 8) { + h = Load8(p) * 0x9E3779B97F4A7C15ULL ^ + (Load8(p + n - 8) + n) * 0xC2B2AE3D27D4EB4FULL; + } else if (n >= 4) { + h = (Load4(p) << 32 | Load4(p + n - 4)) * 0x9E3779B97F4A7C15ULL ^ n; + } else { + h = (uint64_t{static_cast(p[0])} << 16 | + uint64_t{static_cast(p[n / 2])} << 8 | + uint64_t{static_cast(p[n - 1])} | n << 24) * + 0x9E3779B97F4A7C15ULL; + } + return static_cast(h >> 56); // kEntries = 256 + } + IGNAME_INLINE static bool Equal(const char* a, const char* b, size_t n) { + if (n >= 16) { + return ((Load8(a) ^ Load8(b)) | (Load8(a + 8) ^ Load8(b + 8)) | + (Load8(a + n - 16) ^ Load8(b + n - 16)) | + (Load8(a + n - 8) ^ Load8(b + n - 8))) == 0; + } + if (n >= 8) { + return ((Load8(a) ^ Load8(b)) | (Load8(a + n - 8) ^ Load8(b + n - 8))) == + 0; + } + if (n >= 4) { + return ((Load4(a) ^ Load4(b)) | (Load4(a + n - 4) ^ Load4(b + n - 4))) == + 0; + } + return a[0] == b[0] && a[n / 2] == b[n / 2] && a[n - 1] == b[n - 1]; + } + static void Copy(char* d, const char* s, size_t n) { + if (n >= 16) { + const uint64_t a = Load8(s), b = Load8(s + 8), c = Load8(s + n - 16), + e = Load8(s + n - 8); + Store8(d, a); + Store8(d + 8, b); + Store8(d + n - 16, c); + Store8(d + n - 8, e); + } else if (n >= 8) { + const uint64_t a = Load8(s), b = Load8(s + n - 8); + Store8(d, a); + Store8(d + n - 8, b); + } else if (n >= 4) { + const uint64_t a = Load4(s), b = Load4(s + n - 4); + Store4(d, a); + Store4(d + n - 4, b); + } else { + d[0] = s[0]; + d[n / 2] = s[n / 2]; + d[n - 1] = s[n - 1]; + } + } + + std::unique_ptr entries_; // allocated on first use + Entry* pending_ = nullptr; + uint32_t window_ = 0; // lookups in the current window + uint32_t hits_ = 0; // hits in the current window + uint32_t skip_ = 0; // lookups left to skip +}; + +inline void FormatDouble(double v, std::string* out) { + if (std::isnan(v)) { + out->append(".nan"); + return; + } + if (std::isinf(v)) { + out->append(v < 0 ? "-.inf" : ".inf"); + return; + } + char buf[64]; + size_t len = 0; +#if defined(__cpp_lib_to_chars) && __cpp_lib_to_chars >= 201611L && \ + !defined(IGNAME_NO_FROM_CHARS) + auto r = std::to_chars(buf, buf + sizeof(buf), v); // shortest round trip + len = static_cast(r.ptr - buf); +#else + // Shortest of %.15g..%.17g that reads back as the same value. + for (int precision = 15; precision <= 17; ++precision) { + len = static_cast( + snprintf(buf, sizeof(buf), "%.*g", precision, v)); + for (size_t i = 0; i < len; ++i) { + if (buf[i] == ',') buf[i] = '.'; // locales with a decimal comma + } + double back; + if (ParseDouble(std::string_view(buf, len), &back) && back == v) break; + } +#endif + out->append(buf, len); + // Integral values need a fraction to read back as floats. + bool integral = true; + for (size_t i = 0; i < len; ++i) { + if (!(buf[i] == '-' || (buf[i] >= '0' && buf[i] <= '9'))) { + integral = false; + break; + } + } + if (integral) out->append(".0"); +} + +} // namespace detail + +// A mapping key formatted once, for writing many times with Emitter::Key() +// (see Emitter::PrepareKey). Holds copies; independent of the input string. +class PreparedKey { + public: + PreparedKey() = default; + // The key's text, as given to PrepareKey(). + const std::string& text() const { return text_; } + + private: + template + friend class Emitter; + std::string text_; + std::string block_; // as written in a block mapping + std::string flow_; // as written in a flow mapping + uint8_t options_ = 0; // the options it was formatted with + bool valid_ = false; // valid UTF-8 + bool ascii_ = true; +}; + +template +class Emitter { + public: + explicit Emitter(Sink sink, const EmitOptions& options = {}) + : sink_(std::move(sink)), options_(options) { + if (options_.indent < 1) options_.indent = 1; + if (options_.indent > 9) options_.indent = 9; + } + // Appends to `out` (with the default StringSink). + template >> + explicit Emitter(std::string* out, const EmitOptions& options = {}) + : Emitter(StringSink(out), options) {} + + Emitter(const Emitter&) = delete; + Emitter& operator=(const Emitter&) = delete; + + // Documents. BeginDocument/EndDocument are optional for a single document: + // a node at the top level starts one implicitly, and another top-level + // node after it starts the next. + bool BeginDocument() { + if (!ok_) return false; + if (!stack_.empty()) { + if (stack_.size() != 1 || stack_[0].count == 0) { + return Error(EmitError::kInvalidState, "document is not complete"); + } + if (!EndDocument()) return false; + } + return StartDocument(true); + } + + bool EndDocument() { + if (!ok_) return false; + if (stack_.size() != 1) { + return Error(EmitError::kInvalidState, "no complete document to end"); + } + if (stack_[0].count == 0) { + return Error(EmitError::kInvalidState, "document has no content"); + } + if (options_.explicit_document_end) { + if (line_has_content_) Newline(0); + Text("..."); + } + stack_.pop_back(); + return ok_; + } + + bool BeginSequence(CollectionStyle style = CollectionStyle::kBlock, + const Properties& props = {}) { + return BeginCollection(false, style, props); + } + bool EndSequence() { return EndCollection(false); } + bool BeginMapping(CollectionStyle style = CollectionStyle::kBlock, + const Properties& props = {}) { + return BeginCollection(true, style, props); + } + bool EndMapping() { return EndCollection(true); } + + bool Null(const Properties& props = {}) { + return Scalar("null", Mode::kTrusted, props); + } + bool Bool(bool value, const Properties& props = {}) { + return Scalar(value ? "true" : "false", Mode::kTrusted, props); + } + bool Int(int64_t value, const Properties& props = {}) { + char buf[24]; + auto r = std::to_chars(buf, buf + sizeof(buf), value); + return Scalar(std::string_view(buf, r.ptr - buf), Mode::kTrusted, props); + } + bool Double(double value, const Properties& props = {}) { + number_.clear(); + detail::FormatDouble(value, &number_); + return Scalar(number_, Mode::kTrusted, props); + } + // A string. It reads back as a string under the core schema. + bool String(std::string_view value, const Properties& props = {}) { + return Scalar(value, Mode::kString, props); + } + // Formats a string for use as a mapping key, once. Key(k) then writes + // exactly what String(k.text()) would, without examining the string again. + // Meant for keys that repeat, such as the property names of many objects + // of the same shape. A prepared key may be used with any emitter; with one + // whose options affect keys differently, Key() falls back to String(). + PreparedKey PrepareKey(std::string_view text) const { + PreparedKey k; + k.text_.assign(text); + k.options_ = KeyOptions(); + const auto a = detail::AnalyzeString(text); + if (a.non_ascii && + detail::ValidateUtf8(text.data(), text.size()) != text.size()) { + return k; // Key() reports the error + } + k.valid_ = true; + k.ascii_ = !a.non_ascii; + Slot slot; + slot.key = true; + k.block_ = FormatKey(text, a, slot); + slot.flow = true; + k.flow_ = FormatKey(text, a, slot); + return k; + } + // Writes a prepared key: the same as String(k.text()). + bool Key(const PreparedKey& k) { + if (!ok_) return false; + if (!k.valid_ || k.options_ != KeyOptions() || stack_.empty() || + !IsKeyPosition(stack_.back())) { + return String(k.text_); + } + Frame& f = stack_.back(); + const std::string& text = + f.kind == Kind::kFlowMapping ? k.flow_ : k.block_; + KeyPrefix(f); + if (text.size() + 4 > kMaxImplicitKey) { + Indicator("?"); + f.explicit_key = true; + } + if (!k.ascii_) ascii_only_ = false; + Text(text); + return NodeDone(); + } + + // Text written as a plain scalar, for example the digits of an integer + // that does not fit in int64_t. Fails if the text cannot be plain. + bool RawScalar(std::string_view text, const Properties& props = {}) { + return Scalar(text, Mode::kRaw, props); + } + bool Alias(std::string_view anchor) { + if (!ok_ || !CheckAnchor(anchor)) return false; + Frame* f; + if (!Prepare(&f)) return false; + alias_text_.assign("*"); + alias_text_.append(anchor); + if (IsKeyPosition(*f)) { + if (!KeyPrefix(*f)) return false; + if (alias_text_.size() > kMaxImplicitKey) { + Indicator("?"); + f->explicit_key = true; + } else { + f->key_alias = true; + } + Text(alias_text_); + return NodeDone(); + } + Slot slot; + if (!PlaceValue(*f, &slot)) return false; + Text(alias_text_); + return NodeDone(); + } + + // Ends the stream: closes the current document and flushes the output. + // Returns false (see result()) if the stream is incomplete or an error + // occurred. + bool Finish() { + if (!ok_) return false; + if (!stack_.empty()) { + if (stack_.size() != 1 || stack_[0].count == 0) { + return Error(EmitError::kInvalidState, + "unclosed collection or empty document"); + } + if (!EndDocument()) return false; + } + if (line_has_content_) { + Put('\n'); + line_has_content_ = false; + } + FlushBuffer(); + return ok_; + } + + // Starts over as if newly constructed (same sink and options), keeping + // allocated memory and remembered keys for reuse. For emitting many small + // documents: setting up an emitter costs about as much as writing a short + // document. Output not yet written to the sink is discarded. + void Reset() { + result_ = EmitResult(); + ok_ = true; + stack_.clear(); + out_len_ = 0; + column_ = 0; + line_has_content_ = false; + pending_space_ = false; + ascii_only_ = true; + documents_ = 0; + } + + const EmitResult& result() const { return result_; } + // True if everything written so far is ASCII (useful for creating a + // one-byte string from the output). + bool ascii_only() const { return ascii_only_; } + + // --- Parser handler interface --------------------------------------------- + + bool OnStreamStart() { return ok_; } + bool OnStreamEnd() { return ok_; } + bool OnDocumentStart(bool) { return BeginDocument(); } + bool OnDocumentEnd(bool) { return EndDocument(); } + bool OnSequenceStart(CollectionStyle style, const NodeInfo& info) { + return BeginSequence(style, {info.anchor, info.tag}); + } + bool OnSequenceEnd() { return EndSequence(); } + bool OnMappingStart(CollectionStyle style, const NodeInfo& info) { + return BeginMapping(style, {info.anchor, info.tag}); + } + bool OnMappingEnd() { return EndMapping(); } + bool OnScalar(std::string_view value, ScalarStyle style, + const NodeInfo& info) { + const Properties props{info.anchor, info.tag}; + if (style != ScalarStyle::kPlain) return Scalar(value, Mode::kString, props); + if (!info.tag.empty()) return Scalar(value, Mode::kTagged, props); + if (value.empty()) return Scalar("null", Mode::kTrusted, props); + return Scalar(value, Mode::kPlainEvent, props); + } + bool OnAlias(std::string_view name, const Mark&) { return Alias(name); } + + private: + // Longest implicit key written, in bytes (the specification's limit is + // 1024 characters). + static constexpr size_t kMaxImplicitKey = 1024; + + enum class Kind : uint8_t { + kDocument, + kBlockSequence, + kBlockMapping, + kFlowSequence, + kFlowMapping + }; + + struct Frame { + Kind kind; + int indent = 0; // block: column of the entries or keys + size_t count = 0; // children written (mappings: keys + values) + bool inline_start = false; // block: the first entry continues the line + bool explicit_key = false; // mapping: the current key used "?" + bool key_alias = false; // mapping: the current key is an alias + bool explicit_begin = false; // document: started by BeginDocument + }; + + // Where a node is being written. + struct Slot { + bool flow = false; // inside a flow collection + bool key = false; // an implicit mapping key + bool compact = false; // a block collection may continue the line + bool implicit_value = false; // the value of an implicit key + bool root = false; + int n = -1; // indentation of the parent block node + }; + + enum class Mode : uint8_t { + kTrusted, // known-safe plain text (null, true, 12, 1.5) + kString, // a string: quote if it would read back as another type + kPlainEvent, // a plain scalar from the parser: stay plain if possible + kTagged, // a tagged scalar: the tag decides the type + kRaw, // must be written plain + }; + + // --- Output --------------------------------------------------------------- + // + // Output goes to a buffer that grows to kMaxBuffer and is then written to + // the sink, so that the many small writes are cheap and the sink sees + // large chunks. Writes larger than half the buffer go to the sink + // directly (after what is buffered). + + static constexpr size_t kMaxBuffer = 64 << 10; + + // Copies n bytes. Short copies (most scalars and indentation) use + // overlapping fixed-size moves instead of a call to memcpy. + static void Copy(char* d, const char* s, size_t n) { + if (n >= 16) { + memcpy(d, s, n); + } else if (n >= 8) { + uint64_t a, b; + memcpy(&a, s, 8); + memcpy(&b, s + n - 8, 8); + memcpy(d, &a, 8); + memcpy(d + n - 8, &b, 8); + } else if (n >= 4) { + uint32_t a, b; + memcpy(&a, s, 4); + memcpy(&b, s + n - 4, 4); + memcpy(d, &a, 4); + memcpy(d + n - 4, &b, 4); + } else if (n > 0) { + d[0] = s[0]; + d[n / 2] = s[n / 2]; + d[n - 1] = s[n - 1]; + } + } + + static constexpr char kSpaces[] = + " "; + static constexpr size_t kMaxSpaces = sizeof(kSpaces) - 1; // 64 + + // Returns space for n <= kMaxBuffer bytes at out_len_. + char* Room(size_t n) { + if (out_cap_ - out_len_ < n) MakeRoom(n); + return out_.get() + out_len_; + } + + void MakeRoom(size_t n) { + if (out_len_ + n > kMaxBuffer) FlushBuffer(); + if (out_cap_ - out_len_ >= n) return; + size_t cap = out_cap_ < 4096 ? 4096 : out_cap_ * 2; + while (cap < out_len_ + n) cap *= 2; + if (cap > kMaxBuffer) cap = kMaxBuffer; + std::unique_ptr grown(new char[cap]); + if (out_len_ > 0) memcpy(grown.get(), out_.get(), out_len_); + out_ = std::move(grown); + out_cap_ = cap; + } + + // Writes the buffer to the sink. After an error, output is discarded. + void FlushBuffer() { + if (out_len_ > 0 && ok_ && !sink_.Write(out_.get(), out_len_)) { + Error(EmitError::kSinkFailed, "sink write failed"); + } + out_len_ = 0; + } + + void Put(char c) { + *Room(1) = c; + ++out_len_; + } + + void PutRepeated(char c, size_t n) { + while (n > 0) { + const size_t k = n < kMaxBuffer ? n : kMaxBuffer; + memset(Room(k), c, k); + out_len_ += k; + n -= k; + } + } + + void PutBytes(const char* data, size_t n) { + if (n == 0) return; + if (n > kMaxBuffer / 2) { + FlushBuffer(); + if (ok_ && !sink_.Write(data, n)) { + Error(EmitError::kSinkFailed, "sink write failed"); + } + return; + } + memcpy(Room(n), data, n); + out_len_ += n; + } + + void Newline(int indent) { + const auto n = static_cast(indent); + char* d = Room(n + 1); + d[0] = '\n'; + if (n <= kMaxSpaces) { + Copy(d + 1, kSpaces, n); + } else { + memset(d + 1, ' ', n); + } + out_len_ += n + 1; + column_ = indent; + line_has_content_ = false; + pending_space_ = false; + } + + // Moves to a fresh line at `indent`, unless the current line is empty. + void LineFor(int indent) { + if (line_has_content_) { + Newline(indent); + } else if (column_ < indent) { + PutRepeated(' ', static_cast(indent - column_)); + column_ = indent; + } + } + + void Text(std::string_view s) { + const size_t n = s.size(); + const size_t space = pending_space_ ? 1 : 0; + if (out_cap_ - out_len_ >= n + space && n > 0) { // the common case + char* d = out_.get() + out_len_; + if (space) *d++ = ' '; + Copy(d, s.data(), n); + out_len_ += n + space; + } else { + if (space) Put(' '); + PutBytes(s.data(), n); + } + column_ += static_cast(n + space); + pending_space_ = false; + line_has_content_ = true; + } + + void Indicator(std::string_view s) { + Text(s); + pending_space_ = true; + } + + // Text(), for a single character. + void Char(char c) { + const int k = pending_space_ ? 2 : 1; + char* d = Room(2); + d[0] = ' '; + d[k - 1] = c; + out_len_ += static_cast(k); + column_ += k; + pending_space_ = false; + line_has_content_ = true; + } + + void IndicatorChar(char c) { + Char(c); + pending_space_ = true; + } + + bool Error(EmitError error, const char* message) { + if (ok_) { + ok_ = false; + result_.error = error; + result_.message = message; + } + return false; + } + + // --- Structure ------------------------------------------------------------ + + bool StartDocument(bool explicit_begin) { + if (documents_ > 0 || options_.explicit_document_start) { + if (line_has_content_) Newline(0); + Indicator("---"); + } + ++documents_; + Frame f; + f.kind = Kind::kDocument; + f.explicit_begin = explicit_begin; + stack_.push_back(f); + return true; + } + + // Checks that a node may be written and returns its parent frame. + bool Prepare(Frame** parent) { + if (stack_.size() > 1) { // inside a collection: the common case + *parent = &stack_.back(); + return true; + } + if (stack_.empty()) { + if (!StartDocument(false)) return false; + } else if (stack_.size() == 1 && stack_[0].count > 0) { + if (stack_[0].explicit_begin) { + return Error(EmitError::kInvalidState, + "the document already has a root node"); + } + if (!EndDocument() || !StartDocument(false)) return false; + } + *parent = &stack_.back(); + return true; + } + + static bool IsKeyPosition(const Frame& f) { + return (f.kind == Kind::kBlockMapping || f.kind == Kind::kFlowMapping) && + f.count % 2 == 0; + } + + // Writes what precedes a mapping key. + bool KeyPrefix(Frame& f) { + if (f.kind == Kind::kFlowMapping) { + if (f.count > 0) IndicatorChar(','); + } else if (f.count > 0 || !f.inline_start) { + LineFor(f.indent); + } + f.key_alias = false; + f.explicit_key = false; + return true; + } + + // Writes what precedes a node that is not a mapping key, and describes the + // position. + bool PlaceValue(Frame& f, Slot* slot) { + switch (f.kind) { + case Kind::kDocument: + slot->root = true; + slot->compact = !line_has_content_; + break; + case Kind::kBlockSequence: + if (f.count > 0 || !f.inline_start) LineFor(f.indent); + IndicatorChar('-'); + slot->n = f.indent; + slot->compact = true; + break; + case Kind::kBlockMapping: + slot->n = f.indent; + if (f.explicit_key) { + LineFor(f.indent); + Indicator(":"); + slot->compact = true; + } else { + if (f.key_alias) Text(" "); + IndicatorChar(':'); + slot->implicit_value = true; + } + break; + case Kind::kFlowSequence: + if (f.count > 0) IndicatorChar(','); + slot->flow = true; + break; + case Kind::kFlowMapping: + if (f.key_alias) Text(" "); + IndicatorChar(':'); + slot->flow = true; + break; + } + return true; + } + + // Updates the parent after a complete node. (KeyPrefix() resets the key + // flags before the next key.) + bool NodeDone() { + ++stack_.back().count; + return ok_; + } + + bool BeginCollection(bool mapping, CollectionStyle style, + const Properties& props) { + if (!ok_ || !CheckProperties(props)) return false; + if (stack_.size() > options_.max_depth) { + return Error(EmitError::kDepthExceeded, "maximum depth exceeded"); + } + Frame* parent; + if (!Prepare(&parent)) return false; + Slot slot; + if (IsKeyPosition(*parent)) { + // Collections as keys use the explicit "? key" form. + KeyPrefix(*parent); + Indicator("?"); + parent->explicit_key = true; + slot.n = parent->indent; + slot.compact = true; + slot.flow = parent->kind == Kind::kFlowMapping; + } else if (!PlaceValue(*parent, &slot)) { + return false; + } + const bool has_props = WriteProperties(props); + Frame f; + if (slot.flow || style == CollectionStyle::kFlow) { + f.kind = mapping ? Kind::kFlowMapping : Kind::kFlowSequence; + Text(mapping ? "{" : "["); + } else { + f.kind = mapping ? Kind::kBlockMapping : Kind::kBlockSequence; + if (slot.root) { + f.indent = 0; + f.inline_start = !line_has_content_; + } else if (slot.compact && !has_props) { + f.indent = column_ + (pending_space_ ? 1 : 0); + f.inline_start = true; + } else if (slot.implicit_value && !mapping && + !options_.indent_sequences) { + f.indent = slot.n; + } else { + f.indent = slot.n + options_.indent; + } + } + stack_.push_back(f); + return true; + } + + bool EndCollection(bool mapping) { + if (!ok_) return false; + if (stack_.size() < 2) { + return Error(EmitError::kInvalidState, "no collection to end"); + } + Frame& f = stack_.back(); + const bool is_mapping = + f.kind == Kind::kBlockMapping || f.kind == Kind::kFlowMapping; + if (is_mapping != mapping) { + return Error(EmitError::kInvalidState, + mapping ? "EndMapping inside a sequence" + : "EndSequence inside a mapping"); + } + if (is_mapping && f.count % 2 != 0) { + return Error(EmitError::kInvalidState, "mapping key without a value"); + } + if (f.kind == Kind::kFlowSequence) { + Text("]"); + } else if (f.kind == Kind::kFlowMapping) { + Text("}"); + } else if (f.count == 0) { + // Block collections cannot be empty. + Text(mapping ? "{}" : "[]"); + } + stack_.pop_back(); + return NodeDone(); + } + + // --- Properties ----------------------------------------------------------- + + bool CheckUtf8(std::string_view s) { + for (char c : s) { + if (static_cast(c) >= 0x80) { + if (detail::ValidateUtf8(s.data(), s.size()) != s.size()) { + return Error(EmitError::kInvalidUtf8, "invalid UTF-8"); + } + ascii_only_ = false; + break; + } + } + return true; + } + + bool CheckAnchor(std::string_view anchor) { + if (anchor.empty()) { + return Error(EmitError::kInvalidArgument, "empty anchor"); + } + for (char c : anchor) { + if (detail::Has(c, detail::kAnchorStop) || + static_cast(c) < 0x20) { + return Error(EmitError::kInvalidArgument, + "invalid character in an anchor"); + } + } + return CheckUtf8(anchor); + } + + // Tags may hold any bytes (they are URIs, and the parser decodes %HH + // escapes); WriteProperties percent-encodes them as needed. + bool CheckProperties(const Properties& props) { + return props.anchor.empty() || CheckAnchor(props.anchor); + } + + // Appends `s`, percent-encoding bytes for which `allowed` is false. + template + void AppendEncoded(std::string_view s, Allowed allowed) { + static constexpr char kHex[] = "0123456789ABCDEF"; + for (char c : s) { + if (allowed(c)) { + tag_text_.push_back(c); + } else { + const auto b = static_cast(c); + tag_text_.push_back('%'); + tag_text_.push_back(kHex[b >> 4]); + tag_text_.push_back(kHex[b & 15]); + } + } + } + + // Writes the anchor and tag, if any. Returns true if anything was written. + bool WriteProperties(const Properties& props) { + if (props.anchor.empty() && props.tag.empty()) return false; // common + return WriteAnchorAndTag(props); + } + + bool WriteAnchorAndTag(const Properties& props) { + bool any = false; + if (!props.anchor.empty()) { + tag_text_.assign("&"); + tag_text_.append(props.anchor); + Indicator(tag_text_); + any = true; + } + if (!props.tag.empty()) { + const std::string_view tag = props.tag; + const auto tag_char = [](char c) { + return detail::IsTagChar(c) && c != '%'; + }; + tag_text_.clear(); + if (tag == "!") { + tag_text_.assign("!"); + } else if (tag.size() > kCoreTagPrefix.size() && + tag.substr(0, kCoreTagPrefix.size()) == kCoreTagPrefix) { + tag_text_.assign("!!"); + AppendEncoded(tag.substr(kCoreTagPrefix.size()), tag_char); + } else if (tag.size() > 1 && tag[0] == '!') { + tag_text_.assign("!"); + AppendEncoded(tag.substr(1), tag_char); + } else { + tag_text_.assign("!<"); + AppendEncoded(tag, [](char c) { + return detail::Has(c, detail::kUriChar); + }); + tag_text_.push_back('>'); + } + Indicator(tag_text_); + any = true; + } + return any; + } + + // --- Scalars -------------------------------------------------------------- + + enum class Format : uint8_t { kPlain, kFormatted, kLiteral, kError }; + + bool Scalar(std::string_view value, Mode mode, const Properties& props) { + if (!ok_ || !CheckProperties(props)) return false; + // With a tag, the tag decides the type, not the style. + if (mode == Mode::kString && !props.tag.empty()) mode = Mode::kTagged; + Frame* f; + if (!Prepare(&f)) return false; + if (IsKeyPosition(*f)) return KeyScalar(*f, value, mode, props); + Slot slot; + PlaceValue(*f, &slot); + WriteProperties(props); + if (mode == Mode::kTrusted) { + Text(value); + return NodeDone(); + } + detail::StringAnalysis a; + const size_t n = value.size(); + if (n <= kMaxBuffer / 2) { + // Copy the value into the buffer while analyzing it, as if it were + // written plain; the copy is kept only if it may be. (Nothing is + // written after an error: see FlushBuffer().) + const size_t space = pending_space_ ? 1 : 0; + char* d = Room(n + space); + a = detail::AnalyzeString(value, d + space); + if (!CheckAnalyzed(value, a)) return false; + if (PlainAllowed(value, mode, a, slot)) { + if (space) d[0] = ' '; + out_len_ += n + space; + column_ += static_cast(n + space); + pending_space_ = false; + line_has_content_ = true; + return NodeDone(); + } + } else { + a = detail::AnalyzeString(value); + if (!CheckAnalyzed(value, a)) return false; + if (PlainAllowed(value, mode, a, slot)) { + Text(value); + return NodeDone(); + } + } + switch (FormatNonPlain(value, mode, a, slot)) { + case Format::kPlain: break; // not returned + case Format::kFormatted: Text(scratch_); break; + case Format::kLiteral: WriteLiteral(value, slot); break; + case Format::kError: return false; + } + return NodeDone(); + } + + // Checks that an analyzed string is valid UTF-8. + IGNAME_INLINE bool CheckAnalyzed(std::string_view value, + const detail::StringAnalysis& a) { + if (a.non_ascii) { + if (detail::ValidateUtf8(value.data(), value.size()) != value.size()) { + return Error(EmitError::kInvalidUtf8, "invalid UTF-8"); + } + ascii_only_ = false; + } + return true; + } + + // Analyzes a scalar and checks that it is valid UTF-8. + IGNAME_INLINE bool Analyze(std::string_view value, Mode mode, + detail::StringAnalysis* a) { + if (mode == Mode::kTrusted) return true; + *a = detail::AnalyzeString(value); + return CheckAnalyzed(value, *a); + } + + bool KeyScalar(Frame& f, std::string_view value, Mode mode, + const Properties& props) { + // Short keys without properties that were written plain are remembered, + // and written again without being examined (see detail::KeyCache). + uint8_t context = 0; + if ((mode == Mode::kString || mode == Mode::kPlainEvent) && + props.anchor.empty() && props.tag.empty()) { + context = static_cast( + (f.kind == Kind::kFlowMapping ? 2 : 1) + << (mode == Mode::kPlainEvent ? 2 : 0)); + if (key_cache_.Find(value, context)) { + KeyPrefix(f); + Text(value); + return NodeDone(); + } + } + detail::StringAnalysis a; + if (!Analyze(value, mode, &a)) return false; + Slot slot; + slot.key = true; + slot.flow = f.kind == Kind::kFlowMapping; + // Keys are formatted before anything is written, so that a long key can + // still get "?". + const Format format = FormatScalar(value, mode, a, slot); + if (format == Format::kError) return false; + KeyPrefix(f); + const size_t size = + format == Format::kPlain ? value.size() : scratch_.size(); + // Implicit keys are limited to 1024 characters (with properties, + // allowing for percent-encoding of the tag); longer keys use "?". + if (size + props.anchor.size() + 3 * props.tag.size() + 4 > + kMaxImplicitKey) { + Indicator("?"); + f.explicit_key = true; + } + WriteProperties(props); + if (format == Format::kPlain) { + if (context != 0 && !a.non_ascii) key_cache_.Remember(value, context); + Text(value); + } else { + Text(scratch_); + } + return NodeDone(); + } + + // The options that affect how a key is formatted. + uint8_t KeyOptions() const { + return static_cast((options_.escape_non_ascii ? 1 : 0) | + (options_.quote_yaml11 ? 2 : 0)); + } + + // A string formatted as Scalar() formats a key (without properties). + std::string FormatKey(std::string_view text, const detail::StringAnalysis& a, + const Slot& slot) const { + if (PlainAllowed(text, Mode::kString, a, slot)) return std::string(text); + std::string out; + const bool escape_all = options_.escape_non_ascii && a.non_ascii; + if (!a.newline && !a.escape && !escape_all) { + AppendSingleQuoted(text, &out); + } else { + AppendDoubleQuoted(text, &out); + } + return out; + } + + bool PlainAllowed(std::string_view value, Mode mode, + const detail::StringAnalysis& a, const Slot& slot) const { + if (mode == Mode::kTrusted) return true; + if (!(slot.flow ? a.plain_flow : a.plain_block)) return false; + if (options_.escape_non_ascii && a.non_ascii) return false; + if (mode == Mode::kString) { + if (detail::MayResolveToNonString(value[0]) && + ResolvePlainScalar(value).kind != ScalarKind::kString) { + return false; + } + if (options_.quote_yaml11 && detail::IsYaml11Ambiguous(value)) { + return false; + } + } + return true; + } + + // Chooses the style of a scalar. Quoted scalars are formatted into + // scratch_. + Format FormatScalar(std::string_view value, Mode mode, + const detail::StringAnalysis& a, const Slot& slot) { + if (PlainAllowed(value, mode, a, slot)) return Format::kPlain; + return FormatNonPlain(value, mode, a, slot); + } + + // FormatScalar() for a scalar that cannot be plain. + Format FormatNonPlain(std::string_view value, Mode mode, + const detail::StringAnalysis& a, const Slot& slot) { + if (mode == Mode::kRaw) { + Error(EmitError::kInvalidArgument, "text cannot be a plain scalar"); + return Format::kError; + } + scratch_.clear(); + const bool escape_all = options_.escape_non_ascii && a.non_ascii; + if (!a.newline && !a.escape && !escape_all) { + AppendSingleQuoted(value, &scratch_); + return Format::kFormatted; + } + if (a.newline && !a.escape && !escape_all && !slot.flow && !slot.key && + LiteralOk(value, slot)) { + return Format::kLiteral; + } + AppendDoubleQuoted(value, &scratch_); + return Format::kFormatted; + } + + static void AppendSingleQuoted(std::string_view value, std::string* out) { + out->push_back('\''); + for (size_t start = 0;;) { + const size_t quote = value.find('\'', start); + if (quote == std::string_view::npos) { + out->append(value.substr(start)); + break; + } + out->append(value.substr(start, quote + 1 - start)); + out->push_back('\''); + start = quote + 1; + } + out->push_back('\''); + } + + // A literal block needs an indentation indicator when its first non-empty + // line starts with a space; at the document level that indicator is read + // differently by different parsers, so use double quotes there. + static bool NeedsIndentIndicator(std::string_view value) { + size_t i = 0; + while (i < value.size() && value[i] == '\n') ++i; + return i < value.size() && value[i] == ' '; + } + + bool LiteralOk(std::string_view value, const Slot& slot) const { + return !(slot.root && NeedsIndentIndicator(value)); + } + + void WriteLiteral(std::string_view value, const Slot& slot) { + size_t trailing = 0; + while (trailing < value.size() && + value[value.size() - 1 - trailing] == '\n') { + ++trailing; + } + const std::string_view body = value.substr(0, value.size() - trailing); + std::string header = "|"; + if (NeedsIndentIndicator(body)) { + header.push_back(static_cast('0' + options_.indent)); + } + if (body.empty() || trailing > 1) { + header.push_back('+'); + } else if (trailing == 0) { + header.push_back('-'); + } + Text(header); + const int indent = (slot.n < 0 ? 0 : slot.n) + options_.indent; + size_t start = 0; + while (start < body.size()) { + size_t end = body.find('\n', start); + if (end == std::string_view::npos) end = body.size(); + if (end > start) { + Newline(indent); + PutBytes(body.data() + start, end - start); + } else { + Put('\n'); + } + start = end + 1; + } + line_has_content_ = true; + pending_space_ = false; + if (header.back() == '+') { + // Keep the trailing line breaks: the line break after the header (if + // there is no body) or after the last line, plus one per empty line. + PutRepeated('\n', body.empty() ? trailing + 1 : trailing); + line_has_content_ = false; + column_ = 0; + } + } + + void AppendDoubleQuoted(std::string_view value, std::string* out) const { + static constexpr char kHex[] = "0123456789ABCDEF"; + auto hex = [&](char prefix, uint32_t cp, int digits) { + out->push_back('\\'); + out->push_back(prefix); + for (int i = digits - 1; i >= 0; --i) { + out->push_back(kHex[(cp >> (i * 4)) & 15]); + } + }; + out->push_back('"'); + for (size_t i = 0; i < value.size();) { + const auto c = static_cast(value[i]); + if (c < 0x80) { + ++i; + switch (c) { + case '"': out->append("\\\""); continue; + case '\\': out->append("\\\\"); continue; + case '\0': out->append("\\0"); continue; + case '\a': out->append("\\a"); continue; + case '\b': out->append("\\b"); continue; + case '\t': out->append("\\t"); continue; + case '\n': out->append("\\n"); continue; + case '\v': out->append("\\v"); continue; + case '\f': out->append("\\f"); continue; + case '\r': out->append("\\r"); continue; + case 0x1B: out->append("\\e"); continue; + default: + if (c < 0x20 || c == 0x7F) { + hex('x', c, 2); + } else { + out->push_back(static_cast(c)); + } + continue; + } + } + // Decode one UTF-8 sequence (validated earlier). + const size_t len = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : 2; + uint32_t cp = c & (len == 2 ? 0x1F : len == 3 ? 0x0F : 0x07); + for (size_t k = 1; k < len; ++k) { + cp = cp << 6 | (static_cast(value[i + k]) & 0x3F); + } + if (cp == 0x85) { + out->append("\\N"); + } else if (cp == 0x2028) { + out->append("\\L"); + } else if (cp == 0x2029) { + out->append("\\P"); + } else if (cp < 0xA0) { + hex('x', cp, 2); + } else if (cp == 0xFEFF || cp == 0xFFFE || cp == 0xFFFF || + options_.escape_non_ascii) { + if (cp > 0xFFFF) { + hex('U', cp, 8); + } else { + hex('u', cp, 4); + } + } else { + out->append(value.substr(i, len)); + } + i += len; + } + out->push_back('"'); + } + + Sink sink_; + EmitOptions options_; + EmitResult result_; + bool ok_ = true; + std::vector stack_; + std::unique_ptr out_; // output not yet written to the sink + size_t out_len_ = 0; + size_t out_cap_ = 0; + detail::KeyCache key_cache_; + std::string scratch_; // the formatted scalar being written + std::string number_; // the formatted double being written + std::string tag_text_; // the formatted property being written + std::string alias_text_; // the formatted alias being written + int column_ = 0; + bool line_has_content_ = false; + bool pending_space_ = false; // a separating space is owed before content + bool ascii_only_ = true; + size_t documents_ = 0; +}; + +} // namespace igname + +#endif // IGNAME_EMITTER_HPP_ diff --git a/deps/igname/include/igname/igname.hpp b/deps/igname/include/igname/igname.hpp new file mode 100644 index 00000000000..deaef90b596 --- /dev/null +++ b/deps/igname/include/igname/igname.hpp @@ -0,0 +1,2273 @@ +// igname -- a small, fast, exception-free YAML 1.2 event parser. +// +// SPDX-License-Identifier: MIT +// +// igname parses a YAML 1.2 character stream and reports it as a sequence of +// events to a handler supplied as a template parameter. It does not build a +// document tree: the handler (for example a binding that creates JavaScript +// values) builds whatever representation it needs directly, so no intermediate +// copy of the document exists. +// +// struct MyHandler : igname::BaseHandler { +// bool OnScalar(std::string_view value, igname::ScalarStyle style, +// const igname::NodeInfo& info) { ...; return true; } +// ... +// }; +// MyHandler handler; +// igname::Result result = igname::Parse(input, handler); +// if (!result) { /* result.message, result.line, result.column */ } +// +// Design notes: +// * No exceptions and no RTTI. Errors are reported through Result. +// * Every handler method returns bool; returning false aborts parsing with +// Error::kAborted (useful when the embedder has a pending exception). +// * String views passed to the handler are only valid for the duration of +// the call. Scalars are slices of the input whenever possible (plain +// single-line scalars, quoted scalars without escapes or line folding); +// otherwise they point into a scratch buffer that is reused. +// * The input may be UTF-8 (with or without BOM), UTF-16 or UTF-32 (detected +// per YAML 1.2 section 5.2). Line breaks are normalized to '\n'. +// * Optional dependencies, enabled by defining before including this header: +// IGNAME_USE_SIMDUTF use simdutf for UTF-8 validation ("simdutf.h") +// IGNAME_USE_FAST_FLOAT use fast_float for float parsing +// ("fast_float/fast_float.h") +// Without them, portable fallbacks are used (std::from_chars for floats +// where the standard library provides it, strtod otherwise; define +// IGNAME_NO_FROM_CHARS to force strtod, and snprintf in the emitter). + +#ifndef IGNAME_IGNAME_HPP_ +#define IGNAME_IGNAME_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(IGNAME_USE_SIMDUTF) +#include "simdutf.h" +#endif + +#if defined(IGNAME_USE_FAST_FLOAT) +#include "fast_float/fast_float.h" +#else +#include +#endif + +#define IGNAME_VERSION_MAJOR 0 +#define IGNAME_VERSION_MINOR 1 +#define IGNAME_VERSION_PATCH 0 + +namespace igname { + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +enum class ScalarStyle : uint8_t { + kPlain, + kSingleQuoted, + kDoubleQuoted, + kLiteral, + kFolded, +}; + +enum class CollectionStyle : uint8_t { + kBlock, + kFlow, +}; + +// A position in the input. Both fields are 1-based; `column` counts bytes. +struct Mark { + uint32_t line = 0; + uint32_t column = 0; +}; + +// Node properties and position. `tag` is the fully resolved tag (for example +// "tag:yaml.org,2002:str"), "!" for the non-specific tag, or empty when the +// node has no tag. `anchor` is empty when the node has no anchor. +struct NodeInfo { + std::string_view anchor; + std::string_view tag; + Mark mark; +}; + +enum class Error : uint8_t { + kNone = 0, + kInvalidEncoding, // malformed UTF-8/16/32 + kInvalidCharacter, // a character that may not appear in a YAML stream + kSyntax, // the input is not valid YAML + kDepthExceeded, // nesting exceeded ParseOptions::max_depth + kAborted, // a handler method returned false +}; + +struct Result { + Error error = Error::kNone; + const char* message = ""; // static string, never null + uint32_t line = 0; // 1-based line of the error + uint32_t column = 0; // 1-based column of the error, in code points + explicit operator bool() const { return error == Error::kNone; } +}; + +struct ParseOptions { + // Maximum nesting depth of collections. Bounds the parser's recursion. + uint32_t max_depth = 512; +}; + +// A handler that accepts every event. Derive from it and shadow the methods +// you need; dispatch is static, so there is no virtual call overhead. +struct BaseHandler { + bool OnStreamStart() { return true; } + bool OnStreamEnd() { return true; } + bool OnDocumentStart(bool /*explicit_start*/) { return true; } + bool OnDocumentEnd(bool /*explicit_end*/) { return true; } + bool OnSequenceStart(CollectionStyle, const NodeInfo&) { return true; } + bool OnSequenceEnd() { return true; } + bool OnMappingStart(CollectionStyle, const NodeInfo&) { return true; } + bool OnMappingEnd() { return true; } + bool OnScalar(std::string_view, ScalarStyle, const NodeInfo&) { return true; } + bool OnAlias(std::string_view /*name*/, const Mark&) { return true; } +}; + +template +Result Parse(std::string_view input, Handler& handler, + const ParseOptions& options = {}); + +// --- Core schema (YAML 1.2.2 section 10.3) --------------------------------- + +enum class ScalarKind : uint8_t { kNull, kBool, kInt, kFloat, kString }; + +struct ScalarValue { + ScalarKind kind = ScalarKind::kString; + bool boolean = false; + // kInt: true when the integer does not fit in int64_t. `number` then holds + // the nearest double, and the source text can be used for a big integer. + bool overflow = false; + int64_t integer = 0; + double number = 0; // kFloat, or the approximation of an overflowing kInt +}; + +enum class ResolveStatus : uint8_t { + kOk, // `out` holds the value + kInvalid, // a core schema tag whose value does not match, e.g. !!int x + kUnknownTag, // a tag outside the core schema; `out` is a kString +}; + +// Resolves a scalar according to the core schema. Untagged plain scalars are +// matched against the null/bool/int/float patterns; other untagged scalars +// and scalars tagged "!" are strings. The core schema tags +// (tag:yaml.org,2002:{null,bool,int,float,str}) force the type. +ResolveStatus ResolveScalar(std::string_view value, ScalarStyle style, + std::string_view tag, ScalarValue* out); + +// Resolves an untagged plain scalar. Never fails. +ScalarValue ResolvePlainScalar(std::string_view value); + +inline constexpr std::string_view kCoreTagPrefix = "tag:yaml.org,2002:"; + +// --------------------------------------------------------------------------- +// Implementation +// --------------------------------------------------------------------------- + +namespace detail { + +enum : uint16_t { + kWhite = 1 << 0, // space, tab + kFlowIndicator = 1 << 1, // , [ ] { } + kIndicator = 1 << 2, // c-indicator + kWordChar = 1 << 3, // ns-word-char: [0-9A-Za-z-] + kUriChar = 1 << 4, // ns-uri-char (without the %HH form) + kPlainStopBlock = 1 << 5, // characters that interrupt a plain scalar scan + kPlainStopFlow = 1 << 6, + kAnchorStop = 1 << 7, // characters that end an anchor or alias name + kFlowSkipStop = 1 << 8, // characters of interest when skipping flow + kQuoteStop = 1 << 9, // ' and \n + kDoubleQuoteStop = 1 << 10, // " \\ and \n + kNonStringStart = 1 << 11, // may start a non-string plain scalar +}; + +struct CharTable { + uint16_t bits[256]; + constexpr CharTable() : bits{} { + bits[static_cast(' ')] |= kWhite | kAnchorStop; + bits[static_cast('\t')] |= kWhite | kAnchorStop; + bits[static_cast('\n')] |= + kPlainStopBlock | kPlainStopFlow | kAnchorStop; + for (char c : std::string_view(",[]{}")) { + bits[static_cast(c)] |= kFlowIndicator | kPlainStopFlow | + kAnchorStop; + } + for (char c : std::string_view("-?:,[]{}#&*!|>'\"%@`")) { + bits[static_cast(c)] |= kIndicator; + } + for (int c = '0'; c <= '9'; ++c) bits[c] |= kWordChar | kUriChar; + for (int c = 'a'; c <= 'z'; ++c) bits[c] |= kWordChar | kUriChar; + for (int c = 'A'; c <= 'Z'; ++c) bits[c] |= kWordChar | kUriChar; + bits[static_cast('-')] |= kWordChar | kUriChar; + for (char c : std::string_view("#;/?:@&=+$,_.!~*'()[]")) { + bits[static_cast(c)] |= kUriChar; + } + for (char c : std::string_view(":#")) { + bits[static_cast(c)] |= kPlainStopBlock | kPlainStopFlow; + } + for (char c : std::string_view("[]{}\"'#\n")) { + bits[static_cast(c)] |= kFlowSkipStop; + } + // The first characters ResolvePlainScalar() switches on. + for (char c : std::string_view("~nNtTfF-+.0123456789")) { + bits[static_cast(c)] |= kNonStringStart; + } + for (char c : std::string_view("'\n")) { + bits[static_cast(c)] |= kQuoteStop; + } + for (char c : std::string_view("\"\\\n")) { + bits[static_cast(c)] |= kDoubleQuoteStop; + } + } +}; + +inline constexpr CharTable kChars{}; + +inline bool Has(char c, uint16_t mask) { + return (kChars.bits[static_cast(c)] & mask) != 0; +} +inline bool IsWhite(char c) { return c == ' ' || c == '\t'; } +inline bool IsFlowIndicator(char c) { return Has(c, kFlowIndicator); } +inline bool IsTagChar(char c) { + // ns-tag-char: ns-uri-char minus '!' and the flow indicators. '%' escapes + // are validated separately. + return (Has(c, kUriChar) && c != '!' && !IsFlowIndicator(c)) || c == '%'; +} + +// --- SWAR (8 bytes at a time, portable) ------------------------------------ + +inline constexpr uint64_t kOnes = 0x0101010101010101ULL; +inline constexpr uint64_t kHighs = 0x8080808080808080ULL; + +// Loads 8 bytes so that the byte at the lowest address is the least +// significant, on any platform. +inline uint64_t LoadWord(const char* p) { + uint64_t w; + memcpy(&w, p, 8); + if constexpr (std::endian::native == std::endian::big) { +#if defined(_MSC_VER) + w = _byteswap_uint64(w); +#else + w = __builtin_bswap64(w); +#endif + } + return w; +} + +// High bit set in (at least) the first byte of `w` equal to `c`; the lowest +// flagged byte is always exact. +inline uint64_t MatchByte(uint64_t w, char c) { + const uint64_t x = w ^ (kOnes * static_cast(c)); + return (x - kOnes) & ~x & kHighs; +} + +inline int FirstByte(uint64_t mask) { return std::countr_zero(mask) >> 3; } + +// Returns the first position in [q, end) holding a, b or c, or end. +inline const char* FindAny3(const char* q, const char* end, char a, char b, + char c) { + while (end - q >= 8) { + const uint64_t w = LoadWord(q); + const uint64_t m = MatchByte(w, a) | MatchByte(w, b) | MatchByte(w, c); + if (m) return q + FirstByte(m); + q += 8; + } + while (q < end && *q != a && *q != b && *q != c) ++q; + return q; +} + +// Returns the first position in [q, end) that is not a space. +inline const char* SkipSpaces(const char* q, const char* end) { + while (end - q >= 8) { + const uint64_t x = LoadWord(q) ^ (kOnes * ' '); + if (x) return q + FirstByte(x); + q += 8; + } + while (q < end && *q == ' ') ++q; + return q; +} + +inline int HexValue(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +inline void AppendUtf8(std::string* out, uint32_t cp) { + if (cp < 0x80) { + out->push_back(static_cast(cp)); + } else if (cp < 0x800) { + out->push_back(static_cast(0xC0 | (cp >> 6))); + out->push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp < 0x10000) { + out->push_back(static_cast(0xE0 | (cp >> 12))); + out->push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + out->push_back(static_cast(0x80 | (cp & 0x3F))); + } else { + out->push_back(static_cast(0xF0 | (cp >> 18))); + out->push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); + out->push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + out->push_back(static_cast(0x80 | (cp & 0x3F))); + } +} + +// Returns the offset of the first invalid byte, or `size` if `data` is valid +// UTF-8 (no overlong forms, no surrogates, nothing above U+10FFFF). +inline size_t ValidateUtf8(const char* data, size_t size) { +#if defined(IGNAME_USE_SIMDUTF) + if (simdutf::validate_utf8(data, size)) return size; + return simdutf::validate_utf8_with_errors(data, size).count; +#else + const auto* s = reinterpret_cast(data); + size_t i = 0; + while (i < size) { + // ASCII fast path, 8 bytes at a time. + while (i + 8 <= size) { + uint64_t word; + memcpy(&word, s + i, 8); + if (word & 0x8080808080808080ULL) break; + i += 8; + } + if (i >= size) break; + uint8_t c = s[i]; + if (c < 0x80) { + ++i; + continue; + } + size_t n; + uint32_t cp; + if ((c & 0xE0) == 0xC0) { + n = 2; + cp = c & 0x1F; + } else if ((c & 0xF0) == 0xE0) { + n = 3; + cp = c & 0x0F; + } else if ((c & 0xF8) == 0xF0) { + n = 4; + cp = c & 0x07; + } else { + return i; + } + if (i + n > size) return i; + for (size_t k = 1; k < n; ++k) { + if ((s[i + k] & 0xC0) != 0x80) return i; + cp = (cp << 6) | (s[i + k] & 0x3F); + } + if ((n == 2 && cp < 0x80) || (n == 3 && cp < 0x800) || + (n == 4 && (cp < 0x10000 || cp > 0x10FFFF)) || + (cp >= 0xD800 && cp <= 0xDFFF)) { + return i; + } + i += n; + } + return size; +#endif +} + +// Computes a 1-based line and code point column for an offset. +inline void LocateOffset(std::string_view text, size_t offset, Result* r) { + uint32_t line = 1; + size_t line_start = 0; + for (size_t i = 0; i < offset && i < text.size(); ++i) { + if (text[i] == '\n') { + ++line; + line_start = i + 1; + } + } + uint32_t column = 1; + for (size_t i = line_start; i < offset && i < text.size(); ++i) { + if ((static_cast(text[i]) & 0xC0) != 0x80) ++column; + } + r->line = line; + r->column = column; +} + +inline bool FailInput(Result* r, Error error, const char* message, + std::string_view text, size_t offset) { + r->error = error; + r->message = message; + LocateOffset(text, offset, r); + return false; +} + +// Transcodes UTF-16 or UTF-32 input to UTF-8. +inline bool Transcode(std::string_view in, int unit, bool big_endian, + std::string* out, Result* r) { + const auto* s = reinterpret_cast(in.data()); + const size_t n = in.size() / unit; + if (in.size() % unit != 0) { + return FailInput(r, Error::kInvalidEncoding, "truncated UTF-16/32 input", + {}, 0); + } + auto read = [&](size_t i) -> uint32_t { + const uint8_t* p = s + i * unit; + if (unit == 2) { + return big_endian ? (p[0] << 8 | p[1]) : (p[1] << 8 | p[0]); + } + return big_endian ? (uint32_t{p[0]} << 24 | p[1] << 16 | p[2] << 8 | p[3]) + : (uint32_t{p[3]} << 24 | p[2] << 16 | p[1] << 8 | p[0]); + }; + out->clear(); + out->reserve(in.size()); + for (size_t i = 0; i < n; ++i) { + uint32_t cp = read(i); + if (unit == 2 && cp >= 0xD800 && cp <= 0xDBFF && i + 1 < n) { + uint32_t lo = read(i + 1); + if (lo >= 0xDC00 && lo <= 0xDFFF) { + cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); + ++i; + } + } + if ((cp >= 0xD800 && cp <= 0xDFFF) || cp > 0x10FFFF) { + return FailInput(r, Error::kInvalidEncoding, "invalid UTF-16/32 input", + *out, out->size()); + } + AppendUtf8(out, cp); + } + return true; +} + +// Prepares the input for parsing: detects the encoding, transcodes to UTF-8 +// if needed, strips a leading BOM, validates, rejects C0 control characters +// and normalizes line breaks to '\n'. `storage` receives a copy only when one +// is needed. +inline bool PrepareInput(std::string_view in, std::string* storage, + std::string_view* out, Result* r) { + const auto* b = reinterpret_cast(in.data()); + const size_t n = in.size(); + int unit = 1; + bool big_endian = false; + size_t skip = 0; + if (n >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0xFE && b[3] == 0xFF) { + unit = 4, big_endian = true, skip = 4; + } else if (n >= 4 && b[0] == 0xFF && b[1] == 0xFE && b[2] == 0 && + b[3] == 0) { + unit = 4, skip = 4; + } else if (n >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] != 0) { + unit = 4, big_endian = true; + } else if (n >= 4 && b[0] != 0 && b[1] == 0 && b[2] == 0 && b[3] == 0) { + unit = 4; + } else if (n >= 2 && b[0] == 0xFE && b[1] == 0xFF) { + unit = 2, big_endian = true, skip = 2; + } else if (n >= 2 && b[0] == 0xFF && b[1] == 0xFE) { + unit = 2, skip = 2; + } else if (n >= 2 && b[0] == 0 && b[1] != 0) { + unit = 2, big_endian = true; + } else if (n >= 2 && b[0] != 0 && b[1] == 0) { + unit = 2; + } else if (n >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { + skip = 3; + } + + std::string_view text = in.substr(skip); + bool validated = false; + if (unit != 1) { + if (!Transcode(text, unit, big_endian, storage, r)) return false; + text = *storage; + validated = true; + // A BOM may remain if one was both implied and present; drop it. + if (text.size() >= 3 && text.substr(0, 3) == "\xEF\xBB\xBF") { + text.remove_prefix(3); + } + } +#if defined(IGNAME_USE_SIMDUTF) + if (!validated) { + if (!simdutf::validate_utf8(text.data(), text.size())) { + size_t bad = ValidateUtf8(text.data(), text.size()); + return FailInput(r, Error::kInvalidEncoding, "invalid UTF-8", text, + bad); + } + validated = true; + } +#endif + + // Reject C0 control characters other than tab and line breaks, note + // whether there are carriage returns to normalize and (unless already + // done) validate UTF-8. Words of eight plain ASCII bytes are skipped + // without looking at the individual bytes. + bool has_cr = false; + const char* data = text.data(); + const size_t size = text.size(); + size_t i = 0; + while (i < size) { + if (i + 8 <= size) { + uint64_t w; + memcpy(&w, data + i, 8); + constexpr uint64_t k7F = 0x7F7F7F7F7F7F7F7FULL; + constexpr uint64_t k80 = 0x8080808080808080ULL; + // High bit set in each byte that is < 0x20, exact (no carries). + const uint64_t control = ~(((w & k7F) + 0x6060606060606060ULL) | w) & k80; + // ... that is '\n' or '\t' (exact zero-byte tests). + const uint64_t xn = w ^ 0x0A0A0A0A0A0A0A0AULL; + const uint64_t xt = w ^ 0x0909090909090909ULL; + const uint64_t newline = ~(((xn & k7F) + k7F) | xn) & k80; + const uint64_t tab = ~(((xt & k7F) + k7F) | xt) & k80; + const uint64_t non_ascii = validated ? 0 : (w & k80); + if (((control & ~newline & ~tab) | non_ascii) == 0) { + i += 8; + continue; + } + } + const auto c = static_cast(data[i]); + if (c < 0x20) { + if (c == '\r') { + has_cr = true; + } else if (c != '\n' && c != '\t') { + return FailInput(r, Error::kInvalidCharacter, + "control characters are not allowed", text, i); + } + ++i; + } else if (c >= 0x80 && !validated) { + // Validate one UTF-8 sequence. + const size_t seq = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : 2; + const size_t len = size - i < seq ? size - i : seq; + if (ValidateUtf8(data + i, len) != len || len != seq) { + return FailInput(r, Error::kInvalidEncoding, "invalid UTF-8", text, + i); + } + i += seq; + } else { + ++i; + } + } + if (has_cr) { + std::string normalized; + normalized.reserve(text.size()); + for (size_t k = 0; k < text.size(); ++k) { + const char c = text[k]; + if (c == '\r') { + normalized.push_back('\n'); + if (k + 1 < text.size() && text[k + 1] == '\n') ++k; + } else { + normalized.push_back(c); + } + } + *storage = std::move(normalized); + text = *storage; + } + *out = text; + return true; +} + +template +class Parser { + public: + Parser(std::string_view text, Handler& handler, const ParseOptions& options) + : p_(text.data()), + end_(text.data() + text.size()), + line_start_(text.data()), + handler_(handler), + options_(options) {} + + Result Run() { + if (!handler_.OnStreamStart()) Abort(); + if (ok_) ParseStream(); + if (ok_ && !handler_.OnStreamEnd()) Abort(); + return result_; + } + + private: + // Context for parsing a node's content. + struct Props { + std::string_view anchor; + bool has_tag = false; + bool any = false; + Mark mark; + }; + + // --- Errors ------------------------------------------------------------- + + bool Fail(const char* message, Error error = Error::kSyntax) { + if (ok_) { + ok_ = false; + result_.error = error; + result_.message = message; + result_.line = line_ + 1; + uint32_t column = 1; + for (const char* q = line_start_; q < p_ && q < end_; ++q) { + if ((static_cast(*q) & 0xC0) != 0x80) ++column; + } + result_.column = column; + } + return false; + } + + bool Abort() { return Fail("aborted by handler", Error::kAborted); } + + struct DepthGuard { + explicit DepthGuard(Parser* parser) : parser_(parser) { + ok = ++parser_->depth_ <= parser_->options_.max_depth; + if (!ok) parser_->Fail("maximum nesting depth exceeded", + Error::kDepthExceeded); + } + ~DepthGuard() { --parser_->depth_; } + Parser* parser_; + bool ok; + }; + + // --- Low-level scanning --------------------------------------------------- + + bool AtEnd() const { return p_ >= end_; } + char Peek(size_t k = 0) const { return p_ + k < end_ ? p_[k] : '\0'; } + bool IsBlankZ(const char* q) const { + return q >= end_ || *q == ' ' || *q == '\t' || *q == '\n'; + } + int Column() const { return static_cast(p_ - line_start_); } + Mark Here() const { + return Mark{line_ + 1, static_cast(p_ - line_start_) + 1}; + } + + // Number of leading spaces on the current line (cached per line). + int LineIndent() { + if (indent_line_ != line_start_) { + indent_ = static_cast(SkipSpaces(line_start_, end_) - line_start_); + indent_line_ = line_start_; + } + return indent_; + } + + // True if only whitespace precedes `q` on the current line. + bool OnlyWhiteBefore(const char* q) const { + while (q > line_start_ && IsWhite(q[-1])) --q; + return q == line_start_; + } + + // Consumes the '\n' at p_. + void NextLine() { + ++p_; + ++line_; + line_start_ = p_; + } + + void SkipWhite() { + p_ = SkipSpaces(p_, end_); + while (p_ < end_ && IsWhite(*p_)) ++p_; + } + + void SkipToEol() { + const void* nl = memchr(p_, '\n', end_ - p_); + p_ = nl ? static_cast(nl) : end_; + } + + bool IsCommentStart() const { + return p_ < end_ && *p_ == '#' && (p_ == line_start_ || IsWhite(p_[-1])); + } + + static bool IsDocMarker(const char* q, const char* end) { + return end - q >= 3 && + ((q[0] == '-' && q[1] == '-' && q[2] == '-') || + (q[0] == '.' && q[1] == '.' && q[2] == '.')) && + (end - q == 3 || q[3] == ' ' || q[3] == '\t' || q[3] == '\n'); + } + + // A document marker at the start of the current line. + bool AtDocMarker() const { + return p_ == line_start_ && IsDocMarker(p_, end_); + } + bool AtDocStart() const { return AtDocMarker() && *p_ == '-'; } + bool AtDocEnd() const { return AtDocMarker() && *p_ == '.'; } + + // Skips whitespace, comments and line breaks. Returns true if p_ ends up at + // the first non-white character of its line. + bool SkipToContent() { + const char* start = p_; + if (p_ < end_ && !IsWhite(*p_) && *p_ != '\n' && *p_ != '#') { + return OnlyWhiteBefore(start); + } + bool crossed = false; + for (;;) { + SkipWhite(); + if (p_ >= end_) break; + if (*p_ == '#') { + if (!IsCommentStart()) break; + SkipToEol(); + continue; + } + if (*p_ == '\n') { + NextLine(); + crossed = true; + p_ = SkipSpaces(p_, end_); + indent_ = static_cast(p_ - line_start_); + indent_line_ = line_start_; + continue; + } + break; + } + return crossed || OnlyWhiteBefore(start); + } + + // Ensures the rest of the line holds only whitespace and a comment. + bool ExpectLineEnd(const char* message) { + SkipWhite(); + if (p_ >= end_ || *p_ == '\n') return true; + if (IsCommentStart()) { + SkipToEol(); + return true; + } + return Fail(message); + } + + bool IsBlockSeqEntry() const { return Peek() == '-' && IsBlankZ(p_ + 1); } + bool IsExplicitKey() const { return Peek() == '?' && IsBlankZ(p_ + 1); } + bool IsBlockValue() const { return Peek() == ':' && IsBlankZ(p_ + 1); } + bool IsFlowValue(const char* q) const { + return q < end_ && *q == ':' && + (IsBlankZ(q + 1) || IsFlowIndicator(q[1])); + } + + // ns-plain-first(c) + bool PlainFirstOk(const char* q, bool flow) const { + if (q >= end_) return false; + char c = *q; + if (IsWhite(c) || c == '\n') return false; + if (!Has(c, kIndicator)) return true; + if (c == '-' || c == '?' || c == ':') { + const char* r = q + 1; + return !IsBlankZ(r) && !(flow && IsFlowIndicator(*r)); + } + return false; + } + + // Scans a line of a plain scalar starting at q. Returns where the scan + // stopped: a line break, the end of input, a ": " value indicator, a + // comment, or (in flow context) a flow indicator. + const char* ScanPlainLine(const char* q, bool flow) const { + if (!flow) { + for (;; ++q) { + q = FindAny3(q, end_, ':', '#', '\n'); + if (q >= end_ || *q == '\n') return q; + if (*q == ':') { + if (IsBlankZ(q + 1)) return q; + } else if (IsWhite(q[-1])) { + return q; // a comment + } + } + } + for (; q < end_; ++q) { + const char c = *q; + if (!Has(c, kPlainStopFlow)) continue; + if (c == ':') { + if (IsBlankZ(q + 1) || (flow && IsFlowIndicator(q[1]))) break; + continue; + } + if (c == '#') { + if (IsWhite(q[-1])) break; + continue; + } + break; // '\n' or a flow indicator + } + return q; + } + + static const char* TrimRight(const char* begin, const char* end) { + while (end > begin && IsWhite(end[-1])) --end; + return end; + } + + // Skips a quoted scalar on the current line, starting at its opening + // quote. Returns nullptr if it does not end on this line. + const char* SkipQuotedInLine(const char* q, const char* limit) const { + const char quote = *q++; + const uint16_t stop = quote == '"' ? kDoubleQuoteStop : kQuoteStop; + while (q < limit && *q != '\n') { + if (!Has(*q, stop)) { + ++q; + continue; + } + if (quote == '"' && *q == '\\') { + q += 2; + continue; + } + if (*q == quote) { + if (quote == '\'' && q + 1 < limit && q[1] == '\'') { + q += 2; + continue; + } + return q + 1; + } + ++q; + } + return nullptr; + } + + // Skips a flow collection on the current line, starting at its opening + // bracket. Returns nullptr if it does not end on this line. Tracks whether + // the scan is inside a plain scalar, where quotes and ':' are ordinary + // characters ("[a 'b, -'c', :'d']" holds no quoted scalars). + const char* SkipFlowInLine(const char* q, const char* limit) const { + int depth = 0; + bool plain = false; // inside a plain scalar + bool json_end = false; // after a quoted scalar or a collection + while (q < limit) { + if (plain) { + // Spaces do not end a plain scalar; ':', '#', flow indicators, + // quotes and line breaks need a look. + while (q < limit && !Has(*q, kPlainStopFlow | kFlowSkipStop)) ++q; + if (q >= limit) break; + } + const char c = *q; + switch (c) { + case ' ': + case '\t': + ++q; + continue; + case '\n': + return nullptr; + case '[': + case '{': + ++depth; + plain = json_end = false; + ++q; + continue; + case ']': + case '}': + if (--depth == 0) return q + 1; + plain = false; + json_end = true; + ++q; + continue; + case ',': + plain = json_end = false; + ++q; + continue; + case '#': + if (IsWhite(q[-1])) return nullptr; // a comment + break; + case ':': { + const char next = q + 1 < limit ? q[1] : '\n'; + if (json_end || IsWhite(next) || next == '\n' || + IsFlowIndicator(next)) { + plain = json_end = false; // a value indicator + ++q; + continue; + } + break; + } + default: + break; + } + if (plain) { // a quote or ':' inside a plain scalar + ++q; + continue; + } + // The start of a node. + json_end = false; + if (c == '"' || c == '\'') { + q = SkipQuotedInLine(q, limit); + if (!q) return nullptr; + json_end = true; + continue; + } + const char next = q + 1 < limit ? q[1] : '\n'; + if (c == '!' && next == '<') { // a verbatim tag may hold '[' ']' + q += 2; + while (q < limit && *q != '>' && *q != '\n') ++q; + if (q < limit && *q == '>') ++q; + continue; + } + if (c == '&' || c == '!' || c == '*') { // properties, aliases + ++q; + while (q < limit && !Has(*q, kAnchorStop)) ++q; + continue; + } + if (!((c == '-' || c == '?') && (IsWhite(next) || next == '\n'))) { + plain = true; + } + ++q; + } + return nullptr; + } + + // Looks ahead from q for an implicit key on the current line: optional + // properties, a single-line node, optional spaces and a ':' value + // indicator. Implicit keys are limited to 1024 characters (approximated + // here in bytes with headroom for multi-byte characters). + bool ImplicitKeyAhead(const char* q, bool flow) { + if (q == key_memo_pos_ && flow == key_memo_flow_) return key_memo_result_; + key_memo_pos_ = q; + key_memo_flow_ = flow; + key_memo_result_ = ScanImplicitKey(q, flow); + return key_memo_result_; + } + + bool ScanImplicitKey(const char* q, bool flow) { + const char* limit = end_ - q > 4096 ? q + 4096 : end_; + // Properties. + for (;;) { + if (q < limit && *q == '&') { + ++q; + while (q < limit && !Has(*q, kAnchorStop)) ++q; + } else if (q < limit && *q == '!') { + ++q; + if (q < limit && *q == '<') { + while (q < limit && *q != '>' && *q != '\n') ++q; + if (q < limit && *q == '>') ++q; + } else { + while (q < limit && (IsTagChar(*q) || *q == '!')) ++q; + } + } else { + break; + } + while (q < limit && IsWhite(*q)) ++q; + } + if (q >= limit) return false; + bool json_like = false; + const char c = *q; + if (c == '"' || c == '\'') { + q = SkipQuotedInLine(q, limit); + if (!q) return false; + json_like = true; + } else if (c == '[' || c == '{') { + q = SkipFlowInLine(q, limit); + if (!q) return false; + json_like = true; + } else if (c == '*') { + ++q; + while (q < limit && !Has(*q, kAnchorStop)) ++q; + } else if (c == ':' && (flow ? IsFlowValue(q) : IsBlankZ(q + 1))) { + return true; // an empty key + } else { + if (!PlainFirstOk(q, flow)) return false; + const char* stop = ScanPlainLine(q, flow); + plain_memo_start_ = q; + plain_memo_stop_ = stop; + plain_memo_flow_ = flow; + if (stop >= limit) return false; + q = stop; + } + while (q < limit && IsWhite(*q)) ++q; + if (q >= end_ || *q != ':') return false; + if (flow) return json_like || IsFlowValue(q); + return IsBlankZ(q + 1); + } + + // --- Events --------------------------------------------------------------- + + NodeInfo Info(const Props& props) const { + NodeInfo info; + info.anchor = props.anchor; + if (props.has_tag) info.tag = tag_; + info.mark = props.mark; + return info; + } + + bool EmitScalar(std::string_view value, ScalarStyle style, + const Props& props) { + if (!handler_.OnScalar(value, style, Info(props))) return Abort(); + return true; + } + + bool EmitEmpty(const Props& props) { + Props p = props; + if (!p.any) p.mark = Here(); + return EmitScalar({}, ScalarStyle::kPlain, p); + } + + // --- Properties ----------------------------------------------------------- + + bool ParseAnchorName(std::string_view* name) { + ++p_; // '&' or '*' + const char* start = p_; + while (p_ < end_ && !Has(*p_, kAnchorStop)) ++p_; + if (p_ == start) return Fail("expected an anchor or alias name"); + *name = std::string_view(start, p_ - start); + return true; + } + + // Appends `s` to tag_, decoding %HH escapes. + bool AppendUri(std::string_view s) { + for (size_t i = 0; i < s.size(); ++i) { + if (s[i] == '%') { + const int hi = i + 2 < s.size() ? HexValue(s[i + 1]) : -1; + const int lo = i + 2 < s.size() ? HexValue(s[i + 2]) : -1; + if (hi < 0 || lo < 0) return Fail("invalid URI escape in tag"); + tag_.push_back(static_cast(hi << 4 | lo)); + i += 2; + } else { + tag_.push_back(s[i]); + } + } + return true; + } + + bool ParseTag() { + const char* start = p_; + ++p_; // '!' + tag_.clear(); + if (Peek() == '<') { + ++p_; + const char* uri = p_; + while (p_ < end_ && (Has(*p_, kUriChar) || *p_ == '%')) ++p_; + if (Peek() != '>' || p_ == uri) return Fail("invalid verbatim tag"); + std::string_view verbatim(uri, p_ - uri); + ++p_; + if (verbatim == "!") return Fail("invalid verbatim tag"); + return AppendUri(verbatim); + } + // Named handle "!word!", secondary handle "!!" or primary handle "!". + const char* q = p_; + while (q < end_ && Has(*q, kWordChar)) ++q; + std::string_view handle("!"); + if (q < end_ && *q == '!') { + handle = std::string_view(start, q + 1 - start); + p_ = q + 1; + } + const char* suffix = p_; + while (p_ < end_ && IsTagChar(*p_)) ++p_; + std::string_view suf(suffix, p_ - suffix); + if (suf.empty()) { + if (handle == "!") { + tag_ = "!"; // non-specific tag + return true; + } + return Fail("expected a tag suffix"); + } + std::string_view prefix; + if (!LookupTagHandle(handle, &prefix)) { + return Fail("undefined tag handle"); + } + tag_.append(prefix); + return AppendUri(suf); + } + + bool LookupTagHandle(std::string_view handle, std::string_view* prefix) { + for (const auto& [h, p] : tag_handles_) { + if (h == handle) { + *prefix = p; + return true; + } + } + if (handle == "!") { + *prefix = "!"; + return true; + } + if (handle == "!!") { + *prefix = kCoreTagPrefix; + return true; + } + return false; + } + + // Parses node properties (an anchor and/or a tag, in either order) on the + // current line. + bool ParseProperties(Props* props, bool flow) { + if (!props->any) { + props->any = true; + props->mark = Here(); + } + bool have_anchor = !props->anchor.empty(); + for (;;) { + if (Peek() == '&') { + if (have_anchor) return Fail("a node may have only one anchor"); + if (!ParseAnchorName(&props->anchor)) return false; + have_anchor = true; + } else if (Peek() == '!') { + if (props->has_tag) return Fail("a node may have only one tag"); + if (!ParseTag()) return false; + props->has_tag = true; + } else { + break; + } + if (!(IsBlankZ(p_) || (flow && IsFlowIndicator(*p_)))) { + return Fail("expected whitespace after node properties"); + } + const char* q = p_; + while (q < end_ && IsWhite(*q)) ++q; + if (q < end_ && ((*q == '&' && !have_anchor) || + (*q == '!' && !props->has_tag))) { + p_ = q; + continue; + } + break; + } + return true; + } + + // --- Scalars -------------------------------------------------------------- + + // Parses a plain scalar at p_. Continuation lines must be indented by at + // least `min_indent` spaces. + bool ParsePlain(int min_indent, bool flow, bool multiline, + std::string_view* out) { + const char* start = p_; + const char* stop = p_ == plain_memo_start_ && flow == plain_memo_flow_ + ? plain_memo_stop_ + : ScanPlainLine(p_, flow); + const char* seg_end = TrimRight(p_, stop); + bool copied = false; + while (multiline && stop < end_ && *stop == '\n') { + // Look ahead for a continuation line. + const char* q = stop; + uint32_t lines = 0; + const char* ls = nullptr; + int breaks = 0; + const char* text = nullptr; + for (;;) { + ++q; // past '\n' + ++lines; + ++breaks; + ls = q; + const char* r = SkipSpaces(q, end_); + const int indent = static_cast(r - q); + const char* t = r; + while (t < end_ && IsWhite(*t)) ++t; + if (t >= end_) break; + if (*t == '\n') { + q = t; + continue; + } + if (indent == 0 && IsDocMarker(q, end_)) break; + if (indent < min_indent || *t == '#') break; + if (*t == ':' && + (IsBlankZ(t + 1) || (flow && IsFlowIndicator(t[1])))) { + break; + } + if (flow && IsFlowIndicator(*t)) break; + text = t; + break; + } + if (!text) break; + if (!copied) { + scratch_.assign(start, seg_end); + copied = true; + } + if (breaks == 1) { + scratch_.push_back(' '); + } else { + scratch_.append(breaks - 1, '\n'); + } + line_ += lines; + line_start_ = ls; + p_ = text; + stop = ScanPlainLine(p_, flow); + seg_end = TrimRight(p_, stop); + scratch_.append(p_, seg_end); + } + p_ = seg_end; + *out = copied ? std::string_view(scratch_) + : std::string_view(start, seg_end - start); + return true; + } + + // Handles a line break inside a quoted scalar (p_ at '\n'): folds it and + // any following empty lines, and positions p_ at the next content. + bool FoldQuotedBreak(int min_indent, bool escaped) { + int breaks = 0; + for (;;) { + NextLine(); + ++breaks; + const char* r = p_; + while (r < end_ && *r == ' ') ++r; + const int indent = static_cast(r - p_); + const char* t = r; + while (t < end_ && IsWhite(*t)) ++t; + if (indent == 0 && IsDocMarker(p_, end_)) { + return Fail("document marker inside a quoted scalar"); + } + if (t >= end_) { + p_ = t; + return Fail("unterminated quoted scalar"); + } + if (*t == '\n') { + p_ = t; + continue; + } + if (indent < min_indent) { + p_ = t; + return Fail("insufficient indentation in a quoted scalar"); + } + p_ = t; + break; + } + if (escaped) { + scratch_.append(breaks - 1, '\n'); + } else if (breaks == 1) { + scratch_.push_back(' '); + } else { + scratch_.append(breaks - 1, '\n'); + } + return true; + } + + bool ParseEscape() { + // p_ at '\\' + if (p_ + 1 >= end_) return Fail("unterminated double-quoted scalar"); + const char e = p_[1]; + p_ += 2; + int digits = 0; + switch (e) { + case '0': scratch_.push_back('\0'); return true; + case 'a': scratch_.push_back('\a'); return true; + case 'b': scratch_.push_back('\b'); return true; + case 't': + case '\t': scratch_.push_back('\t'); return true; + case 'n': scratch_.push_back('\n'); return true; + case 'v': scratch_.push_back('\v'); return true; + case 'f': scratch_.push_back('\f'); return true; + case 'r': scratch_.push_back('\r'); return true; + case 'e': scratch_.push_back('\x1B'); return true; + case ' ': scratch_.push_back(' '); return true; + case '"': scratch_.push_back('"'); return true; + case '/': scratch_.push_back('/'); return true; + case '\\': scratch_.push_back('\\'); return true; + case 'N': scratch_.append("\xC2\x85"); return true; + case '_': scratch_.append("\xC2\xA0"); return true; + case 'L': scratch_.append("\xE2\x80\xA8"); return true; + case 'P': scratch_.append("\xE2\x80\xA9"); return true; + case 'x': digits = 2; break; + case 'u': digits = 4; break; + case 'U': digits = 8; break; + default: + p_ -= 2; + return Fail("invalid escape sequence"); + } + uint32_t cp = 0; + for (int i = 0; i < digits; ++i) { + const int v = p_ < end_ ? HexValue(*p_) : -1; + if (v < 0) return Fail("invalid escape sequence"); + cp = cp << 4 | v; + ++p_; + } + if (digits == 4 && cp >= 0xD800 && cp <= 0xDBFF && end_ - p_ >= 6 && + p_[0] == '\\' && p_[1] == 'u') { + // A UTF-16 surrogate pair written as two escapes. + uint32_t lo = 0; + bool valid = true; + for (int i = 2; i < 6; ++i) { + const int v = HexValue(p_[i]); + if (v < 0) valid = false; + lo = lo << 4 | (v < 0 ? 0 : v); + } + if (valid && lo >= 0xDC00 && lo <= 0xDFFF) { + cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); + p_ += 6; + } + } + if (cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) { + return Fail("invalid Unicode escape"); + } + AppendUtf8(&scratch_, cp); + return true; + } + + bool ParseDoubleQuoted(int min_indent, bool single_line, + std::string_view* out) { + ++p_; + const char* start = p_; + const char* q = FindAny3(p_, end_, '"', '\\', '\n'); + if (q < end_ && *q == '"') { + *out = std::string_view(start, q - start); + p_ = q + 1; + return true; + } + scratch_.assign(start, q < end_ && *q == '\n' ? TrimRight(start, q) : q); + p_ = q; + for (;;) { + if (p_ >= end_) return Fail("unterminated double-quoted scalar"); + const char c = *p_; + if (c == '"') { + ++p_; + break; + } + if (c == '\\') { + if (p_ + 1 < end_ && p_[1] == '\n') { + if (single_line) return Fail("unterminated double-quoted scalar"); + ++p_; + if (!FoldQuotedBreak(min_indent, true)) return false; + continue; + } + if (!ParseEscape()) return false; + continue; + } + if (c == '\n') { + if (single_line) return Fail("unterminated double-quoted scalar"); + if (!FoldQuotedBreak(min_indent, false)) return false; + continue; + } + const char* run = p_; + p_ = FindAny3(p_, end_, '"', '\\', '\n'); + scratch_.append(run, p_ < end_ && *p_ == '\n' ? TrimRight(run, p_) : p_); + } + *out = scratch_; + return true; + } + + bool ParseSingleQuoted(int min_indent, bool single_line, + std::string_view* out) { + ++p_; + const char* start = p_; + const char* q = FindAny3(p_, end_, '\'', '\n', '\n'); + if (q < end_ && *q == '\'' && !(q + 1 < end_ && q[1] == '\'')) { + *out = std::string_view(start, q - start); + p_ = q + 1; + return true; + } + scratch_.clear(); + p_ = start; + for (;;) { + const char* run = p_; + p_ = FindAny3(p_, end_, '\'', '\n', '\n'); + if (p_ >= end_) return Fail("unterminated single-quoted scalar"); + if (*p_ == '\'') { + scratch_.append(run, p_); + if (p_ + 1 < end_ && p_[1] == '\'') { + scratch_.push_back('\''); + p_ += 2; + continue; + } + ++p_; + break; + } + // '\n' + scratch_.append(run, TrimRight(run, p_)); + if (single_line) return Fail("unterminated single-quoted scalar"); + if (!FoldQuotedBreak(min_indent, false)) return false; + } + *out = scratch_; + return true; + } + + // Parses a literal or folded block scalar. `n` is the indentation of the + // parent node. + bool ParseBlockScalar(int n, const Props& props) { + Props p = props; + if (!p.any) p.mark = Here(); + const bool folded = *p_ == '>'; + ++p_; + int chomp = 0; // -1 strip, 0 clip, +1 keep + int explicit_indent = 0; + for (int i = 0; i < 2; ++i) { + const char c = Peek(); + if ((c == '-' || c == '+') && chomp == 0) { + chomp = c == '-' ? -1 : 1; + ++p_; + } else if (c >= '1' && c <= '9' && explicit_indent == 0) { + explicit_indent = c - '0'; + ++p_; + } else { + break; + } + } + if (!IsBlankZ(p_)) return Fail("invalid block scalar header"); + if (!ExpectLineEnd("invalid block scalar header")) return false; + if (p_ < end_) NextLine(); + + int indent; + if (explicit_indent) { + indent = (n < 0 ? 0 : n) + explicit_indent; + } else { + // Detect the indentation from the first non-empty line. + int max_empty = 0; + indent = -1; + for (const char* q = p_; q < end_;) { + const char* r = q; + while (r < end_ && *r == ' ') ++r; + const int spaces = static_cast(r - q); + if (r >= end_ || *r == '\n') { + // An empty line (the last line may end at the end of input). + if (spaces > max_empty) max_empty = spaces; + q = r + 1; + continue; + } + indent = spaces; + break; + } + if (indent <= n || indent < 0) { + // No content lines: everything up to the end is empty lines. + indent = n + 1 > max_empty ? n + 1 : max_empty; + if (indent < 1 && n >= 0) indent = 1; + } else if (max_empty > indent) { + return Fail( + "leading empty lines of a block scalar are more indented than its " + "first line"); + } + } + + scratch_.clear(); + int pending = 0; // line breaks since the end of the last text line + bool any_text = false; + bool prev_spaced = false; + while (p_ < end_) { + const char* r = p_; + const char* lim = end_ - p_ > indent ? p_ + indent : end_; + while (r < lim && *r == ' ') ++r; + if (r - p_ < indent) { + if (r < end_ && *r == '\n') { + // An empty line. + ++pending; + p_ = r; + NextLine(); + continue; + } + if (r >= end_) { + // Trailing spaces at the end of input: an empty last line. + ++pending; + p_ = r; + } else if (*r == '\t') { + const char* t = r; + while (t < end_ && IsWhite(*t)) ++t; + if (t >= end_ || *t == '\n') { + p_ = r; + return Fail("tabs are not allowed as indentation"); + } + } + break; // less indented: the scalar ends + } + if (indent == 0 && IsDocMarker(p_, end_)) break; + const char* text = r; + const void* nl = memchr(text, '\n', end_ - text); + const char* eol = nl ? static_cast(nl) : end_; + if (text == eol) { + // An empty line. The end of input terminates a non-empty last line. + ++pending; + p_ = eol; + if (p_ < end_) NextLine(); + continue; + } + const bool spaced = IsWhite(*text); + if (!folded || !any_text || prev_spaced || spaced) { + scratch_.append(pending, '\n'); + } else if (pending == 1) { + scratch_.push_back(' '); + } else { + scratch_.append(pending - 1, '\n'); + } + scratch_.append(text, eol); + any_text = true; + prev_spaced = spaced; + pending = 1; // the end of input terminates the last line, too + p_ = eol; + if (p_ < end_) NextLine(); + } + if (chomp == 1) { + scratch_.append(pending, '\n'); + } else if (chomp == 0 && any_text && pending > 0) { + scratch_.push_back('\n'); + } + return EmitScalar(scratch_, + folded ? ScalarStyle::kFolded : ScalarStyle::kLiteral, + p); + } + + bool ParseAlias(const Props& props) { + if (props.any) return Fail("an alias cannot have properties"); + const Mark mark = Here(); + std::string_view name; + if (!ParseAnchorName(&name)) return false; + if (!handler_.OnAlias(name, mark)) return Abort(); + return true; + } + + // --- Block collections ------------------------------------------------- + + // Parses a block node (s-l+block-node, or s-l+block-indented when + // `compact` is set). `n` is the indentation of the parent; `block_out` + // selects the block-out context, in which a block sequence may be + // indented as much as its parent. On entry p_ follows an indicator, a + // document start marker, or is at the start of a line. + bool ParseBlockNode(int n, bool block_out, bool compact) { + const char* entry = p_; + bool fresh = SkipToContent(); + if (AtEnd() || (fresh && AtDocMarker())) return EmitEmpty({}); + + if (!fresh && compact && + !memchr(entry, '\t', static_cast(p_ - entry))) { + if (IsBlockSeqEntry()) return ParseBlockSequence(Column(), {}); + if (IsExplicitKey() || ImplicitKeyAhead(p_, false)) { + return ParseBlockMapping(Column(), {}); + } + } + + // Properties may be separated from each other and from the content by + // line breaks. + Props props; + for (;;) { + if (fresh) { + const int indent = LineIndent(); + const bool tab = Column() != indent; + if (IsBlockSeqEntry() && !tab) { + if (indent > n || (block_out && indent == n)) { + return ParseBlockSequence(indent, props); + } + return EmitEmpty(props); + } + if (indent <= n) return EmitEmpty(props); + if (IsExplicitKey() || ImplicitKeyAhead(p_, false)) { + if (tab) return Fail("tabs are not allowed as indentation"); + return ParseBlockMapping(indent, props); + } + } + if (!(Peek() == '&' && props.anchor.empty()) && + !(Peek() == '!' && !props.has_tag)) { + break; + } + if (!ParseProperties(&props, false)) return false; + fresh = SkipToContent(); + if (AtEnd() || (fresh && AtDocMarker())) return EmitEmpty(props); + } + + const char c = *p_; + if (c == '|' || c == '>') return ParseBlockScalar(n, props); + if (IsBlockSeqEntry()) { + return Fail("block sequence entries are not allowed in this context"); + } + if (fresh && LineIndent() <= n) return EmitEmpty(props); + if (!ParseFlowNodeInBlock(n, props)) return false; + return ExpectLineEnd(Peek() == ':' + ? "mapping values are not allowed in this context" + : "unexpected content after a node"); + } + + // A flow node (scalar, flow collection or alias) used as a block node. + bool ParseFlowNodeInBlock(int n, const Props& props) { + Props p = props; + if (!p.any) p.mark = Here(); + std::string_view value; + switch (*p_) { + case '*': + return ParseAlias(props); + case '[': + return ParseFlowSequence(n + 1, p); + case '{': + return ParseFlowMapping(n + 1, p); + case '"': + return ParseDoubleQuoted(n + 1, false, &value) && + EmitScalar(value, ScalarStyle::kDoubleQuoted, p); + case '\'': + return ParseSingleQuoted(n + 1, false, &value) && + EmitScalar(value, ScalarStyle::kSingleQuoted, p); + default: + if (!PlainFirstOk(p_, false)) return InvalidPlainStart(); + return ParsePlain(n + 1, false, true, &value) && + EmitScalar(value, ScalarStyle::kPlain, p); + } + } + + bool InvalidPlainStart() { + const char c = Peek(); + if (c == '@' || c == '`') { + return Fail("reserved indicators cannot start a plain scalar"); + } + if (c == '\t') return Fail("tabs are not allowed as indentation"); + return Fail("unexpected character"); + } + + bool ParseBlockSequence(int m, const Props& props) { + DepthGuard guard(this); + if (!guard.ok) return false; + Props p = props; + if (!p.any) p.mark = Here(); + if (!handler_.OnSequenceStart(CollectionStyle::kBlock, Info(p))) { + return Abort(); + } + for (;;) { + ++p_; // '-' + if (!ParseBlockNode(m, false, true)) return false; + const bool fresh = SkipToContent(); + if (AtEnd() || AtDocMarker()) break; + if (!fresh) return Fail("unexpected content after a sequence entry"); + const int indent = LineIndent(); + if (indent < m) break; + if (indent > m || Column() != m) { + if (Column() != indent && indent <= m) { + return Fail("tabs are not allowed as indentation"); + } + return Fail("bad indentation of a sequence entry"); + } + if (!IsBlockSeqEntry()) break; + } + if (!handler_.OnSequenceEnd()) return Abort(); + return true; + } + + // Parses an implicit key (properties and a single-line flow node) and the + // following ':'. + bool ParseImplicitKey() { + Props props; + if (Peek() == '&' || Peek() == '!') { + if (!ParseProperties(&props, false)) return false; + SkipWhite(); + } + Props p = props; + if (!p.any) p.mark = Here(); + std::string_view value; + bool ok; + switch (IsBlockValue() ? '\0' : Peek()) { + case '\0': + ok = EmitEmpty(props); + break; + case '*': + ok = ParseAlias(props); + break; + case '"': + ok = ParseDoubleQuoted(0, true, &value) && + EmitScalar(value, ScalarStyle::kDoubleQuoted, p); + break; + case '\'': + ok = ParseSingleQuoted(0, true, &value) && + EmitScalar(value, ScalarStyle::kSingleQuoted, p); + break; + case '[': + ok = ParseFlowSequence(0, p); + break; + case '{': + ok = ParseFlowMapping(0, p); + break; + default: + ok = ParsePlain(0, false, false, &value) && + EmitScalar(value, ScalarStyle::kPlain, p); + break; + } + if (!ok) return false; + SkipWhite(); + if (Peek() != ':') return Fail("expected ':' after a mapping key"); + ++p_; + return true; + } + + bool ParseBlockMapping(int m, const Props& props) { + DepthGuard guard(this); + if (!guard.ok) return false; + Props p = props; + if (!p.any) p.mark = Here(); + if (!handler_.OnMappingStart(CollectionStyle::kBlock, Info(p))) { + return Abort(); + } + for (;;) { + bool fresh; + if (IsExplicitKey()) { + ++p_; + if (!ParseBlockNode(m, true, true)) return false; + fresh = SkipToContent(); + if (!AtEnd() && fresh && !AtDocMarker() && Column() == m && + LineIndent() == m && IsBlockValue()) { + ++p_; + if (!ParseBlockNode(m, true, true)) return false; + fresh = SkipToContent(); + } else if (!EmitEmpty({})) { + return false; + } + } else { + if (!ImplicitKeyAhead(p_, false)) { + return Fail("could not find the ':' of a mapping entry"); + } + if (!ParseImplicitKey()) return false; + if (!ParseBlockNode(m, true, false)) return false; + fresh = SkipToContent(); + } + if (AtEnd() || AtDocMarker()) break; + if (!fresh) return Fail("unexpected content after a mapping entry"); + const int indent = LineIndent(); + if (indent < m) break; + if (indent > m) return Fail("bad indentation of a mapping entry"); + if (Column() != m) return Fail("tabs are not allowed as indentation"); + } + if (!handler_.OnMappingEnd()) return Abort(); + return true; + } + + // --- Flow collections --------------------------------------------------- + + // Skips whitespace, comments and line breaks inside a flow collection. + // Content lines must be indented by at least `n` spaces. + bool SkipFlowWhite(int n) { + // Fast path: at most one space, followed by a token. + if (p_ < end_ && *p_ == ' ') ++p_; + if (p_ < end_ && !IsWhite(*p_) && *p_ != '\n' && *p_ != '#') return true; + return SkipFlowWhiteSlow(n); + } + + bool SkipFlowWhiteSlow(int n) { + for (;;) { + SkipWhite(); + if (p_ >= end_) return true; + const char c = *p_; + if (c == '#') { + if (!IsCommentStart()) return true; + SkipToEol(); + continue; + } + if (c != '\n') return true; + NextLine(); + const char* r = p_; + while (r < end_ && *r == ' ') ++r; + const char* t = r; + while (t < end_ && IsWhite(*t)) ++t; + if (t >= end_ || *t == '\n' || *t == '#') { + p_ = t; + continue; + } + if (IsDocMarker(p_, end_)) { + return Fail("document marker inside a flow collection"); + } + if (r - p_ < n) { + p_ = t; + return Fail("insufficient indentation in a flow collection"); + } + p_ = t; + } + } + + // Parses a flow node inside a flow collection. Sets *json_like when the + // node is a quoted scalar or a flow collection (after which a ':' value + // indicator need not be followed by a space). + bool ParseFlowNode(int n, bool* json_like) { + Props props; + while ((Peek() == '&' && props.anchor.empty()) || + (Peek() == '!' && !props.has_tag)) { + if (!ParseProperties(&props, true)) return false; + if (!SkipFlowWhite(n)) return false; + } + Props p = props; + if (!p.any) p.mark = Here(); + if (AtEnd()) return Fail("unterminated flow collection"); + std::string_view value; + *json_like = false; + switch (*p_) { + case '*': + return ParseAlias(props); + case '[': + *json_like = true; + return ParseFlowSequence(n, p); + case '{': + *json_like = true; + return ParseFlowMapping(n, p); + case '"': + *json_like = true; + return ParseDoubleQuoted(n, false, &value) && + EmitScalar(value, ScalarStyle::kDoubleQuoted, p); + case '\'': + *json_like = true; + return ParseSingleQuoted(n, false, &value) && + EmitScalar(value, ScalarStyle::kSingleQuoted, p); + default: + if (props.any && (IsFlowIndicator(*p_) || IsFlowValue(p_))) { + return EmitEmpty(props); + } + if (!PlainFirstOk(p_, true)) return InvalidPlainStart(); + return ParsePlain(n, true, true, &value) && + EmitScalar(value, ScalarStyle::kPlain, p); + } + } + + // Parses a key/value entry of a flow mapping, or a single-pair mapping + // inside a flow sequence. + bool ParseFlowMapEntry(int n, char close) { + bool json_key = false; + if (Peek() == '?' && (IsBlankZ(p_ + 1) || IsFlowIndicator(p_[1]))) { + ++p_; + if (!SkipFlowWhite(n)) return false; + if (AtEnd()) return Fail("unterminated flow collection"); + if (IsFlowValue(p_) || *p_ == ',' || *p_ == close) { + if (!EmitEmpty({})) return false; + } else if (!ParseFlowNode(n, &json_key)) { + return false; + } + } else if (IsFlowValue(p_)) { + if (!EmitEmpty({})) return false; + } else if (!ParseFlowNode(n, &json_key)) { + return false; + } + if (!SkipFlowWhite(n)) return false; + if (Peek() == ':' && (json_key || IsFlowValue(p_))) { + ++p_; + if (!SkipFlowWhite(n)) return false; + if (AtEnd()) return Fail("unterminated flow collection"); + if (*p_ == ',' || *p_ == close) return EmitEmpty({}); + bool json_value; + return ParseFlowNode(n, &json_value); + } + return EmitEmpty({}); + } + + bool ParseFlowSequence(int n, const Props& props) { + DepthGuard guard(this); + if (!guard.ok) return false; + ++p_; // '[' + if (!handler_.OnSequenceStart(CollectionStyle::kFlow, Info(props))) { + return Abort(); + } + for (;;) { + if (!SkipFlowWhite(n)) return false; + if (AtEnd()) return Fail("unterminated flow sequence"); + if (*p_ == ']') { + ++p_; + break; + } + if ((Peek() == '?' && (IsBlankZ(p_ + 1) || IsFlowIndicator(p_[1]))) || + ImplicitKeyAhead(p_, true)) { + Props pair; + pair.mark = Here(); + if (!handler_.OnMappingStart(CollectionStyle::kFlow, Info(pair))) { + return Abort(); + } + if (!ParseFlowMapEntry(n, ']')) return false; + if (!handler_.OnMappingEnd()) return Abort(); + } else { + bool json_like; + if (!ParseFlowNode(n, &json_like)) return false; + } + if (!SkipFlowWhite(n)) return false; + if (AtEnd()) return Fail("unterminated flow sequence"); + if (*p_ == ',') { + ++p_; + continue; + } + if (*p_ == ']') { + ++p_; + break; + } + return Fail("expected ',' or ']' in a flow sequence"); + } + if (!handler_.OnSequenceEnd()) return Abort(); + return true; + } + + bool ParseFlowMapping(int n, const Props& props) { + DepthGuard guard(this); + if (!guard.ok) return false; + ++p_; // '{' + if (!handler_.OnMappingStart(CollectionStyle::kFlow, Info(props))) { + return Abort(); + } + for (;;) { + if (!SkipFlowWhite(n)) return false; + if (AtEnd()) return Fail("unterminated flow mapping"); + if (*p_ == '}') { + ++p_; + break; + } + if (!ParseFlowMapEntry(n, '}')) return false; + if (!SkipFlowWhite(n)) return false; + if (AtEnd()) return Fail("unterminated flow mapping"); + if (*p_ == ',') { + ++p_; + continue; + } + if (*p_ == '}') { + ++p_; + break; + } + return Fail("expected ',' or '}' in a flow mapping"); + } + if (!handler_.OnMappingEnd()) return Abort(); + return true; + } + + // --- Documents ------------------------------------------------------------ + + bool ParseDirective() { + ++p_; // '%' + const char* name = p_; + while (p_ < end_ && !IsBlankZ(p_)) ++p_; + const std::string_view directive(name, p_ - name); + if (directive == "YAML") { + if (yaml_directive_) return Fail("duplicate %YAML directive"); + yaml_directive_ = true; + if (!IsWhite(Peek())) return Fail("expected a YAML version"); + SkipWhite(); + const char* v = p_; + while (p_ < end_ && *p_ >= '0' && *p_ <= '9') ++p_; + if (p_ == v || Peek() != '.') return Fail("invalid YAML version"); + const std::string_view major(v, p_ - v); + ++p_; + const char* minor = p_; + while (p_ < end_ && *p_ >= '0' && *p_ <= '9') ++p_; + if (p_ == minor || !IsBlankZ(p_)) return Fail("invalid YAML version"); + if (major != "1") return Fail("unsupported YAML version"); + return ExpectLineEnd("unexpected content after a %YAML directive"); + } + if (directive == "TAG") { + if (!IsWhite(Peek())) return Fail("expected a tag handle"); + SkipWhite(); + const char* h = p_; + if (Peek() != '!') return Fail("invalid tag handle"); + ++p_; + while (p_ < end_ && Has(*p_, kWordChar)) ++p_; + if (Peek() == '!') { + ++p_; + } else if (p_ != h + 1) { + return Fail("invalid tag handle"); + } + const std::string_view handle(h, p_ - h); + if (!IsWhite(Peek())) return Fail("expected a tag prefix"); + SkipWhite(); + const char* prefix = p_; + while (p_ < end_ && (Has(*p_, kUriChar) || *p_ == '%')) ++p_; + if (p_ == prefix || !IsBlankZ(p_)) return Fail("invalid tag prefix"); + for (const auto& entry : tag_handles_) { + if (entry.first == handle) return Fail("duplicate %TAG directive"); + } + tag_handles_.emplace_back(handle, + std::string_view(prefix, p_ - prefix)); + return ExpectLineEnd("unexpected content after a %TAG directive"); + } + // Reserved directive: ignored. + SkipToEol(); + return true; + } + + void ParseStream() { + for (;;) { + // Document prefix: comments, blank lines and byte order marks. + for (;;) { + SkipToContent(); + if (p_ == line_start_ && end_ - p_ >= 3 && + memcmp(p_, "\xEF\xBB\xBF", 3) == 0) { + p_ += 3; + continue; + } + break; + } + if (AtEnd()) return; + + tag_handles_.clear(); + yaml_directive_ = false; + bool directives = false; + while (p_ == line_start_ && Peek() == '%') { + if (!ParseDirective()) return; + directives = true; + SkipToContent(); + } + + bool explicit_start = false; + if (AtDocStart()) { + explicit_start = true; + p_ += 3; + } else if (directives) { + Fail("expected '---' after directives"); + return; + } else if (AtDocEnd()) { + // A document end marker with no document. + p_ += 3; + if (!ExpectLineEnd("unexpected content after '...'")) return; + continue; + } else if (!OnlyWhiteBefore(p_)) { + Fail("unexpected content"); + return; + } + + if (!handler_.OnDocumentStart(explicit_start)) { + Abort(); + return; + } + if (!ParseBlockNode(-1, false, false)) return; + const bool fresh = SkipToContent(); + bool explicit_end = false; + if (AtDocEnd()) { + explicit_end = true; + p_ += 3; + if (!ExpectLineEnd("unexpected content after '...'")) return; + } else if (!AtEnd() && !AtDocStart()) { + Fail(fresh ? "unexpected content at the end of a document" + : "unexpected content after a node"); + return; + } + if (!handler_.OnDocumentEnd(explicit_end)) { + Abort(); + return; + } + } + } + + const char* p_; + const char* end_; + const char* line_start_; + const char* indent_line_ = nullptr; // line for which indent_ is valid + int indent_ = 0; + // Memoized lookahead results (the same position is often examined twice). + const char* key_memo_pos_ = nullptr; + bool key_memo_flow_ = false; + bool key_memo_result_ = false; + const char* plain_memo_start_ = nullptr; + const char* plain_memo_stop_ = nullptr; + bool plain_memo_flow_ = false; + uint32_t line_ = 0; + uint32_t depth_ = 0; + bool ok_ = true; + bool yaml_directive_ = false; + Handler& handler_; + ParseOptions options_; + Result result_; + std::string scratch_; // scalar content that is not a slice of the input + std::string tag_; // the resolved tag of the node being parsed + std::vector> tag_handles_; +}; + +// --- Numbers ---------------------------------------------------------------- + +inline bool ParseDouble(std::string_view s, double* out) { + if (!s.empty() && s[0] == '+') s.remove_prefix(1); +#if defined(IGNAME_USE_FAST_FLOAT) || \ + (defined(__cpp_lib_to_chars) && __cpp_lib_to_chars >= 201611L && \ + !defined(IGNAME_NO_FROM_CHARS)) +#if defined(IGNAME_USE_FAST_FLOAT) + auto r = fast_float::from_chars(s.data(), s.data() + s.size(), *out); +#else + auto r = std::from_chars(s.data(), s.data() + s.size(), *out); +#endif + if (r.ptr != s.data() + s.size()) return false; + if (r.ec == std::errc::result_out_of_range) { + // Overflow to infinity or underflow to zero, as strtod does. + const bool negative = s[0] == '-'; + const size_t e = s.find_first_of("eE"); + const bool tiny = + e != std::string_view::npos && e + 1 < s.size() && s[e + 1] == '-'; + *out = tiny ? (negative ? -0.0 : 0.0) : (negative ? -HUGE_VAL : HUGE_VAL); + return true; + } + return r.ec == std::errc(); +#else + // Note: strtod honors LC_NUMERIC. + char buf[128]; + std::string heap; + const char* cstr; + if (s.size() < sizeof(buf)) { + memcpy(buf, s.data(), s.size()); + buf[s.size()] = '\0'; + cstr = buf; + } else { + heap.assign(s); + cstr = heap.c_str(); + } + char* end; + *out = strtod(cstr, &end); + return end == cstr + s.size(); +#endif +} + +// Parses digits in `base`. Returns false on overflow of uint64_t. +inline bool ParseUnsigned(std::string_view digits, int base, uint64_t* out) { + uint64_t value = 0; + for (char c : digits) { + const uint64_t d = static_cast(HexValue(c)); + if (value > (std::numeric_limits::max() - d) / base) { + return false; + } + value = value * base + d; + } + *out = value; + return true; +} + +inline bool AllDigits(std::string_view s, int base) { + if (s.empty()) return false; + for (char c : s) { + const int v = HexValue(c); + if (v < 0 || v >= base) return false; + } + return true; +} + +// [-+]? ( \. [0-9]+ | [0-9]+ ( \. [0-9]* )? ) ( [eE] [-+]? [0-9]+ )? +inline bool IsCoreFloat(std::string_view s) { + size_t i = 0; + const size_t n = s.size(); + if (i < n && (s[i] == '-' || s[i] == '+')) ++i; + size_t int_digits = 0; + while (i < n && s[i] >= '0' && s[i] <= '9') ++i, ++int_digits; + size_t frac_digits = 0; + if (i < n && s[i] == '.') { + ++i; + while (i < n && s[i] >= '0' && s[i] <= '9') ++i, ++frac_digits; + } + if (int_digits == 0 && frac_digits == 0) return false; + if (i < n && (s[i] == 'e' || s[i] == 'E')) { + ++i; + if (i < n && (s[i] == '-' || s[i] == '+')) ++i; + size_t exp_digits = 0; + while (i < n && s[i] >= '0' && s[i] <= '9') ++i, ++exp_digits; + if (exp_digits == 0) return false; + } + return i == n; +} + +inline bool ResolveInt(std::string_view s, ScalarValue* out) { + out->kind = ScalarKind::kInt; + out->overflow = false; + int base = 10; + bool negative = false; + std::string_view digits = s; + if (s.size() > 2 && s[0] == '0' && (s[1] == 'o' || s[1] == 'x')) { + base = s[1] == 'o' ? 8 : 16; + digits.remove_prefix(2); + } else if (!s.empty() && (s[0] == '-' || s[0] == '+')) { + negative = s[0] == '-'; + digits.remove_prefix(1); + } + if (!AllDigits(digits, base)) return false; + uint64_t magnitude; + const bool fits = ParseUnsigned(digits, base, &magnitude); + const uint64_t limit = + static_cast(std::numeric_limits::max()) + negative; + if (fits && magnitude <= limit) { + out->integer = negative ? static_cast(0 - magnitude) + : static_cast(magnitude); + out->number = static_cast(out->integer); + return true; + } + out->overflow = true; + double value = 0; + for (char c : digits) value = value * base + HexValue(c); + out->number = negative ? -value : value; + if (base == 10) ParseDouble(s, &out->number); // correctly rounded + return true; +} + +inline bool ResolveFloat(std::string_view s, ScalarValue* out) { + out->kind = ScalarKind::kFloat; + std::string_view t = s; + bool negative = false; + if (!t.empty() && (t[0] == '-' || t[0] == '+')) { + negative = t[0] == '-'; + t.remove_prefix(1); + } + if (t == ".inf" || t == ".Inf" || t == ".INF") { + out->number = negative ? -std::numeric_limits::infinity() + : std::numeric_limits::infinity(); + return true; + } + if (s == ".nan" || s == ".NaN" || s == ".NAN") { + out->number = std::numeric_limits::quiet_NaN(); + return true; + } + return IsCoreFloat(s) && ParseDouble(s, &out->number); +} + +inline bool IsCoreNull(std::string_view s) { + return s.empty() || s == "~" || s == "null" || s == "Null" || s == "NULL"; +} + +inline int CoreBool(std::string_view s) { + if (s == "true" || s == "True" || s == "TRUE") return 1; + if (s == "false" || s == "False" || s == "FALSE") return 0; + return -1; +} + +} // namespace detail + +namespace detail { +// True if a plain scalar starting with `c` may resolve to something other +// than a string under the core schema (the cases of ResolvePlainScalar's +// switch below; keep kNonStringStart in sync with them). +inline bool MayResolveToNonString(char c) { return Has(c, kNonStringStart); } +} // namespace detail + +inline ScalarValue ResolvePlainScalar(std::string_view s) { + ScalarValue v; + if (s.empty()) { + v.kind = ScalarKind::kNull; + return v; + } + switch (s[0]) { + case '~': + case 'n': + case 'N': + if (detail::IsCoreNull(s)) v.kind = ScalarKind::kNull; + return v; + case 't': + case 'T': + case 'f': + case 'F': { + const int b = detail::CoreBool(s); + if (b >= 0) { + v.kind = ScalarKind::kBool; + v.boolean = b == 1; + } + return v; + } + case '-': + case '+': + case '.': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (detail::ResolveInt(s, &v) || detail::ResolveFloat(s, &v)) return v; + v = ScalarValue(); + return v; + default: + return v; + } +} + +inline ResolveStatus ResolveScalar(std::string_view value, ScalarStyle style, + std::string_view tag, ScalarValue* out) { + *out = ScalarValue(); + if (tag.empty()) { + if (style == ScalarStyle::kPlain) *out = ResolvePlainScalar(value); + return ResolveStatus::kOk; + } + if (tag == "!") return ResolveStatus::kOk; + if (tag.substr(0, kCoreTagPrefix.size()) != kCoreTagPrefix) { + return ResolveStatus::kUnknownTag; + } + const std::string_view type = tag.substr(kCoreTagPrefix.size()); + if (type == "str") return ResolveStatus::kOk; + if (type == "null") { + if (!detail::IsCoreNull(value)) return ResolveStatus::kInvalid; + out->kind = ScalarKind::kNull; + return ResolveStatus::kOk; + } + if (type == "bool") { + const int b = detail::CoreBool(value); + if (b < 0) return ResolveStatus::kInvalid; + out->kind = ScalarKind::kBool; + out->boolean = b == 1; + return ResolveStatus::kOk; + } + if (type == "int") { + if (!detail::ResolveInt(value, out)) { + *out = ScalarValue(); + return ResolveStatus::kInvalid; + } + return ResolveStatus::kOk; + } + if (type == "float") { + ScalarValue v; + if (detail::ResolveFloat(value, &v)) { + *out = v; + return ResolveStatus::kOk; + } + if (detail::ResolveInt(value, &v)) { + out->kind = ScalarKind::kFloat; + out->number = v.number; + return ResolveStatus::kOk; + } + return ResolveStatus::kInvalid; + } + return ResolveStatus::kUnknownTag; +} + +template +Result Parse(std::string_view input, Handler& handler, + const ParseOptions& options) { + Result result; + std::string storage; + std::string_view text; + if (!detail::PrepareInput(input, &storage, &text, &result)) return result; + detail::Parser parser(text, handler, options); + return parser.Run(); +} + +} // namespace igname + +#endif // IGNAME_IGNAME_HPP_ diff --git a/deps/igname/unofficial.gni b/deps/igname/unofficial.gni new file mode 100644 index 00000000000..6c8013c0feb --- /dev/null +++ b/deps/igname/unofficial.gni @@ -0,0 +1,21 @@ +# This file is used by GN for building, which is NOT the build system used for +# building official binaries. +# Please edit the gyp files if you are making changes to build system. + +# The actual configurations are put inside a template in unofficial.gni to +# prevent accidental edits from contributors. +template("igname_gn_build") { + config("igname_config") { + include_dirs = [ "include" ] + } + + # igname is header-only. + source_set(target_name) { + forward_variables_from(invoker, "*") + public_configs = [ ":igname_config" ] + sources = [ + "include/igname/emitter.hpp", + "include/igname/igname.hpp", + ] + } +} diff --git a/doc/api/cli.md b/doc/api/cli.md index 293c5286aa6..1ba73783cc9 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -1760,6 +1760,16 @@ added: Enable experimental support for the worker inspection with Chrome DevTools. +### `--experimental-yaml` + + + +> Stability: 1.0 - Early development + +Enable the experimental [`node:formats/yaml`][] module. + ### `--force-context-aware` + +The input passed to [`yaml.parse()`][] is not valid YAML. The message names +the problem and its line and column. + ### `ERR_IPC_CHANNEL_CLOSED` @@ -4920,6 +4931,7 @@ An error occurred trying to allocate memory. This should never happen. [`util.parseArgs()`]: util.md#utilparseargsconfig [`v8.startupSnapshot.setDeserializeMainFunction()`]: v8.md#v8startupsnapshotsetdeserializemainfunctioncallback-data [`vfs.mount()`]: vfs.md#vfsmount +[`yaml.parse()`]: formats.md#yamlparseinput-options [`zlib`]: zlib.md [crypto digest algorithm]: crypto.md#cryptogethashes [debugger]: debugger.md diff --git a/doc/api/formats.md b/doc/api/formats.md new file mode 100644 index 00000000000..a25afb80bd4 --- /dev/null +++ b/doc/api/formats.md @@ -0,0 +1,119 @@ +# Formats + + + +The `node:formats/*` modules read data interchange formats into JavaScript +values. Each format has its own module, and each module is documented in its +own section with its own stability index. + +The modules are only available under the `node:` scheme. + +| Module | Format | +| ------------------- | ------------ | +| `node:formats/yaml` | [YAML 1.2][] | + +## YAML + + + +> Stability: 1.0 - Early development + + + +The `node:formats/yaml` module parses [YAML 1.2][] into JavaScript values. +Enable it with [`--experimental-yaml`][]: + +```mjs +import yaml from 'node:formats/yaml'; +``` + +```cjs +const yaml = require('node:formats/yaml'); +``` + +Loading the module emits an `ExperimentalWarning`. + +### `yaml.parse(input[, options])` + + + +* `input` {string|ArrayBuffer|SharedArrayBuffer|TypedArray|DataView} The YAML + text. Binary input must be UTF-8. +* `options` {Object} + * `throwIfInvalid` {boolean} Whether invalid YAML throws. When `false`, + `parse()` returns `undefined` instead. **Default:** `true`. +* Returns: {any} The value of the document. An `input` without a document + yields `null`. + +`parse()` uses the YAML 1.2 [core schema][]. Plain scalars resolve to null, +booleans, numbers or strings. For example, `yes` and `no` are strings. Quoted +and block scalars are strings unless a tag changes their type, as in +`!!int "42"`. Mappings become plain objects and sequences become arrays, as +with [`JSON.parse()`][]. + +Documents are read with YAML 1.2 rules whether or not they carry a `%YAML` +directive. A `%YAML 1.1` directive is accepted, as the specification requires, +and the document is still read as YAML 1.2: there is no YAML 1.1 compatibility +mode, so `no` and `0777` are a string and the decimal number 777. A `%YAML` +directive with a major version other than 1 throws. + +```mjs +import yaml from 'node:formats/yaml'; + +const config = yaml.parse(` +name: app +ports: + - 8080 + - 8443 +tls: true +`); +console.log(config); +// { name: 'app', ports: [ 8080, 8443 ], tls: true } + +console.log(yaml.parse('--- [1, 2]')); +// [ 1, 2 ] +``` + +Aliases to a collection refer to the same object. A collection may contain an +alias to itself, so the result can contain cycles. + +The parser applies the core tags `!!str`, `!!int`, `!!float`, `!!bool`, +`!!null`, `!!map` and `!!seq`. A tag must match its value: `!!int abc` throws +an error. Other tags leave collections unchanged and make scalars strings. +For example, `!custom 123` becomes `'123'`. + +Mapping keys become property names. Scalar keys use their string form, so +`null`, `true` and `1` become `'null'`, `'true'` and `'1'`. Collection keys use +their JSON text, with `NaN`, `Infinity` and `-Infinity` for the numbers JSON +cannot represent, and are limited to 1024 characters. Duplicate keys throw. + +`parse()` reads at most one document: an `input` with more than one, such as +`'a\n---\nb'`, is invalid. + +Invalid YAML throws an [`ERR_INVALID_YAML`][] `SyntaxError` with the line and +column, counted in characters. The parser rejects nesting deeper than 1000 +levels, lone surrogates in a string input, binary input that is not valid +UTF-8, and C0 control characters other than tab and line breaks. +Plain and block scalars must also be printable: DEL, the C1 control characters +other than NEL, U+FFFE and U+FFFF throw there. Quoted scalars accept them. + +With `throwIfInvalid: false` the parser returns `undefined` instead of +building an error. A document never has the value `undefined`, so the result +is unambiguous. + +```mjs +import yaml from 'node:formats/yaml'; + +console.log(yaml.parse('a: [1, 2', { throwIfInvalid: false })); +// undefined +``` + +[YAML 1.2]: https://yaml.org/spec/1.2.2/ +[`--experimental-yaml`]: cli.md#--experimental-yaml +[`ERR_INVALID_YAML`]: errors.md#err_invalid_yaml +[`JSON.parse()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse +[core schema]: https://yaml.org/spec/1.2.2/#103-core-schema diff --git a/doc/api/index.md b/doc/api/index.md index a30724c064e..9d99c62d7be 100644 --- a/doc/api/index.md +++ b/doc/api/index.md @@ -29,6 +29,7 @@ * [Events](events.md) * [File system](fs.md) * [FFI](ffi.md) +* [Formats](formats.md) * [Globals](globals.md) * [HTTP](http.md) * [HTTP/2](http2.md) diff --git a/doc/api/process.md b/doc/api/process.md index bec38732850..efa394970d6 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -4635,6 +4635,7 @@ Will generate an object similar to: merve: '1.0.0', cldr: '48.0', icu: '78.2', + igname: '0.1.0', llhttp: '9.3.0', modules: '144', napi: '10', diff --git a/doc/contributing/maintaining/maintaining-dependencies.md b/doc/contributing/maintaining/maintaining-dependencies.md index d4ecedfee28..f3c0b55a604 100644 --- a/doc/contributing/maintaining/maintaining-dependencies.md +++ b/doc/contributing/maintaining/maintaining-dependencies.md @@ -19,6 +19,7 @@ This a list of all the dependencies: * [googletest][] * [histogram][] * [icu-small][] +* [igname][] * [inspector\_protocol][inspector_protocol] * [libffi][] * [libuv][] @@ -298,6 +299,13 @@ and Java libraries providing Unicode and Globalization support for software applications. See [maintaining-icu][] for more information. +### igname + +The [igname](https://github.com/jasnell/igname) dependency is a C++ YAML 1.2 +parser and emitter. It is used by the `node:formats/yaml` module. +It has no releases yet: `tools/dep_updaters/update-igname.sh` vendors the +latest commit of its main branch. + ### inspector\_protocol The [inspector\_protocol](https://chromium.googlesource.com/deps/inspector_protocol/) @@ -461,6 +469,7 @@ according to [RFC 8878](https://datatracker.ietf.org/doc/html/rfc8878). [googletest]: #googletest [histogram]: #histogram [icu-small]: #icu-small +[igname]: #igname [inspector_protocol]: #inspector_protocol [libffi]: #libffi [libuv]: #libuv diff --git a/doc/node-config-schema.json b/doc/node-config-schema.json index 098bae8efd3..856e1824016 100644 --- a/doc/node-config-schema.json +++ b/doc/node-config-schema.json @@ -403,6 +403,10 @@ "type": "boolean", "description": "experimental Web Storage API" }, + "experimental-yaml": { + "type": "boolean", + "description": "experimental node:formats/yaml module" + }, "extra-info-on-fatal-exception": { "type": "boolean", "description": "hide extra information on fatal exception that causes exit" diff --git a/doc/node.1 b/doc/node.1 index c7b49c61603..dba720e9d3d 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -959,6 +959,9 @@ Enable experimental WebAssembly System Interface (WASI) support. .It Fl -experimental-worker-inspection Enable experimental support for the worker inspection with Chrome DevTools. . +.It Fl -experimental-yaml +Enable the experimental \fBnode:formats/yaml\fR module. +. .It Fl -force-context-aware Disable loading native addons that are not context-aware. . @@ -2370,6 +2373,8 @@ one is included in the list below. .It \fB--experimental-websocket\fR .It +\fB--experimental-yaml\fR +.It \fB--force-context-aware\fR .It \fB--force-fips\fR diff --git a/lib/formats/yaml.js b/lib/formats/yaml.js new file mode 100644 index 00000000000..2f923c51f13 --- /dev/null +++ b/lib/formats/yaml.js @@ -0,0 +1,78 @@ +'use strict'; + +const { + NumberPrototypeToString, + StringPrototypeCharCodeAt, + StringPrototypeIsWellFormed, +} = primordials; + +const { + codes: { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_YAML, + }, +} = require('internal/errors'); +const { emitExperimentalWarning, kEmptyObject } = require('internal/util'); +const { validateBoolean, validateObject } = require('internal/validators'); +const { + isAnyArrayBuffer, + isArrayBufferView, +} = require('internal/util/types'); +const { parse: parseYAML } = internalBinding('yaml'); + +emitExperimentalWarning('YAML'); + +// A string is passed to the parser as UTF-8, where a lone surrogate would +// silently become U+FFFD. Binary input is validated by the parser. +function throwLoneSurrogate(text) { + let line = 1; + let column = 1; + // A leading byte order mark is not part of the first line. + for (let i = StringPrototypeCharCodeAt(text, 0) === 0xFEFF ? 1 : 0; i < text.length; i++) { + const c = StringPrototypeCharCodeAt(text, i); + if (c >= 0xD800 && c <= 0xDBFF) { + const next = StringPrototypeCharCodeAt(text, i + 1); + if (next >= 0xDC00 && next <= 0xDFFF) { + i++; + column++; + continue; + } + } + if (c >= 0xD800 && c <= 0xDFFF) { + throw new ERR_INVALID_YAML( + `Character U+${NumberPrototypeToString(c, 16)} is not allowed in YAML ` + + `(line ${line}, column ${column})`); + } + if (c === 0x0A || (c === 0x0D && StringPrototypeCharCodeAt(text, i + 1) !== 0x0A)) { + line++; + column = 1; + } else { + column++; + } + } +} + +/** + * Parses YAML text that holds at most one document, and returns its value. + * @param {string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView} input + * @param {{ throwIfInvalid?: boolean }} [options] + * @returns {unknown} + */ +function parse(input, options = kEmptyObject) { + if (typeof input !== 'string' && !isArrayBufferView(input) && !isAnyArrayBuffer(input)) { + throw new ERR_INVALID_ARG_TYPE( + 'input', ['string', 'ArrayBuffer', 'SharedArrayBuffer', 'ArrayBufferView'], input); + } + validateObject(options, 'options'); + const { throwIfInvalid = true } = options; + validateBoolean(throwIfInvalid, 'options.throwIfInvalid'); + if (typeof input === 'string' && !StringPrototypeIsWellFormed(input)) { + if (throwIfInvalid) throwLoneSurrogate(input); + return undefined; + } + return parseYAML(input, throwIfInvalid); +} + +module.exports = { + parse, +}; diff --git a/lib/internal/bootstrap/realm.js b/lib/internal/bootstrap/realm.js index 0160012fed2..755c25a11a8 100644 --- a/lib/internal/bootstrap/realm.js +++ b/lib/internal/bootstrap/realm.js @@ -199,6 +199,7 @@ const builtinModulePolicies = [ ['bench/reporters', true, '--experimental-bench'], ['dtls', true, '--experimental-dtls'], ['ffi', true, '--experimental-ffi'], + ['formats/yaml', true, '--experimental-yaml'], ['sea', true, null], ['sqlite', true, null], ['quic', true, '--experimental-quic'], diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 83731d42d12..53687ace196 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1665,6 +1665,7 @@ E('ERR_INVALID_URL_SCHEME', `of scheme ${expected[0]}`; return `The URL must be ${res}`; }, TypeError); +E('ERR_INVALID_YAML', '%s', SyntaxError); E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed', Error); E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected', Error); E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe', Error); diff --git a/node.gyp b/node.gyp index 3d7c29c6bdb..fa0f23e2f71 100644 --- a/node.gyp +++ b/node.gyp @@ -184,6 +184,7 @@ 'src/node_wasm_web_api.cc', 'src/node_watchdog.cc', 'src/node_worker.cc', + 'src/node_yaml.cc', 'src/node_zlib.cc', 'src/path.cc', 'src/permission/env_permission.cc', @@ -835,6 +836,7 @@ ], 'dependencies': [ 'node_js2c#host', + 'deps/igname/igname.gyp:igname', ], 'sources': [ diff --git a/src/node_binding.cc b/src/node_binding.cc index b4560045eba..917fd1aad58 100644 --- a/src/node_binding.cc +++ b/src/node_binding.cc @@ -115,6 +115,7 @@ V(wasm_web_api) \ V(watchdog) \ V(worker) \ + V(yaml) \ V(zlib) #define NODE_BUILTIN_BINDINGS(V) \ diff --git a/src/node_builtins.cc b/src/node_builtins.cc index 21af988c95d..ea6911d4e13 100644 --- a/src/node_builtins.cc +++ b/src/node_builtins.cc @@ -162,6 +162,7 @@ BuiltinLoader::BuiltinCategories BuiltinLoader::GetBuiltinCategories() const { "bench/reporters", // Experimental. "dtls", // Experimental. "ffi", // Experimental. + "formats/yaml", // Experimental. "quic", // Experimental. "sqlite", // Experimental. "stream/iter", // Experimental. diff --git a/src/node_errors.h b/src/node_errors.h index 2e44642fe1b..d8313df5cd7 100644 --- a/src/node_errors.h +++ b/src/node_errors.h @@ -111,6 +111,7 @@ void OOMErrorHandler(const char* location, const v8::OOMDetails& details); V(ERR_INVALID_URL, TypeError) \ V(ERR_INVALID_URL_PATTERN, TypeError) \ V(ERR_INVALID_URL_SCHEME, TypeError) \ + V(ERR_INVALID_YAML, SyntaxError) \ V(ERR_LOAD_SQLITE_EXTENSION, Error) \ V(ERR_MEMORY_ALLOCATION_FAILED, RangeError) \ V(ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE, Error) \ diff --git a/src/node_external_reference.h b/src/node_external_reference.h index abdf6a36cbc..b4f3ea73f6a 100644 --- a/src/node_external_reference.h +++ b/src/node_external_reference.h @@ -117,7 +117,8 @@ class ExternalReferenceRegistry { V(v8) \ V(zlib) \ V(wasm_web_api) \ - V(worker) + V(worker) \ + V(yaml) #if NODE_HAVE_I18N_SUPPORT #define EXTERNAL_REFERENCE_BINDING_LIST_I18N(V) V(icu) diff --git a/src/node_metadata.cc b/src/node_metadata.cc index 44d9de8abd6..31169b11dee 100644 --- a/src/node_metadata.cc +++ b/src/node_metadata.cc @@ -4,6 +4,7 @@ #include "amaro_version.h" #include "ares.h" #include "brotli/encode.h" +#include "igname/igname.hpp" #include "llhttp.h" #include "merve.h" #include "nbytes.h" @@ -143,6 +144,8 @@ Metadata::Versions::Versions() { acorn = ACORN_VERSION; merve = MERVE_VERSION; + igname = NODE_STRINGIFY(IGNAME_VERSION_MAJOR) "." NODE_STRINGIFY( + IGNAME_VERSION_MINOR) "." NODE_STRINGIFY(IGNAME_VERSION_PATCH); uvwasi = UVWASI_VERSION_STRING; zstd = ZSTD_VERSION_STRING; diff --git a/src/node_metadata.h b/src/node_metadata.h index 57043a0356c..72d44c56a8a 100644 --- a/src/node_metadata.h +++ b/src/node_metadata.h @@ -64,7 +64,8 @@ namespace node { V(nghttp3) \ NODE_VERSIONS_KEY_AMARO(V) \ NODE_VERSIONS_KEY_UNDICI(V) \ - V(merve) + V(merve) \ + V(igname) #if HAVE_OPENSSL #define NODE_VERSIONS_KEY_CRYPTO(V) V(openssl) V(ncrypto) diff --git a/src/node_options.cc b/src/node_options.cc index cece3acc4a9..acb072176e6 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -819,6 +819,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { BOOL_FIELD(experimental_vfs), kAllowedInEnvvar, true); + AddOption("--experimental-yaml", + "experimental node:formats/yaml module", + BOOL_FIELD(experimental_yaml), + kAllowedInEnvvar); // Choosing the entry point is the command line's alone: an environment // variable must not be able to redirect what a `node ` invocation runs, // so this is rejected in NODE_OPTIONS. The source and whether to run from it diff --git a/src/node_options.h b/src/node_options.h index 6392c39cd3d..276610291ff 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -219,6 +219,7 @@ class EnvironmentOptions : public Options { DEFINE_BOOL_FIELD(experimental_websocket) = true; DEFINE_BOOL_FIELD(experimental_stream_iter) = EXPERIMENTALS_DEFAULT_VALUE; DEFINE_BOOL_FIELD(experimental_vfs) = true; + DEFINE_BOOL_FIELD(experimental_yaml) = EXPERIMENTALS_DEFAULT_VALUE; DEFINE_BOOL_FIELD(vfs_load) = false; DEFINE_BOOL_FIELD(sea_vfs) = false; DEFINE_BOOL_FIELD(webstorage) = HAVE_SQLITE; diff --git a/src/node_yaml.cc b/src/node_yaml.cc new file mode 100644 index 00000000000..2a8fe8326e4 --- /dev/null +++ b/src/node_yaml.cc @@ -0,0 +1,653 @@ +#include "env-inl.h" +#include "node_errors.h" +#include "node_external_reference.h" +#include "util-inl.h" +#include "v8.h" + +#include "igname/igname.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace node { +namespace yaml { + +using v8::Array; +using v8::Boolean; +using v8::Context; +using v8::FunctionCallbackInfo; +using v8::Isolate; +using v8::JSON; +using v8::Local; +using v8::LocalVector; +using v8::Name; +using v8::NewStringType; +using v8::Null; +using v8::Number; +using v8::Object; +using v8::String; +using v8::Value; + +namespace { + +// Nesting limit of collections, which bounds the recursion of the parser. +constexpr uint32_t kMaxDepth = 1000; +// Limit of the text of a collection used as a mapping key. Aliases can make +// a small key expand to a huge text. +constexpr int kMaxKeyLength = 1024; +// Mappings with more keys than this use a hash table to find duplicates. +constexpr size_t kLinearKeySearch = 16; + +// Returns the first character of `text` that is outside of the printable +// characters of YAML 1.2 (DEL, the C1 control characters other than NEL, +// U+FFFE and U+FFFF), or 0. The parser already rejects the C0 control +// characters. +uint32_t FindNonPrintable(std::string_view text) { + const size_t length = text.size(); + for (size_t i = 0; i < length; i++) { + const uint8_t c = static_cast(text[i]); + if (c < 0x7F) continue; + if (c == 0x7F) return c; + if (c == 0xC2 && i + 1 < length) { + const uint8_t next = static_cast(text[i + 1]); + if (next >= 0x80 && next <= 0x9F && next != 0x85) return next; + } else if (c == 0xEF && i + 2 < length && + static_cast(text[i + 1]) == 0xBF) { + const uint8_t last = static_cast(text[i + 2]); + if (last == 0xBE) return 0xFFFE; + if (last == 0xBF) return 0xFFFF; + } + } + return 0; +} + +constexpr std::string_view kScalarTags[] = { + "str", "int", "float", "bool", "null"}; + +// Builds JavaScript values from the events of the parser, without an +// intermediate tree. The children of the collections being read are kept on +// two stacks, and each collection is created when it ends. +class ValueBuilder : public igname::BaseHandler { + public: + ValueBuilder(Isolate* isolate, Local context) + : isolate_(isolate), + context_(context), + names_(isolate), + values_(isolate), + anchored_(isolate) {} + + bool OnDocumentStart(bool) { + // The start of a document has no position: a second document is reported + // at its first node. + extra_document_ = !values_.empty(); + return true; + } + + bool OnSequenceStart(igname::CollectionStyle, const igname::NodeInfo& info) { + return StartCollection(false, info); + } + + bool OnMappingStart(igname::CollectionStyle, const igname::NodeInfo& info) { + return StartCollection(true, info); + } + + bool OnSequenceEnd() { + Frame frame = std::move(frames_.back()); + frames_.pop_back(); + const size_t length = values_.size() - frame.values_start; + Local* items = values_.data() + frame.values_start; + Local result; + if (frame.eager) { + // The array exists since the start of the sequence: an alias inside + // the sequence may refer to it. + Local array = values_[frame.values_start - 1].As(); + for (size_t i = 0; i < length; i++) { + if (array + ->CreateDataProperty( + context_, static_cast(i), items[i]) + .IsNothing()) { + return false; + } + } + result = array; + values_.resize(frame.values_start - 1); + } else { + result = Array::New(isolate_, items, length); + values_.resize(frame.values_start); + } + return AddNode(result, frame.mark); + } + + bool OnMappingEnd() { + Frame frame = std::move(frames_.back()); + frames_.pop_back(); + const size_t length = values_.size() - frame.values_start; + Local* names = names_.data() + frame.names_start; + Local* values = values_.data() + frame.values_start; + // An anchored mapping exists since its start: an alias inside the mapping + // may refer to it. + Local object = frame.eager + ? values_[frame.values_start - 1].As() + : Object::New(isolate_); + // The properties are defined on the object, so that accessors and + // read-only properties of Object.prototype are not involved. Adding them + // one by one keeps the object in fast mode, unlike the Object::New() + // overload that takes the names and the values. + for (size_t i = 0; i < length; i++) { + if (object->CreateDataProperty(context_, names[i], values[i]) + .IsNothing()) { + return false; + } + } + values_.resize(frame.values_start - (frame.eager ? 1 : 0)); + names_.resize(frame.names_start); + return AddNode(object, frame.mark); + } + + bool OnScalar(std::string_view text, + igname::ScalarStyle style, + const igname::NodeInfo& info) { + if (extra_document_) return FailExtraDocument(info.mark); + // Quoted scalars may hold any character other than the C0 control + // characters. Plain and block scalars are limited to printable ones. + if (style != igname::ScalarStyle::kSingleQuoted && + style != igname::ScalarStyle::kDoubleQuoted) { + const uint32_t c = FindNonPrintable(text); + if (c != 0) { + char hex[16]; + snprintf(hex, sizeof(hex), "%x", c); + return Fail( + info.mark, + std::string("Character U+") + hex + " is not allowed in YAML"); + } + } + + igname::ScalarValue scalar; + switch (igname::ResolveScalar(text, style, info.tag, &scalar)) { + case igname::ResolveStatus::kOk: + break; + case igname::ResolveStatus::kInvalid: + return Fail( + info.mark, + "\"" + std::string(text) + "\" is not " + TagTypeName(info.tag)); + case igname::ResolveStatus::kUnknownTag: + if (IsCoreTag(info.tag, "map") || IsCoreTag(info.tag, "seq")) { + return Fail(info.mark, + "Tag " + std::string(info.tag) + + " cannot be applied to a scalar"); + } + break; + } + + // The common case of a mapping key: a string without an anchor. Keys are + // internalized, which ToV8Value() does not do. + if (scalar.kind == igname::ScalarKind::kString && info.anchor.empty() && + ExpectsKey()) { + Local name; + if (!NewKey(text).ToLocal(&name)) return false; + return AddKey(name, info.mark); + } + + Local value; + switch (scalar.kind) { + case igname::ScalarKind::kNull: + value = Null(isolate_); + break; + case igname::ScalarKind::kBool: + value = Boolean::New(isolate_, scalar.boolean); + break; + case igname::ScalarKind::kInt: + value = + Number::New(isolate_, + scalar.overflow ? scalar.number + : static_cast(scalar.integer)); + break; + case igname::ScalarKind::kFloat: + value = Number::New(isolate_, scalar.number); + break; + case igname::ScalarKind::kString: + if (!ToV8Value(context_, text, isolate_).ToLocal(&value)) return false; + break; + } + if (!info.anchor.empty()) SetAnchor(info.anchor, value); + return AddNode(value, info.mark); + } + + bool OnAlias(std::string_view name, const igname::Mark& mark) { + if (extra_document_) return FailExtraDocument(mark); + auto it = anchors_.find(std::string(name)); + if (it == anchors_.end()) { + return Fail(mark, "Unknown anchor \"" + std::string(name) + "\""); + } + return AddNode(anchored_[it->second], mark); + } + + // The value of the document, if the input has one. + bool has_document() const { return !values_.empty(); } + Local document() const { return values_[0]; } + + // Set when a handler stopped the parser because the input is invalid, as + // opposed to a pending JavaScript exception. + bool failed() const { return failed_; } + const std::string& message() const { return message_; } + const igname::Mark& mark() const { return mark_; } + + private: + struct Frame { + bool mapping; + // Whether the next node of the mapping is a key. + bool expect_key; + // Whether the collection was created when it started, because it has an + // anchor. It is then the value below `values_start`. + bool eager; + size_t names_start; + size_t values_start; + igname::Mark mark; + // Identity hashes of the keys, for mappings with many keys. + std::unique_ptr> seen; + }; + + static bool IsCoreTag(std::string_view tag, std::string_view name) { + return tag.size() == igname::kCoreTagPrefix.size() + name.size() && + tag.starts_with(igname::kCoreTagPrefix) && tag.ends_with(name); + } + + static const char* TagTypeName(std::string_view tag) { + if (IsCoreTag(tag, "int")) return "an integer"; + if (IsCoreTag(tag, "float")) return "a float"; + if (IsCoreTag(tag, "bool")) return "a boolean"; + return "null"; + } + + bool Fail(const igname::Mark& mark, std::string message) { + failed_ = true; + message_ = std::move(message); + mark_ = mark; + return false; + } + + bool FailExtraDocument(const igname::Mark& mark) { + return Fail(mark, "The input holds more than one document"); + } + + bool ExpectsKey() const { + return !frames_.empty() && frames_.back().mapping && + frames_.back().expect_key; + } + + // Property names are internalized, so that duplicate keys are found by + // comparing identities. V8 returns an empty handle without an exception + // for a text that is too long for a string. + v8::MaybeLocal NewKey(std::string_view text) { + if (text.size() >= static_cast(String::kMaxLength)) [[unlikely]] { + ThrowErrStringTooLong(isolate_); + return {}; + } + return String::NewFromUtf8(isolate_, + text.data(), + NewStringType::kInternalized, + static_cast(text.size())); + } + + void SetAnchor(std::string_view name, Local value) { + anchors_[std::string(name)] = anchored_.size(); + anchored_.push_back(value); + } + + bool StartCollection(bool mapping, const igname::NodeInfo& info) { + if (extra_document_) return FailExtraDocument(info.mark); + if (info.tag.starts_with(igname::kCoreTagPrefix)) { + const std::string_view name = + info.tag.substr(igname::kCoreTagPrefix.size()); + bool mismatch = name == (mapping ? "seq" : "map"); + for (const std::string_view scalar_tag : kScalarTags) { + if (name == scalar_tag) mismatch = true; + } + if (mismatch) { + return Fail(info.mark, + "Tag " + std::string(info.tag) + + " cannot be applied to a " + + (mapping ? "mapping" : "sequence")); + } + } + const bool eager = !info.anchor.empty(); + if (eager) { + Local value; + if (mapping) { + value = Object::New(isolate_); + } else { + value = Array::New(isolate_); + } + SetAnchor(info.anchor, value); + values_.push_back(value); + } + frames_.push_back(Frame{mapping, + mapping, + eager, + names_.size(), + values_.size(), + info.mark, + nullptr}); + return true; + } + + // Adds a complete node to the collection being read, as a key or a value, + // or as a document when there is none. + bool AddNode(Local value, const igname::Mark& mark) { + if (!ExpectsKey()) { + values_.push_back(value); + if (!frames_.empty() && frames_.back().mapping) { + frames_.back().expect_key = true; + } + return true; + } + Local name; + if (!KeyToString(value, mark).ToLocal(&name)) return false; + return AddKey(name, mark); + } + + // Mapping keys become property names: scalars as their string form, + // collections as their JSON text, with numbers in their string form too so + // that NaN and the infinities do not all become null. + v8::MaybeLocal KeyToString(Local value, + const igname::Mark& mark) { + Local text; + if (value->IsObject()) { + std::string json; + int budget = kMaxKeyLength; + if (!AppendKeyJSON(value, &json, &budget)) { + if (budget < 0) { + Fail(mark, + "A collection key must not exceed " + + std::to_string(kMaxKeyLength) + " characters"); + } + return {}; + } + return NewKey(json); + } + if (!value->ToString(context_).ToLocal(&text)) return {}; + Utf8Value utf8(isolate_, text); + return NewKey(utf8.ToStringView()); + } + + bool AppendKeyText(Local part, std::string* out, int* budget) { + *budget -= part->Length(); + if (*budget < 0) return false; + Utf8Value utf8(isolate_, part); + out->append(*utf8, utf8.length()); + return true; + } + + bool AppendKeyText(char c, std::string* out, int* budget) { + if (--*budget < 0) return false; + out->push_back(c); + return true; + } + + // Returns false with a negative budget when the text is too long, and with + // a pending exception otherwise. + bool AppendKeyJSON(Local value, std::string* out, int* budget) { + if (!value->IsObject()) { + Local text; + if (value->IsNumber()) { + if (!value->ToString(context_).ToLocal(&text)) return false; + } else if (!JSON::Stringify(context_, value).ToLocal(&text)) { + return false; + } + return AppendKeyText(text, out, budget); + } + if (value->IsArray()) { + Local array = value.As(); + if (!AppendKeyText('[', out, budget)) return false; + for (uint32_t i = 0; i < array->Length(); i++) { + Local item; + if (i > 0 && !AppendKeyText(',', out, budget)) return false; + if (!array->Get(context_, i).ToLocal(&item) || + !AppendKeyJSON(item, out, budget)) { + return false; + } + } + return AppendKeyText(']', out, budget); + } + Local object = value.As(); + Local keys; + if (!object->GetOwnPropertyNames(context_).ToLocal(&keys)) return false; + if (!AppendKeyText('{', out, budget)) return false; + for (uint32_t i = 0; i < keys->Length(); i++) { + Local key; + Local key_string; + Local key_text; + Local item; + if (i > 0 && !AppendKeyText(',', out, budget)) return false; + if (!keys->Get(context_, i).ToLocal(&key) || + !key->ToString(context_).ToLocal(&key_string) || + !JSON::Stringify(context_, key_string).ToLocal(&key_text) || + !AppendKeyText(key_text, out, budget) || + !AppendKeyText(':', out, budget) || + !object->Get(context_, key).ToLocal(&item) || + !AppendKeyJSON(item, out, budget)) { + return false; + } + } + return AppendKeyText('}', out, budget); + } + + // `name` is internalized, so equal keys are the same object. + bool AddKey(Local name, const igname::Mark& mark) { + Frame& frame = frames_.back(); + const size_t count = names_.size() - frame.names_start; + bool duplicate = false; + if (count < kLinearKeySearch) { + for (size_t i = frame.names_start; i < names_.size(); i++) { + if (names_[i] == name) { + duplicate = true; + break; + } + } + } else { + if (!frame.seen) { + frame.seen = std::make_unique>(); + for (size_t i = frame.names_start; i < names_.size(); i++) { + frame.seen->emplace(names_[i]->GetIdentityHash(), i); + } + } + const int hash = name->GetIdentityHash(); + auto range = frame.seen->equal_range(hash); + for (auto it = range.first; it != range.second; ++it) { + if (names_[it->second] == name) { + duplicate = true; + break; + } + } + if (!duplicate) frame.seen->emplace(hash, names_.size()); + } + if (duplicate) { + Utf8Value utf8(isolate_, name); + return Fail(mark, + "Duplicate mapping key \"" + + std::string(*utf8, utf8.length()) + "\""); + } + names_.push_back(name); + frame.expect_key = false; + return true; + } + + Isolate* isolate_; + Local context_; + std::vector frames_; + // Keys and values of the collections being read. A frame owns the entries + // from its `names_start` and `values_start`. Below the first frame, + // `values_` holds the document. + LocalVector names_; + LocalVector values_; + // Anchors of the document, as indexes in `anchored_`. + std::unordered_map anchors_; + LocalVector anchored_; + bool extra_document_ = false; + bool failed_ = false; + std::string message_; + igname::Mark mark_; +}; + +std::string FormatError(std::string_view message, + uint32_t line, + uint32_t column) { + std::string out(message); + out += " (line "; + out += std::to_string(line); + out += ", column "; + out += std::to_string(column); + out += ")"; + return out; +} + +constexpr std::string_view kUtf8Bom = "\xEF\xBB\xBF"; + +bool IsContinuationByte(char c) { + return (static_cast(c) & 0xC0) == 0x80; +} + +// The line and the column, both starting at 1 and the column counted in +// characters, of the byte at `offset`. +igname::Mark PositionOf(std::string_view input, size_t offset) { + igname::Mark mark{1, 1}; + for (size_t i = input.starts_with(kUtf8Bom) ? kUtf8Bom.size() : 0; i < offset; + i++) { + const char c = input[i]; + if (c == '\n' || (c == '\r' && input[i + 1] != '\n')) { + mark.line++; + mark.column = 1; + } else if (c != '\r' && !IsContinuationByte(c)) { + mark.column++; + } + } + return mark; +} + +// The marks of the parser count the column in bytes. Returns the column in +// characters, as the errors of the parser itself report it. +uint32_t CharacterColumn(std::string_view input, const igname::Mark& mark) { + size_t i = input.starts_with(kUtf8Bom) ? kUtf8Bom.size() : 0; + for (uint32_t line = 1; line < mark.line && i < input.size(); i++) { + const char c = input[i]; + if (c == '\n') { + line++; + } else if (c == '\r') { + if (i + 1 < input.size() && input[i + 1] == '\n') i++; + line++; + } + } + uint32_t column = 1; + for (uint32_t bytes = 1; bytes < mark.column && i < input.size(); bytes++) { + if (!IsContinuationByte(input[i++])) column++; + } + return column; +} + +} // anonymous namespace + +// parse(input, throwIfInvalid): the value of the document, or null when there +// is none. More than one document is invalid. +// The input is a string, or UTF-8 in an ArrayBufferView, an ArrayBuffer or a +// SharedArrayBuffer. Invalid YAML throws, or returns undefined when +// throwIfInvalid is false. +void Parse(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + Isolate* isolate = env->isolate(); + CHECK(args[1]->IsBoolean()); + const bool throw_if_invalid = args[1]->IsTrue(); + + std::optional text; + std::string storage; + std::string_view input; + if (args[0]->IsString()) { + text.emplace(isolate, args[0]); + input = text->ToStringView(); + } else { + CHECK(args[0]->IsArrayBufferView() || args[0]->IsArrayBuffer() || + args[0]->IsSharedArrayBuffer()); + // The bytes are copied because shared memory can change while the parser + // reads it. The parser validates the UTF-8. + ArrayBufferViewContents contents; + contents.ReadValue(args[0]); + if (contents.length() > 0) { + storage.assign(contents.data(), contents.length()); + } + input = storage; + } + + // The input is always UTF-8. A NUL is not allowed in YAML, and a NUL or the + // byte order mark of another encoding would make the parser read the input + // as UTF-16 or UTF-32. + const size_t nul = input.find('\0'); + if (nul != std::string_view::npos) { + if (!throw_if_invalid) return; + const igname::Mark mark = PositionOf(input, nul); + THROW_ERR_INVALID_YAML( + env, + "%s", + FormatError( + "Character U+0 is not allowed in YAML", mark.line, mark.column)); + return; + } + if (input.starts_with("\xFE\xFF") || input.starts_with("\xFF\xFE")) { + if (!throw_if_invalid) return; + THROW_ERR_INVALID_YAML(env, "%s", FormatError("invalid UTF-8", 1, 1)); + return; + } + + ValueBuilder builder(isolate, env->context()); + igname::ParseOptions options; + options.max_depth = kMaxDepth; + const igname::Result result = igname::Parse(input, builder, options); + + if (!result) { + // A handler stopped because of a pending exception. + if (result.error == igname::Error::kAborted && !builder.failed()) return; + // Without throwIfInvalid the result is undefined. + if (!throw_if_invalid) return; + std::string message; + if (result.error == igname::Error::kAborted) { + message = FormatError(builder.message(), + builder.mark().line, + CharacterColumn(input, builder.mark())); + } else if (result.error == igname::Error::kDepthExceeded) { + message = FormatError( + "Nesting deeper than " + std::to_string(kMaxDepth) + " levels", + result.line, + result.column); + } else { + message = FormatError(result.message, result.line, result.column); + } + THROW_ERR_INVALID_YAML(env, "%s", message); + return; + } + + if (builder.has_document()) { + args.GetReturnValue().Set(builder.document()); + } else { + args.GetReturnValue().SetNull(); + } +} + +void Initialize(Local target, + Local unused, + Local context, + void* priv) { + SetMethod(context, target, "parse", Parse); +} + +void RegisterExternalReferences(ExternalReferenceRegistry* registry) { + registry->Register(Parse); +} + +} // namespace yaml +} // namespace node + +NODE_BINDING_CONTEXT_AWARE_INTERNAL(yaml, node::yaml::Initialize) +NODE_BINDING_EXTERNAL_REFERENCE(yaml, node::yaml::RegisterExternalReferences) diff --git a/test/parallel/test-module-builtin-experimental.js b/test/parallel/test-module-builtin-experimental.js index 444c254b4ff..597f96f270c 100644 --- a/test/parallel/test-module-builtin-experimental.js +++ b/test/parallel/test-module-builtin-experimental.js @@ -8,6 +8,7 @@ const experimentalBuiltins = [ ['bench', '--experimental-bench', true], ['bench/reporters', '--experimental-bench', true], ['dtls', '--experimental-dtls', common.hasDtls], + ['formats/yaml', '--experimental-yaml', true], ['quic', '--experimental-quic', common.hasQuic], ].filter(([, , available]) => available); diff --git a/test/parallel/test-process-get-builtin.mjs b/test/parallel/test-process-get-builtin.mjs index a4feabf5b93..7096ff20667 100644 --- a/test/parallel/test-process-get-builtin.mjs +++ b/test/parallel/test-process-get-builtin.mjs @@ -40,6 +40,8 @@ publicBuiltins.delete('node:dtls'); publicBuiltins.delete('node:quic'); // Remove this once node:vfs graduates from unflagged. publicBuiltins.delete('node:vfs'); +// Remove this once node:formats/yaml graduates from unflagged. +publicBuiltins.delete('node:formats/yaml'); if (!hasInspector) { publicBuiltins.delete('inspector'); diff --git a/test/parallel/test-process-versions.js b/test/parallel/test-process-versions.js index c6eb09693cd..650df49b494 100644 --- a/test/parallel/test-process-versions.js +++ b/test/parallel/test-process-versions.js @@ -25,6 +25,7 @@ const expected_keys = [ 'ada', 'nbytes', 'merve', + 'igname', ]; @@ -77,6 +78,7 @@ const commonTemplate = /^\d+\.\d+\.\d+(?:-.*)?$/; assert.match(process.versions.acorn, commonTemplate); assert.match(process.versions.ares, commonTemplate); assert.match(process.versions.brotli, commonTemplate); +assert.match(process.versions.igname, commonTemplate); assert.match(process.versions.llhttp, commonTemplate); assert.match(process.versions.merve, commonTemplate); assert.match(process.versions.node, commonTemplate); diff --git a/test/parallel/test-require-resolve.js b/test/parallel/test-require-resolve.js index 984afa78a1a..f541b37940c 100644 --- a/test/parallel/test-require-resolve.js +++ b/test/parallel/test-require-resolve.js @@ -62,6 +62,8 @@ require(fixtures.path('resolve-paths', 'default', 'verify-paths.js')); builtinModules.forEach((mod) => { // TODO(@jasnell): Remove once node:quic is no longer flagged if (mod === 'node:quic') return; + // Remove once node:formats/yaml is no longer flagged + if (mod === 'node:formats/yaml') return; if (mod === 'node:sqlite' && !common.hasSQLite) return; assert.strictEqual(require.resolve.paths(mod), null); if (!mod.startsWith('node:')) { diff --git a/test/parallel/test-yaml.js b/test/parallel/test-yaml.js new file mode 100644 index 00000000000..184526ba443 --- /dev/null +++ b/test/parallel/test-yaml.js @@ -0,0 +1,376 @@ +// Flags: --experimental-yaml +'use strict'; + +// Tests what node:formats/yaml adds on top of the igname parser: the +// JavaScript values, mapping keys, aliases, tags, documents, input types and +// errors. The YAML syntax itself is covered by the tests of igname. + +const common = require('../common'); +const assert = require('node:assert'); +const { parse } = require('node:formats/yaml'); + +common.expectWarning('ExperimentalWarning', 'YAML is an experimental feature and might change at any time'); + +// Scalars of the core schema become JavaScript values. +assert.deepStrictEqual(parse(` +nothing: ~ +empty: +yes: true +no: FALSE +int: -42 +hex: 0x1F +octal: 0o17 +float: 1.5e3 +inf: -.inf +str: yes +quoted: "0x10" +`), { + nothing: null, + empty: null, + yes: true, + no: false, + int: -42, + hex: 31, + octal: 15, + float: 1500, + inf: -Infinity, + str: 'yes', + quoted: '0x10', +}); +assert.ok(Number.isNaN(parse('.nan'))); +assert.deepStrictEqual(parse('[-0, -0.0, +3, 9223372036854775808]'), [0, -0, 3, 9223372036854775808]); +assert.strictEqual(parse('"\u00e9 \u{1F600}"'), '\u00e9 \u{1F600}'); + +// Collections. +assert.deepStrictEqual(parse(` +- a +- - nested + - seq +- key: value + other: 2 +- [1, 2, {x: y}] +- [a: 1, b] +`), [ + 'a', + ['nested', 'seq'], + { key: 'value', other: 2 }, + [1, 2, { x: 'y' }], + [{ a: 1 }, 'b'], +]); + +// Scalar keys use the string form of their value. +assert.deepStrictEqual( + parse('{0x1F: a, 1.0: b, True: c, Null: d, 9223372036854775808: e, "quoted": f}'), + { '31': 'a', '1': 'b', 'true': 'c', 'null': 'd', '9223372036854776000': 'e', 'quoted': 'f' }); + +// Collection keys become their JSON text. +assert.deepStrictEqual(parse('? [a, b]\n: c\n{x: 1}: d'), + { '["a","b"]': 'c', '{"x":1}': 'd' }); +// Numbers that JSON has no text for stay distinct from null and from strings. +assert.deepStrictEqual( + parse('? [.nan]\n: a\n? [~]\n: b\n? [.inf, -.inf, "NaN"]\n: c\n? {k: .nan}\n: d'), + { '[NaN]': 'a', '[null]': 'b', '[Infinity,-Infinity,"NaN"]': 'c', '{"k":NaN}': 'd' }); +assert.throws(() => parse('? [.nan]\n: a\n? [.NaN]\n: b'), + { code: 'ERR_INVALID_YAML', message: /Duplicate mapping key "\[NaN\]" \(line 3, column 3\)/ }); + +// A collection key is bounded, so aliases cannot blow it up. +{ + let yaml = 'a0: &a0 [x, x, x, x, x, x, x, x, x, x]\n'; + for (let i = 1; i < 12; i++) { + const prev = `*a${i - 1}`; + yaml += `a${i}: &a${i} [${Array(10).fill(prev).join(', ')}]\n`; + } + assert.throws(() => parse(`${yaml}? *a11\n: 1\n`), { + code: 'ERR_INVALID_YAML', + message: /A collection key must not exceed 1024 characters \(line 13, column \d+\)/, + }); + assert.strictEqual(parse(yaml).a11.length, 10); + // A key that contains itself. + assert.throws(() => parse('? &a [*a]\n: 1'), { + code: 'ERR_INVALID_YAML', + message: /A collection key must not exceed 1024 characters/, + }); +} + +// Duplicate keys throw, in mappings of any size. +assert.throws(() => parse('a: 1\na: 2'), + { code: 'ERR_INVALID_YAML', message: /Duplicate mapping key "a" \(line 2, column 1\)/ }); +assert.throws(() => parse('{1: a, 0x1: b}'), + { code: 'ERR_INVALID_YAML', message: /Duplicate mapping key "1"/ }); +assert.throws(() => parse('"50%s %d": 1\n"50%s %d": 2'), + { code: 'ERR_INVALID_YAML', message: /Duplicate mapping key "50%s %d" \(line 2, column 1\)/ }); +assert.throws(() => parse('[a]: 1\n[a]: 2'), + { code: 'ERR_INVALID_YAML', message: /Duplicate mapping key "\["a"\]"/ }); +{ + let yaml = ''; + for (let i = 0; i < 100; i++) yaml += `key${i}: ${i}\n`; + const value = parse(yaml); + assert.strictEqual(Object.keys(value).length, 100); + assert.strictEqual(value.key99, 99); + for (const key of ['key0', 'key16', 'key99']) { + assert.throws(() => parse(`${yaml}${key}: again\n`), { + code: 'ERR_INVALID_YAML', + message: new RegExp(`Duplicate mapping key "${key}" \\(line 101, column 1\\)`), + }); + } + // A mapping inside a large mapping has its own keys. + assert.deepStrictEqual(parse(`${yaml}nested: {key0: 1, key1: 2}\n`).nested, { key0: 1, key1: 2 }); +} + +// Prototype keys are own properties, as with JSON.parse(). +{ + const value = parse('__proto__: 1\nconstructor: 2\n'); + assert.strictEqual(Object.getPrototypeOf(value), Object.prototype); + assert.deepStrictEqual(Object.keys(value), ['__proto__', 'constructor']); + assert.strictEqual(Object.getOwnPropertyDescriptor(value, '__proto__').value, 1); + const anchored = parse('&a\n__proto__: 1\nself: *a\n'); + assert.strictEqual(Object.getPrototypeOf(anchored), Object.prototype); + assert.strictEqual(Object.getOwnPropertyDescriptor(anchored, '__proto__').value, 1); +} + +// Properties inherited from Object.prototype do not affect mappings. +{ + Object.defineProperty(Object.prototype, 'setter', { + __proto__: null, + get: common.mustNotCall(), + set: common.mustNotCall(), + configurable: true, + }); + Object.defineProperty(Object.prototype, 'readonly', { + __proto__: null, + value: 'inherited', + writable: false, + configurable: true, + }); + try { + const value = parse('setter: 1\nreadonly: 2\n{a: 1, setter: 2}: 3\n'); + assert.strictEqual(Object.getPrototypeOf(value), Object.prototype); + assert.deepStrictEqual(Object.keys(value), ['setter', 'readonly', '{"a":1,"setter":2}']); + assert.strictEqual(value.setter, 1); + assert.strictEqual(value.readonly, 2); + const anchored = parse('&a\nsetter: 1\nreadonly: 2\n'); + assert.deepStrictEqual(Object.keys(anchored), ['setter', 'readonly']); + assert.strictEqual(anchored.readonly, 2); + assert.throws(() => parse('readonly: 1\nreadonly: 2\n'), { code: 'ERR_INVALID_YAML' }); + } finally { + delete Object.prototype.setter; + delete Object.prototype.readonly; + } +} + +// Aliases refer to the same value, also from inside the collection. +{ + const value = parse(` +base: &base + name: base +copy: *base +list: &list + - *base + - *list +`); + assert.strictEqual(value.copy, value.base); + assert.strictEqual(value.list[0], value.base); + assert.strictEqual(value.list[1], value.list); + assert.strictEqual(value.list.length, 2); + + const flow = parse('&a [*a, {b: *a}]'); + assert.strictEqual(flow[0], flow); + assert.strictEqual(flow[1].b, flow); + const map = parse('&a {k: *a, n: 1}'); + assert.strictEqual(map.k, map); + assert.deepStrictEqual(Object.keys(map), ['k', 'n']); + + // Anchors on scalars and on keys, and aliases as keys. + assert.deepStrictEqual(parse('- &x 1\n- *x'), [1, 1]); + assert.deepStrictEqual(parse('&k key: 1\nother: *k'), { key: 1, other: 'key' }); + assert.deepStrictEqual(parse('- &n 7\n- &s [a]\n- {*n : x, *s : y}')[2], { '7': 'x', '["a"]': 'y' }); + // A later anchor of the same name replaces the earlier one. + assert.deepStrictEqual(parse('- &x 1\n- &x 2\n- *x'), [1, 2, 2]); +} +assert.throws(() => parse('*missing'), + { code: 'ERR_INVALID_YAML', message: /Unknown anchor "missing" \(line 1, column 1\)/ }); + +// Tags of the core schema are applied, other tags leave scalars as strings. +assert.deepStrictEqual( + parse('[!!str 123, !!int "42", !!int 0x1f, !!float 1, !!float .inf, !!null ~, !!bool True]'), + ['123', 42, 31, 1, Infinity, null, true]); +assert.deepStrictEqual(parse('[!custom 12, !!binary abc, ! 5]'), ['12', 'abc', '5']); +assert.strictEqual(parse('%TAG !e! tag:yaml.org,2002:\n--- !e!int "7"'), 7); +assert.deepStrictEqual(parse('[!!seq [1], !!map {a: 1}, !custom [2], !custom {b: 2}]'), + [[1], { a: 1 }, [2], { b: 2 }]); +const invalidTags = [ + ['!!int abc', /"abc" is not an integer \(line 1, column 1\)/], + ['!!int 1.0', /"1\.0" is not an integer/], + ['!!float abc', /"abc" is not a float/], + ['!!bool yes', /"yes" is not a boolean/], + ['!!null x', /"x" is not null/], + ['!!map 1', /Tag tag:yaml\.org,2002:map cannot be applied to a scalar/], + ['!!seq 1', /Tag tag:yaml\.org,2002:seq cannot be applied to a scalar/], + ['!!seq {}', /Tag tag:yaml\.org,2002:seq cannot be applied to a mapping/], + ['!!int {a: 1}', /Tag tag:yaml\.org,2002:int cannot be applied to a mapping/], + ['!!map [a]', /Tag tag:yaml\.org,2002:map cannot be applied to a sequence/], + ['!!str [a]', /Tag tag:yaml\.org,2002:str cannot be applied to a sequence/], +]; +for (const [input, message] of invalidTags) { + assert.throws(() => parse(input), { code: 'ERR_INVALID_YAML', name: 'SyntaxError', message }, input); + assert.strictEqual(parse(input, { throwIfInvalid: false }), undefined); +} + +// Documents: none is null, one is its value, more than one is invalid. +assert.strictEqual(parse(''), null); +assert.strictEqual(parse('# only a comment\n'), null); +assert.strictEqual(parse('---\n'), null); +assert.strictEqual(parse('--- text\n...\n'), 'text'); +assert.strictEqual(parse('--- text\n...\n# comment\n'), 'text'); +for (const [input, position] of [ + ['a: 1\n---\n- 2\n', 'line 3, column 1'], + ['--- 1\n--- 2\n', 'line 2, column 5'], + ['a\n--- {b: 1}', 'line 2, column 5'], + ['a: &x 1\n---\nb: *x', 'line 3, column 1'], + ['--- &x 1\n--- *x', 'line 2, column 5'], + ['a\n...\nb', 'line 3, column 1'], + ['a\n---\n', 'line 3, column 1'], + ['---\n---\n', 'line 3, column 1'], +]) { + assert.throws(() => parse(input), { + code: 'ERR_INVALID_YAML', + name: 'SyntaxError', + message: `The input holds more than one document (${position})`, + }); + assert.strictEqual(parse(input, { throwIfInvalid: false }), undefined); +} + +// Binary input is read as UTF-8. +assert.deepStrictEqual(parse(Buffer.from('caf\u00e9: 1')), { 'caf\u00e9': 1 }); +assert.deepStrictEqual(parse(new TextEncoder().encode('[1]').buffer), [1]); +{ + const bytes = new TextEncoder().encode('xx[2]yy'); + assert.deepStrictEqual(parse(new Uint8Array(bytes.buffer, 2, 3)), [2]); + assert.deepStrictEqual(parse(new DataView(bytes.buffer, 2, 3)), [2]); + const shared = new SharedArrayBuffer(3); + new Uint8Array(shared).set(bytes.subarray(2, 5)); + assert.deepStrictEqual(parse(shared), [2]); + assert.deepStrictEqual(parse(new Uint8Array(shared)), [2]); +} +assert.strictEqual(parse('\uFEFFbom'), 'bom'); +assert.strictEqual(parse(Buffer.from('\uFEFFbom')), 'bom'); +assert.strictEqual(parse(Buffer.alloc(0)), null); +assert.strictEqual(parse(new ArrayBuffer(0)), null); + +// Binary input that is not UTF-8 is invalid, including other encodings. +for (const bytes of [ + [0x61, 0x3a, 0x20, 0xff], + [0x61, 0x3a, 0x20, 0xc3, 0x28], + [0x61, 0x3a, 0x20, 0xed, 0xa0, 0x80], + [0xff, 0xfe, 0x61, 0x62], + [0xfe, 0xff, 0x61, 0x62], +]) { + assert.throws(() => parse(Buffer.from(bytes)), { + code: 'ERR_INVALID_YAML', + name: 'SyntaxError', + message: /^invalid UTF-8 \(line 1, column \d+\)$/, + }); + assert.strictEqual(parse(new Uint8Array(bytes), { throwIfInvalid: false }), undefined); +} + +// Arguments. +for (const input of [1, null, undefined, {}, [], Symbol('x')]) { + assert.throws(() => parse(input), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => parse(input, { throwIfInvalid: false }), { code: 'ERR_INVALID_ARG_TYPE' }); +} +for (const options of [null, 1, { throwIfInvalid: 'no' }]) { + assert.throws(() => parse('a: 1', options), { code: 'ERR_INVALID_ARG_TYPE' }); +} + +// Invalid YAML throws a SyntaxError with the position, or yields undefined +// without throwIfInvalid. +for (const input of ['a: [1, 2', '"open', 'a: 1\n b: 2', '%YAML 2.0\n---\na', 'a:\n\tb: 1']) { + assert.throws(() => parse(input), { + code: 'ERR_INVALID_YAML', + name: 'SyntaxError', + message: / \(line \d+, column \d+\)$/, + }, input); + assert.strictEqual(parse(input, { throwIfInvalid: false }), undefined); +} +assert.throws(() => parse('a: 1\nb: [1, 2'), { message: /\(line 2, column 9\)$/ }); + +// Columns count characters, not bytes or UTF-16 code units. +for (const [input, position] of [ + ['{a: 1, a: 2}', 'line 1, column 8'], + ['{\u00e9: 1, \u00e9: 2}', 'line 1, column 8'], + ['{\u00e9\u00e9\u00e9: 1, \u00e9\u00e9\u00e9: 2}', 'line 1, column 10'], + ['[\u00e9\u00e9\u00e9, !!int a]', 'line 1, column 7'], + ['\uFEFF{\u00e9: 1, \u00e9: 2}', 'line 1, column 8'], + ['x: 1\r\n\u00e9: [\u{1F600}, *nope]', 'line 2, column 8'], + ['a: 1\rb: 2\r\u20ac\u20ac: !!int z', 'line 3, column 5'], + ['a: 1\n\u00e9\u00e9: [\u00e9, a\x7Fb]', 'line 2, column 9'], + ['\u00e9\u00e9: [1', 'line 1, column 7'], +]) { + for (const value of [input, Buffer.from(input)]) { + assert.throws(() => parse(value), { message: new RegExp(` \\(${position}\\)$`) }, input); + } +} +assert.strictEqual(parse('a: 1\na: 2', { throwIfInvalid: false }), undefined); +assert.deepStrictEqual(parse('a: 1', { throwIfInvalid: false }), { a: 1 }); +assert.strictEqual(parse('', { throwIfInvalid: false }), null); +assert.deepStrictEqual(parse('--- [1, 2]', { throwIfInvalid: true }), [1, 2]); + +// A NUL is rejected, and never makes the input read as UTF-16 or UTF-32. +for (const input of ['a\0b\0', 'a\0', '\0a', 'a\0\0\0b\0\0\0', '\0\0\0a', '"a\0b"', 'k: v\n# \0']) { + for (const value of [input, Buffer.from(input)]) { + assert.throws(() => parse(value), { + code: 'ERR_INVALID_YAML', + name: 'SyntaxError', + message: /Character U\+0 is not allowed in YAML \(line \d+, column \d+\)/, + }); + assert.strictEqual(parse(value, { throwIfInvalid: false }), undefined); + } +} +assert.throws(() => parse('\u00e9: 1\r\nab\0'), { message: /\(line 2, column 3\)$/ }); +assert.strictEqual(parse('"\\0"'), '\0'); + +// Raw C0 control characters are rejected everywhere. +for (const c of ['\x01', '\x07', '\x1f']) { + for (const input of [`"a${c}b"`, `a${c}b`, `# ${c}`]) { + assert.throws(() => parse(input), { code: 'ERR_INVALID_YAML', name: 'SyntaxError' }); + } +} + +// DEL, the C1 control characters and the non-characters are not printable: +// they are rejected in plain and block scalars and accepted in quoted ones. +for (const [c, hex] of [['\x7f', '7f'], ['\x80', '80'], ['\x9f', '9f'], ['\ufffe', 'fffe'], ['\uffff', 'ffff']]) { + const expected = { + code: 'ERR_INVALID_YAML', + name: 'SyntaxError', + message: new RegExp(`Character U\\+${hex} is not allowed in YAML \\(line \\d+, column \\d+\\)`), + }; + for (const input of [`a${c}b`, `k: a${c}b`, `a${c}b: 1`, `[a${c}b]`, `|\n a${c}b`, `>\n a${c}b`, `caf\u00e9${c}`]) { + assert.throws(() => parse(input), expected); + assert.strictEqual(parse(input, { throwIfInvalid: false }), undefined); + } + assert.strictEqual(parse(`"a${c}b"`), `a${c}b`); + assert.strictEqual(parse(`'a${c}b'`), `a${c}b`); +} +// NEL, the other characters above U+009F and escapes are accepted. +assert.strictEqual(parse('a\u0085b \u00a0\u00e9\ufffd\u{1F600}'), 'a\u0085b \u00a0\u00e9\ufffd\u{1F600}'); +assert.strictEqual(parse('"\\x7f\\x9f\\uFFFE"'), '\x7f\x9f\ufffe'); + +// Lone surrogates of a string input are reported with their position. +assert.strictEqual(parse('"\ud83d\ude00"'), '\ud83d\ude00'); +for (const lone of ['\ud83d', '\ude00', '\ude00\ud83d', '\ud83d\ud83d']) { + assert.throws(() => parse(`"${lone}"`), + { code: 'ERR_INVALID_YAML', message: /Character U\+d(83d|e00) is not allowed in YAML/ }); +} +assert.throws(() => parse('a: "\u{1F600}"\r\nb: "\ud83d"'), + { code: 'ERR_INVALID_YAML', message: /Character U\+d83d is not allowed in YAML \(line 2, column 5\)/ }); +assert.throws(() => parse('a\rb\n\ude00'), + { code: 'ERR_INVALID_YAML', message: /Character U\+de00 is not allowed in YAML \(line 3, column 1\)/ }); +assert.throws(() => parse('\uFEFFa\ud800'), + { code: 'ERR_INVALID_YAML', message: /Character U\+d800 is not allowed in YAML \(line 1, column 2\)/ }); +assert.strictEqual(parse('"\ud83d"', { throwIfInvalid: false }), undefined); + +// Deep nesting is bounded. +assert.throws(() => parse('['.repeat(1001) + ']'.repeat(1001)), + { code: 'ERR_INVALID_YAML', message: /Nesting deeper than 1000 levels/ }); +assert.ok(Array.isArray(parse('['.repeat(1000) + ']'.repeat(1000)))); +assert.strictEqual(parse('['.repeat(1001) + ']'.repeat(1001), { throwIfInvalid: false }), undefined); diff --git a/tools/dep_updaters/update-igname.sh b/tools/dep_updaters/update-igname.sh new file mode 100755 index 00000000000..598b390a0f8 --- /dev/null +++ b/tools/dep_updaters/update-igname.sh @@ -0,0 +1,64 @@ +#!/bin/sh +set -e +# Shell script to update igname in the source tree to the most recent version. +# igname has no releases yet, so the latest commit on the main branch is used. + +BASE_DIR=$(cd "$(dirname "$0")/../.." && pwd) +DEPS_DIR="$BASE_DIR/deps" + +# shellcheck disable=SC1091 +. "$BASE_DIR/tools/dep_updaters/utils.sh" + +NEW_UPSTREAM_SHA1=$(git ls-remote "https://github.com/jasnell/igname.git" HEAD | awk '{print $1}') +NEW_VERSION=$(echo "$NEW_UPSTREAM_SHA1" | head -c 7) + +echo "Making temporary workspace..." + +WORKSPACE=$(mktemp -d 2> /dev/null || mktemp -d -t 'tmp') + +cleanup () { + EXIT_CODE=$? + [ -d "$WORKSPACE" ] && rm -rf "$WORKSPACE" + exit $EXIT_CODE +} + +trap cleanup INT TERM EXIT + +cd "$WORKSPACE" + +echo "Fetching igname source archive..." +IGNAME_TARBALL="archive-$NEW_VERSION.tar.gz" +curl -sL -o "$IGNAME_TARBALL" "https://github.com/jasnell/igname/archive/$NEW_UPSTREAM_SHA1.tar.gz" +log_and_verify_sha256sum "igname" "$IGNAME_TARBALL" +gzip -dc "$IGNAME_TARBALL" | tar xf - +mv igname-* source +rm "$IGNAME_TARBALL" + +echo "Comparing $NEW_VERSION with the current files" + +# The files that are vendored: the headers, the GYP file, the license and the +# README. +IGNAME_FILES="LICENSE README.md igname.gyp include" + +UP_TO_DATE=true +for p in $IGNAME_FILES; do + if ! diff -r "$WORKSPACE/source/$p" "$DEPS_DIR/igname/$p" > /dev/null 2>&1; then + UP_TO_DATE=false + fi +done + +if [ "$UP_TO_DATE" = "true" ]; then + echo "Skipped because igname is on the latest version." + exit 0 +fi + +echo "Replacing existing igname (except GN build files)" +for p in $IGNAME_FILES; do + rm -rf "$DEPS_DIR/igname/$p" + cp -R "$WORKSPACE/source/$p" "$DEPS_DIR/igname/$p" +done + +# Update the version number on maintaining-dependencies.md +# and print the new version as the last line of the script as we need +# to add it to $GITHUB_ENV variable +finalize_version_update "igname" "$NEW_VERSION" diff --git a/tools/license-builder.sh b/tools/license-builder.sh index 852bfca8c96..ecfb9854265 100755 --- a/tools/license-builder.sh +++ b/tools/license-builder.sh @@ -36,6 +36,8 @@ licenseText="$(cat "${rootdir}/deps/cares/LICENSE.md")" addlicense "c-ares" "deps/cares" "$licenseText" licenseText="$(cat "${rootdir}/deps/merve/LICENSE-MIT")" addlicense "merve" "deps/merve" "$licenseText" +licenseText="$(cat "${rootdir}/deps/igname/LICENSE")" +addlicense "igname" "deps/igname" "$licenseText" licenseText="$(cat "${rootdir}/deps/v8/third_party/ittapi/LICENSES/BSD-3-Clause.txt")" addlicense "ittapi" "deps/v8/third_party/ittapi" "$licenseText" licenseText="$(cat "${rootdir}/deps/amaro/LICENSE.md")" diff --git a/tools/sbom/generate_sbom.py b/tools/sbom/generate_sbom.py index 80bcf58a8e4..d82d8bf3a2b 100644 --- a/tools/sbom/generate_sbom.py +++ b/tools/sbom/generate_sbom.py @@ -609,6 +609,14 @@ def version_from_openssl(root): 'version_fn': lambda root: version_from_texi( root / 'deps/libffi/doc/version.texi'), }, + { + 'name': 'igname', + 'description': 'YAML 1.2 parser and emitter', + 'purl_base': 'pkg:github/jasnell/igname', + 'version_fn': lambda root: version_from_c_macros( + root / 'deps/igname/include/igname/igname.hpp', + 'IGNAME_VERSION_MAJOR', 'IGNAME_VERSION_MINOR', 'IGNAME_VERSION_PATCH'), + }, { 'name': 'merve', 'description': 'String interning library', diff --git a/typings/globals.d.ts b/typings/globals.d.ts index 4a7c52ab774..912e9bf5aea 100644 --- a/typings/globals.d.ts +++ b/typings/globals.d.ts @@ -49,6 +49,7 @@ import { UVBinding } from './internalBinding/uv'; import { WASIBinding } from './internalBinding/wasi'; import { WatchdogBinding } from './internalBinding/watchdog'; import { WorkerBinding } from './internalBinding/worker'; +import { YAMLBinding } from './internalBinding/yaml'; import { ZlibBinding } from './internalBinding/zlib'; interface InternalBindingMap { @@ -103,6 +104,7 @@ interface InternalBindingMap { wasi: WASIBinding; watchdog: WatchdogBinding; worker: WorkerBinding; + yaml: YAMLBinding; zlib: ZlibBinding; } diff --git a/typings/internalBinding/yaml.d.ts b/typings/internalBinding/yaml.d.ts new file mode 100644 index 00000000000..1a1153e4a15 --- /dev/null +++ b/typings/internalBinding/yaml.d.ts @@ -0,0 +1,3 @@ +export interface YAMLBinding { + parse(input: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, throwIfInvalid: boolean): unknown; +} diff --git a/unofficial.gni b/unofficial.gni index 5878f079d94..658e6ee2728 100644 --- a/unofficial.gni +++ b/unofficial.gni @@ -170,6 +170,7 @@ template("node_gn_build") { "deps/brotli", "deps/cares", "deps/histogram", + "deps/igname", "deps/llhttp", "deps/merve", "deps/nbytes",