Run cargo fmt and enable monocodus (#63)

This commit is contained in:
João Capucho authored and GitHub committed 2020-06-09 14:49:12 -04:00
1 parent b91b9ca987
commit f94b486d8b
11 files changed
+1053 -679

No files matched your search

+1 -1
View File
@@ -1 +1 @@
pub mod msl;
pub mod msl;
+335 -172
View File
@@ -14,16 +14,9 @@ the output struct. If there is a structure in the outputs, and it contains any b
we move them up to the root output structure that we define ourselves.
!*/
use std::{
fmt::{
Display, Error as FmtError, Formatter, Write,
},
};
use std::fmt::{Display, Error as FmtError, Formatter, Write};
use crate::{
arena::Handle,
FastHashMap,
};
use crate::{arena::Handle, FastHashMap};
/// Expect all the global variables to have a pointer type,
/// like in SPIR-V.
@@ -49,7 +42,10 @@ enum ResolvedBinding {
BuiltIn(spirv::BuiltIn),
Attribute(spirv::Word),
Color(spirv::Word),
User { prefix: &'static str, index: spirv::Word },
User {
prefix: &'static str,
index: spirv::Word,
},
Resource(BindTarget),
}
@@ -61,7 +57,7 @@ impl Level {
}
impl Display for Level {
fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> {
(0 .. self.0).map(|_| formatter.write_str("\t")).collect()
(0..self.0).map(|_| formatter.write_str("\t")).collect()
}
}
@@ -115,7 +111,11 @@ pub struct Options<'a> {
}
impl Options<'_> {
fn resolve_binding(&self, binding: &crate::Binding, mode: LocationMode) -> Result<ResolvedBinding, Error> {
fn resolve_binding(
&self,
binding: &crate::Binding,
mode: LocationMode,
) -> Result<ResolvedBinding, Error> {
match *binding {
crate::Binding::BuiltIn(built_in) => Ok(ResolvedBinding::BuiltIn(built_in)),
crate::Binding::Location(index) => match mode {
@@ -134,13 +134,11 @@ impl Options<'_> {
.cloned()
.map(ResolvedBinding::Resource)
.ok_or(Error::MissingBindTarget(source))
}
}
}
}
trait Indexed {
const CLASS: &'static str;
const PREFIX: bool = false;
@@ -149,42 +147,58 @@ trait Indexed {
impl Indexed for crate::Handle<crate::Type> {
const CLASS: &'static str = "Type";
fn id(&self) -> usize { self.index() }
fn id(&self) -> usize {
self.index()
}
}
impl Indexed for crate::Handle<crate::GlobalVariable> {
const CLASS: &'static str = "global";
fn id(&self) -> usize { self.index() }
fn id(&self) -> usize {
self.index()
}
}
impl Indexed for crate::Handle<crate::LocalVariable> {
const CLASS: &'static str = "local";
fn id(&self) -> usize { self.index() }
fn id(&self) -> usize {
self.index()
}
}
impl Indexed for crate::Handle<crate::Function> {
const CLASS: &'static str = "function";
fn id(&self) -> usize { self.index() }
fn id(&self) -> usize {
self.index()
}
}
struct MemberIndex(usize);
impl Indexed for MemberIndex {
const CLASS: &'static str = "field";
fn id(&self) -> usize { self.0 }
fn id(&self) -> usize {
self.0
}
}
struct ParameterIndex(usize);
impl Indexed for ParameterIndex {
const CLASS: &'static str = "param";
fn id(&self) -> usize { self.0 }
fn id(&self) -> usize {
self.0
}
}
struct InputStructIndex(crate::Handle<crate::Function>);
impl Indexed for InputStructIndex {
const CLASS: &'static str = "Input";
const PREFIX: bool = true;
fn id(&self) -> usize { self.0.index() }
fn id(&self) -> usize {
self.0.index()
}
}
struct OutputStructIndex(crate::Handle<crate::Function>);
impl Indexed for OutputStructIndex {
const CLASS: &'static str = "Output";
const PREFIX: bool = true;
fn id(&self) -> usize { self.0.index() }
fn id(&self) -> usize {
self.0.index()
}
}
enum NameSource<'a> {
@@ -192,9 +206,7 @@ enum NameSource<'a> {
Index(usize),
}
const RESERVED_NAMES: &[&str] = &[
"main",
];
const RESERVED_NAMES: &[&str] = &["main"];
struct Name<'a> {
class: &'static str,
@@ -203,10 +215,14 @@ struct Name<'a> {
impl Display for Name<'_> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> Result<(), FmtError> {
match self.source {
NameSource::Custom { name, prefix: false } if RESERVED_NAMES.contains(&name) => {
write!(formatter, "{}_", name)
}
NameSource::Custom { name, prefix: false } => formatter.write_str(name),
NameSource::Custom {
name,
prefix: false,
} if RESERVED_NAMES.contains(&name) => write!(formatter, "{}_", name),
NameSource::Custom {
name,
prefix: false,
} => formatter.write_str(name),
NameSource::Custom { name, prefix: true } => {
let (head, tail) = name.split_at(1);
write!(formatter, "{}{}{}", self.class, head.to_uppercase(), tail)
@@ -232,7 +248,10 @@ impl AsName for Option<String> {
Name {
class: I::CLASS,
source: match *self {
Some(ref name) if !name.is_empty() => NameSource::Custom { name, prefix: I::PREFIX },
Some(ref name) if !name.is_empty() => NameSource::Custom {
name,
prefix: I::PREFIX,
},
_ => NameSource::Index(index.id()),
},
}
@@ -250,9 +269,9 @@ impl<'a> TypedGlobalVariable<'a> {
let var = &self.module.global_variables[self.handle];
let name = var.name.or_index(self.handle);
let (space_qualifier, reference) = match var.class {
spirv::StorageClass::Uniform |
spirv::StorageClass::UniformConstant |
spirv::StorageClass::StorageBuffer => {
spirv::StorageClass::Uniform
| spirv::StorageClass::UniformConstant
| spirv::StorageClass::StorageBuffer => {
let space = if self.usage.contains(crate::GlobalUse::STORE) {
"device "
} else {
@@ -260,18 +279,18 @@ impl<'a> TypedGlobalVariable<'a> {
};
(space, "&")
}
_ => ("", "")
_ => ("", ""),
};
if GLOBAL_POINTERS {
let ty = &self.module.types[var.ty];
match ty.inner {
crate::TypeInner::Pointer { base, class } => {
crate::TypeInner::Pointer { base, class } => {
let ty_handle = match class {
spirv::StorageClass::Input |
spirv::StorageClass::Output |
spirv::StorageClass::Uniform |
spirv::StorageClass::UniformConstant => base,
_ => var.ty
spirv::StorageClass::Input
| spirv::StorageClass::Output
| spirv::StorageClass::Uniform
| spirv::StorageClass::UniformConstant => base,
_ => var.ty,
};
let ty_name = self.module.types[ty_handle].name.or_index(ty_handle);
Ok(write!(formatter, "{} {}", ty_name, name)?)
@@ -280,7 +299,11 @@ impl<'a> TypedGlobalVariable<'a> {
}
} else {
let ty_name = self.module.types[var.ty].name.or_index(var.ty);
Ok(write!(formatter, "{}{}{} {}", space_qualifier, ty_name, reference, name)?)
Ok(write!(
formatter,
"{}{}{} {}",
space_qualifier, ty_name, reference, name
)?)
}
}
}
@@ -298,12 +321,8 @@ impl ResolvedBinding {
};
Ok(formatter.write_str(name)?)
}
ResolvedBinding::Attribute(index) => {
Ok(write!(formatter, "attribute({})", index)?)
}
ResolvedBinding::Color(index) => {
Ok(write!(formatter, "color({})", index)?)
}
ResolvedBinding::Attribute(index) => Ok(write!(formatter, "attribute({})", index)?),
ResolvedBinding::Color(index) => Ok(write!(formatter, "color({})", index)?),
ResolvedBinding::User { prefix, index } => {
Ok(write!(formatter, "user({}{})", prefix, index)?)
}
@@ -321,7 +340,11 @@ impl ResolvedBinding {
}
}
fn try_fmt_decorated<W: Write>(&self, formatter: &mut W, terminator: &str) -> Result<(), Error> {
fn try_fmt_decorated<W: Write>(
&self,
formatter: &mut W,
terminator: &str,
) -> Result<(), Error> {
formatter.write_str(" [[")?;
self.try_fmt(formatter)?;
formatter.write_str("]]")?;
@@ -356,7 +379,11 @@ const LOCATION_INPUT_STRUCT_NAME: &str = "input";
const COMPONENTS: &[char] = &['x', 'y', 'z', 'w'];
fn separate(is_last: bool) -> &'static str {
if is_last { "" } else { "," }
if is_last {
""
} else {
","
}
}
#[derive(Debug)]
@@ -410,9 +437,15 @@ impl<W: Write> Writer<W> {
write!(self.out, ".{}", name)?;
Ok(module.borrow_type(member.ty))
}
crate::TypeInner::Matrix { rows, kind, width, .. } => {
crate::TypeInner::Matrix {
rows, kind, width, ..
} => {
write!(self.out, ".{}", COMPONENTS[index as usize])?;
Ok(MaybeOwned::Owned(crate::TypeInner::Vector { size: rows, kind, width }))
Ok(MaybeOwned::Owned(crate::TypeInner::Vector {
size: rows,
kind,
width,
}))
}
crate::TypeInner::Vector { kind, width, .. } => {
write!(self.out, ".{}", COMPONENTS[index as usize])?;
@@ -428,14 +461,17 @@ impl<W: Write> Writer<W> {
ref other => Err(Error::UnexpectedIndexing(other.clone())),
}
}
crate::Expression::Constant(handle) => {
self.put_constant(handle, module)
}
crate::Expression::Constant(handle) => self.put_constant(handle, module),
crate::Expression::Compose { ty, ref components } => {
let inner = &module.types[ty].inner;
match *inner {
crate::TypeInner::Vector { size, kind, .. } => {
write!(self.out, "{}{}(", scalar_kind_string(kind), vector_size_string(size))?;
write!(
self.out,
"{}{}(",
scalar_kind_string(kind),
vector_size_string(size)
)?;
for (i, &handle) in components.iter().enumerate() {
if i != 0 {
write!(self.out, ",")?;
@@ -461,7 +497,7 @@ impl<W: Write> Writer<W> {
}
}
} else if let crate::TypeInner::Struct { .. } = *inner {
return Ok(MaybeOwned::Borrowed(inner));
return Ok(MaybeOwned::Borrowed(inner));
}
write!(self.out, "{}.", OUTPUT_STRUCT_NAME)?;
}
@@ -486,9 +522,7 @@ impl<W: Write> Writer<W> {
crate::Expression::Load { pointer } => {
//write!(self.out, "*")?;
match *self.put_expression(pointer, function, module)?.borrow() {
crate::TypeInner::Pointer { base, .. } => {
Ok(module.borrow_type(base))
}
crate::TypeInner::Pointer { base, .. } => Ok(module.borrow_type(base)),
ref other => Err(Error::UnexpectedLoadPointer(other.clone())),
}
}
@@ -523,20 +557,42 @@ impl<W: Write> Writer<W> {
Ok(if op_str.len() == 1 {
match (ty_left.borrow(), ty_right.borrow()) {
(&crate::TypeInner::Scalar { kind, width }, &crate::TypeInner::Scalar { .. }) =>
MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width }),
(&crate::TypeInner::Scalar { .. }, &crate::TypeInner::Vector { size, kind, width }) |
(&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Scalar { .. }) |
(&crate::TypeInner::Vector { size, kind, width }, &crate::TypeInner::Vector { .. }) =>
MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }),
(other_left, other_right) =>
return Err(Error::UnableToInferBinaryOpOutput(other_left.clone(), op, other_right.clone())),
(
&crate::TypeInner::Scalar { kind, width },
&crate::TypeInner::Scalar { .. },
) => MaybeOwned::Owned(crate::TypeInner::Scalar { kind, width }),
(
&crate::TypeInner::Scalar { .. },
&crate::TypeInner::Vector { size, kind, width },
)
| (
&crate::TypeInner::Vector { size, kind, width },
&crate::TypeInner::Scalar { .. },
)
| (
&crate::TypeInner::Vector { size, kind, width },
&crate::TypeInner::Vector { .. },
) => MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }),
(other_left, other_right) => {
return Err(Error::UnableToInferBinaryOpOutput(
other_left.clone(),
op,
other_right.clone(),
))
}
}
} else {
MaybeOwned::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Bool, width: 1 })
MaybeOwned::Owned(crate::TypeInner::Scalar {
kind: crate::ScalarKind::Bool,
width: 1,
})
})
}
crate::Expression::ImageSample { image, sampler, coordinate } => {
crate::Expression::ImageSample {
image,
sampler,
coordinate,
} => {
let ty_image = self.put_expression(image, function, module)?;
write!(self.out, ".sample(")?;
self.put_expression(sampler, function, module)?;
@@ -548,58 +604,67 @@ impl<W: Write> Writer<W> {
ref other => Err(Error::UnexpectedImageType(other.clone())),
}
}
crate::Expression::Call { ref name, ref arguments } => {
match name.as_str() {
"cos" |
"normalize" |
"sin" => {
write!(self.out, "{}(", name)?;
let result = self.put_expression(arguments[0], function, module)?;
write!(self.out, ")")?;
Ok(result)
}
"fclamp" => {
write!(self.out, "clamp(")?;
let result = self.put_expression(arguments[0], function, module)?;
write!(self.out, ", ")?;
self.put_expression(arguments[1], function, module)?;
write!(self.out, ", ")?;
self.put_expression(arguments[2], function, module)?;
write!(self.out, ")")?;
Ok(result)
}
"atan2" => {
write!(self.out, "{}(", name)?;
let result = self.put_expression(arguments[0], function, module)?;
write!(self.out, ", ")?;
self.put_expression(arguments[1], function, module)?;
write!(self.out, ")")?;
Ok(result)
}
"distance" => {
write!(self.out, "distance(")?;
let result = match *self.put_expression(arguments[0], function, module)?.borrow() {
crate::TypeInner::Vector { kind, width, .. } => crate::TypeInner::Scalar { kind, width },
ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())),
};
write!(self.out, ", ")?;
self.put_expression(arguments[1], function, module)?;
write!(self.out, ")")?;
Ok(MaybeOwned::Owned(result))
}
"length" => {
write!(self.out, "length(")?;
let result = match *self.put_expression(arguments[0], function, module)?.borrow() {
crate::TypeInner::Vector { kind, width, .. } => crate::TypeInner::Scalar { kind, width },
ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())),
};
write!(self.out, ")")?;
Ok(MaybeOwned::Owned(result))
}
other => Err(Error::UnsupportedCall(other.to_owned())),
crate::Expression::Call {
ref name,
ref arguments,
} => match name.as_str() {
"cos" | "normalize" | "sin" => {
write!(self.out, "{}(", name)?;
let result = self.put_expression(arguments[0], function, module)?;
write!(self.out, ")")?;
Ok(result)
}
}
"fclamp" => {
write!(self.out, "clamp(")?;
let result = self.put_expression(arguments[0], function, module)?;
write!(self.out, ", ")?;
self.put_expression(arguments[1], function, module)?;
write!(self.out, ", ")?;
self.put_expression(arguments[2], function, module)?;
write!(self.out, ")")?;
Ok(result)
}
"atan2" => {
write!(self.out, "{}(", name)?;
let result = self.put_expression(arguments[0], function, module)?;
write!(self.out, ", ")?;
self.put_expression(arguments[1], function, module)?;
write!(self.out, ")")?;
Ok(result)
}
"distance" => {
write!(self.out, "distance(")?;
let result = match *self
.put_expression(arguments[0], function, module)?
.borrow()
{
crate::TypeInner::Vector { kind, width, .. } => {
crate::TypeInner::Scalar { kind, width }
}
ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())),
};
write!(self.out, ", ")?;
self.put_expression(arguments[1], function, module)?;
write!(self.out, ")")?;
Ok(MaybeOwned::Owned(result))
}
"length" => {
write!(self.out, "length(")?;
let result = match *self
.put_expression(arguments[0], function, module)?
.borrow()
{
crate::TypeInner::Vector { kind, width, .. } => {
crate::TypeInner::Scalar { kind, width }
}
ref other => return Err(Error::UnexpectedDistanceArgument(other.clone())),
};
write!(self.out, ")")?;
Ok(MaybeOwned::Owned(result))
}
other => Err(Error::UnsupportedCall(other.to_owned())),
},
ref other => Err(Error::UnsupportedExpression(other.clone())),
}
}
@@ -655,7 +720,11 @@ impl<W: Write> Writer<W> {
log::trace!("statement[{}] {:?}", level.0, statement);
match *statement {
crate::Statement::Empty => {}
crate::Statement::If { condition, ref accept, ref reject } => {
crate::Statement::If {
condition,
ref accept,
ref reject,
} => {
write!(self.out, "{}if (", level)?;
self.put_expression(condition, function, module)?;
writeln!(self.out, ") {{")?;
@@ -670,7 +739,10 @@ impl<W: Write> Writer<W> {
}
writeln!(self.out, "{}}}", level)?;
}
crate::Statement::Loop { ref body, ref continuing } => {
crate::Statement::Loop {
ref body,
ref continuing,
} => {
writeln!(self.out, "{}while(true) {{", level)?;
for s in body {
self.put_statement(level.next(), s, function, has_output, module)?;
@@ -733,20 +805,38 @@ impl<W: Write> Writer<W> {
match ty.inner {
crate::TypeInner::Scalar { kind, .. } => {
write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?;
},
}
crate::TypeInner::Vector { size, kind, .. } => {
write!(self.out, "typedef {}{} {}", scalar_kind_string(kind), vector_size_string(size), name)?;
},
crate::TypeInner::Matrix { columns, rows, kind, .. } => {
write!(self.out, "typedef {}{}x{} {}", scalar_kind_string(kind), vector_size_string(columns), vector_size_string(rows), name)?;
write!(
self.out,
"typedef {}{} {}",
scalar_kind_string(kind),
vector_size_string(size),
name
)?;
}
crate::TypeInner::Matrix {
columns,
rows,
kind,
..
} => {
write!(
self.out,
"typedef {}{}x{} {}",
scalar_kind_string(kind),
vector_size_string(columns),
vector_size_string(rows),
name
)?;
}
crate::TypeInner::Pointer { base, class } => {
let base_name = module.types[base].name.or_index(base);
let class_name = match class {
spirv::StorageClass::Input |
spirv::StorageClass::Output => continue,
spirv::StorageClass::Uniform |
spirv::StorageClass::UniformConstant => "constant",
spirv::StorageClass::Input | spirv::StorageClass::Output => continue,
spirv::StorageClass::Uniform | spirv::StorageClass::UniformConstant => {
"constant"
}
other => {
log::warn!("Unexpected pointer class {:?}", other);
""
@@ -760,7 +850,11 @@ impl<W: Write> Writer<W> {
crate::ArraySize::Static(length) => length,
crate::ArraySize::Dynamic => 1,
};
write!(self.out, "typedef {} {}[{}]", base_name, name, resolved_size)?;
write!(
self.out,
"typedef {} {}[{}]",
base_name, name, resolved_size
)?;
}
crate::TypeInner::Struct { ref members } => {
writeln!(self.out, "struct {} {{", name)?;
@@ -769,7 +863,8 @@ impl<W: Write> Writer<W> {
let base_name = module.types[member.ty].name.or_index(member.ty);
write!(self.out, "\t{} {}", base_name, name)?;
if let Some(ref binding) = member.binding {
let resolved = options.resolve_binding(binding, LocationMode::Intermediate)?;
let resolved =
options.resolve_binding(binding, LocationMode::Intermediate)?;
resolved.try_fmt_decorated(&mut self.out, "")?;
}
writeln!(self.out, ";")?;
@@ -790,7 +885,9 @@ impl<W: Write> Writer<W> {
return Err(Error::InvalidImageFlags(flags));
}
"sample"
} else if flags.contains(crate::ImageFlags::CAN_LOAD | crate::ImageFlags::CAN_STORE) {
} else if flags
.contains(crate::ImageFlags::CAN_LOAD | crate::ImageFlags::CAN_STORE)
{
"read_write"
} else if flags.contains(crate::ImageFlags::CAN_STORE) {
"write"
@@ -799,7 +896,11 @@ impl<W: Write> Writer<W> {
} else {
return Err(Error::InvalidImageFlags(flags));
};
write!(self.out, "typedef texture{}<{}, access::{}> {}", dim, base_name, access, name)?;
write!(
self.out,
"typedef texture{}<{}, access::{}> {}",
dim, base_name, access, name
)?;
}
crate::TypeInner::Sampler => {
write!(self.out, "typedef sampler {}", name)?;
@@ -820,7 +921,7 @@ impl<W: Write> Writer<W> {
match var.class {
spirv::StorageClass::Input => {
if let Some(crate::Binding::Location(_)) = var.binding {
continue
continue;
}
}
spirv::StorageClass::Output => continue,
@@ -846,32 +947,52 @@ impl<W: Write> Writer<W> {
// make dedicated input/output structs
if let Some(em) = exec_model {
if let Some(return_type) = fun.return_type {
return Err(Error::ExecutionModelReturnType(em, return_type))
return Err(Error::ExecutionModelReturnType(em, return_type));
}
let (em_str, in_mode, out_mode) = match em {
spirv::ExecutionModel::Vertex => ("vertex", LocationMode::VertexInput, LocationMode::Intermediate),
spirv::ExecutionModel::Fragment => ("fragment", LocationMode::Intermediate, LocationMode::FragmentOutput),
spirv::ExecutionModel::GLCompute => ("kernel", LocationMode::Uniform, LocationMode::Uniform),
spirv::ExecutionModel::Vertex => (
"vertex",
LocationMode::VertexInput,
LocationMode::Intermediate,
),
spirv::ExecutionModel::Fragment => (
"fragment",
LocationMode::Intermediate,
LocationMode::FragmentOutput,
),
spirv::ExecutionModel::GLCompute => {
("kernel", LocationMode::Uniform, LocationMode::Uniform)
}
_ => return Err(Error::UnsupportedExecutionModel(em)),
};
let location_input_name = fun.name.or_index(InputStructIndex(fun_handle));
if em != spirv::ExecutionModel::GLCompute {
writeln!(self.out, "struct {} {{", location_input_name)?;
for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) {
if var.class != spirv::StorageClass::Input || !usage.contains(crate::GlobalUse::LOAD) {
continue
for ((handle, var), &usage) in
module.global_variables.iter().zip(&fun.global_usage)
{
if var.class != spirv::StorageClass::Input
|| !usage.contains(crate::GlobalUse::LOAD)
{
continue;
}
// if it's a struct, lift all the built-in contents up to the root
let mut ty_handle = var.ty;
if GLOBAL_POINTERS {
if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner {
if let crate::TypeInner::Pointer { base, .. } =
module.types[var.ty].inner
{
ty_handle = base;
}
}
if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner {
if let crate::TypeInner::Struct { ref members } =
module.types[ty_handle].inner
{
for (index, member) in members.iter().enumerate() {
if let Some(ref binding@crate::Binding::Location(_)) = member.binding {
if let Some(ref binding @ crate::Binding::Location(_)) =
member.binding
{
let name = member.name.or_index(MemberIndex(index));
let ty_name = module.types[member.ty].name.or_index(member.ty);
let resolved = options.resolve_binding(binding, in_mode)?;
@@ -879,8 +1000,13 @@ impl<W: Write> Writer<W> {
resolved.try_fmt_decorated(&mut self.out, ";\n")?;
}
}
} else if let Some(ref binding@crate::Binding::Location(_)) = var.binding {
let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() };
} else if let Some(ref binding @ crate::Binding::Location(_)) = var.binding
{
let tyvar = TypedGlobalVariable {
module,
handle,
usage: crate::GlobalUse::empty(),
};
let resolved = options.resolve_binding(binding, in_mode)?;
write!(self.out, "\t")?;
@@ -890,22 +1016,31 @@ impl<W: Write> Writer<W> {
}
writeln!(self.out, "}};")?;
writeln!(self.out, "struct {} {{", output_name)?;
for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) {
if var.class != spirv::StorageClass::Output || !usage.contains(crate::GlobalUse::STORE) {
continue
for ((handle, var), &usage) in
module.global_variables.iter().zip(&fun.global_usage)
{
if var.class != spirv::StorageClass::Output
|| !usage.contains(crate::GlobalUse::STORE)
{
continue;
}
// if it's a struct, lift all the built-in contents up to the root
let mut ty_handle = var.ty;
if GLOBAL_POINTERS {
if let crate::TypeInner::Pointer { base, .. } = module.types[var.ty].inner {
if let crate::TypeInner::Pointer { base, .. } =
module.types[var.ty].inner
{
ty_handle = base;
}
}
if let crate::TypeInner::Struct { ref members } = module.types[ty_handle].inner {
if let crate::TypeInner::Struct { ref members } =
module.types[ty_handle].inner
{
for (index, member) in members.iter().enumerate() {
let name = member.name.or_index(MemberIndex(index));
let ty_name = module.types[member.ty].name.or_index(member.ty);
let binding = member.binding
let binding = member
.binding
.as_ref()
.ok_or(Error::MissingBinding(handle))?;
let resolved = options.resolve_binding(binding, out_mode)?;
@@ -913,7 +1048,11 @@ impl<W: Write> Writer<W> {
resolved.try_fmt_decorated(&mut self.out, ";\n")?;
}
} else {
let tyvar = TypedGlobalVariable { module, handle, usage: crate::GlobalUse::empty() };
let tyvar = TypedGlobalVariable {
module,
handle,
usage: crate::GlobalUse::empty(),
};
write!(self.out, "\t")?;
tyvar.try_fmt(&mut self.out)?;
if let Some(ref binding) = var.binding {
@@ -926,31 +1065,46 @@ impl<W: Write> Writer<W> {
writeln!(self.out, "}};")?;
writeln!(self.out, "{} {} {}(", em_str, output_name, fun_name)?;
let separator = separate(last_used_global.is_none());
writeln!(self.out, "\t{} {} [[stage_in]]{}",
location_input_name, LOCATION_INPUT_STRUCT_NAME, separator)?;
writeln!(
self.out,
"\t{} {} [[stage_in]]{}",
location_input_name, LOCATION_INPUT_STRUCT_NAME, separator
)?;
} else {
writeln!(self.out, "{} void {}(", em_str, fun_name)?;
}
for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage) {
for ((handle, var), &usage) in module.global_variables.iter().zip(&fun.global_usage)
{
if usage.is_empty() || var.class == spirv::StorageClass::Output {
continue
continue;
}
if var.class == spirv::StorageClass::Input {
if let Some(crate::Binding::Location(_)) = var.binding {
// location inputs are put into a separate struct
continue
continue;
}
}
let loc_mode = match (em, var.class) {
(spirv::ExecutionModel::Vertex, spirv::StorageClass::Input) => LocationMode::VertexInput,
(spirv::ExecutionModel::Vertex, spirv::StorageClass::Output) |
(spirv::ExecutionModel::Fragment, spirv::StorageClass::Input) => LocationMode::Intermediate,
(spirv::ExecutionModel::Fragment, spirv::StorageClass::Output) => LocationMode::FragmentOutput,
(spirv::ExecutionModel::Vertex, spirv::StorageClass::Input) => {
LocationMode::VertexInput
}
(spirv::ExecutionModel::Vertex, spirv::StorageClass::Output)
| (spirv::ExecutionModel::Fragment, spirv::StorageClass::Input) => {
LocationMode::Intermediate
}
(spirv::ExecutionModel::Fragment, spirv::StorageClass::Output) => {
LocationMode::FragmentOutput
}
_ => LocationMode::Uniform,
};
let resolved = options.resolve_binding(var.binding.as_ref().unwrap(), loc_mode)?;
let tyvar = TypedGlobalVariable { module, handle, usage };
let resolved =
options.resolve_binding(var.binding.as_ref().unwrap(), loc_mode)?;
let tyvar = TypedGlobalVariable {
module,
handle,
usage,
};
let separator = separate(last_used_global == Some(handle));
write!(self.out, "\t")?;
tyvar.try_fmt(&mut self.out)?;
@@ -962,14 +1116,19 @@ impl<W: Write> Writer<W> {
Some(type_id) => module.types[type_id].name.or_index(type_id),
None => Name {
class: "",
source: NameSource::Custom { name: "void", prefix: false },
source: NameSource::Custom {
name: "void",
prefix: false,
},
},
};
writeln!(self.out, "{} {}(", result_type_name, fun_name)?;
for (index, &ty) in fun.parameter_types.iter().enumerate() {
let name = Name::from(ParameterIndex(index));
let member_type_name = module.types[ty].name.or_index(ty);
let separator = separate(index + 1 == fun.parameter_types.len() && last_used_global.is_none());
let separator = separate(
index + 1 == fun.parameter_types.len() && last_used_global.is_none(),
);
writeln!(self.out, "\t{} {}{}", member_type_name, name, separator)?;
}
}
@@ -977,16 +1136,20 @@ impl<W: Write> Writer<W> {
// write down function body
let has_output = match exec_model {
Some(spirv::ExecutionModel::Vertex) |
Some(spirv::ExecutionModel::Fragment) => {
Some(spirv::ExecutionModel::Vertex) | Some(spirv::ExecutionModel::Fragment) => {
writeln!(self.out, "\t{} {};", output_name, OUTPUT_STRUCT_NAME)?;
true
}
_ => false
_ => false,
};
for (local_handle, local) in fun.local_variables.iter() {
let ty_name = module.types[local.ty].name.or_index(local.ty);
write!(self.out, "\t{} {}", ty_name, local.name.or_index(local_handle))?;
write!(
self.out,
"\t{} {}",
ty_name,
local.name.or_index(local_handle)
)?;
if let Some(value) = local.init {
write!(self.out, " = ")?;
self.put_expression(value, fun, module)?;