use crate::jqlang::{JqVal, NumLit};
use std::rc::Rc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Style {
#[default]
Plain,
Single,
Double,
Literal,
Folded,
Flow,
Block,
}
impl Style {
pub fn name(self) -> &'static str {
match self {
Style::Plain | Style::Block => "",
Style::Single => "single",
Style::Double => "double",
Style::Literal => "literal",
Style::Folded => "folded",
Style::Flow => "flow",
}
}
pub fn parse(s: &str) -> Style {
match s {
"single" | "singleQuoted" | "single_quoted" => Style::Single,
"double" | "doubleQuoted" | "double_quoted" => Style::Double,
"literal" => Style::Literal,
"folded" => Style::Folded,
"flow" => Style::Flow,
_ => Style::Plain,
}
}
pub fn is_block_scalar(self) -> bool {
matches!(self, Style::Literal | Style::Folded)
}
}
#[derive(Debug, Clone)]
pub struct NodeMeta {
pub head: Rc<str>,
pub line: Rc<str>,
pub foot: Rc<str>,
pub anchor: Rc<str>,
pub alias: Rc<str>,
pub tag: Rc<str>,
pub style: Style,
pub line_no: u32,
pub col_no: u32,
pub path: Rc<Vec<JqVal>>,
pub key: Option<Rc<JqVal>>,
pub is_key: bool,
pub doc: u32,
pub file: Rc<str>,
pub file_index: u32,
pub raw: Rc<str>,
pub blank: bool,
pub marker: bool,
pub explicit_doc: bool,
pub written: Option<Entries>,
}
thread_local! {
static EMPTY: Rc<str> = Rc::from("");
}
pub fn empty_str() -> Rc<str> {
EMPTY.with(Rc::clone)
}
impl Default for NodeMeta {
fn default() -> Self {
let e = empty_str();
NodeMeta {
head: e.clone(),
line: e.clone(),
foot: e.clone(),
anchor: e.clone(),
alias: e.clone(),
tag: e.clone(),
style: Style::Plain,
line_no: 0,
col_no: 0,
path: Rc::new(Vec::new()),
key: None,
is_key: false,
doc: 0,
file: e.clone(),
file_index: 0,
raw: e,
blank: false,
marker: false,
explicit_doc: false,
written: None,
}
}
}
impl NodeMeta {
pub fn is_bare(&self) -> bool {
self.head.is_empty()
&& self.line.is_empty()
&& self.foot.is_empty()
&& self.anchor.is_empty()
&& self.alias.is_empty()
&& self.tag.is_empty()
&& self.raw.is_empty()
&& self.written.is_none()
&& !self.blank
&& !self.marker
&& !self.explicit_doc
&& self.line_no == 0
&& self.col_no == 0
&& self.path.is_empty()
&& self.key.is_none()
&& !self.is_key
&& self.file.is_empty()
&& matches!(self.style, Style::Plain | Style::Block)
}
}
pub type Entries = Rc<Vec<(Rc<str>, JqVal)>>;
#[derive(Debug, Clone)]
pub struct YNode {
pub meta: NodeMeta,
pub val: JqVal,
}
pub fn quote_scalar_value(v: &JqVal) -> String {
match v.bare() {
JqVal::Null => "null".to_string(),
JqVal::Bool(b) => b.to_string(),
JqVal::Num(n, lit) => match lit {
NumLit::Text(t) => t.to_string(),
_ => crate::jqlang::fmt_num(*n),
},
JqVal::Str(s) => quote_scalar(s, Style::Plain),
other => crate::jqlang::render(other),
}
}
pub fn implicit_tag(v: &JqVal) -> &'static str {
match v.bare() {
JqVal::Null => "!!null",
JqVal::Bool(_) => "!!bool",
JqVal::Num(n, lit) => {
let is_int = match lit {
NumLit::Text(l) => !l.contains(['.', 'e', 'E']),
_ => n.fract() == 0.0 && n.is_finite(),
};
if is_int {
"!!int"
} else {
"!!float"
}
}
JqVal::Str(_) => "!!str",
JqVal::Arr(_) => "!!seq",
JqVal::Obj(_) => "!!map",
JqVal::Node(_) => "!!str",
}
}
pub fn resolved_tag(v: &JqVal) -> &'static str {
if let JqVal::Node(n) = v {
if n.meta.style == Style::Plain {
if let JqVal::Str(s) = &n.val {
if is_timestamp(s) {
return "!!timestamp";
}
}
}
}
implicit_tag(v)
}
fn is_timestamp(s: &str) -> bool {
fn digits(s: &str, min: usize, max: usize) -> Option<&str> {
let n = s.bytes().take_while(u8::is_ascii_digit).count();
(min..=max).contains(&n).then(|| &s[n..])
}
let Some(r) = digits(s, 4, 4) else {
return false;
};
let Some(r) = r.strip_prefix('-').and_then(|r| digits(r, 1, 2)) else {
return false;
};
let Some(r) = r.strip_prefix('-').and_then(|r| digits(r, 1, 2)) else {
return false;
};
if r.is_empty() {
return true;
}
let r = match r.strip_prefix(['T', 't']) {
Some(r) => r,
None if r.starts_with([' ', '\t']) => r.trim_start_matches([' ', '\t']),
None => return false,
};
let Some(r) = digits(r, 1, 2) else {
return false;
};
let Some(r) = r.strip_prefix(':').and_then(|r| digits(r, 2, 2)) else {
return false;
};
let Some(mut r) = r.strip_prefix(':').and_then(|r| digits(r, 2, 2)) else {
return false;
};
if let Some(f) = r.strip_prefix('.') {
r = f.trim_start_matches(|c: char| c.is_ascii_digit());
}
let r = r.trim_start_matches([' ', '\t']);
match r.strip_prefix(['Z', '+', '-']) {
_ if r.is_empty() => true,
Some(z) if r.starts_with('Z') => z.is_empty(),
Some(z) => digits(z, 1, 2).is_some_and(|t| {
t.is_empty()
|| t.strip_prefix(':')
.and_then(|m| digits(m, 2, 2))
.is_some_and(str::is_empty)
}),
None => false,
}
}
pub fn kind_of(v: &JqVal) -> &'static str {
if let JqVal::Node(n) = v {
if !n.meta.alias.is_empty() {
return "alias";
}
}
match v.bare() {
JqVal::Arr(_) => "seq",
JqVal::Obj(_) => "map",
_ => "scalar",
}
}
#[derive(Debug, Clone, Copy)]
pub struct Emit {
pub indent: usize,
}
impl Default for Emit {
fn default() -> Self {
Emit { indent: 2 }
}
}
pub fn emit_docs(docs: &[JqVal], o: Emit) -> String {
let mut out = String::new();
for (i, d) in docs.iter().enumerate() {
if i > 0 || d.meta().is_some_and(|m| m.explicit_doc) {
out.push_str("---\n");
}
out.push_str(&emit_doc(d, o));
}
out
}
pub fn emit_doc(v: &JqVal, o: Emit) -> String {
let mut out = String::new();
let m = v.meta();
if let Some(m) = m {
push_comment(&mut out, &m.head, 0);
}
match v.bare() {
JqVal::Obj(map) if !map.is_empty() && !is_flow(v) && !is_alias(v) => {
push_block_map(&mut out, entries(v, map), 0, o)
}
JqVal::Arr(a) if !a.is_empty() && !is_flow(v) && !is_alias(v) => {
push_block_seq(&mut out, a, 0, o)
}
_ => {
out.push_str(&inline(v, o));
out.push('\n');
}
}
if let Some(m) = m {
push_foot(&mut out, &m.foot, 0);
}
while out.ends_with("\n\n") {
out.pop();
}
out
}
fn is_flow(v: &JqVal) -> bool {
v.meta().is_some_and(|m| m.style == Style::Flow)
}
fn is_alias(v: &JqVal) -> bool {
v.meta().is_some_and(|m| !m.alias.is_empty())
}
fn push_foot(out: &mut String, text: &str, ind: usize) {
if text.is_empty() {
return;
}
push_comment(out, text, ind);
out.push('\n');
}
fn push_comment(out: &mut String, text: &str, ind: usize) {
if text.is_empty() {
return;
}
for line in text.split('\n') {
for _ in 0..ind {
out.push(' ');
}
out.push('#');
if !line.is_empty() {
out.push(' ');
out.push_str(line);
}
out.push('\n');
}
}
fn decorations(v: &JqVal) -> String {
let Some(m) = v.meta() else {
return String::new();
};
let mut s = String::new();
if !m.anchor.is_empty() {
s.push('&');
s.push_str(&m.anchor);
s.push(' ');
}
if !m.tag.is_empty() {
s.push_str(&m.tag);
s.push(' ');
}
s
}
fn entries<'a>(v: &'a JqVal, map: &'a [(Rc<str>, JqVal)]) -> &'a [(Rc<str>, JqVal)] {
match v.meta().and_then(|m| m.written.as_ref()) {
Some(w) => w.as_slice(),
None => map,
}
}
fn push_block_map(out: &mut String, map: &[(Rc<str>, JqVal)], ind: usize, o: Emit) {
for (k, v) in map.iter() {
let key_node = v.meta().and_then(|m| m.key.clone());
let km = key_node.as_deref().and_then(JqVal::meta);
let head: Rc<str> = km.map_or(Rc::from(""), |m| m.head.clone());
let foot: Rc<str> = match km.map(|m| m.foot.clone()).filter(|f| !f.is_empty()) {
Some(f) => f,
None => v.meta().map_or(Rc::from(""), |m| m.foot.clone()),
};
push_comment(out, &head, ind);
pad(out, ind);
out.push_str(&scalar_key(k, key_node.as_deref()));
out.push(':');
push_value(out, v, ind, o);
push_foot(out, &foot, ind);
}
}
fn first_key_head(item: &JqVal) -> Rc<str> {
let JqVal::Obj(m) = item.bare() else {
return Rc::from("");
};
m.first()
.and_then(|(_, v)| v.meta())
.and_then(|mm| mm.key.as_deref())
.and_then(JqVal::meta)
.map_or(Rc::from(""), |km| km.head.clone())
}
fn strip_leading_comment(body: &str) -> &str {
let mut rest = body;
while rest.trim_start_matches(' ').starts_with('#') {
match rest.find('\n') {
Some(at) => rest = &rest[at + 1..],
None => return "",
}
}
rest
}
fn push_block_seq(out: &mut String, items: &[JqVal], ind: usize, o: Emit) {
for item in items {
if let Some(m) = item.meta() {
push_comment(out, &m.head, ind);
}
pad(out, ind);
out.push('-');
let marker = item.meta().is_some_and(|m| m.marker);
if marker {
let note = first_key_head(item);
out.push_str(" # ");
out.push_str(¬e);
out.push('\n');
}
match item.bare() {
JqVal::Obj(map) if !map.is_empty() && !is_flow(item) && !is_alias(item) => {
let mut body = String::new();
push_block_map(&mut body, entries(item, map), ind + o.indent, o);
if marker {
out.push_str(strip_leading_comment(&body));
} else {
out.push(' ');
out.push_str(&decorations(item));
out.push_str(body.trim_start_matches(' '));
}
}
JqVal::Arr(a) if !a.is_empty() && !is_flow(item) && !is_alias(item) => {
out.push('\n');
push_block_seq(out, a, ind + o.indent, o);
}
_ => {
out.push(' ');
out.push_str(&inline(item, o));
push_line_comment(out, item);
out.push('\n');
}
}
if let Some(m) = item.meta() {
push_foot(out, &m.foot, ind);
}
}
}
fn push_value(out: &mut String, v: &JqVal, ind: usize, o: Emit) {
let style = v.meta().map_or(Style::Plain, |m| m.style);
let head: Rc<str> = v.meta().map_or(Rc::from(""), |m| m.head.clone());
match v.bare() {
JqVal::Obj(map) if !map.is_empty() && !is_flow(v) && !is_alias(v) => {
let deco = decorations(v);
if !deco.is_empty() {
out.push(' ');
out.push_str(deco.trim_end());
}
push_line_comment(out, v);
out.push('\n');
push_comment(out, &head, ind + o.indent);
push_block_map(out, entries(v, map), ind + o.indent, o);
}
JqVal::Arr(a) if !a.is_empty() && !is_flow(v) && !is_alias(v) => {
let deco = decorations(v);
if !deco.is_empty() {
out.push(' ');
out.push_str(deco.trim_end());
}
push_line_comment(out, v);
out.push('\n');
push_comment(out, &head, ind + o.indent);
push_block_seq(out, a, ind + o.indent, o);
}
JqVal::Str(s) if style.is_block_scalar() && !is_alias(v) => {
out.push(' ');
out.push_str(&decorations(v));
let raw = v
.meta()
.map(|m| m.raw.to_string())
.filter(|r| !r.is_empty());
let note = v.meta().map_or(Rc::from(""), |m| m.line.clone());
push_block_scalar(out, s, raw.as_deref(), style, ¬e, ind + o.indent);
push_comment(out, &head, ind);
}
_ => {
let text = inline(v, o);
if !text.is_empty() {
out.push(' ');
out.push_str(&text);
}
push_line_comment(out, v);
out.push('\n');
push_comment(out, &head, ind);
}
}
}
fn push_line_comment(out: &mut String, v: &JqVal) {
if let Some(m) = v.meta() {
if !m.line.is_empty() {
out.push_str(" # ");
out.push_str(&m.line);
}
}
}
fn push_block_scalar(
out: &mut String,
s: &str,
raw: Option<&str>,
style: Style,
note: &str,
ind: usize,
) {
out.push(if style == Style::Literal { '|' } else { '>' });
let trailing = s.len() - s.trim_end_matches('\n').len();
match trailing {
0 => out.push('-'),
1 => {}
_ => out.push('+'),
}
if !note.is_empty() {
out.push_str(" # ");
out.push_str(note);
}
out.push('\n');
let body = if trailing > 1 {
&s[..s.len() - (trailing - 1)]
} else {
s
};
let body = raw.unwrap_or(body);
let lines: Vec<&str> = body.trim_end_matches('\n').split('\n').collect();
let strip = lines
.iter()
.skip(1)
.filter(|l| !l.trim().is_empty())
.map(|l| l.len() - l.trim_start_matches(' ').len())
.min()
.unwrap_or(0);
for (i, line) in lines.iter().enumerate() {
if line.trim().is_empty() {
out.push('\n');
continue;
}
pad(out, ind);
out.push_str(if i == 0 {
line
} else {
&line[strip.min(line.len())..]
});
out.push('\n');
}
for _ in 1..trailing {
out.push('\n');
}
}
fn pad(out: &mut String, n: usize) {
for _ in 0..n {
out.push(' ');
}
}
fn scalar_key(k: &str, node: Option<&JqVal>) -> String {
let style = node.and_then(JqVal::meta).map_or(Style::Plain, |m| m.style);
let deco = node.map(decorations).unwrap_or_default();
let body = match style {
Style::Plain | Style::Block if !needs_single_quote(k) && !k.is_empty() => k.to_string(),
_ => quote_scalar(k, style),
};
format!("{deco}{body}")
}
fn inline(v: &JqVal, o: Emit) -> String {
let _ = o;
if let Some(m) = v.meta() {
if !m.alias.is_empty() {
return format!("*{}", m.alias);
}
}
let deco = decorations(v);
let style = v.meta().map_or(Style::Plain, |m| m.style);
if let Some(m) = v.meta() {
if !m.raw.is_empty() {
return format!("{deco}{}", m.raw);
}
}
let body = match v.bare() {
JqVal::Null if v.meta().is_some_and(|m| m.blank) && deco.is_empty() => {
return String::new()
}
JqVal::Null => "null".to_string(),
JqVal::Bool(b) => b.to_string(),
JqVal::Num(n, lit) => match lit {
NumLit::Text(t) => t.to_string(),
_ => crate::jqlang::fmt_num(*n),
},
JqVal::Str(s) if !deco.is_empty() && style == Style::Plain => s.to_string(),
JqVal::Str(s) => quote_scalar(s, style),
JqVal::Arr(a) => {
let parts: Vec<String> = a.iter().map(|e| inline(e, o)).collect();
format!("[{}]", parts.join(", "))
}
JqVal::Obj(m) => {
if m.is_empty() {
"{}".to_string()
} else {
let parts: Vec<String> = m
.iter()
.map(|(k, val)| {
let kn = val.meta().and_then(|mm| mm.key.clone());
format!("{}: {}", scalar_key(k, kn.as_deref()), inline(val, o))
})
.collect();
format!("{{{}}}", parts.join(", "))
}
}
JqVal::Node(_) => unreachable!("bare() never returns a Node"),
};
format!("{deco}{body}")
}
pub fn quote_scalar(s: &str, style: Style) -> String {
match style {
Style::Single => format!("'{}'", s.replace('\'', "''")),
Style::Double => double_quote(s),
_ => {
if s.is_empty() || reparses_as_non_string(s) {
return double_quote(s);
}
if needs_single_quote(s) {
return format!("'{}'", s.replace('\'', "''"));
}
s.to_string()
}
}
}
pub fn needs_quoting(s: &str) -> bool {
s.is_empty() || reparses_as_non_string(s) || needs_single_quote(s)
}
fn reparses_as_non_string(s: &str) -> bool {
if matches!(s, "null" | "Null" | "NULL" | "~") {
return true;
}
if matches!(s, "true" | "True" | "TRUE" | "false" | "False" | "FALSE") {
return true;
}
if matches!(s, ".inf" | "-.inf" | ".nan" | ".Inf" | ".NaN") {
return true;
}
let body = s.strip_prefix(['-', '+']).unwrap_or(s);
!body.is_empty()
&& body
.chars()
.all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-' | 'x' | 'o'))
&& body.chars().any(|c| c.is_ascii_digit())
}
fn needs_single_quote(s: &str) -> bool {
let first = s.chars().next().unwrap_or(' ');
if matches!(
first,
'#' | '&'
| '*'
| '!'
| '|'
| '>'
| '%'
| '@'
| '`'
| '{'
| '}'
| '['
| ']'
| ','
| '\''
| '"'
| ' '
) {
return true;
}
if (first == '-' || first == '?' || first == ':') && s.len() > 1 && s.as_bytes()[1] == b' ' {
return true;
}
if s == "-" || s == "?" || s == ":" {
return true;
}
if s.ends_with(' ') || s.contains('\n') || s.contains('\t') {
return true;
}
s.contains(": ") || s.contains(" #") || s.ends_with(':')
}
fn double_quote(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'\r' => out.push_str("\\r"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\x{:02x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}