-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
context.rs
1655 lines (1435 loc) · 57 KB
/
context.rs
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Implementation of lint checking.
//!
//! The lint checking is mostly consolidated into one pass which runs
//! after all other analyses. Throughout compilation, lint warnings
//! can be added via the `add_lint` method on the Session structure. This
//! requires a span and an ID of the node that the lint is being added to. The
//! lint isn't actually emitted at that time because it is unknown what the
//! actual lint level at that location is.
//!
//! To actually emit lint warnings/errors, a separate pass is used.
//! A context keeps track of the current state of all lint levels.
//! Upon entering a node of the ast which can modify the lint settings, the
//! previous lint state is pushed onto a stack and the ast is then recursed
//! upon. As the ast is traversed, this keeps track of the current lint level
//! for all lint attributes.
use self::TargetLint::*;
use std::slice;
use rustc_data_structures::sync::{ReadGuard, Lock, ParallelIterator, join, par_iter};
use crate::lint::{EarlyLintPass, LateLintPass, EarlyLintPassObject, LateLintPassObject};
use crate::lint::{LintArray, Level, Lint, LintId, LintPass, LintBuffer};
use crate::lint::builtin::BuiltinLintDiagnostics;
use crate::lint::levels::{LintLevelSets, LintLevelsBuilder};
use crate::middle::privacy::AccessLevels;
use crate::rustc_serialize::{Decoder, Decodable, Encoder, Encodable};
use crate::session::{config, early_error, Session};
use crate::ty::{self, print::Printer, subst::Kind, TyCtxt, Ty};
use crate::ty::layout::{LayoutError, LayoutOf, TyLayout};
use crate::util::nodemap::FxHashMap;
use crate::util::common::time;
use std::default::Default as StdDefault;
use syntax::ast;
use syntax::edition;
use syntax_pos::{MultiSpan, Span, symbol::{LocalInternedString, Symbol}};
use errors::DiagnosticBuilder;
use crate::hir;
use crate::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use crate::hir::intravisit as hir_visit;
use crate::hir::intravisit::Visitor;
use crate::hir::map::{definitions::DisambiguatedDefPathData, DefPathData};
use syntax::util::lev_distance::find_best_match_for_name;
use syntax::visit as ast_visit;
/// Information about the registered lints.
///
/// This is basically the subset of `Context` that we can
/// build early in the compile pipeline.
pub struct LintStore {
/// Registered lints. The bool is true if the lint was
/// added by a plugin.
lints: Vec<(&'static Lint, bool)>,
/// Trait objects for each lint pass.
/// This is only `None` while performing a lint pass.
pre_expansion_passes: Option<Vec<EarlyLintPassObject>>,
early_passes: Option<Vec<EarlyLintPassObject>>,
late_passes: Lock<Option<Vec<LateLintPassObject>>>,
late_module_passes: Vec<LateLintPassObject>,
/// Lints indexed by name.
by_name: FxHashMap<String, TargetLint>,
/// Map of registered lint groups to what lints they expand to.
lint_groups: FxHashMap<&'static str, LintGroup>,
/// Extra info for future incompatibility lints, describing the
/// issue or RFC that caused the incompatibility.
future_incompatible: FxHashMap<LintId, FutureIncompatibleInfo>,
}
/// Lints that are buffered up early on in the `Session` before the
/// `LintLevels` is calculated
#[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub struct BufferedEarlyLint {
pub lint_id: LintId,
pub ast_id: ast::NodeId,
pub span: MultiSpan,
pub msg: String,
pub diagnostic: BuiltinLintDiagnostics,
}
/// Extra information for a future incompatibility lint. See the call
/// to `register_future_incompatible` in `librustc_lint/lib.rs` for
/// guidelines.
pub struct FutureIncompatibleInfo {
pub id: LintId,
/// e.g., a URL for an issue/PR/RFC or error code
pub reference: &'static str,
/// If this is an edition fixing lint, the edition in which
/// this lint becomes obsolete
pub edition: Option<edition::Edition>,
}
/// The target of the `by_name` map, which accounts for renaming/deprecation.
enum TargetLint {
/// A direct lint target
Id(LintId),
/// Temporary renaming, used for easing migration pain; see #16545
Renamed(String, LintId),
/// Lint with this name existed previously, but has been removed/deprecated.
/// The string argument is the reason for removal.
Removed(String),
}
pub enum FindLintError {
NotFound,
Removed,
}
struct LintAlias {
name: &'static str,
/// Whether deprecation warnings should be suppressed for this alias.
silent: bool,
}
struct LintGroup {
lint_ids: Vec<LintId>,
from_plugin: bool,
depr: Option<LintAlias>,
}
pub enum CheckLintNameResult<'a> {
Ok(&'a [LintId]),
/// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
NoLint(Option<Symbol>),
/// The lint is either renamed or removed. This is the warning
/// message, and an optional new name (`None` if removed).
Warning(String, Option<String>),
/// The lint is from a tool. If the Option is None, then either
/// the lint does not exist in the tool or the code was not
/// compiled with the tool and therefore the lint was never
/// added to the `LintStore`. Otherwise the `LintId` will be
/// returned as if it where a rustc lint.
Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
}
impl LintStore {
pub fn new() -> LintStore {
LintStore {
lints: vec![],
pre_expansion_passes: Some(vec![]),
early_passes: Some(vec![]),
late_passes: Lock::new(Some(vec![])),
late_module_passes: vec![],
by_name: Default::default(),
future_incompatible: Default::default(),
lint_groups: Default::default(),
}
}
pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] {
&self.lints
}
pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
self.lint_groups.iter()
.filter(|(_, LintGroup { depr, .. })| {
// Don't display deprecated lint groups.
depr.is_none()
})
.map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
(*k, lint_ids.clone(), *from_plugin)
})
.collect()
}
pub fn register_early_pass(&mut self,
sess: Option<&Session>,
from_plugin: bool,
register_only: bool,
pass: EarlyLintPassObject) {
self.push_pass(sess, from_plugin, &pass);
if !register_only {
self.early_passes.as_mut().unwrap().push(pass);
}
}
pub fn register_pre_expansion_pass(
&mut self,
sess: Option<&Session>,
from_plugin: bool,
register_only: bool,
pass: EarlyLintPassObject,
) {
self.push_pass(sess, from_plugin, &pass);
if !register_only {
self.pre_expansion_passes.as_mut().unwrap().push(pass);
}
}
pub fn register_late_pass(&mut self,
sess: Option<&Session>,
from_plugin: bool,
register_only: bool,
per_module: bool,
pass: LateLintPassObject) {
self.push_pass(sess, from_plugin, &pass);
if !register_only {
if per_module {
self.late_module_passes.push(pass);
} else {
self.late_passes.lock().as_mut().unwrap().push(pass);
}
}
}
// Helper method for register_early/late_pass
fn push_pass<P: LintPass + ?Sized + 'static>(&mut self,
sess: Option<&Session>,
from_plugin: bool,
pass: &Box<P>) {
for lint in pass.get_lints() {
self.lints.push((lint, from_plugin));
let id = LintId::of(lint);
if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
let msg = format!("duplicate specification of lint {}", lint.name_lower());
match (sess, from_plugin) {
// We load builtin lints first, so a duplicate is a compiler bug.
// Use early_error when handling -W help with no crate.
(None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
(Some(_), false) => bug!("{}", msg),
// A duplicate name from a plugin is a user error.
(Some(sess), true) => sess.err(&msg[..]),
}
}
}
}
pub fn register_future_incompatible(&mut self,
sess: Option<&Session>,
lints: Vec<FutureIncompatibleInfo>) {
for edition in edition::ALL_EDITIONS {
let lints = lints.iter().filter(|f| f.edition == Some(*edition)).map(|f| f.id)
.collect::<Vec<_>>();
if !lints.is_empty() {
self.register_group(sess, false, edition.lint_name(), None, lints)
}
}
let mut future_incompatible = Vec::with_capacity(lints.len());
for lint in lints {
future_incompatible.push(lint.id);
self.future_incompatible.insert(lint.id, lint);
}
self.register_group(
sess,
false,
"future_incompatible",
None,
future_incompatible,
);
}
pub fn future_incompatible(&self, id: LintId) -> Option<&FutureIncompatibleInfo> {
self.future_incompatible.get(&id)
}
pub fn register_group_alias(
&mut self,
lint_name: &'static str,
alias: &'static str,
) {
self.lint_groups.insert(alias, LintGroup {
lint_ids: vec![],
from_plugin: false,
depr: Some(LintAlias { name: lint_name, silent: true }),
});
}
pub fn register_group(
&mut self,
sess: Option<&Session>,
from_plugin: bool,
name: &'static str,
deprecated_name: Option<&'static str>,
to: Vec<LintId>,
) {
let new = self
.lint_groups
.insert(name, LintGroup {
lint_ids: to,
from_plugin,
depr: None,
})
.is_none();
if let Some(deprecated) = deprecated_name {
self.lint_groups.insert(deprecated, LintGroup {
lint_ids: vec![],
from_plugin,
depr: Some(LintAlias { name, silent: false }),
});
}
if !new {
let msg = format!("duplicate specification of lint group {}", name);
match (sess, from_plugin) {
// We load builtin lints first, so a duplicate is a compiler bug.
// Use early_error when handling -W help with no crate.
(None, _) => early_error(config::ErrorOutputType::default(), &msg[..]),
(Some(_), false) => bug!("{}", msg),
// A duplicate name from a plugin is a user error.
(Some(sess), true) => sess.err(&msg[..]),
}
}
}
pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
let target = match self.by_name.get(new_name) {
Some(&Id(lint_id)) => lint_id.clone(),
_ => bug!("invalid lint renaming of {} to {}", old_name, new_name)
};
self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
}
pub fn register_removed(&mut self, name: &str, reason: &str) {
self.by_name.insert(name.into(), Removed(reason.into()));
}
pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
match self.by_name.get(lint_name) {
Some(&Id(lint_id)) => Ok(vec![lint_id]),
Some(&Renamed(_, lint_id)) => {
Ok(vec![lint_id])
},
Some(&Removed(_)) => {
Err(FindLintError::Removed)
},
None => {
loop {
return match self.lint_groups.get(lint_name) {
Some(LintGroup {lint_ids, depr, .. }) => {
if let Some(LintAlias { name, .. }) = depr {
lint_name = name;
continue;
}
Ok(lint_ids.clone())
}
None => Err(FindLintError::Removed)
};
}
}
}
}
/// Checks the validity of lint names derived from the command line
pub fn check_lint_name_cmdline(&self,
sess: &Session,
lint_name: &str,
level: Level) {
let db = match self.check_lint_name(lint_name, None) {
CheckLintNameResult::Ok(_) => None,
CheckLintNameResult::Warning(ref msg, _) => {
Some(sess.struct_warn(msg))
},
CheckLintNameResult::NoLint(suggestion) => {
let mut err = struct_err!(sess, E0602, "unknown lint: `{}`", lint_name);
if let Some(suggestion) = suggestion {
err.help(&format!("did you mean: `{}`", suggestion));
}
Some(err)
}
CheckLintNameResult::Tool(result) => match result {
Err((Some(_), new_name)) => Some(sess.struct_warn(&format!(
"lint name `{}` is deprecated \
and does not have an effect anymore. \
Use: {}",
lint_name, new_name
))),
_ => None,
},
};
if let Some(mut db) = db {
let msg = format!("requested on the command line with `{} {}`",
match level {
Level::Allow => "-A",
Level::Warn => "-W",
Level::Deny => "-D",
Level::Forbid => "-F",
},
lint_name);
db.note(&msg);
db.emit();
}
}
/// Checks the name of a lint for its existence, and whether it was
/// renamed or removed. Generates a DiagnosticBuilder containing a
/// warning for renamed and removed lints. This is over both lint
/// names from attributes and those passed on the command line. Since
/// it emits non-fatal warnings and there are *two* lint passes that
/// inspect attributes, this is only run from the late pass to avoid
/// printing duplicate warnings.
pub fn check_lint_name(
&self,
lint_name: &str,
tool_name: Option<LocalInternedString>,
) -> CheckLintNameResult<'_> {
let complete_name = if let Some(tool_name) = tool_name {
format!("{}::{}", tool_name, lint_name)
} else {
lint_name.to_string()
};
// If the lint was scoped with `tool::` check if the tool lint exists
if let Some(_) = tool_name {
match self.by_name.get(&complete_name) {
None => match self.lint_groups.get(&*complete_name) {
None => return CheckLintNameResult::Tool(Err((None, String::new()))),
Some(LintGroup { lint_ids, .. }) => {
return CheckLintNameResult::Tool(Ok(&lint_ids));
}
},
Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
// If the lint was registered as removed or renamed by the lint tool, we don't need
// to treat tool_lints and rustc lints different and can use the code below.
_ => {}
}
}
match self.by_name.get(&complete_name) {
Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
format!(
"lint `{}` has been renamed to `{}`",
complete_name, new_name
),
Some(new_name.to_owned()),
),
Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
format!("lint `{}` has been removed: `{}`", complete_name, reason),
None,
),
None => match self.lint_groups.get(&*complete_name) {
// If neither the lint, nor the lint group exists check if there is a `clippy::`
// variant of this lint
None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
Some(LintGroup { lint_ids, depr, .. }) => {
// Check if the lint group name is deprecated
if let Some(LintAlias { name, silent }) = depr {
let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
return if *silent {
CheckLintNameResult::Ok(&lint_ids)
} else {
CheckLintNameResult::Tool(Err((
Some(&lint_ids),
name.to_string(),
)))
};
}
CheckLintNameResult::Ok(&lint_ids)
}
},
Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
}
}
fn check_tool_name_for_backwards_compat(
&self,
lint_name: &str,
tool_name: &str,
) -> CheckLintNameResult<'_> {
let complete_name = format!("{}::{}", tool_name, lint_name);
match self.by_name.get(&complete_name) {
None => match self.lint_groups.get(&*complete_name) {
// Now we are sure, that this lint exists nowhere
None => {
let symbols = self.by_name.keys()
.map(|name| Symbol::intern(&name))
.collect::<Vec<_>>();
let suggestion =
find_best_match_for_name(symbols.iter(), &lint_name.to_lowercase(), None);
CheckLintNameResult::NoLint(suggestion)
}
Some(LintGroup { lint_ids, depr, .. }) => {
// Reaching this would be weird, but let's cover this case anyway
if let Some(LintAlias { name, silent }) = depr {
let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
return if *silent {
CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
} else {
CheckLintNameResult::Tool(Err((
Some(&lint_ids),
name.to_string(),
)))
};
}
CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
}
},
Some(&Id(ref id)) => {
CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
}
_ => CheckLintNameResult::NoLint(None),
}
}
}
/// Context for lint checking after type checking.
pub struct LateContext<'a, 'tcx: 'a> {
/// Type context we're checking in.
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
/// Side-tables for the body we are in.
// FIXME: Make this lazy to avoid running the TypeckTables query?
pub tables: &'a ty::TypeckTables<'tcx>,
/// Parameter environment for the item we are in.
pub param_env: ty::ParamEnv<'tcx>,
/// Items accessible from the crate being checked.
pub access_levels: &'a AccessLevels,
/// The store of registered lints and the lint levels.
lint_store: ReadGuard<'a, LintStore>,
last_node_with_lint_attrs: hir::HirId,
/// Generic type parameters in scope for the item we are in.
pub generics: Option<&'tcx hir::Generics>,
/// We are only looking at one module
only_module: bool,
}
pub struct LateContextAndPass<'a, 'tcx: 'a, T: LateLintPass<'a, 'tcx>> {
context: LateContext<'a, 'tcx>,
pass: T,
}
/// Context for lint checking of the AST, after expansion, before lowering to
/// HIR.
pub struct EarlyContext<'a> {
/// Type context we're checking in.
pub sess: &'a Session,
/// The crate being checked.
pub krate: &'a ast::Crate,
builder: LintLevelsBuilder<'a>,
/// The store of registered lints and the lint levels.
lint_store: ReadGuard<'a, LintStore>,
buffered: LintBuffer,
}
pub struct EarlyContextAndPass<'a, T: EarlyLintPass> {
context: EarlyContext<'a>,
pass: T,
}
pub trait LintPassObject: Sized {}
impl LintPassObject for EarlyLintPassObject {}
impl LintPassObject for LateLintPassObject {}
pub trait LintContext<'tcx>: Sized {
type PassObject: LintPassObject;
fn sess(&self) -> &Session;
fn lints(&self) -> &LintStore;
fn lookup_and_emit<S: Into<MultiSpan>>(&self,
lint: &'static Lint,
span: Option<S>,
msg: &str) {
self.lookup(lint, span, msg).emit();
}
fn lookup_and_emit_with_diagnostics<S: Into<MultiSpan>>(&self,
lint: &'static Lint,
span: Option<S>,
msg: &str,
diagnostic: BuiltinLintDiagnostics) {
let mut db = self.lookup(lint, span, msg);
diagnostic.run(self.sess(), &mut db);
db.emit();
}
fn lookup<S: Into<MultiSpan>>(&self,
lint: &'static Lint,
span: Option<S>,
msg: &str)
-> DiagnosticBuilder<'_>;
/// Emit a lint at the appropriate level, for a particular span.
fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
self.lookup_and_emit(lint, Some(span), msg);
}
fn struct_span_lint<S: Into<MultiSpan>>(&self,
lint: &'static Lint,
span: S,
msg: &str)
-> DiagnosticBuilder<'_> {
self.lookup(lint, Some(span), msg)
}
/// Emit a lint and note at the appropriate level, for a particular span.
fn span_lint_note(&self, lint: &'static Lint, span: Span, msg: &str,
note_span: Span, note: &str) {
let mut err = self.lookup(lint, Some(span), msg);
if note_span == span {
err.note(note);
} else {
err.span_note(note_span, note);
}
err.emit();
}
/// Emit a lint and help at the appropriate level, for a particular span.
fn span_lint_help(&self, lint: &'static Lint, span: Span,
msg: &str, help: &str) {
let mut err = self.lookup(lint, Some(span), msg);
self.span_lint(lint, span, msg);
err.span_help(span, help);
err.emit();
}
/// Emit a lint at the appropriate level, with no associated span.
fn lint(&self, lint: &'static Lint, msg: &str) {
self.lookup_and_emit(lint, None as Option<Span>, msg);
}
}
impl<'a> EarlyContext<'a> {
fn new(
sess: &'a Session,
krate: &'a ast::Crate,
buffered: LintBuffer,
) -> EarlyContext<'a> {
EarlyContext {
sess,
krate,
lint_store: sess.lint_store.borrow(),
builder: LintLevelSets::builder(sess),
buffered,
}
}
}
macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
$cx.pass.$f(&$cx.context, $($args),*);
}) }
macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
$cx.pass.$f(&$cx.context, $($args),*);
}) }
impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
fn check_id(&mut self, id: ast::NodeId) {
for early_lint in self.context.buffered.take(id) {
self.context.lookup_and_emit_with_diagnostics(
early_lint.lint_id.lint,
Some(early_lint.span.clone()),
&early_lint.msg,
early_lint.diagnostic
);
}
}
/// Merge the lints specified by any lint attributes into the
/// current lint context, call the provided function, then reset the
/// lints in effect to their previous state.
fn with_lint_attrs<F>(&mut self,
id: ast::NodeId,
attrs: &'a [ast::Attribute],
f: F)
where F: FnOnce(&mut Self)
{
let push = self.context.builder.push(attrs);
self.check_id(id);
self.enter_attrs(attrs);
f(self);
self.exit_attrs(attrs);
self.context.builder.pop(push);
}
fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) {
debug!("early context: enter_attrs({:?})", attrs);
run_early_pass!(self, enter_lint_attrs, attrs);
}
fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) {
debug!("early context: exit_attrs({:?})", attrs);
run_early_pass!(self, exit_lint_attrs, attrs);
}
}
impl<'a, 'tcx> LintContext<'tcx> for LateContext<'a, 'tcx> {
type PassObject = LateLintPassObject;
/// Gets the overall compiler `Session` object.
fn sess(&self) -> &Session {
&self.tcx.sess
}
fn lints(&self) -> &LintStore {
&*self.lint_store
}
fn lookup<S: Into<MultiSpan>>(&self,
lint: &'static Lint,
span: Option<S>,
msg: &str)
-> DiagnosticBuilder<'_> {
let hir_id = self.last_node_with_lint_attrs;
match span {
Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, msg),
None => {
self.tcx.struct_lint_node(lint, hir_id, msg)
},
}
}
}
impl<'a> LintContext<'a> for EarlyContext<'a> {
type PassObject = EarlyLintPassObject;
/// Gets the overall compiler `Session` object.
fn sess(&self) -> &Session {
&self.sess
}
fn lints(&self) -> &LintStore {
&*self.lint_store
}
fn lookup<S: Into<MultiSpan>>(&self,
lint: &'static Lint,
span: Option<S>,
msg: &str)
-> DiagnosticBuilder<'_> {
self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
}
}
impl<'a, 'tcx> LateContext<'a, 'tcx> {
pub fn current_lint_root(&self) -> hir::HirId {
self.last_node_with_lint_attrs
}
/// Check if a `DefId`'s path matches the given absolute type path usage.
///
/// # Examples
/// ```rust,ignore (no `cx` or `def_id` available)
/// if cx.match_def_path(def_id, &["core", "option", "Option"]) {
/// // The given `def_id` is that of an `Option` type
/// }
/// ```
// Uplifted from rust-lang/rust-clippy
pub fn match_def_path(&self, def_id: DefId, path: &[&str]) -> bool {
let names = self.get_def_path(def_id);
names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| *a == *b)
}
/// Gets the absolute path of `def_id` as a vector of `&str`.
///
/// # Examples
/// ```rust,ignore (no `cx` or `def_id` available)
/// let def_path = cx.get_def_path(def_id);
/// if let &["core", "option", "Option"] = &def_path[..] {
/// // The given `def_id` is that of an `Option` type
/// }
/// ```
// Uplifted from rust-lang/rust-clippy
pub fn get_def_path(&self, def_id: DefId) -> Vec<LocalInternedString> {
pub struct AbsolutePathPrinter<'a, 'tcx> {
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
}
impl<'tcx> Printer<'tcx, 'tcx> for AbsolutePathPrinter<'_, 'tcx> {
type Error = !;
type Path = Vec<LocalInternedString>;
type Region = ();
type Type = ();
type DynExistential = ();
fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx> {
self.tcx
}
fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
Ok(())
}
fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
Ok(())
}
fn print_dyn_existential(
self,
_predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
) -> Result<Self::DynExistential, Self::Error> {
Ok(())
}
fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
Ok(vec![self.tcx.original_crate_name(cnum).as_str()])
}
fn path_qualified(
self,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<Self::Path, Self::Error> {
if trait_ref.is_none() {
if let ty::Adt(def, substs) = self_ty.sty {
return self.print_def_path(def.did, substs);
}
}
// This shouldn't ever be needed, but just in case:
Ok(vec![match trait_ref {
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)).as_str(),
None => Symbol::intern(&format!("<{}>", self_ty)).as_str(),
}])
}
fn path_append_impl(
self,
print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
_disambiguated_data: &DisambiguatedDefPathData,
self_ty: Ty<'tcx>,
trait_ref: Option<ty::TraitRef<'tcx>>,
) -> Result<Self::Path, Self::Error> {
let mut path = print_prefix(self)?;
// This shouldn't ever be needed, but just in case:
path.push(match trait_ref {
Some(trait_ref) => {
Symbol::intern(&format!("<impl {} for {}>", trait_ref, self_ty)).as_str()
},
None => Symbol::intern(&format!("<impl {}>", self_ty)).as_str(),
});
Ok(path)
}
fn path_append(
self,
print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
disambiguated_data: &DisambiguatedDefPathData,
) -> Result<Self::Path, Self::Error> {
let mut path = print_prefix(self)?;
// Skip `::{{constructor}}` on tuple/unit structs.
match disambiguated_data.data {
DefPathData::Ctor => return Ok(path),
_ => {}
}
path.push(disambiguated_data.data.as_interned_str().as_str());
Ok(path)
}
fn path_generic_args(
self,
print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
_args: &[Kind<'tcx>],
) -> Result<Self::Path, Self::Error> {
print_prefix(self)
}
}
AbsolutePathPrinter { tcx: self.tcx }
.print_def_path(def_id, &[])
.unwrap()
}
}
impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
type Ty = Ty<'tcx>;
type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
self.tcx.layout_of(self.param_env.and(ty))
}
}
impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> LateContextAndPass<'a, 'tcx, T> {
/// Merge the lints specified by any lint attributes into the
/// current lint context, call the provided function, then reset the
/// lints in effect to their previous state.
fn with_lint_attrs<F>(&mut self,
id: hir::HirId,
attrs: &'tcx [ast::Attribute],
f: F)
where F: FnOnce(&mut Self)
{
let prev = self.context.last_node_with_lint_attrs;
self.context.last_node_with_lint_attrs = id;
self.enter_attrs(attrs);
f(self);
self.exit_attrs(attrs);
self.context.last_node_with_lint_attrs = prev;
}
fn with_param_env<F>(&mut self, id: hir::HirId, f: F)
where F: FnOnce(&mut Self),
{
let old_param_env = self.context.param_env;
self.context.param_env = self.context.tcx.param_env(
self.context.tcx.hir().local_def_id_from_hir_id(id)
);
f(self);
self.context.param_env = old_param_env;
}
fn process_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: hir::HirId) {
lint_callback!(self, check_mod, m, s, n);
hir_visit::walk_mod(self, m, n);
lint_callback!(self, check_mod_post, m, s, n);
}
fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
debug!("late context: enter_attrs({:?})", attrs);
lint_callback!(self, enter_lint_attrs, attrs);
}
fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) {
debug!("late context: exit_attrs({:?})", attrs);
lint_callback!(self, exit_lint_attrs, attrs);
}
}
impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx>
for LateContextAndPass<'a, 'tcx, T> {
/// Because lints are scoped lexically, we want to walk nested
/// items in the context of the outer item, so enable
/// deep-walking.
fn nested_visit_map<'this>(&'this mut self) -> hir_visit::NestedVisitorMap<'this, 'tcx> {
hir_visit::NestedVisitorMap::All(&self.context.tcx.hir())
}
fn visit_nested_body(&mut self, body: hir::BodyId) {
let old_tables = self.context.tables;
self.context.tables = self.context.tcx.body_tables(body);
let body = self.context.tcx.hir().body(body);
self.visit_body(body);
self.context.tables = old_tables;
}
fn visit_body(&mut self, body: &'tcx hir::Body) {
lint_callback!(self, check_body, body);
hir_visit::walk_body(self, body);
lint_callback!(self, check_body_post, body);
}
fn visit_item(&mut self, it: &'tcx hir::Item) {
let generics = self.context.generics.take();
self.context.generics = it.node.generics();
self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
cx.with_param_env(it.hir_id, |cx| {
lint_callback!(cx, check_item, it);
hir_visit::walk_item(cx, it);
lint_callback!(cx, check_item_post, it);
});
});
self.context.generics = generics;
}
fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) {
self.with_lint_attrs(it.hir_id, &it.attrs, |cx| {
cx.with_param_env(it.hir_id, |cx| {
lint_callback!(cx, check_foreign_item, it);
hir_visit::walk_foreign_item(cx, it);
lint_callback!(cx, check_foreign_item_post, it);
});
})
}
fn visit_pat(&mut self, p: &'tcx hir::Pat) {
lint_callback!(self, check_pat, p);
hir_visit::walk_pat(self, p);
}
fn visit_expr(&mut self, e: &'tcx hir::Expr) {
self.with_lint_attrs(e.hir_id, &e.attrs, |cx| {
lint_callback!(cx, check_expr, e);
hir_visit::walk_expr(cx, e);
lint_callback!(cx, check_expr_post, e);
})
}