1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt;
use std::str::FromStr;
use syntax::{ast, ext};
use syntax::ext::build::AstBuilder;
use syntax::ext::deriving::generic;
use syntax::{attr, codemap};
use syntax::parse::token;
use syntax::ptr::P;
use syntax::ext::base::ItemDecorator;

/// A component modifier.
#[derive(Copy, Clone, PartialEq)]
enum Modifier {
    /// Corresponds to the `#[normalized]` attribute.
    ///
    /// Normalizes the component at runtime. Unsigned integers are normalized to
    /// `[0, 1]`. Signed integers are normalized to `[-1, 1]`.
    Normalized,
    /// Corresponds to the `#[as_float]` attribute.
    ///
    /// Casts the component to a float precision floating-point number at runtime.
    AsFloat,
    /// Corresponds to the `#[as_double]` attribute.
    ///
    /// Specifies a high-precision float.
    AsDouble,
}

impl fmt::Debug for Modifier {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Modifier::Normalized => write!(f, "normalized"),
            Modifier::AsFloat => write!(f, "as_float"),
            Modifier::AsDouble => write!(f, "as_double"),
        }
    }
}

impl FromStr for Modifier {
    type Err = ();

    fn from_str(src: &str) -> Result<Modifier, ()> {
        match src {
            "normalized" => Ok(Modifier::Normalized),
            "as_float" => Ok(Modifier::AsFloat),
            "as_double" => Ok(Modifier::AsDouble),
            _ => Err(()),
        }
    }
}

/// Scan through the field's attributes and extract a relevant modifier. If
/// multiple modifier attributes are found, use the first modifier and emit a
/// warning.
fn find_modifier(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                 attributes: &[ast::Attribute]) -> Option<Modifier> {
    attributes.iter().fold(None, |modifier, attribute| {
        match attribute.node.value.node {
            ast::MetaWord(ref word) => {
                word.parse().ok().and_then(|new_modifier| {
                    attr::mark_used(attribute);
                    modifier.map_or(Some(new_modifier), |modifier| {
                        cx.span_warn(span, &format!(
                            "Extra attribute modifier detected: `#[{:?}]` - \
                            ignoring in favour of `#[{:?}]`.", new_modifier, modifier
                        ));
                        None
                    })
                }).or(modifier)
            },
            _ => modifier,
        }
    })
}

/// Find a `gfx::attrib::Type` that describes the given type identifier.
fn decode_type(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
               ty_ident: &ast::Ident, modifier: Option<Modifier>,
               path_root: ast::Ident) -> P<ast::Expr> {
    let ty_str = ty_ident.name.as_str();
    match ty_str {
        "f32" | "f64" => {
            let kind = cx.ident_of(match modifier {
                None | Some(Modifier::AsFloat) => "Default",
                Some(Modifier::AsDouble) => "Precision",
                Some(Modifier::Normalized) => {
                    cx.span_warn(span, &format!(
                        "Incompatible float modifier attribute: `#[{:?}]`", modifier
                    ));
                    ""
                }
            });
            let size = cx.ident_of(&format!("F{}", &ty_str[1..]));
            quote_expr!(cx, $path_root::gfx::attrib::Type::Float($path_root::gfx::attrib::FloatSubType::$kind,
                                                                 $path_root::gfx::attrib::FloatSize::$size))
        },
        "u8" | "u16" | "u32" | "u64" |
        "i8" | "i16" | "i32" | "i64" => {
            let sign = cx.ident_of({
                if ty_str.starts_with("i") { "Signed" } else { "Unsigned" }
            });
            let kind = cx.ident_of(match modifier {
                None => "Raw",
                Some(Modifier::Normalized) => "Normalized",
                Some(Modifier::AsFloat) => "AsFloat",
                Some(Modifier::AsDouble) => {
                    cx.span_warn(span, &format!(
                        "Incompatible int modifier attribute: `#[{:?}]`", modifier
                    ));
                    ""
                }
            });
            let size = cx.ident_of(&format!("U{}", &ty_str[1..]));
            quote_expr!(cx, $path_root::gfx::attrib::Type::Int($path_root::gfx::attrib::IntSubType::$kind,
                                                               $path_root::gfx::attrib::IntSize::$size,
                                                               $path_root::gfx::attrib::SignFlag::$sign))
        },
        ty_str => {
            cx.span_err(span, &format!("Unrecognized component type: `{:?}`",
                                      ty_str));
            cx.expr_tuple(span, vec![])
        },
    }
}

fn decode_count_and_type(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                         field: &ast::StructField,
                         path_root: ast::Ident) -> (P<ast::Expr>, P<ast::Expr>) {
    let modifier = find_modifier(cx, span, &field.node.attrs);
    match field.node.ty.node {
        ast::TyPath(_,ref p) => (
            cx.expr_lit(span, ast::LitInt(1, ast::UnsuffixedIntLit(ast::Plus))),
            decode_type(cx, span, &p.segments[0].identifier, modifier, path_root),
        ),
        ast::TyFixedLengthVec(ref pty, ref expr) => (expr.clone(), match pty.node {
            ast::TyPath(_,ref p) => {
                decode_type(cx, span, &p.segments[0].identifier, modifier, path_root)
            },
            _ => {
                cx.span_err(span, &format!("Unsupported fixed vector sub-type: \
                                          `{:?}`",pty.node));
                cx.expr_tuple(span, vec![])
            },
        }),
        _ => {
            cx.span_err(span, &format!("Unsupported attribute type: `{:?}`",
                                      field.node.ty.node));
            (cx.expr_tuple(span, vec![]), cx.expr_tuple(span, vec![]))
        },
    }
}

/// Generates the the method body for `gfx::VertexFormat::generate`.
fn method_body(cx: &mut ext::base::ExtCtxt, span: codemap::Span,
                   substr: &generic::Substructure,
                   path_root: ast::Ident) -> P<ast::Expr> {
    match *substr.fields {
        generic::StaticStruct(ref definition, generic::Named(ref fields)) => {
            let attribute_pushes = definition.fields.iter().zip(fields.iter())
                .map(|(def, &(ident, _))| {
                    let struct_ident = substr.type_ident;
                    let buffer_expr = &substr.nonself_args[0];
                    let (count_expr, type_expr) = decode_count_and_type(cx, span, def, path_root);
                    let ident_str = match super::find_name(cx, span, &def.node.attrs) {
                        Some(name) => name,
                        None => token::get_ident(ident),
                    };
                    let ident_str = &ident_str[..];
                    let instance_expr = cx.expr_u8(span, 0); // not supposed to be set by the macro
                    quote_expr!(cx, {
                        attributes.push($path_root::gfx::Attribute {
                            name: $ident_str.to_string(),
                            buffer: $buffer_expr.raw().clone(),
                            format: $path_root::gfx::attrib::Format {
                                elem_count: $count_expr,
                                elem_type: $type_expr,
                                offset: unsafe {
                                    let x: $struct_ident = ::std::mem::uninitialized();
                                    let offset = (&x.$ident as *const _ as usize) -
                                        (&x as *const _ as usize);
                                    ::std::mem::forget(x);
                                    offset as $path_root::gfx::attrib::Offset
                                },
                                stride: { use std::mem;
                                    mem::size_of::<$struct_ident>() as
                                        $path_root::gfx::attrib::Stride
                                },
                                instance_rate: $instance_expr,
                            }
                        });
                    })
                }).collect::<Vec<P<ast::Expr>>>();
            let capacity = fields.len();
            quote_expr!(cx, {
                let mut attributes = Vec::with_capacity($capacity);
                $attribute_pushes;
                attributes
            })
        },
        _ => {
            cx.span_err(span, "Unable to implement `gfx::VertexFormat::generate` \
                              on a non-structure");
            cx.expr_tuple(span, vec![])
        }
    }
}

#[derive(Copy, Clone)]
pub struct VertexFormat;

impl ItemDecorator for VertexFormat {
    /// Derive a `gfx::VertexFormat` implementation for the `struct`
    fn expand(&self, context: &mut ext::base::ExtCtxt, span: codemap::Span,
              meta_item: &ast::MetaItem, item: &ast::Item,
              push: &mut FnMut(P<ast::Item>)) {
        // Insert the `gfx` reexport module
        let path_root = super::extern_crate_hack(context, span, |i| (*push)(i));
        let mut fixup = |item| {
            (*push)(super::fixup_extern_crate_paths(item, path_root))
        };

        // `impl<R: gfx::Resources> gfx::VertexFormat for $item`
        generic::TraitDef {
            span: span,
            attributes: Vec::new(),
            path: generic::ty::Path::new(
                vec![super::EXTERN_CRATE_HACK, "gfx", "VertexFormat"],
            ),
            additional_bounds: Vec::new(),
            generics: generic::ty::LifetimeBounds::empty(),
            methods: vec![
                // `fn generate(gfx::handle::RawBuffer) -> Vec<gfx::Attribute>`
                generic::MethodDef {
                    name: "generate",
                    generics: generic::ty::LifetimeBounds {
                        lifetimes: Vec::new(),
                        bounds: vec![
                            ("R", vec![
                                generic::ty::Path::new(vec![
                                    super::EXTERN_CRATE_HACK, "gfx", "Resources"
                                ]),
                            ]),
                        ],
                    },
                    explicit_self: None,
                    args: vec![
                        generic::ty::Ptr(
                            box generic::ty::Literal(generic::ty::Path {
                                path: vec![super::EXTERN_CRATE_HACK, "gfx", "handle", "Buffer"],
                                lifetime: None,
                                params: vec![
                                    box generic::ty::Literal(generic::ty::Path::new_local("R")),
                                    box generic::ty::Self_,
                                ],
                                global: false,
                            }),
                            generic::ty::PtrTy::Borrowed(None, ast::Mutability::MutImmutable),
                        ),
                    ],
                    ret_ty: generic::ty::Literal(
                        generic::ty::Path {
                            path: vec!["Vec"],
                            lifetime: None,
                            params: vec![
                                box generic::ty::Literal(generic::ty::Path {
                                    path: vec![super::EXTERN_CRATE_HACK, "gfx", "Attribute"],
                                    lifetime: None,
                                    params: vec![box generic::ty::Literal(
                                        generic::ty::Path::new_local("R")
                                    )],
                                    global: false,
                                }),
                            ],
                            global: false,
                        },
                    ),
                    attributes: Vec::new(),
                    // generate the method body
                    combine_substructure: generic::combine_substructure(
                        box |c, s, ss| method_body(c, s, ss, path_root)),
                },
            ],
            associated_types: Vec::new(),
        }.expand(context, meta_item, item, &mut fixup);
    }
}