|
| 1 | +use crate::pretty_print::PrettyRenderer; |
| 2 | +use crate::types::{PrimitiveType, Type}; |
| 3 | +use crate::visitor::{Accept, Visitor}; |
| 4 | +use pretty::RcDoc; |
| 5 | + |
| 6 | +impl<'a> Visitor<PrimitiveType<'a>, RcDoc<'a>> for PrettyRenderer { |
| 7 | + fn visit(&self, value: &PrimitiveType<'a>) -> RcDoc<'a> { |
| 8 | + RcDoc::text(value.as_str()) |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +impl<'a> Visitor<Type<'a>, RcDoc<'a>> for PrettyRenderer { |
| 13 | + fn visit(&self, value: &Type<'a>) -> RcDoc<'a> { |
| 14 | + match value { |
| 15 | + Type::Exactly(t) => RcDoc::text(t.as_str()), |
| 16 | + Type::EitherOf(ts) => RcDoc::text("(either") |
| 17 | + .append(RcDoc::softline()) |
| 18 | + .group() |
| 19 | + .nest(4) |
| 20 | + .append(RcDoc::intersperse( |
| 21 | + ts.iter().map(|t| t.accept(self)), |
| 22 | + RcDoc::softline(), |
| 23 | + )) |
| 24 | + .nest(4) |
| 25 | + .group() |
| 26 | + .append(")"), |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +#[cfg(test)] |
| 32 | +mod tests { |
| 33 | + use super::*; |
| 34 | + use crate::pretty_print::prettify; |
| 35 | + use crate::visitor::Accept; |
| 36 | + |
| 37 | + #[test] |
| 38 | + fn primitive_type_works() { |
| 39 | + let x = PrimitiveType::new("pt"); |
| 40 | + assert_eq!(prettify!(x, 10), "pt"); |
| 41 | + } |
| 42 | + |
| 43 | + #[test] |
| 44 | + fn simple_type_works() { |
| 45 | + let x = Type::from("a"); |
| 46 | + assert_eq!(prettify!(x, 10), "a"); |
| 47 | + } |
| 48 | + |
| 49 | + #[test] |
| 50 | + fn either_type_works() { |
| 51 | + let x = Type::from_iter(["a", "b"]); |
| 52 | + assert_eq!(prettify!(x, 12), "(either a b)"); |
| 53 | + assert_eq!(prettify!(x, 10), "(either a\n b)"); |
| 54 | + assert_eq!(prettify!(x, 8), "(either\n a b)"); |
| 55 | + } |
| 56 | +} |
0 commit comments