Debian Codegraph @

third_party/rust/askama_derive/src/generator/node.rs

raw
1 use std::borrow::Cow;
2 use std::collections::hash_map::{Entry, HashMap};
3 use std::fmt::{self, Write};
4 use std::mem;
5
6 use parser::node::{
7 Call, Comment, Cond, CondTest, FilterBlock, If, Include, Let, Lit, Loop, Macro, Match,
8 Whitespace, Ws,
9 };
10 use parser::{Expr, Filter, Node, Span, Target, WithSpan};
11 use rustc_hash::FxBuildHasher;
12
13 use super::{
14 DisplayWrap, FILTER_SOURCE, Generator, LocalMeta, MapChain, compile_time_escape, is_copyable,
15 normalize_identifier,
16 };
17 use crate::generator::Writable;
18 use crate::heritage::{Context, Heritage};
19 use crate::integration::Buffer;
20 use crate::{CompileError, FileInfo, fmt_left, fmt_right};
21
22 impl<'a> Generator<'a, '_> {
23 pub(super) fn impl_template_inner(
24 &mut self,
25 ctx: &Context<'a>,
26 buf: &mut Buffer,
27 ) -> Result<usize, CompileError> {
28 buf.set_discard(self.buf_writable.discard);
29 let size_hint = if let Some(heritage) = self.heritage {
30 self.handle(heritage.root, heritage.root.nodes, buf, AstLevel::Top)
31 } else {
32 self.handle(ctx, ctx.nodes, buf, AstLevel::Top)
33 }?;
34 self.flush_ws(Ws(None, None));
35 buf.set_discard(false);
36 Ok(size_hint)
37 }
38
39 fn push_locals<T, F>(&mut self, callback: F) -> Result<T, CompileError>
40 where
41 F: FnOnce(&mut Self) -> Result<T, CompileError>,
42 {
43 self.locals.scopes.push(HashMap::default());
44 let res = callback(self);
45 self.locals.scopes.pop().unwrap();
46 res
47 }
48
49 fn with_child<'b, T, F>(
50 &mut self,
51 heritage: Option<&'b Heritage<'a, 'b>>,
52 callback: F,
53 ) -> Result<T, CompileError>
54 where
55 F: FnOnce(&mut Generator<'a, 'b>) -> Result<T, CompileError>,
56 {
57 self.locals.scopes.push(HashMap::default());
58
59 let buf_writable = mem::take(&mut self.buf_writable);
60 let locals = mem::replace(&mut self.locals, MapChain::new_empty());
61
62 let mut child = Generator::new(
63 self.input,
64 self.contexts,
65 heritage,
66 locals,
67 self.buf_writable.discard,
68 self.is_in_filter_block,
69 );
70 child.buf_writable = buf_writable;
71 let res = callback(&mut child);
72 Generator {
73 locals: self.locals,
74 buf_writable: self.buf_writable,
75 ..
76 } = child;
77
78 self.locals.scopes.pop().unwrap();
79 res
80 }
81
82 fn handle(
83 &mut self,
84 ctx: &Context<'a>,
85 nodes: &'a [Node<'_>],
86 buf: &mut Buffer,
87 level: AstLevel,
88 ) -> Result<usize, CompileError> {
89 let mut size_hint = 0;
90 for n in nodes {
91 match *n {
92 Node::Lit(ref lit) => {
93 self.write_lit(lit);
94 }
95 Node::Comment(ref comment) => {
96 self.write_comment(comment);
97 }
98 Node::Expr(ws, ref val) => {
99 self.write_expr(ws, val);
100 }
101 Node::Let(ref l) => {
102 self.write_let(ctx, buf, l)?;
103 }
104 Node::If(ref i) => {
105 size_hint += self.write_if(ctx, buf, i)?;
106 }
107 Node::Match(ref m) => {
108 size_hint += self.write_match(ctx, buf, m)?;
109 }
110 Node::Loop(ref loop_block) => {
111 size_hint += self.write_loop(ctx, buf, loop_block)?;
112 }
113 Node::BlockDef(ref b) => {
114 size_hint +=
115 self.write_block(ctx, buf, Some(b.name), Ws(b.ws1.0, b.ws2.1), b.span())?;
116 }
117 Node::Include(ref i) => {
118 size_hint += self.handle_include(ctx, buf, i)?;
119 }
120 Node::Call(ref call) => {
121 size_hint += self.write_call(ctx, buf, call)?;
122 }
123 Node::FilterBlock(ref filter) => {
124 size_hint += self.write_filter_block(ctx, buf, filter)?;
125 }
126 Node::Macro(ref m) => {
127 if level != AstLevel::Top {
128 return Err(ctx.generate_error(
129 "macro blocks only allowed at the top level",
130 m.span(),
131 ));
132 }
133 self.flush_ws(m.ws1);
134 self.prepare_ws(m.ws2);
135 }
136 Node::Raw(ref raw) => {
137 self.handle_ws(raw.ws1);
138 self.write_lit(&raw.lit);
139 self.handle_ws(raw.ws2);
140 }
141 Node::Import(ref i) => {
142 if level != AstLevel::Top {
143 return Err(ctx.generate_error(
144 "import blocks only allowed at the top level",
145 i.span(),
146 ));
147 }
148 self.handle_ws(i.ws);
149 }
150 Node::Extends(ref e) => {
151 if level != AstLevel::Top {
152 return Err(ctx.generate_error(
153 "extend blocks only allowed at the top level",
154 e.span(),
155 ));
156 }
157 // No whitespace handling: child template top-level is not used,
158 // except for the blocks defined in it.
159 }
160 Node::Break(ref ws) => {
161 self.handle_ws(**ws);
162 self.write_buf_writable(ctx, buf)?;
163 buf.write("break;");
164 }
165 Node::Continue(ref ws) => {
166 self.handle_ws(**ws);
167 self.write_buf_writable(ctx, buf)?;
168 buf.write("continue;");
169 }
170 }
171 }
172
173 if AstLevel::Top == level {
174 // Handle any pending whitespace.
175 if self.next_ws.is_some() {
176 self.flush_ws(Ws(Some(self.skip_ws), None));
177 }
178
179 size_hint += self.write_buf_writable(ctx, buf)?;
180 }
181 Ok(size_hint)
182 }
183
184 fn evaluate_condition(
185 &self,
186 expr: WithSpan<'a, Expr<'a>>,
187 only_contains_is_defined: &mut bool,
188 ) -> (EvaluatedResult, WithSpan<'a, Expr<'a>>) {
189 let (expr, span) = expr.deconstruct();
190
191 match expr {
192 Expr::NumLit(_, _)
193 | Expr::StrLit(_)
194 | Expr::CharLit(_)
195 | Expr::Var(_)
196 | Expr::Path(_)
197 | Expr::Array(_)
198 | Expr::Attr(_, _)
199 | Expr::Index(_, _)
200 | Expr::Filter(_)
201 | Expr::Range(_, _, _)
202 | Expr::Call { .. }
203 | Expr::RustMacro(_, _)
204 | Expr::Try(_)
205 | Expr::Tuple(_)
206 | Expr::NamedArgument(_, _)
207 | Expr::FilterSource
208 | Expr::As(_, _)
209 | Expr::Concat(_)
210 | Expr::LetCond(_) => {
211 *only_contains_is_defined = false;
212 (EvaluatedResult::Unknown, WithSpan::new(expr, span))
213 }
214 Expr::BoolLit(true) => (EvaluatedResult::AlwaysTrue, WithSpan::new(expr, span)),
215 Expr::BoolLit(false) => (EvaluatedResult::AlwaysFalse, WithSpan::new(expr, span)),
216 Expr::Unary("!", inner) => {
217 let (result, expr) = self.evaluate_condition(*inner, only_contains_is_defined);
218 match result {
219 EvaluatedResult::AlwaysTrue => (
220 EvaluatedResult::AlwaysFalse,
221 WithSpan::new(Expr::BoolLit(false), ""),
222 ),
223 EvaluatedResult::AlwaysFalse => (
224 EvaluatedResult::AlwaysTrue,
225 WithSpan::new(Expr::BoolLit(true), ""),
226 ),
227 EvaluatedResult::Unknown => (
228 EvaluatedResult::Unknown,
229 WithSpan::new(Expr::Unary("!", Box::new(expr)), span),
230 ),
231 }
232 }
233 Expr::Unary(_, _) => (EvaluatedResult::Unknown, WithSpan::new(expr, span)),
234 Expr::BinOp("&&", left, right) => {
235 let (result_left, expr_left) =
236 self.evaluate_condition(*left, only_contains_is_defined);
237 if result_left == EvaluatedResult::AlwaysFalse {
238 // The right side of the `&&` won't be evaluated, no need to go any further.
239 return (result_left, WithSpan::new(Expr::BoolLit(false), ""));
240 }
241 let (result_right, expr_right) =
242 self.evaluate_condition(*right, only_contains_is_defined);
243 match (result_left, result_right) {
244 (EvaluatedResult::AlwaysTrue, EvaluatedResult::AlwaysTrue) => (
245 EvaluatedResult::AlwaysTrue,
246 WithSpan::new(Expr::BoolLit(true), ""),
247 ),
248 (_, EvaluatedResult::AlwaysFalse) => (
249 EvaluatedResult::AlwaysFalse,
250 WithSpan::new(
251 Expr::BinOp("&&", Box::new(expr_left), Box::new(expr_right)),
252 span,
253 ),
254 ),
255 (EvaluatedResult::AlwaysTrue, _) => (result_right, expr_right),
256 (_, EvaluatedResult::AlwaysTrue) => (result_left, expr_left),
257 _ => (
258 EvaluatedResult::Unknown,
259 WithSpan::new(
260 Expr::BinOp("&&", Box::new(expr_left), Box::new(expr_right)),
261 span,
262 ),
263 ),
264 }
265 }
266 Expr::BinOp("||", left, right) => {
267 let (result_left, expr_left) =
268 self.evaluate_condition(*left, only_contains_is_defined);
269 if result_left == EvaluatedResult::AlwaysTrue {
270 // The right side of the `||` won't be evaluated, no need to go any further.
271 return (result_left, WithSpan::new(Expr::BoolLit(true), ""));
272 }
273 let (result_right, expr_right) =
274 self.evaluate_condition(*right, only_contains_is_defined);
275 match (result_left, result_right) {
276 (EvaluatedResult::AlwaysFalse, EvaluatedResult::AlwaysFalse) => (
277 EvaluatedResult::AlwaysFalse,
278 WithSpan::new(Expr::BoolLit(false), ""),
279 ),
280 (_, EvaluatedResult::AlwaysTrue) => (
281 EvaluatedResult::AlwaysTrue,
282 WithSpan::new(
283 Expr::BinOp("||", Box::new(expr_left), Box::new(expr_right)),
284 span,
285 ),
286 ),
287 (EvaluatedResult::AlwaysFalse, _) => (result_right, expr_right),
288 (_, EvaluatedResult::AlwaysFalse) => (result_left, expr_left),
289 _ => (
290 EvaluatedResult::Unknown,
291 WithSpan::new(
292 Expr::BinOp("||", Box::new(expr_left), Box::new(expr_right)),
293 span,
294 ),
295 ),
296 }
297 }
298 Expr::BinOp(_, _, _) => {
299 *only_contains_is_defined = false;
300 (EvaluatedResult::Unknown, WithSpan::new(expr, span))
301 }
302 Expr::Group(inner) => {
303 let (result, expr) = self.evaluate_condition(*inner, only_contains_is_defined);
304 (result, WithSpan::new(Expr::Group(Box::new(expr)), span))
305 }
306 Expr::IsDefined(left) => {
307 // Variable is defined so we want to keep the condition.
308 if self.is_var_defined(left) {
309 (
310 EvaluatedResult::AlwaysTrue,
311 WithSpan::new(Expr::BoolLit(true), ""),
312 )
313 } else {
314 (
315 EvaluatedResult::AlwaysFalse,
316 WithSpan::new(Expr::BoolLit(false), ""),
317 )
318 }
319 }
320 Expr::IsNotDefined(left) => {
321 // Variable is defined so we don't want to keep the condition.
322 if self.is_var_defined(left) {
323 (
324 EvaluatedResult::AlwaysFalse,
325 WithSpan::new(Expr::BoolLit(false), ""),
326 )
327 } else {
328 (
329 EvaluatedResult::AlwaysTrue,
330 WithSpan::new(Expr::BoolLit(true), ""),
331 )
332 }
333 }
334 }
335 }
336
337 fn write_if(
338 &mut self,
339 ctx: &Context<'a>,
340 buf: &mut Buffer,
341 if_: &'a If<'_>,
342 ) -> Result<usize, CompileError> {
343 let mut flushed = 0;
344 let mut arm_sizes = Vec::new();
345 let mut has_else = false;
346
347 let conds = Conds::compute_branches(self, if_);
348
349 if let Some(ws_before) = conds.ws_before {
350 self.handle_ws(ws_before);
351 }
352
353 let mut iter = conds.conds.iter().enumerate().peekable();
354 while let Some((pos, cond_info)) = iter.next() {
355 let cond = cond_info.cond;
356
357 if pos == 0 {
358 self.handle_ws(cond.ws);
359 flushed += self.write_buf_writable(ctx, buf)?;
360 }
361
362 self.push_locals(|this| {
363 let mut arm_size = 0;
364
365 if let Some(CondTest { target, expr, .. }) = &cond.cond {
366 let expr = cond_info.cond_expr.as_ref().unwrap_or(expr);
367
368 if pos == 0 {
369 if cond_info.generate_condition {
370 buf.write("if ");
371 }
372 // Otherwise it means it will be the only condition generated,
373 // so nothing to be added here.
374 } else if cond_info.generate_condition {
375 buf.write("} else if ");
376 } else {
377 buf.write("} else {");
378 has_else = true;
379 }
380
381 if let Some(target) = target {
382 let mut expr_buf = Buffer::new();
383 buf.write("let ");
384 // If this is a chain condition, then we need to declare the variable after the
385 // left expression has been handled but before the right expression is handled
386 // but this one should have access to the let-bound variable.
387 match &**expr {
388 Expr::BinOp(op @ ("||" | "&&"), ref left, ref right) => {
389 let display_wrap =
390 this.visit_expr_first(ctx, &mut expr_buf, left)?;
391 this.visit_target(buf, true, true, target);
392 this.visit_expr_not_first(ctx, &mut expr_buf, left, display_wrap)?;
393 buf.write(format_args!("= &{expr_buf}"));
394 buf.write(format_args!(" {op} "));
395 this.visit_condition(ctx, buf, right)?;
396 }
397 _ => {
398 let display_wrap =
399 this.visit_expr_first(ctx, &mut expr_buf, expr)?;
400 this.visit_target(buf, true, true, target);
401 this.visit_expr_not_first(ctx, &mut expr_buf, expr, display_wrap)?;
402 buf.write(format_args!("= &{expr_buf}"));
403 }
404 }
405 buf.write("{");
406 } else if cond_info.generate_condition {
407 this.visit_condition(ctx, buf, expr)?;
408 buf.write('{');
409 }
410 } else if pos != 0 {
411 buf.write("} else {");
412 has_else = true;
413 }
414
415 if cond_info.generate_content {
416 arm_size += this.handle(ctx, &cond.nodes, buf, AstLevel::Nested)?;
417 }
418 arm_sizes.push(arm_size);
419
420 if let Some((_, cond_info)) = iter.peek() {
421 let cond = cond_info.cond;
422
423 this.handle_ws(cond.ws);
424 flushed += this.write_buf_writable(ctx, buf)?;
425 } else {
426 if let Some(ws_after) = conds.ws_after {
427 this.handle_ws(ws_after);
428 }
429 this.handle_ws(if_.ws);
430 flushed += this.write_buf_writable(ctx, buf)?;
431 }
432 Ok(0)
433 })?;
434 }
435
436 if conds.nb_conds > 0 {
437 buf.write('}');
438 }
439
440 if !has_else && !conds.conds.is_empty() {
441 arm_sizes.push(0);
442 }
443 Ok(flushed + median(&mut arm_sizes))
444 }
445
446 #[allow(clippy::too_many_arguments)]
447 fn write_match(
448 &mut self,
449 ctx: &Context<'a>,
450 buf: &mut Buffer,
451 m: &'a Match<'a>,
452 ) -> Result<usize, CompileError> {
453 let Match {
454 ws1,
455 ref expr,
456 ref arms,
457 ws2,
458 } = *m;
459
460 self.flush_ws(ws1);
461 let flushed = self.write_buf_writable(ctx, buf)?;
462 let mut arm_sizes = Vec::new();
463
464 let expr_code = self.visit_expr_root(ctx, expr)?;
465 buf.write(format_args!("match &{expr_code} {{"));
466
467 let mut arm_size = 0;
468 let mut iter = arms.iter().enumerate().peekable();
469 while let Some((i, arm)) = iter.next() {
470 if i == 0 {
471 self.handle_ws(arm.ws);
472 }
473
474 self.push_locals(|this| {
475 for (index, target) in arm.target.iter().enumerate() {
476 if index != 0 {
477 buf.write('|');
478 }
479 this.visit_target(buf, true, true, target);
480 }
481 buf.write(" => {");
482
483 arm_size = this.handle(ctx, &arm.nodes, buf, AstLevel::Nested)?;
484
485 if let Some((_, arm)) = iter.peek() {
486 this.handle_ws(arm.ws);
487 arm_sizes.push(arm_size + this.write_buf_writable(ctx, buf)?);
488
489 buf.write('}');
490 } else {
491 this.handle_ws(ws2);
492 arm_sizes.push(arm_size + this.write_buf_writable(ctx, buf)?);
493 buf.write('}');
494 }
495 Ok(0)
496 })?;
497 }
498
499 buf.write('}');
500
501 Ok(flushed + median(&mut arm_sizes))
502 }
503
504 #[allow(clippy::too_many_arguments)]
505 fn write_loop(
506 &mut self,
507 ctx: &Context<'a>,
508 buf: &mut Buffer,
509 loop_block: &'a WithSpan<'_, Loop<'_>>,
510 ) -> Result<usize, CompileError> {
511 self.handle_ws(loop_block.ws1);
512 self.push_locals(|this| {
513 let expr_code = this.visit_expr_root(ctx, &loop_block.iter)?;
514
515 let has_else_nodes = !loop_block.else_nodes.is_empty();
516
517 let flushed = this.write_buf_writable(ctx, buf)?;
518 buf.write('{');
519 if has_else_nodes {
520 buf.write("let mut _did_loop = false;");
521 }
522 match &*loop_block.iter {
523 Expr::Range(_, _, _) => buf.write(format_args!("let _iter = {expr_code};")),
524 Expr::Array(..) => buf.write(format_args!("let _iter = {expr_code}.iter();")),
525 // If `iter` is a call then we assume it's something that returns
526 // an iterator. If not then the user can explicitly add the needed
527 // call without issues.
528 Expr::Call { .. } | Expr::Index(..) => {
529 buf.write(format_args!("let _iter = ({expr_code}).into_iter();"));
530 }
531 // If accessing `self` then it most likely needs to be
532 // borrowed, to prevent an attempt of moving.
533 _ if expr_code.starts_with("self.") => {
534 buf.write(format_args!("let _iter = (&{expr_code}).into_iter();"));
535 }
536 // If accessing a field then it most likely needs to be
537 // borrowed, to prevent an attempt of moving.
538 Expr::Attr(..) => {
539 buf.write(format_args!("let _iter = (&{expr_code}).into_iter();"));
540 }
541 // Otherwise, we borrow `iter` assuming that it implements `IntoIterator`.
542 _ => buf.write(format_args!("let _iter = ({expr_code}).into_iter();")),
543 }
544 if let Some(cond) = &loop_block.cond {
545 this.push_locals(|this| {
546 buf.write("let _iter = _iter.filter(|");
547 this.visit_target(buf, true, true, &loop_block.var);
548 buf.write("| -> bool {");
549 this.visit_expr(ctx, buf, cond)?;
550 buf.write("});");
551 Ok(0)
552 })?;
553 }
554
555 let size_hint1 = this.push_locals(|this| {
556 buf.write("for (");
557 this.visit_target(buf, true, true, &loop_block.var);
558 buf.write(", _loop_item) in askama::helpers::TemplateLoop::new(_iter) {");
559
560 if has_else_nodes {
561 buf.write("_did_loop = true;");
562 }
563 let mut size_hint1 = this.handle(ctx, &loop_block.body, buf, AstLevel::Nested)?;
564 this.handle_ws(loop_block.ws2);
565 size_hint1 += this.write_buf_writable(ctx, buf)?;
566 Ok(size_hint1)
567 })?;
568 buf.write('}');
569
570 let size_hint2;
571 if has_else_nodes {
572 buf.write("if !_did_loop {");
573 size_hint2 = this.push_locals(|this| {
574 let mut size_hint =
575 this.handle(ctx, &loop_block.else_nodes, buf, AstLevel::Nested)?;
576 this.handle_ws(loop_block.ws3);
577 size_hint += this.write_buf_writable(ctx, buf)?;
578 Ok(size_hint)
579 })?;
580 buf.write('}');
581 } else {
582 this.handle_ws(loop_block.ws3);
583 size_hint2 = this.write_buf_writable(ctx, buf)?;
584 }
585
586 buf.write('}');
587 Ok(flushed + ((size_hint1 * 3) + size_hint2) / 2)
588 })
589 }
590
591 fn write_call(
592 &mut self,
593 ctx: &Context<'a>,
594 buf: &mut Buffer,
595 call: &'a WithSpan<'_, Call<'_>>,
596 ) -> Result<usize, CompileError> {
597 let Call {
598 ws,
599 scope,
600 name,
601 ref args,
602 } = **call;
603 if name == "super" {
604 return self.write_block(ctx, buf, None, ws, call.span());
605 }
606
607 let (def, own_ctx) = if let Some(s) = scope {
608 let path = ctx.imports.get(s).ok_or_else(|| {
609 ctx.generate_error(format_args!("no import found for scope {s:?}"), call.span())
610 })?;
611 let mctx = self.contexts.get(path).ok_or_else(|| {
612 ctx.generate_error(format_args!("context for {path:?} not found"), call.span())
613 })?;
614 let def = mctx.macros.get(name).ok_or_else(|| {
615 ctx.generate_error(
616 format_args!("macro {name:?} not found in scope {s:?}"),
617 call.span(),
618 )
619 })?;
620 (*def, mctx)
621 } else {
622 let def = ctx.macros.get(name).ok_or_else(|| {
623 ctx.generate_error(format_args!("macro {name:?} not found"), call.span())
624 })?;
625 (*def, ctx)
626 };
627
628 if self.seen_macros.iter().any(|(s, _)| std::ptr::eq(*s, def)) {
629 let mut message = "Found recursion in macro calls:".to_owned();
630 for (m, f) in &self.seen_macros {
631 if let Some(f) = f {
632 write!(message, "{f}").unwrap();
633 } else {
634 write!(message, "\n`{}`", m.name.escape_debug()).unwrap();
635 }
636 }
637 return Err(ctx.generate_error(message, call.span()));
638 } else {
639 self.seen_macros.push((def, ctx.file_info_of(call.span())));
640 }
641
642 self.flush_ws(ws); // Cannot handle_ws() here: whitespace from macro definition comes first
643 let size_hint = self.push_locals(|this| {
644 macro_call_ensure_arg_count(call, def, ctx)?;
645
646 this.write_buf_writable(ctx, buf)?;
647 buf.write('{');
648 this.prepare_ws(def.ws1);
649
650 let mut named_arguments: HashMap<&str, _, FxBuildHasher> = HashMap::default();
651 // Since named arguments can only be passed last, we only need to check if the last argument
652 // is a named one.
653 if let Some(Expr::NamedArgument(_, _)) = args.last().map(|expr| &**expr) {
654 // First we check that all named arguments actually exist in the called item.
655 for (index, arg) in args.iter().enumerate().rev() {
656 let Expr::NamedArgument(arg_name, _) = &**arg else {
657 break;
658 };
659 if !def.args.iter().any(|(arg, _)| arg == arg_name) {
660 return Err(ctx.generate_error(
661 format_args!("no argument named `{arg_name}` in macro {name:?}"),
662 call.span(),
663 ));
664 }
665 named_arguments.insert(arg_name, (index, arg));
666 }
667 }
668
669 let mut value = Buffer::new();
670
671 // Handling both named and unnamed arguments requires to be careful of the named arguments
672 // order. To do so, we iterate through the macro defined arguments and then check if we have
673 // a named argument with this name:
674 //
675 // * If there is one, we add it and move to the next argument.
676 // * If there isn't one, then we pick the next argument (we can do it without checking
677 // anything since named arguments are always last).
678 let mut allow_positional = true;
679 let mut used_named_args = vec![false; args.len()];
680 for (index, (arg, default_value)) in def.args.iter().enumerate() {
681 let expr = if let Some((index, expr)) = named_arguments.get(arg) {
682 used_named_args[*index] = true;
683 allow_positional = false;
684 expr
685 } else {
686 match args.get(index) {
687 Some(arg_expr) if !matches!(**arg_expr, Expr::NamedArgument(_, _)) => {
688 // If there is already at least one named argument, then it's not allowed
689 // to use unnamed ones at this point anymore.
690 if !allow_positional {
691 return Err(ctx.generate_error(
692 format_args!(
693 "cannot have unnamed argument (`{arg}`) after named argument \
694 in call to macro {name:?}"
695 ),
696 call.span(),
697 ));
698 }
699 arg_expr
700 }
701 Some(arg_expr) if used_named_args[index] => {
702 let Expr::NamedArgument(name, _) = **arg_expr else { unreachable!() };
703 return Err(ctx.generate_error(
704 format_args!("`{name}` is passed more than once"),
705 call.span(),
706 ));
707 }
708 _ => {
709 if let Some(default_value) = default_value {
710 default_value
711 } else {
712 return Err(ctx.generate_error(format_args!("missing `{arg}` argument"), call.span()));
713 }
714 }
715 }
716 };
717 match &**expr {
718 // If `expr` is already a form of variable then
719 // don't reintroduce a new variable. This is
720 // to avoid moving non-copyable values.
721 Expr::Var(name) if *name != "self" => {
722 let var = this.locals.resolve_or_self(name);
723 this.locals
724 .insert(Cow::Borrowed(arg), LocalMeta::with_ref(var));
725 }
726 Expr::Attr(obj, attr) => {
727 let mut attr_buf = Buffer::new();
728 this.visit_attr(ctx, &mut attr_buf, obj, attr)?;
729
730 let attr = attr_buf.into_string();
731 let var = this.locals.resolve(&attr).unwrap_or(attr);
732 this.locals
733 .insert(Cow::Borrowed(arg), LocalMeta::with_ref(var));
734 }
735 // Everything else still needs to become variables,
736 // to avoid having the same logic be executed
737 // multiple times, e.g. in the case of macro
738 // parameters being used multiple times.
739 _ => {
740 value.clear();
741 let (before, after) = if !is_copyable(expr) {
742 ("&(", ")")
743 } else {
744 ("", "")
745 };
746 value.write(this.visit_expr_root(ctx, expr)?);
747 // We need to normalize the arg to write it, thus we need to add it to
748 // locals in the normalized manner
749 let normalized_arg = normalize_identifier(arg);
750 buf.write(format_args!("let {} = {before}{value}{after};", normalized_arg));
751 this.locals.insert_with_default(Cow::Borrowed(normalized_arg));
752 }
753 }
754 }
755
756 let mut size_hint = this.handle(own_ctx, &def.nodes, buf, AstLevel::Nested)?;
757
758 this.flush_ws(def.ws2);
759 size_hint += this.write_buf_writable(ctx, buf)?;
760 buf.write('}');
761 Ok(size_hint)
762 })?;
763 self.prepare_ws(ws);
764 self.seen_macros.pop();
765 Ok(size_hint)
766 }
767
768 fn write_filter_block(
769 &mut self,
770 ctx: &Context<'a>,
771 buf: &mut Buffer,
772 filter: &'a WithSpan<'_, FilterBlock<'_>>,
773 ) -> Result<usize, CompileError> {
774 self.write_buf_writable(ctx, buf)?;
775 self.flush_ws(filter.ws1);
776 self.is_in_filter_block += 1;
777 self.write_buf_writable(ctx, buf)?;
778 buf.write('{');
779
780 // build `FmtCell` that contains the inner block
781 buf.write(format_args!(
782 "let {FILTER_SOURCE} = askama::helpers::FmtCell::new(\
783 |__askama_writer: &mut askama::helpers::core::fmt::Formatter<'_>| -> askama::Result<()> {{"
784 ));
785 let size_hint = self.push_locals(|this| {
786 this.prepare_ws(filter.ws1);
787 let size_hint = this.handle(ctx, &filter.nodes, buf, AstLevel::Nested)?;
788 this.flush_ws(filter.ws2);
789 this.write_buf_writable(ctx, buf)?;
790 Ok(size_hint)
791 })?;
792 buf.write(
793 "\
794 askama::Result::Ok(())\
795 });",
796 );
797
798 // display the `FmtCell`
799 let mut filter_buf = Buffer::new();
800 let display_wrap = self.visit_filter(
801 ctx,
802 &mut filter_buf,
803 filter.filters.name,
804 &filter.filters.arguments,
805 &filter.filters.generics,
806 filter.span(),
807 )?;
808 let filter_buf = match display_wrap {
809 DisplayWrap::Wrapped => fmt_left!("{filter_buf}"),
810 DisplayWrap::Unwrapped => fmt_right!(
811 "(&&askama::filters::AutoEscaper::new(&({filter_buf}), {})).askama_auto_escape()?",
812 self.input.escaper,
813 ),
814 };
815 buf.write(format_args!(
816 "if askama::helpers::core::write!(__askama_writer, \"{{}}\", {filter_buf}).is_err() {{\
817 return {FILTER_SOURCE}.take_err();\
818 }}"
819 ));
820
821 buf.write('}');
822 self.is_in_filter_block -= 1;
823 self.prepare_ws(filter.ws2);
824 Ok(size_hint)
825 }
826
827 fn handle_include(
828 &mut self,
829 ctx: &Context<'a>,
830 buf: &mut Buffer,
831 i: &'a WithSpan<'_, Include<'_>>,
832 ) -> Result<usize, CompileError> {
833 self.flush_ws(i.ws);
834 self.write_buf_writable(ctx, buf)?;
835 let file_info = ctx
836 .path
837 .map(|path| FileInfo::of(i.span(), path, ctx.parsed));
838 let path = self
839 .input
840 .config
841 .find_template(i.path, Some(&self.input.path), file_info)?;
842
843 // We clone the context of the child in order to preserve their macros and imports.
844 // But also add all the imports and macros from this template that don't override the
845 // child's ones to preserve this template's context.
846 let child_ctx = &mut self.contexts[&path].clone();
847 for (name, mac) in &ctx.macros {
848 child_ctx.macros.entry(name).or_insert(mac);
849 }
850 for (name, import) in &ctx.imports {
851 child_ctx
852 .imports
853 .entry(name)
854 .or_insert_with(|| import.clone());
855 }
856
857 // Create a new generator for the child, and call it like in `impl_template` as if it were
858 // a full template, while preserving the context.
859 let heritage = if !child_ctx.blocks.is_empty() || child_ctx.extends.is_some() {
860 Some(Heritage::new(child_ctx, self.contexts))
861 } else {
862 None
863 };
864
865 let handle_ctx = match &heritage {
866 Some(heritage) => heritage.root,
867 None => child_ctx,
868 };
869
870 let size_hint = self.with_child(heritage.as_ref(), |child| {
871 let mut size_hint = 0;
872 size_hint += child.handle(handle_ctx, handle_ctx.nodes, buf, AstLevel::Top)?;
873 size_hint += child.write_buf_writable(handle_ctx, buf)?;
874 Ok(size_hint)
875 })?;
876
877 self.prepare_ws(i.ws);
878
879 Ok(size_hint)
880 }
881
882 fn is_shadowing_variable(
883 &self,
884 ctx: &Context<'_>,
885 var: &Target<'a>,
886 l: Span<'_>,
887 ) -> Result<bool, CompileError> {
888 match var {
889 Target::Name(name) => {
890 let name = normalize_identifier(name);
891 match self.locals.get(name) {
892 // declares a new variable
893 None => Ok(false),
894 // an initialized variable gets shadowed
895 Some(meta) if meta.initialized => Ok(true),
896 // initializes a variable that was introduced in a LetDecl before
897 _ => Ok(false),
898 }
899 }
900 Target::Placeholder(_) => Ok(false),
901 Target::Rest(var_name) => {
902 if let Some(var_name) = **var_name {
903 match self.is_shadowing_variable(ctx, &Target::Name(var_name), l) {
904 Ok(false) => {}
905 outcome => return outcome,
906 }
907 }
908 Ok(false)
909 }
910 Target::Tuple(_, targets) => {
911 for target in targets {
912 match self.is_shadowing_variable(ctx, target, l) {
913 Ok(false) => continue,
914 outcome => return outcome,
915 }
916 }
917 Ok(false)
918 }
919 Target::Struct(_, named_targets) => {
920 for (_, target) in named_targets {
921 match self.is_shadowing_variable(ctx, target, l) {
922 Ok(false) => continue,
923 outcome => return outcome,
924 }
925 }
926 Ok(false)
927 }
928 _ => Err(ctx.generate_error(
929 "literals are not allowed on the left-hand side of an assignment",
930 l,
931 )),
932 }
933 }
934
935 fn write_let(
936 &mut self,
937 ctx: &Context<'_>,
938 buf: &mut Buffer,
939 l: &'a WithSpan<'_, Let<'_>>,
940 ) -> Result<(), CompileError> {
941 self.handle_ws(l.ws);
942
943 let Some(val) = &l.val else {
944 self.write_buf_writable(ctx, buf)?;
945 buf.write("let ");
946 self.visit_target(buf, false, true, &l.var);
947 buf.write(';');
948 return Ok(());
949 };
950
951 let mut expr_buf = Buffer::new();
952 self.visit_expr(ctx, &mut expr_buf, val)?;
953
954 let shadowed = self.is_shadowing_variable(ctx, &l.var, l.span())?;
955 if shadowed {
956 // Need to flush the buffer if the variable is being shadowed,
957 // to ensure the old variable is used.
958 self.write_buf_writable(ctx, buf)?;
959 }
960 if shadowed
961 || !matches!(l.var, Target::Name(_))
962 || matches!(&l.var, Target::Name(name) if self.locals.get(name).is_none())
963 {
964 buf.write("let ");
965 }
966
967 self.visit_target(buf, true, true, &l.var);
968 let (before, after) = if !is_copyable(val) {
969 ("&(", ")")
970 } else {
971 ("", "")
972 };
973 buf.write(format_args!(" = {before}{expr_buf}{after};"));
974 Ok(())
975 }
976
977 // If `name` is `Some`, this is a call to a block definition, and we have to find
978 // the first block for that name from the ancestry chain. If name is `None`, this
979 // is from a `super()` call, and we can get the name from `self.super_block`.
980 fn write_block(
981 &mut self,
982 ctx: &Context<'a>,
983 buf: &mut Buffer,
984 name: Option<&'a str>,
985 outer: Ws,
986 node: Span<'_>,
987 ) -> Result<usize, CompileError> {
988 if self.is_in_filter_block > 0 {
989 return Err(ctx.generate_error("cannot have a block inside a filter block", node));
990 }
991 // Flush preceding whitespace according to the outer WS spec
992 self.flush_ws(outer);
993
994 let cur = match (name, self.super_block) {
995 // The top-level context contains a block definition
996 (Some(cur_name), None) => (cur_name, 0),
997 // A block definition contains a block definition of the same name
998 (Some(cur_name), Some((prev_name, _))) if cur_name == prev_name => {
999 return Err(ctx.generate_error(
1000 format_args!("cannot define recursive blocks ({cur_name})"),
1001 node,
1002 ));
1003 }
1004 // A block definition contains a definition of another block
1005 (Some(cur_name), Some((_, _))) => (cur_name, 0),
1006 // `super()` was called inside a block
1007 (None, Some((prev_name, gen))) => (prev_name, gen + 1),
1008 // `super()` is called from outside a block
1009 (None, None) => {
1010 return Err(ctx.generate_error("cannot call 'super()' outside block", node));
1011 }
1012 };
1013
1014 self.write_buf_writable(ctx, buf)?;
1015
1016 let block_fragment_write =
1017 self.input.block.map(|(block, _)| block) == name && self.buf_writable.discard;
1018 // Allow writing to the buffer if we're in the block fragment
1019 if block_fragment_write {
1020 self.buf_writable.discard = false;
1021 }
1022 let prev_buf_discard = buf.is_discard();
1023 buf.set_discard(self.buf_writable.discard);
1024
1025 // Get the block definition from the heritage chain
1026 let heritage = self
1027 .heritage
1028 .ok_or_else(|| ctx.generate_error("no block ancestors available", node))?;
1029 let (child_ctx, def) = *heritage.blocks[cur.0].get(cur.1).ok_or_else(|| {
1030 ctx.generate_error(
1031 match name {
1032 None => fmt_left!("no super() block found for block '{}'", cur.0),
1033 Some(name) => fmt_right!(move "no block found for name '{name}'"),
1034 },
1035 node,
1036 )
1037 })?;
1038
1039 // We clone the context of the child in order to preserve their macros and imports.
1040 // But also add all the imports and macros from this template that don't override the
1041 // child's ones to preserve this template's context.
1042 let mut child_ctx = child_ctx.clone();
1043 for (name, mac) in &ctx.macros {
1044 child_ctx.macros.entry(name).or_insert(mac);
1045 }
1046 for (name, import) in &ctx.imports {
1047 child_ctx
1048 .imports
1049 .entry(name)
1050 .or_insert_with(|| import.clone());
1051 }
1052
1053 let size_hint = self.with_child(Some(heritage), |child| {
1054 // Handle inner whitespace suppression spec and process block nodes
1055 child.prepare_ws(def.ws1);
1056
1057 child.super_block = Some(cur);
1058 let size_hint = child.handle(&child_ctx, &def.nodes, buf, AstLevel::Block)?;
1059
1060 if !child.locals.is_current_empty() {
1061 // Need to flush the buffer before popping the variable stack
1062 child.write_buf_writable(ctx, buf)?;
1063 }
1064
1065 child.flush_ws(def.ws2);
1066 Ok(size_hint)
1067 })?;
1068
1069 // Restore original block context and set whitespace suppression for
1070 // succeeding whitespace according to the outer WS spec
1071 self.prepare_ws(outer);
1072
1073 // If we are rendering a specific block and the discard changed, it means that we're done
1074 // with the block we want to render and that from this point, everything will be discarded.
1075 //
1076 // To get this block content rendered as well, we need to write to the buffer before then.
1077 if buf.is_discard() != prev_buf_discard {
1078 self.write_buf_writable(ctx, buf)?;
1079 }
1080 // Restore the original buffer discarding state
1081 if block_fragment_write {
1082 self.buf_writable.discard = true;
1083 }
1084 buf.set_discard(prev_buf_discard);
1085
1086 Ok(size_hint)
1087 }
1088
1089 fn write_expr(&mut self, ws: Ws, s: &'a WithSpan<'a, Expr<'a>>) {
1090 self.handle_ws(ws);
1091 let items = if let Expr::Concat(exprs) = &**s {
1092 exprs
1093 } else {
1094 std::slice::from_ref(s)
1095 };
1096 for s in items {
1097 self.buf_writable
1098 .push(compile_time_escape(s, self.input.escaper).unwrap_or(Writable::Expr(s)));
1099 }
1100 }
1101
1102 // Write expression buffer and empty
1103 fn write_buf_writable(
1104 &mut self,
1105 ctx: &Context<'_>,
1106 buf: &mut Buffer,
1107 ) -> Result<usize, CompileError> {
1108 let mut size_hint = 0;
1109 let items = mem::take(&mut self.buf_writable.buf);
1110 let mut it = items.iter().enumerate().peekable();
1111
1112 while let Some((_, Writable::Lit(s))) = it.peek() {
1113 size_hint += buf.write_writer(s);
1114 it.next();
1115 }
1116 if it.peek().is_none() {
1117 return Ok(size_hint);
1118 }
1119
1120 let mut targets = Buffer::new();
1121 let mut lines = Buffer::new();
1122 let mut expr_cache = HashMap::with_capacity(self.buf_writable.len());
1123 // the `last_line` contains any sequence of trailing simple `writer.write_str()` calls
1124 let mut trailing_simple_lines = Vec::new();
1125
1126 buf.write("match (");
1127 while let Some((idx, s)) = it.next() {
1128 match s {
1129 Writable::Lit(s) => {
1130 let mut items = vec![s];
1131 while let Some((_, Writable::Lit(s))) = it.peek() {
1132 items.push(s);
1133 it.next();
1134 }
1135 if it.peek().is_some() {
1136 for s in items {
1137 size_hint += lines.write_writer(s);
1138 }
1139 } else {
1140 trailing_simple_lines = items;
1141 break;
1142 }
1143 }
1144 Writable::Expr(s) => {
1145 size_hint += 3;
1146
1147 let mut expr_buf = Buffer::new();
1148 let expr = match self.visit_expr(ctx, &mut expr_buf, s)? {
1149 DisplayWrap::Wrapped => expr_buf.into_string(),
1150 DisplayWrap::Unwrapped => format!(
1151 "(&&askama::filters::AutoEscaper::new(&({expr_buf}), {})).\
1152 askama_auto_escape()?",
1153 self.input.escaper,
1154 ),
1155 };
1156 let idx = if is_cacheable(s) {
1157 match expr_cache.entry(expr) {
1158 Entry::Occupied(e) => *e.get(),
1159 Entry::Vacant(e) => {
1160 buf.write(format_args!("&({}),", e.key()));
1161 targets.write(format_args!("expr{idx},"));
1162 e.insert(idx);
1163 idx
1164 }
1165 }
1166 } else {
1167 buf.write(format_args!("&({expr}),"));
1168 targets.write(format_args!("expr{idx}, "));
1169 idx
1170 };
1171 lines.write(format_args!(
1172 "(&&&askama::filters::Writable(expr{idx})).\
1173 askama_write(__askama_writer, __askama_values)?;",
1174 ));
1175 }
1176 }
1177 }
1178 buf.write(format_args!(
1179 ") {{\
1180 ({targets}) => {{\
1181 {lines}\
1182 }}\
1183 }}"
1184 ));
1185
1186 for s in trailing_simple_lines {
1187 size_hint += buf.write_writer(s);
1188 }
1189
1190 Ok(size_hint)
1191 }
1192
1193 fn write_comment(&mut self, comment: &'a WithSpan<'_, Comment<'_>>) {
1194 self.handle_ws(comment.ws);
1195 }
1196
1197 fn write_lit(&mut self, lit: &'a Lit<'_>) {
1198 assert!(self.next_ws.is_none());
1199 let Lit { lws, val, rws } = *lit;
1200 if !lws.is_empty() {
1201 match self.skip_ws {
1202 Whitespace::Suppress => {}
1203 _ if val.is_empty() => {
1204 assert!(rws.is_empty());
1205 self.next_ws = Some(lws);
1206 }
1207 Whitespace::Preserve => {
1208 self.buf_writable.push(Writable::Lit(Cow::Borrowed(lws)));
1209 }
1210 Whitespace::Minimize => {
1211 self.buf_writable.push(Writable::Lit(Cow::Borrowed(
1212 match lws.contains('\n') {
1213 true => "\n",
1214 false => " ",
1215 },
1216 )));
1217 }
1218 }
1219 }
1220
1221 if !val.is_empty() {
1222 self.skip_ws = Whitespace::Preserve;
1223 self.buf_writable.push(Writable::Lit(Cow::Borrowed(val)));
1224 }
1225
1226 if !rws.is_empty() {
1227 self.next_ws = Some(rws);
1228 }
1229 }
1230
1231 // Helper methods for dealing with whitespace nodes
1232
1233 // Combines `flush_ws()` and `prepare_ws()` to handle both trailing whitespace from the
1234 // preceding literal and leading whitespace from the succeeding literal.
1235 fn handle_ws(&mut self, ws: Ws) {
1236 self.flush_ws(ws);
1237 self.prepare_ws(ws);
1238 }
1239
1240 fn should_trim_ws(&self, ws: Option<Whitespace>) -> Whitespace {
1241 ws.unwrap_or(self.input.config.whitespace)
1242 }
1243
1244 // If the previous literal left some trailing whitespace in `next_ws` and the
1245 // prefix whitespace suppressor from the given argument, flush that whitespace.
1246 // In either case, `next_ws` is reset to `None` (no trailing whitespace).
1247 fn flush_ws(&mut self, ws: Ws) {
1248 if self.next_ws.is_none() {
1249 return;
1250 }
1251
1252 // If `whitespace` is set to `suppress`, we keep the whitespace characters only if there is
1253 // a `+` character.
1254 match self.should_trim_ws(ws.0) {
1255 Whitespace::Preserve => {
1256 let val = self.next_ws.unwrap();
1257 if !val.is_empty() {
1258 self.buf_writable.push(Writable::Lit(Cow::Borrowed(val)));
1259 }
1260 }
1261 Whitespace::Minimize => {
1262 let val = self.next_ws.unwrap();
1263 if !val.is_empty() {
1264 self.buf_writable.push(Writable::Lit(Cow::Borrowed(
1265 match val.contains('\n') {
1266 true => "\n",
1267 false => " ",
1268 },
1269 )));
1270 }
1271 }
1272 Whitespace::Suppress => {}
1273 }
1274 self.next_ws = None;
1275 }
1276
1277 // Sets `skip_ws` to match the suffix whitespace suppressor from the given
1278 // argument, to determine whether to suppress leading whitespace from the
1279 // next literal.
1280 fn prepare_ws(&mut self, ws: Ws) {
1281 self.skip_ws = self.should_trim_ws(ws.1);
1282 }
1283 }
1284
1285 struct CondInfo<'a> {
1286 cond: &'a WithSpan<'a, Cond<'a>>,
1287 cond_expr: Option<WithSpan<'a, Expr<'a>>>,
1288 generate_condition: bool,
1289 generate_content: bool,
1290 }
1291
1292 struct Conds<'a> {
1293 conds: Vec<CondInfo<'a>>,
1294 ws_before: Option<Ws>,
1295 ws_after: Option<Ws>,
1296 nb_conds: usize,
1297 }
1298
1299 #[derive(Clone, Copy, PartialEq, Debug)]
1300 enum EvaluatedResult {
1301 AlwaysTrue,
1302 AlwaysFalse,
1303 Unknown,
1304 }
1305
1306 impl<'a> Conds<'a> {
1307 fn compute_branches(generator: &Generator<'a, '_>, i: &'a If<'a>) -> Self {
1308 let mut conds = Vec::with_capacity(i.branches.len());
1309 let mut ws_before = None;
1310 let mut ws_after = None;
1311 let mut nb_conds = 0;
1312 let mut stop_loop = false;
1313
1314 for cond in &i.branches {
1315 if stop_loop {
1316 ws_after = Some(cond.ws);
1317 break;
1318 }
1319 if let Some(CondTest {
1320 expr,
1321 contains_bool_lit_or_is_defined,
1322 ..
1323 }) = &cond.cond
1324 {
1325 let mut only_contains_is_defined = true;
1326
1327 let (evaluated_result, cond_expr) = if *contains_bool_lit_or_is_defined {
1328 let (evaluated_result, expr) =
1329 generator.evaluate_condition(expr.clone(), &mut only_contains_is_defined);
1330 (evaluated_result, Some(expr))
1331 } else {
1332 (EvaluatedResult::Unknown, None)
1333 };
1334
1335 match evaluated_result {
1336 // We generate the condition in case some calls are changing a variable, but
1337 // no need to generate the condition body since it will never be called.
1338 //
1339 // However, if the condition only contains "is (not) defined" checks, then we
1340 // can completely skip it.
1341 EvaluatedResult::AlwaysFalse => {
1342 if only_contains_is_defined {
1343 if conds.is_empty() && ws_before.is_none() {
1344 // If this is the first `if` and it's skipped, we definitely don't
1345 // want its whitespace control to be lost.
1346 ws_before = Some(cond.ws);
1347 }
1348 continue;
1349 }
1350 nb_conds += 1;
1351 conds.push(CondInfo {
1352 cond,
1353 cond_expr,
1354 generate_condition: true,
1355 generate_content: false,
1356 });
1357 }
1358 // This case is more interesting: it means that we will always enter this
1359 // condition, meaning that any following should not be generated. Another
1360 // thing to take into account: if there are no if branches before this one,
1361 // no need to generate an `else`.
1362 EvaluatedResult::AlwaysTrue => {
1363 let generate_condition = !only_contains_is_defined;
1364 if generate_condition {
1365 nb_conds += 1;
1366 }
1367 conds.push(CondInfo {
1368 cond,
1369 cond_expr,
1370 generate_condition,
1371 generate_content: true,
1372 });
1373 // Since it's always true, we can stop here.
1374 stop_loop = true;
1375 }
1376 EvaluatedResult::Unknown => {
1377 nb_conds += 1;
1378 conds.push(CondInfo {
1379 cond,
1380 cond_expr,
1381 generate_condition: true,
1382 generate_content: true,
1383 });
1384 }
1385 }
1386 } else {
1387 let generate_condition = !conds.is_empty();
1388 if generate_condition {
1389 nb_conds += 1;
1390 }
1391 conds.push(CondInfo {
1392 cond,
1393 cond_expr: None,
1394 generate_condition,
1395 generate_content: true,
1396 });
1397 }
1398 }
1399 Self {
1400 conds,
1401 ws_before,
1402 ws_after,
1403 nb_conds,
1404 }
1405 }
1406 }
1407
1408 fn median(sizes: &mut [usize]) -> usize {
1409 if sizes.is_empty() {
1410 return 0;
1411 }
1412 sizes.sort_unstable();
1413 if sizes.len() % 2 == 1 {
1414 sizes[sizes.len() / 2]
1415 } else {
1416 (sizes[sizes.len() / 2 - 1] + sizes[sizes.len() / 2]) / 2
1417 }
1418 }
1419
1420 fn macro_call_ensure_arg_count(
1421 call: &WithSpan<'_, Call<'_>>,
1422 def: &Macro<'_>,
1423 ctx: &Context<'_>,
1424 ) -> Result<(), CompileError> {
1425 if call.args.len() > def.args.len() {
1426 return Err(ctx.generate_error(
1427 format_args!(
1428 "macro `{}` expected {} argument{}, found {}",
1429 def.name,
1430 def.args.len(),
1431 if def.args.len() > 1 { "s" } else { "" },
1432 call.args.len(),
1433 ),
1434 call.span(),
1435 ));
1436 }
1437
1438 // First we list of arguments position, then we remove every argument with a value.
1439 let mut args: Vec<_> = def.args.iter().map(|&(name, _)| Some(name)).collect();
1440 for (pos, arg) in call.args.iter().enumerate() {
1441 let pos = match **arg {
1442 Expr::NamedArgument(name, ..) => {
1443 def.args.iter().position(|(arg_name, _)| *arg_name == name)
1444 }
1445 _ => Some(pos),
1446 };
1447 if let Some(pos) = pos {
1448 if mem::take(&mut args[pos]).is_none() {
1449 // This argument was already passed, so error.
1450 return Err(ctx.generate_error(
1451 format_args!(
1452 "argument `{}` was passed more than once when calling macro `{}`",
1453 def.args[pos].0, def.name,
1454 ),
1455 call.span(),
1456 ));
1457 }
1458 }
1459 }
1460
1461 // Now we can check off arguments with a default value, too.
1462 for (pos, (_, dflt)) in def.args.iter().enumerate() {
1463 if dflt.is_some() {
1464 args[pos] = None;
1465 }
1466 }
1467
1468 // Now that we have a needed information, we can print an error message (if needed).
1469 struct FmtMissing<'a, I> {
1470 count: usize,
1471 missing: I,
1472 name: &'a str,
1473 }
1474
1475 impl<'a, I: Iterator<Item = &'a str> + Clone> fmt::Display for FmtMissing<'a, I> {
1476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1477 if self.count == 1 {
1478 let a = self.missing.clone().next().unwrap();
1479 write!(
1480 f,
1481 "missing argument when calling macro `{}`: `{a}`",
1482 self.name
1483 )
1484 } else {
1485 write!(f, "missing arguments when calling macro `{}`: ", self.name)?;
1486 for (idx, a) in self.missing.clone().enumerate() {
1487 if idx == self.count - 1 {
1488 write!(f, " and ")?;
1489 } else if idx > 0 {
1490 write!(f, ", ")?;
1491 }
1492 write!(f, "`{a}`")?;
1493 }
1494 Ok(())
1495 }
1496 }
1497 }
1498
1499 let missing = args.iter().filter_map(Option::as_deref);
1500 let fmt_missing = FmtMissing {
1501 count: missing.clone().count(),
1502 missing,
1503 name: def.name,
1504 };
1505 if fmt_missing.count == 0 {
1506 Ok(())
1507 } else {
1508 Err(ctx.generate_error(fmt_missing, call.span()))
1509 }
1510 }
1511
1512 #[derive(Clone, Copy, PartialEq)]
1513 enum AstLevel {
1514 Top,
1515 Block,
1516 Nested,
1517 }
1518
1519 /// Returns `true` if the outcome of this expression may be used multiple times in the same
1520 /// `write!()` call, without evaluating the expression again, i.e. the expression should be
1521 /// side-effect free.
1522 fn is_cacheable(expr: &WithSpan<'_, Expr<'_>>) -> bool {
1523 match &**expr {
1524 // Literals are the definition of pure:
1525 Expr::BoolLit(_) => true,
1526 Expr::NumLit(_, _) => true,
1527 Expr::StrLit(_) => true,
1528 Expr::CharLit(_) => true,
1529 // fmt::Display should have no effects:
1530 Expr::Var(_) => true,
1531 Expr::Path(_) => true,
1532 // Check recursively:
1533 Expr::Array(args) => args.iter().all(is_cacheable),
1534 Expr::Attr(lhs, _) => is_cacheable(lhs),
1535 Expr::Index(lhs, rhs) => is_cacheable(lhs) && is_cacheable(rhs),
1536 Expr::Filter(Filter { arguments, .. }) => arguments.iter().all(is_cacheable),
1537 Expr::Unary(_, arg) => is_cacheable(arg),
1538 Expr::BinOp(_, lhs, rhs) => is_cacheable(lhs) && is_cacheable(rhs),
1539 Expr::IsDefined(_) | Expr::IsNotDefined(_) => true,
1540 Expr::Range(_, lhs, rhs) => {
1541 lhs.as_ref().map_or(true, |v| is_cacheable(v))
1542 && rhs.as_ref().map_or(true, |v| is_cacheable(v))
1543 }
1544 Expr::Group(arg) => is_cacheable(arg),
1545 Expr::Tuple(args) => args.iter().all(is_cacheable),
1546 Expr::NamedArgument(_, expr) => is_cacheable(expr),
1547 Expr::As(expr, _) => is_cacheable(expr),
1548 Expr::Try(expr) => is_cacheable(expr),
1549 Expr::Concat(args) => args.iter().all(is_cacheable),
1550 // Doesn't make sense in this context.
1551 Expr::LetCond(_) => false,
1552 // We have too little information to tell if the expression is pure:
1553 Expr::Call { .. } => false,
1554 Expr::RustMacro(_, _) => false,
1555 // Should never be encountered:
1556 Expr::FilterSource => unreachable!("FilterSource in expression?"),
1557 }
1558 }