1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![deny(elided_lifetimes_in_paths)]
3#![deny(unreachable_pub)]
4#![cfg_attr(
5 all(feature = "external-sources", feature = "nightly-spans"),
6 feature(proc_macro_def_site, proc_macro_expand)
7)]
8
9extern crate proc_macro;
10
11mod ascii_str;
12mod config;
13mod filter_fn;
14mod generator;
15mod heritage;
16mod html;
17mod input;
18mod integration;
19mod spans;
20#[cfg(test)]
21mod tests;
22
23#[doc(hidden)]
24#[cfg(feature = "proc-macro")]
25pub mod __macro_support {
26 pub use proc_macro::TokenStream as TokenStream1;
27 pub use proc_macro2::TokenStream as TokenStream2;
28 pub use quote::quote;
29}
30
31use std::borrow::{Borrow, Cow};
32use std::collections::hash_map::Entry;
33use std::fmt;
34use std::hash::{BuildHasher, Hash};
35use std::ops::ControlFlow;
36use std::path::Path;
37use std::sync::Mutex;
38
39use parser::{Parsed, is_rust_keyword, strip_common};
40use proc_macro2::{Literal, Span, TokenStream};
41use quote::{ToTokens, quote, quote_spanned};
42use rustc_hash::FxBuildHasher;
43use syn::parse::Parse;
44use syn::spanned::Spanned;
45use syn::{Ident, parse2};
46
47use crate::config::{Config, read_config_file};
48pub use crate::filter_fn::derive_filter_fn;
49use crate::generator::{TmplKind, template_to_string};
50use crate::heritage::{Context, Heritage};
51use crate::input::{AnyTemplateArgs, Print, TemplateArgs, TemplateInput};
52use crate::integration::{Buffer, build_template_enum};
53
54pub const CAN_USE_EXTERNAL_SOURCES: bool = cfg!(feature = "external-sources");
56
57#[macro_export]
58#[cfg(feature = "proc-macro")]
59macro_rules! make_derive_template {
60 (
61 $(#[$meta:meta])*
62 $vis:vis fn $name:ident() {
63 $($import:stmt)+
64 }
65 ) => {
66 $(#[$meta])*
235 $vis fn $name(
236 input: $crate::__macro_support::TokenStream1,
237 ) -> $crate::__macro_support::TokenStream1 {
238 fn import_askama() -> $crate::__macro_support::TokenStream2 {
239 $crate::__macro_support::quote!($($import)*)
240 }
241
242 $crate::derive_template(input.into(), import_askama).into()
243 }
244 };
245}
246
247#[macro_export]
248#[cfg(feature = "proc-macro")]
249macro_rules! make_filter_fn {
250 (
251 $(#[$meta:meta])*
252 $vis:vis fn $name:ident() {
253 $($import:stmt)+
254 }
255 ) => {
256 $(#[$meta])*
257 $vis fn $name(
258 attr: $crate::__macro_support::TokenStream1,
259 item: $crate::__macro_support::TokenStream1,
260 ) -> $crate::__macro_support::TokenStream1 {
261 fn import_askama() -> $crate::__macro_support::TokenStream2 {
262 $crate::__macro_support::quote!($($import)*)
263 }
264
265 $crate::derive_filter_fn(attr.into(), item.into(), import_askama).into()
266 }
267 }
268}
269
270pub fn derive_template(input: TokenStream, import_askama: fn() -> TokenStream) -> TokenStream {
271 let ast = match parse_ts_or_compile_error(input, import_askama) {
272 ControlFlow::Continue(ast) => ast,
273 ControlFlow::Break(err) => return err,
274 };
275
276 let mut buf = Buffer::new();
277 let mut args = AnyTemplateArgs::new(&ast);
278 let crate_name = args
279 .as_mut()
280 .map(|a| a.take_crate_name())
281 .unwrap_or_default();
282
283 let ts = match args.and_then(|args| build_template(&mut buf, &ast, args)) {
284 Ok(_) => buf.into_token_stream(),
285 Err(CompileError { msg, span }) => {
286 let mut ts = quote::quote_spanned! {
287 span.unwrap_or(ast.ident.span()) =>
288 askama::helpers::core::compile_error!(#msg);
289 };
290 buf.clear();
291 if build_skeleton(&mut buf, &ast).is_ok() {
292 let source: TokenStream = buf.into_token_stream();
293 ts.extend(source);
294 }
295 ts
296 }
297 };
298 let import_askama = match crate_name {
299 Some(crate_name) => quote!(use #crate_name as askama;),
300 None => import_askama(),
301 };
302 quote_spanned! {
303 ast.ident.span() =>
304 #[allow(
305 clippy::init_numbered_fields, non_shorthand_field_patterns,
307 clippy::suspicious_else_formatting,
309 dead_code,
311 non_camel_case_types, non_snake_case,
313 clippy::double_parens, clippy::identity_op, clippy::into_iter_on_ref,
316 clippy::needless_borrow, clippy::needless_borrows_for_generic_args,
317 clippy::nonminimal_bool, clippy::op_ref, clippy::useless_conversion, unused_braces,
318 unused_parens,
319 )]
320 const _: () = {
321 #import_askama
322 #ts
323 };
324 }
325}
326
327fn parse_ts_or_compile_error<T: Parse>(
328 input: TokenStream,
329 import_askama: fn() -> TokenStream,
330) -> ControlFlow<TokenStream, T> {
331 match parse2(input) {
332 Ok(ast) => ControlFlow::Continue(ast),
333 Err(err) => {
334 let import_askama = import_askama();
335 let msgs = err.into_iter().map(|err| err.to_string());
336 ControlFlow::Break(quote! {
337 const _: () = {
338 #import_askama
339 #(core::compile_error!(#msgs);)*
340 };
341 })
342 }
343 }
344}
345
346fn build_skeleton(buf: &mut Buffer, ast: &syn::DeriveInput) -> Result<SizeHint, CompileError> {
347 let template_args = TemplateArgs::fallback();
348 let config = Config::new("", None, None, None, None)?;
349 let input = TemplateInput::new(ast, None, config, &template_args)?;
350 let mut contexts = HashMap::default();
351 let parsed = parser::Parsed::default();
352 contexts.insert(&input.path, Context::empty(&parsed, ast.span()));
353 template_to_string(buf, &input, &contexts, None, TmplKind::Struct)
354}
355
356pub(crate) fn build_template(
364 buf: &mut Buffer,
365 ast: &syn::DeriveInput,
366 args: AnyTemplateArgs,
367) -> Result<SizeHint, CompileError> {
368 let err_span;
369 let mut result = match args {
370 AnyTemplateArgs::Struct(item) => {
371 err_span = Some(item.source.1.config_span());
372 build_template_item(buf, ast, None, &item, TmplKind::Struct)
373 }
374 AnyTemplateArgs::Enum {
375 enum_args,
376 vars_args,
377 has_default_impl,
378 } => {
379 err_span = enum_args
380 .as_ref()
381 .and_then(|v| v.source.as_ref())
382 .map(|s| s.span())
383 .or_else(|| enum_args.as_ref().map(|v| v.template_span));
384 build_template_enum(buf, ast, enum_args, vars_args, has_default_impl)
385 }
386 };
387 if let Err(err) = &mut result
388 && err.span.is_none()
389 {
390 err.span = err_span;
391 }
392 result
393}
394
395#[derive(Default)]
396pub(crate) struct CalledBlocks<'a> {
397 pub(crate) called_blocks: HashMap<&'a str, Vec<FileInfo<'a>>>,
398 pub(crate) unprocessed: Vec<(&'a str, FileInfo<'a>)>,
399}
400
401impl CalledBlocks<'_> {
402 fn check_if_already_called(&self, block_name: &str, current: FileInfo<'_>) {
403 if let Some(calls) = self.called_blocks.get(&block_name)
404 && let Some(prev) = calls.iter().skip(1).last()
406 {
407 crate::heritage::duplicated_block_call(current, block_name, prev);
408 }
409 }
410}
411
412fn build_template_item(
413 buf: &mut Buffer,
414 ast: &syn::DeriveInput,
415 enum_ast: Option<&syn::DeriveInput>,
416 template_args: &TemplateArgs,
417 tmpl_kind: TmplKind<'_>,
418) -> Result<SizeHint, CompileError> {
419 let config_path = template_args.config_path();
420 let (s, full_config_path) = read_config_file(config_path, template_args.config_span)?;
421 let config = Config::new(
422 &s,
423 config_path,
424 template_args.whitespace,
425 template_args.config_span,
426 full_config_path,
427 )?;
428 let input = TemplateInput::new(ast, enum_ast, config, template_args)?;
429
430 let mut templates = HashMap::default();
431 input.find_used_templates(&mut templates)?;
432
433 let mut contexts = HashMap::default();
434 let mut called_blocks = CalledBlocks::default();
435
436 for (path, parsed) in &templates {
437 contexts.insert(
438 path,
439 Context::new(
440 input.config,
441 path,
442 parsed,
443 input.source_span.clone(),
444 input.template_span,
445 &mut called_blocks,
446 )?,
447 );
448 }
449
450 let mut unprocessed_items = std::mem::take(&mut called_blocks.unprocessed);
452 while let Some((name, file_info)) = unprocessed_items.pop() {
453 called_blocks
456 .called_blocks
457 .entry(name)
458 .or_default()
459 .push(file_info);
460 }
461
462 let ctx = &contexts[&input.path];
463 let heritage = if !ctx.blocks.is_empty() || ctx.extends.is_some() {
464 Some(Heritage::new(ctx, &contexts))
465 } else {
466 None
467 };
468
469 if let Some((block_name, block_span)) = input.block {
470 let has_block = match &heritage {
471 Some(heritage) => heritage.blocks.contains_key(&block_name),
472 None => ctx.blocks.contains_key(&block_name),
473 };
474 if !has_block {
475 return Err(CompileError::no_file_info(
476 format_args!("cannot find block `{block_name}`"),
477 Some(block_span),
478 ));
479 }
480 }
481
482 if input.print == Print::Ast || input.print == Print::All {
483 eprintln!("== Askama AST ==\n{:?}", templates[&input.path].nodes());
484 }
485
486 let size_hint = template_to_string(buf, &input, &contexts, heritage.as_ref(), tmpl_kind)?;
487
488 if input.print == Print::Code || input.print == Print::All {
489 eprintln!("== Askama code ==\n{}", buf.to_token_stream());
490 }
491
492 Ok(size_hint)
493}
494
495#[derive(Debug, Clone)]
496struct CompileError {
497 msg: String,
498 span: Option<Span>,
499}
500
501impl CompileError {
502 fn new<S: fmt::Display>(msg: S, file_info: Option<FileInfo<'_>>) -> Self {
503 Self::new_with_span_stable(msg, file_info, None)
504 }
505
506 fn new_with_span<S: fmt::Display>(
507 msg: S,
508 file_info: Option<FileInfo<'_>>,
509 span: Option<Span>,
510 ) -> Self {
511 let span = if let Some(span) = span
514 && span.join(proc_macro2::Span::call_site()).is_none()
515 {
516 None
517 } else {
518 span
519 };
520 Self::new_with_span_stable(msg, file_info, span)
521 }
522
523 fn new_with_span_stable<S: fmt::Display>(
524 msg: S,
525 file_info: Option<FileInfo<'_>>,
526 span: Option<Span>,
527 ) -> Self {
528 let msg = match (span, file_info) {
529 (None, Some(file_info)) => format!("{msg}{file_info}"),
530 _ => msg.to_string(),
531 };
532 Self { msg, span }
533 }
534
535 fn no_file_info<S: ToString>(msg: S, span: Option<Span>) -> Self {
536 Self {
537 msg: msg.to_string(),
538 span,
539 }
540 }
541}
542
543impl std::error::Error for CompileError {}
544
545impl fmt::Display for CompileError {
546 #[inline]
547 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
548 fmt.write_str(&self.msg)
549 }
550}
551
552#[derive(Debug, Clone, Copy)]
553struct FileInfo<'a> {
554 path: &'a Path,
555 source: Option<&'a str>,
556 node_source: Option<&'a str>,
557}
558
559impl<'a> FileInfo<'a> {
560 fn new(path: &'a Path, source: Option<&'a str>, node_source: Option<&'a str>) -> Self {
561 Self {
562 path,
563 source,
564 node_source,
565 }
566 }
567
568 fn of(node: parser::Span, path: &'a Path, parsed: &'a Parsed) -> Self {
569 let source = parsed.source();
570 Self {
571 path,
572 source: Some(source),
573 node_source: node
574 .byte_range()
575 .and_then(|range| source.get(range.start..)),
576 }
577 }
578}
579
580impl fmt::Display for FileInfo<'_> {
581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
582 if !f.alternate() {
583 f.write_str("\n --> ")?;
584 }
585 if let (Some(source), Some(node_source)) = (self.source, self.node_source) {
586 let (error_info, file_path) = generate_error_info(source, node_source, self.path);
587 write!(
588 f,
589 "{file_path}:{row}:{column}",
590 row = error_info.row,
591 column = error_info.column,
592 )?;
593 if !f.alternate() {
594 write!(
595 f,
596 "\n{source_after}",
597 source_after = error_info.source_after,
598 )?;
599 }
600 Ok(())
601 } else {
602 write!(
603 f,
604 "{}",
605 match std::env::current_dir() {
606 Ok(cwd) => fmt_left!(move "{}", strip_common(&cwd, self.path)),
607 Err(_) => fmt_right!("{}", self.path.display()),
608 }
609 )
610 }
611 }
612}
613
614struct ErrorInfo {
615 row: usize,
616 column: usize,
617 source_after: String,
618}
619
620fn generate_row_and_column(src: &str, input: &str) -> ErrorInfo {
621 const MAX_LINE_LEN: usize = 80;
622
623 let offset = src.len() - input.len();
624 let (source_before, source_after) = src.split_at(offset);
625
626 let source_after = match source_after
627 .char_indices()
628 .enumerate()
629 .take(MAX_LINE_LEN + 1)
630 .last()
631 {
632 Some((MAX_LINE_LEN, (i, _))) => format!("{:?}...", &source_after[..i]),
633 _ => format!("{source_after:?}"),
634 };
635
636 let (row, last_line) = source_before.lines().enumerate().last().unwrap_or_default();
637 let column = last_line.chars().count();
638 ErrorInfo {
639 row: row + 1,
640 column,
641 source_after,
642 }
643}
644
645fn generate_error_info(src: &str, input: &str, file_path: &Path) -> (ErrorInfo, String) {
647 let file_path = match std::env::current_dir() {
648 Ok(cwd) => strip_common(&cwd, file_path),
649 Err(_) => file_path.display().to_string(),
650 };
651 let error_info = generate_row_and_column(src, input);
652 (error_info, file_path)
653}
654
655struct MsgValidEscapers<'a>(&'a [(Vec<Cow<'a, str>>, Cow<'a, str>)]);
656
657impl fmt::Display for MsgValidEscapers<'_> {
658 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659 let mut exts = self
660 .0
661 .iter()
662 .flat_map(|(exts, _)| exts)
663 .map(|x| format!("{x:?}"))
664 .collect::<Vec<_>>();
665 exts.sort();
666 write!(f, "The available extensions are: {}", exts.join(", "))
667 }
668}
669
670#[must_use = "Don't ignore the size_hint!"]
671#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
672struct SizeHint(usize);
673
674impl SizeHint {
675 const EMPTY: Self = Self(0);
676
677 #[inline]
678 fn midpoint(self, rhs: Self) -> Self {
679 Self(self.0.midpoint(rhs.0))
680 }
681}
682
683impl std::ops::Add for SizeHint {
684 type Output = Self;
685
686 #[inline]
687 fn add(self, rhs: Self) -> Self::Output {
688 Self(self.0 + rhs.0)
689 }
690}
691
692impl<R> std::ops::AddAssign<R> for SizeHint
693where
694 Self: std::ops::Add<R, Output = Self>,
695{
696 #[inline]
697 fn add_assign(&mut self, rhs: R) {
698 *self = *self + rhs;
699 }
700}
701
702impl std::ops::Add<usize> for SizeHint {
703 type Output = Self;
704
705 #[inline]
706 fn add(self, rhs: usize) -> Self::Output {
707 Self(self.0 + rhs)
708 }
709}
710
711impl std::ops::Mul<usize> for SizeHint {
712 type Output = Self;
713
714 #[inline]
715 fn mul(self, rhs: usize) -> Self::Output {
716 Self(self.0 * rhs)
717 }
718}
719
720impl std::ops::Div<usize> for SizeHint {
721 type Output = Self;
722
723 #[inline]
724 fn div(self, rhs: usize) -> Self::Output {
725 Self(self.0 / rhs)
726 }
727}
728
729impl ToTokens for SizeHint {
730 #[inline]
731 fn to_tokens(&self, tokens: &mut TokenStream) {
732 self.0.to_tokens(tokens);
733 }
734
735 #[inline]
736 fn to_token_stream(&self) -> TokenStream {
737 self.0.to_token_stream()
738 }
739}
740
741fn field_new(name: &str, span: proc_macro2::Span) -> TokenStream {
742 if name.starts_with(|c: char| c.is_ascii_digit()) {
743 let mut literal: Literal = name.parse().unwrap();
744 literal.set_span(span);
745 literal.into_token_stream()
746 } else if is_rust_keyword(name) && !matches!(name, "self" | "Self" | "crate" | "super") {
747 Ident::new_raw(name, span).into_token_stream()
748 } else {
749 Ident::new(name, span).into_token_stream()
750 }
751}
752
753fn var_writer() -> Ident {
754 syn::Ident::new("__askama_writer", proc_macro2::Span::call_site())
755}
756
757fn var_filter_source() -> Ident {
758 syn::Ident::new("__askama_filter_block", proc_macro2::Span::call_site())
759}
760
761fn var_let_source() -> Ident {
762 syn::Ident::new("__askama_let_block", proc_macro2::Span::call_site())
763}
764
765fn var_let_caller() -> Ident {
766 syn::Ident::new("__askama_let_caller", proc_macro2::Span::call_site())
767}
768
769fn var_values() -> Ident {
770 syn::Ident::new("__askama_values", proc_macro2::Span::call_site())
771}
772
773fn var_arg() -> Ident {
774 syn::Ident::new("__askama_arg", proc_macro2::Span::call_site())
775}
776
777fn var_item() -> Ident {
778 syn::Ident::new("__askama_item", proc_macro2::Span::call_site())
779}
780
781fn var_len() -> Ident {
782 syn::Ident::new("__askama_len", proc_macro2::Span::call_site())
783}
784
785fn var_iter() -> Ident {
786 syn::Ident::new("__askama_iter", proc_macro2::Span::call_site())
787}
788
789fn var_cycle() -> Ident {
790 syn::Ident::new("__askama_cycle", proc_macro2::Span::call_site())
791}
792
793fn var_did_loop() -> Ident {
794 syn::Ident::new("__askama_did_loop", proc_macro2::Span::call_site())
795}
796
797fn var_expr_n(n: usize, span: proc_macro2::Span) -> Ident {
798 syn::Ident::new(&format!("__askama_expr{n}"), span)
799}
800
801#[derive(Debug)]
802struct OnceMap<K, V>([Mutex<HashMap<K, V>>; 8]);
803
804impl<K, V> Default for OnceMap<K, V> {
805 fn default() -> Self {
806 Self(Default::default())
807 }
808}
809
810impl<K: Hash + Eq, V> OnceMap<K, V> {
811 fn get_or_try_insert<T, Q, E>(
814 &self,
815 key: &Q,
816 make_key_value: impl FnOnce(&Q) -> Result<(K, V), E>,
817 to_value: impl FnOnce(&V) -> T,
818 ) -> Result<T, E>
819 where
820 K: Borrow<Q>,
821 Q: Hash + Eq,
822 {
823 let shard_idx = (FxBuildHasher.hash_one(key) % self.0.len() as u64) as usize;
824 let mut shard = self.0[shard_idx].lock().unwrap();
825 Ok(to_value(if let Some(v) = shard.get(key) {
826 v
827 } else {
828 let (k, v) = make_key_value(key)?;
829 match shard.entry(k) {
830 Entry::Vacant(entry) => entry.insert(v),
831 Entry::Occupied(_) => unreachable!("key in map when it should not have been"),
832 }
833 }))
834 }
835}
836
837enum EitherFormat<L, R>
838where
839 L: for<'a, 'b> Fn(&'a mut fmt::Formatter<'b>) -> fmt::Result,
840 R: for<'a, 'b> Fn(&'a mut fmt::Formatter<'b>) -> fmt::Result,
841{
842 Left(L),
843 Right(R),
844}
845
846impl<L, R> fmt::Display for EitherFormat<L, R>
847where
848 L: for<'a, 'b> Fn(&'a mut fmt::Formatter<'b>) -> fmt::Result,
849 R: for<'a, 'b> Fn(&'a mut fmt::Formatter<'b>) -> fmt::Result,
850{
851 #[inline]
852 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
853 match self {
854 Self::Left(v) => v(f),
855 Self::Right(v) => v(f),
856 }
857 }
858}
859
860macro_rules! fmt_left {
861 (move $fmt:literal $($tt:tt)*) => {
862 $crate::EitherFormat::Left(move |f: &mut std::fmt::Formatter<'_>| {
863 write!(f, $fmt $($tt)*)
864 })
865 };
866 ($fmt:literal $($tt:tt)*) => {
867 $crate::EitherFormat::Left(|f: &mut std::fmt::Formatter<'_>| {
868 write!(f, $fmt $($tt)*)
869 })
870 };
871}
872
873macro_rules! fmt_right {
874 (move $fmt:literal $($tt:tt)*) => {
875 $crate::EitherFormat::Right(move |f: &mut std::fmt::Formatter<'_>| {
876 write!(f, $fmt $($tt)*)
877 })
878 };
879 ($fmt:literal $($tt:tt)*) => {
880 $crate::EitherFormat::Right(|f: &mut std::fmt::Formatter<'_>| {
881 write!(f, $fmt $($tt)*)
882 })
883 };
884}
885
886macro_rules! quote_into {
887 ($buffer:expr, $span:expr, { $($x:tt)+ } $(,)?) => {{
888 let buffer: &mut $crate::integration::Buffer = $buffer;
889 if !buffer.is_discard() {
890 let span: ::proc_macro2::Span = $span;
891 buffer.write_tokens(::quote::quote_spanned!(span => $($x)+));
892 }
893 }};
894}
895
896pub(crate) use fmt_left;
897pub(crate) use fmt_right;
898pub(crate) use quote_into;
899
900type HashMap<K, V> = std::collections::hash_map::HashMap<K, V, FxBuildHasher>;
901type HashSet<T> = std::collections::hash_set::HashSet<T, FxBuildHasher>;