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
//! geiger ☢
//! ========
//!
//! This crate provides some library parts used by `cargo-geiger` that are decoupled
//! from `cargo`.

#![forbid(unsafe_code)]
#![deny(warnings)]

pub mod find;
mod geiger_syn_visitor;

use cargo_geiger_serde::CounterBlock;
use std::error::Error;
use std::fmt;
use std::io;
use std::path::PathBuf;
use std::string::FromUtf8Error;
use syn::{ItemFn, ItemMod};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IncludeTests {
    Yes,
    No,
}

/// Scan result for a single `.rs` file.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RsFileMetrics {
    /// Metrics storage.
    pub counters: CounterBlock,

    /// This file is decorated with `#![forbid(unsafe_code)]`
    pub forbids_unsafe: bool,
}

#[derive(Debug)]
pub enum ScanFileError {
    Io(io::Error, PathBuf),
    Utf8(FromUtf8Error, PathBuf),
    Syn(syn::Error, PathBuf),
}

impl Error for ScanFileError {}

/// Forward Display to Debug, probably good enough for
/// programmer facing error messages.
impl fmt::Display for ScanFileError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

fn file_forbids_unsafe(f: &syn::File) -> bool {
    use syn::AttrStyle;
    use syn::Meta;
    use syn::MetaList;
    use syn::NestedMeta;
    f.attrs
        .iter()
        .filter(|a| matches!(a.style, AttrStyle::Inner(_)))
        .filter_map(|a| a.parse_meta().ok())
        .filter(|meta| match meta {
            Meta::List(MetaList {
                path,
                paren_token: _paren,
                nested,
            }) => {
                if !path.is_ident("forbid") {
                    return false;
                }
                nested.iter().any(|n| match n {
                    NestedMeta::Meta(Meta::Path(p)) => {
                        p.is_ident("unsafe_code")
                    }
                    _ => false,
                })
            }
            _ => false,
        })
        .count()
        > 0
}

fn is_test_fn(item_fn: &ItemFn) -> bool {
    use syn::Attribute;
    item_fn
        .attrs
        .iter()
        .flat_map(Attribute::parse_meta)
        .any(|m| meta_contains_ident(&m, "test"))
}

fn has_unsafe_attributes(item_fn: &ItemFn) -> bool {
    use syn::Attribute;
    item_fn
        .attrs
        .iter()
        .flat_map(Attribute::parse_meta)
        .any(|m| {
            meta_contains_ident(&m, "no_mangle")
                || meta_contains_attribute(&m, "export_name")
        })
}

/// Will return true for #[cfg(test)] decorated modules.
///
/// This function is a somewhat of a hack and will probably misinterpret more
/// advanced cfg expressions. A better way to do this would be to let rustc emit
/// every single source file path and span within each source file and use that
/// as a general filter for included code.
/// TODO: Investigate if the needed information can be emitted by rustc today.
fn is_test_mod(i: &ItemMod) -> bool {
    use syn::Attribute;
    use syn::Meta;
    i.attrs
        .iter()
        .flat_map(Attribute::parse_meta)
        .any(|m| match m {
            Meta::List(ml) => meta_list_is_cfg_test(&ml),
            _ => false,
        })
}

fn meta_contains_ident(m: &syn::Meta, ident: &str) -> bool {
    use syn::Meta;
    match m {
        Meta::Path(p) => p.is_ident(ident),
        _ => false,
    }
}

fn meta_contains_attribute(m: &syn::Meta, ident: &str) -> bool {
    use syn::Meta;
    match m {
        Meta::NameValue(nv) => nv.path.is_ident(ident),
        _ => false,
    }
}

// MetaList {
//     ident: Ident(
//         cfg
//     ),
//     paren_token: Paren,
//     nested: [
//         Meta(
//             Word(
//                 Ident(
//                     test
//                 )
//             )
//         )
//     ]
// }
fn meta_list_is_cfg_test(meta_list: &syn::MetaList) -> bool {
    use syn::NestedMeta;
    if !meta_list.path.is_ident("cfg") {
        return false;
    }
    meta_list.nested.iter().any(|n| match n {
        NestedMeta::Meta(meta) => meta_contains_ident(meta, "test"),
        _ => false,
    })
}