-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
builtin.rs
1854 lines (1655 loc) · 65.3 KB
/
builtin.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
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Lints in the Rust compiler.
//!
//! This contains lints which can feasibly be implemented as their own
//! AST visitor. Also see `rustc::lint::builtin`, which contains the
//! definitions of lints that are emitted directly inside the main
//! compiler.
//!
//! To add a new lint to rustc, declare it here using `declare_lint!()`.
//! Then add code to emit the new lint in the appropriate circumstances.
//! You can do that in an existing `LintPass` if it makes sense, or in a
//! new `LintPass`, or using `Session::add_lint` elsewhere in the
//! compiler. Only do the latter if the check can't be written cleanly as a
//! `LintPass` (also, note that such lints will need to be defined in
//! `rustc::lint::builtin`, not here).
//!
//! If you define a new `LintPass`, you will also need to add it to the
//! `add_builtin!` or `add_builtin_with_new!` invocation in `lib.rs`.
//! Use the former for unit-like structs and the latter for structs with
//! a `pub fn new()`.
use rustc::hir::def::Def;
use rustc::hir::def_id::DefId;
use rustc::ty::{self, Ty};
use hir::Node;
use util::nodemap::NodeSet;
use lint::{LateContext, LintContext, LintArray};
use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
use rustc::util::nodemap::FxHashSet;
use syntax::tokenstream::{TokenTree, TokenStream};
use syntax::ast;
use syntax::ptr::P;
use syntax::ast::Expr;
use syntax::attr;
use syntax::source_map::Spanned;
use syntax::edition::Edition;
use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
use syntax_pos::{BytePos, Span, SyntaxContext};
use syntax::symbol::keywords;
use syntax::errors::{Applicability, DiagnosticBuilder};
use syntax::print::pprust::expr_to_string;
use rustc::hir::{self, GenericParamKind, PatKind};
use rustc::hir::intravisit::FnKind;
use nonstandard_style::{MethodLateContext, method_context};
// hardwired lints from librustc
pub use lint::builtin::*;
declare_lint! {
WHILE_TRUE,
Warn,
"suggest using `loop { }` instead of `while true { }`"
}
#[derive(Copy, Clone)]
pub struct WhileTrue;
impl LintPass for WhileTrue {
fn get_lints(&self) -> LintArray {
lint_array!(WHILE_TRUE)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
if let hir::ExprKind::While(ref cond, ..) = e.node {
if let hir::ExprKind::Lit(ref lit) = cond.node {
if let ast::LitKind::Bool(true) = lit.node {
if lit.span.ctxt() == SyntaxContext::empty() {
let msg = "denote infinite loops with `loop { ... }`";
let condition_span = cx.tcx.sess.source_map().def_span(e.span);
let mut err = cx.struct_span_lint(WHILE_TRUE, condition_span, msg);
err.span_suggestion_short_with_applicability(
condition_span,
"use `loop`",
"loop".to_owned(),
Applicability::MachineApplicable
);
err.emit();
}
}
}
}
}
}
declare_lint! {
BOX_POINTERS,
Allow,
"use of owned (Box type) heap memory"
}
#[derive(Copy, Clone)]
pub struct BoxPointers;
impl BoxPointers {
fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
for leaf_ty in ty.walk() {
if leaf_ty.is_box() {
let m = format!("type uses owned (Box type) pointers: {}", ty);
cx.span_lint(BOX_POINTERS, span, &m);
}
}
}
}
impl LintPass for BoxPointers {
fn get_lints(&self) -> LintArray {
lint_array!(BOX_POINTERS)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
match it.node {
hir::ItemKind::Fn(..) |
hir::ItemKind::Ty(..) |
hir::ItemKind::Enum(..) |
hir::ItemKind::Struct(..) |
hir::ItemKind::Union(..) => {
let def_id = cx.tcx.hir().local_def_id(it.id);
self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
}
_ => ()
}
// If it's a struct, we also have to check the fields' types
match it.node {
hir::ItemKind::Struct(ref struct_def, _) |
hir::ItemKind::Union(ref struct_def, _) => {
for struct_field in struct_def.fields() {
let def_id = cx.tcx.hir().local_def_id(struct_field.id);
self.check_heap_type(cx, struct_field.span,
cx.tcx.type_of(def_id));
}
}
_ => (),
}
}
fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
let ty = cx.tables.node_id_to_type(e.hir_id);
self.check_heap_type(cx, e.span, ty);
}
}
declare_lint! {
NON_SHORTHAND_FIELD_PATTERNS,
Warn,
"using `Struct { x: x }` instead of `Struct { x }` in a pattern"
}
#[derive(Copy, Clone)]
pub struct NonShorthandFieldPatterns;
impl LintPass for NonShorthandFieldPatterns {
fn get_lints(&self) -> LintArray {
lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node {
let variant = cx.tables.pat_ty(pat).ty_adt_def()
.expect("struct pattern type is not an ADT")
.variant_of_def(cx.tables.qpath_def(qpath, pat.hir_id));
for fieldpat in field_pats {
if fieldpat.node.is_shorthand {
continue;
}
if fieldpat.span.ctxt().outer().expn_info().is_some() {
// Don't lint if this is a macro expansion: macro authors
// shouldn't have to worry about this kind of style issue
// (Issue #49588)
continue;
}
if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
if cx.tcx.find_field_index(ident, &variant) ==
Some(cx.tcx.field_index(fieldpat.node.id, cx.tables)) {
let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
fieldpat.span,
&format!("the `{}:` in this pattern is redundant", ident));
let subspan = cx.tcx.sess.source_map().span_through_char(fieldpat.span,
':');
err.span_suggestion_short_with_applicability(
subspan,
"remove this",
ident.to_string(),
Applicability::MachineApplicable
);
err.emit();
}
}
}
}
}
}
declare_lint! {
UNSAFE_CODE,
Allow,
"usage of `unsafe` code"
}
#[derive(Copy, Clone)]
pub struct UnsafeCode;
impl LintPass for UnsafeCode {
fn get_lints(&self) -> LintArray {
lint_array!(UNSAFE_CODE)
}
}
impl UnsafeCode {
fn report_unsafe(&self, cx: &LateContext, span: Span, desc: &'static str) {
// This comes from a macro that has #[allow_internal_unsafe].
if span.allows_unsafe() {
return;
}
cx.span_lint(UNSAFE_CODE, span, desc);
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
if let hir::ExprKind::Block(ref blk, _) = e.node {
// Don't warn about generated blocks, that'll just pollute the output.
if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
}
}
}
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
match it.node {
hir::ItemKind::Trait(_, hir::Unsafety::Unsafe, ..) => {
self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
}
hir::ItemKind::Impl(hir::Unsafety::Unsafe, ..) => {
self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
}
_ => return,
}
}
fn check_fn(&mut self,
cx: &LateContext,
fk: FnKind<'tcx>,
_: &hir::FnDecl,
_: &hir::Body,
span: Span,
_: ast::NodeId) {
match fk {
FnKind::ItemFn(_, _, hir::FnHeader { unsafety: hir::Unsafety::Unsafe, .. }, ..) => {
self.report_unsafe(cx, span, "declaration of an `unsafe` function")
}
FnKind::Method(_, sig, ..) => {
if sig.header.unsafety == hir::Unsafety::Unsafe {
self.report_unsafe(cx, span, "implementation of an `unsafe` method")
}
}
_ => (),
}
}
fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
if sig.header.unsafety == hir::Unsafety::Unsafe {
self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
}
}
}
}
declare_lint! {
pub MISSING_DOCS,
Allow,
"detects missing documentation for public members",
report_in_external_macro: true
}
pub struct MissingDoc {
/// Stack of whether #[doc(hidden)] is set
/// at each level which has lint attributes.
doc_hidden_stack: Vec<bool>,
/// Private traits or trait items that leaked through. Don't check their methods.
private_traits: FxHashSet<ast::NodeId>,
}
impl MissingDoc {
pub fn new() -> MissingDoc {
MissingDoc {
doc_hidden_stack: vec![false],
private_traits: FxHashSet::default(),
}
}
fn doc_hidden(&self) -> bool {
*self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
}
fn check_missing_docs_attrs(&self,
cx: &LateContext,
id: Option<ast::NodeId>,
attrs: &[ast::Attribute],
sp: Span,
desc: &'static str) {
// If we're building a test harness, then warning about
// documentation is probably not really relevant right now.
if cx.sess().opts.test {
return;
}
// `#[doc(hidden)]` disables missing_docs check.
if self.doc_hidden() {
return;
}
// Only check publicly-visible items, using the result from the privacy pass.
// It's an option so the crate root can also use this function (it doesn't
// have a NodeId).
if let Some(id) = id {
if !cx.access_levels.is_exported(id) {
return;
}
}
fn has_doc(attr: &ast::Attribute) -> bool {
if !attr.check_name("doc") {
return false;
}
if attr.is_value_str() {
return true;
}
if let Some(list) = attr.meta_item_list() {
for meta in list {
if meta.check_name("include") {
return true;
}
}
}
false
}
let has_doc = attrs.iter().any(|a| has_doc(a));
if !has_doc {
cx.span_lint(MISSING_DOCS,
cx.tcx.sess.source_map().def_span(sp),
&format!("missing documentation for {}", desc));
}
}
}
impl LintPass for MissingDoc {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_DOCS)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
let doc_hidden = self.doc_hidden() ||
attrs.iter().any(|attr| {
attr.check_name("doc") &&
match attr.meta_item_list() {
None => false,
Some(l) => attr::list_contains_name(&l, "hidden"),
}
});
self.doc_hidden_stack.push(doc_hidden);
}
fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
}
fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
}
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
let desc = match it.node {
hir::ItemKind::Fn(..) => "a function",
hir::ItemKind::Mod(..) => "a module",
hir::ItemKind::Enum(..) => "an enum",
hir::ItemKind::Struct(..) => "a struct",
hir::ItemKind::Union(..) => "a union",
hir::ItemKind::Trait(.., ref trait_item_refs) => {
// Issue #11592, traits are always considered exported, even when private.
if let hir::VisibilityKind::Inherited = it.vis.node {
self.private_traits.insert(it.id);
for trait_item_ref in trait_item_refs {
self.private_traits.insert(trait_item_ref.id.node_id);
}
return;
}
"a trait"
}
hir::ItemKind::Ty(..) => "a type alias",
hir::ItemKind::Impl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
// If the trait is private, add the impl items to private_traits so they don't get
// reported for missing docs.
let real_trait = trait_ref.path.def.def_id();
if let Some(node_id) = cx.tcx.hir().as_local_node_id(real_trait) {
match cx.tcx.hir().find(node_id) {
Some(Node::Item(item)) => {
if let hir::VisibilityKind::Inherited = item.vis.node {
for impl_item_ref in impl_item_refs {
self.private_traits.insert(impl_item_ref.id.node_id);
}
}
}
_ => {}
}
}
return;
}
hir::ItemKind::Const(..) => "a constant",
hir::ItemKind::Static(..) => "a static",
_ => return,
};
self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
}
fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
if self.private_traits.contains(&trait_item.id) {
return;
}
let desc = match trait_item.node {
hir::TraitItemKind::Const(..) => "an associated constant",
hir::TraitItemKind::Method(..) => "a trait method",
hir::TraitItemKind::Type(..) => "an associated type",
};
self.check_missing_docs_attrs(cx,
Some(trait_item.id),
&trait_item.attrs,
trait_item.span,
desc);
}
fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
// If the method is an impl for a trait, don't doc.
if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
return;
}
let desc = match impl_item.node {
hir::ImplItemKind::Const(..) => "an associated constant",
hir::ImplItemKind::Method(..) => "a method",
hir::ImplItemKind::Type(_) => "an associated type",
hir::ImplItemKind::Existential(_) => "an associated existential type",
};
self.check_missing_docs_attrs(cx,
Some(impl_item.id),
&impl_item.attrs,
impl_item.span,
desc);
}
fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
if !sf.is_positional() {
self.check_missing_docs_attrs(cx,
Some(sf.id),
&sf.attrs,
sf.span,
"a struct field")
}
}
fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
self.check_missing_docs_attrs(cx,
Some(v.node.data.id()),
&v.node.attrs,
v.span,
"a variant");
}
}
declare_lint! {
pub MISSING_COPY_IMPLEMENTATIONS,
Allow,
"detects potentially-forgotten implementations of `Copy`"
}
#[derive(Copy, Clone)]
pub struct MissingCopyImplementations;
impl LintPass for MissingCopyImplementations {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_COPY_IMPLEMENTATIONS)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
if !cx.access_levels.is_reachable(item.id) {
return;
}
let (def, ty) = match item.node {
hir::ItemKind::Struct(_, ref ast_generics) => {
if !ast_generics.params.is_empty() {
return;
}
let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.id));
(def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
}
hir::ItemKind::Union(_, ref ast_generics) => {
if !ast_generics.params.is_empty() {
return;
}
let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.id));
(def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
}
hir::ItemKind::Enum(_, ref ast_generics) => {
if !ast_generics.params.is_empty() {
return;
}
let def = cx.tcx.adt_def(cx.tcx.hir().local_def_id(item.id));
(def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
}
_ => return,
};
if def.has_dtor(cx.tcx) {
return;
}
let param_env = ty::ParamEnv::empty();
if !ty.moves_by_default(cx.tcx, param_env, item.span) {
return;
}
if param_env.can_type_implement_copy(cx.tcx, ty).is_ok() {
cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
item.span,
"type could implement `Copy`; consider adding `impl \
Copy`")
}
}
}
declare_lint! {
MISSING_DEBUG_IMPLEMENTATIONS,
Allow,
"detects missing implementations of fmt::Debug"
}
pub struct MissingDebugImplementations {
impling_types: Option<NodeSet>,
}
impl MissingDebugImplementations {
pub fn new() -> MissingDebugImplementations {
MissingDebugImplementations { impling_types: None }
}
}
impl LintPass for MissingDebugImplementations {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
if !cx.access_levels.is_reachable(item.id) {
return;
}
match item.node {
hir::ItemKind::Struct(..) |
hir::ItemKind::Union(..) |
hir::ItemKind::Enum(..) => {}
_ => return,
}
let debug = match cx.tcx.lang_items().debug_trait() {
Some(debug) => debug,
None => return,
};
if self.impling_types.is_none() {
let mut impls = NodeSet::default();
cx.tcx.for_each_impl(debug, |d| {
if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
if let Some(node_id) = cx.tcx.hir().as_local_node_id(ty_def.did) {
impls.insert(node_id);
}
}
});
self.impling_types = Some(impls);
debug!("{:?}", self.impling_types);
}
if !self.impling_types.as_ref().unwrap().contains(&item.id) {
cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
item.span,
"type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
or a manual implementation")
}
}
}
declare_lint! {
pub ANONYMOUS_PARAMETERS,
Allow,
"detects anonymous parameters"
}
/// Checks for use of anonymous parameters (RFC 1685)
#[derive(Clone)]
pub struct AnonymousParameters;
impl LintPass for AnonymousParameters {
fn get_lints(&self) -> LintArray {
lint_array!(ANONYMOUS_PARAMETERS)
}
}
impl EarlyLintPass for AnonymousParameters {
fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
match it.node {
ast::TraitItemKind::Method(ref sig, _) => {
for arg in sig.decl.inputs.iter() {
match arg.pat.node {
ast::PatKind::Ident(_, ident, None) => {
if ident.name == keywords::Invalid.name() {
let ty_snip = cx
.sess
.source_map()
.span_to_snippet(arg.ty.span);
let (ty_snip, appl) = if let Ok(snip) = ty_snip {
(snip, Applicability::MachineApplicable)
} else {
("<type>".to_owned(), Applicability::HasPlaceholders)
};
cx.struct_span_lint(
ANONYMOUS_PARAMETERS,
arg.pat.span,
"anonymous parameters are deprecated and will be \
removed in the next edition."
).span_suggestion_with_applicability(
arg.pat.span,
"Try naming the parameter or explicitly \
ignoring it",
format!("_: {}", ty_snip),
appl
).emit();
}
}
_ => (),
}
}
},
_ => (),
}
}
}
/// Checks for incorrect use use of `repr` attributes.
#[derive(Clone)]
pub struct BadRepr;
impl LintPass for BadRepr {
fn get_lints(&self) -> LintArray {
lint_array!()
}
}
impl EarlyLintPass for BadRepr {
fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
if attr.name() == "repr" {
let list = attr.meta_item_list();
let repr_str = |lit: &str| { format!("#[repr({})]", lit) };
// Emit warnings with `repr` either has a literal assignment (`#[repr = "C"]`) or
// no hints (``#[repr]`)
let has_hints = list.as_ref().map(|ref list| !list.is_empty()).unwrap_or(false);
if !has_hints {
let mut suggested = false;
let mut warn = if let Some(ref lit) = attr.value_str() {
// avoid warning about empty `repr` on `#[repr = "foo"]`
let mut warn = cx.struct_span_lint(
BAD_REPR,
attr.span,
"`repr` attribute isn't configurable with a literal",
);
match lit.to_string().as_ref() {
| "C" | "packed" | "rust" | "transparent"
| "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
| "i8" | "i16" | "i32" | "i64" | "i128" | "isize" => {
// if the literal could have been a valid `repr` arg,
// suggest the correct syntax
warn.span_suggestion_with_applicability(
attr.span,
"give `repr` a hint",
repr_str(&lit.as_str()),
Applicability::MachineApplicable
);
suggested = true;
}
_ => { // the literal wasn't a valid `repr` arg
warn.span_label(attr.span, "needs a hint");
}
};
warn
} else {
let mut warn = cx.struct_span_lint(
BAD_REPR,
attr.span,
"`repr` attribute must have a hint",
);
warn.span_label(attr.span, "needs a hint");
warn
};
if !suggested {
warn.help(&format!(
"valid hints include `{}`, `{}`, `{}` and `{}`",
repr_str("C"),
repr_str("packed"),
repr_str("rust"),
repr_str("transparent"),
));
warn.note("for more information, visit \
<https://doc.rust-lang.org/reference/type-layout.html>");
}
warn.emit();
}
}
}
}
/// Checks for use of attributes which have been deprecated.
#[derive(Clone)]
pub struct DeprecatedAttr {
// This is not free to compute, so we want to keep it around, rather than
// compute it for every attribute.
depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
}
impl DeprecatedAttr {
pub fn new() -> DeprecatedAttr {
DeprecatedAttr {
depr_attrs: deprecated_attributes(),
}
}
}
impl LintPass for DeprecatedAttr {
fn get_lints(&self) -> LintArray {
lint_array!()
}
}
impl EarlyLintPass for DeprecatedAttr {
fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
for &&(n, _, ref g) in &self.depr_attrs {
if attr.name() == n {
if let &AttributeGate::Gated(Stability::Deprecated(link, suggestion),
ref name,
ref reason,
_) = g {
let msg = format!("use of deprecated attribute `{}`: {}. See {}",
name, reason, link);
let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
err.span_suggestion_short_with_applicability(
attr.span,
suggestion.unwrap_or("remove this attribute"),
String::new(),
Applicability::MachineApplicable
);
err.emit();
}
return;
}
}
}
}
declare_lint! {
pub UNUSED_DOC_COMMENTS,
Warn,
"detects doc comments that aren't used by rustdoc"
}
#[derive(Copy, Clone)]
pub struct UnusedDocComment;
impl LintPass for UnusedDocComment {
fn get_lints(&self) -> LintArray {
lint_array![UNUSED_DOC_COMMENTS]
}
}
impl UnusedDocComment {
fn warn_if_doc<'a, 'tcx,
I: Iterator<Item=&'a ast::Attribute>,
C: LintContext<'tcx>>(&self, mut attrs: I, cx: &C) {
if let Some(attr) = attrs.find(|a| a.is_value_str() && a.check_name("doc")) {
cx.struct_span_lint(UNUSED_DOC_COMMENTS, attr.span, "doc comment not used by rustdoc")
.emit();
}
}
}
impl EarlyLintPass for UnusedDocComment {
fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) {
self.warn_if_doc(decl.attrs.iter(), cx);
}
fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) {
self.warn_if_doc(arm.attrs.iter(), cx);
}
fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
self.warn_if_doc(expr.attrs.iter(), cx);
}
}
declare_lint! {
PLUGIN_AS_LIBRARY,
Warn,
"compiler plugin used as ordinary library in non-plugin crate"
}
#[derive(Copy, Clone)]
pub struct PluginAsLibrary;
impl LintPass for PluginAsLibrary {
fn get_lints(&self) -> LintArray {
lint_array![PLUGIN_AS_LIBRARY]
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
if cx.sess().plugin_registrar_fn.get().is_some() {
// We're compiling a plugin; it's fine to link other plugins.
return;
}
match it.node {
hir::ItemKind::ExternCrate(..) => (),
_ => return,
};
let def_id = cx.tcx.hir().local_def_id(it.id);
let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
None => {
// Probably means we aren't linking the crate for some reason.
//
// Not sure if / when this could happen.
return;
}
};
if prfn.is_some() {
cx.span_lint(PLUGIN_AS_LIBRARY,
it.span,
"compiler plugin used as an ordinary library");
}
}
}
declare_lint! {
NO_MANGLE_CONST_ITEMS,
Deny,
"const items will not have their symbols exported"
}
declare_lint! {
NO_MANGLE_GENERIC_ITEMS,
Warn,
"generic items must be mangled"
}
#[derive(Copy, Clone)]
pub struct InvalidNoMangleItems;
impl LintPass for InvalidNoMangleItems {
fn get_lints(&self) -> LintArray {
lint_array!(NO_MANGLE_CONST_ITEMS,
NO_MANGLE_GENERIC_ITEMS)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
match it.node {
hir::ItemKind::Fn(.., ref generics, _) => {
if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
for param in &generics.params {
match param.kind {
GenericParamKind::Lifetime { .. } => {}
GenericParamKind::Type { .. } => {
let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
it.span,
"functions generic over \
types must be mangled");
err.span_suggestion_short_with_applicability(
no_mangle_attr.span,
"remove this attribute",
String::new(),
// Use of `#[no_mangle]` suggests FFI intent; correct
// fix may be to monomorphize source by hand
Applicability::MaybeIncorrect
);
err.emit();
break;
}
}
}
}
}
hir::ItemKind::Const(..) => {
if attr::contains_name(&it.attrs, "no_mangle") {
// Const items do not refer to a particular location in memory, and therefore
// don't have anything to attach a symbol to
let msg = "const items should never be #[no_mangle]";
let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
// account for "pub const" (#45562)
let start = cx.tcx.sess.source_map().span_to_snippet(it.span)
.map(|snippet| snippet.find("const").unwrap_or(0))
.unwrap_or(0) as u32;
// `const` is 5 chars
let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
err.span_suggestion_with_applicability(
const_span,
"try a static value",
"pub static".to_owned(),
Applicability::MachineApplicable
);
err.emit();
}
}
_ => {}
}
}
}
#[derive(Clone, Copy)]
pub struct MutableTransmutes;
declare_lint! {
MUTABLE_TRANSMUTES,
Deny,
"mutating transmuted &mut T from &T may cause undefined behavior"
}
impl LintPass for MutableTransmutes {
fn get_lints(&self) -> LintArray {
lint_array!(MUTABLE_TRANSMUTES)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
use rustc_target::spec::abi::Abi::RustIntrinsic;
let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
consider instead using an UnsafeCell";
match get_transmute_from_to(cx, expr) {
Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => {
if to_mt == hir::Mutability::MutMutable &&
from_mt == hir::Mutability::MutImmutable {
cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
}
}
_ => (),
}