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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::cmp;
use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{Diagnostic, DiagnosticId, LintDiagnosticBuilder, MultiSpan};
use rustc_hir::HirId;
use rustc_session::lint::{
builtin::{self, FORBIDDEN_LINT_GROUPS},
FutureIncompatibilityReason, Level, Lint, LintId,
};
use rustc_session::Session;
use rustc_span::hygiene::MacroKind;
use rustc_span::source_map::{DesugaringKind, ExpnKind};
use rustc_span::{symbol, Span, Symbol, DUMMY_SP};
use crate::ty::TyCtxt;
#[derive(Clone, Copy, PartialEq, Eq, HashStable, Debug)]
pub enum LintLevelSource {
Default,
Node {
name: Symbol,
span: Span,
reason: Option<Symbol>,
},
CommandLine(Symbol, Level),
}
impl LintLevelSource {
pub fn name(&self) -> Symbol {
match *self {
LintLevelSource::Default => symbol::kw::Default,
LintLevelSource::Node { name, .. } => name,
LintLevelSource::CommandLine(name, _) => name,
}
}
pub fn span(&self) -> Span {
match *self {
LintLevelSource::Default => DUMMY_SP,
LintLevelSource::Node { span, .. } => span,
LintLevelSource::CommandLine(_, _) => DUMMY_SP,
}
}
}
pub type LevelAndSource = (Level, LintLevelSource);
#[derive(Default, Debug, HashStable)]
pub struct ShallowLintLevelMap {
pub specs: FxHashMap<LintId, LevelAndSource>,
}
pub fn reveal_actual_level(
level: Option<Level>,
src: &mut LintLevelSource,
sess: &Session,
lint: LintId,
probe_for_lint_level: impl FnOnce(LintId) -> (Option<Level>, LintLevelSource),
) -> Level {
let mut level = level.unwrap_or_else(|| lint.lint.default_level(sess.edition()));
if level == Level::Warn && lint != LintId::of(FORBIDDEN_LINT_GROUPS) {
let (warnings_level, warnings_src) = probe_for_lint_level(LintId::of(builtin::WARNINGS));
if let Some(configured_warning_level) = warnings_level {
if configured_warning_level != Level::Warn {
level = configured_warning_level;
*src = warnings_src;
}
}
}
level = if let LintLevelSource::CommandLine(_, Level::ForceWarn(_)) = src {
level
} else {
cmp::min(level, sess.opts.lint_cap.unwrap_or(Level::Forbid))
};
if let Some(driver_level) = sess.driver_lint_caps.get(&lint) {
level = cmp::min(*driver_level, level);
}
level
}
impl ShallowLintLevelMap {
fn probe_for_lint_level(
&self,
tcx: TyCtxt<'_>,
id: LintId,
start: HirId,
) -> (Option<Level>, LintLevelSource) {
if let Some(&(level, src)) = self.specs.get(&id) {
return (Some(level), src);
}
for parent in tcx.hir().parent_id_iter(start) {
let specs = tcx.shallow_lint_levels_on(parent);
if let Some(&(level, src)) = specs.specs.get(&id) {
return (Some(level), src);
}
}
(None, LintLevelSource::Default)
}
pub fn lint_level_id_at_node(
&self,
tcx: TyCtxt<'_>,
lint: LintId,
id: HirId,
) -> (Level, LintLevelSource) {
let (level, mut src) = self.probe_for_lint_level(tcx, lint, id);
let level = reveal_actual_level(level, &mut src, tcx.sess, lint, |lint| {
self.probe_for_lint_level(tcx, lint, id)
});
debug!(?id, ?level, ?src);
(level, src)
}
}
impl TyCtxt<'_> {
pub fn lint_level_at_node(self, lint: &'static Lint, id: HirId) -> (Level, LintLevelSource) {
self.shallow_lint_levels_on(id).lint_level_id_at_node(self, LintId::of(lint), id)
}
pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId {
let hir = self.hir();
while id != bound && self.shallow_lint_levels_on(id).specs.is_empty() {
id = hir.get_parent_node(id)
}
id
}
}
#[derive(Clone, Debug, HashStable)]
pub struct LintExpectation {
pub reason: Option<Symbol>,
pub emission_span: Span,
pub is_unfulfilled_lint_expectations: bool,
pub lint_tool: Option<Symbol>,
}
impl LintExpectation {
pub fn new(
reason: Option<Symbol>,
emission_span: Span,
is_unfulfilled_lint_expectations: bool,
lint_tool: Option<Symbol>,
) -> Self {
Self { reason, emission_span, is_unfulfilled_lint_expectations, lint_tool }
}
}
pub fn explain_lint_level_source(
lint: &'static Lint,
level: Level,
src: LintLevelSource,
err: &mut Diagnostic,
) {
let name = lint.name_lower();
match src {
LintLevelSource::Default => {
err.note_once(&format!("`#[{}({})]` on by default", level.as_str(), name));
}
LintLevelSource::CommandLine(lint_flag_val, orig_level) => {
let flag = match orig_level {
Level::Warn => "-W",
Level::Deny => "-D",
Level::Forbid => "-F",
Level::Allow => "-A",
Level::ForceWarn(_) => "--force-warn",
Level::Expect(_) => {
unreachable!("the expect level does not have a commandline flag")
}
};
let hyphen_case_lint_name = name.replace('_', "-");
if lint_flag_val.as_str() == name {
err.note_once(&format!(
"requested on the command line with `{} {}`",
flag, hyphen_case_lint_name
));
} else {
let hyphen_case_flag_val = lint_flag_val.as_str().replace('_', "-");
err.note_once(&format!(
"`{} {}` implied by `{} {}`",
flag, hyphen_case_lint_name, flag, hyphen_case_flag_val
));
}
}
LintLevelSource::Node { name: lint_attr_name, span, reason, .. } => {
if let Some(rationale) = reason {
err.note(rationale.as_str());
}
err.span_note_once(span, "the lint level is defined here");
if lint_attr_name.as_str() != name {
let level_str = level.as_str();
err.note_once(&format!(
"`#[{}({})]` implied by `#[{}({})]`",
level_str, name, level_str, lint_attr_name
));
}
}
}
}
pub fn struct_lint_level<'s, 'd>(
sess: &'s Session,
lint: &'static Lint,
level: Level,
src: LintLevelSource,
span: Option<MultiSpan>,
decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>) + 'd,
) {
fn struct_lint_level_impl<'s, 'd>(
sess: &'s Session,
lint: &'static Lint,
level: Level,
src: LintLevelSource,
span: Option<MultiSpan>,
decorate: Box<dyn for<'b> FnOnce(LintDiagnosticBuilder<'b, ()>) + 'd>,
) {
let future_incompatible = lint.future_incompatible;
let has_future_breakage = future_incompatible.map_or(
sess.opts.unstable_opts.future_incompat_test && lint.default_level != Level::Allow,
|incompat| {
matches!(incompat.reason, FutureIncompatibilityReason::FutureReleaseErrorReportNow)
},
);
let mut err = match (level, span) {
(Level::Allow, span) => {
if has_future_breakage {
if let Some(span) = span {
sess.struct_span_allow(span, "")
} else {
sess.struct_allow("")
}
} else {
return;
}
}
(Level::Expect(expect_id), _) => {
sess.struct_expect("", expect_id)
}
(Level::ForceWarn(Some(expect_id)), Some(span)) => {
sess.struct_span_warn_with_expectation(span, "", expect_id)
}
(Level::ForceWarn(Some(expect_id)), None) => {
sess.struct_warn_with_expectation("", expect_id)
}
(Level::Warn | Level::ForceWarn(None), Some(span)) => sess.struct_span_warn(span, ""),
(Level::Warn | Level::ForceWarn(None), None) => sess.struct_warn(""),
(Level::Deny | Level::Forbid, Some(span)) => {
let mut builder = sess.diagnostic().struct_err_lint("");
builder.set_span(span);
builder
}
(Level::Deny | Level::Forbid, None) => sess.diagnostic().struct_err_lint(""),
};
if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
err.disable_suggestions();
let not_future_incompatible =
future_incompatible.map(|f| f.reason.edition().is_some()).unwrap_or(true);
if not_future_incompatible && !lint.report_in_external_macro {
err.cancel();
return;
}
}
if let Level::Expect(_) = level {
let name = lint.name_lower();
err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn: false });
decorate(LintDiagnosticBuilder::new(err));
return;
}
explain_lint_level_source(lint, level, src, &mut err);
let name = lint.name_lower();
let is_force_warn = matches!(level, Level::ForceWarn(_));
err.code(DiagnosticId::Lint { name, has_future_breakage, is_force_warn });
if let Some(future_incompatible) = future_incompatible {
let explanation = match future_incompatible.reason {
FutureIncompatibilityReason::FutureReleaseError
| FutureIncompatibilityReason::FutureReleaseErrorReportNow => {
"this was previously accepted by the compiler but is being phased out; \
it will become a hard error in a future release!"
.to_owned()
}
FutureIncompatibilityReason::FutureReleaseSemanticsChange => {
"this will change its meaning in a future release!".to_owned()
}
FutureIncompatibilityReason::EditionError(edition) => {
let current_edition = sess.edition();
format!(
"this is accepted in the current edition (Rust {}) but is a hard error in Rust {}!",
current_edition, edition
)
}
FutureIncompatibilityReason::EditionSemanticsChange(edition) => {
format!("this changes meaning in Rust {}", edition)
}
FutureIncompatibilityReason::Custom(reason) => reason.to_owned(),
};
if future_incompatible.explain_reason {
err.warn(&explanation);
}
if !future_incompatible.reference.is_empty() {
let citation =
format!("for more information, see {}", future_incompatible.reference);
err.note(&citation);
}
}
decorate(LintDiagnosticBuilder::new(err));
}
struct_lint_level_impl(sess, lint, level, src, span, Box::new(decorate))
}
pub fn in_external_macro(sess: &Session, span: Span) -> bool {
let expn_data = span.ctxt().outer_expn_data();
match expn_data.kind {
ExpnKind::Inlined
| ExpnKind::Root
| ExpnKind::Desugaring(DesugaringKind::ForLoop | DesugaringKind::WhileLoop) => false,
ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, ExpnKind::Macro(MacroKind::Bang, _) => {
expn_data.def_site.is_dummy() || sess.source_map().is_imported(expn_data.def_site)
}
ExpnKind::Macro { .. } => true, }
}