-
Notifications
You must be signed in to change notification settings - Fork 195
/
mod.rs
3336 lines (3193 loc) · 134 KB
/
mod.rs
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Front end for consuming [WebGPU Shading Language][wgsl].
//!
//! [wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html
mod conv;
mod lexer;
#[cfg(test)]
mod tests;
use crate::{
arena::{Arena, Handle},
proc::{
ensure_block_returns, Alignment, Layouter, ResolveContext, ResolveError, TypeResolution,
},
ConstantInner, FastHashMap, ScalarValue,
};
use self::lexer::Lexer;
use codespan_reporting::{
diagnostic::{Diagnostic, Label},
files::{Files, SimpleFile},
term::{
self,
termcolor::{ColorChoice, ColorSpec, StandardStream, WriteColor},
},
};
use std::{
borrow::Cow,
convert::TryFrom,
io::{self, Write},
iter,
num::{NonZeroU32, ParseFloatError, ParseIntError},
ops,
};
use thiserror::Error;
type Span = ops::Range<usize>;
type TokenSpan<'a> = (Token<'a>, Span);
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Token<'a> {
Separator(char),
DoubleColon,
Paren(char),
DoubleParen(char),
Number {
value: &'a str,
ty: char,
width: &'a str,
},
String(&'a str),
Word(&'a str),
Operation(char),
LogicalOperation(char),
ShiftOperation(char),
Arrow,
Unknown(char),
UnterminatedString,
Trivia,
End,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ExpectedToken<'a> {
Token(Token<'a>),
Identifier,
Float,
Uint,
Sint,
Constant,
/// Expected: constant, parenthesized expression, identifier
PrimaryExpression,
/// Expected: ']]', ','
AttributeSeparator,
/// Expected: '}', identifier
FieldName,
/// Expected: ']]', 'access', 'stride'
TypeAttribute,
/// Expected: ';', '{', word
Statement,
/// Expected: 'case', 'default', '}'
SwitchItem,
/// Expected: ',', ')'
WorkgroupSizeSeparator,
/// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof
GlobalItem,
/// Expected: ']]', 'size', 'align'
StructAttribute,
}
#[derive(Clone, Debug, Error)]
pub enum Error<'a> {
#[error("")]
Unexpected(TokenSpan<'a>, ExpectedToken<'a>),
#[error("")]
BadU32(Span, ParseIntError),
#[error("")]
BadI32(Span, ParseIntError),
#[error("")]
BadFloat(Span, ParseFloatError),
#[error("")]
BadU32Constant(Span),
#[error("")]
BadScalarWidth(Span, &'a str),
#[error("")]
BadAccessor(Span),
#[error("bad texture`")]
BadTexture(Span),
#[error("bad texture coordinate")]
BadCoordinate,
#[error("invalid type cast")]
BadTypeCast {
span: Span,
from_type: String,
to_type: String,
},
#[error("bad texture sample type. Only f32, i32 and u32 are valid")]
BadTextureSampleType {
span: Span,
kind: crate::ScalarKind,
width: u8,
},
#[error(transparent)]
InvalidResolve(ResolveError),
#[error("for(;;) initializer is not an assignment or a function call")]
InvalidForInitializer(Span),
#[error("resource type {0:?} is invalid")]
InvalidResourceType(Handle<crate::Type>),
#[error("unknown import: `{0}`")]
UnknownImport(&'a str),
#[error("unknown storage class")]
UnknownStorageClass(Span),
#[error("unknown attribute")]
UnknownAttribute(Span),
#[error("unknown scalar kind: `{0}`")]
UnknownScalarKind(&'a str),
#[error("unknown builtin")]
UnknownBuiltin(Span),
#[error("unknown access: `{0}`")]
UnknownAccess(&'a str),
#[error("unknown shader stage")]
UnknownShaderStage(Span),
#[error("unknown identifier: `{1}`")]
UnknownIdent(Span, &'a str),
#[error("unknown scalar type")]
UnknownScalarType(Span),
#[error("unknown type")]
UnknownType(Span),
#[error("unknown function: `{0}`")]
UnknownFunction(&'a str),
#[error("unknown storage format")]
UnknownStorageFormat(Span),
#[error("unknown conservative depth")]
UnknownConservativeDepth(Span),
#[error("array stride must not be 0")]
ZeroStride(Span),
#[error("struct member size or alignment must not be 0")]
ZeroSizeOrAlign(Span),
#[error("not a composite type: {0:?}")]
NotCompositeType(Handle<crate::Type>),
#[error("Input/output binding is not consistent: location {0:?}, built-in {1:?}, interpolation {2:?}, and sampling {3:?}")]
InconsistentBinding(
Option<u32>,
Option<crate::BuiltIn>,
Option<crate::Interpolation>,
Option<crate::Sampling>,
),
#[error("call to local `{0}(..)` can't be resolved")]
UnknownLocalFunction(&'a str),
#[error("builtin {0:?} is not implemented")]
UnimplementedBuiltin(crate::BuiltIn),
#[error("expression {0} doesn't match its given type {1:?}")]
LetTypeMismatch(&'a str, Handle<crate::Type>),
#[error("other error")]
Other,
}
impl<'a> Error<'a> {
fn as_parse_error(&self, source: &'a str) -> ParseError {
match *self {
Error::Unexpected((_, ref unexpected_span), expected) => {
let expected_str = match expected {
ExpectedToken::Token(token) => {
match token {
Token::Separator(c) => format!("'{}'", c),
Token::DoubleColon => "'::'".to_string(),
Token::Paren(c) => format!("'{}'", c),
Token::DoubleParen(c) => format!("'{}{}'", c, c),
Token::Number { value, .. } => {
format!("number ({})", value)
}
Token::String(s) => format!("string literal ('{}')", s.to_string()),
Token::Word(s) => s.to_string(),
Token::Operation(c) => format!("operation ('{}')", c),
Token::LogicalOperation(c) => format!("logical operation ('{}')", c),
Token::ShiftOperation(c) => format!("bitshift ('{}{}')", c, c),
Token::Arrow => "->".to_string(),
Token::Unknown(c) => format!("unkown ('{}')", c),
Token::UnterminatedString => "unterminated string".to_string(),
Token::Trivia => "trivia".to_string(),
Token::End => "end".to_string(),
}
}
ExpectedToken::Identifier => "identifier".to_string(),
ExpectedToken::Float => "floating point literal".to_string(),
ExpectedToken::Uint => "non-negative integer literal".to_string(),
ExpectedToken::Sint => "integer literal".to_string(),
ExpectedToken::Constant => "constant".to_string(),
ExpectedToken::PrimaryExpression => "expression".to_string(),
ExpectedToken::AttributeSeparator => "attribute separator (',') or an end of the attribute list (']]')".to_string(),
ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(),
ExpectedToken::TypeAttribute => "type attribute ('access' or 'stride') or and of the attribute list (']]')".to_string(),
ExpectedToken::Statement => "statement".to_string(),
ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(),
ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(),
ExpectedToken::GlobalItem => "global item ('struct', 'let', 'var', 'type', ';', 'fn') or the end of the file".to_string(),
ExpectedToken::StructAttribute => "struct attribute ('size' or 'align') or an end of the attribute list (']]')".to_string(),
};
ParseError {
message: format!(
"expected {}, found '{}'",
expected_str,
&source[unexpected_span.clone()],
),
labels: vec![(
unexpected_span.clone(),
format!("expected {}", expected_str).into(),
)],
notes: vec![],
}
},
Error::BadU32(ref bad_span, ref err) => ParseError {
message: format!(
"expected non-negative integer literal, found `{}`",
&source[bad_span.clone()],
),
labels: vec![(bad_span.clone(), "expected positive integer".into())],
notes: vec![err.to_string()],
},
Error::BadI32(ref bad_span, ref err) => ParseError {
message: format!(
"expected integer literal, found `{}`",
&source[bad_span.clone()],
),
labels: vec![(bad_span.clone(), "expected integer".into())],
notes: vec![err.to_string()],
},
Error::BadFloat(ref bad_span, ref err) => ParseError {
message: format!(
"expected floating-point literal, found `{}`",
&source[bad_span.clone()],
),
labels: vec![(bad_span.clone(), "expected floating-point literal".into())],
notes: vec![err.to_string()],
},
Error::BadU32Constant(ref bad_span) => ParseError {
message: format!(
"expected non-negative integer constant expression, found `{}`",
&source[bad_span.clone()],
),
labels: vec![(bad_span.clone(), "expected non-negative integer".into())],
notes: vec![],
},
Error::BadScalarWidth(ref bad_span, width) => ParseError {
message: format!("invalid width of `{}` for literal", width,),
labels: vec![(bad_span.clone(), "invalid width".into())],
notes: vec!["valid widths are 8, 16, 32, 64".to_string()],
},
Error::BadAccessor(ref accessor_span) => ParseError {
message: format!(
"invalid field accessor `{}`",
&source[accessor_span.clone()],
),
labels: vec![(accessor_span.clone(), "invalid accessor".into())],
notes: vec![],
},
Error::UnknownIdent(ref ident_span, ident) => ParseError {
message: format!("no definition in scope for identifier: '{}'", ident),
labels: vec![(ident_span.clone(), "unknown identifier".into())],
notes: vec![],
},
Error::UnknownScalarType(ref bad_span) => ParseError {
message: format!("unknown scalar type: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "unknown scalar type".into())],
notes: vec!["Valid scalar types are f16, f32, f64, i8, i16, i32, i64, u8, u16, u32, u64, bool".into()],
},
Error::BadTextureSampleType { ref span, kind, width } => ParseError {
message: format!("texture sample type must be one of f32, i32 or u32, but found {}", kind.to_wgsl(width)),
labels: vec![(span.clone(), "must be one of f32, i32 or u32".into())],
notes: vec![],
},
Error::BadTexture(ref bad_span) => ParseError {
message: format!("expected an image, but found '{}' which is not an image", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "not an image".into())],
notes: vec![],
},
Error::BadTypeCast { ref span, ref from_type, ref to_type } => {
let msg = format!("cannot cast a {} to a {}", from_type, to_type);
ParseError {
message: msg.clone(),
labels: vec![(span.clone(), msg.into())],
notes: vec![],
}
},
Error::InvalidForInitializer(ref bad_span) => ParseError {
message: format!("for(;;) initializer is not an assignment or a function call: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "not an assignment or function call".into())],
notes: vec![],
},
Error::UnknownStorageClass(ref bad_span) => ParseError {
message: format!("unknown storage class: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "unknown storage class".into())],
notes: vec![],
},
Error::UnknownAttribute(ref bad_span) => ParseError {
message: format!("unknown attribute: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "unknown attribute".into())],
notes: vec![],
},
Error::UnknownBuiltin(ref bad_span) => ParseError {
message: format!("unknown builtin: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "unknown builtin".into())],
notes: vec![],
},
Error::UnknownShaderStage(ref bad_span) => ParseError {
message: format!("unknown shader stage: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "unknown shader stage".into())],
notes: vec![],
},
Error::UnknownStorageFormat(ref bad_span) => ParseError {
message: format!("unknown storage format: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "unknown storage format".into())],
notes: vec![],
},
Error::UnknownConservativeDepth(ref bad_span) => ParseError {
message: format!("unknown conservative depth: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "unknown conservative depth".into())],
notes: vec![],
},
Error::UnknownType(ref bad_span) => ParseError {
message: format!("unknown type: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "unknown type".into())],
notes: vec![],
},
Error::ZeroStride(ref bad_span) => ParseError {
message: "array stride must not be zero".to_string(),
labels: vec![(bad_span.clone(), "array stride must not be zero".into())],
notes: vec![],
},
Error::ZeroSizeOrAlign(ref bad_span) => ParseError {
message: "struct member size or alignment must not be 0".to_string(),
labels: vec![(bad_span.clone(), "struct member size or alignment must not be 0".into())],
notes: vec![],
},
ref error => ParseError {
message: error.to_string(),
labels: vec![],
notes: vec![],
},
}
}
}
impl crate::StorageFormat {
pub fn to_wgsl(self) -> &'static str {
use crate::StorageFormat as Sf;
match self {
Sf::R8Unorm => "r8unorm",
Sf::R8Snorm => "r8snorm",
Sf::R8Uint => "r8uint",
Sf::R8Sint => "r8sint",
Sf::R16Uint => "r16uint",
Sf::R16Sint => "r16sint",
Sf::R16Float => "r16float",
Sf::Rg8Unorm => "rg8unorm",
Sf::Rg8Snorm => "rg8snorm",
Sf::Rg8Uint => "rg8uint",
Sf::Rg8Sint => "rg8sint",
Sf::R32Uint => "r32uint",
Sf::R32Sint => "r32sint",
Sf::R32Float => "r32float",
Sf::Rg16Uint => "rg16uint",
Sf::Rg16Sint => "rg16sint",
Sf::Rg16Float => "rg16float",
Sf::Rgba8Unorm => "rgba8unorm",
Sf::Rgba8Snorm => "rgba8snorm",
Sf::Rgba8Uint => "rgba8uint",
Sf::Rgba8Sint => "rgba8sint",
Sf::Rgb10a2Unorm => "rgb10a2unorm",
Sf::Rg11b10Float => "rg11b10float",
Sf::Rg32Uint => "rg32uint",
Sf::Rg32Sint => "rg32sint",
Sf::Rg32Float => "rg32float",
Sf::Rgba16Uint => "rgba16uint",
Sf::Rgba16Sint => "rgba16sint",
Sf::Rgba16Float => "rgba16float",
Sf::Rgba32Uint => "rgba32uint",
Sf::Rgba32Sint => "rgba32sint",
Sf::Rgba32Float => "rgba32float",
}
}
}
impl crate::TypeInner {
/// Formats the type as it is written in wgsl.
///
/// For example `vec3<f32>`.
///
/// Note: The names of a `TypeInner::Struct` is not known. Therefore this method will simply return "struct" for them.
pub fn to_wgsl(
&self,
types: &Arena<crate::Type>,
constants: &Arena<crate::Constant>,
) -> String {
match *self {
crate::TypeInner::Scalar { kind, width } => kind.to_wgsl(width),
crate::TypeInner::Vector { size, kind, width } => {
format!("vec{}<{}>", size as u32, kind.to_wgsl(width))
}
crate::TypeInner::Matrix {
columns,
rows,
width,
} => {
format!(
"mat{}x{}<{}>",
columns as u32,
rows as u32,
crate::ScalarKind::Float.to_wgsl(width),
)
}
crate::TypeInner::Pointer { base, .. } => {
let base = &types[base];
let name = base.name.as_deref().unwrap_or("unknown");
format!("*{}", name)
}
crate::TypeInner::ValuePointer { kind, width, .. } => {
format!("*{}", kind.to_wgsl(width))
}
crate::TypeInner::Array { base, size, .. } => {
let member_type = &types[base];
let base = member_type.name.as_deref().unwrap_or("unknown");
match size {
crate::ArraySize::Constant(size) => {
let size = constants[size].name.as_deref().unwrap_or("unknown");
format!("{}[{}]", base, size)
}
crate::ArraySize::Dynamic => format!("{}[]", base),
}
}
crate::TypeInner::Struct { .. } => {
// TODO: Actually output the struct?
"struct".to_string()
}
crate::TypeInner::Image {
dim,
arrayed,
class,
} => {
let dim_suffix = match dim {
crate::ImageDimension::D1 => "_1d",
crate::ImageDimension::D2 => "_2d",
crate::ImageDimension::D3 => "_3d",
crate::ImageDimension::Cube => "_cube",
};
let array_suffix = if arrayed { "_array" } else { "" };
let class_suffix = match class {
crate::ImageClass::Sampled { multi: true, .. } => "_multisampled",
crate::ImageClass::Depth => "_depth",
_ => "",
};
let type_in_brackets = match class {
crate::ImageClass::Sampled { kind, .. } => {
// Note: The only valid widths are 4 bytes wide.
// The lexer has already verified this, so we can safely assume it here.
// https://gpuweb.github.io/gpuweb/wgsl/#sampled-texture-type
let element_type = kind.to_wgsl(4);
format!("<{}>", element_type)
}
crate::ImageClass::Depth => String::new(),
crate::ImageClass::Storage(format) => {
format!("<{}>", format.to_wgsl())
}
};
format!(
"texture{}{}{}{}",
class_suffix, dim_suffix, array_suffix, type_in_brackets
)
}
crate::TypeInner::Sampler { .. } => "sampler".to_string(),
}
}
}
mod type_inner_tests {
#[test]
fn to_wgsl() {
let mut types = crate::Arena::new();
let mut constants = crate::Arena::new();
let c = constants.append(crate::Constant {
name: Some("C".to_string()),
specialization: None,
inner: crate::ConstantInner::Scalar {
width: 4,
value: crate::ScalarValue::Uint(32),
},
});
let mytype1 = types.append(crate::Type {
name: Some("MyType1".to_string()),
inner: crate::TypeInner::Struct {
top_level: true,
members: vec![],
span: 0,
},
});
let mytype2 = types.append(crate::Type {
name: Some("MyType2".to_string()),
inner: crate::TypeInner::Struct {
top_level: true,
members: vec![],
span: 0,
},
});
let array = crate::TypeInner::Array {
base: mytype1,
stride: 4,
size: crate::ArraySize::Constant(c),
};
assert_eq!(array.to_wgsl(&types, &constants), "MyType1[C]");
let mat = crate::TypeInner::Matrix {
rows: crate::VectorSize::Quad,
columns: crate::VectorSize::Bi,
width: 8,
};
assert_eq!(mat.to_wgsl(&types, &constants), "mat2x4<f64>");
let ptr = crate::TypeInner::Pointer {
base: mytype2,
class: crate::StorageClass::Storage,
};
assert_eq!(ptr.to_wgsl(&types, &constants), "*MyType2");
let img1 = crate::TypeInner::Image {
dim: crate::ImageDimension::D2,
arrayed: false,
class: crate::ImageClass::Sampled {
kind: crate::ScalarKind::Float,
multi: true,
},
};
assert_eq!(
img1.to_wgsl(&types, &constants),
"texture_multisampled_2d<f32>"
);
let img2 = crate::TypeInner::Image {
dim: crate::ImageDimension::Cube,
arrayed: true,
class: crate::ImageClass::Depth,
};
assert_eq!(img2.to_wgsl(&types, &constants), "texture_depth_cube_array");
}
}
impl crate::ScalarKind {
/// Format a scalar kind+width as a type is written in wgsl.
///
/// Examples: `f32`, `u64`, `bool`.
fn to_wgsl(self, width: u8) -> String {
let prefix = match self {
crate::ScalarKind::Sint => "i",
crate::ScalarKind::Uint => "u",
crate::ScalarKind::Float => "f",
crate::ScalarKind::Bool => return "bool".to_string(),
};
format!("{}{}", prefix, width * 8)
}
}
trait StringValueLookup<'a> {
type Value;
fn lookup(&self, key: &'a str, span: Span) -> Result<Self::Value, Error<'a>>;
}
impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle<crate::Expression>> {
type Value = Handle<crate::Expression>;
fn lookup(&self, key: &'a str, span: Span) -> Result<Self::Value, Error<'a>> {
self.get(key).cloned().ok_or(Error::UnknownIdent(span, key))
}
}
struct StatementContext<'input, 'temp, 'out> {
lookup_ident: &'temp mut FastHashMap<&'input str, Handle<crate::Expression>>,
typifier: &'temp mut super::Typifier,
variables: &'out mut Arena<crate::LocalVariable>,
expressions: &'out mut Arena<crate::Expression>,
named_expressions: &'out mut FastHashMap<Handle<crate::Expression>, String>,
types: &'out mut Arena<crate::Type>,
constants: &'out mut Arena<crate::Constant>,
global_vars: &'out Arena<crate::GlobalVariable>,
functions: &'out Arena<crate::Function>,
arguments: &'out [crate::FunctionArgument],
}
impl<'a, 'temp> StatementContext<'a, 'temp, '_> {
fn reborrow(&mut self) -> StatementContext<'a, '_, '_> {
StatementContext {
lookup_ident: self.lookup_ident,
typifier: self.typifier,
variables: self.variables,
expressions: self.expressions,
named_expressions: self.named_expressions,
types: self.types,
constants: self.constants,
global_vars: self.global_vars,
functions: self.functions,
arguments: self.arguments,
}
}
fn as_expression<'t>(
&'t mut self,
block: &'t mut crate::Block,
emitter: &'t mut super::Emitter,
) -> ExpressionContext<'a, 't, '_>
where
'temp: 't,
{
ExpressionContext {
lookup_ident: self.lookup_ident,
typifier: self.typifier,
expressions: self.expressions,
types: self.types,
constants: self.constants,
global_vars: self.global_vars,
local_vars: self.variables,
functions: self.functions,
arguments: self.arguments,
block,
emitter,
}
}
}
struct SamplingContext {
image: Handle<crate::Expression>,
arrayed: bool,
}
struct ExpressionContext<'input, 'temp, 'out> {
lookup_ident: &'temp FastHashMap<&'input str, Handle<crate::Expression>>,
typifier: &'temp mut super::Typifier,
expressions: &'out mut Arena<crate::Expression>,
types: &'out mut Arena<crate::Type>,
constants: &'out mut Arena<crate::Constant>,
global_vars: &'out Arena<crate::GlobalVariable>,
local_vars: &'out Arena<crate::LocalVariable>,
arguments: &'out [crate::FunctionArgument],
functions: &'out Arena<crate::Function>,
block: &'temp mut crate::Block,
emitter: &'temp mut super::Emitter,
}
impl<'a> ExpressionContext<'a, '_, '_> {
fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> {
ExpressionContext {
lookup_ident: self.lookup_ident,
typifier: self.typifier,
expressions: self.expressions,
types: self.types,
constants: self.constants,
global_vars: self.global_vars,
local_vars: self.local_vars,
functions: self.functions,
arguments: self.arguments,
block: self.block,
emitter: self.emitter,
}
}
fn resolve_type(
&mut self,
handle: Handle<crate::Expression>,
) -> Result<&crate::TypeInner, Error<'a>> {
let resolve_ctx = ResolveContext {
constants: self.constants,
types: self.types,
global_vars: self.global_vars,
local_vars: self.local_vars,
functions: self.functions,
arguments: self.arguments,
};
match self.typifier.grow(handle, self.expressions, &resolve_ctx) {
Err(e) => Err(Error::InvalidResolve(e)),
Ok(()) => Ok(self.typifier.get(handle, self.types)),
}
}
fn prepare_sampling(
&mut self,
image_name: &'a str,
span: Span,
) -> Result<SamplingContext, Error<'a>> {
let image = self.lookup_ident.lookup(image_name, span.clone())?;
Ok(SamplingContext {
image,
arrayed: match *self.resolve_type(image)? {
crate::TypeInner::Image { arrayed, .. } => arrayed,
_ => return Err(Error::BadTexture(span)),
},
})
}
fn parse_binary_op(
&mut self,
lexer: &mut Lexer<'a>,
classifier: impl Fn(Token<'a>) -> Option<crate::BinaryOperator>,
mut parser: impl FnMut(
&mut Lexer<'a>,
ExpressionContext<'a, '_, '_>,
) -> Result<Handle<crate::Expression>, Error<'a>>,
) -> Result<Handle<crate::Expression>, Error<'a>> {
let mut left = parser(lexer, self.reborrow())?;
while let Some(op) = classifier(lexer.peek().0) {
let _ = lexer.next();
let right = parser(lexer, self.reborrow())?;
left = self
.expressions
.append(crate::Expression::Binary { op, left, right });
}
Ok(left)
}
fn parse_binary_splat_op(
&mut self,
lexer: &mut Lexer<'a>,
classifier: impl Fn(Token<'a>) -> Option<crate::BinaryOperator>,
mut parser: impl FnMut(
&mut Lexer<'a>,
ExpressionContext<'a, '_, '_>,
) -> Result<Handle<crate::Expression>, Error<'a>>,
) -> Result<Handle<crate::Expression>, Error<'a>> {
let mut left = parser(lexer, self.reborrow())?;
while let Some(op) = classifier(lexer.peek().0) {
let _ = lexer.next();
let mut right = parser(lexer, self.reborrow())?;
// insert splats, if needed by the non-'*' operations
if op != crate::BinaryOperator::Multiply {
let left_size = match *self.resolve_type(left)? {
crate::TypeInner::Vector { size, .. } => Some(size),
_ => None,
};
match (left_size, self.resolve_type(right)?) {
(Some(size), &crate::TypeInner::Scalar { .. }) => {
right = self
.expressions
.append(crate::Expression::Splat { size, value: right });
}
(None, &crate::TypeInner::Vector { size, .. }) => {
left = self
.expressions
.append(crate::Expression::Splat { size, value: left });
}
_ => {}
}
}
left = self
.expressions
.append(crate::Expression::Binary { op, left, right });
}
Ok(left)
}
}
enum Composition {
Single(u32),
Multi(crate::VectorSize, [crate::SwizzleComponent; 4]),
}
impl Composition {
//TODO: could be `const fn` once MSRV allows
fn letter_component(letter: char) -> Option<crate::SwizzleComponent> {
use crate::SwizzleComponent as Sc;
match letter {
'x' | 'r' => Some(Sc::X),
'y' | 'g' => Some(Sc::Y),
'z' | 'b' => Some(Sc::Z),
'w' | 'a' => Some(Sc::W),
_ => None,
}
}
fn extract_impl(name: &str, name_span: Span) -> Result<u32, Error> {
let ch = name
.chars()
.next()
.ok_or_else(|| Error::BadAccessor(name_span.clone()))?;
match Self::letter_component(ch) {
Some(sc) => Ok(sc as u32),
None => Err(Error::BadAccessor(name_span)),
}
}
fn extract(
base: Handle<crate::Expression>,
name: &str,
name_span: Span,
) -> Result<crate::Expression, Error> {
Self::extract_impl(name, name_span)
.map(|index| crate::Expression::AccessIndex { base, index })
}
fn make(name: &str, name_span: Span) -> Result<Self, Error> {
if name.len() > 1 {
let mut components = [crate::SwizzleComponent::X; 4];
for (comp, ch) in components.iter_mut().zip(name.chars()) {
*comp = Self::letter_component(ch)
.ok_or_else(|| Error::BadAccessor(name_span.clone()))?;
}
let size = match name.len() {
2 => crate::VectorSize::Bi,
3 => crate::VectorSize::Tri,
4 => crate::VectorSize::Quad,
_ => return Err(Error::BadAccessor(name_span)),
};
Ok(Composition::Multi(size, components))
} else {
Self::extract_impl(name, name_span).map(Composition::Single)
}
}
}
#[derive(Default)]
struct TypeAttributes {
stride: Option<NonZeroU32>,
access: crate::StorageAccess,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Scope {
Attribute,
ImportDecl,
VariableDecl,
TypeDecl,
FunctionDecl,
Block,
Statement,
ConstantExpr,
PrimaryExpr,
SingularExpr,
GeneralExpr,
}
type LocalFunctionCall = (Handle<crate::Function>, Vec<Handle<crate::Expression>>);
#[derive(Default)]
struct BindingParser {
location: Option<u32>,
built_in: Option<crate::BuiltIn>,
interpolation: Option<crate::Interpolation>,
sampling: Option<crate::Sampling>,
}
impl BindingParser {
fn parse<'a>(
&mut self,
lexer: &mut Lexer<'a>,
name: &'a str,
name_span: Span,
) -> Result<(), Error<'a>> {
match name {
"location" => {
lexer.expect(Token::Paren('('))?;
self.location = Some(lexer.next_uint_literal()?);
lexer.expect(Token::Paren(')'))?;
}
"builtin" => {
lexer.expect(Token::Paren('('))?;
let (raw, span) = lexer.next_ident_with_span()?;
self.built_in = Some(conv::map_built_in(raw, span)?);
lexer.expect(Token::Paren(')'))?;
}
"interpolate" => {
lexer.expect(Token::Paren('('))?;
let (raw, span) = lexer.next_ident_with_span()?;
self.interpolation = Some(conv::map_interpolation(raw, span)?);
if lexer.skip(Token::Separator(',')) {
let (raw, span) = lexer.next_ident_with_span()?;
self.sampling = Some(conv::map_sampling(raw, span)?);
}
lexer.expect(Token::Paren(')'))?;
}
_ => return Err(Error::UnknownAttribute(name_span)),
}
Ok(())
}
fn finish<'a>(self) -> Result<Option<crate::Binding>, Error<'a>> {
match (
self.location,
self.built_in,
self.interpolation,
self.sampling,
) {
(None, None, None, None) => Ok(None),
(Some(location), None, interpolation, sampling) => {
// Before handing over the completed `Module`, we call
// `apply_common_default_interpolation` to ensure that the interpolation and
// sampling have been explicitly specified on all vertex shader output and fragment
// shader input user bindings, so leaving them potentially `None` here is fine.
Ok(Some(crate::Binding::Location {
location,
interpolation,
sampling,
}))
}
(None, Some(bi), None, None) => Ok(Some(crate::Binding::BuiltIn(bi))),
(location, built_in, interpolation, sampling) => Err(Error::InconsistentBinding(
location,
built_in,
interpolation,
sampling,
)),
}
}
}
struct ParsedVariable<'a> {
name: &'a str,
class: Option<crate::StorageClass>,
ty: Handle<crate::Type>,
access: crate::StorageAccess,
init: Option<Handle<crate::Constant>>,
}
#[derive(Clone, Debug)]
pub struct ParseError {
message: String,
labels: Vec<(Span, Cow<'static, str>)>,
notes: Vec<String>,
}
impl ParseError {
fn diagnostic(&self) -> Diagnostic<()> {
let diagnostic = Diagnostic::error()
.with_message(self.message.to_string())
.with_labels(
self.labels
.iter()
.map(|label| {
Label::primary((), label.0.clone()).with_message(label.1.to_string())
})
.collect(),
)
.with_notes(
self.notes
.iter()
.map(|note| format!("note: {}", note))
.collect(),
);
diagnostic
}
/// Emits a summary of the error to standard error stream.
pub fn emit_to_stderr(&self, source: &str) {
let files = SimpleFile::new("wgsl", source);
let config = codespan_reporting::term::Config::default();
let writer = StandardStream::stderr(ColorChoice::Always);
term::emit(&mut writer.lock(), &config, &files, &self.diagnostic())
.expect("cannot write error");
}
/// Emits a summary of the error to a string.
pub fn emit_to_string(&self, source: &str) -> String {
let files = SimpleFile::new("wgsl", source);
let config = codespan_reporting::term::Config::default();
let mut writer = StringErrorBuffer::new();
term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error");
writer.into_string()
}
/// Returns the 1-based line number and column of the first label in the
/// error message.
pub fn location(&self, source: &str) -> (usize, usize) {
let files = SimpleFile::new("wgsl", source);
match self.labels.get(0) {
Some(label) => {
let location = files
.location((), label.0.start)
.expect("invalid span location");
(location.line_number, location.column_number)
}