use crate::{
ast::*,
error::{Error, ErrorKind, Result},
lexer::{self, DirectiveTable, Mode, Tag, Token, TokenKind},
span::{FileId, Span},
syntax,
};
use std::collections::HashSet;
#[derive(Debug)]
pub struct Parsed {
pub template: Template,
pub errors: Vec<Error>,
}
pub fn parse(file: FileId, source: &str, directives: &DirectiveTable) -> Parsed {
let lexed = lexer::lex(file, source, directives, Mode::Template);
parse_tokens(file, source, &lexed.tokens, lexed.errors)
}
pub fn parse_tokens(file: FileId, source: &str, tokens: &[Token], errors: Vec<Error>) -> Parsed {
let eof = u32::try_from(source.len()).unwrap_or(u32::MAX);
let span = Span::new(file, 0, eof);
let lex_error_offsets = errors
.iter()
.filter(|error| error.kind == ErrorKind::Lex)
.filter_map(|error| error.span)
.map(|span| (span.file, span.start))
.collect();
let mut parser = Parser {
source,
tokens,
at: 0,
stops: Vec::new(),
errors,
lex_error_offsets,
eof: Span::new(file, eof, eof),
};
let nodes = parser.nodes(Vec::new());
parser
.errors
.sort_by_key(|error| error.span.map(|span| span.start));
Parsed {
template: Template { span, nodes },
errors: parser.errors,
}
}
#[derive(Clone)]
enum Stop {
Directive(DirectiveName),
EmptyBranch,
Tag(String),
}
impl From<DirectiveName> for Stop {
fn from(name: DirectiveName) -> Self {
Self::Directive(name)
}
}
impl Stop {
fn matches(&self, token: &TokenKind) -> bool {
match (self, token) {
(Self::EmptyBranch, TokenKind::Directive(D::Empty, None)) => true,
(Self::Directive(expected), TokenKind::Directive(actual, _)) => expected == actual,
(Self::Tag(expected), TokenKind::Tag(tag)) => {
tag.closing
&& (tag.name == *expected
|| (tag.name == "slot" && expected.starts_with("slot:")))
}
_ => false,
}
}
fn label(&self) -> String {
match self {
Self::Directive(name) => format!("@{}", name.spelling()),
Self::EmptyBranch => "@empty".into(),
Self::Tag(name) => format!("</x-{name}>"),
}
}
}
use DirectiveName as D;
struct Parser<'a> {
source: &'a str,
tokens: &'a [Token],
at: usize,
stops: Vec<Vec<Stop>>,
errors: Vec<Error>,
lex_error_offsets: HashSet<(FileId, u32)>,
eof: Span,
}
const MAX_TEMPLATE_DEPTH: usize = 96;
impl Parser<'_> {
fn current(&self) -> Option<&Token> {
self.tokens.get(self.at)
}
fn previous(&self) -> Span {
self.at
.checked_sub(1)
.and_then(|at| self.tokens.get(at))
.map_or(self.eof, |token| token.span)
}
fn advance(&mut self) -> Option<Token> {
let token = self.current()?.clone();
self.at += 1;
Some(token)
}
fn text(&self, span: Span) -> &str {
span.slice(self.source).unwrap_or_default()
}
fn error(&mut self, span: Span, message: impl Into<String>) {
self.errors
.push(Error::new(ErrorKind::Parse, message, span));
}
fn record<T>(&mut self, value: Result<T>) -> Option<T> {
match value {
Ok(value) => Some(value),
Err(error) => {
self.errors.push(error);
None
}
}
}
fn nodes(&mut self, stops: Vec<Stop>) -> Vec<Node> {
let mut nodes = Vec::new();
self.stops.push(stops);
while let Some(token) = self.current() {
if self.at_stop(&token.kind) {
break;
}
let Some(token) = self.advance() else { break };
if self.stops.len() >= MAX_TEMPLATE_DEPTH && opens_block(&token.kind) {
self.error(token.span, "template nesting limit exceeded");
continue;
}
let pad_slot =
matches!(&token.kind, TokenKind::Tag(tag) if !tag.closing && tag.is_slot());
if pad_slot {
nodes.push(space(token.span.file, token.span.start));
}
if let Some(node) = self.node(token) {
let trailing = matches!(
&node.kind,
NodeKind::Slot(Slot {
self_closing: true,
..
})
)
.then(|| space(node.span.file, node.span.end));
nodes.push(node);
nodes.extend(trailing);
}
}
self.stops.pop();
nodes
}
fn at_stop(&self, kind: &TokenKind) -> bool {
self.stops
.iter()
.rev()
.flatten()
.any(|stop| stop.matches(kind))
}
fn matches(&self, stop: &Stop) -> bool {
self.current()
.is_some_and(|token| stop.matches(&token.kind))
}
fn end(&mut self, stops: &[Stop], opening: Span) -> Option<Token> {
if stops.iter().any(|stop| self.matches(stop)) {
return self.advance();
}
let expected = stops
.iter()
.map(Stop::label)
.collect::<Vec<_>>()
.join(" or ");
let span = self.current().map_or(self.eof, |token| token.span);
self.errors.push(
Error::new(ErrorKind::Parse, format!("expected {expected}"), span)
.with_help(format!("unclosed block starts at byte {}", opening.start)),
);
None
}
fn node(&mut self, token: Token) -> Option<Node> {
let mut span = token.span;
let after_token = self.at;
let kind = match token.kind {
TokenKind::Text => {
let previous = self.tokens[..self.at - 1]
.iter()
.rev()
.find(|token| !matches!(token.kind, TokenKind::Comment));
if previous.is_some_and(|token| token.consumes_newline) {
span.start += lexer::newline_len(self.text(span).as_bytes()) as u32;
}
if span.start == span.end {
return None;
}
NodeKind::Text(self.text(span).to_owned())
}
TokenKind::Comment => NodeKind::Comment,
TokenKind::Escaped { head, arguments } => {
let mut text = self.text(head).to_owned();
if let Some(arguments) = arguments {
text.push_str(self.text(arguments));
}
NodeKind::Text(text)
}
TokenKind::Verbatim(body) => NodeKind::Text(self.text(body).to_owned()),
TokenKind::Code(body) => {
let (statements, errors) = syntax::parse_code(self.source, body);
self.errors.extend(errors);
NodeKind::Code(statements)
}
TokenKind::Php(_) | TokenKind::RawPhp(_) => {
self.php_error(span);
return None;
}
TokenKind::Echo(kind, body) => NodeKind::Echo(
kind,
self.record(syntax::parse_echo_expression(self.source, body))?,
),
TokenKind::Directive(name, args) => self.directive(span, name, args)?,
TokenKind::Tag(tag) if !tag.closing => self.tag(span, tag),
TokenKind::Tag(tag) => {
self.error(span, format!("unexpected closing tag </x-{}>", tag.name));
return None;
}
};
if self.at != after_token {
span = span.cover(self.previous());
}
Some(Node { span, kind })
}
fn php_error(&mut self, span: Span) {
self.errors.push(
Error::new(ErrorKind::Parse, "PHP is not supported in Rust Blade", span)
.with_help("use @code for Rust statements or migrate the PHP Blade source"),
);
}
fn arguments(&mut self, args: Option<Span>) -> Option<Vec<Expr>> {
args.map_or(Some(Vec::new()), |span| {
self.record(syntax::parse_arguments(self.source, span))
})
}
fn required(&mut self, args: Option<Span>, opening: Span) -> Option<Span> {
if args.is_none() {
let at = Span::new(opening.file, opening.end, opening.end);
let mut end = opening.end;
while self
.source
.as_bytes()
.get(end as usize)
.is_some_and(|byte| matches!(byte, b' ' | b'\t'))
{
end += 1;
}
let lex_error = self.source.as_bytes().get(end as usize) == Some(&b'(')
&& self.lex_error_offsets.contains(&(at.file, end));
if !lex_error {
self.error(at, "expected directive arguments");
}
}
args
}
fn directive(&mut self, span: Span, name: D, raw: Option<Span>) -> Option<NodeKind> {
if let Some((test, branch, end, bounds)) = condition(&name, raw.is_some()) {
return Some(self.conditional(span, raw, test, branch, end, bounds));
}
if let Some((kind, end, bounds)) = block(&name, raw.map(|span| self.text(span))) {
return Some(self.block(span, raw, kind, end, bounds));
}
if let Some((kind, bounds)) = inline(&name) {
let args = if bounds == (0, 0) {
Vec::new()
} else {
self.operands(span, raw, bounds)
};
return Some(NodeKind::Inline {
kind,
args,
raw_args: raw,
});
}
match name {
D::Switch => self.switch(span, raw),
D::Foreach | D::Forelse | D::For => self.iteration(span, raw, name),
D::While => {
let test = self.expression(span, raw);
let body = self.body(span, D::Endwhile);
Some(NodeKind::While { test: test?, body })
}
D::Let | D::Code => {
let args = self.required(raw, span)?;
let parse = if name == D::Let {
syntax::parse_binding
} else {
syntax::parse_statement
};
Some(NodeKind::Code(vec![self.record(parse(self.source, args))?]))
}
D::Props | D::Aware => {
let args = self.required(raw, span)?;
let fields = self.record(syntax::parse_fields(self.source, args))?;
Some(if name == D::Props {
NodeKind::Props(fields)
} else {
NodeKind::Aware(fields)
})
}
D::Inject => {
let args = self.required(raw, span)?;
Some(NodeKind::Inject(
self.record(syntax::parse_injection(self.source, args))?,
))
}
D::Use => {
let args = self.required(raw, span)?;
Some(NodeKind::Use(
self.record(syntax::parse_import(self.source, args))?,
))
}
D::Section => self.section(span, raw),
D::PushIf => Some(self.push_if(span, raw)),
D::Php => {
self.php_error(span);
None
}
D::Verbatim => {
self.error(span, "unclosed @verbatim block");
None
}
_ => {
self.error(span, format!("unexpected directive @{}", name.spelling()));
None
}
}
}
fn operands(&mut self, opening: Span, raw: Option<Span>, bounds: Bounds) -> Vec<Expr> {
let (minimum, maximum) = bounds;
if maximum == 0 || (minimum > 0 && self.required(raw, opening).is_none()) {
return Vec::new();
}
let Some(args) = self.arguments(raw) else {
return Vec::new();
};
if !(minimum..=maximum).contains(&args.len()) {
let count = if minimum == maximum {
minimum.to_string()
} else if maximum == usize::MAX {
format!("at least {minimum}")
} else {
format!("{minimum} to {maximum}")
};
self.error(
raw.unwrap_or(opening),
format!("expected {count} directive arguments"),
);
}
args
}
fn expression(&mut self, opening: Span, raw: Option<Span>) -> Option<Expr> {
let raw = self.required(raw, opening)?;
self.record(syntax::parse_expression(self.source, raw))
}
fn body(&mut self, opening: Span, end: D) -> Vec<Node> {
let stops = vec![end.into()];
let body = self.nodes(stops.clone());
self.end(&stops, opening);
body
}
fn conditional(
&mut self,
opening: Span,
raw: Option<Span>,
kind: ConditionKind,
branch: Option<D>,
end: D,
bounds: Bounds,
) -> NodeKind {
let close = Stop::from(end);
let mut stops = vec![close.clone(), D::Else.into(), D::Elseif.into()];
if let Some(branch) = &branch
&& *branch != D::Elseif
{
stops.push(branch.clone().into());
}
let mut test = Some(Condition {
args: self.operands(opening, raw, bounds),
kind: kind.clone(),
});
let mut span = opening;
let mut branches = Vec::new();
loop {
let body = self.nodes(stops.clone());
let final_else = test.is_none();
branches.push(Branch { test, body, span });
if final_else {
self.end(&[close], opening);
break;
}
let Some(marker) = self.end(&stops, opening) else {
break;
};
let TokenKind::Directive(name, raw) = marker.kind else {
break;
};
span = marker.span;
test = if name == D::Else {
stops = vec![close.clone()];
None
} else if name == D::Elseif {
Some(Condition {
kind: ConditionKind::If,
args: self.operands(span, raw, (1, 1)),
})
} else if branch.as_ref() == Some(&name) {
let branch_kind = match &kind {
ConditionKind::Custom { name, .. } => ConditionKind::Custom {
name: name.clone(),
negated: false,
},
_ => kind.clone(),
};
Some(Condition {
kind: branch_kind,
args: self.operands(span, raw, bounds),
})
} else {
break;
};
}
NodeKind::Conditional(branches)
}
fn iteration(&mut self, span: Span, args: Option<Span>, name: D) -> Option<NodeKind> {
let iteration = self
.required(args, span)
.and_then(|raw| self.record(syntax::parse_iteration(self.source, raw)));
let (kind, end) = match name {
D::For => (LoopKind::For, D::Endfor),
D::Foreach => (LoopKind::Foreach, D::Endforeach),
_ => (LoopKind::Forelse, D::Endforelse),
};
let close = Stop::from(end);
let mut stops = vec![close.clone()];
if name == D::Forelse {
stops.push(Stop::EmptyBranch);
}
let body = self.nodes(stops.clone());
let empty = match self.end(&stops, span) {
Some(Token {
kind: TokenKind::Directive(D::Empty, None),
..
}) => {
let empty = self.nodes(vec![close.clone()]);
self.end(&[close], span);
Some(empty)
}
_ => None,
};
let (pattern, iterable) = iteration?;
Some(NodeKind::Loop {
kind,
pattern,
iterable,
body,
empty,
})
}
fn switch(&mut self, span: Span, args: Option<Span>) -> Option<NodeKind> {
let value = self.expression(span, args);
let stops = vec![D::Case.into(), D::Default.into(), D::Endswitch.into()];
while let Some(token) = self.current() {
if self.at_stop(&token.kind)
|| stops.iter().any(|stop: &Stop| stop.matches(&token.kind))
{
break;
}
if token.kind == TokenKind::Text
&& let Some(space) = switch_prefix_whitespace(self.text(token.span))
{
let start = token.span.start + space.start as u32;
let end = token.span.start + space.end as u32;
self.error(
Span::new(token.span.file, start, end),
"non-ASCII whitespace before the first switch arm",
);
}
self.advance();
}
let mut arms = Vec::new();
let mut default_seen = false;
while let Some(marker) = self.end(&stops, span) {
let test = match marker.kind {
TokenKind::Directive(D::Case, raw) => self.expression(marker.span, raw),
TokenKind::Directive(D::Default, _) => {
if default_seen {
self.error(marker.span, "duplicate @default in switch");
}
default_seen = true;
None
}
_ => break,
};
let body = self.nodes(stops.clone());
arms.push(SwitchArm {
test,
body,
span: marker.span,
});
}
Some(NodeKind::Switch {
value: value?,
arms,
})
}
fn section(&mut self, span: Span, raw: Option<Span>) -> Option<NodeKind> {
let mut args = self.operands(span, raw, (1, 2)).into_iter();
let name = args.next();
let content = args.next();
let mut section_end = SectionEnd::Stop;
let body = if content.is_none() {
let stops: Vec<_> = [D::Endsection, D::Stop, D::Show, D::Append, D::Overwrite]
.into_iter()
.map(Stop::from)
.collect();
let body = self.nodes(stops.clone());
if let Some(end) = self.end(&stops, span) {
section_end = match end.kind {
TokenKind::Directive(D::Show, _) => SectionEnd::Show,
TokenKind::Directive(D::Append, _) => SectionEnd::Append,
TokenKind::Directive(D::Overwrite, _) => SectionEnd::Overwrite,
_ => SectionEnd::Stop,
};
}
body
} else {
Vec::new()
};
Some(NodeKind::Section {
name: name?,
content,
body,
end: section_end,
})
}
fn block(
&mut self,
span: Span,
raw: Option<Span>,
kind: BlockKind,
end: D,
bounds: Bounds,
) -> NodeKind {
let args = self.operands(span, raw, bounds);
let inline = match kind {
BlockKind::Push | BlockKind::Prepend => args.len() == 2,
BlockKind::Slot => {
args.len() == 2
|| args.get(1).is_some_and(|content| {
!matches!(content.kind, ExprKind::Literal(Literal::Null))
})
}
_ => false,
};
let body = if inline {
Vec::new()
} else if kind == BlockKind::ComponentFirst {
let stops = vec![D::Endcomponent.into(), D::Endcomponentfirst.into()];
let body = self.nodes(stops.clone());
self.end(&stops, span);
body
} else {
self.body(span, end)
};
NodeKind::Block { kind, args, body }
}
fn push_if(&mut self, opening: Span, raw: Option<Span>) -> NodeKind {
let mut stops = vec![
D::ElsePushIf.into(),
D::ElsePush.into(),
D::Endpushif.into(),
];
let mut span = opening;
let mut args = self.operands(span, raw, (2, 2)).into_iter();
let mut branches = Vec::new();
let mut unconditional = false;
loop {
let test = if unconditional { None } else { args.next() };
let stack = args.next();
let body = self.nodes(stops.clone());
if let Some(stack) = stack {
branches.push(PushBranch {
condition: test,
stack,
body,
span,
});
}
let Some(marker) = self.end(&stops, opening) else {
break;
};
let TokenKind::Directive(name, raw) = marker.kind else {
break;
};
if name == D::Endpushif {
break;
}
span = marker.span;
unconditional = name == D::ElsePush;
if unconditional {
stops = vec![D::Endpushif.into()];
}
let count = if unconditional { 1 } else { 2 };
args = self.operands(span, raw, (count, count)).into_iter();
}
NodeKind::PushIf(branches)
}
fn tag(&mut self, span: Span, tag: Tag) -> NodeKind {
let (attributes, errors) = attributes(self.source, tag.attributes);
self.errors.extend(errors);
let slot = tag.is_slot();
let mut body = Vec::new();
if !tag.self_closing {
let stops = vec![Stop::Tag(tag.name.clone())];
if slot {
body.push(space(span.file, span.end));
}
body.extend(self.nodes(stops.clone()));
if let Some(close) = self.end(&stops, span) {
if !self
.text(match close.kind {
TokenKind::Tag(ref tag) => tag.attributes,
_ => close.span,
})
.trim()
.is_empty()
{
self.error(close.span, "closing component tags cannot have attributes");
}
if slot {
body.push(space(span.file, close.span.start));
}
}
}
if slot {
let name = tag.name.strip_prefix("slot:").map(str::to_owned);
NodeKind::Slot(Slot {
name,
attributes,
body,
self_closing: tag.self_closing,
})
} else {
NodeKind::Component(Component {
name: tag.name,
attributes,
body,
self_closing: tag.self_closing,
})
}
}
}
fn switch_prefix_whitespace(text: &str) -> Option<std::ops::Range<usize>> {
let source = text.as_bytes();
let mut at = 0;
while let Some(&next) = source.get(at) {
if let Some(end) = lexer::comment_end(source, at, true) {
at = end;
} else if matches!(next, b'\'' | b'"' | b'`') {
at = lexer::quoted_end(source, at, true).map_or(at + 1, |end| end + 1);
} else if next.is_ascii() {
at += 1;
} else {
let ch = text[at..].chars().next()?;
let end = at + ch.len_utf8();
if ch.is_whitespace() {
return Some(at..end);
}
at = end;
}
}
None
}
fn space(file: FileId, at: u32) -> Node {
Node {
kind: NodeKind::Text(" ".into()),
span: Span::new(file, at, at),
}
}
type Bounds = (usize, usize);
fn condition(name: &D, has_args: bool) -> Option<(ConditionKind, Option<D>, D, Bounds)> {
use ConditionKind as C;
let (kind, branch, end, bounds) = match name {
D::If => (C::If, None, D::Endif, (1, 1)),
D::Unless => (C::Unless, None, D::Endunless, (1, 1)),
D::Isset => (C::Isset, None, D::Endisset, (1, usize::MAX)),
D::Empty if has_args => (C::Empty, None, D::Endempty, (1, 1)),
D::Auth => (C::Auth, Some(D::Elseauth), D::Endauth, (0, 1)),
D::Guest => (C::Guest, Some(D::Elseguest), D::Endguest, (0, 1)),
D::Can => (C::Can, Some(D::Elsecan), D::Endcan, (1, 2)),
D::Cannot => (C::Cannot, Some(D::Elsecannot), D::Endcannot, (1, 2)),
D::CanAny => (C::CanAny, Some(D::Elsecanany), D::Endcanany, (1, 2)),
D::Env => (C::Env, None, D::Endenv, (1, usize::MAX)),
D::Production => (C::Production, None, D::Endproduction, (0, 0)),
D::Session => (C::Session, None, D::Endsession, (1, 1)),
D::Context => (C::Context, None, D::Endcontext, (1, 1)),
D::Error => (C::Error, None, D::Enderror, (1, 2)),
D::HasSection => (C::HasSection, None, D::Endif, (1, 1)),
D::SectionMissing => (C::SectionMissing, None, D::Endif, (1, 1)),
D::HasStack => (C::HasStack, None, D::Endif, (1, 1)),
D::Condition(custom) | D::UnlessCondition(custom) => (
C::Custom {
name: custom.clone(),
negated: matches!(name, D::UnlessCondition(_)),
},
Some(D::ElseCondition(custom.clone())),
D::EndCondition(custom.clone()),
(0, usize::MAX),
),
_ => return None,
};
Some((kind, branch, end, bounds))
}
fn block(name: &D, raw: Option<&str>) -> Option<(BlockKind, D, Bounds)> {
use BlockKind as B;
let spec = match name {
D::Once => (B::Once, D::Endonce, (0, 1)),
D::Push => (B::Push, D::Endpush, (1, 2)),
D::PushOnce => (B::PushOnce, D::Endpushonce, (1, 2)),
D::Prepend => (B::Prepend, D::Endprepend, (1, 2)),
D::PrependOnce => (B::PrependOnce, D::Endprependonce, (1, 2)),
D::Fragment => (B::Fragment, D::Endfragment, (1, 1)),
D::Component => (B::Component, D::Endcomponent, (1, 2)),
D::ComponentFirst => (B::ComponentFirst, D::Endcomponentfirst, (1, 2)),
D::Slot => (B::Slot, D::Endslot, (1, 3)),
D::Lang if raw.is_none_or(|raw| raw.trim_start().starts_with(['{', '['])) => {
(B::Lang, D::Endlang, (0, 1))
}
_ => return None,
};
Some(spec)
}
fn inline(name: &D) -> Option<(InlineKind, Bounds)> {
use InlineKind as I;
Some(match name {
D::Extends => (I::Extends, (1, 2)),
D::ExtendsFirst => (I::ExtendsFirst, (1, 2)),
D::Yield => (I::Yield, (1, 2)),
D::Parent => (I::Parent, (0, 0)),
D::Include => (I::Include, (1, 2)),
D::IncludeIf => (I::IncludeIf, (1, 2)),
D::IncludeWhen => (I::IncludeWhen, (2, 3)),
D::IncludeUnless => (I::IncludeUnless, (2, 3)),
D::IncludeFirst => (I::IncludeFirst, (1, 2)),
D::IncludeIsolated => (I::IncludeIsolated, (1, 2)),
D::Each => (I::Each, (3, 4)),
D::Break => (I::Break, (0, 1)),
D::Continue => (I::Continue, (0, 1)),
D::Unset => (I::Unset, (1, usize::MAX)),
D::Class => (I::Class, (1, 1)),
D::Style => (I::Style, (1, 1)),
D::Checked => (I::Checked, (1, 1)),
D::Selected => (I::Selected, (1, 1)),
D::Disabled => (I::Disabled, (1, 1)),
D::Readonly => (I::Readonly, (1, 1)),
D::Required => (I::Required, (1, 1)),
D::Bool => (I::Bool, (1, 1)),
D::Csrf => (I::Csrf, (0, 0)),
D::Method => (I::Method, (1, 1)),
D::Json => (I::Json, (1, 3)),
D::Js => (I::Js, (1, 3)),
D::Lang => (I::Lang, (1, 3)),
D::Choice => (I::Choice, (2, 4)),
D::Vite => (I::Vite, (1, 2)),
D::ViteReactRefresh => (I::ViteReactRefresh, (0, 0)),
D::Fonts => (I::Fonts, (0, 1)),
D::Dump => (I::Dump, (0, usize::MAX)),
D::Dd => (I::Dd, (0, usize::MAX)),
D::Stack => (I::Stack, (1, 2)),
D::Custom(name) => (I::Custom(name.clone()), (0, usize::MAX)),
_ => return None,
})
}
fn opens_block(token: &TokenKind) -> bool {
match token {
TokenKind::Tag(tag) => !tag.closing && !tag.self_closing,
TokenKind::Directive(name, args) => {
condition(name, args.is_some()).is_some()
|| block(name, None).is_some()
|| matches!(
name,
D::Switch
| D::Foreach
| D::Forelse
| D::For
| D::While
| D::Section
| D::PushIf
)
}
_ => false,
}
}
fn attributes(source: &str, span: Span) -> (Vec<ComponentAttr>, Vec<Error>) {
let Some(text) = span.slice(source) else {
return (
Vec::new(),
vec![Error::new(
ErrorKind::Parse,
"invalid attribute range",
span,
)],
);
};
let mut parser = Attributes {
source,
span,
text,
at: 0,
errors: Vec::new(),
};
let mut attrs = Vec::new();
parser.skip_spaces();
while parser.at < text.len() {
let start = parser.at;
match parser.attribute() {
Ok(Some(kind)) => attrs.push(ComponentAttr {
span: parser.span(start, parser.at),
kind,
}),
Ok(None) => {}
Err(error) => parser.errors.push(error),
}
if parser.at == start {
parser.at += text[start..].chars().next().map_or(1, char::len_utf8);
}
parser.skip_spaces();
}
(attrs, parser.errors)
}
struct Attributes<'a> {
source: &'a str,
span: Span,
text: &'a str,
at: usize,
errors: Vec<Error>,
}
impl Attributes<'_> {
fn span(&self, start: usize, end: usize) -> Span {
Span::new(
self.span.file,
self.span.start + start as u32,
self.span.start + end as u32,
)
}
fn skip_spaces(&mut self) {
while self
.text
.as_bytes()
.get(self.at)
.is_some_and(u8::is_ascii_whitespace)
{
self.at += 1;
}
}
fn attribute(&mut self) -> Result<Option<ComponentAttrKind>> {
let start = self.at;
let rest = &self.text[start..];
if rest.starts_with("{{--")
&& let Some(close) = rest.find("--}}")
{
self.at += close + 4;
return Ok(None);
}
if let Some((_, open, close)) = lexer::echo_delimiters(rest.as_bytes()) {
let body = start + open;
let end =
lexer::echo_end(self.text.as_bytes(), body, close, false).ok_or_else(|| {
Error::new(
ErrorKind::Parse,
"unclosed attribute echo",
self.span(start, body),
)
})?;
self.at = end + close.len();
return Ok(Some(ComponentAttrKind::Spread(syntax::parse_expression(
self.source,
self.span(body, end),
)?)));
}
let name_end = start
+ rest
.bytes()
.take_while(|byte| {
!byte.is_ascii_whitespace()
&& !matches!(byte, b'=' | b'\'' | b'"' | b'<' | b'>' | b'(')
})
.count();
let name = &self.text[start..name_end];
if name.is_empty() {
let end = start + rest.chars().next().map_or(0, char::len_utf8);
return Err(Error::new(
ErrorKind::Parse,
"expected a component attribute",
self.span(start, end),
));
}
self.at = name_end;
self.skip_spaces();
if let Some(class) = match name.to_ascii_lowercase().as_str() {
"@class" => Some(true),
"@style" => Some(false),
_ => None,
} {
let opening = self.at;
let end = (self.text.as_bytes().get(opening) == Some(&b'('))
.then(|| lexer::argument_end(self.text.as_bytes(), opening, Mode::Template))
.flatten()
.ok_or_else(|| {
Error::new(
ErrorKind::Parse,
"expected attribute directive arguments",
self.span(start, name_end),
)
})?;
self.at = end + 1;
let expr = syntax::parse_expression(self.source, self.span(opening + 1, end))?;
return Ok(Some(if class {
ComponentAttrKind::Class(expr)
} else {
ComponentAttrKind::Style(expr)
}));
}
let value = if self.text.as_bytes().get(self.at) == Some(&b'=') {
self.at += 1;
self.skip_spaces();
Some(self.value()?)
} else {
self.at = name_end;
None
};
let kind = if let Some(shorthand) = name.strip_prefix(":$") {
let mut chars = shorthand.chars();
if value.is_some()
|| !chars
.next()
.is_some_and(|ch| ch.is_alphabetic() || ch == '_')
|| !chars.all(|ch| ch.is_alphanumeric() || ch == '_')
{
return Err(Error::new(
ErrorKind::Parse,
"invalid shorthand attribute",
self.span(start, self.at),
));
}
ComponentAttrKind::Shorthand(shorthand.to_owned())
} else if name.starts_with("::") {
let parts = value.map(|value| self.parts(value));
ComponentAttrKind::Escaped {
name: name[1..].to_owned(),
parts,
}
} else if let Some(name) = name.strip_prefix(':') {
let value = value.ok_or_else(|| {
Error::new(
ErrorKind::Parse,
"bound attribute requires a value",
self.span(start, name_end),
)
})?;
ComponentAttrKind::Bound {
name: name.to_owned(),
value: syntax::parse_expression(self.source, value)?,
}
} else if let Some(value) = value {
ComponentAttrKind::Literal {
name: name.to_owned(),
parts: self.parts(value),
}
} else {
ComponentAttrKind::Bare(name.to_owned())
};
Ok(Some(kind))
}
fn value(&mut self) -> Result<Span> {
let start = self.at;
let Some(&next) = self.text.as_bytes().get(start) else {
return Err(Error::new(
ErrorKind::Parse,
"expected an attribute value",
self.span(start, start),
));
};
if matches!(next, b'\'' | b'"') {
let end = lexer::tag_quote_end(self.text.as_bytes(), start, Mode::Template)
.ok_or_else(|| {
Error::new(
ErrorKind::Parse,
"unclosed attribute value",
self.span(start, start + 1),
)
})?;
self.at = end + 1;
Ok(self.span(start + 1, end))
} else {
self.at += self.text[start..]
.bytes()
.take_while(|byte| !byte.is_ascii_whitespace())
.count();
Ok(self.span(start, self.at))
}
}
fn parts(&mut self, value: Span) -> Vec<AttributePart> {
let text = value.slice(self.source).unwrap_or_default();
let mut parts = Vec::new();
let mut start = 0;
let mut at = 0;
while at < text.len() {
let escaped = text.as_bytes()[at] == b'@';
let marker = at + usize::from(escaped);
if text.as_bytes()[at..].starts_with(b"{{--")
&& let Some(close) = text[at + 4..].find("--}}")
{
if start < at {
parts.push(AttributePart::Text(text[start..at].to_owned()));
}
at += close + 8;
start = at;
continue;
}
if let Some((kind, open, close)) = lexer::echo_delimiters(&text.as_bytes()[marker..]) {
let body = marker + open;
if let Some(end) = lexer::echo_end(text.as_bytes(), body, close, escaped) {
if start < at {
parts.push(AttributePart::Text(text[start..at].to_owned()));
}
at = end + close.len();
start = at;
if escaped {
parts.push(AttributePart::Text(text[marker..at].to_owned()));
} else {
let expr_span = Span::new(
value.file,
value.start + body as u32,
value.start + end as u32,
);
match syntax::parse_echo_expression(self.source, expr_span) {
Ok(expr) => parts.push(AttributePart::Echo(kind, expr)),
Err(error) => self.errors.push(error),
}
}
continue;
}
let span = Span::new(
value.file,
value.start + marker as u32,
value.start + body as u32,
);
self.errors.push(Error::new(
ErrorKind::Parse,
"unclosed attribute echo",
span,
));
break;
}
at += 1;
}
if start < text.len() {
parts.push(AttributePart::Text(text[start..].to_owned()));
}
parts
}
}