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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
use std::fmt::Write;
use std::str;
pub const DEFAULT_WIDTH: usize = 80;
pub trait Emittable: std::fmt::Debug {
fn write_on(&self, f: &mut Formatter);
}
#[derive(Clone, PartialEq, Eq)]
pub enum VerticalMode {
Variable,
Normal,
ExtraNewline,
}
pub trait Vertical {
fn set_vertical_mode(&mut self, mode: VerticalMode);
fn write_vertically_on(&self, f: &mut Formatter);
}
pub type Item = std::rc::Rc<dyn Emittable>;
#[derive(Clone)]
pub struct Sequence {
pub items: Vec<Item>,
pub vertical_mode: VerticalMode,
pub separator: &'static str,
pub terminator: &'static str,
}
#[derive(Clone)]
pub struct Grouping {
pub sequence: Sequence,
pub open: &'static str,
pub close: &'static str,
}
pub struct Formatter {
pub width: usize,
indent_delta: String,
current_indent: String,
pub buffer: String,
}
impl Formatter {
pub fn new() -> Self {
Formatter {
width: DEFAULT_WIDTH,
indent_delta: " ".to_owned(),
current_indent: "\n".to_owned(),
buffer: String::new(),
}
}
pub fn copy_empty(&self) -> Formatter {
Formatter {
width: self.width,
indent_delta: self.indent_delta.clone(),
current_indent: self.current_indent.clone(),
buffer: String::new(),
}
}
pub fn indent_size(self) -> usize {
self.indent_delta.len()
}
pub fn set_indent_size(&mut self, n: usize) {
self.indent_delta = str::repeat(" ", n)
}
pub fn write<E: Emittable>(&mut self, e: E) {
e.write_on(self)
}
pub fn newline(&mut self) {
self.buffer.push_str(&self.current_indent)
}
pub fn to_string<E: Emittable>(e: E) -> String {
let mut f = Formatter::new();
f.write(e);
f.buffer
}
pub fn with_indent<R, F: FnOnce(&mut Self) -> R>(&mut self, f: F) -> R {
let old_indent = self.current_indent.clone();
self.current_indent += &self.indent_delta;
let r = f(self);
self.current_indent = old_indent;
r
}
}
impl Default for VerticalMode {
fn default() -> Self {
Self::Variable
}
}
impl Emittable for &str {
fn write_on(&self, f: &mut Formatter) {
f.buffer.push_str(self)
}
}
impl Emittable for String {
fn write_on(&self, f: &mut Formatter) {
f.write(self.as_str())
}
}
impl<'a, E: Emittable> Emittable for &'a Vec<E> where &'a E: Emittable {
fn write_on(&self, f: &mut Formatter) {
for e in self.iter() {
f.write(e)
}
}
}
impl Emittable for Sequence {
fn write_on(&self, f: &mut Formatter) {
if self.vertical_mode != VerticalMode::Variable {
self.write_vertically_on(f)
} else {
let mut need_sep = false;
for e in self.items.iter() {
if need_sep {
self.separator.write_on(f)
} else {
need_sep = true
}
e.write_on(f)
}
if !self.items.is_empty() {
self.terminator.write_on(f)
}
}
}
}
impl Vertical for Sequence {
fn set_vertical_mode(&mut self, vertical_mode: VerticalMode) {
self.vertical_mode = vertical_mode;
}
fn write_vertically_on(&self, f: &mut Formatter) {
let mut i = self.items.len();
let mut first = true;
for e in self.items.iter() {
if !first {
if self.vertical_mode == VerticalMode::ExtraNewline {
f.write("\n");
}
f.newline();
}
first = false;
e.write_on(f);
let delim = if i == 1 { self.terminator } else { self.separator };
delim.trim_end_matches(|c: char| c.is_whitespace() && c != '\n').write_on(f);
i = i - 1;
}
}
}
impl Emittable for Grouping {
fn write_on(&self, f: &mut Formatter) {
if self.sequence.vertical_mode != VerticalMode::Variable {
self.write_vertically_on(f)
} else {
let mut g = f.copy_empty();
self.open.write_on(&mut g);
g.write(&self.sequence);
self.close.write_on(&mut g);
let s = g.buffer;
if s.len() <= f.width {
f.write(&s)
} else {
self.write_vertically_on(f)
}
}
}
}
impl Vertical for Grouping {
fn set_vertical_mode(&mut self, vertical_mode: VerticalMode) {
self.sequence.set_vertical_mode(vertical_mode);
}
fn write_vertically_on(&self, f: &mut Formatter) {
self.open.write_on(f);
if !self.sequence.items.is_empty() {
f.with_indent(|f| {
f.newline();
self.sequence.write_vertically_on(f)
});
f.newline()
}
self.close.write_on(f);
}
}
impl<'a, E: Emittable> Emittable for &'a E {
fn write_on(&self, f: &mut Formatter) {
(*self).write_on(f)
}
}
impl Emittable for Item {
fn write_on(&self, f: &mut Formatter) {
(**self).write_on(f)
}
}
impl std::fmt::Debug for Sequence {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str(&Formatter::to_string(self))
}
}
impl std::fmt::Debug for Grouping {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str(&Formatter::to_string(self))
}
}
pub fn escape_string(s: &str) -> String {
let mut buf = String::new();
buf.push('"');
for c in s.chars() {
match c {
'\\' => buf.push_str("\\\\"),
'"' => buf.push_str("\\\""),
_ if c >= ' ' && c <= '~' => buf.push(c),
_ => write!(&mut buf, "\\u{{{:x}}}", c as i32).expect("no IO errors building a string"),
}
}
buf.push('"');
buf
}
pub fn escape_bytes(bs: &[u8]) -> String {
let mut buf = String::new();
buf.push_str("b\"");
for b in bs {
let c = *b as char;
match c {
'\\' => buf.push_str("\\\\"),
'"' => buf.push_str("\\\""),
_ if c >= ' ' && c <= '~' => buf.push(c),
_ => write!(&mut buf, "\\x{{{:02x}}}", b).expect("no IO errors building a string"),
}
}
buf.push('"');
buf
}
pub mod constructors {
use super::Sequence;
use super::Grouping;
use super::Item;
use super::Emittable;
use super::VerticalMode;
use super::Vertical;
pub fn item<E: 'static + Emittable>(i: E) -> Item {
std::rc::Rc::new(i)
}
pub fn name(pieces: Vec<Item>) -> Sequence {
Sequence { items: pieces, vertical_mode: VerticalMode::default(), separator: "::", terminator: "" }
}
pub fn seq(items: Vec<Item>) -> Sequence {
Sequence { items: items, vertical_mode: VerticalMode::default(), separator: "", terminator: "" }
}
pub fn commas(items: Vec<Item>) -> Sequence {
Sequence { items: items, vertical_mode: VerticalMode::default(), separator: ", ", terminator: "" }
}
pub fn parens(items: Vec<Item>) -> Grouping {
Grouping { sequence: commas(items), open: "(", close: ")" }
}
pub fn brackets(items: Vec<Item>) -> Grouping {
Grouping { sequence: commas(items), open: "[", close: "]" }
}
pub fn anglebrackets(items: Vec<Item>) -> Grouping {
Grouping { sequence: commas(items), open: "<", close: ">" }
}
pub fn braces(items: Vec<Item>) -> Grouping {
Grouping { sequence: commas(items), open: "{", close: "}" }
}
pub fn block(items: Vec<Item>) -> Grouping {
Grouping {
sequence: Sequence {
items: items,
vertical_mode: VerticalMode::default(),
separator: " ",
terminator: "",
},
open: "{",
close: "}",
}
}
pub fn codeblock(items: Vec<Item>) -> Grouping {
vertical(false, block(items))
}
pub fn semiblock(items: Vec<Item>) -> Grouping {
Grouping {
sequence: Sequence {
items: items,
vertical_mode: VerticalMode::default(),
separator: "; ",
terminator: "",
},
open: "{",
close: "}",
}
}
pub fn vertical<V: Vertical>(spaced: bool, mut v: V) -> V {
v.set_vertical_mode(if spaced { VerticalMode::ExtraNewline } else { VerticalMode::Normal });
v
}
pub fn indented(sequence: Sequence) -> Grouping {
Grouping { sequence, open: "", close: "" }
}
}
pub mod macros {
#[macro_export]
macro_rules! name {
($($item:expr),*) => {$crate::syntax::block::constructors::name(vec![$(std::rc::Rc::new($item)),*])}
}
#[macro_export]
macro_rules! seq {
($($item:expr),*) => {$crate::syntax::block::constructors::seq(vec![$(std::rc::Rc::new($item)),*])}
}
#[macro_export]
macro_rules! commas {
($($item:expr),*) => {$crate::syntax::block::constructors::commas(vec![$(std::rc::Rc::new($item)),*])}
}
#[macro_export]
macro_rules! parens {
($($item:expr),*) => {$crate::syntax::block::constructors::parens(vec![$(std::rc::Rc::new($item)),*])}
}
#[macro_export]
macro_rules! brackets {
($($item:expr),*) => {$crate::syntax::block::constructors::brackets(vec![$(std::rc::Rc::new($item)),*])}
}
#[macro_export]
macro_rules! anglebrackets {
($($item:expr),*) => {$crate::syntax::block::constructors::anglebrackets(vec![$(std::rc::Rc::new($item)),*])}
}
#[macro_export]
macro_rules! braces {
($($item:expr),*) => {$crate::syntax::block::constructors::braces(vec![$(std::rc::Rc::new($item)),*])}
}
#[macro_export]
macro_rules! block {
($($item:expr),*) => {$crate::syntax::block::constructors::block(vec![$(std::rc::Rc::new($item)),*])}
}
#[macro_export]
macro_rules! codeblock {
($($item:expr),*) => {$crate::syntax::block::constructors::codeblock(vec![$(std::rc::Rc::new($item)),*])}
}
#[macro_export]
macro_rules! semiblock {
($($item:expr),*) => {$crate::syntax::block::constructors::semiblock(vec![$(std::rc::Rc::new($item)),*])}
}
}