| 1 |
mod expr; |
| 2 |
mod node; |
| 3 |
|
| 4 |
use std::borrow::Cow; |
| 5 |
use std::collections::hash_map::HashMap; |
| 6 |
use std::ops::Deref; |
| 7 |
use std::path::Path; |
| 8 |
use std::str; |
| 9 |
use std::sync::Arc; |
| 10 |
|
| 11 |
use parser::node::{Macro, Whitespace}; |
| 12 |
use parser::{ |
| 13 |
CharLit, Expr, FloatKind, IntKind, MAX_RUST_KEYWORD_LEN, Num, RUST_KEYWORDS, StrLit, WithSpan, |
| 14 |
}; |
| 15 |
use rustc_hash::FxBuildHasher; |
| 16 |
|
| 17 |
use crate::ascii_str::{AsciiChar, AsciiStr}; |
| 18 |
use crate::heritage::{Context, Heritage}; |
| 19 |
use crate::html::write_escaped_str; |
| 20 |
use crate::input::{Source, TemplateInput}; |
| 21 |
use crate::integration::{Buffer, impl_everything, write_header}; |
| 22 |
use crate::{CompileError, FileInfo}; |
| 23 |
|
| 24 |
pub(crate) fn template_to_string( |
| 25 |
buf: &mut Buffer, |
| 26 |
input: &TemplateInput<'_>, |
| 27 |
contexts: &HashMap<&Arc<Path>, Context<'_>, FxBuildHasher>, |
| 28 |
heritage: Option<&Heritage<'_, '_>>, |
| 29 |
tmpl_kind: TmplKind<'_>, |
| 30 |
) -> Result<usize, CompileError> { |
| 31 |
let generator = Generator::new( |
| 32 |
input, |
| 33 |
contexts, |
| 34 |
heritage, |
| 35 |
MapChain::default(), |
| 36 |
input.block.is_some(), |
| 37 |
0, |
| 38 |
); |
| 39 |
let size_hint = match generator.impl_template(buf, tmpl_kind) { |
| 40 |
Err(mut err) if err.span.is_none() => { |
| 41 |
err.span = input.source_span; |
| 42 |
Err(err) |
| 43 |
} |
| 44 |
result => result, |
| 45 |
}?; |
| 46 |
|
| 47 |
if tmpl_kind == TmplKind::Struct { |
| 48 |
impl_everything(input.ast, buf); |
| 49 |
} |
| 50 |
Ok(size_hint) |
| 51 |
} |
| 52 |
|
| 53 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 54 |
pub(crate) enum TmplKind<'a> { |
| 55 |
/// [`askama::Template`] |
| 56 |
Struct, |
| 57 |
/// [`askama::helpers::EnumVariantTemplate`] |
| 58 |
Variant, |
| 59 |
/// Used in `blocks` implementation |
| 60 |
#[allow(unused)] |
| 61 |
Block(&'a str), |
| 62 |
} |
| 63 |
|
| 64 |
struct Generator<'a, 'h> { |
| 65 |
/// The template input state: original struct AST and attributes |
| 66 |
input: &'a TemplateInput<'a>, |
| 67 |
/// All contexts, keyed by the package-relative template path |
| 68 |
contexts: &'a HashMap<&'a Arc<Path>, Context<'a>, FxBuildHasher>, |
| 69 |
/// The heritage contains references to blocks and their ancestry |
| 70 |
heritage: Option<&'h Heritage<'a, 'h>>, |
| 71 |
/// Variables accessible directly from the current scope (not redirected to context) |
| 72 |
locals: MapChain<'a>, |
| 73 |
/// Suffix whitespace from the previous literal. Will be flushed to the |
| 74 |
/// output buffer unless suppressed by whitespace suppression on the next |
| 75 |
/// non-literal. |
| 76 |
next_ws: Option<&'a str>, |
| 77 |
/// Whitespace suppression from the previous non-literal. Will be used to |
| 78 |
/// determine whether to flush prefix whitespace from the next literal. |
| 79 |
skip_ws: Whitespace, |
| 80 |
/// If currently in a block, this will contain the name of a potential parent block |
| 81 |
super_block: Option<(&'a str, usize)>, |
| 82 |
/// Buffer for writable |
| 83 |
buf_writable: WritableBuffer<'a>, |
| 84 |
/// Used in blocks to check if we are inside a filter block. |
| 85 |
is_in_filter_block: usize, |
| 86 |
/// Set of called macros we are currently in. Used to prevent (indirect) recursions. |
| 87 |
seen_macros: Vec<(&'a Macro<'a>, Option<FileInfo<'a>>)>, |
| 88 |
} |
| 89 |
|
| 90 |
impl<'a, 'h> Generator<'a, 'h> { |
| 91 |
fn new( |
| 92 |
input: &'a TemplateInput<'a>, |
| 93 |
contexts: &'a HashMap<&'a Arc<Path>, Context<'a>, FxBuildHasher>, |
| 94 |
heritage: Option<&'h Heritage<'a, 'h>>, |
| 95 |
locals: MapChain<'a>, |
| 96 |
buf_writable_discard: bool, |
| 97 |
is_in_filter_block: usize, |
| 98 |
) -> Self { |
| 99 |
Self { |
| 100 |
input, |
| 101 |
contexts, |
| 102 |
heritage, |
| 103 |
locals, |
| 104 |
next_ws: None, |
| 105 |
skip_ws: Whitespace::Preserve, |
| 106 |
super_block: None, |
| 107 |
buf_writable: WritableBuffer { |
| 108 |
discard: buf_writable_discard, |
| 109 |
..Default::default() |
| 110 |
}, |
| 111 |
is_in_filter_block, |
| 112 |
seen_macros: Vec::new(), |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
// Implement `Template` for the given context struct. |
| 117 |
fn impl_template( |
| 118 |
mut self, |
| 119 |
buf: &mut Buffer, |
| 120 |
tmpl_kind: TmplKind<'a>, |
| 121 |
) -> Result<usize, CompileError> { |
| 122 |
let ctx = &self.contexts[&self.input.path]; |
| 123 |
|
| 124 |
let target = match tmpl_kind { |
| 125 |
TmplKind::Struct => "askama::Template", |
| 126 |
TmplKind::Variant => "askama::helpers::EnumVariantTemplate", |
| 127 |
TmplKind::Block(trait_name) => trait_name, |
| 128 |
}; |
| 129 |
write_header(self.input.ast, buf, target); |
| 130 |
buf.write( |
| 131 |
"fn render_into_with_values<AskamaW>(\ |
| 132 |
&self,\ |
| 133 |
__askama_writer: &mut AskamaW,\ |
| 134 |
__askama_values: &dyn askama::Values\ |
| 135 |
) -> askama::Result<()>\ |
| 136 |
where \ |
| 137 |
AskamaW: askama::helpers::core::fmt::Write + ?askama::helpers::core::marker::Sized\ |
| 138 |
{\ |
| 139 |
#[allow(unused_imports)]\ |
| 140 |
use askama::{\ |
| 141 |
filters::{AutoEscape as _, WriteWritable as _},\ |
| 142 |
helpers::{ResultConverter as _, core::fmt::Write as _},\ |
| 143 |
};", |
| 144 |
); |
| 145 |
|
| 146 |
if let Some(full_config_path) = &self.input.config.full_config_path { |
| 147 |
buf.write(format_args!( |
| 148 |
"const _: &[askama::helpers::core::primitive::u8] =\ |
| 149 |
askama::helpers::core::include_bytes!({:?});", |
| 150 |
full_config_path.display() |
| 151 |
)); |
| 152 |
} |
| 153 |
|
| 154 |
// Make sure the compiler understands that the generated code depends on the template files. |
| 155 |
let mut paths = self |
| 156 |
.contexts |
| 157 |
.keys() |
| 158 |
.map(|path| -> &Path { path }) |
| 159 |
.collect::<Vec<_>>(); |
| 160 |
paths.sort(); |
| 161 |
for path in paths { |
| 162 |
// Skip the fake path of templates defined in rust source. |
| 163 |
let path_is_valid = match self.input.source { |
| 164 |
Source::Path(_) => true, |
| 165 |
Source::Source(_) => path != &*self.input.path, |
| 166 |
}; |
| 167 |
if path_is_valid { |
| 168 |
buf.write(format_args!( |
| 169 |
"const _: &[askama::helpers::core::primitive::u8] =\ |
| 170 |
askama::helpers::core::include_bytes!({:#?});", |
| 171 |
path.canonicalize().as_deref().unwrap_or(path), |
| 172 |
)); |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
let size_hint = self.impl_template_inner(ctx, buf)?; |
| 177 |
|
| 178 |
buf.write("askama::Result::Ok(()) }"); |
| 179 |
if tmpl_kind == TmplKind::Struct { |
| 180 |
buf.write(format_args!( |
| 181 |
"const SIZE_HINT: askama::helpers::core::primitive::usize = {size_hint}usize;", |
| 182 |
)); |
| 183 |
} |
| 184 |
|
| 185 |
buf.write('}'); |
| 186 |
|
| 187 |
#[cfg(feature = "blocks")] |
| 188 |
for block in self.input.blocks { |
| 189 |
self.impl_block(buf, block)?; |
| 190 |
} |
| 191 |
|
| 192 |
Ok(size_hint) |
| 193 |
} |
| 194 |
|
| 195 |
#[cfg(feature = "blocks")] |
| 196 |
fn impl_block( |
| 197 |
&self, |
| 198 |
buf: &mut Buffer, |
| 199 |
block: &crate::input::Block, |
| 200 |
) -> Result<(), CompileError> { |
| 201 |
// RATIONALE: `*self` must be the input type, implementation details should not leak: |
| 202 |
// - impl Self { fn as_block(self) } -> |
| 203 |
// - struct __Askama__Self__as__block__Wrapper { this: self } -> |
| 204 |
// - impl Template for __Askama__Self__as__block__Wrapper { fn render_into_with_values() } -> |
| 205 |
// - impl __Askama__Self__as__block for Self { render_into_with_values() } |
| 206 |
|
| 207 |
use quote::quote_spanned; |
| 208 |
use syn::{GenericParam, Ident, Lifetime, LifetimeParam, Token}; |
| 209 |
|
| 210 |
let span = block.span; |
| 211 |
buf.write( |
| 212 |
"\ |
| 213 |
#[allow(missing_docs, non_camel_case_types, non_snake_case, unreachable_pub)]\ |
| 214 |
const _: () = {", |
| 215 |
); |
| 216 |
|
| 217 |
let ident = &self.input.ast.ident; |
| 218 |
|
| 219 |
let doc = format!( |
| 220 |
"A sub-template that renders only the block `{}` of [`{ident}`].", |
| 221 |
block.name |
| 222 |
); |
| 223 |
let method_name = format!("as_{}", block.name); |
| 224 |
let trait_name = format!("__Askama__{ident}__as__{}", block.name); |
| 225 |
let wrapper_name = format!("__Askama__{ident}__as__{}__Wrapper", block.name); |
| 226 |
let self_lt_name = format!("'__Askama__{ident}__as__{}__self", block.name); |
| 227 |
|
| 228 |
let method_id = Ident::new(&method_name, span); |
| 229 |
let trait_id = Ident::new(&trait_name, span); |
| 230 |
let wrapper_id = Ident::new(&wrapper_name, span); |
| 231 |
let self_lt = Lifetime::new(&self_lt_name, span); |
| 232 |
|
| 233 |
// generics of the input with an additional lifetime to capture `self` |
| 234 |
let mut wrapper_generics = self.input.ast.generics.clone(); |
| 235 |
if wrapper_generics.lt_token.is_none() { |
| 236 |
wrapper_generics.lt_token = Some(Token); |
| 237 |
wrapper_generics.gt_token = Some(Token); |
| 238 |
} |
| 239 |
wrapper_generics.params.insert( |
| 240 |
0, |
| 241 |
GenericParam::Lifetime(LifetimeParam::new(self_lt.clone())), |
| 242 |
); |
| 243 |
|
| 244 |
let (impl_generics, ty_generics, where_clause) = self.input.ast.generics.split_for_impl(); |
| 245 |
let (wrapper_impl_generics, wrapper_ty_generics, wrapper_where_clause) = |
| 246 |
wrapper_generics.split_for_impl(); |
| 247 |
|
| 248 |
let input = TemplateInput { |
| 249 |
block: Some((&block.name, span)), |
| 250 |
blocks: &[], |
| 251 |
..self.input.clone() |
| 252 |
}; |
| 253 |
let size_hint = template_to_string( |
| 254 |
buf, |
| 255 |
&input, |
| 256 |
self.contexts, |
| 257 |
self.heritage, |
| 258 |
TmplKind::Block(&trait_name), |
| 259 |
)?; |
| 260 |
|
| 261 |
buf.write(quote_spanned! { |
| 262 |
span => |
| 263 |
pub trait #trait_id { |
| 264 |
fn render_into_with_values<AskamaW>( |
| 265 |
&self, |
| 266 |
writer: &mut AskamaW, |
| 267 |
values: &dyn askama::Values, |
| 268 |
) -> askama::Result<()> |
| 269 |
where |
| 270 |
AskamaW: |
| 271 |
askama::helpers::core::fmt::Write + ?askama::helpers::core::marker::Sized; |
| 272 |
} |
| 273 |
|
| 274 |
impl #impl_generics #ident #ty_generics #where_clause { |
| 275 |
#[inline] |
| 276 |
#[doc = #doc] |
| 277 |
pub fn #method_id(&self) -> impl askama::Template + '_ { |
| 278 |
#wrapper_id { |
| 279 |
this: self, |
| 280 |
} |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
#[askama::helpers::core::prelude::rust_2021::derive( |
| 285 |
askama::helpers::core::prelude::rust_2021::Clone, |
| 286 |
askama::helpers::core::prelude::rust_2021::Copy |
| 287 |
)] |
| 288 |
pub struct #wrapper_id #wrapper_generics #wrapper_where_clause { |
| 289 |
this: &#self_lt #ident #ty_generics, |
| 290 |
} |
| 291 |
|
| 292 |
impl #wrapper_impl_generics askama::Template |
| 293 |
for #wrapper_id #wrapper_ty_generics #wrapper_where_clause { |
| 294 |
#[inline] |
| 295 |
fn render_into_with_values<AskamaW>( |
| 296 |
&self, |
| 297 |
writer: &mut AskamaW, |
| 298 |
values: &dyn askama::Values |
| 299 |
) -> askama::Result<()> |
| 300 |
where |
| 301 |
AskamaW: askama::helpers::core::fmt::Write + ?askama::helpers::core::marker::Sized |
| 302 |
{ |
| 303 |
<_ as #trait_id>::render_into_with_values(self.this, writer, values) |
| 304 |
} |
| 305 |
|
| 306 |
const SIZE_HINT: askama::helpers::core::primitive::usize = #size_hint; |
| 307 |
} |
| 308 |
|
| 309 |
// cannot use `crate::integrations::impl_fast_writable()` w/o cloning the struct |
| 310 |
impl #wrapper_impl_generics askama::filters::FastWritable |
| 311 |
for #wrapper_id #wrapper_ty_generics #wrapper_where_clause { |
| 312 |
#[inline] |
| 313 |
fn write_into<AskamaW>(&self, dest: &mut AskamaW) -> askama::Result<()> |
| 314 |
where |
| 315 |
AskamaW: askama::helpers::core::fmt::Write + ?askama::helpers::core::marker::Sized |
| 316 |
{ |
| 317 |
<_ as askama::Template>::render_into(self, dest) |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
// cannot use `crate::integrations::impl_display()` w/o cloning the struct |
| 322 |
impl #wrapper_impl_generics askama::helpers::core::fmt::Display |
| 323 |
for #wrapper_id #wrapper_ty_generics #wrapper_where_clause { |
| 324 |
#[inline] |
| 325 |
fn fmt( |
| 326 |
&self, |
| 327 |
f: &mut askama::helpers::core::fmt::Formatter<'_> |
| 328 |
) -> askama::helpers::core::fmt::Result { |
| 329 |
<_ as askama::Template>::render_into(self, f) |
| 330 |
.map_err(|_| askama::helpers::core::fmt::Error) |
| 331 |
} |
| 332 |
} |
| 333 |
}); |
| 334 |
|
| 335 |
buf.write("};"); |
| 336 |
Ok(()) |
| 337 |
} |
| 338 |
|
| 339 |
fn is_var_defined(&self, var_name: &str) -> bool { |
| 340 |
self.locals.get(var_name).is_some() || self.input.fields.iter().any(|f| f == var_name) |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
#[cfg(target_pointer_width = "16")] |
| 345 |
type TargetIsize = i16; |
| 346 |
#[cfg(target_pointer_width = "32")] |
| 347 |
type TargetIsize = i32; |
| 348 |
#[cfg(target_pointer_width = "64")] |
| 349 |
type TargetIsize = i64; |
| 350 |
|
| 351 |
#[cfg(target_pointer_width = "16")] |
| 352 |
type TargetUsize = u16; |
| 353 |
#[cfg(target_pointer_width = "32")] |
| 354 |
type TargetUsize = u32; |
| 355 |
#[cfg(target_pointer_width = "64")] |
| 356 |
type TargetUsize = u64; |
| 357 |
|
| 358 |
#[cfg(not(any( |
| 359 |
target_pointer_width = "16", |
| 360 |
target_pointer_width = "32", |
| 361 |
target_pointer_width = "64" |
| 362 |
)))] |
| 363 |
const _: () = { |
| 364 |
panic!("unknown cfg!(target_pointer_width)"); |
| 365 |
}; |
| 366 |
|
| 367 |
/// In here, we inspect in the expression if it is a literal, and if it is, whether it |
| 368 |
/// can be escaped at compile time. |
| 369 |
fn compile_time_escape<'a>(expr: &Expr<'a>, escaper: &str) -> Option<Writable<'a>> { |
| 370 |
// we only optimize for known escapers |
| 371 |
enum OutputKind { |
| 372 |
Html, |
| 373 |
Text, |
| 374 |
} |
| 375 |
|
| 376 |
// we only optimize for known escapers |
| 377 |
let output = match escaper.strip_prefix("askama::filters::")? { |
| 378 |
"Html" => OutputKind::Html, |
| 379 |
"Text" => OutputKind::Text, |
| 380 |
_ => return None, |
| 381 |
}; |
| 382 |
|
| 383 |
// for now, we only escape strings, chars, numbers, and bools at compile time |
| 384 |
let value = match *expr { |
| 385 |
Expr::StrLit(StrLit { |
| 386 |
prefix: None, |
| 387 |
content, |
| 388 |
}) => { |
| 389 |
if content.find('\\').is_none() { |
| 390 |
// if the literal does not contain any backslashes, then it does not need unescaping |
| 391 |
Cow::Borrowed(content) |
| 392 |
} else { |
| 393 |
// the input could be string escaped if it contains any backslashes |
| 394 |
let input = format!(r#""{content}""#); |
| 395 |
let input = input.parse().ok()?; |
| 396 |
let input = syn::parse2::<syn::LitStr>(input).ok()?; |
| 397 |
Cow::Owned(input.value()) |
| 398 |
} |
| 399 |
} |
| 400 |
Expr::CharLit(CharLit { |
| 401 |
prefix: None, |
| 402 |
content, |
| 403 |
}) => { |
| 404 |
if content.find('\\').is_none() { |
| 405 |
// if the literal does not contain any backslashes, then it does not need unescaping |
| 406 |
Cow::Borrowed(content) |
| 407 |
} else { |
| 408 |
// the input could be string escaped if it contains any backslashes |
| 409 |
let input = format!(r#"'{content}'"#); |
| 410 |
let input = input.parse().ok()?; |
| 411 |
let input = syn::parse2::<syn::LitChar>(input).ok()?; |
| 412 |
Cow::Owned(input.value().to_string()) |
| 413 |
} |
| 414 |
} |
| 415 |
Expr::NumLit(_, value) => { |
| 416 |
enum NumKind { |
| 417 |
Int(Option<IntKind>), |
| 418 |
Float(Option<FloatKind>), |
| 419 |
} |
| 420 |
|
| 421 |
let (orig_value, kind) = match value { |
| 422 |
Num::Int(value, kind) => (value, NumKind::Int(kind)), |
| 423 |
Num::Float(value, kind) => (value, NumKind::Float(kind)), |
| 424 |
}; |
| 425 |
let value = match orig_value.chars().any(|c| c == '_') { |
| 426 |
true => Cow::Owned(orig_value.chars().filter(|&c| c != '_').collect()), |
| 427 |
false => Cow::Borrowed(orig_value), |
| 428 |
}; |
| 429 |
|
| 430 |
fn int<T: ToString, E>( |
| 431 |
from_str_radix: impl Fn(&str, u32) -> Result<T, E>, |
| 432 |
value: &str, |
| 433 |
) -> Option<String> { |
| 434 |
Some(from_str_radix(value, 10).ok()?.to_string()) |
| 435 |
} |
| 436 |
|
| 437 |
let value = match kind { |
| 438 |
NumKind::Int(Some(IntKind::I8)) => int(i8::from_str_radix, &value)?, |
| 439 |
NumKind::Int(Some(IntKind::I16)) => int(i16::from_str_radix, &value)?, |
| 440 |
NumKind::Int(Some(IntKind::I32)) => int(i32::from_str_radix, &value)?, |
| 441 |
NumKind::Int(Some(IntKind::I64)) => int(i64::from_str_radix, &value)?, |
| 442 |
NumKind::Int(Some(IntKind::I128)) => int(i128::from_str_radix, &value)?, |
| 443 |
NumKind::Int(Some(IntKind::Isize)) => int(TargetIsize::from_str_radix, &value)?, |
| 444 |
NumKind::Int(Some(IntKind::U8)) => int(u8::from_str_radix, &value)?, |
| 445 |
NumKind::Int(Some(IntKind::U16)) => int(u16::from_str_radix, &value)?, |
| 446 |
NumKind::Int(Some(IntKind::U32)) => int(u32::from_str_radix, &value)?, |
| 447 |
NumKind::Int(Some(IntKind::U64)) => int(u64::from_str_radix, &value)?, |
| 448 |
NumKind::Int(Some(IntKind::U128)) => int(u128::from_str_radix, &value)?, |
| 449 |
NumKind::Int(Some(IntKind::Usize)) => int(TargetUsize::from_str_radix, &value)?, |
| 450 |
NumKind::Int(None) => match value.starts_with('-') { |
| 451 |
true => int(i128::from_str_radix, &value)?, |
| 452 |
false => int(u128::from_str_radix, &value)?, |
| 453 |
}, |
| 454 |
NumKind::Float(Some(FloatKind::F32)) => value.parse::<f32>().ok()?.to_string(), |
| 455 |
NumKind::Float(Some(FloatKind::F64) | None) => { |
| 456 |
value.parse::<f64>().ok()?.to_string() |
| 457 |
} |
| 458 |
// FIXME: implement once `f16` and `f128` are available |
| 459 |
NumKind::Float(Some(FloatKind::F16 | FloatKind::F128)) => return None, |
| 460 |
}; |
| 461 |
match value == orig_value { |
| 462 |
true => Cow::Borrowed(orig_value), |
| 463 |
false => Cow::Owned(value), |
| 464 |
} |
| 465 |
} |
| 466 |
Expr::BoolLit(true) => Cow::Borrowed("true"), |
| 467 |
Expr::BoolLit(false) => Cow::Borrowed("false"), |
| 468 |
_ => return None, |
| 469 |
}; |
| 470 |
|
| 471 |
// escape the un-string-escaped input using the selected escaper |
| 472 |
Some(Writable::Lit(match output { |
| 473 |
OutputKind::Text => value, |
| 474 |
OutputKind::Html => { |
| 475 |
let mut escaped = String::with_capacity(value.len() + 20); |
| 476 |
write_escaped_str(&mut escaped, &value).ok()?; |
| 477 |
match escaped == value { |
| 478 |
true => value, |
| 479 |
false => Cow::Owned(escaped), |
| 480 |
} |
| 481 |
} |
| 482 |
})) |
| 483 |
} |
| 484 |
|
| 485 |
#[derive(Clone, Default)] |
| 486 |
struct LocalMeta { |
| 487 |
refs: Option<String>, |
| 488 |
initialized: bool, |
| 489 |
} |
| 490 |
|
| 491 |
impl LocalMeta { |
| 492 |
fn initialized() -> Self { |
| 493 |
Self { |
| 494 |
refs: None, |
| 495 |
initialized: true, |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
fn with_ref(refs: String) -> Self { |
| 500 |
Self { |
| 501 |
refs: Some(refs), |
| 502 |
initialized: true, |
| 503 |
} |
| 504 |
} |
| 505 |
} |
| 506 |
|
| 507 |
struct MapChain<'a> { |
| 508 |
scopes: Vec<HashMap<Cow<'a, str>, LocalMeta, FxBuildHasher>>, |
| 509 |
} |
| 510 |
|
| 511 |
impl<'a> MapChain<'a> { |
| 512 |
fn new_empty() -> Self { |
| 513 |
Self { scopes: vec![] } |
| 514 |
} |
| 515 |
|
| 516 |
/// Iterates the scopes in reverse and returns `Some(LocalMeta)` |
| 517 |
/// from the first scope where `key` exists. |
| 518 |
fn get<'b>(&'b self, key: &str) -> Option<&'b LocalMeta> { |
| 519 |
self.scopes.iter().rev().find_map(|set| set.get(key)) |
| 520 |
} |
| 521 |
|
| 522 |
fn is_current_empty(&self) -> bool { |
| 523 |
self.scopes.last().unwrap().is_empty() |
| 524 |
} |
| 525 |
|
| 526 |
fn insert(&mut self, key: Cow<'a, str>, val: LocalMeta) { |
| 527 |
self.scopes.last_mut().unwrap().insert(key, val); |
| 528 |
|
| 529 |
// Note that if `insert` returns `Some` then it implies |
| 530 |
// an identifier is reused. For e.g. `{% macro f(a, a) %}` |
| 531 |
// and `{% let (a, a) = ... %}` then this results in a |
| 532 |
// generated template, which when compiled fails with the |
| 533 |
// compile error "identifier `a` used more than once". |
| 534 |
} |
| 535 |
|
| 536 |
fn insert_with_default(&mut self, key: Cow<'a, str>) { |
| 537 |
self.insert(key, LocalMeta::default()); |
| 538 |
} |
| 539 |
|
| 540 |
fn resolve(&self, name: &str) -> Option<String> { |
| 541 |
let name = normalize_identifier(name); |
| 542 |
self.get(&Cow::Borrowed(name)).map(|meta| match &meta.refs { |
| 543 |
Some(expr) => expr.clone(), |
| 544 |
None => name.to_string(), |
| 545 |
}) |
| 546 |
} |
| 547 |
|
| 548 |
fn resolve_or_self(&self, name: &str) -> String { |
| 549 |
let name = normalize_identifier(name); |
| 550 |
self.resolve(name).unwrap_or_else(|| format!("self.{name}")) |
| 551 |
} |
| 552 |
} |
| 553 |
|
| 554 |
impl Default for MapChain<'_> { |
| 555 |
fn default() -> Self { |
| 556 |
Self { |
| 557 |
scopes: vec![HashMap::default()], |
| 558 |
} |
| 559 |
} |
| 560 |
} |
| 561 |
|
| 562 |
/// Returns `true` if enough assumptions can be made, |
| 563 |
/// to determine that `self` is copyable. |
| 564 |
fn is_copyable(expr: &Expr<'_>) -> bool { |
| 565 |
is_copyable_within_op(expr, false) |
| 566 |
} |
| 567 |
|
| 568 |
fn is_copyable_within_op(expr: &Expr<'_>, within_op: bool) -> bool { |
| 569 |
match expr { |
| 570 |
Expr::BoolLit(_) |
| 571 |
| Expr::NumLit(_, _) |
| 572 |
| Expr::StrLit(_) |
| 573 |
| Expr::CharLit(_) |
| 574 |
| Expr::BinOp(_, _, _) => true, |
| 575 |
Expr::Unary(.., expr) => is_copyable_within_op(expr, true), |
| 576 |
Expr::Range(..) => true, |
| 577 |
// The result of a call likely doesn't need to be borrowed, |
| 578 |
// as in that case the call is more likely to return a |
| 579 |
// reference in the first place then. |
| 580 |
Expr::Call { .. } | Expr::Path(..) | Expr::Filter(..) | Expr::RustMacro(..) => true, |
| 581 |
// If the `expr` is within a `Unary` or `BinOp` then |
| 582 |
// an assumption can be made that the operand is copy. |
| 583 |
// If not, then the value is moved and adding `.clone()` |
| 584 |
// will solve that issue. However, if the operand is |
| 585 |
// implicitly borrowed, then it's likely not even possible |
| 586 |
// to get the template to compile. |
| 587 |
_ => within_op && is_attr_self(expr), |
| 588 |
} |
| 589 |
} |
| 590 |
|
| 591 |
/// Returns `true` if this is an `Attr` where the `obj` is `"self"`. |
| 592 |
fn is_attr_self(mut expr: &Expr<'_>) -> bool { |
| 593 |
loop { |
| 594 |
match expr { |
| 595 |
Expr::Attr(obj, _) if matches!(***obj, Expr::Var("self")) => return true, |
| 596 |
Expr::Attr(obj, _) if matches!(***obj, Expr::Attr(..)) => expr = obj, |
| 597 |
_ => return false, |
| 598 |
} |
| 599 |
} |
| 600 |
} |
| 601 |
|
| 602 |
const FILTER_SOURCE: &str = "__askama_filter_block"; |
| 603 |
|
| 604 |
#[derive(Clone, Copy, Debug)] |
| 605 |
enum DisplayWrap { |
| 606 |
Wrapped, |
| 607 |
Unwrapped, |
| 608 |
} |
| 609 |
|
| 610 |
#[derive(Default, Debug)] |
| 611 |
struct WritableBuffer<'a> { |
| 612 |
buf: Vec<Writable<'a>>, |
| 613 |
discard: bool, |
| 614 |
} |
| 615 |
|
| 616 |
impl<'a> WritableBuffer<'a> { |
| 617 |
fn push(&mut self, writable: Writable<'a>) { |
| 618 |
if !self.discard { |
| 619 |
self.buf.push(writable); |
| 620 |
} |
| 621 |
} |
| 622 |
} |
| 623 |
|
| 624 |
impl<'a> Deref for WritableBuffer<'a> { |
| 625 |
type Target = [Writable<'a>]; |
| 626 |
|
| 627 |
fn deref(&self) -> &Self::Target { |
| 628 |
&self.buf[..] |
| 629 |
} |
| 630 |
} |
| 631 |
|
| 632 |
#[derive(Debug)] |
| 633 |
enum Writable<'a> { |
| 634 |
Lit(Cow<'a, str>), |
| 635 |
Expr(&'a WithSpan<'a, Expr<'a>>), |
| 636 |
} |
| 637 |
|
| 638 |
/// Identifiers to be replaced with raw identifiers, so as to avoid |
| 639 |
/// collisions between template syntax and Rust's syntax. In particular |
| 640 |
/// [Rust keywords](https://doc.rust-lang.org/reference/keywords.html) |
| 641 |
/// should be replaced, since they're not reserved words in Askama |
| 642 |
/// syntax but have a high probability of causing problems in the |
| 643 |
/// generated code. |
| 644 |
/// |
| 645 |
/// This list excludes the Rust keywords *self*, *Self*, and *super* |
| 646 |
/// because they are not allowed to be raw identifiers, and *loop* |
| 647 |
/// because it's used something like a keyword in the template |
| 648 |
/// language. |
| 649 |
fn normalize_identifier(ident: &str) -> &str { |
| 650 |
// This table works for as long as the replacement string is the original string |
| 651 |
// prepended with "r#". The strings get right-padded to the same length with b'_'. |
| 652 |
// While the code does not need it, please keep the list sorted when adding new |
| 653 |
// keywords. |
| 654 |
|
| 655 |
if ident.len() > MAX_RUST_KEYWORD_LEN { |
| 656 |
return ident; |
| 657 |
} |
| 658 |
let kws = RUST_KEYWORDS[ident.len()]; |
| 659 |
|
| 660 |
let mut padded_ident = [0; MAX_RUST_KEYWORD_LEN]; |
| 661 |
padded_ident[..ident.len()].copy_from_slice(ident.as_bytes()); |
| 662 |
|
| 663 |
// Since the individual buckets are quite short, a linear search is faster than a binary search. |
| 664 |
for probe in kws { |
| 665 |
if padded_ident == *AsciiChar::slice_as_bytes(probe[2..].try_into().unwrap()) { |
| 666 |
return AsciiStr::from_slice(&probe[..ident.len() + 2]); |
| 667 |
} |
| 668 |
} |
| 669 |
ident |
| 670 |
} |