From 0bf0a1430f8fedb0cbdea061d705ddc76f07d861 Mon Sep 17 00:00:00 2001 From: Atul Bhosale Date: Thu, 20 Feb 2020 19:30:04 +0530 Subject: [PATCH] Format code using 'cargo fmt' --- rasen-dsl/codegen/mod.rs | 6 +- rasen-dsl/codegen/mul.rs | 5 +- rasen-dsl/codegen/operations.rs | 472 +++++++++++++---------------- rasen-dsl/codegen/types.rs | 39 ++- rasen-dsl/src/context/execute.rs | 8 +- rasen-dsl/src/context/mod.rs | 6 +- rasen-dsl/src/context/parse.rs | 11 +- rasen-dsl/src/lib.rs | 2 +- rasen-dsl/src/module.rs | 31 +- rasen-dsl/src/prelude.rs | 12 +- rasen-dsl/src/value.rs | 6 +- rasen-dsl/tests/exec.rs | 10 +- rasen-plugin/src/lib.rs | 493 +++++++++++++++++-------------- rasen-plugin/tests/graph.rs | 2 +- rasen/src/errors.rs | 2 +- rasen/src/operations/glsl.rs | 286 +++++++++--------- 16 files changed, 713 insertions(+), 678 deletions(-) diff --git a/rasen-dsl/codegen/mod.rs b/rasen-dsl/codegen/mod.rs index 78e8e8e..3adad27 100644 --- a/rasen-dsl/codegen/mod.rs +++ b/rasen-dsl/codegen/mod.rs @@ -1,6 +1,6 @@ pub mod defs; pub mod functions; -pub mod types; -pub mod operations; -pub mod mul; pub mod math; +pub mod mul; +pub mod operations; +pub mod types; diff --git a/rasen-dsl/codegen/mul.rs b/rasen-dsl/codegen/mul.rs index cb5feda..e0349ff 100644 --- a/rasen-dsl/codegen/mul.rs +++ b/rasen-dsl/codegen/mul.rs @@ -65,8 +65,9 @@ pub fn impl_mul_variant(left_res: Type, right_res: Type) -> Option right_res.category, right_res.ty, ) { - (_, "bool", _, _) | (_, _, _, "bool") | - (Category::SCALAR, _, Category::SCALAR, _) => return None, + (_, "bool", _, _) | (_, _, _, "bool") | (Category::SCALAR, _, Category::SCALAR, _) => { + return None + } (lc, lt, rc, rt) if lc == rc && lt == rt && left_res.size == right_res.size => ( left_res.name.clone(), diff --git a/rasen-dsl/codegen/operations.rs b/rasen-dsl/codegen/operations.rs index 96cbda6..dd48143 100644 --- a/rasen-dsl/codegen/operations.rs +++ b/rasen-dsl/codegen/operations.rs @@ -1,7 +1,7 @@ //! GLSL Operation declarations -use std::collections::{HashMap, hash_map::Entry}; use proc_macro2::{Ident, Span, TokenStream}; +use std::collections::{hash_map::Entry, HashMap}; enum Generic { Container, @@ -15,16 +15,16 @@ impl Generic { Generic::Other(gen) => Some(*gen), } } - + fn tokens(&self) -> TokenStream { match self { Generic::Container => { quote! { T } - }, + } Generic::Other(gen) => { let name = Ident::new(&gen.to_string(), Span::call_site()); quote! { #name } - }, + } } } } @@ -50,9 +50,7 @@ impl ArgType { fn tokens(&self, is_trait: bool, is_ret: bool) -> TokenStream { match self { - ArgType::Generic(gen) => { - gen.tokens() - }, + ArgType::Generic(gen) => gen.tokens(), ArgType::Value(inner) => { let inner = inner.tokens(is_trait, is_ret); let ctx = if is_trait { @@ -67,7 +65,11 @@ impl ArgType { quote! { impl IntoValue<#ctx, Output = #inner> } } } - ArgType::Associated { generic, trait_, name } => { + ArgType::Associated { + generic, + trait_, + name, + } => { let generic = generic.tokens(); let name = Ident::new(name, Span::call_site()); quote! { <#generic as #trait_>::#name } @@ -81,10 +83,7 @@ impl ArgType { let tokens = inner.tokens(context.is_trait(), true); let mut inner = inner.constraints(context); - inner.add( - quote! { #tokens }, - quote! { Copy }, - ); + inner.add(quote! { #tokens }, quote! { Copy }); match context { Context::Trait => inner.add(quote! { Self }, quote! { Container<#tokens> }), @@ -95,12 +94,11 @@ impl ArgType { inner } - ArgType::Associated { generic, trait_, .. } => { + ArgType::Associated { + generic, trait_, .. + } => { let generic = generic.tokens(); - Constraints::of( - quote! { #generic }, - trait_.clone(), - ) + Constraints::of(quote! { #generic }, trait_.clone()) } _ => Constraints::default(), @@ -144,7 +142,13 @@ struct Constraints { impl Constraints { fn of(key: TokenStream, value: TokenStream) -> Self { let mut inner = HashMap::new(); - inner.insert(key.to_string(), Constraint { key, values: vec![value] }); + inner.insert( + key.to_string(), + Constraint { + key, + values: vec![value], + }, + ); Constraints { inner } } @@ -192,25 +196,31 @@ fn operation( TokenStream::new(), ]; - let generics: Vec<_> = args.into_iter() - .filter_map(|arg| - arg.ty.generic().map(|name| - Ident::new(&name.to_string(), Span::call_site()) - ) - ) + let generics: Vec<_> = args + .into_iter() + .filter_map(|arg| { + arg.ty + .generic() + .map(|name| Ident::new(&name.to_string(), Span::call_site())) + }) .collect(); - for (index, context) in [Context::Trait, Context::Parse, Context::Execute, Context::Func].iter().enumerate() { + for (index, context) in [ + Context::Trait, + Context::Parse, + Context::Execute, + Context::Func, + ] + .iter() + .enumerate() + { let generics = generics.clone(); let mut constraints = Constraints::default(); - + for constraint in constraint_list { for value in &constraint.values { - constraints.add( - constraint.key.clone(), - value.clone(), - ); + constraints.add(constraint.key.clone(), value.clone()); } } @@ -220,7 +230,9 @@ fn operation( constraints.extend(result.constraints(context)); - let constraints: Vec<_> = constraints.inner.values() + let constraints: Vec<_> = constraints + .inner + .values() .map(|constraint| { let key = constraint.key.clone(); let values = constraint.values.clone(); @@ -230,7 +242,8 @@ fn operation( let is_trait = context.is_trait(); - let fn_args: Vec<_> = args.into_iter() + let fn_args: Vec<_> = args + .into_iter() .map(|arg| { let name = Ident::new(&arg.name, Span::call_site()); let ty = arg.ty.tokens(is_trait, false); @@ -248,7 +261,8 @@ fn operation( }, Context::Parse => { - let edges: Vec<_> = edges.into_iter() + let edges: Vec<_> = edges + .into_iter() .enumerate() .map(|(index, name)| { let ident = Ident::new(name, Span::call_site()); @@ -267,10 +281,11 @@ fn operation( }) } } - }, + } Context::Execute => { - let args_unwrap: Vec<_> = args.into_iter() + let args_unwrap: Vec<_> = args + .into_iter() .filter_map(|arg| { if let ArgType::Value(_) = arg.ty { let name = Ident::new(&arg.name, Span::call_site()); @@ -288,10 +303,11 @@ fn operation( Value({ #implementation }) } } - }, + } Context::Func => { - let arg_names: Vec<_> = args.into_iter() + let arg_names: Vec<_> = args + .into_iter() .map(|arg| { let name = Ident::new(&arg.name, Span::call_site()); if let ArgType::Value(_) = arg.ty { @@ -308,7 +324,7 @@ fn operation( >::#fn_name( #( #arg_names ),* ) } } - }, + } }; } @@ -354,12 +370,10 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { ), operation( "normalize", - &[ - Argument { - name: "vector", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "vector", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), &[ Constraint { @@ -377,7 +391,7 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { &["vector"], quote! { vector.normalize() - } + }, ), operation( "dot", @@ -412,7 +426,7 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { &["a", "b"], quote! { a.dot(&b) - } + }, ), operation( "clamp", @@ -431,19 +445,17 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { }, ], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Numerical }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Numerical }], + }], quote! { Node::Clamp }, &["x", "min", "max"], quote! { x.max(min).min(max) - } + }, ), operation( "cross", @@ -458,157 +470,131 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { }, ], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Vector3 }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Vector3 }], + }], quote! { Node::Cross }, &["x", "y"], quote! { x.cross(&y) - } + }, ), operation( "floor", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Floating }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Floating }], + }], quote! { Node::Floor }, &["val"], quote! { val.floor() - } + }, ), operation( "ceil", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Floating }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Floating }], + }], quote! { Node::Ceil }, &["val"], quote! { val.ceil() - } + }, ), operation( "round", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Floating }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Floating }], + }], quote! { Node::Round }, &["val"], quote! { val.round() - } + }, ), operation( "sin", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Floating }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Floating }], + }], quote! { Node::Sin }, &["val"], quote! { val.sin() - } + }, ), operation( "cos", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Floating }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Floating }], + }], quote! { Node::Cos }, &["val"], quote! { val.cos() - } + }, ), operation( "tan", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Floating }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Floating }], + }], quote! { Node::Tan }, &["val"], quote! { val.tan() - } + }, ), operation( "pow", @@ -623,19 +609,17 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { }, ], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Numerical }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Numerical }], + }], quote! { Node::Pow }, &["x", "y"], quote! { x.pow(y) - } + }, ), operation( "min", @@ -650,19 +634,17 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { }, ], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Numerical }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Numerical }], + }], quote! { Node::Min }, &["x", "y"], quote! { x.min(y) - } + }, ), operation( "max", @@ -677,28 +659,24 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { }, ], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Numerical }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Numerical }], + }], quote! { Node::Max }, &["x", "y"], quote! { x.max(y) - } + }, ), operation( "length", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Associated { generic: Generic::Container, trait_: quote! { Vector }, @@ -720,7 +698,7 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { &["val"], quote! { val.length() - } + }, ), operation( "distance", @@ -755,7 +733,7 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { &["x", "y"], quote! { (x - y).length() - } + }, ), operation( "reflect", @@ -791,7 +769,7 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { quote! { let dot = n.dot(&i); i - (dot + dot) * n - } + }, ), operation( "refract", @@ -817,10 +795,7 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { &[ Constraint { key: quote! { T }, - values: vec![ - quote! { VectorFloating }, - quote! { Sub }, - ], + values: vec![quote! { VectorFloating }, quote! { Sub }], }, Constraint { key: quote! { ::Scalar }, @@ -846,7 +821,7 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { } else { eta * i - (eta * n.dot(&i) + k.sqrt()) * n } - } + }, ), operation( "mix", @@ -865,93 +840,79 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { }, ], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![ - quote! { GenType }, - quote! { Add }, - quote! { Sub }, - quote! { Mul }, - ], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![ + quote! { GenType }, + quote! { Add }, + quote! { Sub }, + quote! { Mul }, + ], + }], quote! { Node::Mix }, &["x", "y", "a"], quote! { x * (T::one() - a) + y * a - } + }, ), operation( "sqrt", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Floating }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Floating }], + }], quote! { Node::Sqrt }, &["val"], quote! { val.sqrt() - } + }, ), operation( "log", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Floating }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Floating }], + }], quote! { Node::Log }, &["val"], quote! { val.ln() - } + }, ), operation( "abs", - &[ - Argument { - name: "val", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "val", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![quote! { Floating }], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Floating }], + }], quote! { Node::Abs }, &["val"], quote! { val.abs() - } + }, ), operation( "smoothstep", @@ -970,18 +931,16 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { }, ], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![ - quote! { GenType }, - quote! { Add }, - quote! { Sub }, - quote! { Mul }, - quote! { Div }, - ], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![ + quote! { GenType }, + quote! { Add }, + quote! { Sub }, + quote! { Mul }, + quote! { Div }, + ], + }], quote! { Node::Smoothstep }, @@ -992,32 +951,26 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { let t = ((x - edge0) / (edge1 - edge0)).max(T::zero()).min(T::one()); t * t * (three - two * t) - } + }, ), operation( "inverse", - &[ - Argument { - name: "v", - ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - }, - ], + &[Argument { + name: "v", + ty: ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), + }], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![ - quote! { Matrix }, - ], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { Matrix }], + }], quote! { Node::Inverse }, &["v"], quote! { v.inverse() - } + }, ), operation( "step", @@ -1032,15 +985,10 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { }, ], ArgType::Value(Box::new(ArgType::Generic(Generic::Container))), - &[ - Constraint { - key: quote! { T }, - values: vec![ - quote! { GenType }, - quote! { PartialOrd }, - ], - }, - ], + &[Constraint { + key: quote! { T }, + values: vec![quote! { GenType }, quote! { PartialOrd }], + }], quote! { Node::Step }, @@ -1051,7 +999,7 @@ pub fn impl_operations() -> Vec<[TokenStream; 4]> { } else { T::one() } - } + }, ), ] } diff --git a/rasen-dsl/codegen/types.rs b/rasen-dsl/codegen/types.rs index 2dac051..2a67201 100644 --- a/rasen-dsl/codegen/types.rs +++ b/rasen-dsl/codegen/types.rs @@ -1,8 +1,6 @@ //! GLSL Types declarations -use codegen::{ - defs::{all_types, Category, Type}, -}; +use codegen::defs::{all_types, Category, Type}; use proc_macro2::{Ident, Span, TokenStream}; fn type_scalar(name: &Ident, kind: &'static str) -> [TokenStream; 5] { @@ -13,7 +11,7 @@ fn type_scalar(name: &Ident, kind: &'static str) -> [TokenStream; 5] { let mut traits = Vec::new(); match kind { - "bool" => {}, + "bool" => {} "i32" => { traits.push(quote! { @@ -33,7 +31,7 @@ fn type_scalar(name: &Ident, kind: &'static str) -> [TokenStream; 5] { fn pow(self, rhs: Self) -> Self { self.pow(std::convert::TryInto::try_into(rhs).unwrap()) } } }); - }, + } "u32" => { traits.push(quote! { impl GenType for #name { @@ -52,7 +50,7 @@ fn type_scalar(name: &Ident, kind: &'static str) -> [TokenStream; 5] { fn pow(self, rhs: Self) -> Self { self.pow(rhs) } } }); - }, + } _ => { traits.push(quote! { @@ -159,7 +157,8 @@ fn type_vector( .collect(); let args2 = args1.clone(); - let parse_edges: Vec<_> = args1.iter() + let parse_edges: Vec<_> = args1 + .iter() .enumerate() .map(|(index, ident)| { let ident = ident.clone(); @@ -368,7 +367,8 @@ fn type_matrix( .map(|i| Ident::new(&format!("arg_{}", i), Span::call_site())) .collect(); - let parse_edges: Vec<_> = args.iter() + let parse_edges: Vec<_> = args + .iter() .enumerate() .map(|(index, ident)| { let ident = ident.clone(); @@ -377,7 +377,8 @@ fn type_matrix( }) .collect(); - let execute_unwrap: Vec<_> = args.iter() + let execute_unwrap: Vec<_> = args + .iter() .map(|ident| { let ident = quote! { (#ident.0).0 }; let items: Vec<_> = (0..(size as usize)) @@ -387,10 +388,9 @@ fn type_matrix( quote! { #( #items ),* } }) .collect(); - + let container_args: Vec<_> = { - args - .iter() + args.iter() .map(|name| { let comp = comp.clone(); quote! { #name: Value } @@ -398,8 +398,7 @@ fn type_matrix( .collect() }; let arg_list: Vec<_> = { - args - .iter() + args.iter() .map(|name| { let comp = comp.clone(); quote! { #name: impl IntoValue } @@ -468,9 +467,17 @@ fn type_matrix( } pub fn type_structs() -> Vec<[TokenStream; 5]> { - all_types().iter() + all_types() + .iter() .filter_map(|ty| { - let Type { name, category, ty, component, size, .. } = ty.clone(); + let Type { + name, + category, + ty, + component, + size, + .. + } = ty.clone(); let decl = match category { Category::SCALAR => type_scalar(&name, ty), Category::VECTOR => type_vector(&name, ty, component, size), diff --git a/rasen-dsl/src/context/execute.rs b/rasen-dsl/src/context/execute.rs index ac91de9..de06ee1 100644 --- a/rasen-dsl/src/context/execute.rs +++ b/rasen-dsl/src/context/execute.rs @@ -1,6 +1,10 @@ -use std::ops::{Add, Sub, Mul, Div, Rem, Index}; +use std::ops::{Add, Div, Index, Mul, Rem, Sub}; -use crate::{context::{Container, Context}, value::Value, types::*}; +use crate::{ + context::{Container, Context}, + types::*, + value::Value, +}; pub enum Execute {} diff --git a/rasen-dsl/src/context/mod.rs b/rasen-dsl/src/context/mod.rs index 7c88a6e..a0ce169 100644 --- a/rasen-dsl/src/context/mod.rs +++ b/rasen-dsl/src/context/mod.rs @@ -1,9 +1,9 @@ -use std::ops::{Add, Sub, Mul, Div, Rem, Index}; +use std::ops::{Add, Div, Index, Mul, Rem, Sub}; -use crate::{value::Value, types::*}; +use crate::{types::*, value::Value}; -pub mod parse; pub mod execute; +pub mod parse; include! { concat!(env!("OUT_DIR"), "/container.rs") diff --git a/rasen-dsl/src/context/parse.rs b/rasen-dsl/src/context/parse.rs index 91a32b0..1c8d16c 100644 --- a/rasen-dsl/src/context/parse.rs +++ b/rasen-dsl/src/context/parse.rs @@ -1,8 +1,13 @@ -use std::ops::{Add, Sub, Mul, Div, Rem, Index}; +use std::ops::{Add, Div, Index, Mul, Rem, Sub}; -use rasen::prelude::{NodeIndex, Node, TypeName, TypedValue}; +use rasen::prelude::{Node, NodeIndex, TypeName, TypedValue}; -use crate::{context::{Container, Context}, value::Value, types::*, module::with_graph}; +use crate::{ + context::{Container, Context}, + module::with_graph, + types::*, + value::Value, +}; pub(crate) type ParseNode = NodeIndex; diff --git a/rasen-dsl/src/lib.rs b/rasen-dsl/src/lib.rs index d3b4024..b68b437 100644 --- a/rasen-dsl/src/lib.rs +++ b/rasen-dsl/src/lib.rs @@ -13,7 +13,7 @@ //! let res = clamp(dot(normal, light), 0.1f32, 1.0f32) * color; //! module.output(0, "o_color", res); //! }); -//! +//! //! # #[allow(unused_variables)] //! let bytecode = build_program(&shader, ShaderType::Fragment).unwrap(); //! # } diff --git a/rasen-dsl/src/module.rs b/rasen-dsl/src/module.rs index 31e48a2..c40ba72 100644 --- a/rasen-dsl/src/module.rs +++ b/rasen-dsl/src/module.rs @@ -1,9 +1,9 @@ //! Module builder utility use std::{ - rc::Rc, cell::RefCell, ops::{Fn, FnMut, FnOnce}, + rc::Rc, }; use crate::{ @@ -16,7 +16,7 @@ use crate::{ }; use rasen::{ module::FunctionRef, - prelude::{Graph, Module as ModuleImpl, Node, VariableName, BuiltIn}, + prelude::{BuiltIn, Graph, Module as ModuleImpl, Node, VariableName}, }; type Shared = Rc>; @@ -42,7 +42,11 @@ pub(crate) fn with_graph(thunk: impl FnOnce(&mut Graph) -> T) -> T { }) } -fn using_module(push: impl FnOnce(&mut BuilderContext) -> (), code: impl FnOnce() -> (), pop: impl FnOnce(&mut BuilderContext) -> T) -> T { +fn using_module( + push: impl FnOnce(&mut BuilderContext) -> (), + code: impl FnOnce() -> (), + pop: impl FnOnce(&mut BuilderContext) -> T, +) -> T { CONTEXT.with(move |cell| { let mut ctx = cell.borrow_mut(); push(&mut ctx as &mut BuilderContext); @@ -92,9 +96,7 @@ pub struct Module; impl Module { pub fn build(thunk: impl FnOnce(&Self) -> ()) -> ModuleImpl { - let module = Rc::new(RefCell::new( - ModuleImpl::default() - )); + let module = Rc::new(RefCell::new(ModuleImpl::default())); using_module( |ctx| { @@ -108,8 +110,11 @@ impl Module { let value = ctx.take(); let (module, func) = value.expect("Builder is missing in thread local key"); - debug_assert!(func.is_none(), "Module builder unwrapped from function context"); - + debug_assert!( + func.is_none(), + "Module builder unwrapped from function context" + ); + let module = Rc::try_unwrap(module).expect("Module builder has live references"); module.into_inner() }, @@ -132,7 +137,11 @@ impl Module { Parse: Container, { with_graph(|graph| { - Value(graph.add_node(Node::Uniform(index, T::TYPE_NAME, name.into_variable_name()))) + Value(graph.add_node(Node::Uniform( + index, + T::TYPE_NAME, + name.into_variable_name(), + ))) }) } @@ -180,9 +189,7 @@ impl Module { }, ); - FnWrapper(move |args: A| -> Value { - Value(args.call(func)) - }) + FnWrapper(move |args: A| -> Value { Value(args.call(func)) }) } } diff --git a/rasen-dsl/src/prelude.rs b/rasen-dsl/src/prelude.rs index c4de313..03db590 100644 --- a/rasen-dsl/src/prelude.rs +++ b/rasen-dsl/src/prelude.rs @@ -2,8 +2,10 @@ pub use rasen::prelude::*; -pub use crate::types::*; -pub use crate::context::Context; -pub use crate::value::{Value, IntoValue}; -pub use crate::module::Module; -pub use crate::operations::*; +pub use crate::{ + context::Context, + module::Module, + operations::*, + types::*, + value::{IntoValue, Value}, +}; diff --git a/rasen-dsl/src/value.rs b/rasen-dsl/src/value.rs index 8b3c2b9..1ea0b8a 100644 --- a/rasen-dsl/src/value.rs +++ b/rasen-dsl/src/value.rs @@ -1,10 +1,8 @@ //! Definitions for the Value type -use std::{ - ops::{Add, Sub, Mul, Div, Rem}, -}; +use std::ops::{Add, Div, Mul, Rem, Sub}; -use crate::context::{Container, execute::Execute}; +use crate::context::{execute::Execute, Container}; pub struct Value + ?Sized, T>(pub(crate) C::Value); diff --git a/rasen-dsl/tests/exec.rs b/rasen-dsl/tests/exec.rs index 85432b2..57640ff 100644 --- a/rasen-dsl/tests/exec.rs +++ b/rasen-dsl/tests/exec.rs @@ -51,10 +51,7 @@ fn test_run_basic_vert() { assert_eq!(v_pos, [1.0, 2.0, 3.0, 1.0]); let Vec4(v_norm) = v_norm.read(); - assert_eq!( - v_norm, - [0.0, 1.0, 0.0, 1.0] - ); + assert_eq!(v_norm, [0.0, 1.0, 0.0, 1.0]); let Vec2(v_uv) = v_uv.read(); assert_eq!(v_uv, [0.5, 0.5]); @@ -69,10 +66,7 @@ fn test_run_basic_frag() { ); let Vec4(color) = color.read(); - assert_eq!( - color, - [0.025, 0.0625, 0.1, 0.1] - ); + assert_eq!(color, [0.025, 0.0625, 0.1, 0.1]); } #[test] diff --git a/rasen-plugin/src/lib.rs b/rasen-plugin/src/lib.rs index 6c7e151..ae5a2fc 100644 --- a/rasen-plugin/src/lib.rs +++ b/rasen-plugin/src/lib.rs @@ -3,7 +3,7 @@ //! # Module wrapper //! The `rasen(module)` attribute on a function will generate a wrapper function with the `_module` suffix, //! returning the corresponding Module object. -//! +//! //! The `rasen(function)` attribute flags a function to be exported when called from a module builder function. //! Otherwise, due to the way the compiler works on data-flow graph, any function called in Rust will be inlined //! in the resulting code. @@ -20,7 +20,7 @@ //! fn clamp_light(value: Value) -> Value { //! clamp(value, 0.1f32, 1.0f32) //! } -//! +//! //! #[rasen(module)] // This will create the function basic_frag_module() -> Module //! fn basic_frag(a_normal: Value) -> Value { //! let normal = normalize(a_normal); @@ -69,57 +69,70 @@ //! # constructors_module() //! ``` -#![recursion_limit="256"] +#![recursion_limit = "256"] #![feature(plugin_registrar, rustc_private, custom_attribute, box_syntax)] #![warn(clippy::all, clippy::pedantic)] extern crate rustc_plugin; extern crate syntax; -#[macro_use] extern crate quote; +#[macro_use] +extern crate quote; extern crate proc_macro2; -use syntax::source_map::{Span, FileName}; -use syntax::symbol::Symbol; -use syntax::ext::build::AstBuilder; use rustc_plugin::registry::Registry; -use syntax::parse::{self, token::{Token, Lit}}; -use syntax::tokenstream::{TokenStream, TokenTree}; -use syntax::ast::{ - self, Item, ItemKind, - MetaItem, MetaItemKind, NestedMetaItemKind, - FnDecl, FunctionRetTy, TyKind, PatKind, ExprKind, +use syntax::{ + ast::{ + self, ExprKind, FnDecl, FunctionRetTy, Item, ItemKind, MetaItem, MetaItemKind, + NestedMetaItemKind, PatKind, TyKind, + }, + ext::{ + base::{Annotatable, ExtCtxt, MacEager, MacResult, SyntaxExtension, TTMacroExpander}, + build::AstBuilder, + }, + parse::{ + self, + token::{Lit, Token}, + }, + source_map::{edition::Edition, FileName, Span}, + symbol::Symbol, + tokenstream::{TokenStream, TokenTree}, }; -use syntax::ext::base::{Annotatable, ExtCtxt, SyntaxExtension, MacResult, MacEager, TTMacroExpander}; -use syntax::source_map::edition::Edition; use proc_macro2::{Ident, Span as MacroSpan}; #[allow(clippy::cast_possible_truncation)] fn insert_module_wrapper(ecx: &mut ExtCtxt, span: Span, item: Annotatable) -> Vec { let tokens = if let Annotatable::Item(ref item) = item { - let Item { ident, ref node, .. } = **item; + let Item { + ident, ref node, .. + } = **item; let fn_name = Ident::new(&format!("{}", ident), MacroSpan::call_site()); let aux_name = Ident::new(&format!("{}_module", ident), MacroSpan::call_site()); if let ItemKind::Fn(ref decl, ..) = *node { - let FnDecl { ref inputs, ref output, .. } = **decl; + let FnDecl { + ref inputs, + ref output, + .. + } = **decl; let args: Vec<_> = { - inputs.iter() + inputs + .iter() .map(|arg| match arg.pat.node { - PatKind::Ident(_, ident, _) => Ident::new(&format!("{}", ident.name), MacroSpan::call_site()), + PatKind::Ident(_, ident, _) => { + Ident::new(&format!("{}", ident.name), MacroSpan::call_site()) + } _ => panic!("unimplemented {:?}", arg.pat.node), }) .collect() }; let (attributes, uniforms): (Vec<_>, Vec<_>) = { - args.clone() - .into_iter() - .partition(|ident| { - let name = format!("{}", ident); - name.starts_with("a_") - }) + args.clone().into_iter().partition(|ident| { + let name = format!("{}", ident); + name.starts_with("a_") + }) }; let attr_names: Vec<_> = attributes.iter().map(|id| id.to_string()).collect(); @@ -138,11 +151,11 @@ fn insert_module_wrapper(ecx: &mut ExtCtxt, span: Span, item: Annotatable) -> Ve let outputs = list.clone(); (quote! { ( #( #list ),* ) }, outputs) - }, + } TyKind::Path(_, _) => { let output = Ident::new("output", MacroSpan::call_site()); - (quote!{ #output }, vec![ output ]) - }, + (quote! { #output }, vec![output]) + } _ => panic!("unimplemented {:?}", ty.node), }, _ => panic!("unimplemented {:?}", output), @@ -152,17 +165,20 @@ fn insert_module_wrapper(ecx: &mut ExtCtxt, span: Span, item: Annotatable) -> Ve let uni_id: Vec<_> = (0..uniforms.len()).map(|i| i as u32).collect(); let out_id: Vec<_> = (0..outputs.len()).map(|i| i as u32).collect(); - Some((format!("{}_module", ident), quote! { - #[allow(dead_code)] - pub fn #aux_name() -> Module { - let module = Module::new(); - #( let #attributes = module.input(#attr_id, #attr_names); )* - #( let #uniforms = module.uniform(#uni_id, #uni_names); )* - let #output = #fn_name( #( #args ),* ); - #( module.output(#out_id, None, #outputs); )* - module - } - })) + Some(( + format!("{}_module", ident), + quote! { + #[allow(dead_code)] + pub fn #aux_name() -> Module { + let module = Module::new(); + #( let #attributes = module.input(#attr_id, #attr_names); )* + #( let #uniforms = module.uniform(#uni_id, #uni_names); )* + let #output = #fn_name( #( #args ),* ); + #( module.output(#out_id, None, #outputs); )* + module + } + }, + )) } else { None } @@ -190,7 +206,7 @@ fn insert_module_wrapper(ecx: &mut ExtCtxt, span: Span, item: Annotatable) -> Ve * let func = |args: T, ...| -> R { * // Code * }; - * + * * if let Some(module) = args.get_module().or_else(...) { * let func = module.function(func); * func(args, ...) @@ -201,119 +217,170 @@ fn insert_module_wrapper(ecx: &mut ExtCtxt, span: Span, item: Annotatable) -> Ve */ fn insert_function_wrapper(ecx: &mut ExtCtxt, span: Span, item: Annotatable) -> Vec { if let Annotatable::Item(item) = item { - let Item { ident, ref attrs, ref node, span, .. } = *item; + let Item { + ident, + ref attrs, + ref node, + span, + .. + } = *item; if let ItemKind::Fn(ref decl, header, ref generics, ref block) = *node { - let FnDecl { ref inputs, ref output, .. } = **decl; - return vec![ - Annotatable::Item(ecx.item( - span, ident, + let FnDecl { + ref inputs, + ref output, + .. + } = **decl; + return vec![Annotatable::Item( + ecx.item( + span, + ident, attrs.clone(), ItemKind::Fn( - ecx.fn_decl( - inputs.clone(), - output.clone(), - ), + ecx.fn_decl(inputs.clone(), output.clone()), header, generics.clone(), - ecx.block(block.span, vec![ - ecx.stmt_let( - block.span, false, - ecx.ident_of("func"), - ecx.lambda_fn_decl( + ecx.block( + block.span, + vec![ + ecx.stmt_let( block.span, - ecx.fn_decl( - inputs.clone(), - output.clone(), + false, + ecx.ident_of("func"), + ecx.lambda_fn_decl( + block.span, + ecx.fn_decl(inputs.clone(), output.clone()), + ecx.expr_block(block.clone()), + block.span, ), - ecx.expr_block(block.clone()), - block.span, ), - ), - ecx.stmt_expr(ecx.expr(block.span, ExprKind::IfLet( - vec![ - ecx.pat_some( + ecx.stmt_expr( + ecx.expr( block.span, - ecx.pat_ident(block.span, ecx.ident_of("module")), - ) - ], - inputs.iter() - .fold(None, |current, arg| match arg.pat.node { - PatKind::Ident(_, ident, _) => Some({ - let id = ecx.expr_ident(ident.span, ident); - let module = ecx.expr_method_call( - ident.span, id, - ecx.ident_of("get_module"), - Vec::new(), - ); - - if let Some(chain) = current { - ecx.expr_method_call( - ident.span, chain, - ecx.ident_of("or_else"), - vec![ - ecx.lambda0(ident.span, module), - ], - ) - } else { - module - } - }), - _ => ecx.span_fatal(arg.pat.span, "Unsupported destructuring"), - }) - .unwrap(), - ecx.block(block.span, vec![ - ecx.stmt_let( - block.span, false, - ecx.ident_of("func"), - ecx.expr_method_call( - block.span, - ecx.expr_ident(block.span, ecx.ident_of("module")), - ecx.ident_of("function"), - vec![ - ecx.expr_ident(block.span, ecx.ident_of("func")), - ], + ExprKind::IfLet( + vec![ecx.pat_some( + block.span, + ecx.pat_ident(block.span, ecx.ident_of("module")), + )], + inputs + .iter() + .fold(None, |current, arg| match arg.pat.node { + PatKind::Ident(_, ident, _) => Some({ + let id = ecx.expr_ident(ident.span, ident); + let module = ecx.expr_method_call( + ident.span, + id, + ecx.ident_of("get_module"), + Vec::new(), + ); + + if let Some(chain) = current { + ecx.expr_method_call( + ident.span, + chain, + ecx.ident_of("or_else"), + vec![ + ecx.lambda0(ident.span, module) + ], + ) + } else { + module + } + }), + _ => ecx.span_fatal( + arg.pat.span, + "Unsupported destructuring", + ), + }) + .unwrap(), + ecx.block( + block.span, + vec![ + ecx.stmt_let( + block.span, + false, + ecx.ident_of("func"), + ecx.expr_method_call( + block.span, + ecx.expr_ident( + block.span, + ecx.ident_of("module"), + ), + ecx.ident_of("function"), + vec![ecx.expr_ident( + block.span, + ecx.ident_of("func"), + )], + ), + ), + ecx.stmt_expr( + ecx.expr_call_ident( + block.span, + ecx.ident_of("func"), + inputs + .iter() + .map(|arg| match arg.pat.node { + PatKind::Ident(_, ident, _) => { + ecx.expr_ident( + ident.span, ident, + ) + } + _ => ecx.span_fatal( + arg.pat.span, + "Unsupported destructuring", + ), + }) + .collect(), + ), + ), + ], + ), + Some( + ecx.expr_call_ident( + block.span, + ecx.ident_of("func"), + inputs + .iter() + .map(|arg| match arg.pat.node { + PatKind::Ident(_, ident, _) => { + ecx.expr_ident(ident.span, ident) + } + _ => ecx.span_fatal( + arg.pat.span, + "Unsupported destructuring", + ), + }) + .collect(), + ), + ), ), ), - ecx.stmt_expr(ecx.expr_call_ident( - block.span, - ecx.ident_of("func"), - inputs.iter() - .map(|arg| match arg.pat.node { - PatKind::Ident(_, ident, _) => ecx.expr_ident(ident.span, ident), - _ => ecx.span_fatal(arg.pat.span, "Unsupported destructuring"), - }) - .collect(), - )), - ]), - Some( - ecx.expr_call_ident( - block.span, - ecx.ident_of("func"), - inputs.iter() - .map(|arg| match arg.pat.node { - PatKind::Ident(_, ident, _) => ecx.expr_ident(ident.span, ident), - _ => ecx.span_fatal(arg.pat.span, "Unsupported destructuring"), - }) - .collect(), - ), ), - ))), - ]), + ], + ), ), - )), - ]; + ), + )]; } } ecx.span_fatal(span, "Unsupported item for Rasen function attribute") } -fn rasen_attribute(ecx: &mut ExtCtxt, _: Span, meta_item: &MetaItem, item: Annotatable) -> Vec { +fn rasen_attribute( + ecx: &mut ExtCtxt, + _: Span, + meta_item: &MetaItem, + item: Annotatable, +) -> Vec { let res = match meta_item.node { MetaItemKind::List(ref list) if list.len() == 1 => { let first = &list[0]; match first.node { - NestedMetaItemKind::MetaItem(MetaItem { ref ident, node: MetaItemKind::Word, span }) => { + NestedMetaItemKind::MetaItem(MetaItem { + ref ident, + node: MetaItemKind::Word, + span, + }) => { if ident.segments.len() == 1 { let segment = &ident.segments[0]; if segment.ident.name == Symbol::intern("module") { @@ -326,10 +393,10 @@ fn rasen_attribute(ecx: &mut ExtCtxt, _: Span, meta_item: &MetaItem, item: Annot } else { Err(span) } - }, - _ => Err(first.span) + } + _ => Err(first.span), } - }, + } _ => Err(meta_item.span), }; @@ -341,31 +408,34 @@ fn rasen_attribute(ecx: &mut ExtCtxt, _: Span, meta_item: &MetaItem, item: Annot fn idx_macro<'cx>(ecx: &'cx mut ExtCtxt, span: Span, tt: &[TokenTree]) -> Box { match (&tt[0], &tt[2]) { - (&TokenTree::Token(_, Token::Ident(obj, _)), &TokenTree::Token(_, Token::Ident(index, _))) => { + ( + &TokenTree::Token(_, Token::Ident(obj, _)), + &TokenTree::Token(_, Token::Ident(index, _)), + ) => { let index = index.to_string(); if index.is_empty() { ecx.span_fatal(span, "Empty composite field"); } let mut fields: Vec<_> = { - index.chars() + index + .chars() .map(|field| { let index = match field { 'x' | 'r' | 's' => 0, 'y' | 'g' | 't' => 1, 'z' | 'b' | 'p' => 2, 'w' | 'a' | 'q' => 3, - _ => ecx.span_fatal(span, &format!("invalid composite field {}", field)), + _ => { + ecx.span_fatal(span, &format!("invalid composite field {}", field)) + } }; ecx.expr_call_ident( span, ast::Ident::from_str("index"), vec![ - ecx.expr_addr_of( - span, - ecx.expr_ident(span, obj), - ), + ecx.expr_addr_of(span, ecx.expr_ident(span, obj)), ecx.expr_u32(span, index), ], ) @@ -374,33 +444,31 @@ fn idx_macro<'cx>(ecx: &'cx mut ExtCtxt, span: Span, tt: &[TokenTree]) -> Box 1 { - ecx.expr_call_ident( - span, - ast::Ident::from_str(&format!("vec{}", count)), - fields, - ) - } else { - fields.remove(0) - } - ) - }, - _ => { - box MacEager::default() - }, + MacEager::expr(if count > 1 { + ecx.expr_call_ident(span, ast::Ident::from_str(&format!("vec{}", count)), fields) + } else { + fields.remove(0) + }) + } + _ => box MacEager::default(), } } #[derive(Clone)] -struct CompositeMacro<'a>{ +struct CompositeMacro<'a> { pub func: &'a str, pub float_ty: Option, pub int_ty: Option, } impl<'a> TTMacroExpander for CompositeMacro<'a> { - fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, ts: TokenStream, _: Option) -> Box { + fn expand<'cx>( + &self, + ecx: &'cx mut ExtCtxt, + span: Span, + ts: TokenStream, + _: Option, + ) -> Box { let func = ast::Ident::from_str(self.func); let vec = ast::Ident::from_str("vec"); @@ -410,10 +478,10 @@ impl<'a> TTMacroExpander for CompositeMacro<'a> { .map(|i| { ecx.expr_method_call( span, - ecx.expr(span, ExprKind::Index( - ecx.expr_ident(span, vec), - ecx.expr_usize(span, i), - )), + ecx.expr( + span, + ExprKind::Index(ecx.expr_ident(span, vec), ecx.expr_usize(span, i)), + ), ast::Ident::from_str("clone"), vec![], ) @@ -421,69 +489,48 @@ impl<'a> TTMacroExpander for CompositeMacro<'a> { .collect() }; - let mut block = vec![ - ecx.stmt_let( - span, true, vec, - ecx.expr_vec_ng(span), - ), - ]; - - block.extend( - ts.trees() - .filter_map(|tt| { - let expr = match tt { - TokenTree::Token(_, token) => match token { - Token::Ident(id, _) => ecx.expr_ident(span, id), - Token::Literal(lit, _) => match lit { - Lit::Integer(name) => { - let val: u128 = format!("{}", name).parse().unwrap(); - ecx.expr_lit(span, ast::LitKind::Int( - val, self.int_ty.unwrap(), - )) - }, - Lit::Float(name) => ecx.expr_lit(span, ast::LitKind::Float( - name, self.float_ty.unwrap(), - )), - _ => return None, - }, - _ => return None, - }, - _ => return None, - }; - - Some(ecx.stmt_expr( - ecx.expr_method_call( - span, - ecx.expr_ident(span, vec), - ast::Ident::from_str("extend"), - vec![ - ecx.expr_call( - span, - ecx.expr_path(ecx.path(span, vec![ - ast::Ident::from_str("ValueIter"), - ast::Ident::from_str("iter"), - ])), - vec![ - ecx.expr_addr_of(span, expr), - ], - ), - ], - ), - )) - }) - ); + let mut block = vec![ecx.stmt_let(span, true, vec, ecx.expr_vec_ng(span))]; - block.push( - ecx.stmt_expr( - ecx.expr_call_ident(span, func, indices), - ), - ); + block.extend(ts.trees().filter_map(|tt| { + let expr = match tt { + TokenTree::Token(_, token) => match token { + Token::Ident(id, _) => ecx.expr_ident(span, id), + Token::Literal(lit, _) => match lit { + Lit::Integer(name) => { + let val: u128 = format!("{}", name).parse().unwrap(); + ecx.expr_lit(span, ast::LitKind::Int(val, self.int_ty.unwrap())) + } + Lit::Float(name) => { + ecx.expr_lit(span, ast::LitKind::Float(name, self.float_ty.unwrap())) + } + _ => return None, + }, + _ => return None, + }, + _ => return None, + }; - MacEager::expr( - ecx.expr_block( - ecx.block(span, block), - ), - ) + Some(ecx.stmt_expr(ecx.expr_method_call( + span, + ecx.expr_ident(span, vec), + ast::Ident::from_str("extend"), + vec![ecx.expr_call( + span, + ecx.expr_path(ecx.path( + span, + vec![ + ast::Ident::from_str("ValueIter"), + ast::Ident::from_str("iter"), + ], + )), + vec![ecx.expr_addr_of(span, expr)], + )], + ))) + })); + + block.push(ecx.stmt_expr(ecx.expr_call_ident(span, func, indices))); + + MacEager::expr(ecx.expr_block(ecx.block(span, block))) } } @@ -586,6 +633,6 @@ pub fn plugin_registrar(reg: &mut Registry) { reg.register_syntax_extension( Symbol::intern("rasen"), - SyntaxExtension::MultiModifier(box rasen_attribute) + SyntaxExtension::MultiModifier(box rasen_attribute), ); } diff --git a/rasen-plugin/tests/graph.rs b/rasen-plugin/tests/graph.rs index 23767e1..06ffd53 100644 --- a/rasen-plugin/tests/graph.rs +++ b/rasen-plugin/tests/graph.rs @@ -1,10 +1,10 @@ #![feature(plugin, custom_attribute, try_from)] #![plugin(rasen_plugin)] +extern crate insta; extern crate rasen; extern crate rasen_dsl; extern crate rspirv; -extern crate insta; use rasen_dsl::prelude::*; use std::f32::consts::PI; diff --git a/rasen/src/errors.rs b/rasen/src/errors.rs index a1df2be..199894f 100644 --- a/rasen/src/errors.rs +++ b/rasen/src/errors.rs @@ -1,7 +1,7 @@ //! Error-related definitions generated by `error_chain` -use types::TypeName; use module::FunctionRef; +use types::TypeName; error_chain! { errors { diff --git a/rasen/src/operations/glsl.rs b/rasen/src/operations/glsl.rs index fbe1e26..04a3c00 100644 --- a/rasen/src/operations/glsl.rs +++ b/rasen/src/operations/glsl.rs @@ -1,19 +1,19 @@ #![allow(clippy::enum_glob_use)] -use spirv_headers::*; -use spirv_headers::GLOp::*; -use rspirv::mr::{ - Instruction, Operand -}; +use rspirv::mr::{Instruction, Operand}; +use spirv_headers::{GLOp::*, *}; use builder::Builder; -use types::*; use errors::*; +use types::*; macro_rules! unary_vec { ( $name:ident, $op:ident ) => { #[inline] - pub(crate) fn $name(builder: &mut B, args: Vec<(&'static TypeName, u32)>) -> Result<(&'static TypeName, u32)> { + pub(crate) fn $name( + builder: &mut B, + args: Vec<(&'static TypeName, u32)>, + ) -> Result<(&'static TypeName, u32)> { use types::TypeName::*; if args.len() != 1 { @@ -24,24 +24,22 @@ macro_rules! unary_vec { let (res_type, scalar) = if let Vec(_, scalar) = *arg_ty { (builder.register_type(scalar), scalar) } else { - bail!(ErrorKind::BadArguments(Box::new([ arg_ty ]))); + bail!(ErrorKind::BadArguments(Box::new([arg_ty]))); }; let res_id = builder.get_id(); let ext_id = builder.import_set("GLSL.std.450"); - builder.push_instruction( - Instruction::new( - Op::ExtInst, - Some(res_type), - Some(res_id), - vec![ - Operand::IdRef(ext_id), - Operand::LiteralExtInstInteger($op as Word), - Operand::IdRef(arg_val) - ] - ) - ); + builder.push_instruction(Instruction::new( + Op::ExtInst, + Some(res_type), + Some(res_id), + vec![ + Operand::IdRef(ext_id), + Operand::LiteralExtInstInteger($op as Word), + Operand::IdRef(arg_val), + ], + )); Ok((scalar, res_id)) } @@ -56,18 +54,15 @@ unary_vec!(length, Length); macro_rules! variadic_any { ( $name:ident, $op:ident, $scode:ident, $ucode:ident, $fcode:ident ) => { #[inline] - pub(crate) fn $name(builder: &mut B, args: Vec<(&'static TypeName, u32)>) -> Result<(&'static TypeName, u32)> { + pub(crate) fn $name( + builder: &mut B, + args: Vec<(&'static TypeName, u32)>, + ) -> Result<(&'static TypeName, u32)> { use types::TypeName::*; let (l_arg, r_arg) = match args.len() { - 2 => ( - args[0], - args[1], - ), - n if n > 2 => ( - $name(builder, args[0..n - 1].to_vec())?, - args[n - 1], - ), + 2 => (args[0], args[1]), + n if n > 2 => ($name(builder, args[0..n - 1].to_vec())?, args[n - 1]), n => bail!(ErrorKind::WrongArgumentsCount(n, 2)), }; @@ -76,17 +71,27 @@ macro_rules! variadic_any { let inst_id = match (l_type, r_type) { _ if l_type == r_type && r_type.is_signed() => $scode, - (&Vec(l_len, l_scalar), &Vec(r_len, r_scalar)) if l_len == r_len && l_scalar == r_scalar && r_scalar.is_signed() => $scode, + (&Vec(l_len, l_scalar), &Vec(r_len, r_scalar)) + if l_len == r_len && l_scalar == r_scalar && r_scalar.is_signed() => + { + $scode + } _ if l_type == r_type && r_type.is_integer() && !r_type.is_signed() => $ucode, - (&Vec(l_len, l_scalar), &Vec(r_len, r_scalar)) if l_len == r_len && l_scalar == r_scalar && r_scalar.is_integer() => $ucode, + (&Vec(l_len, l_scalar), &Vec(r_len, r_scalar)) + if l_len == r_len && l_scalar == r_scalar && r_scalar.is_integer() => + { + $ucode + } _ if l_type == r_type && r_type.is_float() => $fcode, - (&Vec(l_len, l_scalar), &Vec(r_len, r_scalar)) if l_len == r_len && l_scalar == r_scalar && r_scalar.is_float() => $fcode, + (&Vec(l_len, l_scalar), &Vec(r_len, r_scalar)) + if l_len == r_len && l_scalar == r_scalar && r_scalar.is_float() => + { + $fcode + } - _ => bail!(ErrorKind::BadArguments(Box::new([ - l_type, r_type - ]))), + _ => bail!(ErrorKind::BadArguments(Box::new([l_type, r_type]))), }; let res_type = builder.register_type(l_type); @@ -94,19 +99,17 @@ macro_rules! variadic_any { let ext_id = builder.import_set("GLSL.std.450"); - builder.push_instruction( - Instruction::new( - Op::ExtInst, - Some(res_type), - Some(res_id), - vec![ - Operand::IdRef(ext_id), - Operand::LiteralExtInstInteger(inst_id as Word), - Operand::IdRef(l_value), - Operand::IdRef(r_value) - ] - ) - ); + builder.push_instruction(Instruction::new( + Op::ExtInst, + Some(res_type), + Some(res_id), + vec![ + Operand::IdRef(ext_id), + Operand::LiteralExtInstInteger(inst_id as Word), + Operand::IdRef(l_value), + Operand::IdRef(r_value), + ], + )); Ok((l_type, res_id)) } @@ -176,7 +179,10 @@ trinary_any!(clamp, Clamp, FClamp, SClamp, UClamp); trinary_any!(mix, Mix, FMix); #[inline] -pub(crate) fn distance(builder: &mut B, args: &[(&'static TypeName, u32)]) -> Result<(&'static TypeName, u32)> { +pub(crate) fn distance( + builder: &mut B, + args: &[(&'static TypeName, u32)], +) -> Result<(&'static TypeName, u32)> { use types::TypeName::*; if args.len() != 2 { @@ -187,36 +193,37 @@ pub(crate) fn distance(builder: &mut B, args: &[(&'static TypeName, let (r_type, r_value) = args[1]; match (l_type, r_type) { - (&Vec(l_size, l_scalar), &Vec(r_size, r_scalar)) if l_size == r_size && l_scalar == r_scalar => { + (&Vec(l_size, l_scalar), &Vec(r_size, r_scalar)) + if l_size == r_size && l_scalar == r_scalar => + { let res_type = builder.register_type(l_scalar); let res_id = builder.get_id(); let ext_id = builder.import_set("GLSL.std.450"); - builder.push_instruction( - Instruction::new( - Op::ExtInst, - Some(res_type), - Some(res_id), - vec![ - Operand::IdRef(ext_id), - Operand::LiteralExtInstInteger(Distance as u32), - Operand::IdRef(l_value), - Operand::IdRef(r_value) - ] - ) - ); + builder.push_instruction(Instruction::new( + Op::ExtInst, + Some(res_type), + Some(res_id), + vec![ + Operand::IdRef(ext_id), + Operand::LiteralExtInstInteger(Distance as u32), + Operand::IdRef(l_value), + Operand::IdRef(r_value), + ], + )); Ok((l_scalar, res_id)) - }, - _ => bail!(ErrorKind::BadArguments(Box::new([ - l_type, r_type - ]))), + } + _ => bail!(ErrorKind::BadArguments(Box::new([l_type, r_type]))), } } #[inline] -pub(crate) fn reflect(builder: &mut B, args: &[(&'static TypeName, u32)]) -> Result<(&'static TypeName, u32)> { +pub(crate) fn reflect( + builder: &mut B, + args: &[(&'static TypeName, u32)], +) -> Result<(&'static TypeName, u32)> { use types::TypeName::*; if args.len() != 2 { @@ -227,34 +234,37 @@ pub(crate) fn reflect(builder: &mut B, args: &[(&'static TypeName, u let (r_type, r_value) = args[1]; match (l_type, r_type) { - (&Vec(l_size, l_scalar), &Vec(r_size, r_scalar)) if l_size == r_size && l_scalar == r_scalar => { + (&Vec(l_size, l_scalar), &Vec(r_size, r_scalar)) + if l_size == r_size && l_scalar == r_scalar => + { let vec_type = builder.register_type(l_type); let result_id = builder.get_id(); let ext_id = builder.import_set("GLSL.std.450"); - builder.push_instruction( - Instruction::new( - Op::ExtInst, - Some(vec_type), - Some(result_id), - vec![ - Operand::IdRef(ext_id), - Operand::LiteralExtInstInteger(Reflect as u32), - Operand::IdRef(l_value), - Operand::IdRef(r_value) - ] - ) - ); + builder.push_instruction(Instruction::new( + Op::ExtInst, + Some(vec_type), + Some(result_id), + vec![ + Operand::IdRef(ext_id), + Operand::LiteralExtInstInteger(Reflect as u32), + Operand::IdRef(l_value), + Operand::IdRef(r_value), + ], + )); Ok((l_type, result_id)) - }, - _ => bail!(ErrorKind::BadArguments(Box::new([ l_type, r_type ]))), + } + _ => bail!(ErrorKind::BadArguments(Box::new([l_type, r_type]))), } } #[inline] -pub(crate) fn refract(builder: &mut B, args: &[(&'static TypeName, u32)]) -> Result<(&'static TypeName, u32)> { +pub(crate) fn refract( + builder: &mut B, + args: &[(&'static TypeName, u32)], +) -> Result<(&'static TypeName, u32)> { use types::TypeName::*; if args.len() != 3 { @@ -266,35 +276,41 @@ pub(crate) fn refract(builder: &mut B, args: &[(&'static TypeName, u let (i_type, i_value) = args[2]; match (l_type, r_type) { - (&Vec(l_size, l_scalar), &Vec(r_size, r_scalar)) if l_size == r_size && l_scalar == r_scalar && l_scalar == i_type && i_type.is_float() => { + (&Vec(l_size, l_scalar), &Vec(r_size, r_scalar)) + if l_size == r_size + && l_scalar == r_scalar + && l_scalar == i_type + && i_type.is_float() => + { let vec_type = builder.register_type(l_type); let res_id = builder.get_id(); let ext_id = builder.import_set("GLSL.std.450"); - builder.push_instruction( - Instruction::new( - Op::ExtInst, - Some(vec_type), - Some(res_id), - vec![ - Operand::IdRef(ext_id), - Operand::LiteralExtInstInteger(Refract as u32), - Operand::IdRef(l_value), - Operand::IdRef(r_value), - Operand::IdRef(i_value) - ] - ) - ); + builder.push_instruction(Instruction::new( + Op::ExtInst, + Some(vec_type), + Some(res_id), + vec![ + Operand::IdRef(ext_id), + Operand::LiteralExtInstInteger(Refract as u32), + Operand::IdRef(l_value), + Operand::IdRef(r_value), + Operand::IdRef(i_value), + ], + )); Ok((l_type, res_id)) - }, - _ => bail!(ErrorKind::BadArguments(Box::new([ l_type, r_type, i_type ]))), + } + _ => bail!(ErrorKind::BadArguments(Box::new([l_type, r_type, i_type]))), } } #[inline] -pub(crate) fn sample(builder: &mut B, args: &[(&'static TypeName, u32)]) -> Result<(&'static TypeName, u32)> { +pub(crate) fn sample( + builder: &mut B, + args: &[(&'static TypeName, u32)], +) -> Result<(&'static TypeName, u32)> { use types::TypeName::*; if args.len() < 2 || args.len() > 3 { @@ -305,15 +321,16 @@ pub(crate) fn sample(builder: &mut B, args: &[(&'static TypeName, u3 let (coords_type, coords_value) = args[1]; match (image_type, coords_type) { - (&Sampler(sampled_type, Dim::Dim1D), &Vec(1, coords_scalar)) | - (&Sampler(sampled_type, Dim::Dim2D), &Vec(2, coords_scalar)) | - (&Sampler(sampled_type, Dim::Dim3D), &Vec(3, coords_scalar)) | - (&Sampler(sampled_type, Dim::DimCube), &Vec(3, coords_scalar)) | - (&Sampler(sampled_type, Dim::DimRect), &Vec(2, coords_scalar)) | - (&Sampler(sampled_type, Dim::DimBuffer), &Vec(1, coords_scalar)) | - - (&Sampler(sampled_type, Dim::DimBuffer), coords_scalar) | - (&Sampler(sampled_type, Dim::Dim1D), coords_scalar) if sampled_type.is_num() && coords_scalar.is_float() => { + (&Sampler(sampled_type, Dim::Dim1D), &Vec(1, coords_scalar)) + | (&Sampler(sampled_type, Dim::Dim2D), &Vec(2, coords_scalar)) + | (&Sampler(sampled_type, Dim::Dim3D), &Vec(3, coords_scalar)) + | (&Sampler(sampled_type, Dim::DimCube), &Vec(3, coords_scalar)) + | (&Sampler(sampled_type, Dim::DimRect), &Vec(2, coords_scalar)) + | (&Sampler(sampled_type, Dim::DimBuffer), &Vec(1, coords_scalar)) + | (&Sampler(sampled_type, Dim::DimBuffer), coords_scalar) + | (&Sampler(sampled_type, Dim::Dim1D), coords_scalar) + if sampled_type.is_num() && coords_scalar.is_float() => + { let res_type = match *sampled_type { Int(true) => TypeName::IVEC4, Int(false) => TypeName::UVEC4, @@ -324,36 +341,41 @@ pub(crate) fn sample(builder: &mut B, args: &[(&'static TypeName, u3 let vec_type = builder.register_type(res_type); let res_id = builder.get_id(); - let mut operands = vec![ - Operand::IdRef(image_value), - Operand::IdRef(coords_value), - ]; + let mut operands = vec![Operand::IdRef(image_value), Operand::IdRef(coords_value)]; if let Some(&(bias_type, bias_value)) = args.get(2) { if bias_type != TypeName::FLOAT { - bail!(ErrorKind::BadArguments(Box::new([ image_type, coords_type, bias_type ]))); + bail!(ErrorKind::BadArguments(Box::new([ + image_type, + coords_type, + bias_type + ]))); } operands.push(Operand::ImageOperands(ImageOperands::BIAS)); operands.push(Operand::IdRef(bias_value)); } - builder.push_instruction( - Instruction::new( - Op::ImageSampleImplicitLod, - Some(vec_type), - Some(res_id), - operands, - ) - ); + builder.push_instruction(Instruction::new( + Op::ImageSampleImplicitLod, + Some(vec_type), + Some(res_id), + operands, + )); Ok((res_type, res_id)) - }, - - _ => if let Some(&(bias_type, _)) = args.get(2) { - bail!(ErrorKind::BadArguments(Box::new([ image_type, coords_type, bias_type ]))) - } else { - bail!(ErrorKind::BadArguments(Box::new([ image_type, coords_type ]))) - }, + } + + _ => { + if let Some(&(bias_type, _)) = args.get(2) { + bail!(ErrorKind::BadArguments(Box::new([ + image_type, + coords_type, + bias_type + ]))) + } else { + bail!(ErrorKind::BadArguments(Box::new([image_type, coords_type]))) + } + } } }