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
#![doc(html_root_url = "https://docs.rs/fast_new_type/0.1.7/")]
#![no_std]

/*!
This crate serves the purporse of implement [`Deref`],[`DerefMut`],[`AsRef`],[`AsMut`] and [`From`] in new
types,either for the first value of a struct,the "value" or "slot" field or the specified in the attribute.

With `default-features = false` you can opt-out of the [`From`] impl which in some cases is not desirable. 

This crate is **no_std**.

# Examples

```
use fast_new_type::new_type;

#[new_type]
struct FirstField(u32, u16);

#[new_type]
struct ValueField {
    value: u16,
    other_meta: u16,
}

#[new_type]
struct SlotField {
    slot: u16,
    other_meta: u16,
}

#[new_type(other)]
struct SpecField {
    other: u16,
    other_meta: u16,
}

```

[`Deref`]: https://doc.rust-lang.org/std/ops/trait.Deref.html
[`DerefMut`]: https://doc.rust-lang.org/std/ops/trait.DerefMut.html
[`AsRef`]: https://doc.rust-lang.org/std/convert/trait.AsRef.html
[`AsMut`]: https://doc.rust-lang.org/std/convert/trait.AsMut.html
[`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
*/

extern crate alloc;
extern crate proc_macro;

use alloc::format;
use alloc::string::{String, ToString};
use core::fmt::Write;
use proc_macro::TokenStream;
use syn_str::remove_item_attrs;
use syn_str::custom_types::{DisplayGeneric, Struct, StructType, ORDER_FIELDS};

/// Implement common traits in a wrapper for a type,with the specifie field as arg where needed.
#[proc_macro_attribute]
pub fn new_type(attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut expansion = String::new();
    let item = item.to_string();
    let mut attr = attr.to_string();

    if attr.is_empty() {
        attr.push_str("slot, value");
    } else {
        attr.push_str(",slot, value");
    }

    let mut iter = attr.split(',');

    unsafe {
        ORDER_FIELDS = false;
    }

    let item2 = match remove_item_attrs(&item) {
        Ok(itm) => itm,
        Err(s) => format!("compile_error!(\"{}\")", s).parse().unwrap()
    };

    let syn_struct = match Struct::new(item2.as_ref()) {
        Ok(s) => s,
        Err(s) => {
            return format!("compile_error!(\"Error parsing the struct: {}\")", s)
                .parse()
                .unwrap()
        }
    };

    let (field_name, type_field) = if let Some(f) = syn_struct.fields.get(0) {
        if f.name == "" {
            ("0", f.f_type)
        } else if syn_struct.fields.len() == 1 {
            (f.name, f.f_type)
        } else {
            let mut field = None;

            'a: for mut s in iter.by_ref() {
                s = s.trim();

                for f2 in syn_struct.fields.iter() {
                    if f2.name == s {
                        field = Some(f2);
                        break 'a;
                    }
                }
            }

            match field {
                Some(f2) => (f2.name, f2.f_type),
                None => (f.name, f.f_type),
            }
        }
    } else {
        return String::from("compile_error!(\"Expected struct with fields\")")
            .parse()
            .unwrap();
    };

    writeln!(expansion).unwrap();

    writeln!(expansion, "{}", item).unwrap();

    writeln!(expansion).unwrap();

    writeln!(
        expansion,
        "impl{} core::ops::Deref for {} {{",
        syn_struct.interface.format_generics(),
        syn_struct.interface.name_boundless()
    )
    .unwrap();

    writeln!(expansion, "\ttype Target = {};", type_field).unwrap();

    writeln!(expansion).unwrap();

    writeln!(expansion, "\tfn deref(&self) -> &Self::Target {{").unwrap();

    if syn_struct.interface.item_type != StructType::Union {
        writeln!(expansion, "\t\t&self.{}", field_name).unwrap();
    } else {
        writeln!(expansion, "\t\tunsafe {{ &self.{} }}", field_name).unwrap();
    }

    writeln!(expansion, "\t}}").unwrap();
    writeln!(expansion, "}}").unwrap();
    writeln!(expansion).unwrap();

    writeln!(
        expansion,
        "impl{} core::ops::DerefMut for {} {{",
        syn_struct.interface.format_generics(),
        syn_struct.interface.name_boundless()
    )
    .unwrap();

    writeln!(
        expansion,
        "\tfn deref_mut(&mut self) -> &mut Self::Target {{"
    )
    .unwrap();

    if syn_struct.interface.item_type != StructType::Union {
        writeln!(expansion, "\t\t&mut self.{}", field_name).unwrap();
    } else {
        writeln!(expansion, "\t\tunsafe {{ &mut self.{} }}", field_name).unwrap();
    }

    writeln!(expansion, "\t}}").unwrap();
    writeln!(expansion, "}}").unwrap();
    writeln!(expansion).unwrap();

    if cfg!(feature = "from_struct_for_field") {
    writeln!(
        expansion,
        "impl{} From<{}> for {} {{",
        syn_struct.interface.format_generics(),
        syn_struct.interface.name_boundless(),
        type_field
    )
    .unwrap();

    writeln!(
        expansion,
        "\tfn from(a: {}) -> Self {{",
        syn_struct.interface.name_boundless()
    )
    .unwrap();

    if syn_struct.interface.item_type != StructType::Union {
        writeln!(expansion, "\t\ta.{}", field_name).unwrap();
    } else {
        writeln!(expansion, "\t\tunsafe {{ a.{} }}", field_name).unwrap();
    }

    writeln!(expansion, "\t}}").unwrap();
    writeln!(expansion, "}}").unwrap();
    writeln!(expansion).unwrap();
    }

    writeln!(
        expansion,
        "impl{} AsRef<{}> for {} {{",
        syn_struct.interface.format_generics(),
        type_field,
        syn_struct.interface.name_boundless()
    )
    .unwrap();

    writeln!(expansion, "\tfn as_ref(&self) -> &{} {{", type_field).unwrap();

    if syn_struct.interface.item_type != StructType::Union {
        writeln!(expansion, "\t\t&self.{}", field_name).unwrap();
    } else {
        writeln!(expansion, "\t\tunsafe {{ &self.{} }}", field_name).unwrap();
    }

    writeln!(expansion, "\t}}").unwrap();
    writeln!(expansion, "}}").unwrap();
    writeln!(expansion).unwrap();

    writeln!(
        expansion,
        "impl{} AsMut<{}> for {} {{",
        syn_struct.interface.format_generics(),
        type_field,
        syn_struct.interface.name_boundless(),
    )
    .unwrap();

    writeln!(
        expansion,
        "\tfn as_mut(&mut self) -> &mut {} {{",
        type_field
    )
    .unwrap();

    if syn_struct.interface.item_type != StructType::Union {
        writeln!(expansion, "\t\t&mut self.{}", field_name).unwrap();
    } else {
        writeln!(expansion, "\t\tunsafe {{ &mut self.{} }}", field_name).unwrap();
    }

    writeln!(expansion, "\t}}").unwrap();
    writeln!(expansion, "}}").unwrap();

    expansion.parse().unwrap()
}