1use crate::{
2 prelude::*,
3 strcmd::{PrefixWriter, StrCmd},
4 term::{CmdOrHole, STerm, Term},
5 validate::Validate,
6};
7use serde::{Deserialize, Serialize};
8use std::{iter::once, sync::Arc};
9
10pub type Gaps = Box<[CmdOrHole]>;
13
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
30pub enum Repr {
31 #[default]
32 Cst,
33 Str,
34 Qt,
35}
36
37impl Repr {
38 #[must_use]
40 pub fn name(self) -> &'static str {
41 match self {
42 Repr::Cst => "cst",
43 Repr::Str => "str",
44 Repr::Qt => "qt",
45 }
46 }
47
48 pub fn from_name(name: &str) -> Result<Self> {
50 match name {
51 "cst" => Ok(Repr::Cst),
52 "str" => Ok(Repr::Str),
53 "qt" => Ok(Repr::Qt),
54 _ => miette::bail!(
55 "unknown quote representation `⟨{name}⟩`: the representations are \
56 `⟨cst⟩` (the default), `⟨str⟩` and `⟨qt⟩`"
57 ),
58 }
59 }
60}
61
62impl std::fmt::Display for Repr {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 write!(f, "⟨{}⟩", self.name())
65 }
66}
67
68#[derive(Debug, Clone, Eq, Serialize, Deserialize)]
69pub enum QTerm {
70 Quote {
71 tag: Box<str>,
72 index: Index,
73 lang: Box<str>,
74 term: Arc<QTerm>,
75 cmds: Box<[CmdOrHole]>,
76 span: Option<Span>,
82 #[serde(skip)]
90 repr: Repr,
91 },
92 Unquote {
93 tag: Box<str>,
94 index: Index,
95 lang: Box<str>,
96 term: Arc<QTerm>,
97 cmds: Box<[CmdOrHole]>,
98 span: Option<Span>,
101 },
102 Tuple {
103 tag: Box<str>,
104 terms: Box<[Arc<QTerm>]>,
105 cmds: Box<[CmdOrHole]>,
106 },
107}
108
109impl PartialEq for QTerm {
112 fn eq(&self, other: &Self) -> bool {
113 match (self, other) {
114 (
115 QTerm::Quote {
116 tag,
117 index,
118 lang,
119 term,
120 cmds,
121 span: _,
122 repr,
123 },
124 QTerm::Quote {
125 tag: tag2,
126 index: index2,
127 lang: lang2,
128 term: term2,
129 cmds: cmds2,
130 span: _,
131 repr: repr2,
132 },
133 ) => {
134 tag == tag2
135 && index == index2
136 && lang == lang2
137 && term == term2
138 && cmds == cmds2
139 && repr == repr2
140 }
141 (
142 QTerm::Unquote {
143 tag,
144 index,
145 lang,
146 term,
147 cmds,
148 span: _,
149 },
150 QTerm::Unquote {
151 tag: tag2,
152 index: index2,
153 lang: lang2,
154 term: term2,
155 cmds: cmds2,
156 span: _,
157 },
158 ) => tag == tag2 && index == index2 && lang == lang2 && term == term2 && cmds == cmds2,
159 (
160 QTerm::Tuple { tag, terms, cmds },
161 QTerm::Tuple {
162 tag: tag2,
163 terms: terms2,
164 cmds: cmds2,
165 },
166 ) => tag == tag2 && terms == terms2 && cmds == cmds2,
167 _ => false,
168 }
169 }
170}
171
172pub fn quote(
173 tag: &str,
174 index: Index,
175 lang: &str,
176 term: Arc<QTerm>,
177 cmds: &[CmdOrHole],
178) -> Arc<QTerm> {
179 qquote(tag, index, lang, term, cmds).into()
180}
181pub fn unquote(
182 tag: &str,
183 index: Index,
184 lang: &str,
185 term: Arc<QTerm>,
186 cmds: &[CmdOrHole],
187) -> Arc<QTerm> {
188 qunquote(tag, index, lang, term, cmds).into()
189}
190pub fn tuple(tag: &str, terms: &[Arc<QTerm>], cmds: &[CmdOrHole]) -> Arc<QTerm> {
191 QTerm::Tuple {
192 tag: tag.into(),
193 terms: terms.into(),
194 cmds: cmds.into(),
195 }
196 .into()
197}
198pub fn leaf(s: &str, code: &str) -> Arc<QTerm> {
199 tuple(s, &[], &[cmd(write(code))])
200}
201pub fn sym(s: &str) -> Arc<QTerm> {
202 leaf(s, s)
203}
204
205pub fn qquote(tag: &str, index: Index, lang: &str, term: Arc<QTerm>, cmds: &[CmdOrHole]) -> QTerm {
206 qquote_at(tag, index, lang, term, cmds, None)
207}
208pub fn qunquote(
209 tag: &str,
210 index: Index,
211 lang: &str,
212 term: Arc<QTerm>,
213 cmds: &[CmdOrHole],
214) -> QTerm {
215 qunquote_at(tag, index, lang, term, cmds, None)
216}
217pub fn qquote_at(
218 tag: &str,
219 index: Index,
220 lang: &str,
221 term: Arc<QTerm>,
222 cmds: &[CmdOrHole],
223 span: Option<Span>,
224) -> QTerm {
225 QTerm::Quote {
226 tag: tag.into(),
227 index,
228 lang: lang.into(),
229 term,
230 cmds: cmds.into(),
231 span,
232 repr: Repr::Cst,
233 }
234}
235pub fn qquote_repr_at(
238 tag: &str,
239 index: Index,
240 lang: &str,
241 term: Arc<QTerm>,
242 cmds: &[CmdOrHole],
243 span: Option<Span>,
244 repr: Repr,
245) -> QTerm {
246 let mut q = qquote_at(tag, index, lang, term, cmds, span);
247 if let QTerm::Quote { repr: r, .. } = &mut q {
248 *r = repr;
249 }
250 q
251}
252pub fn qunquote_at(
253 tag: &str,
254 index: Index,
255 lang: &str,
256 term: Arc<QTerm>,
257 cmds: &[CmdOrHole],
258 span: Option<Span>,
259) -> QTerm {
260 QTerm::Unquote {
261 tag: tag.into(),
262 index,
263 lang: lang.into(),
264 term,
265 cmds: cmds.into(),
266 span,
267 }
268}
269pub fn qtuple(tag: &str, terms: &[Arc<QTerm>], cmds: &[CmdOrHole]) -> QTerm {
270 QTerm::Tuple {
271 tag: tag.into(),
272 terms: terms.into(),
273 cmds: cmds.into(),
274 }
275}
276pub fn qleaf(s: &str, code: &str) -> QTerm {
277 qtuple(s, &[], &[cmd(write(code))])
278}
279pub fn qsym(s: &str) -> QTerm {
280 qleaf(s, s)
281}
282
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub enum QTermTag {
285 Quote(Box<str>, Index, Box<str>),
286 Unquote(Box<str>, Index, Box<str>),
287 Tuple(Box<str>),
288}
289
290impl QTermTag {
291 pub fn tuple(tag: &str) -> Self {
292 QTermTag::Tuple(tag.into())
293 }
294}
295
296impl QTerm {
297 fn cmds(&self) -> &[CmdOrHole] {
298 match self {
299 QTerm::Quote { cmds, .. } | QTerm::Unquote { cmds, .. } | QTerm::Tuple { cmds, .. } => {
300 cmds
301 }
302 }
303 }
304
305 pub fn squash(&self) -> QTerm {
307 assert!(
308 self.len() == 1,
309 "squash called on term without exactly one child"
310 );
311 let child = &self[0];
312 let self_cmds = self.cmds();
313 let child_cmds = child.cmds();
314 let hole_ind = self_cmds
315 .iter()
316 .position(|cmd| matches!(cmd, CmdOrHole::Hole))
317 .unwrap();
318 let mut cmds = Vec::with_capacity(self_cmds.len() + child_cmds.len() - 1);
319 cmds.extend(self_cmds[..hole_ind].iter().cloned());
320 cmds.extend(child_cmds.iter().cloned());
321 cmds.extend(self_cmds[hole_ind + 1..].iter().cloned());
322 match child {
323 QTerm::Quote {
324 tag,
325 index,
326 lang,
327 term,
328 span,
329 ..
330 } => qquote_at(tag, *index, lang, term.clone(), &cmds, span.clone()),
331 QTerm::Unquote {
332 tag,
333 index,
334 lang,
335 term,
336 span,
337 ..
338 } => qunquote_at(tag, *index, lang, term.clone(), &cmds, span.clone()),
339 QTerm::Tuple { tag, terms, .. } => qtuple(tag, terms, &cmds),
340 }
341 }
342
343 pub fn rewrite_naive(&self, find: &Self, replace: &Self) -> Arc<Self> {
344 if self == find {
345 return arc(replace.clone());
346 }
347 match self {
348 QTerm::Quote {
349 tag,
350 index,
351 lang,
352 term,
353 cmds,
354 span,
355 repr,
356 } => {
357 let term = term.rewrite_naive(find, replace);
358 arc(qquote_repr_at(
359 tag,
360 *index,
361 lang,
362 term,
363 cmds,
364 span.clone(),
365 *repr,
366 ))
367 }
368 QTerm::Unquote {
369 tag,
370 index,
371 lang,
372 term,
373 cmds,
374 span,
375 } => {
376 let term = term.rewrite_naive(find, replace);
377 arc(qunquote_at(tag, *index, lang, term, cmds, span.clone()))
378 }
379 QTerm::Tuple { tag, terms, cmds } => {
380 let terms = terms
381 .iter()
382 .map(|s| s.rewrite_naive(find, replace))
383 .collect::<Vec<_>>();
384 tuple(tag, &terms, cmds)
385 }
386 }
387 }
388
389 pub fn with_content(&self, content: &str) -> Arc<Self> {
390 match self {
391 QTerm::Tuple { tag, terms, .. } if terms.is_empty() => leaf(tag, content),
392 _ => panic!("with_content: not a leaf: {self:?}"),
393 }
394 }
395
396 pub fn sexp(&self) -> String {
397 match self {
398 QTerm::Quote { lang, term, .. } => {
399 format!("{}↖{}↗", lang, term.sexp())
400 }
401 QTerm::Unquote { lang, term, .. } => {
402 format!("{}↙{}↘", lang, term.sexp())
403 }
404 QTerm::Tuple { tag, terms, .. } => {
405 if terms.is_empty() {
406 return format!("{tag}");
407 }
408 let mut ret = String::new();
409 ret.push_str(tag);
410 ret.push('(');
411 for (i, term) in terms.iter().enumerate() {
412 if i > 0 {
413 ret.push(',');
414 }
415 ret.push_str(&term.sexp());
416 }
417 ret.push(')');
418 ret
419 }
420 }
421 }
422}
423
424impl Term for QTerm {
425 type Tag = QTermTag;
426
427 fn tag(&self) -> Self::Tag {
428 match self {
429 QTerm::Quote {
430 tag, index, lang, ..
431 } => QTermTag::Quote(tag.clone(), *index, lang.clone()),
432 QTerm::Unquote {
433 tag, index, lang, ..
434 } => QTermTag::Unquote(tag.clone(), *index, lang.clone()),
435 QTerm::Tuple { tag, .. } => QTermTag::Tuple(tag.clone()),
436 }
437 }
438
439 fn children(&self) -> impl Iterator<Item = &Self> {
440 let ret: Box<dyn Iterator<Item = _>> = match self {
441 QTerm::Quote { term, .. } | QTerm::Unquote { term, .. } => bx(once(term.as_ref())),
442 QTerm::Tuple { terms, .. } => bx(terms.iter().map(|x| x.as_ref())),
443 };
444 ret
445 }
446
447 fn len(&self) -> usize {
448 match self {
449 QTerm::Quote { .. } | QTerm::Unquote { .. } => 1,
450 QTerm::Tuple { terms, .. } => terms.len(),
451 }
452 }
453
454 fn is_empty(&self) -> bool {
455 match self {
456 QTerm::Quote { .. } | QTerm::Unquote { .. } => false,
457 QTerm::Tuple { terms, .. } => terms.is_empty(),
458 }
459 }
460}
461
462impl QTerm {
463 fn is_deferred_operator(&self) -> bool {
476 let QTerm::Tuple { tag, terms, cmds } = self else {
477 return false;
478 };
479 if !terms.is_empty() {
480 return false;
481 }
482 match cmds.as_ref() {
483 [CmdOrHole::Cmd(StrCmd::Write(text))] => {
484 **text != **tag && crate::glyphs::is_deferred_operator(text)
485 }
486 _ => false,
487 }
488 }
489
490 fn is_plain_comment(&self) -> bool {
502 matches!(self, QTerm::Tuple { tag, .. } if crate::lang::is_comment_tag(tag))
503 && self
504 .leading_text()
505 .is_some_and(|t| t.starts_with("//") || t.starts_with("/*"))
506 }
507
508 fn leading_text(&self) -> Option<&str> {
511 for cmd in self.cmds() {
512 match cmd {
513 CmdOrHole::Cmd(StrCmd::Write(s)) if !s.is_empty() => return Some(s),
514 CmdOrHole::Cmd(_) => {}
515 CmdOrHole::Hole => return self.children().next().and_then(Self::leading_text),
516 }
517 }
518 None
519 }
520}
521
522impl STerm for QTerm {
523 fn write<W: std::io::Write>(&self, writer: &mut PrefixWriter<'_, W>) {
524 match self {
525 QTerm::Quote { term, cmds, .. } | QTerm::Unquote { term, cmds, .. } => {
526 let outer = writer.set_escaping(false);
530 let outer_bracketed = writer.bracketed();
531 for cmd in cmds {
532 match cmd {
533 CmdOrHole::Cmd(cmd) => writer.interpret(cmd),
534 CmdOrHole::Hole => {
535 writer.set_escaping(outer);
536 writer.set_bracketed(true);
537 term.write(writer);
538 writer.set_bracketed(outer_bracketed);
539 writer.set_escaping(false);
540 }
541 }
542 }
543 writer.set_escaping(outer);
544 }
545 QTerm::Tuple { terms, cmds, .. } => {
546 let raw =
556 (writer.bracketed() && self.is_deferred_operator()) || self.is_plain_comment();
557 let outer = if raw {
558 writer.set_escaping(false)
559 } else {
560 writer.escaping()
561 };
562 let mut children = terms.iter();
563 for cmd in cmds {
564 match cmd {
565 CmdOrHole::Cmd(cmd) => writer.interpret(cmd),
566 CmdOrHole::Hole => children.next().unwrap().write(writer),
567 }
568 }
569 writer.set_escaping(outer);
570 }
571 }
572 }
573}
574
575impl std::ops::Index<usize> for QTerm {
576 type Output = QTerm;
577
578 fn index(&self, index: usize) -> &Self::Output {
579 self.get(index).unwrap()
580 }
581}
582
583impl Validate for QTerm {
584 type Error = miette::Error;
585
586 fn validate(self) -> Result<Self, Self::Error> {
587 let mut depth: u32 = 0;
588 let mut holes = 0;
589 for cmd in self.cmds() {
590 match cmd {
591 CmdOrHole::Cmd(cmd) => match cmd {
592 StrCmd::Push(_) => depth += 1,
593 StrCmd::Pop => {
594 if depth == 0 {
595 miette::bail!("running stack depth below 0");
596 }
597 depth -= 1;
598 }
599 _ => (),
600 },
601 CmdOrHole::Hole => {
602 holes += 1;
603 }
604 }
605 }
606 if depth != 0 {
607 miette::bail!("total stack depth not 0");
608 }
609 if holes != self.len() {
610 miette::bail!("number of holes does not match number of children");
611 }
612 Ok(self)
613 }
614}
615
616pub struct QTermBuilder {
619 tag: QTermTag,
620 children: Vec<Arc<QTerm>>,
621 cmds: Vec<CmdOrHole>,
622 span: Option<Span>,
624 repr: Repr,
626 sep: Option<Separated>,
628 aligned: bool,
631}
632
633struct Separated {
636 token: Box<str>,
637 last: Option<usize>,
641}
642
643impl Separated {
644 fn is_token(&self, child: &QTerm) -> bool {
646 match child {
647 QTerm::Tuple { tag, terms, cmds } => {
648 **tag == *self.token
649 && terms.is_empty()
650 && matches!(&**cmds, [CmdOrHole::Cmd(StrCmd::Write(s))] if **s == *self.token)
651 }
652 _ => false,
653 }
654 }
655}
656
657impl QTermBuilder {
658 pub fn new(tag: QTermTag) -> Self {
659 Self {
660 tag,
661 children: Vec::new(),
662 cmds: Vec::new(),
663 span: None,
664 repr: Repr::Cst,
665 sep: None,
666 aligned: false,
667 }
668 }
669
670 pub fn span(&mut self, span: Span) -> &mut Self {
671 self.span = Some(span);
672 self
673 }
674
675 pub fn repr(&mut self, repr: Repr) -> &mut Self {
677 self.repr = repr;
678 self
679 }
680
681 pub fn child(&mut self, child: &Arc<QTerm>) -> &mut Self {
682 if let Some(sep) = &mut self.sep {
683 if sep.is_token(child) {
684 sep.last = None;
685 } else {
686 if let Some(at) = sep.last {
687 let between = &self.cmds[at + 1..];
688 let placed = between.iter().any(
689 |c| matches!(c, CmdOrHole::Cmd(StrCmd::Write(s)) if s.contains(&*sep.token)),
690 );
691 if !placed {
692 let adjacent = between.is_empty();
698 self.cmds.insert(at + 1, CmdOrHole::Hole);
699 self.children.push(sym(&sep.token));
700 if adjacent {
701 self.cmds.push(CmdOrHole::Cmd(StrCmd::Write(" ".into())));
702 }
703 }
704 }
705 sep.last = Some(self.cmds.len());
706 }
707 }
708 self.cmds.push(CmdOrHole::Hole);
709 self.children.push(child.clone());
710 self
711 }
712
713 pub fn sep(&mut self, token: &str) -> &mut Self {
723 self.sep = Some(Separated {
724 token: token.into(),
725 last: None,
726 });
727 self
728 }
729
730 pub fn end_sep(&mut self) -> &mut Self {
732 self.sep = None;
733 self
734 }
735
736 pub fn cmd(&mut self, cmd: &StrCmd) -> &mut Self {
737 self.cmds.push(CmdOrHole::Cmd(cmd.clone()));
738 self
739 }
740
741 pub fn build(self) -> QTerm {
742 match self.tag {
743 QTermTag::Quote(tag, index, lang) => {
744 assert_eq!(self.children.len(), 1);
745 let mut q = qquote_at(
746 &tag,
747 index,
748 &lang,
749 self.children[0].clone(),
750 &self.cmds,
751 self.span,
752 );
753 if let QTerm::Quote { repr, .. } = &mut q {
754 *repr = self.repr;
755 }
756 q
757 }
758 QTermTag::Unquote(tag, index, lang) => {
759 assert_eq!(self.children.len(), 1);
760 qunquote_at(
761 &tag,
762 index,
763 &lang,
764 self.children[0].clone(),
765 &self.cmds,
766 self.span,
767 )
768 }
769 QTermTag::Tuple(tag) => qtuple(&tag, &self.children, &self.cmds),
770 }
771 }
772
773 pub fn first(self) -> Option<Arc<QTerm>> {
774 self.children.first().cloned()
775 }
776
777 pub fn write(&mut self, s: &str) -> &mut Self {
780 if s.is_empty() {
781 self
782 } else {
783 self.cmd(&StrCmd::Write(s.into()))
784 }
785 }
786
787 pub fn nl(&mut self) -> &mut Self {
788 self.cmd(&StrCmd::NewLine)
789 }
790
791 pub fn push(&mut self, s: &str) -> &mut Self {
792 self.cmd(&StrCmd::Push(s.into()))
795 }
796
797 pub fn pop(&mut self) -> &mut Self {
798 self.aligned = false;
799 self.cmd(&StrCmd::Pop)
800 }
801
802 pub fn align(&mut self, pad: &str) -> &mut Self {
813 self.push(pad);
814 self.aligned = true;
815 self
816 }
817
818 pub fn text(&mut self, s: &str) -> &mut Self {
822 if !self.aligned {
823 return self.write(s);
824 }
825 for (i, line) in s.split('\n').enumerate() {
826 if i > 0 {
827 self.nl();
828 }
829 self.write(line);
830 }
831 self
832 }
833
834 pub fn emit(&mut self, x: impl Emit) -> &mut Self {
835 x.emit(self);
836 self
837 }
838
839 pub fn write_if(&mut self, s: &str, b: bool) -> &mut Self {
840 if b && !s.is_empty() {
841 self.cmd(&StrCmd::Write(s.into()))
842 } else {
843 self
844 }
845 }
846
847 pub fn nl_if(&mut self, b: bool) -> &mut Self {
848 if b {
849 self.cmd(&StrCmd::NewLine)
850 } else {
851 self
852 }
853 }
854
855 pub fn push_if(&mut self, s: &str, b: bool) -> &mut Self {
856 if b {
857 self.cmd(&StrCmd::Push(s.into()))
858 } else {
859 self
860 }
861 }
862
863 pub fn pop_if(&mut self, b: bool) -> &mut Self {
864 if b {
865 self.cmd(&StrCmd::Pop)
866 } else {
867 self
868 }
869 }
870
871 pub fn c(mut self, child: &Arc<QTerm>) -> Self {
872 self.child(child);
873 self
874 }
875 pub fn w(mut self, s: &str) -> Self {
876 self.write(s);
877 self
878 }
879 pub fn n(mut self) -> Self {
880 self.nl();
881 self
882 }
883 pub fn p(mut self, s: &str) -> Self {
884 self.push(s);
885 self
886 }
887 pub fn x(mut self) -> Self {
888 self.pop();
889 self
890 }
891 pub fn e(mut self, x: impl Emit) -> Self {
892 self.emit(x);
893 self
894 }
895 pub fn b(self) -> Arc<QTerm> {
896 arc(self.build())
897 }
898}
899
900pub fn qb(tag: &str, index: Index, lang: &str) -> QTermBuilder {
901 QTermBuilder::new(QTermTag::Quote(tag.into(), index, lang.into()))
902}
903pub fn ub(tag: &str, index: Index, lang: &str) -> QTermBuilder {
904 QTermBuilder::new(QTermTag::Unquote(tag.into(), index, lang.into()))
905}
906pub fn tb(tag: &str) -> QTermBuilder {
907 QTermBuilder::new(QTermTag::Tuple(tag.into()))
908}
909
910pub trait Emit {
937 fn emit(self, builder: &mut QTermBuilder);
938}
939
940impl Emit for &Arc<QTerm> {
941 fn emit(self, builder: &mut QTermBuilder) {
942 builder.child(self);
943 }
944}
945
946impl Emit for &() {
947 fn emit(self, _builder: &mut QTermBuilder) {}
948}
949
950impl<'a, T> Emit for &'a Vec<T>
955where
956 &'a T: Emit,
957{
958 fn emit(self, builder: &mut QTermBuilder) {
959 for item in self {
960 item.emit(builder);
961 }
962 }
963}
964
965impl Emit for &str {
966 fn emit(self, builder: &mut QTermBuilder) {
967 builder.text(self);
968 }
969}
970
971impl Emit for &String {
977 fn emit(self, builder: &mut QTermBuilder) {
978 builder.text(self);
979 }
980}
981
982impl<'a, T: ?Sized> Emit for &&'a T
986where
987 &'a T: Emit,
988{
989 fn emit(self, builder: &mut QTermBuilder) {
990 (*self).emit(builder);
991 }
992}
993
994impl Emit for &StrCmd {
995 fn emit(self, builder: &mut QTermBuilder) {
996 builder.cmd(self);
997 }
998}
999
1000#[allow(unused_macros)]
1001macro_rules! emit {
1002 ($b:expr, $e:expr) => {
1004 $e.emit(&mut $b);
1005 };
1006 ($b:expr, $e:expr, $($rest:expr),+) => {
1007 emit!($b, $e);
1008 emit!($b, $($rest),+);
1009 };
1010}
1011
1012#[cfg(test)]
1015mod tests {
1016 use super::*;
1017
1018 #[test]
1019 fn emit() {
1020 let mut b_ = tb("block");
1021 sym("a").emit(&mut b_);
1022 ().emit(&mut b_);
1023 vec![sym("b"), sym("c")].emit(&mut b_);
1024 let qterm = b_.build();
1025
1026 let expected = tb("block").c(&sym("a")).c(&sym("b")).c(&sym("c")).build();
1027 assert_eq!(qterm, expected);
1028 }
1029
1030 #[test]
1042 fn emit_borrows_rather_than_consuming() {
1043 let name = sym("a");
1044 let mut b_ = tb("block");
1045 name.emit(&mut b_);
1046 name.emit(&mut b_);
1048 let terms = vec![sym("b")];
1049 terms.emit(&mut b_);
1050 terms.emit(&mut b_);
1051 assert_eq!(name, sym("a"));
1052
1053 let expected = tb("block")
1054 .c(&sym("a"))
1055 .c(&sym("a"))
1056 .c(&sym("b"))
1057 .c(&sym("b"))
1058 .build();
1059 assert_eq!(b_.build(), expected);
1060 }
1061
1062 #[test]
1063 fn emit_macro() {
1064 let mut b_ = tb("block");
1065 emit!(b_, sym("a"), (), vec![sym("b"), sym("c")]);
1066 let qterm = b_.build();
1067
1068 let expected = tb("block").c(&sym("a")).c(&sym("b")).c(&sym("c")).build();
1069 assert_eq!(qterm, expected);
1070 }
1071
1072 #[test]
1073 fn emit_macro_nested() {
1074 let mut b_ = tb("block");
1075 emit!(b_, sym("a"), {
1076 emit!(b_, sym("b"));
1077 sym("c")
1078 });
1079 let qterm = b_.build();
1080
1081 let expected = tb("block").c(&sym("a")).c(&sym("b")).c(&sym("c")).build();
1082 assert_eq!(qterm, expected);
1083 }
1084
1085 #[test]
1099 fn postcard_round_trip_preserves_spans() {
1100 let inner = qunquote_at("x", 1, "rs", sym("n"), &[HOLE], Some(7..12)).into();
1101 let quoted = qquote_at("q", 0, "py", inner, &[HOLE], Some(3..20)).into();
1102 let term: Arc<QTerm> = tb("block").w("[").c("ed).w("]").b();
1103
1104 let bytes = postcard::to_allocvec(&term).expect("serializes");
1105 let back: Arc<QTerm> = postcard::from_bytes(&bytes).expect("deserializes");
1106
1107 assert_eq!(back, term, "round trip changed the tree");
1108 assert_eq!(
1109 back.coparse(),
1110 term.coparse(),
1111 "round trip changed the text"
1112 );
1113 assert_eq!(
1114 postcard::to_allocvec(&back).expect("re-serializes"),
1115 bytes,
1116 "round trip re-serializes to different bytes"
1117 );
1118
1119 let QTerm::Tuple { terms, .. } = &*back else {
1121 panic!("expected a tuple");
1122 };
1123 let QTerm::Quote { span, term, .. } = &*terms[0] else {
1124 panic!("expected a quote");
1125 };
1126 assert_eq!(*span, Some(3..20), "the quote's span was lost");
1127 let QTerm::Unquote { span, .. } = &**term else {
1128 panic!("expected an unquote");
1129 };
1130 assert_eq!(*span, Some(7..12), "the nested unquote's span was lost");
1131 }
1132
1133 #[test]
1136 fn sep_separates_the_elements_of_a_region() {
1137 let elems = vec![sym("a"), sym("b"), sym("c")];
1138 let mut b_ = tb("array_expression");
1139 sym("[").emit(&mut b_);
1140 b_.sep(",");
1141 elems.emit(&mut b_);
1142 b_.end_sep();
1143 sym("]").emit(&mut b_);
1144 let built = b_.b();
1145 assert_eq!(built.coparse(), "[a, b, c]");
1146 let QTerm::Tuple { terms, .. } = &*built else {
1148 panic!("expected a tuple");
1149 };
1150 assert_eq!(terms.len(), 7);
1151 assert_eq!(terms[2], sym(","));
1152
1153 let mut b_ = tb("arguments");
1155 b_.sep(",");
1156 sym("a").emit(&mut b_);
1157 b_.nl();
1158 sym("b").emit(&mut b_);
1159 assert_eq!(b_.b().coparse(), "a,\nb");
1160
1161 let mut b_ = tb("arguments");
1163 b_.sep(",");
1164 sym("a").emit(&mut b_);
1165 sym(",").emit(&mut b_);
1166 b_.write(" ");
1167 sym("b").emit(&mut b_);
1168 b_.write(", ");
1169 sym("c").emit(&mut b_);
1170 assert_eq!(b_.b().coparse(), "a, b, c");
1171
1172 let mut b_ = tb("arguments");
1174 b_.sep(",");
1175 sym("a").emit(&mut b_);
1176 b_.end_sep();
1177 sym("b").emit(&mut b_);
1178 assert_eq!(b_.b().coparse(), "ab");
1179 }
1180
1181 #[test]
1185 fn text_in_an_aligned_splice_keeps_its_column() {
1186 let mut b_ = tb("def");
1187 b_.write("def x := ");
1188 b_.align(" ");
1189 "{ a := 1,\n b := 2 }".emit(&mut b_);
1190 b_.pop();
1191 assert_eq!(b_.b().coparse(), "def x := { a := 1,\n b := 2 }");
1192
1193 let mut b_ = tb("def");
1194 b_.write("def x := ");
1195 b_.push(" ");
1196 "{ a := 1,\n b := 2 }".emit(&mut b_);
1197 b_.pop();
1198 "\nc".emit(&mut b_);
1199 assert_eq!(b_.b().coparse(), "def x := { a := 1,\n b := 2 }\nc");
1200 }
1201
1202 #[test]
1206 fn strings_emit_as_text() {
1207 let s = String::from("a");
1208 let owned = vec![String::from("b"), String::from("c")];
1209 let strs = vec!["d", "e"];
1210 let refs: Vec<&String> = owned.iter().collect();
1211 let terms = [sym("f")];
1212 let term_refs: Vec<&Arc<QTerm>> = terms.iter().collect();
1213
1214 let mut b_ = tb("block");
1215 s.emit(&mut b_);
1216 (&s).emit(&mut b_);
1217 owned.emit(&mut b_);
1218 strs.emit(&mut b_);
1219 refs.emit(&mut b_);
1220 term_refs.emit(&mut b_);
1221 assert_eq!((s.as_str(), owned.len()), ("a", 2));
1223 assert_eq!(b_.b().coparse(), "aabcdebcf");
1224 }
1225}