Files
aho_corasick
bigdecimal
bitflags
byteorder
cfg_if
chrono
diesel
associations
connection
expression
expression_methods
macros
migration
mysql
pg
query_builder
query_dsl
query_source
sql_types
sqlite
type_impls
types
diesel_derives
diesel_migrations
env_logger
idna
instant
ipnetwork
itoa
kernel32
libc
libsqlite3_sys
lock_api
log
matches
memchr
migrations_internals
migrations_macros
mysqlclient_sys
num_bigint
num_integer
num_traits
parking_lot
parking_lot_core
percent_encoding
pq_sys
proc_macro2
quickcheck
quote
r2d2
regex
regex_syntax
ryu
scheduled_thread_pool
scopeguard
serde
serde_derive
serde_json
smallvec
syn
thread_id
thread_local
time
tinyvec
tinyvec_macros
unicode_bidi
unicode_normalization
unicode_xid
url
utf8_ranges
uuid
winapi
  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
use proc_macro2::{Ident, Span};
use syn;
use syn::fold::Fold;
use syn::spanned::Spanned;

use resolved_at_shim::*;
use util::*;

pub struct MetaItem {
    meta: syn::Meta,
}

pub(crate) fn path_to_string(path: &syn::Path) -> String {
    path.segments
        .iter()
        .map(|s| s.ident.to_string())
        .collect::<Vec<String>>()
        .join("::")
}

impl MetaItem {
    pub fn all_with_name(attrs: &[syn::Attribute], name: &str) -> Vec<Self> {
        attrs
            .iter()
            .filter_map(|attr| {
                attr.parse_meta()
                    .ok()
                    .map(|m| FixSpan(attr.pound_token.spans[0]).fold_meta(m))
            })
            .filter(|m| m.path().is_ident(name))
            .map(|meta| Self { meta })
            .collect()
    }

    pub fn with_name(attrs: &[syn::Attribute], name: &str) -> Option<Self> {
        Self::all_with_name(attrs, name).pop()
    }

    pub fn empty(name: &str) -> Self {
        Self {
            meta: syn::Meta::List(syn::MetaList {
                path: syn::Path::from(Ident::new(name, Span::call_site())),
                paren_token: Default::default(),
                nested: Default::default(),
            }),
        }
    }

    pub fn nested_item(&self, name: &str) -> Result<Option<Self>, Diagnostic> {
        self.nested()
            .map(|mut i| i.find(|n| n.name().is_ident(name)))
    }

    pub fn required_nested_item(&self, name: &str) -> Result<Self, Diagnostic> {
        self.nested_item(name)?.ok_or_else(|| {
            self.span()
                .error(format!("Missing required option `{}`", name))
        })
    }

    pub fn expect_bool_value(&self) -> bool {
        match self.str_value().as_ref().map(|s| s.as_str()) {
            Ok("true") => true,
            Ok("false") => false,
            _ => {
                self.span()
                    .error(format!(
                        "`{0}` must be in the form `{0} = \"true\"`",
                        path_to_string(&self.name())
                    ))
                    .emit();
                false
            }
        }
    }

    pub fn expect_ident_value(&self) -> syn::Ident {
        self.ident_value().unwrap_or_else(|e| {
            e.emit();
            self.name().segments.first().unwrap().ident.clone()
        })
    }

    pub fn ident_value(&self) -> Result<syn::Ident, Diagnostic> {
        let maybe_attr = self.nested().ok().and_then(|mut n| n.nth(0));
        let maybe_path = maybe_attr.as_ref().and_then(|m| m.path().ok());
        match maybe_path {
            Some(x) => {
                self.span()
                    .warning(format!(
                        "The form `{0}(value)` is deprecated. Use `{0} = \"value\"` instead",
                        path_to_string(&self.name()),
                    ))
                    .emit();
                Ok(x.segments.first().unwrap().ident.clone())
            }
            _ => Ok(syn::Ident::new(
                &self.str_value()?,
                self.value_span().resolved_at(Span::call_site()),
            )),
        }
    }

    pub fn expect_path(&self) -> syn::Path {
        self.path().unwrap_or_else(|e| {
            e.emit();
            self.name()
        })
    }

    pub fn path(&self) -> Result<syn::Path, Diagnostic> {
        use syn::Meta::*;

        match self.meta {
            Path(ref x) => Ok(x.clone()),
            _ => {
                let meta = &self.meta;
                Err(self.span().error(format!(
                    "Expected `{}` found `{}`",
                    path_to_string(&self.name()),
                    quote!(#meta)
                )))
            }
        }
    }

    pub fn nested(&self) -> Result<Nested, Diagnostic> {
        use syn::Meta::*;

        match self.meta {
            List(ref list) => Ok(Nested(list.nested.iter())),
            _ => Err(self.span().error(format!(
                "`{0}` must be in the form `{0}(...)`",
                path_to_string(&self.name())
            ))),
        }
    }

    pub fn name(&self) -> syn::Path {
        self.meta.path().clone()
    }

    pub fn has_flag(&self, flag: &str) -> bool {
        self.nested()
            .map(|mut n| {
                n.any(|m| match m.path() {
                    Ok(word) => word.is_ident(flag),
                    Err(_) => false,
                })
            })
            .unwrap_or_else(|e| {
                e.emit();
                false
            })
    }

    pub fn ty_value(&self) -> Result<syn::Type, Diagnostic> {
        let str = self.lit_str_value()?;
        str.parse()
            .map_err(|_| str.span().error("Invalid Rust type"))
    }

    pub fn expect_str_value(&self) -> String {
        self.str_value().unwrap_or_else(|e| {
            e.emit();
            path_to_string(&self.name())
        })
    }

    fn str_value(&self) -> Result<String, Diagnostic> {
        self.lit_str_value().map(syn::LitStr::value)
    }

    fn lit_str_value(&self) -> Result<&syn::LitStr, Diagnostic> {
        use syn::Lit::*;

        match *self.lit_value()? {
            Str(ref s) => Ok(s),
            _ => Err(self.span().error(format!(
                "`{0}` must be in the form `{0} = \"value\"`",
                path_to_string(&self.name())
            ))),
        }
    }

    pub fn expect_int_value(&self) -> u64 {
        self.int_value().emit_error().unwrap_or(0)
    }

    pub fn int_value(&self) -> Result<u64, Diagnostic> {
        use syn::Lit::*;

        let error = self.value_span().error("Expected a number");

        match *self.lit_value()? {
            Str(ref s) => s.value().parse().map_err(|_| error),
            Int(ref i) => i.base10_parse().map_err(|_| error),
            _ => Err(error),
        }
    }

    fn lit_value(&self) -> Result<&syn::Lit, Diagnostic> {
        use syn::Meta::*;

        match self.meta {
            NameValue(ref name_value) => Ok(&name_value.lit),
            _ => Err(self.span().error(format!(
                "`{0}` must be in the form `{0} = \"value\"`",
                path_to_string(&self.name())
            ))),
        }
    }

    pub fn warn_if_other_options(&self, options: &[&str]) {
        let nested = match self.nested() {
            Ok(x) => x,
            Err(_) => return,
        };
        let unrecognized_options =
            nested.filter(|n| !options.iter().any(|&o| n.name().is_ident(o)));
        for ignored in unrecognized_options {
            ignored
                .span()
                .warning(format!(
                    "Option {} has no effect",
                    path_to_string(&ignored.name())
                ))
                .emit();
        }
    }

    fn value_span(&self) -> Span {
        use syn::Meta::*;

        match self.meta {
            Path(ref path) => path.span(),
            List(ref meta) => meta.nested.span(),
            NameValue(ref meta) => meta.lit.span(),
        }
    }

    pub fn span(&self) -> Span {
        self.meta.span()
    }
}

#[cfg_attr(rustfmt, rustfmt_skip)] // https://github.com/rust-lang-nursery/rustfmt/issues/2392
pub struct Nested<'a>(syn::punctuated::Iter<'a, syn::NestedMeta>);

impl<'a> Iterator for Nested<'a> {
    type Item = MetaItem;

    fn next(&mut self) -> Option<Self::Item> {
        use syn::NestedMeta::*;

        match self.0.next() {
            Some(&Meta(ref item)) => Some(MetaItem { meta: item.clone() }),
            Some(_) => self.next(),
            None => None,
        }
    }
}

/// If the given span is affected by
/// <https://github.com/rust-lang/rust/issues/47941>,
/// returns the span of the pound token
struct FixSpan(Span);

impl Fold for FixSpan {
    fn fold_span(&mut self, span: Span) -> Span {
        fix_span(span, self.0)
    }
}