From 4ed846ad4d4e0be96efc4837fa416aabce1882db Mon Sep 17 00:00:00 2001 From: Javier Blazquez Date: Mon, 11 Oct 2021 12:09:32 -0700 Subject: [PATCH 1/4] Add -Z no-unique-section-names to reduce ELF header bloat. This change adds a new compiler flag that can help reduce the size of ELF binaries that contain many functions. By default, when enabling function sections (which is the default for most targets), the LLVM backend will generate different section names for each function. For example, a function "func" would generate a section called ".text.func". Normally this is fine because the linker will merge all those sections into a single one in the binary. However, starting with LLVM 12 (llvm/llvm-project@ee5d1a0), the backend will also generate unique section names for exception handling, resulting in thousands of ".gcc_except_table.*" sections ending up in the final binary because some linkers don't currently merge or strip these EH sections. This can bloat the ELF headers and string table significantly in binaries that contain many functions. The new option is analogous to Clang's -fno-unique-section-names, and instructs LLVM to generate the same ".text" and ".gcc_except_table" section for each function, resulting in smaller object files and potentially a smaller final binary. --- compiler/rustc_codegen_llvm/src/back/write.rs | 2 ++ compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 1 + compiler/rustc_interface/src/tests.rs | 1 + compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp | 2 ++ compiler/rustc_session/src/options.rs | 2 ++ .../src/compiler-flags/no-unique-section-names.md | 9 +++++++++ 6 files changed, 17 insertions(+) create mode 100644 src/doc/unstable-book/src/compiler-flags/no-unique-section-names.md diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index ab48c56a62663..d6c122aabdbb5 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -161,6 +161,7 @@ pub fn target_machine_factory( let ffunction_sections = sess.opts.debugging_opts.function_sections.unwrap_or(sess.target.function_sections); let fdata_sections = ffunction_sections; + let funique_section_names = !sess.opts.debugging_opts.no_unique_section_names; let code_model = to_llvm_code_model(sess.code_model()); @@ -205,6 +206,7 @@ pub fn target_machine_factory( use_softfp, ffunction_sections, fdata_sections, + funique_section_names, trap_unreachable, singlethread, asm_comments, diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 436d906827b5b..3e7048e7b80db 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -2153,6 +2153,7 @@ extern "C" { UseSoftFP: bool, FunctionSections: bool, DataSections: bool, + UniqueSectionNames: bool, TrapUnreachable: bool, Singlethread: bool, AsmComments: bool, diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index cfe13b1fd4e1f..021afde8c62ac 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -740,6 +740,7 @@ fn test_debugging_options_tracking_hash() { tracked!(new_llvm_pass_manager, Some(true)); tracked!(no_generate_arange_section, true); tracked!(no_link, true); + tracked!(no_unique_section_names, true); tracked!(no_profiler_runtime, true); tracked!(osx_rpath_install_name, true); tracked!(panic_abort_tests, true); diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index ddb5f7dcebfad..42d2c13b783d5 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -459,6 +459,7 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat, bool FunctionSections, bool DataSections, + bool UniqueSectionNames, bool TrapUnreachable, bool Singlethread, bool AsmComments, @@ -488,6 +489,7 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( } Options.DataSections = DataSections; Options.FunctionSections = FunctionSections; + Options.UniqueSectionNames = UniqueSectionNames; Options.MCOptions.AsmVerbose = AsmComments; Options.MCOptions.PreserveAsmComments = AsmComments; Options.MCOptions.ABIName = ABIStr; diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 8ecb7a031ad81..b76ea98e637da 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1188,6 +1188,8 @@ options! { "compile without linking"), no_parallel_llvm: bool = (false, parse_no_flag, [UNTRACKED], "run LLVM in non-parallel mode (while keeping codegen-units and ThinLTO)"), + no_unique_section_names: bool = (false, parse_bool, [TRACKED], + "do not use unique names for text and data sections when -Z function-sections is used"), no_profiler_runtime: bool = (false, parse_no_flag, [TRACKED], "prevent automatic injection of the profiler_builtins crate"), normalize_docs: bool = (false, parse_bool, [TRACKED], diff --git a/src/doc/unstable-book/src/compiler-flags/no-unique-section-names.md b/src/doc/unstable-book/src/compiler-flags/no-unique-section-names.md new file mode 100644 index 0000000000000..5c1c7cda7013e --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/no-unique-section-names.md @@ -0,0 +1,9 @@ +# `no-unique-section-names` + +------------------------ + +This flag currently applies only to ELF-based targets using the LLVM codegen backend. It prevents the generation of unique ELF section names for each separate code and data item when `-Z function-sections` is also in use, which is the default for most targets. This option can reduce the size of object files, and depending on the linker, the final ELF binary as well. + +For example, a function `func` will by default generate a code section called `.text.func`. Normally this is fine because the linker will merge all those `.text.*` sections into a single one in the binary. However, starting with [LLVM 12](https://github.com/llvm/llvm-project/commit/ee5d1a04), the backend will also generate unique section names for exception handling, so you would see a section name of `.gcc_except_table.func` in the object file and potentially in the final ELF binary, which could add significant bloat to programs that contain many functions. + +This flag instructs LLVM to use the same `.text` and `.gcc_except_table` section name for each function, and it is analogous to Clang's `-fno-unique-section-names` option. From b7a948da4c91549d92e6c02c45dae8c7395a4bcd Mon Sep 17 00:00:00 2001 From: Jacob Hoffman-Andrews Date: Fri, 22 Oct 2021 13:45:10 -0700 Subject: [PATCH 2/4] Fix documentation header sizes And add a rustdoc-gui test confirming various header sizes. --- src/librustdoc/html/render/mod.rs | 2 +- src/librustdoc/html/render/print_item.rs | 8 +- src/test/rustdoc-gui/header-size.goml | 99 +++++++++++++++++ src/test/rustdoc-gui/sidebar.goml | 3 +- src/test/rustdoc-gui/src/test_docs/lib.rs | 126 ++++++++++++++++++++++ 5 files changed, 232 insertions(+), 6 deletions(-) create mode 100644 src/test/rustdoc-gui/header-size.goml diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 69c5c2c4abc2a..2898da1cbf81f 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -1596,7 +1596,7 @@ fn render_impl( error_codes: cx.shared.codes, edition: cx.shared.edition(), playground: &cx.shared.playground, - heading_offset: HeadingOffset::H2 + heading_offset: HeadingOffset::H4 } .into_string() ); diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 58cd1018c316f..3fffbbefb1cb9 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -983,7 +983,7 @@ fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Uni if let Some(stability_class) = field.stability_class(cx.tcx()) { write!(w, "", stab = stability_class); } - document(w, cx, field, Some(it), HeadingOffset::H2); + document(w, cx, field, Some(it), HeadingOffset::H3); } } let def_id = it.def_id.expect_def_id(); @@ -1094,7 +1094,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum w.write_str(""); render_stability_since(w, variant, it, cx.tcx()); w.write_str(""); - document(w, cx, variant, Some(it), HeadingOffset::H2); + document(w, cx, variant, Some(it), HeadingOffset::H3); document_non_exhaustive(w, variant); use crate::clean::Variant; @@ -1134,7 +1134,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum f = field.name.as_ref().unwrap(), t = ty.print(cx) ); - document(w, cx, field, Some(variant), HeadingOffset::H2); + document(w, cx, field, Some(variant), HeadingOffset::H4); } _ => unreachable!(), } @@ -1285,7 +1285,7 @@ fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::St name = field_name, ty = ty.print(cx) ); - document(w, cx, field, Some(it), HeadingOffset::H2); + document(w, cx, field, Some(it), HeadingOffset::H3); } } } diff --git a/src/test/rustdoc-gui/header-size.goml b/src/test/rustdoc-gui/header-size.goml new file mode 100644 index 0000000000000..bd865e2c4f2d7 --- /dev/null +++ b/src/test/rustdoc-gui/header-size.goml @@ -0,0 +1,99 @@ +// This test check that headers (a) have the correct heading level, and (b) are the right size. +// The sizes may change as design changes, but try to make sure a lower header is never bigger than +// its parent headers. +// Most of these sizes are set in CSS in `em` units, so here's a conversion chart based on our +// default 16px font size: +// 24px 1.5em +// 22.4px 1.4em +// 20.8px 1.3em +// 18.4px 1.15em +// 17.6px 1.1em +// 16px 1em +// 15.2px 0.95em +goto: file://|DOC_PATH|/test_docs/struct.HeavilyDocumentedStruct.html + +assert-css: ("h1.fqn", {"font-size": "24px"}) // 1.5em + +assert-css: ("h2#top-doc-prose-title", {"font-size": "20.8px"}) // 1.3em +assert-css: ("h3#top-doc-prose-sub-heading", {"font-size": "18.4px"}) // 1.15em +assert-css: ("h4#top-doc-prose-sub-sub-heading", {"font-size": "17.6px"}) // 1.1em + +assert-css: ("h2#fields", {"font-size": "22.4px"}) // 1.4em +assert-css: ("h3#title-for-field", {"font-size": "20.8px"}) // 1.3em +assert-css: ("h4#sub-heading-for-field", {"font-size": "16px"}) + +assert-css: ("h2#implementations", {"font-size": "22.4px"}) // 1.4em + +assert-css: ("#impl > h3.code-header", {"font-size": "16px"}) // 1em +assert-css: ("#method\.do_nothing > h4.code-header", {"font-size": "16px"}) // 1em + +assert-css: ("h4#title-for-struct-impl-doc", {"font-size": "16px"}) +assert-css: ("h5#sub-heading-for-struct-impl-doc", {"font-size": "16px"}) +assert-css: ("h6#sub-sub-heading-for-struct-impl-doc", {"font-size": "15.2px"}) // 0.95em + +assert-css: ("h5#title-for-struct-impl-item-doc", {"font-size": "16px"}) // 1em +assert-css: ("h6#sub-heading-for-struct-impl-item-doc", {"font-size": "15.2px"}) // 0.95em +assert-css: ("h6#sub-sub-heading-for-struct-impl-item-doc", {"font-size": "15.2px"}) // 0.95em + +goto: file://|DOC_PATH|/test_docs/enum.HeavilyDocumentedEnum.html + +assert-css: ("h1.fqn", {"font-size": "24px"}) // 1.5em + +assert-css: ("h2#top-doc-prose-title", {"font-size": "20.8px"}) // 1.3em +assert-css: ("h3#top-doc-prose-sub-heading", {"font-size": "18.4px"}) // 1.15em +assert-css: ("h4#top-doc-prose-sub-sub-heading", {"font-size": "17.6px"}) // 1.1em + +assert-css: ("h2#variants", {"font-size": "22.4px"}) // 1.4em + +assert-css: ("h3#none-prose-title", {"font-size": "20.8px"}) // 1.3em +assert-css: ("h4#none-prose-sub-heading", {"font-size": "16px"}) + +assert-css: ("h3#wrapped-prose-title", {"font-size": "20.8px"}) // 1.3em +assert-css: ("h4#wrapped-prose-sub-heading", {"font-size": "16px"}) + +assert-css: ("h4#wrapped0-prose-title", {"font-size": "16px"}) +assert-css: ("h5#wrapped0-prose-sub-heading", {"font-size": "16px"}) + +assert-css: ("h4#structy-prose-title", {"font-size": "16px"}) +assert-css: ("h5#structy-prose-sub-heading", {"font-size": "16px"}) + +assert-css: ("h2#implementations", {"font-size": "22.4px"}) // 1.4em + +assert-css: ("#impl > h3.code-header", {"font-size": "16px"}) // 1em +assert-css: ("#method\.do_nothing > h4.code-header", {"font-size": "16px"}) // 1em + +assert-css: ("h4#title-for-enum-impl-doc", {"font-size": "16px"}) +assert-css: ("h5#sub-heading-for-enum-impl-doc", {"font-size": "16px"}) +assert-css: ("h6#sub-sub-heading-for-enum-impl-doc", {"font-size": "15.2px"}) // 0.95em + +assert-css: ("h5#title-for-enum-impl-item-doc", {"font-size": "16px"}) // 1em +assert-css: ("h6#sub-heading-for-enum-impl-item-doc", {"font-size": "15.2px"}) // 0.95em +assert-css: ("h6#sub-sub-heading-for-enum-impl-item-doc", {"font-size": "15.2px"}) // 0.95em + +goto: file://|DOC_PATH|/test_docs/union.HeavilyDocumentedUnion.html + +assert-css: ("h1.fqn", {"font-size": "24px"}) // 1.5em + +assert-css: ("h2#top-doc-prose-title", {"font-size": "20.8px"}) // 1.3em +assert-css: ("h3#top-doc-prose-sub-heading", {"font-size": "18.4px"}) // 1.15em + +assert-css: ("h2#fields", {"font-size": "22.4px"}) // 1.4em + +assert-css: ("h3#title-for-union-variant", {"font-size": "20.8px"}) // 1.3em +assert-css: ("h4#sub-heading-for-union-variant", {"font-size": "16px"}) + +assert-css: ("h2#implementations", {"font-size": "22.4px"}) // 1.4em + +assert-css: ("#impl > h3.code-header", {"font-size": "16px"}) // 1em +assert-css: ("h4#title-for-union-impl-doc", {"font-size": "16px"}) +assert-css: ("h5#sub-heading-for-union-impl-doc", {"font-size": "16px"}) + +assert-css: ("h5#title-for-union-impl-item-doc", {"font-size": "16px"}) // 1em +assert-css: ("h6#sub-heading-for-union-impl-item-doc", {"font-size": "15.2px"}) // 0.95em + +goto: file://|DOC_PATH|/test_docs/macro.heavily_documented_macro.html + +assert-css: ("h1.fqn", {"font-size": "24px"}) // 1.5em + +assert-css: ("h2#top-doc-prose-title", {"font-size": "20.8px"}) // 1.3em +assert-css: ("h3#top-doc-prose-sub-heading", {"font-size": "18.4px"}) // 1.15em diff --git a/src/test/rustdoc-gui/sidebar.goml b/src/test/rustdoc-gui/sidebar.goml index 62dc76a40bcf5..eacc9f6c15fe1 100644 --- a/src/test/rustdoc-gui/sidebar.goml +++ b/src/test/rustdoc-gui/sidebar.goml @@ -13,7 +13,8 @@ assert-text: (".sidebar-elems > .items > ul > li:nth-child(4)", "Enums") assert-text: (".sidebar-elems > .items > ul > li:nth-child(5)", "Traits") assert-text: (".sidebar-elems > .items > ul > li:nth-child(6)", "Functions") assert-text: (".sidebar-elems > .items > ul > li:nth-child(7)", "Type Definitions") -assert-text: (".sidebar-elems > .items > ul > li:nth-child(8)", "Keywords") +assert-text: (".sidebar-elems > .items > ul > li:nth-child(8)", "Unions") +assert-text: (".sidebar-elems > .items > ul > li:nth-child(9)", "Keywords") assert-text: ("#structs + .item-table .item-left > a", "Foo") click: "#structs + .item-table .item-left > a" diff --git a/src/test/rustdoc-gui/src/test_docs/lib.rs b/src/test/rustdoc-gui/src/test_docs/lib.rs index 652308a71cb85..14d8b18613087 100644 --- a/src/test/rustdoc-gui/src/test_docs/lib.rs +++ b/src/test/rustdoc-gui/src/test_docs/lib.rs @@ -131,3 +131,129 @@ macro_rules! repro { } pub use crate::repro as repro2; + +/// # Top-doc Prose title +/// +/// Text below title. +/// +/// ## Top-doc Prose sub-heading +/// +/// Text below sub-heading. +/// +/// ### Top-doc Prose sub-sub-heading +/// +/// Text below sub-sub-heading +pub struct HeavilyDocumentedStruct { + /// # Title for field + /// ## Sub-heading for field + pub nothing: (), +} + +/// # Title for struct impl doc +/// +/// Text below heading. +/// +/// ## Sub-heading for struct impl doc +/// +/// Text below sub-heading. +/// +/// ### Sub-sub-heading for struct impl doc +/// +/// Text below sub-sub-heading. +/// +impl HeavilyDocumentedStruct { + /// # Title for struct impl-item doc + /// Text below title. + /// ## Sub-heading for struct impl-item doc + /// Text below sub-heading. + /// ### Sub-sub-heading for struct impl-item doc + /// Text below sub-sub-heading. + pub fn do_nothing() {} +} + +/// # Top-doc Prose title +/// +/// Text below title. +/// +/// ## Top-doc Prose sub-heading +/// +/// Text below sub-heading. +/// +/// ### Top-doc Prose sub-sub-heading +/// +/// Text below sub-sub-heading +pub enum HeavilyDocumentedEnum { + /// # None prose title + /// ## None prose sub-heading + None, + /// # Wrapped prose title + /// ## Wrapped prose sub-heading + Wrapped( + /// # Wrapped.0 prose title + /// ## Wrapped.0 prose sub-heading + String, + String, + ), + Structy { + /// # Structy prose title + /// ## Structy prose sub-heading + alpha: String, + beta: String, + }, +} + +/// # Title for enum impl doc +/// +/// Text below heading. +/// +/// ## Sub-heading for enum impl doc +/// +/// Text below sub-heading. +/// +/// ### Sub-sub-heading for enum impl doc +/// +/// Text below sub-sub-heading. +/// +impl HeavilyDocumentedEnum { + /// # Title for enum impl-item doc + /// Text below title. + /// ## Sub-heading for enum impl-item doc + /// Text below sub-heading. + /// ### Sub-sub-heading for enum impl-item doc + /// Text below sub-sub-heading. + pub fn do_nothing() {} +} + +/// # Top-doc prose title +/// +/// Text below heading. +/// +/// ## Top-doc prose sub-heading +/// +/// Text below heading. +pub union HeavilyDocumentedUnion { + /// # Title for union variant + /// ## Sub-heading for union variant + pub nothing: (), + pub something: f32, +} + +/// # Title for union impl doc +/// ## Sub-heading for union impl doc +impl HeavilyDocumentedUnion { + /// # Title for union impl-item doc + /// ## Sub-heading for union impl-item doc + pub fn do_nothing() {} +} + +/// # Top-doc prose title +/// +/// Text below heading. +/// +/// ## Top-doc prose sub-heading +/// +/// Text below heading. +#[macro_export] +macro_rules! heavily_documented_macro { + () => {}; +} From 4614ca4541c891e044c447c8ee7d50d325bdc6a6 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 1 Oct 2021 17:12:39 +0200 Subject: [PATCH 3/4] Fix clippy lints in librustdoc --- src/librustdoc/clean/auto_trait.rs | 24 ++++---- src/librustdoc/clean/mod.rs | 50 +++++++-------- src/librustdoc/clean/types.rs | 24 ++++---- src/librustdoc/clean/utils.rs | 16 ++--- src/librustdoc/config.rs | 20 +++--- src/librustdoc/core.rs | 4 +- src/librustdoc/doctest.rs | 8 +-- src/librustdoc/formats/cache.rs | 4 +- src/librustdoc/html/format.rs | 10 +-- src/librustdoc/html/highlight.rs | 4 +- src/librustdoc/html/layout.rs | 6 +- src/librustdoc/html/markdown.rs | 61 ++++++++----------- src/librustdoc/html/render/cache.rs | 26 ++++---- src/librustdoc/html/render/context.rs | 4 +- src/librustdoc/html/render/mod.rs | 37 ++++++----- src/librustdoc/html/render/print_item.rs | 12 ++-- src/librustdoc/html/render/span_map.rs | 49 ++++++--------- src/librustdoc/html/render/write_shared.rs | 2 +- src/librustdoc/html/sources.rs | 6 +- src/librustdoc/json/conversions.rs | 2 +- src/librustdoc/lib.rs | 2 +- src/librustdoc/passes/bare_urls.rs | 2 +- .../passes/check_code_block_syntax.rs | 10 +-- .../passes/check_doc_test_visibility.rs | 4 +- .../passes/collect_intra_doc_links.rs | 21 +++---- .../passes/collect_intra_doc_links/early.rs | 4 +- src/librustdoc/visit_ast.rs | 3 +- 27 files changed, 194 insertions(+), 221 deletions(-) diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 05817e1b1d99e..ba701f42c660b 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -136,7 +136,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { let f = auto_trait::AutoTraitFinder::new(tcx); debug!("get_auto_trait_impls({:?})", ty); - let auto_traits: Vec<_> = self.cx.auto_traits.iter().cloned().collect(); + let auto_traits: Vec<_> = self.cx.auto_traits.iter().copied().collect(); let mut auto_traits: Vec = auto_traits .into_iter() .filter_map(|trait_def_id| { @@ -193,8 +193,8 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { // to its smaller and larger regions. Note that 'larger' regions correspond // to sub-regions in Rust code (e.g., in 'a: 'b, 'a is the larger region). for constraint in regions.constraints.keys() { - match constraint { - &Constraint::VarSubVar(r1, r2) => { + match *constraint { + Constraint::VarSubVar(r1, r2) => { { let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default(); deps1.larger.insert(RegionTarget::RegionVid(r2)); @@ -203,15 +203,15 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default(); deps2.smaller.insert(RegionTarget::RegionVid(r1)); } - &Constraint::RegSubVar(region, vid) => { + Constraint::RegSubVar(region, vid) => { let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default(); deps.smaller.insert(RegionTarget::Region(region)); } - &Constraint::VarSubReg(vid, region) => { + Constraint::VarSubReg(vid, region) => { let deps = vid_map.entry(RegionTarget::RegionVid(vid)).or_default(); deps.larger.insert(RegionTarget::Region(region)); } - &Constraint::RegSubReg(r1, r2) => { + Constraint::RegSubReg(r1, r2) => { // The constraint is already in the form that we want, so we're done with it // Desired order is 'larger, smaller', so flip then if region_name(r1) != region_name(r2) { @@ -513,8 +513,8 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { // as we want to combine them with any 'Output' qpaths // later - let is_fn = match &mut b { - &mut GenericBound::TraitBound(ref mut p, _) => { + let is_fn = match b { + GenericBound::TraitBound(ref mut p, _) => { // Insert regions into the for_generics hash map first, to ensure // that we don't end up with duplicate bounds (e.g., for<'b, 'b>) for_generics.extend(p.generic_params.clone()); @@ -699,8 +699,8 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { } fn region_name(region: Region<'_>) -> Option { - match region { - &ty::ReEarlyBound(r) => Some(r.name), + match *region { + ty::ReEarlyBound(r) => Some(r.name), _ => None, } } @@ -717,8 +717,8 @@ impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> { } fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { - (match r { - &ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(), + (match *r { + ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(), _ => None, }) .unwrap_or_else(|| r.super_fold_with(self)) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7a1c561c8e531..d6bc870d3f9b0 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -216,17 +216,15 @@ impl<'tcx> Clean for ty::PolyTraitRef<'tcx> { impl Clean for hir::Lifetime { fn clean(&self, cx: &mut DocContext<'_>) -> Lifetime { let def = cx.tcx.named_region(self.hir_id); - match def { - Some( - rl::Region::EarlyBound(_, node_id, _) - | rl::Region::LateBound(_, _, node_id, _) - | rl::Region::Free(_, node_id), - ) => { - if let Some(lt) = cx.lt_substs.get(&node_id).cloned() { - return lt; - } + if let Some( + rl::Region::EarlyBound(_, node_id, _) + | rl::Region::LateBound(_, _, node_id, _) + | rl::Region::Free(_, node_id), + ) = def + { + if let Some(lt) = cx.lt_substs.get(&node_id).cloned() { + return lt; } - _ => {} } Lifetime(self.name.ident().name) } @@ -828,7 +826,7 @@ impl<'a> Clean for (&'a [hir::Ty<'a>], hir::BodyId) { .iter() .enumerate() .map(|(i, ty)| Argument { - name: name_from_pat(&body.params[i].pat), + name: name_from_pat(body.params[i].pat), type_: ty.clean(cx), }) .collect(), @@ -924,7 +922,7 @@ impl Clean for hir::TraitItem<'_> { } MethodItem(m, None) } - hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => { + hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => { let (generics, decl) = enter_impl_trait(cx, |cx| { (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx)) }); @@ -936,7 +934,7 @@ impl Clean for hir::TraitItem<'_> { } TyMethodItem(t) } - hir::TraitItemKind::Type(ref bounds, ref default) => { + hir::TraitItemKind::Type(bounds, ref default) => { AssocTypeItem(bounds.clean(cx), default.clean(cx)) } }; @@ -1260,7 +1258,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type { let path = path.clean(cx); resolve_type(cx, path) } - hir::QPath::Resolved(Some(ref qself), ref p) => { + hir::QPath::Resolved(Some(ref qself), p) => { // Try to normalize `::T` to a type let ty = hir_ty_to_ty(cx.tcx, hir_ty); if let Some(normalized_value) = normalize(cx, ty) { @@ -1281,7 +1279,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type { trait_, } } - hir::QPath::TypeRelative(ref qself, ref segment) => { + hir::QPath::TypeRelative(ref qself, segment) => { let ty = hir_ty_to_ty(cx.tcx, hir_ty); let res = match ty.kind() { ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id), @@ -1337,7 +1335,7 @@ impl Clean for hir::Ty<'_> { let length = print_const(cx, ct.eval(cx.tcx, param_env)); Array(box ty.clean(cx), length) } - TyKind::Tup(ref tys) => Tuple(tys.clean(cx)), + TyKind::Tup(tys) => Tuple(tys.clean(cx)), TyKind::OpaqueDef(item_id, _) => { let item = cx.tcx.hir().item(item_id); if let hir::ItemKind::OpaqueTy(ref ty) = item.kind { @@ -1346,8 +1344,8 @@ impl Clean for hir::Ty<'_> { unreachable!() } } - TyKind::Path(_) => clean_qpath(&self, cx), - TyKind::TraitObject(ref bounds, ref lifetime, _) => { + TyKind::Path(_) => clean_qpath(self, cx), + TyKind::TraitObject(bounds, ref lifetime, _) => { let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect(); let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None }; DynTrait(bounds, lifetime) @@ -1441,7 +1439,7 @@ impl<'tcx> Clean for Ty<'tcx> { let path = external_path(cx, did, false, vec![], InternalSubsts::empty()); ResolvedPath { path, did } } - ty::Dynamic(ref obj, ref reg) => { + ty::Dynamic(obj, ref reg) => { // HACK: pick the first `did` as the `did` of the trait object. Someone // might want to implement "native" support for marker-trait-only // trait objects. @@ -1481,9 +1479,7 @@ impl<'tcx> Clean for Ty<'tcx> { DynTrait(bounds, lifetime) } - ty::Tuple(ref t) => { - Tuple(t.iter().map(|t| t.expect_ty()).collect::>().clean(cx)) - } + ty::Tuple(t) => Tuple(t.iter().map(|t| t.expect_ty()).collect::>().clean(cx)), ty::Projection(ref data) => data.clean(cx), @@ -1821,9 +1817,9 @@ impl Clean> for (&hir::Item<'_>, Option) { clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx) } ItemKind::Macro(ref macro_def) => MacroItem(Macro { - source: display_macro_source(cx, name, ¯o_def, def_id, &item.vis), + source: display_macro_source(cx, name, macro_def, def_id, &item.vis), }), - ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => { + ItemKind::Trait(is_auto, unsafety, ref generics, bounds, item_ids) => { let items = item_ids .iter() .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx)) @@ -2065,10 +2061,10 @@ impl Clean for (&hir::ForeignItem<'_>, Option) { let def_id = item.def_id.to_def_id(); cx.with_param_env(def_id, |cx| { let kind = match item.kind { - hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => { + hir::ForeignItemKind::Fn(decl, names, ref generics) => { let abi = cx.tcx.hir().get_foreign_abi(item.hir_id()); let (generics, decl) = enter_impl_trait(cx, |cx| { - (generics.clean(cx), (&**decl, &names[..]).clean(cx)) + (generics.clean(cx), (&*decl, &names[..]).clean(cx)) }); ForeignFunctionItem(Function { decl, @@ -2113,7 +2109,7 @@ impl Clean for hir::TypeBindingKind<'_> { hir::TypeBindingKind::Equality { ref ty } => { TypeBindingKind::Equality { ty: ty.clean(cx) } } - hir::TypeBindingKind::Constraint { ref bounds } => { + hir::TypeBindingKind::Constraint { bounds } => { TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() } } } diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index d25e166629fa2..0a6d5f97c4e6b 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -204,7 +204,7 @@ impl ExternalCrate { .filter_map(|a| a.value_str()) .map(to_remote) .next() - .or(extern_url.map(to_remote)) // NOTE: only matters if `extern_url_takes_precedence` is false + .or_else(|| extern_url.map(to_remote)) // NOTE: only matters if `extern_url_takes_precedence` is false .unwrap_or(Unknown) // Well, at least we tried. } @@ -238,7 +238,7 @@ impl ExternalCrate { hir::ItemKind::Mod(_) => { as_keyword(Res::Def(DefKind::Mod, id.def_id.to_def_id())) } - hir::ItemKind::Use(ref path, hir::UseKind::Single) + hir::ItemKind::Use(path, hir::UseKind::Single) if item.vis.node.is_pub() => { as_keyword(path.res.expect_non_local()) @@ -304,7 +304,7 @@ impl ExternalCrate { hir::ItemKind::Mod(_) => { as_primitive(Res::Def(DefKind::Mod, id.def_id.to_def_id())) } - hir::ItemKind::Use(ref path, hir::UseKind::Single) + hir::ItemKind::Use(path, hir::UseKind::Single) if item.vis.node.is_pub() => { as_primitive(path.res.expect_non_local()).map(|(_, prim)| { @@ -381,7 +381,7 @@ impl Item { { *span } else { - self.def_id.as_def_id().map(|did| rustc_span(did, tcx)).unwrap_or_else(|| Span::dummy()) + self.def_id.as_def_id().map(|did| rustc_span(did, tcx)).unwrap_or_else(Span::dummy) } } @@ -562,7 +562,7 @@ impl Item { } crate fn stability_class(&self, tcx: TyCtxt<'_>) -> Option { - self.stability(tcx).as_ref().and_then(|ref s| { + self.stability(tcx).as_ref().and_then(|s| { let mut classes = Vec::with_capacity(2); if s.level.is_unstable() { @@ -820,9 +820,9 @@ impl AttributesExt for [ast::Attribute] { // #[doc(cfg(...))] if let Some(cfg_mi) = item .meta_item() - .and_then(|item| rustc_expand::config::parse_cfg(&item, sess)) + .and_then(|item| rustc_expand::config::parse_cfg(item, sess)) { - match Cfg::parse(&cfg_mi) { + match Cfg::parse(cfg_mi) { Ok(new_cfg) => cfg &= new_cfg, Err(e) => sess.span_err(e.span, e.msg), } @@ -934,7 +934,7 @@ impl<'a> FromIterator<&'a DocFragment> for String { T: IntoIterator, { iter.into_iter().fold(String::new(), |mut acc, frag| { - add_doc_fragment(&mut acc, &frag); + add_doc_fragment(&mut acc, frag); acc }) } @@ -1061,12 +1061,12 @@ impl Attributes { let ori = iter.next()?; let mut out = String::new(); - add_doc_fragment(&mut out, &ori); - while let Some(new_frag) = iter.next() { + add_doc_fragment(&mut out, ori); + for new_frag in iter { if new_frag.kind != ori.kind || new_frag.parent_module != ori.parent_module { break; } - add_doc_fragment(&mut out, &new_frag); + add_doc_fragment(&mut out, new_frag); } if out.is_empty() { None } else { Some(out) } } @@ -1079,7 +1079,7 @@ impl Attributes { for new_frag in self.doc_strings.iter() { let out = ret.entry(new_frag.parent_module).or_default(); - add_doc_fragment(out, &new_frag); + add_doc_fragment(out, new_frag); } ret } diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index de43daff6f0d7..0573a1ada3a84 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -171,8 +171,8 @@ crate fn strip_path_generics(path: Path) -> Path { crate fn qpath_to_string(p: &hir::QPath<'_>) -> String { let segments = match *p { - hir::QPath::Resolved(_, ref path) => &path.segments, - hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(), + hir::QPath::Resolved(_, path) => &path.segments, + hir::QPath::TypeRelative(_, segment) => return segment.ident.to_string(), hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(), }; @@ -217,15 +217,15 @@ crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { PatKind::Wild | PatKind::Struct(..) => return kw::Underscore, PatKind::Binding(_, _, ident, _) => return ident.name, PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p), - PatKind::Or(ref pats) => { + PatKind::Or(pats) => { pats.iter().map(|p| name_from_pat(p).to_string()).collect::>().join(" | ") } - PatKind::Tuple(ref elts, _) => format!( + PatKind::Tuple(elts, _) => format!( "({})", elts.iter().map(|p| name_from_pat(p).to_string()).collect::>().join(", ") ), - PatKind::Box(ref p) => return name_from_pat(&**p), - PatKind::Ref(ref p, _) => return name_from_pat(&**p), + PatKind::Box(p) => return name_from_pat(&*p), + PatKind::Ref(p, _) => return name_from_pat(&*p), PatKind::Lit(..) => { warn!( "tried to get argument name from PatKind::Lit, which is silly in function arguments" @@ -233,7 +233,7 @@ crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { return Symbol::intern("()"); } PatKind::Range(..) => return kw::Underscore, - PatKind::Slice(ref begin, ref mid, ref end) => { + PatKind::Slice(begin, ref mid, end) => { let begin = begin.iter().map(|p| name_from_pat(p).to_string()); let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter(); let end = end.iter().map(|p| name_from_pat(p).to_string()); @@ -507,7 +507,7 @@ crate fn has_doc_flag(attrs: ty::Attributes<'_>, flag: Symbol) -> bool { /// so that the channel is consistent. /// /// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable. -crate const DOC_RUST_LANG_ORG_CHANNEL: &'static str = env!("DOC_RUST_LANG_ORG_CHANNEL"); +crate const DOC_RUST_LANG_ORG_CHANNEL: &str = env!("DOC_RUST_LANG_ORG_CHANNEL"); /// Render a sequence of macro arms in a format suitable for displaying to the user /// as part of an item declaration. diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 7342478c3ec0d..493aa56fce6ef 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -321,13 +321,13 @@ impl Options { /// been printed, returns `Err` with the exit code. crate fn from_matches(matches: &getopts::Matches) -> Result { // Check for unstable options. - nightly_options::check_nightly_options(&matches, &opts()); + nightly_options::check_nightly_options(matches, &opts()); if matches.opt_present("h") || matches.opt_present("help") { crate::usage("rustdoc"); return Err(0); } else if matches.opt_present("version") { - rustc_driver::version("rustdoc", &matches); + rustc_driver::version("rustdoc", matches); return Err(0); } @@ -363,10 +363,10 @@ impl Options { return Err(0); } - let color = config::parse_color(&matches); + let color = config::parse_color(matches); let config::JsonConfig { json_rendered, json_unused_externs, .. } = - config::parse_json(&matches); - let error_format = config::parse_error_format(&matches, color, json_rendered); + config::parse_json(matches); + let error_format = config::parse_error_format(matches, color, json_rendered); let codegen_options = CodegenOptions::build(matches, error_format); let debugging_opts = DebuggingOptions::build(matches, error_format); @@ -374,7 +374,7 @@ impl Options { let diag = new_handler(error_format, None, &debugging_opts); // check for deprecated options - check_deprecated_options(&matches, &diag); + check_deprecated_options(matches, &diag); let mut emit = Vec::new(); for list in matches.opt_strs("emit") { @@ -440,8 +440,8 @@ impl Options { .iter() .map(|s| SearchPath::from_cli_opt(s, error_format)) .collect(); - let externs = parse_externs(&matches, &debugging_opts, error_format); - let extern_html_root_urls = match parse_extern_html_roots(&matches) { + let externs = parse_externs(matches, &debugging_opts, error_format); + let extern_html_root_urls = match parse_extern_html_roots(matches) { Ok(ex) => ex, Err(err) => { diag.struct_err(err).emit(); @@ -560,7 +560,7 @@ impl Options { } } - let edition = config::parse_crate_edition(&matches); + let edition = config::parse_crate_edition(matches); let mut id_map = html::markdown::IdMap::new(); let external_html = match ExternalHtml::load( @@ -569,7 +569,7 @@ impl Options { &matches.opt_strs("html-after-content"), &matches.opt_strs("markdown-before-content"), &matches.opt_strs("markdown-after-content"), - nightly_options::match_is_nightly_build(&matches), + nightly_options::match_is_nightly_build(matches), &diag, &mut id_map, edition, diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 074744b3d11e2..b7251e8f57151 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -85,7 +85,7 @@ crate struct DocContext<'tcx> { impl<'tcx> DocContext<'tcx> { crate fn sess(&self) -> &'tcx Session { - &self.tcx.sess + self.tcx.sess } crate fn with_param_env T>(&mut self, def_id: DefId, f: F) -> T { @@ -464,7 +464,7 @@ crate fn run_global_ctxt( _ => continue, }; for name in value.as_str().split_whitespace() { - let span = attr.name_value_literal_span().unwrap_or(attr.span()); + let span = attr.name_value_literal_span().unwrap_or_else(|| attr.span()); manual_passes.extend(parse_pass(name, Some(span))); } } diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 9e64d200b4373..9b32ad979e385 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -73,7 +73,7 @@ crate fn run(options: Options) -> Result<(), ErrorReported> { search_paths: options.libs.clone(), crate_types, lint_opts: if !options.display_doctest_warnings { lint_opts } else { vec![] }, - lint_cap: Some(options.lint_cap.unwrap_or_else(|| lint::Forbid)), + lint_cap: Some(options.lint_cap.unwrap_or(lint::Forbid)), cg: options.codegen_options.clone(), externs: options.externs.clone(), unstable_features: options.render_options.unstable_features, @@ -176,7 +176,7 @@ crate fn run(options: Options) -> Result<(), ErrorReported> { .iter() .map(|uexts| uexts.unused_extern_names.iter().collect::>()) .fold(extern_names, |uextsa, uextsb| { - uextsa.intersection(&uextsb).map(|v| *v).collect::>() + uextsa.intersection(&uextsb).copied().collect::>() }) .iter() .map(|v| (*v).clone()) @@ -423,7 +423,7 @@ fn run_test( // Add a \n to the end to properly terminate the last line, // but only if there was output to be printed - if out_lines.len() > 0 { + if !out_lines.is_empty() { out_lines.push(""); } @@ -1124,7 +1124,7 @@ impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> { let mut attrs = Attributes::from_ast(ast_attrs, None); if let Some(ref cfg) = ast_attrs.cfg(self.tcx, &FxHashSet::default()) { - if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) { + if !cfg.matches(&self.sess.parse_sess, Some(self.sess.features_untracked())) { return; } } diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index 8b883ffaaf095..c733b8fe0817b 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -292,7 +292,7 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { // inserted later on when serializing the search-index. if item.def_id.index().map_or(false, |idx| idx != CRATE_DEF_INDEX) { let desc = item.doc_value().map_or_else(String::new, |x| { - short_markdown_summary(&x.as_str(), &item.link_names(&self.cache)) + short_markdown_summary(x.as_str(), &item.link_names(self.cache)) }); self.cache.search_index.push(IndexItem { ty: item.type_(), @@ -462,7 +462,7 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { let impl_item = Impl { impl_item: item }; if impl_item.trait_did().map_or(true, |d| self.cache.traits.contains_key(&d)) { for did in dids { - self.cache.impls.entry(did).or_insert(vec![]).push(impl_item.clone()); + self.cache.impls.entry(did).or_insert_with(Vec::new).push(impl_item.clone()); } } else { let trait_did = impl_item.trait_did().expect("no trait did"); diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index f2751947c7eb9..c51bda60b7385 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -597,7 +597,7 @@ crate fn href_relative_parts<'a>(fqp: &'a [String], relative_to_fqp: &'a [String /// Used when rendering a `ResolvedPath` structure. This invokes the `path` /// rendering function with the necessary arguments for linking to a local path. -fn resolved_path<'a, 'cx: 'a>( +fn resolved_path<'cx>( w: &mut fmt::Formatter<'_>, did: DefId, path: &clean::Path, @@ -696,7 +696,7 @@ fn primitive_link( /// Helper to render type parameters fn tybounds<'a, 'tcx: 'a>( - bounds: &'a Vec, + bounds: &'a [clean::PolyTrait], lt: &'a Option, cx: &'a Context<'tcx>, ) -> impl fmt::Display + 'a + Captures<'tcx> { @@ -886,7 +886,7 @@ fn fmt_type<'cx>( if bounds.len() > 1 || trait_lt.is_some() => { write!(f, "{}{}{}(", amp, lt, m)?; - fmt_type(&ty, f, use_absolute, cx)?; + fmt_type(ty, f, use_absolute, cx)?; write!(f, ")") } clean::Generic(..) => { @@ -896,11 +896,11 @@ fn fmt_type<'cx>( &format!("{}{}{}", amp, lt, m), cx, )?; - fmt_type(&ty, f, use_absolute, cx) + fmt_type(ty, f, use_absolute, cx) } _ => { write!(f, "{}{}{}", amp, lt, m)?; - fmt_type(&ty, f, use_absolute, cx) + fmt_type(ty, f, use_absolute, cx) } } } diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index fa8ad2a37e726..66059ef65de6d 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -62,7 +62,7 @@ crate fn render_with_highlighting( } write_header(out, class, extra_content); - write_code(out, &src, edition, context_info, decoration_info); + write_code(out, src, edition, context_info, decoration_info); write_footer(out, playground_button); } @@ -718,7 +718,7 @@ fn string( .map(|(url, _, _)| url) } LinkFromSrc::Primitive(prim) => format::href_with_root_path( - PrimitiveType::primitive_locations(context.tcx())[&prim], + PrimitiveType::primitive_locations(context.tcx())[prim], context, Some(context_info.root_path), ) diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index bd06f88cb3587..71d7cc1a09dce 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -68,10 +68,8 @@ crate fn render( let krate_with_trailing_slash = ensure_trailing_slash(&layout.krate).to_string(); let style_files = style_files .iter() - .filter_map(|t| { - if let Some(stem) = t.path.file_stem() { Some((stem, t.disabled)) } else { None } - }) - .filter_map(|t| if let Some(path) = t.0.to_str() { Some((path, t.1)) } else { None }) + .filter_map(|t| t.path.file_stem().map(|stem| (stem, t.disabled))) + .filter_map(|t| t.0.to_str().map(|path| (path, t.1))) .map(|t| { format!( r#""#, diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index bda0f0aa3f13e..47772651bf9b9 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -178,7 +178,7 @@ fn map_line(s: &str) -> Line<'_> { Line::Shown(Cow::Owned(s.replacen("##", "#", 1))) } else if let Some(stripped) = trimmed.strip_prefix("# ") { // # text - Line::Hidden(&stripped) + Line::Hidden(stripped) } else if trimmed == "#" { // We cannot handle '#text' because it could be #[attr]. Line::Hidden("") @@ -258,7 +258,7 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { let parse_result = match kind { CodeBlockKind::Fenced(ref lang) => { let parse_result = - LangString::parse_without_check(&lang, self.check_error_codes, false); + LangString::parse_without_check(lang, self.check_error_codes, false); if !parse_result.rust { return Some(Event::Html( format!( @@ -669,7 +669,7 @@ impl<'a, I: Iterator>> Iterator for Footnotes<'a, I> { loop { match self.inner.next() { Some((Event::FootnoteReference(ref reference), range)) => { - let entry = self.get_entry(&reference); + let entry = self.get_entry(reference); let reference = format!( "{0}", (*entry).1 @@ -904,7 +904,7 @@ impl LangString { string .split(|c| c == ',' || c == ' ' || c == '\t') .map(str::trim) - .map(|token| if token.chars().next() == Some('.') { &token[1..] } else { token }) + .map(|token| token.strip_prefix('.').unwrap_or(token)) .filter(|token| !token.is_empty()) } @@ -974,7 +974,10 @@ impl LangString { } x if extra.is_some() => { let s = x.to_lowercase(); - match if s == "compile-fail" || s == "compile_fail" || s == "compilefail" { + if let Some((flag, help)) = if s == "compile-fail" + || s == "compile_fail" + || s == "compilefail" + { Some(( "compile_fail", "the code block will either not be tested if not marked as a rust one \ @@ -1007,15 +1010,12 @@ impl LangString { } else { None } { - Some((flag, help)) => { - if let Some(ref extra) = extra { - extra.error_invalid_codeblock_attr( - &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag), - help, - ); - } + if let Some(extra) = extra { + extra.error_invalid_codeblock_attr( + &format!("unknown attribute `{}`. Did you mean `{}`?", x, flag), + help, + ); } - None => {} } seen_other_tags = true; } @@ -1051,13 +1051,10 @@ impl Markdown<'_> { return String::new(); } let mut replacer = |broken_link: BrokenLink<'_>| { - if let Some(link) = - links.iter().find(|link| &*link.original_text == broken_link.reference) - { - Some((link.href.as_str().into(), link.new_text.as_str().into())) - } else { - None - } + links + .iter() + .find(|link| &*link.original_text == broken_link.reference) + .map(|link| (link.href.as_str().into(), link.new_text.as_str().into())) }; let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut replacer)); @@ -1135,13 +1132,10 @@ impl MarkdownSummaryLine<'_> { } let mut replacer = |broken_link: BrokenLink<'_>| { - if let Some(link) = - links.iter().find(|link| &*link.original_text == broken_link.reference) - { - Some((link.href.as_str().into(), link.new_text.as_str().into())) - } else { - None - } + links + .iter() + .find(|link| &*link.original_text == broken_link.reference) + .map(|link| (link.href.as_str().into(), link.new_text.as_str().into())) }; let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer)); @@ -1172,13 +1166,10 @@ fn markdown_summary_with_limit( } let mut replacer = |broken_link: BrokenLink<'_>| { - if let Some(link) = - link_names.iter().find(|link| &*link.original_text == broken_link.reference) - { - Some((link.href.as_str().into(), link.new_text.as_str().into())) - } else { - None - } + link_names + .iter() + .find(|link| &*link.original_text == broken_link.reference) + .map(|link| (link.href.as_str().into(), link.new_text.as_str().into())) }; let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer)); @@ -1413,7 +1404,7 @@ crate fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_>) -> Vec { // The ending of the offset goes too far sometime so we reduce it by one in // these cases. - if offset.end > offset.start && md.get(offset.end..=offset.end) == Some(&"\n") { + if offset.end > offset.start && md.get(offset.end..=offset.end) == Some("\n") { ( LangString::default(), offset.start, diff --git a/src/librustdoc/html/render/cache.rs b/src/librustdoc/html/render/cache.rs index 9c05c80d55dfe..7142a84d6b017 100644 --- a/src/librustdoc/html/render/cache.rs +++ b/src/librustdoc/html/render/cache.rs @@ -1,3 +1,4 @@ +use std::collections::hash_map::Entry; use std::collections::BTreeMap; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -36,7 +37,7 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt< if let Some(&(ref fqp, _)) = cache.paths.get(&did) { let desc = item .doc_value() - .map_or_else(String::new, |s| short_markdown_summary(&s, &item.link_names(&cache))); + .map_or_else(String::new, |s| short_markdown_summary(&s, &item.link_names(cache))); cache.search_index.push(IndexItem { ty: item.type_(), name: item.name.unwrap().to_string(), @@ -44,7 +45,7 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt< desc, parent: Some(did), parent_idx: None, - search_type: get_index_search_type(&item, tcx), + search_type: get_index_search_type(item, tcx), aliases: item.attrs.get_doc_aliases(), }); } @@ -53,7 +54,7 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt< let crate_doc = krate .module .doc_value() - .map_or_else(String::new, |s| short_markdown_summary(&s, &krate.module.link_names(&cache))); + .map_or_else(String::new, |s| short_markdown_summary(&s, &krate.module.link_names(cache))); let Cache { ref mut search_index, ref paths, .. } = *cache; @@ -72,7 +73,7 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt< // Set up alias indexes. for (i, item) in search_index.iter().enumerate() { for alias in &item.aliases[..] { - aliases.entry(alias.to_lowercase()).or_insert(Vec::new()).push(i); + aliases.entry(alias.to_lowercase()).or_insert_with(Vec::new).push(i); } } @@ -82,12 +83,11 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt< let mut lastpathid = 0usize; for item in search_index { - item.parent_idx = item.parent.and_then(|defid| { - if defid_to_pathid.contains_key(&defid) { - defid_to_pathid.get(&defid).copied() - } else { + item.parent_idx = item.parent.and_then(|defid| match defid_to_pathid.entry(defid) { + Entry::Occupied(entry) => Some(*entry.get()), + Entry::Vacant(entry) => { let pathid = lastpathid; - defid_to_pathid.insert(defid, pathid); + entry.insert(pathid); lastpathid += 1; if let Some(&(ref fqp, short)) = paths.get(&defid) { @@ -203,12 +203,12 @@ crate fn get_index_search_type<'tcx>( let inputs = all_types .iter() - .map(|(ty, kind)| TypeWithKind::from((get_index_type(&ty), *kind))) + .map(|(ty, kind)| TypeWithKind::from((get_index_type(ty), *kind))) .filter(|a| a.ty.name.is_some()) .collect(); let output = ret_types .iter() - .map(|(ty, kind)| TypeWithKind::from((get_index_type(&ty), *kind))) + .map(|(ty, kind)| TypeWithKind::from((get_index_type(ty), *kind))) .filter(|a| a.ty.name.is_some()) .collect::>(); let output = if output.is_empty() { None } else { Some(output) }; @@ -296,7 +296,7 @@ crate fn get_real_types<'tcx>( } let mut nb_added = 0; - if let &Type::Generic(arg_s) = arg { + if let Type::Generic(arg_s) = *arg { if let Some(where_pred) = generics.where_predicates.iter().find(|g| match g { WherePredicate::BoundPredicate { ty, .. } => ty.def_id() == arg.def_id(), _ => false, @@ -374,7 +374,7 @@ crate fn get_all_types<'tcx>( let ret_types = match decl.output { FnRetTy::Return(ref return_type) => { let mut ret = FxHashSet::default(); - get_real_types(generics, &return_type, tcx, 0, &mut ret); + get_real_types(generics, return_type, tcx, 0, &mut ret); if ret.is_empty() { if let Some(kind) = return_type.def_id().map(|did| tcx.def_kind(did).into()) { ret.insert((return_type.clone(), kind)); diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index d7ef8513d6a89..0e29cc85f9e75 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -160,7 +160,7 @@ impl<'tcx> Context<'tcx> { } pub(super) fn sess(&self) -> &'tcx Session { - &self.shared.tcx.sess + self.shared.tcx.sess } pub(super) fn derive_id(&self, id: String) -> String { @@ -188,7 +188,7 @@ impl<'tcx> Context<'tcx> { }; title.push_str(" - Rust"); let tyname = it.type_(); - let desc = it.doc_value().as_ref().map(|doc| plain_text_summary(&doc)); + let desc = it.doc_value().as_ref().map(|doc| plain_text_summary(doc)); let desc = if let Some(desc) = desc { desc } else if it.is_crate() { diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index bd6cb9c298842..a5e62baca3816 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -126,8 +126,8 @@ impl Serialize for IndexItemFunctionType { // If we couldn't figure out a type, just write `null`. let mut iter = self.inputs.iter(); if match self.output { - Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()), - None => iter.any(|ref i| i.ty.name.is_none()), + Some(ref output) => iter.chain(output.iter()).any(|i| i.ty.name.is_none()), + None => iter.any(|i| i.ty.name.is_none()), } { serializer.serialize_none() } else { @@ -906,7 +906,7 @@ fn render_assoc_item( AssocItemLink::GotoSource(did, provided_methods) => { // We're creating a link from an impl-item to the corresponding // trait-item and need to map the anchored type accordingly. - let ty = if provided_methods.contains(&name) { + let ty = if provided_methods.contains(name) { ItemType::Method } else { ItemType::TyMethod @@ -965,7 +965,7 @@ fn render_assoc_item( name = name, generics = g.print(cx), decl = d.full_print(header_len, indent, header.asyncness, cx), - notable_traits = notable_traits_decl(&d, cx), + notable_traits = notable_traits_decl(d, cx), where_clause = print_where_clause(g, cx, indent, end_newline), ) } @@ -1008,7 +1008,7 @@ fn attributes(it: &clean::Item) -> Vec { .iter() .filter_map(|attr| { if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) { - Some(pprust::attribute_to_string(&attr).replace("\n", "").replace(" ", " ")) + Some(pprust::attribute_to_string(attr).replace("\n", "").replace(" ", " ")) } else { None } @@ -1041,7 +1041,7 @@ enum AssocItemLink<'a> { impl<'a> AssocItemLink<'a> { fn anchor(&self, id: &'a str) -> Self { match *self { - AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)), + AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(id)), ref other => *other, } } @@ -1120,7 +1120,7 @@ fn render_assoc_items( let (blanket_impl, concrete): (Vec<&&Impl>, _) = concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some()); - let mut impls = Buffer::empty_from(&w); + let mut impls = Buffer::empty_from(w); render_impls(cx, &mut impls, &concrete, containing_item); let impls = impls.into_inner(); if !impls.is_empty() { @@ -1333,7 +1333,7 @@ fn render_impl( && match render_mode { RenderMode::Normal => true, RenderMode::ForDeref { mut_: deref_mut_ } => { - should_render_item(&item, deref_mut_, cx.tcx()) + should_render_item(item, deref_mut_, cx.tcx()) } }; @@ -1566,7 +1566,7 @@ fn render_impl( &mut impl_items, cx, &t.trait_, - &i.inner_impl(), + i.inner_impl(), &i.impl_item, parent, render_mode, @@ -2060,7 +2060,7 @@ fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) { } } -fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec) { +fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &[Impl]) { let c = cx.cache(); debug!("found Deref: {:?}", impl_); @@ -2159,16 +2159,14 @@ fn get_id_for_impl_on_foreign_type( fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> { match *item.kind { clean::ItemKind::ImplItem(ref i) => { - if let Some(ref trait_) = i.trait_ { + i.trait_.as_ref().map(|trait_| { // Alternative format produces no URLs, // so this parameter does nothing. - Some(( + ( format!("{:#}", i.for_.print(cx)), get_id_for_impl_on_foreign_type(&i.for_, trait_, cx), - )) - } else { - None - } + ) + }) } _ => None, } @@ -2343,9 +2341,10 @@ fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean: let mut variants = e .variants .iter() - .filter_map(|v| match v.name { - Some(ref name) => Some(format!("{name}", name = name)), - _ => None, + .filter_map(|v| { + v.name + .as_ref() + .map(|name| format!("{name}", name = name)) }) .collect::>(); if !variants.is_empty() { diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index f452836962227..12ea7b4f74bce 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -34,10 +34,10 @@ use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine}; use serde::Serialize; -const ITEM_TABLE_OPEN: &'static str = "
"; -const ITEM_TABLE_CLOSE: &'static str = "
"; -const ITEM_TABLE_ROW_OPEN: &'static str = "
"; -const ITEM_TABLE_ROW_CLOSE: &'static str = "
"; +const ITEM_TABLE_OPEN: &str = "
"; +const ITEM_TABLE_CLOSE: &str = "
"; +const ITEM_TABLE_ROW_OPEN: &str = "
"; +const ITEM_TABLE_ROW_CLOSE: &str = "
"; // A component in a `use` path, like `string` in std::string::ToString #[derive(Serialize)] @@ -761,7 +761,7 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra render_impl( w, cx, - &implementor, + implementor, it, assoc_link, RenderMode::Normal, @@ -1497,7 +1497,7 @@ fn render_union( ); if let Some(g) = g { write!(w, "{}", g.print(cx)); - write!(w, "{}", print_where_clause(&g, cx, 0, true)); + write!(w, "{}", print_where_clause(g, cx, 0, true)); } write!(w, " {{\n{}", tab); diff --git a/src/librustdoc/html/render/span_map.rs b/src/librustdoc/html/render/span_map.rs index d517f3ac0e3a9..1a8562d05eab7 100644 --- a/src/librustdoc/html/render/span_map.rs +++ b/src/librustdoc/html/render/span_map.rs @@ -105,7 +105,7 @@ impl Visitor<'tcx> for SpanMapVisitor<'tcx> { } for bound in p.bounds { if let Some(trait_ref) = bound.trait_ref() { - self.handle_path(&trait_ref.path, None); + self.handle_path(trait_ref.path, None); } } } @@ -121,42 +121,33 @@ impl Visitor<'tcx> for SpanMapVisitor<'tcx> { if !span.overlaps(m.inner) { // Now that we confirmed it's a file import, we want to get the span for the module // name only and not all the "mod foo;". - if let Some(node) = self.tcx.hir().find(id) { - match node { - Node::Item(item) => { - self.matches - .insert(item.ident.span, LinkFromSrc::Local(clean::Span::new(m.inner))); - } - _ => {} - } + if let Some(Node::Item(item)) = self.tcx.hir().find(id) { + self.matches.insert(item.ident.span, LinkFromSrc::Local(clean::Span::new(m.inner))); } } intravisit::walk_mod(self, m, id); } fn visit_expr(&mut self, expr: &'tcx rustc_hir::Expr<'tcx>) { - match expr.kind { - ExprKind::MethodCall(segment, method_span, _, _) => { - if let Some(hir_id) = segment.hir_id { - let hir = self.tcx.hir(); - let body_id = hir.enclosing_body_owner(hir_id); - let typeck_results = self.tcx.sess.with_disabled_diagnostic(|| { - self.tcx.typeck_body( - hir.maybe_body_owned_by(body_id).expect("a body which isn't a body"), - ) - }); - if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) { - self.matches.insert( - method_span, - match hir.span_if_local(def_id) { - Some(span) => LinkFromSrc::Local(clean::Span::new(span)), - None => LinkFromSrc::External(def_id), - }, - ); - } + if let ExprKind::MethodCall(segment, method_span, _, _) = expr.kind { + if let Some(hir_id) = segment.hir_id { + let hir = self.tcx.hir(); + let body_id = hir.enclosing_body_owner(hir_id); + let typeck_results = self.tcx.sess.with_disabled_diagnostic(|| { + self.tcx.typeck_body( + hir.maybe_body_owned_by(body_id).expect("a body which isn't a body"), + ) + }); + if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) { + self.matches.insert( + method_span, + match hir.span_if_local(def_id) { + Some(span) => LinkFromSrc::Local(clean::Span::new(span)), + None => LinkFromSrc::External(def_id), + }, + ); } } - _ => {} } intravisit::walk_expr(self, expr); } diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index 31aaf46d7d595..3bb879b507afc 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -128,7 +128,7 @@ impl Context<'_> { ) -> Result<(), Error> { if minify { let contents = contents.as_ref(); - let contents = if resource.extension() == Some(&OsStr::new("css")) { + let contents = if resource.extension() == Some(OsStr::new("css")) { minifier::css::minify(contents).map_err(|e| { Error::new(format!("failed to minify CSS file: {}", e), resource.path(self)) })? diff --git a/src/librustdoc/html/sources.rs b/src/librustdoc/html/sources.rs index ffefc5450cd73..667bbc24ba5ed 100644 --- a/src/librustdoc/html/sources.rs +++ b/src/librustdoc/html/sources.rs @@ -67,7 +67,7 @@ impl LocalSourcesCollector<'_, '_> { } let mut href = String::new(); - clean_path(&self.src_root, &p, false, |component| { + clean_path(self.src_root, &p, false, |component| { href.push_str(&component.to_string_lossy()); href.push('/'); }); @@ -168,7 +168,7 @@ impl SourceCollector<'_, 'tcx> { }; // Remove the utf-8 BOM if any - let contents = if contents.starts_with('\u{feff}') { &contents[3..] } else { &contents }; + let contents = contents.strip_prefix('\u{feff}').unwrap_or(&contents); // Create the intermediate directories let mut cur = self.dst.clone(); @@ -209,7 +209,7 @@ impl SourceCollector<'_, 'tcx> { contents, self.cx.shared.edition(), file_span, - &self.cx, + self.cx, &root_path, None, SourceContext::Standalone, diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 924275dc18588..6fa0425c4956b 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -412,7 +412,7 @@ impl FromWithTcx for Type { .map(|t| { clean::GenericBound::TraitBound(t, rustc_hir::TraitBoundModifier::None) }) - .chain(lt.into_iter().map(|lt| clean::GenericBound::Outlives(lt))) + .chain(lt.into_iter().map(clean::GenericBound::Outlives)) .map(|bound| bound.into_tcx(tcx)) .collect(), } diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 17e00e4b66271..93dffc27659c2 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -775,7 +775,7 @@ fn main_options(options: config::Options) -> MainResult { // We need to hold on to the complete resolver, so we cause everything to be // cloned for the analysis passes to use. Suboptimal, but necessary in the // current architecture. - let resolver = core::create_resolver(queries, &sess); + let resolver = core::create_resolver(queries, sess); if sess.has_errors() { sess.fatal("Compilation failed, aborting rustdoc"); diff --git a/src/librustdoc/passes/bare_urls.rs b/src/librustdoc/passes/bare_urls.rs index 37faa6742927a..4501914fe0c07 100644 --- a/src/librustdoc/passes/bare_urls.rs +++ b/src/librustdoc/passes/bare_urls.rs @@ -39,7 +39,7 @@ impl<'a, 'tcx> BareUrlsLinter<'a, 'tcx> { ) { trace!("looking for raw urls in {}", text); // For now, we only check "full" URLs (meaning, starting with "http://" or "https://"). - for match_ in URL_REGEX.find_iter(&text) { + for match_ in URL_REGEX.find_iter(text) { let url = match_.as_str(); let url_range = match_.range(); f( diff --git a/src/librustdoc/passes/check_code_block_syntax.rs b/src/librustdoc/passes/check_code_block_syntax.rs index d2b3c5239c778..b18208d26e2c4 100644 --- a/src/librustdoc/passes/check_code_block_syntax.rs +++ b/src/librustdoc/passes/check_code_block_syntax.rs @@ -36,7 +36,7 @@ impl<'a, 'tcx> SyntaxChecker<'a, 'tcx> { let source = dox[code_block.code].to_owned(); let sess = ParseSess::with_span_handler(handler, sm); - let edition = code_block.lang_string.edition.unwrap_or(self.cx.tcx.sess.edition()); + let edition = code_block.lang_string.edition.unwrap_or_else(|| self.cx.tcx.sess.edition()); let expn_data = ExpnData::default( ExpnKind::AstPass(AstPass::TestHarness), DUMMY_SP, @@ -77,7 +77,7 @@ impl<'a, 'tcx> SyntaxChecker<'a, 'tcx> { // The span and whether it is precise or not. let (sp, precise_span) = match super::source_span_for_markdown_range( self.cx.tcx, - &dox, + dox, &code_block.range, &item.attrs, ) { @@ -123,7 +123,7 @@ impl<'a, 'tcx> SyntaxChecker<'a, 'tcx> { // FIXME(#67563): Provide more context for these errors by displaying the spans inline. for message in buffer.messages.iter() { - diag.note(&message); + diag.note(message); } diag.emit(); @@ -150,8 +150,8 @@ impl<'a, 'tcx> DocFolder for SyntaxChecker<'a, 'tcx> { item.def_id.expect_def_id(), sp, ); - for code_block in markdown::rust_code_blocks(&dox, &extra) { - self.check_rust_syntax(&item, &dox, code_block); + for code_block in markdown::rust_code_blocks(dox, &extra) { + self.check_rust_syntax(&item, dox, code_block); } } diff --git a/src/librustdoc/passes/check_doc_test_visibility.rs b/src/librustdoc/passes/check_doc_test_visibility.rs index 1f7d6054233dd..69a526d461810 100644 --- a/src/librustdoc/passes/check_doc_test_visibility.rs +++ b/src/librustdoc/passes/check_doc_test_visibility.rs @@ -115,10 +115,10 @@ crate fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item) { let mut tests = Tests { found_tests: 0 }; - find_testable_code(&dox, &mut tests, ErrorCodes::No, false, None); + find_testable_code(dox, &mut tests, ErrorCodes::No, false, None); if tests.found_tests == 0 && cx.tcx.sess.is_nightly_build() { - if should_have_doc_example(cx, &item) { + if should_have_doc_example(cx, item) { debug!("reporting error for {:?} (hir_id={:?})", item, hir_id); let sp = item.attr_span(cx.tcx); cx.tcx.struct_span_lint_hir( diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 318c897bcbdf6..9b2fe0c77e6cf 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -289,7 +289,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { ) -> Result<(Res, Option), ErrorKind<'path>> { let tcx = self.cx.tcx; let no_res = || ResolutionFailure::NotResolved { - module_id: module_id, + module_id, partial_res: None, unresolved: path_str.into(), }; @@ -437,7 +437,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option { let result = self.cx.enter_resolver(|resolver| { resolver - .resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id) + .resolve_str_path_error(DUMMY_SP, path_str, ns, module_id) .and_then(|(_, res)| res.try_into()) }); debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns); @@ -543,7 +543,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { ty::Uint(uty) => Res::Primitive(uty.into()), ty::Float(fty) => Res::Primitive(fty.into()), ty::Str => Res::Primitive(Str), - ty::Tuple(ref tys) if tys.is_empty() => Res::Primitive(Unit), + ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit), ty::Tuple(_) => Res::Primitive(Tuple), ty::Array(..) => Res::Primitive(Array), ty::Slice(_) => Res::Primitive(Slice), @@ -978,13 +978,13 @@ fn preprocess_link<'a>( } // Parse and strip the disambiguator from the link, if present. - let (disambiguator, path_str, link_text) = match Disambiguator::from_str(&link) { + let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) { Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()), Ok(None) => (None, link.trim(), link.trim()), Err((err_msg, relative_range)) => { // Only report error if we would not have ignored this link. See issue #83859. if !should_ignore_link_with_disambiguators(link) { - let no_backticks_range = range_between_backticks(&ori_link); + let no_backticks_range = range_between_backticks(ori_link); let disambiguator_range = (no_backticks_range.start + relative_range.start) ..(no_backticks_range.start + relative_range.end); return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg))); @@ -1000,7 +1000,7 @@ fn preprocess_link<'a>( // Strip generics from the path. let path_str = if path_str.contains(['<', '>'].as_slice()) { - match strip_generics_from_path(&path_str) { + match strip_generics_from_path(path_str) { Ok(path) => path, Err(err_kind) => { debug!("link has malformed generics: {}", path_str); @@ -1228,7 +1228,7 @@ impl LinkCollector<'_, '_> { if self.cx.tcx.privacy_access_levels(()).is_exported(src_id) && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id) { - privacy_error(self.cx, &diag_info, &path_str); + privacy_error(self.cx, &diag_info, path_str); } } @@ -1766,8 +1766,8 @@ fn report_diagnostic( let span = super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| { - if dox.bytes().nth(link_range.start) == Some(b'`') - && dox.bytes().nth(link_range.end - 1) == Some(b'`') + if dox.as_bytes().get(link_range.start) == Some(&b'`') + && dox.as_bytes().get(link_range.end - 1) == Some(&b'`') { sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1)) } else { @@ -1868,8 +1868,7 @@ fn resolution_failure( }; name = start; for ns in [TypeNS, ValueNS, MacroNS] { - if let Some(res) = - collector.check_full_res(ns, &start, module_id, &None) + if let Some(res) = collector.check_full_res(ns, start, module_id, &None) { debug!("found partial_res={:?}", res); *partial_res = Some(res); diff --git a/src/librustdoc/passes/collect_intra_doc_links/early.rs b/src/librustdoc/passes/collect_intra_doc_links/early.rs index cd90528ab9c8a..565bcb8bd1340 100644 --- a/src/librustdoc/passes/collect_intra_doc_links/early.rs +++ b/src/librustdoc/passes/collect_intra_doc_links/early.rs @@ -34,7 +34,7 @@ impl IntraLinkCrateLoader { let attrs = crate::clean::Attributes::from_ast(attrs, None); for (parent_module, doc) in attrs.collapsed_doc_value_by_module_level() { debug!(?doc); - for link in markdown_links(&doc.as_str()) { + for link in markdown_links(doc.as_str()) { debug!(?link.link); let path_str = if let Some(Ok(x)) = preprocess_link(&link) { x.path_str @@ -46,7 +46,7 @@ impl IntraLinkCrateLoader { span, &path_str, TypeNS, - parent_module.unwrap_or(self.current_mod.to_def_id()), + parent_module.unwrap_or_else(|| self.current_mod.to_def_id()), ); }); } diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 3e853456fad77..5d1f934240f03 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -9,7 +9,6 @@ use rustc_hir::Node; use rustc_hir::CRATE_HIR_ID; use rustc_middle::middle::privacy::AccessLevel; use rustc_middle::ty::TyCtxt; -use rustc_span; use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Symbol}; @@ -277,7 +276,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { _ if self.inlining && !is_pub => {} hir::ItemKind::GlobalAsm(..) => {} hir::ItemKind::Use(_, hir::UseKind::ListStem) => {} - hir::ItemKind::Use(ref path, kind) => { + hir::ItemKind::Use(path, kind) => { let is_glob = kind == hir::UseKind::Glob; // Struct and variant constructors and proc macro stubs always show up alongside From 25a82fdb329555d7564ac57aea74104940b918e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauren=C8=9Biu=20Nicola?= Date: Mon, 25 Oct 2021 13:30:24 +0300 Subject: [PATCH 4/4] :arrow_up: rust-analyzer --- src/tools/rust-analyzer | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer b/src/tools/rust-analyzer index 91cbda43c2af8..1f47693e02809 160000 --- a/src/tools/rust-analyzer +++ b/src/tools/rust-analyzer @@ -1 +1 @@ -Subproject commit 91cbda43c2af82b9377eff70a21f59ade18cd23c +Subproject commit 1f47693e02809c97db61b51247ae4e4d46744c61