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
//! WGSL's automatic conversions for abstract types.

use crate::{Handle, Span};

impl<'source, 'temp, 'out> super::ExpressionContext<'source, 'temp, 'out> {
    /// Try to use WGSL's automatic conversions to convert `expr` to `goal_ty`.
    ///
    /// If no conversions are necessary, return `expr` unchanged.
    ///
    /// If automatic conversions cannot convert `expr` to `goal_ty`, return an
    /// [`AutoConversion`] error.
    ///
    /// Although the Load Rule is one of the automatic conversions, this
    /// function assumes it has already been applied if appropriate, as
    /// indicated by the fact that the Rust type of `expr` is not `Typed<_>`.
    ///
    /// [`AutoConversion`]: super::Error::AutoConversion
    pub fn try_automatic_conversions(
        &mut self,
        expr: Handle<crate::Expression>,
        goal_ty: &crate::proc::TypeResolution,
        goal_span: Span,
    ) -> Result<Handle<crate::Expression>, super::Error<'source>> {
        let expr_span = self.get_expression_span(expr);
        // Keep the TypeResolution so we can get type names for
        // structs in error messages.
        let expr_resolution = super::resolve!(self, expr);
        let types = &self.module.types;
        let expr_inner = expr_resolution.inner_with(types);
        let goal_inner = goal_ty.inner_with(types);

        // If `expr` already has the requested type, we're done.
        if expr_inner.equivalent(goal_inner, types) {
            return Ok(expr);
        }

        let (_expr_scalar, goal_scalar) =
            match expr_inner.automatically_converts_to(goal_inner, types) {
                Some(scalars) => scalars,
                None => {
                    let gctx = &self.module.to_ctx();
                    let source_type = expr_resolution.to_wgsl(gctx);
                    let dest_type = goal_ty.to_wgsl(gctx);

                    return Err(super::Error::AutoConversion {
                        dest_span: goal_span,
                        dest_type,
                        source_span: expr_span,
                        source_type,
                    });
                }
            };

        self.convert_leaf_scalar(expr, expr_span, goal_scalar)
    }

    /// Try to convert `expr`'s leaf scalar to `goal` using automatic conversions.
    ///
    /// If no conversions are necessary, return `expr` unchanged.
    ///
    /// If automatic conversions cannot convert `expr` to `goal_scalar`, return
    /// an [`AutoConversionLeafScalar`] error.
    ///
    /// Although the Load Rule is one of the automatic conversions, this
    /// function assumes it has already been applied if appropriate, as
    /// indicated by the fact that the Rust type of `expr` is not `Typed<_>`.
    ///
    /// [`AutoConversionLeafScalar`]: super::Error::AutoConversionLeafScalar
    pub fn try_automatic_conversion_for_leaf_scalar(
        &mut self,
        expr: Handle<crate::Expression>,
        goal_scalar: crate::Scalar,
        goal_span: Span,
    ) -> Result<Handle<crate::Expression>, super::Error<'source>> {
        let expr_span = self.get_expression_span(expr);
        let expr_resolution = super::resolve!(self, expr);
        let types = &self.module.types;
        let expr_inner = expr_resolution.inner_with(types);

        let make_error = || {
            let gctx = &self.module.to_ctx();
            let source_type = expr_resolution.to_wgsl(gctx);
            super::Error::AutoConversionLeafScalar {
                dest_span: goal_span,
                dest_scalar: goal_scalar.to_wgsl(),
                source_span: expr_span,
                source_type,
            }
        };

        let expr_scalar = match expr_inner.scalar() {
            Some(scalar) => scalar,
            None => return Err(make_error()),
        };

        if expr_scalar == goal_scalar {
            return Ok(expr);
        }

        if !expr_scalar.automatically_converts_to(goal_scalar) {
            return Err(make_error());
        }

        assert!(expr_scalar.is_abstract());

        self.convert_leaf_scalar(expr, expr_span, goal_scalar)
    }

    fn convert_leaf_scalar(
        &mut self,
        expr: Handle<crate::Expression>,
        expr_span: Span,
        goal_scalar: crate::Scalar,
    ) -> Result<Handle<crate::Expression>, super::Error<'source>> {
        let expr_inner = super::resolve_inner!(self, expr);
        if let crate::TypeInner::Array { .. } = *expr_inner {
            self.as_const_evaluator()
                .cast_array(expr, goal_scalar, expr_span)
                .map_err(|err| super::Error::ConstantEvaluatorError(err, expr_span))
        } else {
            let cast = crate::Expression::As {
                expr,
                kind: goal_scalar.kind,
                convert: Some(goal_scalar.width),
            };
            self.append_expression(cast, expr_span)
        }
    }

    /// Try to convert `exprs` to `goal_ty` using WGSL's automatic conversions.
    pub fn try_automatic_conversions_slice(
        &mut self,
        exprs: &mut [Handle<crate::Expression>],
        goal_ty: &crate::proc::TypeResolution,
        goal_span: Span,
    ) -> Result<(), super::Error<'source>> {
        for expr in exprs.iter_mut() {
            *expr = self.try_automatic_conversions(*expr, goal_ty, goal_span)?;
        }

        Ok(())
    }

    /// Apply WGSL's automatic conversions to a vector constructor's arguments.
    ///
    /// When calling a vector constructor like `vec3<f32>(...)`, the parameters
    /// can be a mix of scalars and vectors, with the latter being spread out to
    /// contribute each of their components as a component of the new value.
    /// When the element type is explicit, as with `<f32>` in the example above,
    /// WGSL's automatic conversions should convert abstract scalar and vector
    /// parameters to the constructor's required scalar type.
    pub fn try_automatic_conversions_for_vector(
        &mut self,
        exprs: &mut [Handle<crate::Expression>],
        goal_scalar: crate::Scalar,
        goal_span: Span,
    ) -> Result<(), super::Error<'source>> {
        use crate::proc::TypeResolution as Tr;
        use crate::TypeInner as Ti;
        let goal_scalar_res = Tr::Value(Ti::Scalar(goal_scalar));

        for (i, expr) in exprs.iter_mut().enumerate() {
            // Keep the TypeResolution so we can get full type names
            // in error messages.
            let expr_resolution = super::resolve!(self, *expr);
            let types = &self.module.types;
            let expr_inner = expr_resolution.inner_with(types);

            match *expr_inner {
                Ti::Scalar(_) => {
                    *expr = self.try_automatic_conversions(*expr, &goal_scalar_res, goal_span)?;
                }
                Ti::Vector { size, scalar: _ } => {
                    let goal_vector_res = Tr::Value(Ti::Vector {
                        size,
                        scalar: goal_scalar,
                    });
                    *expr = self.try_automatic_conversions(*expr, &goal_vector_res, goal_span)?;
                }
                _ => {
                    let span = self.get_expression_span(*expr);
                    return Err(super::Error::InvalidConstructorComponentType(
                        span, i as i32,
                    ));
                }
            }
        }

        Ok(())
    }

    /// Convert `expr` to the leaf scalar type `scalar`.
    pub fn convert_to_leaf_scalar(
        &mut self,
        expr: &mut Handle<crate::Expression>,
        goal: crate::Scalar,
    ) -> Result<(), super::Error<'source>> {
        let inner = super::resolve_inner!(self, *expr);
        // Do nothing if `inner` doesn't even have leaf scalars;
        // it's a type error that validation will catch.
        if inner.scalar() != Some(goal) {
            let cast = crate::Expression::As {
                expr: *expr,
                kind: goal.kind,
                convert: Some(goal.width),
            };
            let expr_span = self.get_expression_span(*expr);
            *expr = self.append_expression(cast, expr_span)?;
        }

        Ok(())
    }

    /// Convert all expressions in `exprs` to a common scalar type.
    ///
    /// Note that the caller is responsible for making sure these
    /// conversions are actually justified. This function simply
    /// generates `As` expressions, regardless of whether they are
    /// permitted WGSL automatic conversions. Callers intending to
    /// implement automatic conversions need to determine for
    /// themselves whether the casts we we generate are justified,
    /// perhaps by calling `TypeInner::automatically_converts_to` or
    /// `Scalar::automatic_conversion_combine`.
    pub fn convert_slice_to_common_leaf_scalar(
        &mut self,
        exprs: &mut [Handle<crate::Expression>],
        goal: crate::Scalar,
    ) -> Result<(), super::Error<'source>> {
        for expr in exprs.iter_mut() {
            self.convert_to_leaf_scalar(expr, goal)?;
        }

        Ok(())
    }

    /// Return an expression for the concretized value of `expr`.
    ///
    /// If `expr` is already concrete, return it unchanged.
    pub fn concretize(
        &mut self,
        mut expr: Handle<crate::Expression>,
    ) -> Result<Handle<crate::Expression>, super::Error<'source>> {
        let inner = super::resolve_inner!(self, expr);
        if let Some(scalar) = inner.automatically_convertible_scalar(&self.module.types) {
            let concretized = scalar.concretize();
            if concretized != scalar {
                assert!(scalar.is_abstract());
                let expr_span = self.get_expression_span(expr);
                expr = self
                    .as_const_evaluator()
                    .cast_array(expr, concretized, expr_span)
                    .map_err(|err| {
                        // A `TypeResolution` includes the type's full name, if
                        // it has one. Also, avoid holding the borrow of `inner`
                        // across the call to `cast_array`.
                        let expr_type = &self.typifier()[expr];
                        super::Error::ConcretizationFailed {
                            expr_span,
                            expr_type: expr_type.to_wgsl(&self.module.to_ctx()),
                            scalar: concretized.to_wgsl(),
                            inner: err,
                        }
                    })?;
            }
        }

        Ok(expr)
    }

    /// Find the consensus scalar of `components` under WGSL's automatic
    /// conversions.
    ///
    /// If `components` can all be converted to any common scalar via
    /// WGSL's automatic conversions, return the best such scalar.
    ///
    /// The `components` slice must not be empty. All elements' types must
    /// have been resolved.
    ///
    /// If `components` are definitely not acceptable as arguments to such
    /// constructors, return `Err(i)`, where `i` is the index in
    /// `components` of some problematic argument.
    ///
    /// This function doesn't fully type-check the arguments - it only
    /// considers their leaf scalar types. This means it may return `Ok`
    /// even when the Naga validator will reject the resulting
    /// construction expression later.
    pub fn automatic_conversion_consensus<'handle, I>(
        &self,
        components: I,
    ) -> Result<crate::Scalar, usize>
    where
        I: IntoIterator<Item = &'handle Handle<crate::Expression>>,
        I::IntoIter: Clone, // for debugging
    {
        let types = &self.module.types;
        let mut inners = components
            .into_iter()
            .map(|&c| self.typifier()[c].inner_with(types));
        log::debug!(
            "wgsl automatic_conversion_consensus: {:?}",
            inners
                .clone()
                .map(|inner| inner.to_wgsl(&self.module.to_ctx()))
                .collect::<Vec<String>>()
        );
        let mut best = inners.next().unwrap().scalar().ok_or(0_usize)?;
        for (inner, i) in inners.zip(1..) {
            let scalar = inner.scalar().ok_or(i)?;
            match best.automatic_conversion_combine(scalar) {
                Some(new_best) => {
                    best = new_best;
                }
                None => return Err(i),
            }
        }

        log::debug!("    consensus: {:?}", best.to_wgsl());
        Ok(best)
    }
}

impl crate::TypeInner {
    /// Determine whether `self` automatically converts to `goal`.
    ///
    /// If WGSL's automatic conversions (excluding the Load Rule) will
    /// convert `self` to `goal`, then return a pair `(from, to)`,
    /// where `from` and `to` are the scalar types of the leaf values
    /// of `self` and `goal`.
    ///
    /// This function assumes that `self` and `goal` are different
    /// types. Callers should first check whether any conversion is
    /// needed at all.
    ///
    /// If the automatic conversions cannot convert `self` to `goal`,
    /// return `None`.
    fn automatically_converts_to(
        &self,
        goal: &Self,
        types: &crate::UniqueArena<crate::Type>,
    ) -> Option<(crate::Scalar, crate::Scalar)> {
        use crate::ScalarKind as Sk;
        use crate::TypeInner as Ti;

        // Automatic conversions only change the scalar type of a value's leaves
        // (e.g., `vec4<AbstractFloat>` to `vec4<f32>`), never the type
        // constructors applied to those scalar types (e.g., never scalar to
        // `vec4`, or `vec2` to `vec3`). So first we check that the type
        // constructors match, extracting the leaf scalar types in the process.
        let expr_scalar;
        let goal_scalar;
        match (self, goal) {
            (&Ti::Scalar(expr), &Ti::Scalar(goal)) => {
                expr_scalar = expr;
                goal_scalar = goal;
            }
            (
                &Ti::Vector {
                    size: expr_size,
                    scalar: expr,
                },
                &Ti::Vector {
                    size: goal_size,
                    scalar: goal,
                },
            ) if expr_size == goal_size => {
                expr_scalar = expr;
                goal_scalar = goal;
            }
            (
                &Ti::Matrix {
                    rows: expr_rows,
                    columns: expr_columns,
                    scalar: expr,
                },
                &Ti::Matrix {
                    rows: goal_rows,
                    columns: goal_columns,
                    scalar: goal,
                },
            ) if expr_rows == goal_rows && expr_columns == goal_columns => {
                expr_scalar = expr;
                goal_scalar = goal;
            }
            (
                &Ti::Array {
                    base: expr_base,
                    size: expr_size,
                    stride: _,
                },
                &Ti::Array {
                    base: goal_base,
                    size: goal_size,
                    stride: _,
                },
            ) if expr_size == goal_size => {
                return types[expr_base]
                    .inner
                    .automatically_converts_to(&types[goal_base].inner, types);
            }
            _ => return None,
        }

        match (expr_scalar.kind, goal_scalar.kind) {
            (Sk::AbstractFloat, Sk::Float) => {}
            (Sk::AbstractInt, Sk::Sint | Sk::Uint | Sk::AbstractFloat | Sk::Float) => {}
            _ => return None,
        }

        log::trace!("      okay: expr {expr_scalar:?}, goal {goal_scalar:?}");
        Some((expr_scalar, goal_scalar))
    }

    fn automatically_convertible_scalar(
        &self,
        types: &crate::UniqueArena<crate::Type>,
    ) -> Option<crate::Scalar> {
        use crate::TypeInner as Ti;
        match *self {
            Ti::Scalar(scalar) | Ti::Vector { scalar, .. } | Ti::Matrix { scalar, .. } => {
                Some(scalar)
            }
            Ti::Array { base, .. } => types[base].inner.automatically_convertible_scalar(types),
            Ti::Atomic(_)
            | Ti::Pointer { .. }
            | Ti::ValuePointer { .. }
            | Ti::Struct { .. }
            | Ti::Image { .. }
            | Ti::Sampler { .. }
            | Ti::AccelerationStructure
            | Ti::RayQuery
            | Ti::BindingArray { .. } => None,
        }
    }
}

impl crate::Scalar {
    /// Find the common type of `self` and `other` under WGSL's
    /// automatic conversions.
    ///
    /// If there are any scalars to which WGSL's automatic conversions
    /// will convert both `self` and `other`, return the best such
    /// scalar. Otherwise, return `None`.
    pub const fn automatic_conversion_combine(self, other: Self) -> Option<crate::Scalar> {
        use crate::ScalarKind as Sk;

        match (self.kind, other.kind) {
            // When the kinds match...
            (Sk::AbstractFloat, Sk::AbstractFloat)
            | (Sk::AbstractInt, Sk::AbstractInt)
            | (Sk::Sint, Sk::Sint)
            | (Sk::Uint, Sk::Uint)
            | (Sk::Float, Sk::Float)
            | (Sk::Bool, Sk::Bool) => {
                if self.width == other.width {
                    // ... either no conversion is necessary ...
                    Some(self)
                } else {
                    // ... or no conversion is possible.
                    // We never convert concrete to concrete, and
                    // abstract types should have only one size.
                    None
                }
            }

            // AbstractInt converts to AbstractFloat.
            (Sk::AbstractFloat, Sk::AbstractInt) => Some(self),
            (Sk::AbstractInt, Sk::AbstractFloat) => Some(other),

            // AbstractFloat converts to Float.
            (Sk::AbstractFloat, Sk::Float) => Some(other),
            (Sk::Float, Sk::AbstractFloat) => Some(self),

            // AbstractInt converts to concrete integer or float.
            (Sk::AbstractInt, Sk::Uint | Sk::Sint | Sk::Float) => Some(other),
            (Sk::Uint | Sk::Sint | Sk::Float, Sk::AbstractInt) => Some(self),

            // AbstractFloat can't be reconciled with concrete integer types.
            (Sk::AbstractFloat, Sk::Uint | Sk::Sint) | (Sk::Uint | Sk::Sint, Sk::AbstractFloat) => {
                None
            }

            // Nothing can be reconciled with `bool`.
            (Sk::Bool, _) | (_, Sk::Bool) => None,

            // Different concrete types cannot be reconciled.
            (Sk::Sint | Sk::Uint | Sk::Float, Sk::Sint | Sk::Uint | Sk::Float) => None,
        }
    }

    /// Return `true` if automatic conversions will covert `self` to `goal`.
    pub fn automatically_converts_to(self, goal: Self) -> bool {
        self.automatic_conversion_combine(goal) == Some(goal)
    }

    const fn concretize(self) -> Self {
        use crate::ScalarKind as Sk;
        match self.kind {
            Sk::Sint | Sk::Uint | Sk::Float | Sk::Bool => self,
            Sk::AbstractInt => Self::I32,
            Sk::AbstractFloat => Self::F32,
        }
    }
}