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
//! # Macros for peptidic sequences regular expressions
//!
//! Collection of macros to help crafting regular expression matching peptidic sequences.
//!
//! ## Usage
//!
//! ```rust
//! use aa_regex::{any, except};
//!
//! let any_amino_acid = any!();
//! // => "[ARNDCEQGHILKMFPSTWYV]"
//!
//! let any_aromatics = any!('W', 'F', 'Y');
//! // => "[WFY]"
//!
//! let no_proline = except!('P');
//! // => "[ARNDCEQGHILKMFSTWYV]"
//!
//! // concatenation
//! let motif = concat!(any!('R', 'H', 'K'), except!('P'));
//! // => "[RHK][ARNDCEQGHILKMFSTWYV]"
//! ```
use proc_macro::TokenStream;
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input, Error, Result, Token,
};

macro_rules! all_aa_vec {
    () => {
        vec![
            'A', 'R', 'N', 'D', 'C', 'E', 'Q', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T',
            'W', 'Y', 'V',
        ]
    };
}

macro_rules! q {
    () => {
        "\""
    };
}

macro_rules! any_start {
    () => {
        "\"["
    };
}

macro_rules! any_end {
    () => {
        "]\""
    };
}

trait AaRegexBuilder {
    fn build(&self) -> Result<proc_macro2::TokenStream>;
}

fn build<T: AaRegexBuilder + Sized>(aas: T) -> Result<proc_macro2::TokenStream> {
    aas.build()
}

fn join_regex_aa(aas: &[char]) -> Result<proc_macro2::TokenStream> {
    let mut out = String::new();
    let joined = aas.to_owned().into_iter().collect::<String>();

    if aas.len() == 1 {
        out += q!();
        out += &joined;
        out += q!();
    } else {
        out += any_start!();
        out += &joined;
        out += any_end!();
    }

    Ok(out.parse::<proc_macro2::TokenStream>().unwrap()) // TODO: get rid of unwrap
}

/* ----------------------------------- Any ---------------------------------- */

struct AnyInput(Vec<char>);

impl Parse for AnyInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut aas: Vec<char> = Vec::new();

        if input.is_empty() {
            aas = all_aa_vec!();
        } else {
            loop {
                let aa = input.parse::<syn::LitChar>()?;
                if all_aa_vec!().contains(&aa.value()) {
                    aas.push(aa.value());
                } else {
                    return Err(Error::new(aa.span(), "expected amino acid 1-letter code"));
                }
                if input.parse::<Option<Token![,]>>()?.is_none() {
                    // no comma -> end
                    break;
                }
            }
        }

        Ok(AnyInput(aas))
    }
}

impl AaRegexBuilder for AnyInput {
    fn build(&self) -> Result<proc_macro2::TokenStream> {
        join_regex_aa(&self.0)
    }
}

/// # Any amino acid or any of...
///
/// Any of all valid amino acids or any of the selected amino acids
///
/// ## Usage
///
/// ```
/// #[macro_use]
///  use aa_regex::any;
///
/// let some = any!('C', 'D', 'E');
/// let all = any!();
/// ```
///
/// ## Errors
///
/// - non amino acid characters
///  
#[proc_macro]
pub fn any(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as AnyInput);
    build(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/* --------------------------------- Except --------------------------------- */

struct ExceptInput(Vec<char>);

impl Parse for ExceptInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut aas_to_remove: Vec<char> = Vec::new();

        loop {
            let aa = input.parse::<syn::LitChar>()?;
            if all_aa_vec!().contains(&aa.value()) {
                aas_to_remove.push(aa.value());
            } else {
                return Err(Error::new(aa.span(), "expected amino acid 1-letter code"));
            }
            if input.parse::<Option<Token![,]>>()?.is_none() {
                // no comma -> end
                break;
            }
        }
        let mut aas = all_aa_vec!();
        aas.retain(|c| !aas_to_remove.contains(c));

        if aas.is_empty() {
            return Err(Error::new(
                input.span(),
                "cannot remove all the possible amino acids",
            ));
        }

        Ok(ExceptInput(aas))
    }
}

impl AaRegexBuilder for ExceptInput {
    fn build(&self) -> Result<proc_macro2::TokenStream> {
        join_regex_aa(&self.0)
    }
}

/// # Except some amino acids
///
/// ## Usage
///
/// ```
/// #[macro_use]
///  use aa_regex::except;
///
/// let some = except!('C', 'D', 'E');
/// ```
///
/// ## Errors
///
/// - non amino acid characters
/// - trying to except all amnino acids
///
#[proc_macro]
pub fn except(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ExceptInput);
    build(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}