From 0000b35288f7f7d929dd9afe7a5f4b47305f8bff Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 20 Nov 2023 03:27:41 +0000 Subject: [PATCH 1/8] Document DefiningAnchor a bit more --- compiler/rustc_middle/src/traits/mod.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 6cd75e087276..8af4f57d5e83 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -956,13 +956,26 @@ pub enum CodegenObligationError { FulfillmentError, } +/// Defines the treatment of opaque types in a given inference context. +/// +/// This affects both what opaques are allowed to be defined, but also whether +/// opaques are replaced with inference vars eagerly in the old solver (e.g. +/// in projection, and in the signature during function type-checking). #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, HashStable, TypeFoldable, TypeVisitable)] pub enum DefiningAnchor { - /// `DefId` of the item. + /// Define opaques which are in-scope of the `LocalDefId`. Also, eagerly + /// replace opaque types in `replace_opaque_types_with_inference_vars`. Bind(LocalDefId), - /// When opaque types are not resolved, we `Bubble` up, meaning - /// return the opaque/hidden type pair from query, for caller of query to handle it. + /// In contexts where we don't currently know what opaques are allowed to be + /// defined, such as (old solver) canonical queries, we will simply allow + /// opaques to be defined, but "bubble" them up in the canonical response or + /// otherwise treat them to be handled later. + /// + /// We do not eagerly replace opaque types in `replace_opaque_types_with_inference_vars`, + /// which may affect what predicates pass and fail in the old trait solver. Bubble, - /// Used to catch type mismatch errors when handling opaque types. + /// Do not allow any opaques to be defined. This is used to catch type mismatch + /// errors when handling opaque types, and also should be used when we would + /// otherwise reveal opaques (such as [`Reveal::All`] reveal mode). Error, } From 273dc22b04411b9c156375d15ad2c8cead2e619e Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 20 Nov 2023 23:35:20 +0000 Subject: [PATCH 2/8] Don't ICE when ambiguity is found when selecting Index implementation in typeck --- compiler/rustc_hir_typeck/src/expr.rs | 22 +++++++++++--- .../bad-index-modulo-higher-ranked-regions.rs | 29 +++++++++++++++++++ ...-index-modulo-higher-ranked-regions.stderr | 9 ++++++ 3 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 tests/ui/typeck/bad-index-modulo-higher-ranked-regions.rs create mode 100644 tests/ui/typeck/bad-index-modulo-higher-ranked-regions.stderr diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index d9b27fc13182..8fcbe90e91a8 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -3064,7 +3064,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return None; }; - self.commit_if_ok(|_| { + self.commit_if_ok(|snapshot| { + let outer_universe = self.universe(); + let ocx = ObligationCtxt::new(self); let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id); let impl_trait_ref = @@ -3074,7 +3076,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Match the impl self type against the base ty. If this fails, // we just skip this impl, since it's not particularly useful. let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref); - ocx.eq(&cause, self.param_env, impl_trait_ref.self_ty(), base_ty)?; + ocx.eq(&cause, self.param_env, base_ty, impl_trait_ref.self_ty())?; // Register the impl's predicates. One of these predicates // must be unsatisfied, or else we wouldn't have gotten here @@ -3110,11 +3112,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ty::new_projection(self.tcx, index_trait_output_def_id, impl_trait_ref.args), ); - let errors = ocx.select_where_possible(); + let true_errors = ocx.select_where_possible(); + + // Do a leak check -- we can't really report report a useful error here, + // but it at least avoids an ICE when the error has to do with higher-ranked + // lifetimes. + self.leak_check(outer_universe, Some(snapshot))?; + + // Bail if we have ambiguity errors, which we can't report in a useful way. + let ambiguity_errors = ocx.select_all_or_error(); + if true_errors.is_empty() && !ambiguity_errors.is_empty() { + return Err(NoSolution); + } + // There should be at least one error reported. If not, we // will still delay a span bug in `report_fulfillment_errors`. Ok::<_, NoSolution>(( - self.err_ctxt().report_fulfillment_errors(errors), + self.err_ctxt().report_fulfillment_errors(true_errors), impl_trait_ref.args.type_at(1), element_ty, )) diff --git a/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.rs b/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.rs new file mode 100644 index 000000000000..c8f6db7aef3e --- /dev/null +++ b/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.rs @@ -0,0 +1,29 @@ +// Test against ICE in #118111 + +use std::ops::Index; + +struct Map { + f: F, + inner: T, +} + +impl Index for Map +where + T: Index, + F: FnOnce(&T, Idx) -> Idx, +{ + type Output = T::Output; + + fn index(&self, index: Idx) -> &Self::Output { + todo!() + } +} + +fn main() { + Map { inner: [0_usize], f: |_, i: usize| 1_usize }[0]; + //~^ ERROR cannot index into a value of type + // Problem here is that + // `f: |_, i: usize| ...` + // should be + // `f: |_: &_, i: usize| ...` +} diff --git a/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.stderr b/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.stderr new file mode 100644 index 000000000000..7c9784308391 --- /dev/null +++ b/tests/ui/typeck/bad-index-modulo-higher-ranked-regions.stderr @@ -0,0 +1,9 @@ +error[E0608]: cannot index into a value of type `Map<[usize; 1], {closure@$DIR/bad-index-modulo-higher-ranked-regions.rs:23:32: 23:45}>` + --> $DIR/bad-index-modulo-higher-ranked-regions.rs:23:55 + | +LL | Map { inner: [0_usize], f: |_, i: usize| 1_usize }[0]; + | ^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0608`. From 018b85986d67945d50ea7aac176307877aaa053a Mon Sep 17 00:00:00 2001 From: ouz-a Date: Thu, 16 Nov 2023 16:04:26 +0300 Subject: [PATCH 3/8] Add VarDebugInfo to Stable MIR --- compiler/rustc_smir/src/rustc_smir/mod.rs | 45 +++++++++++++++++++- compiler/stable_mir/src/mir/body.rs | 50 +++++++++++++++++++++-- compiler/stable_mir/src/mir/visit.rs | 26 +++++++++++- 3 files changed, 116 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 167a01ab7990..e83e301d83bf 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -18,7 +18,10 @@ use rustc_middle::ty::{self, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, Variance use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc_target::abi::FieldIdx; use stable_mir::mir::mono::InstanceDef; -use stable_mir::mir::{Body, CopyNonOverlapping, Statement, UserTypeProjection, VariantIdx}; +use stable_mir::mir::{ + Body, ConstOperand, CopyNonOverlapping, Statement, UserTypeProjection, VarDebugInfoFragment, + VariantIdx, +}; use stable_mir::ty::{ AdtDef, AdtKind, ClosureDef, ClosureKind, Const, ConstId, ConstantKind, EarlyParamRegion, FloatTy, FnDef, GenericArgs, GenericParamDef, IntTy, LineInfo, Movability, RigidTy, Span, @@ -444,10 +447,50 @@ impl<'tcx> Stable<'tcx> for mir::Body<'tcx> { }) .collect(), self.arg_count, + self.var_debug_info.iter().map(|info| info.stable(tables)).collect(), ) } } +impl<'tcx> Stable<'tcx> for mir::VarDebugInfo<'tcx> { + type T = stable_mir::mir::VarDebugInfo; + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + stable_mir::mir::VarDebugInfo { + name: self.name.to_string(), + source_info: stable_mir::mir::SourceInfo { + span: self.source_info.span.stable(tables), + scope: self.source_info.scope.into(), + }, + composite: { + if let Some(composite) = &self.composite { + Some(VarDebugInfoFragment { + ty: composite.ty.stable(tables), + projection: composite.projection.iter().map(|e| e.stable(tables)).collect(), + }) + } else { + None + } + }, + value: { + match self.value { + mir::VarDebugInfoContents::Place(place) => { + stable_mir::mir::VarDebugInfoContents::Place(place.stable(tables)) + } + mir::VarDebugInfoContents::Const(const_operand) => { + let op = ConstOperand { + span: const_operand.span.stable(tables), + user_ty: const_operand.user_ty.map(|index| index.as_usize()), + const_: const_operand.const_.stable(tables), + }; + stable_mir::mir::VarDebugInfoContents::Const(op) + } + } + }, + argument_index: self.argument_index, + } + } +} + impl<'tcx> Stable<'tcx> for mir::Statement<'tcx> { type T = stable_mir::mir::Statement; fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs index ac07246dfd3e..8d237fc9f1d9 100644 --- a/compiler/stable_mir/src/mir/body.rs +++ b/compiler/stable_mir/src/mir/body.rs @@ -2,7 +2,7 @@ use crate::mir::pretty::{function_body, pretty_statement}; use crate::ty::{ AdtDef, ClosureDef, Const, CoroutineDef, GenericArgs, Movability, Region, RigidTy, Ty, TyKind, }; -use crate::{Error, Opaque, Span}; +use crate::{Error, Opaque, Span, Symbol}; use std::io; /// The SMIR representation of a single function. @@ -19,6 +19,9 @@ pub struct Body { // The number of arguments this function takes. pub(super) arg_count: usize, + + // Debug information pertaining to user variables, including captures. + pub(super) var_debug_info: Vec, } impl Body { @@ -26,14 +29,19 @@ impl Body { /// /// A constructor is required to build a `Body` from outside the crate /// because the `arg_count` and `locals` fields are private. - pub fn new(blocks: Vec, locals: LocalDecls, arg_count: usize) -> Self { + pub fn new( + blocks: Vec, + locals: LocalDecls, + arg_count: usize, + var_debug_info: Vec, + ) -> Self { // If locals doesn't contain enough entries, it can lead to panics in // `ret_local`, `arg_locals`, and `inner_locals`. assert!( locals.len() > arg_count, "A Body must contain at least a local for the return value and each of the function's arguments" ); - Self { blocks, locals, arg_count } + Self { blocks, locals, arg_count, var_debug_info } } /// Return local that holds this function's return value. @@ -427,6 +435,42 @@ pub struct Place { pub projection: Vec, } +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct VarDebugInfo { + pub name: Symbol, + pub source_info: SourceInfo, + pub composite: Option, + pub value: VarDebugInfoContents, + pub argument_index: Option, +} + +pub type SourceScope = u32; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SourceInfo { + pub span: Span, + pub scope: SourceScope, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct VarDebugInfoFragment { + pub ty: Ty, + pub projection: Vec, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum VarDebugInfoContents { + Place(Place), + Const(ConstOperand), +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ConstOperand { + pub span: Span, + pub user_ty: Option, + pub const_: Const, +} + // In MIR ProjectionElem is parameterized on the second Field argument and the Index argument. This // is so it can be used for both Places (for which the projection elements are of type // ProjectionElem) and user-provided type annotations (for which the projection elements diff --git a/compiler/stable_mir/src/mir/visit.rs b/compiler/stable_mir/src/mir/visit.rs index 40bedd67352f..488363d6a7f1 100644 --- a/compiler/stable_mir/src/mir/visit.rs +++ b/compiler/stable_mir/src/mir/visit.rs @@ -128,8 +128,12 @@ pub trait MirVisitor { self.super_assert_msg(msg, location) } + fn visit_var_debug_info(&mut self, var_debug_info: &VarDebugInfo) { + self.super_var_debug_info(var_debug_info); + } + fn super_body(&mut self, body: &Body) { - let Body { blocks, locals: _, arg_count } = body; + let Body { blocks, locals: _, arg_count, var_debug_info } = body; for bb in blocks { self.visit_basic_block(bb); @@ -145,6 +149,10 @@ pub trait MirVisitor { for (idx, arg) in body.inner_locals().iter().enumerate() { self.visit_local_decl(idx + local_start, arg) } + + for info in var_debug_info.iter() { + self.visit_var_debug_info(info); + } } fn super_basic_block(&mut self, bb: &BasicBlock) { @@ -382,6 +390,22 @@ pub trait MirVisitor { let _ = args; } + fn super_var_debug_info(&mut self, var_debug_info: &VarDebugInfo) { + self.visit_span(&var_debug_info.source_info.span); + let location = Location(var_debug_info.source_info.span); + if let Some(composite) = &var_debug_info.composite { + self.visit_ty(&composite.ty, location); + } + match &var_debug_info.value { + VarDebugInfoContents::Place(place) => { + self.visit_place(place, PlaceContext::NON_USE, location); + } + VarDebugInfoContents::Const(constant) => { + self.visit_const(&constant.const_, location); + } + } + } + fn super_assert_msg(&mut self, msg: &AssertMessage, location: Location) { match msg { AssertMessage::BoundsCheck { len, index } => { From d0dd19a6c959c90eb7b28c3fa7f127b92fd0af36 Mon Sep 17 00:00:00 2001 From: ouz-a Date: Fri, 17 Nov 2023 23:41:34 +0300 Subject: [PATCH 4/8] de-structure variable and add stables --- compiler/rustc_smir/src/rustc_smir/mod.rs | 68 +++++++++++++---------- compiler/stable_mir/src/mir/visit.rs | 10 ++-- 2 files changed, 45 insertions(+), 33 deletions(-) diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index e83e301d83bf..04986a6c02fb 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -457,35 +457,9 @@ impl<'tcx> Stable<'tcx> for mir::VarDebugInfo<'tcx> { fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { stable_mir::mir::VarDebugInfo { name: self.name.to_string(), - source_info: stable_mir::mir::SourceInfo { - span: self.source_info.span.stable(tables), - scope: self.source_info.scope.into(), - }, - composite: { - if let Some(composite) = &self.composite { - Some(VarDebugInfoFragment { - ty: composite.ty.stable(tables), - projection: composite.projection.iter().map(|e| e.stable(tables)).collect(), - }) - } else { - None - } - }, - value: { - match self.value { - mir::VarDebugInfoContents::Place(place) => { - stable_mir::mir::VarDebugInfoContents::Place(place.stable(tables)) - } - mir::VarDebugInfoContents::Const(const_operand) => { - let op = ConstOperand { - span: const_operand.span.stable(tables), - user_ty: const_operand.user_ty.map(|index| index.as_usize()), - const_: const_operand.const_.stable(tables), - }; - stable_mir::mir::VarDebugInfoContents::Const(op) - } - } - }, + source_info: self.source_info.stable(tables), + composite: self.composite.as_ref().map(|composite| composite.stable(tables)), + value: self.value.stable(tables), argument_index: self.argument_index, } } @@ -498,6 +472,42 @@ impl<'tcx> Stable<'tcx> for mir::Statement<'tcx> { } } +impl<'tcx> Stable<'tcx> for mir::SourceInfo { + type T = stable_mir::mir::SourceInfo; + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + stable_mir::mir::SourceInfo { span: self.span.stable(tables), scope: self.scope.into() } + } +} + +impl<'tcx> Stable<'tcx> for mir::VarDebugInfoFragment<'tcx> { + type T = stable_mir::mir::VarDebugInfoFragment; + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + VarDebugInfoFragment { + ty: self.ty.stable(tables), + projection: self.projection.iter().map(|e| e.stable(tables)).collect(), + } + } +} + +impl<'tcx> Stable<'tcx> for mir::VarDebugInfoContents<'tcx> { + type T = stable_mir::mir::VarDebugInfoContents; + fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { + match self { + mir::VarDebugInfoContents::Place(place) => { + stable_mir::mir::VarDebugInfoContents::Place(place.stable(tables)) + } + mir::VarDebugInfoContents::Const(const_operand) => { + let op = ConstOperand { + span: const_operand.span.stable(tables), + user_ty: const_operand.user_ty.map(|index| index.as_usize()), + const_: const_operand.const_.stable(tables), + }; + stable_mir::mir::VarDebugInfoContents::Const(op) + } + } + } +} + impl<'tcx> Stable<'tcx> for mir::StatementKind<'tcx> { type T = stable_mir::mir::StatementKind; fn stable(&self, tables: &mut Tables<'tcx>) -> Self::T { diff --git a/compiler/stable_mir/src/mir/visit.rs b/compiler/stable_mir/src/mir/visit.rs index 488363d6a7f1..d90808725ae4 100644 --- a/compiler/stable_mir/src/mir/visit.rs +++ b/compiler/stable_mir/src/mir/visit.rs @@ -391,12 +391,14 @@ pub trait MirVisitor { } fn super_var_debug_info(&mut self, var_debug_info: &VarDebugInfo) { - self.visit_span(&var_debug_info.source_info.span); - let location = Location(var_debug_info.source_info.span); - if let Some(composite) = &var_debug_info.composite { + let VarDebugInfo { source_info, composite, value, name: _, argument_index: _ } = + var_debug_info; + self.visit_span(&source_info.span); + let location = Location(source_info.span); + if let Some(composite) = composite { self.visit_ty(&composite.ty, location); } - match &var_debug_info.value { + match value { VarDebugInfoContents::Place(place) => { self.visit_place(place, PlaceContext::NON_USE, location); } From 0b25415559662352bbfd03a315d2a715663618b6 Mon Sep 17 00:00:00 2001 From: ouz-a Date: Tue, 21 Nov 2023 16:56:19 +0300 Subject: [PATCH 5/8] remove quotation from filename --- compiler/rustc_smir/src/rustc_smir/mod.rs | 16 +++++++--------- compiler/stable_mir/src/lib.rs | 2 +- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 167a01ab7990..0201df721f29 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -69,15 +69,13 @@ impl<'tcx> Context for TablesWrapper<'tcx> { fn get_filename(&self, span: &Span) -> Filename { let tables = self.0.borrow(); - opaque( - &tables - .tcx - .sess - .source_map() - .span_to_filename(tables[*span]) - .display(rustc_span::FileNameDisplayPreference::Local) - .to_string(), - ) + tables + .tcx + .sess + .source_map() + .span_to_filename(tables[*span]) + .display(rustc_span::FileNameDisplayPreference::Local) + .to_string() } fn get_lines(&self, span: &Span) -> LineInfo { diff --git a/compiler/stable_mir/src/lib.rs b/compiler/stable_mir/src/lib.rs index 91f1066d7205..5eb6a8a5e543 100644 --- a/compiler/stable_mir/src/lib.rs +++ b/compiler/stable_mir/src/lib.rs @@ -110,7 +110,7 @@ pub enum ItemKind { Const, } -pub type Filename = Opaque; +pub type Filename = String; /// Holds information about an item in the crate. #[derive(Copy, Clone, PartialEq, Eq, Debug)] From d82a08537aab25f3d1d43a30ea4b06422819bbfd Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 20 Nov 2023 13:15:47 -0700 Subject: [PATCH 6/8] rustdoc-search: clean up `checkPath` This computes the same result with less code by computing many of the old checks at once: * It won't enter the loop if clength > length, because then the result of length - clength will be negative and the loop conditional will fail. * i + clength will never be greater than length, because it starts out as i = length - clength, implying that i + clength equals length, and it only goes down from there. * The aborted variable is replaced with control flow. --- src/librustdoc/html/static/js/search.js | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 22dcb8701431..495c28d91e8a 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -1840,26 +1840,16 @@ function initSearch(rawSearchIndex) { const length = path.length; const clength = contains.length; - if (clength > length) { - return maxEditDistance + 1; - } - for (let i = 0; i < length; ++i) { - if (i + clength > length) { - break; - } + pathiter: for (let i = length - clength; i >= 0; i -= 1) { let dist_total = 0; - let aborted = false; for (let x = 0; x < clength; ++x) { const dist = editDistance(path[i + x], contains[x], maxEditDistance); if (dist > maxEditDistance) { - aborted = true; - break; + continue pathiter; } dist_total += dist; } - if (!aborted) { - ret_dist = Math.min(ret_dist, Math.round(dist_total / clength)); - } + ret_dist = Math.min(ret_dist, Math.round(dist_total / clength)); } return ret_dist; } From 28f17d97a9e7276a383e11e91ef2d4159e670726 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 20 Nov 2023 13:37:57 -0700 Subject: [PATCH 7/8] rustdoc-search: make primitives and keywords less special The search sorting code already sorts by item type discriminant, putting things with smaller discriminants first. There was also a special case for sorting keywords and primitives earlier, and this commit removes it by giving them lower discriminants. The sorting code has another criteria where items with descriptions appear earlier than items without, and that criteria has higher priority than the item type. This shouldn't matter, though, because primitives and keywords normally only appear in the standard library, and it always gives them descriptions. --- src/librustdoc/formats/item_type.rs | 51 ++++++++++++---------- src/librustdoc/html/static/js/search.js | 36 +++++---------- tests/rustdoc-js-std/keyword.js | 4 +- tests/rustdoc-js-std/macro-check.js | 4 +- tests/rustdoc-js-std/parser-bindings.js | 8 ++-- tests/rustdoc-js-std/parser-filter.js | 22 +++++----- tests/rustdoc-js-std/parser-ident.js | 6 +-- tests/rustdoc-js-std/parser-returned.js | 2 +- tests/rustdoc-js-std/parser-slice-array.js | 20 ++++----- 9 files changed, 74 insertions(+), 79 deletions(-) diff --git a/src/librustdoc/formats/item_type.rs b/src/librustdoc/formats/item_type.rs index 22527876b76f..5666751d1ce9 100644 --- a/src/librustdoc/formats/item_type.rs +++ b/src/librustdoc/formats/item_type.rs @@ -16,6 +16,13 @@ use crate::clean; /// Consequently, every change to this type should be synchronized to /// the `itemTypes` mapping table in `html/static/js/search.js`. /// +/// The search engine in search.js also uses item type numbers as a tie breaker when +/// sorting results. Keywords and primitives are given first because we want them to be easily +/// found by new users who don't know about advanced features like type filters. The rest are +/// mostly in an arbitrary order, but it's easier to test the search engine when +/// it's deterministic, and these are strictly finer-grained than language namespaces, so +/// using the path and the item type together to sort ensures that search sorting is stable. +/// /// In addition, code in `html::render` uses this enum to generate CSS classes, page prefixes, and /// module headings. If you are adding to this enum and want to ensure that the sidebar also prints /// a heading, edit the listing in `html/render.rs`, function `sidebar_module`. This uses an @@ -23,28 +30,28 @@ use crate::clean; #[derive(Copy, PartialEq, Eq, Hash, Clone, Debug, PartialOrd, Ord)] #[repr(u8)] pub(crate) enum ItemType { - Module = 0, - ExternCrate = 1, - Import = 2, - Struct = 3, - Enum = 4, - Function = 5, - TypeAlias = 6, - Static = 7, - Trait = 8, - Impl = 9, - TyMethod = 10, - Method = 11, - StructField = 12, - Variant = 13, - Macro = 14, - Primitive = 15, - AssocType = 16, - Constant = 17, - AssocConst = 18, - Union = 19, - ForeignType = 20, - Keyword = 21, + Keyword = 0, + Primitive = 1, + Module = 2, + ExternCrate = 3, + Import = 4, + Struct = 5, + Enum = 6, + Function = 7, + TypeAlias = 8, + Static = 9, + Trait = 10, + Impl = 11, + TyMethod = 12, + Method = 13, + StructField = 14, + Variant = 15, + Macro = 16, + AssocType = 17, + Constant = 18, + AssocConst = 19, + Union = 20, + ForeignType = 21, OpaqueTy = 22, ProcAttribute = 23, ProcDerive = 24, diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 495c28d91e8a..4822690fd04b 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -18,28 +18,28 @@ if (!Array.prototype.toSpliced) { // This mapping table should match the discriminants of // `rustdoc::formats::item_type::ItemType` type in Rust. const itemTypes = [ + "keyword", + "primitive", "mod", "externcrate", "import", - "struct", + "struct", // 5 "enum", - "fn", // 5 + "fn", "type", "static", - "trait", + "trait", // 10 "impl", - "tymethod", // 10 + "tymethod", "method", "structfield", - "variant", + "variant", // 15 "macro", - "primitive", // 15 "associatedtype", "constant", "associatedconstant", - "union", - "foreigntype", // 20 - "keyword", + "union", // 20 + "foreigntype", "existential", "attr", "derive", @@ -48,6 +48,8 @@ const itemTypes = [ ]; const longItemTypes = [ + "keyword", + "primitive type", "module", "extern crate", "re-export", @@ -63,13 +65,11 @@ const longItemTypes = [ "struct field", "enum variant", "macro", - "primitive type", "assoc type", "constant", "assoc const", "union", "foreign type", - "keyword", "existential type", "attribute macro", "derive macro", @@ -77,8 +77,6 @@ const longItemTypes = [ ]; // used for special search precedence -const TY_PRIMITIVE = itemTypes.indexOf("primitive"); -const TY_KEYWORD = itemTypes.indexOf("keyword"); const TY_GENERIC = itemTypes.indexOf("generic"); const ROOT_PATH = typeof window !== "undefined" ? window.rootPath : "../"; @@ -1317,16 +1315,6 @@ function initSearch(rawSearchIndex) { return (a > b ? +1 : -1); } - // special precedence for primitive and keyword pages - if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) || - (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) { - return -1; - } - if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) || - (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) { - return 1; - } - // sort by description (no description goes later) a = (aaa.item.desc === ""); b = (bbb.item.desc === ""); @@ -2943,7 +2931,7 @@ ${item.displayPath}${name}\ // https://mathiasbynens.be/notes/shapes-ics const crateRow = { crate: crate, - ty: 1, // == ExternCrate + ty: 3, // == ExternCrate name: crate, path: "", desc: crateCorpus.doc, diff --git a/tests/rustdoc-js-std/keyword.js b/tests/rustdoc-js-std/keyword.js index b85ba34138ba..1837b1e71f78 100644 --- a/tests/rustdoc-js-std/keyword.js +++ b/tests/rustdoc-js-std/keyword.js @@ -3,7 +3,7 @@ const EXPECTED = { 'query': 'fn', 'others': [ - { 'path': 'std', 'name': 'fn', ty: 15 }, // 15 is for primitive types - { 'path': 'std', 'name': 'fn', ty: 21 }, // 21 is for keywords + { 'path': 'std', 'name': 'fn', ty: 1 }, // 1 is for primitive types + { 'path': 'std', 'name': 'fn', ty: 0 }, // 0 is for keywords ], }; diff --git a/tests/rustdoc-js-std/macro-check.js b/tests/rustdoc-js-std/macro-check.js index c22b1753fd71..37d5e7dae62e 100644 --- a/tests/rustdoc-js-std/macro-check.js +++ b/tests/rustdoc-js-std/macro-check.js @@ -3,7 +3,7 @@ const EXPECTED = { 'query': 'panic', 'others': [ - { 'path': 'std', 'name': 'panic', ty: 14 }, // 15 is for macros - { 'path': 'std', 'name': 'panic', ty: 0 }, // 0 is for modules + { 'path': 'std', 'name': 'panic', ty: 16 }, // 16 is for macros + { 'path': 'std', 'name': 'panic', ty: 2 }, // 2 is for modules ], }; diff --git a/tests/rustdoc-js-std/parser-bindings.js b/tests/rustdoc-js-std/parser-bindings.js index faf880c8116c..c4909c6242d7 100644 --- a/tests/rustdoc-js-std/parser-bindings.js +++ b/tests/rustdoc-js-std/parser-bindings.js @@ -81,7 +81,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }] ], ], @@ -112,7 +112,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "[]", generics: [], - typeFilter: 15, + typeFilter: 1, }] ], ], @@ -149,10 +149,10 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }, ], - typeFilter: 15, + typeFilter: 1, }] ], ], diff --git a/tests/rustdoc-js-std/parser-filter.js b/tests/rustdoc-js-std/parser-filter.js index 3b9cc5b1bf09..a1dd0ea3b5a9 100644 --- a/tests/rustdoc-js-std/parser-filter.js +++ b/tests/rustdoc-js-std/parser-filter.js @@ -7,7 +7,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "foo", generics: [], - typeFilter: 5, + typeFilter: 7, }], foundElems: 1, original: "fn:foo", @@ -23,7 +23,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "foo", generics: [], - typeFilter: 4, + typeFilter: 6, }], foundElems: 1, original: "enum : foo", @@ -48,7 +48,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "macro", generics: [], - typeFilter: 14, + typeFilter: 16, }], foundElems: 1, original: "macro!", @@ -64,7 +64,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "mac", generics: [], - typeFilter: 14, + typeFilter: 16, }], foundElems: 1, original: "macro:mac!", @@ -80,7 +80,7 @@ const PARSED = [ pathWithoutLast: ["a"], pathLast: "mac", generics: [], - typeFilter: 14, + typeFilter: 16, }], foundElems: 1, original: "a::mac!", @@ -99,7 +99,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "foo", generics: [], - typeFilter: 5, + typeFilter: 7, }], userQuery: "-> fn:foo", error: null, @@ -121,10 +121,10 @@ const PARSED = [ pathWithoutLast: [], pathLast: "bar", generics: [], - typeFilter: 5, + typeFilter: 7, } ], - typeFilter: 5, + typeFilter: 7, }], userQuery: "-> fn:foo", error: null, @@ -146,7 +146,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "bar", generics: [], - typeFilter: 5, + typeFilter: 7, }, { name: "baz::fuzz", @@ -154,10 +154,10 @@ const PARSED = [ pathWithoutLast: ["baz"], pathLast: "fuzz", generics: [], - typeFilter: 4, + typeFilter: 6, }, ], - typeFilter: 5, + typeFilter: 7, }], userQuery: "-> fn:foo", error: null, diff --git a/tests/rustdoc-js-std/parser-ident.js b/tests/rustdoc-js-std/parser-ident.js index f65a7ce6692b..cc79c58f1da3 100644 --- a/tests/rustdoc-js-std/parser-ident.js +++ b/tests/rustdoc-js-std/parser-ident.js @@ -13,7 +13,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }, ], typeFilter: -1, @@ -32,7 +32,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }], foundElems: 1, original: "!", @@ -48,7 +48,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "a", generics: [], - typeFilter: 14, + typeFilter: 16, }], foundElems: 1, original: "a!", diff --git a/tests/rustdoc-js-std/parser-returned.js b/tests/rustdoc-js-std/parser-returned.js index 6ea86609115b..44e517c49b59 100644 --- a/tests/rustdoc-js-std/parser-returned.js +++ b/tests/rustdoc-js-std/parser-returned.js @@ -89,7 +89,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "never", generics: [], - typeFilter: 15, + typeFilter: 1, }], userQuery: "-> !", error: null, diff --git a/tests/rustdoc-js-std/parser-slice-array.js b/tests/rustdoc-js-std/parser-slice-array.js index c22b7870dbf8..239391bed420 100644 --- a/tests/rustdoc-js-std/parser-slice-array.js +++ b/tests/rustdoc-js-std/parser-slice-array.js @@ -43,16 +43,16 @@ const PARSED = [ pathWithoutLast: [], pathLast: "[]", generics: [], - typeFilter: 15, + typeFilter: 1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -70,7 +70,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "[]", generics: [], - typeFilter: 15, + typeFilter: 1, }, { name: "u8", @@ -105,7 +105,7 @@ const PARSED = [ typeFilter: -1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -140,7 +140,7 @@ const PARSED = [ typeFilter: -1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -176,7 +176,7 @@ const PARSED = [ typeFilter: -1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -194,7 +194,7 @@ const PARSED = [ pathWithoutLast: [], pathLast: "[]", generics: [], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, @@ -284,7 +284,7 @@ const PARSED = [ typeFilter: -1, }, ], - typeFilter: 15, + typeFilter: 1, }, ], foundElems: 1, From c089a162d80dbbcc0543649fa78ccabac569db81 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Tue, 21 Nov 2023 21:46:17 +0100 Subject: [PATCH 8/8] Fix some unnecessary casts `x clippy compiler -Aclippy::all -Wclippy::unnecessary_cast --fix` with some manual review to ensure every fix is correct. --- compiler/rustc_codegen_ssa/src/mir/place.rs | 12 +++++------- compiler/rustc_const_eval/src/const_eval/machine.rs | 2 +- compiler/rustc_hir_typeck/src/method/probe.rs | 2 +- compiler/rustc_infer/src/infer/fudge.rs | 4 ++-- .../src/infer/lexical_region_resolve/mod.rs | 12 ++++-------- .../rustc_infer/src/infer/region_constraints/mod.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 6 +----- compiler/rustc_metadata/src/rmeta/table.rs | 2 +- compiler/rustc_middle/src/mir/tcx.rs | 4 +--- compiler/rustc_symbol_mangling/src/v0.rs | 2 +- 10 files changed, 18 insertions(+), 30 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index eb590a45a63f..45795a7f7359 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -474,27 +474,25 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { cg_base.project_index(bx, llindex) } mir::ProjectionElem::ConstantIndex { offset, from_end: false, min_length: _ } => { - let lloffset = bx.cx().const_usize(offset as u64); + let lloffset = bx.cx().const_usize(offset); cg_base.project_index(bx, lloffset) } mir::ProjectionElem::ConstantIndex { offset, from_end: true, min_length: _ } => { - let lloffset = bx.cx().const_usize(offset as u64); + let lloffset = bx.cx().const_usize(offset); let lllen = cg_base.len(bx.cx()); let llindex = bx.sub(lllen, lloffset); cg_base.project_index(bx, llindex) } mir::ProjectionElem::Subslice { from, to, from_end } => { - let mut subslice = cg_base.project_index(bx, bx.cx().const_usize(from as u64)); + let mut subslice = cg_base.project_index(bx, bx.cx().const_usize(from)); let projected_ty = PlaceTy::from_ty(cg_base.layout.ty).projection_ty(tcx, *elem).ty; subslice.layout = bx.cx().layout_of(self.monomorphize(projected_ty)); if subslice.layout.is_unsized() { assert!(from_end, "slice subslices should be `from_end`"); - subslice.llextra = Some(bx.sub( - cg_base.llextra.unwrap(), - bx.cx().const_usize((from as u64) + (to as u64)), - )); + subslice.llextra = + Some(bx.sub(cg_base.llextra.unwrap(), bx.cx().const_usize(from + to))); } subslice diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 4b447229c5f6..5b04b37cdf51 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -485,7 +485,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, }; let ptr = ecx.allocate_ptr( - Size::from_bytes(size as u64), + Size::from_bytes(size), align, interpret::MemoryKind::Machine(MemoryKind::Heap), )?; diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index d2a72f8f2338..22d94b9ca281 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1861,7 +1861,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // method yet. So create fresh variables here for those too, // if there are any. let generics = self.tcx.generics_of(method); - assert_eq!(args.len(), generics.parent_count as usize); + assert_eq!(args.len(), generics.parent_count); let xform_fn_sig = if generics.params.is_empty() { fn_sig.instantiate(self.tcx, args) diff --git a/compiler/rustc_infer/src/infer/fudge.rs b/compiler/rustc_infer/src/infer/fudge.rs index 7e878ac06c7f..8ca97ae1b8e5 100644 --- a/compiler/rustc_infer/src/infer/fudge.rs +++ b/compiler/rustc_infer/src/infer/fudge.rs @@ -187,7 +187,7 @@ impl<'a, 'tcx> TypeFolder> for InferenceFudger<'a, 'tcx> { if self.type_vars.0.contains(&vid) { // This variable was created during the fudging. // Recreate it with a fresh variable here. - let idx = (vid.as_usize() - self.type_vars.0.start.as_usize()) as usize; + let idx = vid.as_usize() - self.type_vars.0.start.as_usize(); let origin = self.type_vars.1[idx]; self.infcx.next_ty_var(origin) } else { @@ -236,7 +236,7 @@ impl<'a, 'tcx> TypeFolder> for InferenceFudger<'a, 'tcx> { if self.const_vars.0.contains(&vid) { // This variable was created during the fudging. // Recreate it with a fresh variable here. - let idx = (vid.index() - self.const_vars.0.start.index()) as usize; + let idx = vid.index() - self.const_vars.0.start.index(); let origin = self.const_vars.1[idx]; self.infcx.next_const_var(ct.ty(), origin) } else { diff --git a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs index 800aee1f4d3b..b0e82a92674f 100644 --- a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs +++ b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs @@ -681,17 +681,13 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { for constraint in self.data.constraints.keys() { match *constraint { Constraint::VarSubVar(a_id, b_id) => { - graph.add_edge( - NodeIndex(a_id.index() as usize), - NodeIndex(b_id.index() as usize), - *constraint, - ); + graph.add_edge(NodeIndex(a_id.index()), NodeIndex(b_id.index()), *constraint); } Constraint::RegSubVar(_, b_id) => { - graph.add_edge(dummy_source, NodeIndex(b_id.index() as usize), *constraint); + graph.add_edge(dummy_source, NodeIndex(b_id.index()), *constraint); } Constraint::VarSubReg(a_id, _) => { - graph.add_edge(NodeIndex(a_id.index() as usize), dummy_sink, *constraint); + graph.add_edge(NodeIndex(a_id.index()), dummy_sink, *constraint); } Constraint::RegSubReg(..) => { // this would be an edge from `dummy_source` to @@ -878,7 +874,7 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> { ) { debug!("process_edges(source_vid={:?}, dir={:?})", source_vid, dir); - let source_node_index = NodeIndex(source_vid.index() as usize); + let source_node_index = NodeIndex(source_vid.index()); for (_, edge) in graph.adjacent_edges(source_node_index, dir) { match edge.data { Constraint::VarSubVar(from_vid, to_vid) => { diff --git a/compiler/rustc_infer/src/infer/region_constraints/mod.rs b/compiler/rustc_infer/src/infer/region_constraints/mod.rs index e888340bde3f..260f4bc671fb 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/mod.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/mod.rs @@ -316,7 +316,7 @@ impl<'tcx> RegionConstraintStorage<'tcx> { match undo_entry { AddVar(vid) => { self.var_infos.pop().unwrap(); - assert_eq!(self.var_infos.len(), vid.index() as usize); + assert_eq!(self.var_infos.len(), vid.index()); } AddConstraint(ref constraint) => { self.data.constraints.remove(constraint); diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index b6ffdc7378f6..109757f8719c 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -2269,11 +2269,7 @@ fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) { file.seek(std::io::SeekFrom::Start(pos_before_seek)).unwrap(); // Record metadata size for self-profiling - tcx.prof.artifact_size( - "crate_metadata", - "crate_metadata", - file.metadata().unwrap().len() as u64, - ); + tcx.prof.artifact_size("crate_metadata", "crate_metadata", file.metadata().unwrap().len()); } pub fn provide(providers: &mut Providers) { diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index 027994c40ab7..0d97b6b76744 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -497,7 +497,7 @@ impl> TableBui } LazyTable::from_position_and_encoded_size( - NonZeroUsize::new(pos as usize).unwrap(), + NonZeroUsize::new(pos).unwrap(), width, self.blocks.len(), ) diff --git a/compiler/rustc_middle/src/mir/tcx.rs b/compiler/rustc_middle/src/mir/tcx.rs index 6ab2da23a8ad..17eb6ae274e1 100644 --- a/compiler/rustc_middle/src/mir/tcx.rs +++ b/compiler/rustc_middle/src/mir/tcx.rs @@ -95,9 +95,7 @@ impl<'tcx> PlaceTy<'tcx> { ProjectionElem::Subslice { from, to, from_end } => { PlaceTy::from_ty(match self.ty.kind() { ty::Slice(..) => self.ty, - ty::Array(inner, _) if !from_end => { - Ty::new_array(tcx, *inner, (to - from) as u64) - } + ty::Array(inner, _) if !from_end => Ty::new_array(tcx, *inner, to - from), ty::Array(inner, size) if from_end => { let size = size.eval_target_usize(tcx, param_env); let len = size - from - to; diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 01cbee3a7159..88989806997e 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -189,7 +189,7 @@ impl<'tcx> SymbolMangler<'tcx> { self.push("N"); self.out.push(ns); print_prefix(self)?; - self.push_disambiguator(disambiguator as u64); + self.push_disambiguator(disambiguator); self.push_ident(name); Ok(()) }