use super::expressions::{narrow, present, string};
use super::signatures::flag_names;
use super::types::{Environment, Place, Ty, shape_fields};
use super::{ComponentDefinition, Frame, Memo, Run};
use crate::ast::*;
use crate::shape::{Direction, Presence, TypeDesc};
use crate::span::Span;
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone)]
struct Prop {
ty: Ty,
required: bool,
spelling: Option<String>,
aliases: Vec<String>,
}
struct Input {
ty: Ty,
span: Span,
literal: Option<String>,
}
#[derive(Default)]
struct Slots {
named: BTreeMap<String, (Span, bool)>,
dynamic: bool,
}
impl Run<'_, '_> {
pub(super) fn template(&mut self, template: &Template, env: &mut Environment) {
self.active.push(template.span);
self.visited.insert(template.span.file.0);
self.nodes(&template.nodes, env);
self.active.pop();
}
fn dependent(&mut self, template: &Template, mut env: Environment, call: Span) {
if self.active.contains(&template.span) {
self.unchecked(
"recursive-template",
call,
"recursive template edge is checked at runtime",
);
return;
}
let scope = env.for_include();
let key = (template.span.file.0, template.span.start, template.span.end);
let cached = self
.memo
.get(&key)
.and_then(|entries| entries.iter().find(|memo| memo.scope == scope));
let result = if let Some(memo) = cached {
memo.frame.clone()
} else {
self.frames.push(Frame::default());
self.template(template, &mut env);
let frame = self.frames.pop().unwrap_or_default();
self.memo.entry(key).or_default().push(Memo {
scope,
frame: frame.clone(),
});
frame
};
for index in &result.diagnostics {
let callers = &mut self.report.diagnostics[*index].callers;
if !callers.contains(&call) {
callers.push(call);
}
}
if let Some(frame) = self.frames.last_mut() {
frame.diagnostics.extend(result.diagnostics);
frame.reads.extend(result.reads);
}
}
fn nodes(&mut self, nodes: &[Node], env: &mut Environment) {
for node in nodes {
let span = node.span;
match &node.kind {
NodeKind::Text(_) => {}
NodeKind::Comment => {
let source = self
.config
.sources
.source(span.file)
.and_then(|src| span.slice(src))
.unwrap_or_default();
for (offset, marker) in source.match_indices("RUST-BLADE-TODO") {
let start = span.start + offset as u32;
let at = Span::new(span.file, start, start + marker.len() as u32);
self.error("migration-todo", at, "unresolved RUST-BLADE-TODO marker");
}
}
NodeKind::Echo(kind, expr) => {
let attribute = self
.config
.sources
.source(span.file)
.and_then(|src| html_attribute(src, span.start as usize));
self.echo(*kind, expr, env);
if *kind != EchoKind::Raw && attribute.as_deref().is_some_and(script_attribute)
{
self.warn(
"script-attribute-echo",
expr.span,
"escaped HTML is not JavaScript encoding; use `js()`",
);
}
}
NodeKind::Code(stmts) => self.statements(stmts, env),
NodeKind::Inline {
kind: InlineKind::Custom(name),
raw_args,
..
} => {
let resolver = self.config.resolver;
if let Some(expansion) = resolver.directive(name, *raw_args) {
self.dependent(expansion, env.for_include(), span);
} else {
self.unchecked(
"custom-directive",
span,
format!("custom directive `{name}` has no static expansion"),
);
}
}
NodeKind::Inline { kind, args, .. } => self.inline(kind, args, span, env),
NodeKind::Conditional(branches) => {
let mut remaining = env.clone();
let mut exits = Vec::new();
for branch in branches {
let mut local = remaining.clone();
if let Some(test) = &branch.test {
self.directive_condition(test, branch.span, &mut local);
remaining.join(&local);
condition_facts(test, false, &mut remaining);
condition_facts(test, true, &mut local);
match test.kind {
ConditionKind::Error => {
local.bind("message".into(), Ty::String, false)
}
ConditionKind::Session | ConditionKind::Context => {
local.bind("value".into(), Ty::Any, false)
}
_ => {}
}
}
self.nodes(&branch.body, &mut local);
exits.push(local);
}
for exit in exits {
env.join(&exit);
}
}
NodeKind::Loop {
pattern,
iterable,
body,
empty,
..
} => {
let ty = self.expr(iterable, env);
let (key, value) = self.iterable(&ty, iterable.span);
let ty = if matches!(pattern.kind, PatternKind::Tuple(_)) {
Ty::Tuple(vec![key, value])
} else {
value
};
let mut local = env.clone();
local.loop_depth += 1;
local.break_scopes += 1;
local.continue_scopes += 1;
local.bind("loop".into(), Ty::Loop(local.loop_depth), false);
self.pattern(pattern, &ty, false, &mut local);
let mut next = local.clone();
self.nodes(body, &mut local);
if next.forget_loop_mutations(env, &local) {
self.nodes(body, &mut next);
}
let mut fallback = env.clone();
if let Some(empty) = empty {
self.nodes(empty, &mut fallback);
}
env.join(&local);
env.join(&fallback);
}
NodeKind::While { test, body } => {
self.condition(test, env);
let mut local = env.clone();
local.break_scopes += 1;
local.continue_scopes += 1;
narrow(test, true, &mut local);
self.nodes(body, &mut local);
let mut next = env.clone();
if next.forget_loop_mutations(env, &local) {
self.condition(test, &mut next);
narrow(test, true, &mut next);
next.break_scopes += 1;
next.continue_scopes += 1;
self.nodes(body, &mut next);
}
env.join(&local);
}
NodeKind::Switch { value, arms } => {
let ty = self.expr(value, env);
let mut previous = env.clone();
for (index, arm) in arms.iter().enumerate() {
let mut local = env.clone();
local.join(&previous);
local.break_scopes += 1;
if let Some(test) = &arm.test {
let actual = self.expr(test, &mut local);
if !self.same(&actual, &ty) {
self.require(&actual, &ty, test.span, "switch-type");
}
}
if index + 1 < arms.len() && !arm.body.iter().any(unconditional_break)
&& arm.body.iter().any(|node| !matches!(&node.kind, NodeKind::Comment) && !matches!(&node.kind, NodeKind::Text(text) if text.trim().is_empty()))
{
self.warn("switch-fallthrough", arm.span, "switch case falls through without an unconditional `@break`");
}
self.nodes(&arm.body, &mut local);
previous = local;
}
env.join(&previous);
}
NodeKind::Block {
kind: kind @ (BlockKind::Component | BlockKind::ComponentFirst),
args,
body,
} => {
self.legacy_component(kind, args, body, span, env);
}
NodeKind::Block { args, body, .. } => {
for arg in args {
self.expr(arg, env);
}
let mut local = env.clone();
self.nodes(body, &mut local);
env.join(&local);
}
NodeKind::Section {
name,
content,
body,
..
} => {
let ty = self.expr(name, env);
self.require(&ty, &Ty::String, name.span, "section-name");
if let Some(content) = content {
self.expr(content, env);
}
let mut local = env.clone();
self.nodes(body, &mut local);
env.join(&local);
}
NodeKind::PushIf(branches) => {
let mut remaining = env.clone();
let mut exits = Vec::new();
for branch in branches {
let mut local = remaining.clone();
if let Some(test) = &branch.condition {
self.condition(test, &mut local);
remaining.join(&local);
narrow(test, false, &mut remaining);
narrow(test, true, &mut local);
}
self.expr(&branch.stack, &mut local);
self.nodes(&branch.body, &mut local);
exits.push(local);
}
for exit in exits {
env.join(&exit);
}
}
NodeKind::Props(decls) | NodeKind::Aware(decls) => {
for decl in decls {
if matches!(node.kind, NodeKind::Props(_))
&& env.contract.contains(&decl.name)
{
continue;
}
let prop = self.declaration(decl, env);
env.bind(decl.name.clone(), prop.ty, false);
}
}
NodeKind::Inject(decl) => {
if let Some(name) = &decl.ty {
if !self.config.methods.keys().any(|(id, _)| id == name) {
self.unchecked(
"injected-service",
span,
format!("no registered signatures for injected service `{name}`"),
);
}
env.bind(decl.name.clone(), Ty::Service(name.clone()), false);
} else {
self.error("inject-type", span, "injected service needs a type");
}
}
NodeKind::Use(_) => {}
NodeKind::Component(component) => self.component(component, span, env),
NodeKind::Slot(slot) => {
self.attributes(&slot.attributes, env);
let mut local = env.clone();
self.nodes(&slot.body, &mut local);
env.join(&local);
}
}
}
}
fn echo(&mut self, kind: EchoKind, expr: &Expr, env: &mut Environment) {
let ty = self.expr(expr, env);
let resolved = self.resolve(&ty);
if kind == EchoKind::Raw {
if !trusted(&resolved) {
self.error(
"untrusted-html",
expr.span,
format!(
"raw echo requires trusted HTML, found {}",
self.type_name(&ty)
),
);
}
} else {
if resolved == Ty::Bool {
self.warn(
"echo-bool",
expr.span,
"echo prints a Bool; use `@bool` when intentional",
);
}
self.require_printable(&ty, expr.span);
}
}
fn directive_condition(&mut self, test: &Condition, span: Span, env: &mut Environment) {
let args = &test.args;
match &test.kind {
ConditionKind::If | ConditionKind::Unless => {
self.arity("condition", args.len(), 1, Some(1), span);
for arg in args {
self.condition(arg, env);
}
}
ConditionKind::Isset => {
self.arity("@isset", args.len(), 1, None, span);
for arg in args {
self.guarded(arg, env);
}
}
ConditionKind::Can | ConditionKind::Cannot | ConditionKind::CanAny => {
let name = match test.kind {
ConditionKind::Can => "@can",
ConditionKind::Cannot => "@cannot",
_ => "@canany",
};
self.arity(name, args.len(), 1, Some(2), span);
for (index, arg) in args.iter().enumerate() {
let actual = self.expr(arg, env);
if index == 0 {
let expected = if test.kind == ConditionKind::CanAny {
Ty::list(Ty::String)
} else {
Ty::String
};
self.require(&actual, &expected, arg.span, "ability-name");
let empty =
|expr: &Expr| string(expr).is_some_and(|name| name.trim().is_empty());
if empty(arg)
|| matches!(&arg.kind, ExprKind::List(list) if list.is_empty() || list.iter().any(empty))
{
self.error("ability-name", arg.span, "ability names must be nonempty");
}
}
}
}
ConditionKind::Custom { name, .. } => {
if let Some(sig) = self.config.conditions.get(name) {
let result = self.check_signature(name, sig, args, span, env);
self.require(&result, &Ty::Bool, span, "condition-type");
} else {
for arg in args {
self.expr(arg, env);
}
self.unchecked(
"custom-condition",
span,
format!("condition `{name}` has no registered signature"),
);
}
}
_ => {
for arg in args {
self.expr(arg, env);
}
}
}
}
fn inline(&mut self, kind: &InlineKind, args: &[Expr], span: Span, env: &mut Environment) {
match kind {
InlineKind::Include
| InlineKind::IncludeIf
| InlineKind::IncludeWhen
| InlineKind::IncludeUnless
| InlineKind::IncludeFirst
| InlineKind::IncludeIsolated
| InlineKind::Each
| InlineKind::Extends
| InlineKind::ExtendsFirst => self.include(kind, args, span, env),
InlineKind::Checked
| InlineKind::Selected
| InlineKind::Disabled
| InlineKind::Readonly
| InlineKind::Required
| InlineKind::Bool => {
self.arity("boolean directive", args.len(), 1, Some(1), span);
for arg in args {
self.condition(arg, env);
}
}
InlineKind::Class | InlineKind::Style => {
for arg in args {
self.class_or_style(arg, env);
}
}
InlineKind::Unset => {
for arg in args {
if let ExprKind::Path(path) = &arg.kind
&& let [name] = path.as_slice()
{
self.name(path, arg.span, env, false);
env.unset(name);
} else {
self.expr(arg, env);
self.error("unset-target", arg.span, "`@unset` requires a binding name");
}
}
}
InlineKind::Break | InlineKind::Continue => {
if (kind == &InlineKind::Break && env.break_scopes == 0)
|| (kind == &InlineKind::Continue && env.continue_scopes == 0)
{
self.error(
"loop-control",
span,
"directive requires an enclosing loop or switch",
);
}
for arg in args {
self.condition(arg, env);
}
}
InlineKind::Dump | InlineKind::Dd => {
for arg in args {
self.expr(arg, env);
}
self.warn(
"debug-directive",
span,
"debug directive remains in the template",
);
}
InlineKind::Json | InlineKind::Js => {
let flags = flag_names();
for (index, arg) in args.iter().enumerate() {
if index == 1
&& let ExprKind::List(list) = &arg.kind
{
for value in list {
if !matches!(&value.kind, ExprKind::Path(path) if path.len() == 1 && flags.contains(path[0].as_str()))
{
self.expr(value, env);
}
}
} else {
self.expr(arg, env);
}
}
}
_ => {
for arg in args {
self.expr(arg, env);
}
}
}
}
fn class_or_style(&mut self, arg: &Expr, env: &mut Environment) {
if let ExprKind::Map(entries) = &arg.kind {
for (key, condition) in entries {
if let MapKey::Computed(key) = key {
self.expr(key, env);
}
self.condition(condition, env);
}
} else {
self.expr(arg, env);
}
}
fn include(&mut self, kind: &InlineKind, args: &[Expr], span: Span, env: &mut Environment) {
use InlineKind::*;
let conditional = matches!(kind, IncludeWhen | IncludeUnless);
if conditional && let Some(test) = args.first() {
self.condition(test, env);
}
let mut caller = env.for_include();
if conditional && let Some(test) = args.first() {
narrow(test, kind == &IncludeWhen, &mut caller);
}
let Some(view) = args.get(usize::from(conditional)) else {
self.error("include-arguments", span, "missing template name");
return;
};
self.expr(view, env);
if kind == &Each {
self.each(view, args, span, env);
return;
}
let data = args.get(1 + usize::from(conditional));
let data = data.map(|arg| {
let ty = self.expr(arg, env);
self.data_fields(&ty, arg.span)
});
if kind == &IncludeIsolated {
caller = Environment::default();
}
if let Some(fields) = data {
for (name, ty) in fields {
caller.bind(name, ty, false);
}
}
let first = matches!(kind, IncludeFirst | ExtendsFirst);
let mut names = Vec::new();
if first && let ExprKind::List(list) = &view.kind {
for candidate in list {
if let Some(name) = string(candidate) {
names.push(name);
} else {
self.unchecked(
"dynamic-include",
candidate.span,
"template candidate is computed at runtime",
);
return;
}
}
} else if let Some(name) = string(view) {
names.push(name);
} else {
self.unchecked(
"dynamic-include",
view.span,
"template name is computed at runtime",
);
return;
}
let resolver = self.config.resolver;
if let Some(template) = names.iter().find_map(|name| resolver.include(name)) {
let caller = self.partial_scope(&template.nodes, caller, span);
self.dependent(template, caller, span);
} else if kind != &IncludeIf {
self.error(
"missing-include",
view.span,
format!("cannot resolve template {}", names.join(", ")),
);
}
}
fn each(&mut self, view: &Expr, args: &[Expr], span: Span, env: &mut Environment) {
self.arity("@each", args.len(), 3, Some(4), span);
let Some(iterable) = args.get(1) else {
return;
};
let ty = self.expr(iterable, env);
let (key, value) = self.iterable(&ty, iterable.span);
let item = args.get(2).and_then(string);
let resolver = self.config.resolver;
if let (Some(name), Some(item)) = (string(view), item) {
if let Some(template) = resolver.include(name) {
let mut scope = self.root();
scope.bind(item.into(), value, false);
scope.bind("key".into(), key, false);
let scope = self.partial_scope(&template.nodes, scope, span);
self.dependent(template, scope, span);
} else {
self.error(
"missing-include",
view.span,
format!("cannot resolve template `{name}`"),
);
}
} else {
if let Some(arg) = args.get(2) {
self.expr(arg, env);
}
self.unchecked(
"dynamic-include",
view.span,
"`@each` template or item binding is computed at runtime",
);
}
if let Some(empty) = args.get(3) {
if let Some(name) = string(empty) {
if let Some(template) = resolver.include(name) {
let scope = self.partial_scope(&template.nodes, self.root(), span);
self.dependent(template, scope, span);
} else if !name.starts_with("raw|") {
self.error(
"missing-include",
empty.span,
format!("cannot resolve template `{name}`"),
);
}
} else {
self.expr(empty, env);
self.unchecked(
"dynamic-include",
empty.span,
"empty template name is computed at runtime",
);
}
}
}
fn partial_scope(&mut self, nodes: &[Node], caller: Environment, span: Span) -> Environment {
let mut props = declarations(nodes).peekable();
if props.peek().is_none() {
return caller;
}
let mut scope = Environment::default();
for decl in props {
let prop = self.declaration(decl, &mut scope);
if let Some(binding) = caller.bindings.get(&decl.name) {
let offered = if caller
.narrowed
.iter()
.any(|p| p.name == decl.name && p.is_root())
{
self.present_type(binding.ty.clone())
} else {
binding.ty.clone()
};
self.require(&offered, &prop.ty, span, "include-prop-type");
} else if prop.required {
self.error(
"include-missing-prop",
span,
format!("include needs `{}`", decl.name),
);
}
scope.contract.insert(decl.name.clone());
if let Some(binding) = caller.bindings.get(&decl.name)
&& binding.model
{
scope.bind_model(&decl.name, prop.ty);
} else {
scope.bind(decl.name.clone(), prop.ty, false);
}
}
scope
}
fn data_fields(&mut self, ty: &Ty, span: Span) -> BTreeMap<String, Ty> {
if let Some(fields) = self.members(ty) {
return fields;
}
if matches!(self.resolve(ty), Ty::Map(..) | Ty::Any) {
self.unchecked(
"dynamic-template-data",
span,
"data keys are known only at runtime",
);
} else if !ty.unknown() {
self.error(
"template-data-type",
span,
"template data must be a named map",
);
}
BTreeMap::new()
}
fn declaration(&mut self, decl: &FieldDecl, env: &mut Environment) -> Prop {
let default = decl.default.as_ref().map(|value| self.expr(value, env));
let ty = if let Some(spelling) = &decl.ty {
if let Some(ty) = self.annotation(spelling) {
if let Some(default) = &default {
let at = decl.default.as_ref().map_or(decl.span, |value| value.span);
self.require(default, &ty, at, "prop-default-type");
}
ty
} else {
self.error(
"unknown-type",
decl.span,
format!("unknown type `{spelling}`"),
);
Ty::Error
}
} else {
default.unwrap_or_else(|| {
self.unchecked(
"untyped-prop",
decl.span,
format!("prop `{}` has no declared type or default", decl.name),
);
Ty::Any
})
};
Prop {
ty,
required: decl.default.is_none(),
spelling: decl.ty.clone(),
aliases: Vec::new(),
}
}
fn component(&mut self, component: &Component, span: Span, env: &mut Environment) {
let (mut inputs, spread) = self.attributes(&component.attributes, env);
let mut slots = Slots::default();
let mut local = env.clone();
self.slot_names(&component.body, &mut slots, true);
self.nodes(&component.body, &mut local);
env.join(&local);
let resolver = self.config.resolver;
let name = if component.name == "dynamic-component" {
let name = inputs
.remove("component")
.and_then(|input| input.literal)
.or_else(|| {
component
.attributes
.iter()
.find_map(|attr| match &attr.kind {
ComponentAttrKind::Bound { name, value } if name == "component" => {
string(value).map(str::to_owned)
}
_ => None,
})
});
let Some(name) = name else {
self.unchecked(
"dynamic-component",
span,
"component name is computed at runtime",
);
return;
};
name
} else {
component.name.clone()
};
if resolver.has_runtime_component(&name) {
return;
}
if let Some(definition) = resolver.component(&name) {
self.component_contract(&name, definition, &inputs, &slots, spread, span);
} else {
self.error(
"missing-component",
span,
format!("cannot resolve component `{name}`"),
);
}
}
fn legacy_component(
&mut self,
kind: &BlockKind,
args: &[Expr],
body: &[Node],
span: Span,
env: &mut Environment,
) {
let mut local = env.clone();
self.nodes(body, &mut local);
env.join(&local);
let Some(view) = args.first() else {
self.error(
"component-arguments",
span,
"component needs a template name",
);
return;
};
self.expr(view, env);
let mut inputs = BTreeMap::new();
if let Some(data) = args.get(1) {
let ty = self.expr(data, env);
for (name, ty) in self.data_fields(&ty, data.span) {
inputs.insert(
normalize(&name),
Input {
ty,
span: data.span,
literal: None,
},
);
}
}
let mut slots = Slots::default();
self.slot_names(body, &mut slots, true);
let mut candidates = Vec::new();
if let Some(name) = string(view) {
candidates.push(name);
} else if kind == &BlockKind::ComponentFirst
&& let ExprKind::List(items) = &view.kind
{
candidates.extend(items.iter().filter_map(string));
}
if candidates.is_empty() {
self.unchecked(
"dynamic-component",
view.span,
"component name is computed at runtime",
);
return;
}
let resolver = self.config.resolver;
for name in candidates {
if let Some(definition) = resolver.component(name).or_else(|| {
resolver.include(name).map(|template| ComponentDefinition {
template: Some(template),
..Default::default()
})
}) {
self.component_contract(name, definition, &inputs, &slots, false, span);
return;
}
}
self.error(
"missing-component",
view.span,
"cannot resolve legacy component",
);
}
fn component_contract(
&mut self,
name: &str,
definition: ComponentDefinition<'_>,
inputs: &BTreeMap<String, Input>,
supplied_slots: &Slots,
spread: bool,
span: Span,
) {
let mut scope = self.root();
scope.optional_slots = true;
scope.helpers = definition.helpers;
scope.bind("slot".into(), Ty::Slot, false);
scope.bind("attributes".into(), Ty::Attributes, false);
let mut props = BTreeMap::new();
let mut slots = definition
.slots
.into_iter()
.map(|(name, required)| (normalize(&name), required))
.collect::<BTreeMap<_, _>>();
if let Some(desc) = definition.props.as_ref() {
let mut required = BTreeMap::new();
self.prop_presence(desc, &mut required, &mut BTreeSet::new());
for (name, ty) in shape_fields(self.config.types, desc, Direction::Deserialize).bindings
{
let (presence, aliases) = required.remove(&name).unwrap_or_default();
props.insert(
name,
Prop {
ty: Ty::shape(ty, Direction::Deserialize),
required: presence,
spelling: None,
aliases,
},
);
}
}
if let Some(template) = definition.template {
for decl in declarations(&template.nodes) {
let prop = self.declaration(decl, &mut scope);
if matches!(self.resolve(&prop.ty), Ty::Slot | Ty::Option(_))
&& slot_type(&self.resolve(&prop.ty))
{
slots.insert(decl.name.clone(), prop.required && prop.ty == Ty::Slot);
} else {
props.insert(decl.name.clone(), prop);
}
}
implicit_slots(&template.nodes, &mut slots, &props, &scope);
}
for (prop_name, prop) in &props {
scope.contract.insert(prop_name.clone());
let input = inputs.get(&normalize(prop_name)).or_else(|| {
prop.aliases
.iter()
.find_map(|alias| inputs.get(&normalize(alias)))
});
if let Some(input) = input {
let ty = if let Some(literal) = &input.literal {
self.literal_prop(literal, prop, input.span)
} else {
input.ty.clone()
};
if !self.fits(&ty, &prop.ty) {
self.error(
"component-prop-type",
input.span,
format!(
"`<x-{name}>` prop `{prop_name}` expects {}, found {}",
self.type_name(&prop.ty),
self.type_name(&ty)
),
);
}
} else if prop.required {
let message = format!("`<x-{name}>` needs the prop `{prop_name}`");
if spread {
self.unchecked("spread-component-prop", span, message);
} else {
self.error("missing-component-prop", span, message);
}
}
scope.bind(prop_name.clone(), prop.ty.clone(), false);
}
for (slot, &(at, _)) in &supplied_slots.named {
if !slots.contains_key(slot) {
self.error(
"unknown-component-slot",
at,
format!("`<x-{name}>` has no named slot `{slot}`"),
);
}
}
let contract_names: BTreeSet<_> = props.keys().chain(slots.keys()).cloned().collect();
for (slot, required) in slots {
scope.contract.insert(slot.clone());
let provided = supplied_slots.named.get(&slot);
let supplied = provided.is_some_and(|(_, guaranteed)| *guaranteed);
if required && !supplied {
if provided.is_some() || supplied_slots.dynamic {
self.unchecked(
"conditional-component-slot",
span,
format!("`<x-{name}>` may omit required slot `{slot}` at runtime"),
);
} else {
self.error(
"missing-component-slot",
span,
format!("`<x-{name}>` needs the slot `{slot}`"),
);
}
}
scope.bind(
slot,
if supplied || required {
Ty::Slot
} else {
Ty::Slot.optional()
},
false,
);
}
for (field, ty) in &definition.computed {
if contract_names.contains(field) || matches!(field.as_str(), "attributes" | "slot") {
self.error(
"component-shadow",
span,
format!("computed field `{field}` shadows a prop or slot on `<x-{name}>`"),
);
}
scope.bind(field.clone(), Ty::from(ty.clone()), false);
}
if let Some(template) = definition.template {
self.dependent(template, scope, span);
}
}
fn prop_presence(
&self,
shape: &TypeDesc,
props: &mut BTreeMap<String, (bool, Vec<String>)>,
seen: &mut BTreeSet<&'static str>,
) {
match shape {
TypeDesc::Ref(name) if seen.insert(name) => {
if let Some(named) = self.config.types.get(name, Direction::Deserialize) {
self.prop_presence(&named.ty, props, seen);
}
}
TypeDesc::Display { ty, .. } => self.prop_presence(ty, props, seen),
TypeDesc::Struct(fields) => {
for field in fields {
if field.flatten {
self.prop_presence(&field.ty, props, seen);
} else {
props.insert(
field.name.into(),
(
field.presence == Presence::Required,
field.aliases.iter().map(|alias| (*alias).into()).collect(),
),
);
}
}
}
_ => {}
}
}
fn literal_prop(&mut self, literal: &str, prop: &Prop, span: Span) -> Ty {
let mut expected = self.resolve(&prop.ty);
if let Ty::Option(inner) = expected {
expected = self.resolve(&inner);
}
let valid = match expected {
Ty::Bool => literal.parse::<bool>().is_ok(),
Ty::Int => {
let spelling = prop.spelling.as_deref().map(|text| {
text.trim()
.strip_prefix("Option<")
.and_then(|inner| inner.strip_suffix('>'))
.unwrap_or(text)
.trim()
});
let typed = match spelling {
Some("i8") => literal.parse::<i8>().is_ok(),
Some("i16") => literal.parse::<i16>().is_ok(),
Some("i32") => literal.parse::<i32>().is_ok(),
Some("u8") => literal.parse::<u8>().is_ok(),
Some("u16") => literal.parse::<u16>().is_ok(),
Some("u32") => literal.parse::<u32>().is_ok(),
Some("u64" | "usize" | "u128") => literal.parse::<u64>().is_ok(),
_ => true,
};
typed && literal.parse::<i64>().is_ok()
}
Ty::Float => literal.parse::<f64>().is_ok_and(f64::is_finite),
_ => return Ty::String,
};
if valid {
expected
} else {
self.error("literal-prop-type", span, format!("literal `{literal}` cannot be parsed as {}; use a bound attribute for an expression", expected.label()));
Ty::Error
}
}
fn attributes(
&mut self,
attributes: &[ComponentAttr],
env: &mut Environment,
) -> (BTreeMap<String, Input>, bool) {
let mut inputs = BTreeMap::new();
let mut spread = false;
for attr in attributes {
let span = attr.span;
let (name, ty, literal) = match &attr.kind {
ComponentAttrKind::Literal { name, parts } => {
self.attribute_parts(name, parts, env);
let literal = literal_parts(parts);
(name, Ty::String, literal)
}
ComponentAttrKind::Escaped { name, parts } => {
if let Some(parts) = parts {
self.attribute_parts(name, parts, env);
}
continue;
}
ComponentAttrKind::Bound { name, value } => (name, self.expr(value, env), None),
ComponentAttrKind::Shorthand(name) => {
let ty = self.expr(
&Expr {
span,
kind: ExprKind::Path(vec![name.clone()]),
},
env,
);
(name, ty, None)
}
ComponentAttrKind::Bare(name) => (name, Ty::Bool, None),
ComponentAttrKind::Spread(value) => {
let ty = self.expr(value, env);
if let Some(fields) = self.members(&ty) {
for (name, ty) in fields {
inputs.insert(
normalize(&name),
Input {
ty,
span,
literal: None,
},
);
}
} else {
spread = true;
}
continue;
}
ComponentAttrKind::Class(expr) | ComponentAttrKind::Style(expr) => {
self.class_or_style(expr, env);
continue;
}
};
inputs.insert(normalize(name), Input { ty, span, literal });
}
(inputs, spread)
}
fn attribute_parts(&mut self, name: &str, parts: &[AttributePart], env: &mut Environment) {
for part in parts {
if let AttributePart::Echo(kind, expr) = part {
self.echo(*kind, expr, env);
if *kind != EchoKind::Raw && script_attribute(name) {
self.warn(
"script-attribute-echo",
expr.span,
"escaped HTML is not JavaScript encoding; use `js()`",
);
}
}
}
}
fn slot_names(&mut self, nodes: &[Node], slots: &mut Slots, guaranteed: bool) {
for node in nodes {
let name = match &node.kind {
NodeKind::Slot(slot) => slot.name.clone().or_else(|| {
slot.attributes.iter().find_map(|attr| match &attr.kind {
ComponentAttrKind::Literal { name, parts } if name == "name" => {
literal_parts(parts)
}
ComponentAttrKind::Bound { name, value } if name == "name" => {
string(value).map(str::to_owned)
}
_ => None,
})
}),
NodeKind::Inline {
kind: InlineKind::Slot,
args,
..
}
| NodeKind::Block {
kind: BlockKind::Slot,
args,
..
} => args.first().and_then(string).map(str::to_owned),
NodeKind::Conditional(branches) => {
for branch in branches {
self.slot_names(&branch.body, slots, false);
}
continue;
}
NodeKind::Loop { body, empty, .. } => {
self.slot_names(body, slots, false);
if let Some(empty) = empty {
self.slot_names(empty, slots, false);
}
continue;
}
NodeKind::While { body, .. } => {
self.slot_names(body, slots, false);
continue;
}
NodeKind::Switch { arms, .. } => {
for arm in arms {
self.slot_names(&arm.body, slots, false);
}
continue;
}
_ => continue,
};
if let Some(name) = name {
slots
.named
.entry(normalize(&name))
.and_modify(|(_, existing)| *existing |= guaranteed)
.or_insert((node.span, guaranteed));
} else {
slots.dynamic = true;
self.unchecked(
"dynamic-slot",
node.span,
"named slot is computed at runtime",
);
}
}
}
}
fn declarations(nodes: &[Node]) -> impl Iterator<Item = &FieldDecl> {
nodes
.iter()
.filter_map(|node| match &node.kind {
NodeKind::Props(decls) => Some(decls.as_slice()),
_ => None,
})
.flatten()
}
fn slot_type(ty: &Ty) -> bool {
matches!(ty, Ty::Slot) || matches!(ty, Ty::Option(inner) if **inner == Ty::Slot)
}
fn implicit_slots(
nodes: &[Node],
slots: &mut BTreeMap<String, bool>,
props: &BTreeMap<String, Prop>,
scope: &Environment,
) {
for node in nodes {
match &node.kind {
NodeKind::Conditional(branches) => {
for branch in branches {
if let Some(test) = &branch.test {
for expr in &test.args {
if test.kind == ConditionKind::Isset {
discover_slot(expr, slots, props, scope);
} else {
guarded_slots(expr, slots, props, scope);
}
}
}
implicit_slots(&branch.body, slots, props, scope);
}
}
NodeKind::Block { body, .. }
| NodeKind::Section { body, .. }
| NodeKind::While { body, .. }
| NodeKind::Loop { body, .. } => implicit_slots(body, slots, props, scope),
NodeKind::Echo(_, expr) => guarded_slots(expr, slots, props, scope),
_ => {}
}
}
}
fn guarded_slots(
expr: &Expr,
slots: &mut BTreeMap<String, bool>,
props: &BTreeMap<String, Prop>,
scope: &Environment,
) {
match &expr.kind {
ExprKind::Call { callee, args } if matches!(&callee.kind, ExprKind::Path(path) if path == &["isset"]) => {
for arg in &args.values {
discover_slot(arg, slots, props, scope);
}
}
ExprKind::Binary {
op: BinaryOp::Coalesce,
left,
right,
} => {
discover_slot(left, slots, props, scope);
guarded_slots(right, slots, props, scope);
}
ExprKind::Binary { left, right, .. } => {
guarded_slots(left, slots, props, scope);
guarded_slots(right, slots, props, scope);
}
ExprKind::Unary { value, .. } => guarded_slots(value, slots, props, scope),
_ => {}
}
}
fn discover_slot(
expr: &Expr,
slots: &mut BTreeMap<String, bool>,
props: &BTreeMap<String, Prop>,
scope: &Environment,
) {
if let Some(name) = Place::root(expr)
&& !props.contains_key(name)
&& !scope.bindings.contains_key(name)
&& name != "loop"
{
slots.entry(name.into()).or_insert(false);
}
}
fn condition_facts(test: &Condition, positive: bool, env: &mut Environment) {
match test.kind {
ConditionKind::If | ConditionKind::Unless => {
if let Some(expr) = test.args.first() {
narrow(expr, positive == (test.kind == ConditionKind::If), env);
}
}
ConditionKind::Isset if positive => {
for arg in &test.args {
present(arg, env);
}
}
ConditionKind::Auth if positive && test.args.is_empty() => env.mark_present("auth_user"),
ConditionKind::Guest if !positive && test.args.is_empty() => env.mark_present("auth_user"),
_ => {}
}
}
fn trusted(ty: &Ty) -> bool {
match ty {
Ty::Html | Ty::Slot | Ty::Attributes | Ty::Error | Ty::Any => true,
Ty::Union(types) => types.iter().all(trusted),
_ => false,
}
}
fn unconditional_break(node: &Node) -> bool {
matches!(&node.kind, NodeKind::Inline { kind: InlineKind::Break, args, .. } if args.is_empty())
}
fn normalize(name: &str) -> String {
name.replace('-', "_")
}
fn literal_parts(parts: &[AttributePart]) -> Option<String> {
parts
.iter()
.map(|part| match part {
AttributePart::Text(text) => Some(text.as_str()),
_ => None,
})
.collect()
}
fn script_attribute(name: &str) -> bool {
let name = name.to_ascii_lowercase();
name.starts_with("x-")
|| name.starts_with(':')
|| name.starts_with('@')
|| name
.strip_prefix("on")
.is_some_and(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphabetic()))
}
fn html_attribute(source: &str, offset: usize) -> Option<String> {
let prefix = source.get(..offset)?;
let mut tag = false;
let mut quote = None;
let mut attribute = None;
let mut chars = prefix.char_indices().peekable();
while let Some((index, c)) = chars.next() {
let rest = &prefix[index..];
let skipped = if rest.starts_with("{{--") {
Some("--}}")
} else if rest.starts_with("{{") {
Some("}}")
} else if rest.starts_with("{!!") {
Some("!!}")
} else if rest.starts_with("<!--") {
Some("-->")
} else {
None
};
if let Some(end) = skipped
&& let Some(length) = rest.find(end)
{
while chars
.peek()
.is_some_and(|(next, _)| *next < index + length + end.len())
{
chars.next();
}
continue;
}
if let Some(delimiter) = quote {
if c == delimiter {
quote = None;
attribute = None;
}
continue;
}
if c == '<'
&& chars
.peek()
.is_some_and(|(_, next)| next.is_ascii_alphabetic())
{
tag = true;
} else if c == '>' {
tag = false;
attribute = None;
} else if tag && c == '=' {
let name = prefix[..index]
.trim_end()
.rsplit(|c: char| c.is_whitespace() || c == '<')
.next()
.unwrap_or_default();
attribute = Some(name.to_owned());
while chars.next_if(|(_, next)| next.is_whitespace()).is_some() {}
if let Some((_, delimiter)) = chars.next_if(|(_, next)| matches!(next, '\'' | '"')) {
quote = Some(delimiter);
} else {
while chars
.next_if(|(_, next)| !next.is_whitespace() && *next != '>')
.is_some()
{}
if chars.peek().is_some() {
attribute = None;
}
}
}
}
attribute
}