wgslift-syntax 0.2.0

Preprocessor, lexer and parser for HLSL, the front end of the wgslift translator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! The syntax tree. Every node has the span of the source text it came from.

use crate::span::Span;

/// A name with its place in the source.
#[derive(Debug, Clone, PartialEq)]
pub struct Ident {
    /// The name.
    pub name: String,
    /// Where it is.
    pub span: Span,
}

/// One parsed file after preprocessing.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TranslationUnit {
    /// The top-level items in source order.
    pub items: Vec<Item>,
}

/// A top-level item.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Item {
    /// Global variables, constants, textures and samplers.
    Variable(VarDecl),
    /// A function definition or declaration.
    Function(Function),
    /// A struct definition.
    Struct(StructDef),
    /// `typedef T name;`
    Typedef(Typedef),
    /// A `cbuffer` or `tbuffer` block.
    Buffer(BufferBlock),
    /// An `enum` or `enum class` definition.
    Enum(EnumDef),
    /// `namespace Name { items }`.
    Namespace(Namespace),
}

/// `namespace Name { items }`. The items can refer to each other without the
/// namespace name; from outside, their names are written `Name::x`.
#[derive(Debug, Clone, PartialEq)]
pub struct Namespace {
    /// The namespace's name; `None` for `namespace { ... }`.
    pub name: Option<Ident>,
    /// The items in source order.
    pub items: Vec<Item>,
    /// The whole namespace.
    pub span: Span,
}

/// A type as written, for example `float4`, `vector<float, 3>` or `MyStruct`.
#[derive(Debug, Clone, PartialEq)]
pub struct TypeRef {
    /// The type's name. A qualified name keeps its `::`, for example `N::T`.
    pub name: Ident,
    /// Arguments in `<>`, for example `float` and `3` in `vector<float, 3>`.
    pub args: Vec<TypeArg>,
    /// The whole type.
    pub span: Span,
}

/// One argument of a template type.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum TypeArg {
    /// A type argument.
    Type(TypeRef),
    /// A constant argument.
    Expr(Expr),
    /// A type with `unorm` or `snorm`, for example in `RWTexture2D<unorm float4>`.
    Modified(Vec<Modifier>, TypeRef),
}

/// A keyword before a declaration that changes its storage, layout or use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum Modifier {
    Static,
    Uniform,
    Extern,
    Const,
    Shared,
    Volatile,
    Groupshared,
    Precise,
    Inline,
    RowMajor,
    ColumnMajor,
    Nointerpolation,
    Linear,
    Centroid,
    Noperspective,
    Sample,
    In,
    Out,
    Inout,
    Snorm,
    Unorm,
    Point,
    Line,
    Triangle,
    LineAdj,
    TriangleAdj,
    Globallycoherent,
    Reordercoherent,
    Export,
    Payload,
    Vertices,
    Indices,
    Primitives,
}

impl Modifier {
    /// The modifier with this keyword.
    pub fn from_word(word: &str) -> Option<Modifier> {
        Some(match word {
            "static" => Modifier::Static,
            "uniform" => Modifier::Uniform,
            "extern" => Modifier::Extern,
            "const" => Modifier::Const,
            "shared" => Modifier::Shared,
            "volatile" => Modifier::Volatile,
            "groupshared" => Modifier::Groupshared,
            "precise" => Modifier::Precise,
            "inline" => Modifier::Inline,
            "row_major" => Modifier::RowMajor,
            "column_major" => Modifier::ColumnMajor,
            "nointerpolation" => Modifier::Nointerpolation,
            "linear" => Modifier::Linear,
            "centroid" => Modifier::Centroid,
            "noperspective" => Modifier::Noperspective,
            "sample" => Modifier::Sample,
            "in" => Modifier::In,
            "out" => Modifier::Out,
            "inout" => Modifier::Inout,
            "snorm" => Modifier::Snorm,
            "unorm" => Modifier::Unorm,
            "point" => Modifier::Point,
            "line" => Modifier::Line,
            "triangle" => Modifier::Triangle,
            "lineadj" => Modifier::LineAdj,
            "triangleadj" => Modifier::TriangleAdj,
            "globallycoherent" => Modifier::Globallycoherent,
            "reordercoherent" => Modifier::Reordercoherent,
            "export" => Modifier::Export,
            "payload" => Modifier::Payload,
            "vertices" => Modifier::Vertices,
            "indices" => Modifier::Indices,
            "primitives" => Modifier::Primitives,
            _ => return None,
        })
    }
}

/// `register(c0)`, `register(ps_3_0, s1)` or `register(t0, space1)` after a declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct Register {
    /// The shader profile, if one is given.
    pub profile: Option<Ident>,
    /// The register, for example `c0` or `s1`.
    pub slot: Ident,
    /// The number in brackets after the register, for example `8` in `s[8]`.
    pub subcomponent: Option<Expr>,
    /// The register space, for example `space1`.
    pub space: Option<Ident>,
    /// The whole `register(...)`.
    pub span: Span,
}

/// `packoffset(c0.y)` after a member of a constant buffer.
#[derive(Debug, Clone, PartialEq)]
pub struct PackOffset {
    /// The register, for example `c0`.
    pub slot: Ident,
    /// The component, for example `y`.
    pub component: Option<Ident>,
    /// The whole `packoffset(...)`.
    pub span: Span,
}

/// The things that can follow `:` after a declarator, a parameter or a function.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Bindings {
    /// A semantic, for example `TEXCOORD0` or `SV_Target`.
    pub semantic: Option<Ident>,
    /// The `register(...)` bindings: one for each shader profile, or one for all.
    pub registers: Vec<Register>,
    /// A `packoffset(...)` binding.
    pub packoffset: Option<PackOffset>,
}

/// One declaration statement: modifiers, a type and one or more names.
#[derive(Debug, Clone, PartialEq)]
pub struct VarDecl {
    /// Attributes before the declaration, for example `[[vk::binding(0)]]`.
    pub attributes: Vec<Attribute>,
    /// Keywords before the type.
    pub modifiers: Vec<Modifier>,
    /// The type of all declarators.
    pub ty: TypeRef,
    /// The declared names.
    pub declarators: Vec<Declarator>,
    /// The whole declaration.
    pub span: Span,
}

/// One declared name, with its array sizes, bindings and initializer.
#[derive(Debug, Clone, PartialEq)]
pub struct Declarator {
    /// The name.
    pub name: Ident,
    /// One entry for each `[...]`; `None` for `[]`.
    pub array: Vec<Option<Expr>>,
    /// Semantic, register and packoffset.
    pub bindings: Bindings,
    /// The span of an annotation block `<...>`, which is kept as text.
    pub annotations: Option<Span>,
    /// The value after `=`.
    pub init: Option<Initializer>,
    /// The whole declarator.
    pub span: Span,
}

/// The value of a declaration.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Initializer {
    /// `= expr`
    Expr(Expr),
    /// `= { a, b, ... }`
    List(Vec<Initializer>, Span),
    /// `= sampler_state { Name = value; ... }`, or the D3D10 form
    /// `SamplerState s { Name = value; ... };`
    SamplerState(Vec<StateAssignment>, Span),
}

/// One `Name = value;` line in a `sampler_state` block.
#[derive(Debug, Clone, PartialEq)]
pub struct StateAssignment {
    /// The state, for example `MinFilter`.
    pub name: Ident,
    /// The value. A texture reference `<tex>` or `(tex)` is an identifier expression.
    pub value: Expr,
    /// The whole line.
    pub span: Span,
}

/// An attribute in `[]` or `[[]]`, for example `[unroll]`, `[numthreads(8, 8, 1)]`
/// or `[[vk::binding(0, 1)]]`.
#[derive(Debug, Clone, PartialEq)]
pub struct Attribute {
    /// The attribute's name. A qualified name keeps its `::`, for example `vk::binding`.
    pub name: Ident,
    /// Its arguments, if it has parentheses.
    pub args: Vec<Expr>,
    /// The whole attribute, with the brackets when it is alone in them. In
    /// `[[a, b]]`, each span covers only the name and the arguments.
    pub span: Span,
}

/// A function.
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
    /// Attributes before the function.
    pub attributes: Vec<Attribute>,
    /// Keywords before the return type.
    pub modifiers: Vec<Modifier>,
    /// The return type.
    pub return_type: TypeRef,
    /// The function's name.
    pub name: Ident,
    /// The parameters.
    pub params: Vec<Param>,
    /// The semantic or register of the return value.
    pub return_bindings: Bindings,
    /// The body; `None` for a declaration that ends in `;`.
    pub body: Option<Block>,
    /// The whole function.
    pub span: Span,
}

/// A function parameter.
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
    /// Attributes before the parameter, for example `[[vk::location(0)]]`.
    pub attributes: Vec<Attribute>,
    /// Keywords such as `in`, `out`, `inout` and `uniform`.
    pub modifiers: Vec<Modifier>,
    /// The type.
    pub ty: TypeRef,
    /// The name. HLSL lets a declaration leave it out.
    pub name: Option<Ident>,
    /// One entry for each `[...]`.
    pub array: Vec<Option<Expr>>,
    /// Semantic and register.
    pub bindings: Bindings,
    /// The default value after `=`.
    pub default: Option<Expr>,
    /// The whole parameter.
    pub span: Span,
}

/// `struct Name : Base { members };`
#[derive(Debug, Clone, PartialEq)]
pub struct StructDef {
    /// Attributes after `struct`, for example `[raypayload]`.
    pub attributes: Vec<Attribute>,
    /// The struct's name.
    pub name: Ident,
    /// The base struct after `:`.
    pub base: Option<TypeRef>,
    /// The fields, as declarations.
    pub fields: Vec<VarDecl>,
    /// The member functions, with their bodies.
    pub methods: Vec<Function>,
    /// The structs, enums and typedefs declared inside, in source order.
    pub nested: Vec<Item>,
    /// The whole definition.
    pub span: Span,
}

/// `typedef T name;`
#[derive(Debug, Clone, PartialEq)]
pub struct Typedef {
    /// Modifiers such as `const`.
    pub modifiers: Vec<Modifier>,
    /// The type that gets the new name.
    pub ty: TypeRef,
    /// The new names, with their array sizes.
    pub names: Vec<(Ident, Vec<Option<Expr>>)>,
    /// The whole typedef.
    pub span: Span,
}

/// `enum Name : Type { A, B = 2 };`, or `enum class Name { ... };`.
#[derive(Debug, Clone, PartialEq)]
pub struct EnumDef {
    /// `enum class`: the enumerators are written `Name::A`, not `A`.
    pub scoped: bool,
    /// The enum's name; `None` for `enum { ... }`.
    pub name: Option<Ident>,
    /// The underlying type after `:`.
    pub base: Option<TypeRef>,
    /// The enumerators in source order.
    pub enumerators: Vec<Enumerator>,
    /// The whole definition, with the `;`.
    pub span: Span,
}

/// One name in an enum, with its value.
#[derive(Debug, Clone, PartialEq)]
pub struct Enumerator {
    /// The name.
    pub name: Ident,
    /// The constant after `=`.
    pub value: Option<Expr>,
    /// The name and the value.
    pub span: Span,
}

/// The kind of a buffer block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BufferKind {
    /// `cbuffer`
    Constant,
    /// `tbuffer`
    Texture,
}

/// `cbuffer Name : register(b0) { members };`
#[derive(Debug, Clone, PartialEq)]
pub struct BufferBlock {
    /// Attributes before the block, for example `[[vk::push_constant]]`.
    pub attributes: Vec<Attribute>,
    /// `cbuffer` or `tbuffer`.
    pub kind: BufferKind,
    /// The block's name.
    pub name: Ident,
    /// The register binding.
    pub bindings: Bindings,
    /// The members.
    pub members: Vec<VarDecl>,
    /// The whole block.
    pub span: Span,
}

/// A block of statements in `{}`.
#[derive(Debug, Clone, PartialEq)]
pub struct Block {
    /// The statements.
    pub stmts: Vec<Stmt>,
    /// The block, with the braces.
    pub span: Span,
}

/// A statement, with the attributes written before it.
#[derive(Debug, Clone, PartialEq)]
pub struct Stmt {
    /// Attributes such as `[unroll]` or `[branch]`.
    pub attributes: Vec<Attribute>,
    /// What the statement does.
    pub kind: StmtKind,
    /// The whole statement.
    pub span: Span,
}

/// The kinds of statements.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum StmtKind {
    /// `;`
    Empty,
    /// A local declaration.
    Var(VarDecl),
    /// An expression and `;`.
    Expr(Expr),
    /// `{ ... }`
    Block(Block),
    /// `if (cond) then else otherwise`
    If {
        /// The condition.
        cond: Expr,
        /// The statement for a true condition.
        then: Box<Stmt>,
        /// The statement after `else`.
        otherwise: Option<Box<Stmt>>,
    },
    /// `for (init; cond; step) body`
    For {
        /// The first part: a declaration or an expression.
        init: Option<Box<Stmt>>,
        /// The condition.
        cond: Option<Expr>,
        /// The expression after each pass.
        step: Option<Expr>,
        /// The loop body.
        body: Box<Stmt>,
    },
    /// `while (cond) body`
    While {
        /// The condition.
        cond: Expr,
        /// The loop body.
        body: Box<Stmt>,
    },
    /// `do body while (cond);`
    DoWhile {
        /// The loop body.
        body: Box<Stmt>,
        /// The condition.
        cond: Expr,
    },
    /// `switch (value) { cases }`
    Switch {
        /// The value to compare.
        value: Expr,
        /// The cases in order.
        cases: Vec<SwitchCase>,
    },
    /// `break;`
    Break,
    /// `continue;`
    Continue,
    /// `discard;`
    Discard,
    /// `return;` or `return value;`
    Return(Option<Expr>),
    /// A local enum.
    Enum(EnumDef),
    /// A local struct, with the variables declared after it.
    Struct {
        /// The definition.
        def: Box<StructDef>,
        /// The variables in `struct S { ... } a, b;`.
        vars: Option<VarDecl>,
    },
    /// A local typedef.
    Typedef(Typedef),
}

/// One `case`/`default` label group and its statements.
#[derive(Debug, Clone, PartialEq)]
pub struct SwitchCase {
    /// The labels; `None` is `default`.
    pub labels: Vec<Option<Expr>>,
    /// The statements after the labels.
    pub stmts: Vec<Stmt>,
    /// The labels and statements.
    pub span: Span,
}

/// An expression.
#[derive(Debug, Clone, PartialEq)]
pub struct Expr {
    /// What the expression is.
    pub kind: ExprKind,
    /// The whole expression.
    pub span: Span,
}

/// A literal value. The text keeps the suffix, for example `1.5f` or `2u`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Literal {
    /// An integer literal.
    Int(String),
    /// A floating-point literal.
    Float(String),
    /// `true` or `false`.
    Bool(bool),
    /// A string literal, with its quotes.
    Str(String),
}

/// Prefix operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum UnaryOp {
    Neg,
    Plus,
    Not,
    BitNot,
    PreInc,
    PreDec,
    PostInc,
    PostDec,
}

/// Binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum BinaryOp {
    Mul,
    Div,
    Rem,
    Add,
    Sub,
    Shl,
    Shr,
    Lt,
    Gt,
    Le,
    Ge,
    Eq,
    Ne,
    BitAnd,
    BitXor,
    BitOr,
    And,
    Or,
}

/// The kinds of expressions.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ExprKind {
    /// A literal.
    Literal(Literal),
    /// A name. A qualified name keeps its `::`, for example `N::f` or `E::A`.
    Ident(String),
    /// A prefix or postfix operator.
    Unary(UnaryOp, Box<Expr>),
    /// A binary operator.
    Binary(BinaryOp, Box<Expr>, Box<Expr>),
    /// `target = value`, or a compound form such as `+=` with its operator.
    Assign(Option<BinaryOp>, Box<Expr>, Box<Expr>),
    /// `cond ? a : b`
    Ternary(Box<Expr>, Box<Expr>, Box<Expr>),
    /// `a, b`
    Comma(Vec<Expr>),
    /// A call of a function or method: `f(x)` or `tex.Sample(s, uv)`.
    Call(Box<Expr>, Vec<Expr>),
    /// A constructor: `float4(a, b)`.
    Construct(Box<TypeRef>, Vec<Expr>),
    /// `(type)value`
    Cast(Box<TypeRef>, Box<Expr>),
    /// `value.name`, which includes swizzles.
    Member(Box<Expr>, Ident),
    /// `value[index]`
    Index(Box<Expr>, Box<Expr>),
}