use std::collections::{HashMap, HashSet};
use crate::ast::*;
use crate::diagnostic::Diagnostic;
use crate::lexer::{Punct, Token, TokenKind, is_valid_number};
use crate::span::Span;
pub const MAX_DEPTH: usize = 64;
pub const MAX_TREE_DEPTH: usize = 256;
const KEYWORDS: [&str; 25] = [
"if",
"else",
"for",
"while",
"do",
"switch",
"case",
"default",
"break",
"continue",
"discard",
"return",
"struct",
"enum",
"namespace",
"typedef",
"cbuffer",
"tbuffer",
"true",
"false",
"technique",
"technique10",
"technique11",
"pass",
"sampler_state",
];
const SCALARS: [&str; 21] = [
"bool",
"int",
"uint",
"dword",
"half",
"float",
"double",
"min16float",
"min10float",
"min16int",
"min12int",
"min16uint",
"int16_t",
"uint16_t",
"int32_t",
"uint32_t",
"int64_t",
"uint64_t",
"float16_t",
"float32_t",
"float64_t",
];
const TEMPLATE_TYPES: [&str; 28] = [
"vector",
"matrix",
"Texture1D",
"Texture1DArray",
"Texture2D",
"Texture2DArray",
"Texture2DMS",
"Texture2DMSArray",
"Texture3D",
"TextureCube",
"TextureCubeArray",
"Buffer",
"RWBuffer",
"StructuredBuffer",
"RWStructuredBuffer",
"AppendStructuredBuffer",
"ConsumeStructuredBuffer",
"RWTexture1D",
"RWTexture1DArray",
"RWTexture2D",
"RWTexture2DArray",
"RWTexture3D",
"ConstantBuffer",
"PointStream",
"LineStream",
"TriangleStream",
"InputPatch",
"OutputPatch",
];
const OTHER_TYPES: [&str; 15] = [
"void",
"string",
"sampler",
"sampler1D",
"sampler2D",
"sampler3D",
"samplerCUBE",
"SamplerState",
"SamplerComparisonState",
"texture",
"texture1D",
"texture2D",
"texture3D",
"textureCUBE",
"ByteAddressBuffer",
];
fn is_keyword(word: &str) -> bool {
KEYWORDS.contains(&word)
}
fn is_sampler_type(word: &str) -> bool {
word.starts_with("sampler") || word == "SamplerState" || word == "SamplerComparisonState"
}
fn is_template_type(word: &str) -> bool {
TEMPLATE_TYPES.contains(&word)
}
pub fn is_builtin_type(word: &str) -> bool {
if is_template_type(word) || OTHER_TYPES.contains(&word) || word == "RWByteAddressBuffer" {
return true;
}
let dim = |c: u8| (b'1'..=b'4').contains(&c);
SCALARS.iter().any(|scalar| {
word.strip_prefix(scalar)
.is_some_and(|rest| match rest.as_bytes() {
[] => true,
[n] => dim(*n),
[n, b'x', m] => dim(*n) && dim(*m),
_ => false,
})
})
}
struct Stop;
type PResult<T> = Result<T, Stop>;
pub fn parse_tokens(
mut tokens: Vec<Token>,
eof: Span,
diagnostics: &mut Vec<Diagnostic>,
) -> TranslationUnit {
tokens.retain(|t| {
if t.kind == TokenKind::Other {
diagnostics.push(Diagnostic::error(
t.site(),
format!("unexpected character `{}`", t.text),
));
}
t.kind != TokenKind::Other
});
let mut parser = Parser {
tokens,
pos: 0,
types: HashSet::new(),
path: Vec::new(),
vars: Vec::new(),
var_count: HashMap::new(),
diagnostics,
depth: 0,
tree_depth: 0,
eof,
};
let mut items = Vec::new();
while parser.pos < parser.tokens.len() {
let start = parser.pos;
if parser.item(&mut items).is_err() {
parser.recover(false);
}
if parser.pos == start {
parser.pos += 1;
}
}
TranslationUnit { items }
}
struct Parser<'a> {
tokens: Vec<Token>,
pos: usize,
types: HashSet<String>,
path: Vec<String>,
vars: Vec<String>,
var_count: HashMap<String, usize>,
diagnostics: &'a mut Vec<Diagnostic>,
depth: usize,
tree_depth: usize,
eof: Span,
}
impl Parser<'_> {
fn peek(&self) -> Option<&Token> {
self.tokens.get(self.pos)
}
fn peek_at(&self, n: usize) -> Option<&Token> {
self.tokens.get(self.pos + n)
}
fn at(&self, punct: Punct) -> bool {
self.peek().is_some_and(|t| t.is(punct))
}
fn at_word(&self, word: &str) -> bool {
self.peek().is_some_and(|t| t.is_word(word))
}
fn eat(&mut self, punct: Punct) -> bool {
let found = self.at(punct);
self.pos += usize::from(found);
found
}
fn eat_word(&mut self, word: &str) -> bool {
let found = self.at_word(word);
self.pos += usize::from(found);
found
}
fn eat_gt(&mut self) -> Option<Span> {
if self.at(Punct::Gt) {
let site = self.here();
self.pos += 1;
return Some(site);
}
let t = self.tokens.get_mut(self.pos).filter(|t| t.is(Punct::Shr))?;
let mut first = t.site();
if t.expanded_from.is_none() {
first.end = first.start + 1;
}
t.kind = TokenKind::Punct(Punct::Gt);
t.text = ">".to_string();
t.span.start += 1;
Some(first)
}
fn here(&self) -> Span {
self.peek().map_or(self.eof, Token::site)
}
fn prev(&self) -> Span {
self.pos
.checked_sub(1)
.and_then(|i| self.tokens.get(i))
.map_or(self.eof, Token::site)
}
fn since(&self, start: Span) -> Span {
start.to(self.prev())
}
fn error(&mut self, span: Span, message: impl Into<String>) -> Stop {
self.diagnostics.push(Diagnostic::error(span, message));
Stop
}
fn expected(&mut self, what: &str) -> Stop {
let message = match self.peek() {
Some(t) => format!("expected {what}, found `{}`", t.text),
None => format!("expected {what}, found the end of the input"),
};
let here = self.here();
self.error(here, message)
}
fn expect(&mut self, punct: Punct) -> PResult<()> {
if self.eat(punct) {
Ok(())
} else {
Err(self.expected(&format!("`{}`", punct.as_str())))
}
}
fn nested<T>(&mut self, f: impl FnOnce(&mut Self) -> PResult<T>) -> PResult<T> {
if self.depth >= MAX_DEPTH {
let here = self.here();
return Err(self.error(
here,
format!("the code is nested more than {MAX_DEPTH} levels deep"),
));
}
self.depth += 1;
let result = f(self);
self.depth -= 1;
result
}
fn recover(&mut self, in_block: bool) {
self.skip(in_block, false);
}
fn recover_in_switch(&mut self) {
self.skip(true, true);
}
fn skip(&mut self, in_block: bool, stop_at_labels: bool) {
let mut depth = 0usize;
while let Some(t) = self.peek() {
if stop_at_labels && depth == 0 && (t.is_word("case") || t.is_word("default")) {
return;
}
if t.is(Punct::LBrace) {
depth += 1;
} else if t.is(Punct::RBrace) {
if depth == 0 {
if !in_block {
self.pos += 1;
}
return;
}
depth -= 1;
if depth == 0 {
self.pos += 1;
return;
}
} else if t.is(Punct::Semi) && depth == 0 {
self.pos += 1;
return;
}
self.pos += 1;
}
}
fn ident(&mut self) -> PResult<Ident> {
match self.peek() {
Some(t) if t.kind == TokenKind::Ident && !is_keyword(&t.text) => {
let ident = Ident {
name: t.text.clone(),
span: t.site(),
};
self.pos += 1;
Ok(ident)
}
_ => Err(self.expected("a name")),
}
}
fn word(&mut self) -> PResult<Ident> {
match self.peek() {
Some(t) if t.kind == TokenKind::Ident => {
let ident = Ident {
name: t.text.clone(),
span: t.site(),
};
self.pos += 1;
Ok(ident)
}
_ => Err(self.expected("a name")),
}
}
fn is_type_name(&self, name: &str) -> bool {
is_builtin_type(name) || self.types.contains(name)
}
fn qualified_at(&self, mut p: usize) -> Option<(String, usize)> {
let is_name = |t: &Token| t.kind == TokenKind::Ident && !is_keyword(&t.text);
let mut name = self.tokens.get(p).filter(|t| is_name(t))?.text.clone();
p += 1;
while let (Some(sep), Some(next)) = (self.tokens.get(p), self.tokens.get(p + 1)) {
if !sep.is(Punct::ColonColon) || !is_name(next) {
break;
}
name.push_str("::");
name.push_str(&next.text);
p += 2;
}
Some((name, p))
}
fn type_at(&self, p: usize) -> Option<usize> {
let t = self.tokens.get(p)?;
if t.is_word("unsigned") || t.is_word("signed") {
let int = self.tokens.get(p + 1).is_some_and(|n| n.is_word("int"));
return Some(p + 1 + usize::from(int));
}
let (name, end) = self.qualified_at(p)?;
self.is_type_name(&name).then_some(end)
}
fn declare_type(&mut self, name: &str) {
let mut qualified = name.to_string();
self.types.insert(qualified.clone());
for outer in self.path.iter().rev() {
qualified = format!("{outer}::{qualified}");
self.types.insert(qualified.clone());
}
}
fn type_name(&mut self) -> PResult<Ident> {
let start = self.here();
if let Some(name) = ["unsigned", "signed"].into_iter().find(|w| self.at_word(w)) {
self.pos += 1;
self.eat_word("int");
let name = if name == "unsigned" { "uint" } else { "int" };
return Ok(Ident {
name: name.to_string(),
span: self.since(start),
});
}
let mut name = self.ident().map_err(|_| {
self.diagnostics.pop();
self.expected("a type")
})?;
while self.at(Punct::ColonColon) {
self.pos += 1;
let part = self.ident()?;
name.name = format!("{}::{}", name.name, part.name);
name.span = name.span.to(part.span);
}
Ok(name)
}
fn declare(&mut self, name: &str) {
self.vars.push(name.to_string());
*self.var_count.entry(name.to_string()).or_default() += 1;
}
fn declare_all(&mut self, decl: &VarDecl) {
for d in &decl.declarators {
self.declare(&d.name.name);
}
}
fn end_scope(&mut self, mark: usize) {
while self.vars.len() > mark {
let name = self.vars.pop().expect("longer than mark");
if let Some(count) = self.var_count.get_mut(&name) {
*count -= 1;
if *count == 0 {
self.var_count.remove(&name);
}
}
}
}
fn type_ref(&mut self) -> PResult<TypeRef> {
let name = self.type_name()?;
let mut args = Vec::new();
let mut span = name.span;
let mut deepest = 0;
if is_template_type(&name.name) && self.eat(Punct::Lt) {
let close;
(args, close) = self.nested(|p| {
let mut args = Vec::new();
loop {
args.push(p.type_arg()?);
deepest = deepest.max(p.tree_depth);
if let Some(close) = p.eat_gt() {
return Ok((args, close));
}
p.expect(Punct::Comma)?;
}
})?;
span = span.to(close);
}
self.tree_depth = deepest;
Ok(TypeRef { span, name, args })
}
fn type_arg(&mut self) -> PResult<TypeArg> {
let mut after = self.pos;
while self
.tokens
.get(after)
.is_some_and(|t| t.is_word("unorm") || t.is_word("snorm"))
{
after += 1;
}
if self.type_at(after).is_none() {
return Ok(TypeArg::Expr(self.binary(8)?));
}
let modifiers: Vec<Modifier> = self.tokens[self.pos..after]
.iter()
.filter_map(|t| Modifier::from_word(&t.text))
.collect();
self.pos = after;
let ty = self.type_ref()?;
Ok(if modifiers.is_empty() {
TypeArg::Type(ty)
} else {
TypeArg::Modified(modifiers, ty)
})
}
fn modifiers(&mut self) -> Vec<Modifier> {
let mut modifiers = Vec::new();
while let (Some(t), Some(next)) = (self.peek(), self.peek_at(1)) {
match Modifier::from_word(&t.text) {
Some(m) if t.kind == TokenKind::Ident && next.kind == TokenKind::Ident => {
modifiers.push(m);
self.pos += 1;
}
_ => break,
}
}
modifiers
}
fn at_declaration(&self) -> bool {
let mut p = self.pos;
while let (Some(t), Some(next)) = (self.tokens.get(p), self.tokens.get(p + 1)) {
if t.kind == TokenKind::Ident
&& next.kind == TokenKind::Ident
&& Modifier::from_word(&t.text).is_some()
{
p += 1;
} else {
break;
}
}
let Some((name, end)) = self.qualified_at(p) else {
return false;
};
p = end;
if is_template_type(&name) && self.tokens.get(p).is_some_and(|n| n.is(Punct::Lt)) {
let Some(end) = self.after_template_args(p) else {
return false;
};
p = end;
}
self.tokens
.get(p)
.is_some_and(|n| n.kind == TokenKind::Ident && !is_keyword(&n.text))
}
fn after_template_args(&self, mut p: usize) -> Option<usize> {
let mut depth = 0usize;
while let Some(n) = self.tokens.get(p) {
p += 1;
match n.kind {
TokenKind::Punct(Punct::Lt) => depth += 1,
TokenKind::Punct(Punct::Gt) => depth -= 1,
TokenKind::Punct(Punct::Shr) => depth = depth.saturating_sub(2),
TokenKind::Punct(Punct::Semi | Punct::LBrace | Punct::RBrace) => return None,
_ => {}
}
if depth == 0 {
return Some(p);
}
}
None
}
fn item(&mut self, items: &mut Vec<Item>) -> PResult<()> {
if self.eat(Punct::Semi) {
return Ok(());
}
let start = self.here();
let attributes = self.attributes()?;
self.no_attributes_before_type(&attributes)?;
if self.at_word("namespace") {
let namespace = self.namespace()?;
items.push(Item::Namespace(namespace));
return Ok(());
}
self.other_item(start, attributes, items)
}
fn other_item(
&mut self,
start: Span,
attributes: Vec<Attribute>,
items: &mut Vec<Item>,
) -> PResult<()> {
if self.at_word("struct") {
let def = self.struct_def()?;
let vars = self.struct_vars(start, &def);
items.push(Item::Struct(def));
if let Some(decl) = vars? {
items.push(Item::Variable(decl));
}
return Ok(());
}
if self.at_word("typedef") {
let typedef = self.typedef()?;
items.push(Item::Typedef(typedef));
return Ok(());
}
if self.at_word("enum") {
let def = self.enum_def()?;
items.push(Item::Enum(def));
return Ok(());
}
if self.at_word("cbuffer") || self.at_word("tbuffer") {
let buffer = self.buffer(start, attributes)?;
items.push(Item::Buffer(buffer));
return Ok(());
}
if ["technique", "technique10", "technique11"]
.iter()
.any(|w| self.at_word(w))
{
let stop = self.error(start, "effect techniques are not supported");
self.pos += 1;
if self.peek().is_some_and(|t| t.kind == TokenKind::Ident) {
self.pos += 1;
}
if self.at(Punct::Lt) {
self.annotations()?;
}
return Err(stop);
}
if let Some(word) = ["template", "class", "interface"]
.into_iter()
.find(|w| self.at_word(w))
{
return Err(self.error(start, format!("`{word}` is not supported yet")));
}
let modifiers = self.modifiers();
let ty = self.type_ref()?;
let name = self.ident()?;
if self.at(Punct::LParen) {
let mark = self.vars.len();
let function = self.function(start, attributes, modifiers, ty, name);
self.end_scope(mark);
items.push(Item::Function(function?));
return Ok(());
}
let declarators = self.declarators(name, &ty)?;
self.expect(Punct::Semi)?;
let decl = VarDecl {
attributes,
modifiers,
ty,
declarators,
span: self.since(start),
};
self.declare_all(&decl);
items.push(Item::Variable(decl));
Ok(())
}
fn struct_def(&mut self) -> PResult<StructDef> {
let start = self.here();
self.pos += 1;
let attributes = self.attributes()?;
let name = self.ident()?;
self.declare_type(&name.name);
let base = if self.eat(Punct::Colon) {
Some(self.type_ref()?)
} else {
None
};
self.expect(Punct::LBrace)?;
let mut def = StructDef {
attributes,
name,
base,
fields: Vec::new(),
methods: Vec::new(),
nested: Vec::new(),
span: start,
};
let mark = self.vars.len();
self.path.push(def.name.name.clone());
let parsed = self.nested(|p| p.body_list(|p| p.member(&mut def)));
self.path.pop();
self.end_scope(mark);
parsed?;
def.span = self.since(start);
Ok(def)
}
fn struct_vars(&mut self, start: Span, def: &StructDef) -> PResult<Option<VarDecl>> {
if self.eat(Punct::Semi) {
return Ok(None);
}
let ty = TypeRef {
name: def.name.clone(),
args: Vec::new(),
span: def.name.span,
};
let first = self.ident()?;
let declarators = self.declarators(first, &ty)?;
self.expect(Punct::Semi)?;
let decl = VarDecl {
attributes: Vec::new(),
modifiers: Vec::new(),
ty,
declarators,
span: self.since(start),
};
self.declare_all(&decl);
Ok(Some(decl))
}
fn no_attributes_before_type(&mut self, attributes: &[Attribute]) -> PResult<()> {
match attributes.first() {
Some(a)
if ["struct", "typedef", "enum", "namespace"]
.iter()
.any(|w| self.at_word(w)) =>
{
Err(self.error(a.span, "attributes are not allowed here"))
}
_ => Ok(()),
}
}
fn member(&mut self, def: &mut StructDef) -> PResult<()> {
let start = self.here();
let attributes = self.attributes()?;
self.no_attributes_before_type(&attributes)?;
if self.at_word("struct") {
let inner = self.struct_def()?;
let vars = self.struct_vars(start, &inner);
def.nested.push(Item::Struct(inner));
def.fields.extend(vars?);
return Ok(());
}
self.other_member(start, attributes, def)
}
fn other_member(
&mut self,
start: Span,
attributes: Vec<Attribute>,
def: &mut StructDef,
) -> PResult<()> {
if self.at_word("enum") {
def.nested.push(Item::Enum(self.enum_def()?));
return Ok(());
}
if self.at_word("typedef") {
def.nested.push(Item::Typedef(self.typedef()?));
return Ok(());
}
let modifiers = self.modifiers();
let ty = self.type_ref()?;
let name = self.ident()?;
if self.at(Punct::LParen) {
let mark = self.vars.len();
let method = self.function(start, attributes, modifiers, ty, name);
self.end_scope(mark);
def.methods.push(method?);
return Ok(());
}
let declarators = self.declarators(name, &ty)?;
self.expect(Punct::Semi)?;
let decl = VarDecl {
attributes,
modifiers,
ty,
declarators,
span: self.since(start),
};
self.declare_all(&decl);
def.fields.push(decl);
Ok(())
}
fn namespace(&mut self) -> PResult<Namespace> {
let start = self.here();
self.pos += 1;
let name = if self.at(Punct::LBrace) {
None
} else {
Some(self.ident()?)
};
self.expect(Punct::LBrace)?;
if let Some(name) = &name {
self.path.push(name.name.clone());
}
let mut items = Vec::new();
let parsed = self.nested(|p| p.body_list(|p| p.item(&mut items)));
if name.is_some() {
self.path.pop();
}
parsed?;
Ok(Namespace {
name,
items,
span: self.since(start),
})
}
fn body_list<T>(&mut self, mut item: impl FnMut(&mut Self) -> PResult<T>) -> PResult<Vec<T>> {
let mut list = Vec::new();
while !self.eat(Punct::RBrace) {
if self.peek().is_none() {
return Err(self.expected("`}`"));
}
let before = self.pos;
match item(self) {
Ok(entry) => list.push(entry),
Err(Stop) => {
self.recover(true);
if self.pos == before && !self.at(Punct::RBrace) {
self.pos += 1;
}
}
}
}
Ok(list)
}
fn members(&mut self) -> PResult<Vec<VarDecl>> {
self.body_list(Self::var_decl)
}
fn typedef(&mut self) -> PResult<Typedef> {
let start = self.here();
self.pos += 1;
let modifiers = self.modifiers();
let ty = self.type_ref()?;
let mut names = Vec::new();
loop {
let name = self.ident()?;
self.declare_type(&name.name);
let array = self.array_dims()?;
names.push((name, array));
if !self.eat(Punct::Comma) {
break;
}
}
self.expect(Punct::Semi)?;
Ok(Typedef {
modifiers,
ty,
names,
span: self.since(start),
})
}
fn enum_def(&mut self) -> PResult<EnumDef> {
let start = self.here();
self.pos += 1;
let scoped = self.eat_word("class");
let name = if scoped || !(self.at(Punct::LBrace) || self.at(Punct::Colon)) {
let name = self.ident()?;
self.declare_type(&name.name);
Some(name)
} else {
None
};
let base = if self.eat(Punct::Colon) {
Some(self.type_ref()?)
} else {
None
};
self.expect(Punct::LBrace)?;
let mut enumerators = Vec::new();
while !self.eat(Punct::RBrace) {
let name = self.ident()?;
let value = if self.eat(Punct::Eq) {
Some(self.ternary()?)
} else {
None
};
enumerators.push(Enumerator {
span: self.since(name.span),
name,
value,
});
if !self.eat(Punct::Comma) {
self.expect(Punct::RBrace)?;
break;
}
}
self.expect(Punct::Semi)?;
if !scoped {
for e in &enumerators {
self.declare(&e.name.name);
}
}
Ok(EnumDef {
scoped,
name,
base,
enumerators,
span: self.since(start),
})
}
fn buffer(&mut self, start: Span, attributes: Vec<Attribute>) -> PResult<BufferBlock> {
let kind = if self.eat_word("cbuffer") {
BufferKind::Constant
} else {
self.pos += 1;
BufferKind::Texture
};
let name = self.ident()?;
let bindings = self.bindings()?;
self.expect(Punct::LBrace)?;
let members = self.members()?;
for member in &members {
self.declare_all(member);
}
self.eat(Punct::Semi);
Ok(BufferBlock {
attributes,
kind,
name,
bindings,
members,
span: self.since(start),
})
}
fn function(
&mut self,
start: Span,
attributes: Vec<Attribute>,
modifiers: Vec<Modifier>,
return_type: TypeRef,
name: Ident,
) -> PResult<Function> {
self.expect(Punct::LParen)?;
let mut params = Vec::new();
if self.at_word("void") && self.peek_at(1).is_some_and(|t| t.is(Punct::RParen)) {
self.pos += 1;
}
if !self.eat(Punct::RParen) {
loop {
params.push(self.param()?);
if self.eat(Punct::RParen) {
break;
}
self.expect(Punct::Comma)?;
}
}
let return_bindings = self.bindings()?;
let body = if self.eat(Punct::Semi) {
None
} else {
Some(self.block()?)
};
Ok(Function {
attributes,
modifiers,
return_type,
name,
params,
return_bindings,
body,
span: self.since(start),
})
}
fn param(&mut self) -> PResult<Param> {
let start = self.here();
let attributes = self.attributes()?;
let modifiers = self.modifiers();
let ty = self.type_ref()?;
let name = match self.peek() {
Some(t) if t.kind == TokenKind::Ident && !is_keyword(&t.text) => Some(self.ident()?),
_ => None,
};
if let Some(name) = &name {
self.declare(&name.name);
}
let array = self.array_dims()?;
let bindings = self.bindings()?;
let default = if self.eat(Punct::Eq) {
Some(self.assign()?)
} else {
None
};
Ok(Param {
attributes,
modifiers,
ty,
name,
array,
bindings,
default,
span: self.since(start),
})
}
fn attributes(&mut self) -> PResult<Vec<Attribute>> {
let mut attributes = Vec::new();
while self.at(Punct::LBracket) {
let start = self.here();
self.pos += 1;
let double = self.eat(Punct::LBracket);
let first = attributes.len();
loop {
let mut name = self.word()?;
while self.eat(Punct::ColonColon) {
let part = self.word()?;
name.name = format!("{}::{}", name.name, part.name);
name.span = name.span.to(part.span);
}
let args = if self.at(Punct::LParen) {
self.call_args()?
} else {
Vec::new()
};
attributes.push(Attribute {
span: self.since(name.span),
name,
args,
});
if !(double && self.eat(Punct::Comma)) {
break;
}
}
self.expect(Punct::RBracket)?;
if double {
self.expect(Punct::RBracket)?;
}
if let [alone] = &mut attributes[first..] {
alone.span = self.since(start);
}
}
Ok(attributes)
}
fn var_decl(&mut self) -> PResult<VarDecl> {
let start = self.here();
let attributes = self.attributes()?;
let modifiers = self.modifiers();
let ty = self.type_ref()?;
let first = self.ident()?;
let declarators = self.declarators(first, &ty)?;
self.expect(Punct::Semi)?;
Ok(VarDecl {
attributes,
modifiers,
ty,
declarators,
span: self.since(start),
})
}
fn declarators(&mut self, first: Ident, ty: &TypeRef) -> PResult<Vec<Declarator>> {
let mut declarators = vec![self.declarator(first, ty)?];
while self.eat(Punct::Comma) {
let name = self.ident()?;
declarators.push(self.declarator(name, ty)?);
}
Ok(declarators)
}
fn declarator(&mut self, name: Ident, ty: &TypeRef) -> PResult<Declarator> {
let array = self.array_dims()?;
let bindings = self.bindings()?;
let annotations = if self.at(Punct::Lt) {
Some(self.annotations()?)
} else {
None
};
let init = if self.eat(Punct::Eq) {
Some(self.initializer()?)
} else if self.at(Punct::LBrace) && is_sampler_type(&ty.name.name) {
let start = self.here();
self.pos += 1;
let states = self.body_list(Self::state_assignment)?;
Some(Initializer::SamplerState(states, self.since(start)))
} else {
None
};
Ok(Declarator {
span: self.since(name.span),
name,
array,
bindings,
annotations,
init,
})
}
fn array_dims(&mut self) -> PResult<Vec<Option<Expr>>> {
let mut dims = Vec::new();
while self.eat(Punct::LBracket) {
if self.eat(Punct::RBracket) {
dims.push(None);
} else {
dims.push(Some(self.expr()?));
self.expect(Punct::RBracket)?;
}
}
Ok(dims)
}
fn bindings(&mut self) -> PResult<Bindings> {
let mut bindings = Bindings::default();
while self.eat(Punct::Colon) {
let start = self.here();
if self.eat_word("register") {
self.expect(Punct::LParen)?;
let mut words = Vec::new();
let mut subscript = None;
loop {
words.push(self.word()?);
if self.eat(Punct::LBracket) {
subscript = Some((words.len(), self.expr()?));
self.expect(Punct::RBracket)?;
}
if words.len() == 3 || !self.eat(Punct::Comma) {
break;
}
}
self.expect(Punct::RParen)?;
let is_space = |w: &Ident| {
w.name
.strip_prefix("space")
.is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
};
let space = match words.last() {
Some(last) if words.len() > 1 && is_space(last) => words.pop(),
_ => None,
};
let slot_at = words.len();
let slot = words.pop().expect("one word at least");
let profile = words.pop();
if !words.is_empty() {
return Err(self.error(self.since(start), "too many words in `register(...)`"));
}
let subcomponent = match subscript {
Some((at, index)) if at == slot_at => Some(index),
Some((_, index)) => {
return Err(self.error(index.span, "only the register can have a `[...]`"));
}
None => None,
};
bindings.registers.push(Register {
profile,
slot,
subcomponent,
space,
span: self.since(start),
});
} else if self.eat_word("packoffset") {
self.expect(Punct::LParen)?;
let slot = self.word()?;
let component = if self.eat(Punct::Dot) {
Some(self.word()?)
} else {
None
};
self.expect(Punct::RParen)?;
let span = self.since(start);
if bindings.packoffset.is_some() {
self.error(span, "a declaration can have only one `packoffset`");
} else {
bindings.packoffset = Some(PackOffset {
slot,
component,
span,
});
}
} else {
let semantic = self.word()?;
if bindings.semantic.is_some() {
self.error(semantic.span, "a declaration can have only one semantic");
} else {
bindings.semantic = Some(semantic);
}
}
}
Ok(bindings)
}
fn annotations(&mut self) -> PResult<Span> {
let start = self.here();
self.pos += 1;
let mut depth = 0usize;
let mut entry_start = true;
while let Some(t) = self.peek() {
let kind = t.kind;
self.pos += 1;
match kind {
TokenKind::Punct(Punct::Gt) if entry_start => return Ok(self.since(start)),
TokenKind::Punct(Punct::LParen | Punct::LBracket | Punct::LBrace) => depth += 1,
TokenKind::Punct(Punct::RParen | Punct::RBracket | Punct::RBrace) => {
depth = depth.saturating_sub(1);
}
_ => {}
}
entry_start = depth == 0 && kind == TokenKind::Punct(Punct::Semi);
}
Err(self.expected("`>` to close the annotations"))
}
fn initializer(&mut self) -> PResult<Initializer> {
self.nested(|p| {
let start = p.here();
if p.eat(Punct::LBrace) {
let mut list = Vec::new();
while !p.eat(Punct::RBrace) {
list.push(p.initializer()?);
if !p.eat(Punct::Comma) {
p.expect(Punct::RBrace)?;
break;
}
}
return Ok(Initializer::List(list, p.since(start)));
}
if p.eat_word("sampler_state") {
p.expect(Punct::LBrace)?;
let states = p.body_list(Self::state_assignment)?;
return Ok(Initializer::SamplerState(states, p.since(start)));
}
Ok(Initializer::Expr(p.assign()?))
})
}
fn state_assignment(&mut self) -> PResult<StateAssignment> {
let name = self.word()?;
self.expect(Punct::Eq)?;
let value = if self.at(Punct::Lt) {
let open = self.here();
self.pos += 1;
let texture = self.ident()?;
if self.eat_gt().is_none() {
return Err(self.expected("`>`"));
}
Expr {
kind: ExprKind::Ident(texture.name),
span: self.since(open),
}
} else {
self.assign()?
};
self.expect(Punct::Semi)?;
Ok(StateAssignment {
span: self.since(name.span),
name,
value,
})
}
fn block(&mut self) -> PResult<Block> {
let start = self.here();
self.expect(Punct::LBrace)?;
let mark = self.vars.len();
let mut stmts = Vec::new();
while !self.at(Punct::RBrace) {
if self.peek().is_none() {
return Err(self.expected("`}`"));
}
let before = self.pos;
match self.stmt() {
Ok(stmt) => stmts.push(stmt),
Err(Stop) => self.recover(true),
}
if self.pos == before {
self.pos += 1;
}
}
self.pos += 1;
self.end_scope(mark);
Ok(Block {
stmts,
span: self.since(start),
})
}
fn stmt(&mut self) -> PResult<Stmt> {
self.nested(Self::stmt_inner)
}
fn stmt_inner(&mut self) -> PResult<Stmt> {
let start = self.here();
let attributes = self.attributes()?;
let kind = self.stmt_kind()?;
Ok(Stmt {
attributes,
kind,
span: self.since(start),
})
}
fn stmt_kind(&mut self) -> PResult<StmtKind> {
if self.at(Punct::LBrace) {
return Ok(StmtKind::Block(self.block()?));
}
if self.eat(Punct::Semi) {
return Ok(StmtKind::Empty);
}
let word = self
.peek()
.filter(|t| t.kind == TokenKind::Ident)
.map(|t| t.text.clone())
.unwrap_or_default();
match word.as_str() {
"if" => self.if_stmt(),
"for" => self.for_stmt(),
"while" => self.while_stmt(),
"do" => self.do_stmt(),
"switch" => self.switch_stmt(),
"break" | "continue" | "discard" | "return" => self.jump_stmt(),
"enum" => Ok(StmtKind::Enum(self.enum_def()?)),
"typedef" => Ok(StmtKind::Typedef(self.typedef()?)),
"struct" => self.local_struct(),
_ => self.simple_stmt(),
}
}
fn if_stmt(&mut self) -> PResult<StmtKind> {
self.pos += 1;
let cond = self.paren_expr()?;
let then = Box::new(self.stmt()?);
let otherwise = if self.eat_word("else") {
Some(Box::new(self.stmt()?))
} else {
None
};
Ok(StmtKind::If {
cond,
then,
otherwise,
})
}
fn while_stmt(&mut self) -> PResult<StmtKind> {
self.pos += 1;
let cond = self.paren_expr()?;
let body = Box::new(self.stmt()?);
Ok(StmtKind::While { cond, body })
}
fn do_stmt(&mut self) -> PResult<StmtKind> {
self.pos += 1;
let body = Box::new(self.stmt()?);
if !self.eat_word("while") {
return Err(self.expected("`while`"));
}
let cond = self.paren_expr()?;
self.expect(Punct::Semi)?;
Ok(StmtKind::DoWhile { body, cond })
}
fn jump_stmt(&mut self) -> PResult<StmtKind> {
let kind = if self.eat_word("break") {
StmtKind::Break
} else if self.eat_word("continue") {
StmtKind::Continue
} else if self.eat_word("discard") {
StmtKind::Discard
} else {
self.pos += 1;
if self.at(Punct::Semi) {
StmtKind::Return(None)
} else {
StmtKind::Return(Some(self.expr()?))
}
};
self.expect(Punct::Semi)?;
Ok(kind)
}
fn local_struct(&mut self) -> PResult<StmtKind> {
let start = self.here();
let def = Box::new(self.struct_def()?);
let vars = self.struct_vars(start, &def)?;
Ok(StmtKind::Struct { def, vars })
}
fn simple_stmt(&mut self) -> PResult<StmtKind> {
if self.at_declaration() {
let decl = self.var_decl()?;
self.declare_all(&decl);
return Ok(StmtKind::Var(decl));
}
let expr = self.expr()?;
self.expect(Punct::Semi)?;
Ok(StmtKind::Expr(expr))
}
fn paren_expr(&mut self) -> PResult<Expr> {
self.expect(Punct::LParen)?;
let expr = self.expr()?;
self.expect(Punct::RParen)?;
Ok(expr)
}
fn for_stmt(&mut self) -> PResult<StmtKind> {
self.pos += 1;
self.expect(Punct::LParen)?;
let start = self.here();
let mark = self.vars.len();
let init = if self.eat(Punct::Semi) {
None
} else {
let kind = if self.at_declaration() {
let decl = self.var_decl()?;
self.declare_all(&decl);
StmtKind::Var(decl)
} else {
let expr = self.expr()?;
self.expect(Punct::Semi)?;
StmtKind::Expr(expr)
};
Some(Box::new(Stmt {
attributes: Vec::new(),
kind,
span: self.since(start),
}))
};
let cond = if self.at(Punct::Semi) {
None
} else {
Some(self.expr()?)
};
self.expect(Punct::Semi)?;
let step = if self.at(Punct::RParen) {
None
} else {
Some(self.expr()?)
};
self.expect(Punct::RParen)?;
let body = Box::new(self.stmt()?);
self.end_scope(mark);
Ok(StmtKind::For {
init,
cond,
step,
body,
})
}
fn switch_stmt(&mut self) -> PResult<StmtKind> {
self.pos += 1;
let value = self.paren_expr()?;
self.expect(Punct::LBrace)?;
let mut cases: Vec<SwitchCase> = Vec::new();
while !self.eat(Punct::RBrace) {
if self.peek().is_none() {
return Err(self.expected("`}`"));
}
let before = self.pos;
if self.at_word("case") || self.at_word("default") {
let start = self.here();
let mut labels = Vec::new();
let parsed = self.labels(&mut labels);
cases.push(SwitchCase {
labels,
stmts: Vec::new(),
span: self.since(start),
});
if parsed.is_err() {
self.recover_in_switch();
}
continue;
}
let stmt = match cases.last() {
Some(_) => self.stmt(),
None => Err(self.expected("`case` or `default`")),
};
match stmt {
Ok(stmt) => {
let case = cases.last_mut().expect("checked above");
case.span = case.span.to(stmt.span);
case.stmts.push(stmt);
}
Err(Stop) => {
self.recover_in_switch();
let at_label = self.at_word("case") || self.at_word("default");
if self.pos == before && !self.at(Punct::RBrace) && !at_label {
self.pos += 1;
}
}
}
}
Ok(StmtKind::Switch { value, cases })
}
fn labels(&mut self, labels: &mut Vec<Option<Expr>>) -> PResult<()> {
while self.at_word("case") || self.at_word("default") {
if self.eat_word("case") {
labels.push(Some(self.ternary()?));
} else {
self.pos += 1;
labels.push(None);
}
self.expect(Punct::Colon)?;
}
Ok(())
}
fn node(&mut self, kind: ExprKind, span: Span, child_depth: usize) -> PResult<Expr> {
if child_depth >= MAX_TREE_DEPTH {
return Err(self.error(
span,
format!("the expression is nested more than {MAX_TREE_DEPTH} levels deep"),
));
}
self.tree_depth = child_depth + 1;
Ok(Expr { kind, span })
}
fn expr(&mut self) -> PResult<Expr> {
let first = self.assign()?;
if !self.at(Punct::Comma) {
return Ok(first);
}
let start = first.span;
let mut deepest = self.tree_depth;
let mut list = vec![first];
while self.eat(Punct::Comma) {
list.push(self.assign()?);
deepest = deepest.max(self.tree_depth);
}
let span = self.since(start);
self.node(ExprKind::Comma(list), span, deepest)
}
fn assign(&mut self) -> PResult<Expr> {
let mut targets = Vec::new();
let mut value = self.ternary()?;
while let Some(op) = self.peek().and_then(|t| assign_op(t.kind)) {
self.pos += 1;
targets.push((value, op, self.tree_depth));
value = self.ternary()?;
}
while let Some((target, op, target_depth)) = targets.pop() {
let span = target.span.to(value.span);
let deepest = target_depth.max(self.tree_depth);
let kind = ExprKind::Assign(op, Box::new(target), Box::new(value));
value = self.node(kind, span, deepest)?;
}
Ok(value)
}
fn ternary(&mut self) -> PResult<Expr> {
let cond = self.binary(0)?;
if !self.eat(Punct::Question) {
return Ok(cond);
}
let cond_depth = self.tree_depth;
self.nested(|p| {
let then = p.expr()?;
let then_depth = p.tree_depth;
p.expect(Punct::Colon)?;
let otherwise = p.assign()?;
let deepest = cond_depth.max(then_depth).max(p.tree_depth);
let span = cond.span.to(otherwise.span);
let kind = ExprKind::Ternary(Box::new(cond), Box::new(then), Box::new(otherwise));
p.node(kind, span, deepest)
})
}
fn binary(&mut self, min: u8) -> PResult<Expr> {
let mut lhs = self.unary()?;
loop {
let lhs_depth = self.tree_depth;
let Some(TokenKind::Punct(punct)) = self.peek().map(|t| t.kind) else {
return Ok(lhs);
};
let Some((level, op)) = binary_op(punct) else {
return Ok(lhs);
};
if level < min {
return Ok(lhs);
}
self.pos += 1;
let rhs = self.binary(level + 1)?;
let deepest = lhs_depth.max(self.tree_depth);
let span = lhs.span.to(rhs.span);
lhs = self.node(
ExprKind::Binary(op, Box::new(lhs), Box::new(rhs)),
span,
deepest,
)?;
}
}
fn unary(&mut self) -> PResult<Expr> {
self.nested(Self::unary_inner)
}
fn unary_inner(&mut self) -> PResult<Expr> {
if let Some(op) = self.peek().and_then(|t| prefix_op(t.kind)) {
return self.prefix(op);
}
if self.at_cast() {
return self.cast();
}
let primary = if self.at(Punct::LParen) {
self.paren()?
} else {
self.atom()?
};
self.postfix(primary)
}
fn prefix(&mut self, op: UnaryOp) -> PResult<Expr> {
let start = self.here();
self.pos += 1;
let operand = self.unary()?;
let span = start.to(operand.span);
let depth = self.tree_depth;
self.node(ExprKind::Unary(op, Box::new(operand)), span, depth)
}
fn cast(&mut self) -> PResult<Expr> {
let start = self.here();
self.pos += 1;
let ty = self.type_ref()?;
let ty_depth = self.tree_depth;
self.expect(Punct::RParen)?;
let operand = self.unary()?;
let span = start.to(operand.span);
let depth = ty_depth.max(self.tree_depth);
self.node(ExprKind::Cast(Box::new(ty), Box::new(operand)), span, depth)
}
fn paren(&mut self) -> PResult<Expr> {
let start = self.here();
self.pos += 1;
let mut inner = self.expr()?;
self.expect(Punct::RParen)?;
inner.span = self.since(start);
Ok(inner)
}
fn at_cast(&self) -> bool {
if !self.at(Punct::LParen) {
return false;
}
let Some(end) = self.type_at(self.pos + 1) else {
return false;
};
if end == self.pos + 2
&& self
.peek_at(1)
.is_some_and(|t| self.var_count.contains_key(&t.text))
{
return false;
}
match self.tokens.get(end) {
Some(t) if t.is(Punct::RParen) => true,
Some(t) if t.is(Punct::Lt) => {
self.peek_at(1).is_some_and(|t| is_template_type(&t.text))
&& self
.after_template_args(self.pos + 2)
.and_then(|p| self.tokens.get(p))
.is_some_and(|t| t.is(Punct::RParen))
}
_ => false,
}
}
fn postfix(&mut self, mut expr: Expr) -> PResult<Expr> {
loop {
let depth = self.tree_depth;
if self.eat(Punct::Dot) {
let name = self.word()?;
let span = expr.span.to(name.span);
expr = self.node(ExprKind::Member(Box::new(expr), name), span, depth)?;
} else if self.eat(Punct::LBracket) {
let index = self.expr()?;
let deepest = depth.max(self.tree_depth);
self.expect(Punct::RBracket)?;
let span = self.since(expr.span);
expr = self.node(
ExprKind::Index(Box::new(expr), Box::new(index)),
span,
deepest,
)?;
} else if self.at(Punct::LParen) {
let args = self.call_args()?;
let deepest = depth.max(self.tree_depth);
let span = self.since(expr.span);
expr = self.node(ExprKind::Call(Box::new(expr), args), span, deepest)?;
} else if let Some(op) = self.peek().and_then(|t| postfix_op(t.kind)) {
self.pos += 1;
let span = self.since(expr.span);
expr = self.node(ExprKind::Unary(op, Box::new(expr)), span, depth)?;
} else {
return Ok(expr);
}
}
}
fn call_args(&mut self) -> PResult<Vec<Expr>> {
self.expect(Punct::LParen)?;
let mut args = Vec::new();
let mut deepest = 0;
if !self.eat(Punct::RParen) {
loop {
args.push(self.assign()?);
deepest = deepest.max(self.tree_depth);
if self.eat(Punct::RParen) {
break;
}
self.expect(Punct::Comma)?;
}
}
self.tree_depth = deepest;
Ok(args)
}
fn atom(&mut self) -> PResult<Expr> {
let Some(t) = self.peek().cloned() else {
return Err(self.expected("an expression"));
};
let span = t.site();
let literal = match t.kind {
TokenKind::Int => Some(Literal::Int(t.text.clone())),
TokenKind::Float => Some(Literal::Float(t.text.clone())),
TokenKind::Str => Some(Literal::Str(t.text.clone())),
TokenKind::Ident if t.text == "true" || t.text == "false" => {
Some(Literal::Bool(t.text == "true"))
}
_ => None,
};
if let Some(literal) = literal {
if matches!(t.kind, TokenKind::Int | TokenKind::Float) && !is_valid_number(&t.text) {
self.error(span, format!("`{}` is not a valid number", t.text));
}
self.pos += 1;
if let Literal::Str(mut text) = literal {
while let Some(next) = self.peek().filter(|t| t.kind == TokenKind::Str) {
text.pop();
text.push_str(&next.text[1..]);
self.pos += 1;
}
let span = self.since(span);
return self.node(ExprKind::Literal(Literal::Str(text)), span, 0);
}
return self.node(ExprKind::Literal(literal), span, 0);
}
let Some((name, end)) = self.qualified_at(self.pos) else {
return Err(self.expected("an expression"));
};
let next = self.tokens.get(end);
let constructor = next.is_some_and(|n| n.is(Punct::LParen))
|| (next.is_some_and(|n| n.is(Punct::Lt)) && is_template_type(&name));
if constructor && self.is_type_name(&name) {
let ty = self.type_ref()?;
let ty_depth = self.tree_depth;
if !self.at(Punct::LParen) {
return Err(self.expected("`(`"));
}
let args = self.call_args()?;
let span = self.since(span);
let depth = ty_depth.max(self.tree_depth);
return self.node(ExprKind::Construct(Box::new(ty), args), span, depth);
}
self.pos = end;
let span = self.since(span);
self.node(ExprKind::Ident(name), span, 0)
}
}
fn postfix_op(kind: TokenKind) -> Option<UnaryOp> {
match kind {
TokenKind::Punct(Punct::PlusPlus) => Some(UnaryOp::PostInc),
TokenKind::Punct(Punct::MinusMinus) => Some(UnaryOp::PostDec),
_ => None,
}
}
fn prefix_op(kind: TokenKind) -> Option<UnaryOp> {
let TokenKind::Punct(punct) = kind else {
return None;
};
Some(match punct {
Punct::Minus => UnaryOp::Neg,
Punct::Plus => UnaryOp::Plus,
Punct::Bang => UnaryOp::Not,
Punct::Tilde => UnaryOp::BitNot,
Punct::PlusPlus => UnaryOp::PreInc,
Punct::MinusMinus => UnaryOp::PreDec,
_ => return None,
})
}
fn assign_op(kind: TokenKind) -> Option<Option<BinaryOp>> {
let TokenKind::Punct(punct) = kind else {
return None;
};
Some(match punct {
Punct::Eq => None,
Punct::PlusEq => Some(BinaryOp::Add),
Punct::MinusEq => Some(BinaryOp::Sub),
Punct::StarEq => Some(BinaryOp::Mul),
Punct::SlashEq => Some(BinaryOp::Div),
Punct::PercentEq => Some(BinaryOp::Rem),
Punct::ShlEq => Some(BinaryOp::Shl),
Punct::ShrEq => Some(BinaryOp::Shr),
Punct::AmpEq => Some(BinaryOp::BitAnd),
Punct::PipeEq => Some(BinaryOp::BitOr),
Punct::CaretEq => Some(BinaryOp::BitXor),
_ => return None,
})
}
fn binary_op(punct: Punct) -> Option<(u8, BinaryOp)> {
Some(match punct {
Punct::OrOr => (0, BinaryOp::Or),
Punct::AndAnd => (1, BinaryOp::And),
Punct::Pipe => (2, BinaryOp::BitOr),
Punct::Caret => (3, BinaryOp::BitXor),
Punct::Amp => (4, BinaryOp::BitAnd),
Punct::EqEq => (5, BinaryOp::Eq),
Punct::NotEq => (5, BinaryOp::Ne),
Punct::Lt => (6, BinaryOp::Lt),
Punct::Gt => (6, BinaryOp::Gt),
Punct::LtEq => (6, BinaryOp::Le),
Punct::GtEq => (6, BinaryOp::Ge),
Punct::Shl => (7, BinaryOp::Shl),
Punct::Shr => (7, BinaryOp::Shr),
Punct::Plus => (8, BinaryOp::Add),
Punct::Minus => (8, BinaryOp::Sub),
Punct::Star => (9, BinaryOp::Mul),
Punct::Slash => (9, BinaryOp::Div),
Punct::Percent => (9, BinaryOp::Rem),
_ => return None,
})
}
#[cfg(test)]
mod tests {
use crate::{Options, parse};
#[test]
fn template_arguments_count_toward_the_tree_depth() {
let mut construct = "0".to_string();
let mut cast = "0".to_string();
for _ in 0..30 {
construct = format!("vector<float, 0+{construct}{}>(0)", "+0".repeat(250));
cast = format!("(vector<float, 0+{cast}{}>)0", "+0".repeat(250));
}
for e in [construct, cast] {
let text = format!("static float4 v = {e};");
let parsed = parse("t.hlsl", &text, Options::default());
assert!(
parsed
.diagnostics
.iter()
.any(|d| d.message.contains("the expression is nested more than")),
"{:?}",
parsed.diagnostics
);
}
}
}