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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
#![forbid(unsafe_code)]
#![warn(absolute_paths_not_starting_with_crate)]
#![warn(elided_lifetimes_in_paths)]
#![warn(explicit_outlives_requirements)]
#![warn(meta_variable_misuse)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(non_ascii_idents)]
#![warn(noop_method_call)]
#![warn(single_use_lifetimes)]
#![warn(trivial_casts)]
#![warn(unreachable_pub)]
#![warn(unused_crate_dependencies)]
#![warn(unused_extern_crates)]
#![warn(unused_lifetimes)]
#![warn(unused_results)]
use std::env::var;
use std::fmt::Write;
use std::fs::OpenOptions;
use std::io::{Read, Write as _};
use std::path::Path;
use darling::{FromDeriveInput, FromMeta};
use memchr::{memchr, memchr2};
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::combinator::opt;
use nom::error::ErrorKind;
use nom::sequence::{terminated, tuple};
use nom::{error_position, IResult};
use proc_macro::TokenStream;
use quote::quote;
use syn::DeriveInput;
const TAIL: &str = r#"
::nate::details::std::fmt::Result::Ok(())
}
}
};
"#;
#[proc_macro_derive(Nate, attributes(template))]
pub fn derive_nate(input: TokenStream) -> TokenStream {
let ast: DeriveInput = syn::parse(input).unwrap();
let ident = ast.ident.to_string();
let opts: TemplateAttrs = match TemplateAttrs::from_derive_input(&ast) {
Ok(opts) => opts,
Err(err) => {
let err = format!("{}", err);
return Into::into(quote!(
const _: () = {
::nate::details::std::compile_error!(#err);
};
));
},
};
let base = var("CARGO_MANIFEST_DIR").unwrap();
let path = Path::new(&base).join(&opts.path);
let output = opts.generated.as_ref().map(|s| Path::new(&base).join(s));
let left_generics = &ast.generics;
let left_generics = quote!(#left_generics);
let mut generics = String::new();
if !ast.generics.params.is_empty() {
write!(generics, "<").unwrap();
for arg in ast.generics.params.iter() {
match arg {
syn::GenericParam::Type(ty) => {
write!(generics, " {}, ", ty.ident).unwrap();
},
syn::GenericParam::Lifetime(def) => {
write!(generics, " '{}, ", def.lifetime.ident).unwrap();
},
syn::GenericParam::Const(par) => {
write!(generics, " {}, ", par.ident).unwrap();
},
}
}
writeln!(generics, ">").unwrap();
}
if let Some(where_clause) = ast.generics.where_clause {
writeln!(generics, " {} ", quote!(#where_clause)).unwrap();
}
let mut content = String::new();
write!(
content,
r#"
#[automatically_derived]
#[allow(unused_qualifications)]
const _: () = {{
impl {left_generics} ::nate::details::std::fmt::Display for {ident} {generics} {{
#[inline]
fn fmt(
&self,
output: &mut ::nate::details::std::fmt::Formatter<'_>,
) -> ::nate::details::std::fmt::Result {{
::nate::RenderInto::render_fmt(self, output)
}}
}}
impl {left_generics} ::nate::RenderInto for {ident} {generics} {{
#[inline]
fn render_into(
&self,
mut output: impl ::nate::WriteAny,
) -> ::nate::details::std::fmt::Result {{
#[allow(unused_imports)]
use ::nate::details::{{RawKind as _, EscapeKind as _}};
"#,
left_generics = left_generics,
generics = generics,
ident = ident
)
.unwrap();
parse_file(&path, &mut content, &opts).unwrap();
write!(content, "{}", TAIL).unwrap();
if let Some(output) = output {
let mut f = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&output)
.expect("Could not open output file");
write!(f, "{}", &content)
.expect("Could not write to output file after successfully opening it");
}
content
.parse()
.expect("Could not parse generated code as Rust source.")
}
#[derive(Debug, Default, FromDeriveInput)]
#[darling(attributes(template))]
struct TemplateAttrs {
path: String,
#[darling(default)]
generated: Option<String>,
#[darling(default)]
#[allow(unused)]
strip: Strip,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromMeta)]
enum Strip {
None,
Tail,
Trim,
Eager,
}
impl Default for Strip {
fn default() -> Self {
Strip::None
}
}
impl Strip {
#[allow(unused)]
fn apply(self, mut src: String) -> String {
match self {
Strip::None => src,
Strip::Tail => {
if src.ends_with('\n') {
let _ = src.pop();
}
src
},
Strip::Trim | Strip::Eager => {
let mut stripped = String::with_capacity(src.len());
for line in src.lines().map(|s| s.trim()).filter(|&s| !s.is_empty()) {
if !stripped.is_empty() {
stripped.push('\n');
}
if self == Strip::Eager {
for (index, word) in line.split_ascii_whitespace().enumerate() {
if index > 0 {
stripped.push(' ');
}
stripped.push_str(word);
}
} else {
stripped.push_str(line);
}
}
stripped
},
}
}
}
fn load_file(path: &Path) -> String {
let mut buf = String::new();
match OpenOptions::new().read(true).open(&path) {
Ok(mut f) => {
let _ = f
.read_to_string(&mut buf)
.expect("Could not read source file even after successfully opening it.");
},
Err(err) => {
eprintln!("Could not open file={:?}: {:?}", path, err);
panic!();
},
}
buf
}
fn parse_file(path: &Path, mut output: impl Write, opts: &TemplateAttrs) -> std::fmt::Result {
use DataSection::*;
let buf = load_file(path);
for (block_index, blocks) in parse(path, &buf, opts)?.into_iter().enumerate() {
match blocks {
ParsedData::Code(blocks) => {
for code in blocks.into_iter() {
writeln!(output, "{}", code)?;
}
},
ParsedData::Data(blocks) => {
let any_arg = blocks.iter().any(|data| match data {
Data(_) => false,
Raw(_) | Escaped(_) | Debug(_) | Verbose(_) => true,
});
writeln!(output, "{{")?;
if any_arg {
writeln!(output, "match (")?;
for data in &blocks {
match data {
Data(_) => {},
Raw(s) | Escaped(s) | Debug(s) | Verbose(s) => {
writeln!(output, "&({}),", s)?;
},
}
}
writeln!(output, ") {{\n(")?;
for (data_index, data) in blocks.iter().enumerate() {
match data {
Data(_) => {},
Raw(_) | Escaped(_) | Debug(_) | Verbose(_) => {
writeln!(
output,
"_nate_{block}_{data},",
block = block_index,
data = data_index,
)?;
},
}
}
writeln!(output, ") => match (")?;
for (data_index, data) in blocks.iter().enumerate() {
match data {
Data(_) => {},
Raw(_) => {
writeln!(
output,
"_nate_{block}_{data},",
block = block_index,
data = data_index,
)?;
},
Escaped(_) => {
writeln!(
output,
"(&::nate::details::TagWrapper::new(_nate_{block}_{data})).\
wrap(_nate_{block}_{data}),",
block = block_index,
data = data_index,
)?;
},
Debug(_) | Verbose(_) => {
writeln!(
output,
"::nate::XmlEscape(_nate_{block}_{data}),",
block = block_index,
data = data_index,
)?;
},
}
}
writeln!(output, ") {{\n(")?;
for (data_index, data) in blocks.iter().enumerate() {
match data {
Data(_) => {},
Raw(_) | Escaped(_) | Debug(_) | Verbose(_) => {
writeln!(
output,
"_nate_{block}_{data},",
block = block_index,
data = data_index,
)?;
},
}
}
write!(output, ") => {{")?;
}
write!(
output,
"output.write_fmt(::nate::details::std::format_args!(\n\""
)?;
for (data_index, data) in blocks.iter().enumerate() {
match data {
Data(s) => {
let s = format!("{:#?}", s).replace('{', "{{").replace('}', "}}");
write!(output, "{}", &s[1..s.len() - 1])?;
},
Raw(_) | Escaped(_) => write!(
output,
"{{_nate_{block}_{data}}}",
block = block_index,
data = data_index
)?,
Debug(_) => write!(
output,
"{{_nate_{block}_{data}:?}}",
block = block_index,
data = data_index
)?,
Verbose(_) => write!(
output,
"{{_nate_{block}_{data}:#?}}",
block = block_index,
data = data_index
)?,
}
}
writeln!(output, "\",")?;
for (data_index, data) in blocks.into_iter().enumerate() {
match data {
Data(_) => {},
Raw(_) | Escaped(_) | Debug(_) | Verbose(_) => writeln!(
output,
"_nate_{block}_{data} = _nate_{block}_{data},",
block = block_index,
data = data_index
)?,
}
}
writeln!(output, "))?;\n}}")?;
if any_arg {
writeln!(output, "}}\n}}\n}}")?;
}
},
}
}
Ok(())
}
fn parse(path: &Path, i: &str, opts: &TemplateAttrs) -> Result<Vec<ParsedData>, std::fmt::Error> {
let mut output = Vec::new();
parse_into(path, i, &mut output, opts)?;
Ok(output)
}
fn parse_into(
path: &Path,
i: &str,
accu: &mut Vec<ParsedData>,
opts: &TemplateAttrs,
) -> std::fmt::Result {
let it = WsBlockIter::new(path, i)
.map(|WsBlock(a, b, z)| match b {
Block::Data(DataSection::Data(s)) => {
let t = match (a, z) {
(true, true) => s.trim(),
(true, false) => s.trim_start(),
(false, true) => s.trim_end(),
(false, false) => &s,
};
if s.len() != t.len() {
Block::Data(DataSection::Data(t.to_owned()))
} else {
Block::Data(DataSection::Data(s))
}
},
b => b,
})
.filter(|block| !block.is_empty());
let s = format!(
"\
{{\n\
const _: &'static [::nate::details::std::primitive::u8] = \
::nate::details::std::include_bytes!({:?});",
path
);
match accu.last_mut() {
Some(ParsedData::Code(blocks)) => blocks.push(s),
_ => accu.push(ParsedData::Code(vec![s])),
}
for block in it {
match block {
Block::Comment => {},
Block::Code(s) => match accu.last_mut() {
Some(ParsedData::Code(blocks)) => blocks.push(s),
_ => accu.push(ParsedData::Code(vec![s])),
},
Block::Data(data) => match accu.last_mut() {
Some(ParsedData::Data(blocks)) => blocks.push(data),
_ => accu.push(ParsedData::Data(vec![data])),
},
Block::Include(include_path) => {
let include_path = include_path.trim();
let include_path = match Path::new(include_path).iter().next() {
Some(d) if d.eq(".") || d.eq("..") => {
path.parent().unwrap_or(path).join(include_path)
},
_ => Path::new(&var("CARGO_MANIFEST_DIR").map_err(|_| std::fmt::Error)?)
.join(include_path),
};
let buf = load_file(&include_path);
parse_into(&include_path, &buf, accu, opts)?;
},
}
}
let s = "}".to_owned();
match accu.last_mut() {
Some(ParsedData::Code(blocks)) => blocks.push(s),
_ => accu.push(ParsedData::Code(vec![s])),
}
Ok(())
}
#[derive(Debug)]
enum ParsedData {
Code(Vec<String>),
Data(Vec<DataSection>),
}
#[derive(Debug, Clone)]
enum DataSection {
Data(String),
Raw(String),
Escaped(String),
Debug(String),
Verbose(String),
}
#[derive(Debug, Clone)]
enum Block {
Data(DataSection),
Code(String),
Comment,
Include(String),
}
struct WsBlock(bool, Block, bool);
struct WsBlockIter<'a> {
path: &'a Path,
start: &'a str,
pos: &'a str,
next: Option<WsBlock>,
}
impl Block {
fn is_empty(&self) -> bool {
match self {
Block::Comment => true,
Block::Code(s) | Block::Data(DataSection::Data(s)) => s.is_empty(),
Block::Data(_) | Block::Include(_) => false,
}
}
}
impl<'a> WsBlockIter<'a> {
fn new(path: &'a Path, i: &'a str) -> Self {
Self {
path,
start: i,
pos: i,
next: Some(WsBlock(false, Block::Comment, false)),
}
}
}
fn abort_with_nom_error(err: nom::Err<nom::error::Error<&str>>, start: &str, path: &Path) -> ! {
match err {
nom::Err::Incomplete(_) => {
panic!("Impossible");
},
nom::Err::Error(err) | nom::Err::Failure(err) => {
let offset = start.len() - err.input.len();
let (source_before, source_after) = start.split_at(offset);
let source_after = match source_after.char_indices().enumerate().take(41).last() {
Some((40, (i, _))) => format!("{:?}...", &source_after[..i]),
_ => format!("{:?}", source_after),
};
let (row, last_line) = source_before.lines().enumerate().last().unwrap();
let column = last_line.chars().count();
panic!(
"Problems parsing template source {:?} at row {}, column {} near:\n{}",
path,
row + 1,
column,
source_after,
);
},
}
}
impl Iterator for WsBlockIter<'_> {
type Item = WsBlock;
fn next(&mut self) -> Option<Self::Item> {
let cur = if !self.pos.is_empty() {
match parse_ws_block(self.pos) {
Ok((j, b)) => {
self.pos = j;
Some(b)
},
Err(err) => {
abort_with_nom_error(err, self.start, self.path);
},
}
} else {
None
};
match (cur, &self.next) {
(Some(WsBlock(next_a, next_b, next_z)), Some(WsBlock(cur_a, cur_b, cur_z))) => {
let result = WsBlock(*cur_a, cur_b.clone(), cur_z | next_a);
self.next = Some(WsBlock(next_a || *cur_z, next_b, next_z));
Some(result)
},
(None, _) => self.next.take(),
(_, None) => panic!("Impossible"),
}
}
}
fn parse_ws_block(i: &str) -> IResult<&str, WsBlock> {
alt((
|i| {
let (i, (a, b, z)) = parse_block(i, "{%", "%}")?;
Ok((i, WsBlock(a, Block::Code(b.to_owned()), z)))
},
|i| {
let (i, (a, _, z)) = parse_block(i, "{#", "#}")?;
Ok((i, WsBlock(a, Block::Comment, z)))
},
|i| {
let (next_i, (a, b, z)) = parse_block(i, "{<", ">}")?;
match b.is_empty() {
false => Ok((next_i, WsBlock(a, Block::Include(b.to_owned()), z))),
true => Err(nom::Err::Error(error_position!(i, ErrorKind::NonEmpty))),
}
},
|i| parse_data_section(i, "{{{{{", "}}}}}", DataSection::Verbose),
|i| parse_data_section(i, "{{{{", "}}}}", DataSection::Debug),
|i| parse_data_section(i, "{{{", "}}}", DataSection::Raw),
|i| parse_data_section(i, "{{", "}}", DataSection::Escaped),
parse_data,
))(i)
}
fn parse_block<'a>(
i: &'a str,
start: &'static str,
end: &'static str,
) -> IResult<&'a str, (bool, &'a str, bool)> {
let inner = |i: &'a str| -> IResult<&'a str, (&'a str, bool)> {
let mut start = 0;
while (i.len() - start) >= end.len() {
let pos = match memchr2(end.as_bytes()[0], b'-', &i.as_bytes()[start..]) {
Some(pos) => pos,
None => break,
};
let (j, end) = opt(terminated(opt(tag("-")), tag(end)))(&i[start + pos..])?;
if let Some(trim) = end {
return Ok((j, ((&i[..start + pos]).trim(), trim.is_some())));
} else if pos > 0 {
start += pos;
} else {
start += 1;
}
}
Ok(("", (i, false)))
};
let (i, (_, trim_start, (b, trim_end))) = tuple((tag(start), opt(tag("-")), inner))(i)?;
Ok((i, (trim_start.is_some(), b, trim_end)))
}
fn parse_data_section<'a>(
i: &'a str,
start: &'static str,
end: &'static str,
kind: impl 'static + Fn(String) -> DataSection,
) -> IResult<&'a str, WsBlock> {
let (j, (trim_start, b, trim_end)) = parse_block(i, start, end)?;
if !b.is_empty() {
Ok((
j,
WsBlock(trim_start, Block::Data(kind(b.to_owned())), trim_end),
))
} else {
Err(nom::Err::Error(error_position!(i, ErrorKind::NonEmpty)))
}
}
fn parse_data(i: &str) -> IResult<&str, WsBlock> {
let (b, i) = match memchr(b'{', &i.as_bytes()[1..]) {
Some(pos) => i.split_at(pos + 1),
None => (i, ""),
};
let b = DataSection::Data(b.to_owned());
Ok((i, WsBlock(false, Block::Data(b), false)))
}