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
use crate::{LightContext, ToConsoleString};
use ansi_term::{
    Color::{Green, Yellow},
    Style,
};
use anyhow::{bail, Result};
use bitflags::bitflags;
use heck::ToKebabCase;
use is_terminal::IsTerminal;
use std::{collections::BTreeMap, sync::Mutex};

// smoelius: `Warning` is part of Necessist's public API. Please try to follow the naming convention
// of `what` (e.g., `Output`) followed by `why` (e.g., `Invalid`).
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[non_exhaustive]
#[remain::sorted]
pub enum Warning {
    All,
    DatabaseDoesNotExist,
    DryRunFailed,
    FilesChanged,
    IgnoredFunctionsUnsupported,
    IgnoredMacrosUnsupported,
    IgnoredMethodsUnsupported,
    ItMessageNotFound,
    ModulePathUnknown,
    OutputInvalid,
    ParsingFailed,
    RunTestFailed,
}

impl std::fmt::Display for Warning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", format!("{self:?}").to_kebab_case())
    }
}

bitflags! {
    #[derive(Clone, Copy)]
    pub struct Flags: u8 {
        const ONCE = 1 << 0;
    }
}

/// Like [`warn`], but prints the warning prefixed with its source.
#[allow(clippy::module_name_repetitions)]
pub fn source_warn(
    context: &LightContext,
    warning: Warning,
    source: &dyn ToConsoleString,
    msg: &str,
    flags: Flags,
) -> Result<()> {
    warn_internal(context, warning, Some(source), msg, flags)
}

/// Prints a warning message to the console.
///
/// # Arguments
///
/// * `context` - The context to use for printing the warning.
/// * `warning` - The type of the warning.
/// * `msg` - The message to print.
/// * `flags` - The flags to use for printing the warning.
///
/// # Errors
///
/// Returns an error if the message could not be printed.
pub fn warn(context: &LightContext, warning: Warning, msg: &str, flags: Flags) -> Result<()> {
    warn_internal(context, warning, None, msg, flags)
}

const BUG_MSG: &str = "

This may indicate a bug in Necessist. Consider opening an issue at: \
https://github.com/trailofbits/necessist/issues
";

bitflags! {
    struct State: u8 {
        const ALLOW_MSG_EMITTED = 1 << 0;
        const BUG_MSG_EMITTED = 1 << 1;
        const WARNING_EMITTED = 1 << 2;
    }
}

static WARNING_STATE_MAP: Mutex<BTreeMap<Warning, State>> = Mutex::new(BTreeMap::new());

#[cfg_attr(dylint_lib = "general", allow(non_local_effect_before_error_return))]
fn warn_internal(
    context: &LightContext,
    warning: Warning,
    source: Option<&dyn ToConsoleString>,
    msg: &str,
    flags: Flags,
) -> Result<()> {
    assert_ne!(warning, Warning::All);

    #[allow(clippy::unwrap_used)]
    let mut warning_state_map = WARNING_STATE_MAP.lock().unwrap();

    let state = warning_state_map
        .entry(warning)
        .or_insert_with(State::empty);

    // smoelius: Append `BUG_MSG` to `msg` in case we have to `bail!`.
    let msg = msg.to_owned()
        + if may_be_bug(warning) && !state.contains(State::BUG_MSG_EMITTED) {
            state.insert(State::BUG_MSG_EMITTED);
            BUG_MSG
        } else {
            ""
        };

    if context.opts.deny.contains(&Warning::All) || context.opts.deny.contains(&warning) {
        bail!(msg);
    }

    if context.opts.quiet
        || context.opts.allow.contains(&Warning::All)
        || context.opts.allow.contains(&warning)
        || (flags.contains(Flags::ONCE) && state.contains(State::WARNING_EMITTED))
    {
        return Ok(());
    }

    let allow_msg = if state.contains(State::ALLOW_MSG_EMITTED) {
        String::new()
    } else {
        state.insert(State::ALLOW_MSG_EMITTED);
        format!(
            "
Silence this warning with: --allow {warning}"
        )
    };

    (context.println)(&format!(
        "{}{}: {}{}",
        source.map_or(String::new(), |source| format!(
            "{}: ",
            source.to_console_string()
        )),
        if std::io::stdout().is_terminal() {
            Yellow.bold()
        } else {
            Style::default()
        }
        .paint("Warning"),
        msg,
        allow_msg
    ));

    state.insert(State::WARNING_EMITTED);

    Ok(())
}

pub(crate) fn note(context: &LightContext, msg: &str) {
    if context.opts.quiet {
        return;
    }

    (context.println)(&format!(
        "{}: {}",
        if std::io::stdout().is_terminal() {
            Green.bold()
        } else {
            Style::default()
        }
        .paint("Note"),
        msg
    ));
}

fn may_be_bug(warning: Warning) -> bool {
    match warning {
        Warning::All => unreachable!(),
        Warning::DatabaseDoesNotExist
        | Warning::DryRunFailed
        | Warning::FilesChanged
        | Warning::IgnoredFunctionsUnsupported
        | Warning::IgnoredMacrosUnsupported
        | Warning::IgnoredMethodsUnsupported
        | Warning::ItMessageNotFound
        | Warning::OutputInvalid
        | Warning::ParsingFailed => false,
        Warning::ModulePathUnknown | Warning::RunTestFailed => true,
    }
}