use super::LiftTo;
use crate::qterm::{leaf, QTerm};
use crate::term::STerm as _;
use std::marker::PhantomData;
use std::sync::Arc;
pub const TEXT_IN_QUOTES: &str = "text-in-quotes";
const TEXT_TAG: &str = "text";
pub trait TextDialect {
const LIST_OPEN: &'static str = "[";
const LIST_SEP: &'static str = ", ";
const LIST_CLOSE: &'static str = "]";
fn string(s: &str) -> String {
json_string(s)
}
fn in_quotes(s: &str) -> String {
json_escape(s)
}
fn boolean(b: bool) -> String {
b.to_string()
}
fn float(f: f64) -> String {
json_float(f)
}
}
pub struct Json;
impl TextDialect for Json {}
pub struct Raw;
impl TextDialect for Raw {
const LIST_OPEN: &'static str = "";
const LIST_SEP: &'static str = " ";
const LIST_CLOSE: &'static str = "";
fn string(s: &str) -> String {
s.to_string()
}
fn in_quotes(s: &str) -> String {
s.to_string()
}
fn float(f: f64) -> String {
format!("{f:?}")
}
}
pub struct Text<D = Json>(PhantomData<D>);
pub struct InQuotes<M>(PhantomData<M>);
pub trait TextValue {
fn render<D: TextDialect>(&self, in_quotes: bool) -> String;
}
impl<D: TextDialect, T: TextValue + ?Sized> LiftTo<Text<D>> for T {
fn lift_to(&self) -> Arc<QTerm> {
leaf(TEXT_TAG, &self.render::<D>(false))
}
}
impl<D: TextDialect, T: TextValue + ?Sized> LiftTo<InQuotes<Text<D>>> for T {
fn lift_to(&self) -> Arc<QTerm> {
leaf(TEXT_TAG, &self.render::<D>(true))
}
}
macro_rules! text_ints {
($($t:ty),*) => {$(
impl TextValue for $t {
fn render<D: TextDialect>(&self, _in_quotes: bool) -> String {
self.to_string()
}
}
)*};
}
text_ints!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
impl TextValue for f64 {
fn render<D: TextDialect>(&self, _in_quotes: bool) -> String {
D::float(*self)
}
}
impl TextValue for f32 {
fn render<D: TextDialect>(&self, _in_quotes: bool) -> String {
D::float(format!("{self:?}").parse().unwrap_or(f64::from(*self)))
}
}
impl TextValue for bool {
fn render<D: TextDialect>(&self, _in_quotes: bool) -> String {
D::boolean(*self)
}
}
impl TextValue for str {
fn render<D: TextDialect>(&self, in_quotes: bool) -> String {
if in_quotes {
D::in_quotes(self)
} else {
D::string(self)
}
}
}
impl TextValue for String {
fn render<D: TextDialect>(&self, in_quotes: bool) -> String {
self.as_str().render::<D>(in_quotes)
}
}
impl TextValue for char {
fn render<D: TextDialect>(&self, in_quotes: bool) -> String {
self.to_string().render::<D>(in_quotes)
}
}
impl<T: TextValue> TextValue for [T] {
fn render<D: TextDialect>(&self, in_quotes: bool) -> String {
let items: Vec<String> = self.iter().map(|x| x.render::<D>(in_quotes)).collect();
let body = items.join(D::LIST_SEP);
if in_quotes {
body
} else {
format!("{}{body}{}", D::LIST_OPEN, D::LIST_CLOSE)
}
}
}
impl<T: TextValue> TextValue for Vec<T> {
fn render<D: TextDialect>(&self, in_quotes: bool) -> String {
self.as_slice().render::<D>(in_quotes)
}
}
impl<T: TextValue + ?Sized> TextValue for &T {
fn render<D: TextDialect>(&self, in_quotes: bool) -> String {
(**self).render::<D>(in_quotes)
}
}
impl TextValue for Arc<QTerm> {
fn render<D: TextDialect>(&self, _in_quotes: bool) -> String {
self.coparse()
}
}
#[must_use]
pub fn json_escape(s: &str) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' | '\\' => {
out.push('\\');
out.push(c);
}
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c.is_control() => write!(out, "\\u{:04x}", c as u32).unwrap(),
c => out.push(c),
}
}
out
}
#[must_use]
pub fn json_string(s: &str) -> String {
format!("\"{}\"", json_escape(s))
}
#[must_use]
pub fn json_float(f: f64) -> String {
assert!(
f.is_finite(),
"cannot lift {f:?} into text: JSON has no spelling for NaN or infinity \
(override `TextDialect::float` in a dialect that has one)"
);
format!("{f:?}")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lift::QLiftTo as _;
fn text<T: LiftTo<Text> + ?Sized>(x: &T) -> String {
x.lift_to().coparse()
}
fn quoted<T: LiftTo<InQuotes<Text>> + ?Sized>(x: &T) -> String {
x.lift_to().coparse()
}
#[test]
fn scalars_spell_as_json() {
assert_eq!(text(&42u64), "42");
assert_eq!(text(&-7i32), "-7");
assert_eq!(text(&u128::MAX), u128::MAX.to_string());
assert_eq!(text(&1.0f64), "1.0");
assert_eq!(text(&-1.5f32), "-1.5");
assert_eq!(text(&0.1f32), "0.1");
assert_eq!(text(&true), "true");
assert_eq!(text(&false), "false");
}
#[test]
fn strings_are_json_literals() {
assert_eq!(text("hi"), "\"hi\"");
assert_eq!(text(""), "\"\"");
assert_eq!(text(&String::from("a b")), "\"a b\"");
assert_eq!(text("say \"hi\"\\"), r#""say \"hi\"\\""#);
assert_eq!(text("a\nb\tc\r"), r#""a\nb\tc\r""#);
assert_eq!(text("\u{0}\u{7f}\u{85}"), r#""\u0000\u007f\u0085""#);
assert_eq!(text("héllo ${x} {y} 'z' #"), "\"héllo ${x} {y} 'z' #\"");
}
#[test]
fn in_quotes_is_the_escaped_contents() {
assert_eq!(quoted("hi"), "hi");
assert_eq!(quoted("say \"hi\"\n"), r#"say \"hi\"\n"#);
assert_eq!(quoted(&3u32), "3");
assert_eq!(quoted(&true), "true");
assert_eq!(quoted(&2.5f64), "2.5");
}
#[test]
fn lists_join_with_the_dialect_separator() {
assert_eq!(text(&vec![1u32, 2, 3]), "[1, 2, 3]");
assert_eq!(text(&Vec::<u8>::new()), "[]");
assert_eq!(text(&vec!["a", "b\""]), r#"["a", "b\""]"#);
assert_eq!(text(&vec![vec![1u8], vec![]]), "[[1], []]");
assert_eq!(quoted(&vec!["a", "b"]), "a, b");
}
#[test]
fn raw_is_verbatim() {
let s = "a \"b\" ${c}\n";
assert_eq!(s.qlift_to::<Text<Raw>>().coparse(), s);
assert_eq!(s.qlift_to::<InQuotes<Text<Raw>>>().coparse(), s);
assert_eq!(
vec!["a", "b", "c"].qlift_to::<Text<Raw>>().coparse(),
"a b c"
);
assert_eq!(f64::NAN.qlift_to::<Text<Raw>>().coparse(), "NaN");
}
#[test]
#[should_panic(expected = "JSON has no spelling for NaN")]
fn json_refuses_nan_at_the_lift_site() {
let _ = f64::NAN.qlift_to::<Text>();
}
#[test]
fn a_user_dialect_overrides_only_what_differs() {
struct Conf;
impl TextDialect for Conf {
const LIST_OPEN: &'static str = "";
const LIST_SEP: &'static str = "\n";
const LIST_CLOSE: &'static str = "";
fn string(s: &str) -> String {
if !s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || "._-/".contains(c)) {
s.to_string()
} else {
json_string(s)
}
}
fn boolean(b: bool) -> String {
(if b { "on" } else { "off" }).to_string()
}
}
assert_eq!("web-1".qlift_to::<Text<Conf>>().coparse(), "web-1");
assert_eq!("a b".qlift_to::<Text<Conf>>().coparse(), "\"a b\"");
assert_eq!(true.qlift_to::<Text<Conf>>().coparse(), "on");
assert_eq!(
vec!["x", "y z"].qlift_to::<Text<Conf>>().coparse(),
"x\n\"y z\""
);
assert_eq!(1.5f64.qlift_to::<Text<Conf>>().coparse(), "1.5");
assert_eq!("q\"".qlift_to::<InQuotes<Text<Conf>>>().coparse(), "q\\\"");
}
#[test]
fn a_lift_is_one_text_leaf() {
let QTerm::Tuple { tag, terms, .. } = &*vec![1u8, 2].qlift_to::<Text>() else {
panic!("expected tuple");
};
assert_eq!(&**tag, "text");
assert!(
terms.is_empty(),
"a lifted list is flat text, as the parser reads it"
);
}
}