1use alloc::{format, string::String, vec::Vec};
2
3use super::{
4 ast::*,
5 context::{Context, ExprPos},
6 error::{Error, ErrorKind},
7 Frontend, Result, Span,
8};
9use crate::{
10 AddressSpace, Binding, BuiltIn, Constant, Expression, GlobalVariable, Handle, LocalVariable,
11 Override, ResourceBinding, Scalar, ShaderStage, SwizzleComponent, Type, TypeInner, VectorSize,
12};
13
14pub struct VarDeclaration<'a, 'key> {
15 pub qualifiers: &'a mut TypeQualifiers<'key>,
16 pub ty: Handle<Type>,
17 pub name: Option<String>,
18 pub init: Option<Handle<Expression>>,
19 pub meta: Span,
20}
21
22struct BuiltInData {
24 inner: TypeInner,
26 builtin: BuiltIn,
28 mutable: bool,
30 storage: StorageQualifier,
32}
33
34pub enum GlobalOrConstant {
35 Global(Handle<GlobalVariable>),
36 Constant(Handle<Constant>),
37 Override(Handle<Override>),
38}
39
40impl Frontend {
41 fn add_builtin(
43 &mut self,
44 ctx: &mut Context,
45 name: &str,
46 data: BuiltInData,
47 meta: Span,
48 ) -> Result<Option<VariableReference>> {
49 let ty = ctx.module.types.insert(
50 Type {
51 name: None,
52 inner: data.inner,
53 },
54 meta,
55 );
56
57 let handle = ctx.module.global_variables.append(
58 GlobalVariable {
59 name: Some(name.into()),
60 space: AddressSpace::Private,
61 binding: None,
62 ty,
63 init: None,
64 memory_decorations: crate::MemoryDecorations::empty(),
65 },
66 meta,
67 );
68
69 let idx = self.entry_args.len();
70 self.entry_args.push(EntryArg {
71 name: Some(name.into()),
72 binding: Binding::BuiltIn(data.builtin),
73 handle,
74 storage: data.storage,
75 });
76
77 self.global_variables.push((
78 name.into(),
79 GlobalLookup {
80 kind: GlobalLookupKind::Variable(handle),
81 entry_arg: Some(idx),
82 mutable: data.mutable,
83 },
84 ));
85
86 let expr = ctx.add_expression(Expression::GlobalVariable(handle), meta)?;
87
88 let var = VariableReference {
89 expr,
90 load: true,
91 mutable: data.mutable,
92 constant: None,
93 entry_arg: Some(idx),
94 };
95
96 ctx.symbol_table.add_root(name.into(), var.clone());
97
98 Ok(Some(var))
99 }
100
101 pub(crate) fn lookup_variable(
102 &mut self,
103 ctx: &mut Context,
104 name: &str,
105 meta: Span,
106 ) -> Result<Option<VariableReference>> {
107 if let Some(var) = ctx.symbol_table.lookup(name).cloned() {
108 return Ok(Some(var));
109 }
110
111 let data = match name {
112 "gl_Position" => BuiltInData {
113 inner: TypeInner::Vector {
114 size: VectorSize::Quad,
115 scalar: Scalar::F32,
116 },
117 builtin: BuiltIn::Position { invariant: false },
118 mutable: true,
119 storage: StorageQualifier::Output,
120 },
121 "gl_FragCoord" => BuiltInData {
122 inner: TypeInner::Vector {
123 size: VectorSize::Quad,
124 scalar: Scalar::F32,
125 },
126 builtin: BuiltIn::Position { invariant: false },
127 mutable: false,
128 storage: StorageQualifier::Input,
129 },
130 "gl_PointCoord" => BuiltInData {
131 inner: TypeInner::Vector {
132 size: VectorSize::Bi,
133 scalar: Scalar::F32,
134 },
135 builtin: BuiltIn::PointCoord,
136 mutable: false,
137 storage: StorageQualifier::Input,
138 },
139 "gl_GlobalInvocationID"
140 | "gl_NumWorkGroups"
141 | "gl_WorkGroupSize"
142 | "gl_WorkGroupID"
143 | "gl_LocalInvocationID" => BuiltInData {
144 inner: TypeInner::Vector {
145 size: VectorSize::Tri,
146 scalar: Scalar::U32,
147 },
148 builtin: match name {
149 "gl_GlobalInvocationID" => BuiltIn::GlobalInvocationId,
150 "gl_NumWorkGroups" => BuiltIn::NumWorkGroups,
151 "gl_WorkGroupSize" => BuiltIn::WorkGroupSize,
152 "gl_WorkGroupID" => BuiltIn::WorkGroupId,
153 "gl_LocalInvocationID" => BuiltIn::LocalInvocationId,
154 _ => unreachable!(),
155 },
156 mutable: false,
157 storage: StorageQualifier::Input,
158 },
159 "gl_FrontFacing" => BuiltInData {
160 inner: TypeInner::Scalar(Scalar::BOOL),
161 builtin: BuiltIn::FrontFacing,
162 mutable: false,
163 storage: StorageQualifier::Input,
164 },
165 "gl_PointSize" | "gl_FragDepth" => BuiltInData {
166 inner: TypeInner::Scalar(Scalar::F32),
167 builtin: match name {
168 "gl_PointSize" => BuiltIn::PointSize,
169 "gl_FragDepth" => BuiltIn::FragDepth,
170 _ => unreachable!(),
171 },
172 mutable: true,
173 storage: StorageQualifier::Output,
174 },
175 "gl_ClipDistance" | "gl_CullDistance" => {
176 let base = ctx.module.types.insert(
177 Type {
178 name: None,
179 inner: TypeInner::Scalar(Scalar::F32),
180 },
181 meta,
182 );
183
184 BuiltInData {
185 inner: TypeInner::Array {
186 base,
187 size: crate::ArraySize::Dynamic,
188 stride: 4,
189 },
190 builtin: match name {
191 "gl_ClipDistance" => BuiltIn::ClipDistances,
192 "gl_CullDistance" => BuiltIn::CullDistance,
193 _ => unreachable!(),
194 },
195 mutable: self.meta.stage == ShaderStage::Vertex,
196 storage: StorageQualifier::Output,
197 }
198 }
199 _ => {
200 let builtin = match name {
201 "gl_BaseVertex" => BuiltIn::BaseVertex,
202 "gl_BaseInstance" => BuiltIn::BaseInstance,
203 "gl_PrimitiveID" => BuiltIn::PrimitiveIndex,
204 "gl_BaryCoordEXT" => BuiltIn::Barycentric { perspective: true },
205 "gl_BaryCoordNoPerspEXT" => BuiltIn::Barycentric { perspective: false },
206 "gl_InstanceIndex" => BuiltIn::InstanceIndex,
207 "gl_VertexIndex" => BuiltIn::VertexIndex,
208 "gl_SampleID" => BuiltIn::SampleIndex,
209 "gl_LocalInvocationIndex" => BuiltIn::LocalInvocationIndex,
210 "gl_DrawID" => BuiltIn::DrawIndex,
211 "gl_SubgroupSize" => BuiltIn::SubgroupSize,
212 "gl_SubgroupInvocationID" => BuiltIn::SubgroupInvocationId,
213 _ => return Ok(None),
214 };
215
216 BuiltInData {
217 inner: TypeInner::Scalar(Scalar::U32),
218 builtin,
219 mutable: false,
220 storage: StorageQualifier::Input,
221 }
222 }
223 };
224
225 self.add_builtin(ctx, name, data, meta)
226 }
227
228 pub(crate) fn make_variable_invariant(
229 &mut self,
230 ctx: &mut Context,
231 name: &str,
232 meta: Span,
233 ) -> Result<()> {
234 if let Some(var) = self.lookup_variable(ctx, name, meta)? {
235 if let Some(index) = var.entry_arg {
236 if let Binding::BuiltIn(BuiltIn::Position { ref mut invariant }) =
237 self.entry_args[index].binding
238 {
239 *invariant = true;
240 }
241 }
242 }
243 Ok(())
244 }
245
246 pub(crate) fn field_selection(
247 &mut self,
248 ctx: &mut Context,
249 pos: ExprPos,
250 expression: Handle<Expression>,
251 name: &str,
252 meta: Span,
253 ) -> Result<Handle<Expression>> {
254 let (ty, is_pointer) = match *ctx.resolve_type(expression, meta)? {
255 TypeInner::Pointer { base, .. } => (&ctx.module.types[base].inner, true),
256 ref ty => (ty, false),
257 };
258 match *ty {
259 TypeInner::Struct { ref members, .. } => {
260 let index = members
261 .iter()
262 .position(|m| m.name == Some(name.into()))
263 .ok_or_else(|| Error {
264 kind: ErrorKind::UnknownField(name.into()),
265 meta,
266 })?;
267 let pointer = ctx.add_expression(
268 Expression::AccessIndex {
269 base: expression,
270 index: index as u32,
271 },
272 meta,
273 )?;
274
275 Ok(match pos {
276 ExprPos::Rhs if is_pointer => {
277 ctx.add_expression(Expression::Load { pointer }, meta)?
278 }
279 _ => pointer,
280 })
281 }
282 TypeInner::Vector { size, .. } => {
284 let check_swizzle_components = |comps: &str| {
285 name.chars()
286 .map(|c| {
287 comps
288 .find(c)
289 .filter(|i| *i < size as usize)
290 .map(|i| SwizzleComponent::from_index(i as u32))
291 })
292 .collect::<Option<Vec<SwizzleComponent>>>()
293 };
294
295 let components = check_swizzle_components("xyzw")
296 .or_else(|| check_swizzle_components("rgba"))
297 .or_else(|| check_swizzle_components("stpq"));
298
299 if let Some(components) = components {
300 if let ExprPos::Lhs = pos {
301 let not_unique = (1..components.len())
302 .any(|i| components[i..].contains(&components[i - 1]));
303 if not_unique {
304 self.errors.push(Error {
305 kind: ErrorKind::SemanticError(
306 format!(
307 concat!(
308 "swizzle cannot have duplicate components in ",
309 "left-hand-side expression for \"{:?}\""
310 ),
311 name
312 )
313 .into(),
314 ),
315 meta,
316 })
317 }
318 }
319
320 let mut pattern = [SwizzleComponent::X; 4];
321 for (pat, component) in pattern.iter_mut().zip(&components) {
322 *pat = *component;
323 }
324
325 let mut expression = expression;
327 if let Expression::Swizzle {
328 size: _,
329 vector,
330 pattern: ref src_pattern,
331 } = ctx[expression]
332 {
333 expression = vector;
334 for pat in &mut pattern {
335 *pat = src_pattern[pat.index() as usize];
336 }
337 }
338
339 let size = match components.len() {
340 1 => {
342 match pos {
343 ExprPos::Rhs if is_pointer => {
347 expression = ctx.add_expression(
348 Expression::Load {
349 pointer: expression,
350 },
351 meta,
352 )?;
353 }
354 _ => {}
355 };
356 return ctx.add_expression(
357 Expression::AccessIndex {
358 base: expression,
359 index: pattern[0].index(),
360 },
361 meta,
362 );
363 }
364 2 => VectorSize::Bi,
365 3 => VectorSize::Tri,
366 4 => VectorSize::Quad,
367 _ => {
368 self.errors.push(Error {
369 kind: ErrorKind::SemanticError(
370 format!("Bad swizzle size for \"{name:?}\"").into(),
371 ),
372 meta,
373 });
374
375 VectorSize::Quad
376 }
377 };
378
379 if is_pointer {
380 expression = ctx.add_expression(
384 Expression::Load {
385 pointer: expression,
386 },
387 meta,
388 )?;
389 }
390
391 Ok(ctx.add_expression(
392 Expression::Swizzle {
393 size,
394 vector: expression,
395 pattern,
396 },
397 meta,
398 )?)
399 } else {
400 Err(Error {
401 kind: ErrorKind::SemanticError(
402 format!("Invalid swizzle for vector \"{name}\"").into(),
403 ),
404 meta,
405 })
406 }
407 }
408 _ => Err(Error {
409 kind: ErrorKind::SemanticError(
410 format!("Can't lookup field on this type \"{name}\"").into(),
411 ),
412 meta,
413 }),
414 }
415 }
416
417 pub(crate) fn add_global_var(
418 &mut self,
419 ctx: &mut Context,
420 VarDeclaration {
421 qualifiers,
422 mut ty,
423 name,
424 init,
425 meta,
426 }: VarDeclaration,
427 ) -> Result<GlobalOrConstant> {
428 let storage = qualifiers.storage.0;
429 let (ret, lookup) = match storage {
430 StorageQualifier::Input | StorageQualifier::Output => {
431 let input = storage == StorageQualifier::Input;
432 let location = qualifiers
435 .uint_layout_qualifier("location", &mut self.errors)
436 .unwrap_or(0);
437
438 let interpolation = qualifiers.interpolation.take().map(|(i, _)| i);
439 let sampling = qualifiers.sampling.take().map(|(s, _)| s);
440
441 let handle = ctx.module.global_variables.append(
442 GlobalVariable {
443 name: name.clone(),
444 space: AddressSpace::Private,
445 binding: None,
446 ty,
447 init,
448 memory_decorations: crate::MemoryDecorations::empty(),
449 },
450 meta,
451 );
452
453 let blend_src = qualifiers
454 .layout_qualifiers
455 .remove(&QualifierKey::Index)
456 .and_then(|(value, _span)| match value {
457 QualifierValue::Uint(index) => Some(index),
458 _ => None,
459 });
460
461 let mut binding = Binding::Location {
462 location,
463 interpolation,
464 sampling,
465 blend_src,
466 per_primitive: false,
467 };
468
469 binding.apply_default_interpolation(&ctx.module.types[ty].inner);
470
471 let idx = self.entry_args.len();
472 self.entry_args.push(EntryArg {
473 name: name.clone(),
474 binding,
475 handle,
476 storage,
477 });
478
479 let lookup = GlobalLookup {
480 kind: GlobalLookupKind::Variable(handle),
481 entry_arg: Some(idx),
482 mutable: !input,
483 };
484
485 (GlobalOrConstant::Global(handle), lookup)
486 }
487 StorageQualifier::Const => {
488 let constant_id = qualifiers.uint_layout_qualifier("constant_id", &mut self.errors);
490
491 if let Some(id) = constant_id {
492 let id: Option<u16> = match id.try_into() {
494 Ok(v) => Some(v),
495 Err(_) => {
496 self.errors.push(Error {
497 kind: ErrorKind::SemanticError(
498 format!(
499 "constant_id value {id} is too high (maximum is {})",
500 u16::MAX
501 )
502 .into(),
503 ),
504 meta,
505 });
506 None
507 }
508 };
509
510 let override_handle = ctx.module.overrides.append(
511 Override {
512 name: name.clone(),
513 id,
514 ty,
515 init,
516 },
517 meta,
518 );
519
520 let lookup = GlobalLookup {
521 kind: GlobalLookupKind::Override(override_handle, ty),
522 entry_arg: None,
523 mutable: false,
524 };
525
526 (GlobalOrConstant::Override(override_handle), lookup)
527 } else {
528 let init = init.ok_or_else(|| Error {
530 kind: ErrorKind::SemanticError(
531 "const values must have an initializer".into(),
532 ),
533 meta,
534 })?;
535
536 let constant = Constant {
537 name: name.clone(),
538 ty,
539 init,
540 };
541 let handle = ctx.module.constants.append(constant, meta);
542
543 let lookup = GlobalLookup {
544 kind: GlobalLookupKind::Constant(handle, ty),
545 entry_arg: None,
546 mutable: false,
547 };
548
549 (GlobalOrConstant::Constant(handle), lookup)
550 }
551 }
552 StorageQualifier::AddressSpace(mut space) => {
553 match space {
554 AddressSpace::Storage { ref mut access } => {
555 if let Some((allowed_access, _)) = qualifiers.storage_access.take() {
556 *access = allowed_access;
557 }
558 }
559 AddressSpace::Uniform => match ctx.module.types[ty].inner {
560 TypeInner::Image {
561 class,
562 dim,
563 arrayed,
564 } => {
565 if let crate::ImageClass::Storage {
566 mut access,
567 mut format,
568 } = class
569 {
570 if let Some((allowed_access, _)) = qualifiers.storage_access.take()
571 {
572 access = allowed_access;
573 }
574
575 match qualifiers.layout_qualifiers.remove(&QualifierKey::Format) {
576 Some((QualifierValue::Format(f), _)) => format = f,
577 None => self.errors.push(Error {
580 kind: ErrorKind::SemanticError(
581 "image types require a format layout qualifier".into(),
582 ),
583 meta,
584 }),
585 _ => unreachable!(),
586 }
587
588 ty = ctx.module.types.insert(
589 Type {
590 name: None,
591 inner: TypeInner::Image {
592 dim,
593 arrayed,
594 class: crate::ImageClass::Storage { format, access },
595 },
596 },
597 meta,
598 );
599 }
600
601 space = AddressSpace::Handle
602 }
603 TypeInner::Sampler { .. } => space = AddressSpace::Handle,
604 _ => {
605 if qualifiers.none_layout_qualifier("push_constant", &mut self.errors) {
606 space = AddressSpace::Immediate
607 }
608 }
609 },
610 AddressSpace::Function => space = AddressSpace::Private,
611 _ => {}
612 };
613
614 let binding = match space {
615 AddressSpace::Uniform | AddressSpace::Storage { .. } | AddressSpace::Handle => {
616 let binding = qualifiers.uint_layout_qualifier("binding", &mut self.errors);
617 if binding.is_none() {
618 self.errors.push(Error {
619 kind: ErrorKind::SemanticError(
620 "uniform/buffer blocks require layout(binding=X)".into(),
621 ),
622 meta,
623 });
624 }
625 let set = qualifiers.uint_layout_qualifier("set", &mut self.errors);
626 binding.map(|binding| ResourceBinding {
627 group: set.unwrap_or(0),
628 binding,
629 })
630 }
631 _ => None,
632 };
633
634 let handle = ctx.module.global_variables.append(
635 GlobalVariable {
636 name: name.clone(),
637 space,
638 binding,
639 ty,
640 init,
641 memory_decorations: crate::MemoryDecorations::empty(),
642 },
643 meta,
644 );
645
646 let lookup = GlobalLookup {
647 kind: GlobalLookupKind::Variable(handle),
648 entry_arg: None,
649 mutable: true,
650 };
651
652 (GlobalOrConstant::Global(handle), lookup)
653 }
654 };
655
656 if let Some(name) = name {
657 ctx.add_global(&name, lookup)?;
658
659 self.global_variables.push((name, lookup));
660 }
661
662 qualifiers.unused_errors(&mut self.errors);
663
664 Ok(ret)
665 }
666
667 pub(crate) fn add_local_var(
668 &mut self,
669 ctx: &mut Context,
670 decl: VarDeclaration,
671 ) -> Result<Handle<Expression>> {
672 let storage = decl.qualifiers.storage;
673 let mutable = match storage.0 {
674 StorageQualifier::AddressSpace(AddressSpace::Function) => true,
675 StorageQualifier::Const => false,
676 _ => {
677 self.errors.push(Error {
678 kind: ErrorKind::SemanticError("Locals cannot have a storage qualifier".into()),
679 meta: storage.1,
680 });
681 true
682 }
683 };
684
685 let handle = ctx.locals.append(
686 LocalVariable {
687 name: decl.name.clone(),
688 ty: decl.ty,
689 init: decl.init,
690 },
691 decl.meta,
692 );
693 let expr = ctx.add_expression(Expression::LocalVariable(handle), decl.meta)?;
694
695 if let Some(name) = decl.name {
696 let maybe_var = ctx.add_local_var(name.clone(), expr, mutable);
697
698 if maybe_var.is_some() {
699 self.errors.push(Error {
700 kind: ErrorKind::VariableAlreadyDeclared(name),
701 meta: decl.meta,
702 })
703 }
704 }
705
706 decl.qualifiers.unused_errors(&mut self.errors);
707
708 Ok(expr)
709 }
710}