1use rustc_data_structures::fx::FxHashMap;
2use rustc_errors::{Applicability, Diag};
3use rustc_hir::PrimTy;
4use rustc_hir::def::{DefKind, Res};
5use rustc_hir::def_id::DefIdMap;
6use rustc_middle::ty::TyCtxt;
7use rustc_span::Span;
8use serde::de::{self, Deserializer, Visitor};
9use serde::{Deserialize, Serialize, ser};
10use std::collections::HashMap;
11use std::fmt;
12
13#[derive(Debug, Deserialize)]
14pub struct Rename {
15 pub path: String,
16 pub rename: String,
17}
18
19pub type DisallowedPathWithoutReplacement = DisallowedPath<false>;
20
21#[derive(Debug, Serialize)]
22pub struct DisallowedPath<const REPLACEMENT_ALLOWED: bool = true> {
23 path: String,
24 reason: Option<String>,
25 replacement: Option<String>,
26 allow_invalid: bool,
32 #[serde(skip_serializing)]
36 span: Span,
37}
38
39impl<'de, const REPLACEMENT_ALLOWED: bool> Deserialize<'de> for DisallowedPath<REPLACEMENT_ALLOWED> {
40 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
41 where
42 D: Deserializer<'de>,
43 {
44 let enum_ = DisallowedPathEnum::deserialize(deserializer)?;
45 if !REPLACEMENT_ALLOWED && enum_.replacement().is_some() {
46 return Err(de::Error::custom("replacement not allowed for this configuration"));
47 }
48 Ok(Self {
49 path: enum_.path().to_owned(),
50 reason: enum_.reason().map(ToOwned::to_owned),
51 replacement: enum_.replacement().map(ToOwned::to_owned),
52 allow_invalid: enum_.allow_invalid(),
53 span: Span::default(),
54 })
55 }
56}
57
58#[derive(Debug, Deserialize, Serialize)]
61#[serde(untagged)]
62enum DisallowedPathEnum {
63 Simple(String),
64 WithReason {
65 path: String,
66 reason: Option<String>,
67 replacement: Option<String>,
68 #[serde(rename = "allow-invalid")]
69 allow_invalid: Option<bool>,
70 },
71}
72
73impl<const REPLACEMENT_ALLOWED: bool> DisallowedPath<REPLACEMENT_ALLOWED> {
74 pub fn path(&self) -> &str {
75 &self.path
76 }
77
78 pub fn diag_amendment(&self, span: Span) -> impl FnOnce(&mut Diag<'_, ()>) {
79 move |diag| {
80 if let Some(replacement) = &self.replacement {
81 diag.span_suggestion(
82 span,
83 self.reason.as_ref().map_or_else(|| String::from("use"), Clone::clone),
84 replacement,
85 Applicability::MachineApplicable,
86 );
87 } else if let Some(reason) = &self.reason {
88 diag.note(reason.clone());
89 }
90 }
91 }
92
93 pub fn span(&self) -> Span {
94 self.span
95 }
96
97 pub fn set_span(&mut self, span: Span) {
98 self.span = span;
99 }
100}
101
102impl DisallowedPathEnum {
103 pub fn path(&self) -> &str {
104 let (Self::Simple(path) | Self::WithReason { path, .. }) = self;
105
106 path
107 }
108
109 fn reason(&self) -> Option<&str> {
110 match &self {
111 Self::WithReason { reason, .. } => reason.as_deref(),
112 Self::Simple(_) => None,
113 }
114 }
115
116 fn replacement(&self) -> Option<&str> {
117 match &self {
118 Self::WithReason { replacement, .. } => replacement.as_deref(),
119 Self::Simple(_) => None,
120 }
121 }
122
123 fn allow_invalid(&self) -> bool {
124 match &self {
125 Self::WithReason { allow_invalid, .. } => allow_invalid.unwrap_or_default(),
126 Self::Simple(_) => false,
127 }
128 }
129}
130
131#[allow(clippy::type_complexity)]
133pub fn create_disallowed_map<const REPLACEMENT_ALLOWED: bool>(
134 tcx: TyCtxt<'_>,
135 disallowed_paths: &'static [DisallowedPath<REPLACEMENT_ALLOWED>],
136 def_kind_predicate: impl Fn(DefKind) -> bool,
137 predicate_description: &str,
138 allow_prim_tys: bool,
139) -> (
140 DefIdMap<(&'static str, &'static DisallowedPath<REPLACEMENT_ALLOWED>)>,
141 FxHashMap<PrimTy, (&'static str, &'static DisallowedPath<REPLACEMENT_ALLOWED>)>,
142) {
143 let mut def_ids: DefIdMap<(&'static str, &'static DisallowedPath<REPLACEMENT_ALLOWED>)> = DefIdMap::default();
144 let mut prim_tys: FxHashMap<PrimTy, (&'static str, &'static DisallowedPath<REPLACEMENT_ALLOWED>)> =
145 FxHashMap::default();
146 for disallowed_path in disallowed_paths {
147 let path = disallowed_path.path();
148 let mut resolutions = clippy_utils::def_path_res(tcx, &path.split("::").collect::<Vec<_>>());
149
150 let mut found_def_id = None;
151 let mut found_prim_ty = false;
152 resolutions.retain(|res| match res {
153 Res::Def(def_kind, def_id) => {
154 found_def_id = Some(*def_id);
155 def_kind_predicate(*def_kind)
156 },
157 Res::PrimTy(_) => {
158 found_prim_ty = true;
159 allow_prim_tys
160 },
161 _ => false,
162 });
163
164 if resolutions.is_empty() {
165 let span = disallowed_path.span();
166
167 if let Some(def_id) = found_def_id {
168 tcx.sess.dcx().span_warn(
169 span,
170 format!(
171 "expected a {predicate_description}, found {} {}",
172 tcx.def_descr_article(def_id),
173 tcx.def_descr(def_id)
174 ),
175 );
176 } else if found_prim_ty {
177 tcx.sess.dcx().span_warn(
178 span,
179 format!("expected a {predicate_description}, found a primitive type",),
180 );
181 } else if !disallowed_path.allow_invalid {
182 tcx.sess.dcx().span_warn(
183 span,
184 format!("`{path}` does not refer to an existing {predicate_description}"),
185 );
186 }
187 }
188
189 for res in resolutions {
190 match res {
191 Res::Def(_, def_id) => {
192 def_ids.insert(def_id, (path, disallowed_path));
193 },
194 Res::PrimTy(ty) => {
195 prim_tys.insert(ty, (path, disallowed_path));
196 },
197 _ => unreachable!(),
198 }
199 }
200 }
201
202 (def_ids, prim_tys)
203}
204
205#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
206pub enum MatchLintBehaviour {
207 AllTypes,
208 WellKnownTypes,
209 Never,
210}
211
212#[derive(Debug)]
213pub struct MacroMatcher {
214 pub name: String,
215 pub braces: (char, char),
216}
217
218impl<'de> Deserialize<'de> for MacroMatcher {
219 fn deserialize<D>(deser: D) -> Result<Self, D::Error>
220 where
221 D: Deserializer<'de>,
222 {
223 #[derive(Deserialize)]
224 #[serde(field_identifier, rename_all = "lowercase")]
225 enum Field {
226 Name,
227 Brace,
228 }
229 struct MacVisitor;
230 impl<'de> Visitor<'de> for MacVisitor {
231 type Value = MacroMatcher;
232
233 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
234 formatter.write_str("struct MacroMatcher")
235 }
236
237 fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
238 where
239 V: de::MapAccess<'de>,
240 {
241 let mut name = None;
242 let mut brace: Option<char> = None;
243 while let Some(key) = map.next_key()? {
244 match key {
245 Field::Name => {
246 if name.is_some() {
247 return Err(de::Error::duplicate_field("name"));
248 }
249 name = Some(map.next_value()?);
250 },
251 Field::Brace => {
252 if brace.is_some() {
253 return Err(de::Error::duplicate_field("brace"));
254 }
255 brace = Some(map.next_value()?);
256 },
257 }
258 }
259 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
260 let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?;
261 Ok(MacroMatcher {
262 name,
263 braces: [('(', ')'), ('{', '}'), ('[', ']')]
264 .into_iter()
265 .find(|b| b.0 == brace)
266 .map(|(o, c)| (o.to_owned(), c.to_owned()))
267 .ok_or_else(|| de::Error::custom(format!("expected one of `(`, `{{`, `[` found `{brace}`")))?,
268 })
269 }
270 }
271
272 const FIELDS: &[&str] = &["name", "brace"];
273 deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor)
274 }
275}
276
277#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
279#[serde(rename_all = "snake_case")]
280pub enum SourceItemOrderingCategory {
281 Enum,
282 Impl,
283 Module,
284 Struct,
285 Trait,
286}
287
288pub struct SourceItemOrdering(Vec<SourceItemOrderingCategory>);
293
294impl SourceItemOrdering {
295 pub fn contains(&self, category: &SourceItemOrderingCategory) -> bool {
296 self.0.contains(category)
297 }
298}
299
300impl<T> From<T> for SourceItemOrdering
301where
302 T: Into<Vec<SourceItemOrderingCategory>>,
303{
304 fn from(value: T) -> Self {
305 Self(value.into())
306 }
307}
308
309impl core::fmt::Debug for SourceItemOrdering {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 self.0.fmt(f)
312 }
313}
314
315impl<'de> Deserialize<'de> for SourceItemOrdering {
316 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
317 where
318 D: Deserializer<'de>,
319 {
320 let items = Vec::<SourceItemOrderingCategory>::deserialize(deserializer)?;
321 let mut items_set = std::collections::HashSet::new();
322
323 for item in &items {
324 if items_set.contains(item) {
325 return Err(de::Error::custom(format!(
326 "The category \"{item:?}\" was enabled more than once in the source ordering configuration."
327 )));
328 }
329 items_set.insert(item);
330 }
331
332 Ok(Self(items))
333 }
334}
335
336impl Serialize for SourceItemOrdering {
337 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
338 where
339 S: ser::Serializer,
340 {
341 self.0.serialize(serializer)
342 }
343}
344
345#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
347#[serde(rename_all = "snake_case")]
348pub enum SourceItemOrderingModuleItemKind {
349 ExternCrate,
350 Mod,
351 ForeignMod,
352 Use,
353 Macro,
354 GlobalAsm,
355 Static,
356 Const,
357 TyAlias,
358 Enum,
359 Struct,
360 Union,
361 Trait,
362 TraitAlias,
363 Impl,
364 Fn,
365}
366
367impl SourceItemOrderingModuleItemKind {
368 pub fn all_variants() -> Vec<Self> {
369 #[allow(clippy::enum_glob_use)] use SourceItemOrderingModuleItemKind::*;
371 vec![
372 ExternCrate,
373 Mod,
374 ForeignMod,
375 Use,
376 Macro,
377 GlobalAsm,
378 Static,
379 Const,
380 TyAlias,
381 Enum,
382 Struct,
383 Union,
384 Trait,
385 TraitAlias,
386 Impl,
387 Fn,
388 ]
389 }
390}
391
392#[derive(Clone)]
397pub struct SourceItemOrderingModuleItemGroupings {
398 groups: Vec<(String, Vec<SourceItemOrderingModuleItemKind>)>,
399 lut: HashMap<SourceItemOrderingModuleItemKind, usize>,
400 back_lut: HashMap<SourceItemOrderingModuleItemKind, String>,
401}
402
403impl SourceItemOrderingModuleItemGroupings {
404 fn build_lut(
405 groups: &[(String, Vec<SourceItemOrderingModuleItemKind>)],
406 ) -> HashMap<SourceItemOrderingModuleItemKind, usize> {
407 let mut lut = HashMap::new();
408 for (group_index, (_, items)) in groups.iter().enumerate() {
409 for item in items {
410 lut.insert(item.clone(), group_index);
411 }
412 }
413 lut
414 }
415
416 fn build_back_lut(
417 groups: &[(String, Vec<SourceItemOrderingModuleItemKind>)],
418 ) -> HashMap<SourceItemOrderingModuleItemKind, String> {
419 let mut lut = HashMap::new();
420 for (group_name, items) in groups {
421 for item in items {
422 lut.insert(item.clone(), group_name.clone());
423 }
424 }
425 lut
426 }
427
428 pub fn grouping_name_of(&self, item: &SourceItemOrderingModuleItemKind) -> Option<&String> {
429 self.back_lut.get(item)
430 }
431
432 pub fn grouping_names(&self) -> Vec<String> {
433 self.groups.iter().map(|(name, _)| name.clone()).collect()
434 }
435
436 pub fn is_grouping(&self, grouping: &str) -> bool {
437 self.groups.iter().any(|(g, _)| g == grouping)
438 }
439
440 pub fn module_level_order_of(&self, item: &SourceItemOrderingModuleItemKind) -> Option<usize> {
441 self.lut.get(item).copied()
442 }
443}
444
445impl From<&[(&str, &[SourceItemOrderingModuleItemKind])]> for SourceItemOrderingModuleItemGroupings {
446 fn from(value: &[(&str, &[SourceItemOrderingModuleItemKind])]) -> Self {
447 let groups: Vec<(String, Vec<SourceItemOrderingModuleItemKind>)> =
448 value.iter().map(|item| (item.0.to_string(), item.1.to_vec())).collect();
449 let lut = Self::build_lut(&groups);
450 let back_lut = Self::build_back_lut(&groups);
451 Self { groups, lut, back_lut }
452 }
453}
454
455impl core::fmt::Debug for SourceItemOrderingModuleItemGroupings {
456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 self.groups.fmt(f)
458 }
459}
460
461impl<'de> Deserialize<'de> for SourceItemOrderingModuleItemGroupings {
462 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
463 where
464 D: Deserializer<'de>,
465 {
466 let groups = Vec::<(String, Vec<SourceItemOrderingModuleItemKind>)>::deserialize(deserializer)?;
467 let items_total: usize = groups.iter().map(|(_, v)| v.len()).sum();
468 let lut = Self::build_lut(&groups);
469 let back_lut = Self::build_back_lut(&groups);
470
471 let mut expected_items = SourceItemOrderingModuleItemKind::all_variants();
472 for item in lut.keys() {
473 expected_items.retain(|i| i != item);
474 }
475
476 let all_items = SourceItemOrderingModuleItemKind::all_variants();
477 if expected_items.is_empty() && items_total == all_items.len() {
478 let Some(use_group_index) = lut.get(&SourceItemOrderingModuleItemKind::Use) else {
479 return Err(de::Error::custom("Error in internal LUT."));
480 };
481 let Some((_, use_group_items)) = groups.get(*use_group_index) else {
482 return Err(de::Error::custom("Error in internal LUT."));
483 };
484 if use_group_items.len() > 1 {
485 return Err(de::Error::custom(
486 "The group containing the \"use\" item kind may not contain any other item kinds. \
487 The \"use\" items will (generally) be sorted by rustfmt already. \
488 Therefore it makes no sense to implement linting rules that may conflict with rustfmt.",
489 ));
490 }
491
492 Ok(Self { groups, lut, back_lut })
493 } else if items_total != all_items.len() {
494 Err(de::Error::custom(format!(
495 "Some module item kinds were configured more than once, or were missing, in the source ordering configuration. \
496 The module item kinds are: {all_items:?}"
497 )))
498 } else {
499 Err(de::Error::custom(format!(
500 "Not all module item kinds were part of the configured source ordering rule. \
501 All item kinds must be provided in the config, otherwise the required source ordering would remain ambiguous. \
502 The module item kinds are: {all_items:?}"
503 )))
504 }
505 }
506}
507
508impl Serialize for SourceItemOrderingModuleItemGroupings {
509 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
510 where
511 S: ser::Serializer,
512 {
513 self.groups.serialize(serializer)
514 }
515}
516
517#[derive(Clone, Debug, Deserialize, PartialEq, PartialOrd, Serialize)]
519#[serde(rename_all = "snake_case")]
520pub enum SourceItemOrderingTraitAssocItemKind {
521 Const,
522 Fn,
523 Type,
524}
525
526impl SourceItemOrderingTraitAssocItemKind {
527 pub fn all_variants() -> Vec<Self> {
528 #[allow(clippy::enum_glob_use)] use SourceItemOrderingTraitAssocItemKind::*;
530 vec![Const, Fn, Type]
531 }
532}
533
534#[derive(Clone)]
542pub struct SourceItemOrderingTraitAssocItemKinds(Vec<SourceItemOrderingTraitAssocItemKind>);
543
544impl SourceItemOrderingTraitAssocItemKinds {
545 pub fn index_of(&self, item: &SourceItemOrderingTraitAssocItemKind) -> Option<usize> {
546 self.0.iter().position(|i| i == item)
547 }
548}
549
550impl<T> From<T> for SourceItemOrderingTraitAssocItemKinds
551where
552 T: Into<Vec<SourceItemOrderingTraitAssocItemKind>>,
553{
554 fn from(value: T) -> Self {
555 Self(value.into())
556 }
557}
558
559impl core::fmt::Debug for SourceItemOrderingTraitAssocItemKinds {
560 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561 self.0.fmt(f)
562 }
563}
564
565impl<'de> Deserialize<'de> for SourceItemOrderingTraitAssocItemKinds {
566 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
567 where
568 D: Deserializer<'de>,
569 {
570 let items = Vec::<SourceItemOrderingTraitAssocItemKind>::deserialize(deserializer)?;
571
572 let mut expected_items = SourceItemOrderingTraitAssocItemKind::all_variants();
573 for item in &items {
574 expected_items.retain(|i| i != item);
575 }
576
577 let all_items = SourceItemOrderingTraitAssocItemKind::all_variants();
578 if expected_items.is_empty() && items.len() == all_items.len() {
579 Ok(Self(items))
580 } else if items.len() != all_items.len() {
581 Err(de::Error::custom(format!(
582 "Some trait associated item kinds were configured more than once, or were missing, in the source ordering configuration. \
583 The trait associated item kinds are: {all_items:?}",
584 )))
585 } else {
586 Err(de::Error::custom(format!(
587 "Not all trait associated item kinds were part of the configured source ordering rule. \
588 All item kinds must be provided in the config, otherwise the required source ordering would remain ambiguous. \
589 The trait associated item kinds are: {all_items:?}"
590 )))
591 }
592 }
593}
594
595impl Serialize for SourceItemOrderingTraitAssocItemKinds {
596 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
597 where
598 S: ser::Serializer,
599 {
600 self.0.serialize(serializer)
601 }
602}
603
604#[derive(Clone, Debug)]
612pub enum SourceItemOrderingWithinModuleItemGroupings {
613 All,
615
616 None,
618
619 Custom(Vec<String>),
621}
622
623impl SourceItemOrderingWithinModuleItemGroupings {
624 pub fn ordered_within(&self, grouping_name: &String) -> bool {
625 match self {
626 SourceItemOrderingWithinModuleItemGroupings::All => true,
627 SourceItemOrderingWithinModuleItemGroupings::None => false,
628 SourceItemOrderingWithinModuleItemGroupings::Custom(groups) => groups.contains(grouping_name),
629 }
630 }
631}
632
633#[derive(Deserialize)]
635#[serde(untagged)]
636enum StringOrVecOfString {
637 String(String),
638 Vec(Vec<String>),
639}
640
641impl<'de> Deserialize<'de> for SourceItemOrderingWithinModuleItemGroupings {
642 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
643 where
644 D: Deserializer<'de>,
645 {
646 let description = "The available options for configuring an ordering within module item groups are: \
647 \"all\", \"none\", or a list of module item group names \
648 (as configured with the `module-item-order-groupings` configuration option).";
649
650 match StringOrVecOfString::deserialize(deserializer) {
651 Ok(StringOrVecOfString::String(preset)) if preset == "all" => {
652 Ok(SourceItemOrderingWithinModuleItemGroupings::All)
653 },
654 Ok(StringOrVecOfString::String(preset)) if preset == "none" => {
655 Ok(SourceItemOrderingWithinModuleItemGroupings::None)
656 },
657 Ok(StringOrVecOfString::String(preset)) => Err(de::Error::custom(format!(
658 "Unknown configuration option: {preset}.\n{description}"
659 ))),
660 Ok(StringOrVecOfString::Vec(groupings)) => {
661 Ok(SourceItemOrderingWithinModuleItemGroupings::Custom(groupings))
662 },
663 Err(e) => Err(de::Error::custom(format!("{e}\n{description}"))),
664 }
665 }
666}
667
668impl Serialize for SourceItemOrderingWithinModuleItemGroupings {
669 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
670 where
671 S: ser::Serializer,
672 {
673 match self {
674 SourceItemOrderingWithinModuleItemGroupings::All => serializer.serialize_str("all"),
675 SourceItemOrderingWithinModuleItemGroupings::None => serializer.serialize_str("none"),
676 SourceItemOrderingWithinModuleItemGroupings::Custom(vec) => vec.serialize(serializer),
677 }
678 }
679}
680
681macro_rules! unimplemented_serialize {
684 ($($t:ty,)*) => {
685 $(
686 impl Serialize for $t {
687 fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
688 where
689 S: ser::Serializer,
690 {
691 Err(ser::Error::custom("unimplemented"))
692 }
693 }
694 )*
695 }
696}
697
698unimplemented_serialize! {
699 Rename,
700 MacroMatcher,
701}
702
703#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
704pub enum PubUnderscoreFieldsBehaviour {
705 PubliclyExported,
706 AllPubFields,
707}