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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#![doc(html_root_url = "https://docs.rs/macro_helper/0.1.6/")]
#![no_std]
/*!
This crate is a collection of ligthweight procedural macros typically used for writing others,either procedural or not,as such covers
some of the missing features you might expect from macro_rules! like expansion bucles controlled by you and not an input.Or guarantee an identifier is borrowed in the manner you want over any other,included own.

This crate is **no_std**.
*/

extern crate proc_macro;
extern crate alloc;

use proc_macro::TokenStream;
use alloc::{ string::{String, ToString}, vec::Vec, format };
use alloc::borrow::Cow;

fn ops(input: TokenStream) -> TokenStream {
    let input = input.to_string();

    let mut operators = String::with_capacity(input.len());
    let mut err = String::with_capacity(64);

    let mut it: Vec<String> = input.split(|c: char| {
        match c {
            '+' => {operators.push('+'); true},
            '-' => {operators.push('-'); true},
            '*' => {operators.push('*'); true},
            '/' => {operators.push('/'); true},
            '%' => {operators.push('%'); true},
            '^' => {operators.push('^'); true},
            _ => false   
        }
    }).map(|e| {
        let mut trigger = false;
        let mut string = String::with_capacity(e.len()+1);

        string.push('0');

        string.extend(e.chars().filter(|c| {
            if *c == '!' {
                trigger = true;
            }

            c.is_numeric() && !trigger
        }));

        string
    }).collect();

    let mut result: isize = it[0].parse().unwrap_or_else(|_| {
        err.push_str("compile_error!(\"Error at parsing first operand.\")");
        0
    });

    if err != "" {
        return err.parse().unwrap();
    }

    for (i, (e, op)) in it.drain(1..).zip(operators.chars()).enumerate() {

        if e == "" {
            return format!("compile_error!(\"Error at parsing operand number {}.\")", i+1).parse().unwrap()
        }

        let e: isize = match e.parse() {
            Ok(i) => i,
            Err(_) => return format!("compile_error!(\"Error operand number {} overflows an isize.\")", i+1).parse().unwrap(),
        };

        match op {
            '+' => result = match result.checked_add(e) {
                Some(i) => i,
                None => return format!("compile_error!(\"operation number {} failed.\")", i+1).parse().unwrap(),
            },

            '-' => result = match result.checked_sub(e) {
                Some(i) => i,
                None => return format!("compile_error!(\"operation number {} failed.\")", i+1).parse().unwrap(),
            },

            '*' => result = match result.checked_mul(e) {
                Some(i) => i,
                None => return format!("compile_error!(\"operation number {} failed.\")", i+1).parse().unwrap(),
            },

            '/' => result = match result.checked_div(e) {
                Some(i) => i,
                None => return format!("compile_error!(\"operation number {} failed.\")", i+1).parse().unwrap(),
            },

            '%' => result = match result.checked_rem(e) {
                Some(i) => i,
                None => return format!("compile_error!(\"operation number {} failed.\")", i+1).parse().unwrap(),
            },

            '^' => result = match result.checked_pow(e as u32) {
                Some(i) => i,
                None => return format!("compile_error!(\"operation number {} failed.\")", i+1).parse().unwrap(),
            },

            _ => ()
        }        
    }

    result.to_string().parse().unwrap()
}

/// An expansion bucle with syntax **code => num** when num is the number of times the code should be expanded.
/// 
/// The num part supports encoded arithmetic operations.
/// 
/// Note that a zero not throws an compiler error rather than that it expands zero times the given code.
#[proc_macro]
pub fn expansion_bucle(input: TokenStream) -> TokenStream {
    let mut expansion = String::new();
    let input = input.to_string();
    let index = input.rfind("=>").unwrap_or_else(|| 1);
    
    let (code, mut repetitions) = input.split_at(index);
    repetitions = &repetitions[2..];
    let mathematic = repetitions.contains(|c: char| {
        match c {
            '+' => true,
            '-' => true,
            '*' => true,
            '/' => true,
            '%' => true,
            '^' => true,
            _ => false   
        }
    });

    let repetitions = if mathematic {
        ops(repetitions.to_string().parse().unwrap()).to_string().parse::<usize>().unwrap()
    } else {
        repetitions.trim().parse::<usize>().unwrap()
    };

    let mut code = code.trim().to_string();

    let mut indexes = Vec::with_capacity(code.len()/4);

    let mut codes = &code[..];

    while let Some(i) = codes.find("$") {
        codes = &codes[i+1..];

        if codes.as_bytes()[1] == b'[' {
            indexes.push(i);   
        }
    }

    for i in indexes {
        let mut s = &code[i..];

        let index = match s.find(']') {
            Some(i) => i,
            None => return "compile_error!(\"Detected unmatch \"[\".\")".to_string().parse().unwrap(),
        };

        s = &s[..=index];

        let result = ops(s.to_string().parse().unwrap()).to_string();

        code = code.replacen(&s, &result, 1);
    }

    if repetitions == 0 {
        return expansion.parse().unwrap();
    }

    expansion.reserve(code.len()*repetitions);

    for _ in 0..repetitions {
        expansion.push_str(&code);
    }

    expansion.parse().unwrap()  
} 

/// An expansion bucle with syntax **code => num** when num is the number of times the code should be expanded along with a
/// replacement of the **rep_count** imaginary variable at each "iteration" with values from 0 thought num-1.
/// 
/// Like rep_count this macro support replacement of tokens prefixed by ":" at each iteration in order of aparition
/// in **num**,relying in the last if it does not find other.
/// 
/// The **num** and the **code** within $[] supports compile-time arithmetic operations with encoded(meta_lit and rep_count included) operands.
/// 
/// This macro can cause your code to not compile properly with a variable named **rep_count**something.
/// Because it replaces the rep_count identifier with an integer.
/// 
/// Note that a zero not throws an compiler error,rather than that it expands zero times the given code.
#[proc_macro]
pub fn expansion_bucle_counted(input: TokenStream) -> TokenStream {
    let mut expansion = String::new();
    let input = input.to_string();
    let index = input.rfind("=>").unwrap_or_else(|| 1);
    
    let (code, repetitions) = input.split_at(index);
    let mut repetitions = Cow::Borrowed(&repetitions[2..]);
    let mathematic = repetitions.contains(|c: char| {
        match c {
            '+' => true,
            '-' => true,
            '*' => true,
            '/' => true,
            '%' => true,
            '^' => true,
            _ => false   
        }
    });

    let mut meta_lit = Vec::new();

    let mut search = "";

    if let Some(i) = repetitions.find(':') {
        search = &repetitions[i+1..];
    }

    while let Some(i) = search.find(':') {
        meta_lit.push((&search[..i]).to_string());
        search = &search[i+1..];
    }

    if search != "" {
        meta_lit.push(search.to_string());
    }

    for e in meta_lit.iter() {
        let pat = format!(":{}", &e[..]);
        repetitions = Cow::Owned(repetitions.replace(&pat, ""));
    }

    let repetitions = if mathematic {
        ops(repetitions.to_string().parse().unwrap()).to_string().parse::<usize>().unwrap()
    } else {
        repetitions.trim().parse::<usize>().unwrap()
    };

    if repetitions == 0 {
        return expansion.parse().unwrap();
    }

    let code = code.trim().to_string();

    let mut expansion_v = Vec::with_capacity(repetitions);

    let default = String::from("meta_lit");

    let last_lit = meta_lit.get(meta_lit.len().saturating_sub(1)).unwrap_or(&default);

    for i in 0..repetitions {
        let mut codef = code.replace( "rep_count", &i.to_string() );

        if last_lit != &default {
            codef = codef.replace("meta_lit", meta_lit.get(i).unwrap_or(last_lit));
        }

        expansion_v.push(codef);
    }

    for e in expansion_v.iter_mut() {
        let mut codes = &e[..];
        let mut indexes = Vec::with_capacity(code.len()/4);

        while let Some(i) = codes.find("$") {
            codes = &codes[i+1..];

            if codes.as_bytes()[1] == b'[' {
                indexes.push(i);   
            }
        }

        for i in indexes {
            let mut s = &e[i..];

            let index = match s.find(']') {
                Some(i) => i,
                None => return "compile_error!(\"Detected unmatch \"[\".\")".to_string().parse().unwrap(),
            };

            s = &s[..=index];

            let result = ops(s.to_string().parse().unwrap()).to_string();

            *e = e.replacen(&s, &result, 1);
        }
    }

    expansion.reserve(code.len() * repetitions);

    for e in expansion_v {
        expansion.push_str(&e[..]);
    }

    expansion.parse().unwrap()  
} 

/// Ensures that the reference or identifier passed is shared and changes it if is not.
/// 
/// Typically useless because inside macros it ignores the namespace of the tokens captured by input and returns one that doesn't
/// have always a declared identifier.This will change if the hygiene of the procedural macros is sync with the by-example ones.
#[proc_macro]
pub fn as_ref_token(input: TokenStream) -> TokenStream {
    let input = input.to_string();
    let inputt = input.trim();
    let bool1 = input.contains('&');

    if bool1 && !inputt.contains("&mut") {
        inputt.parse().unwrap()
    } else {
        let index = if bool1 { inputt.rfind(' ').unwrap()+1 } else { 0 };
        format!("&{}", &inputt[index..]).parse().unwrap()
    }
}

/// Ensures that the reference or identifier passed is mutable and changes it if is not.
/// 
/// Typically useless because inside macros it ignores the namespace of the tokens captured by input and returns one that doesn't
/// have always a declared identifier.This will change if the hygiene of the procedural macros is sync with the by-example ones.
#[proc_macro]
pub fn as_mut_ref_token(input: TokenStream) -> TokenStream {
    let input = input.to_string();
    let inputt = input.trim();
    let bool1 = input.contains('&');

    if bool1 && inputt.contains("&mut") {
        inputt.parse().unwrap()
    } else {
        let a = if bool1 {1} else {0};
        format!("&mut {}", &inputt[a..]).parse().unwrap()
    }
}

/// Eval encoded strings that maybe are from other macros.
/// 
/// The unique thing this macro does is omit the first and last token,that is,the quote `"`.This might be
/// useful when you receive a str into a macro and you want evaluate they to not waste more code in 
/// replicate the behaviour,while you also want the string for other things,saving you from a possible parse.
/// 
/// The indentifiers are parsed literally in procedural macros so this macro is not a security problem 
/// as a true eval is in a scripted language. 
#[proc_macro]
pub fn eval_encoded(input: TokenStream) -> TokenStream {
    let input = input.to_string();
    (&input[1..input.len()-1]).to_string().parse().unwrap()
}

/// **String**ify the input. 
#[allow(non_snake_case)]
#[proc_macro]
pub fn Stringify(input: TokenStream) -> TokenStream {
    let mut input = input.to_string();
    input.reserve(16);
    input.insert_str(0, "String::from(");
    input.push_str("\")");
    input.parse().unwrap()      
}

/// This macro panics with the message "Prototype reached '*tokens*'." where *tokens* are the tokens
/// passed.
#[proc_macro]
pub fn proto(input: TokenStream) -> TokenStream {
    format!("panic!(\"Prototype reached '{}'.\")", input).parse().unwrap()
}

/// Expands to the number of tokens you pass.
#[proc_macro]
pub fn count_tokens(input: TokenStream) -> TokenStream {
    input.to_string().len().to_string().parse().unwrap()
}

/// Expands to the number of **spec** tokens you pass in **tokens => spec** syntax,useful when expanding
/// expansion bucles with a given separator matched in **spec**;to retrieve the number of expansions,as
/// it have more precedence than the other macros.
/// 
/// If you omit the `=>` it will have the same effect of [count_tokens](macro.count_tokens.html).
#[proc_macro]
pub fn count_spec_tokens(input: TokenStream) -> TokenStream {
    let input = input.to_string();

    let index = match input.rfind("=>") {
        Some(i) => i,
        None => return input.to_string().len().to_string().parse().unwrap()
    };

    let (haystack, search) = (&input[..index], &input[index+2..]);

    haystack.matches(search).count().to_string().parse().unwrap()
}