Skip to main content

wgslift_syntax/
ast.rs

1//! The syntax tree. Every node has the span of the source text it came from.
2
3use crate::span::Span;
4
5/// A name with its place in the source.
6#[derive(Debug, Clone, PartialEq)]
7pub struct Ident {
8    /// The name.
9    pub name: String,
10    /// Where it is.
11    pub span: Span,
12}
13
14/// One parsed file after preprocessing.
15#[derive(Debug, Clone, Default, PartialEq)]
16pub struct TranslationUnit {
17    /// The top-level items in source order.
18    pub items: Vec<Item>,
19}
20
21/// A top-level item.
22#[derive(Debug, Clone, PartialEq)]
23#[non_exhaustive]
24pub enum Item {
25    /// Global variables, constants, textures and samplers.
26    Variable(VarDecl),
27    /// A function definition or declaration.
28    Function(Function),
29    /// A struct definition.
30    Struct(StructDef),
31    /// `typedef T name;`
32    Typedef(Typedef),
33    /// A `cbuffer` or `tbuffer` block.
34    Buffer(BufferBlock),
35    /// An `enum` or `enum class` definition.
36    Enum(EnumDef),
37    /// `namespace Name { items }`.
38    Namespace(Namespace),
39}
40
41/// `namespace Name { items }`. The items can refer to each other without the
42/// namespace name; from outside, their names are written `Name::x`.
43#[derive(Debug, Clone, PartialEq)]
44pub struct Namespace {
45    /// The namespace's name; `None` for `namespace { ... }`.
46    pub name: Option<Ident>,
47    /// The items in source order.
48    pub items: Vec<Item>,
49    /// The whole namespace.
50    pub span: Span,
51}
52
53/// A type as written, for example `float4`, `vector<float, 3>` or `MyStruct`.
54#[derive(Debug, Clone, PartialEq)]
55pub struct TypeRef {
56    /// The type's name. A qualified name keeps its `::`, for example `N::T`.
57    pub name: Ident,
58    /// Arguments in `<>`, for example `float` and `3` in `vector<float, 3>`.
59    pub args: Vec<TypeArg>,
60    /// The whole type.
61    pub span: Span,
62}
63
64/// One argument of a template type.
65#[derive(Debug, Clone, PartialEq)]
66#[non_exhaustive]
67pub enum TypeArg {
68    /// A type argument.
69    Type(TypeRef),
70    /// A constant argument.
71    Expr(Expr),
72    /// A type with `unorm` or `snorm`, for example in `RWTexture2D<unorm float4>`.
73    Modified(Vec<Modifier>, TypeRef),
74}
75
76/// A keyword before a declaration that changes its storage, layout or use.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78#[allow(missing_docs)]
79#[non_exhaustive]
80pub enum Modifier {
81    Static,
82    Uniform,
83    Extern,
84    Const,
85    Shared,
86    Volatile,
87    Groupshared,
88    Precise,
89    Inline,
90    RowMajor,
91    ColumnMajor,
92    Nointerpolation,
93    Linear,
94    Centroid,
95    Noperspective,
96    Sample,
97    In,
98    Out,
99    Inout,
100    Snorm,
101    Unorm,
102    Point,
103    Line,
104    Triangle,
105    LineAdj,
106    TriangleAdj,
107    Globallycoherent,
108    Reordercoherent,
109    Export,
110    Payload,
111    Vertices,
112    Indices,
113    Primitives,
114}
115
116impl Modifier {
117    /// The modifier with this keyword.
118    pub fn from_word(word: &str) -> Option<Modifier> {
119        Some(match word {
120            "static" => Modifier::Static,
121            "uniform" => Modifier::Uniform,
122            "extern" => Modifier::Extern,
123            "const" => Modifier::Const,
124            "shared" => Modifier::Shared,
125            "volatile" => Modifier::Volatile,
126            "groupshared" => Modifier::Groupshared,
127            "precise" => Modifier::Precise,
128            "inline" => Modifier::Inline,
129            "row_major" => Modifier::RowMajor,
130            "column_major" => Modifier::ColumnMajor,
131            "nointerpolation" => Modifier::Nointerpolation,
132            "linear" => Modifier::Linear,
133            "centroid" => Modifier::Centroid,
134            "noperspective" => Modifier::Noperspective,
135            "sample" => Modifier::Sample,
136            "in" => Modifier::In,
137            "out" => Modifier::Out,
138            "inout" => Modifier::Inout,
139            "snorm" => Modifier::Snorm,
140            "unorm" => Modifier::Unorm,
141            "point" => Modifier::Point,
142            "line" => Modifier::Line,
143            "triangle" => Modifier::Triangle,
144            "lineadj" => Modifier::LineAdj,
145            "triangleadj" => Modifier::TriangleAdj,
146            "globallycoherent" => Modifier::Globallycoherent,
147            "reordercoherent" => Modifier::Reordercoherent,
148            "export" => Modifier::Export,
149            "payload" => Modifier::Payload,
150            "vertices" => Modifier::Vertices,
151            "indices" => Modifier::Indices,
152            "primitives" => Modifier::Primitives,
153            _ => return None,
154        })
155    }
156}
157
158/// `register(c0)`, `register(ps_3_0, s1)` or `register(t0, space1)` after a declaration.
159#[derive(Debug, Clone, PartialEq)]
160pub struct Register {
161    /// The shader profile, if one is given.
162    pub profile: Option<Ident>,
163    /// The register, for example `c0` or `s1`.
164    pub slot: Ident,
165    /// The number in brackets after the register, for example `8` in `s[8]`.
166    pub subcomponent: Option<Expr>,
167    /// The register space, for example `space1`.
168    pub space: Option<Ident>,
169    /// The whole `register(...)`.
170    pub span: Span,
171}
172
173/// `packoffset(c0.y)` after a member of a constant buffer.
174#[derive(Debug, Clone, PartialEq)]
175pub struct PackOffset {
176    /// The register, for example `c0`.
177    pub slot: Ident,
178    /// The component, for example `y`.
179    pub component: Option<Ident>,
180    /// The whole `packoffset(...)`.
181    pub span: Span,
182}
183
184/// The things that can follow `:` after a declarator, a parameter or a function.
185#[derive(Debug, Clone, Default, PartialEq)]
186pub struct Bindings {
187    /// A semantic, for example `TEXCOORD0` or `SV_Target`.
188    pub semantic: Option<Ident>,
189    /// The `register(...)` bindings: one for each shader profile, or one for all.
190    pub registers: Vec<Register>,
191    /// A `packoffset(...)` binding.
192    pub packoffset: Option<PackOffset>,
193}
194
195/// One declaration statement: modifiers, a type and one or more names.
196#[derive(Debug, Clone, PartialEq)]
197pub struct VarDecl {
198    /// Attributes before the declaration, for example `[[vk::binding(0)]]`.
199    pub attributes: Vec<Attribute>,
200    /// Keywords before the type.
201    pub modifiers: Vec<Modifier>,
202    /// The type of all declarators.
203    pub ty: TypeRef,
204    /// The declared names.
205    pub declarators: Vec<Declarator>,
206    /// The whole declaration.
207    pub span: Span,
208}
209
210/// One declared name, with its array sizes, bindings and initializer.
211#[derive(Debug, Clone, PartialEq)]
212pub struct Declarator {
213    /// The name.
214    pub name: Ident,
215    /// One entry for each `[...]`; `None` for `[]`.
216    pub array: Vec<Option<Expr>>,
217    /// Semantic, register and packoffset.
218    pub bindings: Bindings,
219    /// The span of an annotation block `<...>`, which is kept as text.
220    pub annotations: Option<Span>,
221    /// The value after `=`.
222    pub init: Option<Initializer>,
223    /// The whole declarator.
224    pub span: Span,
225}
226
227/// The value of a declaration.
228#[derive(Debug, Clone, PartialEq)]
229#[non_exhaustive]
230pub enum Initializer {
231    /// `= expr`
232    Expr(Expr),
233    /// `= { a, b, ... }`
234    List(Vec<Initializer>, Span),
235    /// `= sampler_state { Name = value; ... }`, or the D3D10 form
236    /// `SamplerState s { Name = value; ... };`
237    SamplerState(Vec<StateAssignment>, Span),
238}
239
240/// One `Name = value;` line in a `sampler_state` block.
241#[derive(Debug, Clone, PartialEq)]
242pub struct StateAssignment {
243    /// The state, for example `MinFilter`.
244    pub name: Ident,
245    /// The value. A texture reference `<tex>` or `(tex)` is an identifier expression.
246    pub value: Expr,
247    /// The whole line.
248    pub span: Span,
249}
250
251/// An attribute in `[]` or `[[]]`, for example `[unroll]`, `[numthreads(8, 8, 1)]`
252/// or `[[vk::binding(0, 1)]]`.
253#[derive(Debug, Clone, PartialEq)]
254pub struct Attribute {
255    /// The attribute's name. A qualified name keeps its `::`, for example `vk::binding`.
256    pub name: Ident,
257    /// Its arguments, if it has parentheses.
258    pub args: Vec<Expr>,
259    /// The whole attribute, with the brackets when it is alone in them. In
260    /// `[[a, b]]`, each span covers only the name and the arguments.
261    pub span: Span,
262}
263
264/// A function.
265#[derive(Debug, Clone, PartialEq)]
266pub struct Function {
267    /// Attributes before the function.
268    pub attributes: Vec<Attribute>,
269    /// Keywords before the return type.
270    pub modifiers: Vec<Modifier>,
271    /// The return type.
272    pub return_type: TypeRef,
273    /// The function's name.
274    pub name: Ident,
275    /// The parameters.
276    pub params: Vec<Param>,
277    /// The semantic or register of the return value.
278    pub return_bindings: Bindings,
279    /// The body; `None` for a declaration that ends in `;`.
280    pub body: Option<Block>,
281    /// The whole function.
282    pub span: Span,
283}
284
285/// A function parameter.
286#[derive(Debug, Clone, PartialEq)]
287pub struct Param {
288    /// Attributes before the parameter, for example `[[vk::location(0)]]`.
289    pub attributes: Vec<Attribute>,
290    /// Keywords such as `in`, `out`, `inout` and `uniform`.
291    pub modifiers: Vec<Modifier>,
292    /// The type.
293    pub ty: TypeRef,
294    /// The name. HLSL lets a declaration leave it out.
295    pub name: Option<Ident>,
296    /// One entry for each `[...]`.
297    pub array: Vec<Option<Expr>>,
298    /// Semantic and register.
299    pub bindings: Bindings,
300    /// The default value after `=`.
301    pub default: Option<Expr>,
302    /// The whole parameter.
303    pub span: Span,
304}
305
306/// `struct Name : Base { members };`
307#[derive(Debug, Clone, PartialEq)]
308pub struct StructDef {
309    /// Attributes after `struct`, for example `[raypayload]`.
310    pub attributes: Vec<Attribute>,
311    /// The struct's name.
312    pub name: Ident,
313    /// The base struct after `:`.
314    pub base: Option<TypeRef>,
315    /// The fields, as declarations.
316    pub fields: Vec<VarDecl>,
317    /// The member functions, with their bodies.
318    pub methods: Vec<Function>,
319    /// The structs, enums and typedefs declared inside, in source order.
320    pub nested: Vec<Item>,
321    /// The whole definition.
322    pub span: Span,
323}
324
325/// `typedef T name;`
326#[derive(Debug, Clone, PartialEq)]
327pub struct Typedef {
328    /// Modifiers such as `const`.
329    pub modifiers: Vec<Modifier>,
330    /// The type that gets the new name.
331    pub ty: TypeRef,
332    /// The new names, with their array sizes.
333    pub names: Vec<(Ident, Vec<Option<Expr>>)>,
334    /// The whole typedef.
335    pub span: Span,
336}
337
338/// `enum Name : Type { A, B = 2 };`, or `enum class Name { ... };`.
339#[derive(Debug, Clone, PartialEq)]
340pub struct EnumDef {
341    /// `enum class`: the enumerators are written `Name::A`, not `A`.
342    pub scoped: bool,
343    /// The enum's name; `None` for `enum { ... }`.
344    pub name: Option<Ident>,
345    /// The underlying type after `:`.
346    pub base: Option<TypeRef>,
347    /// The enumerators in source order.
348    pub enumerators: Vec<Enumerator>,
349    /// The whole definition, with the `;`.
350    pub span: Span,
351}
352
353/// One name in an enum, with its value.
354#[derive(Debug, Clone, PartialEq)]
355pub struct Enumerator {
356    /// The name.
357    pub name: Ident,
358    /// The constant after `=`.
359    pub value: Option<Expr>,
360    /// The name and the value.
361    pub span: Span,
362}
363
364/// The kind of a buffer block.
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366#[non_exhaustive]
367pub enum BufferKind {
368    /// `cbuffer`
369    Constant,
370    /// `tbuffer`
371    Texture,
372}
373
374/// `cbuffer Name : register(b0) { members };`
375#[derive(Debug, Clone, PartialEq)]
376pub struct BufferBlock {
377    /// Attributes before the block, for example `[[vk::push_constant]]`.
378    pub attributes: Vec<Attribute>,
379    /// `cbuffer` or `tbuffer`.
380    pub kind: BufferKind,
381    /// The block's name.
382    pub name: Ident,
383    /// The register binding.
384    pub bindings: Bindings,
385    /// The members.
386    pub members: Vec<VarDecl>,
387    /// The whole block.
388    pub span: Span,
389}
390
391/// A block of statements in `{}`.
392#[derive(Debug, Clone, PartialEq)]
393pub struct Block {
394    /// The statements.
395    pub stmts: Vec<Stmt>,
396    /// The block, with the braces.
397    pub span: Span,
398}
399
400/// A statement, with the attributes written before it.
401#[derive(Debug, Clone, PartialEq)]
402pub struct Stmt {
403    /// Attributes such as `[unroll]` or `[branch]`.
404    pub attributes: Vec<Attribute>,
405    /// What the statement does.
406    pub kind: StmtKind,
407    /// The whole statement.
408    pub span: Span,
409}
410
411/// The kinds of statements.
412#[derive(Debug, Clone, PartialEq)]
413#[non_exhaustive]
414pub enum StmtKind {
415    /// `;`
416    Empty,
417    /// A local declaration.
418    Var(VarDecl),
419    /// An expression and `;`.
420    Expr(Expr),
421    /// `{ ... }`
422    Block(Block),
423    /// `if (cond) then else otherwise`
424    If {
425        /// The condition.
426        cond: Expr,
427        /// The statement for a true condition.
428        then: Box<Stmt>,
429        /// The statement after `else`.
430        otherwise: Option<Box<Stmt>>,
431    },
432    /// `for (init; cond; step) body`
433    For {
434        /// The first part: a declaration or an expression.
435        init: Option<Box<Stmt>>,
436        /// The condition.
437        cond: Option<Expr>,
438        /// The expression after each pass.
439        step: Option<Expr>,
440        /// The loop body.
441        body: Box<Stmt>,
442    },
443    /// `while (cond) body`
444    While {
445        /// The condition.
446        cond: Expr,
447        /// The loop body.
448        body: Box<Stmt>,
449    },
450    /// `do body while (cond);`
451    DoWhile {
452        /// The loop body.
453        body: Box<Stmt>,
454        /// The condition.
455        cond: Expr,
456    },
457    /// `switch (value) { cases }`
458    Switch {
459        /// The value to compare.
460        value: Expr,
461        /// The cases in order.
462        cases: Vec<SwitchCase>,
463    },
464    /// `break;`
465    Break,
466    /// `continue;`
467    Continue,
468    /// `discard;`
469    Discard,
470    /// `return;` or `return value;`
471    Return(Option<Expr>),
472    /// A local enum.
473    Enum(EnumDef),
474    /// A local struct, with the variables declared after it.
475    Struct {
476        /// The definition.
477        def: Box<StructDef>,
478        /// The variables in `struct S { ... } a, b;`.
479        vars: Option<VarDecl>,
480    },
481    /// A local typedef.
482    Typedef(Typedef),
483}
484
485/// One `case`/`default` label group and its statements.
486#[derive(Debug, Clone, PartialEq)]
487pub struct SwitchCase {
488    /// The labels; `None` is `default`.
489    pub labels: Vec<Option<Expr>>,
490    /// The statements after the labels.
491    pub stmts: Vec<Stmt>,
492    /// The labels and statements.
493    pub span: Span,
494}
495
496/// An expression.
497#[derive(Debug, Clone, PartialEq)]
498pub struct Expr {
499    /// What the expression is.
500    pub kind: ExprKind,
501    /// The whole expression.
502    pub span: Span,
503}
504
505/// A literal value. The text keeps the suffix, for example `1.5f` or `2u`.
506#[derive(Debug, Clone, PartialEq)]
507#[non_exhaustive]
508pub enum Literal {
509    /// An integer literal.
510    Int(String),
511    /// A floating-point literal.
512    Float(String),
513    /// `true` or `false`.
514    Bool(bool),
515    /// A string literal, with its quotes.
516    Str(String),
517}
518
519/// Prefix operators.
520#[derive(Debug, Clone, Copy, PartialEq, Eq)]
521#[allow(missing_docs)]
522#[non_exhaustive]
523pub enum UnaryOp {
524    Neg,
525    Plus,
526    Not,
527    BitNot,
528    PreInc,
529    PreDec,
530    PostInc,
531    PostDec,
532}
533
534/// Binary operators.
535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
536#[allow(missing_docs)]
537#[non_exhaustive]
538pub enum BinaryOp {
539    Mul,
540    Div,
541    Rem,
542    Add,
543    Sub,
544    Shl,
545    Shr,
546    Lt,
547    Gt,
548    Le,
549    Ge,
550    Eq,
551    Ne,
552    BitAnd,
553    BitXor,
554    BitOr,
555    And,
556    Or,
557}
558
559/// The kinds of expressions.
560#[derive(Debug, Clone, PartialEq)]
561#[non_exhaustive]
562pub enum ExprKind {
563    /// A literal.
564    Literal(Literal),
565    /// A name. A qualified name keeps its `::`, for example `N::f` or `E::A`.
566    Ident(String),
567    /// A prefix or postfix operator.
568    Unary(UnaryOp, Box<Expr>),
569    /// A binary operator.
570    Binary(BinaryOp, Box<Expr>, Box<Expr>),
571    /// `target = value`, or a compound form such as `+=` with its operator.
572    Assign(Option<BinaryOp>, Box<Expr>, Box<Expr>),
573    /// `cond ? a : b`
574    Ternary(Box<Expr>, Box<Expr>, Box<Expr>),
575    /// `a, b`
576    Comma(Vec<Expr>),
577    /// A call of a function or method: `f(x)` or `tex.Sample(s, uv)`.
578    Call(Box<Expr>, Vec<Expr>),
579    /// A constructor: `float4(a, b)`.
580    Construct(Box<TypeRef>, Vec<Expr>),
581    /// `(type)value`
582    Cast(Box<TypeRef>, Box<Expr>),
583    /// `value.name`, which includes swizzles.
584    Member(Box<Expr>, Ident),
585    /// `value[index]`
586    Index(Box<Expr>, Box<Expr>),
587}