C Collections

cyaml · Section 3

cyaml_parse_mp, cyaml_parse

cyaml_parse_mp, cyaml_parse - parse a null-terminated YAML string into a DOM tree

C Collections (libccollections, -lccollections)

#include <ccollections/cyaml.h>
 
cyaml cyaml_parse_mp(const char *yaml_str, char **err_str,
                     ccol_memmgmt_procs *mp);
cyaml cyaml_parse(const char *yaml_str, char **err_str);

Parses a null-terminated YAML string and returns the root DOM node.
Comments (#) are dropped without a trace, anchors (&name) and aliases
(*name) are resolved into independent deep clones, and an unquoted
scalar gets its type from the implicit YAML 1.2 core schema.
 
A tag (!tag, !!tag, !<verbatim>, or a shorthand from a %TAG
directive) is resolved and attached to its node, and
cyaml_node_tag(3) describes how a tag and the type of a node work
together.  A "<<" mapping key is expanded as a merge key when it is a
plain, untagged scalar or when it carries the core merge tag
(!!merge).  A mapping can hold several merge keys and every one of
them is expanded.  A merge key never becomes a member, so it never
replaces another merge key or an ordinary "<<" member.  cyaml(7)
gives the rules for the expansion and its precedence, and the rules
for anchors, aliases and tags.  The merged members take the place of
the merge key that first brings their key in the mapping's member
order; see cyaml_dictionary_first(3).  A dictionary keeps its members
in the order of the text, and a key that the text repeats has the
place of its first occurrence and the value of its last.  Three more
cases make the parse fail, like any other malformed input: A tag that
doesn't match the type of the content, a malformed %TAG directive,
and a merge-key source that is not valid.  !!null is the one
exception to the first of these, because it forces CYAML_NULL on any
text and has no canonical "wrong" spelling.
 
These are parse errors too: A plain scalar that starts with ']', '}'
or ',' outside a flow collection, a '[' or '{' inside a flow plain
scalar, a tag that holds a byte outside the URI characters of YAML
1.2 (see cyaml(7)), a %YAML directive whose major version is not 1,
and a '%' with no directive name after it.  Inside a flow collection
a comment may follow an anchor or a tag on its line, and the node
then comes on a later line.
 
SINGLE-DOCUMENT STREAMS
The input can hold exactly one document, with or without a leading
"---" marker and with or without a trailing "..." marker.  The
function then returns the root node of that document directly.
 
MULTI-DOCUMENT STREAMS
The input can hold more than one document, with "---" markers between
them.  The function then collects every document root and returns one
CYAML_LIST node whose elements are the document roots, in order.  The
anchor table is reset between two documents, so a later document
cannot name an anchor of an earlier one.  An empty document, such as
the one between two "---" markers in a row, gives a CYAML_NULL
element.
A later document can leave out its own "---" marker only when the
document right before it ended with an explicit "..." marker.  In
every other case it must start with "---", and bare content that
comes directly after a document with no "..." is a parse error.  A
document that starts with its own "%YAML" directive always needs an
explicit "..." in front of it, even when it has its own "---"
marker.
cyaml_serialize_stream(3) writes such a list back as a stream, one
document per element.
 
cyaml_parse() is an inline wrapper that passes NULL for mp.
 
On a parse failure, when err_str is not NULL, the function points
*err_str at a null-terminated error message.  The LIBRARY owns that
message, so never free it: It is not an allocation, and mp never sees
it.  The text stays readable until the next FAILING parse on the same
thread, the same lifetime that strerror(3) gives.  The storage is per
thread, so two threads that parse at the same time never overwrite
each other's message; copy the text if you need it longer.  When the
thread cannot keep a message buffer (memory runs out, or the process
has no thread-specific key left for the buffer), the message is a
fixed text that names no reason.  On success the function sets
*err_str to NULL.  Only the return value tells success from failure,
never *err_str.  Pass NULL for err_str to discard the error details.
 
The message is printable ASCII whatever the input holds.  Where it
quotes text of the input (a scalar, a tag, an anchor or alias name, a
single character), a byte from 0x20 to 0x7E is written as it is and
any other byte as <0xNN>, and a long quoted text is cut short at a
whole byte with "...".  So a raw control character, a terminal escape
sequence or a byte of a multi-byte UTF-8 sequence in the input never
reaches a log that records the message.  A character that the input
may not hold at all is named as 0xNN, with its line and column.

yaml_str   Null-terminated YAML input.
err_str    Out-parameter for the error string, or NULL to ignore it.
           The library owns that string and the caller never frees
           it.
mp         Custom allocator for every node of the tree that this
           function builds, or NULL for the default allocator.
           The library keeps its own copy of the struct, so the caller
           may release or reuse the struct once this call returns.
           The functions that it names must stay callable until the
           last node built with them is destroyed.  A process can use
           at most 64 distinct sets of four functions, and a call that
           would need a 65th fails and returns NULL.

For an input with one document, the root cyaml node.
For an input with more than one document, a CYAML_LIST node that
holds every document root.
NULL on a parse failure, or when the parser runs out of memory.

The caller owns the returned tree and must free it with
cyaml_destroy().
 
The caller does NOT own the error string.  The err and err_str
out-parameters of every module in this library follow one rule: The
library owns the string and the caller never frees it.  See the note
at the top of common.h.
 
Check the node's type with cyaml_type() to see whether the result
holds one document or more than one.
 
A plain, single-quoted or double-quoted scalar VALUE can span more
than one physical line.  Each line break folds to one space, and a
run of blank lines folds to that many newlines instead, as in a
folded block scalar.  An implicit mapping KEY is different, because
it must always fit on one physical line whatever its scalar style.
An implicit key is written "key:" with no leading "?", while an
explicit key ("? key") has no such restriction.  A sequence, mapping
or flow collection that is a dictionary key is canonicalized
directly into its flow-style text.  A scalar dictionary key gets its
core-schema type resolved before it is stored, exactly as in an
ordinary value position.  For example, "~", "null" and an empty key
all canonicalize to the identical "null" string key; "true", "True"
and "TRUE" give "true", and "false", "False" and "FALSE" give "false";
"yes", "no", "on" and "off" are strings under YAML 1.2 and keep their
own text.  An integer key gives its decimal text, so "0x10" gives
"16".  A float key gives the shortest decimal text that reads back as
the same double: "3.10" gives "3.1", "0.1" stays "0.1", "1e300" gives
"1e+300", and the subnormal "4.9406564584124654e-324" gives "5e-324",
while ".inf", "-.inf" and ".nan" keep those spellings.
Both zeros give "0", and a float with an integral value has no
fractional part, so the keys 1.0 and 1 are the same key.  Look such a
key up by its canonical text, for example
cyaml_get(doc, "python.3\\.1") for the key that "3.10:" wrote, or
quote the key in the document to keep its text as written.  This
holds for an implicit key, an explicit key, a flow dictionary key and
the "key: value" shorthand of a flow sequence, so every spelling of
the same value lands on the same key, whatever the notation.  A
quoted key with no tag is never canonicalized: The stored key text
is always exactly its own decoded content.
 
A tag on a key types that key exactly as it types a value, in every
key notation, and the parser then stores the canonical text of the
typed key.  "!!str 010:" and "!!str 10:" are two different keys,
'!!int "0x10":' is the key "16", and "!!int abc:" is a parse error.
The keys of this DOM are plain strings and not nodes, so the tag
itself is not kept.  An anchor on a tagged key names the typed node.
 
The text under an explicit !!int or !!float tag must match the
core-schema grammar of that type from its first byte: An int begins
with a digit or a sign, and a float with a digit, a sign or ".".
A space, tab or line break at the end of the text is ignored, but no
byte in front of the number is, so '!!int " 42"' and '!!int "\v42"'
(a vertical tab) are parse errors, and so is any other leading space,
tab, line break or form feed that a double-quoted scalar carries
through an escape.
 
A node can carry at most one anchor and one tag, in either order, and
an alias can never carry either.  A "<<" key is read as a merge
directive whenever it is a plain, untagged scalar, and whenever its
tag is the core merge tag, tag:yaml.org,2002:merge (!!merge, a %TAG
shorthand of it, or its verbatim form), whether the key is plain or
quoted.  That holds in any mapping, whatever built it.  There are
five forms: The implicit style of a block mapping ("<<: value"), the
explicit style of a block mapping ("? <<" and ": value"), the
implicit style of a flow mapping ("{<<: value}"), the explicit style
of a flow mapping ("{? <<: value}"), and the one-entry mapping that
the compact-mapping shorthand of a block or flow sequence gives
("- <<: value", "[<<: value]", "[? <<: value]").  That shorthand is
the "key: value" and "? key: value" notation.  An anchor on the key
itself changes none of this.  A "<<" that is quoted with no tag, or
that carries any tag other than the merge tag, is always an ordinary
literal key, in every one of those forms.
 
The input must be UTF-8 text made only of the printable characters of
YAML 1.2 section 5.1 (c-printable): TAB, LF, CR, 0x20 to 0x7E, NEL
(U+0085), U+00A0 to U+D7FF, U+E000 to U+FFFD and U+10000 to U+10FFFF.
Every byte of the stream is checked before anything is parsed
(scalars of every style, keys, comments, tags, anchors, directives
and the space between tokens), and the whole document is refused at
the first byte that breaks the rule.  That covers a byte sequence
that is not well-formed UTF-8 (a truncated sequence, a continuation
byte with no lead byte, an overlong form, an encoded surrogate, a
code point above U+10FFFF, a byte from 0xF5 to 0xFF), a C0 control
other than TAB, LF and CR, DEL, a C1 control (U+0080 to U+009F) other
than NEL, and the noncharacters U+FFFE and U+FFFF.  The error message
names the defect, shows the offending bytes as 0xNN, and gives the
line and the column, both counted from 1.  LF, CR and CRLF each end a
line, and the column counts characters.  For example:
 
    raw control character 0x01 is not allowed in a YAML stream
    (line 3, column 7); write it as an escape sequence in a
    double-quoted scalar
 
    invalid UTF-8 in a YAML stream (line 1, column 4): Overlong
    encoding (lead byte 0xc0)
 
Most other parse errors give a byte offset into the input instead, as
in "tab cannot be used as block mapping indentation at position 4",
or "unknown alias '*x' at position 3" for the text "a: *x", where the
offset is that of the "*" that starts the alias.  A few quote the
offending text with no position, as in
"'abc' is not a valid !!int value".
 
The parser never repairs the input and never substitutes a
character, so fix the data.  An escape sequence in a double-quoted
scalar is the one way to put such a character into a value: "\x01",
"\x7f", "\x80" and "\uFFFE" are printable text that names it.  Two
"\u" escapes that form a UTF-16 surrogate pair ("\uD83D\uDE00")
name one character, as in JSON.  An escape that names no character
is a parse error: A lone surrogate in a "\u" escape, and a "\U"
value that is a surrogate or above U+10FFFF.  Percent-escapes in a
tag must decode to well-formed UTF-8.
 
An escape that decodes to the null character ("\0", "\x00",
"\u0000", "\U00000000") is refused, and so is the percent-escaped
spelling of the same byte inside a tag ("%00").  The scalar value of
a node, its anchor name and its tag are each a plain null-terminated
C string, so a null byte inside one of them can never be
represented.  A raw null byte is outside c-printable, and it can
reach the parser only through cyaml_parse_n(3) and
cyaml_parse_n_mp(3), which take an explicit length, because
cyaml_parse(3) stops at the first one.
 
An implicit decimal, hex or octal integer literal whose value doesn't
fit a signed 64-bit long long falls back to CYAML_FLOAT, or to a plain
CYAML_STRING when the text doesn't parse as a float either.  The
parser never quietly turns it into an integer that wrapped around or
that has the wrong sign.
 
Indentation is spaces only, as YAML 1.2 defines it.  A tab is
separation whitespace wherever the grammar allows separation: After a
'-', '?' or ':' indicator ("key:\tvalue"), after the spaces that
indent a line, inside a flow collection, after "---" or "...", between
the parts of a directive, and before a comment, so JSON indented with
tabs parses.  A tab is refused where it would decide a
block-structural column: In front of a block mapping key or a block
sequence '-' on its line ("\ta: 1", "key:\t- a", "-\tb: c"), and as
the indentation of a block scalar.  Inside a scalar a tab is content.
 
Block-structured content (a mapping or a sequence) must start on its
own line after an explicit "---" marker and must not share that line,
but a scalar or a flow collection may share it.
 
A UTF-8 byte order mark may stand in the prefix of a document: At the
start of the stream, at the start of the line of a later document
after a "..." or before a "---", and at the end of the stream.  A
prefix may hold several marks, with comment lines between them.  The
mark is not content, and a comment may follow it directly.  YAML 1.2
section 5.2 forbids a mark inside a document, so a mark at the start
of a line anywhere else is a parse error.  That is why a file that
ends without a "..." and a file that starts with a mark, joined
together, need a "---" after the mark.  A mark in the middle of a
line is ordinary content.
 
Every continuation line of a flow collection must be indented more
than the block mapping key or the "- " that holds the collection,
counting spaces only.  The one exception is a line that starts with
the closing ']' or '}', which may sit exactly at that indentation,
after spaces only, and so closes the collection under the line that
opened it:
 
    key: [
      a,
      b
    ]
 
Any other content at that column, and a closing indicator further to
the left, is a parse error.
 
A document that nests more than 500 containers (sequences and
mappings) on any path is a parse error, counting the root when it is
a container.  Scalars, tags and anchors take no level, so 500 nested
containers are accepted with anything inside the innermost one, and
a 501st container is refused.  A "key: value" pair inside a flow
sequence is a one-entry mapping and takes a level.  An alias copies
its anchored node below the containers around the alias, so its
expansion must fit in the levels left there, and the value of a merge
key counts where it stands, before the merge moves its members into
the mapping.  A collection that serves as a dictionary key counts
below the mapping that holds the key, in every key form: An implicit
or explicit key of a block mapping, an alias used as a key, a key of
a flow mapping, and the key of a "key: value" pair in a flow
sequence.  When a stream holds several documents, the parse gives a
list that holds them, so each document may nest at most 499
containers.  cyaml_clone(3) and the serializers apply exactly the
same limit, so every tree that a parse gives can be cloned and
serialized.
An explicit worklist drives the parse instead of recursion, so the
call stack that one parse needs is constant and doesn't grow with the
nesting depth of the document.  The limit bounds the work of a
single call, not the stack the caller has to provide.  A non-scalar
dictionary key whose canonicalized flow-YAML text is larger than
64 KiB is refused too.  This second limit is for a key that is itself
a mapping holding another such key many levels deep: Canonicalization
quotes the quoted text of each enclosing level again, so that text
grows fast with the nesting depth.  The text is built only up to the
limit, so a refused key costs at most 64 KiB of text whatever its
shape and however many aliases it expands.  The limit applies only to
a key, and a flow collection in a value position, anchored, tagged or
neither, has no length limit of its own.  No realistic document that
a person writes or a program generates reaches either limit.
 
One parse call also refuses a document that needs more DOM nodes
than the larger of 4,000,000 and 4 per byte of input, with a parse
error that names the limit explicitly.
 
One parse call also refuses a document whose DOM would use more than
the larger of 256 MiB and 512 bytes per byte of input.  An ordinary
document of any size stays well below both limits.  The count covers
the node structs, their backing containers, and the text of every
scalar, every tag and every dictionary key.  The parse error names
this limit explicitly as well, instead of reporting out of memory.
This limit catches what the node count alone cannot, because a node
is not a fixed amount of memory and an alias deep-copies everything
its anchor holds, so a small document whose bytes sit in a few large
anchored scalars could otherwise expand without bound while its node
count stays low.
 
The nodes and bytes that a parse makes by copying what it has already
built also count against a fixed alias expansion limit of 4,000,000
nodes and 256 MiB, which doesn't grow with the input.  A copy is the
node that an alias resolves to, a member that a merge key copies into
its mapping, and the canonical text of a key that is a sequence or a
mapping.  An anchor alone copies nothing, so an anchored node that
no alias names costs no more than the same node without the anchor.
These are the only ways a document can make more DOM than its text
describes, so a nested-alias document hits this limit at the same
point whether or not a long comment pads it.  The parse error names
this limit too.
 
None of these limits applies to a tree that the caller builds
directly through the construction API outside a parse.
 
The decimal point of a float is always '.', whatever LC_NUMERIC the
process or the calling thread uses.  For the length of the call the
calling thread switches to the "C" locale through uselocale(3), which
changes no other thread, and the thread's own locale is back in place
before the call returns.  A custom allocator that the call invokes
runs inside that window.

cyaml_parse_n_mp(3), cyaml_destroy(3), cyaml_node_tag(3), cyaml_serialize(3), cyaml_serialize_stream(3), cyaml_serialize_free_mp(3), cyaml(7)