Skip to main content

wgslift_syntax/
parser.rs

1//! The parser: preprocessed tokens to a syntax tree.
2//!
3//! After an error the parser skips to the end of the statement or item and goes
4//! on, so one run reports all independent errors.
5
6use std::collections::{HashMap, HashSet};
7
8use crate::ast::*;
9use crate::diagnostic::Diagnostic;
10use crate::lexer::{Punct, Token, TokenKind, is_valid_number};
11use crate::span::Span;
12
13/// The deepest nesting of expressions and statements the parser accepts.
14pub const MAX_DEPTH: usize = 64;
15/// The deepest expression tree the parser builds. Any recursive walk over a
16/// tree, `Drop` included, then stays within a small stack.
17pub const MAX_TREE_DEPTH: usize = 256;
18
19const KEYWORDS: [&str; 25] = [
20    "if",
21    "else",
22    "for",
23    "while",
24    "do",
25    "switch",
26    "case",
27    "default",
28    "break",
29    "continue",
30    "discard",
31    "return",
32    "struct",
33    "enum",
34    "namespace",
35    "typedef",
36    "cbuffer",
37    "tbuffer",
38    "true",
39    "false",
40    "technique",
41    "technique10",
42    "technique11",
43    "pass",
44    "sampler_state",
45];
46
47const SCALARS: [&str; 21] = [
48    "bool",
49    "int",
50    "uint",
51    "dword",
52    "half",
53    "float",
54    "double",
55    "min16float",
56    "min10float",
57    "min16int",
58    "min12int",
59    "min16uint",
60    "int16_t",
61    "uint16_t",
62    "int32_t",
63    "uint32_t",
64    "int64_t",
65    "uint64_t",
66    "float16_t",
67    "float32_t",
68    "float64_t",
69];
70
71/// Types that take arguments in `<>`.
72const TEMPLATE_TYPES: [&str; 28] = [
73    "vector",
74    "matrix",
75    "Texture1D",
76    "Texture1DArray",
77    "Texture2D",
78    "Texture2DArray",
79    "Texture2DMS",
80    "Texture2DMSArray",
81    "Texture3D",
82    "TextureCube",
83    "TextureCubeArray",
84    "Buffer",
85    "RWBuffer",
86    "StructuredBuffer",
87    "RWStructuredBuffer",
88    "AppendStructuredBuffer",
89    "ConsumeStructuredBuffer",
90    "RWTexture1D",
91    "RWTexture1DArray",
92    "RWTexture2D",
93    "RWTexture2DArray",
94    "RWTexture3D",
95    "ConstantBuffer",
96    "PointStream",
97    "LineStream",
98    "TriangleStream",
99    "InputPatch",
100    "OutputPatch",
101];
102
103const OTHER_TYPES: [&str; 15] = [
104    "void",
105    "string",
106    "sampler",
107    "sampler1D",
108    "sampler2D",
109    "sampler3D",
110    "samplerCUBE",
111    "SamplerState",
112    "SamplerComparisonState",
113    "texture",
114    "texture1D",
115    "texture2D",
116    "texture3D",
117    "textureCUBE",
118    "ByteAddressBuffer",
119];
120
121fn is_keyword(word: &str) -> bool {
122    KEYWORDS.contains(&word)
123}
124
125fn is_sampler_type(word: &str) -> bool {
126    word.starts_with("sampler") || word == "SamplerState" || word == "SamplerComparisonState"
127}
128
129fn is_template_type(word: &str) -> bool {
130    TEMPLATE_TYPES.contains(&word)
131}
132
133/// `word` names a type that HLSL defines, for example `float3x4` or `sampler2D`.
134pub fn is_builtin_type(word: &str) -> bool {
135    if is_template_type(word) || OTHER_TYPES.contains(&word) || word == "RWByteAddressBuffer" {
136        return true;
137    }
138    let dim = |c: u8| (b'1'..=b'4').contains(&c);
139    SCALARS.iter().any(|scalar| {
140        word.strip_prefix(scalar)
141            .is_some_and(|rest| match rest.as_bytes() {
142                [] => true,
143                [n] => dim(*n),
144                [n, b'x', m] => dim(*n) && dim(*m),
145                _ => false,
146            })
147    })
148}
149
150/// An error was reported; the caller recovers.
151struct Stop;
152
153type PResult<T> = Result<T, Stop>;
154
155/// Parses preprocessed tokens into a syntax tree. `eof` is where an error at the end
156/// of the input points: the end of the main file.
157pub fn parse_tokens(
158    mut tokens: Vec<Token>,
159    eof: Span,
160    diagnostics: &mut Vec<Diagnostic>,
161) -> TranslationUnit {
162    tokens.retain(|t| {
163        if t.kind == TokenKind::Other {
164            diagnostics.push(Diagnostic::error(
165                t.site(),
166                format!("unexpected character `{}`", t.text),
167            ));
168        }
169        t.kind != TokenKind::Other
170    });
171    let mut parser = Parser {
172        tokens,
173        pos: 0,
174        types: HashSet::new(),
175        path: Vec::new(),
176        vars: Vec::new(),
177        var_count: HashMap::new(),
178        diagnostics,
179        depth: 0,
180        tree_depth: 0,
181        eof,
182    };
183    let mut items = Vec::new();
184    while parser.pos < parser.tokens.len() {
185        let start = parser.pos;
186        if parser.item(&mut items).is_err() {
187            parser.recover(false);
188        }
189        if parser.pos == start {
190            parser.pos += 1;
191        }
192    }
193    TranslationUnit { items }
194}
195
196struct Parser<'a> {
197    tokens: Vec<Token>,
198    pos: usize,
199    /// Struct, typedef and enum names declared so far, also with the names of
200    /// the namespaces they are in, for example `S` and `N::S`.
201    types: HashSet<String>,
202    /// The namespaces and structs the parser is in, outermost first.
203    path: Vec<String>,
204    /// The variables in scope, innermost last.
205    vars: Vec<String>,
206    /// How many variables in scope have each name.
207    var_count: HashMap<String, usize>,
208    diagnostics: &'a mut Vec<Diagnostic>,
209    depth: usize,
210    /// The depth of the expression tree that was built last.
211    tree_depth: usize,
212    eof: Span,
213}
214
215impl Parser<'_> {
216    // Token access.
217
218    fn peek(&self) -> Option<&Token> {
219        self.tokens.get(self.pos)
220    }
221
222    fn peek_at(&self, n: usize) -> Option<&Token> {
223        self.tokens.get(self.pos + n)
224    }
225
226    fn at(&self, punct: Punct) -> bool {
227        self.peek().is_some_and(|t| t.is(punct))
228    }
229
230    fn at_word(&self, word: &str) -> bool {
231        self.peek().is_some_and(|t| t.is_word(word))
232    }
233
234    fn eat(&mut self, punct: Punct) -> bool {
235        let found = self.at(punct);
236        self.pos += usize::from(found);
237        found
238    }
239
240    fn eat_word(&mut self, word: &str) -> bool {
241        let found = self.at_word(word);
242        self.pos += usize::from(found);
243        found
244    }
245
246    /// Takes one `>` and returns its span. A `>>` is split, so that
247    /// `vector<vector<float, 2>>` closes twice.
248    fn eat_gt(&mut self) -> Option<Span> {
249        if self.at(Punct::Gt) {
250            let site = self.here();
251            self.pos += 1;
252            return Some(site);
253        }
254        let t = self.tokens.get_mut(self.pos).filter(|t| t.is(Punct::Shr))?;
255        let mut first = t.site();
256        if t.expanded_from.is_none() {
257            first.end = first.start + 1;
258        }
259        t.kind = TokenKind::Punct(Punct::Gt);
260        t.text = ">".to_string();
261        t.span.start += 1;
262        Some(first)
263    }
264
265    fn here(&self) -> Span {
266        self.peek().map_or(self.eof, Token::site)
267    }
268
269    fn prev(&self) -> Span {
270        self.pos
271            .checked_sub(1)
272            .and_then(|i| self.tokens.get(i))
273            .map_or(self.eof, Token::site)
274    }
275
276    fn since(&self, start: Span) -> Span {
277        start.to(self.prev())
278    }
279
280    fn error(&mut self, span: Span, message: impl Into<String>) -> Stop {
281        self.diagnostics.push(Diagnostic::error(span, message));
282        Stop
283    }
284
285    fn expected(&mut self, what: &str) -> Stop {
286        let message = match self.peek() {
287            Some(t) => format!("expected {what}, found `{}`", t.text),
288            None => format!("expected {what}, found the end of the input"),
289        };
290        let here = self.here();
291        self.error(here, message)
292    }
293
294    fn expect(&mut self, punct: Punct) -> PResult<()> {
295        if self.eat(punct) {
296            Ok(())
297        } else {
298            Err(self.expected(&format!("`{}`", punct.as_str())))
299        }
300    }
301
302    /// Runs `f` one level deeper, or reports an error past `MAX_DEPTH`.
303    fn nested<T>(&mut self, f: impl FnOnce(&mut Self) -> PResult<T>) -> PResult<T> {
304        if self.depth >= MAX_DEPTH {
305            let here = self.here();
306            return Err(self.error(
307                here,
308                format!("the code is nested more than {MAX_DEPTH} levels deep"),
309            ));
310        }
311        self.depth += 1;
312        let result = f(self);
313        self.depth -= 1;
314        result
315    }
316
317    /// Skips to the end of the statement or item: past a `;` or a `{}` block. In a
318    /// block, a `}` that closes the block stays for the block.
319    fn recover(&mut self, in_block: bool) {
320        self.skip(in_block, false);
321    }
322
323    /// Like `recover` in a block, but also stops before a `case` or `default` label.
324    fn recover_in_switch(&mut self) {
325        self.skip(true, true);
326    }
327
328    fn skip(&mut self, in_block: bool, stop_at_labels: bool) {
329        let mut depth = 0usize;
330        while let Some(t) = self.peek() {
331            if stop_at_labels && depth == 0 && (t.is_word("case") || t.is_word("default")) {
332                return;
333            }
334            if t.is(Punct::LBrace) {
335                depth += 1;
336            } else if t.is(Punct::RBrace) {
337                if depth == 0 {
338                    if !in_block {
339                        self.pos += 1;
340                    }
341                    return;
342                }
343                depth -= 1;
344                if depth == 0 {
345                    self.pos += 1;
346                    return;
347                }
348            } else if t.is(Punct::Semi) && depth == 0 {
349                self.pos += 1;
350                return;
351            }
352            self.pos += 1;
353        }
354    }
355
356    // Names and types.
357
358    fn ident(&mut self) -> PResult<Ident> {
359        match self.peek() {
360            Some(t) if t.kind == TokenKind::Ident && !is_keyword(&t.text) => {
361                let ident = Ident {
362                    name: t.text.clone(),
363                    span: t.site(),
364                };
365                self.pos += 1;
366                Ok(ident)
367            }
368            _ => Err(self.expected("a name")),
369        }
370    }
371
372    /// Any word, also a keyword: for members, swizzles and sampler states.
373    fn word(&mut self) -> PResult<Ident> {
374        match self.peek() {
375            Some(t) if t.kind == TokenKind::Ident => {
376                let ident = Ident {
377                    name: t.text.clone(),
378                    span: t.site(),
379                };
380                self.pos += 1;
381                Ok(ident)
382            }
383            _ => Err(self.expected("a name")),
384        }
385    }
386
387    fn is_type_name(&self, name: &str) -> bool {
388        is_builtin_type(name) || self.types.contains(name)
389    }
390
391    /// The name at `p` with its `::` parts, for example `N::M::x`, and the index
392    /// after it.
393    fn qualified_at(&self, mut p: usize) -> Option<(String, usize)> {
394        let is_name = |t: &Token| t.kind == TokenKind::Ident && !is_keyword(&t.text);
395        let mut name = self.tokens.get(p).filter(|t| is_name(t))?.text.clone();
396        p += 1;
397        while let (Some(sep), Some(next)) = (self.tokens.get(p), self.tokens.get(p + 1)) {
398            if !sep.is(Punct::ColonColon) || !is_name(next) {
399                break;
400            }
401            name.push_str("::");
402            name.push_str(&next.text);
403            p += 2;
404        }
405        Some((name, p))
406    }
407
408    /// If the tokens at `p` name a type, the index after the name, before any `<`.
409    fn type_at(&self, p: usize) -> Option<usize> {
410        let t = self.tokens.get(p)?;
411        if t.is_word("unsigned") || t.is_word("signed") {
412            let int = self.tokens.get(p + 1).is_some_and(|n| n.is_word("int"));
413            return Some(p + 1 + usize::from(int));
414        }
415        let (name, end) = self.qualified_at(p)?;
416        self.is_type_name(&name).then_some(end)
417    }
418
419    /// Records the name of a struct, typedef or enum, also with the names of the
420    /// enclosing namespaces and structs.
421    fn declare_type(&mut self, name: &str) {
422        let mut qualified = name.to_string();
423        self.types.insert(qualified.clone());
424        for outer in self.path.iter().rev() {
425            qualified = format!("{outer}::{qualified}");
426            self.types.insert(qualified.clone());
427        }
428    }
429
430    /// The name of a type. `unsigned int` and `unsigned` are `uint`; `signed int`
431    /// and `signed` are `int`.
432    fn type_name(&mut self) -> PResult<Ident> {
433        let start = self.here();
434        if let Some(name) = ["unsigned", "signed"].into_iter().find(|w| self.at_word(w)) {
435            self.pos += 1;
436            self.eat_word("int");
437            let name = if name == "unsigned" { "uint" } else { "int" };
438            return Ok(Ident {
439                name: name.to_string(),
440                span: self.since(start),
441            });
442        }
443        let mut name = self.ident().map_err(|_| {
444            self.diagnostics.pop();
445            self.expected("a type")
446        })?;
447        while self.at(Punct::ColonColon) {
448            self.pos += 1;
449            let part = self.ident()?;
450            name.name = format!("{}::{}", name.name, part.name);
451            name.span = name.span.to(part.span);
452        }
453        Ok(name)
454    }
455
456    fn declare(&mut self, name: &str) {
457        self.vars.push(name.to_string());
458        *self.var_count.entry(name.to_string()).or_default() += 1;
459    }
460
461    fn declare_all(&mut self, decl: &VarDecl) {
462        for d in &decl.declarators {
463            self.declare(&d.name.name);
464        }
465    }
466
467    /// Ends the scopes opened since `vars` had `mark` names.
468    fn end_scope(&mut self, mark: usize) {
469        while self.vars.len() > mark {
470            let name = self.vars.pop().expect("longer than mark");
471            if let Some(count) = self.var_count.get_mut(&name) {
472                *count -= 1;
473                if *count == 0 {
474                    self.var_count.remove(&name);
475                }
476            }
477        }
478    }
479
480    /// Parses a type. Leaves the depth of its deepest expression argument in `tree_depth`.
481    fn type_ref(&mut self) -> PResult<TypeRef> {
482        let name = self.type_name()?;
483        let mut args = Vec::new();
484        let mut span = name.span;
485        let mut deepest = 0;
486        if is_template_type(&name.name) && self.eat(Punct::Lt) {
487            let close;
488            (args, close) = self.nested(|p| {
489                let mut args = Vec::new();
490                loop {
491                    args.push(p.type_arg()?);
492                    deepest = deepest.max(p.tree_depth);
493                    if let Some(close) = p.eat_gt() {
494                        return Ok((args, close));
495                    }
496                    p.expect(Punct::Comma)?;
497                }
498            })?;
499            span = span.to(close);
500        }
501        self.tree_depth = deepest;
502        Ok(TypeRef { span, name, args })
503    }
504
505    /// One template argument: a type, a type after `unorm` or `snorm`, or a constant.
506    fn type_arg(&mut self) -> PResult<TypeArg> {
507        let mut after = self.pos;
508        while self
509            .tokens
510            .get(after)
511            .is_some_and(|t| t.is_word("unorm") || t.is_word("snorm"))
512        {
513            after += 1;
514        }
515        if self.type_at(after).is_none() {
516            // Above the comparisons and shifts, so that `>` closes the list.
517            return Ok(TypeArg::Expr(self.binary(8)?));
518        }
519        let modifiers: Vec<Modifier> = self.tokens[self.pos..after]
520            .iter()
521            .filter_map(|t| Modifier::from_word(&t.text))
522            .collect();
523        self.pos = after;
524        let ty = self.type_ref()?;
525        Ok(if modifiers.is_empty() {
526            TypeArg::Type(ty)
527        } else {
528            TypeArg::Modified(modifiers, ty)
529        })
530    }
531
532    fn modifiers(&mut self) -> Vec<Modifier> {
533        let mut modifiers = Vec::new();
534        while let (Some(t), Some(next)) = (self.peek(), self.peek_at(1)) {
535            match Modifier::from_word(&t.text) {
536                Some(m) if t.kind == TokenKind::Ident && next.kind == TokenKind::Ident => {
537                    modifiers.push(m);
538                    self.pos += 1;
539                }
540                _ => break,
541            }
542        }
543        modifiers
544    }
545
546    /// The tokens from here start a declaration: modifiers, then a type and a name.
547    fn at_declaration(&self) -> bool {
548        let mut p = self.pos;
549        while let (Some(t), Some(next)) = (self.tokens.get(p), self.tokens.get(p + 1)) {
550            if t.kind == TokenKind::Ident
551                && next.kind == TokenKind::Ident
552                && Modifier::from_word(&t.text).is_some()
553            {
554                p += 1;
555            } else {
556                break;
557            }
558        }
559        let Some((name, end)) = self.qualified_at(p) else {
560            return false;
561        };
562        p = end;
563        if is_template_type(&name) && self.tokens.get(p).is_some_and(|n| n.is(Punct::Lt)) {
564            // Skip the template arguments: `vector<float, 2> v` declares, but
565            // `vector<float, 2>(1, 2)` constructs.
566            let Some(end) = self.after_template_args(p) else {
567                return false;
568            };
569            p = end;
570        }
571        self.tokens
572            .get(p)
573            .is_some_and(|n| n.kind == TokenKind::Ident && !is_keyword(&n.text))
574    }
575
576    /// The index after the `>` that closes the `<` at `p`, if the list closes
577    /// before a `;` or a brace.
578    fn after_template_args(&self, mut p: usize) -> Option<usize> {
579        let mut depth = 0usize;
580        while let Some(n) = self.tokens.get(p) {
581            p += 1;
582            match n.kind {
583                TokenKind::Punct(Punct::Lt) => depth += 1,
584                TokenKind::Punct(Punct::Gt) => depth -= 1,
585                TokenKind::Punct(Punct::Shr) => depth = depth.saturating_sub(2),
586                TokenKind::Punct(Punct::Semi | Punct::LBrace | Punct::RBrace) => return None,
587                _ => {}
588            }
589            if depth == 0 {
590                return Some(p);
591            }
592        }
593        None
594    }
595
596    // Items.
597
598    fn item(&mut self, items: &mut Vec<Item>) -> PResult<()> {
599        if self.eat(Punct::Semi) {
600            return Ok(());
601        }
602        let start = self.here();
603        let attributes = self.attributes()?;
604        self.no_attributes_before_type(&attributes)?;
605        if self.at_word("namespace") {
606            let namespace = self.namespace()?;
607            items.push(Item::Namespace(namespace));
608            return Ok(());
609        }
610        self.other_item(start, attributes, items)
611    }
612
613    /// Any item but a namespace, after its attributes.
614    fn other_item(
615        &mut self,
616        start: Span,
617        attributes: Vec<Attribute>,
618        items: &mut Vec<Item>,
619    ) -> PResult<()> {
620        if self.at_word("struct") {
621            let def = self.struct_def()?;
622            let vars = self.struct_vars(start, &def);
623            items.push(Item::Struct(def));
624            if let Some(decl) = vars? {
625                items.push(Item::Variable(decl));
626            }
627            return Ok(());
628        }
629        if self.at_word("typedef") {
630            let typedef = self.typedef()?;
631            items.push(Item::Typedef(typedef));
632            return Ok(());
633        }
634        if self.at_word("enum") {
635            let def = self.enum_def()?;
636            items.push(Item::Enum(def));
637            return Ok(());
638        }
639        if self.at_word("cbuffer") || self.at_word("tbuffer") {
640            let buffer = self.buffer(start, attributes)?;
641            items.push(Item::Buffer(buffer));
642            return Ok(());
643        }
644        if ["technique", "technique10", "technique11"]
645            .iter()
646            .any(|w| self.at_word(w))
647        {
648            let stop = self.error(start, "effect techniques are not supported");
649            // Skip the name and the annotations; recovery then skips the body.
650            self.pos += 1;
651            if self.peek().is_some_and(|t| t.kind == TokenKind::Ident) {
652                self.pos += 1;
653            }
654            if self.at(Punct::Lt) {
655                self.annotations()?;
656            }
657            return Err(stop);
658        }
659        if let Some(word) = ["template", "class", "interface"]
660            .into_iter()
661            .find(|w| self.at_word(w))
662        {
663            return Err(self.error(start, format!("`{word}` is not supported yet")));
664        }
665        let modifiers = self.modifiers();
666        let ty = self.type_ref()?;
667        let name = self.ident()?;
668        if self.at(Punct::LParen) {
669            let mark = self.vars.len();
670            let function = self.function(start, attributes, modifiers, ty, name);
671            self.end_scope(mark);
672            items.push(Item::Function(function?));
673            return Ok(());
674        }
675        let declarators = self.declarators(name, &ty)?;
676        self.expect(Punct::Semi)?;
677        let decl = VarDecl {
678            attributes,
679            modifiers,
680            ty,
681            declarators,
682            span: self.since(start),
683        };
684        self.declare_all(&decl);
685        items.push(Item::Variable(decl));
686        Ok(())
687    }
688
689    fn struct_def(&mut self) -> PResult<StructDef> {
690        let start = self.here();
691        self.pos += 1;
692        let attributes = self.attributes()?;
693        let name = self.ident()?;
694        self.declare_type(&name.name);
695        let base = if self.eat(Punct::Colon) {
696            Some(self.type_ref()?)
697        } else {
698            None
699        };
700        self.expect(Punct::LBrace)?;
701        let mut def = StructDef {
702            attributes,
703            name,
704            base,
705            fields: Vec::new(),
706            methods: Vec::new(),
707            nested: Vec::new(),
708            span: start,
709        };
710        // The fields are in scope in the methods.
711        let mark = self.vars.len();
712        self.path.push(def.name.name.clone());
713        let parsed = self.nested(|p| p.body_list(|p| p.member(&mut def)));
714        self.path.pop();
715        self.end_scope(mark);
716        parsed?;
717        def.span = self.since(start);
718        Ok(def)
719    }
720
721    /// The variables after a struct definition, through the `;`.
722    fn struct_vars(&mut self, start: Span, def: &StructDef) -> PResult<Option<VarDecl>> {
723        if self.eat(Punct::Semi) {
724            return Ok(None);
725        }
726        let ty = TypeRef {
727            name: def.name.clone(),
728            args: Vec::new(),
729            span: def.name.span,
730        };
731        let first = self.ident()?;
732        let declarators = self.declarators(first, &ty)?;
733        self.expect(Punct::Semi)?;
734        let decl = VarDecl {
735            attributes: Vec::new(),
736            modifiers: Vec::new(),
737            ty,
738            declarators,
739            span: self.since(start),
740        };
741        self.declare_all(&decl);
742        Ok(Some(decl))
743    }
744
745    /// Reports attributes before `struct`, `typedef`, `enum` or `namespace`.
746    fn no_attributes_before_type(&mut self, attributes: &[Attribute]) -> PResult<()> {
747        match attributes.first() {
748            Some(a)
749                if ["struct", "typedef", "enum", "namespace"]
750                    .iter()
751                    .any(|w| self.at_word(w)) =>
752            {
753                Err(self.error(a.span, "attributes are not allowed here"))
754            }
755            _ => Ok(()),
756        }
757    }
758
759    /// One field, method, struct, enum or typedef in a struct body.
760    fn member(&mut self, def: &mut StructDef) -> PResult<()> {
761        let start = self.here();
762        let attributes = self.attributes()?;
763        self.no_attributes_before_type(&attributes)?;
764        if self.at_word("struct") {
765            let inner = self.struct_def()?;
766            let vars = self.struct_vars(start, &inner);
767            def.nested.push(Item::Struct(inner));
768            def.fields.extend(vars?);
769            return Ok(());
770        }
771        self.other_member(start, attributes, def)
772    }
773
774    /// A field, method, enum or typedef in a struct body, after its attributes.
775    fn other_member(
776        &mut self,
777        start: Span,
778        attributes: Vec<Attribute>,
779        def: &mut StructDef,
780    ) -> PResult<()> {
781        if self.at_word("enum") {
782            def.nested.push(Item::Enum(self.enum_def()?));
783            return Ok(());
784        }
785        if self.at_word("typedef") {
786            def.nested.push(Item::Typedef(self.typedef()?));
787            return Ok(());
788        }
789        let modifiers = self.modifiers();
790        let ty = self.type_ref()?;
791        let name = self.ident()?;
792        if self.at(Punct::LParen) {
793            let mark = self.vars.len();
794            let method = self.function(start, attributes, modifiers, ty, name);
795            self.end_scope(mark);
796            def.methods.push(method?);
797            return Ok(());
798        }
799        let declarators = self.declarators(name, &ty)?;
800        self.expect(Punct::Semi)?;
801        let decl = VarDecl {
802            attributes,
803            modifiers,
804            ty,
805            declarators,
806            span: self.since(start),
807        };
808        self.declare_all(&decl);
809        def.fields.push(decl);
810        Ok(())
811    }
812
813    /// `namespace [Name] { items }`.
814    fn namespace(&mut self) -> PResult<Namespace> {
815        let start = self.here();
816        self.pos += 1;
817        let name = if self.at(Punct::LBrace) {
818            None
819        } else {
820            Some(self.ident()?)
821        };
822        self.expect(Punct::LBrace)?;
823        if let Some(name) = &name {
824            self.path.push(name.name.clone());
825        }
826        let mut items = Vec::new();
827        let parsed = self.nested(|p| p.body_list(|p| p.item(&mut items)));
828        if name.is_some() {
829            self.path.pop();
830        }
831        parsed?;
832        Ok(Namespace {
833            name,
834            items,
835            span: self.since(start),
836        })
837    }
838
839    /// Runs `item` for each entry of a `{}` body after the `{`, through the `}`.
840    /// After an error it goes on at the next entry.
841    fn body_list<T>(&mut self, mut item: impl FnMut(&mut Self) -> PResult<T>) -> PResult<Vec<T>> {
842        let mut list = Vec::new();
843        while !self.eat(Punct::RBrace) {
844            if self.peek().is_none() {
845                return Err(self.expected("`}`"));
846            }
847            let before = self.pos;
848            match item(self) {
849                Ok(entry) => list.push(entry),
850                Err(Stop) => {
851                    self.recover(true);
852                    if self.pos == before && !self.at(Punct::RBrace) {
853                        self.pos += 1;
854                    }
855                }
856            }
857        }
858        Ok(list)
859    }
860
861    /// The declarations of a buffer body, through the `}`.
862    fn members(&mut self) -> PResult<Vec<VarDecl>> {
863        self.body_list(Self::var_decl)
864    }
865
866    fn typedef(&mut self) -> PResult<Typedef> {
867        let start = self.here();
868        self.pos += 1;
869        let modifiers = self.modifiers();
870        let ty = self.type_ref()?;
871        let mut names = Vec::new();
872        loop {
873            let name = self.ident()?;
874            self.declare_type(&name.name);
875            let array = self.array_dims()?;
876            names.push((name, array));
877            if !self.eat(Punct::Comma) {
878                break;
879            }
880        }
881        self.expect(Punct::Semi)?;
882        Ok(Typedef {
883            modifiers,
884            ty,
885            names,
886            span: self.since(start),
887        })
888    }
889
890    /// `enum [class] [Name] [: Type] { A [= value], ... };`. Unscoped enumerators
891    /// are names in the enclosing scope.
892    fn enum_def(&mut self) -> PResult<EnumDef> {
893        let start = self.here();
894        self.pos += 1;
895        let scoped = self.eat_word("class");
896        let name = if scoped || !(self.at(Punct::LBrace) || self.at(Punct::Colon)) {
897            let name = self.ident()?;
898            self.declare_type(&name.name);
899            Some(name)
900        } else {
901            None
902        };
903        let base = if self.eat(Punct::Colon) {
904            Some(self.type_ref()?)
905        } else {
906            None
907        };
908        self.expect(Punct::LBrace)?;
909        let mut enumerators = Vec::new();
910        while !self.eat(Punct::RBrace) {
911            let name = self.ident()?;
912            let value = if self.eat(Punct::Eq) {
913                Some(self.ternary()?)
914            } else {
915                None
916            };
917            enumerators.push(Enumerator {
918                span: self.since(name.span),
919                name,
920                value,
921            });
922            if !self.eat(Punct::Comma) {
923                self.expect(Punct::RBrace)?;
924                break;
925            }
926        }
927        self.expect(Punct::Semi)?;
928        if !scoped {
929            for e in &enumerators {
930                self.declare(&e.name.name);
931            }
932        }
933        Ok(EnumDef {
934            scoped,
935            name,
936            base,
937            enumerators,
938            span: self.since(start),
939        })
940    }
941
942    fn buffer(&mut self, start: Span, attributes: Vec<Attribute>) -> PResult<BufferBlock> {
943        let kind = if self.eat_word("cbuffer") {
944            BufferKind::Constant
945        } else {
946            self.pos += 1;
947            BufferKind::Texture
948        };
949        let name = self.ident()?;
950        let bindings = self.bindings()?;
951        self.expect(Punct::LBrace)?;
952        let members = self.members()?;
953        for member in &members {
954            self.declare_all(member);
955        }
956        self.eat(Punct::Semi);
957        Ok(BufferBlock {
958            attributes,
959            kind,
960            name,
961            bindings,
962            members,
963            span: self.since(start),
964        })
965    }
966
967    fn function(
968        &mut self,
969        start: Span,
970        attributes: Vec<Attribute>,
971        modifiers: Vec<Modifier>,
972        return_type: TypeRef,
973        name: Ident,
974    ) -> PResult<Function> {
975        self.expect(Punct::LParen)?;
976        let mut params = Vec::new();
977        if self.at_word("void") && self.peek_at(1).is_some_and(|t| t.is(Punct::RParen)) {
978            self.pos += 1;
979        }
980        if !self.eat(Punct::RParen) {
981            loop {
982                params.push(self.param()?);
983                if self.eat(Punct::RParen) {
984                    break;
985                }
986                self.expect(Punct::Comma)?;
987            }
988        }
989        let return_bindings = self.bindings()?;
990        let body = if self.eat(Punct::Semi) {
991            None
992        } else {
993            Some(self.block()?)
994        };
995        Ok(Function {
996            attributes,
997            modifiers,
998            return_type,
999            name,
1000            params,
1001            return_bindings,
1002            body,
1003            span: self.since(start),
1004        })
1005    }
1006
1007    fn param(&mut self) -> PResult<Param> {
1008        let start = self.here();
1009        let attributes = self.attributes()?;
1010        let modifiers = self.modifiers();
1011        let ty = self.type_ref()?;
1012        let name = match self.peek() {
1013            Some(t) if t.kind == TokenKind::Ident && !is_keyword(&t.text) => Some(self.ident()?),
1014            _ => None,
1015        };
1016        if let Some(name) = &name {
1017            self.declare(&name.name);
1018        }
1019        let array = self.array_dims()?;
1020        let bindings = self.bindings()?;
1021        let default = if self.eat(Punct::Eq) {
1022            Some(self.assign()?)
1023        } else {
1024            None
1025        };
1026        Ok(Param {
1027            attributes,
1028            modifiers,
1029            ty,
1030            name,
1031            array,
1032            bindings,
1033            default,
1034            span: self.since(start),
1035        })
1036    }
1037
1038    /// Attributes in `[]`, and lists of them in `[[]]`.
1039    fn attributes(&mut self) -> PResult<Vec<Attribute>> {
1040        let mut attributes = Vec::new();
1041        while self.at(Punct::LBracket) {
1042            let start = self.here();
1043            self.pos += 1;
1044            let double = self.eat(Punct::LBracket);
1045            let first = attributes.len();
1046            loop {
1047                let mut name = self.word()?;
1048                while self.eat(Punct::ColonColon) {
1049                    let part = self.word()?;
1050                    name.name = format!("{}::{}", name.name, part.name);
1051                    name.span = name.span.to(part.span);
1052                }
1053                let args = if self.at(Punct::LParen) {
1054                    self.call_args()?
1055                } else {
1056                    Vec::new()
1057                };
1058                attributes.push(Attribute {
1059                    span: self.since(name.span),
1060                    name,
1061                    args,
1062                });
1063                if !(double && self.eat(Punct::Comma)) {
1064                    break;
1065                }
1066            }
1067            self.expect(Punct::RBracket)?;
1068            if double {
1069                self.expect(Punct::RBracket)?;
1070            }
1071            if let [alone] = &mut attributes[first..] {
1072                alone.span = self.since(start);
1073            }
1074        }
1075        Ok(attributes)
1076    }
1077
1078    // Declarations.
1079
1080    fn var_decl(&mut self) -> PResult<VarDecl> {
1081        let start = self.here();
1082        let attributes = self.attributes()?;
1083        let modifiers = self.modifiers();
1084        let ty = self.type_ref()?;
1085        let first = self.ident()?;
1086        let declarators = self.declarators(first, &ty)?;
1087        self.expect(Punct::Semi)?;
1088        Ok(VarDecl {
1089            attributes,
1090            modifiers,
1091            ty,
1092            declarators,
1093            span: self.since(start),
1094        })
1095    }
1096
1097    fn declarators(&mut self, first: Ident, ty: &TypeRef) -> PResult<Vec<Declarator>> {
1098        let mut declarators = vec![self.declarator(first, ty)?];
1099        while self.eat(Punct::Comma) {
1100            let name = self.ident()?;
1101            declarators.push(self.declarator(name, ty)?);
1102        }
1103        Ok(declarators)
1104    }
1105
1106    fn declarator(&mut self, name: Ident, ty: &TypeRef) -> PResult<Declarator> {
1107        let array = self.array_dims()?;
1108        let bindings = self.bindings()?;
1109        let annotations = if self.at(Punct::Lt) {
1110            Some(self.annotations()?)
1111        } else {
1112            None
1113        };
1114        let init = if self.eat(Punct::Eq) {
1115            Some(self.initializer()?)
1116        } else if self.at(Punct::LBrace) && is_sampler_type(&ty.name.name) {
1117            // The D3D10 form: `SamplerState s { Filter = ...; };`
1118            let start = self.here();
1119            self.pos += 1;
1120            let states = self.body_list(Self::state_assignment)?;
1121            Some(Initializer::SamplerState(states, self.since(start)))
1122        } else {
1123            None
1124        };
1125        Ok(Declarator {
1126            span: self.since(name.span),
1127            name,
1128            array,
1129            bindings,
1130            annotations,
1131            init,
1132        })
1133    }
1134
1135    fn array_dims(&mut self) -> PResult<Vec<Option<Expr>>> {
1136        let mut dims = Vec::new();
1137        while self.eat(Punct::LBracket) {
1138            if self.eat(Punct::RBracket) {
1139                dims.push(None);
1140            } else {
1141                dims.push(Some(self.expr()?));
1142                self.expect(Punct::RBracket)?;
1143            }
1144        }
1145        Ok(dims)
1146    }
1147
1148    fn bindings(&mut self) -> PResult<Bindings> {
1149        let mut bindings = Bindings::default();
1150        while self.eat(Punct::Colon) {
1151            let start = self.here();
1152            if self.eat_word("register") {
1153                self.expect(Punct::LParen)?;
1154                let mut words = Vec::new();
1155                // The number of words up to the one with the `[...]`, and its value.
1156                let mut subscript = None;
1157                loop {
1158                    words.push(self.word()?);
1159                    if self.eat(Punct::LBracket) {
1160                        subscript = Some((words.len(), self.expr()?));
1161                        self.expect(Punct::RBracket)?;
1162                    }
1163                    if words.len() == 3 || !self.eat(Punct::Comma) {
1164                        break;
1165                    }
1166                }
1167                self.expect(Punct::RParen)?;
1168                let is_space = |w: &Ident| {
1169                    w.name
1170                        .strip_prefix("space")
1171                        .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
1172                };
1173                let space = match words.last() {
1174                    Some(last) if words.len() > 1 && is_space(last) => words.pop(),
1175                    _ => None,
1176                };
1177                let slot_at = words.len();
1178                let slot = words.pop().expect("one word at least");
1179                let profile = words.pop();
1180                if !words.is_empty() {
1181                    return Err(self.error(self.since(start), "too many words in `register(...)`"));
1182                }
1183                let subcomponent = match subscript {
1184                    Some((at, index)) if at == slot_at => Some(index),
1185                    Some((_, index)) => {
1186                        return Err(self.error(index.span, "only the register can have a `[...]`"));
1187                    }
1188                    None => None,
1189                };
1190                bindings.registers.push(Register {
1191                    profile,
1192                    slot,
1193                    subcomponent,
1194                    space,
1195                    span: self.since(start),
1196                });
1197            } else if self.eat_word("packoffset") {
1198                self.expect(Punct::LParen)?;
1199                let slot = self.word()?;
1200                let component = if self.eat(Punct::Dot) {
1201                    Some(self.word()?)
1202                } else {
1203                    None
1204                };
1205                self.expect(Punct::RParen)?;
1206                let span = self.since(start);
1207                if bindings.packoffset.is_some() {
1208                    self.error(span, "a declaration can have only one `packoffset`");
1209                } else {
1210                    bindings.packoffset = Some(PackOffset {
1211                        slot,
1212                        component,
1213                        span,
1214                    });
1215                }
1216            } else {
1217                let semantic = self.word()?;
1218                if bindings.semantic.is_some() {
1219                    self.error(semantic.span, "a declaration can have only one semantic");
1220                } else {
1221                    bindings.semantic = Some(semantic);
1222                }
1223            }
1224        }
1225        Ok(bindings)
1226    }
1227
1228    /// Skips an annotation block `<...>` and returns its span. Each entry ends in
1229    /// `;`, so only a `>` where an entry would start closes the block.
1230    fn annotations(&mut self) -> PResult<Span> {
1231        let start = self.here();
1232        self.pos += 1;
1233        let mut depth = 0usize;
1234        let mut entry_start = true;
1235        while let Some(t) = self.peek() {
1236            let kind = t.kind;
1237            self.pos += 1;
1238            match kind {
1239                TokenKind::Punct(Punct::Gt) if entry_start => return Ok(self.since(start)),
1240                TokenKind::Punct(Punct::LParen | Punct::LBracket | Punct::LBrace) => depth += 1,
1241                TokenKind::Punct(Punct::RParen | Punct::RBracket | Punct::RBrace) => {
1242                    depth = depth.saturating_sub(1);
1243                }
1244                _ => {}
1245            }
1246            entry_start = depth == 0 && kind == TokenKind::Punct(Punct::Semi);
1247        }
1248        Err(self.expected("`>` to close the annotations"))
1249    }
1250
1251    fn initializer(&mut self) -> PResult<Initializer> {
1252        self.nested(|p| {
1253            let start = p.here();
1254            if p.eat(Punct::LBrace) {
1255                let mut list = Vec::new();
1256                while !p.eat(Punct::RBrace) {
1257                    list.push(p.initializer()?);
1258                    if !p.eat(Punct::Comma) {
1259                        p.expect(Punct::RBrace)?;
1260                        break;
1261                    }
1262                }
1263                return Ok(Initializer::List(list, p.since(start)));
1264            }
1265            if p.eat_word("sampler_state") {
1266                p.expect(Punct::LBrace)?;
1267                let states = p.body_list(Self::state_assignment)?;
1268                return Ok(Initializer::SamplerState(states, p.since(start)));
1269            }
1270            Ok(Initializer::Expr(p.assign()?))
1271        })
1272    }
1273
1274    /// `Name = value;` in a sampler state block.
1275    fn state_assignment(&mut self) -> PResult<StateAssignment> {
1276        let name = self.word()?;
1277        self.expect(Punct::Eq)?;
1278        let value = if self.at(Punct::Lt) {
1279            let open = self.here();
1280            self.pos += 1;
1281            let texture = self.ident()?;
1282            if self.eat_gt().is_none() {
1283                return Err(self.expected("`>`"));
1284            }
1285            Expr {
1286                kind: ExprKind::Ident(texture.name),
1287                span: self.since(open),
1288            }
1289        } else {
1290            self.assign()?
1291        };
1292        self.expect(Punct::Semi)?;
1293        Ok(StateAssignment {
1294            span: self.since(name.span),
1295            name,
1296            value,
1297        })
1298    }
1299
1300    // Statements.
1301
1302    fn block(&mut self) -> PResult<Block> {
1303        let start = self.here();
1304        self.expect(Punct::LBrace)?;
1305        let mark = self.vars.len();
1306        let mut stmts = Vec::new();
1307        while !self.at(Punct::RBrace) {
1308            if self.peek().is_none() {
1309                return Err(self.expected("`}`"));
1310            }
1311            let before = self.pos;
1312            match self.stmt() {
1313                Ok(stmt) => stmts.push(stmt),
1314                Err(Stop) => self.recover(true),
1315            }
1316            if self.pos == before {
1317                self.pos += 1;
1318            }
1319        }
1320        self.pos += 1;
1321        self.end_scope(mark);
1322        Ok(Block {
1323            stmts,
1324            span: self.since(start),
1325        })
1326    }
1327
1328    fn stmt(&mut self) -> PResult<Stmt> {
1329        self.nested(Self::stmt_inner)
1330    }
1331
1332    fn stmt_inner(&mut self) -> PResult<Stmt> {
1333        let start = self.here();
1334        let attributes = self.attributes()?;
1335        let kind = self.stmt_kind()?;
1336        Ok(Stmt {
1337            attributes,
1338            kind,
1339            span: self.since(start),
1340        })
1341    }
1342
1343    fn stmt_kind(&mut self) -> PResult<StmtKind> {
1344        if self.at(Punct::LBrace) {
1345            return Ok(StmtKind::Block(self.block()?));
1346        }
1347        if self.eat(Punct::Semi) {
1348            return Ok(StmtKind::Empty);
1349        }
1350        let word = self
1351            .peek()
1352            .filter(|t| t.kind == TokenKind::Ident)
1353            .map(|t| t.text.clone())
1354            .unwrap_or_default();
1355        match word.as_str() {
1356            "if" => self.if_stmt(),
1357            "for" => self.for_stmt(),
1358            "while" => self.while_stmt(),
1359            "do" => self.do_stmt(),
1360            "switch" => self.switch_stmt(),
1361            "break" | "continue" | "discard" | "return" => self.jump_stmt(),
1362            "enum" => Ok(StmtKind::Enum(self.enum_def()?)),
1363            "typedef" => Ok(StmtKind::Typedef(self.typedef()?)),
1364            "struct" => self.local_struct(),
1365            _ => self.simple_stmt(),
1366        }
1367    }
1368
1369    fn if_stmt(&mut self) -> PResult<StmtKind> {
1370        self.pos += 1;
1371        let cond = self.paren_expr()?;
1372        let then = Box::new(self.stmt()?);
1373        let otherwise = if self.eat_word("else") {
1374            Some(Box::new(self.stmt()?))
1375        } else {
1376            None
1377        };
1378        Ok(StmtKind::If {
1379            cond,
1380            then,
1381            otherwise,
1382        })
1383    }
1384
1385    fn while_stmt(&mut self) -> PResult<StmtKind> {
1386        self.pos += 1;
1387        let cond = self.paren_expr()?;
1388        let body = Box::new(self.stmt()?);
1389        Ok(StmtKind::While { cond, body })
1390    }
1391
1392    fn do_stmt(&mut self) -> PResult<StmtKind> {
1393        self.pos += 1;
1394        let body = Box::new(self.stmt()?);
1395        if !self.eat_word("while") {
1396            return Err(self.expected("`while`"));
1397        }
1398        let cond = self.paren_expr()?;
1399        self.expect(Punct::Semi)?;
1400        Ok(StmtKind::DoWhile { body, cond })
1401    }
1402
1403    fn jump_stmt(&mut self) -> PResult<StmtKind> {
1404        let kind = if self.eat_word("break") {
1405            StmtKind::Break
1406        } else if self.eat_word("continue") {
1407            StmtKind::Continue
1408        } else if self.eat_word("discard") {
1409            StmtKind::Discard
1410        } else {
1411            self.pos += 1;
1412            if self.at(Punct::Semi) {
1413                StmtKind::Return(None)
1414            } else {
1415                StmtKind::Return(Some(self.expr()?))
1416            }
1417        };
1418        self.expect(Punct::Semi)?;
1419        Ok(kind)
1420    }
1421
1422    fn local_struct(&mut self) -> PResult<StmtKind> {
1423        let start = self.here();
1424        let def = Box::new(self.struct_def()?);
1425        let vars = self.struct_vars(start, &def)?;
1426        Ok(StmtKind::Struct { def, vars })
1427    }
1428
1429    /// A declaration or an expression statement.
1430    fn simple_stmt(&mut self) -> PResult<StmtKind> {
1431        if self.at_declaration() {
1432            let decl = self.var_decl()?;
1433            self.declare_all(&decl);
1434            return Ok(StmtKind::Var(decl));
1435        }
1436        let expr = self.expr()?;
1437        self.expect(Punct::Semi)?;
1438        Ok(StmtKind::Expr(expr))
1439    }
1440
1441    fn paren_expr(&mut self) -> PResult<Expr> {
1442        self.expect(Punct::LParen)?;
1443        let expr = self.expr()?;
1444        self.expect(Punct::RParen)?;
1445        Ok(expr)
1446    }
1447
1448    fn for_stmt(&mut self) -> PResult<StmtKind> {
1449        self.pos += 1;
1450        self.expect(Punct::LParen)?;
1451        let start = self.here();
1452        let mark = self.vars.len();
1453        let init = if self.eat(Punct::Semi) {
1454            None
1455        } else {
1456            let kind = if self.at_declaration() {
1457                let decl = self.var_decl()?;
1458                self.declare_all(&decl);
1459                StmtKind::Var(decl)
1460            } else {
1461                let expr = self.expr()?;
1462                self.expect(Punct::Semi)?;
1463                StmtKind::Expr(expr)
1464            };
1465            Some(Box::new(Stmt {
1466                attributes: Vec::new(),
1467                kind,
1468                span: self.since(start),
1469            }))
1470        };
1471        let cond = if self.at(Punct::Semi) {
1472            None
1473        } else {
1474            Some(self.expr()?)
1475        };
1476        self.expect(Punct::Semi)?;
1477        let step = if self.at(Punct::RParen) {
1478            None
1479        } else {
1480            Some(self.expr()?)
1481        };
1482        self.expect(Punct::RParen)?;
1483        let body = Box::new(self.stmt()?);
1484        self.end_scope(mark);
1485        Ok(StmtKind::For {
1486            init,
1487            cond,
1488            step,
1489            body,
1490        })
1491    }
1492
1493    fn switch_stmt(&mut self) -> PResult<StmtKind> {
1494        self.pos += 1;
1495        let value = self.paren_expr()?;
1496        self.expect(Punct::LBrace)?;
1497        let mut cases: Vec<SwitchCase> = Vec::new();
1498        while !self.eat(Punct::RBrace) {
1499            if self.peek().is_none() {
1500                return Err(self.expected("`}`"));
1501            }
1502            let before = self.pos;
1503            if self.at_word("case") || self.at_word("default") {
1504                let start = self.here();
1505                let mut labels = Vec::new();
1506                let parsed = self.labels(&mut labels);
1507                // A case with a bad label stays, so that its statements have a place.
1508                cases.push(SwitchCase {
1509                    labels,
1510                    stmts: Vec::new(),
1511                    span: self.since(start),
1512                });
1513                if parsed.is_err() {
1514                    self.recover_in_switch();
1515                }
1516                continue;
1517            }
1518            let stmt = match cases.last() {
1519                Some(_) => self.stmt(),
1520                None => Err(self.expected("`case` or `default`")),
1521            };
1522            match stmt {
1523                Ok(stmt) => {
1524                    let case = cases.last_mut().expect("checked above");
1525                    case.span = case.span.to(stmt.span);
1526                    case.stmts.push(stmt);
1527                }
1528                Err(Stop) => {
1529                    self.recover_in_switch();
1530                    let at_label = self.at_word("case") || self.at_word("default");
1531                    if self.pos == before && !self.at(Punct::RBrace) && !at_label {
1532                        self.pos += 1;
1533                    }
1534                }
1535            }
1536        }
1537        Ok(StmtKind::Switch { value, cases })
1538    }
1539
1540    /// One or more `case value:` and `default:` labels.
1541    fn labels(&mut self, labels: &mut Vec<Option<Expr>>) -> PResult<()> {
1542        while self.at_word("case") || self.at_word("default") {
1543            if self.eat_word("case") {
1544                labels.push(Some(self.ternary()?));
1545            } else {
1546                self.pos += 1;
1547                labels.push(None);
1548            }
1549            self.expect(Punct::Colon)?;
1550        }
1551        Ok(())
1552    }
1553
1554    // Expressions. Each function that returns an expression leaves the depth of
1555    // its tree in `tree_depth`, and `node` builds every node and checks the limit.
1556
1557    /// Builds a node one level above its deepest child, of depth `child_depth`.
1558    fn node(&mut self, kind: ExprKind, span: Span, child_depth: usize) -> PResult<Expr> {
1559        if child_depth >= MAX_TREE_DEPTH {
1560            return Err(self.error(
1561                span,
1562                format!("the expression is nested more than {MAX_TREE_DEPTH} levels deep"),
1563            ));
1564        }
1565        self.tree_depth = child_depth + 1;
1566        Ok(Expr { kind, span })
1567    }
1568
1569    fn expr(&mut self) -> PResult<Expr> {
1570        let first = self.assign()?;
1571        if !self.at(Punct::Comma) {
1572            return Ok(first);
1573        }
1574        let start = first.span;
1575        let mut deepest = self.tree_depth;
1576        let mut list = vec![first];
1577        while self.eat(Punct::Comma) {
1578            list.push(self.assign()?);
1579            deepest = deepest.max(self.tree_depth);
1580        }
1581        let span = self.since(start);
1582        self.node(ExprKind::Comma(list), span, deepest)
1583    }
1584
1585    /// Assignment is right-associative. A loop collects the chain, so that
1586    /// `a = b = c = ...` uses no stack per link.
1587    fn assign(&mut self) -> PResult<Expr> {
1588        let mut targets = Vec::new();
1589        let mut value = self.ternary()?;
1590        while let Some(op) = self.peek().and_then(|t| assign_op(t.kind)) {
1591            self.pos += 1;
1592            targets.push((value, op, self.tree_depth));
1593            value = self.ternary()?;
1594        }
1595        while let Some((target, op, target_depth)) = targets.pop() {
1596            let span = target.span.to(value.span);
1597            let deepest = target_depth.max(self.tree_depth);
1598            let kind = ExprKind::Assign(op, Box::new(target), Box::new(value));
1599            value = self.node(kind, span, deepest)?;
1600        }
1601        Ok(value)
1602    }
1603
1604    fn ternary(&mut self) -> PResult<Expr> {
1605        let cond = self.binary(0)?;
1606        if !self.eat(Punct::Question) {
1607            return Ok(cond);
1608        }
1609        let cond_depth = self.tree_depth;
1610        self.nested(|p| {
1611            let then = p.expr()?;
1612            let then_depth = p.tree_depth;
1613            p.expect(Punct::Colon)?;
1614            let otherwise = p.assign()?;
1615            let deepest = cond_depth.max(then_depth).max(p.tree_depth);
1616            let span = cond.span.to(otherwise.span);
1617            let kind = ExprKind::Ternary(Box::new(cond), Box::new(then), Box::new(otherwise));
1618            p.node(kind, span, deepest)
1619        })
1620    }
1621
1622    fn binary(&mut self, min: u8) -> PResult<Expr> {
1623        let mut lhs = self.unary()?;
1624        loop {
1625            let lhs_depth = self.tree_depth;
1626            let Some(TokenKind::Punct(punct)) = self.peek().map(|t| t.kind) else {
1627                return Ok(lhs);
1628            };
1629            let Some((level, op)) = binary_op(punct) else {
1630                return Ok(lhs);
1631            };
1632            if level < min {
1633                return Ok(lhs);
1634            }
1635            self.pos += 1;
1636            let rhs = self.binary(level + 1)?;
1637            let deepest = lhs_depth.max(self.tree_depth);
1638            let span = lhs.span.to(rhs.span);
1639            lhs = self.node(
1640                ExprKind::Binary(op, Box::new(lhs), Box::new(rhs)),
1641                span,
1642                deepest,
1643            )?;
1644        }
1645    }
1646
1647    // The functions on the recursive path stay small and send the bulky work to
1648    // helpers that return first: a debug build gives every local its own stack slot.
1649
1650    fn unary(&mut self) -> PResult<Expr> {
1651        self.nested(Self::unary_inner)
1652    }
1653
1654    fn unary_inner(&mut self) -> PResult<Expr> {
1655        if let Some(op) = self.peek().and_then(|t| prefix_op(t.kind)) {
1656            return self.prefix(op);
1657        }
1658        if self.at_cast() {
1659            return self.cast();
1660        }
1661        let primary = if self.at(Punct::LParen) {
1662            self.paren()?
1663        } else {
1664            self.atom()?
1665        };
1666        self.postfix(primary)
1667    }
1668
1669    fn prefix(&mut self, op: UnaryOp) -> PResult<Expr> {
1670        let start = self.here();
1671        self.pos += 1;
1672        let operand = self.unary()?;
1673        let span = start.to(operand.span);
1674        let depth = self.tree_depth;
1675        self.node(ExprKind::Unary(op, Box::new(operand)), span, depth)
1676    }
1677
1678    fn cast(&mut self) -> PResult<Expr> {
1679        let start = self.here();
1680        self.pos += 1;
1681        let ty = self.type_ref()?;
1682        let ty_depth = self.tree_depth;
1683        self.expect(Punct::RParen)?;
1684        let operand = self.unary()?;
1685        let span = start.to(operand.span);
1686        let depth = ty_depth.max(self.tree_depth);
1687        self.node(ExprKind::Cast(Box::new(ty), Box::new(operand)), span, depth)
1688    }
1689
1690    fn paren(&mut self) -> PResult<Expr> {
1691        let start = self.here();
1692        self.pos += 1;
1693        let mut inner = self.expr()?;
1694        self.expect(Punct::RParen)?;
1695        inner.span = self.since(start);
1696        Ok(inner)
1697    }
1698
1699    /// `(type)` comes next: a type name in parentheses. A variable in scope hides
1700    /// a type of the same name.
1701    fn at_cast(&self) -> bool {
1702        if !self.at(Punct::LParen) {
1703            return false;
1704        }
1705        let Some(end) = self.type_at(self.pos + 1) else {
1706            return false;
1707        };
1708        if end == self.pos + 2
1709            && self
1710                .peek_at(1)
1711                .is_some_and(|t| self.var_count.contains_key(&t.text))
1712        {
1713            return false;
1714        }
1715        match self.tokens.get(end) {
1716            Some(t) if t.is(Punct::RParen) => true,
1717            // `(vector<float, 2>)x` casts, `(vector<float, 2>(1, 2))` constructs.
1718            Some(t) if t.is(Punct::Lt) => {
1719                self.peek_at(1).is_some_and(|t| is_template_type(&t.text))
1720                    && self
1721                        .after_template_args(self.pos + 2)
1722                        .and_then(|p| self.tokens.get(p))
1723                        .is_some_and(|t| t.is(Punct::RParen))
1724            }
1725            _ => false,
1726        }
1727    }
1728
1729    fn postfix(&mut self, mut expr: Expr) -> PResult<Expr> {
1730        loop {
1731            let depth = self.tree_depth;
1732            if self.eat(Punct::Dot) {
1733                let name = self.word()?;
1734                let span = expr.span.to(name.span);
1735                expr = self.node(ExprKind::Member(Box::new(expr), name), span, depth)?;
1736            } else if self.eat(Punct::LBracket) {
1737                let index = self.expr()?;
1738                let deepest = depth.max(self.tree_depth);
1739                self.expect(Punct::RBracket)?;
1740                let span = self.since(expr.span);
1741                expr = self.node(
1742                    ExprKind::Index(Box::new(expr), Box::new(index)),
1743                    span,
1744                    deepest,
1745                )?;
1746            } else if self.at(Punct::LParen) {
1747                let args = self.call_args()?;
1748                let deepest = depth.max(self.tree_depth);
1749                let span = self.since(expr.span);
1750                expr = self.node(ExprKind::Call(Box::new(expr), args), span, deepest)?;
1751            } else if let Some(op) = self.peek().and_then(|t| postfix_op(t.kind)) {
1752                self.pos += 1;
1753                let span = self.since(expr.span);
1754                expr = self.node(ExprKind::Unary(op, Box::new(expr)), span, depth)?;
1755            } else {
1756                return Ok(expr);
1757            }
1758        }
1759    }
1760
1761    /// Parses `(a, b, ...)`. Leaves the depth of the deepest argument in `tree_depth`.
1762    fn call_args(&mut self) -> PResult<Vec<Expr>> {
1763        self.expect(Punct::LParen)?;
1764        let mut args = Vec::new();
1765        let mut deepest = 0;
1766        if !self.eat(Punct::RParen) {
1767            loop {
1768                args.push(self.assign()?);
1769                deepest = deepest.max(self.tree_depth);
1770                if self.eat(Punct::RParen) {
1771                    break;
1772                }
1773                self.expect(Punct::Comma)?;
1774            }
1775        }
1776        self.tree_depth = deepest;
1777        Ok(args)
1778    }
1779
1780    /// A literal, a name or a constructor.
1781    fn atom(&mut self) -> PResult<Expr> {
1782        let Some(t) = self.peek().cloned() else {
1783            return Err(self.expected("an expression"));
1784        };
1785        let span = t.site();
1786        let literal = match t.kind {
1787            TokenKind::Int => Some(Literal::Int(t.text.clone())),
1788            TokenKind::Float => Some(Literal::Float(t.text.clone())),
1789            TokenKind::Str => Some(Literal::Str(t.text.clone())),
1790            TokenKind::Ident if t.text == "true" || t.text == "false" => {
1791                Some(Literal::Bool(t.text == "true"))
1792            }
1793            _ => None,
1794        };
1795        if let Some(literal) = literal {
1796            if matches!(t.kind, TokenKind::Int | TokenKind::Float) && !is_valid_number(&t.text) {
1797                self.error(span, format!("`{}` is not a valid number", t.text));
1798            }
1799            self.pos += 1;
1800            if let Literal::Str(mut text) = literal {
1801                // Adjacent strings are one string, as in C.
1802                while let Some(next) = self.peek().filter(|t| t.kind == TokenKind::Str) {
1803                    text.pop();
1804                    text.push_str(&next.text[1..]);
1805                    self.pos += 1;
1806                }
1807                let span = self.since(span);
1808                return self.node(ExprKind::Literal(Literal::Str(text)), span, 0);
1809            }
1810            return self.node(ExprKind::Literal(literal), span, 0);
1811        }
1812        let Some((name, end)) = self.qualified_at(self.pos) else {
1813            return Err(self.expected("an expression"));
1814        };
1815        let next = self.tokens.get(end);
1816        let constructor = next.is_some_and(|n| n.is(Punct::LParen))
1817            || (next.is_some_and(|n| n.is(Punct::Lt)) && is_template_type(&name));
1818        if constructor && self.is_type_name(&name) {
1819            let ty = self.type_ref()?;
1820            let ty_depth = self.tree_depth;
1821            if !self.at(Punct::LParen) {
1822                return Err(self.expected("`(`"));
1823            }
1824            let args = self.call_args()?;
1825            let span = self.since(span);
1826            let depth = ty_depth.max(self.tree_depth);
1827            return self.node(ExprKind::Construct(Box::new(ty), args), span, depth);
1828        }
1829        self.pos = end;
1830        let span = self.since(span);
1831        self.node(ExprKind::Ident(name), span, 0)
1832    }
1833}
1834
1835fn postfix_op(kind: TokenKind) -> Option<UnaryOp> {
1836    match kind {
1837        TokenKind::Punct(Punct::PlusPlus) => Some(UnaryOp::PostInc),
1838        TokenKind::Punct(Punct::MinusMinus) => Some(UnaryOp::PostDec),
1839        _ => None,
1840    }
1841}
1842
1843fn prefix_op(kind: TokenKind) -> Option<UnaryOp> {
1844    let TokenKind::Punct(punct) = kind else {
1845        return None;
1846    };
1847    Some(match punct {
1848        Punct::Minus => UnaryOp::Neg,
1849        Punct::Plus => UnaryOp::Plus,
1850        Punct::Bang => UnaryOp::Not,
1851        Punct::Tilde => UnaryOp::BitNot,
1852        Punct::PlusPlus => UnaryOp::PreInc,
1853        Punct::MinusMinus => UnaryOp::PreDec,
1854        _ => return None,
1855    })
1856}
1857
1858/// The operator of `=` (`None`) or a compound assignment such as `+=`.
1859fn assign_op(kind: TokenKind) -> Option<Option<BinaryOp>> {
1860    let TokenKind::Punct(punct) = kind else {
1861        return None;
1862    };
1863    Some(match punct {
1864        Punct::Eq => None,
1865        Punct::PlusEq => Some(BinaryOp::Add),
1866        Punct::MinusEq => Some(BinaryOp::Sub),
1867        Punct::StarEq => Some(BinaryOp::Mul),
1868        Punct::SlashEq => Some(BinaryOp::Div),
1869        Punct::PercentEq => Some(BinaryOp::Rem),
1870        Punct::ShlEq => Some(BinaryOp::Shl),
1871        Punct::ShrEq => Some(BinaryOp::Shr),
1872        Punct::AmpEq => Some(BinaryOp::BitAnd),
1873        Punct::PipeEq => Some(BinaryOp::BitOr),
1874        Punct::CaretEq => Some(BinaryOp::BitXor),
1875        _ => return None,
1876    })
1877}
1878
1879fn binary_op(punct: Punct) -> Option<(u8, BinaryOp)> {
1880    Some(match punct {
1881        Punct::OrOr => (0, BinaryOp::Or),
1882        Punct::AndAnd => (1, BinaryOp::And),
1883        Punct::Pipe => (2, BinaryOp::BitOr),
1884        Punct::Caret => (3, BinaryOp::BitXor),
1885        Punct::Amp => (4, BinaryOp::BitAnd),
1886        Punct::EqEq => (5, BinaryOp::Eq),
1887        Punct::NotEq => (5, BinaryOp::Ne),
1888        Punct::Lt => (6, BinaryOp::Lt),
1889        Punct::Gt => (6, BinaryOp::Gt),
1890        Punct::LtEq => (6, BinaryOp::Le),
1891        Punct::GtEq => (6, BinaryOp::Ge),
1892        Punct::Shl => (7, BinaryOp::Shl),
1893        Punct::Shr => (7, BinaryOp::Shr),
1894        Punct::Plus => (8, BinaryOp::Add),
1895        Punct::Minus => (8, BinaryOp::Sub),
1896        Punct::Star => (9, BinaryOp::Mul),
1897        Punct::Slash => (9, BinaryOp::Div),
1898        Punct::Percent => (9, BinaryOp::Rem),
1899        _ => return None,
1900    })
1901}
1902
1903#[cfg(test)]
1904mod tests {
1905    use crate::{Options, parse};
1906
1907    #[test]
1908    fn template_arguments_count_toward_the_tree_depth() {
1909        let mut construct = "0".to_string();
1910        let mut cast = "0".to_string();
1911        for _ in 0..30 {
1912            construct = format!("vector<float, 0+{construct}{}>(0)", "+0".repeat(250));
1913            cast = format!("(vector<float, 0+{cast}{}>)0", "+0".repeat(250));
1914        }
1915        for e in [construct, cast] {
1916            let text = format!("static float4 v = {e};");
1917            let parsed = parse("t.hlsl", &text, Options::default());
1918            assert!(
1919                parsed
1920                    .diagnostics
1921                    .iter()
1922                    .any(|d| d.message.contains("the expression is nested more than")),
1923                "{:?}",
1924                parsed.diagnostics
1925            );
1926        }
1927    }
1928}