1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
|
//! Syntax types.
mod expr;
mod ident;
mod node;
mod span;
mod token;
pub mod visit;
pub use expr::*;
pub use ident::*;
pub use node::*;
pub use span::*;
pub use token::*;
use crate::pretty::{Pretty, Printer};
/// The abstract syntax tree.
pub type Tree = SpanVec<Node>;
impl Pretty for Tree {
fn pretty(&self, p: &mut Printer) {
for node in self {
node.v.pretty(p);
}
}
}
#[cfg(test)]
mod tests {
use crate::parse::parse;
use crate::pretty::pretty;
#[track_caller]
fn test(src: &str, exp: &str) {
let tree = parse(src).output;
let found = pretty(&tree);
if exp != found {
println!("tree: {:#?}", tree);
println!("expected: {}", exp);
println!("found: {}", found);
panic!("test failed");
}
}
#[track_caller]
fn roundtrip(src: &str) {
test(src, src);
}
#[test]
fn test_pretty_print_node() {
// Basic text and markup.
roundtrip("*");
roundtrip("_");
roundtrip(" ");
roundtrip("\\ ");
roundtrip("\n\n");
roundtrip("hi");
// Heading.
roundtrip("# *Ok*");
// Raw.
roundtrip("`lang 1`");
test("`` hi``", "`hi`");
test("`` ` ``", "```");
}
#[test]
fn test_pretty_print_expr() {
// Basic expressions.
roundtrip("{none}");
roundtrip("{hi}");
roundtrip("{true}");
roundtrip("{10}");
roundtrip("{3.14}");
roundtrip("{10pt}");
roundtrip("{14.1deg}");
roundtrip("{20%}");
roundtrip("{#abcdef}");
roundtrip(r#"{"hi"}"#);
test(r#"{"let's go"}"#, r#"{"let\'s go"}"#);
// Arrays.
roundtrip("{()}");
roundtrip("{(1)}");
roundtrip("{(1, 2, 3)}");
// Dictionaries.
roundtrip("{(:)}");
roundtrip("{(key: value)}");
roundtrip("{(a: 1, b: 2)}");
// Templates.
roundtrip("{[]}");
roundtrip("{[*Ok*]}");
roundtrip("{[[f]]}");
// Groups.
roundtrip("{(1)}");
// Blocks.
roundtrip("{}");
roundtrip("{1}");
roundtrip("{ #let x = 1; x += 2; x + 1 }");
// Operators.
roundtrip("{-x}");
roundtrip("{not true}");
roundtrip("{1 + 3}");
// Parenthesized calls.
roundtrip("{v()}");
roundtrip("{v(1)}");
roundtrip("{v(a: 1, b)}");
// Bracket calls.
roundtrip("[v]");
roundtrip("[v 1]");
roundtrip("[v 1, 2][*Ok*]");
roundtrip("[v 1 | f 2]");
roundtrip("{[[v]]}");
test("[v 1, [[f 2]]]", "[v 1 | f 2]");
test("[v 1, 2][[f 3]]", "[v 1, 2 | f 3]");
// Keywords.
roundtrip("#let x = 1 + 2");
roundtrip("#if x [y] #else [z]");
roundtrip("#for x #in y {z}");
roundtrip("#for k, x #in y {z}");
}
}
|