use crate::qterm::{leaf, tb, QTerm};
use std::sync::Arc;
pub struct Rust;
pub struct Python;
pub struct Wgsl;
pub struct Zsh;
pub struct Bash;
pub trait LiftTo<L> {
fn lift_to(&self) -> Arc<QTerm>;
}
pub trait QLiftTo {
fn qlift_to<L>(&self) -> Arc<QTerm>
where
Self: LiftTo<L>,
{
LiftTo::<L>::lift_to(self)
}
}
impl<T: ?Sized> QLiftTo for T {}
macro_rules! wgsl_lift_int {
($suffix:literal: $($t:ty),* $(,)?) => {$(
impl LiftTo<Wgsl> for $t {
fn lift_to(&self) -> Arc<QTerm> {
leaf("int_literal", &format!(concat!("{}", $suffix), self))
}
}
)*};
}
wgsl_lift_int!("u": u8, u16, u32, usize);
wgsl_lift_int!("i": i8, i16, i32, isize);
impl LiftTo<Wgsl> for f32 {
fn lift_to(&self) -> Arc<QTerm> {
leaf("float_literal", &format!("{self}f"))
}
}
impl LiftTo<Wgsl> for bool {
fn lift_to(&self) -> Arc<QTerm> {
leaf("bool_literal", &self.to_string())
}
}
macro_rules! python_lift_int {
($($t:ty),* $(,)?) => {$(
impl LiftTo<Python> for $t {
fn lift_to(&self) -> Arc<QTerm> {
leaf("integer", &self.to_string())
}
}
)*};
}
python_lift_int!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
macro_rules! python_lift_float {
($($t:ty),* $(,)?) => {$(
impl LiftTo<Python> for $t {
fn lift_to(&self) -> Arc<QTerm> {
leaf("float", &format!("{self:?}"))
}
}
)*};
}
python_lift_float!(f32, f64);
impl LiftTo<Python> for bool {
fn lift_to(&self) -> Arc<QTerm> {
if *self {
leaf("true", "True")
} else {
leaf("false", "False")
}
}
}
fn py_dquote_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, "\\x{:02x}", c as u32).unwrap(),
c => out.push(c),
}
}
out
}
impl LiftTo<Python> for str {
fn lift_to(&self) -> Arc<QTerm> {
leaf("string", &format!("\"{}\"", py_dquote_escape(self)))
}
}
impl LiftTo<Python> for String {
fn lift_to(&self) -> Arc<QTerm> {
LiftTo::<Python>::lift_to(self.as_str())
}
}
impl<T: LiftTo<Python>> LiftTo<Python> for [T] {
fn lift_to(&self) -> Arc<QTerm> {
let mut b = tb("list").w("[");
for (i, x) in self.iter().enumerate() {
if i > 0 {
b = b.w(", ");
}
b = b.c(&x.lift_to());
}
b.w("]").b()
}
}
impl<T: LiftTo<Python>> LiftTo<Python> for Vec<T> {
fn lift_to(&self) -> Arc<QTerm> {
self.as_slice().lift_to()
}
}
fn sh_dquote_escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(c, '"' | '\\' | '$' | '`') {
out.push('\\');
}
out.push(c);
}
out
}
macro_rules! shell_lifts {
($marker:ty; $($t:ty),* $(,)?) => {
impl LiftTo<$marker> for str {
fn lift_to(&self) -> Arc<QTerm> {
leaf("string", &format!("\"{}\"", sh_dquote_escape(self)))
}
}
impl LiftTo<$marker> for String {
fn lift_to(&self) -> Arc<QTerm> {
LiftTo::<$marker>::lift_to(self.as_str())
}
}
$(
impl LiftTo<$marker> for $t {
fn lift_to(&self) -> Arc<QTerm> {
leaf("number", &self.to_string())
}
}
)*
};
}
shell_lifts!(Zsh; u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);
shell_lifts!(Bash; u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);
#[cfg(test)]
mod tests {
use super::*;
use crate::term::STerm;
#[test]
fn wgsl_ints() {
assert_eq!(3u32.qlift_to::<Wgsl>().coparse(), "3u");
assert_eq!(7usize.qlift_to::<Wgsl>().coparse(), "7u");
assert_eq!((-2i32).qlift_to::<Wgsl>().coparse(), "-2i");
}
#[test]
fn wgsl_float_bool() {
assert_eq!(1.5f32.qlift_to::<Wgsl>().coparse(), "1.5f");
assert_eq!(true.qlift_to::<Wgsl>().coparse(), "true");
}
#[test]
fn wgsl_tags() {
let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Wgsl>() else {
panic!("expected tuple");
};
assert_eq!(&**tag, "int_literal");
}
#[test]
fn python_scalars() {
assert_eq!(42u64.qlift_to::<Python>().coparse(), "42");
assert_eq!((-7i32).qlift_to::<Python>().coparse(), "-7");
assert_eq!(1.0f64.qlift_to::<Python>().coparse(), "1.0");
assert_eq!(2.5f32.qlift_to::<Python>().coparse(), "2.5");
assert_eq!(true.qlift_to::<Python>().coparse(), "True");
assert_eq!(false.qlift_to::<Python>().coparse(), "False");
}
#[test]
fn python_strings() {
let owned = String::from("hi there");
assert_eq!(owned.qlift_to::<Python>().coparse(), "\"hi there\"");
assert_eq!(
"say \"hi\\\"\nbye".qlift_to::<Python>().coparse(),
"\"say \\\"hi\\\\\\\"\\nbye\""
);
}
#[test]
fn python_lists() {
let squares: Vec<u64> = (1..=5).map(|n| n * n).collect();
assert_eq!(squares.qlift_to::<Python>().coparse(), "[1, 4, 9, 16, 25]");
let nested = vec![vec![1u8], vec![2, 3]];
assert_eq!(nested.qlift_to::<Python>().coparse(), "[[1], [2, 3]]");
let empty: Vec<u8> = Vec::new();
assert_eq!(empty.qlift_to::<Python>().coparse(), "[]");
}
#[test]
fn python_tags() {
let QTerm::Tuple { tag, .. } = &*3u32.qlift_to::<Python>() else {
panic!("expected tuple");
};
assert_eq!(&**tag, "integer");
let QTerm::Tuple { tag, .. } = &*vec![1u8].qlift_to::<Python>() else {
panic!("expected tuple");
};
assert_eq!(&**tag, "list");
}
#[test]
fn zsh_strings() {
let owned = String::from("hi there");
let borrowed: &str = "/var/log";
assert_eq!(owned.qlift_to::<Zsh>().coparse(), "\"hi there\"");
assert_eq!(borrowed.qlift_to::<Zsh>().coparse(), "\"/var/log\"");
assert_eq!("plain".qlift_to::<Zsh>().coparse(), "\"plain\"");
}
#[test]
fn zsh_escaping() {
assert_eq!(
"say \"$x\" `now`".qlift_to::<Zsh>().coparse(),
"\"say \\\"\\$x\\\" \\`now\\`\""
);
}
#[test]
fn zsh_ints() {
assert_eq!(42u32.qlift_to::<Zsh>().coparse(), "42");
assert_eq!((-7i32).qlift_to::<Zsh>().coparse(), "-7");
}
#[test]
fn bash_lifts() {
let p: &str = "/var/log";
assert_eq!(p.qlift_to::<Bash>().coparse(), "\"/var/log\"");
assert_eq!(
"echo `id`".qlift_to::<Bash>().coparse(),
"\"echo \\`id\\`\""
);
assert_eq!(42u32.qlift_to::<Bash>().coparse(), "42");
}
}