-
Notifications
You must be signed in to change notification settings - Fork 11
/
html.rs
517 lines (478 loc) Β· 18.1 KB
/
html.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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use proc_macro2::{Delimiter, Group, Ident, Literal, Span, TokenStream, TokenTree};
use quote::{quote, quote_spanned};
use crate::config::required_children;
use crate::error::ParseError;
use crate::ident;
use crate::lexer::{to_stream, Lexer, Token};
use crate::map::StringyMap;
use crate::parser::grammar;
use std::iter::FromIterator;
#[derive(Clone)]
pub enum Node {
Element(Element),
Text(Literal),
Block(Group),
}
impl Node {
pub fn into_token_stream(self, ty: &Option<Vec<Token>>) -> Result<TokenStream, TokenStream> {
match self {
Node::Element(el) => el.into_token_stream(ty),
Node::Text(text) => {
let text = TokenTree::Literal(text);
Ok(quote!(Box::new(axohtml::dom::TextNode::new(#text.to_string()))))
}
Node::Block(group) => {
let span = group.span();
let error =
"you cannot use a block as a top level element or a required child element";
Err(quote_spanned! { span=>
compile_error! { #error }
})
}
}
}
fn into_child_stream(self, ty: &Option<Vec<Token>>) -> Result<TokenStream, TokenStream> {
match self {
Node::Element(el) => {
let el = el.into_token_stream(ty)?;
Ok(quote!(
element.children.push(#el);
))
}
tx @ Node::Text(_) => {
let tx = tx.into_token_stream(ty)?;
Ok(quote!(
element.children.push(#tx);
))
}
Node::Block(group) => {
let group: TokenTree = group.into();
Ok(quote!(
for child in #group.into_iter() {
element.children.push(child);
}
))
}
}
}
}
#[derive(Clone)]
pub struct Element {
pub name: Ident,
pub attributes: StringyMap<Ident, TokenTree>,
pub children: Vec<Node>,
}
fn extract_data_attrs(attrs: &mut StringyMap<Ident, TokenTree>) -> StringyMap<String, TokenTree> {
let mut data = StringyMap::new();
let keys: Vec<Ident> = attrs.keys().cloned().collect();
for key in keys {
let key_name = key.to_string();
if let Some(key_name) = key_name.strip_prefix("data_") {
let value = attrs.remove(&key).unwrap();
// makes sure if a data attribute has more than one hyphen
// they all get transformed
let key = str::replace(key_name, "_", "-");
data.insert(key.to_string(), value);
}
}
data
}
fn extract_event_handlers(
attrs: &mut StringyMap<Ident, TokenTree>,
) -> StringyMap<Ident, TokenTree> {
let mut events = StringyMap::new();
let keys: Vec<Ident> = attrs.keys().cloned().collect();
for key in keys {
let key_name = key.to_string();
if let Some(event_name) = key_name.strip_prefix("on") {
let value = attrs.remove(&key).unwrap();
events.insert(ident::new_raw(event_name, key.span()), value);
}
}
events
}
fn extract_aria_attributes(
attrs: &mut StringyMap<Ident, TokenTree>,
) -> StringyMap<String, TokenTree> {
let mut data = StringyMap::new();
let keys: Vec<Ident> = attrs.keys().cloned().collect();
for key in keys {
let key_name = key.to_string();
if let Some(key_name) = key_name.strip_prefix("aria_") {
let value = attrs.remove(&key).unwrap();
data.insert(key_name.to_string(), value);
}
}
data
}
fn process_value(value: &TokenTree) -> TokenStream {
match value {
TokenTree::Group(g) if g.delimiter() == Delimiter::Bracket => {
let content = g.stream();
quote!( [ #content ] )
}
TokenTree::Group(g) if g.delimiter() == Delimiter::Parenthesis => {
let content = g.stream();
quote!( ( #content ) )
}
v => TokenStream::from_iter(vec![v.clone()]),
}
}
fn is_string_literal(literal: &Literal) -> bool {
// This is the worst API
literal.to_string().starts_with('"')
}
#[allow(dead_code)]
fn stringify_ident(ident: &Ident) -> String {
let s = ident.to_string();
if let Some(raw_s) = s.strip_prefix("r#") {
raw_s.to_string()
} else {
s
}
}
impl Element {
fn into_token_stream(mut self, ty: &Option<Vec<Token>>) -> Result<TokenStream, TokenStream> {
let name = self.name;
let name_str = name.to_string();
let typename: TokenTree = Ident::new(&name_str, name.span()).into();
let req_names = required_children(&name_str);
if req_names.len() > self.children.len() {
let span = name.span();
let error = format!(
"<{}> requires {} children but there are only {}",
name_str,
req_names.len(),
self.children.len()
);
return Err(quote_spanned! {span=>
compile_error! { #error }
});
}
let events = extract_event_handlers(&mut self.attributes);
let data_attrs = extract_data_attrs(&mut self.attributes);
let aria_attrs = extract_aria_attributes(&mut self.attributes);
let attrs = self.attributes.iter().map(|(key, value)| {
(
key.to_string(),
TokenTree::Ident(ident::new_raw(&key.to_string(), key.span())),
value,
)
});
let opt_children = self
.children
.split_off(req_names.len())
.into_iter()
.map(|node| node.into_child_stream(ty))
.collect::<Result<Vec<TokenStream>, TokenStream>>()?;
let req_children = self
.children
.into_iter()
.map(|node| node.into_token_stream(ty))
.collect::<Result<Vec<TokenStream>, TokenStream>>()?;
let mut body = TokenStream::new();
for (attr_str, key, value) in attrs {
match value {
TokenTree::Literal(lit) if is_string_literal(lit) => {
let mut eprintln_msg = "ERROR: ".to_owned();
#[cfg(can_show_location_of_runtime_parse_error)]
{
let span = lit.span();
eprintln_msg += &format!(
"{}:{}:{}: ",
span.unstable()
.source_file()
.path()
.to_str()
.unwrap_or("unknown"),
span.unstable().start().line,
span.unstable().start().column
);
}
eprintln_msg += &format!(
"<{} {}={}> failed to parse attribute value: {{}}",
name_str, attr_str, lit,
);
#[cfg(not(can_show_location_of_runtime_parse_error))]
{
eprintln_msg += "\nERROR: rebuild with nightly to print source location";
}
body.extend(quote!(
element.attrs.#key = Some(#lit.parse().unwrap_or_else(|err| {
eprintln!(#eprintln_msg, err);
panic!("failed to parse string literal");
}));
));
}
value => {
let value = process_value(value);
body.extend(quote!(
element.attrs.#key = Some(std::convert::TryInto::try_into(#value).unwrap());
));
}
}
}
for (key, value) in data_attrs
.iter()
.map(|(k, v)| (TokenTree::from(Literal::string(k)), v.clone()))
{
body.extend(quote!(
element.data_attributes.push((#key, #value.into()));
));
}
for (key, value) in aria_attrs
.iter()
.map(|(k, v)| (TokenTree::from(Literal::string(k)), v.clone()))
{
body.extend(quote!(
element.aria_attributes.push((#key, #value.into()));
));
}
body.extend(opt_children);
for (key, value) in events.iter() {
if ty.is_none() {
let mut err = quote_spanned! { key.span() =>
compile_error! { "when using event handlers, you must declare the output type inside the html! macro" }
};
let hint = quote_spanned! { Span::call_site() =>
compile_error! { "for example: change html!(<div>...</div>) to html!(<div>...</div> : String)" }
};
err.extend(hint);
return Err(err);
}
let key = TokenTree::Ident(key.clone());
let value = process_value(value);
body.extend(quote!(
element.events.#key = Some(#value.into());
));
}
let mut args = TokenStream::new();
for arg in req_children {
args.extend(quote!( #arg, ));
}
let mut type_annotation = TokenStream::new();
if let Some(ty) = ty {
let type_var = to_stream(ty.clone());
type_annotation.extend(quote!(: axohtml::elements::#typename<#type_var>));
}
Ok(quote!(
{
let mut element #type_annotation = axohtml::elements::#typename::new(#args);
#body
Box::new(element)
}
))
}
#[cfg(feature = "dodrio")]
fn into_dodrio_token_stream(
mut self,
bump: &Ident,
is_req_child: bool,
) -> Result<TokenStream, TokenStream> {
let name = self.name;
let name_str = stringify_ident(&name);
let typename: TokenTree = ident::new_raw(&name_str, name.span()).into();
let tag_name = TokenTree::from(Literal::string(&name_str));
let req_names = required_children(&name_str);
if req_names.len() > self.children.len() {
let span = name.span();
let error = format!(
"<{}> requires {} children but there are only {}",
name_str,
req_names.len(),
self.children.len()
);
return Err(quote_spanned! {span=>
compile_error! { #error }
});
}
let events = extract_event_handlers(&mut self.attributes);
let data_attrs = extract_data_attrs(&mut self.attributes);
let attrs = self.attributes.iter().map(|(key, value)| {
(
key.to_string(),
TokenTree::Ident(ident::new_raw(&key.to_string(), key.span())),
value,
)
});
let opt_children = self.children.split_off(req_names.len());
let req_children = self
.children
.into_iter()
.map(|node| node.into_dodrio_token_stream(bump, true))
.collect::<Result<Vec<TokenStream>, TokenStream>>()?;
let mut set_attrs = TokenStream::new();
for (attr_str, key, value) in attrs {
match value {
TokenTree::Literal(lit) if is_string_literal(lit) => {
let mut eprintln_msg = "ERROR: ".to_owned();
#[cfg(can_show_location_of_runtime_parse_error)]
{
let span = lit.span();
eprintln_msg += &format!(
"{}:{}:{}: ",
span.unstable()
.source_file()
.path()
.to_str()
.unwrap_or("unknown"),
span.unstable().start().line,
span.unstable().start().column
);
}
eprintln_msg += &format!(
"<{} {}={}> failed to parse attribute value: {{}}",
name_str, attr_str, lit,
);
#[cfg(not(can_show_location_of_runtime_parse_error))]
{
eprintln_msg += "\nERROR: rebuild with nightly to print source location";
}
set_attrs.extend(quote!(
element.attrs.#key = Some(#lit.parse().unwrap_or_else(|err| {
eprintln!(#eprintln_msg, err);
panic!("failed to parse string literal");
}));
));
}
value => {
let value = process_value(value);
set_attrs.extend(quote!(
element.attrs.#key = Some(std::convert::TryInto::try_into(#value).unwrap());
));
}
}
}
let attr_max_len = self.attributes.len() + data_attrs.len();
let mut builder = quote!(
let mut attr_list = dodrio::bumpalo::collections::Vec::with_capacity_in(#attr_max_len, #bump);
);
// Build the attributes.
for (key, _) in self.attributes.iter() {
let key_str = stringify_ident(key);
let key = ident::new_raw(&key_str, key.span());
let key_str = TokenTree::from(Literal::string(&key_str));
builder.extend(quote!(
let attr_value = dodrio::bumpalo::format!(
in &#bump, "{}", element.attrs.#key.unwrap());
if !attr_value.is_empty() {
attr_list.push(dodrio::builder::attr(#key_str, attr_value.into_bump_str()));
}
));
}
for (key, value) in data_attrs
.iter()
.map(|(k, v)| (TokenTree::from(Literal::string(&k)), v.clone()))
{
builder.extend(quote!(
attr_list.push(dodrio::builder::attr(
#key,
dodrio::bumpalo::format!(
in &#bump, "{}", #value
).into_bump_str()
));
));
}
builder.extend(quote!(
let mut node = dodrio::builder::ElementBuilder::new(#bump, #tag_name)
.attributes(attr_list)
));
// Build an array of event listeners.
let mut event_array = TokenStream::new();
for (key, value) in events.iter() {
let key = TokenTree::from(Literal::string(&stringify_ident(key)));
let value = process_value(value);
event_array.extend(quote!(
dodrio::builder::on(&#bump, #key, #value),
));
}
builder.extend(quote!(
.listeners([#event_array]);
));
// And finally an array of children, or a stream of builder commands
// if we have a group inside the child list.
let mut child_array = TokenStream::new();
let mut child_builder = TokenStream::new();
let mut static_children = true;
// Walk through required children and build them inline.
let mut make_req_children = TokenStream::new();
let mut arg_list = Vec::new();
for (index, child) in req_children.into_iter().enumerate() {
let req_child = TokenTree::from(ident::new_raw(
&format!("req_child_{}", index),
Span::call_site(),
));
let child_node = TokenTree::from(ident::new_raw(
&format!("child_node_{}", index),
Span::call_site(),
));
make_req_children.extend(quote!(
let (#req_child, #child_node) = #child;
));
child_array.extend(quote!(
#child_node,
));
child_builder.extend(quote!(
node = node.child(#child_node);
));
arg_list.push(req_child);
}
// Build optional children, test if we have groups.
for child_node in opt_children {
let child = match child_node {
Node::Text(text) => dodrio_text_node(text),
Node::Element(el) => el.into_dodrio_token_stream(bump, false)?,
Node::Block(group) => {
static_children = false;
let group: TokenTree = group.into();
child_builder.extend(quote!(
for child in #group.into_iter() {
node = node.child(child);
}
));
continue;
}
};
child_array.extend(quote!(
#child,
));
child_builder.extend(quote!(
node = node.child(#child);
));
}
if static_children {
builder.extend(quote!(
let node = node.children([#child_array]);
));
} else {
builder.extend(child_builder);
}
builder.extend(quote!(node.finish()));
if is_req_child {
builder = quote!(
(element, {#builder})
);
}
let mut args = TokenStream::new();
for arg in arg_list {
args.extend(quote!( #arg, ));
}
Ok(quote!(
{
#make_req_children
let mut element: axohtml::elements::#typename<axohtml::output::dodrio::Dodrio> =
axohtml::elements::#typename::new(#args);
#set_attrs
#builder
}
))
}
}
// FIXME report a decent error when the macro contains multiple top level elements
pub fn expand_html(input: &[Token]) -> Result<(Node, Option<Vec<Token>>), ParseError> {
grammar::NodeWithTypeParser::new().parse(Lexer::new(input))
}
#[allow(dead_code)]
pub fn expand_dodrio(input: &[Token]) -> Result<(Ident, Node), ParseError> {
grammar::NodeWithBumpParser::new().parse(Lexer::new(input))
}