Debian Codegraph @

third_party/rust/askama_derive/src/input.rs

raw
1 use std::borrow::Cow;
2 use std::collections::hash_map::{Entry, HashMap};
3 use std::fs::read_to_string;
4 use std::iter::FusedIterator;
5 use std::path::{Path, PathBuf};
6 use std::str::FromStr;
7 use std::sync::{Arc, OnceLock};
8
9 use parser::node::Whitespace;
10 use parser::{Node, Parsed};
11 use proc_macro2::Span;
12 use rustc_hash::FxBuildHasher;
13 use syn::punctuated::Punctuated;
14 use syn::spanned::Spanned;
15 use syn::{Attribute, Expr, ExprLit, ExprPath, Ident, Lit, LitBool, LitStr, Meta, Token};
16
17 use crate::config::{Config, SyntaxAndCache};
18 use crate::{CompileError, FileInfo, MsgValidEscapers, OnceMap};
19
20 #[derive(Clone)]
21 pub(crate) struct TemplateInput<'a> {
22 pub(crate) ast: &'a syn::DeriveInput,
23 pub(crate) enum_ast: Option<&'a syn::DeriveInput>,
24 pub(crate) config: &'a Config,
25 pub(crate) syntax: &'a SyntaxAndCache<'a>,
26 pub(crate) source: &'a Source,
27 pub(crate) source_span: Option<Span>,
28 pub(crate) block: Option<(&'a str, Span)>,
29 #[cfg(feature = "blocks")]
30 pub(crate) blocks: &'a [Block],
31 pub(crate) print: Print,
32 pub(crate) escaper: &'a str,
33 pub(crate) path: Arc<Path>,
34 pub(crate) fields: Arc<[String]>,
35 }
36
37 impl TemplateInput<'_> {
38 /// Extract the template metadata from the `DeriveInput` structure. This
39 /// mostly recovers the data for the `TemplateInput` fields from the
40 /// `template()` attribute list fields.
41 pub(crate) fn new<'n>(
42 ast: &'n syn::DeriveInput,
43 enum_ast: Option<&'n syn::DeriveInput>,
44 config: &'n Config,
45 args: &'n TemplateArgs,
46 ) -> Result<TemplateInput<'n>, CompileError> {
47 let TemplateArgs {
48 source: (source, source_span),
49 block,
50 #[cfg(feature = "blocks")]
51 blocks,
52 print,
53 escaping,
54 ext,
55 ext_span,
56 syntax,
57 ..
58 } = args;
59
60 // Validate the `source` and `ext` value together, since they are
61 // related. In case `source` was used instead of `path`, the value
62 // of `ext` is merged into a synthetic `path` value here.
63 let path = match (&source, &ext) {
64 (Source::Path(path), _) => config.find_template(path, None, None)?,
65 (&Source::Source(_), Some(ext)) => {
66 PathBuf::from(format!("{}.{}", ast.ident, ext)).into()
67 }
68 (&Source::Source(_), None) => {
69 return Err(CompileError::no_file_info(
70 #[cfg(not(feature = "code-in-doc"))]
71 "must include `ext` attribute when using `source` attribute",
72 #[cfg(feature = "code-in-doc")]
73 "must include `ext` attribute when using `source` or `in_doc` attribute",
74 None,
75 ));
76 }
77 };
78
79 // Validate syntax
80 let syntax = syntax.as_deref().map_or_else(
81 || Ok(config.syntaxes.get(config.default_syntax).unwrap()),
82 |s| {
83 config.syntaxes.get(s).ok_or_else(|| {
84 CompileError::no_file_info(format_args!("syntax `{s}` is undefined"), None)
85 })
86 },
87 )?;
88
89 // Match extension against defined output formats
90
91 let escaping = escaping
92 .as_deref()
93 .or_else(|| path.extension().and_then(|s| s.to_str()))
94 .unwrap_or_default();
95
96 let escaper = config
97 .escapers
98 .iter()
99 .find_map(|(extensions, path)| {
100 extensions
101 .contains(&Cow::Borrowed(escaping))
102 .then_some(path.as_ref())
103 })
104 .ok_or_else(|| {
105 CompileError::no_file_info(
106 format_args!(
107 "no escaper defined for extension '{escaping}'. You can define an escaper \
108 in the config file (named `askama.toml` by default). {}",
109 MsgValidEscapers(&config.escapers),
110 ),
111 *ext_span,
112 )
113 })?;
114
115 let empty_punctuated = Punctuated::new();
116 let fields = match ast.data {
117 syn::Data::Struct(ref struct_) => {
118 if let syn::Fields::Named(ref fields) = &struct_.fields {
119 &fields.named
120 } else {
121 &empty_punctuated
122 }
123 }
124 syn::Data::Union(ref union_) => &union_.fields.named,
125 syn::Data::Enum(_) => &empty_punctuated,
126 }
127 .iter()
128 .map(|f| match &f.ident {
129 Some(ident) => ident.to_string(),
130 None => unreachable!("we checked that we are using a struct"),
131 })
132 .collect::<Vec<_>>();
133
134 Ok(TemplateInput {
135 ast,
136 enum_ast,
137 config,
138 syntax,
139 source,
140 source_span: *source_span,
141 block: block.as_ref().map(|(block, span)| (block.as_str(), *span)),
142 #[cfg(feature = "blocks")]
143 blocks: blocks.as_slice(),
144 print: *print,
145 escaper,
146 path,
147 fields: fields.into(),
148 })
149 }
150
151 pub(crate) fn find_used_templates(
152 &self,
153 map: &mut HashMap<Arc<Path>, Arc<Parsed>, FxBuildHasher>,
154 ) -> Result<(), CompileError> {
155 let (source, source_path) = match &self.source {
156 Source::Source(s) => (s.clone(), None),
157 Source::Path(_) => (
158 get_template_source(&self.path, None)?,
159 Some(Arc::clone(&self.path)),
160 ),
161 };
162
163 let mut dependency_graph = Vec::new();
164 let mut check = vec![(Arc::clone(&self.path), source, source_path)];
165 while let Some((path, source, source_path)) = check.pop() {
166 let parsed = match self.syntax.parse(Arc::clone(&source), source_path) {
167 Ok(parsed) => parsed,
168 Err(err) => {
169 let msg = err
170 .message
171 .unwrap_or_else(|| "failed to parse template source".into());
172 let file_path = err
173 .file_path
174 .as_deref()
175 .unwrap_or(Path::new("<source attribute>"));
176 let file_info =
177 FileInfo::new(file_path, Some(&source), Some(&source[err.offset..]));
178 return Err(CompileError::new(msg, Some(file_info)));
179 }
180 };
181
182 let mut top = true;
183 let mut nested = vec![parsed.nodes()];
184 while let Some(nodes) = nested.pop() {
185 for n in nodes {
186 let mut add_to_check = |new_path: Arc<Path>| -> Result<(), CompileError> {
187 if let Entry::Vacant(e) = map.entry(new_path) {
188 // Add a dummy entry to `map` in order to prevent adding `path`
189 // multiple times to `check`.
190 let new_path = e.key();
191 let source = parsed.source();
192 let source = get_template_source(
193 new_path,
194 Some((
195 &path,
196 source,
197 n.span().as_suffix_of(source).unwrap_or_default(),
198 )),
199 )?;
200 check.push((new_path.clone(), source, Some(new_path.clone())));
201 e.insert(Arc::default());
202 }
203 Ok(())
204 };
205
206 match n {
207 Node::Extends(extends) if top => {
208 let extends = self.config.find_template(
209 extends.path,
210 Some(&path),
211 Some(FileInfo::of(extends.span(), &path, &parsed)),
212 )?;
213 let dependency_path = (path.clone(), extends.clone());
214 if path == extends {
215 // We add the path into the graph to have a better looking error.
216 dependency_graph.push(dependency_path);
217 return cyclic_graph_error(&dependency_graph);
218 } else if dependency_graph.contains(&dependency_path) {
219 return cyclic_graph_error(&dependency_graph);
220 }
221 dependency_graph.push(dependency_path);
222 add_to_check(extends)?;
223 }
224 Node::Macro(m) if top => {
225 nested.push(&m.nodes);
226 }
227 Node::Import(import) if top => {
228 let import = self.config.find_template(
229 import.path,
230 Some(&path),
231 Some(FileInfo::of(import.span(), &path, &parsed)),
232 )?;
233 add_to_check(import)?;
234 }
235 Node::FilterBlock(f) => {
236 nested.push(&f.nodes);
237 }
238 Node::Include(include) => {
239 let include = self.config.find_template(
240 include.path,
241 Some(&path),
242 Some(FileInfo::of(include.span(), &path, &parsed)),
243 )?;
244 add_to_check(include)?;
245 }
246 Node::BlockDef(b) => {
247 nested.push(&b.nodes);
248 }
249 Node::If(i) => {
250 for cond in &i.branches {
251 nested.push(&cond.nodes);
252 }
253 }
254 Node::Loop(l) => {
255 nested.push(&l.body);
256 nested.push(&l.else_nodes);
257 }
258 Node::Match(m) => {
259 for arm in &m.arms {
260 nested.push(&arm.nodes);
261 }
262 }
263 Node::Lit(_)
264 | Node::Comment(_)
265 | Node::Expr(_, _)
266 | Node::Call(_)
267 | Node::Extends(_)
268 | Node::Let(_)
269 | Node::Import(_)
270 | Node::Macro(_)
271 | Node::Raw(_)
272 | Node::Continue(_)
273 | Node::Break(_) => {}
274 }
275 }
276 top = false;
277 }
278 map.insert(path, parsed);
279 }
280 Ok(())
281 }
282 }
283
284 pub(crate) enum AnyTemplateArgs {
285 Struct(TemplateArgs),
286 Enum {
287 enum_args: Option<PartialTemplateArgs>,
288 vars_args: Vec<Option<PartialTemplateArgs>>,
289 has_default_impl: bool,
290 },
291 }
292
293 impl AnyTemplateArgs {
294 pub(crate) fn new(ast: &syn::DeriveInput) -> Result<Self, CompileError> {
295 let syn::Data::Enum(enum_data) = &ast.data else {
296 return Ok(Self::Struct(TemplateArgs::new(ast)?));
297 };
298
299 let enum_args = PartialTemplateArgs::new(ast, &ast.attrs, false)?;
300 let vars_args = enum_data
301 .variants
302 .iter()
303 .map(|variant| PartialTemplateArgs::new(ast, &variant.attrs, true))
304 .collect::<Result<Vec<_>, _>>()?;
305 if vars_args.is_empty() {
306 return Ok(Self::Struct(TemplateArgs::from_partial(ast, enum_args)?));
307 }
308
309 let mut needs_default_impl = vars_args.len();
310 let enum_source = enum_args.as_ref().and_then(|v| v.source.as_ref());
311 for (variant, var_args) in enum_data.variants.iter().zip(&vars_args) {
312 if var_args
313 .as_ref()
314 .and_then(|v| v.source.as_ref())
315 .or(enum_source)
316 .is_none()
317 {
318 return Err(CompileError::new_with_span(
319 #[cfg(not(feature = "code-in-doc"))]
320 "either all `enum` variants need a `path` or `source` argument, \
321 or the `enum` itself needs a default implementation",
322 #[cfg(feature = "code-in-doc")]
323 "either all `enum` variants need a `path`, `source` or `in_doc` argument, \
324 or the `enum` itself needs a default implementation",
325 None,
326 Some(variant.ident.span()),
327 ));
328 } else if !var_args.is_none() {
329 needs_default_impl -= 1;
330 }
331 }
332
333 Ok(Self::Enum {
334 enum_args,
335 vars_args,
336 has_default_impl: needs_default_impl > 0,
337 })
338 }
339
340 pub(crate) fn take_crate_name(&mut self) -> Option<ExprPath> {
341 match self {
342 AnyTemplateArgs::Struct(template_args) => template_args.crate_name.take(),
343 AnyTemplateArgs::Enum { enum_args, .. } => {
344 if let Some(PartialTemplateArgs { crate_name, .. }) = enum_args {
345 crate_name.take()
346 } else {
347 None
348 }
349 }
350 }
351 }
352 }
353
354 #[cfg(feature = "blocks")]
355 pub(crate) struct Block {
356 pub(crate) name: String,
357 pub(crate) span: Span,
358 }
359
360 pub(crate) struct TemplateArgs {
361 pub(crate) source: (Source, Option<Span>),
362 block: Option<(String, Span)>,
363 #[cfg(feature = "blocks")]
364 blocks: Vec<Block>,
365 print: Print,
366 escaping: Option<String>,
367 ext: Option<String>,
368 ext_span: Option<Span>,
369 syntax: Option<String>,
370 config: Option<String>,
371 crate_name: Option<ExprPath>,
372 pub(crate) whitespace: Option<Whitespace>,
373 pub(crate) template_span: Option<Span>,
374 pub(crate) config_span: Option<Span>,
375 }
376
377 impl TemplateArgs {
378 pub(crate) fn new(ast: &syn::DeriveInput) -> Result<Self, CompileError> {
379 Self::from_partial(ast, PartialTemplateArgs::new(ast, &ast.attrs, false)?)
380 }
381
382 pub(crate) fn from_partial(
383 ast: &syn::DeriveInput,
384 args: Option<PartialTemplateArgs>,
385 ) -> Result<Self, CompileError> {
386 let Some(args) = args else {
387 return Err(CompileError::new_with_span(
388 "no attribute `template` found",
389 None,
390 Some(ast.ident.span()),
391 ));
392 };
393 Ok(Self {
394 source: match args.source {
395 Some(PartialTemplateArgsSource::Path(s)) => {
396 (Source::Path(s.value().into()), Some(s.span()))
397 }
398 Some(PartialTemplateArgsSource::Source(s)) => {
399 (Source::Source(s.value().into()), Some(s.span()))
400 }
401 #[cfg(feature = "code-in-doc")]
402 Some(PartialTemplateArgsSource::InDoc(span, source)) => (source, Some(span)),
403 None => {
404 return Err(CompileError::no_file_info(
405 #[cfg(not(feature = "code-in-doc"))]
406 "specify one template argument `path` or `source`",
407 #[cfg(feature = "code-in-doc")]
408 "specify one template argument `path`, `source` or `in_doc`",
409 Some(args.template.span()),
410 ));
411 }
412 },
413 block: args.block.map(|value| (value.value(), value.span())),
414 #[cfg(feature = "blocks")]
415 blocks: args
416 .blocks
417 .unwrap_or_default()
418 .into_iter()
419 .map(|value| Block {
420 name: value.value(),
421 span: value.span(),
422 })
423 .collect(),
424 print: args.print.unwrap_or_default(),
425 escaping: args.escape.map(|value| value.value()),
426 ext: args.ext.as_ref().map(|value| value.value()),
427 ext_span: args.ext.as_ref().map(|value| value.span()),
428 syntax: args.syntax.map(|value| value.value()),
429 config: args.config.as_ref().map(|value| value.value()),
430 crate_name: args.crate_name,
431 whitespace: args.whitespace,
432 template_span: Some(args.template.span()),
433 config_span: args.config.as_ref().map(|value| value.span()),
434 })
435 }
436
437 pub(crate) fn fallback() -> Self {
438 Self {
439 source: (Source::Source("".into()), None),
440 block: None,
441 #[cfg(feature = "blocks")]
442 blocks: vec![],
443 print: Print::default(),
444 escaping: None,
445 ext: Some("txt".to_string()),
446 ext_span: None,
447 syntax: None,
448 config: None,
449 crate_name: None,
450 whitespace: None,
451 template_span: None,
452 config_span: None,
453 }
454 }
455
456 pub(crate) fn config_path(&self) -> Option<&str> {
457 self.config.as_deref()
458 }
459 }
460
461 /// Try to find the source in the comment, in a `askama` code block.
462 ///
463 /// This is only done if no path or source was given in the `#[template]` attribute.
464 #[cfg(feature = "code-in-doc")]
465 fn source_from_docs(
466 span: Span,
467 docs: &[&Attribute],
468 ast: &syn::DeriveInput,
469 ) -> Result<(Source, Option<Span>), CompileError> {
470 let (source_span, source) = collect_comment_blocks(span, docs, ast)?;
471 let source = strip_common_ws_prefix(source);
472 let source = collect_askama_code_blocks(span, ast, source)?;
473 Ok((source, source_span))
474 }
475
476 #[cfg(feature = "code-in-doc")]
477 fn collect_comment_blocks(
478 span: Span,
479 docs: &[&Attribute],
480 ast: &syn::DeriveInput,
481 ) -> Result<(Option<Span>, String), CompileError> {
482 let mut source_span: Option<Span> = None;
483 let mut assign_span = |kv: &syn::MetaNameValue| {
484 // FIXME: uncomment once <https://github.com/rust-lang/rust/issues/54725> is stable
485 // let new_span = kv.path.span();
486 // source_span = Some(match source_span {
487 // Some(cur_span) => cur_span.join(new_span).unwrap_or(cur_span),
488 // None => new_span,
489 // });
490
491 if source_span.is_none() {
492 source_span = Some(kv.path.span());
493 }
494 };
495
496 let mut source = String::new();
497 for a in docs {
498 // is a comment?
499 let Meta::NameValue(kv) = &a.meta else {
500 continue;
501 };
502 if !kv.path.is_ident("doc") {
503 continue;
504 }
505
506 // is an understood comment, e.g. not `#[doc = inline_str(…)]`
507 let mut value = &kv.value;
508 let value = loop {
509 match value {
510 Expr::Lit(lit) => break lit,
511 Expr::Group(group) => value = &group.expr,
512 _ => continue,
513 }
514 };
515 let Lit::Str(value) = &value.lit else {
516 continue;
517 };
518
519 assign_span(kv);
520 source.push_str(value.value().as_str());
521 source.push('\n');
522 }
523 if source.is_empty() {
524 return Err(no_askama_code_block(span, ast));
525 }
526
527 Ok((source_span, source))
528 }
529
530 #[cfg(feature = "code-in-doc")]
531 fn no_askama_code_block(span: Span, ast: &syn::DeriveInput) -> CompileError {
532 let kind = match &ast.data {
533 syn::Data::Struct(_) => "struct",
534 syn::Data::Enum(_) => "enum",
535 // actually unreachable: `union`s are rejected by `TemplateArgs::new()`
536 syn::Data::Union(_) => "union",
537 };
538 CompileError::no_file_info(
539 format_args!(
540 "when using `in_doc` with the value `true`, the {kind}'s documentation needs a \
541 `askama` code block"
542 ),
543 Some(span),
544 )
545 }
546
547 #[cfg(feature = "code-in-doc")]
548 fn strip_common_ws_prefix(source: String) -> String {
549 let mut common_prefix_iter = source
550 .lines()
551 .filter_map(|s| Some(&s[..s.find(|c: char| !c.is_ascii_whitespace())?]));
552 let mut common_prefix = common_prefix_iter.next().unwrap_or_default();
553 for p in common_prefix_iter {
554 if common_prefix.is_empty() {
555 break;
556 }
557 let ((pos, _), _) = common_prefix
558 .char_indices()
559 .zip(p.char_indices())
560 .take_while(|(l, r)| l == r)
561 .last()
562 .unwrap_or_default();
563 common_prefix = &common_prefix[..pos];
564 }
565 if common_prefix.is_empty() {
566 return source;
567 }
568
569 source
570 .lines()
571 .flat_map(|s| [s.get(common_prefix.len()..).unwrap_or_default(), "\n"])
572 .collect()
573 }
574
575 #[cfg(feature = "code-in-doc")]
576 fn collect_askama_code_blocks(
577 span: Span,
578 ast: &syn::DeriveInput,
579 source: String,
580 ) -> Result<Source, CompileError> {
581 use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag, TagEnd};
582
583 let mut tmpl_source = String::new();
584 let mut in_askama_code = false;
585 let mut had_askama_code = false;
586 for e in Parser::new(&source) {
587 match (in_askama_code, e) {
588 (false, Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(s)))) => {
589 if s.split(",")
590 .any(|s| JINJA_EXTENSIONS.contains(&s.trim_ascii()))
591 {
592 in_askama_code = true;
593 had_askama_code = true;
594 }
595 }
596 (true, Event::End(TagEnd::CodeBlock)) => in_askama_code = false,
597 (true, Event::Text(text)) => tmpl_source.push_str(&text),
598 _ => {}
599 }
600 }
601 if !had_askama_code {
602 return Err(no_askama_code_block(span, ast));
603 }
604
605 if tmpl_source.ends_with('\n') {
606 tmpl_source.pop();
607 }
608 Ok(Source::Source(tmpl_source.into()))
609 }
610
611 struct ResultIter<I, E>(Result<I, Option<E>>);
612
613 impl<I: IntoIterator, E> From<Result<I, E>> for ResultIter<I::IntoIter, E> {
614 fn from(value: Result<I, E>) -> Self {
615 Self(match value {
616 Ok(i) => Ok(i.into_iter()),
617 Err(e) => Err(Some(e)),
618 })
619 }
620 }
621
622 impl<I: Iterator, E> Iterator for ResultIter<I, E> {
623 type Item = Result<I::Item, E>;
624
625 fn next(&mut self) -> Option<Self::Item> {
626 match &mut self.0 {
627 Ok(iter) => Some(Ok(iter.next()?)),
628 Err(err) => Some(Err(err.take()?)),
629 }
630 }
631 }
632
633 impl<I: FusedIterator, E> FusedIterator for ResultIter<I, E> {}
634
635 #[derive(Debug, Clone, Hash, PartialEq)]
636 pub(crate) enum Source {
637 Path(Arc<str>),
638 Source(Arc<str>),
639 }
640
641 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
642 pub(crate) enum Print {
643 All,
644 Ast,
645 Code,
646 None,
647 }
648
649 impl Default for Print {
650 fn default() -> Self {
651 Self::None
652 }
653 }
654
655 impl FromStr for Print {
656 type Err = String;
657
658 fn from_str(s: &str) -> Result<Self, Self::Err> {
659 match s {
660 "all" => Ok(Self::All),
661 "ast" => Ok(Self::Ast),
662 "code" => Ok(Self::Code),
663 "none" => Ok(Self::None),
664 _ => Err(format!("invalid value for `print` option: {s}")),
665 }
666 }
667 }
668
669 fn cyclic_graph_error(dependency_graph: &[(Arc<Path>, Arc<Path>)]) -> Result<(), CompileError> {
670 Err(CompileError::no_file_info(
671 format_args!(
672 "cyclic dependency in graph {:#?}",
673 dependency_graph
674 .iter()
675 .map(|e| format!("{:#?} --> {:#?}", e.0, e.1))
676 .collect::<Vec<String>>()
677 ),
678 None,
679 ))
680 }
681
682 pub(crate) fn get_template_source(
683 tpl_path: &Arc<Path>,
684 import_from: Option<(&Arc<Path>, &str, &str)>,
685 ) -> Result<Arc<str>, CompileError> {
686 static CACHE: OnceLock<OnceMap<Arc<Path>, Arc<str>>> = OnceLock::new();
687
688 CACHE.get_or_init(OnceMap::default).get_or_try_insert(
689 tpl_path,
690 |tpl_path| match read_to_string(tpl_path) {
691 Ok(mut source) => {
692 if source.ends_with('\n') {
693 let _ = source.pop();
694 }
695 Ok((Arc::clone(tpl_path), Arc::from(source)))
696 }
697 Err(err) => Err(CompileError::new(
698 format_args!(
699 "unable to open template file '{}': {err}",
700 tpl_path.to_str().unwrap(),
701 ),
702 import_from.map(|(node_file, file_source, node_source)| {
703 FileInfo::new(node_file, Some(file_source), Some(node_source))
704 }),
705 )),
706 },
707 Arc::clone,
708 )
709 }
710
711 pub(crate) struct PartialTemplateArgs {
712 pub(crate) template: Ident,
713 pub(crate) source: Option<PartialTemplateArgsSource>,
714 pub(crate) block: Option<LitStr>,
715 pub(crate) print: Option<Print>,
716 pub(crate) escape: Option<LitStr>,
717 pub(crate) ext: Option<LitStr>,
718 pub(crate) syntax: Option<LitStr>,
719 pub(crate) config: Option<LitStr>,
720 pub(crate) whitespace: Option<Whitespace>,
721 pub(crate) crate_name: Option<ExprPath>,
722 #[cfg(feature = "blocks")]
723 pub(crate) blocks: Option<Vec<LitStr>>,
724 }
725
726 #[derive(Clone)]
727 pub(crate) enum PartialTemplateArgsSource {
728 Path(LitStr),
729 Source(LitStr),
730 #[cfg(feature = "code-in-doc")]
731 InDoc(Span, Source),
732 }
733
734 impl PartialTemplateArgsSource {
735 pub(crate) fn span(&self) -> Span {
736 match self {
737 Self::Path(s) => s.span(),
738 Self::Source(s) => s.span(),
739 #[cfg(feature = "code-in-doc")]
740 Self::InDoc(s, _) => s.span(),
741 }
742 }
743 }
744
745 // implement PartialTemplateArgs::new()
746 const _: () = {
747 impl PartialTemplateArgs {
748 pub(crate) fn new(
749 ast: &syn::DeriveInput,
750 attrs: &[Attribute],
751 is_enum_variant: bool,
752 ) -> Result<Option<Self>, CompileError> {
753 new(ast, attrs, is_enum_variant)
754 }
755 }
756
757 #[inline]
758 fn new(
759 ast: &syn::DeriveInput,
760 attrs: &[Attribute],
761 is_enum_variant: bool,
762 ) -> Result<Option<PartialTemplateArgs>, CompileError> {
763 // FIXME: implement once <https://github.com/rust-lang/rfcs/pull/3715> is stable
764 if let syn::Data::Union(data) = &ast.data {
765 return Err(CompileError::new_with_span(
766 "askama templates are not supported for `union` types, only `struct` and `enum`",
767 None,
768 Some(data.union_token.span),
769 ));
770 }
771
772 #[cfg(feature = "code-in-doc")]
773 let mut meta_docs = vec![];
774
775 let mut this = PartialTemplateArgs {
776 template: Ident::new("template", Span::call_site()),
777 source: None,
778 block: None,
779 print: None,
780 escape: None,
781 ext: None,
782 syntax: None,
783 config: None,
784 whitespace: None,
785 crate_name: None,
786 #[cfg(feature = "blocks")]
787 blocks: None,
788 };
789 let mut has_data = false;
790
791 for attr in attrs {
792 let Some(ident) = attr.path().get_ident() else {
793 continue;
794 };
795 if ident == "template" {
796 this.template = ident.clone();
797 has_data = true;
798 } else {
799 #[cfg(feature = "code-in-doc")]
800 if ident == "doc" {
801 meta_docs.push(attr);
802 }
803 continue;
804 }
805
806 let args = attr
807 .parse_args_with(<Punctuated<Meta, Token![,]>>::parse_terminated)
808 .map_err(|e| {
809 CompileError::no_file_info(
810 format_args!("unable to parse template arguments: {e}"),
811 Some(attr.path().span()),
812 )
813 })?;
814 for arg in args {
815 let pair = match arg {
816 Meta::NameValue(pair) => pair,
817 v => {
818 return Err(CompileError::no_file_info(
819 "unsupported attribute argument",
820 Some(v.span()),
821 ));
822 }
823 };
824 let ident = match pair.path.get_ident() {
825 Some(ident) => ident,
826 None => unreachable!("not possible in syn::Meta::NameValue(…)"),
827 };
828
829 if ident == "askama" {
830 if is_enum_variant {
831 return Err(CompileError::no_file_info(
832 "template attribute `askama` can only be used on the `enum`, \
833 not its variants",
834 Some(ident.span()),
835 ));
836 }
837 ensure_only_once(ident, &mut this.crate_name)?;
838 this.crate_name = Some(get_exprpath(ident, pair.value)?);
839 continue;
840 } else if ident == "blocks" {
841 if !cfg!(feature = "blocks") {
842 return Err(CompileError::no_file_info(
843 "enable feature `blocks` to use `blocks` argument",
844 Some(ident.span()),
845 ));
846 } else if is_enum_variant {
847 return Err(CompileError::no_file_info(
848 "template attribute `blocks` can only be used on the `enum`, \
849 not its variants",
850 Some(ident.span()),
851 ));
852 }
853 #[cfg(feature = "blocks")]
854 {
855 ensure_only_once(ident, &mut this.blocks)?;
856 this.blocks = Some(
857 get_exprarray(ident, pair.value)?
858 .elems
859 .into_iter()
860 .map(|value| get_strlit(ident, get_lit(ident, value)?))
861 .collect::<Result<_, _>>()?,
862 );
863 continue;
864 }
865 }
866
867 let value = get_lit(ident, pair.value)?;
868
869 if ident == "path" {
870 ensure_source_only_once(ident, &this.source)?;
871 this.source = Some(PartialTemplateArgsSource::Path(get_strlit(ident, value)?));
872 } else if ident == "source" {
873 ensure_source_only_once(ident, &this.source)?;
874 this.source =
875 Some(PartialTemplateArgsSource::Source(get_strlit(ident, value)?));
876 } else if ident == "in_doc" {
877 let value = get_boollit(ident, value)?;
878 if !value.value() {
879 continue;
880 }
881 ensure_source_only_once(ident, &this.source)?;
882
883 #[cfg(not(feature = "code-in-doc"))]
884 {
885 return Err(CompileError::no_file_info(
886 "enable feature `code-in-doc` to use `in_doc` argument",
887 Some(ident.span()),
888 ));
889 }
890 #[cfg(feature = "code-in-doc")]
891 {
892 this.source = Some(PartialTemplateArgsSource::InDoc(
893 value.span(),
894 Source::Path("".into()),
895 ));
896 }
897 } else if ident == "block" {
898 set_strlit_pair(ident, value, &mut this.block)?;
899 } else if ident == "print" {
900 set_parseable_string(ident, value, &mut this.print)?;
901 } else if ident == "escape" {
902 set_strlit_pair(ident, value, &mut this.escape)?;
903 } else if ident == "ext" {
904 set_strlit_pair(ident, value, &mut this.ext)?;
905 } else if ident == "syntax" {
906 set_strlit_pair(ident, value, &mut this.syntax)?;
907 } else if ident == "config" {
908 set_strlit_pair(ident, value, &mut this.config)?;
909 } else if ident == "whitespace" {
910 set_parseable_string(ident, value, &mut this.whitespace)?;
911 } else {
912 return Err(CompileError::no_file_info(
913 format_args!("unsupported template attribute `{ident}` found"),
914 Some(ident.span()),
915 ));
916 }
917 }
918 }
919 if !has_data {
920 return Ok(None);
921 }
922
923 #[cfg(feature = "code-in-doc")]
924 if let Some(PartialTemplateArgsSource::InDoc(lit_span, _)) = this.source {
925 let (source, doc_span) = source_from_docs(lit_span, &meta_docs, ast)?;
926 this.source = Some(PartialTemplateArgsSource::InDoc(
927 doc_span.unwrap_or(lit_span),
928 source,
929 ));
930 }
931
932 Ok(Some(this))
933 }
934
935 fn set_strlit_pair(
936 name: &Ident,
937 value: ExprLit,
938 dest: &mut Option<LitStr>,
939 ) -> Result<(), CompileError> {
940 ensure_only_once(name, dest)?;
941 *dest = Some(get_strlit(name, value)?);
942 Ok(())
943 }
944
945 fn set_parseable_string<T: FromStr<Err: ToString>>(
946 name: &Ident,
947 value: ExprLit,
948 dest: &mut Option<T>,
949 ) -> Result<(), CompileError> {
950 ensure_only_once(name, dest)?;
951 let str_value = get_strlit(name, value)?;
952 *dest = Some(
953 str_value
954 .value()
955 .parse()
956 .map_err(|msg| CompileError::no_file_info(msg, Some(str_value.span())))?,
957 );
958 Ok(())
959 }
960
961 fn ensure_only_once<T>(name: &Ident, dest: &mut Option<T>) -> Result<(), CompileError> {
962 if dest.is_none() {
963 Ok(())
964 } else {
965 Err(CompileError::no_file_info(
966 format_args!("template attribute `{name}` already set"),
967 Some(name.span()),
968 ))
969 }
970 }
971
972 fn get_lit(name: &Ident, mut expr: Expr) -> Result<ExprLit, CompileError> {
973 loop {
974 match expr {
975 Expr::Lit(lit) => return Ok(lit),
976 Expr::Group(group) => expr = *group.expr,
977 v => {
978 return Err(CompileError::no_file_info(
979 format_args!("template attribute `{name}` expects a literal"),
980 Some(v.span()),
981 ));
982 }
983 }
984 }
985 }
986
987 fn get_strlit(name: &Ident, value: ExprLit) -> Result<LitStr, CompileError> {
988 if let Lit::Str(s) = value.lit {
989 Ok(s)
990 } else {
991 Err(CompileError::no_file_info(
992 format_args!("template attribute `{name}` expects a string literal"),
993 Some(value.lit.span()),
994 ))
995 }
996 }
997
998 fn get_boollit(name: &Ident, value: ExprLit) -> Result<LitBool, CompileError> {
999 if let Lit::Bool(s) = value.lit {
1000 Ok(s)
1001 } else {
1002 Err(CompileError::no_file_info(
1003 format_args!("template attribute `{name}` expects a boolean value"),
1004 Some(value.lit.span()),
1005 ))
1006 }
1007 }
1008
1009 fn get_exprpath(name: &Ident, mut expr: Expr) -> Result<ExprPath, CompileError> {
1010 loop {
1011 match expr {
1012 Expr::Path(path) => return Ok(path),
1013 Expr::Group(group) => expr = *group.expr,
1014 v => {
1015 return Err(CompileError::no_file_info(
1016 format_args!("template attribute `{name}` expects a path or identifier"),
1017 Some(v.span()),
1018 ));
1019 }
1020 }
1021 }
1022 }
1023
1024 #[cfg(feature = "blocks")]
1025 fn get_exprarray(name: &Ident, mut expr: Expr) -> Result<syn::ExprArray, CompileError> {
1026 loop {
1027 match expr {
1028 Expr::Array(array) => return Ok(array),
1029 Expr::Group(group) => expr = *group.expr,
1030 v => {
1031 return Err(CompileError::no_file_info(
1032 format_args!("template attribute `{name}` expects an array"),
1033 Some(v.span()),
1034 ));
1035 }
1036 }
1037 }
1038 }
1039
1040 fn ensure_source_only_once(
1041 name: &Ident,
1042 source: &Option<PartialTemplateArgsSource>,
1043 ) -> Result<(), CompileError> {
1044 if source.is_some() {
1045 return Err(CompileError::no_file_info(
1046 #[cfg(feature = "code-in-doc")]
1047 "must specify `source`, `path` or `is_doc` exactly once",
1048 #[cfg(not(feature = "code-in-doc"))]
1049 "must specify `source` or `path` exactly once",
1050 Some(name.span()),
1051 ));
1052 }
1053 Ok(())
1054 }
1055 };
1056
1057 #[cfg(feature = "code-in-doc")]
1058 const JINJA_EXTENSIONS: &[&str] = &["askama", "j2", "jinja", "jinja2", "rinja"];
1059
1060 #[test]
1061 fn get_source() {
1062 let path = Config::new("", None, None, None, None)
1063 .and_then(|config| config.find_template("b.html", None, None))
1064 .unwrap();
1065 assert_eq!(get_template_source(&path, None).unwrap(), "bar".into());
1066 }