jj_cli/
template_builder.rs

1// Copyright 2020-2023 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::cmp::Ordering;
16use std::collections::HashMap;
17use std::io;
18use std::iter;
19
20use itertools::Itertools as _;
21use jj_lib::backend::Signature;
22use jj_lib::backend::Timestamp;
23use jj_lib::config::ConfigNamePathBuf;
24use jj_lib::config::ConfigValue;
25use jj_lib::content_hash::blake2b_hash;
26use jj_lib::hex_util;
27use jj_lib::op_store::TimestampRange;
28use jj_lib::settings::UserSettings;
29use jj_lib::time_util::DatePattern;
30use serde::Deserialize;
31use serde::de::IntoDeserializer as _;
32
33use crate::config;
34use crate::formatter::FormatRecorder;
35use crate::formatter::Formatter;
36use crate::template_parser;
37use crate::template_parser::BinaryOp;
38use crate::template_parser::ExpressionKind;
39use crate::template_parser::ExpressionNode;
40use crate::template_parser::FunctionCallNode;
41use crate::template_parser::LambdaNode;
42use crate::template_parser::TemplateAliasesMap;
43use crate::template_parser::TemplateDiagnostics;
44use crate::template_parser::TemplateParseError;
45use crate::template_parser::TemplateParseErrorKind;
46use crate::template_parser::TemplateParseResult;
47use crate::template_parser::UnaryOp;
48use crate::templater::BoxedSerializeProperty;
49use crate::templater::BoxedTemplateProperty;
50use crate::templater::CoalesceTemplate;
51use crate::templater::ConcatTemplate;
52use crate::templater::ConditionalTemplate;
53use crate::templater::Email;
54use crate::templater::LabelTemplate;
55use crate::templater::ListPropertyTemplate;
56use crate::templater::ListTemplate;
57use crate::templater::Literal;
58use crate::templater::PlainTextFormattedProperty;
59use crate::templater::PropertyPlaceholder;
60use crate::templater::RawEscapeSequenceTemplate;
61use crate::templater::ReformatTemplate;
62use crate::templater::SeparateTemplate;
63use crate::templater::SizeHint;
64use crate::templater::Template;
65use crate::templater::TemplateProperty;
66use crate::templater::TemplatePropertyError;
67use crate::templater::TemplatePropertyExt as _;
68use crate::templater::TemplateRenderer;
69use crate::templater::WrapTemplateProperty;
70use crate::text_util;
71use crate::time_util;
72
73/// Callbacks to build usage-context-specific evaluation objects from AST nodes.
74///
75/// This is used to implement different meanings of `self` or different
76/// globally available functions in the template language depending on the
77/// context in which it is invoked.
78pub trait TemplateLanguage<'a> {
79    type Property: CoreTemplatePropertyVar<'a>;
80
81    fn settings(&self) -> &UserSettings;
82
83    /// Translates the given global `function` call to a property.
84    ///
85    /// This should be delegated to
86    /// `CoreTemplateBuildFnTable::build_function()`.
87    fn build_function(
88        &self,
89        diagnostics: &mut TemplateDiagnostics,
90        build_ctx: &BuildContext<Self::Property>,
91        function: &FunctionCallNode,
92    ) -> TemplateParseResult<Self::Property>;
93
94    /// Creates a method call thunk for the given `function` of the given
95    /// `property`.
96    fn build_method(
97        &self,
98        diagnostics: &mut TemplateDiagnostics,
99        build_ctx: &BuildContext<Self::Property>,
100        property: Self::Property,
101        function: &FunctionCallNode,
102    ) -> TemplateParseResult<Self::Property>;
103}
104
105/// Implements [`WrapTemplateProperty<'a, O>`] for property types.
106///
107/// - `impl_property_wrappers!(Kind { Foo(Foo), FooList(Vec<Foo>), .. });` to
108///   implement conversion from types `Foo`, `Vec<Foo>`, ...
109/// - `impl_property_wrappers!(<'a> Kind<'a> { .. });` for types with lifetime.
110/// - `impl_property_wrappers!(Kind => Core { .. });` to forward conversion to
111///   `Kind::Core(_)`.
112macro_rules! impl_property_wrappers {
113    ($kind:path $(=> $var:ident)? { $($body:tt)* }) => {
114        $crate::template_builder::_impl_property_wrappers_many!(
115            [], 'static, $kind $(=> $var)?, { $($body)* });
116    };
117    // capture the first lifetime as the lifetime of template objects.
118    (<$a:lifetime $(, $p:lifetime)* $(, $q:ident)*>
119     $kind:path $(=> $var:ident)? { $($body:tt)* }) => {
120        $crate::template_builder::_impl_property_wrappers_many!(
121            [$a, $($p,)* $($q,)*], $a, $kind $(=> $var)?, { $($body)* });
122    };
123}
124
125macro_rules! _impl_property_wrappers_many {
126    // lifetime/type parameters are packed in order to disable zipping.
127    // https://github.com/rust-lang/rust/issues/96184#issuecomment-1294999418
128    ($ps:tt, $a:lifetime, $kind:path, { $( $var:ident($ty:ty), )* }) => {
129        $(
130            $crate::template_builder::_impl_property_wrappers_one!(
131                $ps, $a, $kind, $var, $ty, std::convert::identity);
132        )*
133    };
134    // variant part in body is ignored so the same body can be reused for
135    // implementing forwarding conversion.
136    ($ps:tt, $a:lifetime, $kind:path => $var:ident, { $( $ignored_var:ident($ty:ty), )* }) => {
137        $(
138            $crate::template_builder::_impl_property_wrappers_one!(
139                $ps, $a, $kind, $var, $ty, $crate::templater::WrapTemplateProperty::wrap_property);
140        )*
141    };
142}
143
144macro_rules! _impl_property_wrappers_one {
145    ([$($p:tt)*], $a:lifetime, $kind:path, $var:ident, $ty:ty, $inner:path) => {
146        impl<$($p)*> $crate::templater::WrapTemplateProperty<$a, $ty> for $kind {
147            fn wrap_property(property: $crate::templater::BoxedTemplateProperty<$a, $ty>) -> Self {
148                Self::$var($inner(property))
149            }
150        }
151    };
152}
153
154pub(crate) use _impl_property_wrappers_many;
155pub(crate) use _impl_property_wrappers_one;
156pub(crate) use impl_property_wrappers;
157
158/// Wrapper for the core template property types.
159pub trait CoreTemplatePropertyVar<'a>
160where
161    Self: WrapTemplateProperty<'a, String>,
162    Self: WrapTemplateProperty<'a, Vec<String>>,
163    Self: WrapTemplateProperty<'a, bool>,
164    Self: WrapTemplateProperty<'a, i64>,
165    Self: WrapTemplateProperty<'a, Option<i64>>,
166    Self: WrapTemplateProperty<'a, ConfigValue>,
167    Self: WrapTemplateProperty<'a, Signature>,
168    Self: WrapTemplateProperty<'a, Email>,
169    Self: WrapTemplateProperty<'a, SizeHint>,
170    Self: WrapTemplateProperty<'a, Timestamp>,
171    Self: WrapTemplateProperty<'a, TimestampRange>,
172{
173    fn wrap_template(template: Box<dyn Template + 'a>) -> Self;
174    fn wrap_list_template(template: Box<dyn ListTemplate + 'a>) -> Self;
175
176    /// Type name of the property output.
177    fn type_name(&self) -> &'static str;
178
179    fn try_into_boolean(self) -> Option<BoxedTemplateProperty<'a, bool>>;
180    fn try_into_integer(self) -> Option<BoxedTemplateProperty<'a, i64>>;
181
182    /// Transforms into a string property by formatting the value if needed.
183    fn try_into_stringify(self) -> Option<BoxedTemplateProperty<'a, String>>;
184    fn try_into_serialize(self) -> Option<BoxedSerializeProperty<'a>>;
185    fn try_into_template(self) -> Option<Box<dyn Template + 'a>>;
186
187    /// Transforms into a property that will evaluate to `self == other`.
188    fn try_into_eq(self, other: Self) -> Option<BoxedTemplateProperty<'a, bool>>;
189
190    /// Transforms into a property that will evaluate to an [`Ordering`].
191    fn try_into_cmp(self, other: Self) -> Option<BoxedTemplateProperty<'a, Ordering>>;
192}
193
194pub enum CoreTemplatePropertyKind<'a> {
195    String(BoxedTemplateProperty<'a, String>),
196    StringList(BoxedTemplateProperty<'a, Vec<String>>),
197    Boolean(BoxedTemplateProperty<'a, bool>),
198    Integer(BoxedTemplateProperty<'a, i64>),
199    IntegerOpt(BoxedTemplateProperty<'a, Option<i64>>),
200    ConfigValue(BoxedTemplateProperty<'a, ConfigValue>),
201    Signature(BoxedTemplateProperty<'a, Signature>),
202    Email(BoxedTemplateProperty<'a, Email>),
203    SizeHint(BoxedTemplateProperty<'a, SizeHint>),
204    Timestamp(BoxedTemplateProperty<'a, Timestamp>),
205    TimestampRange(BoxedTemplateProperty<'a, TimestampRange>),
206
207    // Both TemplateProperty and Template can represent a value to be evaluated
208    // dynamically, which suggests that `Box<dyn Template + 'a>` could be
209    // composed as `Box<dyn TemplateProperty<Output = Box<dyn Template ..`.
210    // However, there's a subtle difference: TemplateProperty is strict on
211    // error, whereas Template is usually lax and prints an error inline. If
212    // `concat(x, y)` were a property returning Template, and if `y` failed to
213    // evaluate, the whole expression would fail. In this example, a partial
214    // evaluation output is more useful. That's one reason why Template isn't
215    // wrapped in a TemplateProperty. Another reason is that the outermost
216    // caller expects a Template, not a TemplateProperty of Template output.
217    Template(Box<dyn Template + 'a>),
218    ListTemplate(Box<dyn ListTemplate + 'a>),
219}
220
221/// Implements `WrapTemplateProperty<type>` for core property types.
222///
223/// Use `impl_core_property_wrappers!(<'a> Kind<'a> => Core);` to implement
224/// forwarding conversion.
225macro_rules! impl_core_property_wrappers {
226    ($($head:tt)+) => {
227        $crate::template_builder::impl_property_wrappers!($($head)+ {
228            String(String),
229            StringList(Vec<String>),
230            Boolean(bool),
231            Integer(i64),
232            IntegerOpt(Option<i64>),
233            ConfigValue(jj_lib::config::ConfigValue),
234            Signature(jj_lib::backend::Signature),
235            Email($crate::templater::Email),
236            SizeHint($crate::templater::SizeHint),
237            Timestamp(jj_lib::backend::Timestamp),
238            TimestampRange(jj_lib::op_store::TimestampRange),
239        });
240    };
241}
242
243pub(crate) use impl_core_property_wrappers;
244
245impl_core_property_wrappers!(<'a> CoreTemplatePropertyKind<'a>);
246
247impl<'a> CoreTemplatePropertyVar<'a> for CoreTemplatePropertyKind<'a> {
248    fn wrap_template(template: Box<dyn Template + 'a>) -> Self {
249        Self::Template(template)
250    }
251
252    fn wrap_list_template(template: Box<dyn ListTemplate + 'a>) -> Self {
253        Self::ListTemplate(template)
254    }
255
256    fn type_name(&self) -> &'static str {
257        match self {
258            Self::String(_) => "String",
259            Self::StringList(_) => "List<String>",
260            Self::Boolean(_) => "Boolean",
261            Self::Integer(_) => "Integer",
262            Self::IntegerOpt(_) => "Option<Integer>",
263            Self::ConfigValue(_) => "ConfigValue",
264            Self::Signature(_) => "Signature",
265            Self::Email(_) => "Email",
266            Self::SizeHint(_) => "SizeHint",
267            Self::Timestamp(_) => "Timestamp",
268            Self::TimestampRange(_) => "TimestampRange",
269            Self::Template(_) => "Template",
270            Self::ListTemplate(_) => "ListTemplate",
271        }
272    }
273
274    fn try_into_boolean(self) -> Option<BoxedTemplateProperty<'a, bool>> {
275        match self {
276            Self::String(property) => Some(property.map(|s| !s.is_empty()).into_dyn()),
277            Self::StringList(property) => Some(property.map(|l| !l.is_empty()).into_dyn()),
278            Self::Boolean(property) => Some(property),
279            Self::Integer(_) => None,
280            Self::IntegerOpt(property) => Some(property.map(|opt| opt.is_some()).into_dyn()),
281            Self::ConfigValue(_) => None,
282            Self::Signature(_) => None,
283            Self::Email(property) => Some(property.map(|e| !e.0.is_empty()).into_dyn()),
284            Self::SizeHint(_) => None,
285            Self::Timestamp(_) => None,
286            Self::TimestampRange(_) => None,
287            // Template types could also be evaluated to boolean, but it's less likely
288            // to apply label() or .map() and use the result as conditional. It's also
289            // unclear whether ListTemplate should behave as a "list" or a "template".
290            Self::Template(_) => None,
291            Self::ListTemplate(_) => None,
292        }
293    }
294
295    fn try_into_integer(self) -> Option<BoxedTemplateProperty<'a, i64>> {
296        match self {
297            Self::Integer(property) => Some(property),
298            Self::IntegerOpt(property) => Some(property.try_unwrap("Integer").into_dyn()),
299            _ => None,
300        }
301    }
302
303    fn try_into_stringify(self) -> Option<BoxedTemplateProperty<'a, String>> {
304        match self {
305            Self::String(property) => Some(property),
306            _ => {
307                let template = self.try_into_template()?;
308                Some(PlainTextFormattedProperty::new(template).into_dyn())
309            }
310        }
311    }
312
313    fn try_into_serialize(self) -> Option<BoxedSerializeProperty<'a>> {
314        match self {
315            Self::String(property) => Some(property.into_serialize()),
316            Self::StringList(property) => Some(property.into_serialize()),
317            Self::Boolean(property) => Some(property.into_serialize()),
318            Self::Integer(property) => Some(property.into_serialize()),
319            Self::IntegerOpt(property) => Some(property.into_serialize()),
320            Self::ConfigValue(property) => {
321                Some(property.map(config::to_serializable_value).into_serialize())
322            }
323            Self::Signature(property) => Some(property.into_serialize()),
324            Self::Email(property) => Some(property.into_serialize()),
325            Self::SizeHint(property) => Some(property.into_serialize()),
326            Self::Timestamp(property) => Some(property.into_serialize()),
327            Self::TimestampRange(property) => Some(property.into_serialize()),
328            Self::Template(_) => None,
329            Self::ListTemplate(_) => None,
330        }
331    }
332
333    fn try_into_template(self) -> Option<Box<dyn Template + 'a>> {
334        match self {
335            Self::String(property) => Some(property.into_template()),
336            Self::StringList(property) => Some(property.into_template()),
337            Self::Boolean(property) => Some(property.into_template()),
338            Self::Integer(property) => Some(property.into_template()),
339            Self::IntegerOpt(property) => Some(property.into_template()),
340            Self::ConfigValue(property) => Some(property.into_template()),
341            Self::Signature(property) => Some(property.into_template()),
342            Self::Email(property) => Some(property.into_template()),
343            Self::SizeHint(_) => None,
344            Self::Timestamp(property) => Some(property.into_template()),
345            Self::TimestampRange(property) => Some(property.into_template()),
346            Self::Template(template) => Some(template),
347            Self::ListTemplate(template) => Some(template),
348        }
349    }
350
351    fn try_into_eq(self, other: Self) -> Option<BoxedTemplateProperty<'a, bool>> {
352        match (self, other) {
353            (Self::String(lhs), Self::String(rhs)) => {
354                Some((lhs, rhs).map(|(l, r)| l == r).into_dyn())
355            }
356            (Self::String(lhs), Self::Email(rhs)) => {
357                Some((lhs, rhs).map(|(l, r)| l == r.0).into_dyn())
358            }
359            (Self::Boolean(lhs), Self::Boolean(rhs)) => {
360                Some((lhs, rhs).map(|(l, r)| l == r).into_dyn())
361            }
362            (Self::Integer(lhs), Self::Integer(rhs)) => {
363                Some((lhs, rhs).map(|(l, r)| l == r).into_dyn())
364            }
365            (Self::Integer(lhs), Self::IntegerOpt(rhs)) => {
366                Some((lhs, rhs).map(|(l, r)| Some(l) == r).into_dyn())
367            }
368            (Self::IntegerOpt(lhs), Self::Integer(rhs)) => {
369                Some((lhs, rhs).map(|(l, r)| l == Some(r)).into_dyn())
370            }
371            (Self::IntegerOpt(lhs), Self::IntegerOpt(rhs)) => {
372                Some((lhs, rhs).map(|(l, r)| l == r).into_dyn())
373            }
374            (Self::Email(lhs), Self::Email(rhs)) => {
375                Some((lhs, rhs).map(|(l, r)| l == r).into_dyn())
376            }
377            (Self::Email(lhs), Self::String(rhs)) => {
378                Some((lhs, rhs).map(|(l, r)| l.0 == r).into_dyn())
379            }
380            (Self::String(_), _) => None,
381            (Self::StringList(_), _) => None,
382            (Self::Boolean(_), _) => None,
383            (Self::Integer(_), _) => None,
384            (Self::IntegerOpt(_), _) => None,
385            (Self::ConfigValue(_), _) => None,
386            (Self::Signature(_), _) => None,
387            (Self::Email(_), _) => None,
388            (Self::SizeHint(_), _) => None,
389            (Self::Timestamp(_), _) => None,
390            (Self::TimestampRange(_), _) => None,
391            (Self::Template(_), _) => None,
392            (Self::ListTemplate(_), _) => None,
393        }
394    }
395
396    fn try_into_cmp(self, other: Self) -> Option<BoxedTemplateProperty<'a, Ordering>> {
397        match (self, other) {
398            (Self::Integer(lhs), Self::Integer(rhs)) => {
399                Some((lhs, rhs).map(|(l, r)| l.cmp(&r)).into_dyn())
400            }
401            (Self::Integer(lhs), Self::IntegerOpt(rhs)) => {
402                Some((lhs, rhs).map(|(l, r)| Some(l).cmp(&r)).into_dyn())
403            }
404            (Self::IntegerOpt(lhs), Self::Integer(rhs)) => {
405                Some((lhs, rhs).map(|(l, r)| l.cmp(&Some(r))).into_dyn())
406            }
407            (Self::IntegerOpt(lhs), Self::IntegerOpt(rhs)) => {
408                Some((lhs, rhs).map(|(l, r)| l.cmp(&r)).into_dyn())
409            }
410            (Self::String(_), _) => None,
411            (Self::StringList(_), _) => None,
412            (Self::Boolean(_), _) => None,
413            (Self::Integer(_), _) => None,
414            (Self::IntegerOpt(_), _) => None,
415            (Self::ConfigValue(_), _) => None,
416            (Self::Signature(_), _) => None,
417            (Self::Email(_), _) => None,
418            (Self::SizeHint(_), _) => None,
419            (Self::Timestamp(_), _) => None,
420            (Self::TimestampRange(_), _) => None,
421            (Self::Template(_), _) => None,
422            (Self::ListTemplate(_), _) => None,
423        }
424    }
425}
426
427/// Function that translates global function call node.
428// The lifetime parameter 'a could be replaced with for<'a> to keep the method
429// table away from a certain lifetime. That's technically more correct, but I
430// couldn't find an easy way to expand that to the core template methods, which
431// are defined for L: TemplateLanguage<'a>. That's why the build fn table is
432// bound to a named lifetime, and therefore can't be cached statically.
433pub type TemplateBuildFunctionFn<'a, L, P> =
434    fn(&L, &mut TemplateDiagnostics, &BuildContext<P>, &FunctionCallNode) -> TemplateParseResult<P>;
435
436type BuildMethodFn<'a, L, T, P> = fn(
437    &L,
438    &mut TemplateDiagnostics,
439    &BuildContext<P>,
440    T,
441    &FunctionCallNode,
442) -> TemplateParseResult<P>;
443
444/// Function that translates method call node of self type `T`.
445pub type TemplateBuildMethodFn<'a, L, T, P> = BuildMethodFn<'a, L, BoxedTemplateProperty<'a, T>, P>;
446
447/// Function that translates method call node of `Template`.
448pub type BuildTemplateMethodFn<'a, L, P> = BuildMethodFn<'a, L, Box<dyn Template + 'a>, P>;
449
450/// Function that translates method call node of `ListTemplate`.
451pub type BuildListTemplateMethodFn<'a, L, P> = BuildMethodFn<'a, L, Box<dyn ListTemplate + 'a>, P>;
452
453/// Table of functions that translate global function call node.
454pub type TemplateBuildFunctionFnMap<'a, L, P = <L as TemplateLanguage<'a>>::Property> =
455    HashMap<&'static str, TemplateBuildFunctionFn<'a, L, P>>;
456
457/// Table of functions that translate method call node of self type `T`.
458pub type TemplateBuildMethodFnMap<'a, L, T, P = <L as TemplateLanguage<'a>>::Property> =
459    HashMap<&'static str, TemplateBuildMethodFn<'a, L, T, P>>;
460
461/// Table of functions that translate method call node of `Template`.
462pub type BuildTemplateMethodFnMap<'a, L, P = <L as TemplateLanguage<'a>>::Property> =
463    HashMap<&'static str, BuildTemplateMethodFn<'a, L, P>>;
464
465/// Table of functions that translate method call node of `ListTemplate`.
466pub type BuildListTemplateMethodFnMap<'a, L, P = <L as TemplateLanguage<'a>>::Property> =
467    HashMap<&'static str, BuildListTemplateMethodFn<'a, L, P>>;
468
469/// Symbol table of functions and methods available in the core template.
470pub struct CoreTemplateBuildFnTable<'a, L: ?Sized, P = <L as TemplateLanguage<'a>>::Property> {
471    pub functions: TemplateBuildFunctionFnMap<'a, L, P>,
472    pub string_methods: TemplateBuildMethodFnMap<'a, L, String, P>,
473    pub string_list_methods: TemplateBuildMethodFnMap<'a, L, Vec<String>, P>,
474    pub boolean_methods: TemplateBuildMethodFnMap<'a, L, bool, P>,
475    pub integer_methods: TemplateBuildMethodFnMap<'a, L, i64, P>,
476    pub config_value_methods: TemplateBuildMethodFnMap<'a, L, ConfigValue, P>,
477    pub email_methods: TemplateBuildMethodFnMap<'a, L, Email, P>,
478    pub signature_methods: TemplateBuildMethodFnMap<'a, L, Signature, P>,
479    pub size_hint_methods: TemplateBuildMethodFnMap<'a, L, SizeHint, P>,
480    pub timestamp_methods: TemplateBuildMethodFnMap<'a, L, Timestamp, P>,
481    pub timestamp_range_methods: TemplateBuildMethodFnMap<'a, L, TimestampRange, P>,
482    pub template_methods: BuildTemplateMethodFnMap<'a, L, P>,
483    pub list_template_methods: BuildListTemplateMethodFnMap<'a, L, P>,
484}
485
486pub fn merge_fn_map<'s, F>(base: &mut HashMap<&'s str, F>, extension: HashMap<&'s str, F>) {
487    for (name, function) in extension {
488        if base.insert(name, function).is_some() {
489            panic!("Conflicting template definitions for '{name}' function");
490        }
491    }
492}
493
494impl<L: ?Sized, P> CoreTemplateBuildFnTable<'_, L, P> {
495    pub fn empty() -> Self {
496        Self {
497            functions: HashMap::new(),
498            string_methods: HashMap::new(),
499            string_list_methods: HashMap::new(),
500            boolean_methods: HashMap::new(),
501            integer_methods: HashMap::new(),
502            config_value_methods: HashMap::new(),
503            signature_methods: HashMap::new(),
504            email_methods: HashMap::new(),
505            size_hint_methods: HashMap::new(),
506            timestamp_methods: HashMap::new(),
507            timestamp_range_methods: HashMap::new(),
508            template_methods: HashMap::new(),
509            list_template_methods: HashMap::new(),
510        }
511    }
512
513    pub fn merge(&mut self, other: Self) {
514        let Self {
515            functions,
516            string_methods,
517            string_list_methods,
518            boolean_methods,
519            integer_methods,
520            config_value_methods,
521            signature_methods,
522            email_methods,
523            size_hint_methods,
524            timestamp_methods,
525            timestamp_range_methods,
526            template_methods,
527            list_template_methods,
528        } = other;
529
530        merge_fn_map(&mut self.functions, functions);
531        merge_fn_map(&mut self.string_methods, string_methods);
532        merge_fn_map(&mut self.string_list_methods, string_list_methods);
533        merge_fn_map(&mut self.boolean_methods, boolean_methods);
534        merge_fn_map(&mut self.integer_methods, integer_methods);
535        merge_fn_map(&mut self.config_value_methods, config_value_methods);
536        merge_fn_map(&mut self.signature_methods, signature_methods);
537        merge_fn_map(&mut self.email_methods, email_methods);
538        merge_fn_map(&mut self.size_hint_methods, size_hint_methods);
539        merge_fn_map(&mut self.timestamp_methods, timestamp_methods);
540        merge_fn_map(&mut self.timestamp_range_methods, timestamp_range_methods);
541        merge_fn_map(&mut self.template_methods, template_methods);
542        merge_fn_map(&mut self.list_template_methods, list_template_methods);
543    }
544}
545
546impl<'a, L> CoreTemplateBuildFnTable<'a, L, L::Property>
547where
548    L: TemplateLanguage<'a> + ?Sized,
549{
550    /// Creates new symbol table containing the builtin functions and methods.
551    pub fn builtin() -> Self {
552        Self {
553            functions: builtin_functions(),
554            string_methods: builtin_string_methods(),
555            string_list_methods: builtin_formattable_list_methods(),
556            boolean_methods: HashMap::new(),
557            integer_methods: HashMap::new(),
558            config_value_methods: builtin_config_value_methods(),
559            signature_methods: builtin_signature_methods(),
560            email_methods: builtin_email_methods(),
561            size_hint_methods: builtin_size_hint_methods(),
562            timestamp_methods: builtin_timestamp_methods(),
563            timestamp_range_methods: builtin_timestamp_range_methods(),
564            template_methods: HashMap::new(),
565            list_template_methods: builtin_list_template_methods(),
566        }
567    }
568
569    /// Translates the function call node `function` by using this symbol table.
570    pub fn build_function(
571        &self,
572        language: &L,
573        diagnostics: &mut TemplateDiagnostics,
574        build_ctx: &BuildContext<L::Property>,
575        function: &FunctionCallNode,
576    ) -> TemplateParseResult<L::Property> {
577        let table = &self.functions;
578        let build = template_parser::lookup_function(table, function)?;
579        build(language, diagnostics, build_ctx, function)
580    }
581
582    /// Applies the method call node `function` to the given `property` by using
583    /// this symbol table.
584    pub fn build_method(
585        &self,
586        language: &L,
587        diagnostics: &mut TemplateDiagnostics,
588        build_ctx: &BuildContext<L::Property>,
589        property: CoreTemplatePropertyKind<'a>,
590        function: &FunctionCallNode,
591    ) -> TemplateParseResult<L::Property> {
592        let type_name = property.type_name();
593        match property {
594            CoreTemplatePropertyKind::String(property) => {
595                let table = &self.string_methods;
596                let build = template_parser::lookup_method(type_name, table, function)?;
597                build(language, diagnostics, build_ctx, property, function)
598            }
599            CoreTemplatePropertyKind::StringList(property) => {
600                let table = &self.string_list_methods;
601                let build = template_parser::lookup_method(type_name, table, function)?;
602                build(language, diagnostics, build_ctx, property, function)
603            }
604            CoreTemplatePropertyKind::Boolean(property) => {
605                let table = &self.boolean_methods;
606                let build = template_parser::lookup_method(type_name, table, function)?;
607                build(language, diagnostics, build_ctx, property, function)
608            }
609            CoreTemplatePropertyKind::Integer(property) => {
610                let table = &self.integer_methods;
611                let build = template_parser::lookup_method(type_name, table, function)?;
612                build(language, diagnostics, build_ctx, property, function)
613            }
614            CoreTemplatePropertyKind::IntegerOpt(property) => {
615                let type_name = "Integer";
616                let table = &self.integer_methods;
617                let build = template_parser::lookup_method(type_name, table, function)?;
618                let inner_property = property.try_unwrap(type_name).into_dyn();
619                build(language, diagnostics, build_ctx, inner_property, function)
620            }
621            CoreTemplatePropertyKind::ConfigValue(property) => {
622                let table = &self.config_value_methods;
623                let build = template_parser::lookup_method(type_name, table, function)?;
624                build(language, diagnostics, build_ctx, property, function)
625            }
626            CoreTemplatePropertyKind::Signature(property) => {
627                let table = &self.signature_methods;
628                let build = template_parser::lookup_method(type_name, table, function)?;
629                build(language, diagnostics, build_ctx, property, function)
630            }
631            CoreTemplatePropertyKind::Email(property) => {
632                let table = &self.email_methods;
633                let build = template_parser::lookup_method(type_name, table, function)?;
634                build(language, diagnostics, build_ctx, property, function)
635            }
636            CoreTemplatePropertyKind::SizeHint(property) => {
637                let table = &self.size_hint_methods;
638                let build = template_parser::lookup_method(type_name, table, function)?;
639                build(language, diagnostics, build_ctx, property, function)
640            }
641            CoreTemplatePropertyKind::Timestamp(property) => {
642                let table = &self.timestamp_methods;
643                let build = template_parser::lookup_method(type_name, table, function)?;
644                build(language, diagnostics, build_ctx, property, function)
645            }
646            CoreTemplatePropertyKind::TimestampRange(property) => {
647                let table = &self.timestamp_range_methods;
648                let build = template_parser::lookup_method(type_name, table, function)?;
649                build(language, diagnostics, build_ctx, property, function)
650            }
651            CoreTemplatePropertyKind::Template(template) => {
652                let table = &self.template_methods;
653                let build = template_parser::lookup_method(type_name, table, function)?;
654                build(language, diagnostics, build_ctx, template, function)
655            }
656            CoreTemplatePropertyKind::ListTemplate(template) => {
657                let table = &self.list_template_methods;
658                let build = template_parser::lookup_method(type_name, table, function)?;
659                build(language, diagnostics, build_ctx, template, function)
660            }
661        }
662    }
663}
664
665/// Opaque struct that represents a template value.
666pub struct Expression<P> {
667    property: P,
668    labels: Vec<String>,
669}
670
671impl<P> Expression<P> {
672    fn unlabeled(property: P) -> Self {
673        let labels = vec![];
674        Self { property, labels }
675    }
676
677    fn with_label(property: P, label: impl Into<String>) -> Self {
678        let labels = vec![label.into()];
679        Self { property, labels }
680    }
681}
682
683impl<'a, P: CoreTemplatePropertyVar<'a>> Expression<P> {
684    pub fn type_name(&self) -> &'static str {
685        self.property.type_name()
686    }
687
688    pub fn try_into_boolean(self) -> Option<BoxedTemplateProperty<'a, bool>> {
689        self.property.try_into_boolean()
690    }
691
692    pub fn try_into_integer(self) -> Option<BoxedTemplateProperty<'a, i64>> {
693        self.property.try_into_integer()
694    }
695
696    pub fn try_into_stringify(self) -> Option<BoxedTemplateProperty<'a, String>> {
697        self.property.try_into_stringify()
698    }
699
700    pub fn try_into_serialize(self) -> Option<BoxedSerializeProperty<'a>> {
701        self.property.try_into_serialize()
702    }
703
704    pub fn try_into_template(self) -> Option<Box<dyn Template + 'a>> {
705        let template = self.property.try_into_template()?;
706        if self.labels.is_empty() {
707            Some(template)
708        } else {
709            Some(Box::new(LabelTemplate::new(template, Literal(self.labels))))
710        }
711    }
712
713    pub fn try_into_eq(self, other: Self) -> Option<BoxedTemplateProperty<'a, bool>> {
714        self.property.try_into_eq(other.property)
715    }
716
717    pub fn try_into_cmp(self, other: Self) -> Option<BoxedTemplateProperty<'a, Ordering>> {
718        self.property.try_into_cmp(other.property)
719    }
720}
721
722/// Environment (locals and self) in a stack frame.
723pub struct BuildContext<'i, P> {
724    /// Map of functions to create `L::Property`.
725    local_variables: HashMap<&'i str, &'i dyn Fn() -> P>,
726    /// Function to create `L::Property` representing `self`.
727    ///
728    /// This could be `local_variables["self"]`, but keyword lookup shouldn't be
729    /// overridden by a user-defined `self` variable.
730    self_variable: &'i dyn Fn() -> P,
731}
732
733fn build_keyword<'a, L: TemplateLanguage<'a> + ?Sized>(
734    language: &L,
735    diagnostics: &mut TemplateDiagnostics,
736    build_ctx: &BuildContext<L::Property>,
737    name: &str,
738    name_span: pest::Span<'_>,
739) -> TemplateParseResult<L::Property> {
740    // Keyword is a 0-ary method on the "self" property
741    let self_property = (build_ctx.self_variable)();
742    let function = FunctionCallNode {
743        name,
744        name_span,
745        args: vec![],
746        keyword_args: vec![],
747        args_span: name_span.end_pos().span(&name_span.end_pos()),
748    };
749    language
750        .build_method(diagnostics, build_ctx, self_property, &function)
751        .map_err(|err| match err.kind() {
752            TemplateParseErrorKind::NoSuchMethod { candidates, .. } => {
753                let kind = TemplateParseErrorKind::NoSuchKeyword {
754                    name: name.to_owned(),
755                    // TODO: filter methods by arity?
756                    candidates: candidates.clone(),
757                };
758                TemplateParseError::with_span(kind, name_span)
759            }
760            // Since keyword is a 0-ary method, any argument errors mean there's
761            // no such keyword.
762            TemplateParseErrorKind::InvalidArguments { .. } => {
763                let kind = TemplateParseErrorKind::NoSuchKeyword {
764                    name: name.to_owned(),
765                    // TODO: might be better to phrase the error differently
766                    candidates: vec![format!("self.{name}(..)")],
767                };
768                TemplateParseError::with_span(kind, name_span)
769            }
770            // The keyword function may fail with the other reasons.
771            _ => err,
772        })
773}
774
775fn build_unary_operation<'a, L: TemplateLanguage<'a> + ?Sized>(
776    language: &L,
777    diagnostics: &mut TemplateDiagnostics,
778    build_ctx: &BuildContext<L::Property>,
779    op: UnaryOp,
780    arg_node: &ExpressionNode,
781) -> TemplateParseResult<L::Property> {
782    match op {
783        UnaryOp::LogicalNot => {
784            let arg = expect_boolean_expression(language, diagnostics, build_ctx, arg_node)?;
785            Ok(arg.map(|v| !v).into_dyn_wrapped())
786        }
787        UnaryOp::Negate => {
788            let arg = expect_integer_expression(language, diagnostics, build_ctx, arg_node)?;
789            let out = arg.and_then(|v| {
790                v.checked_neg()
791                    .ok_or_else(|| TemplatePropertyError("Attempt to negate with overflow".into()))
792            });
793            Ok(out.into_dyn_wrapped())
794        }
795    }
796}
797
798fn build_binary_operation<'a, L: TemplateLanguage<'a> + ?Sized>(
799    language: &L,
800    diagnostics: &mut TemplateDiagnostics,
801    build_ctx: &BuildContext<L::Property>,
802    op: BinaryOp,
803    lhs_node: &ExpressionNode,
804    rhs_node: &ExpressionNode,
805    span: pest::Span<'_>,
806) -> TemplateParseResult<L::Property> {
807    match op {
808        BinaryOp::LogicalOr => {
809            let lhs = expect_boolean_expression(language, diagnostics, build_ctx, lhs_node)?;
810            let rhs = expect_boolean_expression(language, diagnostics, build_ctx, rhs_node)?;
811            let out = lhs.and_then(move |l| Ok(l || rhs.extract()?));
812            Ok(out.into_dyn_wrapped())
813        }
814        BinaryOp::LogicalAnd => {
815            let lhs = expect_boolean_expression(language, diagnostics, build_ctx, lhs_node)?;
816            let rhs = expect_boolean_expression(language, diagnostics, build_ctx, rhs_node)?;
817            let out = lhs.and_then(move |l| Ok(l && rhs.extract()?));
818            Ok(out.into_dyn_wrapped())
819        }
820        BinaryOp::Eq | BinaryOp::Ne => {
821            let lhs = build_expression(language, diagnostics, build_ctx, lhs_node)?;
822            let rhs = build_expression(language, diagnostics, build_ctx, rhs_node)?;
823            let lty = lhs.type_name();
824            let rty = rhs.type_name();
825            let eq = lhs.try_into_eq(rhs).ok_or_else(|| {
826                let message = format!("Cannot compare expressions of type `{lty}` and `{rty}`");
827                TemplateParseError::expression(message, span)
828            })?;
829            let out = match op {
830                BinaryOp::Eq => eq.into_dyn(),
831                BinaryOp::Ne => eq.map(|eq| !eq).into_dyn(),
832                _ => unreachable!(),
833            };
834            Ok(L::Property::wrap_property(out))
835        }
836        BinaryOp::Ge | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Lt => {
837            let lhs = build_expression(language, diagnostics, build_ctx, lhs_node)?;
838            let rhs = build_expression(language, diagnostics, build_ctx, rhs_node)?;
839            let lty = lhs.type_name();
840            let rty = rhs.type_name();
841            let cmp = lhs.try_into_cmp(rhs).ok_or_else(|| {
842                let message = format!("Cannot compare expressions of type `{lty}` and `{rty}`");
843                TemplateParseError::expression(message, span)
844            })?;
845            let out = match op {
846                BinaryOp::Ge => cmp.map(|ordering| ordering.is_ge()).into_dyn(),
847                BinaryOp::Gt => cmp.map(|ordering| ordering.is_gt()).into_dyn(),
848                BinaryOp::Le => cmp.map(|ordering| ordering.is_le()).into_dyn(),
849                BinaryOp::Lt => cmp.map(|ordering| ordering.is_lt()).into_dyn(),
850                _ => unreachable!(),
851            };
852            Ok(L::Property::wrap_property(out))
853        }
854        BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Rem => {
855            let lhs = expect_integer_expression(language, diagnostics, build_ctx, lhs_node)?;
856            let rhs = expect_integer_expression(language, diagnostics, build_ctx, rhs_node)?;
857            let build = |op: fn(i64, i64) -> Option<i64>, msg: fn(i64) -> &'static str| {
858                (lhs, rhs).and_then(move |(l, r)| {
859                    op(l, r).ok_or_else(|| TemplatePropertyError(msg(r).into()))
860                })
861            };
862            let out = match op {
863                BinaryOp::Add => build(i64::checked_add, |_| "Attempt to add with overflow"),
864                BinaryOp::Sub => build(i64::checked_sub, |_| "Attempt to subtract with overflow"),
865                BinaryOp::Mul => build(i64::checked_mul, |_| "Attempt to multiply with overflow"),
866                BinaryOp::Div => build(i64::checked_div, |r| {
867                    if r == 0 {
868                        "Attempt to divide by zero"
869                    } else {
870                        "Attempt to divide with overflow"
871                    }
872                }),
873                BinaryOp::Rem => build(i64::checked_rem, |r| {
874                    if r == 0 {
875                        "Attempt to divide by zero"
876                    } else {
877                        "Attempt to divide with overflow"
878                    }
879                }),
880                _ => unreachable!(),
881            };
882            Ok(out.into_dyn_wrapped())
883        }
884    }
885}
886
887fn builtin_string_methods<'a, L: TemplateLanguage<'a> + ?Sized>()
888-> TemplateBuildMethodFnMap<'a, L, String> {
889    // Not using maplit::hashmap!{} or custom declarative macro here because
890    // code completion inside macro is quite restricted.
891    let mut map = TemplateBuildMethodFnMap::<L, String>::new();
892    map.insert(
893        "len",
894        |_language, _diagnostics, _build_ctx, self_property, function| {
895            function.expect_no_arguments()?;
896            let out_property = self_property.and_then(|s| Ok(i64::try_from(s.len())?));
897            Ok(out_property.into_dyn_wrapped())
898        },
899    );
900    map.insert(
901        "contains",
902        |language, diagnostics, build_ctx, self_property, function| {
903            let [needle_node] = function.expect_exact_arguments()?;
904            // TODO: or .try_into_string() to disable implicit type cast?
905            let needle_property =
906                expect_stringify_expression(language, diagnostics, build_ctx, needle_node)?;
907            let out_property = (self_property, needle_property)
908                .map(|(haystack, needle)| haystack.contains(&needle));
909            Ok(out_property.into_dyn_wrapped())
910        },
911    );
912    map.insert(
913        "match",
914        |_language, _diagnostics, _build_ctx, self_property, function| {
915            let [needle_node] = function.expect_exact_arguments()?;
916            let needle = template_parser::expect_string_pattern(needle_node)?;
917            let regex = needle.to_regex();
918
919            let out_property = self_property.and_then(move |haystack| {
920                if let Some(m) = regex.find(haystack.as_bytes()) {
921                    Ok(str::from_utf8(m.as_bytes())?.to_owned())
922                } else {
923                    // We don't have optional strings, so empty string is the
924                    // right null value.
925                    Ok(String::new())
926                }
927            });
928            Ok(out_property.into_dyn_wrapped())
929        },
930    );
931    map.insert(
932        "starts_with",
933        |language, diagnostics, build_ctx, self_property, function| {
934            let [needle_node] = function.expect_exact_arguments()?;
935            let needle_property =
936                expect_stringify_expression(language, diagnostics, build_ctx, needle_node)?;
937            let out_property = (self_property, needle_property)
938                .map(|(haystack, needle)| haystack.starts_with(&needle));
939            Ok(out_property.into_dyn_wrapped())
940        },
941    );
942    map.insert(
943        "ends_with",
944        |language, diagnostics, build_ctx, self_property, function| {
945            let [needle_node] = function.expect_exact_arguments()?;
946            let needle_property =
947                expect_stringify_expression(language, diagnostics, build_ctx, needle_node)?;
948            let out_property = (self_property, needle_property)
949                .map(|(haystack, needle)| haystack.ends_with(&needle));
950            Ok(out_property.into_dyn_wrapped())
951        },
952    );
953    map.insert(
954        "remove_prefix",
955        |language, diagnostics, build_ctx, self_property, function| {
956            let [needle_node] = function.expect_exact_arguments()?;
957            let needle_property =
958                expect_stringify_expression(language, diagnostics, build_ctx, needle_node)?;
959            let out_property = (self_property, needle_property).map(|(haystack, needle)| {
960                haystack
961                    .strip_prefix(&needle)
962                    .map(ToOwned::to_owned)
963                    .unwrap_or(haystack)
964            });
965            Ok(out_property.into_dyn_wrapped())
966        },
967    );
968    map.insert(
969        "remove_suffix",
970        |language, diagnostics, build_ctx, self_property, function| {
971            let [needle_node] = function.expect_exact_arguments()?;
972            let needle_property =
973                expect_stringify_expression(language, diagnostics, build_ctx, needle_node)?;
974            let out_property = (self_property, needle_property).map(|(haystack, needle)| {
975                haystack
976                    .strip_suffix(&needle)
977                    .map(ToOwned::to_owned)
978                    .unwrap_or(haystack)
979            });
980            Ok(out_property.into_dyn_wrapped())
981        },
982    );
983    map.insert(
984        "trim",
985        |_language, _diagnostics, _build_ctx, self_property, function| {
986            function.expect_no_arguments()?;
987            let out_property = self_property.map(|s| s.trim().to_owned());
988            Ok(out_property.into_dyn_wrapped())
989        },
990    );
991    map.insert(
992        "trim_start",
993        |_language, _diagnostics, _build_ctx, self_property, function| {
994            function.expect_no_arguments()?;
995            let out_property = self_property.map(|s| s.trim_start().to_owned());
996            Ok(out_property.into_dyn_wrapped())
997        },
998    );
999    map.insert(
1000        "trim_end",
1001        |_language, _diagnostics, _build_ctx, self_property, function| {
1002            function.expect_no_arguments()?;
1003            let out_property = self_property.map(|s| s.trim_end().to_owned());
1004            Ok(out_property.into_dyn_wrapped())
1005        },
1006    );
1007    map.insert(
1008        "substr",
1009        |language, diagnostics, build_ctx, self_property, function| {
1010            let [start_idx, end_idx] = function.expect_exact_arguments()?;
1011            let start_idx_property =
1012                expect_isize_expression(language, diagnostics, build_ctx, start_idx)?;
1013            let end_idx_property =
1014                expect_isize_expression(language, diagnostics, build_ctx, end_idx)?;
1015            let out_property = (self_property, start_idx_property, end_idx_property).map(
1016                |(s, start_idx, end_idx)| {
1017                    let start_idx = string_index_to_char_boundary(&s, start_idx);
1018                    let end_idx = string_index_to_char_boundary(&s, end_idx);
1019                    s.get(start_idx..end_idx).unwrap_or_default().to_owned()
1020                },
1021            );
1022            Ok(out_property.into_dyn_wrapped())
1023        },
1024    );
1025    map.insert(
1026        "first_line",
1027        |_language, _diagnostics, _build_ctx, self_property, function| {
1028            function.expect_no_arguments()?;
1029            let out_property =
1030                self_property.map(|s| s.lines().next().unwrap_or_default().to_string());
1031            Ok(out_property.into_dyn_wrapped())
1032        },
1033    );
1034    map.insert(
1035        "lines",
1036        |_language, _diagnostics, _build_ctx, self_property, function| {
1037            function.expect_no_arguments()?;
1038            let out_property = self_property.map(|s| s.lines().map(|l| l.to_owned()).collect_vec());
1039            Ok(out_property.into_dyn_wrapped())
1040        },
1041    );
1042    map.insert(
1043        "upper",
1044        |_language, _diagnostics, _build_ctx, self_property, function| {
1045            function.expect_no_arguments()?;
1046            let out_property = self_property.map(|s| s.to_uppercase());
1047            Ok(out_property.into_dyn_wrapped())
1048        },
1049    );
1050    map.insert(
1051        "lower",
1052        |_language, _diagnostics, _build_ctx, self_property, function| {
1053            function.expect_no_arguments()?;
1054            let out_property = self_property.map(|s| s.to_lowercase());
1055            Ok(out_property.into_dyn_wrapped())
1056        },
1057    );
1058    map.insert(
1059        "escape_json",
1060        |_language, _diagnostics, _build_ctx, self_property, function| {
1061            function.expect_no_arguments()?;
1062            let out_property = self_property.map(|s| serde_json::to_string(&s).unwrap());
1063            Ok(out_property.into_dyn_wrapped())
1064        },
1065    );
1066    map.insert(
1067        "replace",
1068        |language, diagnostics, build_ctx, self_property, function| {
1069            let ([pattern_node, replacement_node], [limit_node]) = function.expect_arguments()?;
1070            let pattern = template_parser::expect_string_pattern(pattern_node)?;
1071            let replacement_property =
1072                expect_stringify_expression(language, diagnostics, build_ctx, replacement_node)?;
1073
1074            let regex = pattern.to_regex();
1075
1076            if let Some(limit_node) = limit_node {
1077                let limit_property =
1078                    expect_usize_expression(language, diagnostics, build_ctx, limit_node)?;
1079                let out_property = (self_property, replacement_property, limit_property).and_then(
1080                    move |(haystack, replacement, limit)| {
1081                        if limit == 0 {
1082                            // We need to special-case zero because regex.replacen(_, 0, _) replaces
1083                            // all occurrences, and we want zero to mean no occurrences are
1084                            // replaced.
1085                            Ok(haystack)
1086                        } else {
1087                            let haystack_bytes = haystack.as_bytes();
1088                            let replace_bytes = replacement.as_bytes();
1089                            let result = regex.replacen(haystack_bytes, limit, replace_bytes);
1090                            Ok(str::from_utf8(&result)?.to_owned())
1091                        }
1092                    },
1093                );
1094                Ok(out_property.into_dyn_wrapped())
1095            } else {
1096                let out_property = (self_property, replacement_property).and_then(
1097                    move |(haystack, replacement)| {
1098                        let haystack_bytes = haystack.as_bytes();
1099                        let replace_bytes = replacement.as_bytes();
1100                        let result = regex.replace_all(haystack_bytes, replace_bytes);
1101                        Ok(str::from_utf8(&result)?.to_owned())
1102                    },
1103                );
1104                Ok(out_property.into_dyn_wrapped())
1105            }
1106        },
1107    );
1108    map
1109}
1110
1111/// Clamps and aligns the given index `i` to char boundary.
1112///
1113/// Negative index counts from the end. If the index isn't at a char boundary,
1114/// it will be rounded towards 0 (left or right depending on the sign.)
1115fn string_index_to_char_boundary(s: &str, i: isize) -> usize {
1116    // TODO: use floor/ceil_char_boundary() if get stabilized
1117    let magnitude = i.unsigned_abs();
1118    if i < 0 {
1119        let p = s.len().saturating_sub(magnitude);
1120        (p..=s.len()).find(|&p| s.is_char_boundary(p)).unwrap()
1121    } else {
1122        let p = magnitude.min(s.len());
1123        (0..=p).rev().find(|&p| s.is_char_boundary(p)).unwrap()
1124    }
1125}
1126
1127fn builtin_config_value_methods<'a, L: TemplateLanguage<'a> + ?Sized>()
1128-> TemplateBuildMethodFnMap<'a, L, ConfigValue> {
1129    fn extract<'de, T: Deserialize<'de>>(value: ConfigValue) -> Result<T, TemplatePropertyError> {
1130        T::deserialize(value.into_deserializer())
1131            // map to err.message() because TomlError appends newline to it
1132            .map_err(|err| TemplatePropertyError(err.message().into()))
1133    }
1134
1135    // Not using maplit::hashmap!{} or custom declarative macro here because
1136    // code completion inside macro is quite restricted.
1137    let mut map = TemplateBuildMethodFnMap::<L, ConfigValue>::new();
1138    // These methods are called "as_<type>", not "to_<type>" to clarify that
1139    // they'll never convert types (e.g. integer to string.) Since templater
1140    // doesn't provide binding syntax, there's no need to distinguish between
1141    // reference and consuming access.
1142    map.insert(
1143        "as_boolean",
1144        |_language, _diagnostics, _build_ctx, self_property, function| {
1145            function.expect_no_arguments()?;
1146            let out_property = self_property.and_then(extract::<bool>);
1147            Ok(out_property.into_dyn_wrapped())
1148        },
1149    );
1150    map.insert(
1151        "as_integer",
1152        |_language, _diagnostics, _build_ctx, self_property, function| {
1153            function.expect_no_arguments()?;
1154            let out_property = self_property.and_then(extract::<i64>);
1155            Ok(out_property.into_dyn_wrapped())
1156        },
1157    );
1158    map.insert(
1159        "as_string",
1160        |_language, _diagnostics, _build_ctx, self_property, function| {
1161            function.expect_no_arguments()?;
1162            let out_property = self_property.and_then(extract::<String>);
1163            Ok(out_property.into_dyn_wrapped())
1164        },
1165    );
1166    map.insert(
1167        "as_string_list",
1168        |_language, _diagnostics, _build_ctx, self_property, function| {
1169            function.expect_no_arguments()?;
1170            let out_property = self_property.and_then(extract::<Vec<String>>);
1171            Ok(out_property.into_dyn_wrapped())
1172        },
1173    );
1174    // TODO: add is_<type>() -> Boolean?
1175    // TODO: add .get(key) -> ConfigValue or Option<ConfigValue>?
1176    map
1177}
1178
1179fn builtin_signature_methods<'a, L: TemplateLanguage<'a> + ?Sized>()
1180-> TemplateBuildMethodFnMap<'a, L, Signature> {
1181    // Not using maplit::hashmap!{} or custom declarative macro here because
1182    // code completion inside macro is quite restricted.
1183    let mut map = TemplateBuildMethodFnMap::<L, Signature>::new();
1184    map.insert(
1185        "name",
1186        |_language, _diagnostics, _build_ctx, self_property, function| {
1187            function.expect_no_arguments()?;
1188            let out_property = self_property.map(|signature| signature.name);
1189            Ok(out_property.into_dyn_wrapped())
1190        },
1191    );
1192    map.insert(
1193        "email",
1194        |_language, _diagnostics, _build_ctx, self_property, function| {
1195            function.expect_no_arguments()?;
1196            let out_property = self_property.map(|signature| Email(signature.email));
1197            Ok(out_property.into_dyn_wrapped())
1198        },
1199    );
1200    map.insert(
1201        "timestamp",
1202        |_language, _diagnostics, _build_ctx, self_property, function| {
1203            function.expect_no_arguments()?;
1204            let out_property = self_property.map(|signature| signature.timestamp);
1205            Ok(out_property.into_dyn_wrapped())
1206        },
1207    );
1208    map
1209}
1210
1211fn builtin_email_methods<'a, L: TemplateLanguage<'a> + ?Sized>()
1212-> TemplateBuildMethodFnMap<'a, L, Email> {
1213    // Not using maplit::hashmap!{} or custom declarative macro here because
1214    // code completion inside macro is quite restricted.
1215    let mut map = TemplateBuildMethodFnMap::<L, Email>::new();
1216    map.insert(
1217        "local",
1218        |_language, _diagnostics, _build_ctx, self_property, function| {
1219            function.expect_no_arguments()?;
1220            let out_property = self_property.map(|email| {
1221                let (local, _) = text_util::split_email(&email.0);
1222                local.to_owned()
1223            });
1224            Ok(out_property.into_dyn_wrapped())
1225        },
1226    );
1227    map.insert(
1228        "domain",
1229        |_language, _diagnostics, _build_ctx, self_property, function| {
1230            function.expect_no_arguments()?;
1231            let out_property = self_property.map(|email| {
1232                let (_, domain) = text_util::split_email(&email.0);
1233                domain.unwrap_or_default().to_owned()
1234            });
1235            Ok(out_property.into_dyn_wrapped())
1236        },
1237    );
1238    map
1239}
1240
1241fn builtin_size_hint_methods<'a, L: TemplateLanguage<'a> + ?Sized>()
1242-> TemplateBuildMethodFnMap<'a, L, SizeHint> {
1243    // Not using maplit::hashmap!{} or custom declarative macro here because
1244    // code completion inside macro is quite restricted.
1245    let mut map = TemplateBuildMethodFnMap::<L, SizeHint>::new();
1246    map.insert(
1247        "lower",
1248        |_language, _diagnostics, _build_ctx, self_property, function| {
1249            function.expect_no_arguments()?;
1250            let out_property = self_property.and_then(|(lower, _)| Ok(i64::try_from(lower)?));
1251            Ok(out_property.into_dyn_wrapped())
1252        },
1253    );
1254    map.insert(
1255        "upper",
1256        |_language, _diagnostics, _build_ctx, self_property, function| {
1257            function.expect_no_arguments()?;
1258            let out_property =
1259                self_property.and_then(|(_, upper)| Ok(upper.map(i64::try_from).transpose()?));
1260            Ok(out_property.into_dyn_wrapped())
1261        },
1262    );
1263    map.insert(
1264        "exact",
1265        |_language, _diagnostics, _build_ctx, self_property, function| {
1266            function.expect_no_arguments()?;
1267            let out_property = self_property.and_then(|(lower, upper)| {
1268                let exact = (Some(lower) == upper).then_some(lower);
1269                Ok(exact.map(i64::try_from).transpose()?)
1270            });
1271            Ok(out_property.into_dyn_wrapped())
1272        },
1273    );
1274    map.insert(
1275        "zero",
1276        |_language, _diagnostics, _build_ctx, self_property, function| {
1277            function.expect_no_arguments()?;
1278            let out_property = self_property.map(|(_, upper)| upper == Some(0));
1279            Ok(out_property.into_dyn_wrapped())
1280        },
1281    );
1282    map
1283}
1284
1285fn builtin_timestamp_methods<'a, L: TemplateLanguage<'a> + ?Sized>()
1286-> TemplateBuildMethodFnMap<'a, L, Timestamp> {
1287    // Not using maplit::hashmap!{} or custom declarative macro here because
1288    // code completion inside macro is quite restricted.
1289    let mut map = TemplateBuildMethodFnMap::<L, Timestamp>::new();
1290    map.insert(
1291        "ago",
1292        |_language, _diagnostics, _build_ctx, self_property, function| {
1293            function.expect_no_arguments()?;
1294            let now = Timestamp::now();
1295            let format = timeago::Formatter::new();
1296            let out_property = self_property.and_then(move |timestamp| {
1297                Ok(time_util::format_duration(&timestamp, &now, &format)?)
1298            });
1299            Ok(out_property.into_dyn_wrapped())
1300        },
1301    );
1302    map.insert(
1303        "format",
1304        |_language, diagnostics, _build_ctx, self_property, function| {
1305            // No dynamic string is allowed as the templater has no runtime error type.
1306            let [format_node] = function.expect_exact_arguments()?;
1307            let format =
1308                template_parser::catch_aliases(diagnostics, format_node, |_diagnostics, node| {
1309                    let format = template_parser::expect_string_literal(node)?;
1310                    time_util::FormattingItems::parse(format).ok_or_else(|| {
1311                        TemplateParseError::expression("Invalid time format", node.span)
1312                    })
1313                })?
1314                .into_owned();
1315            let out_property = self_property.and_then(move |timestamp| {
1316                Ok(time_util::format_absolute_timestamp_with(
1317                    &timestamp, &format,
1318                )?)
1319            });
1320            Ok(out_property.into_dyn_wrapped())
1321        },
1322    );
1323    map.insert(
1324        "utc",
1325        |_language, _diagnostics, _build_ctx, self_property, function| {
1326            function.expect_no_arguments()?;
1327            let out_property = self_property.map(|mut timestamp| {
1328                timestamp.tz_offset = 0;
1329                timestamp
1330            });
1331            Ok(out_property.into_dyn_wrapped())
1332        },
1333    );
1334    map.insert(
1335        "local",
1336        |_language, _diagnostics, _build_ctx, self_property, function| {
1337            function.expect_no_arguments()?;
1338            let tz_offset = std::env::var("JJ_TZ_OFFSET_MINS")
1339                .ok()
1340                .and_then(|tz_string| tz_string.parse::<i32>().ok())
1341                .unwrap_or_else(|| chrono::Local::now().offset().local_minus_utc() / 60);
1342            let out_property = self_property.map(move |mut timestamp| {
1343                timestamp.tz_offset = tz_offset;
1344                timestamp
1345            });
1346            Ok(out_property.into_dyn_wrapped())
1347        },
1348    );
1349    map.insert(
1350        "after",
1351        |_language, diagnostics, _build_ctx, self_property, function| {
1352            let [date_pattern_node] = function.expect_exact_arguments()?;
1353            let now = chrono::Local::now();
1354            let date_pattern = template_parser::catch_aliases(
1355                diagnostics,
1356                date_pattern_node,
1357                |_diagnostics, node| {
1358                    let date_pattern = template_parser::expect_string_literal(node)?;
1359                    DatePattern::from_str_kind(date_pattern, function.name, now).map_err(|err| {
1360                        TemplateParseError::expression("Invalid date pattern", node.span)
1361                            .with_source(err)
1362                    })
1363                },
1364            )?;
1365            let out_property = self_property.map(move |timestamp| date_pattern.matches(&timestamp));
1366            Ok(out_property.into_dyn_wrapped())
1367        },
1368    );
1369    map.insert("before", map["after"]);
1370    map
1371}
1372
1373fn builtin_timestamp_range_methods<'a, L: TemplateLanguage<'a> + ?Sized>()
1374-> TemplateBuildMethodFnMap<'a, L, TimestampRange> {
1375    // Not using maplit::hashmap!{} or custom declarative macro here because
1376    // code completion inside macro is quite restricted.
1377    let mut map = TemplateBuildMethodFnMap::<L, TimestampRange>::new();
1378    map.insert(
1379        "start",
1380        |_language, _diagnostics, _build_ctx, self_property, function| {
1381            function.expect_no_arguments()?;
1382            let out_property = self_property.map(|time_range| time_range.start);
1383            Ok(out_property.into_dyn_wrapped())
1384        },
1385    );
1386    map.insert(
1387        "end",
1388        |_language, _diagnostics, _build_ctx, self_property, function| {
1389            function.expect_no_arguments()?;
1390            let out_property = self_property.map(|time_range| time_range.end);
1391            Ok(out_property.into_dyn_wrapped())
1392        },
1393    );
1394    map.insert(
1395        "duration",
1396        |_language, _diagnostics, _build_ctx, self_property, function| {
1397            function.expect_no_arguments()?;
1398            // TODO: Introduce duration type, and move formatting to it.
1399            let out_property = self_property.and_then(|time_range| {
1400                let mut f = timeago::Formatter::new();
1401                f.min_unit(timeago::TimeUnit::Microseconds).ago("");
1402                let duration = time_util::format_duration(&time_range.start, &time_range.end, &f)?;
1403                if duration == "now" {
1404                    Ok("less than a microsecond".to_owned())
1405                } else {
1406                    Ok(duration)
1407                }
1408            });
1409            Ok(out_property.into_dyn_wrapped())
1410        },
1411    );
1412    map
1413}
1414
1415fn builtin_list_template_methods<'a, L: TemplateLanguage<'a> + ?Sized>()
1416-> BuildListTemplateMethodFnMap<'a, L> {
1417    // Not using maplit::hashmap!{} or custom declarative macro here because
1418    // code completion inside macro is quite restricted.
1419    let mut map = BuildListTemplateMethodFnMap::<L>::new();
1420    map.insert(
1421        "join",
1422        |language, diagnostics, build_ctx, self_template, function| {
1423            let [separator_node] = function.expect_exact_arguments()?;
1424            let separator =
1425                expect_template_expression(language, diagnostics, build_ctx, separator_node)?;
1426            Ok(L::Property::wrap_template(self_template.join(separator)))
1427        },
1428    );
1429    map
1430}
1431
1432/// Creates new symbol table for printable list property.
1433pub fn builtin_formattable_list_methods<'a, L, O>() -> TemplateBuildMethodFnMap<'a, L, Vec<O>>
1434where
1435    L: TemplateLanguage<'a> + ?Sized,
1436    L::Property: WrapTemplateProperty<'a, O> + WrapTemplateProperty<'a, Vec<O>>,
1437    O: Template + Clone + 'a,
1438{
1439    let mut map = builtin_unformattable_list_methods::<L, O>();
1440    map.insert(
1441        "join",
1442        |language, diagnostics, build_ctx, self_property, function| {
1443            let [separator_node] = function.expect_exact_arguments()?;
1444            let separator =
1445                expect_template_expression(language, diagnostics, build_ctx, separator_node)?;
1446            let template =
1447                ListPropertyTemplate::new(self_property, separator, |formatter, item| {
1448                    item.format(formatter)
1449                });
1450            Ok(L::Property::wrap_template(Box::new(template)))
1451        },
1452    );
1453    map
1454}
1455
1456/// Creates new symbol table for unprintable list property.
1457pub fn builtin_unformattable_list_methods<'a, L, O>() -> TemplateBuildMethodFnMap<'a, L, Vec<O>>
1458where
1459    L: TemplateLanguage<'a> + ?Sized,
1460    L::Property: WrapTemplateProperty<'a, O> + WrapTemplateProperty<'a, Vec<O>>,
1461    O: Clone + 'a,
1462{
1463    // Not using maplit::hashmap!{} or custom declarative macro here because
1464    // code completion inside macro is quite restricted.
1465    let mut map = TemplateBuildMethodFnMap::<L, Vec<O>>::new();
1466    map.insert(
1467        "len",
1468        |_language, _diagnostics, _build_ctx, self_property, function| {
1469            function.expect_no_arguments()?;
1470            let out_property = self_property.and_then(|items| Ok(i64::try_from(items.len())?));
1471            Ok(out_property.into_dyn_wrapped())
1472        },
1473    );
1474    map.insert(
1475        "filter",
1476        |language, diagnostics, build_ctx, self_property, function| {
1477            let out_property: BoxedTemplateProperty<'a, Vec<O>> =
1478                build_filter_operation(language, diagnostics, build_ctx, self_property, function)?;
1479            Ok(L::Property::wrap_property(out_property))
1480        },
1481    );
1482    map.insert(
1483        "map",
1484        |language, diagnostics, build_ctx, self_property, function| {
1485            let template =
1486                build_map_operation(language, diagnostics, build_ctx, self_property, function)?;
1487            Ok(L::Property::wrap_list_template(template))
1488        },
1489    );
1490    map.insert(
1491        "any",
1492        |language, diagnostics, build_ctx, self_property, function| {
1493            let out_property =
1494                build_any_operation(language, diagnostics, build_ctx, self_property, function)?;
1495            Ok(out_property.into_dyn_wrapped())
1496        },
1497    );
1498    map.insert(
1499        "all",
1500        |language, diagnostics, build_ctx, self_property, function| {
1501            let out_property =
1502                build_all_operation(language, diagnostics, build_ctx, self_property, function)?;
1503            Ok(out_property.into_dyn_wrapped())
1504        },
1505    );
1506    map
1507}
1508
1509/// Builds expression that extracts iterable property and filters its items.
1510fn build_filter_operation<'a, L, O, P, B>(
1511    language: &L,
1512    diagnostics: &mut TemplateDiagnostics,
1513    build_ctx: &BuildContext<L::Property>,
1514    self_property: P,
1515    function: &FunctionCallNode,
1516) -> TemplateParseResult<BoxedTemplateProperty<'a, B>>
1517where
1518    L: TemplateLanguage<'a> + ?Sized,
1519    L::Property: WrapTemplateProperty<'a, O>,
1520    P: TemplateProperty + 'a,
1521    P::Output: IntoIterator<Item = O>,
1522    O: Clone + 'a,
1523    B: FromIterator<O>,
1524{
1525    let [lambda_node] = function.expect_exact_arguments()?;
1526    let item_placeholder = PropertyPlaceholder::new();
1527    let item_predicate =
1528        template_parser::catch_aliases(diagnostics, lambda_node, |diagnostics, node| {
1529            let lambda = template_parser::expect_lambda(node)?;
1530            build_lambda_expression(
1531                build_ctx,
1532                lambda,
1533                &[&|| item_placeholder.clone().into_dyn_wrapped()],
1534                |build_ctx, body| expect_boolean_expression(language, diagnostics, build_ctx, body),
1535            )
1536        })?;
1537    let out_property = self_property.and_then(move |items| {
1538        items
1539            .into_iter()
1540            .filter_map(|item| {
1541                // Evaluate predicate with the current item
1542                item_placeholder.set(item);
1543                let result = item_predicate.extract();
1544                let item = item_placeholder.take().unwrap();
1545                result.map(|pred| pred.then_some(item)).transpose()
1546            })
1547            .collect()
1548    });
1549    Ok(out_property.into_dyn())
1550}
1551
1552/// Builds expression that extracts iterable property and applies template to
1553/// each item.
1554fn build_map_operation<'a, L, O, P>(
1555    language: &L,
1556    diagnostics: &mut TemplateDiagnostics,
1557    build_ctx: &BuildContext<L::Property>,
1558    self_property: P,
1559    function: &FunctionCallNode,
1560) -> TemplateParseResult<Box<dyn ListTemplate + 'a>>
1561where
1562    L: TemplateLanguage<'a> + ?Sized,
1563    L::Property: WrapTemplateProperty<'a, O>,
1564    P: TemplateProperty + 'a,
1565    P::Output: IntoIterator<Item = O>,
1566    O: Clone + 'a,
1567{
1568    let [lambda_node] = function.expect_exact_arguments()?;
1569    let item_placeholder = PropertyPlaceholder::new();
1570    let item_template =
1571        template_parser::catch_aliases(diagnostics, lambda_node, |diagnostics, node| {
1572            let lambda = template_parser::expect_lambda(node)?;
1573            build_lambda_expression(
1574                build_ctx,
1575                lambda,
1576                &[&|| item_placeholder.clone().into_dyn_wrapped()],
1577                |build_ctx, body| {
1578                    expect_template_expression(language, diagnostics, build_ctx, body)
1579                },
1580            )
1581        })?;
1582    let list_template = ListPropertyTemplate::new(
1583        self_property,
1584        Literal(" "), // separator
1585        move |formatter, item| {
1586            item_placeholder.with_value(item, || item_template.format(formatter))
1587        },
1588    );
1589    Ok(Box::new(list_template))
1590}
1591
1592/// Builds expression that checks if any item in the list satisfies the
1593/// predicate.
1594fn build_any_operation<'a, L, O, P>(
1595    language: &L,
1596    diagnostics: &mut TemplateDiagnostics,
1597    build_ctx: &BuildContext<L::Property>,
1598    self_property: P,
1599    function: &FunctionCallNode,
1600) -> TemplateParseResult<BoxedTemplateProperty<'a, bool>>
1601where
1602    L: TemplateLanguage<'a> + ?Sized,
1603    L::Property: WrapTemplateProperty<'a, O>,
1604    P: TemplateProperty + 'a,
1605    P::Output: IntoIterator<Item = O>,
1606    O: Clone + 'a,
1607{
1608    let [lambda_node] = function.expect_exact_arguments()?;
1609    let item_placeholder = PropertyPlaceholder::new();
1610    let item_predicate =
1611        template_parser::catch_aliases(diagnostics, lambda_node, |diagnostics, node| {
1612            let lambda = template_parser::expect_lambda(node)?;
1613            build_lambda_expression(
1614                build_ctx,
1615                lambda,
1616                &[&|| item_placeholder.clone().into_dyn_wrapped()],
1617                |build_ctx, body| expect_boolean_expression(language, diagnostics, build_ctx, body),
1618            )
1619        })?;
1620
1621    let out_property = self_property.and_then(move |items| {
1622        items
1623            .into_iter()
1624            .map(|item| item_placeholder.with_value(item, || item_predicate.extract()))
1625            .process_results(|mut predicates| predicates.any(|p| p))
1626    });
1627    Ok(out_property.into_dyn())
1628}
1629
1630/// Builds expression that checks if all items in the list satisfy the
1631/// predicate.
1632fn build_all_operation<'a, L, O, P>(
1633    language: &L,
1634    diagnostics: &mut TemplateDiagnostics,
1635    build_ctx: &BuildContext<L::Property>,
1636    self_property: P,
1637    function: &FunctionCallNode,
1638) -> TemplateParseResult<BoxedTemplateProperty<'a, bool>>
1639where
1640    L: TemplateLanguage<'a> + ?Sized,
1641    L::Property: WrapTemplateProperty<'a, O>,
1642    P: TemplateProperty + 'a,
1643    P::Output: IntoIterator<Item = O>,
1644    O: Clone + 'a,
1645{
1646    let [lambda_node] = function.expect_exact_arguments()?;
1647    let item_placeholder = PropertyPlaceholder::new();
1648    let item_predicate =
1649        template_parser::catch_aliases(diagnostics, lambda_node, |diagnostics, node| {
1650            let lambda = template_parser::expect_lambda(node)?;
1651            build_lambda_expression(
1652                build_ctx,
1653                lambda,
1654                &[&|| item_placeholder.clone().into_dyn_wrapped()],
1655                |build_ctx, body| expect_boolean_expression(language, diagnostics, build_ctx, body),
1656            )
1657        })?;
1658
1659    let out_property = self_property.and_then(move |items| {
1660        items
1661            .into_iter()
1662            .map(|item| item_placeholder.with_value(item, || item_predicate.extract()))
1663            .process_results(|mut predicates| predicates.all(|p| p))
1664    });
1665    Ok(out_property.into_dyn())
1666}
1667
1668/// Builds lambda expression to be evaluated with the provided arguments.
1669/// `arg_fns` is usually an array of wrapped [`PropertyPlaceholder`]s.
1670fn build_lambda_expression<'i, P, T>(
1671    build_ctx: &BuildContext<'i, P>,
1672    lambda: &LambdaNode<'i>,
1673    arg_fns: &[&'i dyn Fn() -> P],
1674    build_body: impl FnOnce(&BuildContext<'i, P>, &ExpressionNode<'i>) -> TemplateParseResult<T>,
1675) -> TemplateParseResult<T> {
1676    if lambda.params.len() != arg_fns.len() {
1677        return Err(TemplateParseError::expression(
1678            format!("Expected {} lambda parameters", arg_fns.len()),
1679            lambda.params_span,
1680        ));
1681    }
1682    let mut local_variables = build_ctx.local_variables.clone();
1683    local_variables.extend(iter::zip(&lambda.params, arg_fns));
1684    let inner_build_ctx = BuildContext {
1685        local_variables,
1686        self_variable: build_ctx.self_variable,
1687    };
1688    build_body(&inner_build_ctx, &lambda.body)
1689}
1690
1691fn builtin_functions<'a, L: TemplateLanguage<'a> + ?Sized>() -> TemplateBuildFunctionFnMap<'a, L> {
1692    // Not using maplit::hashmap!{} or custom declarative macro here because
1693    // code completion inside macro is quite restricted.
1694    let mut map = TemplateBuildFunctionFnMap::<L>::new();
1695    map.insert("fill", |language, diagnostics, build_ctx, function| {
1696        let [width_node, content_node] = function.expect_exact_arguments()?;
1697        let width = expect_usize_expression(language, diagnostics, build_ctx, width_node)?;
1698        let content = expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1699        let template =
1700            ReformatTemplate::new(content, move |formatter, recorded| match width.extract() {
1701                Ok(width) => text_util::write_wrapped(formatter.as_mut(), recorded, width),
1702                Err(err) => formatter.handle_error(err),
1703            });
1704        Ok(L::Property::wrap_template(Box::new(template)))
1705    });
1706    map.insert("indent", |language, diagnostics, build_ctx, function| {
1707        let [prefix_node, content_node] = function.expect_exact_arguments()?;
1708        let prefix = expect_template_expression(language, diagnostics, build_ctx, prefix_node)?;
1709        let content = expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1710        let template = ReformatTemplate::new(content, move |formatter, recorded| {
1711            let rewrap = formatter.rewrap_fn();
1712            text_util::write_indented(formatter.as_mut(), recorded, |formatter| {
1713                prefix.format(&mut rewrap(formatter))
1714            })
1715        });
1716        Ok(L::Property::wrap_template(Box::new(template)))
1717    });
1718    map.insert("pad_start", |language, diagnostics, build_ctx, function| {
1719        let ([width_node, content_node], [fill_char_node]) =
1720            function.expect_named_arguments(&["", "", "fill_char"])?;
1721        let width = expect_usize_expression(language, diagnostics, build_ctx, width_node)?;
1722        let content = expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1723        let fill_char = fill_char_node
1724            .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
1725            .transpose()?;
1726        let template = new_pad_template(content, fill_char, width, text_util::write_padded_start);
1727        Ok(L::Property::wrap_template(template))
1728    });
1729    map.insert("pad_end", |language, diagnostics, build_ctx, function| {
1730        let ([width_node, content_node], [fill_char_node]) =
1731            function.expect_named_arguments(&["", "", "fill_char"])?;
1732        let width = expect_usize_expression(language, diagnostics, build_ctx, width_node)?;
1733        let content = expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1734        let fill_char = fill_char_node
1735            .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
1736            .transpose()?;
1737        let template = new_pad_template(content, fill_char, width, text_util::write_padded_end);
1738        Ok(L::Property::wrap_template(template))
1739    });
1740    map.insert(
1741        "pad_centered",
1742        |language, diagnostics, build_ctx, function| {
1743            let ([width_node, content_node], [fill_char_node]) =
1744                function.expect_named_arguments(&["", "", "fill_char"])?;
1745            let width = expect_usize_expression(language, diagnostics, build_ctx, width_node)?;
1746            let content =
1747                expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1748            let fill_char = fill_char_node
1749                .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
1750                .transpose()?;
1751            let template =
1752                new_pad_template(content, fill_char, width, text_util::write_padded_centered);
1753            Ok(L::Property::wrap_template(template))
1754        },
1755    );
1756    map.insert(
1757        "truncate_start",
1758        |language, diagnostics, build_ctx, function| {
1759            let ([width_node, content_node], [ellipsis_node]) =
1760                function.expect_named_arguments(&["", "", "ellipsis"])?;
1761            let width = expect_usize_expression(language, diagnostics, build_ctx, width_node)?;
1762            let content =
1763                expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1764            let ellipsis = ellipsis_node
1765                .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
1766                .transpose()?;
1767            let template =
1768                new_truncate_template(content, ellipsis, width, text_util::write_truncated_start);
1769            Ok(L::Property::wrap_template(template))
1770        },
1771    );
1772    map.insert(
1773        "truncate_end",
1774        |language, diagnostics, build_ctx, function| {
1775            let ([width_node, content_node], [ellipsis_node]) =
1776                function.expect_named_arguments(&["", "", "ellipsis"])?;
1777            let width = expect_usize_expression(language, diagnostics, build_ctx, width_node)?;
1778            let content =
1779                expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1780            let ellipsis = ellipsis_node
1781                .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
1782                .transpose()?;
1783            let template =
1784                new_truncate_template(content, ellipsis, width, text_util::write_truncated_end);
1785            Ok(L::Property::wrap_template(template))
1786        },
1787    );
1788    map.insert("hash", |language, diagnostics, build_ctx, function| {
1789        let [content_node] = function.expect_exact_arguments()?;
1790        let content = expect_stringify_expression(language, diagnostics, build_ctx, content_node)?;
1791        let result = content.map(|c| hex_util::encode_hex(blake2b_hash(&c).as_ref()));
1792        Ok(result.into_dyn_wrapped())
1793    });
1794    map.insert("label", |language, diagnostics, build_ctx, function| {
1795        let [label_node, content_node] = function.expect_exact_arguments()?;
1796        let label_property =
1797            expect_stringify_expression(language, diagnostics, build_ctx, label_node)?;
1798        let content = expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1799        let labels =
1800            label_property.map(|s| s.split_whitespace().map(ToString::to_string).collect());
1801        Ok(L::Property::wrap_template(Box::new(LabelTemplate::new(
1802            content, labels,
1803        ))))
1804    });
1805    map.insert(
1806        "raw_escape_sequence",
1807        |language, diagnostics, build_ctx, function| {
1808            let [content_node] = function.expect_exact_arguments()?;
1809            let content =
1810                expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1811            Ok(L::Property::wrap_template(Box::new(
1812                RawEscapeSequenceTemplate(content),
1813            )))
1814        },
1815    );
1816    map.insert("stringify", |language, diagnostics, build_ctx, function| {
1817        let [content_node] = function.expect_exact_arguments()?;
1818        let content = expect_stringify_expression(language, diagnostics, build_ctx, content_node)?;
1819        Ok(L::Property::wrap_property(content))
1820    });
1821    map.insert("json", |language, diagnostics, build_ctx, function| {
1822        // TODO: Add pretty=true|false? or json(key=value, ..)? The latter might
1823        // be implemented as a map constructor/literal if we add support for
1824        // heterogeneous list/map types.
1825        let [value_node] = function.expect_exact_arguments()?;
1826        let value = expect_serialize_expression(language, diagnostics, build_ctx, value_node)?;
1827        let out_property = value.and_then(|v| Ok(serde_json::to_string(&v)?));
1828        Ok(out_property.into_dyn_wrapped())
1829    });
1830    map.insert("if", |language, diagnostics, build_ctx, function| {
1831        let ([condition_node, true_node], [false_node]) = function.expect_arguments()?;
1832        let condition =
1833            expect_boolean_expression(language, diagnostics, build_ctx, condition_node)?;
1834        let true_template =
1835            expect_template_expression(language, diagnostics, build_ctx, true_node)?;
1836        let false_template = false_node
1837            .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
1838            .transpose()?;
1839        let template = ConditionalTemplate::new(condition, true_template, false_template);
1840        Ok(L::Property::wrap_template(Box::new(template)))
1841    });
1842    map.insert("coalesce", |language, diagnostics, build_ctx, function| {
1843        let contents = function
1844            .args
1845            .iter()
1846            .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
1847            .try_collect()?;
1848        Ok(L::Property::wrap_template(Box::new(CoalesceTemplate(
1849            contents,
1850        ))))
1851    });
1852    map.insert("concat", |language, diagnostics, build_ctx, function| {
1853        let contents = function
1854            .args
1855            .iter()
1856            .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
1857            .try_collect()?;
1858        Ok(L::Property::wrap_template(Box::new(ConcatTemplate(
1859            contents,
1860        ))))
1861    });
1862    map.insert("separate", |language, diagnostics, build_ctx, function| {
1863        let ([separator_node], content_nodes) = function.expect_some_arguments()?;
1864        let separator =
1865            expect_template_expression(language, diagnostics, build_ctx, separator_node)?;
1866        let contents = content_nodes
1867            .iter()
1868            .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
1869            .try_collect()?;
1870        Ok(L::Property::wrap_template(Box::new(SeparateTemplate::new(
1871            separator, contents,
1872        ))))
1873    });
1874    map.insert("surround", |language, diagnostics, build_ctx, function| {
1875        let [prefix_node, suffix_node, content_node] = function.expect_exact_arguments()?;
1876        let prefix = expect_template_expression(language, diagnostics, build_ctx, prefix_node)?;
1877        let suffix = expect_template_expression(language, diagnostics, build_ctx, suffix_node)?;
1878        let content = expect_template_expression(language, diagnostics, build_ctx, content_node)?;
1879        let template = ReformatTemplate::new(content, move |formatter, recorded| {
1880            if recorded.data().is_empty() {
1881                return Ok(());
1882            }
1883            prefix.format(formatter)?;
1884            recorded.replay(formatter.as_mut())?;
1885            suffix.format(formatter)?;
1886            Ok(())
1887        });
1888        Ok(L::Property::wrap_template(Box::new(template)))
1889    });
1890    map.insert("config", |language, diagnostics, _build_ctx, function| {
1891        // Dynamic lookup can be implemented if needed. The name is literal
1892        // string for now so the error can be reported early.
1893        let [name_node] = function.expect_exact_arguments()?;
1894        let name: ConfigNamePathBuf =
1895            template_parser::catch_aliases(diagnostics, name_node, |_diagnostics, node| {
1896                let name = template_parser::expect_string_literal(node)?;
1897                name.parse().map_err(|err| {
1898                    TemplateParseError::expression("Failed to parse config name", node.span)
1899                        .with_source(err)
1900                })
1901            })?;
1902        let value = language.settings().get_value(&name).map_err(|err| {
1903            TemplateParseError::expression("Failed to get config value", function.name_span)
1904                .with_source(err)
1905        })?;
1906        // .decorated("", "") to trim leading/trailing whitespace
1907        Ok(Literal(value.decorated("", "")).into_dyn_wrapped())
1908    });
1909    map
1910}
1911
1912fn new_pad_template<'a, W>(
1913    content: Box<dyn Template + 'a>,
1914    fill_char: Option<Box<dyn Template + 'a>>,
1915    width: BoxedTemplateProperty<'a, usize>,
1916    write_padded: W,
1917) -> Box<dyn Template + 'a>
1918where
1919    W: Fn(&mut dyn Formatter, &FormatRecorder, &FormatRecorder, usize) -> io::Result<()> + 'a,
1920{
1921    let default_fill_char = FormatRecorder::with_data(" ");
1922    let template = ReformatTemplate::new(content, move |formatter, recorded| {
1923        let width = match width.extract() {
1924            Ok(width) => width,
1925            Err(err) => return formatter.handle_error(err),
1926        };
1927        let mut fill_char_recorder;
1928        let recorded_fill_char = if let Some(fill_char) = &fill_char {
1929            let rewrap = formatter.rewrap_fn();
1930            fill_char_recorder = FormatRecorder::new();
1931            fill_char.format(&mut rewrap(&mut fill_char_recorder))?;
1932            &fill_char_recorder
1933        } else {
1934            &default_fill_char
1935        };
1936        write_padded(formatter.as_mut(), recorded, recorded_fill_char, width)
1937    });
1938    Box::new(template)
1939}
1940
1941fn new_truncate_template<'a, W>(
1942    content: Box<dyn Template + 'a>,
1943    ellipsis: Option<Box<dyn Template + 'a>>,
1944    width: BoxedTemplateProperty<'a, usize>,
1945    write_truncated: W,
1946) -> Box<dyn Template + 'a>
1947where
1948    W: Fn(&mut dyn Formatter, &FormatRecorder, &FormatRecorder, usize) -> io::Result<usize> + 'a,
1949{
1950    let default_ellipsis = FormatRecorder::with_data("");
1951    let template = ReformatTemplate::new(content, move |formatter, recorded| {
1952        let width = match width.extract() {
1953            Ok(width) => width,
1954            Err(err) => return formatter.handle_error(err),
1955        };
1956        let mut ellipsis_recorder;
1957        let recorded_ellipsis = if let Some(ellipsis) = &ellipsis {
1958            let rewrap = formatter.rewrap_fn();
1959            ellipsis_recorder = FormatRecorder::new();
1960            ellipsis.format(&mut rewrap(&mut ellipsis_recorder))?;
1961            &ellipsis_recorder
1962        } else {
1963            &default_ellipsis
1964        };
1965        write_truncated(formatter.as_mut(), recorded, recorded_ellipsis, width)?;
1966        Ok(())
1967    });
1968    Box::new(template)
1969}
1970
1971/// Builds intermediate expression tree from AST nodes.
1972pub fn build_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
1973    language: &L,
1974    diagnostics: &mut TemplateDiagnostics,
1975    build_ctx: &BuildContext<L::Property>,
1976    node: &ExpressionNode,
1977) -> TemplateParseResult<Expression<L::Property>> {
1978    template_parser::catch_aliases(diagnostics, node, |diagnostics, node| match &node.kind {
1979        ExpressionKind::Identifier(name) => {
1980            if let Some(make) = build_ctx.local_variables.get(name) {
1981                // Don't label a local variable with its name
1982                Ok(Expression::unlabeled(make()))
1983            } else if *name == "self" {
1984                // "self" is a special variable, so don't label it
1985                let make = build_ctx.self_variable;
1986                Ok(Expression::unlabeled(make()))
1987            } else {
1988                let property = build_keyword(language, diagnostics, build_ctx, name, node.span)
1989                    .map_err(|err| {
1990                        err.extend_keyword_candidates(itertools::chain(
1991                            build_ctx.local_variables.keys().copied(),
1992                            ["self"],
1993                        ))
1994                    })?;
1995                Ok(Expression::with_label(property, *name))
1996            }
1997        }
1998        ExpressionKind::Boolean(value) => {
1999            let property = Literal(*value).into_dyn_wrapped();
2000            Ok(Expression::unlabeled(property))
2001        }
2002        ExpressionKind::Integer(value) => {
2003            let property = Literal(*value).into_dyn_wrapped();
2004            Ok(Expression::unlabeled(property))
2005        }
2006        ExpressionKind::String(value) => {
2007            let property = Literal(value.clone()).into_dyn_wrapped();
2008            Ok(Expression::unlabeled(property))
2009        }
2010        ExpressionKind::StringPattern { .. } => Err(TemplateParseError::expression(
2011            "String patterns may not be used as expression values",
2012            node.span,
2013        )),
2014        ExpressionKind::Unary(op, arg_node) => {
2015            let property = build_unary_operation(language, diagnostics, build_ctx, *op, arg_node)?;
2016            Ok(Expression::unlabeled(property))
2017        }
2018        ExpressionKind::Binary(op, lhs_node, rhs_node) => {
2019            let property = build_binary_operation(
2020                language,
2021                diagnostics,
2022                build_ctx,
2023                *op,
2024                lhs_node,
2025                rhs_node,
2026                node.span,
2027            )?;
2028            Ok(Expression::unlabeled(property))
2029        }
2030        ExpressionKind::Concat(nodes) => {
2031            let templates = nodes
2032                .iter()
2033                .map(|node| expect_template_expression(language, diagnostics, build_ctx, node))
2034                .try_collect()?;
2035            let property = L::Property::wrap_template(Box::new(ConcatTemplate(templates)));
2036            Ok(Expression::unlabeled(property))
2037        }
2038        ExpressionKind::FunctionCall(function) => {
2039            let property = language.build_function(diagnostics, build_ctx, function)?;
2040            Ok(Expression::unlabeled(property))
2041        }
2042        ExpressionKind::MethodCall(method) => {
2043            let mut expression =
2044                build_expression(language, diagnostics, build_ctx, &method.object)?;
2045            expression.property = language.build_method(
2046                diagnostics,
2047                build_ctx,
2048                expression.property,
2049                &method.function,
2050            )?;
2051            expression.labels.push(method.function.name.to_owned());
2052            Ok(expression)
2053        }
2054        ExpressionKind::Lambda(_) => Err(TemplateParseError::expression(
2055            "Lambda cannot be defined here",
2056            node.span,
2057        )),
2058        ExpressionKind::AliasExpanded(..) => unreachable!(),
2059    })
2060}
2061
2062/// Builds template evaluation tree from AST nodes, with fresh build context.
2063pub fn build<'a, C, L>(
2064    language: &L,
2065    diagnostics: &mut TemplateDiagnostics,
2066    node: &ExpressionNode,
2067) -> TemplateParseResult<TemplateRenderer<'a, C>>
2068where
2069    C: Clone + 'a,
2070    L: TemplateLanguage<'a> + ?Sized,
2071    L::Property: WrapTemplateProperty<'a, C>,
2072{
2073    let self_placeholder = PropertyPlaceholder::new();
2074    let build_ctx = BuildContext {
2075        local_variables: HashMap::new(),
2076        self_variable: &|| self_placeholder.clone().into_dyn_wrapped(),
2077    };
2078    let template = expect_template_expression(language, diagnostics, &build_ctx, node)?;
2079    Ok(TemplateRenderer::new(template, self_placeholder))
2080}
2081
2082/// Parses text, expands aliases, then builds template evaluation tree.
2083pub fn parse<'a, C, L>(
2084    language: &L,
2085    diagnostics: &mut TemplateDiagnostics,
2086    template_text: &str,
2087    aliases_map: &TemplateAliasesMap,
2088) -> TemplateParseResult<TemplateRenderer<'a, C>>
2089where
2090    C: Clone + 'a,
2091    L: TemplateLanguage<'a> + ?Sized,
2092    L::Property: WrapTemplateProperty<'a, C>,
2093{
2094    let node = template_parser::parse(template_text, aliases_map)?;
2095    build(language, diagnostics, &node).map_err(|err| err.extend_alias_candidates(aliases_map))
2096}
2097
2098pub fn expect_boolean_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
2099    language: &L,
2100    diagnostics: &mut TemplateDiagnostics,
2101    build_ctx: &BuildContext<L::Property>,
2102    node: &ExpressionNode,
2103) -> TemplateParseResult<BoxedTemplateProperty<'a, bool>> {
2104    expect_expression_of_type(
2105        language,
2106        diagnostics,
2107        build_ctx,
2108        node,
2109        "Boolean",
2110        |expression| expression.try_into_boolean(),
2111    )
2112}
2113
2114pub fn expect_integer_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
2115    language: &L,
2116    diagnostics: &mut TemplateDiagnostics,
2117    build_ctx: &BuildContext<L::Property>,
2118    node: &ExpressionNode,
2119) -> TemplateParseResult<BoxedTemplateProperty<'a, i64>> {
2120    expect_expression_of_type(
2121        language,
2122        diagnostics,
2123        build_ctx,
2124        node,
2125        "Integer",
2126        |expression| expression.try_into_integer(),
2127    )
2128}
2129
2130/// If the given expression `node` is of `Integer` type, converts it to `isize`.
2131pub fn expect_isize_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
2132    language: &L,
2133    diagnostics: &mut TemplateDiagnostics,
2134    build_ctx: &BuildContext<L::Property>,
2135    node: &ExpressionNode,
2136) -> TemplateParseResult<BoxedTemplateProperty<'a, isize>> {
2137    let i64_property = expect_integer_expression(language, diagnostics, build_ctx, node)?;
2138    let isize_property = i64_property.and_then(|v| Ok(isize::try_from(v)?));
2139    Ok(isize_property.into_dyn())
2140}
2141
2142/// If the given expression `node` is of `Integer` type, converts it to `usize`.
2143pub fn expect_usize_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
2144    language: &L,
2145    diagnostics: &mut TemplateDiagnostics,
2146    build_ctx: &BuildContext<L::Property>,
2147    node: &ExpressionNode,
2148) -> TemplateParseResult<BoxedTemplateProperty<'a, usize>> {
2149    let i64_property = expect_integer_expression(language, diagnostics, build_ctx, node)?;
2150    let usize_property = i64_property.and_then(|v| Ok(usize::try_from(v)?));
2151    Ok(usize_property.into_dyn())
2152}
2153
2154pub fn expect_stringify_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
2155    language: &L,
2156    diagnostics: &mut TemplateDiagnostics,
2157    build_ctx: &BuildContext<L::Property>,
2158    node: &ExpressionNode,
2159) -> TemplateParseResult<BoxedTemplateProperty<'a, String>> {
2160    // Since any formattable type can be converted to a string property, the
2161    // expected type is not a String.
2162    expect_expression_of_type(
2163        language,
2164        diagnostics,
2165        build_ctx,
2166        node,
2167        "Stringify",
2168        |expression| expression.try_into_stringify(),
2169    )
2170}
2171
2172pub fn expect_serialize_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
2173    language: &L,
2174    diagnostics: &mut TemplateDiagnostics,
2175    build_ctx: &BuildContext<L::Property>,
2176    node: &ExpressionNode,
2177) -> TemplateParseResult<BoxedSerializeProperty<'a>> {
2178    expect_expression_of_type(
2179        language,
2180        diagnostics,
2181        build_ctx,
2182        node,
2183        "Serialize",
2184        |expression| expression.try_into_serialize(),
2185    )
2186}
2187
2188pub fn expect_template_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
2189    language: &L,
2190    diagnostics: &mut TemplateDiagnostics,
2191    build_ctx: &BuildContext<L::Property>,
2192    node: &ExpressionNode,
2193) -> TemplateParseResult<Box<dyn Template + 'a>> {
2194    expect_expression_of_type(
2195        language,
2196        diagnostics,
2197        build_ctx,
2198        node,
2199        "Template",
2200        |expression| expression.try_into_template(),
2201    )
2202}
2203
2204fn expect_expression_of_type<'a, L: TemplateLanguage<'a> + ?Sized, T>(
2205    language: &L,
2206    diagnostics: &mut TemplateDiagnostics,
2207    build_ctx: &BuildContext<L::Property>,
2208    node: &ExpressionNode,
2209    expected_type: &str,
2210    f: impl FnOnce(Expression<L::Property>) -> Option<T>,
2211) -> TemplateParseResult<T> {
2212    template_parser::catch_aliases(diagnostics, node, |diagnostics, node| {
2213        let expression = build_expression(language, diagnostics, build_ctx, node)?;
2214        let actual_type = expression.type_name();
2215        f(expression)
2216            .ok_or_else(|| TemplateParseError::expected_type(expected_type, actual_type, node.span))
2217    })
2218}
2219
2220#[cfg(test)]
2221mod tests {
2222    use jj_lib::backend::MillisSinceEpoch;
2223    use jj_lib::config::StackedConfig;
2224
2225    use super::*;
2226    use crate::formatter;
2227    use crate::formatter::ColorFormatter;
2228    use crate::generic_templater;
2229    use crate::generic_templater::GenericTemplateLanguage;
2230
2231    #[derive(Clone, Debug, serde::Serialize)]
2232    struct Context;
2233
2234    type TestTemplateLanguage = GenericTemplateLanguage<'static, Context>;
2235    type TestTemplatePropertyKind = <TestTemplateLanguage as TemplateLanguage<'static>>::Property;
2236
2237    generic_templater::impl_self_property_wrapper!(Context);
2238
2239    /// Helper to set up template evaluation environment.
2240    struct TestTemplateEnv {
2241        language: TestTemplateLanguage,
2242        aliases_map: TemplateAliasesMap,
2243        color_rules: Vec<(Vec<String>, formatter::Style)>,
2244    }
2245
2246    impl TestTemplateEnv {
2247        fn new() -> Self {
2248            Self::with_config(StackedConfig::with_defaults())
2249        }
2250
2251        fn with_config(config: StackedConfig) -> Self {
2252            let settings = UserSettings::from_config(config).unwrap();
2253            Self {
2254                language: TestTemplateLanguage::new(&settings),
2255                aliases_map: TemplateAliasesMap::new(),
2256                color_rules: Vec::new(),
2257            }
2258        }
2259    }
2260
2261    impl TestTemplateEnv {
2262        fn add_keyword<F>(&mut self, name: &'static str, build: F)
2263        where
2264            F: Fn() -> TestTemplatePropertyKind + 'static,
2265        {
2266            self.language.add_keyword(name, move |_| Ok(build()));
2267        }
2268
2269        fn add_alias(&mut self, decl: impl AsRef<str>, defn: impl Into<String>) {
2270            self.aliases_map.insert(decl, defn).unwrap();
2271        }
2272
2273        fn add_color(&mut self, label: &str, fg: crossterm::style::Color) {
2274            let labels = label.split_whitespace().map(|s| s.to_owned()).collect();
2275            let style = formatter::Style {
2276                fg: Some(fg),
2277                ..Default::default()
2278            };
2279            self.color_rules.push((labels, style));
2280        }
2281
2282        fn parse(&self, template: &str) -> TemplateParseResult<TemplateRenderer<'static, Context>> {
2283            parse(
2284                &self.language,
2285                &mut TemplateDiagnostics::new(),
2286                template,
2287                &self.aliases_map,
2288            )
2289        }
2290
2291        fn parse_err(&self, template: &str) -> String {
2292            let err = self
2293                .parse(template)
2294                .err()
2295                .expect("Got unexpected successful template rendering");
2296
2297            iter::successors(Some(&err as &dyn std::error::Error), |e| e.source()).join("\n")
2298        }
2299
2300        fn render_ok(&self, template: &str) -> String {
2301            let template = self.parse(template).unwrap();
2302            let mut output = Vec::new();
2303            let mut formatter =
2304                ColorFormatter::new(&mut output, self.color_rules.clone().into(), false);
2305            template.format(&Context, &mut formatter).unwrap();
2306            drop(formatter);
2307            String::from_utf8(output).unwrap()
2308        }
2309    }
2310
2311    fn literal<'a, O>(value: O) -> TestTemplatePropertyKind
2312    where
2313        O: Clone + 'a,
2314        TestTemplatePropertyKind: WrapTemplateProperty<'a, O>,
2315    {
2316        Literal(value).into_dyn_wrapped()
2317    }
2318
2319    fn new_error_property<'a, O>(message: &'a str) -> TestTemplatePropertyKind
2320    where
2321        TestTemplatePropertyKind: WrapTemplateProperty<'a, O>,
2322    {
2323        Literal(())
2324            .and_then(|()| Err(TemplatePropertyError(message.into())))
2325            .into_dyn_wrapped()
2326    }
2327
2328    fn new_signature(name: &str, email: &str) -> Signature {
2329        Signature {
2330            name: name.to_owned(),
2331            email: email.to_owned(),
2332            timestamp: new_timestamp(0, 0),
2333        }
2334    }
2335
2336    fn new_timestamp(msec: i64, tz_offset: i32) -> Timestamp {
2337        Timestamp {
2338            timestamp: MillisSinceEpoch(msec),
2339            tz_offset,
2340        }
2341    }
2342
2343    #[test]
2344    fn test_parsed_tree() {
2345        let mut env = TestTemplateEnv::new();
2346        env.add_keyword("divergent", || literal(false));
2347        env.add_keyword("empty", || literal(true));
2348        env.add_keyword("hello", || literal("Hello".to_owned()));
2349
2350        // Empty
2351        insta::assert_snapshot!(env.render_ok(r#"  "#), @"");
2352
2353        // Single term with whitespace
2354        insta::assert_snapshot!(env.render_ok(r#"  hello.upper()  "#), @"HELLO");
2355
2356        // Multiple terms
2357        insta::assert_snapshot!(env.render_ok(r#"  hello.upper()  ++ true "#), @"HELLOtrue");
2358
2359        // Parenthesized single term
2360        insta::assert_snapshot!(env.render_ok(r#"(hello.upper())"#), @"HELLO");
2361
2362        // Parenthesized multiple terms and concatenation
2363        insta::assert_snapshot!(env.render_ok(r#"(hello.upper() ++ " ") ++ empty"#), @"HELLO true");
2364
2365        // Parenthesized "if" condition
2366        insta::assert_snapshot!(env.render_ok(r#"if((divergent), "t", "f")"#), @"f");
2367
2368        // Parenthesized method chaining
2369        insta::assert_snapshot!(env.render_ok(r#"(hello).upper()"#), @"HELLO");
2370
2371        // Multi-line method chaining
2372        insta::assert_snapshot!(env.render_ok("hello\n  .upper()"), @"HELLO");
2373    }
2374
2375    #[test]
2376    fn test_parse_error() {
2377        let mut env = TestTemplateEnv::new();
2378        env.add_keyword("description", || literal("".to_owned()));
2379        env.add_keyword("empty", || literal(true));
2380
2381        insta::assert_snapshot!(env.parse_err(r#"foo bar"#), @r"
2382         --> 1:5
2383          |
2384        1 | foo bar
2385          |     ^---
2386          |
2387          = expected <EOI>, `++`, `||`, `&&`, `==`, `!=`, `>=`, `>`, `<=`, `<`, `+`, `-`, `*`, `/`, or `%`
2388        ");
2389
2390        insta::assert_snapshot!(env.parse_err(r#"foo"#), @r"
2391         --> 1:1
2392          |
2393        1 | foo
2394          | ^-^
2395          |
2396          = Keyword `foo` doesn't exist
2397        ");
2398
2399        insta::assert_snapshot!(env.parse_err(r#"foo()"#), @r"
2400         --> 1:1
2401          |
2402        1 | foo()
2403          | ^-^
2404          |
2405          = Function `foo` doesn't exist
2406        ");
2407        insta::assert_snapshot!(env.parse_err(r#"false()"#), @r"
2408         --> 1:1
2409          |
2410        1 | false()
2411          | ^---^
2412          |
2413          = Expected identifier
2414        ");
2415
2416        insta::assert_snapshot!(env.parse_err(r#"!foo"#), @r"
2417         --> 1:2
2418          |
2419        1 | !foo
2420          |  ^-^
2421          |
2422          = Keyword `foo` doesn't exist
2423        ");
2424        insta::assert_snapshot!(env.parse_err(r#"true && 123"#), @r"
2425         --> 1:9
2426          |
2427        1 | true && 123
2428          |         ^-^
2429          |
2430          = Expected expression of type `Boolean`, but actual type is `Integer`
2431        ");
2432        insta::assert_snapshot!(env.parse_err(r#"true == 1"#), @r"
2433         --> 1:1
2434          |
2435        1 | true == 1
2436          | ^-------^
2437          |
2438          = Cannot compare expressions of type `Boolean` and `Integer`
2439        ");
2440        insta::assert_snapshot!(env.parse_err(r#"true != 'a'"#), @r"
2441         --> 1:1
2442          |
2443        1 | true != 'a'
2444          | ^---------^
2445          |
2446          = Cannot compare expressions of type `Boolean` and `String`
2447        ");
2448        insta::assert_snapshot!(env.parse_err(r#"1 == true"#), @r"
2449         --> 1:1
2450          |
2451        1 | 1 == true
2452          | ^-------^
2453          |
2454          = Cannot compare expressions of type `Integer` and `Boolean`
2455        ");
2456        insta::assert_snapshot!(env.parse_err(r#"1 != 'a'"#), @r"
2457         --> 1:1
2458          |
2459        1 | 1 != 'a'
2460          | ^------^
2461          |
2462          = Cannot compare expressions of type `Integer` and `String`
2463        ");
2464        insta::assert_snapshot!(env.parse_err(r#"'a' == true"#), @r"
2465         --> 1:1
2466          |
2467        1 | 'a' == true
2468          | ^---------^
2469          |
2470          = Cannot compare expressions of type `String` and `Boolean`
2471        ");
2472        insta::assert_snapshot!(env.parse_err(r#"'a' != 1"#), @r"
2473         --> 1:1
2474          |
2475        1 | 'a' != 1
2476          | ^------^
2477          |
2478          = Cannot compare expressions of type `String` and `Integer`
2479        ");
2480        insta::assert_snapshot!(env.parse_err(r#"'a' == label("", "")"#), @r#"
2481         --> 1:1
2482          |
2483        1 | 'a' == label("", "")
2484          | ^------------------^
2485          |
2486          = Cannot compare expressions of type `String` and `Template`
2487        "#);
2488        insta::assert_snapshot!(env.parse_err(r#"'a' > 1"#), @r"
2489         --> 1:1
2490          |
2491        1 | 'a' > 1
2492          | ^-----^
2493          |
2494          = Cannot compare expressions of type `String` and `Integer`
2495        ");
2496
2497        insta::assert_snapshot!(env.parse_err(r#"description.first_line().foo()"#), @r"
2498         --> 1:26
2499          |
2500        1 | description.first_line().foo()
2501          |                          ^-^
2502          |
2503          = Method `foo` doesn't exist for type `String`
2504        ");
2505
2506        insta::assert_snapshot!(env.parse_err(r#"10000000000000000000"#), @r"
2507         --> 1:1
2508          |
2509        1 | 10000000000000000000
2510          | ^------------------^
2511          |
2512          = Invalid integer literal
2513        number too large to fit in target type
2514        ");
2515        insta::assert_snapshot!(env.parse_err(r#"42.foo()"#), @r"
2516         --> 1:4
2517          |
2518        1 | 42.foo()
2519          |    ^-^
2520          |
2521          = Method `foo` doesn't exist for type `Integer`
2522        ");
2523        insta::assert_snapshot!(env.parse_err(r#"(-empty)"#), @r"
2524         --> 1:3
2525          |
2526        1 | (-empty)
2527          |   ^---^
2528          |
2529          = Expected expression of type `Integer`, but actual type is `Boolean`
2530        ");
2531
2532        insta::assert_snapshot!(env.parse_err(r#"("foo" ++ "bar").baz()"#), @r#"
2533         --> 1:18
2534          |
2535        1 | ("foo" ++ "bar").baz()
2536          |                  ^-^
2537          |
2538          = Method `baz` doesn't exist for type `Template`
2539        "#);
2540
2541        insta::assert_snapshot!(env.parse_err(r#"description.contains()"#), @r"
2542         --> 1:22
2543          |
2544        1 | description.contains()
2545          |                      ^
2546          |
2547          = Function `contains`: Expected 1 arguments
2548        ");
2549
2550        insta::assert_snapshot!(env.parse_err(r#"description.first_line("foo")"#), @r#"
2551         --> 1:24
2552          |
2553        1 | description.first_line("foo")
2554          |                        ^---^
2555          |
2556          = Function `first_line`: Expected 0 arguments
2557        "#);
2558
2559        insta::assert_snapshot!(env.parse_err(r#"label()"#), @r"
2560         --> 1:7
2561          |
2562        1 | label()
2563          |       ^
2564          |
2565          = Function `label`: Expected 2 arguments
2566        ");
2567        insta::assert_snapshot!(env.parse_err(r#"label("foo", "bar", "baz")"#), @r#"
2568         --> 1:7
2569          |
2570        1 | label("foo", "bar", "baz")
2571          |       ^-----------------^
2572          |
2573          = Function `label`: Expected 2 arguments
2574        "#);
2575
2576        insta::assert_snapshot!(env.parse_err(r#"if()"#), @r"
2577         --> 1:4
2578          |
2579        1 | if()
2580          |    ^
2581          |
2582          = Function `if`: Expected 2 to 3 arguments
2583        ");
2584        insta::assert_snapshot!(env.parse_err(r#"if("foo", "bar", "baz", "quux")"#), @r#"
2585         --> 1:4
2586          |
2587        1 | if("foo", "bar", "baz", "quux")
2588          |    ^-------------------------^
2589          |
2590          = Function `if`: Expected 2 to 3 arguments
2591        "#);
2592
2593        insta::assert_snapshot!(env.parse_err(r#"pad_start("foo", fill_char = "bar", "baz")"#), @r#"
2594         --> 1:37
2595          |
2596        1 | pad_start("foo", fill_char = "bar", "baz")
2597          |                                     ^---^
2598          |
2599          = Function `pad_start`: Positional argument follows keyword argument
2600        "#);
2601
2602        insta::assert_snapshot!(env.parse_err(r#"if(label("foo", "bar"), "baz")"#), @r#"
2603         --> 1:4
2604          |
2605        1 | if(label("foo", "bar"), "baz")
2606          |    ^-----------------^
2607          |
2608          = Expected expression of type `Boolean`, but actual type is `Template`
2609        "#);
2610
2611        insta::assert_snapshot!(env.parse_err(r#"|x| description"#), @r"
2612         --> 1:1
2613          |
2614        1 | |x| description
2615          | ^-------------^
2616          |
2617          = Lambda cannot be defined here
2618        ");
2619    }
2620
2621    #[test]
2622    fn test_self_keyword() {
2623        let mut env = TestTemplateEnv::new();
2624        env.add_keyword("say_hello", || literal("Hello".to_owned()));
2625
2626        insta::assert_snapshot!(env.render_ok(r#"self.say_hello()"#), @"Hello");
2627        insta::assert_snapshot!(env.parse_err(r#"self"#), @r"
2628         --> 1:1
2629          |
2630        1 | self
2631          | ^--^
2632          |
2633          = Expected expression of type `Template`, but actual type is `Self`
2634        ");
2635    }
2636
2637    #[test]
2638    fn test_boolean_cast() {
2639        let mut env = TestTemplateEnv::new();
2640
2641        insta::assert_snapshot!(env.render_ok(r#"if("", true, false)"#), @"false");
2642        insta::assert_snapshot!(env.render_ok(r#"if("a", true, false)"#), @"true");
2643
2644        env.add_keyword("sl0", || literal::<Vec<String>>(vec![]));
2645        env.add_keyword("sl1", || literal(vec!["".to_owned()]));
2646        insta::assert_snapshot!(env.render_ok(r#"if(sl0, true, false)"#), @"false");
2647        insta::assert_snapshot!(env.render_ok(r#"if(sl1, true, false)"#), @"true");
2648
2649        // No implicit cast of integer
2650        insta::assert_snapshot!(env.parse_err(r#"if(0, true, false)"#), @r"
2651         --> 1:4
2652          |
2653        1 | if(0, true, false)
2654          |    ^
2655          |
2656          = Expected expression of type `Boolean`, but actual type is `Integer`
2657        ");
2658
2659        // Optional integer can be converted to boolean, and Some(0) is truthy.
2660        env.add_keyword("none_i64", || literal(None));
2661        env.add_keyword("some_i64", || literal(Some(0)));
2662        insta::assert_snapshot!(env.render_ok(r#"if(none_i64, true, false)"#), @"false");
2663        insta::assert_snapshot!(env.render_ok(r#"if(some_i64, true, false)"#), @"true");
2664
2665        insta::assert_snapshot!(env.parse_err(r#"if(label("", ""), true, false)"#), @r#"
2666         --> 1:4
2667          |
2668        1 | if(label("", ""), true, false)
2669          |    ^-----------^
2670          |
2671          = Expected expression of type `Boolean`, but actual type is `Template`
2672        "#);
2673        insta::assert_snapshot!(env.parse_err(r#"if(sl0.map(|x| x), true, false)"#), @r"
2674         --> 1:4
2675          |
2676        1 | if(sl0.map(|x| x), true, false)
2677          |    ^------------^
2678          |
2679          = Expected expression of type `Boolean`, but actual type is `ListTemplate`
2680        ");
2681
2682        env.add_keyword("empty_email", || literal(Email("".to_owned())));
2683        env.add_keyword("nonempty_email", || {
2684            literal(Email("local@domain".to_owned()))
2685        });
2686        insta::assert_snapshot!(env.render_ok(r#"if(empty_email, true, false)"#), @"false");
2687        insta::assert_snapshot!(env.render_ok(r#"if(nonempty_email, true, false)"#), @"true");
2688    }
2689
2690    #[test]
2691    fn test_arithmetic_operation() {
2692        let mut env = TestTemplateEnv::new();
2693        env.add_keyword("none_i64", || literal(None));
2694        env.add_keyword("some_i64", || literal(Some(1)));
2695        env.add_keyword("i64_min", || literal(i64::MIN));
2696        env.add_keyword("i64_max", || literal(i64::MAX));
2697
2698        insta::assert_snapshot!(env.render_ok(r#"-1"#), @"-1");
2699        insta::assert_snapshot!(env.render_ok(r#"--2"#), @"2");
2700        insta::assert_snapshot!(env.render_ok(r#"-(3)"#), @"-3");
2701        insta::assert_snapshot!(env.render_ok(r#"1 + 2"#), @"3");
2702        insta::assert_snapshot!(env.render_ok(r#"2 * 3"#), @"6");
2703        insta::assert_snapshot!(env.render_ok(r#"1 + 2 * 3"#), @"7");
2704        insta::assert_snapshot!(env.render_ok(r#"4 / 2"#), @"2");
2705        insta::assert_snapshot!(env.render_ok(r#"5 / 2"#), @"2");
2706        insta::assert_snapshot!(env.render_ok(r#"5 % 2"#), @"1");
2707
2708        // Since methods of the contained value can be invoked, it makes sense
2709        // to apply operators to optional integers as well.
2710        insta::assert_snapshot!(env.render_ok(r#"-none_i64"#), @"<Error: No Integer available>");
2711        insta::assert_snapshot!(env.render_ok(r#"-some_i64"#), @"-1");
2712        insta::assert_snapshot!(env.render_ok(r#"some_i64 + some_i64"#), @"2");
2713        insta::assert_snapshot!(env.render_ok(r#"some_i64 + none_i64"#), @"<Error: No Integer available>");
2714        insta::assert_snapshot!(env.render_ok(r#"none_i64 + some_i64"#), @"<Error: No Integer available>");
2715        insta::assert_snapshot!(env.render_ok(r#"none_i64 + none_i64"#), @"<Error: No Integer available>");
2716
2717        // No panic on integer overflow.
2718        insta::assert_snapshot!(
2719            env.render_ok(r#"-i64_min"#),
2720            @"<Error: Attempt to negate with overflow>");
2721        insta::assert_snapshot!(
2722            env.render_ok(r#"i64_max + 1"#),
2723            @"<Error: Attempt to add with overflow>");
2724        insta::assert_snapshot!(
2725            env.render_ok(r#"i64_min - 1"#),
2726            @"<Error: Attempt to subtract with overflow>");
2727        insta::assert_snapshot!(
2728            env.render_ok(r#"i64_max * 2"#),
2729            @"<Error: Attempt to multiply with overflow>");
2730        insta::assert_snapshot!(
2731            env.render_ok(r#"i64_min / -1"#),
2732            @"<Error: Attempt to divide with overflow>");
2733        insta::assert_snapshot!(
2734            env.render_ok(r#"1 / 0"#),
2735            @"<Error: Attempt to divide by zero>");
2736        insta::assert_snapshot!(
2737            env.render_ok(r#"1 % 0"#),
2738            @"<Error: Attempt to divide by zero>");
2739    }
2740
2741    #[test]
2742    fn test_relational_operation() {
2743        let mut env = TestTemplateEnv::new();
2744        env.add_keyword("none_i64", || literal(None::<i64>));
2745        env.add_keyword("some_i64_0", || literal(Some(0_i64)));
2746        env.add_keyword("some_i64_1", || literal(Some(1_i64)));
2747
2748        insta::assert_snapshot!(env.render_ok(r#"1 >= 1"#), @"true");
2749        insta::assert_snapshot!(env.render_ok(r#"0 >= 1"#), @"false");
2750        insta::assert_snapshot!(env.render_ok(r#"2 > 1"#), @"true");
2751        insta::assert_snapshot!(env.render_ok(r#"1 > 1"#), @"false");
2752        insta::assert_snapshot!(env.render_ok(r#"1 <= 1"#), @"true");
2753        insta::assert_snapshot!(env.render_ok(r#"2 <= 1"#), @"false");
2754        insta::assert_snapshot!(env.render_ok(r#"0 < 1"#), @"true");
2755        insta::assert_snapshot!(env.render_ok(r#"1 < 1"#), @"false");
2756
2757        // none < some
2758        insta::assert_snapshot!(env.render_ok(r#"none_i64 < some_i64_0"#), @"true");
2759        insta::assert_snapshot!(env.render_ok(r#"some_i64_0 > some_i64_1"#), @"false");
2760        insta::assert_snapshot!(env.render_ok(r#"none_i64 < 0"#), @"true");
2761        insta::assert_snapshot!(env.render_ok(r#"1 > some_i64_0"#), @"true");
2762    }
2763
2764    #[test]
2765    fn test_logical_operation() {
2766        let mut env = TestTemplateEnv::new();
2767        env.add_keyword("none_i64", || literal::<Option<i64>>(None));
2768        env.add_keyword("some_i64_0", || literal(Some(0_i64)));
2769        env.add_keyword("some_i64_1", || literal(Some(1_i64)));
2770        env.add_keyword("email1", || literal(Email("local-1@domain".to_owned())));
2771        env.add_keyword("email2", || literal(Email("local-2@domain".to_owned())));
2772
2773        insta::assert_snapshot!(env.render_ok(r#"!false"#), @"true");
2774        insta::assert_snapshot!(env.render_ok(r#"false || !false"#), @"true");
2775        insta::assert_snapshot!(env.render_ok(r#"false && true"#), @"false");
2776        insta::assert_snapshot!(env.render_ok(r#"true == true"#), @"true");
2777        insta::assert_snapshot!(env.render_ok(r#"true == false"#), @"false");
2778        insta::assert_snapshot!(env.render_ok(r#"true != true"#), @"false");
2779        insta::assert_snapshot!(env.render_ok(r#"true != false"#), @"true");
2780
2781        insta::assert_snapshot!(env.render_ok(r#"1 == 1"#), @"true");
2782        insta::assert_snapshot!(env.render_ok(r#"1 == 2"#), @"false");
2783        insta::assert_snapshot!(env.render_ok(r#"1 != 1"#), @"false");
2784        insta::assert_snapshot!(env.render_ok(r#"1 != 2"#), @"true");
2785        insta::assert_snapshot!(env.render_ok(r#"none_i64 == none_i64"#), @"true");
2786        insta::assert_snapshot!(env.render_ok(r#"some_i64_0 != some_i64_0"#), @"false");
2787        insta::assert_snapshot!(env.render_ok(r#"none_i64 == 0"#), @"false");
2788        insta::assert_snapshot!(env.render_ok(r#"some_i64_0 != 0"#), @"false");
2789        insta::assert_snapshot!(env.render_ok(r#"1 == some_i64_1"#), @"true");
2790
2791        insta::assert_snapshot!(env.render_ok(r#"'a' == 'a'"#), @"true");
2792        insta::assert_snapshot!(env.render_ok(r#"'a' == 'b'"#), @"false");
2793        insta::assert_snapshot!(env.render_ok(r#"'a' != 'a'"#), @"false");
2794        insta::assert_snapshot!(env.render_ok(r#"'a' != 'b'"#), @"true");
2795        insta::assert_snapshot!(env.render_ok(r#"email1 == email1"#), @"true");
2796        insta::assert_snapshot!(env.render_ok(r#"email1 == email2"#), @"false");
2797        insta::assert_snapshot!(env.render_ok(r#"email1 == 'local-1@domain'"#), @"true");
2798        insta::assert_snapshot!(env.render_ok(r#"email1 != 'local-2@domain'"#), @"true");
2799        insta::assert_snapshot!(env.render_ok(r#"'local-1@domain' == email1"#), @"true");
2800        insta::assert_snapshot!(env.render_ok(r#"'local-2@domain' != email1"#), @"true");
2801
2802        insta::assert_snapshot!(env.render_ok(r#" !"" "#), @"true");
2803        insta::assert_snapshot!(env.render_ok(r#" "" || "a".lines() "#), @"true");
2804
2805        // Short-circuiting
2806        env.add_keyword("bad_bool", || new_error_property::<bool>("Bad"));
2807        insta::assert_snapshot!(env.render_ok(r#"false && bad_bool"#), @"false");
2808        insta::assert_snapshot!(env.render_ok(r#"true && bad_bool"#), @"<Error: Bad>");
2809        insta::assert_snapshot!(env.render_ok(r#"false || bad_bool"#), @"<Error: Bad>");
2810        insta::assert_snapshot!(env.render_ok(r#"true || bad_bool"#), @"true");
2811    }
2812
2813    #[test]
2814    fn test_list_method() {
2815        let mut env = TestTemplateEnv::new();
2816        env.add_keyword("empty", || literal(true));
2817        env.add_keyword("sep", || literal("sep".to_owned()));
2818
2819        insta::assert_snapshot!(env.render_ok(r#""".lines().len()"#), @"0");
2820        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc".lines().len()"#), @"3");
2821
2822        insta::assert_snapshot!(env.render_ok(r#""".lines().join("|")"#), @"");
2823        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc".lines().join("|")"#), @"a|b|c");
2824        // Null separator
2825        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc".lines().join("\0")"#), @"a\0b\0c");
2826        // Keyword as separator
2827        insta::assert_snapshot!(
2828            env.render_ok(r#""a\nb\nc".lines().join(sep.upper())"#),
2829            @"aSEPbSEPc");
2830
2831        insta::assert_snapshot!(
2832            env.render_ok(r#""a\nbb\nc".lines().filter(|s| s.len() == 1)"#),
2833            @"a c");
2834
2835        insta::assert_snapshot!(
2836            env.render_ok(r#""a\nb\nc".lines().map(|s| s ++ s)"#),
2837            @"aa bb cc");
2838
2839        // Test any() method
2840        insta::assert_snapshot!(
2841            env.render_ok(r#""a\nb\nc".lines().any(|s| s == "b")"#),
2842            @"true");
2843        insta::assert_snapshot!(
2844            env.render_ok(r#""a\nb\nc".lines().any(|s| s == "d")"#),
2845            @"false");
2846        insta::assert_snapshot!(
2847            env.render_ok(r#""".lines().any(|s| s == "a")"#),
2848            @"false");
2849        // any() with more complex predicate
2850        insta::assert_snapshot!(
2851            env.render_ok(r#""ax\nbb\nc".lines().any(|s| s.contains("x"))"#),
2852            @"true");
2853        insta::assert_snapshot!(
2854            env.render_ok(r#""a\nbb\nc".lines().any(|s| s.len() > 1)"#),
2855            @"true");
2856
2857        // Test all() method
2858        insta::assert_snapshot!(
2859            env.render_ok(r#""a\nb\nc".lines().all(|s| s.len() == 1)"#),
2860            @"true");
2861        insta::assert_snapshot!(
2862            env.render_ok(r#""a\nbb\nc".lines().all(|s| s.len() == 1)"#),
2863            @"false");
2864        // Empty list returns true for all()
2865        insta::assert_snapshot!(
2866            env.render_ok(r#""".lines().all(|s| s == "a")"#),
2867            @"true");
2868        // all() with more complex predicate
2869        insta::assert_snapshot!(
2870            env.render_ok(r#""ax\nbx\ncx".lines().all(|s| s.ends_with("x"))"#),
2871            @"true");
2872        insta::assert_snapshot!(
2873            env.render_ok(r#""a\nbb\nc".lines().all(|s| s.len() < 3)"#),
2874            @"true");
2875
2876        // Combining any/all with filter
2877        insta::assert_snapshot!(
2878            env.render_ok(r#""a\nbb\nccc".lines().filter(|s| s.len() > 1).any(|s| s == "bb")"#),
2879            @"true");
2880        insta::assert_snapshot!(
2881            env.render_ok(r#""a\nbb\nccc".lines().filter(|s| s.len() > 1).all(|s| s.len() >= 2)"#),
2882            @"true");
2883
2884        // Nested any/all operations
2885        insta::assert_snapshot!(
2886            env.render_ok(r#"if("a\nb".lines().any(|s| s == "a"), "found", "not found")"#),
2887            @"found");
2888        insta::assert_snapshot!(
2889            env.render_ok(r#"if("a\nb".lines().all(|s| s.len() == 1), "all single", "not all")"#),
2890            @"all single");
2891
2892        // Global keyword in item template
2893        insta::assert_snapshot!(
2894            env.render_ok(r#""a\nb\nc".lines().map(|s| s ++ empty)"#),
2895            @"atrue btrue ctrue");
2896        // Global keyword in item template shadowing 'self'
2897        insta::assert_snapshot!(
2898            env.render_ok(r#""a\nb\nc".lines().map(|self| self ++ empty)"#),
2899            @"atrue btrue ctrue");
2900        // Override global keyword 'empty'
2901        insta::assert_snapshot!(
2902            env.render_ok(r#""a\nb\nc".lines().map(|empty| empty)"#),
2903            @"a b c");
2904        // Nested map operations
2905        insta::assert_snapshot!(
2906            env.render_ok(r#""a\nb\nc".lines().map(|s| "x\ny".lines().map(|t| s ++ t))"#),
2907            @"ax ay bx by cx cy");
2908        // Nested map/join operations
2909        insta::assert_snapshot!(
2910            env.render_ok(r#""a\nb\nc".lines().map(|s| "x\ny".lines().map(|t| s ++ t).join(",")).join(";")"#),
2911            @"ax,ay;bx,by;cx,cy");
2912        // Nested string operations
2913        insta::assert_snapshot!(
2914            env.render_ok(r#""!  a\n!b\nc\n   end".remove_suffix("end").trim_end().lines().map(|s| s.remove_prefix("!").trim_start())"#),
2915            @"a b c");
2916
2917        // Lambda expression in alias
2918        env.add_alias("identity", "|x| x");
2919        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc".lines().map(identity)"#), @"a b c");
2920
2921        // Not a lambda expression
2922        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(empty)"#), @r#"
2923         --> 1:17
2924          |
2925        1 | "a".lines().map(empty)
2926          |                 ^---^
2927          |
2928          = Expected lambda expression
2929        "#);
2930        // Bad lambda parameter count
2931        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(|| "")"#), @r#"
2932         --> 1:18
2933          |
2934        1 | "a".lines().map(|| "")
2935          |                  ^
2936          |
2937          = Expected 1 lambda parameters
2938        "#);
2939        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(|a, b| "")"#), @r#"
2940         --> 1:18
2941          |
2942        1 | "a".lines().map(|a, b| "")
2943          |                  ^--^
2944          |
2945          = Expected 1 lambda parameters
2946        "#);
2947        // Bad lambda output
2948        insta::assert_snapshot!(env.parse_err(r#""a".lines().filter(|s| s ++ "\n")"#), @r#"
2949         --> 1:24
2950          |
2951        1 | "a".lines().filter(|s| s ++ "\n")
2952          |                        ^-------^
2953          |
2954          = Expected expression of type `Boolean`, but actual type is `Template`
2955        "#);
2956
2957        // Error in any() and all()
2958        insta::assert_snapshot!(env.parse_err(r#""a".lines().any(|s| s.len())"#), @r#"
2959         --> 1:21
2960          |
2961        1 | "a".lines().any(|s| s.len())
2962          |                     ^-----^
2963          |
2964          = Expected expression of type `Boolean`, but actual type is `Integer`
2965        "#);
2966        // Bad lambda output for all()
2967        insta::assert_snapshot!(env.parse_err(r#""a".lines().all(|s| s ++ "x")"#), @r#"
2968         --> 1:21
2969          |
2970        1 | "a".lines().all(|s| s ++ "x")
2971          |                     ^------^
2972          |
2973          = Expected expression of type `Boolean`, but actual type is `Template`
2974        "#);
2975        // Wrong parameter count for any()
2976        insta::assert_snapshot!(env.parse_err(r#""a".lines().any(|| true)"#), @r#"
2977         --> 1:18
2978          |
2979        1 | "a".lines().any(|| true)
2980          |                  ^
2981          |
2982          = Expected 1 lambda parameters
2983        "#);
2984        // Wrong parameter count for all()
2985        insta::assert_snapshot!(env.parse_err(r#""a".lines().all(|a, b| true)"#), @r#"
2986         --> 1:18
2987          |
2988        1 | "a".lines().all(|a, b| true)
2989          |                  ^--^
2990          |
2991          = Expected 1 lambda parameters
2992        "#);
2993        // Error in lambda expression
2994        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(|s| s.unknown())"#), @r#"
2995         --> 1:23
2996          |
2997        1 | "a".lines().map(|s| s.unknown())
2998          |                       ^-----^
2999          |
3000          = Method `unknown` doesn't exist for type `String`
3001        "#);
3002        // Error in lambda alias
3003        env.add_alias("too_many_params", "|x, y| x");
3004        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(too_many_params)"#), @r#"
3005         --> 1:17
3006          |
3007        1 | "a".lines().map(too_many_params)
3008          |                 ^-------------^
3009          |
3010          = In alias `too_many_params`
3011         --> 1:2
3012          |
3013        1 | |x, y| x
3014          |  ^--^
3015          |
3016          = Expected 1 lambda parameters
3017        "#);
3018    }
3019
3020    #[test]
3021    fn test_string_method() {
3022        let mut env = TestTemplateEnv::new();
3023        env.add_keyword("description", || literal("description 1".to_owned()));
3024        env.add_keyword("bad_string", || new_error_property::<String>("Bad"));
3025
3026        insta::assert_snapshot!(env.render_ok(r#""".len()"#), @"0");
3027        insta::assert_snapshot!(env.render_ok(r#""foo".len()"#), @"3");
3028        insta::assert_snapshot!(env.render_ok(r#""💩".len()"#), @"4");
3029
3030        insta::assert_snapshot!(env.render_ok(r#""fooo".contains("foo")"#), @"true");
3031        insta::assert_snapshot!(env.render_ok(r#""foo".contains("fooo")"#), @"false");
3032        insta::assert_snapshot!(env.render_ok(r#"description.contains("description")"#), @"true");
3033        insta::assert_snapshot!(
3034            env.render_ok(r#""description 123".contains(description.first_line())"#),
3035            @"true");
3036
3037        // String patterns are not stringifiable
3038        insta::assert_snapshot!(env.parse_err(r#""fa".starts_with(regex:'[a-f]o+')"#), @r#"
3039         --> 1:18
3040          |
3041        1 | "fa".starts_with(regex:'[a-f]o+')
3042          |                  ^-------------^
3043          |
3044          = String patterns may not be used as expression values
3045        "#);
3046
3047        // inner template error should propagate
3048        insta::assert_snapshot!(env.render_ok(r#""foo".contains(bad_string)"#), @"<Error: Bad>");
3049        insta::assert_snapshot!(
3050            env.render_ok(r#""foo".contains("f" ++ bad_string) ++ "bar""#), @"<Error: Bad>bar");
3051        insta::assert_snapshot!(
3052            env.render_ok(r#""foo".contains(separate("o", "f", bad_string))"#), @"<Error: Bad>");
3053
3054        insta::assert_snapshot!(env.render_ok(r#""fooo".match(regex:'[a-f]o+')"#), @"fooo");
3055        insta::assert_snapshot!(env.render_ok(r#""fa".match(regex:'[a-f]o+')"#), @"");
3056        insta::assert_snapshot!(env.render_ok(r#""hello".match(regex:"h(ell)o")"#), @"hello");
3057        insta::assert_snapshot!(env.render_ok(r#""HEllo".match(regex-i:"h(ell)o")"#), @"HEllo");
3058        insta::assert_snapshot!(env.render_ok(r#""hEllo".match(glob:"h*o")"#), @"hEllo");
3059        insta::assert_snapshot!(env.render_ok(r#""Hello".match(glob:"h*o")"#), @"");
3060        insta::assert_snapshot!(env.render_ok(r#""HEllo".match(glob-i:"h*o")"#), @"HEllo");
3061        insta::assert_snapshot!(env.render_ok(r#""hello".match("he")"#), @"he");
3062        insta::assert_snapshot!(env.render_ok(r#""hello".match(substring:"he")"#), @"he");
3063        insta::assert_snapshot!(env.render_ok(r#""hello".match(exact:"he")"#), @"");
3064
3065        // Evil regexes can cause invalid UTF-8 output, which nothing can
3066        // really be done about given we're matching against non-UTF-8 stuff a
3067        // lot as well.
3068        insta::assert_snapshot!(env.render_ok(r#""🥺".match(regex:'(?-u)^(?:.)')"#), @"<Error: incomplete utf-8 byte sequence from index 0>");
3069
3070        insta::assert_snapshot!(env.parse_err(r#""🥺".match(not-a-pattern:"abc")"#), @r#"
3071         --> 1:11
3072          |
3073        1 | "🥺".match(not-a-pattern:"abc")
3074          |           ^-----------------^
3075          |
3076          = Bad string pattern
3077        Invalid string pattern kind `not-a-pattern:`
3078        "#);
3079
3080        insta::assert_snapshot!(env.render_ok(r#""".first_line()"#), @"");
3081        insta::assert_snapshot!(env.render_ok(r#""foo\nbar".first_line()"#), @"foo");
3082
3083        insta::assert_snapshot!(env.render_ok(r#""".lines()"#), @"");
3084        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc\n".lines()"#), @"a b c");
3085
3086        insta::assert_snapshot!(env.render_ok(r#""".starts_with("")"#), @"true");
3087        insta::assert_snapshot!(env.render_ok(r#""everything".starts_with("")"#), @"true");
3088        insta::assert_snapshot!(env.render_ok(r#""".starts_with("foo")"#), @"false");
3089        insta::assert_snapshot!(env.render_ok(r#""foo".starts_with("foo")"#), @"true");
3090        insta::assert_snapshot!(env.render_ok(r#""foobar".starts_with("foo")"#), @"true");
3091        insta::assert_snapshot!(env.render_ok(r#""foobar".starts_with("bar")"#), @"false");
3092
3093        insta::assert_snapshot!(env.render_ok(r#""".ends_with("")"#), @"true");
3094        insta::assert_snapshot!(env.render_ok(r#""everything".ends_with("")"#), @"true");
3095        insta::assert_snapshot!(env.render_ok(r#""".ends_with("foo")"#), @"false");
3096        insta::assert_snapshot!(env.render_ok(r#""foo".ends_with("foo")"#), @"true");
3097        insta::assert_snapshot!(env.render_ok(r#""foobar".ends_with("foo")"#), @"false");
3098        insta::assert_snapshot!(env.render_ok(r#""foobar".ends_with("bar")"#), @"true");
3099
3100        insta::assert_snapshot!(env.render_ok(r#""".remove_prefix("wip: ")"#), @"");
3101        insta::assert_snapshot!(
3102            env.render_ok(r#""wip: testing".remove_prefix("wip: ")"#),
3103            @"testing");
3104
3105        insta::assert_snapshot!(
3106            env.render_ok(r#""bar@my.example.com".remove_suffix("@other.example.com")"#),
3107            @"bar@my.example.com");
3108        insta::assert_snapshot!(
3109            env.render_ok(r#""bar@other.example.com".remove_suffix("@other.example.com")"#),
3110            @"bar");
3111
3112        insta::assert_snapshot!(env.render_ok(r#"" \n \r    \t \r ".trim()"#), @"");
3113        insta::assert_snapshot!(env.render_ok(r#"" \n \r foo  bar \t \r ".trim()"#), @"foo  bar");
3114
3115        insta::assert_snapshot!(env.render_ok(r#"" \n \r    \t \r ".trim_start()"#), @"");
3116        insta::assert_snapshot!(env.render_ok(r#"" \n \r foo  bar \t \r ".trim_start()"#), @"foo  bar");
3117
3118        insta::assert_snapshot!(env.render_ok(r#"" \n \r    \t \r ".trim_end()"#), @"");
3119        insta::assert_snapshot!(env.render_ok(r#"" \n \r foo  bar \t \r ".trim_end()"#), @" foo  bar");
3120
3121        insta::assert_snapshot!(env.render_ok(r#""foo".substr(0, 0)"#), @"");
3122        insta::assert_snapshot!(env.render_ok(r#""foo".substr(0, 1)"#), @"f");
3123        insta::assert_snapshot!(env.render_ok(r#""foo".substr(0, 3)"#), @"foo");
3124        insta::assert_snapshot!(env.render_ok(r#""foo".substr(0, 4)"#), @"foo");
3125        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(2, -1)"#), @"cde");
3126        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(-3, 99)"#), @"def");
3127        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(-6, 99)"#), @"abcdef");
3128        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(-7, 1)"#), @"a");
3129
3130        // non-ascii characters
3131        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(2, -1)"#), @"c💩");
3132        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, -3)"#), @"💩");
3133        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, -4)"#), @"");
3134        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(6, -3)"#), @"💩");
3135        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(7, -3)"#), @"");
3136        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, 4)"#), @"");
3137        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, 6)"#), @"");
3138        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, 7)"#), @"💩");
3139        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(-1, 7)"#), @"");
3140        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(-3, 7)"#), @"");
3141        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(-4, 7)"#), @"💩");
3142
3143        // ranges with end > start are empty
3144        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(4, 2)"#), @"");
3145        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(-2, -4)"#), @"");
3146
3147        insta::assert_snapshot!(env.render_ok(r#""hello".escape_json()"#), @r#""hello""#);
3148        insta::assert_snapshot!(env.render_ok(r#""he \n ll \n \" o".escape_json()"#), @r#""he \n ll \n \" o""#);
3149
3150        // simple substring replacement
3151        insta::assert_snapshot!(env.render_ok(r#""hello world".replace("world", "jj")"#), @"hello jj");
3152        insta::assert_snapshot!(env.render_ok(r#""hello world world".replace("world", "jj")"#), @"hello jj jj");
3153        insta::assert_snapshot!(env.render_ok(r#""hello".replace("missing", "jj")"#), @"hello");
3154
3155        // replace with limit >=0
3156        insta::assert_snapshot!(env.render_ok(r#""hello world world".replace("world", "jj", 0)"#), @"hello world world");
3157        insta::assert_snapshot!(env.render_ok(r#""hello world world".replace("world", "jj", 1)"#), @"hello jj world");
3158        insta::assert_snapshot!(env.render_ok(r#""hello world world world".replace("world", "jj", 2)"#), @"hello jj jj world");
3159
3160        // replace with limit <0 (error due to negative limit)
3161        insta::assert_snapshot!(env.render_ok(r#""hello world world".replace("world", "jj", -1)"#), @"<Error: out of range integral type conversion attempted>");
3162        insta::assert_snapshot!(env.render_ok(r#""hello world world".replace("world", "jj", -5)"#), @"<Error: out of range integral type conversion attempted>");
3163
3164        // replace with regex patterns
3165        insta::assert_snapshot!(env.render_ok(r#""hello123world456".replace(regex:'\d+', "X")"#), @"helloXworldX");
3166        insta::assert_snapshot!(env.render_ok(r#""hello123world456".replace(regex:'\d+', "X", 1)"#), @"helloXworld456");
3167
3168        // replace with regex patterns (capture groups)
3169        insta::assert_snapshot!(env.render_ok(r#""HELLO    WORLD".replace(regex-i:"(hello) +(world)", "$2 $1")"#), @"WORLD HELLO");
3170        insta::assert_snapshot!(env.render_ok(r#""abc123".replace(regex:"([a-z]+)([0-9]+)", "$2-$1")"#), @"123-abc");
3171        insta::assert_snapshot!(env.render_ok(r#""foo123bar".replace(regex:'\d+', "[$0]")"#), @"foo[123]bar");
3172
3173        // replace with regex patterns (case insensitive)
3174        insta::assert_snapshot!(env.render_ok(r#""Hello World".replace(regex-i:"hello", "hi")"#), @"hi World");
3175        insta::assert_snapshot!(env.render_ok(r#""Hello World Hello".replace(regex-i:"hello", "hi")"#), @"hi World hi");
3176        insta::assert_snapshot!(env.render_ok(r#""Hello World Hello".replace(regex-i:"hello", "hi", 1)"#), @"hi World Hello");
3177
3178        // replace with strings that look regex-y ($n patterns are always expanded)
3179        insta::assert_snapshot!(env.render_ok(r#"'hello\d+world'.replace('\d+', "X")"#), @"helloXworld");
3180        insta::assert_snapshot!(env.render_ok(r#""(foo)($1)bar".replace("$1", "$2")"#), @"(foo)()bar");
3181        insta::assert_snapshot!(env.render_ok(r#""test(abc)end".replace("(abc)", "X")"#), @"testXend");
3182
3183        // replace with templates
3184        insta::assert_snapshot!(env.render_ok(r#""hello world".replace("world", description.first_line())"#), @"hello description 1");
3185
3186        // replace with error
3187        insta::assert_snapshot!(env.render_ok(r#""hello world".replace("world", bad_string)"#), @"<Error: Bad>");
3188    }
3189
3190    #[test]
3191    fn test_config_value_method() {
3192        let mut env = TestTemplateEnv::new();
3193        env.add_keyword("boolean", || literal(ConfigValue::from(true)));
3194        env.add_keyword("integer", || literal(ConfigValue::from(42)));
3195        env.add_keyword("string", || literal(ConfigValue::from("foo")));
3196        env.add_keyword("string_list", || {
3197            literal(ConfigValue::from_iter(["foo", "bar"]))
3198        });
3199
3200        insta::assert_snapshot!(env.render_ok("boolean"), @"true");
3201        insta::assert_snapshot!(env.render_ok("integer"), @"42");
3202        insta::assert_snapshot!(env.render_ok("string"), @r#""foo""#);
3203        insta::assert_snapshot!(env.render_ok("string_list"), @r#"["foo", "bar"]"#);
3204
3205        insta::assert_snapshot!(env.render_ok("boolean.as_boolean()"), @"true");
3206        insta::assert_snapshot!(env.render_ok("integer.as_integer()"), @"42");
3207        insta::assert_snapshot!(env.render_ok("string.as_string()"), @"foo");
3208        insta::assert_snapshot!(env.render_ok("string_list.as_string_list()"), @"foo bar");
3209
3210        insta::assert_snapshot!(
3211            env.render_ok("boolean.as_integer()"),
3212            @"<Error: invalid type: boolean `true`, expected i64>");
3213        insta::assert_snapshot!(
3214            env.render_ok("integer.as_string()"),
3215            @"<Error: invalid type: integer `42`, expected a string>");
3216        insta::assert_snapshot!(
3217            env.render_ok("string.as_string_list()"),
3218            @r#"<Error: invalid type: string "foo", expected a sequence>"#);
3219        insta::assert_snapshot!(
3220            env.render_ok("string_list.as_boolean()"),
3221            @"<Error: invalid type: sequence, expected a boolean>");
3222    }
3223
3224    #[test]
3225    fn test_signature() {
3226        let mut env = TestTemplateEnv::new();
3227
3228        env.add_keyword("author", || {
3229            literal(new_signature("Test User", "test.user@example.com"))
3230        });
3231        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <test.user@example.com>");
3232        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"Test User");
3233        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user@example.com");
3234
3235        env.add_keyword("author", || {
3236            literal(new_signature("Another Test User", "test.user@example.com"))
3237        });
3238        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Another Test User <test.user@example.com>");
3239        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"Another Test User");
3240        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user@example.com");
3241
3242        env.add_keyword("author", || {
3243            literal(new_signature("Test User", "test.user@invalid@example.com"))
3244        });
3245        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <test.user@invalid@example.com>");
3246        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"Test User");
3247        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user@invalid@example.com");
3248
3249        env.add_keyword("author", || {
3250            literal(new_signature("Test User", "test.user"))
3251        });
3252        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <test.user>");
3253        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user");
3254
3255        env.add_keyword("author", || {
3256            literal(new_signature("Test User", "test.user+tag@example.com"))
3257        });
3258        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <test.user+tag@example.com>");
3259        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user+tag@example.com");
3260
3261        env.add_keyword("author", || literal(new_signature("Test User", "x@y")));
3262        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <x@y>");
3263        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"x@y");
3264
3265        env.add_keyword("author", || {
3266            literal(new_signature("", "test.user@example.com"))
3267        });
3268        insta::assert_snapshot!(env.render_ok(r#"author"#), @"<test.user@example.com>");
3269        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"");
3270        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user@example.com");
3271
3272        env.add_keyword("author", || literal(new_signature("Test User", "")));
3273        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User");
3274        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"Test User");
3275        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"");
3276
3277        env.add_keyword("author", || literal(new_signature("", "")));
3278        insta::assert_snapshot!(env.render_ok(r#"author"#), @"");
3279        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"");
3280        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"");
3281    }
3282
3283    #[test]
3284    fn test_size_hint_method() {
3285        let mut env = TestTemplateEnv::new();
3286
3287        env.add_keyword("unbounded", || literal((5, None)));
3288        insta::assert_snapshot!(env.render_ok(r#"unbounded.lower()"#), @"5");
3289        insta::assert_snapshot!(env.render_ok(r#"unbounded.upper()"#), @"");
3290        insta::assert_snapshot!(env.render_ok(r#"unbounded.exact()"#), @"");
3291        insta::assert_snapshot!(env.render_ok(r#"unbounded.zero()"#), @"false");
3292
3293        env.add_keyword("bounded", || literal((0, Some(10))));
3294        insta::assert_snapshot!(env.render_ok(r#"bounded.lower()"#), @"0");
3295        insta::assert_snapshot!(env.render_ok(r#"bounded.upper()"#), @"10");
3296        insta::assert_snapshot!(env.render_ok(r#"bounded.exact()"#), @"");
3297        insta::assert_snapshot!(env.render_ok(r#"bounded.zero()"#), @"false");
3298
3299        env.add_keyword("zero", || literal((0, Some(0))));
3300        insta::assert_snapshot!(env.render_ok(r#"zero.lower()"#), @"0");
3301        insta::assert_snapshot!(env.render_ok(r#"zero.upper()"#), @"0");
3302        insta::assert_snapshot!(env.render_ok(r#"zero.exact()"#), @"0");
3303        insta::assert_snapshot!(env.render_ok(r#"zero.zero()"#), @"true");
3304    }
3305
3306    #[test]
3307    fn test_timestamp_method() {
3308        let mut env = TestTemplateEnv::new();
3309        env.add_keyword("t0", || literal(new_timestamp(0, 0)));
3310
3311        insta::assert_snapshot!(
3312            env.render_ok(r#"t0.format("%Y%m%d %H:%M:%S")"#),
3313            @"19700101 00:00:00");
3314
3315        // Invalid format string
3316        insta::assert_snapshot!(env.parse_err(r#"t0.format("%_")"#), @r#"
3317         --> 1:11
3318          |
3319        1 | t0.format("%_")
3320          |           ^--^
3321          |
3322          = Invalid time format
3323        "#);
3324
3325        // Invalid type
3326        insta::assert_snapshot!(env.parse_err(r#"t0.format(0)"#), @r"
3327         --> 1:11
3328          |
3329        1 | t0.format(0)
3330          |           ^
3331          |
3332          = Expected string literal
3333        ");
3334
3335        // Dynamic string isn't supported yet
3336        insta::assert_snapshot!(env.parse_err(r#"t0.format("%Y" ++ "%m")"#), @r#"
3337         --> 1:11
3338          |
3339        1 | t0.format("%Y" ++ "%m")
3340          |           ^----------^
3341          |
3342          = Expected string literal
3343        "#);
3344
3345        // Literal alias expansion
3346        env.add_alias("time_format", r#""%Y-%m-%d""#);
3347        env.add_alias("bad_time_format", r#""%_""#);
3348        insta::assert_snapshot!(env.render_ok(r#"t0.format(time_format)"#), @"1970-01-01");
3349        insta::assert_snapshot!(env.parse_err(r#"t0.format(bad_time_format)"#), @r#"
3350         --> 1:11
3351          |
3352        1 | t0.format(bad_time_format)
3353          |           ^-------------^
3354          |
3355          = In alias `bad_time_format`
3356         --> 1:1
3357          |
3358        1 | "%_"
3359          | ^--^
3360          |
3361          = Invalid time format
3362        "#);
3363    }
3364
3365    #[test]
3366    fn test_fill_function() {
3367        let mut env = TestTemplateEnv::new();
3368        env.add_color("error", crossterm::style::Color::DarkRed);
3369
3370        insta::assert_snapshot!(
3371            env.render_ok(r#"fill(20, "The quick fox jumps over the " ++
3372                                  label("error", "lazy") ++ " dog\n")"#),
3373            @r"
3374        The quick fox jumps
3375        over the lazy dog
3376        ");
3377
3378        // A low value will not chop words, but can chop a label by words
3379        insta::assert_snapshot!(
3380            env.render_ok(r#"fill(9, "Longlonglongword an some short words " ++
3381                                  label("error", "longlonglongword and short words") ++
3382                                  " back out\n")"#),
3383            @r"
3384        Longlonglongword
3385        an some
3386        short
3387        words
3388        longlonglongword
3389        and short
3390        words
3391        back out
3392        ");
3393
3394        // Filling to 0 means breaking at every word
3395        insta::assert_snapshot!(
3396            env.render_ok(r#"fill(0, "The quick fox jumps over the " ++
3397                                  label("error", "lazy") ++ " dog\n")"#),
3398            @r"
3399        The
3400        quick
3401        fox
3402        jumps
3403        over
3404        the
3405        lazy
3406        dog
3407        ");
3408
3409        // Filling to -0 is the same as 0
3410        insta::assert_snapshot!(
3411            env.render_ok(r#"fill(-0, "The quick fox jumps over the " ++
3412                                  label("error", "lazy") ++ " dog\n")"#),
3413            @r"
3414        The
3415        quick
3416        fox
3417        jumps
3418        over
3419        the
3420        lazy
3421        dog
3422        ");
3423
3424        // Filling to negative width is an error
3425        insta::assert_snapshot!(
3426            env.render_ok(r#"fill(-10, "The quick fox jumps over the " ++
3427                                  label("error", "lazy") ++ " dog\n")"#),
3428            @"<Error: out of range integral type conversion attempted>");
3429
3430        // Word-wrap, then indent
3431        insta::assert_snapshot!(
3432            env.render_ok(r#""START marker to help insta\n" ++
3433                             indent("    ", fill(20, "The quick fox jumps over the " ++
3434                                                 label("error", "lazy") ++ " dog\n"))"#),
3435            @r"
3436        START marker to help insta
3437            The quick fox jumps
3438            over the lazy dog
3439        ");
3440
3441        // Word-wrap indented (no special handling for leading spaces)
3442        insta::assert_snapshot!(
3443            env.render_ok(r#""START marker to help insta\n" ++
3444                             fill(20, indent("    ", "The quick fox jumps over the " ++
3445                                             label("error", "lazy") ++ " dog\n"))"#),
3446            @r"
3447        START marker to help insta
3448            The quick fox
3449        jumps over the lazy
3450        dog
3451        ");
3452    }
3453
3454    #[test]
3455    fn test_indent_function() {
3456        let mut env = TestTemplateEnv::new();
3457        env.add_color("error", crossterm::style::Color::DarkRed);
3458        env.add_color("warning", crossterm::style::Color::DarkYellow);
3459        env.add_color("hint", crossterm::style::Color::DarkCyan);
3460
3461        // Empty line shouldn't be indented. Not using insta here because we test
3462        // whitespace existence.
3463        assert_eq!(env.render_ok(r#"indent("__", "")"#), "");
3464        assert_eq!(env.render_ok(r#"indent("__", "\n")"#), "\n");
3465        assert_eq!(env.render_ok(r#"indent("__", "a\n\nb")"#), "__a\n\n__b");
3466
3467        // "\n" at end of labeled text
3468        insta::assert_snapshot!(
3469            env.render_ok(r#"indent("__", label("error", "a\n") ++ label("warning", "b\n"))"#),
3470            @r"
3471        __a
3472        __b
3473        ");
3474
3475        // "\n" in labeled text
3476        insta::assert_snapshot!(
3477            env.render_ok(r#"indent("__", label("error", "a") ++ label("warning", "b\nc"))"#),
3478            @r"
3479        __ab
3480        __c
3481        ");
3482
3483        // Labeled prefix + unlabeled content
3484        insta::assert_snapshot!(
3485            env.render_ok(r#"indent(label("error", "XX"), "a\nb\n")"#),
3486            @r"
3487        XXa
3488        XXb
3489        ");
3490
3491        // Nested indent, silly but works
3492        insta::assert_snapshot!(
3493            env.render_ok(r#"indent(label("hint", "A"),
3494                                    label("warning", indent(label("hint", "B"),
3495                                                            label("error", "x\n") ++ "y")))"#),
3496            @r"
3497        ABx
3498        ABy
3499        ");
3500    }
3501
3502    #[test]
3503    fn test_pad_function() {
3504        let mut env = TestTemplateEnv::new();
3505        env.add_keyword("bad_string", || new_error_property::<String>("Bad"));
3506        env.add_color("red", crossterm::style::Color::Red);
3507        env.add_color("cyan", crossterm::style::Color::DarkCyan);
3508
3509        // Default fill_char is ' '
3510        insta::assert_snapshot!(
3511            env.render_ok(r"'{' ++ pad_start(5, label('red', 'foo')) ++ '}'"),
3512            @"{  foo}");
3513        insta::assert_snapshot!(
3514            env.render_ok(r"'{' ++ pad_end(5, label('red', 'foo')) ++ '}'"),
3515            @"{foo  }");
3516        insta::assert_snapshot!(
3517            env.render_ok(r"'{' ++ pad_centered(5, label('red', 'foo')) ++ '}'"),
3518            @"{ foo }");
3519
3520        // Labeled fill char
3521        insta::assert_snapshot!(
3522            env.render_ok(r"pad_start(5, label('red', 'foo'), fill_char=label('cyan', '='))"),
3523            @"==foo");
3524        insta::assert_snapshot!(
3525            env.render_ok(r"pad_end(5, label('red', 'foo'), fill_char=label('cyan', '='))"),
3526            @"foo==");
3527        insta::assert_snapshot!(
3528            env.render_ok(r"pad_centered(5, label('red', 'foo'), fill_char=label('cyan', '='))"),
3529            @"=foo=");
3530
3531        // Error in fill char: the output looks odd (because the error message
3532        // isn't 1-width character), but is still readable.
3533        insta::assert_snapshot!(
3534            env.render_ok(r"pad_start(3, 'foo', fill_char=bad_string)"),
3535            @"foo");
3536        insta::assert_snapshot!(
3537            env.render_ok(r"pad_end(5, 'foo', fill_char=bad_string)"),
3538            @"foo<<Error: Error: Bad>Bad>");
3539        insta::assert_snapshot!(
3540            env.render_ok(r"pad_centered(5, 'foo', fill_char=bad_string)"),
3541            @"<Error: Bad>foo<Error: Bad>");
3542    }
3543
3544    #[test]
3545    fn test_truncate_function() {
3546        let mut env = TestTemplateEnv::new();
3547        env.add_color("red", crossterm::style::Color::Red);
3548
3549        insta::assert_snapshot!(
3550            env.render_ok(r"truncate_start(2, label('red', 'foobar')) ++ 'baz'"),
3551            @"arbaz");
3552        insta::assert_snapshot!(
3553            env.render_ok(r"truncate_end(2, label('red', 'foobar')) ++ 'baz'"),
3554            @"fobaz");
3555    }
3556
3557    #[test]
3558    fn test_label_function() {
3559        let mut env = TestTemplateEnv::new();
3560        env.add_keyword("empty", || literal(true));
3561        env.add_color("error", crossterm::style::Color::DarkRed);
3562        env.add_color("warning", crossterm::style::Color::DarkYellow);
3563
3564        // Literal
3565        insta::assert_snapshot!(
3566            env.render_ok(r#"label("error", "text")"#),
3567            @"text");
3568
3569        // Evaluated property
3570        insta::assert_snapshot!(
3571            env.render_ok(r#"label("error".first_line(), "text")"#),
3572            @"text");
3573
3574        // Template
3575        insta::assert_snapshot!(
3576            env.render_ok(r#"label(if(empty, "error", "warning"), "text")"#),
3577            @"text");
3578    }
3579
3580    #[test]
3581    fn test_raw_escape_sequence_function_strip_labels() {
3582        let mut env = TestTemplateEnv::new();
3583        env.add_color("error", crossterm::style::Color::DarkRed);
3584        env.add_color("warning", crossterm::style::Color::DarkYellow);
3585
3586        insta::assert_snapshot!(
3587            env.render_ok(r#"raw_escape_sequence(label("error warning", "text"))"#),
3588            @"text",
3589        );
3590    }
3591
3592    #[test]
3593    fn test_raw_escape_sequence_function_ansi_escape() {
3594        let env = TestTemplateEnv::new();
3595
3596        // Sanitize ANSI escape without raw_escape_sequence
3597        insta::assert_snapshot!(env.render_ok(r#""\e""#), @"␛");
3598        insta::assert_snapshot!(env.render_ok(r#""\x1b""#), @"␛");
3599        insta::assert_snapshot!(env.render_ok(r#""\x1B""#), @"␛");
3600        insta::assert_snapshot!(
3601            env.render_ok(r#""]8;;"
3602                ++ "http://example.com"
3603                ++ "\e\\"
3604                ++ "Example"
3605                ++ "\x1b]8;;\x1B\\""#),
3606            @r"␛]8;;http://example.com␛\Example␛]8;;␛\");
3607
3608        // Don't sanitize ANSI escape with raw_escape_sequence
3609        insta::assert_snapshot!(env.render_ok(r#"raw_escape_sequence("\e")"#), @"");
3610        insta::assert_snapshot!(env.render_ok(r#"raw_escape_sequence("\x1b")"#), @"");
3611        insta::assert_snapshot!(env.render_ok(r#"raw_escape_sequence("\x1B")"#), @"");
3612        insta::assert_snapshot!(
3613            env.render_ok(r#"raw_escape_sequence("]8;;"
3614                ++ "http://example.com"
3615                ++ "\e\\"
3616                ++ "Example"
3617                ++ "\x1b]8;;\x1B\\")"#),
3618            @r"]8;;http://example.com\Example]8;;\");
3619    }
3620
3621    #[test]
3622    fn test_stringify_function() {
3623        let mut env = TestTemplateEnv::new();
3624        env.add_keyword("none_i64", || literal(None::<i64>));
3625        env.add_color("error", crossterm::style::Color::DarkRed);
3626
3627        insta::assert_snapshot!(env.render_ok("stringify(false)"), @"false");
3628        insta::assert_snapshot!(env.render_ok("stringify(42).len()"), @"2");
3629        insta::assert_snapshot!(env.render_ok("stringify(none_i64)"), @"");
3630        insta::assert_snapshot!(env.render_ok("stringify(label('error', 'text'))"), @"text");
3631    }
3632
3633    #[test]
3634    fn test_json_function() {
3635        let mut env = TestTemplateEnv::new();
3636        env.add_keyword("none_i64", || literal(None::<i64>));
3637        env.add_keyword("string_list", || {
3638            literal(vec!["foo".to_owned(), "bar".to_owned()])
3639        });
3640        env.add_keyword("config_value_table", || {
3641            literal(ConfigValue::from_iter([("foo", "bar")]))
3642        });
3643        env.add_keyword("signature", || {
3644            literal(Signature {
3645                name: "Test User".to_owned(),
3646                email: "test.user@example.com".to_owned(),
3647                timestamp: Timestamp {
3648                    timestamp: MillisSinceEpoch(0),
3649                    tz_offset: 0,
3650                },
3651            })
3652        });
3653        env.add_keyword("email", || literal(Email("foo@bar".to_owned())));
3654        env.add_keyword("size_hint", || literal((5, None)));
3655        env.add_keyword("timestamp", || {
3656            literal(Timestamp {
3657                timestamp: MillisSinceEpoch(0),
3658                tz_offset: 0,
3659            })
3660        });
3661        env.add_keyword("timestamp_range", || {
3662            literal(TimestampRange {
3663                start: Timestamp {
3664                    timestamp: MillisSinceEpoch(0),
3665                    tz_offset: 0,
3666                },
3667                end: Timestamp {
3668                    timestamp: MillisSinceEpoch(86_400_000),
3669                    tz_offset: -60,
3670                },
3671            })
3672        });
3673
3674        insta::assert_snapshot!(env.render_ok(r#"json('"quoted"')"#), @r#""\"quoted\"""#);
3675        insta::assert_snapshot!(env.render_ok(r#"json(string_list)"#), @r#"["foo","bar"]"#);
3676        insta::assert_snapshot!(env.render_ok("json(false)"), @"false");
3677        insta::assert_snapshot!(env.render_ok("json(42)"), @"42");
3678        insta::assert_snapshot!(env.render_ok("json(none_i64)"), @"null");
3679        insta::assert_snapshot!(env.render_ok(r#"json(config_value_table)"#), @r#"{"foo":"bar"}"#);
3680        insta::assert_snapshot!(env.render_ok("json(email)"), @r#""foo@bar""#);
3681        insta::assert_snapshot!(
3682            env.render_ok("json(signature)"),
3683            @r#"{"name":"Test User","email":"test.user@example.com","timestamp":"1970-01-01T00:00:00Z"}"#);
3684        insta::assert_snapshot!(env.render_ok("json(size_hint)"), @"[5,null]");
3685        insta::assert_snapshot!(env.render_ok("json(timestamp)"), @r#""1970-01-01T00:00:00Z""#);
3686        insta::assert_snapshot!(
3687            env.render_ok("json(timestamp_range)"),
3688            @r#"{"start":"1970-01-01T00:00:00Z","end":"1970-01-01T23:00:00-01:00"}"#);
3689
3690        insta::assert_snapshot!(env.parse_err(r#"json(string_list.map(|s| s))"#), @r"
3691         --> 1:6
3692          |
3693        1 | json(string_list.map(|s| s))
3694          |      ^--------------------^
3695          |
3696          = Expected expression of type `Serialize`, but actual type is `ListTemplate`
3697        ");
3698    }
3699
3700    #[test]
3701    fn test_coalesce_function() {
3702        let mut env = TestTemplateEnv::new();
3703        env.add_keyword("bad_string", || new_error_property::<String>("Bad"));
3704        env.add_keyword("empty_string", || literal("".to_owned()));
3705        env.add_keyword("non_empty_string", || literal("a".to_owned()));
3706
3707        insta::assert_snapshot!(env.render_ok(r#"coalesce()"#), @"");
3708        insta::assert_snapshot!(env.render_ok(r#"coalesce("")"#), @"");
3709        insta::assert_snapshot!(env.render_ok(r#"coalesce("", "a", "", "b")"#), @"a");
3710        insta::assert_snapshot!(
3711            env.render_ok(r#"coalesce(empty_string, "", non_empty_string)"#), @"a");
3712
3713        // "false" is not empty
3714        insta::assert_snapshot!(env.render_ok(r#"coalesce(false, true)"#), @"false");
3715
3716        // Error is not empty
3717        insta::assert_snapshot!(env.render_ok(r#"coalesce(bad_string, "a")"#), @"<Error: Bad>");
3718        // but can be short-circuited
3719        insta::assert_snapshot!(env.render_ok(r#"coalesce("a", bad_string)"#), @"a");
3720    }
3721
3722    #[test]
3723    fn test_concat_function() {
3724        let mut env = TestTemplateEnv::new();
3725        env.add_keyword("empty", || literal(true));
3726        env.add_keyword("hidden", || literal(false));
3727        env.add_color("empty", crossterm::style::Color::DarkGreen);
3728        env.add_color("error", crossterm::style::Color::DarkRed);
3729        env.add_color("warning", crossterm::style::Color::DarkYellow);
3730
3731        insta::assert_snapshot!(env.render_ok(r#"concat()"#), @"");
3732        insta::assert_snapshot!(
3733            env.render_ok(r#"concat(hidden, empty)"#),
3734            @"falsetrue");
3735        insta::assert_snapshot!(
3736            env.render_ok(r#"concat(label("error", ""), label("warning", "a"), "b")"#),
3737            @"ab");
3738    }
3739
3740    #[test]
3741    fn test_separate_function() {
3742        let mut env = TestTemplateEnv::new();
3743        env.add_keyword("description", || literal("".to_owned()));
3744        env.add_keyword("empty", || literal(true));
3745        env.add_keyword("hidden", || literal(false));
3746        env.add_color("empty", crossterm::style::Color::DarkGreen);
3747        env.add_color("error", crossterm::style::Color::DarkRed);
3748        env.add_color("warning", crossterm::style::Color::DarkYellow);
3749
3750        insta::assert_snapshot!(env.render_ok(r#"separate(" ")"#), @"");
3751        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "")"#), @"");
3752        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a")"#), @"a");
3753        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", "b")"#), @"a b");
3754        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", "", "b")"#), @"a b");
3755        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", "b", "")"#), @"a b");
3756        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "", "a", "b")"#), @"a b");
3757
3758        // Labeled
3759        insta::assert_snapshot!(
3760            env.render_ok(r#"separate(" ", label("error", ""), label("warning", "a"), "b")"#),
3761            @"a b");
3762
3763        // List template
3764        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", ("" ++ ""))"#), @"a");
3765        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", ("" ++ "b"))"#), @"a b");
3766
3767        // Nested separate
3768        insta::assert_snapshot!(
3769            env.render_ok(r#"separate(" ", "a", separate("|", "", ""))"#), @"a");
3770        insta::assert_snapshot!(
3771            env.render_ok(r#"separate(" ", "a", separate("|", "b", ""))"#), @"a b");
3772        insta::assert_snapshot!(
3773            env.render_ok(r#"separate(" ", "a", separate("|", "b", "c"))"#), @"a b|c");
3774
3775        // Conditional template
3776        insta::assert_snapshot!(
3777            env.render_ok(r#"separate(" ", "a", if(true, ""))"#), @"a");
3778        insta::assert_snapshot!(
3779            env.render_ok(r#"separate(" ", "a", if(true, "", "f"))"#), @"a");
3780        insta::assert_snapshot!(
3781            env.render_ok(r#"separate(" ", "a", if(false, "t", ""))"#), @"a");
3782        insta::assert_snapshot!(
3783            env.render_ok(r#"separate(" ", "a", if(true, "t", "f"))"#), @"a t");
3784
3785        // Separate keywords
3786        insta::assert_snapshot!(
3787            env.render_ok(r#"separate(" ", hidden, description, empty)"#),
3788            @"false true");
3789
3790        // Keyword as separator
3791        insta::assert_snapshot!(
3792            env.render_ok(r#"separate(hidden, "X", "Y", "Z")"#),
3793            @"XfalseYfalseZ");
3794    }
3795
3796    #[test]
3797    fn test_surround_function() {
3798        let mut env = TestTemplateEnv::new();
3799        env.add_keyword("lt", || literal("<".to_owned()));
3800        env.add_keyword("gt", || literal(">".to_owned()));
3801        env.add_keyword("content", || literal("content".to_owned()));
3802        env.add_keyword("empty_content", || literal("".to_owned()));
3803        env.add_color("error", crossterm::style::Color::DarkRed);
3804        env.add_color("paren", crossterm::style::Color::Cyan);
3805
3806        insta::assert_snapshot!(env.render_ok(r#"surround("{", "}", "")"#), @"");
3807        insta::assert_snapshot!(env.render_ok(r#"surround("{", "}", "a")"#), @"{a}");
3808
3809        // Labeled
3810        insta::assert_snapshot!(
3811            env.render_ok(
3812                r#"surround(label("paren", "("), label("paren", ")"), label("error", "a"))"#),
3813            @"(a)");
3814
3815        // Keyword
3816        insta::assert_snapshot!(
3817            env.render_ok(r#"surround(lt, gt, content)"#),
3818            @"<content>");
3819        insta::assert_snapshot!(
3820            env.render_ok(r#"surround(lt, gt, empty_content)"#),
3821            @"");
3822
3823        // Conditional template as content
3824        insta::assert_snapshot!(
3825            env.render_ok(r#"surround(lt, gt, if(empty_content, "", "empty"))"#),
3826            @"<empty>");
3827        insta::assert_snapshot!(
3828            env.render_ok(r#"surround(lt, gt, if(empty_content, "not empty", ""))"#),
3829            @"");
3830    }
3831}