mirror of
https://github.com/askama-rs/askama.git
synced 2025-09-29 22:11:17 +00:00
Run clippy --fix -- -D clippy::pedantic
This commit is contained in:
parent
0faa3bd2e5
commit
eed37cd415
@ -1,5 +1,5 @@
|
||||
{
|
||||
const STRING_LONG: &str = r#"
|
||||
const STRING_LONG: &str = r"
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat tellus sit
|
||||
amet ornare fermentum. Etiam nec erat ante. In at metus a orci mollis scelerisque.
|
||||
Sed eget ultrices turpis, at sollicitudin erat. Integer hendrerit nec magna quis
|
||||
@ -36,7 +36,7 @@
|
||||
suscipit leo, lacinia dignissim lacus. Sed eget volutpat mi. In eu bibendum neque. Pellentesque
|
||||
finibus velit a fermentum rhoncus. Maecenas leo purus, eleifend eu lacus a, condimentum sagittis
|
||||
justo.
|
||||
</p>"#;
|
||||
</p>";
|
||||
|
||||
const STRING_SHORT: &str = "Lorem ipsum dolor sit amet,<foo>bar&foo\"bar\\foo/bar";
|
||||
|
||||
@ -44,7 +44,7 @@
|
||||
|
||||
const NO_ESCAPE: &str = "Lorem ipsum dolor sit amet,";
|
||||
|
||||
const NO_ESCAPE_LONG: &str = r#"
|
||||
const NO_ESCAPE_LONG: &str = r"
|
||||
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin scelerisque eu urna in aliquet.
|
||||
Phasellus ac nulla a urna sagittis consequat id quis est. Nullam eu ex eget erat accumsan dictum
|
||||
ac lobortis urna. Etiam fermentum ut quam at dignissim. Curabitur vestibulum luctus tellus, sit
|
||||
@ -56,7 +56,7 @@ lacus ipsum eget quam. Vivamus orci lorem, maximus ac mi eget, bibendum vulputat
|
||||
vestibulum dui hendrerit, vestibulum lacus sit amet, posuere erat. Vivamus euismod massa diam,
|
||||
vulputate euismod lectus vestibulum nec. Donec sit amet massa magna. Nunc ipsum nulla, euismod
|
||||
quis lacus at, gravida maximus elit. Duis tristique, nisl nullam.
|
||||
"#;
|
||||
";
|
||||
|
||||
const STRINGS: &[&str] = &[
|
||||
STRING_LONG,
|
||||
|
@ -685,7 +685,7 @@ const _: () = {
|
||||
std::sync::RwLockWriteGuard<'_, T>
|
||||
}
|
||||
|
||||
/// implement PluralizeCount for unsigned integer types
|
||||
/// implement `PluralizeCount` for unsigned integer types
|
||||
macro_rules! impl_pluralize_for_unsigned_int {
|
||||
($($ty:ty)*) => { $(
|
||||
impl PluralizeCount for $ty {
|
||||
@ -701,7 +701,7 @@ const _: () = {
|
||||
|
||||
impl_pluralize_for_unsigned_int!(u8 u16 u32 u64 u128 usize);
|
||||
|
||||
/// implement PluralizeCount for signed integer types
|
||||
/// implement `PluralizeCount` for signed integer types
|
||||
macro_rules! impl_pluralize_for_signed_int {
|
||||
($($ty:ty)*) => { $(
|
||||
impl PluralizeCount for $ty {
|
||||
@ -717,7 +717,7 @@ const _: () = {
|
||||
|
||||
impl_pluralize_for_signed_int!(i8 i16 i32 i64 i128 isize);
|
||||
|
||||
/// implement PluralizeCount for non-zero integer types
|
||||
/// implement `PluralizeCount` for non-zero integer types
|
||||
macro_rules! impl_pluralize_for_non_zero {
|
||||
($($ty:ident)*) => { $(
|
||||
impl PluralizeCount for std::num::$ty {
|
||||
@ -1009,7 +1009,7 @@ mod tests {
|
||||
assert_eq!(capitalize("foo").unwrap().to_string(), "Foo".to_string());
|
||||
assert_eq!(capitalize("f").unwrap().to_string(), "F".to_string());
|
||||
assert_eq!(capitalize("fO").unwrap().to_string(), "Fo".to_string());
|
||||
assert_eq!(capitalize("").unwrap().to_string(), "".to_string());
|
||||
assert_eq!(capitalize("").unwrap().to_string(), String::new());
|
||||
assert_eq!(capitalize("FoO").unwrap().to_string(), "Foo".to_string());
|
||||
assert_eq!(
|
||||
capitalize("foO BAR").unwrap().to_string(),
|
||||
|
@ -14,6 +14,7 @@ use actix_web::{HttpResponse, HttpResponseBuilder, ResponseError};
|
||||
pub use rinja::*;
|
||||
|
||||
/// Render a [`Template`] into a [`HttpResponse`], or render an error page.
|
||||
#[must_use]
|
||||
pub fn into_response<T: ?Sized + rinja::Template>(tmpl: &T) -> HttpResponse<BoxBody> {
|
||||
try_into_response(tmpl).unwrap_or_else(|err| HttpResponse::from_error(ActixError(err)))
|
||||
}
|
||||
@ -28,7 +29,7 @@ pub fn try_into_response<T: ?Sized + rinja::Template>(
|
||||
.body(value))
|
||||
}
|
||||
|
||||
/// Newtype to let rinja::Error implement actix_web::ResponseError.
|
||||
/// Newtype to let `rinja::Error` implement `actix_web::ResponseError`.
|
||||
struct ActixError(Error);
|
||||
|
||||
impl fmt::Debug for ActixError {
|
||||
|
@ -9,6 +9,7 @@ use axum_core::response::{IntoResponse, Response};
|
||||
pub use rinja::*;
|
||||
|
||||
/// Render a [`Template`] into a [`Response`], or render an error page.
|
||||
#[must_use]
|
||||
pub fn into_response<T: ?Sized + rinja::Template>(tmpl: &T) -> Response {
|
||||
try_into_response(tmpl)
|
||||
.map_err(|err| axum_core::response::ErrorResponse::from(err.to_string()))
|
||||
|
@ -396,7 +396,7 @@ pub(crate) fn read_config_file(
|
||||
span,
|
||||
))
|
||||
} else {
|
||||
Ok("".to_string())
|
||||
Ok(String::new())
|
||||
}
|
||||
}
|
||||
|
||||
@ -767,7 +767,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_config_whitespace_error() {
|
||||
let config = Config::new(r#""#, None, Some("trim"), None);
|
||||
let config = Config::new(r"", None, Some("trim"), None);
|
||||
if let Err(err) = config {
|
||||
assert_eq!(err.msg, "invalid value for `whitespace`: \"trim\"");
|
||||
} else {
|
||||
|
@ -757,17 +757,17 @@ impl<'a> Generator<'a> {
|
||||
// an iterator. If not then the user can explicitly add the needed
|
||||
// call without issues.
|
||||
Expr::Call(..) | Expr::Index(..) => {
|
||||
buf.write(format_args!("let _iter = ({expr_code}).into_iter();"))
|
||||
buf.write(format_args!("let _iter = ({expr_code}).into_iter();"));
|
||||
}
|
||||
// If accessing `self` then it most likely needs to be
|
||||
// borrowed, to prevent an attempt of moving.
|
||||
_ if expr_code.starts_with("self.") => {
|
||||
buf.write(format_args!("let _iter = (&{expr_code}).into_iter();"))
|
||||
buf.write(format_args!("let _iter = (&{expr_code}).into_iter();"));
|
||||
}
|
||||
// If accessing a field then it most likely needs to be
|
||||
// borrowed, to prevent an attempt of moving.
|
||||
Expr::Attr(..) => {
|
||||
buf.write(format_args!("let _iter = (&{expr_code}).into_iter();"))
|
||||
buf.write(format_args!("let _iter = (&{expr_code}).into_iter();"));
|
||||
}
|
||||
// Otherwise, we borrow `iter` assuming that it implements `IntoIterator`.
|
||||
_ => buf.write(format_args!("let _iter = ({expr_code}).into_iter();")),
|
||||
@ -837,25 +837,23 @@ impl<'a> Generator<'a> {
|
||||
return self.write_block(ctx, buf, None, ws, call);
|
||||
}
|
||||
|
||||
let (def, own_ctx) = match scope {
|
||||
Some(s) => {
|
||||
let path = ctx.imports.get(s).ok_or_else(|| {
|
||||
ctx.generate_error(&format!("no import found for scope {s:?}"), call)
|
||||
})?;
|
||||
let mctx = self.contexts.get(path).ok_or_else(|| {
|
||||
ctx.generate_error(&format!("context for {path:?} not found"), call)
|
||||
})?;
|
||||
let def = mctx.macros.get(name).ok_or_else(|| {
|
||||
ctx.generate_error(&format!("macro {name:?} not found in scope {s:?}"), call)
|
||||
})?;
|
||||
(def, mctx)
|
||||
}
|
||||
None => {
|
||||
let def = ctx.macros.get(name).ok_or_else(|| {
|
||||
ctx.generate_error(&format!("macro {name:?} not found"), call)
|
||||
})?;
|
||||
(def, ctx)
|
||||
}
|
||||
let (def, own_ctx) = if let Some(s) = scope {
|
||||
let path = ctx.imports.get(s).ok_or_else(|| {
|
||||
ctx.generate_error(&format!("no import found for scope {s:?}"), call)
|
||||
})?;
|
||||
let mctx = self.contexts.get(path).ok_or_else(|| {
|
||||
ctx.generate_error(&format!("context for {path:?} not found"), call)
|
||||
})?;
|
||||
let def = mctx.macros.get(name).ok_or_else(|| {
|
||||
ctx.generate_error(&format!("macro {name:?} not found in scope {s:?}"), call)
|
||||
})?;
|
||||
(def, mctx)
|
||||
} else {
|
||||
let def = ctx
|
||||
.macros
|
||||
.get(name)
|
||||
.ok_or_else(|| ctx.generate_error(&format!("macro {name:?} not found"), call))?;
|
||||
(def, ctx)
|
||||
};
|
||||
|
||||
self.flush_ws(ws); // Cannot handle_ws() here: whitespace from macro definition comes first
|
||||
@ -906,25 +904,22 @@ impl<'a> Generator<'a> {
|
||||
// anything since named arguments are always last).
|
||||
let mut allow_positional = true;
|
||||
for (index, arg) in def.args.iter().enumerate() {
|
||||
let expr = match named_arguments.get(&Cow::Borrowed(arg)) {
|
||||
Some(expr) => {
|
||||
allow_positional = false;
|
||||
expr
|
||||
}
|
||||
None => {
|
||||
if !allow_positional {
|
||||
// If there is already at least one named argument, then it's not allowed
|
||||
// to use unnamed ones at this point anymore.
|
||||
return Err(ctx.generate_error(
|
||||
&format!(
|
||||
"cannot have unnamed argument (`{arg}`) after named argument in macro \
|
||||
{name:?}"
|
||||
),
|
||||
call,
|
||||
));
|
||||
}
|
||||
&args[index]
|
||||
let expr = if let Some(expr) = named_arguments.get(&Cow::Borrowed(arg)) {
|
||||
allow_positional = false;
|
||||
expr
|
||||
} else {
|
||||
if !allow_positional {
|
||||
// If there is already at least one named argument, then it's not allowed
|
||||
// to use unnamed ones at this point anymore.
|
||||
return Err(ctx.generate_error(
|
||||
&format!(
|
||||
"cannot have unnamed argument (`{arg}`) after named argument in macro \
|
||||
{name:?}"
|
||||
),
|
||||
call,
|
||||
));
|
||||
}
|
||||
&args[index]
|
||||
};
|
||||
match &**expr {
|
||||
// If `expr` is already a form of variable then
|
||||
@ -949,7 +944,7 @@ impl<'a> Generator<'a> {
|
||||
// parameters being used multiple times.
|
||||
_ => {
|
||||
if is_first_variable {
|
||||
is_first_variable = false
|
||||
is_first_variable = false;
|
||||
} else {
|
||||
names.write(',');
|
||||
values.write(',');
|
||||
@ -1407,7 +1402,7 @@ impl<'a> Generator<'a> {
|
||||
self.next_ws = Some(lws);
|
||||
}
|
||||
WhitespaceHandling::Preserve => {
|
||||
self.buf_writable.push(Writable::Lit(Cow::Borrowed(lws)))
|
||||
self.buf_writable.push(Writable::Lit(Cow::Borrowed(lws)));
|
||||
}
|
||||
WhitespaceHandling::Minimize => {
|
||||
self.buf_writable.push(Writable::Lit(Cow::Borrowed(
|
||||
@ -2176,7 +2171,7 @@ impl<'a> Generator<'a> {
|
||||
match target {
|
||||
Target::Placeholder(s) => buf.write(s),
|
||||
Target::Rest(s) => {
|
||||
if let Some(var_name) = s.deref() {
|
||||
if let Some(var_name) = &**s {
|
||||
self.locals
|
||||
.insert(Cow::Borrowed(var_name), LocalMeta::initialized());
|
||||
buf.write(var_name);
|
||||
@ -2578,7 +2573,7 @@ impl Buffer {
|
||||
self.buf.push_str(OPEN);
|
||||
} else {
|
||||
// strip trailing `")?;`, leaving an unterminated string
|
||||
self.buf.truncate(self.buf.len() - CLOSE.len())
|
||||
self.buf.truncate(self.buf.len() - CLOSE.len());
|
||||
}
|
||||
string_escape(&mut self.buf, s);
|
||||
self.buf.push_str(CLOSE);
|
||||
@ -2593,7 +2588,7 @@ trait BufferFmt {
|
||||
|
||||
impl<T: BufferFmt + ?Sized> BufferFmt for &T {
|
||||
fn append_to(&self, buf: &mut String) {
|
||||
T::append_to(self, buf)
|
||||
T::append_to(self, buf);
|
||||
}
|
||||
}
|
||||
|
||||
@ -3028,9 +3023,9 @@ pub(crate) fn string_escape(dest: &mut String, src: &str) {
|
||||
for x in memchr::memchr3_iter(b'\\', b'"', b'\r', src) {
|
||||
dest.extend(&src[last..x]);
|
||||
dest.extend(match src[x] {
|
||||
b'\\' => br#"\\"#,
|
||||
b'\\' => br"\\",
|
||||
b'\"' => br#"\""#,
|
||||
_ => br#"\r"#,
|
||||
_ => br"\r",
|
||||
});
|
||||
last = x + 1;
|
||||
}
|
||||
|
@ -93,7 +93,8 @@ impl TemplateInput<'_> {
|
||||
|
||||
let escaping = escaping
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| path.extension().map(|s| s.to_str().unwrap()).unwrap_or(""));
|
||||
.or_else(|| path.extension().and_then(|s| s.to_str()))
|
||||
.unwrap_or_default();
|
||||
|
||||
let escaper = config
|
||||
.escapers
|
||||
@ -406,7 +407,7 @@ impl TemplateArgs {
|
||||
set_template_str_attr(ident, value, &mut args.syntax)?;
|
||||
} else if ident == "config" {
|
||||
set_template_str_attr(ident, value, &mut args.config)?;
|
||||
args.config_span = Some(value.span())
|
||||
args.config_span = Some(value.span());
|
||||
} else if ident == "whitespace" {
|
||||
set_template_str_attr(ident, value, &mut args.whitespace)?;
|
||||
} else {
|
||||
@ -771,7 +772,7 @@ pub(crate) fn get_template_source(
|
||||
tpl_path,
|
||||
(),
|
||||
Arc::clone,
|
||||
|_, tpl_path| match read_to_string(tpl_path) {
|
||||
|(), tpl_path| match read_to_string(tpl_path) {
|
||||
Ok(mut source) => {
|
||||
if source.ends_with('\n') {
|
||||
let _ = source.pop();
|
||||
@ -789,7 +790,7 @@ pub(crate) fn get_template_source(
|
||||
}),
|
||||
)),
|
||||
},
|
||||
|_, _, cached| Arc::clone(cached),
|
||||
|(), _, cached| Arc::clone(cached),
|
||||
)
|
||||
}
|
||||
|
||||
|
@ -64,7 +64,7 @@ use syn::parse_quote_spanned;
|
||||
/// web framework integrations use it to determine the content type.
|
||||
/// Cannot be used together with `path`.
|
||||
///
|
||||
/// ### in_doc
|
||||
/// ### `in_doc`
|
||||
///
|
||||
/// E.g. `in_doc = true`
|
||||
///
|
||||
@ -113,6 +113,7 @@ use syn::parse_quote_spanned;
|
||||
not(feature = "__standalone"),
|
||||
proc_macro_derive(Template, attributes(template))
|
||||
)]
|
||||
#[must_use]
|
||||
pub fn derive_template(input: TokenStream12) -> TokenStream12 {
|
||||
let ast = match syn::parse2(input.into()) {
|
||||
Ok(ast) => ast,
|
||||
@ -207,7 +208,7 @@ fn build_template_inner(
|
||||
if let Some(block_name) = input.block {
|
||||
if !heritage.blocks.contains_key(&block_name) {
|
||||
return Err(CompileError::no_file_info(
|
||||
format!("cannot find block {}", block_name),
|
||||
format!("cannot find block {block_name}"),
|
||||
None,
|
||||
));
|
||||
}
|
||||
@ -310,24 +311,21 @@ impl<'a> FileInfo<'a> {
|
||||
|
||||
impl fmt::Display for FileInfo<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match (self.source, self.node_source) {
|
||||
(Some(source), Some(node_source)) => {
|
||||
let (error_info, file_path) = generate_error_info(source, node_source, self.path);
|
||||
write!(
|
||||
f,
|
||||
"\n --> {file_path}:{row}:{column}\n{source_after}",
|
||||
row = error_info.row,
|
||||
column = error_info.column,
|
||||
source_after = &error_info.source_after,
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let file_path = match std::env::current_dir() {
|
||||
Ok(cwd) => strip_common(&cwd, self.path),
|
||||
Err(_) => self.path.display().to_string(),
|
||||
};
|
||||
write!(f, "\n --> {file_path}")
|
||||
}
|
||||
if let (Some(source), Some(node_source)) = (self.source, self.node_source) {
|
||||
let (error_info, file_path) = generate_error_info(source, node_source, self.path);
|
||||
write!(
|
||||
f,
|
||||
"\n --> {file_path}:{row}:{column}\n{source_after}",
|
||||
row = error_info.row,
|
||||
column = error_info.column,
|
||||
source_after = &error_info.source_after,
|
||||
)
|
||||
} else {
|
||||
let file_path = match std::env::current_dir() {
|
||||
Ok(cwd) => strip_common(&cwd, self.path),
|
||||
Err(_) => self.path.display().to_string(),
|
||||
};
|
||||
write!(f, "\n --> {file_path}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -133,7 +133,7 @@ fn check_if_let() {
|
||||
// In this test, we ensure that `query` never is `self.query`.
|
||||
compare(
|
||||
"{% if let Some(query) = s && !query.is_empty() %}{{query}}{% endif %}",
|
||||
r#"if let Some(query,) = &self.s && !query.is_empty() {
|
||||
r"if let Some(query,) = &self.s && !query.is_empty() {
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(&(query), ::rinja::filters::Text)).rinja_auto_escape()?),
|
||||
) {
|
||||
@ -141,7 +141,7 @@ fn check_if_let() {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
}",
|
||||
&[],
|
||||
3,
|
||||
);
|
||||
@ -150,7 +150,7 @@ fn check_if_let() {
|
||||
// condition.
|
||||
compare(
|
||||
"{% if let Some(s) = s %}{{ s }}{% endif %}",
|
||||
r#"if let Some(s,) = &self.s {
|
||||
r"if let Some(s,) = &self.s {
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(&(s), ::rinja::filters::Text)).rinja_auto_escape()?),
|
||||
) {
|
||||
@ -158,7 +158,7 @@ fn check_if_let() {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
}",
|
||||
&[],
|
||||
3,
|
||||
);
|
||||
@ -167,7 +167,7 @@ fn check_if_let() {
|
||||
// condition.
|
||||
compare(
|
||||
"{% if let Some(s) = s && !s.is_empty() %}{{s}}{% endif %}",
|
||||
r#"if let Some(s,) = &self.s && !s.is_empty() {
|
||||
r"if let Some(s,) = &self.s && !s.is_empty() {
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(&(s), ::rinja::filters::Text)).rinja_auto_escape()?),
|
||||
) {
|
||||
@ -175,7 +175,7 @@ fn check_if_let() {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
}",
|
||||
&[],
|
||||
3,
|
||||
);
|
||||
@ -299,7 +299,7 @@ writer.write_str("12")?;
|
||||
// are present.
|
||||
compare(
|
||||
"{% if y is defined || x == 12 %}{{x}}{% endif %}",
|
||||
r#"if *(&(self.x == 12) as &::core::primitive::bool) {
|
||||
r"if *(&(self.x == 12) as &::core::primitive::bool) {
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(&(self.x), ::rinja::filters::Text)).rinja_auto_escape()?),
|
||||
) {
|
||||
@ -308,26 +308,26 @@ writer.write_str("12")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[("x", "u32")],
|
||||
3,
|
||||
);
|
||||
compare(
|
||||
"{% if y is defined || x == 12 %}{{x}}{% endif %}",
|
||||
r#"match (
|
||||
r"match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(&(self.x), ::rinja::filters::Text)).rinja_auto_escape()?),
|
||||
) {
|
||||
(expr0,) => {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[("y", "u32"), ("x", "u32")],
|
||||
3,
|
||||
);
|
||||
compare(
|
||||
"{% if y is defined && y == 12 %}{{x}}{% endif %}",
|
||||
r#""#,
|
||||
r"",
|
||||
&[],
|
||||
0,
|
||||
);
|
||||
@ -362,7 +362,7 @@ if *(&(self.y == 12) as &::core::primitive::bool) {
|
||||
// Since the first `if` is always `true`, the `else` should not be generated.
|
||||
compare(
|
||||
"{% if y is defined %}{{y}}{% else %}bli{% endif %}",
|
||||
r#"
|
||||
r"
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(
|
||||
&(self.y),
|
||||
@ -374,7 +374,7 @@ match (
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[("y", "u32")],
|
||||
3,
|
||||
);
|
||||
@ -487,20 +487,20 @@ fn check_bool_conditions() {
|
||||
|
||||
compare(
|
||||
"{% if true || x == 12 %}{{x}}{% endif %}",
|
||||
r#"match (
|
||||
r"match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(&(self.x), ::rinja::filters::Text)).rinja_auto_escape()?),
|
||||
) {
|
||||
(expr0,) => {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[("x", "u32")],
|
||||
3,
|
||||
);
|
||||
compare(
|
||||
"{% if false || x == 12 %}{{x}}{% endif %}",
|
||||
r#"if *(&(self.x == 12) as &::core::primitive::bool) {
|
||||
r"if *(&(self.x == 12) as &::core::primitive::bool) {
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(
|
||||
&(self.x),
|
||||
@ -513,7 +513,7 @@ fn check_bool_conditions() {
|
||||
}
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[("x", "u32")],
|
||||
3,
|
||||
);
|
||||
@ -524,7 +524,7 @@ fn check_bool_conditions() {
|
||||
// condition.
|
||||
compare(
|
||||
"{% if y == 3 || (true || x == 12) %}{{x}}{% endif %}",
|
||||
r#"if *(&(self.y == 3 || (true)) as &::core::primitive::bool) {
|
||||
r"if *(&(self.y == 3 || (true)) as &::core::primitive::bool) {
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(
|
||||
&(self.x),
|
||||
@ -537,7 +537,7 @@ fn check_bool_conditions() {
|
||||
}
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[],
|
||||
3,
|
||||
);
|
||||
@ -545,7 +545,7 @@ fn check_bool_conditions() {
|
||||
// be evaluated so the whole code is removed.
|
||||
compare(
|
||||
"{% if (true || x == 12) || y == 3 %}{{x}}{% endif %}",
|
||||
r#"match (
|
||||
r"match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(
|
||||
&(self.x),
|
||||
::rinja::filters::Text,
|
||||
@ -556,13 +556,13 @@ fn check_bool_conditions() {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[],
|
||||
3,
|
||||
);
|
||||
compare(
|
||||
"{% if y == 3 || (x == 12 || true) %}{{x}}{% endif %}",
|
||||
r#"if *(&(self.y == 3 || (self.x == 12 || true)) as &::core::primitive::bool) {
|
||||
r"if *(&(self.y == 3 || (self.x == 12 || true)) as &::core::primitive::bool) {
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(
|
||||
&(self.x),
|
||||
@ -575,7 +575,7 @@ fn check_bool_conditions() {
|
||||
}
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[],
|
||||
3,
|
||||
);
|
||||
@ -630,7 +630,7 @@ A
|
||||
);
|
||||
|
||||
compare(
|
||||
r#"{{ 1_2_3_4 }} {{ 4e3 }} {{ false }}"#,
|
||||
r"{{ 1_2_3_4 }} {{ 4e3 }} {{ false }}",
|
||||
r#"writer.write_str("1234 4000 false")?;"#,
|
||||
&[],
|
||||
15,
|
||||
@ -738,7 +738,7 @@ fn test_code_in_comment() {
|
||||
#[test]
|
||||
fn test_pluralize() {
|
||||
compare(
|
||||
r#"{{dogs}} dog{{dogs|pluralize}}"#,
|
||||
r"{{dogs}} dog{{dogs|pluralize}}",
|
||||
r#"
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(
|
||||
@ -811,8 +811,8 @@ fn test_pluralize() {
|
||||
);
|
||||
|
||||
compare(
|
||||
r#"{{count|pluralize(one, count)}}"#,
|
||||
r#"
|
||||
r"{{count|pluralize(one, count)}}",
|
||||
r"
|
||||
match (
|
||||
&(::rinja::filters::pluralize(
|
||||
&(self.count),
|
||||
@ -832,14 +832,14 @@ fn test_pluralize() {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[("count", "i8"), ("one", "&'static str")],
|
||||
3,
|
||||
);
|
||||
|
||||
compare(
|
||||
r#"{{0|pluralize(sg, pl)}}"#,
|
||||
r#"
|
||||
r"{{0|pluralize(sg, pl)}}",
|
||||
r"
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(&(self.pl), ::rinja::filters::Text))
|
||||
.rinja_auto_escape()?),
|
||||
@ -848,13 +848,13 @@ fn test_pluralize() {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[("sg", "&'static str"), ("pl", "&'static str")],
|
||||
3,
|
||||
);
|
||||
compare(
|
||||
r#"{{1|pluralize(sg, pl)}}"#,
|
||||
r#"
|
||||
r"{{1|pluralize(sg, pl)}}",
|
||||
r"
|
||||
match (
|
||||
&((&&::rinja::filters::AutoEscaper::new(&(self.sg), ::rinja::filters::Text))
|
||||
.rinja_auto_escape()?),
|
||||
@ -863,7 +863,7 @@ fn test_pluralize() {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[("sg", "&'static str"), ("pl", "&'static str")],
|
||||
3,
|
||||
);
|
||||
@ -894,7 +894,7 @@ fn test_pluralize() {
|
||||
);
|
||||
|
||||
compare(
|
||||
r#"{{0|pluralize}}"#,
|
||||
r"{{0|pluralize}}",
|
||||
r#"
|
||||
match (&(::rinja::filters::Safe("s")),) {
|
||||
(expr0,) => {
|
||||
@ -906,14 +906,14 @@ fn test_pluralize() {
|
||||
3,
|
||||
);
|
||||
compare(
|
||||
r#"{{1|pluralize}}"#,
|
||||
r#"
|
||||
r"{{1|pluralize}}",
|
||||
r"
|
||||
match (&(::rinja::helpers::Empty),) {
|
||||
(expr0,) => {
|
||||
(&&::rinja::filters::Writable(expr0)).rinja_write(writer)?;
|
||||
}
|
||||
}
|
||||
"#,
|
||||
",
|
||||
&[],
|
||||
3,
|
||||
);
|
||||
|
@ -20,7 +20,7 @@ fn hello_world(c: &mut Criterion) {
|
||||
|| ts.clone(),
|
||||
rinja_derive_standalone::derive_template,
|
||||
BatchSize::LargeInput,
|
||||
)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -300,12 +300,9 @@ impl<'a> Expr<'a> {
|
||||
let (_, level) = level.nest(i)?;
|
||||
let start = i;
|
||||
let (i, expr) = preceded(ws(char('(')), opt(|i| Self::parse(i, level)))(i)?;
|
||||
let expr = match expr {
|
||||
Some(expr) => expr,
|
||||
None => {
|
||||
let (i, _) = char(')')(i)?;
|
||||
return Ok((i, WithSpan::new(Self::Tuple(vec![]), start)));
|
||||
}
|
||||
let Some(expr) = expr else {
|
||||
let (i, _) = char(')')(i)?;
|
||||
return Ok((i, WithSpan::new(Self::Tuple(vec![]), start)));
|
||||
};
|
||||
|
||||
let (i, comma) = ws(opt(peek(char(','))))(i)?;
|
||||
@ -315,10 +312,10 @@ impl<'a> Expr<'a> {
|
||||
}
|
||||
|
||||
let mut exprs = vec![expr];
|
||||
let (i, _) = fold_many0(
|
||||
let (i, ()) = fold_many0(
|
||||
preceded(char(','), ws(|i| Self::parse(i, level))),
|
||||
|| (),
|
||||
|_, expr| {
|
||||
|(), expr| {
|
||||
exprs.push(expr);
|
||||
},
|
||||
)(i)?;
|
||||
@ -372,6 +369,7 @@ impl<'a> Expr<'a> {
|
||||
map(char_lit, |i| WithSpan::new(Self::CharLit(i), start))(i)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn contains_bool_lit_or_is_defined(&self) -> bool {
|
||||
match self {
|
||||
Self::BoolLit(_) | Self::IsDefined(_) | Self::IsNotDefined(_) => true,
|
||||
@ -459,7 +457,7 @@ impl<'a> Suffix<'a> {
|
||||
match suffix {
|
||||
Some(Self::Attr(attr)) => expr = WithSpan::new(Expr::Attr(expr.into(), attr), i),
|
||||
Some(Self::Index(index)) => {
|
||||
expr = WithSpan::new(Expr::Index(expr.into(), index.into()), i)
|
||||
expr = WithSpan::new(Expr::Index(expr.into(), index.into()), i);
|
||||
}
|
||||
Some(Self::Call(args)) => expr = WithSpan::new(Expr::Call(expr.into(), args), i),
|
||||
Some(Self::Try) => expr = WithSpan::new(Expr::Try(expr.into()), i),
|
||||
|
@ -62,10 +62,12 @@ mod _parsed {
|
||||
}
|
||||
|
||||
// The return value's lifetime must be limited to `self` to uphold the unsafe invariant.
|
||||
#[must_use]
|
||||
pub fn nodes(&self) -> &[Node<'_>] {
|
||||
&self.ast.nodes
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn source(&self) -> &str {
|
||||
&self.source
|
||||
}
|
||||
@ -124,6 +126,7 @@ impl<'a> Ast<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn nodes(&self) -> &[Node<'a>] {
|
||||
&self.nodes
|
||||
}
|
||||
@ -205,7 +208,7 @@ impl fmt::Display for ParseError {
|
||||
} = self;
|
||||
|
||||
if let Some(message) = message {
|
||||
writeln!(f, "{}", message)?;
|
||||
writeln!(f, "{message}")?;
|
||||
}
|
||||
|
||||
let path = file_path
|
||||
@ -400,7 +403,7 @@ fn num_lit<'a>(start: &'a str) -> ParseResult<'a, Num<'a>> {
|
||||
}
|
||||
})(i)?;
|
||||
match (has_dot, has_exp) {
|
||||
(Some(_), _) | (_, Some(_)) => Ok((i, ())),
|
||||
(Some(_), _) | (_, Some(())) => Ok((i, ())),
|
||||
_ => fail(start),
|
||||
}
|
||||
};
|
||||
@ -450,6 +453,7 @@ pub enum StrPrefix {
|
||||
}
|
||||
|
||||
impl StrPrefix {
|
||||
#[must_use]
|
||||
pub fn to_char(self) -> char {
|
||||
match self {
|
||||
Self::Binary => 'b',
|
||||
@ -549,7 +553,7 @@ fn char_lit(i: &str) -> Result<(&str, CharLit<'_>), ParseErr<'_>> {
|
||||
Char::UnicodeEscape(nb) => (
|
||||
nb,
|
||||
// `0x10FFFF` is the maximum value for a `\u` escaped character.
|
||||
0x10FFFF,
|
||||
0x0010_FFFF,
|
||||
"invalid character in unicode escape",
|
||||
"unicode escape must be at most 10FFFF",
|
||||
),
|
||||
@ -646,7 +650,7 @@ fn path_or_identifier(i: &str) -> ParseResult<'_, PathOrIdentifier<'_>> {
|
||||
path.extend(rest);
|
||||
Ok((i, PathOrIdentifier::Path(path)))
|
||||
}
|
||||
(None, name, []) if name.chars().next().map_or(true, |c| c.is_lowercase()) => {
|
||||
(None, name, []) if name.chars().next().map_or(true, char::is_lowercase) => {
|
||||
Ok((i, PathOrIdentifier::Identifier(name)))
|
||||
}
|
||||
(None, start, tail) => {
|
||||
@ -821,7 +825,7 @@ impl<'a> SyntaxBuilder<'a> {
|
||||
"delimiters must be at least two characters long. \
|
||||
The {k} delimiter ({s:?}) is too short",
|
||||
));
|
||||
} else if s.chars().any(|c| c.is_whitespace()) {
|
||||
} else if s.chars().any(char::is_whitespace) {
|
||||
return Err(format!(
|
||||
"delimiters may not contain white spaces. \
|
||||
The {k} delimiter ({s:?}) contains white spaces",
|
||||
@ -934,6 +938,7 @@ fn filter<'a>(
|
||||
/// ```
|
||||
///
|
||||
/// `strip_common` will return `d/e.txt`.
|
||||
#[must_use]
|
||||
pub fn strip_common(base: &Path, path: &Path) -> String {
|
||||
let path = match path.canonicalize() {
|
||||
Ok(path) => path,
|
||||
@ -1067,7 +1072,7 @@ mod test {
|
||||
let entry = cwd
|
||||
.read_dir()
|
||||
.expect("read_dir failed")
|
||||
.filter_map(|f| f.ok())
|
||||
.filter_map(std::result::Result::ok)
|
||||
.find(|f| f.path().is_file())
|
||||
.expect("no entry");
|
||||
|
||||
|
@ -177,6 +177,7 @@ impl<'a> Node<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn span(&self) -> &str {
|
||||
match self {
|
||||
Self::Lit(span) => span.span,
|
||||
@ -678,7 +679,7 @@ impl<'a> FilterBlock<'a> {
|
||||
)),
|
||||
),
|
||||
));
|
||||
let (i, (pws1, _, (filter_name, params, extra_filters, _, nws1, _))) = start(i)?;
|
||||
let (i, (pws1, _, (filter_name, params, extra_filters, (), nws1, _))) = start(i)?;
|
||||
|
||||
let mut arguments = params.unwrap_or_default();
|
||||
arguments.insert(0, WithSpan::new(Expr::FilterSource, start_s));
|
||||
@ -976,7 +977,7 @@ pub struct Lit<'a> {
|
||||
impl<'a> Lit<'a> {
|
||||
fn parse(i: &'a str, s: &State<'_>) -> ParseResult<'a, WithSpan<'a, Self>> {
|
||||
let start = i;
|
||||
let (i, _) = not(eof)(i)?;
|
||||
let (i, ()) = not(eof)(i)?;
|
||||
|
||||
let candidate_finder = Splitter3::new(
|
||||
s.syntax.block_start,
|
||||
@ -1418,9 +1419,7 @@ mod kws_tests {
|
||||
fn ensure_utf8_inner(entry: &[&[[u8; MAX_REPL_LEN]]]) {
|
||||
for kws in entry {
|
||||
for kw in *kws {
|
||||
if std::str::from_utf8(kw).is_err() {
|
||||
panic!("not UTF-8: {:?}", kw);
|
||||
}
|
||||
assert!(std::str::from_utf8(kw).is_ok(), "not UTF-8: {kw:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -728,7 +728,7 @@ fn test_parse_comments() {
|
||||
assert_eq!(nodes.len(), 1, "expected to parse one node");
|
||||
match nodes.pop().unwrap() {
|
||||
Node::Comment(comment) => assert_eq!(comment.ws, ws),
|
||||
node => panic!("expected a comment not, but parsed {:?}", node),
|
||||
node => panic!("expected a comment not, but parsed {node:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -16,6 +16,7 @@ pub fn respond<T: ?Sized + rinja::Template>(tmpl: &T) -> rocket::response::Resul
|
||||
}
|
||||
|
||||
/// Render a [`Template`] into a [`Response`], or render an error page.
|
||||
#[must_use]
|
||||
pub fn into_response<T: ?Sized + rinja::Template>(tmpl: &T) -> Response<'static> {
|
||||
match try_into_response(tmpl) {
|
||||
Ok(response) => response,
|
||||
|
@ -9,6 +9,7 @@ pub use warp;
|
||||
use warp::reply::Response;
|
||||
|
||||
/// Render a [`Template`] into a [`Response`], or render an error page.
|
||||
#[must_use]
|
||||
pub fn into_response<T: ?Sized + rinja::Template>(tmpl: &T) -> Response {
|
||||
match try_into_response(tmpl) {
|
||||
Ok(response) => response,
|
||||
|
@ -22,7 +22,7 @@ where
|
||||
#[test]
|
||||
fn filter_block_basic() {
|
||||
let template = A { t: "a", u: "B" };
|
||||
assert_eq!(template.render().unwrap(), "\n a / hello / b\n\n\nb\n")
|
||||
assert_eq!(template.render().unwrap(), "\n a / hello / b\n\n\nb\n");
|
||||
}
|
||||
|
||||
// This test ensures that we don't have variable shadowing when we have more than one
|
||||
@ -58,7 +58,7 @@ fn filter_block_shadowing() {
|
||||
let template = B { t: "a", u: "B" };
|
||||
assert_eq!(
|
||||
template.render().unwrap(),
|
||||
r#"
|
||||
r"
|
||||
a / hello / b
|
||||
|
||||
|
||||
@ -70,7 +70,7 @@ B + TADAM + A
|
||||
a - check - a
|
||||
|
||||
|
||||
B"#
|
||||
B"
|
||||
);
|
||||
}
|
||||
|
||||
@ -102,8 +102,8 @@ fn filter_block_whitespace_control() {
|
||||
let template = C { t: "a", u: "B" };
|
||||
assert_eq!(
|
||||
template.render().unwrap(),
|
||||
r#"a / hello / b
|
||||
B + TADAM + A++b"#
|
||||
r"a / hello / b
|
||||
B + TADAM + A++b"
|
||||
);
|
||||
}
|
||||
|
||||
@ -115,7 +115,7 @@ struct D;
|
||||
#[test]
|
||||
fn filter_block_html_escape() {
|
||||
let template = D;
|
||||
assert_eq!(template.render().unwrap(), r#"<block>"#);
|
||||
assert_eq!(template.render().unwrap(), r"<block>");
|
||||
}
|
||||
|
||||
// This test ensures that it is not escaped if it is not HTML.
|
||||
@ -126,7 +126,7 @@ struct E;
|
||||
#[test]
|
||||
fn filter_block_not_html_escape() {
|
||||
let template = E;
|
||||
assert_eq!(template.render().unwrap(), r#"<block>"#);
|
||||
assert_eq!(template.render().unwrap(), r"<block>");
|
||||
}
|
||||
|
||||
// This test checks that the filter chaining is working as expected.
|
||||
@ -182,7 +182,7 @@ fn filter_block_chaining_paren_followed_by_whitespace() {
|
||||
let template = G { v: "pIKA" };
|
||||
assert_eq!(
|
||||
template.render().unwrap(),
|
||||
r#"hello
|
||||
r"hello
|
||||
pika
|
||||
|
||||
hello
|
||||
@ -194,7 +194,7 @@ hello
|
||||
|
||||
|
||||
hello
|
||||
pika"#
|
||||
pika"
|
||||
);
|
||||
}
|
||||
|
||||
@ -302,12 +302,12 @@ fn filter_nested_filter_blocks() {
|
||||
};
|
||||
assert_eq!(
|
||||
template.render().unwrap(),
|
||||
r#"[
|
||||
r"[
|
||||
<P>HELLO &#38;</P><P>GOODBYE!
|
||||
</P>
|
||||
<P>HELLO &#38;</P><P>GOODBYE!
|
||||
</P>]
|
||||
2"#
|
||||
2"
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -344,7 +344,7 @@ struct JsonAttribute2Template<'a> {
|
||||
#[test]
|
||||
fn test_json_attribute2() {
|
||||
let t = JsonAttribute2Template {
|
||||
name: r#"'><button>Hacked!</button>"#,
|
||||
name: r"'><button>Hacked!</button>",
|
||||
};
|
||||
assert_eq!(
|
||||
t.render().unwrap(),
|
||||
@ -366,7 +366,7 @@ struct JsonScriptTemplate<'a> {
|
||||
#[test]
|
||||
fn test_json_script() {
|
||||
let t = JsonScriptTemplate {
|
||||
name: r#"</script><button>Hacked!</button>"#,
|
||||
name: r"</script><button>Hacked!</button>",
|
||||
};
|
||||
assert_eq!(
|
||||
t.render().unwrap(),
|
||||
@ -390,7 +390,7 @@ fn test_let_borrow() {
|
||||
let template = LetBorrow {
|
||||
s: "hello".to_owned(),
|
||||
};
|
||||
assert_eq!(template.render().unwrap(), "hello1")
|
||||
assert_eq!(template.render().unwrap(), "hello1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -10,7 +10,7 @@ struct IncludeTemplate<'a> {
|
||||
fn test_include() {
|
||||
let strs = vec!["foo", "bar"];
|
||||
let s = IncludeTemplate { strs: &strs };
|
||||
assert_eq!(s.render().unwrap(), "\n INCLUDED: foo\n INCLUDED: bar")
|
||||
assert_eq!(s.render().unwrap(), "\n INCLUDED: foo\n INCLUDED: bar");
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
|
@ -22,13 +22,13 @@ fn is_defined_in_expr() {
|
||||
let s = IsDefined { y: 0 };
|
||||
assert_eq!(
|
||||
s.render().unwrap(),
|
||||
r#"<script>
|
||||
r"<script>
|
||||
const x = false;
|
||||
const y = false;
|
||||
const z = true;
|
||||
const w = true;
|
||||
const v = 0;
|
||||
</script>"#
|
||||
</script>"
|
||||
);
|
||||
}
|
||||
|
||||
@ -42,5 +42,5 @@ struct IsDefinedChaining;
|
||||
// This test ensures that if the variable is not defined, it will not generate following code.
|
||||
#[test]
|
||||
fn is_defined_chaining() {
|
||||
assert_eq!(IsDefinedChaining.render().unwrap(), r#"bla"#);
|
||||
assert_eq!(IsDefinedChaining.render().unwrap(), r"bla");
|
||||
}
|
||||
|
@ -415,7 +415,7 @@ fn test_for_cycle_empty() {
|
||||
values: &[1, 2, 3, 4, 5, 6, 7, 8, 9],
|
||||
cycle: &[],
|
||||
};
|
||||
assert!(t.render().is_err())
|
||||
assert!(t.render().is_err());
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
|
@ -507,7 +507,7 @@ struct MixedCase {
|
||||
/// variable names (`foo`). Previously, this test would fail because any
|
||||
/// name containing uppercase characters would be considered a path.
|
||||
///
|
||||
/// https://github.com/rinja-rs/rinja/issues/924
|
||||
/// <https://github.com/rinja-rs/rinja/issues/924>
|
||||
#[test]
|
||||
fn test_mixed_case() {
|
||||
let template = MixedCase { xY: "foo" };
|
||||
@ -558,5 +558,5 @@ struct SplitTemplateDeclaration;
|
||||
|
||||
#[test]
|
||||
fn test_split_template_declaration() {
|
||||
assert_eq!(SplitTemplateDeclaration.to_string(), "🙂")
|
||||
assert_eq!(SplitTemplateDeclaration.to_string(), "🙂");
|
||||
}
|
||||
|
@ -31,13 +31,12 @@ fn ui() {
|
||||
let target = target_crate_root.join(name);
|
||||
if !target.exists() {
|
||||
let original = manifest_dir.join(name);
|
||||
if symlink(&original, &target).is_err() {
|
||||
panic!(
|
||||
"failed to create to create link on `{}` as `{}`",
|
||||
original.display(),
|
||||
target.display(),
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
symlink(&original, &target).is_ok(),
|
||||
"failed to create to create link on `{}` as `{}`",
|
||||
original.display(),
|
||||
target.display(),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user