use crate::{
ast::{DirectiveName, EchoKind},
error::{Error, ErrorKind},
span::{FileId, Span},
};
use std::collections::{BTreeMap, HashMap, HashSet};
mod ends;
use ends::{Ends, Scan};
#[derive(Clone, Debug, Default)]
pub struct DirectiveTable {
directives: HashMap<String, bool>,
conditions: HashSet<String>,
component_tags_disabled: bool,
}
impl DirectiveTable {
pub fn new() -> Self {
Self::default()
}
pub(crate) fn disable_component_tags(&mut self) {
self.component_tags_disabled = true;
}
pub fn register_directive(&mut self, name: &str, consumes_newline: bool) {
self.directives.insert(name.to_owned(), consumes_newline);
}
pub fn register_condition(&mut self, name: &str) {
self.conditions.insert(name.to_owned());
}
pub(crate) fn register_exact_directive(&mut self, name: &str, consumes_newline: bool) {
self.register_directive(name, consumes_newline);
}
pub(crate) fn register_exact_condition(&mut self, name: &str) {
self.register_condition(name);
}
pub fn resolve(&self, name: &str) -> Option<DirectiveName> {
use DirectiveName::*;
if self.directives.contains_key(name) {
return Some(Custom(name.to_owned()));
}
if self.conditions.contains(name) {
return Some(Condition(name.to_owned()));
}
for (prefix, variant) in [
("unless", UnlessCondition as fn(String) -> DirectiveName),
("else", ElseCondition),
("end", EndCondition),
] {
if let Some(base) = name
.strip_prefix(prefix)
.filter(|base| self.conditions.contains(*base))
{
return Some(variant(base.to_owned()));
}
}
DirectiveName::builtin(&name.to_ascii_lowercase())
}
pub(crate) fn whole_tag(&self, name: &DirectiveName, arguments: bool) -> bool {
use DirectiveName::*;
match name {
Custom(name) => self.directives.get(name).copied().unwrap_or(false),
Class | Style | Extends | ExtendsFirst | Switch | Verbatim | Endverbatim | Endphp
| Endcode => false,
Php => arguments,
_ => true,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Mode {
#[default]
Template,
Lossless,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Token {
pub span: Span,
pub consumes_newline: bool,
pub kind: TokenKind,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TokenKind {
Text,
Escaped {
head: Span,
arguments: Option<Span>,
},
Comment,
Verbatim(Span),
Code(Span),
Php(Span),
RawPhp(Span),
Echo(EchoKind, Span),
Directive(DirectiveName, Option<Span>),
Tag(Tag),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Tag {
pub name: String,
pub attributes: Span,
pub closing: bool,
pub self_closing: bool,
}
impl Tag {
pub fn is_slot(&self) -> bool {
self.name == "slot" || self.name.starts_with("slot:")
}
}
#[derive(Debug, Default)]
pub struct Lexed {
pub tokens: Vec<Token>,
pub errors: Vec<Error>,
}
pub fn lex(file: FileId, source: &str, table: &DirectiveTable, mode: Mode) -> Lexed {
if u32::try_from(source.len()).is_err() {
return Lexed {
tokens: Vec::new(),
errors: vec![Error::new(
ErrorKind::Limit,
"template exceeds the span size limit",
None,
)],
};
}
let mut lexer = Lexer {
file,
source,
masked: source.as_bytes().to_vec(),
table,
mode,
tokens: BTreeMap::new(),
errors: Vec::new(),
};
lexer.raw_blocks("verbatim", TokenKind::Verbatim, false);
lexer.raw_blocks("php", TokenKind::Php, true);
lexer.raw_blocks("code", TokenKind::Code, true);
lexer.comments();
if !table.component_tags_disabled {
lexer.tags();
}
lexer.statements();
lexer.finish()
}
struct Lexer<'a> {
file: FileId,
source: &'a str,
masked: Vec<u8>,
table: &'a DirectiveTable,
mode: Mode,
tokens: BTreeMap<usize, Token>,
errors: Vec<Error>,
}
impl Lexer<'_> {
fn span(&self, start: usize, end: usize) -> Span {
Span::new(self.file, start as u32, end as u32)
}
fn add(&mut self, start: usize, end: usize, kind: TokenKind, whole_tag: bool) {
let span = self.span(start, end);
if self
.tokens
.last_key_value()
.is_some_and(|(_, token)| token.span.end as usize > start)
{
let mut covered: Vec<_> = self.tokens.range(start..end).map(|(&at, _)| at).collect();
if let Some((&at, token)) = self.tokens.range(..start).next_back()
&& token.span.end as usize > start
{
covered.push(at);
}
for at in covered {
self.tokens.remove(&at);
}
}
self.tokens.insert(
start,
Token {
span,
kind,
consumes_newline: whole_tag,
},
);
self.masked[start..end].fill(b' ');
}
fn error(&mut self, start: usize, end: usize, message: impl Into<String>) {
self.errors
.push(Error::new(ErrorKind::Lex, message, self.span(start, end)));
}
fn raw_blocks(&mut self, name: &str, token: fn(Span) -> TokenKind, whole_tag: bool) {
let open = format!("@{name}");
let close = format!("@end{name}");
let mut cursor = 0;
let mut ends = Ends::default();
while let Some(start) = find_ascii(&self.masked, cursor, open.as_bytes(), true) {
let body = start + open.len();
cursor = body;
if self.masked.get(start.wrapping_sub(1)) == Some(&b'@')
|| self
.masked
.get(body)
.is_some_and(|byte| word(*byte) || *byte == b':')
|| (whole_tag
&& self.masked.get(skip_horizontal(&self.masked, body)) == Some(&b'('))
{
continue;
}
let closing = if name == "code" {
ends.find(&self.masked, body, Scan::Code, self.mode, || {
closing_code(&self.masked, body, close.as_bytes())
})
} else {
find_ascii(&self.masked, body, close.as_bytes(), true)
};
if let Some(closing) = closing {
cursor = closing + close.len();
self.add(start, cursor, token(self.span(body, closing)), whole_tag);
} else if name != "code" {
break;
}
}
}
fn comments(&mut self) {
let mut cursor = 0;
let mut has_closer = true;
while let Some(start) = find_ascii(&self.masked, cursor, b"{{--", false) {
cursor = start + 4;
if has_closer && let Some(close) = find_ascii(&self.masked, cursor, b"--}}", false) {
cursor = close + 4;
self.add(start, cursor, TokenKind::Comment, false);
} else {
has_closer = false;
self.error(start, cursor, "unclosed Blade comment");
self.add(start, cursor, TokenKind::Text, false);
}
}
}
fn tags(&mut self) {
let mut start = 0;
let mut ends = Ends::default();
while let Some(at) = find_ascii(&self.masked, start, b"<", false) {
start = at + 1;
let name_at = start + usize::from(self.masked.get(start) == Some(&b'/'));
if !self
.masked
.get(name_at..)
.is_some_and(|rest| rest.starts_with(b"x-") || rest.starts_with(b"x:"))
{
continue;
}
let name_start = name_at + 2;
let name_end = take_while(&self.masked, name_start, |b| {
word(b) || matches!(b, b'-' | b'.' | b':')
});
if name_start == name_end {
continue;
}
let Some(end_at) = ends.find(&self.masked, name_end, Scan::Tag, self.mode, || {
tag_end(&self.masked, name_end, self.mode)
}) else {
self.error(at, name_end, "unclosed component tag");
continue;
};
let closing = name_at != start;
let self_closing = !closing && self.masked.get(end_at.wrapping_sub(1)) == Some(&b'/');
let name = self.source[name_start..name_end].to_owned();
let tag = Tag {
name,
attributes: self.span(name_end, end_at - usize::from(self_closing)),
closing,
self_closing,
};
let whole_tag = closing || (self_closing && !tag.is_slot());
start = end_at + 1;
self.add(at, start, TokenKind::Tag(tag), whole_tag);
}
}
fn statements(&mut self) {
let mut start = 0;
let mut statement_offset = 0;
let mut statement_end = 0;
let mut ends = Ends::default();
while start < self.masked.len() {
let rest = &self.masked[start..];
if !matches!(rest[0], b'<' | b'@' | b'{') {
start += 1;
continue;
}
let php_open = if rest.starts_with(b"<?=") {
3
} else if rest
.get(..5)
.is_some_and(|open| open.eq_ignore_ascii_case(b"<?php"))
&& rest.get(5).is_none_or(u8::is_ascii_whitespace)
{
5
} else {
0
};
if php_open > 0 {
let body = start + php_open;
let close = php_end(&self.masked, body);
let body_end = close.unwrap_or(self.source.len());
let end = close.map_or(body_end, |close| close + 2);
self.add(
start,
end,
TokenKind::RawPhp(self.span(body, body_end)),
close.is_some(),
);
start = end;
statement_offset = end;
continue;
}
let escaped = rest.starts_with(b"@");
let body_at = start + usize::from(escaped);
if let Some((kind, open, close)) = echo_delimiters(&self.masked[body_at..]) {
let body = body_at + open;
let opaque = escaped || self.mode == Mode::Lossless;
if let Some(end_at) = ends.find(
&self.masked,
body,
Ends::echo_scan(close, opaque),
self.mode,
|| echo_end(&self.masked, body, close, opaque),
) {
let end = end_at + close.len();
let kind = if escaped {
TokenKind::Escaped {
head: self.span(body_at, end),
arguments: None,
}
} else {
TokenKind::Echo(kind, self.span(body, end_at))
};
self.add(start, end, kind, false);
start = end;
} else {
self.error(start, body, "unclosed echo");
start = body;
}
continue;
}
if escaped
&& start >= statement_end
&& !self
.source
.as_bytes()
.get(start.wrapping_sub(1))
.is_some_and(|byte| word(*byte))
{
(start, statement_end) = self.directive(start, &mut statement_offset, &mut ends);
} else {
start += 1;
}
}
}
fn directive(
&mut self,
candidate: usize,
offset: &mut usize,
ends: &mut Ends,
) -> (usize, usize) {
let escaped = self.masked.get(candidate + 1) == Some(&b'@');
let name_at = candidate + 1 + usize::from(escaped);
let mut name_end = take_while(&self.masked, name_at, word);
if name_end == name_at {
return (candidate + 1, candidate + 1);
}
if self.masked[name_end..].starts_with(b"::")
&& self.masked.get(name_end + 2).is_some_and(|b| word(*b))
{
name_end = take_while(&self.masked, name_end + 2, word);
}
let name = self.table.resolve(&self.source[name_at..name_end]);
let args_at = skip_horizontal(&self.masked, name_end);
let mut end = name_end;
let has_args = if self.masked.get(args_at) == Some(&b'(') {
if let Some(close) =
ends.find(&self.masked, args_at + 1, Scan::Paren, self.mode, || {
argument_end(&self.masked, args_at, self.mode)
})
{
end = close + 1;
true
} else {
if !escaped && name.is_some() {
self.error(args_at, args_at + 1, "unclosed directive arguments");
}
false
}
} else {
false
};
let match_end = if has_args { end } else { args_at };
let start = if self.mode == Mode::Template && *offset < candidate {
find_ascii(
&self.masked[..match_end],
*offset,
&self.masked[candidate..match_end],
false,
)
.unwrap_or(candidate)
} else {
candidate
};
*offset = start + (match_end - candidate);
let shift = candidate - start;
if escaped {
let head = self.span(start + 1, name_end - shift);
let (prefix_end, arguments) = match (self.mode, has_args) {
(Mode::Template, true) => (args_at, None),
(Mode::Lossless, true) => (end, Some(self.span(args_at, end))),
(_, false) => (end, None),
};
self.add(
start,
prefix_end - shift,
TokenKind::Escaped { head, arguments },
false,
);
return (
if start == candidate {
prefix_end
} else {
name_end
},
end,
);
}
if let Some(name) = name {
let arguments = has_args.then(|| self.span(args_at + 1 - shift, end - 1 - shift));
let whole_tag = self.table.whole_tag(&name, has_args);
self.add(
start,
end - shift,
TokenKind::Directive(name, arguments),
whole_tag,
);
if start == candidate {
return (end, end);
}
}
(name_end, end)
}
fn finish(mut self) -> Lexed {
let mut cursor = 0;
let mut tokens = Vec::new();
for (at, token) in self.tokens {
if cursor < at {
tokens.push(text_token(self.file, cursor, at));
}
cursor = token.span.end as usize;
tokens.push(token);
}
if cursor < self.source.len() {
tokens.push(text_token(self.file, cursor, self.source.len()));
}
let mut following_newline = false;
for token in tokens.iter_mut().rev() {
if token.kind == TokenKind::Comment {
continue;
}
token.consumes_newline &= following_newline;
following_newline = token.kind == TokenKind::Text
&& newline_len(&self.source.as_bytes()[token.span.start as usize..]) != 0;
}
self.errors
.sort_by_key(|error| error.span.map(|span| span.start));
Lexed {
tokens,
errors: self.errors,
}
}
}
fn text_token(file: FileId, start: usize, end: usize) -> Token {
Token {
span: Span::new(file, start as u32, end as u32),
consumes_newline: false,
kind: TokenKind::Text,
}
}
pub(crate) fn newline_len(source: &[u8]) -> usize {
if source.starts_with(b"\r\n") {
2
} else {
usize::from(matches!(source.first(), Some(b'\r' | b'\n')))
}
}
pub(crate) fn word(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_'
}
fn take_while(source: &[u8], mut at: usize, test: impl Fn(u8) -> bool) -> usize {
while source.get(at).is_some_and(|byte| test(*byte)) {
at += 1;
}
at
}
fn skip_horizontal(source: &[u8], at: usize) -> usize {
take_while(source, at, |byte| matches!(byte, b' ' | b'\t'))
}
fn find_ascii(source: &[u8], at: usize, needle: &[u8], insensitive: bool) -> Option<usize> {
source
.get(at..)?
.windows(needle.len())
.position(|window| {
if insensitive {
window.eq_ignore_ascii_case(needle)
} else {
window == needle
}
})
.map(|offset| at + offset)
}
pub(crate) fn echo_delimiters(source: &[u8]) -> Option<(EchoKind, usize, &'static [u8])> {
if source.starts_with(b"{{{") {
Some((EchoKind::Legacy, 3, b"}}}"))
} else if source.starts_with(b"{{--") {
None
} else if source.starts_with(b"{{") {
Some((EchoKind::Escaped, 2, b"}}"))
} else if source.starts_with(b"{!!") {
Some((EchoKind::Raw, 3, b"!!}"))
} else {
None
}
}
pub(crate) fn echo_end(source: &[u8], at: usize, close: &[u8], opaque: bool) -> Option<usize> {
if opaque {
find_ascii(source, at, close, false)
} else {
scan_expression(source, at, close, false)
}
}
pub(crate) fn argument_end(source: &[u8], at: usize, mode: Mode) -> Option<usize> {
scan_expression(source, at + 1, b")", mode == Mode::Lossless)
}
fn scan_expression(source: &[u8], mut at: usize, close: &[u8], php: bool) -> Option<usize> {
let mut delimiters = Vec::new();
while let Some(&next) = source.get(at) {
if delimiters.is_empty() && source[at..].starts_with(close) {
return Some(at);
}
if matches!(next, b'\'' | b'"') || (php && next == b'`') {
at = quoted_end(source, at, true)? + 1;
continue;
}
if let Some(end) = comment_end(source, at, php) {
at = end;
continue;
}
match next {
b'(' => delimiters.push(b')'),
b'[' if !php => delimiters.push(b']'),
b'{' if !php => delimiters.push(b'}'),
_ if delimiters.last() == Some(&next) => {
delimiters.pop();
}
_ => {}
}
at += 1;
}
None
}
pub(crate) fn quoted_end(source: &[u8], at: usize, escapes: bool) -> Option<usize> {
let quote = source[at];
let mut cursor = at + 1;
while let Some(&next) = source.get(cursor) {
if next == quote {
return Some(cursor);
}
cursor += if escapes && next == b'\\' { 2 } else { 1 };
}
None
}
pub(crate) fn comment_end(source: &[u8], at: usize, php: bool) -> Option<usize> {
let rest = &source[at..];
if rest.starts_with(b"//") || (php && rest.starts_with(b"#")) {
Some(take_while(source, at + 1, |byte| {
!matches!(byte, b'\r' | b'\n')
}))
} else if rest.starts_with(b"/*") {
Some(find_ascii(source, at + 2, b"*/", false).map_or(source.len(), |close| close + 2))
} else {
None
}
}
fn closing_code(source: &[u8], mut at: usize, close: &[u8]) -> Option<usize> {
while let Some(&next) = source.get(at) {
if source
.get(at..at + close.len())
.is_some_and(|part| part.eq_ignore_ascii_case(close))
&& !source.get(at + close.len()).is_some_and(|b| word(*b))
{
return Some(at);
}
at = match next {
b'\'' | b'"' => quoted_end(source, at, true)? + 1,
_ => comment_end(source, at, false).unwrap_or(at + 1),
};
}
None
}
fn tag_end(source: &[u8], mut cursor: usize, mode: Mode) -> Option<usize> {
while let Some(&next) = source.get(cursor) {
if let Some((_, open, close)) = echo_delimiters(&source[cursor..]) {
cursor = echo_end(source, cursor + open, close, mode == Mode::Lossless)? + close.len();
continue;
}
if next == b'@' {
let name_at = cursor + 1;
let name_end = take_while(source, name_at, word);
let name = &source[name_at..name_end];
if name.eq_ignore_ascii_case(b"class") || name.eq_ignore_ascii_case(b"style") {
let args_at = skip_horizontal(source, name_end);
if source.get(args_at) == Some(&b'(') {
cursor = argument_end(source, args_at, mode)? + 1;
continue;
}
}
}
match next {
b'>' => return Some(cursor),
b'<' => return None,
b'\'' | b'"' => cursor = tag_quote_end(source, cursor, mode)?,
b'(' => cursor = argument_end(source, cursor, mode)?,
_ => {}
}
cursor += 1;
}
None
}
pub(crate) fn tag_quote_end(source: &[u8], at: usize, mode: Mode) -> Option<usize> {
let quote = source[at];
let mut cursor = at + 1;
while let Some(&next) = source.get(cursor) {
if next == quote {
return Some(cursor);
}
if let Some((_, open, close)) = echo_delimiters(&source[cursor..]) {
cursor = echo_end(source, cursor + open, close, mode == Mode::Lossless)? + close.len();
} else {
cursor += 1;
}
}
None
}
fn php_end(source: &[u8], mut at: usize) -> Option<usize> {
while let Some(&next) = source.get(at) {
if source[at..].starts_with(b"?>") {
return Some(at);
}
if matches!(next, b'\'' | b'"' | b'`') {
at = quoted_end(source, at, true)? + 1;
} else if source[at..].starts_with(b"/*") {
at = comment_end(source, at, true)?;
} else {
at += 1;
}
}
None
}