Debian Codegraph @

examples/s-expr.rs

raw
1 // s-expr
2 //
3 // Parse CommonMark source files and print their AST as S-expressions.
4 //
5 // # Usage
6 //
7 // $ cargo run --example s-expr file1.md file2.md ...
8 // $ cat file.md | cargo run --example s-expr
9
10 /// Spaces to indent nested nodes
11 const INDENT: usize = 4;
12
13 /// If true, the close parenthesis is printed in its own line.
14 const CLOSE_NEWLINE: bool = false;
15
16 use std::env;
17 use std::error::Error;
18 use std::fs::File;
19 use std::io::{self, BufWriter, Read, Write};
20
21 use comrak::nodes::{Node, NodeValue};
22 use comrak::{Arena, Options, options, parse_document};
23
24 fn iter_nodes<W: Write>(node: Node<'_>, writer: &mut W, indent: usize) -> io::Result<()> {
25 use NodeValue::*;
26
27 macro_rules! try_node_inline {
28 ($node:expr, $name:ident) => {{
29 if let $name(t) = $node {
30 return write!(writer, concat!(stringify!($name), "({:?})"), t,);
31 }
32 }};
33 }
34
35 match &node.data().value {
36 Text(t) => write!(writer, "{:?}", t)?,
37 value => {
38 try_node_inline!(value, FootnoteDefinition);
39 try_node_inline!(value, FootnoteReference);
40 try_node_inline!(value, HtmlInline);
41
42 if let Code(code) = value {
43 return write!(writer, "Code({:?}, {})", code.literal, code.num_backticks);
44 }
45
46 let has_blocks = node.children().any(|c| c.data().value.block());
47
48 write!(writer, "({:?}", value)?;
49 for child in node.children() {
50 if has_blocks {
51 write!(writer, "\n{1:0$}", indent + INDENT, " ")?;
52 } else {
53 write!(writer, " ")?;
54 }
55 iter_nodes(child, writer, indent + INDENT)?;
56 }
57
58 if indent == 0 {
59 write!(writer, "\n)\n")?;
60 } else if CLOSE_NEWLINE && has_blocks {
61 write!(writer, "\n{1:0$})", indent, " ")?;
62 } else {
63 write!(writer, ")")?;
64 }
65 }
66 }
67
68 Ok(())
69 }
70
71 fn dump(source: &str) -> io::Result<()> {
72 let arena = Arena::new();
73
74 let extension = options::Extension::builder()
75 .strikethrough(true)
76 .tagfilter(true)
77 .table(true)
78 .autolink(true)
79 .tasklist(true)
80 .superscript(true)
81 .footnotes(true)
82 .description_lists(true)
83 .multiline_block_quotes(true)
84 .math_dollars(true)
85 .math_code(true)
86 .wikilinks_title_after_pipe(true)
87 .wikilinks_title_before_pipe(true)
88 .subtext(true)
89 .build();
90
91 let opts = Options {
92 extension,
93 ..Options::default()
94 };
95
96 let doc = parse_document(&arena, source, &opts);
97
98 let mut output = BufWriter::new(io::stdout());
99 iter_nodes(doc, &mut output, 0)
100 }
101
102 fn main() -> Result<(), Box<dyn Error>> {
103 let mut args = env::args_os().skip(1).peekable();
104 let mut body = String::new();
105
106 if args.peek().is_none() {
107 io::stdin().read_to_string(&mut body)?;
108 dump(&body)?;
109 }
110
111 for filename in args {
112 println!("{:?}", filename);
113
114 body.clear();
115 File::open(&filename)?.read_to_string(&mut body)?;
116 dump(&body)?;
117 }
118
119 Ok(())
120 }