-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
ast_validation.rs
1861 lines (1737 loc) · 74.5 KB
/
ast_validation.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
// Validate AST before lowering it to HIR.
//
// This pass is supposed to catch things that fit into AST data structures,
// but not permitted by the language. It runs after expansion when AST is frozen,
// so it can check for erroneous constructions produced by syntax extensions.
// This pass is supposed to perform only simple checks not requiring name resolution
// or type checking or some other kind of complex analysis.
use itertools::{Either, Itertools};
use rustc_ast::ptr::P;
use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor};
use rustc_ast::walk_list;
use rustc_ast::*;
use rustc_ast_pretty::pprust::{self, State};
use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{error_code, pluralize, struct_span_err, Applicability};
use rustc_parse::validate_attr;
use rustc_session::lint::builtin::{
DEPRECATED_WHERE_CLAUSE_LOCATION, MISSING_ABI, PATTERNS_IN_FNS_WITHOUT_BODY,
};
use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
use rustc_session::Session;
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, sym, Ident};
use rustc_span::Span;
use rustc_target::spec::abi;
use std::mem;
use std::ops::{Deref, DerefMut};
const MORE_EXTERN: &str =
"for more information, visit https://doc.rust-lang.org/std/keyword.extern.html";
/// Is `self` allowed semantically as the first parameter in an `FnDecl`?
enum SelfSemantic {
Yes,
No,
}
struct AstValidator<'a> {
session: &'a Session,
/// The span of the `extern` in an `extern { ... }` block, if any.
extern_mod: Option<&'a Item>,
/// Are we inside a trait impl?
in_trait_impl: bool,
in_const_trait_impl: bool,
has_proc_macro_decls: bool,
/// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
/// Nested `impl Trait` _is_ allowed in associated type position,
/// e.g., `impl Iterator<Item = impl Debug>`.
outer_impl_trait: Option<Span>,
is_tilde_const_allowed: bool,
/// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
/// or `Foo::Bar<impl Trait>`
is_impl_trait_banned: bool,
/// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
/// certain positions.
is_assoc_ty_bound_banned: bool,
/// See [ForbiddenLetReason]
forbidden_let_reason: Option<ForbiddenLetReason>,
lint_buffer: &'a mut LintBuffer,
}
impl<'a> AstValidator<'a> {
fn with_in_trait_impl(
&mut self,
is_in: bool,
constness: Option<Const>,
f: impl FnOnce(&mut Self),
) {
let old = mem::replace(&mut self.in_trait_impl, is_in);
let old_const =
mem::replace(&mut self.in_const_trait_impl, matches!(constness, Some(Const::Yes(_))));
f(self);
self.in_trait_impl = old;
self.in_const_trait_impl = old_const;
}
fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
let old = mem::replace(&mut self.is_impl_trait_banned, true);
f(self);
self.is_impl_trait_banned = old;
}
fn with_tilde_const(&mut self, allowed: bool, f: impl FnOnce(&mut Self)) {
let old = mem::replace(&mut self.is_tilde_const_allowed, allowed);
f(self);
self.is_tilde_const_allowed = old;
}
fn with_tilde_const_allowed(&mut self, f: impl FnOnce(&mut Self)) {
self.with_tilde_const(true, f)
}
fn with_banned_tilde_const(&mut self, f: impl FnOnce(&mut Self)) {
self.with_tilde_const(false, f)
}
fn with_let_management(
&mut self,
forbidden_let_reason: Option<ForbiddenLetReason>,
f: impl FnOnce(&mut Self, Option<ForbiddenLetReason>),
) {
let old = mem::replace(&mut self.forbidden_let_reason, forbidden_let_reason);
f(self, old);
self.forbidden_let_reason = old;
}
/// Emits an error banning the `let` expression provided in the given location.
fn ban_let_expr(&self, expr: &'a Expr, forbidden_let_reason: ForbiddenLetReason) {
let sess = &self.session;
if sess.opts.unstable_features.is_nightly_build() {
let err = "`let` expressions are not supported here";
let mut diag = sess.struct_span_err(expr.span, err);
diag.note("only supported directly in conditions of `if` and `while` expressions");
match forbidden_let_reason {
ForbiddenLetReason::GenericForbidden => {}
ForbiddenLetReason::NotSupportedOr(span) => {
diag.span_note(
span,
"`||` operators are not supported in let chain expressions",
);
}
ForbiddenLetReason::NotSupportedParentheses(span) => {
diag.span_note(
span,
"`let`s wrapped in parentheses are not supported in a context with let \
chains",
);
}
}
diag.emit();
} else {
sess.struct_span_err(expr.span, "expected expression, found statement (`let`)")
.note("variable declaration using `let` is a statement")
.emit();
}
}
fn check_gat_where(
&mut self,
id: NodeId,
before_predicates: &[WherePredicate],
where_clauses: (ast::TyAliasWhereClause, ast::TyAliasWhereClause),
) {
if !before_predicates.is_empty() {
let mut state = State::new();
if !where_clauses.1.0 {
state.space();
state.word_space("where");
} else {
state.word_space(",");
}
let mut first = true;
for p in before_predicates.iter() {
if !first {
state.word_space(",");
}
first = false;
state.print_where_predicate(p);
}
let suggestion = state.s.eof();
self.lint_buffer.buffer_lint_with_diagnostic(
DEPRECATED_WHERE_CLAUSE_LOCATION,
id,
where_clauses.0.1,
"where clause not allowed here",
BuiltinLintDiagnostics::DeprecatedWhereclauseLocation(
where_clauses.1.1.shrink_to_hi(),
suggestion,
),
);
}
}
fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) {
let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true);
f(self);
self.is_assoc_ty_bound_banned = old;
}
fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
let old = mem::replace(&mut self.outer_impl_trait, outer);
if outer.is_some() {
self.with_banned_tilde_const(f);
} else {
f(self);
}
self.outer_impl_trait = old;
}
fn visit_assoc_constraint_from_generic_args(&mut self, constraint: &'a AssocConstraint) {
match constraint.kind {
AssocConstraintKind::Equality { .. } => {}
AssocConstraintKind::Bound { .. } => {
if self.is_assoc_ty_bound_banned {
self.err_handler().span_err(
constraint.span,
"associated type bounds are not allowed within structs, enums, or unions",
);
}
}
}
self.visit_assoc_constraint(constraint);
}
// Mirrors `visit::walk_ty`, but tracks relevant state.
fn walk_ty(&mut self, t: &'a Ty) {
match t.kind {
TyKind::ImplTrait(..) => {
self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
}
TyKind::TraitObject(..) => self.with_banned_tilde_const(|this| visit::walk_ty(this, t)),
TyKind::Path(ref qself, ref path) => {
// We allow these:
// - `Option<impl Trait>`
// - `option::Option<impl Trait>`
// - `option::Option<T>::Foo<impl Trait>
//
// But not these:
// - `<impl Trait>::Foo`
// - `option::Option<impl Trait>::Foo`.
//
// To implement this, we disallow `impl Trait` from `qself`
// (for cases like `<impl Trait>::Foo>`)
// but we allow `impl Trait` in `GenericArgs`
// iff there are no more PathSegments.
if let Some(ref qself) = *qself {
// `impl Trait` in `qself` is always illegal
self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
}
// Note that there should be a call to visit_path here,
// so if any logic is added to process `Path`s a call to it should be
// added both in visit_path and here. This code mirrors visit::walk_path.
for (i, segment) in path.segments.iter().enumerate() {
// Allow `impl Trait` iff we're on the final path segment
if i == path.segments.len() - 1 {
self.visit_path_segment(path.span, segment);
} else {
self.with_banned_impl_trait(|this| {
this.visit_path_segment(path.span, segment)
});
}
}
}
_ => visit::walk_ty(self, t),
}
}
fn visit_struct_field_def(&mut self, field: &'a FieldDef) {
if let Some(ident) = field.ident {
if ident.name == kw::Underscore {
self.visit_vis(&field.vis);
self.visit_ident(ident);
self.visit_ty_common(&field.ty);
self.walk_ty(&field.ty);
walk_list!(self, visit_attribute, &field.attrs);
return;
}
}
self.visit_field_def(field);
}
fn err_handler(&self) -> &rustc_errors::Handler {
&self.session.diagnostic()
}
fn check_lifetime(&self, ident: Ident) {
let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Empty];
if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
}
}
fn check_label(&self, ident: Ident) {
if ident.without_first_quote().is_reserved() {
self.err_handler()
.span_err(ident.span, &format!("invalid label name `{}`", ident.name));
}
}
fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
if let VisibilityKind::Inherited = vis.kind {
return;
}
let mut err =
struct_span_err!(self.session, vis.span, E0449, "unnecessary visibility qualifier");
if vis.kind.is_pub() {
err.span_label(vis.span, "`pub` not permitted here because it's implied");
}
if let Some(note) = note {
err.note(note);
}
err.emit();
}
fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, Option<Ident>, bool)) {
for Param { pat, .. } in &decl.inputs {
match pat.kind {
PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, None) | PatKind::Wild => {}
PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ident, None) => {
report_err(pat.span, Some(ident), true)
}
_ => report_err(pat.span, None, false),
}
}
}
fn check_trait_fn_not_async(&self, fn_span: Span, asyncness: Async) {
if let Async::Yes { span, .. } = asyncness {
struct_span_err!(
self.session,
fn_span,
E0706,
"functions in traits cannot be declared `async`"
)
.span_label(span, "`async` because of this")
.note("`async` trait functions are not currently supported")
.note("consider using the `async-trait` crate: https://crates.io/crates/async-trait")
.emit();
}
}
fn check_trait_fn_not_const(&self, constness: Const) {
if let Const::Yes(span) = constness {
struct_span_err!(
self.session,
span,
E0379,
"functions in traits cannot be declared const"
)
.span_label(span, "functions in traits cannot be const")
.emit();
}
}
fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
// Check only lifetime parameters are present and that the lifetime
// parameters that are present have no bounds.
let non_lt_param_spans: Vec<_> = params
.iter()
.filter_map(|param| match param.kind {
GenericParamKind::Lifetime { .. } => {
if !param.bounds.is_empty() {
let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
self.err_handler()
.span_err(spans, "lifetime bounds cannot be used in this context");
}
None
}
_ => Some(param.ident.span),
})
.collect();
if !non_lt_param_spans.is_empty() {
self.err_handler().span_err(
non_lt_param_spans,
"only lifetime parameters can be used in this context",
);
}
}
fn check_fn_decl(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
self.check_decl_num_args(fn_decl);
self.check_decl_cvaradic_pos(fn_decl);
self.check_decl_attrs(fn_decl);
self.check_decl_self_param(fn_decl, self_semantic);
}
/// Emits fatal error if function declaration has more than `u16::MAX` arguments
/// Error is fatal to prevent errors during typechecking
fn check_decl_num_args(&self, fn_decl: &FnDecl) {
let max_num_args: usize = u16::MAX.into();
if fn_decl.inputs.len() > max_num_args {
let Param { span, .. } = fn_decl.inputs[0];
self.err_handler().span_fatal(
span,
&format!("function can not have more than {} arguments", max_num_args),
);
}
}
fn check_decl_cvaradic_pos(&self, fn_decl: &FnDecl) {
match &*fn_decl.inputs {
[Param { ty, span, .. }] => {
if let TyKind::CVarArgs = ty.kind {
self.err_handler().span_err(
*span,
"C-variadic function must be declared with at least one named argument",
);
}
}
[ps @ .., _] => {
for Param { ty, span, .. } in ps {
if let TyKind::CVarArgs = ty.kind {
self.err_handler().span_err(
*span,
"`...` must be the last argument of a C-variadic function",
);
}
}
}
_ => {}
}
}
fn check_decl_attrs(&self, fn_decl: &FnDecl) {
fn_decl
.inputs
.iter()
.flat_map(|i| i.attrs.as_ref())
.filter(|attr| {
let arr = [
sym::allow,
sym::cfg,
sym::cfg_attr,
sym::deny,
sym::expect,
sym::forbid,
sym::warn,
];
!arr.contains(&attr.name_or_empty()) && rustc_attr::is_builtin_attr(attr)
})
.for_each(|attr| {
if attr.is_doc_comment() {
self.err_handler()
.struct_span_err(
attr.span,
"documentation comments cannot be applied to function parameters",
)
.span_label(attr.span, "doc comments are not allowed here")
.emit();
} else {
self.err_handler().span_err(
attr.span,
"allow, cfg, cfg_attr, deny, expect, \
forbid, and warn are the only allowed built-in attributes in function parameters",
);
}
});
}
fn check_decl_self_param(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
if let (SelfSemantic::No, [param, ..]) = (self_semantic, &*fn_decl.inputs) {
if param.is_self() {
self.err_handler()
.struct_span_err(
param.span,
"`self` parameter is only allowed in associated functions",
)
.span_label(param.span, "not semantically valid as function parameter")
.note("associated functions are those in `impl` or `trait` definitions")
.emit();
}
}
}
fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
if let Defaultness::Default(def_span) = defaultness {
let span = self.session.source_map().guess_head_span(span);
self.err_handler()
.struct_span_err(span, "`default` is only allowed on items in trait impls")
.span_label(def_span, "`default` because of this")
.emit();
}
}
fn error_item_without_body(&self, sp: Span, ctx: &str, msg: &str, sugg: &str) {
let source_map = self.session.source_map();
let end = source_map.end_point(sp);
let replace_span = if source_map.span_to_snippet(end).map(|s| s == ";").unwrap_or(false) {
end
} else {
sp.shrink_to_hi()
};
self.err_handler()
.struct_span_err(sp, msg)
.span_suggestion(
replace_span,
&format!("provide a definition for the {}", ctx),
sugg,
Applicability::HasPlaceholders,
)
.emit();
}
fn check_impl_item_provided<T>(&self, sp: Span, body: &Option<T>, ctx: &str, sugg: &str) {
if body.is_none() {
let msg = format!("associated {} in `impl` without body", ctx);
self.error_item_without_body(sp, ctx, &msg, sugg);
}
}
fn check_type_no_bounds(&self, bounds: &[GenericBound], ctx: &str) {
let span = match bounds {
[] => return,
[b0] => b0.span(),
[b0, .., bl] => b0.span().to(bl.span()),
};
self.err_handler()
.struct_span_err(span, &format!("bounds on `type`s in {} have no effect", ctx))
.emit();
}
fn check_foreign_ty_genericless(&self, generics: &Generics, where_span: Span) {
let cannot_have = |span, descr, remove_descr| {
self.err_handler()
.struct_span_err(
span,
&format!("`type`s inside `extern` blocks cannot have {}", descr),
)
.span_suggestion(
span,
&format!("remove the {}", remove_descr),
"",
Applicability::MaybeIncorrect,
)
.span_label(self.current_extern_span(), "`extern` block begins here")
.note(MORE_EXTERN)
.emit();
};
if !generics.params.is_empty() {
cannot_have(generics.span, "generic parameters", "generic parameters");
}
if !generics.where_clause.predicates.is_empty() {
cannot_have(where_span, "`where` clauses", "`where` clause");
}
}
fn check_foreign_kind_bodyless(&self, ident: Ident, kind: &str, body: Option<Span>) {
let Some(body) = body else {
return;
};
self.err_handler()
.struct_span_err(ident.span, &format!("incorrect `{}` inside `extern` block", kind))
.span_label(ident.span, "cannot have a body")
.span_label(body, "the invalid body")
.span_label(
self.current_extern_span(),
format!(
"`extern` blocks define existing foreign {0}s and {0}s \
inside of them cannot have a body",
kind
),
)
.note(MORE_EXTERN)
.emit();
}
/// An `fn` in `extern { ... }` cannot have a body `{ ... }`.
fn check_foreign_fn_bodyless(&self, ident: Ident, body: Option<&Block>) {
let Some(body) = body else {
return;
};
self.err_handler()
.struct_span_err(ident.span, "incorrect function inside `extern` block")
.span_label(ident.span, "cannot have a body")
.span_suggestion(
body.span,
"remove the invalid body",
";",
Applicability::MaybeIncorrect,
)
.help(
"you might have meant to write a function accessible through FFI, \
which can be done by writing `extern fn` outside of the `extern` block",
)
.span_label(
self.current_extern_span(),
"`extern` blocks define existing foreign functions and functions \
inside of them cannot have a body",
)
.note(MORE_EXTERN)
.emit();
}
fn current_extern_span(&self) -> Span {
self.session.source_map().guess_head_span(self.extern_mod.unwrap().span)
}
/// An `fn` in `extern { ... }` cannot have qualifiers, e.g. `async fn`.
fn check_foreign_fn_headerless(&self, ident: Ident, span: Span, header: FnHeader) {
if header.has_qualifiers() {
self.err_handler()
.struct_span_err(ident.span, "functions in `extern` blocks cannot have qualifiers")
.span_label(self.current_extern_span(), "in this `extern` block")
.span_suggestion_verbose(
span.until(ident.span.shrink_to_lo()),
"remove the qualifiers",
"fn ",
Applicability::MaybeIncorrect,
)
.emit();
}
}
/// An item in `extern { ... }` cannot use non-ascii identifier.
fn check_foreign_item_ascii_only(&self, ident: Ident) {
if !ident.as_str().is_ascii() {
let n = 83942;
self.err_handler()
.struct_span_err(
ident.span,
"items in `extern` blocks cannot use non-ascii identifiers",
)
.span_label(self.current_extern_span(), "in this `extern` block")
.note(&format!(
"this limitation may be lifted in the future; see issue #{} <https://github.com/rust-lang/rust/issues/{}> for more information",
n, n,
))
.emit();
}
}
/// Reject C-variadic type unless the function is foreign,
/// or free and `unsafe extern "C"` semantically.
fn check_c_variadic_type(&self, fk: FnKind<'a>) {
match (fk.ctxt(), fk.header()) {
(Some(FnCtxt::Foreign), _) => return,
(Some(FnCtxt::Free), Some(header)) => match header.ext {
Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. }) | Extern::Implicit
if matches!(header.unsafety, Unsafe::Yes(_)) =>
{
return;
}
_ => {}
},
_ => {}
};
for Param { ty, span, .. } in &fk.decl().inputs {
if let TyKind::CVarArgs = ty.kind {
self.err_handler()
.struct_span_err(
*span,
"only foreign or `unsafe extern \"C\"` functions may be C-variadic",
)
.emit();
}
}
}
fn check_item_named(&self, ident: Ident, kind: &str) {
if ident.name != kw::Underscore {
return;
}
self.err_handler()
.struct_span_err(ident.span, &format!("`{}` items in this context need a name", kind))
.span_label(ident.span, format!("`_` is not a valid name for this `{}` item", kind))
.emit();
}
fn check_nomangle_item_asciionly(&self, ident: Ident, item_span: Span) {
if ident.name.as_str().is_ascii() {
return;
}
let head_span = self.session.source_map().guess_head_span(item_span);
struct_span_err!(
self.session,
head_span,
E0754,
"`#[no_mangle]` requires ASCII identifier"
)
.emit();
}
fn check_mod_file_item_asciionly(&self, ident: Ident) {
if ident.name.as_str().is_ascii() {
return;
}
struct_span_err!(
self.session,
ident.span,
E0754,
"trying to load file for module `{}` with non-ascii identifier name",
ident.name
)
.help("consider using `#[path]` attribute to specify filesystem path")
.emit();
}
fn deny_generic_params(&self, generics: &Generics, ident_span: Span) {
if !generics.params.is_empty() {
struct_span_err!(
self.session,
generics.span,
E0567,
"auto traits cannot have generic parameters"
)
.span_label(ident_span, "auto trait cannot have generic parameters")
.span_suggestion(
generics.span,
"remove the parameters",
"",
Applicability::MachineApplicable,
)
.emit();
}
}
fn emit_e0568(&self, span: Span, ident_span: Span) {
struct_span_err!(
self.session,
span,
E0568,
"auto traits cannot have super traits or lifetime bounds"
)
.span_label(ident_span, "auto trait cannot have super traits or lifetime bounds")
.span_suggestion(
span,
"remove the super traits or lifetime bounds",
"",
Applicability::MachineApplicable,
)
.emit();
}
fn deny_super_traits(&self, bounds: &GenericBounds, ident_span: Span) {
if let [.., last] = &bounds[..] {
let span = ident_span.shrink_to_hi().to(last.span());
self.emit_e0568(span, ident_span);
}
}
fn deny_where_clause(&self, where_clause: &WhereClause, ident_span: Span) {
if !where_clause.predicates.is_empty() {
self.emit_e0568(where_clause.span, ident_span);
}
}
fn deny_items(&self, trait_items: &[P<AssocItem>], ident_span: Span) {
if !trait_items.is_empty() {
let spans: Vec<_> = trait_items.iter().map(|i| i.ident.span).collect();
let total_span = trait_items.first().unwrap().span.to(trait_items.last().unwrap().span);
struct_span_err!(
self.session,
spans,
E0380,
"auto traits cannot have associated items"
)
.span_suggestion(
total_span,
"remove these associated items",
"",
Applicability::MachineApplicable,
)
.span_label(ident_span, "auto trait cannot have associated items")
.emit();
}
}
fn correct_generic_order_suggestion(&self, data: &AngleBracketedArgs) -> String {
// Lifetimes always come first.
let lt_sugg = data.args.iter().filter_map(|arg| match arg {
AngleBracketedArg::Arg(lt @ GenericArg::Lifetime(_)) => {
Some(pprust::to_string(|s| s.print_generic_arg(lt)))
}
_ => None,
});
let args_sugg = data.args.iter().filter_map(|a| match a {
AngleBracketedArg::Arg(GenericArg::Lifetime(_)) | AngleBracketedArg::Constraint(_) => {
None
}
AngleBracketedArg::Arg(arg) => Some(pprust::to_string(|s| s.print_generic_arg(arg))),
});
// Constraints always come last.
let constraint_sugg = data.args.iter().filter_map(|a| match a {
AngleBracketedArg::Arg(_) => None,
AngleBracketedArg::Constraint(c) => {
Some(pprust::to_string(|s| s.print_assoc_constraint(c)))
}
});
format!(
"<{}>",
lt_sugg.chain(args_sugg).chain(constraint_sugg).collect::<Vec<String>>().join(", ")
)
}
/// Enforce generic args coming before constraints in `<...>` of a path segment.
fn check_generic_args_before_constraints(&self, data: &AngleBracketedArgs) {
// Early exit in case it's partitioned as it should be.
if data.args.iter().is_partitioned(|arg| matches!(arg, AngleBracketedArg::Arg(_))) {
return;
}
// Find all generic argument coming after the first constraint...
let (constraint_spans, arg_spans): (Vec<Span>, Vec<Span>) =
data.args.iter().partition_map(|arg| match arg {
AngleBracketedArg::Constraint(c) => Either::Left(c.span),
AngleBracketedArg::Arg(a) => Either::Right(a.span()),
});
let args_len = arg_spans.len();
let constraint_len = constraint_spans.len();
// ...and then error:
self.err_handler()
.struct_span_err(
arg_spans.clone(),
"generic arguments must come before the first constraint",
)
.span_label(constraint_spans[0], &format!("constraint{}", pluralize!(constraint_len)))
.span_label(
*arg_spans.iter().last().unwrap(),
&format!("generic argument{}", pluralize!(args_len)),
)
.span_labels(constraint_spans, "")
.span_labels(arg_spans, "")
.span_suggestion_verbose(
data.span,
&format!(
"move the constraint{} after the generic argument{}",
pluralize!(constraint_len),
pluralize!(args_len)
),
self.correct_generic_order_suggestion(&data),
Applicability::MachineApplicable,
)
.emit();
}
fn visit_ty_common(&mut self, ty: &'a Ty) {
match ty.kind {
TyKind::BareFn(ref bfty) => {
self.check_fn_decl(&bfty.decl, SelfSemantic::No);
Self::check_decl_no_pat(&bfty.decl, |span, _, _| {
struct_span_err!(
self.session,
span,
E0561,
"patterns aren't allowed in function pointer types"
)
.emit();
});
self.check_late_bound_lifetime_defs(&bfty.generic_params);
if let Extern::Implicit = bfty.ext {
let sig_span = self.session.source_map().next_point(ty.span.shrink_to_lo());
self.maybe_lint_missing_abi(sig_span, ty.id);
}
}
TyKind::TraitObject(ref bounds, ..) => {
let mut any_lifetime_bounds = false;
for bound in bounds {
if let GenericBound::Outlives(ref lifetime) = *bound {
if any_lifetime_bounds {
struct_span_err!(
self.session,
lifetime.ident.span,
E0226,
"only a single explicit lifetime bound is permitted"
)
.emit();
break;
}
any_lifetime_bounds = true;
}
}
}
TyKind::ImplTrait(_, ref bounds) => {
if self.is_impl_trait_banned {
struct_span_err!(
self.session,
ty.span,
E0667,
"`impl Trait` is not allowed in path parameters"
)
.emit();
}
if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
struct_span_err!(
self.session,
ty.span,
E0666,
"nested `impl Trait` is not allowed"
)
.span_label(outer_impl_trait_sp, "outer `impl Trait`")
.span_label(ty.span, "nested `impl Trait` here")
.emit();
}
if !bounds.iter().any(|b| matches!(b, GenericBound::Trait(..))) {
self.err_handler().span_err(ty.span, "at least one trait must be specified");
}
}
_ => {}
}
}
fn maybe_lint_missing_abi(&mut self, span: Span, id: NodeId) {
// FIXME(davidtwco): This is a hack to detect macros which produce spans of the
// call site which do not have a macro backtrace. See #61963.
let is_macro_callsite = self
.session
.source_map()
.span_to_snippet(span)
.map(|snippet| snippet.starts_with("#["))
.unwrap_or(true);
if !is_macro_callsite {
self.lint_buffer.buffer_lint_with_diagnostic(
MISSING_ABI,
id,
span,
"extern declarations without an explicit ABI are deprecated",
BuiltinLintDiagnostics::MissingAbi(span, abi::Abi::FALLBACK),
)
}
}
}
/// Checks that generic parameters are in the correct order,
/// which is lifetimes, then types and then consts. (`<'a, T, const N: usize>`)
fn validate_generic_param_order(
handler: &rustc_errors::Handler,
generics: &[GenericParam],
span: Span,
) {
let mut max_param: Option<ParamKindOrd> = None;
let mut out_of_order = FxHashMap::default();
let mut param_idents = Vec::with_capacity(generics.len());
for (idx, param) in generics.iter().enumerate() {
let ident = param.ident;
let (kind, bounds, span) = (¶m.kind, ¶m.bounds, ident.span);
let (ord_kind, ident) = match ¶m.kind {
GenericParamKind::Lifetime => (ParamKindOrd::Lifetime, ident.to_string()),
GenericParamKind::Type { default: _ } => (ParamKindOrd::Type, ident.to_string()),
GenericParamKind::Const { ref ty, kw_span: _, default: _ } => {
let ty = pprust::ty_to_string(ty);
(ParamKindOrd::Const, format!("const {}: {}", ident, ty))
}
};
param_idents.push((kind, ord_kind, bounds, idx, ident));
match max_param {
Some(max_param) if max_param > ord_kind => {
let entry = out_of_order.entry(ord_kind).or_insert((max_param, vec![]));
entry.1.push(span);
}
Some(_) | None => max_param = Some(ord_kind),
};
}
if !out_of_order.is_empty() {
let mut ordered_params = "<".to_string();
param_idents.sort_by_key(|&(_, po, _, i, _)| (po, i));
let mut first = true;
for (kind, _, bounds, _, ident) in param_idents {
if !first {
ordered_params += ", ";
}
ordered_params += &ident;
if !bounds.is_empty() {
ordered_params += ": ";
ordered_params += &pprust::bounds_to_string(&bounds);
}
match kind {
GenericParamKind::Type { default: Some(default) } => {
ordered_params += " = ";
ordered_params += &pprust::ty_to_string(default);
}
GenericParamKind::Type { default: None } => (),
GenericParamKind::Lifetime => (),
GenericParamKind::Const { ty: _, kw_span: _, default: Some(default) } => {
ordered_params += " = ";
ordered_params += &pprust::expr_to_string(&*default.value);
}
GenericParamKind::Const { ty: _, kw_span: _, default: None } => (),
}
first = false;
}
ordered_params += ">";
for (param_ord, (max_param, spans)) in &out_of_order {
let mut err = handler.struct_span_err(
spans.clone(),
&format!(
"{} parameters must be declared prior to {} parameters",
param_ord, max_param,
),
);
err.span_suggestion(
span,
"reorder the parameters: lifetimes, then consts and types",
&ordered_params,
Applicability::MachineApplicable,
);
err.emit();
}