This commit is contained in:
2025-02-10 20:54:32 +01:00
parent 40c5eaf3d5
commit 9d744550c1
6 changed files with 44 additions and 15 deletions

View File

@@ -102,11 +102,17 @@ pub struct Variant {
pub elements: Vec<FmtElement>, pub elements: Vec<FmtElement>,
} }
#[test]
fn variants_parse_test() {
let vars = Variants::default().bounded("({0})");
println!("final: {vars:?}")
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, Default)] #[derive(Clone, Debug, Hash, PartialEq, Eq, Default)]
pub struct Variants(pub Vec<Variant>); pub struct Variants(pub Vec<Variant>);
impl Variants { impl Variants {
fn parse_phs(s: &'_ str) -> Vec<FmtElement> { fn parse_phs(s: &'_ str) -> Vec<FmtElement> {
let re = Regex::new(r"(?<tpl>\{\d+?[bl]?\})| (\{\{)|(\}\})").unwrap(); let re = Regex::new(r"(?<tpl>\{\d+?[bl]?\})|(\{\{)|(\}\})").unwrap();
let matches = re.captures_iter(s); let matches = re.captures_iter(s);
let slots = matches.into_iter().filter_map(|m| m.name("tpl")).map(|tpl| { let slots = matches.into_iter().filter_map(|m| m.name("tpl")).map(|tpl| {
let no_opencurly = tpl.as_str().strip_prefix("{").expect("required by regex"); let no_opencurly = tpl.as_str().strip_prefix("{").expect("required by regex");
@@ -126,7 +132,7 @@ impl Variants {
let idx = num.parse::<u32>().expect("Decimal digits required by regex"); let idx = num.parse::<u32>().expect("Decimal digits required by regex");
(tpl.range(), idx, bounded) (tpl.range(), idx, bounded)
}); });
(iter::once(None).chain(slots.into_iter().map(Some)).chain(None).tuple_windows()) (iter::once(None).chain(slots.into_iter().map(Some)).chain([None]).tuple_windows())
.flat_map(|(l, r)| { .flat_map(|(l, r)| {
let string = match (l, &r) { let string = match (l, &r) {
(None, Some((r, ..))) => &s[..r.start], (None, Some((r, ..))) => &s[..r.start],

View File

@@ -52,7 +52,7 @@ impl<'a, A> MTree<'a, A> {
} }
impl<A: Format> Format for MTree<'_, A> { impl<A: Format> Format for MTree<'_, A> {
async fn print<'a>(&'a self, c: &'a (impl FmtCtx + ?Sized + 'a)) -> FmtUnit { async fn print<'a>(&'a self, c: &'a (impl FmtCtx + ?Sized + 'a)) -> FmtUnit {
self.tok.print(c).await self.tok.print(c).boxed_local().await
} }
} }
@@ -108,7 +108,7 @@ impl<A: Format> Format for MTok<'_, A> {
Self::Atom(a) => a.print(c).await, Self::Atom(a) => a.print(c).await,
Self::Done(d) => Self::Done(d) =>
FmtUnit::new(tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("(Done){0l}"))), [ FmtUnit::new(tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("(Done){0l}"))), [
d.print(c).await, d.print(c).boxed_local().await,
]), ]),
Self::Lambda(arg, b) => FmtUnit::new( Self::Lambda(arg, b) => FmtUnit::new(
tl_cache!(Rc<Variants>: Rc::new(Variants::default() tl_cache!(Rc<Variants>: Rc::new(Variants::default()
@@ -120,7 +120,7 @@ impl<A: Format> Format for MTok<'_, A> {
Self::Ph(ph) => format!("{ph}").into(), Self::Ph(ph) => format!("{ph}").into(),
Self::Ref(r) => Self::Ref(r) =>
FmtUnit::new(tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("(ref){0l}"))), [ FmtUnit::new(tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("(ref){0l}"))), [
r.print(c).await, r.print(c).boxed_local().await,
]), ]),
Self::S(p, body) => FmtUnit::new( Self::S(p, body) => FmtUnit::new(
match *p { match *p {

View File

@@ -262,9 +262,9 @@ impl<A: AtomRepr, X: ExtraTok> Format for Token<'_, A, X> {
Self::Ph(ph) => format!("{ph}").into(), Self::Ph(ph) => format!("{ph}").into(),
Self::S(p, b) => FmtUnit::new( Self::S(p, b) => FmtUnit::new(
match *p { match *p {
Paren::Round => Rc::new(Variants::default().bounded("({0b})")), Paren::Round => tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("({0b})"))),
Paren::Curly => Rc::new(Variants::default().bounded("{{{0b}}}")), Paren::Curly => tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("{{{0b}}}"))),
Paren::Square => Rc::new(Variants::default().bounded("[{0b}]")), Paren::Square => tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("[{0b}]"))),
}, },
[ttv_fmt(b, c).await], [ttv_fmt(b, c).await],
), ),

View File

@@ -76,19 +76,24 @@ impl Format for Expr {
ExprKind::Call(f, x) => tl_cache!(Rc<Variants>: Rc::new(Variants::default() ExprKind::Call(f, x) => tl_cache!(Rc<Variants>: Rc::new(Variants::default()
.unbounded("{0} {1l}") .unbounded("{0} {1l}")
.bounded("({0} {1b})"))) .bounded("({0} {1b})")))
.units([f.print(c).await, x.print(c).await]), .units([
print_expr(f, c, visited).boxed_local().await,
print_expr(x, c, visited).boxed_local().await,
]),
ExprKind::Const(c) => format!("{c}").into(), ExprKind::Const(c) => format!("{c}").into(),
ExprKind::Lambda(None, body) => tl_cache!(Rc<Variants>: Rc::new(Variants::default() ExprKind::Lambda(None, body) => tl_cache!(Rc<Variants>: Rc::new(Variants::default()
.unbounded("\\.{0l}") .unbounded("\\.{0l}")
.bounded("(\\.{0b})"))) .bounded("(\\.{0b})")))
.units([body.print(c).await]), .units([print_expr(body, c, visited).boxed_local().await]),
ExprKind::Lambda(Some(path), body) => tl_cache!(Rc<Variants>: Rc::new(Variants::default() ExprKind::Lambda(Some(path), body) => tl_cache!(Rc<Variants>: Rc::new(Variants::default()
.unbounded("\\{0b}. {1l}") .unbounded("\\{0b}. {1l}")
.bounded("(\\{0b}. {1b})"))) .bounded("(\\{0b}. {1b})")))
.units([format!("{path}").into(), body.print(c).await]), .units([format!("{path}").into(), print_expr(body, c, visited).boxed_local().await]),
ExprKind::Seq(l, r) => ExprKind::Seq(l, r) =>
tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("[{0b}]{1l}"))) tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("[{0b}]{1l}"))).units([
.units([l.print(c).await, r.print(c).await]), print_expr(l, c, visited).boxed_local().await,
print_expr(r, c, visited).boxed_local().await,
]),
} }
} }
} }

View File

@@ -91,6 +91,15 @@ impl Format for Item {
tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("macro {{\n\t{0}\n}}"))) tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("macro {{\n\t{0}\n}}")))
.units([Variants::sequence(rules.len(), "\n", None) .units([Variants::sequence(rules.len(), "\n", None)
.units(join_all(rules.iter().map(|r| r.print(c))).await)]), .units(join_all(rules.iter().map(|r| r.print(c))).await)]),
ItemKind::Member(mem) => match mem.kind.get() {
None => format!("lazy {}", mem.name).into(),
Some(MemberKind::Const(val)) =>
tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("const {0} = {1}")))
.units([mem.name.rc().into(), val.print(c).await]),
Some(MemberKind::Mod(module)) =>
tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("module {0} {{\n\t{1}\n}}")))
.units([mem.name.rc().into(), module.print(c).boxed_local().await]),
},
_ => panic!(), _ => panic!(),
}; };
tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("{0}\n{1}"))) tl_cache!(Rc<Variants>: Rc::new(Variants::default().bounded("{0}\n{1}")))
@@ -164,6 +173,15 @@ impl Module {
) )
} }
} }
impl Format for Module {
async fn print<'a>(&'a self, c: &'a (impl FmtCtx + ?Sized + 'a)) -> FmtUnit {
let import_str = self.imports.iter().map(|i| format!("import {i}")).join("\n");
let head_str = format!("{import_str}\nexport ::({})\n", self.exports.iter().join(", "));
Variants::sequence(self.items.len() + 1, "\n", None).units(
[head_str.into()].into_iter().chain(join_all(self.items.iter().map(|i| i.print(c))).await),
)
}
}
pub struct LazyMemberHandle(api::TreeId, System, Vec<Tok<String>>); pub struct LazyMemberHandle(api::TreeId, System, Vec<Tok<String>>);
impl LazyMemberHandle { impl LazyMemberHandle {

View File

@@ -10,7 +10,7 @@ use clap::{Parser, Subcommand};
use futures::{Stream, TryStreamExt, io}; use futures::{Stream, TryStreamExt, io};
use orchid_base::clone; use orchid_base::clone;
use orchid_base::error::ReporterImpl; use orchid_base::error::ReporterImpl;
use orchid_base::format::{FmtCtxImpl, take_first}; use orchid_base::format::{FmtCtxImpl, Format, take_first};
use orchid_base::logging::{LogStrategy, Logger}; use orchid_base::logging::{LogStrategy, Logger};
use orchid_base::parse::Snippet; use orchid_base::parse::Snippet;
use orchid_base::tree::ttv_fmt; use orchid_base::tree::ttv_fmt;
@@ -111,7 +111,7 @@ async fn main() -> io::Result<ExitCode> {
return; return;
} }
for item in ptree { for item in ptree {
println!("{item:?}") println!("{}", take_first(&item.print(&FmtCtxImpl { i: &ctx.i }).await, true))
} }
}, },
} }