| 1 |
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] |
| 2 |
#![deny(elided_lifetimes_in_paths)] |
| 3 |
#![deny(unreachable_pub)] |
| 4 |
|
| 5 |
pub mod ascii_str; |
| 6 |
pub mod expr; |
| 7 |
mod memchr_splitter; |
| 8 |
pub mod node; |
| 9 |
mod target; |
| 10 |
#[cfg(test)] |
| 11 |
mod tests; |
| 12 |
|
| 13 |
use std::borrow::Cow; |
| 14 |
use std::cell::Cell; |
| 15 |
use std::env::current_dir; |
| 16 |
use std::ops::{Deref, DerefMut}; |
| 17 |
use std::path::Path; |
| 18 |
use std::sync::Arc; |
| 19 |
use std::{fmt, str}; |
| 20 |
|
| 21 |
use winnow::ascii::take_escaped; |
| 22 |
use winnow::combinator::{alt, cut_err, delimited, fail, not, opt, peek, preceded, repeat}; |
| 23 |
use winnow::error::FromExternalError; |
| 24 |
use winnow::stream::{AsChar, Stream as _}; |
| 25 |
use winnow::token::{any, one_of, take_till, take_while}; |
| 26 |
use winnow::{ModalParser, Parser}; |
| 27 |
|
| 28 |
use crate::ascii_str::{AsciiChar, AsciiStr}; |
| 29 |
pub use crate::expr::{Attr, Expr, Filter, TyGenerics}; |
| 30 |
pub use crate::node::Node; |
| 31 |
pub use crate::target::Target; |
| 32 |
|
| 33 |
mod _parsed { |
| 34 |
use std::path::Path; |
| 35 |
use std::sync::Arc; |
| 36 |
use std::{fmt, mem}; |
| 37 |
|
| 38 |
use super::node::Node; |
| 39 |
use super::{Ast, ParseError, Syntax}; |
| 40 |
|
| 41 |
pub struct Parsed { |
| 42 |
// `source` must outlive `ast`, so `ast` must be declared before `source` |
| 43 |
ast: Ast<'static>, |
| 44 |
#[allow(dead_code)] |
| 45 |
source: Arc<str>, |
| 46 |
} |
| 47 |
|
| 48 |
impl Parsed { |
| 49 |
/// If `file_path` is `None`, it means the `source` is an inline template. Therefore, if |
| 50 |
/// a parsing error occurs, we won't display the path as it wouldn't be useful. |
| 51 |
pub fn new( |
| 52 |
source: Arc<str>, |
| 53 |
file_path: Option<Arc<Path>>, |
| 54 |
syntax: &Syntax<'_>, |
| 55 |
) -> Result<Self, ParseError> { |
| 56 |
// Self-referential borrowing: `self` will keep the source alive as `String`, |
| 57 |
// internally we will transmute it to `&'static str` to satisfy the compiler. |
| 58 |
// However, we only expose the nodes with a lifetime limited to `self`. |
| 59 |
let src = unsafe { mem::transmute::<&str, &'static str>(source.as_ref()) }; |
| 60 |
let ast = Ast::from_str(src, file_path, syntax)?; |
| 61 |
Ok(Self { ast, source }) |
| 62 |
} |
| 63 |
|
| 64 |
// The return value's lifetime must be limited to `self` to uphold the unsafe invariant. |
| 65 |
#[must_use] |
| 66 |
pub fn nodes(&self) -> &[Node<'_>] { |
| 67 |
&self.ast.nodes |
| 68 |
} |
| 69 |
|
| 70 |
#[must_use] |
| 71 |
pub fn source(&self) -> &str { |
| 72 |
&self.source |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
impl fmt::Debug for Parsed { |
| 77 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 78 |
f.debug_struct("Parsed") |
| 79 |
.field("nodes", &self.ast.nodes) |
| 80 |
.finish_non_exhaustive() |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
impl PartialEq for Parsed { |
| 85 |
fn eq(&self, other: &Self) -> bool { |
| 86 |
self.ast.nodes == other.ast.nodes |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
impl Default for Parsed { |
| 91 |
fn default() -> Self { |
| 92 |
Self { |
| 93 |
ast: Ast::default(), |
| 94 |
source: "".into(), |
| 95 |
} |
| 96 |
} |
| 97 |
} |
| 98 |
} |
| 99 |
|
| 100 |
pub use _parsed::Parsed; |
| 101 |
|
| 102 |
#[derive(Debug, Default)] |
| 103 |
pub struct Ast<'a> { |
| 104 |
nodes: Vec<Node<'a>>, |
| 105 |
} |
| 106 |
|
| 107 |
impl<'a> Ast<'a> { |
| 108 |
/// If `file_path` is `None`, it means the `source` is an inline template. Therefore, if |
| 109 |
/// a parsing error occurs, we won't display the path as it wouldn't be useful. |
| 110 |
pub fn from_str( |
| 111 |
mut src: &'a str, |
| 112 |
file_path: Option<Arc<Path>>, |
| 113 |
syntax: &Syntax<'_>, |
| 114 |
) -> Result<Self, ParseError> { |
| 115 |
let start = src; |
| 116 |
let level = Cell::new(Level::MAX_DEPTH); |
| 117 |
let state = State { |
| 118 |
syntax, |
| 119 |
loop_depth: Cell::new(0), |
| 120 |
level: Level(&level), |
| 121 |
}; |
| 122 |
match Node::parse_template(&mut src, &state) { |
| 123 |
Ok(nodes) if src.is_empty() => Ok(Self { nodes }), |
| 124 |
Ok(_) | Err(winnow::error::ErrMode::Incomplete(_)) => unreachable!(), |
| 125 |
Err( |
| 126 |
winnow::error::ErrMode::Backtrack(ErrorContext { span, message, .. }) |
| 127 |
| winnow::error::ErrMode::Cut(ErrorContext { span, message, .. }), |
| 128 |
) => Err(ParseError { |
| 129 |
message, |
| 130 |
offset: span.offset_from(start).unwrap_or_default(), |
| 131 |
file_path, |
| 132 |
}), |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
#[must_use] |
| 137 |
pub fn nodes(&self) -> &[Node<'a>] { |
| 138 |
&self.nodes |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
/// Struct used to wrap types with their associated "span" which is used when generating errors |
| 143 |
/// in the code generation. |
| 144 |
pub struct WithSpan<'a, T> { |
| 145 |
inner: T, |
| 146 |
span: Span<'a>, |
| 147 |
} |
| 148 |
|
| 149 |
/// An location in `&'a str` |
| 150 |
#[derive(Debug, Clone, Copy)] |
| 151 |
pub struct Span<'a>(&'a [u8; 0]); |
| 152 |
|
| 153 |
impl Default for Span<'static> { |
| 154 |
#[inline] |
| 155 |
fn default() -> Self { |
| 156 |
Self::empty() |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
impl<'a> Span<'a> { |
| 161 |
#[inline] |
| 162 |
pub const fn empty() -> Self { |
| 163 |
Self(&[]) |
| 164 |
} |
| 165 |
|
| 166 |
pub fn offset_from(self, start: &'a str) -> Option<usize> { |
| 167 |
let start_range = start.as_bytes().as_ptr_range(); |
| 168 |
let this_ptr = self.0.as_slice().as_ptr(); |
| 169 |
match start_range.contains(&this_ptr) { |
| 170 |
// SAFETY: we just checked that `this_ptr` is inside `start_range` |
| 171 |
true => Some(unsafe { this_ptr.offset_from(start_range.start) as usize }), |
| 172 |
false => None, |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
pub fn as_suffix_of(self, start: &'a str) -> Option<&'a str> { |
| 177 |
let offset = self.offset_from(start)?; |
| 178 |
match start.is_char_boundary(offset) { |
| 179 |
true => Some(&start[offset..]), |
| 180 |
false => None, |
| 181 |
} |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
impl<'a> From<&'a str> for Span<'a> { |
| 186 |
#[inline] |
| 187 |
fn from(value: &'a str) -> Self { |
| 188 |
Self(value.as_bytes()[..0].try_into().unwrap()) |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
impl<'a, T> WithSpan<'a, T> { |
| 193 |
#[inline] |
| 194 |
pub fn new(inner: T, span: impl Into<Span<'a>>) -> Self { |
| 195 |
Self { |
| 196 |
inner, |
| 197 |
span: span.into(), |
| 198 |
} |
| 199 |
} |
| 200 |
|
| 201 |
#[inline] |
| 202 |
pub const fn new_without_span(inner: T) -> Self { |
| 203 |
Self { |
| 204 |
inner, |
| 205 |
span: Span::empty(), |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
#[inline] |
| 210 |
pub fn span(&self) -> Span<'a> { |
| 211 |
self.span |
| 212 |
} |
| 213 |
|
| 214 |
#[inline] |
| 215 |
pub fn deconstruct(self) -> (T, Span<'a>) { |
| 216 |
let Self { inner, span } = self; |
| 217 |
(inner, span) |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
impl<T> Deref for WithSpan<'_, T> { |
| 222 |
type Target = T; |
| 223 |
|
| 224 |
fn deref(&self) -> &Self::Target { |
| 225 |
&self.inner |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
impl<T> DerefMut for WithSpan<'_, T> { |
| 230 |
fn deref_mut(&mut self) -> &mut Self::Target { |
| 231 |
&mut self.inner |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
impl<T: fmt::Debug> fmt::Debug for WithSpan<'_, T> { |
| 236 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 237 |
write!(f, "{:?}", self.inner) |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
impl<T: Clone> Clone for WithSpan<'_, T> { |
| 242 |
fn clone(&self) -> Self { |
| 243 |
Self { |
| 244 |
inner: self.inner.clone(), |
| 245 |
span: self.span, |
| 246 |
} |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
impl<T: PartialEq> PartialEq for WithSpan<'_, T> { |
| 251 |
fn eq(&self, other: &Self) -> bool { |
| 252 |
// We never want to compare the span information. |
| 253 |
self.inner == other.inner |
| 254 |
} |
| 255 |
} |
| 256 |
|
| 257 |
#[derive(Debug, Clone, PartialEq, Eq)] |
| 258 |
pub struct ParseError { |
| 259 |
pub message: Option<Cow<'static, str>>, |
| 260 |
pub offset: usize, |
| 261 |
pub file_path: Option<Arc<Path>>, |
| 262 |
} |
| 263 |
|
| 264 |
impl std::error::Error for ParseError {} |
| 265 |
|
| 266 |
impl fmt::Display for ParseError { |
| 267 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 268 |
let ParseError { |
| 269 |
message, |
| 270 |
file_path, |
| 271 |
offset, |
| 272 |
} = self; |
| 273 |
|
| 274 |
if let Some(message) = message { |
| 275 |
writeln!(f, "{message}")?; |
| 276 |
} |
| 277 |
|
| 278 |
let path = file_path |
| 279 |
.as_ref() |
| 280 |
.and_then(|path| Some(strip_common(¤t_dir().ok()?, path))); |
| 281 |
match path { |
| 282 |
Some(path) => write!(f, "failed to parse template source\n --> {path}@{offset}"), |
| 283 |
None => write!(f, "failed to parse template source near offset {offset}"), |
| 284 |
} |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
pub(crate) type ParseErr<'a> = winnow::error::ErrMode<ErrorContext<'a>>; |
| 289 |
pub(crate) type ParseResult<'a, T = &'a str> = Result<T, ParseErr<'a>>; |
| 290 |
|
| 291 |
/// This type is used to handle `nom` errors and in particular to add custom error messages. |
| 292 |
/// It used to generate `ParserError`. |
| 293 |
/// |
| 294 |
/// It cannot be used to replace `ParseError` because it expects a generic, which would make |
| 295 |
/// `askama`'s users experience less good (since this generic is only needed for `nom`). |
| 296 |
#[derive(Debug)] |
| 297 |
pub(crate) struct ErrorContext<'a> { |
| 298 |
pub(crate) span: Span<'a>, |
| 299 |
pub(crate) message: Option<Cow<'static, str>>, |
| 300 |
} |
| 301 |
|
| 302 |
impl<'a> ErrorContext<'a> { |
| 303 |
fn unclosed(kind: &str, tag: &str, span: impl Into<Span<'a>>) -> Self { |
| 304 |
Self::new(format!("unclosed {kind}, missing {tag:?}"), span) |
| 305 |
} |
| 306 |
|
| 307 |
fn new(message: impl Into<Cow<'static, str>>, span: impl Into<Span<'a>>) -> Self { |
| 308 |
Self { |
| 309 |
span: span.into(), |
| 310 |
message: Some(message.into()), |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
fn backtrack(self) -> winnow::error::ErrMode<Self> { |
| 315 |
winnow::error::ErrMode::Backtrack(self) |
| 316 |
} |
| 317 |
|
| 318 |
fn cut(self) -> winnow::error::ErrMode<Self> { |
| 319 |
winnow::error::ErrMode::Cut(self) |
| 320 |
} |
| 321 |
} |
| 322 |
|
| 323 |
impl<'a> winnow::error::ParserError<&'a str> for ErrorContext<'a> { |
| 324 |
type Inner = Self; |
| 325 |
|
| 326 |
fn from_input(input: &&'a str) -> Self { |
| 327 |
Self { |
| 328 |
span: (*input).into(), |
| 329 |
message: None, |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
#[inline(always)] |
| 334 |
fn into_inner(self) -> Result<Self::Inner, Self> { |
| 335 |
Ok(self) |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
impl<'a, E: std::fmt::Display> FromExternalError<&'a str, E> for ErrorContext<'a> { |
| 340 |
fn from_external_error(input: &&'a str, e: E) -> Self { |
| 341 |
Self { |
| 342 |
span: (*input).into(), |
| 343 |
message: Some(Cow::Owned(e.to_string())), |
| 344 |
} |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
#[inline] |
| 349 |
fn skip_ws0<'a>(i: &mut &'a str) -> ParseResult<'a, ()> { |
| 350 |
*i = i.trim_ascii_start(); |
| 351 |
Ok(()) |
| 352 |
} |
| 353 |
|
| 354 |
#[inline] |
| 355 |
fn skip_ws1<'a>(i: &mut &'a str) -> ParseResult<'a, ()> { |
| 356 |
let j = i.trim_ascii_start(); |
| 357 |
if i.len() != j.len() { |
| 358 |
*i = i.trim_ascii_start(); |
| 359 |
Ok(()) |
| 360 |
} else { |
| 361 |
fail.parse_next(i) |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
fn ws<'a, O>( |
| 366 |
inner: impl ModalParser<&'a str, O, ErrorContext<'a>>, |
| 367 |
) -> impl ModalParser<&'a str, O, ErrorContext<'a>> { |
| 368 |
delimited(skip_ws0, inner, skip_ws0) |
| 369 |
} |
| 370 |
|
| 371 |
/// Skips input until `end` was found, but does not consume it. |
| 372 |
/// Returns tuple that would be returned when parsing `end`. |
| 373 |
fn skip_till<'a, 'b, O>( |
| 374 |
candidate_finder: impl crate::memchr_splitter::Splitter, |
| 375 |
end: impl ModalParser<&'a str, O, ErrorContext<'a>>, |
| 376 |
) -> impl ModalParser<&'a str, (&'a str, O), ErrorContext<'a>> { |
| 377 |
let mut next = alt((end.map(Some), any.map(|_| None))); |
| 378 |
move |i: &mut &'a str| loop { |
| 379 |
*i = match candidate_finder.split(i) { |
| 380 |
Some((_, i)) => i, |
| 381 |
None => { |
| 382 |
return Err(winnow::error::ErrMode::Backtrack(ErrorContext::new( |
| 383 |
"`end` not found`", |
| 384 |
*i, |
| 385 |
))); |
| 386 |
} |
| 387 |
}; |
| 388 |
let exclusive = *i; |
| 389 |
if let Some(lookahead) = next.parse_next(i)? { |
| 390 |
let inclusive = *i; |
| 391 |
*i = exclusive; |
| 392 |
return Ok((inclusive, lookahead)); |
| 393 |
} |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
fn keyword(k: &str) -> impl ModalParser<&str, &str, ErrorContext<'_>> { |
| 398 |
identifier.verify(move |v: &str| v == k) |
| 399 |
} |
| 400 |
|
| 401 |
fn identifier<'i>(input: &mut &'i str) -> ParseResult<'i> { |
| 402 |
let start = take_while(1.., |c: char| c.is_alpha() || c == '_' || c >= '\u{0080}'); |
| 403 |
|
| 404 |
let tail = take_while(1.., |c: char| { |
| 405 |
c.is_alphanum() || c == '_' || c >= '\u{0080}' |
| 406 |
}); |
| 407 |
|
| 408 |
(start, opt(tail)).take().parse_next(input) |
| 409 |
} |
| 410 |
|
| 411 |
fn bool_lit<'i>(i: &mut &'i str) -> ParseResult<'i> { |
| 412 |
alt((keyword("false"), keyword("true"))).parse_next(i) |
| 413 |
} |
| 414 |
|
| 415 |
#[derive(Debug, Clone, Copy, PartialEq)] |
| 416 |
pub enum Num<'a> { |
| 417 |
Int(&'a str, Option<IntKind>), |
| 418 |
Float(&'a str, Option<FloatKind>), |
| 419 |
} |
| 420 |
|
| 421 |
fn num_lit<'a>(i: &mut &'a str) -> ParseResult<'a, Num<'a>> { |
| 422 |
fn num_lit_suffix<'a, T: Copy>( |
| 423 |
kind: &'a str, |
| 424 |
list: &[(&str, T)], |
| 425 |
start: &'a str, |
| 426 |
i: &mut &'a str, |
| 427 |
) -> ParseResult<'a, T> { |
| 428 |
let suffix = identifier.parse_next(i)?; |
| 429 |
if let Some(value) = list |
| 430 |
.iter() |
| 431 |
.copied() |
| 432 |
.find_map(|(name, value)| (name == suffix).then_some(value)) |
| 433 |
{ |
| 434 |
Ok(value) |
| 435 |
} else { |
| 436 |
Err(winnow::error::ErrMode::Cut(ErrorContext::new( |
| 437 |
format!("unknown {kind} suffix `{suffix}`"), |
| 438 |
start, |
| 439 |
))) |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
let start = *i; |
| 444 |
|
| 445 |
// Equivalent to <https://github.com/rust-lang/rust/blob/e3f909b2bbd0b10db6f164d466db237c582d3045/compiler/rustc_lexer/src/lib.rs#L587-L620>. |
| 446 |
let int_with_base = (opt('-'), |i: &mut _| { |
| 447 |
let (base, kind) = preceded('0', alt(('b'.value(2), 'o'.value(8), 'x'.value(16)))) |
| 448 |
.with_taken() |
| 449 |
.parse_next(i)?; |
| 450 |
match opt(separated_digits(base, false)).parse_next(i)? { |
| 451 |
Some(_) => Ok(()), |
| 452 |
None => Err(winnow::error::ErrMode::Cut(ErrorContext::new( |
| 453 |
format!("expected digits after `{kind}`"), |
| 454 |
start, |
| 455 |
))), |
| 456 |
} |
| 457 |
}); |
| 458 |
|
| 459 |
// Equivalent to <https://github.com/rust-lang/rust/blob/e3f909b2bbd0b10db6f164d466db237c582d3045/compiler/rustc_lexer/src/lib.rs#L626-L653>: |
| 460 |
// no `_` directly after the decimal point `.`, or between `e` and `+/-`. |
| 461 |
let float = |i: &mut &'a str| -> ParseResult<'a, ()> { |
| 462 |
let has_dot = opt(('.', separated_digits(10, true))).parse_next(i)?; |
| 463 |
let has_exp = opt(|i: &mut _| { |
| 464 |
let (kind, op) = (one_of(['e', 'E']), opt(one_of(['+', '-']))).parse_next(i)?; |
| 465 |
match opt(separated_digits(10, op.is_none())).parse_next(i)? { |
| 466 |
Some(_) => Ok(()), |
| 467 |
None => Err(winnow::error::ErrMode::Cut(ErrorContext::new( |
| 468 |
format!("expected decimal digits, `+` or `-` after exponent `{kind}`"), |
| 469 |
start, |
| 470 |
))), |
| 471 |
} |
| 472 |
}) |
| 473 |
.parse_next(i)?; |
| 474 |
match (has_dot, has_exp) { |
| 475 |
(Some(_), _) | (_, Some(())) => Ok(()), |
| 476 |
_ => { |
| 477 |
*i = start; |
| 478 |
fail.parse_next(i) |
| 479 |
} |
| 480 |
} |
| 481 |
}; |
| 482 |
|
| 483 |
let num = if let Ok(Some(num)) = opt(int_with_base.take()).parse_next(i) { |
| 484 |
let suffix = |
| 485 |
opt(|i: &mut _| num_lit_suffix("integer", INTEGER_TYPES, start, i)).parse_next(i)?; |
| 486 |
Num::Int(num, suffix) |
| 487 |
} else { |
| 488 |
let (float, num) = preceded((opt('-'), separated_digits(10, true)), opt(float)) |
| 489 |
.with_taken() |
| 490 |
.parse_next(i)?; |
| 491 |
if float.is_some() { |
| 492 |
let suffix = |
| 493 |
opt(|i: &mut _| num_lit_suffix("float", FLOAT_TYPES, start, i)).parse_next(i)?; |
| 494 |
Num::Float(num, suffix) |
| 495 |
} else { |
| 496 |
let suffix = |
| 497 |
opt(|i: &mut _| num_lit_suffix("number", NUM_TYPES, start, i)).parse_next(i)?; |
| 498 |
match suffix { |
| 499 |
Some(NumKind::Int(kind)) => Num::Int(num, Some(kind)), |
| 500 |
Some(NumKind::Float(kind)) => Num::Float(num, Some(kind)), |
| 501 |
None => Num::Int(num, None), |
| 502 |
} |
| 503 |
} |
| 504 |
}; |
| 505 |
Ok(num) |
| 506 |
} |
| 507 |
|
| 508 |
/// Underscore separated digits of the given base, unless `start` is true this may start |
| 509 |
/// with an underscore. |
| 510 |
fn separated_digits<'a>( |
| 511 |
radix: u32, |
| 512 |
start: bool, |
| 513 |
) -> impl ModalParser<&'a str, &'a str, ErrorContext<'a>> { |
| 514 |
( |
| 515 |
move |i: &mut &'a _| match start { |
| 516 |
true => Ok(()), |
| 517 |
false => repeat(0.., '_').parse_next(i), |
| 518 |
}, |
| 519 |
one_of(move |ch: char| ch.is_digit(radix)), |
| 520 |
repeat(0.., one_of(move |ch: char| ch == '_' || ch.is_digit(radix))).map(|()| ()), |
| 521 |
) |
| 522 |
.take() |
| 523 |
} |
| 524 |
|
| 525 |
#[derive(Clone, Copy, Debug, PartialEq)] |
| 526 |
pub enum StrPrefix { |
| 527 |
Binary, |
| 528 |
CLike, |
| 529 |
} |
| 530 |
|
| 531 |
impl StrPrefix { |
| 532 |
#[must_use] |
| 533 |
pub fn to_char(self) -> char { |
| 534 |
match self { |
| 535 |
Self::Binary => 'b', |
| 536 |
Self::CLike => 'c', |
| 537 |
} |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
impl fmt::Display for StrPrefix { |
| 542 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 543 |
use std::fmt::Write; |
| 544 |
|
| 545 |
f.write_char(self.to_char()) |
| 546 |
} |
| 547 |
} |
| 548 |
|
| 549 |
#[derive(Clone, Debug, PartialEq)] |
| 550 |
pub struct StrLit<'a> { |
| 551 |
pub prefix: Option<StrPrefix>, |
| 552 |
pub content: &'a str, |
| 553 |
} |
| 554 |
|
| 555 |
fn str_lit_without_prefix<'a>(i: &mut &'a str) -> ParseResult<'a> { |
| 556 |
let s = delimited( |
| 557 |
'"', |
| 558 |
opt(take_escaped(take_till(1.., ['\\', '"']), '\\', any)), |
| 559 |
'"', |
| 560 |
) |
| 561 |
.parse_next(i)?; |
| 562 |
Ok(s.unwrap_or_default()) |
| 563 |
} |
| 564 |
|
| 565 |
fn str_lit<'a>(i: &mut &'a str) -> ParseResult<'a, StrLit<'a>> { |
| 566 |
let (prefix, content) = (opt(alt(('b', 'c'))), str_lit_without_prefix).parse_next(i)?; |
| 567 |
let prefix = match prefix { |
| 568 |
Some('b') => Some(StrPrefix::Binary), |
| 569 |
Some('c') => Some(StrPrefix::CLike), |
| 570 |
_ => None, |
| 571 |
}; |
| 572 |
Ok(StrLit { prefix, content }) |
| 573 |
} |
| 574 |
|
| 575 |
#[derive(Clone, Copy, Debug, PartialEq)] |
| 576 |
pub enum CharPrefix { |
| 577 |
Binary, |
| 578 |
} |
| 579 |
|
| 580 |
#[derive(Clone, Debug, PartialEq)] |
| 581 |
pub struct CharLit<'a> { |
| 582 |
pub prefix: Option<CharPrefix>, |
| 583 |
pub content: &'a str, |
| 584 |
} |
| 585 |
|
| 586 |
// Information about allowed character escapes is available at: |
| 587 |
// <https://doc.rust-lang.org/reference/tokens.html#character-literals>. |
| 588 |
fn char_lit<'a>(i: &mut &'a str) -> ParseResult<'a, CharLit<'a>> { |
| 589 |
let start = i.checkpoint(); |
| 590 |
let (b_prefix, s) = ( |
| 591 |
opt('b'), |
| 592 |
delimited( |
| 593 |
'\'', |
| 594 |
opt(take_escaped(take_till(1.., ['\\', '\'']), '\\', any)), |
| 595 |
'\'', |
| 596 |
), |
| 597 |
) |
| 598 |
.parse_next(i)?; |
| 599 |
|
| 600 |
let Some(s) = s else { |
| 601 |
i.reset(&start); |
| 602 |
return Err(winnow::error::ErrMode::Cut(ErrorContext::new( |
| 603 |
"empty character literal", |
| 604 |
*i, |
| 605 |
))); |
| 606 |
}; |
| 607 |
let mut is = s; |
| 608 |
let Ok(c) = Char::parse(&mut is) else { |
| 609 |
i.reset(&start); |
| 610 |
return Err(winnow::error::ErrMode::Cut(ErrorContext::new( |
| 611 |
"invalid character", |
| 612 |
*i, |
| 613 |
))); |
| 614 |
}; |
| 615 |
|
| 616 |
let (nb, max_value, err1, err2) = match c { |
| 617 |
Char::Literal | Char::Escaped => { |
| 618 |
return Ok(CharLit { |
| 619 |
prefix: b_prefix.map(|_| CharPrefix::Binary), |
| 620 |
content: s, |
| 621 |
}); |
| 622 |
} |
| 623 |
Char::AsciiEscape(nb) => ( |
| 624 |
nb, |
| 625 |
// `0x7F` is the maximum value for a `\x` escaped character. |
| 626 |
0x7F, |
| 627 |
"invalid character in ascii escape", |
| 628 |
"must be a character in the range [\\x00-\\x7f]", |
| 629 |
), |
| 630 |
Char::UnicodeEscape(nb) => ( |
| 631 |
nb, |
| 632 |
// `0x10FFFF` is the maximum value for a `\u` escaped character. |
| 633 |
0x0010_FFFF, |
| 634 |
"invalid character in unicode escape", |
| 635 |
"unicode escape must be at most 10FFFF", |
| 636 |
), |
| 637 |
}; |
| 638 |
|
| 639 |
let Ok(nb) = u32::from_str_radix(nb, 16) else { |
| 640 |
i.reset(&start); |
| 641 |
return Err(winnow::error::ErrMode::Cut(ErrorContext::new(err1, *i))); |
| 642 |
}; |
| 643 |
if nb > max_value { |
| 644 |
i.reset(&start); |
| 645 |
return Err(winnow::error::ErrMode::Cut(ErrorContext::new(err2, *i))); |
| 646 |
} |
| 647 |
|
| 648 |
Ok(CharLit { |
| 649 |
prefix: b_prefix.map(|_| CharPrefix::Binary), |
| 650 |
content: s, |
| 651 |
}) |
| 652 |
} |
| 653 |
|
| 654 |
/// Represents the different kinds of char declarations: |
| 655 |
#[derive(Copy, Clone)] |
| 656 |
enum Char<'a> { |
| 657 |
/// Any character that is not escaped. |
| 658 |
Literal, |
| 659 |
/// An escaped character (like `\n`) which doesn't require any extra check. |
| 660 |
Escaped, |
| 661 |
/// Ascii escape (like `\x12`). |
| 662 |
AsciiEscape(&'a str), |
| 663 |
/// Unicode escape (like `\u{12}`). |
| 664 |
UnicodeEscape(&'a str), |
| 665 |
} |
| 666 |
|
| 667 |
impl<'a> Char<'a> { |
| 668 |
fn parse(i: &mut &'a str) -> ParseResult<'a, Self> { |
| 669 |
if i.chars().count() == 1 { |
| 670 |
return any.value(Self::Literal).parse_next(i); |
| 671 |
} |
| 672 |
( |
| 673 |
'\\', |
| 674 |
alt(( |
| 675 |
'n'.value(Self::Escaped), |
| 676 |
'r'.value(Self::Escaped), |
| 677 |
't'.value(Self::Escaped), |
| 678 |
'\\'.value(Self::Escaped), |
| 679 |
'0'.value(Self::Escaped), |
| 680 |
'\''.value(Self::Escaped), |
| 681 |
// Not useful but supported by rust. |
| 682 |
'"'.value(Self::Escaped), |
| 683 |
('x', take_while(2, |c: char| c.is_ascii_hexdigit())) |
| 684 |
.map(|(_, s)| Self::AsciiEscape(s)), |
| 685 |
( |
| 686 |
"u{", |
| 687 |
take_while(1..=6, |c: char| c.is_ascii_hexdigit()), |
| 688 |
'}', |
| 689 |
) |
| 690 |
.map(|(_, s, _)| Self::UnicodeEscape(s)), |
| 691 |
)), |
| 692 |
) |
| 693 |
.map(|(_, ch)| ch) |
| 694 |
.parse_next(i) |
| 695 |
} |
| 696 |
} |
| 697 |
|
| 698 |
enum PathOrIdentifier<'a> { |
| 699 |
Path(Vec<&'a str>), |
| 700 |
Identifier(&'a str), |
| 701 |
} |
| 702 |
|
| 703 |
fn path_or_identifier<'a>(i: &mut &'a str) -> ParseResult<'a, PathOrIdentifier<'a>> { |
| 704 |
let root = ws(opt("::")); |
| 705 |
let tail = opt(repeat(1.., preceded(ws("::"), identifier)).map(|v: Vec<_>| v)); |
| 706 |
|
| 707 |
let (root, start, rest) = (root, identifier, tail).parse_next(i)?; |
| 708 |
let rest = rest.as_deref().unwrap_or_default(); |
| 709 |
|
| 710 |
// The returned identifier can be assumed to be path if: |
| 711 |
// - it is an absolute path (starts with `::`), or |
| 712 |
// - it has multiple components (at least one `::`), or |
| 713 |
// - the first letter is uppercase |
| 714 |
match (root, start, rest) { |
| 715 |
(Some(_), start, tail) => { |
| 716 |
let mut path = Vec::with_capacity(2 + tail.len()); |
| 717 |
path.push(""); |
| 718 |
path.push(start); |
| 719 |
path.extend(rest); |
| 720 |
Ok(PathOrIdentifier::Path(path)) |
| 721 |
} |
| 722 |
(None, name, []) |
| 723 |
if name |
| 724 |
.chars() |
| 725 |
.next() |
| 726 |
.map_or(true, |c| c == '_' || c.is_lowercase()) => |
| 727 |
{ |
| 728 |
Ok(PathOrIdentifier::Identifier(name)) |
| 729 |
} |
| 730 |
(None, start, tail) => { |
| 731 |
let mut path = Vec::with_capacity(1 + tail.len()); |
| 732 |
path.push(start); |
| 733 |
path.extend(rest); |
| 734 |
Ok(PathOrIdentifier::Path(path)) |
| 735 |
} |
| 736 |
} |
| 737 |
} |
| 738 |
|
| 739 |
struct State<'a, 'l> { |
| 740 |
syntax: &'l Syntax<'a>, |
| 741 |
loop_depth: Cell<usize>, |
| 742 |
level: Level<'l>, |
| 743 |
} |
| 744 |
|
| 745 |
impl State<'_, '_> { |
| 746 |
fn tag_block_start<'i>(&self, i: &mut &'i str) -> ParseResult<'i, ()> { |
| 747 |
self.syntax.block_start.value(()).parse_next(i) |
| 748 |
} |
| 749 |
|
| 750 |
fn tag_block_end<'i>(&self, i: &mut &'i str) -> ParseResult<'i, ()> { |
| 751 |
let control = alt(( |
| 752 |
self.syntax.block_end.value(None), |
| 753 |
peek(delimited('%', alt(('-', '~', '+')).map(Some), '}')), |
| 754 |
fail, // rollback on partial matches in the previous line |
| 755 |
)) |
| 756 |
.parse_next(i)?; |
| 757 |
if let Some(control) = control { |
| 758 |
let message = format!( |
| 759 |
"unclosed block, you likely meant to apply whitespace control: \"{}{}\"", |
| 760 |
control.escape_default(), |
| 761 |
self.syntax.block_end.escape_default(), |
| 762 |
); |
| 763 |
Err(ErrorContext::new(message, *i).backtrack()) |
| 764 |
} else { |
| 765 |
Ok(()) |
| 766 |
} |
| 767 |
} |
| 768 |
|
| 769 |
fn tag_comment_start<'i>(&self, i: &mut &'i str) -> ParseResult<'i, ()> { |
| 770 |
self.syntax.comment_start.value(()).parse_next(i) |
| 771 |
} |
| 772 |
|
| 773 |
fn tag_comment_end<'i>(&self, i: &mut &'i str) -> ParseResult<'i, ()> { |
| 774 |
self.syntax.comment_end.value(()).parse_next(i) |
| 775 |
} |
| 776 |
|
| 777 |
fn tag_expr_start<'i>(&self, i: &mut &'i str) -> ParseResult<'i, ()> { |
| 778 |
self.syntax.expr_start.value(()).parse_next(i) |
| 779 |
} |
| 780 |
|
| 781 |
fn tag_expr_end<'i>(&self, i: &mut &'i str) -> ParseResult<'i, ()> { |
| 782 |
self.syntax.expr_end.value(()).parse_next(i) |
| 783 |
} |
| 784 |
|
| 785 |
fn enter_loop(&self) { |
| 786 |
self.loop_depth.set(self.loop_depth.get() + 1); |
| 787 |
} |
| 788 |
|
| 789 |
fn leave_loop(&self) { |
| 790 |
self.loop_depth.set(self.loop_depth.get() - 1); |
| 791 |
} |
| 792 |
|
| 793 |
fn is_in_loop(&self) -> bool { |
| 794 |
self.loop_depth.get() > 0 |
| 795 |
} |
| 796 |
} |
| 797 |
|
| 798 |
#[derive(Default, Hash, PartialEq, Clone, Copy)] |
| 799 |
pub struct Syntax<'a>(InnerSyntax<'a>); |
| 800 |
|
| 801 |
// This abstraction ensures that the fields are readable, but not writable. |
| 802 |
#[derive(Hash, PartialEq, Clone, Copy)] |
| 803 |
pub struct InnerSyntax<'a> { |
| 804 |
pub block_start: &'a str, |
| 805 |
pub block_end: &'a str, |
| 806 |
pub expr_start: &'a str, |
| 807 |
pub expr_end: &'a str, |
| 808 |
pub comment_start: &'a str, |
| 809 |
pub comment_end: &'a str, |
| 810 |
} |
| 811 |
|
| 812 |
impl<'a> Deref for Syntax<'a> { |
| 813 |
type Target = InnerSyntax<'a>; |
| 814 |
|
| 815 |
#[inline] |
| 816 |
fn deref(&self) -> &Self::Target { |
| 817 |
&self.0 |
| 818 |
} |
| 819 |
} |
| 820 |
|
| 821 |
impl Default for InnerSyntax<'static> { |
| 822 |
fn default() -> Self { |
| 823 |
Self { |
| 824 |
block_start: "{%", |
| 825 |
block_end: "%}", |
| 826 |
expr_start: "{{", |
| 827 |
expr_end: "}}", |
| 828 |
comment_start: "{#", |
| 829 |
comment_end: "#}", |
| 830 |
} |
| 831 |
} |
| 832 |
} |
| 833 |
|
| 834 |
impl fmt::Debug for Syntax<'_> { |
| 835 |
#[inline] |
| 836 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 837 |
fmt_syntax("Syntax", self, f) |
| 838 |
} |
| 839 |
} |
| 840 |
|
| 841 |
impl fmt::Debug for InnerSyntax<'_> { |
| 842 |
#[inline] |
| 843 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 844 |
fmt_syntax("InnerSyntax", self, f) |
| 845 |
} |
| 846 |
} |
| 847 |
|
| 848 |
fn fmt_syntax(name: &str, inner: &InnerSyntax<'_>, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 849 |
f.debug_struct(name) |
| 850 |
.field("block_start", &inner.block_start) |
| 851 |
.field("block_end", &inner.block_end) |
| 852 |
.field("expr_start", &inner.expr_start) |
| 853 |
.field("expr_end", &inner.expr_end) |
| 854 |
.field("comment_start", &inner.comment_start) |
| 855 |
.field("comment_end", &inner.comment_end) |
| 856 |
.finish() |
| 857 |
} |
| 858 |
|
| 859 |
#[derive(Debug, Default, Clone, Copy, Hash, PartialEq)] |
| 860 |
#[cfg_attr(feature = "config", derive(serde_derive::Deserialize))] |
| 861 |
pub struct SyntaxBuilder<'a> { |
| 862 |
pub name: &'a str, |
| 863 |
pub block_start: Option<&'a str>, |
| 864 |
pub block_end: Option<&'a str>, |
| 865 |
pub expr_start: Option<&'a str>, |
| 866 |
pub expr_end: Option<&'a str>, |
| 867 |
pub comment_start: Option<&'a str>, |
| 868 |
pub comment_end: Option<&'a str>, |
| 869 |
} |
| 870 |
|
| 871 |
impl<'a> SyntaxBuilder<'a> { |
| 872 |
pub fn to_syntax(&self) -> Result<Syntax<'a>, String> { |
| 873 |
let default = InnerSyntax::default(); |
| 874 |
let syntax = Syntax(InnerSyntax { |
| 875 |
block_start: self.block_start.unwrap_or(default.block_start), |
| 876 |
block_end: self.block_end.unwrap_or(default.block_end), |
| 877 |
expr_start: self.expr_start.unwrap_or(default.expr_start), |
| 878 |
expr_end: self.expr_end.unwrap_or(default.expr_end), |
| 879 |
comment_start: self.comment_start.unwrap_or(default.comment_start), |
| 880 |
comment_end: self.comment_end.unwrap_or(default.comment_end), |
| 881 |
}); |
| 882 |
|
| 883 |
for (s, k, is_closing) in [ |
| 884 |
(syntax.block_start, "opening block", false), |
| 885 |
(syntax.block_end, "closing block", true), |
| 886 |
(syntax.expr_start, "opening expression", false), |
| 887 |
(syntax.expr_end, "closing expression", true), |
| 888 |
(syntax.comment_start, "opening comment", false), |
| 889 |
(syntax.comment_end, "closing comment", true), |
| 890 |
] { |
| 891 |
if s.len() < 2 { |
| 892 |
return Err(format!( |
| 893 |
"delimiters must be at least two characters long. \ |
| 894 |
The {k} delimiter ({s:?}) is too short", |
| 895 |
)); |
| 896 |
} else if s.len() > 32 { |
| 897 |
return Err(format!( |
| 898 |
"delimiters must be at most 32 characters long. \ |
| 899 |
The {k} delimiter ({:?}...) is too long", |
| 900 |
&s[..(16..=s.len()) |
| 901 |
.find(|&i| s.is_char_boundary(i)) |
| 902 |
.unwrap_or(s.len())], |
| 903 |
)); |
| 904 |
} else if s.chars().any(char::is_whitespace) { |
| 905 |
return Err(format!( |
| 906 |
"delimiters may not contain white spaces. \ |
| 907 |
The {k} delimiter ({s:?}) contains white spaces", |
| 908 |
)); |
| 909 |
} else if is_closing |
| 910 |
&& ['(', '-', '+', '~', '.', '>', '<', '&', '|', '!'] |
| 911 |
.contains(&s.chars().next().unwrap()) |
| 912 |
{ |
| 913 |
return Err(format!( |
| 914 |
"closing delimiters may not start with operators. \ |
| 915 |
The {k} delimiter ({s:?}) starts with operator `{}`", |
| 916 |
s.chars().next().unwrap(), |
| 917 |
)); |
| 918 |
} |
| 919 |
} |
| 920 |
|
| 921 |
for ((s1, k1), (s2, k2)) in [ |
| 922 |
( |
| 923 |
(syntax.block_start, "block"), |
| 924 |
(syntax.expr_start, "expression"), |
| 925 |
), |
| 926 |
( |
| 927 |
(syntax.block_start, "block"), |
| 928 |
(syntax.comment_start, "comment"), |
| 929 |
), |
| 930 |
( |
| 931 |
(syntax.expr_start, "expression"), |
| 932 |
(syntax.comment_start, "comment"), |
| 933 |
), |
| 934 |
] { |
| 935 |
if s1.starts_with(s2) || s2.starts_with(s1) { |
| 936 |
let (s1, k1, s2, k2) = match s1.len() < s2.len() { |
| 937 |
true => (s1, k1, s2, k2), |
| 938 |
false => (s2, k2, s1, k1), |
| 939 |
}; |
| 940 |
return Err(format!( |
| 941 |
"an opening delimiter may not be the prefix of another delimiter. \ |
| 942 |
The {k1} delimiter ({s1:?}) clashes with the {k2} delimiter ({s2:?})", |
| 943 |
)); |
| 944 |
} |
| 945 |
} |
| 946 |
|
| 947 |
Ok(syntax) |
| 948 |
} |
| 949 |
} |
| 950 |
|
| 951 |
/// The nesting level of nodes and expressions. |
| 952 |
/// |
| 953 |
/// The level counts down from [`Level::MAX_DEPTH`] to 0. Once the value would reach below 0, |
| 954 |
/// [`Level::nest()`] / [`LevelGuard::nest()`] will return an error. The same [`Level`] instance is |
| 955 |
/// shared across all usages in a [`Parsed::new()`] / [`Ast::from_str()`] call, using a reference |
| 956 |
/// to an interior mutable counter. |
| 957 |
#[derive(Debug, Clone, Copy)] |
| 958 |
struct Level<'l>(&'l Cell<usize>); |
| 959 |
|
| 960 |
impl Level<'_> { |
| 961 |
const MAX_DEPTH: usize = 128; |
| 962 |
|
| 963 |
/// Acquire a [`LevelGuard`] without decrementing the counter, to be used with loops. |
| 964 |
fn guard(&self) -> LevelGuard<'_> { |
| 965 |
LevelGuard { |
| 966 |
level: *self, |
| 967 |
count: 0, |
| 968 |
} |
| 969 |
} |
| 970 |
|
| 971 |
/// Decrement the remaining level counter, and return a [`LevelGuard`] that increments it again |
| 972 |
/// when it's dropped. |
| 973 |
fn nest<'a>(&self, i: &'a str) -> ParseResult<'a, LevelGuard<'_>> { |
| 974 |
if let Some(new_level) = self.0.get().checked_sub(1) { |
| 975 |
self.0.set(new_level); |
| 976 |
Ok(LevelGuard { |
| 977 |
level: *self, |
| 978 |
count: 1, |
| 979 |
}) |
| 980 |
} else { |
| 981 |
Err(Self::_fail(i)) |
| 982 |
} |
| 983 |
} |
| 984 |
|
| 985 |
#[cold] |
| 986 |
#[inline(never)] |
| 987 |
fn _fail(i: &str) -> ParseErr<'_> { |
| 988 |
winnow::error::ErrMode::Cut(ErrorContext::new( |
| 989 |
"your template code is too deeply nested, or the last expression is too complex", |
| 990 |
i, |
| 991 |
)) |
| 992 |
} |
| 993 |
} |
| 994 |
|
| 995 |
/// Used to keep track how often [`LevelGuard::nest()`] was called and to re-increment the |
| 996 |
/// remaining level counter when it is dropped / falls out of scope. |
| 997 |
#[must_use] |
| 998 |
struct LevelGuard<'l> { |
| 999 |
level: Level<'l>, |
| 1000 |
count: usize, |
| 1001 |
} |
| 1002 |
|
| 1003 |
impl Drop for LevelGuard<'_> { |
| 1004 |
fn drop(&mut self) { |
| 1005 |
self.level.0.set(self.level.0.get() + self.count); |
| 1006 |
} |
| 1007 |
} |
| 1008 |
|
| 1009 |
impl LevelGuard<'_> { |
| 1010 |
/// Used to decrement the level multiple times, e.g. for every iteration of a loop. |
| 1011 |
fn nest<'a>(&mut self, i: &'a str) -> ParseResult<'a, ()> { |
| 1012 |
if let Some(new_level) = self.level.0.get().checked_sub(1) { |
| 1013 |
self.level.0.set(new_level); |
| 1014 |
self.count += 1; |
| 1015 |
Ok(()) |
| 1016 |
} else { |
| 1017 |
Err(Level::_fail(i)) |
| 1018 |
} |
| 1019 |
} |
| 1020 |
} |
| 1021 |
|
| 1022 |
#[allow(clippy::type_complexity)] |
| 1023 |
fn filter<'a>( |
| 1024 |
i: &mut &'a str, |
| 1025 |
level: Level<'_>, |
| 1026 |
) -> ParseResult< |
| 1027 |
'a, |
| 1028 |
( |
| 1029 |
&'a str, |
| 1030 |
Vec<WithSpan<'a, TyGenerics<'a>>>, |
| 1031 |
Option<Vec<WithSpan<'a, Expr<'a>>>>, |
| 1032 |
), |
| 1033 |
> { |
| 1034 |
ws(('|', not('|'))).parse_next(i)?; |
| 1035 |
|
| 1036 |
let _level_guard = level.nest(i)?; |
| 1037 |
cut_err(( |
| 1038 |
ws(identifier), |
| 1039 |
opt(|i: &mut _| expr::call_generics(i, level)).map(|generics| generics.unwrap_or_default()), |
| 1040 |
opt(|i: &mut _| Expr::arguments(i, level, false)), |
| 1041 |
)) |
| 1042 |
.parse_next(i) |
| 1043 |
} |
| 1044 |
|
| 1045 |
/// Returns the common parts of two paths. |
| 1046 |
/// |
| 1047 |
/// The goal of this function is to reduce the path length based on the `base` argument |
| 1048 |
/// (generally the path where the program is running into). For example: |
| 1049 |
/// |
| 1050 |
/// ```text |
| 1051 |
/// current dir: /a/b/c |
| 1052 |
/// path: /a/b/c/d/e.txt |
| 1053 |
/// ``` |
| 1054 |
/// |
| 1055 |
/// `strip_common` will return `d/e.txt`. |
| 1056 |
#[must_use] |
| 1057 |
pub fn strip_common(base: &Path, path: &Path) -> String { |
| 1058 |
let path = match path.canonicalize() { |
| 1059 |
Ok(path) => path, |
| 1060 |
Err(_) => return path.display().to_string(), |
| 1061 |
}; |
| 1062 |
let mut components_iter = path.components().peekable(); |
| 1063 |
|
| 1064 |
for current_path_component in base.components() { |
| 1065 |
let Some(path_component) = components_iter.peek() else { |
| 1066 |
return path.display().to_string(); |
| 1067 |
}; |
| 1068 |
if current_path_component != *path_component { |
| 1069 |
break; |
| 1070 |
} |
| 1071 |
components_iter.next(); |
| 1072 |
} |
| 1073 |
let path_parts = components_iter |
| 1074 |
.map(|c| c.as_os_str().to_string_lossy()) |
| 1075 |
.collect::<Vec<_>>(); |
| 1076 |
if path_parts.is_empty() { |
| 1077 |
path.display().to_string() |
| 1078 |
} else { |
| 1079 |
path_parts.join(std::path::MAIN_SEPARATOR_STR) |
| 1080 |
} |
| 1081 |
} |
| 1082 |
|
| 1083 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1084 |
pub enum IntKind { |
| 1085 |
I8, |
| 1086 |
I16, |
| 1087 |
I32, |
| 1088 |
I64, |
| 1089 |
I128, |
| 1090 |
Isize, |
| 1091 |
U8, |
| 1092 |
U16, |
| 1093 |
U32, |
| 1094 |
U64, |
| 1095 |
U128, |
| 1096 |
Usize, |
| 1097 |
} |
| 1098 |
|
| 1099 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1100 |
pub enum FloatKind { |
| 1101 |
F16, |
| 1102 |
F32, |
| 1103 |
F64, |
| 1104 |
F128, |
| 1105 |
} |
| 1106 |
|
| 1107 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1108 |
enum NumKind { |
| 1109 |
Int(IntKind), |
| 1110 |
Float(FloatKind), |
| 1111 |
} |
| 1112 |
|
| 1113 |
/// Primitive integer types. Also used as number suffixes. |
| 1114 |
const INTEGER_TYPES: &[(&str, IntKind)] = &[ |
| 1115 |
("i8", IntKind::I8), |
| 1116 |
("i16", IntKind::I16), |
| 1117 |
("i32", IntKind::I32), |
| 1118 |
("i64", IntKind::I64), |
| 1119 |
("i128", IntKind::I128), |
| 1120 |
("isize", IntKind::Isize), |
| 1121 |
("u8", IntKind::U8), |
| 1122 |
("u16", IntKind::U16), |
| 1123 |
("u32", IntKind::U32), |
| 1124 |
("u64", IntKind::U64), |
| 1125 |
("u128", IntKind::U128), |
| 1126 |
("usize", IntKind::Usize), |
| 1127 |
]; |
| 1128 |
|
| 1129 |
/// Primitive floating point types. Also used as number suffixes. |
| 1130 |
const FLOAT_TYPES: &[(&str, FloatKind)] = &[ |
| 1131 |
("f16", FloatKind::F16), |
| 1132 |
("f32", FloatKind::F32), |
| 1133 |
("f64", FloatKind::F64), |
| 1134 |
("f128", FloatKind::F128), |
| 1135 |
]; |
| 1136 |
|
| 1137 |
/// Primitive numeric types. Also used as number suffixes. |
| 1138 |
const NUM_TYPES: &[(&str, NumKind)] = &{ |
| 1139 |
let mut list = [("", NumKind::Int(IntKind::I8)); INTEGER_TYPES.len() + FLOAT_TYPES.len()]; |
| 1140 |
let mut i = 0; |
| 1141 |
let mut o = 0; |
| 1142 |
while i < INTEGER_TYPES.len() { |
| 1143 |
let (name, value) = INTEGER_TYPES[i]; |
| 1144 |
list[o] = (name, NumKind::Int(value)); |
| 1145 |
i += 1; |
| 1146 |
o += 1; |
| 1147 |
} |
| 1148 |
let mut i = 0; |
| 1149 |
while i < FLOAT_TYPES.len() { |
| 1150 |
let (name, value) = FLOAT_TYPES[i]; |
| 1151 |
list[o] = (name, NumKind::Float(value)); |
| 1152 |
i += 1; |
| 1153 |
o += 1; |
| 1154 |
} |
| 1155 |
list |
| 1156 |
}; |
| 1157 |
|
| 1158 |
/// Complete list of named primitive types. |
| 1159 |
const PRIMITIVE_TYPES: &[&str] = &{ |
| 1160 |
let mut list = [""; NUM_TYPES.len() + 1]; |
| 1161 |
let mut i = 0; |
| 1162 |
let mut o = 0; |
| 1163 |
while i < NUM_TYPES.len() { |
| 1164 |
list[o] = NUM_TYPES[i].0; |
| 1165 |
i += 1; |
| 1166 |
o += 1; |
| 1167 |
} |
| 1168 |
list[o] = "bool"; |
| 1169 |
list |
| 1170 |
}; |
| 1171 |
|
| 1172 |
pub const MAX_RUST_KEYWORD_LEN: usize = 8; |
| 1173 |
pub const MAX_RUST_RAW_KEYWORD_LEN: usize = MAX_RUST_KEYWORD_LEN + 2; |
| 1174 |
|
| 1175 |
pub const RUST_KEYWORDS: &[&[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]]; MAX_RUST_KEYWORD_LEN + 1] = &{ |
| 1176 |
const NO_KWS: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &[]; |
| 1177 |
const KW2: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &[ |
| 1178 |
AsciiStr::new_sized("r#as"), |
| 1179 |
AsciiStr::new_sized("r#do"), |
| 1180 |
AsciiStr::new_sized("r#fn"), |
| 1181 |
AsciiStr::new_sized("r#if"), |
| 1182 |
AsciiStr::new_sized("r#in"), |
| 1183 |
]; |
| 1184 |
const KW3: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &[ |
| 1185 |
AsciiStr::new_sized("r#box"), |
| 1186 |
AsciiStr::new_sized("r#dyn"), |
| 1187 |
AsciiStr::new_sized("r#for"), |
| 1188 |
AsciiStr::new_sized("r#gen"), |
| 1189 |
AsciiStr::new_sized("r#let"), |
| 1190 |
AsciiStr::new_sized("r#mod"), |
| 1191 |
AsciiStr::new_sized("r#mut"), |
| 1192 |
AsciiStr::new_sized("r#pub"), |
| 1193 |
AsciiStr::new_sized("r#ref"), |
| 1194 |
AsciiStr::new_sized("r#try"), |
| 1195 |
AsciiStr::new_sized("r#use"), |
| 1196 |
]; |
| 1197 |
const KW4: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &[ |
| 1198 |
AsciiStr::new_sized("r#else"), |
| 1199 |
AsciiStr::new_sized("r#enum"), |
| 1200 |
AsciiStr::new_sized("r#impl"), |
| 1201 |
AsciiStr::new_sized("r#move"), |
| 1202 |
AsciiStr::new_sized("r#priv"), |
| 1203 |
AsciiStr::new_sized("r#true"), |
| 1204 |
AsciiStr::new_sized("r#type"), |
| 1205 |
]; |
| 1206 |
const KW5: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &[ |
| 1207 |
AsciiStr::new_sized("r#async"), |
| 1208 |
AsciiStr::new_sized("r#await"), |
| 1209 |
AsciiStr::new_sized("r#break"), |
| 1210 |
AsciiStr::new_sized("r#const"), |
| 1211 |
AsciiStr::new_sized("r#crate"), |
| 1212 |
AsciiStr::new_sized("r#false"), |
| 1213 |
AsciiStr::new_sized("r#final"), |
| 1214 |
AsciiStr::new_sized("r#macro"), |
| 1215 |
AsciiStr::new_sized("r#match"), |
| 1216 |
AsciiStr::new_sized("r#trait"), |
| 1217 |
AsciiStr::new_sized("r#where"), |
| 1218 |
AsciiStr::new_sized("r#while"), |
| 1219 |
AsciiStr::new_sized("r#yield"), |
| 1220 |
]; |
| 1221 |
const KW6: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &[ |
| 1222 |
AsciiStr::new_sized("r#become"), |
| 1223 |
AsciiStr::new_sized("r#extern"), |
| 1224 |
AsciiStr::new_sized("r#return"), |
| 1225 |
AsciiStr::new_sized("r#static"), |
| 1226 |
AsciiStr::new_sized("r#struct"), |
| 1227 |
AsciiStr::new_sized("r#typeof"), |
| 1228 |
AsciiStr::new_sized("r#unsafe"), |
| 1229 |
]; |
| 1230 |
const KW7: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &[ |
| 1231 |
AsciiStr::new_sized("r#unsized"), |
| 1232 |
AsciiStr::new_sized("r#virtual"), |
| 1233 |
]; |
| 1234 |
const KW8: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &[ |
| 1235 |
AsciiStr::new_sized("r#abstract"), |
| 1236 |
AsciiStr::new_sized("r#continue"), |
| 1237 |
AsciiStr::new_sized("r#override"), |
| 1238 |
]; |
| 1239 |
|
| 1240 |
[NO_KWS, NO_KWS, KW2, KW3, KW4, KW5, KW6, KW7, KW8] |
| 1241 |
}; |
| 1242 |
|
| 1243 |
// These ones are only used in the parser, hence why they're private. |
| 1244 |
const KWS_PARSER: &[&[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]]; MAX_RUST_KEYWORD_LEN + 1] = &{ |
| 1245 |
const KW4: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &{ |
| 1246 |
let mut result = [AsciiStr::new_sized("r#"); RUST_KEYWORDS[4].len() + 3]; |
| 1247 |
let mut i = 0; |
| 1248 |
while i < RUST_KEYWORDS[4].len() { |
| 1249 |
result[i] = RUST_KEYWORDS[4][i]; |
| 1250 |
i += 1; |
| 1251 |
} |
| 1252 |
result[result.len() - 3] = AsciiStr::new_sized("r#loop"); |
| 1253 |
result[result.len() - 2] = AsciiStr::new_sized("r#self"); |
| 1254 |
result[result.len() - 1] = AsciiStr::new_sized("r#Self"); |
| 1255 |
result |
| 1256 |
}; |
| 1257 |
const KW5: &[[AsciiChar; MAX_RUST_RAW_KEYWORD_LEN]] = &{ |
| 1258 |
let mut result = [AsciiStr::new_sized("r#"); RUST_KEYWORDS[5].len() + 2]; |
| 1259 |
let mut i = 0; |
| 1260 |
while i < RUST_KEYWORDS[5].len() { |
| 1261 |
result[i] = RUST_KEYWORDS[5][i]; |
| 1262 |
i += 1; |
| 1263 |
} |
| 1264 |
result[result.len() - 2] = AsciiStr::new_sized("r#super"); |
| 1265 |
result[result.len() - 1] = AsciiStr::new_sized("r#union"); |
| 1266 |
result |
| 1267 |
}; |
| 1268 |
|
| 1269 |
[ |
| 1270 |
RUST_KEYWORDS[0], |
| 1271 |
RUST_KEYWORDS[1], |
| 1272 |
RUST_KEYWORDS[2], |
| 1273 |
RUST_KEYWORDS[3], |
| 1274 |
KW4, |
| 1275 |
KW5, |
| 1276 |
RUST_KEYWORDS[6], |
| 1277 |
RUST_KEYWORDS[7], |
| 1278 |
RUST_KEYWORDS[8], |
| 1279 |
] |
| 1280 |
}; |
| 1281 |
|
| 1282 |
fn is_rust_keyword(ident: &str) -> bool { |
| 1283 |
let ident_len = ident.len(); |
| 1284 |
if ident_len > MAX_RUST_KEYWORD_LEN { |
| 1285 |
return false; |
| 1286 |
} |
| 1287 |
let kws = KWS_PARSER[ident.len()]; |
| 1288 |
|
| 1289 |
let mut padded_ident = [0; MAX_RUST_KEYWORD_LEN]; |
| 1290 |
padded_ident[..ident_len].copy_from_slice(ident.as_bytes()); |
| 1291 |
|
| 1292 |
// Since the individual buckets are quite short, a linear search is faster than a binary search. |
| 1293 |
for probe in kws { |
| 1294 |
if padded_ident == *AsciiChar::slice_as_bytes(probe[2..].try_into().unwrap()) { |
| 1295 |
return true; |
| 1296 |
} |
| 1297 |
} |
| 1298 |
false |
| 1299 |
} |
| 1300 |
|
| 1301 |
#[cfg(not(windows))] |
| 1302 |
#[cfg(test)] |
| 1303 |
mod test { |
| 1304 |
use std::path::Path; |
| 1305 |
|
| 1306 |
use super::*; |
| 1307 |
|
| 1308 |
#[test] |
| 1309 |
fn test_strip_common() { |
| 1310 |
// Full path is returned instead of empty when the entire path is in common. |
| 1311 |
assert_eq!(strip_common(Path::new("home"), Path::new("home")), "home"); |
| 1312 |
|
| 1313 |
let cwd = std::env::current_dir().expect("current_dir failed"); |
| 1314 |
|
| 1315 |
// We need actual existing paths for `canonicalize` to work, so let's do that. |
| 1316 |
let entry = cwd |
| 1317 |
.read_dir() |
| 1318 |
.expect("read_dir failed") |
| 1319 |
.filter_map(std::result::Result::ok) |
| 1320 |
.find(|f| f.path().is_file()) |
| 1321 |
.expect("no entry"); |
| 1322 |
|
| 1323 |
// Since they have the complete path in common except for the folder entry name, it should |
| 1324 |
// return only the folder entry name. |
| 1325 |
assert_eq!( |
| 1326 |
strip_common(&cwd, &entry.path()), |
| 1327 |
entry.file_name().to_string_lossy() |
| 1328 |
); |
| 1329 |
|
| 1330 |
// In this case it cannot canonicalize `/a/b/c` so it returns the path as is. |
| 1331 |
assert_eq!(strip_common(&cwd, Path::new("/a/b/c")), "/a/b/c"); |
| 1332 |
} |
| 1333 |
|
| 1334 |
#[test] |
| 1335 |
fn test_num_lit() { |
| 1336 |
// Should fail. |
| 1337 |
assert!(num_lit.parse_peek(".").is_err()); |
| 1338 |
// Should succeed. |
| 1339 |
assert_eq!( |
| 1340 |
num_lit.parse_peek("1.2E-02").unwrap(), |
| 1341 |
("", Num::Float("1.2E-02", None)) |
| 1342 |
); |
| 1343 |
assert_eq!( |
| 1344 |
num_lit.parse_peek("4e3").unwrap(), |
| 1345 |
("", Num::Float("4e3", None)), |
| 1346 |
); |
| 1347 |
assert_eq!( |
| 1348 |
num_lit.parse_peek("4e+_3").unwrap(), |
| 1349 |
("", Num::Float("4e+_3", None)), |
| 1350 |
); |
| 1351 |
// Not supported because Rust wants a number before the `.`. |
| 1352 |
assert!(num_lit.parse_peek(".1").is_err()); |
| 1353 |
assert!(num_lit.parse_peek(".1E-02").is_err()); |
| 1354 |
// A `_` directly after the `.` denotes a field. |
| 1355 |
assert_eq!( |
| 1356 |
num_lit.parse_peek("1._0").unwrap(), |
| 1357 |
("._0", Num::Int("1", None)) |
| 1358 |
); |
| 1359 |
assert_eq!( |
| 1360 |
num_lit.parse_peek("1_.0").unwrap(), |
| 1361 |
("", Num::Float("1_.0", None)) |
| 1362 |
); |
| 1363 |
// Not supported (voluntarily because of `1..` syntax). |
| 1364 |
assert_eq!( |
| 1365 |
num_lit.parse_peek("1.").unwrap(), |
| 1366 |
(".", Num::Int("1", None)) |
| 1367 |
); |
| 1368 |
assert_eq!( |
| 1369 |
num_lit.parse_peek("1_.").unwrap(), |
| 1370 |
(".", Num::Int("1_", None)) |
| 1371 |
); |
| 1372 |
assert_eq!( |
| 1373 |
num_lit.parse_peek("1_2.").unwrap(), |
| 1374 |
(".", Num::Int("1_2", None)) |
| 1375 |
); |
| 1376 |
// Numbers with suffixes |
| 1377 |
assert_eq!( |
| 1378 |
num_lit.parse_peek("-1usize").unwrap(), |
| 1379 |
("", Num::Int("-1", Some(IntKind::Usize))) |
| 1380 |
); |
| 1381 |
assert_eq!( |
| 1382 |
num_lit.parse_peek("123_f32").unwrap(), |
| 1383 |
("", Num::Float("123_", Some(FloatKind::F32))) |
| 1384 |
); |
| 1385 |
assert_eq!( |
| 1386 |
num_lit.parse_peek("1_.2_e+_3_f64|into_isize").unwrap(), |
| 1387 |
( |
| 1388 |
"|into_isize", |
| 1389 |
Num::Float("1_.2_e+_3_", Some(FloatKind::F64)) |
| 1390 |
) |
| 1391 |
); |
| 1392 |
assert_eq!( |
| 1393 |
num_lit.parse_peek("4e3f128").unwrap(), |
| 1394 |
("", Num::Float("4e3", Some(FloatKind::F128))), |
| 1395 |
); |
| 1396 |
} |
| 1397 |
|
| 1398 |
#[test] |
| 1399 |
fn test_char_lit() { |
| 1400 |
let lit = |s: &'static str| crate::CharLit { |
| 1401 |
prefix: None, |
| 1402 |
content: s, |
| 1403 |
}; |
| 1404 |
|
| 1405 |
assert_eq!(char_lit.parse_peek("'a'").unwrap(), ("", lit("a"))); |
| 1406 |
assert_eq!(char_lit.parse_peek("'字'").unwrap(), ("", lit("字"))); |
| 1407 |
|
| 1408 |
// Escaped single characters. |
| 1409 |
assert_eq!(char_lit.parse_peek("'\\\"'").unwrap(), ("", lit("\\\""))); |
| 1410 |
assert_eq!(char_lit.parse_peek("'\\''").unwrap(), ("", lit("\\'"))); |
| 1411 |
assert_eq!(char_lit.parse_peek("'\\t'").unwrap(), ("", lit("\\t"))); |
| 1412 |
assert_eq!(char_lit.parse_peek("'\\n'").unwrap(), ("", lit("\\n"))); |
| 1413 |
assert_eq!(char_lit.parse_peek("'\\r'").unwrap(), ("", lit("\\r"))); |
| 1414 |
assert_eq!(char_lit.parse_peek("'\\0'").unwrap(), ("", lit("\\0"))); |
| 1415 |
// Escaped ascii characters (up to `0x7F`). |
| 1416 |
assert_eq!(char_lit.parse_peek("'\\x12'").unwrap(), ("", lit("\\x12"))); |
| 1417 |
assert_eq!(char_lit.parse_peek("'\\x02'").unwrap(), ("", lit("\\x02"))); |
| 1418 |
assert_eq!(char_lit.parse_peek("'\\x6a'").unwrap(), ("", lit("\\x6a"))); |
| 1419 |
assert_eq!(char_lit.parse_peek("'\\x7F'").unwrap(), ("", lit("\\x7F"))); |
| 1420 |
// Escaped unicode characters (up to `0x10FFFF`). |
| 1421 |
assert_eq!( |
| 1422 |
char_lit.parse_peek("'\\u{A}'").unwrap(), |
| 1423 |
("", lit("\\u{A}")) |
| 1424 |
); |
| 1425 |
assert_eq!( |
| 1426 |
char_lit.parse_peek("'\\u{10}'").unwrap(), |
| 1427 |
("", lit("\\u{10}")) |
| 1428 |
); |
| 1429 |
assert_eq!( |
| 1430 |
char_lit.parse_peek("'\\u{aa}'").unwrap(), |
| 1431 |
("", lit("\\u{aa}")) |
| 1432 |
); |
| 1433 |
assert_eq!( |
| 1434 |
char_lit.parse_peek("'\\u{10FFFF}'").unwrap(), |
| 1435 |
("", lit("\\u{10FFFF}")) |
| 1436 |
); |
| 1437 |
|
| 1438 |
// Check with `b` prefix. |
| 1439 |
assert_eq!( |
| 1440 |
char_lit.parse_peek("b'a'").unwrap(), |
| 1441 |
( |
| 1442 |
"", |
| 1443 |
crate::CharLit { |
| 1444 |
prefix: Some(crate::CharPrefix::Binary), |
| 1445 |
content: "a" |
| 1446 |
} |
| 1447 |
) |
| 1448 |
); |
| 1449 |
|
| 1450 |
// Should fail. |
| 1451 |
assert!(char_lit.parse_peek("''").is_err()); |
| 1452 |
assert!(char_lit.parse_peek("'\\o'").is_err()); |
| 1453 |
assert!(char_lit.parse_peek("'\\x'").is_err()); |
| 1454 |
assert!(char_lit.parse_peek("'\\x1'").is_err()); |
| 1455 |
assert!(char_lit.parse_peek("'\\x80'").is_err()); |
| 1456 |
assert!(char_lit.parse_peek("'\\u'").is_err()); |
| 1457 |
assert!(char_lit.parse_peek("'\\u{}'").is_err()); |
| 1458 |
assert!(char_lit.parse_peek("'\\u{110000}'").is_err()); |
| 1459 |
} |
| 1460 |
|
| 1461 |
#[test] |
| 1462 |
fn test_str_lit() { |
| 1463 |
assert_eq!( |
| 1464 |
str_lit.parse_peek(r#"b"hello""#).unwrap(), |
| 1465 |
( |
| 1466 |
"", |
| 1467 |
StrLit { |
| 1468 |
prefix: Some(StrPrefix::Binary), |
| 1469 |
content: "hello" |
| 1470 |
} |
| 1471 |
) |
| 1472 |
); |
| 1473 |
assert_eq!( |
| 1474 |
str_lit.parse_peek(r#"c"hello""#).unwrap(), |
| 1475 |
( |
| 1476 |
"", |
| 1477 |
StrLit { |
| 1478 |
prefix: Some(StrPrefix::CLike), |
| 1479 |
content: "hello" |
| 1480 |
} |
| 1481 |
) |
| 1482 |
); |
| 1483 |
assert!(str_lit.parse_peek(r#"d"hello""#).is_err()); |
| 1484 |
} |
| 1485 |
|
| 1486 |
#[test] |
| 1487 |
fn assert_span_size() { |
| 1488 |
assert_eq!( |
| 1489 |
std::mem::size_of::<Span<'static>>(), |
| 1490 |
std::mem::size_of::<*const ()>() |
| 1491 |
); |
| 1492 |
} |
| 1493 |
|
| 1494 |
#[test] |
| 1495 |
fn test_is_rust_keyword() { |
| 1496 |
assert!(is_rust_keyword("super")); |
| 1497 |
assert!(is_rust_keyword("become")); |
| 1498 |
assert!(!is_rust_keyword("supeeeer")); |
| 1499 |
assert!(!is_rust_keyword("sur")); |
| 1500 |
} |
| 1501 |
} |