| 1 |
use alloc::{format, string::String, vec::Vec}; |
| 2 |
use core::ops::Index; |
| 3 |
|
| 4 |
use super::{ |
| 5 |
ast::{ |
| 6 |
GlobalLookup, GlobalLookupKind, HirExpr, HirExprKind, ParameterInfo, ParameterQualifier, |
| 7 |
VariableReference, |
| 8 |
}, |
| 9 |
error::{Error, ErrorKind}, |
| 10 |
types::{scalar_components, type_power}, |
| 11 |
Frontend, Result, |
| 12 |
}; |
| 13 |
use crate::{ |
| 14 |
front::Typifier, proc::Emitter, proc::Layouter, AddressSpace, Arena, BinaryOperator, Block, |
| 15 |
Expression, FastHashMap, FunctionArgument, Handle, Literal, LocalVariable, RelationalFunction, |
| 16 |
Scalar, Span, Statement, Type, TypeInner, VectorSize, |
| 17 |
}; |
| 18 |
|
| 19 |
/// The position at which an expression is, used while lowering |
| 20 |
#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 21 |
pub enum ExprPos { |
| 22 |
/// The expression is in the left hand side of an assignment |
| 23 |
Lhs, |
| 24 |
/// The expression is in the right hand side of an assignment |
| 25 |
Rhs, |
| 26 |
/// The expression is an array being indexed, needed to allow constant |
| 27 |
/// arrays to be dynamically indexed |
| 28 |
AccessBase { |
| 29 |
/// The index is a constant |
| 30 |
constant_index: bool, |
| 31 |
}, |
| 32 |
} |
| 33 |
|
| 34 |
impl ExprPos { |
| 35 |
/// Returns an lhs position if the current position is lhs otherwise AccessBase |
| 36 |
const fn maybe_access_base(&self, constant_index: bool) -> Self { |
| 37 |
match *self { |
| 38 |
ExprPos::Lhs |
| 39 |
| ExprPos::AccessBase { |
| 40 |
constant_index: false, |
| 41 |
} => *self, |
| 42 |
_ => ExprPos::AccessBase { constant_index }, |
| 43 |
} |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
#[derive(Debug)] |
| 48 |
pub struct Context<'a> { |
| 49 |
pub expressions: Arena<Expression>, |
| 50 |
pub locals: Arena<LocalVariable>, |
| 51 |
|
| 52 |
/// The [`FunctionArgument`]s for the final [`crate::Function`]. |
| 53 |
/// |
| 54 |
/// Parameters with the `out` and `inout` qualifiers have [`Pointer`] types |
| 55 |
/// here. For example, an `inout vec2 a` argument would be a [`Pointer`] to |
| 56 |
/// a [`Vector`]. |
| 57 |
/// |
| 58 |
/// [`Pointer`]: crate::TypeInner::Pointer |
| 59 |
/// [`Vector`]: crate::TypeInner::Vector |
| 60 |
pub arguments: Vec<FunctionArgument>, |
| 61 |
|
| 62 |
/// The parameter types given in the source code. |
| 63 |
/// |
| 64 |
/// The `out` and `inout` qualifiers don't affect the types that appear |
| 65 |
/// here. For example, an `inout vec2 a` argument would simply be a |
| 66 |
/// [`Vector`], not a pointer to one. |
| 67 |
/// |
| 68 |
/// [`Vector`]: crate::TypeInner::Vector |
| 69 |
pub parameters: Vec<Handle<Type>>, |
| 70 |
pub parameters_info: Vec<ParameterInfo>, |
| 71 |
|
| 72 |
pub symbol_table: crate::front::SymbolTable<String, VariableReference>, |
| 73 |
pub samplers: FastHashMap<Handle<Expression>, Handle<Expression>>, |
| 74 |
|
| 75 |
pub const_typifier: Typifier, |
| 76 |
pub typifier: Typifier, |
| 77 |
layouter: Layouter, |
| 78 |
emitter: Emitter, |
| 79 |
stmt_ctx: Option<StmtContext>, |
| 80 |
pub body: Block, |
| 81 |
pub module: &'a mut crate::Module, |
| 82 |
pub is_const: bool, |
| 83 |
/// Tracks the expression kind of `Expression`s residing in `self.expressions` |
| 84 |
pub local_expression_kind_tracker: crate::proc::ExpressionKindTracker, |
| 85 |
/// Tracks the expression kind of `Expression`s residing in `self.module.global_expressions` |
| 86 |
pub global_expression_kind_tracker: &'a mut crate::proc::ExpressionKindTracker, |
| 87 |
} |
| 88 |
|
| 89 |
impl<'a> Context<'a> { |
| 90 |
pub fn new( |
| 91 |
frontend: &Frontend, |
| 92 |
module: &'a mut crate::Module, |
| 93 |
is_const: bool, |
| 94 |
global_expression_kind_tracker: &'a mut crate::proc::ExpressionKindTracker, |
| 95 |
) -> Result<Self> { |
| 96 |
let mut this = Context { |
| 97 |
expressions: Arena::new(), |
| 98 |
locals: Arena::new(), |
| 99 |
arguments: Vec::new(), |
| 100 |
|
| 101 |
parameters: Vec::new(), |
| 102 |
parameters_info: Vec::new(), |
| 103 |
|
| 104 |
symbol_table: crate::front::SymbolTable::default(), |
| 105 |
samplers: FastHashMap::default(), |
| 106 |
|
| 107 |
const_typifier: Typifier::new(), |
| 108 |
typifier: Typifier::new(), |
| 109 |
layouter: Layouter::default(), |
| 110 |
emitter: Emitter::default(), |
| 111 |
stmt_ctx: Some(StmtContext::new()), |
| 112 |
body: Block::new(), |
| 113 |
module, |
| 114 |
is_const: false, |
| 115 |
local_expression_kind_tracker: crate::proc::ExpressionKindTracker::new(), |
| 116 |
global_expression_kind_tracker, |
| 117 |
}; |
| 118 |
|
| 119 |
this.emit_start(); |
| 120 |
|
| 121 |
for &(ref name, lookup) in frontend.global_variables.iter() { |
| 122 |
this.add_global(name, lookup)? |
| 123 |
} |
| 124 |
this.is_const = is_const; |
| 125 |
|
| 126 |
Ok(this) |
| 127 |
} |
| 128 |
|
| 129 |
pub fn new_body<F>(&mut self, cb: F) -> Result<Block> |
| 130 |
where |
| 131 |
F: FnOnce(&mut Self) -> Result<()>, |
| 132 |
{ |
| 133 |
self.new_body_with_ret(cb).map(|(b, _)| b) |
| 134 |
} |
| 135 |
|
| 136 |
pub fn new_body_with_ret<F, R>(&mut self, cb: F) -> Result<(Block, R)> |
| 137 |
where |
| 138 |
F: FnOnce(&mut Self) -> Result<R>, |
| 139 |
{ |
| 140 |
self.emit_restart(); |
| 141 |
let old_body = core::mem::replace(&mut self.body, Block::new()); |
| 142 |
let res = cb(self); |
| 143 |
self.emit_restart(); |
| 144 |
let new_body = core::mem::replace(&mut self.body, old_body); |
| 145 |
res.map(|r| (new_body, r)) |
| 146 |
} |
| 147 |
|
| 148 |
pub fn with_body<F>(&mut self, body: Block, cb: F) -> Result<Block> |
| 149 |
where |
| 150 |
F: FnOnce(&mut Self) -> Result<()>, |
| 151 |
{ |
| 152 |
self.emit_restart(); |
| 153 |
let old_body = core::mem::replace(&mut self.body, body); |
| 154 |
let res = cb(self); |
| 155 |
self.emit_restart(); |
| 156 |
let body = core::mem::replace(&mut self.body, old_body); |
| 157 |
res.map(|_| body) |
| 158 |
} |
| 159 |
|
| 160 |
pub fn add_global( |
| 161 |
&mut self, |
| 162 |
name: &str, |
| 163 |
GlobalLookup { |
| 164 |
kind, |
| 165 |
entry_arg, |
| 166 |
mutable, |
| 167 |
}: GlobalLookup, |
| 168 |
) -> Result<()> { |
| 169 |
let (expr, load, constant) = match kind { |
| 170 |
GlobalLookupKind::Variable(v) => { |
| 171 |
let span = self.module.global_variables.get_span(v); |
| 172 |
( |
| 173 |
self.add_expression(Expression::GlobalVariable(v), span)?, |
| 174 |
self.module.global_variables[v].space != AddressSpace::Handle, |
| 175 |
None, |
| 176 |
) |
| 177 |
} |
| 178 |
GlobalLookupKind::BlockSelect(handle, index) => { |
| 179 |
let span = self.module.global_variables.get_span(handle); |
| 180 |
let base = self.add_expression(Expression::GlobalVariable(handle), span)?; |
| 181 |
let expr = self.add_expression(Expression::AccessIndex { base, index }, span)?; |
| 182 |
|
| 183 |
( |
| 184 |
expr, |
| 185 |
{ |
| 186 |
let ty = self.module.global_variables[handle].ty; |
| 187 |
|
| 188 |
match self.module.types[ty].inner { |
| 189 |
TypeInner::Struct { ref members, .. } => { |
| 190 |
if let TypeInner::Array { |
| 191 |
size: crate::ArraySize::Dynamic, |
| 192 |
.. |
| 193 |
} = self.module.types[members[index as usize].ty].inner |
| 194 |
{ |
| 195 |
false |
| 196 |
} else { |
| 197 |
true |
| 198 |
} |
| 199 |
} |
| 200 |
_ => true, |
| 201 |
} |
| 202 |
}, |
| 203 |
None, |
| 204 |
) |
| 205 |
} |
| 206 |
GlobalLookupKind::Constant(v, ty) => { |
| 207 |
let span = self.module.constants.get_span(v); |
| 208 |
( |
| 209 |
self.add_expression(Expression::Constant(v), span)?, |
| 210 |
false, |
| 211 |
Some((v, ty)), |
| 212 |
) |
| 213 |
} |
| 214 |
}; |
| 215 |
|
| 216 |
let var = VariableReference { |
| 217 |
expr, |
| 218 |
load, |
| 219 |
mutable, |
| 220 |
constant, |
| 221 |
entry_arg, |
| 222 |
}; |
| 223 |
|
| 224 |
self.symbol_table.add(name.into(), var); |
| 225 |
|
| 226 |
Ok(()) |
| 227 |
} |
| 228 |
|
| 229 |
/// Starts the expression emitter |
| 230 |
/// |
| 231 |
/// # Panics |
| 232 |
/// |
| 233 |
/// - If called twice in a row without calling [`emit_end`][Self::emit_end]. |
| 234 |
#[inline] |
| 235 |
pub fn emit_start(&mut self) { |
| 236 |
self.emitter.start(&self.expressions) |
| 237 |
} |
| 238 |
|
| 239 |
/// Emits all the expressions captured by the emitter to the current body |
| 240 |
/// |
| 241 |
/// # Panics |
| 242 |
/// |
| 243 |
/// - If called before calling [`emit_start`]. |
| 244 |
/// - If called twice in a row without calling [`emit_start`]. |
| 245 |
/// |
| 246 |
/// [`emit_start`]: Self::emit_start |
| 247 |
pub fn emit_end(&mut self) { |
| 248 |
self.body.extend(self.emitter.finish(&self.expressions)) |
| 249 |
} |
| 250 |
|
| 251 |
/// Emits all the expressions captured by the emitter to the current body |
| 252 |
/// and starts the emitter again |
| 253 |
/// |
| 254 |
/// # Panics |
| 255 |
/// |
| 256 |
/// - If called before calling [`emit_start`][Self::emit_start]. |
| 257 |
pub fn emit_restart(&mut self) { |
| 258 |
self.emit_end(); |
| 259 |
self.emit_start() |
| 260 |
} |
| 261 |
|
| 262 |
pub fn add_expression(&mut self, expr: Expression, meta: Span) -> Result<Handle<Expression>> { |
| 263 |
let mut eval = if self.is_const { |
| 264 |
crate::proc::ConstantEvaluator::for_glsl_module( |
| 265 |
self.module, |
| 266 |
self.global_expression_kind_tracker, |
| 267 |
&mut self.layouter, |
| 268 |
) |
| 269 |
} else { |
| 270 |
crate::proc::ConstantEvaluator::for_glsl_function( |
| 271 |
self.module, |
| 272 |
&mut self.expressions, |
| 273 |
&mut self.local_expression_kind_tracker, |
| 274 |
&mut self.layouter, |
| 275 |
&mut self.emitter, |
| 276 |
&mut self.body, |
| 277 |
) |
| 278 |
}; |
| 279 |
|
| 280 |
eval.try_eval_and_append(expr, meta).map_err(|e| Error { |
| 281 |
kind: e.into(), |
| 282 |
meta, |
| 283 |
}) |
| 284 |
} |
| 285 |
|
| 286 |
/// Add variable to current scope |
| 287 |
/// |
| 288 |
/// Returns a variable if a variable with the same name was already defined, |
| 289 |
/// otherwise returns `None` |
| 290 |
pub fn add_local_var( |
| 291 |
&mut self, |
| 292 |
name: String, |
| 293 |
expr: Handle<Expression>, |
| 294 |
mutable: bool, |
| 295 |
) -> Option<VariableReference> { |
| 296 |
let var = VariableReference { |
| 297 |
expr, |
| 298 |
load: true, |
| 299 |
mutable, |
| 300 |
constant: None, |
| 301 |
entry_arg: None, |
| 302 |
}; |
| 303 |
|
| 304 |
self.symbol_table.add(name, var) |
| 305 |
} |
| 306 |
|
| 307 |
/// Add function argument to current scope |
| 308 |
pub fn add_function_arg( |
| 309 |
&mut self, |
| 310 |
name_meta: Option<(String, Span)>, |
| 311 |
ty: Handle<Type>, |
| 312 |
qualifier: ParameterQualifier, |
| 313 |
) -> Result<()> { |
| 314 |
let index = self.arguments.len(); |
| 315 |
let mut arg = FunctionArgument { |
| 316 |
name: name_meta.as_ref().map(|&(ref name, _)| name.clone()), |
| 317 |
ty, |
| 318 |
binding: None, |
| 319 |
}; |
| 320 |
self.parameters.push(ty); |
| 321 |
|
| 322 |
let opaque = match self.module.types[ty].inner { |
| 323 |
TypeInner::Image { .. } | TypeInner::Sampler { .. } => true, |
| 324 |
_ => false, |
| 325 |
}; |
| 326 |
|
| 327 |
if qualifier.is_lhs() { |
| 328 |
let span = self.module.types.get_span(arg.ty); |
| 329 |
arg.ty = self.module.types.insert( |
| 330 |
Type { |
| 331 |
name: None, |
| 332 |
inner: TypeInner::Pointer { |
| 333 |
base: arg.ty, |
| 334 |
space: AddressSpace::Function, |
| 335 |
}, |
| 336 |
}, |
| 337 |
span, |
| 338 |
) |
| 339 |
} |
| 340 |
|
| 341 |
self.arguments.push(arg); |
| 342 |
|
| 343 |
self.parameters_info.push(ParameterInfo { |
| 344 |
qualifier, |
| 345 |
depth: false, |
| 346 |
}); |
| 347 |
|
| 348 |
if let Some((name, meta)) = name_meta { |
| 349 |
let expr = self.add_expression(Expression::FunctionArgument(index as u32), meta)?; |
| 350 |
let mutable = qualifier != ParameterQualifier::Const && !opaque; |
| 351 |
let load = qualifier.is_lhs(); |
| 352 |
|
| 353 |
let var = if mutable && !load { |
| 354 |
let handle = self.locals.append( |
| 355 |
LocalVariable { |
| 356 |
name: Some(name.clone()), |
| 357 |
ty, |
| 358 |
init: None, |
| 359 |
}, |
| 360 |
meta, |
| 361 |
); |
| 362 |
let local_expr = self.add_expression(Expression::LocalVariable(handle), meta)?; |
| 363 |
|
| 364 |
self.emit_restart(); |
| 365 |
|
| 366 |
self.body.push( |
| 367 |
Statement::Store { |
| 368 |
pointer: local_expr, |
| 369 |
value: expr, |
| 370 |
}, |
| 371 |
meta, |
| 372 |
); |
| 373 |
|
| 374 |
VariableReference { |
| 375 |
expr: local_expr, |
| 376 |
load: true, |
| 377 |
mutable, |
| 378 |
constant: None, |
| 379 |
entry_arg: None, |
| 380 |
} |
| 381 |
} else { |
| 382 |
VariableReference { |
| 383 |
expr, |
| 384 |
load, |
| 385 |
mutable, |
| 386 |
constant: None, |
| 387 |
entry_arg: None, |
| 388 |
} |
| 389 |
}; |
| 390 |
|
| 391 |
self.symbol_table.add(name, var); |
| 392 |
} |
| 393 |
|
| 394 |
Ok(()) |
| 395 |
} |
| 396 |
|
| 397 |
/// Returns a [`StmtContext`] to be used in parsing and lowering |
| 398 |
/// |
| 399 |
/// # Panics |
| 400 |
/// |
| 401 |
/// - If more than one [`StmtContext`] are active at the same time or if the |
| 402 |
/// previous call didn't use it in lowering. |
| 403 |
#[must_use] |
| 404 |
pub fn stmt_ctx(&mut self) -> StmtContext { |
| 405 |
self.stmt_ctx.take().unwrap() |
| 406 |
} |
| 407 |
|
| 408 |
/// Lowers a [`HirExpr`] which might produce a [`Expression`]. |
| 409 |
/// |
| 410 |
/// consumes a [`StmtContext`] returning it to the context so that it can be |
| 411 |
/// used again later. |
| 412 |
pub fn lower( |
| 413 |
&mut self, |
| 414 |
mut stmt: StmtContext, |
| 415 |
frontend: &mut Frontend, |
| 416 |
expr: Handle<HirExpr>, |
| 417 |
pos: ExprPos, |
| 418 |
) -> Result<(Option<Handle<Expression>>, Span)> { |
| 419 |
let res = self.lower_inner(&stmt, frontend, expr, pos); |
| 420 |
|
| 421 |
stmt.hir_exprs.clear(); |
| 422 |
self.stmt_ctx = Some(stmt); |
| 423 |
|
| 424 |
res |
| 425 |
} |
| 426 |
|
| 427 |
/// Similar to [`lower`](Self::lower) but returns an error if the expression |
| 428 |
/// returns void (ie. doesn't produce a [`Expression`]). |
| 429 |
/// |
| 430 |
/// consumes a [`StmtContext`] returning it to the context so that it can be |
| 431 |
/// used again later. |
| 432 |
pub fn lower_expect( |
| 433 |
&mut self, |
| 434 |
mut stmt: StmtContext, |
| 435 |
frontend: &mut Frontend, |
| 436 |
expr: Handle<HirExpr>, |
| 437 |
pos: ExprPos, |
| 438 |
) -> Result<(Handle<Expression>, Span)> { |
| 439 |
let res = self.lower_expect_inner(&stmt, frontend, expr, pos); |
| 440 |
|
| 441 |
stmt.hir_exprs.clear(); |
| 442 |
self.stmt_ctx = Some(stmt); |
| 443 |
|
| 444 |
res |
| 445 |
} |
| 446 |
|
| 447 |
/// internal implementation of [`lower_expect`](Self::lower_expect) |
| 448 |
/// |
| 449 |
/// this method is only public because it's used in |
| 450 |
/// [`function_call`](Frontend::function_call), unless you know what |
| 451 |
/// you're doing use [`lower_expect`](Self::lower_expect) |
| 452 |
pub fn lower_expect_inner( |
| 453 |
&mut self, |
| 454 |
stmt: &StmtContext, |
| 455 |
frontend: &mut Frontend, |
| 456 |
expr: Handle<HirExpr>, |
| 457 |
pos: ExprPos, |
| 458 |
) -> Result<(Handle<Expression>, Span)> { |
| 459 |
let (maybe_expr, meta) = self.lower_inner(stmt, frontend, expr, pos)?; |
| 460 |
|
| 461 |
let expr = match maybe_expr { |
| 462 |
Some(e) => e, |
| 463 |
None => { |
| 464 |
return Err(Error { |
| 465 |
kind: ErrorKind::SemanticError("Expression returns void".into()), |
| 466 |
meta, |
| 467 |
}) |
| 468 |
} |
| 469 |
}; |
| 470 |
|
| 471 |
Ok((expr, meta)) |
| 472 |
} |
| 473 |
|
| 474 |
fn lower_store( |
| 475 |
&mut self, |
| 476 |
pointer: Handle<Expression>, |
| 477 |
value: Handle<Expression>, |
| 478 |
meta: Span, |
| 479 |
) -> Result<()> { |
| 480 |
if let Expression::Swizzle { |
| 481 |
size, |
| 482 |
mut vector, |
| 483 |
pattern, |
| 484 |
} = self.expressions[pointer] |
| 485 |
{ |
| 486 |
// Stores to swizzled values are not directly supported, |
| 487 |
// lower them as series of per-component stores. |
| 488 |
let size = match size { |
| 489 |
VectorSize::Bi => 2, |
| 490 |
VectorSize::Tri => 3, |
| 491 |
VectorSize::Quad => 4, |
| 492 |
}; |
| 493 |
|
| 494 |
if let Expression::Load { pointer } = self.expressions[vector] { |
| 495 |
vector = pointer; |
| 496 |
} |
| 497 |
|
| 498 |
#[allow(clippy::needless_range_loop)] |
| 499 |
for index in 0..size { |
| 500 |
let dst = self.add_expression( |
| 501 |
Expression::AccessIndex { |
| 502 |
base: vector, |
| 503 |
index: pattern[index].index(), |
| 504 |
}, |
| 505 |
meta, |
| 506 |
)?; |
| 507 |
let src = self.add_expression( |
| 508 |
Expression::AccessIndex { |
| 509 |
base: value, |
| 510 |
index: index as u32, |
| 511 |
}, |
| 512 |
meta, |
| 513 |
)?; |
| 514 |
|
| 515 |
self.emit_restart(); |
| 516 |
|
| 517 |
self.body.push( |
| 518 |
Statement::Store { |
| 519 |
pointer: dst, |
| 520 |
value: src, |
| 521 |
}, |
| 522 |
meta, |
| 523 |
); |
| 524 |
} |
| 525 |
} else { |
| 526 |
self.emit_restart(); |
| 527 |
|
| 528 |
self.body.push(Statement::Store { pointer, value }, meta); |
| 529 |
} |
| 530 |
|
| 531 |
Ok(()) |
| 532 |
} |
| 533 |
|
| 534 |
/// Internal implementation of [`lower`](Self::lower) |
| 535 |
fn lower_inner( |
| 536 |
&mut self, |
| 537 |
stmt: &StmtContext, |
| 538 |
frontend: &mut Frontend, |
| 539 |
expr: Handle<HirExpr>, |
| 540 |
pos: ExprPos, |
| 541 |
) -> Result<(Option<Handle<Expression>>, Span)> { |
| 542 |
let HirExpr { ref kind, meta } = stmt.hir_exprs[expr]; |
| 543 |
|
| 544 |
log::debug!("Lowering {:?} (kind {:?}, pos {:?})", expr, kind, pos); |
| 545 |
|
| 546 |
let handle = match *kind { |
| 547 |
HirExprKind::Access { base, index } => { |
| 548 |
let (index, _) = self.lower_expect_inner(stmt, frontend, index, ExprPos::Rhs)?; |
| 549 |
let maybe_constant_index = match pos { |
| 550 |
// Don't try to generate `AccessIndex` if in a LHS position, since it |
| 551 |
// wouldn't produce a pointer. |
| 552 |
ExprPos::Lhs => None, |
| 553 |
_ => self |
| 554 |
.module |
| 555 |
.to_ctx() |
| 556 |
.eval_expr_to_u32_from(index, &self.expressions) |
| 557 |
.ok(), |
| 558 |
}; |
| 559 |
|
| 560 |
let base = self |
| 561 |
.lower_expect_inner( |
| 562 |
stmt, |
| 563 |
frontend, |
| 564 |
base, |
| 565 |
pos.maybe_access_base(maybe_constant_index.is_some()), |
| 566 |
)? |
| 567 |
.0; |
| 568 |
|
| 569 |
let pointer = maybe_constant_index |
| 570 |
.map(|index| self.add_expression(Expression::AccessIndex { base, index }, meta)) |
| 571 |
.unwrap_or_else(|| { |
| 572 |
self.add_expression(Expression::Access { base, index }, meta) |
| 573 |
})?; |
| 574 |
|
| 575 |
if ExprPos::Rhs == pos { |
| 576 |
let resolved = self.resolve_type(pointer, meta)?; |
| 577 |
if resolved.pointer_space().is_some() { |
| 578 |
return Ok(( |
| 579 |
Some(self.add_expression(Expression::Load { pointer }, meta)?), |
| 580 |
meta, |
| 581 |
)); |
| 582 |
} |
| 583 |
} |
| 584 |
|
| 585 |
pointer |
| 586 |
} |
| 587 |
HirExprKind::Select { base, ref field } => { |
| 588 |
let base = self.lower_expect_inner(stmt, frontend, base, pos)?.0; |
| 589 |
|
| 590 |
frontend.field_selection(self, pos, base, field, meta)? |
| 591 |
} |
| 592 |
HirExprKind::Literal(literal) if pos != ExprPos::Lhs => { |
| 593 |
self.add_expression(Expression::Literal(literal), meta)? |
| 594 |
} |
| 595 |
HirExprKind::Binary { left, op, right } if pos != ExprPos::Lhs => { |
| 596 |
let (mut left, left_meta) = |
| 597 |
self.lower_expect_inner(stmt, frontend, left, ExprPos::Rhs)?; |
| 598 |
let (mut right, right_meta) = |
| 599 |
self.lower_expect_inner(stmt, frontend, right, ExprPos::Rhs)?; |
| 600 |
|
| 601 |
match op { |
| 602 |
BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => { |
| 603 |
self.implicit_conversion(&mut right, right_meta, Scalar::U32)? |
| 604 |
} |
| 605 |
_ => self |
| 606 |
.binary_implicit_conversion(&mut left, left_meta, &mut right, right_meta)?, |
| 607 |
} |
| 608 |
|
| 609 |
self.typifier_grow(left, left_meta)?; |
| 610 |
self.typifier_grow(right, right_meta)?; |
| 611 |
|
| 612 |
let left_inner = self.get_type(left); |
| 613 |
let right_inner = self.get_type(right); |
| 614 |
|
| 615 |
match (left_inner, right_inner) { |
| 616 |
( |
| 617 |
&TypeInner::Matrix { |
| 618 |
columns: left_columns, |
| 619 |
rows: left_rows, |
| 620 |
scalar: left_scalar, |
| 621 |
}, |
| 622 |
&TypeInner::Matrix { |
| 623 |
columns: right_columns, |
| 624 |
rows: right_rows, |
| 625 |
scalar: right_scalar, |
| 626 |
}, |
| 627 |
) => { |
| 628 |
let dimensions_ok = if op == BinaryOperator::Multiply { |
| 629 |
left_columns == right_rows |
| 630 |
} else { |
| 631 |
left_columns == right_columns && left_rows == right_rows |
| 632 |
}; |
| 633 |
|
| 634 |
// Check that the two arguments have the same dimensions |
| 635 |
if !dimensions_ok || left_scalar != right_scalar { |
| 636 |
frontend.errors.push(Error { |
| 637 |
kind: ErrorKind::SemanticError( |
| 638 |
format!( |
| 639 |
"Cannot apply operation to {:?} and {:?}", |
| 640 |
left_inner, right_inner |
| 641 |
) |
| 642 |
.into(), |
| 643 |
), |
| 644 |
meta, |
| 645 |
}) |
| 646 |
} |
| 647 |
|
| 648 |
match op { |
| 649 |
BinaryOperator::Divide => { |
| 650 |
// Naga IR doesn't support matrix division so we need to |
| 651 |
// divide the columns individually and reassemble the matrix |
| 652 |
let mut components = Vec::with_capacity(left_columns as usize); |
| 653 |
|
| 654 |
for index in 0..left_columns as u32 { |
| 655 |
// Get the column vectors |
| 656 |
let left_vector = self.add_expression( |
| 657 |
Expression::AccessIndex { base: left, index }, |
| 658 |
meta, |
| 659 |
)?; |
| 660 |
let right_vector = self.add_expression( |
| 661 |
Expression::AccessIndex { base: right, index }, |
| 662 |
meta, |
| 663 |
)?; |
| 664 |
|
| 665 |
// Divide the vectors |
| 666 |
let column = self.add_expression( |
| 667 |
Expression::Binary { |
| 668 |
op, |
| 669 |
left: left_vector, |
| 670 |
right: right_vector, |
| 671 |
}, |
| 672 |
meta, |
| 673 |
)?; |
| 674 |
|
| 675 |
components.push(column) |
| 676 |
} |
| 677 |
|
| 678 |
let ty = self.module.types.insert( |
| 679 |
Type { |
| 680 |
name: None, |
| 681 |
inner: TypeInner::Matrix { |
| 682 |
columns: left_columns, |
| 683 |
rows: left_rows, |
| 684 |
scalar: left_scalar, |
| 685 |
}, |
| 686 |
}, |
| 687 |
Span::default(), |
| 688 |
); |
| 689 |
|
| 690 |
// Rebuild the matrix from the divided vectors |
| 691 |
self.add_expression(Expression::Compose { ty, components }, meta)? |
| 692 |
} |
| 693 |
BinaryOperator::Equal | BinaryOperator::NotEqual => { |
| 694 |
// Naga IR doesn't support matrix comparisons so we need to |
| 695 |
// compare the columns individually and then fold them together |
| 696 |
// |
| 697 |
// The folding is done using a logical and for equality and |
| 698 |
// a logical or for inequality |
| 699 |
let equals = op == BinaryOperator::Equal; |
| 700 |
|
| 701 |
let (op, combine, fun) = match equals { |
| 702 |
true => ( |
| 703 |
BinaryOperator::Equal, |
| 704 |
BinaryOperator::LogicalAnd, |
| 705 |
RelationalFunction::All, |
| 706 |
), |
| 707 |
false => ( |
| 708 |
BinaryOperator::NotEqual, |
| 709 |
BinaryOperator::LogicalOr, |
| 710 |
RelationalFunction::Any, |
| 711 |
), |
| 712 |
}; |
| 713 |
|
| 714 |
let mut root = None; |
| 715 |
|
| 716 |
for index in 0..left_columns as u32 { |
| 717 |
// Get the column vectors |
| 718 |
let left_vector = self.add_expression( |
| 719 |
Expression::AccessIndex { base: left, index }, |
| 720 |
meta, |
| 721 |
)?; |
| 722 |
let right_vector = self.add_expression( |
| 723 |
Expression::AccessIndex { base: right, index }, |
| 724 |
meta, |
| 725 |
)?; |
| 726 |
|
| 727 |
let argument = self.add_expression( |
| 728 |
Expression::Binary { |
| 729 |
op, |
| 730 |
left: left_vector, |
| 731 |
right: right_vector, |
| 732 |
}, |
| 733 |
meta, |
| 734 |
)?; |
| 735 |
|
| 736 |
// The result of comparing two vectors is a boolean vector |
| 737 |
// so use a relational function like all to get a single |
| 738 |
// boolean value |
| 739 |
let compare = self.add_expression( |
| 740 |
Expression::Relational { fun, argument }, |
| 741 |
meta, |
| 742 |
)?; |
| 743 |
|
| 744 |
// Fold the result |
| 745 |
root = Some(match root { |
| 746 |
Some(right) => self.add_expression( |
| 747 |
Expression::Binary { |
| 748 |
op: combine, |
| 749 |
left: compare, |
| 750 |
right, |
| 751 |
}, |
| 752 |
meta, |
| 753 |
)?, |
| 754 |
None => compare, |
| 755 |
}); |
| 756 |
} |
| 757 |
|
| 758 |
root.unwrap() |
| 759 |
} |
| 760 |
_ => { |
| 761 |
self.add_expression(Expression::Binary { left, op, right }, meta)? |
| 762 |
} |
| 763 |
} |
| 764 |
} |
| 765 |
(&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) => match op { |
| 766 |
BinaryOperator::Equal | BinaryOperator::NotEqual => { |
| 767 |
let equals = op == BinaryOperator::Equal; |
| 768 |
|
| 769 |
let (op, fun) = match equals { |
| 770 |
true => (BinaryOperator::Equal, RelationalFunction::All), |
| 771 |
false => (BinaryOperator::NotEqual, RelationalFunction::Any), |
| 772 |
}; |
| 773 |
|
| 774 |
let argument = |
| 775 |
self.add_expression(Expression::Binary { op, left, right }, meta)?; |
| 776 |
|
| 777 |
self.add_expression(Expression::Relational { fun, argument }, meta)? |
| 778 |
} |
| 779 |
_ => self.add_expression(Expression::Binary { left, op, right }, meta)?, |
| 780 |
}, |
| 781 |
(&TypeInner::Vector { size, .. }, &TypeInner::Scalar { .. }) => match op { |
| 782 |
BinaryOperator::Add |
| 783 |
| BinaryOperator::Subtract |
| 784 |
| BinaryOperator::Divide |
| 785 |
| BinaryOperator::And |
| 786 |
| BinaryOperator::ExclusiveOr |
| 787 |
| BinaryOperator::InclusiveOr |
| 788 |
| BinaryOperator::ShiftLeft |
| 789 |
| BinaryOperator::ShiftRight => { |
| 790 |
let scalar_vector = self |
| 791 |
.add_expression(Expression::Splat { size, value: right }, meta)?; |
| 792 |
|
| 793 |
self.add_expression( |
| 794 |
Expression::Binary { |
| 795 |
op, |
| 796 |
left, |
| 797 |
right: scalar_vector, |
| 798 |
}, |
| 799 |
meta, |
| 800 |
)? |
| 801 |
} |
| 802 |
_ => self.add_expression(Expression::Binary { left, op, right }, meta)?, |
| 803 |
}, |
| 804 |
(&TypeInner::Scalar { .. }, &TypeInner::Vector { size, .. }) => match op { |
| 805 |
BinaryOperator::Add |
| 806 |
| BinaryOperator::Subtract |
| 807 |
| BinaryOperator::Divide |
| 808 |
| BinaryOperator::And |
| 809 |
| BinaryOperator::ExclusiveOr |
| 810 |
| BinaryOperator::InclusiveOr => { |
| 811 |
let scalar_vector = |
| 812 |
self.add_expression(Expression::Splat { size, value: left }, meta)?; |
| 813 |
|
| 814 |
self.add_expression( |
| 815 |
Expression::Binary { |
| 816 |
op, |
| 817 |
left: scalar_vector, |
| 818 |
right, |
| 819 |
}, |
| 820 |
meta, |
| 821 |
)? |
| 822 |
} |
| 823 |
_ => self.add_expression(Expression::Binary { left, op, right }, meta)?, |
| 824 |
}, |
| 825 |
( |
| 826 |
&TypeInner::Scalar(left_scalar), |
| 827 |
&TypeInner::Matrix { |
| 828 |
rows, |
| 829 |
columns, |
| 830 |
scalar: right_scalar, |
| 831 |
}, |
| 832 |
) => { |
| 833 |
// Check that the two arguments have the same scalar type |
| 834 |
if left_scalar != right_scalar { |
| 835 |
frontend.errors.push(Error { |
| 836 |
kind: ErrorKind::SemanticError( |
| 837 |
format!( |
| 838 |
"Cannot apply operation to {:?} and {:?}", |
| 839 |
left_inner, right_inner |
| 840 |
) |
| 841 |
.into(), |
| 842 |
), |
| 843 |
meta, |
| 844 |
}) |
| 845 |
} |
| 846 |
|
| 847 |
match op { |
| 848 |
BinaryOperator::Divide |
| 849 |
| BinaryOperator::Add |
| 850 |
| BinaryOperator::Subtract => { |
| 851 |
// Naga IR doesn't support all matrix by scalar operations so |
| 852 |
// we need for some to turn the scalar into a vector by |
| 853 |
// splatting it and then for each column vector apply the |
| 854 |
// operation and finally reconstruct the matrix |
| 855 |
let scalar_vector = self.add_expression( |
| 856 |
Expression::Splat { |
| 857 |
size: rows, |
| 858 |
value: left, |
| 859 |
}, |
| 860 |
meta, |
| 861 |
)?; |
| 862 |
|
| 863 |
let mut components = Vec::with_capacity(columns as usize); |
| 864 |
|
| 865 |
for index in 0..columns as u32 { |
| 866 |
// Get the column vector |
| 867 |
let matrix_column = self.add_expression( |
| 868 |
Expression::AccessIndex { base: right, index }, |
| 869 |
meta, |
| 870 |
)?; |
| 871 |
|
| 872 |
// Apply the operation to the splatted vector and |
| 873 |
// the column vector |
| 874 |
let column = self.add_expression( |
| 875 |
Expression::Binary { |
| 876 |
op, |
| 877 |
left: scalar_vector, |
| 878 |
right: matrix_column, |
| 879 |
}, |
| 880 |
meta, |
| 881 |
)?; |
| 882 |
|
| 883 |
components.push(column) |
| 884 |
} |
| 885 |
|
| 886 |
let ty = self.module.types.insert( |
| 887 |
Type { |
| 888 |
name: None, |
| 889 |
inner: TypeInner::Matrix { |
| 890 |
columns, |
| 891 |
rows, |
| 892 |
scalar: left_scalar, |
| 893 |
}, |
| 894 |
}, |
| 895 |
Span::default(), |
| 896 |
); |
| 897 |
|
| 898 |
// Rebuild the matrix from the operation result vectors |
| 899 |
self.add_expression(Expression::Compose { ty, components }, meta)? |
| 900 |
} |
| 901 |
_ => { |
| 902 |
self.add_expression(Expression::Binary { left, op, right }, meta)? |
| 903 |
} |
| 904 |
} |
| 905 |
} |
| 906 |
( |
| 907 |
&TypeInner::Matrix { |
| 908 |
rows, |
| 909 |
columns, |
| 910 |
scalar: left_scalar, |
| 911 |
}, |
| 912 |
&TypeInner::Scalar(right_scalar), |
| 913 |
) => { |
| 914 |
// Check that the two arguments have the same scalar type |
| 915 |
if left_scalar != right_scalar { |
| 916 |
frontend.errors.push(Error { |
| 917 |
kind: ErrorKind::SemanticError( |
| 918 |
format!( |
| 919 |
"Cannot apply operation to {:?} and {:?}", |
| 920 |
left_inner, right_inner |
| 921 |
) |
| 922 |
.into(), |
| 923 |
), |
| 924 |
meta, |
| 925 |
}) |
| 926 |
} |
| 927 |
|
| 928 |
match op { |
| 929 |
BinaryOperator::Divide |
| 930 |
| BinaryOperator::Add |
| 931 |
| BinaryOperator::Subtract => { |
| 932 |
// Naga IR doesn't support all matrix by scalar operations so |
| 933 |
// we need for some to turn the scalar into a vector by |
| 934 |
// splatting it and then for each column vector apply the |
| 935 |
// operation and finally reconstruct the matrix |
| 936 |
|
| 937 |
let scalar_vector = self.add_expression( |
| 938 |
Expression::Splat { |
| 939 |
size: rows, |
| 940 |
value: right, |
| 941 |
}, |
| 942 |
meta, |
| 943 |
)?; |
| 944 |
|
| 945 |
let mut components = Vec::with_capacity(columns as usize); |
| 946 |
|
| 947 |
for index in 0..columns as u32 { |
| 948 |
// Get the column vector |
| 949 |
let matrix_column = self.add_expression( |
| 950 |
Expression::AccessIndex { base: left, index }, |
| 951 |
meta, |
| 952 |
)?; |
| 953 |
|
| 954 |
// Apply the operation to the splatted vector and |
| 955 |
// the column vector |
| 956 |
let column = self.add_expression( |
| 957 |
Expression::Binary { |
| 958 |
op, |
| 959 |
left: matrix_column, |
| 960 |
right: scalar_vector, |
| 961 |
}, |
| 962 |
meta, |
| 963 |
)?; |
| 964 |
|
| 965 |
components.push(column) |
| 966 |
} |
| 967 |
|
| 968 |
let ty = self.module.types.insert( |
| 969 |
Type { |
| 970 |
name: None, |
| 971 |
inner: TypeInner::Matrix { |
| 972 |
columns, |
| 973 |
rows, |
| 974 |
scalar: left_scalar, |
| 975 |
}, |
| 976 |
}, |
| 977 |
Span::default(), |
| 978 |
); |
| 979 |
|
| 980 |
// Rebuild the matrix from the operation result vectors |
| 981 |
self.add_expression(Expression::Compose { ty, components }, meta)? |
| 982 |
} |
| 983 |
_ => { |
| 984 |
self.add_expression(Expression::Binary { left, op, right }, meta)? |
| 985 |
} |
| 986 |
} |
| 987 |
} |
| 988 |
_ => self.add_expression(Expression::Binary { left, op, right }, meta)?, |
| 989 |
} |
| 990 |
} |
| 991 |
HirExprKind::Unary { op, expr } if pos != ExprPos::Lhs => { |
| 992 |
let expr = self |
| 993 |
.lower_expect_inner(stmt, frontend, expr, ExprPos::Rhs)? |
| 994 |
.0; |
| 995 |
|
| 996 |
self.add_expression(Expression::Unary { op, expr }, meta)? |
| 997 |
} |
| 998 |
HirExprKind::Variable(ref var) => match pos { |
| 999 |
ExprPos::Lhs => { |
| 1000 |
if !var.mutable { |
| 1001 |
frontend.errors.push(Error { |
| 1002 |
kind: ErrorKind::SemanticError( |
| 1003 |
"Variable cannot be used in LHS position".into(), |
| 1004 |
), |
| 1005 |
meta, |
| 1006 |
}) |
| 1007 |
} |
| 1008 |
|
| 1009 |
var.expr |
| 1010 |
} |
| 1011 |
ExprPos::AccessBase { constant_index } => { |
| 1012 |
// If the index isn't constant all accesses backed by a constant base need |
| 1013 |
// to be done through a proxy local variable, since constants have a non |
| 1014 |
// pointer type which is required for dynamic indexing |
| 1015 |
if !constant_index { |
| 1016 |
if let Some((constant, ty)) = var.constant { |
| 1017 |
let init = self |
| 1018 |
.add_expression(Expression::Constant(constant), Span::default())?; |
| 1019 |
let local = self.locals.append( |
| 1020 |
LocalVariable { |
| 1021 |
name: None, |
| 1022 |
ty, |
| 1023 |
init: Some(init), |
| 1024 |
}, |
| 1025 |
Span::default(), |
| 1026 |
); |
| 1027 |
|
| 1028 |
self.add_expression(Expression::LocalVariable(local), Span::default())? |
| 1029 |
} else { |
| 1030 |
var.expr |
| 1031 |
} |
| 1032 |
} else { |
| 1033 |
var.expr |
| 1034 |
} |
| 1035 |
} |
| 1036 |
_ if var.load => { |
| 1037 |
self.add_expression(Expression::Load { pointer: var.expr }, meta)? |
| 1038 |
} |
| 1039 |
ExprPos::Rhs => { |
| 1040 |
if let Some((constant, _)) = self.is_const.then_some(var.constant).flatten() { |
| 1041 |
self.add_expression(Expression::Constant(constant), meta)? |
| 1042 |
} else { |
| 1043 |
var.expr |
| 1044 |
} |
| 1045 |
} |
| 1046 |
}, |
| 1047 |
HirExprKind::Call(ref call) if pos != ExprPos::Lhs => { |
| 1048 |
let maybe_expr = frontend.function_or_constructor_call( |
| 1049 |
self, |
| 1050 |
stmt, |
| 1051 |
call.kind.clone(), |
| 1052 |
&call.args, |
| 1053 |
meta, |
| 1054 |
)?; |
| 1055 |
return Ok((maybe_expr, meta)); |
| 1056 |
} |
| 1057 |
// `HirExprKind::Conditional` represents the ternary operator in glsl (`:?`) |
| 1058 |
// |
| 1059 |
// The ternary operator is defined to only evaluate one of the two possible |
| 1060 |
// expressions which means that it's behavior is that of an `if` statement, |
| 1061 |
// and it's merely syntactic sugar for it. |
| 1062 |
HirExprKind::Conditional { |
| 1063 |
condition, |
| 1064 |
accept, |
| 1065 |
reject, |
| 1066 |
} if ExprPos::Lhs != pos => { |
| 1067 |
// Given an expression `a ? b : c`, we need to produce a Naga |
| 1068 |
// statement roughly like: |
| 1069 |
// |
| 1070 |
// var temp; |
| 1071 |
// if a { |
| 1072 |
// temp = convert(b); |
| 1073 |
// } else { |
| 1074 |
// temp = convert(c); |
| 1075 |
// } |
| 1076 |
// |
| 1077 |
// where `convert` stands for type conversions to bring `b` and `c` to |
| 1078 |
// the same type, and then use `temp` to represent the value of the whole |
| 1079 |
// conditional expression in subsequent code. |
| 1080 |
|
| 1081 |
// Lower the condition first to the current bodyy |
| 1082 |
let condition = self |
| 1083 |
.lower_expect_inner(stmt, frontend, condition, ExprPos::Rhs)? |
| 1084 |
.0; |
| 1085 |
|
| 1086 |
let (mut accept_body, (mut accept, accept_meta)) = |
| 1087 |
self.new_body_with_ret(|ctx| { |
| 1088 |
// Lower the `true` branch |
| 1089 |
ctx.lower_expect_inner(stmt, frontend, accept, pos) |
| 1090 |
})?; |
| 1091 |
|
| 1092 |
let (mut reject_body, (mut reject, reject_meta)) = |
| 1093 |
self.new_body_with_ret(|ctx| { |
| 1094 |
// Lower the `false` branch |
| 1095 |
ctx.lower_expect_inner(stmt, frontend, reject, pos) |
| 1096 |
})?; |
| 1097 |
|
| 1098 |
// We need to do some custom implicit conversions since the two target expressions |
| 1099 |
// are in different bodies |
| 1100 |
if let (Some((accept_power, accept_scalar)), Some((reject_power, reject_scalar))) = ( |
| 1101 |
// Get the components of both branches and calculate the type power |
| 1102 |
self.expr_scalar_components(accept, accept_meta)? |
| 1103 |
.and_then(|scalar| Some((type_power(scalar)?, scalar))), |
| 1104 |
self.expr_scalar_components(reject, reject_meta)? |
| 1105 |
.and_then(|scalar| Some((type_power(scalar)?, scalar))), |
| 1106 |
) { |
| 1107 |
match accept_power.cmp(&reject_power) { |
| 1108 |
core::cmp::Ordering::Less => { |
| 1109 |
accept_body = self.with_body(accept_body, |ctx| { |
| 1110 |
ctx.conversion(&mut accept, accept_meta, reject_scalar)?; |
| 1111 |
Ok(()) |
| 1112 |
})?; |
| 1113 |
} |
| 1114 |
core::cmp::Ordering::Equal => {} |
| 1115 |
core::cmp::Ordering::Greater => { |
| 1116 |
reject_body = self.with_body(reject_body, |ctx| { |
| 1117 |
ctx.conversion(&mut reject, reject_meta, accept_scalar)?; |
| 1118 |
Ok(()) |
| 1119 |
})?; |
| 1120 |
} |
| 1121 |
} |
| 1122 |
} |
| 1123 |
|
| 1124 |
// We need to get the type of the resulting expression to create the local, |
| 1125 |
// this must be done after implicit conversions to ensure both branches have |
| 1126 |
// the same type. |
| 1127 |
let ty = self.resolve_type_handle(accept, accept_meta)?; |
| 1128 |
|
| 1129 |
// Add the local that will hold the result of our conditional |
| 1130 |
let local = self.locals.append( |
| 1131 |
LocalVariable { |
| 1132 |
name: None, |
| 1133 |
ty, |
| 1134 |
init: None, |
| 1135 |
}, |
| 1136 |
meta, |
| 1137 |
); |
| 1138 |
|
| 1139 |
let local_expr = self.add_expression(Expression::LocalVariable(local), meta)?; |
| 1140 |
|
| 1141 |
// Add to each the store to the result variable |
| 1142 |
accept_body.push( |
| 1143 |
Statement::Store { |
| 1144 |
pointer: local_expr, |
| 1145 |
value: accept, |
| 1146 |
}, |
| 1147 |
accept_meta, |
| 1148 |
); |
| 1149 |
reject_body.push( |
| 1150 |
Statement::Store { |
| 1151 |
pointer: local_expr, |
| 1152 |
value: reject, |
| 1153 |
}, |
| 1154 |
reject_meta, |
| 1155 |
); |
| 1156 |
|
| 1157 |
// Finally add the `If` to the main body with the `condition` we lowered |
| 1158 |
// earlier and the branches we prepared. |
| 1159 |
self.body.push( |
| 1160 |
Statement::If { |
| 1161 |
condition, |
| 1162 |
accept: accept_body, |
| 1163 |
reject: reject_body, |
| 1164 |
}, |
| 1165 |
meta, |
| 1166 |
); |
| 1167 |
|
| 1168 |
// Note: `Expression::Load` must be emitted before it's used so make |
| 1169 |
// sure the emitter is active here. |
| 1170 |
self.add_expression( |
| 1171 |
Expression::Load { |
| 1172 |
pointer: local_expr, |
| 1173 |
}, |
| 1174 |
meta, |
| 1175 |
)? |
| 1176 |
} |
| 1177 |
HirExprKind::Assign { tgt, value } if ExprPos::Lhs != pos => { |
| 1178 |
let (pointer, ptr_meta) = |
| 1179 |
self.lower_expect_inner(stmt, frontend, tgt, ExprPos::Lhs)?; |
| 1180 |
let (mut value, value_meta) = |
| 1181 |
self.lower_expect_inner(stmt, frontend, value, ExprPos::Rhs)?; |
| 1182 |
|
| 1183 |
let ty = match *self.resolve_type(pointer, ptr_meta)? { |
| 1184 |
TypeInner::Pointer { base, .. } => &self.module.types[base].inner, |
| 1185 |
ref ty => ty, |
| 1186 |
}; |
| 1187 |
|
| 1188 |
if let Some(scalar) = scalar_components(ty) { |
| 1189 |
self.implicit_conversion(&mut value, value_meta, scalar)?; |
| 1190 |
} |
| 1191 |
|
| 1192 |
self.lower_store(pointer, value, meta)?; |
| 1193 |
|
| 1194 |
value |
| 1195 |
} |
| 1196 |
HirExprKind::PrePostfix { op, postfix, expr } if ExprPos::Lhs != pos => { |
| 1197 |
let (pointer, _) = self.lower_expect_inner(stmt, frontend, expr, ExprPos::Lhs)?; |
| 1198 |
let left = if let Expression::Swizzle { .. } = self.expressions[pointer] { |
| 1199 |
pointer |
| 1200 |
} else { |
| 1201 |
self.add_expression(Expression::Load { pointer }, meta)? |
| 1202 |
}; |
| 1203 |
|
| 1204 |
let res = match *self.resolve_type(left, meta)? { |
| 1205 |
TypeInner::Scalar(scalar) => { |
| 1206 |
let ty = TypeInner::Scalar(scalar); |
| 1207 |
Literal::one(scalar).map(|i| (ty, i, None, None)) |
| 1208 |
} |
| 1209 |
TypeInner::Vector { size, scalar } => { |
| 1210 |
let ty = TypeInner::Vector { size, scalar }; |
| 1211 |
Literal::one(scalar).map(|i| (ty, i, Some(size), None)) |
| 1212 |
} |
| 1213 |
TypeInner::Matrix { |
| 1214 |
columns, |
| 1215 |
rows, |
| 1216 |
scalar, |
| 1217 |
} => { |
| 1218 |
let ty = TypeInner::Matrix { |
| 1219 |
columns, |
| 1220 |
rows, |
| 1221 |
scalar, |
| 1222 |
}; |
| 1223 |
Literal::one(scalar).map(|i| (ty, i, Some(rows), Some(columns))) |
| 1224 |
} |
| 1225 |
_ => None, |
| 1226 |
}; |
| 1227 |
let (ty_inner, literal, rows, columns) = match res { |
| 1228 |
Some(res) => res, |
| 1229 |
None => { |
| 1230 |
frontend.errors.push(Error { |
| 1231 |
kind: ErrorKind::SemanticError( |
| 1232 |
"Increment/decrement only works on scalar/vector/matrix".into(), |
| 1233 |
), |
| 1234 |
meta, |
| 1235 |
}); |
| 1236 |
return Ok((Some(left), meta)); |
| 1237 |
} |
| 1238 |
}; |
| 1239 |
|
| 1240 |
let mut right = self.add_expression(Expression::Literal(literal), meta)?; |
| 1241 |
|
| 1242 |
// Glsl allows pre/postfixes operations on vectors and matrices, so if the |
| 1243 |
// target is either of them change the right side of the addition to be splatted |
| 1244 |
// to the same size as the target, furthermore if the target is a matrix |
| 1245 |
// use a composed matrix using the splatted value. |
| 1246 |
if let Some(size) = rows { |
| 1247 |
right = self.add_expression(Expression::Splat { size, value: right }, meta)?; |
| 1248 |
|
| 1249 |
if let Some(cols) = columns { |
| 1250 |
let ty = self.module.types.insert( |
| 1251 |
Type { |
| 1252 |
name: None, |
| 1253 |
inner: ty_inner, |
| 1254 |
}, |
| 1255 |
meta, |
| 1256 |
); |
| 1257 |
|
| 1258 |
right = self.add_expression( |
| 1259 |
Expression::Compose { |
| 1260 |
ty, |
| 1261 |
components: core::iter::repeat_n(right, cols as usize).collect(), |
| 1262 |
}, |
| 1263 |
meta, |
| 1264 |
)?; |
| 1265 |
} |
| 1266 |
} |
| 1267 |
|
| 1268 |
let value = self.add_expression(Expression::Binary { op, left, right }, meta)?; |
| 1269 |
|
| 1270 |
self.lower_store(pointer, value, meta)?; |
| 1271 |
|
| 1272 |
if postfix { |
| 1273 |
left |
| 1274 |
} else { |
| 1275 |
value |
| 1276 |
} |
| 1277 |
} |
| 1278 |
HirExprKind::Method { |
| 1279 |
expr: object, |
| 1280 |
ref name, |
| 1281 |
ref args, |
| 1282 |
} if ExprPos::Lhs != pos => { |
| 1283 |
let args = args |
| 1284 |
.iter() |
| 1285 |
.map(|e| self.lower_expect_inner(stmt, frontend, *e, ExprPos::Rhs)) |
| 1286 |
.collect::<Result<Vec<_>>>()?; |
| 1287 |
match name.as_ref() { |
| 1288 |
"length" => { |
| 1289 |
if !args.is_empty() { |
| 1290 |
frontend.errors.push(Error { |
| 1291 |
kind: ErrorKind::SemanticError( |
| 1292 |
".length() doesn't take any arguments".into(), |
| 1293 |
), |
| 1294 |
meta, |
| 1295 |
}); |
| 1296 |
} |
| 1297 |
let lowered_array = self.lower_expect_inner(stmt, frontend, object, pos)?.0; |
| 1298 |
let array_type = self.resolve_type(lowered_array, meta)?; |
| 1299 |
|
| 1300 |
match *array_type { |
| 1301 |
TypeInner::Array { |
| 1302 |
size: crate::ArraySize::Constant(size), |
| 1303 |
.. |
| 1304 |
} => { |
| 1305 |
let mut array_length = self.add_expression( |
| 1306 |
Expression::Literal(Literal::U32(size.get())), |
| 1307 |
meta, |
| 1308 |
)?; |
| 1309 |
self.forced_conversion(&mut array_length, meta, Scalar::I32)?; |
| 1310 |
array_length |
| 1311 |
} |
| 1312 |
// let the error be handled in type checking if it's not a dynamic array |
| 1313 |
_ => { |
| 1314 |
let mut array_length = self |
| 1315 |
.add_expression(Expression::ArrayLength(lowered_array), meta)?; |
| 1316 |
self.conversion(&mut array_length, meta, Scalar::I32)?; |
| 1317 |
array_length |
| 1318 |
} |
| 1319 |
} |
| 1320 |
} |
| 1321 |
_ => { |
| 1322 |
return Err(Error { |
| 1323 |
kind: ErrorKind::SemanticError( |
| 1324 |
format!("unknown method '{name}'").into(), |
| 1325 |
), |
| 1326 |
meta, |
| 1327 |
}); |
| 1328 |
} |
| 1329 |
} |
| 1330 |
} |
| 1331 |
_ => { |
| 1332 |
return Err(Error { |
| 1333 |
kind: ErrorKind::SemanticError( |
| 1334 |
format!("{:?} cannot be in the left hand side", stmt.hir_exprs[expr]) |
| 1335 |
.into(), |
| 1336 |
), |
| 1337 |
meta, |
| 1338 |
}) |
| 1339 |
} |
| 1340 |
}; |
| 1341 |
|
| 1342 |
log::trace!( |
| 1343 |
"Lowered {:?}\n\tKind = {:?}\n\tPos = {:?}\n\tResult = {:?}", |
| 1344 |
expr, |
| 1345 |
kind, |
| 1346 |
pos, |
| 1347 |
handle |
| 1348 |
); |
| 1349 |
|
| 1350 |
Ok((Some(handle), meta)) |
| 1351 |
} |
| 1352 |
|
| 1353 |
pub fn expr_scalar_components( |
| 1354 |
&mut self, |
| 1355 |
expr: Handle<Expression>, |
| 1356 |
meta: Span, |
| 1357 |
) -> Result<Option<Scalar>> { |
| 1358 |
let ty = self.resolve_type(expr, meta)?; |
| 1359 |
Ok(scalar_components(ty)) |
| 1360 |
} |
| 1361 |
|
| 1362 |
pub fn expr_power(&mut self, expr: Handle<Expression>, meta: Span) -> Result<Option<u32>> { |
| 1363 |
Ok(self |
| 1364 |
.expr_scalar_components(expr, meta)? |
| 1365 |
.and_then(type_power)) |
| 1366 |
} |
| 1367 |
|
| 1368 |
pub fn conversion( |
| 1369 |
&mut self, |
| 1370 |
expr: &mut Handle<Expression>, |
| 1371 |
meta: Span, |
| 1372 |
scalar: Scalar, |
| 1373 |
) -> Result<()> { |
| 1374 |
*expr = self.add_expression( |
| 1375 |
Expression::As { |
| 1376 |
expr: *expr, |
| 1377 |
kind: scalar.kind, |
| 1378 |
convert: Some(scalar.width), |
| 1379 |
}, |
| 1380 |
meta, |
| 1381 |
)?; |
| 1382 |
|
| 1383 |
Ok(()) |
| 1384 |
} |
| 1385 |
|
| 1386 |
pub fn implicit_conversion( |
| 1387 |
&mut self, |
| 1388 |
expr: &mut Handle<Expression>, |
| 1389 |
meta: Span, |
| 1390 |
scalar: Scalar, |
| 1391 |
) -> Result<()> { |
| 1392 |
if let (Some(tgt_power), Some(expr_power)) = |
| 1393 |
(type_power(scalar), self.expr_power(*expr, meta)?) |
| 1394 |
{ |
| 1395 |
if tgt_power > expr_power { |
| 1396 |
self.conversion(expr, meta, scalar)?; |
| 1397 |
} |
| 1398 |
} |
| 1399 |
|
| 1400 |
Ok(()) |
| 1401 |
} |
| 1402 |
|
| 1403 |
pub fn forced_conversion( |
| 1404 |
&mut self, |
| 1405 |
expr: &mut Handle<Expression>, |
| 1406 |
meta: Span, |
| 1407 |
scalar: Scalar, |
| 1408 |
) -> Result<()> { |
| 1409 |
if let Some(expr_scalar) = self.expr_scalar_components(*expr, meta)? { |
| 1410 |
if expr_scalar != scalar { |
| 1411 |
self.conversion(expr, meta, scalar)?; |
| 1412 |
} |
| 1413 |
} |
| 1414 |
|
| 1415 |
Ok(()) |
| 1416 |
} |
| 1417 |
|
| 1418 |
pub fn binary_implicit_conversion( |
| 1419 |
&mut self, |
| 1420 |
left: &mut Handle<Expression>, |
| 1421 |
left_meta: Span, |
| 1422 |
right: &mut Handle<Expression>, |
| 1423 |
right_meta: Span, |
| 1424 |
) -> Result<()> { |
| 1425 |
let left_components = self.expr_scalar_components(*left, left_meta)?; |
| 1426 |
let right_components = self.expr_scalar_components(*right, right_meta)?; |
| 1427 |
|
| 1428 |
if let (Some((left_power, left_scalar)), Some((right_power, right_scalar))) = ( |
| 1429 |
left_components.and_then(|scalar| Some((type_power(scalar)?, scalar))), |
| 1430 |
right_components.and_then(|scalar| Some((type_power(scalar)?, scalar))), |
| 1431 |
) { |
| 1432 |
match left_power.cmp(&right_power) { |
| 1433 |
core::cmp::Ordering::Less => { |
| 1434 |
self.conversion(left, left_meta, right_scalar)?; |
| 1435 |
} |
| 1436 |
core::cmp::Ordering::Equal => {} |
| 1437 |
core::cmp::Ordering::Greater => { |
| 1438 |
self.conversion(right, right_meta, left_scalar)?; |
| 1439 |
} |
| 1440 |
} |
| 1441 |
} |
| 1442 |
|
| 1443 |
Ok(()) |
| 1444 |
} |
| 1445 |
|
| 1446 |
pub fn implicit_splat( |
| 1447 |
&mut self, |
| 1448 |
expr: &mut Handle<Expression>, |
| 1449 |
meta: Span, |
| 1450 |
vector_size: Option<VectorSize>, |
| 1451 |
) -> Result<()> { |
| 1452 |
let expr_type = self.resolve_type(*expr, meta)?; |
| 1453 |
|
| 1454 |
if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) { |
| 1455 |
*expr = self.add_expression(Expression::Splat { size, value: *expr }, meta)? |
| 1456 |
} |
| 1457 |
|
| 1458 |
Ok(()) |
| 1459 |
} |
| 1460 |
|
| 1461 |
pub fn vector_resize( |
| 1462 |
&mut self, |
| 1463 |
size: VectorSize, |
| 1464 |
vector: Handle<Expression>, |
| 1465 |
meta: Span, |
| 1466 |
) -> Result<Handle<Expression>> { |
| 1467 |
self.add_expression( |
| 1468 |
Expression::Swizzle { |
| 1469 |
size, |
| 1470 |
vector, |
| 1471 |
pattern: crate::SwizzleComponent::XYZW, |
| 1472 |
}, |
| 1473 |
meta, |
| 1474 |
) |
| 1475 |
} |
| 1476 |
} |
| 1477 |
|
| 1478 |
impl Index<Handle<Expression>> for Context<'_> { |
| 1479 |
type Output = Expression; |
| 1480 |
|
| 1481 |
fn index(&self, index: Handle<Expression>) -> &Self::Output { |
| 1482 |
if self.is_const { |
| 1483 |
&self.module.global_expressions[index] |
| 1484 |
} else { |
| 1485 |
&self.expressions[index] |
| 1486 |
} |
| 1487 |
} |
| 1488 |
} |
| 1489 |
|
| 1490 |
/// Helper struct passed when parsing expressions |
| 1491 |
/// |
| 1492 |
/// This struct should only be obtained through [`stmt_ctx`](Context::stmt_ctx) |
| 1493 |
/// and only one of these may be active at any time per context. |
| 1494 |
#[derive(Debug)] |
| 1495 |
pub struct StmtContext { |
| 1496 |
/// A arena of high level expressions which can be lowered through a |
| 1497 |
/// [`Context`] to Naga's [`Expression`]s |
| 1498 |
pub hir_exprs: Arena<HirExpr>, |
| 1499 |
} |
| 1500 |
|
| 1501 |
impl StmtContext { |
| 1502 |
const fn new() -> Self { |
| 1503 |
StmtContext { |
| 1504 |
hir_exprs: Arena::new(), |
| 1505 |
} |
| 1506 |
} |
| 1507 |
} |