-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathgenerator.rs
2219 lines (2008 loc) · 74.7 KB
/
generator.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
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::config::{get_template_source, read_config_file, Config, WhitespaceHandling};
use crate::heritage::{Context, Heritage};
use crate::input::{Print, Source, TemplateInput};
use crate::parser::{Cond, CondTest, Expr, Loop, Node, Target, When, Whitespace, Ws};
use crate::CompileError;
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::punctuated::Punctuated;
use std::collections::hash_map::{Entry, HashMap};
use std::path::{Path, PathBuf};
use std::{cmp, hash, mem, str};
/// The actual implementation for askama_derive::Template
pub(crate) fn derive_template(input: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(input).unwrap();
match build_template(&ast) {
Ok(source) => source.parse().unwrap(),
Err(e) => e.into_compile_error(),
}
}
/// Takes a `syn::DeriveInput` and generates source code for it
///
/// Reads the metadata from the `template()` attribute to get the template
/// metadata, then fetches the source from the filesystem. The source is
/// parsed, and the parse tree is fed to the code generator. Will print
/// the parse tree and/or generated source according to the `print` key's
/// value as passed to the `template()` attribute.
fn build_template(ast: &syn::DeriveInput) -> Result<String, CompileError> {
let template_args = TemplateArgs::new(ast)?;
let config_toml = read_config_file(template_args.config_path.as_deref())?;
let config = Config::new(&config_toml, template_args.whitespace.as_ref())?;
let input = TemplateInput::new(ast, &config, template_args)?;
let source: String = match input.source {
Source::Source(ref s) => s.clone(),
Source::Path(_) => get_template_source(&input.path)?,
};
let mut templates = HashMap::new();
find_used_templates(&input, &mut templates, source)?;
let mut contexts = HashMap::new();
for (path, parsed) in &templates {
contexts.insert(
path.as_path(),
Context::new(input.config, path, parsed.nodes())?,
);
}
let ctx = &contexts[input.path.as_path()];
let heritage = if !ctx.blocks.is_empty() || ctx.extends.is_some() {
Some(Heritage::new(ctx, &contexts))
} else {
None
};
if input.print == Print::Ast || input.print == Print::All {
eprintln!("{:?}", templates[input.path.as_path()].nodes());
}
let code = Generator::new(
&input,
&contexts,
heritage.as_ref(),
MapChain::new(),
config.whitespace,
)
.build(&contexts[input.path.as_path()])?;
if input.print == Print::Code || input.print == Print::All {
eprintln!("{code}");
}
Ok(code)
}
#[derive(Default)]
pub(crate) struct TemplateArgs {
pub(crate) source: Option<Source>,
pub(crate) print: Print,
pub(crate) escaping: Option<String>,
pub(crate) ext: Option<String>,
pub(crate) syntax: Option<String>,
pub(crate) config_path: Option<String>,
pub(crate) whitespace: Option<String>,
}
impl TemplateArgs {
fn new(ast: &'_ syn::DeriveInput) -> Result<Self, CompileError> {
// Check that an attribute called `template()` exists once and that it is
// the proper type (list).
let mut template_args = None;
for attr in &ast.attrs {
if !attr.path().is_ident("template") {
continue;
}
match attr.parse_args_with(Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated) {
Ok(args) if template_args.is_none() => template_args = Some(args),
Ok(_) => return Err("duplicated 'template' attribute".into()),
Err(e) => return Err(format!("unable to parse template arguments: {e}").into()),
};
}
let template_args =
template_args.ok_or_else(|| CompileError::from("no attribute 'template' found"))?;
let mut args = Self::default();
// Loop over the meta attributes and find everything that we
// understand. Return a CompileError if something is not right.
// `source` contains an enum that can represent `path` or `source`.
for item in template_args {
let pair = match item {
syn::Meta::NameValue(pair) => pair,
_ => {
return Err(format!(
"unsupported attribute argument {:?}",
item.to_token_stream()
)
.into())
}
};
let ident = match pair.path.get_ident() {
Some(ident) => ident,
None => unreachable!("not possible in syn::Meta::NameValue(…)"),
};
let value = match pair.value {
syn::Expr::Lit(lit) => lit,
syn::Expr::Group(group) => match *group.expr {
syn::Expr::Lit(lit) => lit,
_ => {
return Err(format!("unsupported argument value type for {ident:?}").into())
}
},
_ => return Err(format!("unsupported argument value type for {ident:?}").into()),
};
if ident == "path" {
if let syn::Lit::Str(s) = value.lit {
if args.source.is_some() {
return Err("must specify 'source' or 'path', not both".into());
}
args.source = Some(Source::Path(s.value()));
} else {
return Err("template path must be string literal".into());
}
} else if ident == "source" {
if let syn::Lit::Str(s) = value.lit {
if args.source.is_some() {
return Err("must specify 'source' or 'path', not both".into());
}
args.source = Some(Source::Source(s.value()));
} else {
return Err("template source must be string literal".into());
}
} else if ident == "print" {
if let syn::Lit::Str(s) = value.lit {
args.print = s.value().parse()?;
} else {
return Err("print value must be string literal".into());
}
} else if ident == "escape" {
if let syn::Lit::Str(s) = value.lit {
args.escaping = Some(s.value());
} else {
return Err("escape value must be string literal".into());
}
} else if ident == "ext" {
if let syn::Lit::Str(s) = value.lit {
args.ext = Some(s.value());
} else {
return Err("ext value must be string literal".into());
}
} else if ident == "syntax" {
if let syn::Lit::Str(s) = value.lit {
args.syntax = Some(s.value())
} else {
return Err("syntax value must be string literal".into());
}
} else if ident == "config" {
if let syn::Lit::Str(s) = value.lit {
args.config_path = Some(s.value())
} else {
return Err("config value must be string literal".into());
}
} else if ident == "whitespace" {
if let syn::Lit::Str(s) = value.lit {
args.whitespace = Some(s.value())
} else {
return Err("whitespace value must be string literal".into());
}
} else {
return Err(format!("unsupported attribute key {ident:?} found").into());
}
}
Ok(args)
}
}
fn find_used_templates(
input: &TemplateInput<'_>,
map: &mut HashMap<PathBuf, Parsed>,
source: String,
) -> Result<(), CompileError> {
let mut dependency_graph = Vec::new();
let mut check = vec![(input.path.clone(), source)];
while let Some((path, source)) = check.pop() {
let parsed = Parsed::new(source, input.syntax)?;
for n in parsed.nodes() {
match n {
Node::Extends(extends) => {
let extends = input.config.find_template(extends, Some(&path))?;
let dependency_path = (path.clone(), extends.clone());
if dependency_graph.contains(&dependency_path) {
return Err(format!(
"cyclic dependency in graph {:#?}",
dependency_graph
.iter()
.map(|e| format!("{:#?} --> {:#?}", e.0, e.1))
.collect::<Vec<String>>()
)
.into());
}
dependency_graph.push(dependency_path);
let source = get_template_source(&extends)?;
check.push((extends, source));
}
Node::Import(_, import, _) => {
let import = input.config.find_template(import, Some(&path))?;
let source = get_template_source(&import)?;
check.push((import, source));
}
_ => {}
}
}
map.insert(path, parsed);
}
Ok(())
}
mod _parsed {
use std::mem;
use crate::config::Syntax;
use crate::parser::{parse, Node};
use crate::CompileError;
pub(super) struct Parsed {
#[allow(dead_code)]
source: String,
nodes: Vec<Node<'static>>,
}
impl Parsed {
pub(super) fn new(source: String, syntax: &Syntax<'_>) -> Result<Self, CompileError> {
// Self-referential borrowing: `self` will keep the source alive as `String`,
// internally we will transmute it to `&'static str` to satisfy the compiler.
// However, we only expose the nodes with a lifetime limited to `self`.
let src = unsafe { mem::transmute::<&str, &'static str>(source.as_str()) };
let nodes = parse(src, syntax)?;
Ok(Self { source, nodes })
}
// The return value's lifetime must be limited to `self` to uphold the unsafe invariant.
pub(super) fn nodes(&self) -> &[Node<'_>] {
&self.nodes
}
}
}
use _parsed::Parsed;
struct Generator<'a> {
// The template input state: original struct AST and attributes
input: &'a TemplateInput<'a>,
// All contexts, keyed by the package-relative template path
contexts: &'a HashMap<&'a Path, Context<'a>>,
// The heritage contains references to blocks and their ancestry
heritage: Option<&'a Heritage<'a>>,
// Cache ASTs for included templates
includes: HashMap<PathBuf, Parsed>,
// Variables accessible directly from the current scope (not redirected to context)
locals: MapChain<'a, &'a str, LocalMeta>,
// Suffix whitespace from the previous literal. Will be flushed to the
// output buffer unless suppressed by whitespace suppression on the next
// non-literal.
next_ws: Option<&'a str>,
// Whitespace suppression from the previous non-literal. Will be used to
// determine whether to flush prefix whitespace from the next literal.
skip_ws: WhitespaceHandling,
// If currently in a block, this will contain the name of a potential parent block
super_block: Option<(&'a str, usize)>,
// buffer for writable
buf_writable: Vec<Writable<'a>>,
// Counter for write! hash named arguments
named: usize,
// If set to `suppress`, the whitespace characters will be removed by default unless `+` is
// used.
whitespace: WhitespaceHandling,
}
impl<'a> Generator<'a> {
fn new<'n>(
input: &'n TemplateInput<'_>,
contexts: &'n HashMap<&'n Path, Context<'n>>,
heritage: Option<&'n Heritage<'_>>,
locals: MapChain<'n, &'n str, LocalMeta>,
whitespace: WhitespaceHandling,
) -> Generator<'n> {
Generator {
input,
contexts,
heritage,
includes: HashMap::default(),
locals,
next_ws: None,
skip_ws: WhitespaceHandling::Preserve,
super_block: None,
buf_writable: vec![],
named: 0,
whitespace,
}
}
// Takes a Context and generates the relevant implementations.
fn build(mut self, ctx: &'a Context<'_>) -> Result<String, CompileError> {
let mut buf = Buffer::new(0);
self.impl_template(ctx, &mut buf)?;
self.impl_display(&mut buf)?;
#[cfg(feature = "with-actix-web")]
self.impl_actix_web_responder(&mut buf)?;
#[cfg(feature = "with-axum")]
self.impl_axum_into_response(&mut buf)?;
#[cfg(feature = "with-gotham")]
self.impl_gotham_into_response(&mut buf)?;
#[cfg(feature = "with-hyper")]
self.impl_hyper_into_response(&mut buf)?;
#[cfg(feature = "with-mendes")]
self.impl_mendes_responder(&mut buf)?;
#[cfg(feature = "with-rocket")]
self.impl_rocket_responder(&mut buf)?;
#[cfg(feature = "with-tide")]
self.impl_tide_integrations(&mut buf)?;
#[cfg(feature = "with-warp")]
self.impl_warp_reply(&mut buf)?;
Ok(buf.buf)
}
// Implement `Template` for the given context struct.
fn impl_template(
&mut self,
ctx: &'a Context<'_>,
buf: &mut Buffer,
) -> Result<(), CompileError> {
self.write_header(buf, "::askama::Template", None)?;
buf.writeln(
"fn render_into(&self, writer: &mut (impl ::std::fmt::Write + ?Sized)) -> \
::askama::Result<()> {",
)?;
// Make sure the compiler understands that the generated code depends on the template files.
for path in self.contexts.keys() {
// Skip the fake path of templates defined in rust source.
let path_is_valid = match self.input.source {
Source::Path(_) => true,
Source::Source(_) => path != &self.input.path,
};
if path_is_valid {
let path = path.to_str().unwrap();
buf.writeln(
"e! {
include_bytes!(#path);
}
.to_string(),
)?;
}
}
let size_hint = if let Some(heritage) = self.heritage {
self.handle(heritage.root, heritage.root.nodes, buf, AstLevel::Top)
} else {
self.handle(ctx, ctx.nodes, buf, AstLevel::Top)
}?;
self.flush_ws(Ws(None, None));
buf.writeln("::askama::Result::Ok(())")?;
buf.writeln("}")?;
buf.writeln("const EXTENSION: ::std::option::Option<&'static ::std::primitive::str> = ")?;
buf.writeln(&format!("{:?}", self.input.extension()))?;
buf.writeln(";")?;
buf.writeln("const SIZE_HINT: ::std::primitive::usize = ")?;
buf.writeln(&format!("{size_hint}"))?;
buf.writeln(";")?;
buf.writeln("const MIME_TYPE: &'static ::std::primitive::str = ")?;
buf.writeln(&format!("{:?}", &self.input.mime_type))?;
buf.writeln(";")?;
buf.writeln("}")?;
Ok(())
}
// Implement `Display` for the given context struct.
fn impl_display(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
self.write_header(buf, "::std::fmt::Display", None)?;
buf.writeln("#[inline]")?;
buf.writeln("fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {")?;
buf.writeln("::askama::Template::render_into(self, f).map_err(|_| ::std::fmt::Error {})")?;
buf.writeln("}")?;
buf.writeln("}")
}
// Implement Actix-web's `Responder`.
#[cfg(feature = "with-actix-web")]
fn impl_actix_web_responder(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
self.write_header(buf, "::askama_actix::actix_web::Responder", None)?;
buf.writeln("type Body = ::askama_actix::actix_web::body::BoxBody;")?;
buf.writeln("#[inline]")?;
buf.writeln(
"fn respond_to(self, _req: &::askama_actix::actix_web::HttpRequest) \
-> ::askama_actix::actix_web::HttpResponse<Self::Body> {",
)?;
buf.writeln("<Self as ::askama_actix::TemplateToResponse>::to_response(&self)")?;
buf.writeln("}")?;
buf.writeln("}")
}
// Implement Axum's `IntoResponse`.
#[cfg(feature = "with-axum")]
fn impl_axum_into_response(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
self.write_header(buf, "::askama_axum::IntoResponse", None)?;
buf.writeln("#[inline]")?;
buf.writeln(
"fn into_response(self)\
-> ::askama_axum::Response {",
)?;
buf.writeln("::askama_axum::into_response(&self)")?;
buf.writeln("}")?;
buf.writeln("}")
}
// Implement gotham's `IntoResponse`.
#[cfg(feature = "with-gotham")]
fn impl_gotham_into_response(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
self.write_header(buf, "::askama_gotham::IntoResponse", None)?;
buf.writeln("#[inline]")?;
buf.writeln(
"fn into_response(self, _state: &::askama_gotham::State)\
-> ::askama_gotham::Response<::askama_gotham::Body> {",
)?;
buf.writeln("::askama_gotham::respond(&self)")?;
buf.writeln("}")?;
buf.writeln("}")
}
// Implement `From<Template> for hyper::Response<Body>` and `From<Template> for hyper::Body.
#[cfg(feature = "with-hyper")]
fn impl_hyper_into_response(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
let (impl_generics, orig_ty_generics, where_clause) =
self.input.ast.generics.split_for_impl();
let ident = &self.input.ast.ident;
// From<Template> for hyper::Response<Body>
buf.writeln(&format!(
"{} {{",
quote!(
impl #impl_generics ::core::convert::From<&#ident #orig_ty_generics>
for ::askama_hyper::hyper::Response<::askama_hyper::hyper::Body>
#where_clause
)
))?;
buf.writeln("#[inline]")?;
buf.writeln(&format!(
"{} {{",
quote!(fn from(value: &#ident #orig_ty_generics) -> Self)
))?;
buf.writeln("::askama_hyper::respond(value)")?;
buf.writeln("}")?;
buf.writeln("}")?;
// TryFrom<Template> for hyper::Body
buf.writeln(&format!(
"{} {{",
quote!(
impl #impl_generics ::core::convert::TryFrom<&#ident #orig_ty_generics>
for ::askama_hyper::hyper::Body
#where_clause
)
))?;
buf.writeln("type Error = ::askama::Error;")?;
buf.writeln("#[inline]")?;
buf.writeln(&format!(
"{} {{",
quote!(fn try_from(value: &#ident #orig_ty_generics) -> Result<Self, Self::Error>)
))?;
buf.writeln("::askama::Template::render(value).map(Into::into)")?;
buf.writeln("}")?;
buf.writeln("}")
}
// Implement mendes' `Responder`.
#[cfg(feature = "with-mendes")]
fn impl_mendes_responder(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
let param = syn::parse_str("A: ::mendes::Application").unwrap();
let mut generics = self.input.ast.generics.clone();
generics.params.push(param);
let (_, orig_ty_generics, _) = self.input.ast.generics.split_for_impl();
let (impl_generics, _, where_clause) = generics.split_for_impl();
let mut where_clause = match where_clause {
Some(clause) => clause.clone(),
None => syn::WhereClause {
where_token: syn::Token![where](proc_macro2::Span::call_site()),
predicates: syn::punctuated::Punctuated::new(),
},
};
where_clause
.predicates
.push(syn::parse_str("A::ResponseBody: From<String>").unwrap());
where_clause
.predicates
.push(syn::parse_str("A::Error: From<::askama_mendes::Error>").unwrap());
buf.writeln(
format!(
"{} {} for {} {} {{",
quote!(impl #impl_generics),
"::mendes::application::IntoResponse<A>",
self.input.ast.ident,
quote!(#orig_ty_generics #where_clause),
)
.as_ref(),
)?;
buf.writeln(
"fn into_response(self, app: &A, req: &::mendes::http::request::Parts) \
-> ::mendes::http::Response<A::ResponseBody> {",
)?;
buf.writeln("::askama_mendes::into_response(app, req, &self)")?;
buf.writeln("}")?;
buf.writeln("}")?;
Ok(())
}
// Implement Rocket's `Responder`.
#[cfg(feature = "with-rocket")]
fn impl_rocket_responder(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
let lifetime1 = syn::Lifetime::new("'askama1", proc_macro2::Span::call_site());
let lifetime2 = syn::Lifetime::new("'askama2", proc_macro2::Span::call_site());
let mut param2 = syn::LifetimeParam::new(lifetime2);
param2.colon_token = Some(syn::Token![:](proc_macro2::Span::call_site()));
param2.bounds = syn::punctuated::Punctuated::new();
param2.bounds.push_value(lifetime1.clone());
let param1 = syn::GenericParam::Lifetime(syn::LifetimeParam::new(lifetime1));
let param2 = syn::GenericParam::Lifetime(param2);
self.write_header(
buf,
"::askama_rocket::Responder<'askama1, 'askama2>",
Some(vec![param1, param2]),
)?;
buf.writeln("#[inline]")?;
buf.writeln(
"fn respond_to(self, _: &'askama1 ::askama_rocket::Request) \
-> ::askama_rocket::Result<'askama2> {",
)?;
buf.writeln("::askama_rocket::respond(&self)")?;
buf.writeln("}")?;
buf.writeln("}")?;
Ok(())
}
#[cfg(feature = "with-tide")]
fn impl_tide_integrations(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
self.write_header(
buf,
"::std::convert::TryInto<::askama_tide::tide::Body>",
None,
)?;
buf.writeln(
"type Error = ::askama_tide::askama::Error;\n\
#[inline]\n\
fn try_into(self) -> ::askama_tide::askama::Result<::askama_tide::tide::Body> {",
)?;
buf.writeln("::askama_tide::try_into_body(&self)")?;
buf.writeln("}")?;
buf.writeln("}")?;
buf.writeln("#[allow(clippy::from_over_into)]")?;
self.write_header(buf, "Into<::askama_tide::tide::Response>", None)?;
buf.writeln("#[inline]")?;
buf.writeln("fn into(self) -> ::askama_tide::tide::Response {")?;
buf.writeln("::askama_tide::into_response(&self)")?;
buf.writeln("}\n}")
}
#[cfg(feature = "with-warp")]
fn impl_warp_reply(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
self.write_header(buf, "::askama_warp::warp::reply::Reply", None)?;
buf.writeln("#[inline]")?;
buf.writeln("fn into_response(self) -> ::askama_warp::warp::reply::Response {")?;
buf.writeln("::askama_warp::reply(&self)")?;
buf.writeln("}")?;
buf.writeln("}")
}
// Writes header for the `impl` for `TraitFromPathName` or `Template`
// for the given context struct.
fn write_header(
&mut self,
buf: &mut Buffer,
target: &str,
params: Option<Vec<syn::GenericParam>>,
) -> Result<(), CompileError> {
let mut generics = self.input.ast.generics.clone();
if let Some(params) = params {
for param in params {
generics.params.push(param);
}
}
let (_, orig_ty_generics, _) = self.input.ast.generics.split_for_impl();
let (impl_generics, _, where_clause) = generics.split_for_impl();
buf.writeln(
format!(
"{} {} for {}{} {{",
quote!(impl #impl_generics),
target,
self.input.ast.ident,
quote!(#orig_ty_generics #where_clause),
)
.as_ref(),
)
}
/* Helper methods for handling node types */
fn handle(
&mut self,
ctx: &'a Context<'_>,
nodes: &'a [Node<'_>],
buf: &mut Buffer,
level: AstLevel,
) -> Result<usize, CompileError> {
let mut size_hint = 0;
for n in nodes {
match *n {
Node::Lit(lws, val, rws) => {
self.visit_lit(lws, val, rws);
}
Node::Comment(ws) => {
self.write_comment(ws);
}
Node::Expr(ws, ref val) => {
self.write_expr(ws, val);
}
Node::LetDecl(ws, ref var) => {
self.write_let_decl(buf, ws, var)?;
}
Node::Let(ws, ref var, ref val) => {
self.write_let(buf, ws, var, val)?;
}
Node::Cond(ref conds, ws) => {
size_hint += self.write_cond(ctx, buf, conds, ws)?;
}
Node::Match(ws1, ref expr, ref arms, ws2) => {
size_hint += self.write_match(ctx, buf, ws1, expr, arms, ws2)?;
}
Node::Loop(ref loop_block) => {
size_hint += self.write_loop(ctx, buf, loop_block)?;
}
Node::BlockDef(ws1, name, _, ws2) => {
size_hint += self.write_block(buf, Some(name), Ws(ws1.0, ws2.1))?;
}
Node::Include(ws, path) => {
size_hint += self.handle_include(ctx, buf, ws, path)?;
}
Node::Call(ws, scope, name, ref args) => {
size_hint += self.write_call(ctx, buf, ws, scope, name, args)?;
}
Node::Macro(_, ref m) => {
if level != AstLevel::Top {
return Err("macro blocks only allowed at the top level".into());
}
self.flush_ws(m.ws1);
self.prepare_ws(m.ws2);
}
Node::Raw(ws1, lws, val, rws, ws2) => {
self.handle_ws(ws1);
self.visit_lit(lws, val, rws);
self.handle_ws(ws2);
}
Node::Import(ws, _, _) => {
if level != AstLevel::Top {
return Err("import blocks only allowed at the top level".into());
}
self.handle_ws(ws);
}
Node::Extends(_) => {
if level != AstLevel::Top {
return Err("extend blocks only allowed at the top level".into());
}
// No whitespace handling: child template top-level is not used,
// except for the blocks defined in it.
}
Node::Break(ws) => {
self.handle_ws(ws);
self.write_buf_writable(buf)?;
buf.writeln("break;")?;
}
Node::Continue(ws) => {
self.handle_ws(ws);
self.write_buf_writable(buf)?;
buf.writeln("continue;")?;
}
}
}
if AstLevel::Top == level {
// Handle any pending whitespace.
if self.next_ws.is_some() {
self.flush_ws(Ws(Some(self.skip_ws.into()), None));
}
size_hint += self.write_buf_writable(buf)?;
}
Ok(size_hint)
}
fn write_cond(
&mut self,
ctx: &'a Context<'_>,
buf: &mut Buffer,
conds: &'a [Cond<'_>],
ws: Ws,
) -> Result<usize, CompileError> {
let mut flushed = 0;
let mut arm_sizes = Vec::new();
let mut has_else = false;
for (i, &(cws, ref cond, ref nodes)) in conds.iter().enumerate() {
self.handle_ws(cws);
flushed += self.write_buf_writable(buf)?;
if i > 0 {
self.locals.pop();
}
self.locals.push();
let mut arm_size = 0;
if let Some(CondTest { target, expr }) = cond {
if i == 0 {
buf.write("if ");
} else {
buf.dedent()?;
buf.write("} else if ");
}
if let Some(target) = target {
let mut expr_buf = Buffer::new(0);
self.visit_expr(&mut expr_buf, expr)?;
buf.write("let ");
self.visit_target(buf, true, true, target);
buf.write(" = &(");
buf.write(&expr_buf.buf);
buf.write(")");
} else {
// The following syntax `*(&(...) as &bool)` is used to
// trigger Rust's automatic dereferencing, to coerce
// e.g. `&&&&&bool` to `bool`. First `&(...) as &bool`
// coerces e.g. `&&&bool` to `&bool`. Then `*(&bool)`
// finally dereferences it to `bool`.
buf.write("*(&(");
let expr_code = self.visit_expr_root(expr)?;
buf.write(&expr_code);
buf.write(") as &bool)");
}
} else {
buf.dedent()?;
buf.write("} else");
has_else = true;
}
buf.writeln(" {")?;
arm_size += self.handle(ctx, nodes, buf, AstLevel::Nested)?;
arm_sizes.push(arm_size);
}
self.handle_ws(ws);
flushed += self.write_buf_writable(buf)?;
buf.writeln("}")?;
self.locals.pop();
if !has_else {
arm_sizes.push(0);
}
Ok(flushed + median(&mut arm_sizes))
}
#[allow(clippy::too_many_arguments)]
fn write_match(
&mut self,
ctx: &'a Context<'_>,
buf: &mut Buffer,
ws1: Ws,
expr: &Expr<'_>,
arms: &'a [When<'_>],
ws2: Ws,
) -> Result<usize, CompileError> {
self.flush_ws(ws1);
let flushed = self.write_buf_writable(buf)?;
let mut arm_sizes = Vec::new();
let expr_code = self.visit_expr_root(expr)?;
buf.writeln(&format!("match &{expr_code} {{"))?;
let mut arm_size = 0;
for (i, arm) in arms.iter().enumerate() {
let &(ws, ref target, ref body) = arm;
self.handle_ws(ws);
if i > 0 {
arm_sizes.push(arm_size + self.write_buf_writable(buf)?);
buf.writeln("}")?;
self.locals.pop();
}
self.locals.push();
self.visit_target(buf, true, true, target);
buf.writeln(" => {")?;
arm_size = self.handle(ctx, body, buf, AstLevel::Nested)?;
}
self.handle_ws(ws2);
arm_sizes.push(arm_size + self.write_buf_writable(buf)?);
buf.writeln("}")?;
self.locals.pop();
buf.writeln("}")?;
Ok(flushed + median(&mut arm_sizes))
}
#[allow(clippy::too_many_arguments)]
fn write_loop(
&mut self,
ctx: &'a Context<'_>,
buf: &mut Buffer,
loop_block: &'a Loop<'_>,
) -> Result<usize, CompileError> {
self.handle_ws(loop_block.ws1);
self.locals.push();
let expr_code = self.visit_expr_root(&loop_block.iter)?;
let flushed = self.write_buf_writable(buf)?;
buf.writeln("{")?;
buf.writeln("let mut _did_loop = false;")?;
match loop_block.iter {
Expr::Range(_, _, _) => buf.writeln(&format!("let _iter = {expr_code};")),
Expr::Array(..) => buf.writeln(&format!("let _iter = {expr_code}.iter();")),
// If `iter` is a call then we assume it's something that returns
// an iterator. If not then the user can explicitly add the needed
// call without issues.
Expr::Call(..) | Expr::Index(..) => {
buf.writeln(&format!("let _iter = ({expr_code}).into_iter();"))
}
// If accessing `self` then it most likely needs to be
// borrowed, to prevent an attempt of moving.
_ if expr_code.starts_with("self.") => {
buf.writeln(&format!("let _iter = (&{expr_code}).into_iter();"))
}
// If accessing a field then it most likely needs to be
// borrowed, to prevent an attempt of moving.
Expr::Attr(..) => buf.writeln(&format!("let _iter = (&{expr_code}).into_iter();")),
// Otherwise, we borrow `iter` assuming that it implements `IntoIterator`.
_ => buf.writeln(&format!("let _iter = ({expr_code}).into_iter();")),
}?;
if let Some(cond) = &loop_block.cond {
self.locals.push();
buf.write("let _iter = _iter.filter(|");
self.visit_target(buf, true, true, &loop_block.var);
buf.write("| -> bool {");
self.visit_expr(buf, cond)?;
buf.writeln("});")?;
self.locals.pop();
}
self.locals.push();
buf.write("for (");
self.visit_target(buf, true, true, &loop_block.var);
buf.writeln(", _loop_item) in ::askama::helpers::TemplateLoop::new(_iter) {")?;
buf.writeln("_did_loop = true;")?;
let mut size_hint1 = self.handle(ctx, &loop_block.body, buf, AstLevel::Nested)?;
self.handle_ws(loop_block.ws2);
size_hint1 += self.write_buf_writable(buf)?;
self.locals.pop();
buf.writeln("}")?;
buf.writeln("if !_did_loop {")?;
self.locals.push();
let mut size_hint2 = self.handle(ctx, &loop_block.else_block, buf, AstLevel::Nested)?;
self.handle_ws(loop_block.ws3);
size_hint2 += self.write_buf_writable(buf)?;
self.locals.pop();
buf.writeln("}")?;
buf.writeln("}")?;
Ok(flushed + ((size_hint1 * 3) + size_hint2) / 2)
}
fn write_call(
&mut self,
ctx: &'a Context<'_>,
buf: &mut Buffer,
ws: Ws,
scope: Option<&str>,
name: &str,
args: &[Expr<'_>],
) -> Result<usize, CompileError> {
if name == "super" {
return self.write_block(buf, None, ws);
}
let (def, own_ctx) = match scope {
Some(s) => {
let path = ctx.imports.get(s).ok_or_else(|| {
CompileError::from(format!("no import found for scope {s:?}"))
})?;
let mctx = self
.contexts
.get(path.as_path())
.ok_or_else(|| CompileError::from(format!("context for {path:?} not found")))?;
let def = mctx.macros.get(name).ok_or_else(|| {
CompileError::from(format!("macro {name:?} not found in scope {s:?}"))
})?;
(def, mctx)
}
None => {
let def = ctx
.macros
.get(name)
.ok_or_else(|| CompileError::from(format!("macro {name:?} not found")))?;
(def, ctx)
}
};
self.flush_ws(ws); // Cannot handle_ws() here: whitespace from macro definition comes first
self.locals.push();
self.write_buf_writable(buf)?;
buf.writeln("{")?;
self.prepare_ws(def.ws1);
let mut names = Buffer::new(0);
let mut values = Buffer::new(0);
let mut is_first_variable = true;
for (i, arg) in def.args.iter().enumerate() {
let expr = args.get(i).ok_or_else(|| {
CompileError::from(format!("macro {name:?} takes more than {i} arguments"))
})?;
match expr {
// If `expr` is already a form of variable then
// don't reintroduce a new variable. This is
// to avoid moving non-copyable values.
Expr::Var(name) => {
let var = self.locals.resolve_or_self(name);
self.locals.insert(arg, LocalMeta::with_ref(var));
}
Expr::Attr(obj, attr) => {
let mut attr_buf = Buffer::new(0);
self.visit_attr(&mut attr_buf, obj, attr)?;
let var = self.locals.resolve(&attr_buf.buf).unwrap_or(attr_buf.buf);
self.locals.insert(arg, LocalMeta::with_ref(var));
}
// Everything else still needs to become variables,
// to avoid having the same logic be executed
// multiple times, e.g. in the case of macro
// parameters being used multiple times.
_ => {
if is_first_variable {
is_first_variable = false
} else {