use std::cell::Cell;
use std::sync::OnceLock;
use regex::Regex;
use tabnas::{Context, Lexer, Rule, Token, Value};
use crate::lex::{
advance_cols, apply, at, blank, blank_line_end_or_eof, is, is_doc_marker, is_doc_marker_no_tab,
js_substring, js_substring_less_one_unit, line_end, ready, trim_end, Act, Src, Tok,
};
use crate::source::Kept;
use crate::state;
pub(crate) const MATCHER: &str = "@yaml-text";
pub(crate) fn yaml_text(
lexer: &mut Lexer<'_>,
_rule: &mut Rule,
context: &mut Context,
) -> Option<Token> {
let mut kept = Kept::load(context, lexer.windowed());
kept.extend(lexer);
let point = lexer.point();
let start = point.site.si;
let touched = Cell::new(false);
let ready = {
let src = kept.src(lexer.source(), &touched);
let (row, column) = src.row_col(start);
check(src, (start, row, column), context).map(|act| ready(src, &point, act))
};
let windowed = kept.windowed();
kept.store(context);
let token = ready.and_then(|ready| apply(lexer, ready));
if windowed && touched.get() {
lexer.advance_chars(usize::MAX);
}
token
}
fn check(src: Src<'_>, cursor: (usize, usize, usize), context: &mut Context) -> Option<Act> {
let fwd = src.from(src.clamp(cursor.0));
if !fwd.has(0) {
return None;
}
let head = at(fwd, 0);
if head == i32::from(b'|') || head == i32::from(b'>') {
if let Some(act) = block_scalar(src, fwd, cursor) {
return Some(act);
}
return Some(plain_scalar(src, fwd, cursor, context));
}
for owned in *b"{}[],#\n\r\"'*&!" {
if head == i32::from(owned) {
return None;
}
}
if head == i32::from(b':') && blank_line_end_or_eof(at(fwd, 1)) {
return None;
}
if state::flag(context, state::MOVED) {
if let Some(act) = number_run(src, fwd, cursor, crate::core_schema(context)) {
return Some(act);
}
}
Some(plain_scalar(src, fwd, cursor, context))
}
fn engine_number() -> &'static Regex {
static PATTERN: OnceLock<Regex> = OnceLock::new();
PATTERN.get_or_init(|| {
Regex::new(concat!(
"^[-+]?(?:",
"0(?:[xX][0-9a-fA-F_]+|[oO][0-7_]+|[bB][01_]+)",
"|",
r"\.?[0-9]+(?:[0-9_]*[0-9])?",
r"(?:\.(?:[0-9](?:[0-9_]*[0-9])?)?)?",
"(?:[eE][-+]?[0-9]+(?:[0-9_]*[0-9])?)?",
")$"
))
.expect("the number pattern is a literal and compiles")
})
}
fn number_run(
src: Src<'_>,
fwd: Src<'_>,
cursor: (usize, usize, usize),
core: bool,
) -> Option<Act> {
let head = at(fwd, 0);
let numeric = head == i32::from(b'-')
|| head == i32::from(b'+')
|| head == i32::from(b'.')
|| (head >= i32::from(b'0') && head <= i32::from(b'9'));
if !numeric {
return None;
}
let mut end = 0;
while fwd.has(end) {
let byte = at(fwd, end);
if blank_line_end_or_eof(byte)
|| byte == i32::from(b',')
|| byte == i32::from(b'[')
|| byte == i32::from(b']')
|| byte == i32::from(b'{')
|| byte == i32::from(b'}')
|| byte == i32::from(b':')
|| byte == i32::from(b'#')
{
break;
}
end += 1;
}
let run = fwd.slice(0, end);
if !engine_number().is_match(run) {
return None;
}
if core && crate::core_number(run).is_none() {
return None;
}
let stripped: String = run.chars().filter(|character| *character != '_').collect();
let number = crate::js_to_number(&stripped).or_else(|| {
let (sign, rest) = match stripped.as_bytes().first() {
Some(b'-') => (-1.0, &stripped[1..]),
Some(b'+') => (1.0, &stripped[1..]),
_ => return None,
};
crate::js_to_number(rest).map(|value| sign * value)
})?;
let next = advance_cols(src, cursor, end);
Some(Act::moved(
next,
Some(Tok::new("#NR", Value::Number(number), run, cursor)),
))
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Chomp {
Clip,
Strip,
Keep,
}
#[allow(clippy::too_many_lines)]
fn block_scalar(src: Src<'_>, fwd: Src<'_>, cursor: (usize, usize, usize)) -> Option<Act> {
let fold = is(fwd, 0, b'>');
let mut chomp = Chomp::Clip;
let mut explicit_indent = 0usize;
let mut idx = 1;
for _ in 0..2 {
let byte = at(fwd, idx);
if byte == i32::from(b'+') {
chomp = Chomp::Keep;
idx += 1;
} else if byte == i32::from(b'-') {
chomp = Chomp::Strip;
idx += 1;
} else if (i32::from(b'1')..=i32::from(b'9')).contains(&byte) {
explicit_indent = (byte - i32::from(b'0')) as usize;
idx += 1;
}
}
while is(fwd, idx, b' ') {
idx += 1;
}
if is(fwd, idx, b'#') {
while fwd.has(idx) && !line_end(at(fwd, idx)) {
idx += 1;
}
}
if !line_end(at(fwd, idx)) && fwd.has(idx) {
return None;
}
if is(fwd, idx, b'\r') {
idx += 1;
}
if is(fwd, idx, b'\n') {
idx += 1;
}
let mut block_indent = 0usize;
if explicit_indent == 0 {
let mut probe = idx;
while fwd.has(probe) {
let mut spaces = 0;
while is(fwd, probe + spaces, b' ') {
spaces += 1;
}
let after = probe + spaces;
if !fwd.has(after) || line_end(at(fwd, after)) {
probe = after;
if is(fwd, probe, b'\r') {
probe += 1;
}
if is(fwd, probe, b'\n') {
probe += 1;
}
continue;
}
block_indent = spaces;
break;
}
}
let mut containing_indent = 0usize;
let is_doc_start;
let is_doc_root;
{
let mut index = crate::lex::line_start_of(src, cursor.0);
let line_start = index;
while index < cursor.0 && is(src, index, b' ') {
containing_indent += 1;
index += 1;
}
is_doc_start = is(src, line_start, b'-')
&& is(src, line_start + 1, b'-')
&& is(src, line_start + 2, b'-');
is_doc_root = containing_indent == 0 && index == cursor.0;
}
if explicit_indent > 0 {
let mut index = cursor.0;
while index > 0 && !line_end(at(src, index - 1)) {
index -= 1;
}
let mut key_column = containing_indent;
let mut has_colon = false;
for probe in index + containing_indent..cursor.0 {
if is(src, probe, b':') && blank(at(src, probe + 1)) {
has_colon = true;
break;
}
}
if has_colon {
let mut scan = index + containing_indent;
while scan < cursor.0 && is(src, scan, b'-') && blank(at(src, scan + 1)) {
key_column += 2;
scan += 2;
while scan < cursor.0 && is(src, scan, b' ') {
key_column += 1;
scan += 1;
}
}
block_indent = key_column + explicit_indent;
} else {
let mut parent_indent = 0usize;
let mut search = index as isize - 1;
if search > 0 {
if is(src, search as usize, b'\n') {
search -= 1;
}
if search >= 0 && is(src, search as usize, b'\r') {
search -= 1;
}
let previous_end = (search + 1).max(0) as usize;
let mut previous_start = search.max(0) as usize;
while previous_start > 0 && !line_end(at(src, previous_start - 1)) {
previous_start -= 1;
}
for probe in previous_start..previous_end {
if is(src, probe, b':')
&& (blank(at(src, probe + 1))
|| line_end(at(src, probe + 1))
|| probe + 1 >= previous_end)
{
parent_indent = 0;
let mut leading = previous_start;
while leading < previous_end && is(src, leading, b' ') {
parent_indent += 1;
leading += 1;
}
break;
}
}
}
block_indent = parent_indent + explicit_indent;
containing_indent = parent_indent;
}
}
if block_indent <= containing_indent && !is_doc_start && !is_doc_root && fwd.has(idx) {
let mut value = String::new();
let mut end = idx;
if chomp == Chomp::Keep {
let mut blanks = 0;
while fwd.has(end) {
if is(fwd, end, b'\n') {
blanks += 1;
end += 1;
} else if is(fwd, end, b'\r') {
end += 1;
if is(fwd, end, b'\n') {
end += 1;
}
blanks += 1;
} else {
break;
}
}
value = "\n".repeat(blanks.max(1));
}
let source = fwd.slice(0, end).to_string();
return Some(Act::moved(
(cursor.0 + end, cursor.1 + 1, 0),
Some(Tok::new("#TX", Value::String(value), source, cursor)),
));
}
let mut lines: Vec<String> = Vec::new();
let mut pos = idx;
let mut rows = 1usize;
let mut last_newline = idx;
while fwd.has(pos) {
let mut line_indent = 0;
while is(fwd, pos + line_indent, b' ') {
line_indent += 1;
}
let after = pos + line_indent;
if !fwd.has(after) && line_indent <= block_indent {
pos = after;
break;
}
if !fwd.has(after) || line_end(at(fwd, after)) {
if line_indent > block_indent {
lines.push(fwd.slice(pos + block_indent, after).to_string());
} else {
lines.push(String::new());
}
last_newline = after;
pos = after;
if is(fwd, pos, b'\r') {
pos += 1;
}
if is(fwd, pos, b'\n') {
pos += 1;
}
rows += 1;
continue;
}
if line_indent < block_indent {
break;
}
if line_indent == 0 && is_doc_marker_no_tab(fwd, pos) {
break;
}
let line_start = pos + block_indent;
let mut line_stop = line_start;
while fwd.has(line_stop) && !line_end(at(fwd, line_stop)) {
line_stop += 1;
}
lines.push(fwd.slice(line_start, line_stop).to_string());
last_newline = line_stop;
pos = line_stop;
if is(fwd, pos, b'\r') {
pos += 1;
}
if is(fwd, pos, b'\n') {
pos += 1;
}
rows += 1;
}
let mut value = if fold {
fold_lines(&lines)
} else {
lines.join("\n")
};
if lines.is_empty() {
value = String::new();
} else {
match chomp {
Chomp::Strip => {
while value.ends_with('\n') {
value.pop();
}
}
Chomp::Clip => {
while value.ends_with('\n') {
value.pop();
}
value.push('\n');
}
Chomp::Keep => value.push('\n'),
}
}
let mut end_pos = pos;
let mut end_rows = rows;
if fwd.has(pos) && pos > last_newline {
let mut next_indent = 0;
let mut probe = pos;
while is(fwd, probe, b' ') {
next_indent += 1;
probe += 1;
}
let marker = next_indent == 0
&& ((is(fwd, probe, b'-') && is(fwd, probe + 1, b'-') && is(fwd, probe + 2, b'-'))
|| (is(fwd, probe, b'.') && is(fwd, probe + 1, b'.') && is(fwd, probe + 2, b'.')));
if !marker {
end_pos = last_newline;
end_rows = rows - 1;
}
}
let source = fwd.slice(0, end_pos).to_string();
Some(Act::moved(
(cursor.0 + end_pos, cursor.1 + end_rows, 0),
Some(Tok::new("#TX", Value::String(value), source, cursor)),
))
}
fn fold_lines(lines: &[String]) -> String {
let mut result = String::new();
let mut previous_normal = false;
let mut previous_more = false;
let mut pending_empty = 0usize;
for line in lines {
let more_indented = line.starts_with(' ') || line.starts_with('\t');
if line.is_empty() {
pending_empty += 1;
continue;
}
if previous_more {
result.push('\n');
previous_more = false;
}
if more_indented {
if previous_normal && !result.is_empty() {
result.push('\n');
}
for _ in 0..pending_empty {
result.push('\n');
}
pending_empty = 0;
if !result.is_empty() && !result.ends_with('\n') {
result.push('\n');
}
result.push_str(line);
previous_normal = false;
previous_more = true;
} else {
if pending_empty > 0 {
if previous_normal && !result.is_empty() {
result.push('\n');
for _ in 1..pending_empty {
result.push('\n');
}
} else {
for _ in 0..pending_empty {
result.push('\n');
}
}
pending_empty = 0;
}
if previous_normal && !result.is_empty() && !result.ends_with('\n') {
result.push(' ');
}
result.push_str(line);
previous_normal = true;
}
}
for _ in 0..pending_empty {
result.push('\n');
}
result
}
pub(crate) struct Plain {
pub(crate) text: String,
pub(crate) consumed: usize,
pub(crate) rows: usize,
}
#[allow(clippy::too_many_lines)]
pub(crate) fn plain_scalar_at(src: Src<'_>, at_pos: usize, context: &mut Context) -> Plain {
let fwd = src.from(src.clamp(at_pos));
let cursor = (at_pos, 0, 0);
let in_flow = state::flow_depth_at(context, src, cursor.0) > 0;
let line_start = crate::lex::line_start_of(src, cursor.0);
let mut current_line_indent = 0usize;
{
let mut index = line_start;
while index < cursor.0 && is(src, index, b' ') {
current_line_indent += 1;
index += 1;
}
}
let mut is_map_value = false;
{
let mut index = cursor.0 as isize - 1;
while index >= line_start as isize && blank(at(src, index as usize)) {
index -= 1;
}
if index >= line_start as isize && is(src, index as usize, b':') {
is_map_value = true;
}
}
let mut entry_in: Option<usize> = None;
{
let mut index = cursor.0 as isize - 1;
while index >= line_start as isize && blank(at(src, index as usize)) {
index -= 1;
}
if index >= line_start as isize
&& index < cursor.0 as isize - 1
&& is(src, index as usize, b'-')
&& (index == line_start as isize || blank(at(src, index as usize - 1)))
{
entry_in = Some(src.slice(line_start, index as usize).chars().count());
}
}
let minimum_indent = if is_map_value {
current_line_indent + 1
} else if let Some(entry) = entry_in {
entry + 1
} else {
current_line_indent
};
let mut index = 0usize;
let scan_line = |fwd: Src<'_>, index: &mut usize| -> String {
let start = *index;
let mut stop = *index;
while fwd.has(stop) {
let byte = at(fwd, stop);
if line_end(byte) {
break;
}
if byte == i32::from(b':') && blank_line_end_or_eof(at(fwd, stop + 1)) {
break;
}
if blank(byte) && is(fwd, stop + 1, b'#') {
break;
}
if in_flow && (byte == i32::from(b']') || byte == i32::from(b'}')) {
break;
}
if byte == i32::from(b',') && in_flow {
break;
}
stop += 1;
}
*index = stop;
trim_end(fwd.slice(start, stop)).to_string()
};
let mut text = scan_line(fwd, &mut index);
let mut total_consumed = index;
let mut rows = 0usize;
while fwd.has(index) && line_end(at(fwd, index)) {
let mut blank_lines = 0usize;
while fwd.has(index) && line_end(at(fwd, index)) {
if is(fwd, index, b'\r') {
index += 1;
}
if is(fwd, index, b'\n') {
index += 1;
}
let mut leading = 0;
while blank(at(fwd, index + leading)) {
leading += 1;
}
if !fwd.has(index + leading) || line_end(at(fwd, index + leading)) {
blank_lines += 1;
index += leading;
continue;
}
break;
}
let mut line_indent = 0usize;
while blank(at(fwd, index)) {
line_indent += 1;
index += 1;
}
let doc_marker = line_indent == 0 && is_doc_marker(fwd, index);
let mut sequence_marker = false;
if is(fwd, index, b'-') && blank_line_end_or_eof(at(fwd, index + 1)) {
let mut sequence_indent: isize = -1;
let mut probe = cursor.0 as isize - 1;
while probe >= line_start as isize {
if is(src, probe as usize, b'-') && blank(at(src, probe as usize + 1)) {
sequence_indent = probe - line_start as isize;
break;
}
probe -= 1;
}
sequence_marker = (sequence_indent >= 0 && line_indent as isize == sequence_indent)
|| (sequence_indent < 0 && line_indent <= current_line_indent);
}
let can_continue = if in_flow {
fwd.has(index)
&& !line_end(at(fwd, index))
&& !is(fwd, index, b'#')
&& !is(fwd, index, b'{')
&& !is(fwd, index, b'}')
&& !is(fwd, index, b'[')
&& !is(fwd, index, b']')
} else {
line_indent >= minimum_indent
&& fwd.has(index)
&& !line_end(at(fwd, index))
&& !is(fwd, index, b'#')
&& !doc_marker
&& !sequence_marker
};
if can_continue {
let mut peek = index;
let mut is_pair = false;
while fwd.has(peek) && !line_end(at(fwd, peek)) {
if is(fwd, peek, b':') && blank_line_end_or_eof(at(fwd, peek + 1)) {
is_pair = true;
break;
}
if is(fwd, peek, b'}') || is(fwd, peek, b']') || is(fwd, peek, b',') {
break;
}
peek += 1;
}
if !is_pair || in_flow {
let continuation = scan_line(fwd, &mut index);
if !continuation.is_empty() {
if blank_lines > 0 {
for _ in 0..blank_lines {
text.push('\n');
}
} else {
text.push(' ');
}
text.push_str(&continuation);
total_consumed = index;
rows += 1;
continue;
}
}
}
break;
}
Plain {
text: trim_end(&text).to_string(),
consumed: total_consumed,
rows,
}
}
pub(crate) fn plain_scalar(
src: Src<'_>,
fwd: Src<'_>,
cursor: (usize, usize, usize),
context: &mut Context,
) -> Act {
let Plain {
text,
consumed: total_consumed,
rows,
} = plain_scalar_at(src, cursor.0, context);
if text.is_empty() {
return Act::still(cursor);
}
let core = crate::core_schema(context);
if let Some(value) = crate::yaml_keyword(&text, core) {
let next = advance_cols(src, cursor, text.len());
return Act::moved(next, Some(Tok::new("#VL", value, text, cursor)));
}
let number = if core {
crate::core_number(&text)
} else {
crate::js_to_number(&text)
};
if let Some(number) = number {
if !number.is_nan() {
let next = advance_cols(src, cursor, text.len());
return Act::moved(
next,
Some(Tok::new("#NR", Value::Number(number), text, cursor)),
);
}
}
let source = fwd.slice(0, total_consumed).to_string();
let columns = src
.slice(cursor.0, src.clamp(cursor.0 + total_consumed))
.chars()
.count();
Act::moved(
(
cursor.0 + total_consumed,
cursor.1 + rows,
cursor.2 + columns,
),
Some(Tok::new("#TX", Value::String(text), source, cursor)),
)
}
pub(crate) fn type_tag(
src: Src<'_>,
fwd: Src<'_>,
cursor: (usize, usize, usize),
context: &mut Context,
) -> Result<(usize, usize, usize), Box<Act>> {
let mut tag_end = 2;
while fwd.has(tag_end) {
let byte = at(fwd, tag_end);
if byte == i32::from(b' ')
|| line_end(byte)
|| byte == i32::from(b',')
|| byte == i32::from(b'}')
|| byte == i32::from(b']')
|| byte == i32::from(b':')
{
break;
}
tag_end += 1;
}
let tag = fwd.slice(2, tag_end).to_string();
let mut value_start = tag_end;
if is(fwd, value_start, b' ') {
value_start += 1;
}
let mut value_end = value_start;
let mut anchor_name = String::new();
if is(fwd, value_start, b'&') {
let mut anchor_end = value_start + 1;
while fwd.has(anchor_end) && !is(fwd, anchor_end, b' ') && !line_end(at(fwd, anchor_end)) {
anchor_end += 1;
}
anchor_name = fwd.slice(value_start + 1, anchor_end).to_string();
let mut pending = indexmap::IndexMap::new();
pending.insert("n".to_string(), Value::String(anchor_name.clone()));
pending.insert("i".to_string(), Value::Bool(true));
state::pend_anchor(context, &anchor_name, Value::object(pending));
if is(fwd, anchor_end, b' ') {
anchor_end += 1;
}
value_start = anchor_end;
value_end = value_start;
}
let redefined = !matches!(
state::map_get(context, state::TAG_HANDLES, "!!"),
None | Some(Value::Undefined)
);
let mut next_plain: Option<Plain> = None;
let mut tag_newline = value_start;
if is(fwd, tag_newline, b'\r') {
tag_newline += 1;
}
if is(fwd, tag_newline, b'\n') {
tag_newline += 1;
}
if tag_newline > value_start && fwd.has(tag_newline) {
let mut next_in = 0;
while is(fwd, tag_newline + next_in, b' ') {
next_in += 1;
}
let next_char = at(fwd, tag_newline + next_in);
let blank_next = next_char < 0
|| line_end(next_char)
|| next_char == i32::from(b'#')
|| next_char == i32::from(b'\t');
let here = cursor.0;
let line_start = crate::lex::line_start_of(src, here);
let mut line_in = 0;
while line_start + line_in < here && is(src, line_start + line_in, b' ') {
line_in += 1;
}
let mut q = line_start + line_in;
if line_in == 0
&& is(src, q, b'-')
&& is(src, q + 1, b'-')
&& is(src, q + 2, b'-')
&& blank(at(src, q + 3))
{
q += 3;
while q < here && blank(at(src, q)) {
q += 1;
}
}
while q < here && (is(src, q, b'&') || is(src, q, b'!')) {
while q < here && !blank(at(src, q)) {
q += 1;
}
while q < here && blank(at(src, q)) {
q += 1;
}
}
let first_on_line = q == here;
let deep_enough = if first_on_line {
next_in >= line_in
} else {
next_in > line_in
};
if blank_next || deep_enough {
let scalar_next = !blank_next
&& !b"[{&!*|>".iter().any(|&c| next_char == i32::from(c))
&& !crate::lex::block_start_at(src, here + tag_newline + next_in);
if !scalar_next {
return Ok((cursor.0 + value_start, cursor.1, cursor.2));
}
value_start = tag_newline + next_in;
value_end = value_start;
if next_char != i32::from(b'"') && next_char != i32::from(b'\'') {
next_plain = Some(plain_scalar_at(src, cursor.0 + value_start, context));
}
}
}
if is(fwd, value_start, b'"') || is(fwd, value_start, b'\'') {
let quote = at(fwd, value_start);
value_end = value_start + 1;
while fwd.has(value_end) && at(fwd, value_end) != quote {
if is(fwd, value_end, b'\\') && quote == i32::from(b'"') {
value_end += 1;
}
value_end += 1;
}
if at(fwd, value_end) == quote {
value_end += 1;
}
let raw = js_substring_less_one_unit(fwd.up_to(value_end + 4), value_start + 1, value_end);
let value = convert_tag(&tag, &raw, redefined, true);
if !anchor_name.is_empty() {
state::map_set_in_cut(context, state::ANCHORS, anchor_name, value.clone());
}
let name = token_name_for(&value, false);
let source = js_substring(fwd.up_to(value_end + 4), 0, value_end).to_string();
let next = advance_cols(src, cursor, value_end);
return Err(Box::new(Act::moved(
next,
Some(Tok::new(name, value, source, cursor)),
)));
}
while next_plain.is_none() && fwd.has(value_end) {
let byte = at(fwd, value_end);
if value_end == value_start
&& byte == i32::from(b'#')
&& value_start > 0
&& blank(at(fwd, value_start - 1))
{
break;
}
if line_end(byte)
|| byte == i32::from(b',')
|| byte == i32::from(b'}')
|| byte == i32::from(b']')
{
break;
}
if byte == i32::from(b':')
&& (is(fwd, value_end + 1, b' ')
|| line_end(at(fwd, value_end + 1))
|| at(fwd, value_end + 1) < 0)
{
break;
}
if byte == i32::from(b' ') && is(fwd, value_end + 1, b'#') {
break;
}
value_end += 1;
}
let mut raw = trim_end(fwd.slice(value_start, value_end)).to_string();
if let Some(plain) = next_plain {
raw = plain.text;
value_end = value_start + plain.consumed;
}
let value = convert_tag(&tag, &raw, redefined, false);
if !anchor_name.is_empty() {
state::map_set_in_cut(context, state::ANCHORS, anchor_name, value.clone());
}
let name = token_name_for(&value, true);
let source = fwd.slice(0, value_end).to_string();
let next = advance_cols(src, cursor, value_end);
Err(Box::new(Act::moved(
next,
Some(Tok::new(name, value, source, cursor)),
)))
}
fn convert_tag(tag: &str, raw: &str, redefined: bool, quoted: bool) -> Value {
if redefined {
return Value::String(raw.to_string());
}
match tag {
"str" if !quoted => Value::String(raw.to_string()),
"int" => Value::Number(tag_int(raw)),
"float" => Value::Number(tag_float(raw)),
"bool" => Value::Bool(raw == "true" || raw == "True" || raw == "TRUE"),
"null" => Value::Null,
_ => Value::String(raw.to_string()),
}
}
fn tag_int(raw: &str) -> f64 {
let (sign, body) = match raw.as_bytes().first() {
Some(b'-') => (-1.0, &raw[1..]),
Some(b'+') => (1.0, &raw[1..]),
_ => (1.0, raw),
};
let radix = if let Some(digits) = body.strip_prefix("0x") {
Some((digits, 16))
} else {
body.strip_prefix("0o").map(|digits| (digits, 8))
};
if let Some((digits, radix)) = radix {
if !digits.is_empty() && digits.chars().all(|c| c.is_digit(radix)) {
return sign * radix_to_f64(digits, radix);
}
}
crate::parse_int(raw)
}
pub(crate) fn radix_to_f64(digits: &str, radix: u32) -> f64 {
let width = if radix == 16 { 4 } else { 3 };
let mut bits = Vec::with_capacity(digits.len() * width);
for digit in digits.chars().filter_map(|c| c.to_digit(radix)) {
for shift in (0..width).rev() {
let bit = (digit >> shift) & 1 == 1;
if bit || !bits.is_empty() {
bits.push(bit);
}
}
}
const MANTISSA: usize = 53;
let kept = bits.len().min(MANTISSA);
let mut mantissa = bits[..kept]
.iter()
.fold(0u64, |acc, &bit| (acc << 1) | u64::from(bit));
if bits.len() > MANTISSA {
let round = bits[MANTISSA];
let sticky = bits[MANTISSA + 1..].iter().any(|&bit| bit);
if round && (sticky || mantissa & 1 == 1) {
mantissa += 1;
}
}
let exponent = bits.len() - kept;
if exponent > 1100 {
return f64::INFINITY;
}
mantissa as f64 * 2f64.powi(exponent as i32)
}
fn tag_float(raw: &str) -> f64 {
match raw {
".inf" | ".Inf" | ".INF" | "+.inf" | "+.Inf" | "+.INF" => f64::INFINITY,
"-.inf" | "-.Inf" | "-.INF" => f64::NEG_INFINITY,
".nan" | ".NaN" | ".NAN" => f64::NAN,
_ => crate::parse_float(raw),
}
}
fn token_name_for(value: &Value, empty_is_string_token: bool) -> &'static str {
match value {
Value::String(text) if empty_is_string_token && text.is_empty() => "#ST",
Value::String(_) => "#TX",
Value::Number(_) => "#NR",
_ => "#VL",
}
}