#! @file text.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains what YAML's text is made of: which characters it allows, what a plain #! scalar resolves to by the core schema, how numbers read, and how text is written #! back so that it reads as the same text. module std::yaml; # The digits an escape is written with. const hex_digits: strview = "0123456789ABCDEF"; # What a plain scalar resolves to by the core schema. enum resolved: u8 { empty, #! `null`, `Null`, `NULL`, `~`, or nothing. truth, #! `true`, `True`, or `TRUE`. falsehood, #! `false`, `False`, or `FALSE`. integer, #! Decimal, `0o` octal, or `0x` hexadecimal. real, #! A float, `.inf`, or `.nan`. text, #! Anything else. } # Whether a byte separates words on a line: a space or a tab. def is_blank(byte: u8): bool { return byte == ' ' || byte == '\t'; } # Whether a byte breaks a line. def is_break(byte: u8): bool { return byte == '\n' || byte == '\r'; } # Whether a byte ends what is written on a line: a blank, a break, or the end of the # text, which the scanner reads as 0, since the text holds no zero byte. def is_blankz(byte: u8): bool { return byte == ' ' || byte == '\t' || byte == '\n' || byte == '\r' || byte == 0; } # Whether a byte breaks a line or is the end of the text. def is_breakz(byte: u8): bool { return byte == '\n' || byte == '\r' || byte == 0; } # Whether a byte begins or ends a flow collection, or separates its entries. def is_flow_indicator(byte: u8): bool { return byte == ',' || byte == '[' || byte == ']' || byte == '{' || byte == '}'; } # Whether a byte may be in a tag handle's name: a letter, a digit, or `-`. def is_word(byte: u8): bool { return byte.is_alnum || byte == '-'; } # Whether a byte may be written in a URI, as a tag is, other than in a `%` escape. def is_uri_char(byte: u8): bool { if byte.is_alnum { return true; } return match byte { '-', '#', ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '!', '~', '*', '\'', '(', ')', '[', ']' => true, else => false, }; } # Whether a byte may be written in a tag's suffix: what a URI holds, but `!` and the # flow indicators. def is_tag_char(byte: u8): bool { return is_uri_char(byte) && byte != '!' && !is_flow_indicator(byte); } # Finds the first byte of the text YAML does not allow, where text must be UTF-8 and # only of printable characters: no control characters but the tab and line breaks, no # DEL, no C1 control characters but NEL, and neither U+FFFE nor U+FFFF. def first_disallowed(text: strview): maybe { var at: u64 = 0; while at < text.length { val byte := text[at]; if byte >= 0x20 && byte < 0x7F { at++; continue; } if byte < 0x80 { if (byte < 0x20 && byte != '\t' && byte != '\n' && byte != '\r') || byte == 0x7F { # A zero byte at the start is UTF-16 or UTF-32, which YAML could be, but this # does not read. val kind := byte == 0 && at < 4 ? error_kind::invalid_utf8 : error_kind::invalid_character; return disallowed { kind = kind, offset = at }; } at++; continue; } val count := serial::utf8_length(text, at); if count == 0 { return disallowed { kind = error_kind::invalid_utf8, offset = at }; } if count == 2 && byte == 0xC2 && text[at + 1] < 0xA0 && text[at + 1] != 0x85 { return disallowed { kind = error_kind::invalid_character, offset = at }; } if count == 3 && byte == 0xEF && text[at + 1] == 0xBF && text[at + 2] >= 0xBE { return disallowed { kind = error_kind::invalid_character, offset = at }; } at += count; } return nothing {}; } # A byte the text holds that YAML does not allow, and why. struct disallowed { var kind: error_kind; var offset: u64; } # What a plain scalar's text resolves to, by the core schema. def resolve(text: strview): resolved { if text.length == 0 { return resolved::empty; } # Only text beginning with one of these resolves to anything but text, so most # resolves in one comparison. val first := text[0]; if !first.is_digit && first != '-' && first != '+' && first != '.' && first != '~' && first != 'n' && first != 'N' && first != 't' && first != 'T' && first != 'f' && first != 'F' { return resolved::text; } if first == '~' || first == 'n' || first == 'N' { return text == "~" || text == "null" || text == "Null" || text == "NULL" ? resolved::empty : resolved::text; } if first == 't' || first == 'T' { return text == "true" || text == "True" || text == "TRUE" ? resolved::truth : resolved::text; } if first == 'f' || first == 'F' { return text == "false" || text == "False" || text == "FALSE" ? resolved::falsehood : resolved::text; } if is_integer(text) { return resolved::integer; } if is_real(text) { return resolved::real; } return resolved::text; } # Whether text is an integer by the core schema: `[-+]?[0-9]+`, `0o[0-7]+`, or # `0x[0-9a-fA-F]+`. def is_integer(text: strview): bool { if text.length > 2 && text[0] == '0' && (text[1] == 'o' || text[1] == 'x') { val hex := text[1] == 'x'; for at in 2..text.length { val byte := text[at]; if hex ? !byte.is_hex : !byte.is_oct { return false; } } return true; } var at: u64 = text[0] == '-' || text[0] == '+' ? 1 : 0; if at == text.length { return false; } while at < text.length { if !text[at].is_digit { return false; } at++; } return true; } # Whether text is a float by the core schema: # `[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?`, `[-+]?\.inf` and `\.nan` # in their three cases. def is_real(text: strview): bool { var at: u64 = text[0] == '-' || text[0] == '+' ? 1 : 0; val rest := text.substr(at, text.length); if rest == ".inf" || rest == ".Inf" || rest == ".INF" { return true; } if at == 0 && (rest == ".nan" || rest == ".NaN" || rest == ".NAN") { return true; } var digits: u64 = 0; while at < text.length && text[at].is_digit { at++; digits++; } if at < text.length && text[at] == '.' { at++; while at < text.length && text[at].is_digit { at++; digits++; } } if digits == 0 { return false; } if at < text.length && (text[at] == 'e' || text[at] == 'E') { at++; if at < text.length && (text[at] == '-' || text[at] == '+') { at++; } val exponent := at; while at < text.length && text[at].is_digit { at++; } if at == exponent { return false; } } return at == text.length; } # A number's text as an integer exactly, in any base the core schema has: whether it # is whole, and fits in 64 bits. A float that is a whole number, as `1e3` is, is one. def integral_of(text: strview): serial::integral { if text.length > 2 && text[0] == '0' && (text[1] == 'o' || text[1] == 'x') { val base: u64 = text[1] == 'x' ? 16 : 8; var made := serial::integral { whole = true, fits = true }; for at in 2..text.length { val digit := text[at].digit_value; if made.magnitude > (0xFFFFFFFFFFFFFFFFu - digit) / base { made.fits = false; return made; } made.magnitude = made.magnitude * base + digit; } return made; } # Infinity and NaN are no integer. val last := text[text.length - 1]; if !last.is_digit && last != '.' { return serial::integral {}; } return serial::integral_of(text); } # A number's text as the nearest 64-bit float, or `nothing` where it is too large. def real_of(text: strview): maybe { var at: u64 = text[0] == '-' || text[0] == '+' ? 1 : 0; val negative := text[0] == '-'; val rest := text.substr(at, text.length); if rest == ".inf" || rest == ".Inf" || rest == ".INF" { return negative ? -1.0 / 0.0 : 1.0 / 0.0; } if rest == ".nan" || rest == ".NaN" || rest == ".NAN" { return 0.0 / 0.0; } if text.length > 2 && text[0] == '0' && (text[1] == 'o' || text[1] == 'x') { val read := integral_of(text); if !read.fits { val base: f64 = text[1] == 'x' ? 16.0 : 8.0; var made: f64 = 0.0; for index in 2..text.length { made = made * base + text[index].digit_value as f64; } return made; } return read.magnitude as f64; } match real::parse::(text) { value(read) => return read; error(&_) => return nothing {}; } return nothing {}; } # Whether text written plain reads back as the same text, as a value, or as a key, # which is also on one line. Decision 7 has it quote, too, what YAML 1.1 reads as # another kind, so readers of either version read the same. def plain_writes(text: strview): bool { if text.length == 0 || resolve(text) != resolved::text || reads_otherwise_in_1_1(text) { return false; } # It begins with no indicator, but `-`, `?`, or `:` before what is plain, and holds # no space at either end. val first := text[0]; val second: u8 = text.length > 1 ? text[1] : 0; match first { ',', '[', ']', '{', '}', '#', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`', ' ', '\t' => return false; '-', '?', ':' => { if is_blankz(second) || is_flow_indicator(second) { return false; } } else => {} } val last := text[text.length - 1]; if last == ' ' || last == '\t' || last == ':' { return false; } # Nothing within it ends it, or begins a comment, and each character is printable, # with no line break, and none of the flow indicators, so it reads the same within # a flow collection too. var at: u64 = 0; while at < text.length { val byte := text[at]; if byte < 0x20 || byte == 0x7F || is_flow_indicator(byte) { return false; } if byte == ':' && at + 1 < text.length && (text[at + 1] == ' ' || text[at + 1] == '\t') { return false; } if byte == '#' && at > 0 && (text[at - 1] == ' ' || text[at - 1] == '\t') { return false; } if byte >= 0x80 { val count := serial::utf8_length(text, at); if count == 0 || !printable_at(text, at) { return false; } at += count; continue; } at++; } # A document marker would end the document. if text.starts_with("---") || text.starts_with("...") { return false; } return true; } # Whether YAML 1.1 reads plain text as something else, as PyYAML's resolver and the # 1.1 spec do: its booleans, numbers with `_` or in base 2 or 60, dates, the merge # key, and `=`. def reads_otherwise_in_1_1(text: strview): bool { if text.length <= 5 { val lower := text.lower(); val word := lower.span; if word == "y" || word == "n" || word == "yes" || word == "no" || word == "on" || word == "off" { return true; } } if text == "<<" || text == "=" { return true; } return is_1_1_integer(text) || is_1_1_float(text) || is_1_1_date(text); } # Whether text is a YAML 1.1 integer: `0b` binary, `0` octal, `0x` hexadecimal, or # decimal, each with `_` among the digits, or sexagesimal, as `1:30`. def is_1_1_integer(text: strview): bool { var at: u64 = text.length > 0 && (text[0] == '-' || text[0] == '+') ? 1 : 0; val rest := text.substr(at, text.length); if rest.length > 2 && rest[0] == '0' && (rest[1] == 'b' || rest[1] == 'x') { val hex := rest[1] == 'x'; for index in 2..rest.length { val byte := rest[index]; if byte != '_' && !(hex ? byte.is_hex : (byte == '0' || byte == '1')) { return false; } } return true; } val digits := digits_end(rest, 0); if digits == 0 { return false; } if digits == rest.length { return true; } return rest[0] != '0' && sexagesimal_end(rest, digits) == rest.length; } # Whether text is a YAML 1.1 float: digits with `_`, a `.`, and an exponent, or a # sexagesimal one, as `1:30.5`. def is_1_1_float(text: strview): bool { var at: u64 = text.length > 0 && (text[0] == '-' || text[0] == '+') ? 1 : 0; val rest := text.substr(at, text.length); var index := digits_end(rest, 0); if index > 0 && index < rest.length && rest[index] == ':' { index = sexagesimal_end(rest, index); } if index >= rest.length || rest[index] != '.' { return false; } val whole := index; index = digits_end(rest, index + 1); if whole == 0 && index == 1 { return false; } if index < rest.length && (rest[index] == 'e' || rest[index] == 'E') { index++; if index >= rest.length || (rest[index] != '-' && rest[index] != '+') { return false; } val exponent := index + 1; index = exponent; while index < rest.length && rest[index].is_digit { index++; } if index == exponent { return false; } } return index == rest.length; } # Whether text is a YAML 1.1 date, `2026-10-06`, or a time stamp beginning with one. def is_1_1_date(text: strview): bool { if text.length < 8 || !text[0].is_digit || !text[1].is_digit || !text[2].is_digit || !text[3].is_digit || text[4] != '-' { return false; } var index: u64 = 5; for _ in 0..2 { val first := index; while index < text.length && index < first + 2 && text[index].is_digit { index++; } if index == first { return false; } if index < text.length && text[index] == '-' && first == 5 { index++; } } return index == text.length || text[index] == 'T' || text[index] == 't' || text[index] == ' ' || text[index] == '\t'; } # Where a run of decimal digits, and `_` among them, ends. def digits_end(text: strview, from: u64): u64 { var index := from; while index < text.length && (text[index].is_digit || (index > from && text[index] == '_')) { index++; } return index; } # Where sexagesimal parts, each `:` and one or two digits, end, from a `:`. def sexagesimal_end(text: strview, from: u64): u64 { var index := from; while index < text.length && text[index] == ':' { val first := index + 1; index = first; while index < text.length && index < first + 2 && text[index].is_digit { index++; } if index == first { return first - 1; } } return index; } # Whether the character beginning at a byte is printable: not a C1 control character, # nor U+FFFE or U+FFFF, nor anything YAML writes only escaped. def printable_at(text: strview, at: u64): bool { val byte := text[at]; if byte == 0xC2 && text[at + 1] < 0xA0 { return false; } if byte == 0xEF && text[at + 1] == 0xBB && text[at + 2] == 0xBF { return false; } if byte == 0xEF && text[at + 1] == 0xBF && text[at + 2] >= 0xBE { return false; } return true; } # Whether text reads back the same written as a literal block: it holds a line break, # is printable, has no carriage return, and has no line of only spaces or tabs, which # a block would read as empty, nor a tab after a line break, which a block would read # as indentation. def literal_writes(text: strview): bool { var breaks: u64 = 0; var line_blank := true; var at: u64 = 0; while at < text.length { val byte := text[at]; if byte == '\n' { if line_blank && at > 0 && text[at - 1] != '\n' { return false; } breaks++; line_blank = true; at++; continue; } if byte == '\t' && (at == 0 || text[at - 1] == '\n') { return false; } if (byte < 0x20 && byte != '\t') || byte == 0x7F { return false; } if byte >= 0x80 { val count := serial::utf8_length(text, at); if count == 0 || !printable_at(text, at) { return false; } line_blank = false; at += count; continue; } if byte != ' ' && byte != '\t' { line_blank = false; } at++; } if line_blank && text.length > 0 && text[text.length - 1] != '\n' { return false; } return breaks > 0; } # Appends text double-quoted, with YAML's escapes for what is not printable. # @returns Whether the text is UTF-8: text that is not is appended only as far as its # first byte that breaks UTF-8, without the closing quote. def append_double(text: strview, into: &mut string): bool { into.push('"'); var run: u64 = 0; var at: u64 = 0; while at < text.length { val byte := text[at]; if byte >= 0x80 { val count := serial::utf8_length(text, at); if count == 0 { into.append(text.substr(run, at - run)); return false; } if printable_at(text, at) { at += count; continue; } into.append(text.substr(run, at - run)); append_code_escape(code_at(text, at, count), into); at += count; run = at; continue; } if byte >= 0x20 && byte != 0x7F && byte != '"' && byte != '\\' { at++; continue; } into.append(text.substr(run, at - run)); into.push('\\'); match byte { '"' => into.push('"'); '\\' => into.push('\\'); '\n' => into.push('n'); '\r' => into.push('r'); '\t' => into.push('t'); 0x00 => into.push('0'); 0x07 => into.push('a'); 0x08 => into.push('b'); 0x0B => into.push('v'); 0x0C => into.push('f'); 0x1B => into.push('e'); else => { into.push('x'); into.push(hex_digits[(byte >> 4) as u64]); into.push(hex_digits[(byte & 0x0F) as u64]); } } at++; run = at; } into.append(text.substr(run, at - run)); into.push('"'); return true; } # The character a UTF-8 sequence of a length writes. def code_at(text: strview, at: u64, count: u64): u64 { val lead := text[at] as u64; var code: u64 = count == 2 ? lead & 0x1F : (count == 3 ? lead & 0x0F : lead & 0x07); for index in 1..count { code = (code << 6) | ((text[at + index] as u64) & 0x3F); } return code; } # Appends the escape of a character not written as it is, as `\u0085`, or `\N`, # `\_`, `\L`, and `\P` for the ones YAML names. def append_code_escape(code: u64, into: &mut string): void { if code == 0x85 { into.append("\\N"); return; } if code == 0xA0 { into.append("\\_"); return; } if code == 0x2028 { into.append("\\L"); return; } if code == 0x2029 { into.append("\\P"); return; } val wide := code > 0xFFFF; into.append(wide ? "\\U" : "\\u"); var shift: u64 = wide ? 28 : 12; while true { into.push(hex_digits[(code >> shift) & 0xF]); if shift == 0 { break; } shift -= 4; } }