-
Notifications
You must be signed in to change notification settings - Fork 529
/
Copy pathrender_markdown.rs
246 lines (237 loc) · 8.49 KB
/
render_markdown.rs
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
//! Renders the grammar to markdown.
use super::{Characters, Expression, ExpressionKind, Production};
use crate::grammar::Grammar;
use anyhow::bail;
use regex::Regex;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::LazyLock;
impl Grammar {
pub fn render_markdown(
&self,
names: &[&str],
link_map: &HashMap<String, String>,
rr_link_map: &HashMap<String, String>,
output: &mut String,
for_summary: bool,
) -> anyhow::Result<()> {
let mut iter = names.into_iter().peekable();
while let Some(name) = iter.next() {
let Some(prod) = self.productions.get(*name) else {
bail!("could not find grammar production named `{name}`");
};
prod.render_markdown(link_map, rr_link_map, output, for_summary);
if iter.peek().is_some() {
output.push_str("\n");
}
}
Ok(())
}
}
/// The HTML id for the production.
pub fn markdown_id(name: &str, for_summary: bool) -> String {
if for_summary {
format!("grammar-summary-{}", name)
} else {
format!("grammar-{}", name)
}
}
impl Production {
fn render_markdown(
&self,
link_map: &HashMap<String, String>,
rr_link_map: &HashMap<String, String>,
output: &mut String,
for_summary: bool,
) {
let dest = rr_link_map
.get(&self.name)
.map(|path| path.to_string())
.unwrap_or_else(|| format!("missing"));
write!(
output,
"<span class=\"grammar-text grammar-production\" id=\"{id}\" \
onclick=\"show_railroad()\"\
>\
[{name}]({dest})\
</span> → ",
id = markdown_id(&self.name, for_summary),
name = self.name,
)
.unwrap();
self.expression
.render_markdown(link_map, output, for_summary);
output.push('\n');
}
}
impl Expression {
/// Returns the last [`ExpressionKind`] of this expression.
fn last(&self) -> &ExpressionKind {
match &self.kind {
ExpressionKind::Alt(es) | ExpressionKind::Sequence(es) => es.last().unwrap().last(),
ExpressionKind::Grouped(_)
| ExpressionKind::Optional(_)
| ExpressionKind::Repeat(_)
| ExpressionKind::RepeatNonGreedy(_)
| ExpressionKind::RepeatPlus(_)
| ExpressionKind::RepeatPlusNonGreedy(_)
| ExpressionKind::RepeatRange(_, _, _)
| ExpressionKind::Nt(_)
| ExpressionKind::Terminal(_)
| ExpressionKind::Prose(_)
| ExpressionKind::Break(_)
| ExpressionKind::Charset(_)
| ExpressionKind::NegExpression(_)
| ExpressionKind::Unicode(_) => &self.kind,
}
}
fn render_markdown(
&self,
link_map: &HashMap<String, String>,
output: &mut String,
for_summary: bool,
) {
match &self.kind {
ExpressionKind::Grouped(e) => {
output.push_str("( ");
e.render_markdown(link_map, output, for_summary);
if !matches!(e.last(), ExpressionKind::Break(_)) {
output.push(' ');
}
output.push(')');
}
ExpressionKind::Alt(es) => {
let mut iter = es.iter().peekable();
while let Some(e) = iter.next() {
e.render_markdown(link_map, output, for_summary);
if iter.peek().is_some() {
if !matches!(e.last(), ExpressionKind::Break(_)) {
output.push(' ');
}
output.push_str("| ");
}
}
}
ExpressionKind::Sequence(es) => {
let mut iter = es.iter().peekable();
while let Some(e) = iter.next() {
e.render_markdown(link_map, output, for_summary);
if iter.peek().is_some() && !matches!(e.last(), ExpressionKind::Break(_)) {
output.push(' ');
}
}
}
ExpressionKind::Optional(e) => {
e.render_markdown(link_map, output, for_summary);
output.push_str("<sup>?</sup>");
}
ExpressionKind::Repeat(e) => {
e.render_markdown(link_map, output, for_summary);
output.push_str("<sup>\\*</sup>");
}
ExpressionKind::RepeatNonGreedy(e) => {
e.render_markdown(link_map, output, for_summary);
output.push_str("<sup>\\* (non-greedy)</sup>");
}
ExpressionKind::RepeatPlus(e) => {
e.render_markdown(link_map, output, for_summary);
output.push_str("<sup>+</sup>");
}
ExpressionKind::RepeatPlusNonGreedy(e) => {
e.render_markdown(link_map, output, for_summary);
output.push_str("<sup>+ (non-greedy)</sup>");
}
ExpressionKind::RepeatRange(e, a, b) => {
e.render_markdown(link_map, output, for_summary);
write!(
output,
"<sup>{}..{}</sup>",
a.map(|v| v.to_string()).unwrap_or_default(),
b.map(|v| v.to_string()).unwrap_or_default(),
)
.unwrap();
}
ExpressionKind::Nt(nt) => {
let dest = link_map.get(nt).map_or("missing", |d| d.as_str());
write!(output, "<span class=\"grammar-text\">[{nt}]({dest})</span>").unwrap();
}
ExpressionKind::Terminal(t) => {
write!(
output,
"<span class=\"grammar-literal\">{}</span>",
markdown_escape(t)
)
.unwrap();
}
ExpressionKind::Prose(s) => {
write!(output, "<span class=\"grammar-text\">\\<{s}\\></span>").unwrap();
}
ExpressionKind::Break(indent) => {
output.push_str("\\\n");
output.push_str(&" ".repeat(*indent));
}
ExpressionKind::Charset(set) => charset_render_markdown(set, link_map, output),
ExpressionKind::NegExpression(e) => {
output.push('~');
e.render_markdown(link_map, output, for_summary);
}
ExpressionKind::Unicode(s) => {
output.push_str("U+");
output.push_str(s);
}
}
if let Some(suffix) = &self.suffix {
write!(output, "<sub class=\"grammar-text\">{suffix}</sub>").unwrap();
}
if !for_summary {
if let Some(footnote) = &self.footnote {
// The `ZeroWidthSpace` is to avoid conflicts with markdown link
// references.
write!(output, "​[^{footnote}]").unwrap();
}
}
}
}
fn charset_render_markdown(
set: &[Characters],
link_map: &HashMap<String, String>,
output: &mut String,
) {
output.push_str("\\[");
let mut iter = set.iter().peekable();
while let Some(chars) = iter.next() {
chars.render_markdown(link_map, output);
if iter.peek().is_some() {
output.push(' ');
}
}
output.push(']');
}
impl Characters {
fn render_markdown(&self, link_map: &HashMap<String, String>, output: &mut String) {
match self {
Characters::Named(s) => {
let dest = link_map.get(s).map_or("missing", |d| d.as_str());
write!(output, "[{s}]({dest})").unwrap();
}
Characters::Terminal(s) => write!(
output,
"<span class=\"grammar-literal\">{}</span>",
markdown_escape(s)
)
.unwrap(),
Characters::Range(a, b) => write!(
output,
"<span class=\"grammar-literal\">{a}\
</span>-<span class=\"grammar-literal\">{b}</span>"
)
.unwrap(),
}
}
}
/// Escapes characters that markdown would otherwise interpret.
fn markdown_escape(s: &str) -> Cow<'_, str> {
static ESC_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"[\\`_*\[\](){}'"]"#).unwrap());
ESC_RE.replace_all(s, r"\$0")
}