From 8b14227aa96cf1bfdfdf46e879837b0763073a1b Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Fri, 10 Jan 2025 01:53:25 -0600 Subject: [PATCH 01/29] add MSVC tuple providers --- src/etc/lldb_commands | 6 ++++- src/etc/lldb_providers.py | 53 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/etc/lldb_commands b/src/etc/lldb_commands index ef0c3740f032..71968f2dbe61 100644 --- a/src/etc/lldb_commands +++ b/src/etc/lldb_commands @@ -18,7 +18,10 @@ type synthetic add -l lldb_lookup.synthetic_lookup -x "^(core::([a-z_]+::)+)NonZ type synthetic add -l lldb_lookup.synthetic_lookup -x "^core::num::([a-z_]+::)*NonZero.+$" --category Rust type synthetic add -l lldb_lookup.synthetic_lookup -x "^(std::([a-z_]+::)+)PathBuf$" --category Rust type synthetic add -l lldb_lookup.synthetic_lookup -x "^&(mut )?(std::([a-z_]+::)+)Path$" --category Rust -type synthetic add -l lldb_lookup.synthetic_lookup -x "^(.*)$" --category Rust +type synthetic add -l lldb_lookup.MSVCStdSliceSyntheticProvider -x "^ref\$ >" --category Rust +type synthetic add -l lldb_lookup.MSVCTupleSyntheticProvider -x "^tuple\$<.+>$" --category Rust +type summary add -F lldb_lookup.TupleSummaryProvider -e -x -h "^tuple\$<.+>$" --category Rust +type synthetic add -l lldb_lookup.synthetic_lookup -x "^\(.*\)$" --category Rust type summary add -F _ -e -x -h "^.*$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)String$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?str$" --category Rust @@ -40,4 +43,5 @@ type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)N type summary add -F lldb_lookup.summary_lookup -e -x -h "^core::num::([a-z_]+::)*NonZero.+$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::([a-z_]+::)+)PathBuf$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?(std::([a-z_]+::)+)Path$" --category Rust +type summary add -F lldb_lookup.TupleSummaryProvider -e -x -h "^tuple\$<.+>$" --category Rust type category enable Rust diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index 2f32ed833af1..9f2b2c85e653 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -205,6 +205,24 @@ def StdPathSummaryProvider(valobj: SBValue, _dict: LLDBOpaque) -> str: return '"%s"' % data +def sequence_formatter(output: str, valobj: SBValue, _dict: LLDBOpaque): + length: int = valobj.GetNumChildren() + + long: bool = False + for i in range(0, length): + if len(output) > 32: + long = True + break + child: SBValue = valobj.GetChildAtIndex(i) + output += f"{child.value}, " + if long: + output = f"(len: {length}) " + output + "..." + else: + output = output[:-2] + + return output + + class StructSyntheticProvider: """Pretty-printer for structs and struct enum variants""" @@ -348,6 +366,41 @@ def has_children(self) -> bool: return True +class MSVCTupleSyntheticProvider: + __slots__ = ["valobj"] + + def __init__(self, valobj: SBValue, _dict: LLDBOpaque): + self.valobj = valobj + + def num_children(self) -> int: + return self.valobj.GetNumChildren() + + def get_child_index(self, name: str) -> int: + return self.valobj.GetIndexOfChildWithName(name) + + def get_child_at_index(self, index: int) -> SBValue: + child: SBValue = self.valobj.GetChildAtIndex(index) + return child.CreateChildAtOffset(str(index), 0, child.GetType()) + + def update(self): + pass + + def has_children(self) -> bool: + return self.valobj.MightHaveChildren() + + def get_type_name(self) -> str: + name = self.valobj.GetTypeName() + # remove "tuple$<" and ">", str.removeprefix and str.removesuffix require python 3.9+ + name = name[7:-1] + return "(" + name + ")" + + +def TupleSummaryProvider(valobj: SBValue, _dict: LLDBOpaque): + output: str = sequence_formatter("(", valobj, dict) + output += ")" + return output + + class StdVecSyntheticProvider: """Pretty-printer for alloc::vec::Vec From 71b6d49282ee68a980aada44a65d4f6e8f1c8991 Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Fri, 10 Jan 2025 02:02:01 -0600 Subject: [PATCH 02/29] add MSVC slice providers --- src/etc/lldb_commands | 2 ++ src/etc/lldb_providers.py | 27 +++++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/etc/lldb_commands b/src/etc/lldb_commands index 71968f2dbe61..23282d2d25b0 100644 --- a/src/etc/lldb_commands +++ b/src/etc/lldb_commands @@ -44,4 +44,6 @@ type summary add -F lldb_lookup.summary_lookup -e -x -h "^core::num::([a-z_]+:: type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::([a-z_]+::)+)PathBuf$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?(std::([a-z_]+::)+)Path$" --category Rust type summary add -F lldb_lookup.TupleSummaryProvider -e -x -h "^tuple\$<.+>$" --category Rust +type summary add -F lldb_lookup.StdSliceSummaryProvider -e -x -h "^ref(_mut)?\$ >" --category Rust +type synthetic add -l lldb_lookup.MSVCStdSliceSyntheticProvider -x "^ref(_mut)?\$ >" --category Rust type category enable Rust diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index 9f2b2c85e653..7be40068b90a 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -456,6 +456,8 @@ def has_children(self) -> bool: class StdSliceSyntheticProvider: + __slots__ = ["valobj", "length", "ptr", "element_type", "element_size"] + def __init__(self, valobj: SBValue, _dict: LLDBOpaque): self.valobj = valobj self.update() @@ -472,7 +474,7 @@ def get_child_index(self, name: str) -> int: def get_child_at_index(self, index: int) -> SBValue: start = self.data_ptr.GetValueAsUnsigned() - address = start + index * self.element_type_size + address = start + index * self.element_size element = self.data_ptr.CreateValueFromAddress( "[%s]" % index, address, self.element_type ) @@ -483,12 +485,33 @@ def update(self): self.data_ptr = self.valobj.GetChildMemberWithName("data_ptr") self.element_type = self.data_ptr.GetType().GetPointeeType() - self.element_type_size = self.element_type.GetByteSize() + self.element_size = self.element_type.GetByteSize() def has_children(self) -> bool: return True +class MSVCStdSliceSyntheticProvider(StdSliceSyntheticProvider): + def get_type_name(self) -> str: + name = self.valobj.GetTypeName() + + if name.startswith("ref_mut"): + # remove "ref_mut$ >" + name = name[17:-3] + ref = "&mut " + else: + # remove "ref$ >" + name = name[13:-3] + ref = "&" + + return "".join([ref, "[", name, "]"]) + +def StdSliceSummaryProvider(valobj, dict): + output = sequence_formatter("[", valobj, dict) + output += "]" + return output + + class StdVecDequeSyntheticProvider: """Pretty-printer for alloc::collections::vec_deque::VecDeque From c425660858fb19e13dde3a28fef824b1c4dd5f48 Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Fri, 10 Jan 2025 21:13:52 -0600 Subject: [PATCH 03/29] add msvc enum providers --- src/etc/lldb_commands | 6 +- src/etc/lldb_providers.py | 175 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+), 2 deletions(-) diff --git a/src/etc/lldb_commands b/src/etc/lldb_commands index 23282d2d25b0..24c485b35337 100644 --- a/src/etc/lldb_commands +++ b/src/etc/lldb_commands @@ -18,9 +18,10 @@ type synthetic add -l lldb_lookup.synthetic_lookup -x "^(core::([a-z_]+::)+)NonZ type synthetic add -l lldb_lookup.synthetic_lookup -x "^core::num::([a-z_]+::)*NonZero.+$" --category Rust type synthetic add -l lldb_lookup.synthetic_lookup -x "^(std::([a-z_]+::)+)PathBuf$" --category Rust type synthetic add -l lldb_lookup.synthetic_lookup -x "^&(mut )?(std::([a-z_]+::)+)Path$" --category Rust +type synthetic add -l lldb_lookup.MSVCEnumSyntheticProvider -x "^enum2\$<.+>$" --category Rust +type synthetic add -l lldb_lookup.synthetic_lookup -x "^enum2\$<.+>::.*$" --category Rust type synthetic add -l lldb_lookup.MSVCStdSliceSyntheticProvider -x "^ref\$ >" --category Rust type synthetic add -l lldb_lookup.MSVCTupleSyntheticProvider -x "^tuple\$<.+>$" --category Rust -type summary add -F lldb_lookup.TupleSummaryProvider -e -x -h "^tuple\$<.+>$" --category Rust type synthetic add -l lldb_lookup.synthetic_lookup -x "^\(.*\)$" --category Rust type summary add -F _ -e -x -h "^.*$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)String$" --category Rust @@ -45,5 +46,6 @@ type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::([a-z_]+::)+)Pa type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?(std::([a-z_]+::)+)Path$" --category Rust type summary add -F lldb_lookup.TupleSummaryProvider -e -x -h "^tuple\$<.+>$" --category Rust type summary add -F lldb_lookup.StdSliceSummaryProvider -e -x -h "^ref(_mut)?\$ >" --category Rust -type synthetic add -l lldb_lookup.MSVCStdSliceSyntheticProvider -x "^ref(_mut)?\$ >" --category Rust +type summary add -F lldb_lookup.MSVCEnumSummaryProvider -e -x -h "^enum2\$<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^enum2\$<.+>::.*$" --category Rust type category enable Rust diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index 7be40068b90a..b05dd5162f09 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -3,6 +3,8 @@ from lldb import ( SBData, SBError, + SBType, + SBTypeStaticField, SBValue, eBasicTypeLong, eBasicTypeUnsignedLong, @@ -325,6 +327,179 @@ def _getCurrentVariantIndex(self, all_variants: SBValue) -> int: default_index = i return default_index +class MSVCEnumSyntheticProvider: + """ + Synthetic provider for sum-type enums on MSVC. For a detailed explanation of the internals, + see: + + https://github.com/rust-lang/rust/blob/master/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs + """ + + __slots__ = ["valobj", "variant", "value"] + def __init__(self, valobj: SBValue, _dict: LLDBOpaque): + self.valobj = valobj + self.variant: SBValue + self.value: SBValue + self.update() + + def update(self): + tag: SBValue = self.valobj.GetChildMemberWithName("tag") + + if tag.IsValid(): + tag: int = tag.GetValueAsUnsigned() + for child in self.valobj.GetNonSyntheticValue().children: + if not child.name.startswith("variant"): + continue + + variant_type: SBType = child.GetType() + exact: SBTypeStaticField = variant_type.GetStaticFieldWithName( + "DISCR_EXACT" + ) + + if exact.IsValid(): + discr: int = exact.GetConstantValue( + self.valobj.target + ).GetValueAsUnsigned() + if tag == discr: + self.variant = child + self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + return + else: # if invalid, DISCR must be a range + begin: int = variant_type.GetStaticFieldWithName( + "DISCR_BEGIN" + ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + end: int = variant_type.GetStaticFieldWithName( + "DISCR_END" + ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + + # begin isn't necessarily smaller than end, so we must test for both cases + if begin < end: + if begin <= tag <= end: + self.variant = child + self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + return + else: + if tag >= begin or tag <= end: + self.variant = child + self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + return + else: # if invalid, tag is a 128 bit value + tag_lo: int = self.valobj.GetChildMemberWithName("tag128_lo").GetValueAsUnsigned() + tag_hi: int = self.valobj.GetChildMemberWithName("tag128_hi").GetValueAsUnsigned() + + tag: int = (tag_hi << 64) | tag_lo + + for child in self.valobj.GetNonSyntheticValue().children: + if not child.name.startswith("variant"): + continue + + variant_type: SBType = child.GetType() + exact_lo: SBTypeStaticField = variant_type.GetStaticFieldWithName( + "DISCR128_EXACT_LO" + ) + + if exact_lo.IsValid(): + exact_lo: int = exact_lo.GetConstantValue(self.valobj.target).GetValueAsUnsigned() + exact_hi: int = variant_type.GetStaticFieldWithName( + "DISCR128_EXACT_HI" + ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + + discr: int = (exact_hi << 64) | exact_lo + if tag == discr: + self.variant = child + self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + return + else: # if invalid, DISCR must be a range + begin_lo: int = variant_type.GetStaticFieldWithName( + "DISCR128_BEGIN_LO" + ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + begin_hi: int = variant_type.GetStaticFieldWithName( + "DISCR128_BEGIN_HI" + ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + + end_lo: int = variant_type.GetStaticFieldWithName( + "DISCR128_END_LO" + ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + end_hi: int = variant_type.GetStaticFieldWithName( + "DISCR128_END_HI" + ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + + begin = (begin_hi << 64) | begin_lo + end = (end_hi << 64) | end_lo + + # begin isn't necessarily smaller than end, so we must test for both cases + if begin < end: + if begin <= tag <= end: + self.variant = child + self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + return + else: + if tag >= begin or tag <= end: + self.variant = child + self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + return + + def num_children(self) -> int: + return self.value.GetNumChildren() + + def get_child_index(self, name: str) -> int: + return self.value.GetIndexOfChildWithName(name) + + def get_child_at_index(self, index: int) -> SBValue: + return self.value.GetChildAtIndex(index) + + def has_children(self) -> bool: + return self.value.MightHaveChildren() + + def get_type_name(self) -> str: + name = self.valobj.GetTypeName() + # remove "enum2$<", str.removeprefix() is python 3.9+ + name = name[7:] + + # MSVC misinterprets ">>" as a shift operator, so spaces are inserted by rust to + # avoid that + if name.endswith(" >"): + name = name[:-2] + elif name.endswith(">"): + name = name[:-1] + + return name + + +def MSVCEnumSummaryProvider(valobj: SBValue, _dict: LLDBOpaque) -> str: + enum_synth = MSVCEnumSyntheticProvider(valobj.GetNonSyntheticValue(), _dict) + variant_names: SBType = valobj.target.FindFirstType( + f"{enum_synth.valobj.GetTypeName()}::VariantNames" + ) + name_idx = ( + enum_synth.variant.GetType() + .GetStaticFieldWithName("NAME") + .GetConstantValue(valobj.target) + .GetValueAsUnsigned() + ) + + name: str = variant_names.enum_members[name_idx].name + + if enum_synth.num_children() == 0: + return name + + child_name: str = enum_synth.value.GetChildAtIndex(0).name + if child_name == "0" or child_name == "__0": + # enum variant is a tuple struct + return name + TupleSummaryProvider(enum_synth.value, _dict) + else: + # enum variant is a regular struct + var_list = ( + str(enum_synth.value.GetNonSyntheticValue()).split("= ", 1)[1].splitlines() + ) + vars = [x.strip() for x in var_list if x not in ("{", "}")] + if vars[0][0] == "(": + vars[0] = vars[0][1:] + if vars[-1][-1] == ")": + vars[-1] = vars[-1][:-1] + + return f'{name}{{{", ".join(vars)}}}' + class TupleSyntheticProvider: """Pretty-printer for tuples and tuple enum variants""" From 009994a8499d1156b2d54429bfa2622c8140bf5b Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Fri, 10 Jan 2025 21:21:44 -0600 Subject: [PATCH 04/29] organize lldb_commands --- src/etc/lldb_commands | 75 ++++++++++++++++++++++++++++--------------- 1 file changed, 50 insertions(+), 25 deletions(-) diff --git a/src/etc/lldb_commands b/src/etc/lldb_commands index 24c485b35337..b2ec8aa23999 100644 --- a/src/etc/lldb_commands +++ b/src/etc/lldb_commands @@ -1,51 +1,76 @@ +# Std String type synthetic add -l lldb_lookup.synthetic_lookup -x "^(alloc::([a-z_]+::)+)String$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)String$" --category Rust +# Std str type synthetic add -l lldb_lookup.synthetic_lookup -x "^&(mut )?str$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?str$" --category Rust +# Array type synthetic add -l lldb_lookup.synthetic_lookup -x "^&(mut )?\\[.+\\]$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?\\[.+\\]$" --category Rust +# Slice +## MSVC +type synthetic add -l lldb_lookup.MSVCStdSliceSyntheticProvider -x "^ref\$ >" --category Rust +type summary add -F lldb_lookup.StdSliceSummaryProvider -e -x -h "^ref(_mut)?\$ >" --category Rust +# OsString type synthetic add -l lldb_lookup.synthetic_lookup -x "^(std::ffi::([a-z_]+::)+)OsString$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::ffi::([a-z_]+::)+)OsString$" --category Rust +# Vec type synthetic add -l lldb_lookup.synthetic_lookup -x "^(alloc::([a-z_]+::)+)Vec<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)Vec<.+>$" --category Rust +# VecDeque type synthetic add -l lldb_lookup.synthetic_lookup -x "^(alloc::([a-z_]+::)+)VecDeque<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)VecDeque<.+>$" --category Rust +# BTreeSet type synthetic add -l lldb_lookup.synthetic_lookup -x "^(alloc::([a-z_]+::)+)BTreeSet<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)BTreeSet<.+>$" --category Rust +# BTreeMap type synthetic add -l lldb_lookup.synthetic_lookup -x "^(alloc::([a-z_]+::)+)BTreeMap<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)BTreeMap<.+>$" --category Rust +# HashMap type synthetic add -l lldb_lookup.synthetic_lookup -x "^(std::collections::([a-z_]+::)+)HashMap<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::collections::([a-z_]+::)+)HashMap<.+>$" --category Rust +# HashSet type synthetic add -l lldb_lookup.synthetic_lookup -x "^(std::collections::([a-z_]+::)+)HashSet<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::collections::([a-z_]+::)+)HashSet<.+>$" --category Rust +# Rc type synthetic add -l lldb_lookup.synthetic_lookup -x "^(alloc::([a-z_]+::)+)Rc<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)Rc<.+>$" --category Rust +# Arc type synthetic add -l lldb_lookup.synthetic_lookup -x "^(alloc::([a-z_]+::)+)Arc<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)Arc<.+>$" --category Rust +# Cell type synthetic add -l lldb_lookup.synthetic_lookup -x "^(core::([a-z_]+::)+)Cell<.+>$" --category Rust +type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)Cell<.+>$" --category Rust +# RefCell type synthetic add -l lldb_lookup.synthetic_lookup -x "^(core::([a-z_]+::)+)Ref<.+>$" --category Rust type synthetic add -l lldb_lookup.synthetic_lookup -x "^(core::([a-z_]+::)+)RefMut<.+>$" --category Rust type synthetic add -l lldb_lookup.synthetic_lookup -x "^(core::([a-z_]+::)+)RefCell<.+>$" --category Rust -type synthetic add -l lldb_lookup.synthetic_lookup -x "^(core::([a-z_]+::)+)NonZero<.+>$" --category Rust -type synthetic add -l lldb_lookup.synthetic_lookup -x "^core::num::([a-z_]+::)*NonZero.+$" --category Rust -type synthetic add -l lldb_lookup.synthetic_lookup -x "^(std::([a-z_]+::)+)PathBuf$" --category Rust -type synthetic add -l lldb_lookup.synthetic_lookup -x "^&(mut )?(std::([a-z_]+::)+)Path$" --category Rust -type synthetic add -l lldb_lookup.MSVCEnumSyntheticProvider -x "^enum2\$<.+>$" --category Rust -type synthetic add -l lldb_lookup.synthetic_lookup -x "^enum2\$<.+>::.*$" --category Rust -type synthetic add -l lldb_lookup.MSVCStdSliceSyntheticProvider -x "^ref\$ >" --category Rust -type synthetic add -l lldb_lookup.MSVCTupleSyntheticProvider -x "^tuple\$<.+>$" --category Rust -type synthetic add -l lldb_lookup.synthetic_lookup -x "^\(.*\)$" --category Rust -type summary add -F _ -e -x -h "^.*$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)String$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?str$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?\\[.+\\]$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::ffi::([a-z_]+::)+)OsString$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)Vec<.+>$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)VecDeque<.+>$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)BTreeSet<.+>$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)BTreeMap<.+>$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::collections::([a-z_]+::)+)HashMap<.+>$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::collections::([a-z_]+::)+)HashSet<.+>$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)Rc<.+>$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)Arc<.+>$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)Cell<.+>$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)Ref<.+>$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)RefMut<.+>$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)RefCell<.+>$" --category Rust +# NonZero +type synthetic add -l lldb_lookup.synthetic_lookup -x "^(core::([a-z_]+::)+)NonZero<.+>$" --category Rust +type synthetic add -l lldb_lookup.synthetic_lookup -x "^core::num::([a-z_]+::)*NonZero.+$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^(core::([a-z_]+::)+)NonZero<.+>$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^core::num::([a-z_]+::)*NonZero.+$" --category Rust +# PathBuf +type synthetic add -l lldb_lookup.synthetic_lookup -x "^(std::([a-z_]+::)+)PathBuf$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^(std::([a-z_]+::)+)PathBuf$" --category Rust +# Path +type synthetic add -l lldb_lookup.synthetic_lookup -x "^&(mut )?(std::([a-z_]+::)+)Path$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?(std::([a-z_]+::)+)Path$" --category Rust -type summary add -F lldb_lookup.TupleSummaryProvider -e -x -h "^tuple\$<.+>$" --category Rust -type summary add -F lldb_lookup.StdSliceSummaryProvider -e -x -h "^ref(_mut)?\$ >" --category Rust +# Enum +## MSVC +type synthetic add -l lldb_lookup.MSVCEnumSyntheticProvider -x "^enum2\$<.+>$" --category Rust type summary add -F lldb_lookup.MSVCEnumSummaryProvider -e -x -h "^enum2\$<.+>$" --category Rust +## MSVC Variants +type synthetic add -l lldb_lookup.synthetic_lookup -x "^enum2\$<.+>::.*$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^enum2\$<.+>::.*$" --category Rust +# Tuple +type synthetic add -l lldb_lookup.synthetic_lookup -x "^\(.*\)$" --category Rust +## MSVC +type synthetic add -l lldb_lookup.MSVCTupleSyntheticProvider -x "^tuple\$<.+>$" --category Rust +type summary add -F lldb_lookup.TupleSummaryProvider -e -x -h "^tuple\$<.+>$" --category Rust +# Forces test-compliant formatting to all other types +type summary add -F _ -e -x -h "^.*$" --category Rust type category enable Rust From 2b8ff7534a085271d3803cfd9401ef3ec9112563 Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Fri, 10 Jan 2025 21:47:27 -0600 Subject: [PATCH 05/29] add MSVC str providers --- src/etc/lldb_commands | 9 ++- src/etc/lldb_providers.py | 140 +++++++++++++++++++++++++++++--------- 2 files changed, 114 insertions(+), 35 deletions(-) diff --git a/src/etc/lldb_commands b/src/etc/lldb_commands index b2ec8aa23999..e2c30acfc850 100644 --- a/src/etc/lldb_commands +++ b/src/etc/lldb_commands @@ -1,15 +1,20 @@ +# Forces test-compliant formatting to all other types +type summary add -F _ -e -x -h "^.*$" --category Rust # Std String type synthetic add -l lldb_lookup.synthetic_lookup -x "^(alloc::([a-z_]+::)+)String$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)String$" --category Rust # Std str type synthetic add -l lldb_lookup.synthetic_lookup -x "^&(mut )?str$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?str$" --category Rust +## MSVC +type synthetic add -l lldb_lookup.MSVCStrSyntheticProvider -x "^ref(_mut)?\$$" --category Rust +type summary add -F lldb_lookup.StdStrSummaryProvider -e -h -x "^ref(_mut)?\$$" --category Rust # Array type synthetic add -l lldb_lookup.synthetic_lookup -x "^&(mut )?\\[.+\\]$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?\\[.+\\]$" --category Rust # Slice ## MSVC -type synthetic add -l lldb_lookup.MSVCStdSliceSyntheticProvider -x "^ref\$ >" --category Rust +type synthetic add -l lldb_lookup.MSVCStdSliceSyntheticProvider -x "^ref(_mut)?\$ >" --category Rust type summary add -F lldb_lookup.StdSliceSummaryProvider -e -x -h "^ref(_mut)?\$ >" --category Rust # OsString type synthetic add -l lldb_lookup.synthetic_lookup -x "^(std::ffi::([a-z_]+::)+)OsString$" --category Rust @@ -71,6 +76,4 @@ type synthetic add -l lldb_lookup.synthetic_lookup -x "^\(.*\)$" --category Rust ## MSVC type synthetic add -l lldb_lookup.MSVCTupleSyntheticProvider -x "^tuple\$<.+>$" --category Rust type summary add -F lldb_lookup.TupleSummaryProvider -e -x -h "^tuple\$<.+>$" --category Rust -# Forces test-compliant formatting to all other types -type summary add -F _ -e -x -h "^.*$" --category Rust type category enable Rust diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index b05dd5162f09..b1bf6f9b06c2 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -266,6 +266,47 @@ def has_children(self) -> bool: return True +class MSVCStrSyntheticProvider: + __slots__ = ["valobj", "data_ptr", "length"] + + def __init__(self, valobj: SBValue, _dict: LLDBOpaque): + self.valobj = valobj + self.update() + + def update(self): + self.data_ptr = self.valobj.GetChildMemberWithName("data_ptr") + self.length = self.valobj.GetChildMemberWithName("length").GetValueAsUnsigned() + + def has_children(self) -> bool: + return True + + def num_children(self) -> int: + return self.length + + def get_child_index(self, name: str) -> int: + index = name.lstrip("[").rstrip("]") + if index.isdigit(): + return int(index) + + return -1 + + def get_child_at_index(self, index: int) -> SBValue: + if not 0 <= index < self.length: + return None + start = self.data_ptr.GetValueAsUnsigned() + address = start + index + element = self.data_ptr.CreateValueFromAddress( + f"[{index}]", address, self.data_ptr.GetType().GetPointeeType() + ) + return element + + def get_type_name(self): + if self.valobj.GetTypeName().startswith("ref_mut"): + return "&mut str" + else: + return "&str" + + class ClangEncodedEnumProvider: """Pretty-printer for 'clang-encoded' enums support implemented in LLDB""" @@ -327,6 +368,7 @@ def _getCurrentVariantIndex(self, all_variants: SBValue) -> int: default_index = i return default_index + class MSVCEnumSyntheticProvider: """ Synthetic provider for sum-type enums on MSVC. For a detailed explanation of the internals, @@ -336,6 +378,7 @@ class MSVCEnumSyntheticProvider: """ __slots__ = ["valobj", "variant", "value"] + def __init__(self, valobj: SBValue, _dict: LLDBOpaque): self.valobj = valobj self.variant: SBValue @@ -362,30 +405,44 @@ def update(self): ).GetValueAsUnsigned() if tag == discr: self.variant = child - self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + self.value = child.GetChildMemberWithName( + "value" + ).GetSyntheticValue() return else: # if invalid, DISCR must be a range - begin: int = variant_type.GetStaticFieldWithName( - "DISCR_BEGIN" - ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() - end: int = variant_type.GetStaticFieldWithName( - "DISCR_END" - ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + begin: int = ( + variant_type.GetStaticFieldWithName("DISCR_BEGIN") + .GetConstantValue(self.valobj.target) + .GetValueAsUnsigned() + ) + end: int = ( + variant_type.GetStaticFieldWithName("DISCR_END") + .GetConstantValue(self.valobj.target) + .GetValueAsUnsigned() + ) # begin isn't necessarily smaller than end, so we must test for both cases if begin < end: if begin <= tag <= end: self.variant = child - self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + self.value = child.GetChildMemberWithName( + "value" + ).GetSyntheticValue() return else: if tag >= begin or tag <= end: self.variant = child - self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + self.value = child.GetChildMemberWithName( + "value" + ).GetSyntheticValue() return else: # if invalid, tag is a 128 bit value - tag_lo: int = self.valobj.GetChildMemberWithName("tag128_lo").GetValueAsUnsigned() - tag_hi: int = self.valobj.GetChildMemberWithName("tag128_hi").GetValueAsUnsigned() + tag_lo: int = self.valobj.GetChildMemberWithName( + "tag128_lo" + ).GetValueAsUnsigned() + tag_hi: int = self.valobj.GetChildMemberWithName( + "tag128_hi" + ).GetValueAsUnsigned() tag: int = (tag_hi << 64) | tag_lo @@ -399,30 +456,44 @@ def update(self): ) if exact_lo.IsValid(): - exact_lo: int = exact_lo.GetConstantValue(self.valobj.target).GetValueAsUnsigned() - exact_hi: int = variant_type.GetStaticFieldWithName( - "DISCR128_EXACT_HI" - ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + exact_lo: int = exact_lo.GetConstantValue( + self.valobj.target + ).GetValueAsUnsigned() + exact_hi: int = ( + variant_type.GetStaticFieldWithName("DISCR128_EXACT_HI") + .GetConstantValue(self.valobj.target) + .GetValueAsUnsigned() + ) discr: int = (exact_hi << 64) | exact_lo if tag == discr: self.variant = child - self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + self.value = child.GetChildMemberWithName( + "value" + ).GetSyntheticValue() return else: # if invalid, DISCR must be a range - begin_lo: int = variant_type.GetStaticFieldWithName( - "DISCR128_BEGIN_LO" - ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() - begin_hi: int = variant_type.GetStaticFieldWithName( - "DISCR128_BEGIN_HI" - ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() - - end_lo: int = variant_type.GetStaticFieldWithName( - "DISCR128_END_LO" - ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() - end_hi: int = variant_type.GetStaticFieldWithName( - "DISCR128_END_HI" - ).GetConstantValue(self.valobj.target).GetValueAsUnsigned() + begin_lo: int = ( + variant_type.GetStaticFieldWithName("DISCR128_BEGIN_LO") + .GetConstantValue(self.valobj.target) + .GetValueAsUnsigned() + ) + begin_hi: int = ( + variant_type.GetStaticFieldWithName("DISCR128_BEGIN_HI") + .GetConstantValue(self.valobj.target) + .GetValueAsUnsigned() + ) + + end_lo: int = ( + variant_type.GetStaticFieldWithName("DISCR128_END_LO") + .GetConstantValue(self.valobj.target) + .GetValueAsUnsigned() + ) + end_hi: int = ( + variant_type.GetStaticFieldWithName("DISCR128_END_HI") + .GetConstantValue(self.valobj.target) + .GetValueAsUnsigned() + ) begin = (begin_hi << 64) | begin_lo end = (end_hi << 64) | end_lo @@ -431,12 +502,16 @@ def update(self): if begin < end: if begin <= tag <= end: self.variant = child - self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + self.value = child.GetChildMemberWithName( + "value" + ).GetSyntheticValue() return else: if tag >= begin or tag <= end: self.variant = child - self.value = child.GetChildMemberWithName("value").GetSyntheticValue() + self.value = child.GetChildMemberWithName( + "value" + ).GetSyntheticValue() return def num_children(self) -> int: @@ -498,7 +573,7 @@ def MSVCEnumSummaryProvider(valobj: SBValue, _dict: LLDBOpaque) -> str: if vars[-1][-1] == ")": vars[-1] = vars[-1][:-1] - return f'{name}{{{", ".join(vars)}}}' + return f"{name}{{{', '.join(vars)}}}" class TupleSyntheticProvider: @@ -681,6 +756,7 @@ def get_type_name(self) -> str: return "".join([ref, "[", name, "]"]) + def StdSliceSummaryProvider(valobj, dict): output = sequence_formatter("[", valobj, dict) output += "]" From 4f595334f5771b28d85c46f29859d2e48af270b5 Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Fri, 10 Jan 2025 22:02:45 -0600 Subject: [PATCH 06/29] add alternate inner type lookup for vec/string for missing template args --- src/etc/lldb_commands | 4 +- src/etc/lldb_providers.py | 89 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 86 insertions(+), 7 deletions(-) diff --git a/src/etc/lldb_commands b/src/etc/lldb_commands index e2c30acfc850..5f24d0da047e 100644 --- a/src/etc/lldb_commands +++ b/src/etc/lldb_commands @@ -1,8 +1,8 @@ # Forces test-compliant formatting to all other types type summary add -F _ -e -x -h "^.*$" --category Rust # Std String -type synthetic add -l lldb_lookup.synthetic_lookup -x "^(alloc::([a-z_]+::)+)String$" --category Rust -type summary add -F lldb_lookup.summary_lookup -e -x -h "^(alloc::([a-z_]+::)+)String$" --category Rust +type synthetic add -l lldb_lookup.StdStringSyntheticProvider -x "^(alloc::([a-z_]+::)+)String$" --category Rust +type summary add -F lldb_lookup.StdStringSummaryProvider -e -x -h "^(alloc::([a-z_]+::)+)String$" --category Rust # Std str type synthetic add -l lldb_lookup.synthetic_lookup -x "^&(mut )?str$" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h "^&(mut )?str$" --category Rust diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index b1bf6f9b06c2..063db7abb3ca 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -9,6 +9,7 @@ eBasicTypeLong, eBasicTypeUnsignedLong, eBasicTypeUnsignedChar, + eFormatChar, ) # from lldb.formatters import Logger @@ -143,11 +144,32 @@ def vec_to_string(vec: SBValue) -> str: ) -def StdStringSummaryProvider(valobj: SBValue, _dict: LLDBOpaque) -> str: - # logger = Logger.Logger() - # logger >> "[StdStringSummaryProvider] for " + str(valobj.GetName()) - vec = valobj.GetChildAtIndex(0) - return '"%s"' % vec_to_string(vec) +def StdStringSummaryProvider(valobj, dict): + inner_vec = ( + valobj.GetNonSyntheticValue() + .GetChildMemberWithName("vec") + .GetNonSyntheticValue() + ) + + pointer = ( + inner_vec.GetChildMemberWithName("buf") + .GetChildMemberWithName("inner") + .GetChildMemberWithName("ptr") + .GetChildMemberWithName("pointer") + .GetChildMemberWithName("pointer") + ) + + length = inner_vec.GetChildMemberWithName("len").GetValueAsUnsigned() + + if length <= 0: + return "" + error = SBError() + process = pointer.GetProcess() + data = process.ReadMemory(pointer.GetValueAsUnsigned(), length, error) + if error.Success(): + return '"' + data.decode("utf8", "replace") + '"' + else: + raise Exception("ReadMemory error: %s", error.GetCString()) def StdOsStringSummaryProvider(valobj: SBValue, _dict: LLDBOpaque) -> str: @@ -266,6 +288,48 @@ def has_children(self) -> bool: return True +class StdStringSyntheticProvider: + def __init__(self, valobj: SBValue, _dict: LLDBOpaque): + self.valobj = valobj + self.update() + + def update(self): + inner_vec = self.valobj.GetChildMemberWithName("vec").GetNonSyntheticValue() + self.data_ptr = ( + inner_vec.GetChildMemberWithName("buf") + .GetChildMemberWithName("inner") + .GetChildMemberWithName("ptr") + .GetChildMemberWithName("pointer") + .GetChildMemberWithName("pointer") + ) + self.length = inner_vec.GetChildMemberWithName("len").GetValueAsUnsigned() + self.element_type = self.data_ptr.GetType().GetPointeeType() + + def has_children(self) -> bool: + return True + + def num_children(self) -> int: + return self.length + + def get_child_index(self, name: str) -> int: + index = name.lstrip("[").rstrip("]") + if index.isdigit(): + return int(index) + + return -1 + + def get_child_at_index(self, index: int) -> SBValue: + if not 0 <= index < self.length: + return None + start = self.data_ptr.GetValueAsUnsigned() + address = start + index + element = self.data_ptr.CreateValueFromAddress( + f"[{index}]", address, self.element_type + ) + element.SetFormat(eFormatChar) + return element + + class MSVCStrSyntheticProvider: __slots__ = ["valobj", "data_ptr", "length"] @@ -699,6 +763,21 @@ def update(self): ) self.element_type = self.valobj.GetType().GetTemplateArgumentType(0) + + if not self.element_type.IsValid(): + # annoyingly, vec's constituent type isn't guaranteed to be contained anywhere useful. + # Some functions have it, but those functions only exist in binary when they're used. + # that means it's time for string-based garbage. + + # acquire the first generic parameter via its type name + _, _, end = self.valobj.GetTypeName().partition("<") + element_name, _, _ = end.partition(",") + + # this works even for built-in rust types like `u32` because internally it's just a + # `typedef` i really REALLY wish there was a better way to do this, but at the moment + # LLDB flat out ignores template parameters due to piggybacking off of TypeSystemClang. + self.element_type = self.valobj.target.FindFirstType(element_name) + self.element_type_size = self.element_type.GetByteSize() def has_children(self) -> bool: From f725ad7f1d7485ee78feae1db03a37245682b7b0 Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Fri, 10 Jan 2025 22:21:49 -0600 Subject: [PATCH 07/29] more robust tuple summary --- src/etc/lldb_providers.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index 063db7abb3ca..d928f1d0cf5c 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -1,4 +1,5 @@ import sys +from typing import List from lldb import ( SBData, @@ -710,9 +711,18 @@ def get_type_name(self) -> str: def TupleSummaryProvider(valobj: SBValue, _dict: LLDBOpaque): - output: str = sequence_formatter("(", valobj, dict) - output += ")" - return output + output: List[str] = [] + + for i in range(0, valobj.GetNumChildren()): + child: SBValue = valobj.GetChildAtIndex(i) + summary = child.summary + if summary is None: + summary = child.value + if summary is None: + summary = "{...}" + output.append(summary) + + return "(" + ", ".join(output) + ")" class StdVecSyntheticProvider: From 0bf0817dd50b2784c46660ce5778325053e2237d Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Sat, 11 Jan 2025 00:38:48 -0600 Subject: [PATCH 08/29] More robust sequence formatter --- src/etc/lldb_providers.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index d928f1d0cf5c..a1470c4c1a4e 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -238,8 +238,15 @@ def sequence_formatter(output: str, valobj: SBValue, _dict: LLDBOpaque): if len(output) > 32: long = True break + child: SBValue = valobj.GetChildAtIndex(i) - output += f"{child.value}, " + + summary = child.summary + if summary is None: + summary = child.value + if summary is None: + summary = "{...}" + output += f"{summary}, " if long: output = f"(len: {length}) " + output + "..." else: From a3adcd24db6b25b1bf85ef8c3314ee9664c7228c Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Sat, 11 Jan 2025 03:33:41 -0600 Subject: [PATCH 09/29] add alternate inner type lookup for hashmap/set when template args missing --- src/etc/lldb_providers.py | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index a1470c4c1a4e..b380db81eeca 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -130,6 +130,23 @@ def update(self): def has_children(self) -> bool: return False +def get_template_args(type_name: str) -> List[str]: + params = [] + level = 0 + start = 0 + for i, c in enumerate(type_name): + if c == "<": + level += 1 + if level == 1: + start = i + 1 + elif c == ">": + level -= 1 + if level == 0: + params.append(type_name[start:i].strip()) + elif c == "," and level == 1: + params.append(type_name[start:i].strip()) + start = i + 1 + return params def SizeSummaryProvider(valobj: SBValue, _dict: LLDBOpaque) -> str: return "size=" + str(valobj.GetNumChildren()) @@ -1050,7 +1067,16 @@ def update(self): ctrl = inner_table.GetChildMemberWithName("ctrl").GetChildAtIndex(0) self.size = inner_table.GetChildMemberWithName("items").GetValueAsUnsigned() - self.pair_type = table.type.template_args[0] + + template_args = table.type.template_args + + if template_args is None: + type_name = table.GetTypeName() + args = get_template_args(type_name) + self.pair_type = self.valobj.target.FindFirstType(args[0]) + else: + self.pair_type = template_args[0] + if self.pair_type.IsTypedefType(): self.pair_type = self.pair_type.GetTypedefedType() self.pair_type_size = self.pair_type.GetByteSize() From 2be88129f9fc67071df8542035825d74197ac879 Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Sat, 11 Jan 2025 03:40:07 -0600 Subject: [PATCH 10/29] tidy --- src/etc/lldb_providers.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index b380db81eeca..c0371699ed7b 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -130,6 +130,7 @@ def update(self): def has_children(self) -> bool: return False + def get_template_args(type_name: str) -> List[str]: params = [] level = 0 @@ -148,6 +149,7 @@ def get_template_args(type_name: str) -> List[str]: start = i + 1 return params + def SizeSummaryProvider(valobj: SBValue, _dict: LLDBOpaque) -> str: return "size=" + str(valobj.GetNumChildren()) From e8c5e09e4f5df601943c2cfb20d3447a6caed043 Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Sat, 11 Jan 2025 19:09:08 -0600 Subject: [PATCH 11/29] doc comment for get_template_args --- src/etc/lldb_providers.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index c0371699ed7b..3cfec8a6a29e 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -131,7 +131,18 @@ def has_children(self) -> bool: return False -def get_template_args(type_name: str) -> List[str]: +def get_template_args(type_name: str) -> list[str]: + """ + Takes a type name `T, D>` and returns a list of its generic args + `["A", "tuple$", "D"]`. + + String-based replacement for LLDB's `SBType.template_args`, as LLDB is currently unable to + populate this field for targets with PDB debug info. Also useful for manually altering the type + name of generics (e.g. `Vec` -> `Vec<&str>`). + + Each element of the returned list can be looked up for its `SBType` value via + `SBTarget.FindFirstType()` + """ params = [] level = 0 start = 0 @@ -801,17 +812,7 @@ def update(self): self.element_type = self.valobj.GetType().GetTemplateArgumentType(0) if not self.element_type.IsValid(): - # annoyingly, vec's constituent type isn't guaranteed to be contained anywhere useful. - # Some functions have it, but those functions only exist in binary when they're used. - # that means it's time for string-based garbage. - - # acquire the first generic parameter via its type name - _, _, end = self.valobj.GetTypeName().partition("<") - element_name, _, _ = end.partition(",") - - # this works even for built-in rust types like `u32` because internally it's just a - # `typedef` i really REALLY wish there was a better way to do this, but at the moment - # LLDB flat out ignores template parameters due to piggybacking off of TypeSystemClang. + element_name = get_template_args(self.valobj.GetTypeName())[0] self.element_type = self.valobj.target.FindFirstType(element_name) self.element_type_size = self.element_type.GetByteSize() From 0f12b8cf121365ba48703fda854e5b5b523e8938 Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Sat, 18 Jan 2025 21:12:23 -0600 Subject: [PATCH 12/29] slots fix --- src/etc/lldb_providers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index 3cfec8a6a29e..319682a1c8c8 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -822,7 +822,7 @@ def has_children(self) -> bool: class StdSliceSyntheticProvider: - __slots__ = ["valobj", "length", "ptr", "element_type", "element_size"] + __slots__ = ["valobj", "length", "data_ptr", "element_type", "element_size"] def __init__(self, valobj: SBValue, _dict: LLDBOpaque): self.valobj = valobj From 0819c1638c6fdb41884d7aadd1528611b2f09d7b Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Fri, 7 Feb 2025 20:41:57 -0600 Subject: [PATCH 13/29] Fix import/attribute errors related to `SBTypeStaticField` --- src/etc/lldb_providers.py | 56 ++++++++++++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index 319682a1c8c8..573cc50a8685 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -1,18 +1,19 @@ +from __future__ import annotations import sys -from typing import List +from typing import List, TYPE_CHECKING from lldb import ( SBData, SBError, - SBType, - SBTypeStaticField, - SBValue, eBasicTypeLong, eBasicTypeUnsignedLong, eBasicTypeUnsignedChar, eFormatChar, ) +if TYPE_CHECKING: + from lldb import SBValue, SBType, SBTypeStaticField + # from lldb.formatters import Logger #################################################################################################### @@ -497,9 +498,18 @@ def update(self): continue variant_type: SBType = child.GetType() - exact: SBTypeStaticField = variant_type.GetStaticFieldWithName( - "DISCR_EXACT" - ) + try: + exact: SBTypeStaticField = variant_type.GetStaticFieldWithName( + "DISCR_EXACT" + ) + except AttributeError: + # LLDB versions prior to 19.0.0 do not have the `SBTypeGetStaticField` API. + # With current DI generation there's not a great way to provide a "best effort" + # evaluation either, so we just return the object itself with no further + # attempts to inspect the type information + self.variant = self.valobj + self.value = self.valobj + return if exact.IsValid(): discr: int = exact.GetConstantValue( @@ -648,12 +658,32 @@ def MSVCEnumSummaryProvider(valobj: SBValue, _dict: LLDBOpaque) -> str: variant_names: SBType = valobj.target.FindFirstType( f"{enum_synth.valobj.GetTypeName()}::VariantNames" ) - name_idx = ( - enum_synth.variant.GetType() - .GetStaticFieldWithName("NAME") - .GetConstantValue(valobj.target) - .GetValueAsUnsigned() - ) + try: + name_idx = ( + enum_synth.variant.GetType() + .GetStaticFieldWithName("NAME") + .GetConstantValue(valobj.target) + .GetValueAsUnsigned() + ) + except AttributeError: + # LLDB versions prior to 19 do not have the `SBTypeGetStaticField` API, and have no way + # to determine the value based on the tag field. + tag: SBValue = valobj.GetChildMemberWithName("tag") + + if tag.IsValid(): + discr: int = tag.GetValueAsUnsigned() + return "".join(["{tag = ", str(tag.unsigned), "}"]) + else: + tag_lo: int = valobj.GetChildMemberWithName( + "tag128_lo" + ).GetValueAsUnsigned() + tag_hi: int = valobj.GetChildMemberWithName( + "tag128_hi" + ).GetValueAsUnsigned() + + discr: int = (tag_hi << 64) | tag_lo + + return "".join(["{tag = ", str(discr), "}"]) name: str = variant_names.enum_members[name_idx].name From d6f5d34744a2e2b6823d103353b3e9e3d525c714 Mon Sep 17 00:00:00 2001 From: Walnut <39544927+Walnut356@users.noreply.github.com> Date: Wed, 12 Feb 2025 01:30:09 -0600 Subject: [PATCH 14/29] fix string and tuple struct formatting --- src/etc/lldb_commands | 1 + src/etc/lldb_providers.py | 2 +- tests/debuginfo/empty-string.rs | 2 +- tests/debuginfo/msvc-pretty-enums.rs | 2 +- tests/debuginfo/pretty-std.rs | 3 ++- tests/debuginfo/strings-and-strs.rs | 2 +- 6 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/etc/lldb_commands b/src/etc/lldb_commands index 5f24d0da047e..508296c3a5ae 100644 --- a/src/etc/lldb_commands +++ b/src/etc/lldb_commands @@ -1,4 +1,5 @@ # Forces test-compliant formatting to all other types +type synthetic add -l lldb_lookup.synthetic_lookup -x ".*" --category Rust type summary add -F _ -e -x -h "^.*$" --category Rust # Std String type synthetic add -l lldb_lookup.StdStringSyntheticProvider -x "^(alloc::([a-z_]+::)+)String$" --category Rust diff --git a/src/etc/lldb_providers.py b/src/etc/lldb_providers.py index 573cc50a8685..98426e424239 100644 --- a/src/etc/lldb_providers.py +++ b/src/etc/lldb_providers.py @@ -194,7 +194,7 @@ def StdStringSummaryProvider(valobj, dict): length = inner_vec.GetChildMemberWithName("len").GetValueAsUnsigned() if length <= 0: - return "" + return '""' error = SBError() process = pointer.GetProcess() data = process.ReadMemory(pointer.GetValueAsUnsigned(), length, error) diff --git a/tests/debuginfo/empty-string.rs b/tests/debuginfo/empty-string.rs index 014465c27cab..6cf61e177714 100644 --- a/tests/debuginfo/empty-string.rs +++ b/tests/debuginfo/empty-string.rs @@ -17,7 +17,7 @@ // lldb-command:run // lldb-command:fr v empty_string -// lldb-check:[...] empty_string = "" { vec = size=0 } +// lldb-check:[...] empty_string = "" // lldb-command:fr v empty_str // lldb-check:[...] empty_str = "" diff --git a/tests/debuginfo/msvc-pretty-enums.rs b/tests/debuginfo/msvc-pretty-enums.rs index d60a7b81944e..06bc25dc5d59 100644 --- a/tests/debuginfo/msvc-pretty-enums.rs +++ b/tests/debuginfo/msvc-pretty-enums.rs @@ -30,7 +30,7 @@ // lldb-check:(msvc_pretty_enums::CStyleEnum) j = High // lldb-command:v k -// lldb-check:(core::option::Option) k = { value = { 0 = "IAMA optional string!" { vec = size=21 { [0] = 'I' [1] = 'A' [2] = 'M' [3] = 'A' [4] = ' ' [5] = 'o' [6] = 'p' [7] = 't' [8] = 'i' [9] = 'o' [10] = 'n' [11] = 'a' [12] = 'l' [13] = ' ' [14] = 's' [15] = 't' [16] = 'r' [17] = 'i' [18] = 'n' [19] = 'g' [20] = '!' } } } } +// lldb-check:(core::option::Option) k = { value = { 0 = "IAMA optional string!" { [0] = 'I' [1] = 'A' [2] = 'M' [3] = 'A' [4] = ' ' [5] = 'o' [6] = 'p' [7] = 't' [8] = 'i' [9] = 'o' [10] = 'n' [11] = 'a' [12] = 'l' [13] = ' ' [14] = 's' [15] = 't' [16] = 'r' [17] = 'i' [18] = 'n' [19] = 'g' [20] = '!' } } } // lldb-command:v l // lldb-check:(core::result::Result) l = { value = { 0 = {} } } diff --git a/tests/debuginfo/pretty-std.rs b/tests/debuginfo/pretty-std.rs index d7c640a5bea3..53835d41be24 100644 --- a/tests/debuginfo/pretty-std.rs +++ b/tests/debuginfo/pretty-std.rs @@ -51,7 +51,8 @@ // lldb-check:[...] str_slice = "IAMA string slice!" { [0] = 'I' [1] = 'A' [2] = 'M' [3] = 'A' [4] = ' ' [5] = 's' [6] = 't' [7] = 'r' [8] = 'i' [9] = 'n' [10] = 'g' [11] = ' ' [12] = 's' [13] = 'l' [14] = 'i' [15] = 'c' [16] = 'e' [17] = '!' } // lldb-command:v string -// lldb-check:[...] string = "IAMA string!" { vec = size=12 { [0] = 'I' [1] = 'A' [2] = 'M' [3] = 'A' [4] = ' ' [5] = 's' [6] = 't' [7] = 'r' [8] = 'i' [9] = 'n' [10] = 'g' [11] = '!' } } +// lldb-check:[...] string = "IAMA string!" { [0] = 'I' [1] = 'A' [2] = 'M' [3] = 'A' [4] = ' ' [5] = 's' [6] = 't' [7] = 'r' [8] = 'i' [9] = 'n' [10] = 'g' [11] = '!' } + // lldb-command:v some // lldb-check:[...] some = Some(8) diff --git a/tests/debuginfo/strings-and-strs.rs b/tests/debuginfo/strings-and-strs.rs index 3d6589db34b8..ffdad303d515 100644 --- a/tests/debuginfo/strings-and-strs.rs +++ b/tests/debuginfo/strings-and-strs.rs @@ -24,7 +24,7 @@ // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:v plain_string -// lldb-check:(alloc::string::String) plain_string = "Hello" { vec = size=5 { [0] = 'H' [1] = 'e' [2] = 'l' [3] = 'l' [4] = 'o' } } +// lldb-check:(alloc::string::String) plain_string = "Hello" { [0] = 'H' [1] = 'e' [2] = 'l' [3] = 'l' [4] = 'o' } // lldb-command:v plain_str // lldb-check:(&str) plain_str = "Hello" { [0] = 'H' [1] = 'e' [2] = 'l' [3] = 'l' [4] = 'o' } From 7e7f5d385694ca345e0b47d8c59c7c966ee60a30 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Tue, 11 Feb 2025 01:01:00 +0800 Subject: [PATCH 15/29] Replace mem::zeroed with mem::MaybeUninit::uninit for large struct in unix Signed-off-by: xizheyin --- library/std/src/sys/net/connection/socket.rs | 9 +++++--- .../std/src/sys/net/connection/socket/unix.rs | 7 ++++-- .../std/src/sys/pal/unix/stack_overflow.rs | 23 ++++++++++++++----- library/std/src/sys/pal/unix/thread.rs | 5 ++-- 4 files changed, 31 insertions(+), 13 deletions(-) diff --git a/library/std/src/sys/net/connection/socket.rs b/library/std/src/sys/net/connection/socket.rs index b4f0a7836803..ddd74b426158 100644 --- a/library/std/src/sys/net/connection/socket.rs +++ b/library/std/src/sys/net/connection/socket.rs @@ -557,10 +557,13 @@ impl TcpListener { } pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { - let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() }; + // The `accept` function will fill in the storage with the address, + // so we don't need to zero it here. + // reference: https://linux.die.net/man/2/accept4 + let mut storage: mem::MaybeUninit = mem::MaybeUninit::uninit(); let mut len = mem::size_of_val(&storage) as c::socklen_t; - let sock = self.inner.accept((&raw mut storage) as *mut _, &mut len)?; - let addr = unsafe { socket_addr_from_c(&storage, len as usize)? }; + let sock = self.inner.accept(storage.as_mut_ptr() as *mut _, &mut len)?; + let addr = unsafe { socket_addr_from_c(storage.as_ptr(), len as usize)? }; Ok((TcpStream { inner: sock }, addr)) } diff --git a/library/std/src/sys/net/connection/socket/unix.rs b/library/std/src/sys/net/connection/socket/unix.rs index 34ab26bc117a..29fb47ddca3b 100644 --- a/library/std/src/sys/net/connection/socket/unix.rs +++ b/library/std/src/sys/net/connection/socket/unix.rs @@ -322,7 +322,10 @@ impl Socket { buf: &mut [u8], flags: c_int, ) -> io::Result<(usize, SocketAddr)> { - let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; + // The `recvfrom` function will fill in the storage with the address, + // so we don't need to zero it here. + // reference: https://linux.die.net/man/2/recvfrom + let mut storage: mem::MaybeUninit = mem::MaybeUninit::uninit(); let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t; let n = cvt(unsafe { @@ -335,7 +338,7 @@ impl Socket { &mut addrlen, ) })?; - Ok((n as usize, unsafe { socket_addr_from_c(&storage, addrlen as usize)? })) + Ok((n as usize, unsafe { socket_addr_from_c(storage.as_ptr(), addrlen as usize)? })) } pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { diff --git a/library/std/src/sys/pal/unix/stack_overflow.rs b/library/std/src/sys/pal/unix/stack_overflow.rs index db5c6bd3a1c3..1ccf2011ea16 100644 --- a/library/std/src/sys/pal/unix/stack_overflow.rs +++ b/library/std/src/sys/pal/unix/stack_overflow.rs @@ -319,9 +319,14 @@ mod imp { ))] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { let mut ret = None; - let mut attr: libc::pthread_attr_t = crate::mem::zeroed(); - #[cfg(target_os = "freebsd")] - assert_eq!(libc::pthread_attr_init(&mut attr), 0); + let attr: mem::MaybeUninit = if cfg!(target_os = "freebsd") { + let mut attr = mem::MaybeUninit::uninit(); + assert_eq!(libc::pthread_attr_init((&raw mut attr) as *mut _), 0); + attr + } else { + mem::MaybeUninit::zeroed() + }; + let mut attr = unsafe { attr.assume_init() }; #[cfg(target_os = "freebsd")] let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr); #[cfg(not(target_os = "freebsd"))] @@ -509,9 +514,15 @@ mod imp { // FIXME: I am probably not unsafe. unsafe fn current_guard() -> Option> { let mut ret = None; - let mut attr: libc::pthread_attr_t = crate::mem::zeroed(); - #[cfg(target_os = "freebsd")] - assert_eq!(libc::pthread_attr_init(&mut attr), 0); + let attr: mem::MaybeUninit = if cfg!(target_os = "freebsd") { + let mut attr = mem::MaybeUninit::uninit(); + assert_eq!(libc::pthread_attr_init((&raw mut attr) as *mut _), 0); + attr + } else { + mem::MaybeUninit::zeroed() + }; + + let mut attr = unsafe { attr.assume_init() }; #[cfg(target_os = "freebsd")] let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr); #[cfg(not(target_os = "freebsd"))] diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs index 479021af040a..c339970c5d37 100644 --- a/library/std/src/sys/pal/unix/thread.rs +++ b/library/std/src/sys/pal/unix/thread.rs @@ -49,8 +49,9 @@ impl Thread { pub unsafe fn new(stack: usize, p: Box) -> io::Result { let p = Box::into_raw(Box::new(p)); let mut native: libc::pthread_t = mem::zeroed(); - let mut attr: libc::pthread_attr_t = mem::zeroed(); - assert_eq!(libc::pthread_attr_init(&mut attr), 0); + let mut attr: mem::MaybeUninit = mem::MaybeUninit::uninit(); + assert_eq!(libc::pthread_attr_init((&raw mut attr) as *mut _), 0); + let mut attr: libc::pthread_attr_t = unsafe { attr.assume_init() }; #[cfg(target_os = "espidf")] if stack > 0 { From c1ecdf112401cc03f5e0ed364892e5da04d3bf41 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Tue, 11 Feb 2025 20:38:25 +0800 Subject: [PATCH 16/29] Consistently using as_mut_ptr() and as_ptr() in thread Signed-off-by: xizheyin --- library/std/src/sys/pal/unix/thread.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs index c339970c5d37..d476f6600bf4 100644 --- a/library/std/src/sys/pal/unix/thread.rs +++ b/library/std/src/sys/pal/unix/thread.rs @@ -50,24 +50,27 @@ impl Thread { let p = Box::into_raw(Box::new(p)); let mut native: libc::pthread_t = mem::zeroed(); let mut attr: mem::MaybeUninit = mem::MaybeUninit::uninit(); - assert_eq!(libc::pthread_attr_init((&raw mut attr) as *mut _), 0); - let mut attr: libc::pthread_attr_t = unsafe { attr.assume_init() }; + assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); + //let mut attr: libc::pthread_attr_t = unsafe { attr.assume_init() }; #[cfg(target_os = "espidf")] if stack > 0 { // Only set the stack if a non-zero value is passed // 0 is used as an indication that the default stack size configured in the ESP-IDF menuconfig system should be used assert_eq!( - libc::pthread_attr_setstacksize(&mut attr, cmp::max(stack, min_stack_size(&attr))), + libc::pthread_attr_setstacksize( + attr.as_mut_ptr(), + cmp::max(stack, min_stack_size(&attr)) + ), 0 ); } #[cfg(not(target_os = "espidf"))] { - let stack_size = cmp::max(stack, min_stack_size(&attr)); + let stack_size = cmp::max(stack, min_stack_size(attr.as_ptr())); - match libc::pthread_attr_setstacksize(&mut attr, stack_size) { + match libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size) { 0 => {} n => { assert_eq!(n, libc::EINVAL); @@ -78,16 +81,16 @@ impl Thread { let page_size = os::page_size(); let stack_size = (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1); - assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0); + assert_eq!(libc::pthread_attr_setstacksize(attr.as_mut_ptr(), stack_size), 0); } }; } - let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _); + let ret = libc::pthread_create(&mut native, attr.as_ptr(), thread_start, p as *mut _); // Note: if the thread creation fails and this assert fails, then p will // be leaked. However, an alternative design could cause double-free // which is clearly worse. - assert_eq!(libc::pthread_attr_destroy(&mut attr), 0); + assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); return if ret != 0 { // The thread failed to start and as a result p was not consumed. Therefore, it is From 56a850250bd74acec79f2d721e7bcc2b3cad6165 Mon Sep 17 00:00:00 2001 From: Urgau Date: Tue, 18 Feb 2025 19:48:37 +0100 Subject: [PATCH 17/29] Pre-commit unpretty HIR test --- tests/ui/unpretty/debug-fmt-hir.rs | 26 ++++++++++++++++++++++++++ tests/ui/unpretty/debug-fmt-hir.stdout | 25 +++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 tests/ui/unpretty/debug-fmt-hir.rs create mode 100644 tests/ui/unpretty/debug-fmt-hir.stdout diff --git a/tests/ui/unpretty/debug-fmt-hir.rs b/tests/ui/unpretty/debug-fmt-hir.rs new file mode 100644 index 000000000000..c19f3c4c0c57 --- /dev/null +++ b/tests/ui/unpretty/debug-fmt-hir.rs @@ -0,0 +1,26 @@ +//@ compile-flags: -Zunpretty=hir +//@ check-pass + +use std::fmt; + +pub struct Bar { + a: String, + b: u8, +} + +impl fmt::Debug for Bar { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + debug_struct_field2_finish(f, "Bar", "a", &self.a, "b", &&self.b) + } +} + +fn debug_struct_field2_finish<'a>( + name: &str, + name1: &str, + value1: &'a dyn fmt::Debug, + name2: &str, + value2: &'a dyn fmt::Debug, +) -> fmt::Result +{ + loop {} +} diff --git a/tests/ui/unpretty/debug-fmt-hir.stdout b/tests/ui/unpretty/debug-fmt-hir.stdout new file mode 100644 index 000000000000..184c50942858 --- /dev/null +++ b/tests/ui/unpretty/debug-fmt-hir.stdout @@ -0,0 +1,25 @@ +#[prelude_import] +use ::std::prelude::rust_2015::*; +#[macro_use] +extern crate std; +//@ compile-flags: -Zunpretty=hir +//@ check-pass + +use std::fmt; + +struct Bar { + a: String, + b: u8, +} + +impl fmt::Debug for Bar { + fn fmt<'_, '_, '_>(self: &'_ Self, f: &'_ mut fmt::Formatter<'_>) + -> + fmt::Result { + debug_struct_field2_finish(f, "Bar", "a", &self.a, "b", &&self.b) + } +} + +fn debug_struct_field2_finish<'a, '_, '_, + '_>(name: &'_ str, name1: &'_ str, value1: &'a dyn fmt::Debug, + name2: &'_ str, value2: &'a dyn fmt::Debug) -> fmt::Result { loop { } } From 604364fcf44e0843e4ea9818daaf97418da233d5 Mon Sep 17 00:00:00 2001 From: xizheyin Date: Wed, 19 Feb 2025 13:20:03 +0800 Subject: [PATCH 18/29] remove assume_init in stack_overflow Signed-off-by: xizheyin --- library/std/src/sys/pal/unix/stack_overflow.rs | 15 +++++++++------ library/std/src/sys/pal/unix/thread.rs | 1 - 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/library/std/src/sys/pal/unix/stack_overflow.rs b/library/std/src/sys/pal/unix/stack_overflow.rs index 1ccf2011ea16..0550223eb9ac 100644 --- a/library/std/src/sys/pal/unix/stack_overflow.rs +++ b/library/std/src/sys/pal/unix/stack_overflow.rs @@ -319,26 +319,29 @@ mod imp { ))] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { let mut ret = None; - let attr: mem::MaybeUninit = if cfg!(target_os = "freebsd") { + let mut attr: mem::MaybeUninit = if cfg!(target_os = "freebsd") { let mut attr = mem::MaybeUninit::uninit(); assert_eq!(libc::pthread_attr_init((&raw mut attr) as *mut _), 0); attr } else { mem::MaybeUninit::zeroed() }; - let mut attr = unsafe { attr.assume_init() }; + #[cfg(target_os = "freebsd")] - let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr); + let e = libc::pthread_attr_get_np(libc::pthread_self(), attr.as_mut_ptr()); #[cfg(not(target_os = "freebsd"))] - let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr); + let e = libc::pthread_getattr_np(libc::pthread_self(), attr.as_mut_ptr()); if e == 0 { let mut stackaddr = crate::ptr::null_mut(); let mut stacksize = 0; - assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0); + assert_eq!( + libc::pthread_attr_getstack(attr.as_ptr(), &mut stackaddr, &mut stacksize), + 0 + ); ret = Some(stackaddr); } if e == 0 || cfg!(target_os = "freebsd") { - assert_eq!(libc::pthread_attr_destroy(&mut attr), 0); + assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); } ret } diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs index d476f6600bf4..e23d3d6d647a 100644 --- a/library/std/src/sys/pal/unix/thread.rs +++ b/library/std/src/sys/pal/unix/thread.rs @@ -51,7 +51,6 @@ impl Thread { let mut native: libc::pthread_t = mem::zeroed(); let mut attr: mem::MaybeUninit = mem::MaybeUninit::uninit(); assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); - //let mut attr: libc::pthread_attr_t = unsafe { attr.assume_init() }; #[cfg(target_os = "espidf")] if stack > 0 { From 70f11ee0c063fa85dff72306c2ec29532b8cabeb Mon Sep 17 00:00:00 2001 From: xizheyin Date: Wed, 19 Feb 2025 20:16:28 +0800 Subject: [PATCH 19/29] fix by comments Signed-off-by: xizheyin --- .../std/src/sys/pal/unix/stack_overflow.rs | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/library/std/src/sys/pal/unix/stack_overflow.rs b/library/std/src/sys/pal/unix/stack_overflow.rs index 0550223eb9ac..43ece63457fe 100644 --- a/library/std/src/sys/pal/unix/stack_overflow.rs +++ b/library/std/src/sys/pal/unix/stack_overflow.rs @@ -319,14 +319,12 @@ mod imp { ))] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { let mut ret = None; - let mut attr: mem::MaybeUninit = if cfg!(target_os = "freebsd") { - let mut attr = mem::MaybeUninit::uninit(); - assert_eq!(libc::pthread_attr_init((&raw mut attr) as *mut _), 0); - attr - } else { - mem::MaybeUninit::zeroed() - }; - + let mut attr: mem::MaybeUninit = mem::MaybeUninit::uninit(); + if !cfg!(target_os = "freebsd") { + attr = mem::MaybeUninit::zeroed(); + } + #[cfg(target_os = "freebsd")] + assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); #[cfg(target_os = "freebsd")] let e = libc::pthread_attr_get_np(libc::pthread_self(), attr.as_mut_ptr()); #[cfg(not(target_os = "freebsd"))] @@ -517,22 +515,20 @@ mod imp { // FIXME: I am probably not unsafe. unsafe fn current_guard() -> Option> { let mut ret = None; - let attr: mem::MaybeUninit = if cfg!(target_os = "freebsd") { - let mut attr = mem::MaybeUninit::uninit(); - assert_eq!(libc::pthread_attr_init((&raw mut attr) as *mut _), 0); - attr - } else { - mem::MaybeUninit::zeroed() - }; - let mut attr = unsafe { attr.assume_init() }; + let mut attr: mem::MaybeUninit = mem::MaybeUninit::uninit(); + if !cfg!(target_os = "freebsd") { + attr = mem::MaybeUninit::zeroed(); + } + #[cfg(target_os = "freebsd")] + assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); #[cfg(target_os = "freebsd")] - let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr); + let e = libc::pthread_attr_get_np(libc::pthread_self(), attr.as_mut_ptr()); #[cfg(not(target_os = "freebsd"))] - let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr); + let e = libc::pthread_getattr_np(libc::pthread_self(), attr.as_mut_ptr()); if e == 0 { let mut guardsize = 0; - assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0); + assert_eq!(libc::pthread_attr_getguardsize(attr.as_ptr(), &mut guardsize), 0); if guardsize == 0 { if cfg!(all(target_os = "linux", target_env = "musl")) { // musl versions before 1.1.19 always reported guard @@ -545,7 +541,7 @@ mod imp { } let mut stackptr = crate::ptr::null_mut::(); let mut size = 0; - assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackptr, &mut size), 0); + assert_eq!(libc::pthread_attr_getstack(attr.as_ptr(), &mut stackptr, &mut size), 0); let stackaddr = stackptr.addr(); ret = if cfg!(any(target_os = "freebsd", target_os = "netbsd", target_os = "hurd")) { @@ -566,7 +562,7 @@ mod imp { }; } if e == 0 || cfg!(target_os = "freebsd") { - assert_eq!(libc::pthread_attr_destroy(&mut attr), 0); + assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); } ret } From b94162078d43ee07277a8a746e4176588a7ab93b Mon Sep 17 00:00:00 2001 From: Kornel Date: Mon, 17 Feb 2025 17:05:21 +0000 Subject: [PATCH 20/29] Highlight thread_local! const init in docs --- library/std/src/thread/local.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/library/std/src/thread/local.rs b/library/std/src/thread/local.rs index ca04aa4ada49..d5a5d10205dd 100644 --- a/library/std/src/thread/local.rs +++ b/library/std/src/thread/local.rs @@ -50,7 +50,8 @@ use crate::fmt; /// use std::cell::Cell; /// use std::thread; /// -/// thread_local!(static FOO: Cell = Cell::new(1)); +/// // explicit `const {}` block enables more efficient initialization +/// thread_local!(static FOO: Cell = const { Cell::new(1) }); /// /// assert_eq!(FOO.get(), 1); /// FOO.set(2); @@ -138,7 +139,7 @@ impl fmt::Debug for LocalKey { /// use std::cell::{Cell, RefCell}; /// /// thread_local! { -/// pub static FOO: Cell = Cell::new(1); +/// pub static FOO: Cell = const { Cell::new(1) }; /// /// static BAR: RefCell> = RefCell::new(vec![1.0, 2.0]); /// } @@ -394,7 +395,7 @@ impl LocalKey> { /// use std::cell::Cell; /// /// thread_local! { - /// static X: Cell = Cell::new(1); + /// static X: Cell = const { Cell::new(1) }; /// } /// /// assert_eq!(X.get(), 1); @@ -423,7 +424,7 @@ impl LocalKey> { /// use std::cell::Cell; /// /// thread_local! { - /// static X: Cell> = Cell::new(Some(1)); + /// static X: Cell> = const { Cell::new(Some(1)) }; /// } /// /// assert_eq!(X.take(), Some(1)); @@ -453,7 +454,7 @@ impl LocalKey> { /// use std::cell::Cell; /// /// thread_local! { - /// static X: Cell = Cell::new(1); + /// static X: Cell = const { Cell::new(1) }; /// } /// /// assert_eq!(X.replace(2), 1); From ad566646cf02163373c5d60033be07c2d903ef90 Mon Sep 17 00:00:00 2001 From: Kornel Date: Mon, 17 Feb 2025 17:22:01 +0000 Subject: [PATCH 21/29] Use faster thread_local in current_thread_id() --- library/std/src/sync/mpmc/mod.rs | 3 +++ library/std/src/sync/mpmc/tests.rs | 14 ++++++++++++++ library/std/src/sync/mpmc/waker.rs | 2 +- 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 library/std/src/sync/mpmc/tests.rs diff --git a/library/std/src/sync/mpmc/mod.rs b/library/std/src/sync/mpmc/mod.rs index 8caa2dcfad99..8712332dd276 100644 --- a/library/std/src/sync/mpmc/mod.rs +++ b/library/std/src/sync/mpmc/mod.rs @@ -1382,3 +1382,6 @@ impl fmt::Debug for Receiver { f.pad("Receiver { .. }") } } + +#[cfg(test)] +mod tests; diff --git a/library/std/src/sync/mpmc/tests.rs b/library/std/src/sync/mpmc/tests.rs new file mode 100644 index 000000000000..6deb4dc2fe0c --- /dev/null +++ b/library/std/src/sync/mpmc/tests.rs @@ -0,0 +1,14 @@ +// Ensure that thread_local init with `const { 0 }` still has unique address at run-time +#[test] +fn waker_current_thread_id() { + let first = super::waker::current_thread_id(); + let t = crate::thread::spawn(move || { + let second = super::waker::current_thread_id(); + assert_ne!(first, second); + assert_eq!(second, super::waker::current_thread_id()); + }); + + assert_eq!(first, super::waker::current_thread_id()); + t.join().unwrap(); + assert_eq!(first, super::waker::current_thread_id()); +} diff --git a/library/std/src/sync/mpmc/waker.rs b/library/std/src/sync/mpmc/waker.rs index 1895466f95d4..f5e764e69bd6 100644 --- a/library/std/src/sync/mpmc/waker.rs +++ b/library/std/src/sync/mpmc/waker.rs @@ -204,6 +204,6 @@ impl Drop for SyncWaker { pub fn current_thread_id() -> usize { // `u8` is not drop so this variable will be available during thread destruction, // whereas `thread::current()` would not be - thread_local! { static DUMMY: u8 = 0 } + thread_local! { static DUMMY: u8 = const { 0 } } DUMMY.with(|x| (x as *const u8).addr()) } From 4742dbc765165dc0ece5e350b3527e697ff871dc Mon Sep 17 00:00:00 2001 From: Kornel Date: Mon, 17 Feb 2025 17:04:36 +0000 Subject: [PATCH 22/29] Use faster thread_local! for stdout --- library/std/src/io/stdio.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index 661c422811ab..017862c7f3aa 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -20,7 +20,7 @@ type LocalStream = Arc>>; thread_local! { /// Used by the test crate to capture the output of the print macros and panics. - static OUTPUT_CAPTURE: Cell> = { + static OUTPUT_CAPTURE: Cell> = const { Cell::new(None) } } From 12a0e2b4dd1e93d7f68c9bdaf4ada618c9cdfb38 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Fri, 21 Feb 2025 21:09:31 +0530 Subject: [PATCH 23/29] bootstrap: add doc for vendor build step --- src/bootstrap/src/core/build_steps/vendor.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/bootstrap/src/core/build_steps/vendor.rs b/src/bootstrap/src/core/build_steps/vendor.rs index 410dbc04f030..984c70955d7d 100644 --- a/src/bootstrap/src/core/build_steps/vendor.rs +++ b/src/bootstrap/src/core/build_steps/vendor.rs @@ -1,9 +1,14 @@ +//! Handles the vendoring process for the bootstrap system. +//! +//! This module ensures that all required Cargo dependencies are gathered +//! and stored in the `/` directory. use std::path::PathBuf; use crate::core::build_steps::tool::SUBMODULES_FOR_RUSTBOOK; use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::utils::exec::command; +/// The name of the directory where vendored dependencies are stored. pub const VENDOR_DIR: &str = "vendor"; /// Returns the cargo workspaces to vendor for `x vendor` and dist tarballs. @@ -29,11 +34,19 @@ pub fn default_paths_to_vendor(builder: &Builder<'_>) -> Vec<(PathBuf, Vec<&'sta .collect() } +/// Defines the vendoring step in the bootstrap process. +/// +/// This step executes `cargo vendor` to collect all dependencies +/// and store them in the `/` directory. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub(crate) struct Vendor { + /// Additional paths to synchronize during vendoring. pub(crate) sync_args: Vec, + /// Determines whether vendored dependencies use versioned directories. pub(crate) versioned_dirs: bool, + /// The root directory of the source code. pub(crate) root_dir: PathBuf, + /// The target directory for storing vendored dependencies. pub(crate) output_dir: PathBuf, } @@ -55,6 +68,10 @@ impl Step for Vendor { }); } + /// Executes the vendoring process. + /// + /// This function runs `cargo vendor` and ensures all required submodules + /// are initialized before vendoring begins. fn run(self, builder: &Builder<'_>) -> Self::Output { builder.info(&format!("Vendoring sources to {:?}", self.root_dir)); @@ -94,6 +111,7 @@ impl Step for Vendor { } } +/// Stores the result of the vendoring step. #[derive(Debug, Clone)] pub(crate) struct VendorOutput { pub(crate) config: String, From 46154c9b09b81ab02137f2ad1450d2d6277789ce Mon Sep 17 00:00:00 2001 From: Urgau Date: Tue, 18 Feb 2025 21:49:58 +0100 Subject: [PATCH 24/29] Filter elided lifetimes in HIR pretty printing --- compiler/rustc_ast_pretty/src/pprust/state.rs | 14 ++++++++----- compiler/rustc_hir_pretty/src/lib.rs | 21 ++++++++++++++++--- tests/ui/unpretty/debug-fmt-hir.stdout | 8 +++---- 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 0bf5de3ef898..44e956dc37f3 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -424,20 +424,23 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere self.ann_post(ident) } - fn strsep( + fn strsep<'x, T: 'x, F, I>( &mut self, sep: &'static str, space_before: bool, b: Breaks, - elts: &[T], + elts: I, mut op: F, ) where F: FnMut(&mut Self, &T), + I: IntoIterator, { + let mut it = elts.into_iter(); + self.rbox(0, b); - if let Some((first, rest)) = elts.split_first() { + if let Some(first) = it.next() { op(self, first); - for elt in rest { + for elt in it { if space_before { self.space(); } @@ -448,9 +451,10 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere self.end(); } - fn commasep(&mut self, b: Breaks, elts: &[T], op: F) + fn commasep<'x, T: 'x, F, I>(&mut self, b: Breaks, elts: I, op: F) where F: FnMut(&mut Self, &T), + I: IntoIterator, { self.strsep(",", false, b, elts, op) } diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 57df3127a025..566502a4896a 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -2284,7 +2284,9 @@ impl<'a> State<'a> { GenericBound::Use(args, _) => { self.word("use <"); - self.commasep(Inconsistent, args, |s, arg| s.print_precise_capturing_arg(*arg)); + self.commasep(Inconsistent, *args, |s, arg| { + s.print_precise_capturing_arg(*arg) + }); self.word(">"); } @@ -2300,10 +2302,23 @@ impl<'a> State<'a> { } fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) { - if !generic_params.is_empty() { + let is_lifetime_elided = |generic_param: &GenericParam<'_>| { + matches!( + generic_param.kind, + GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) } + ) + }; + + // We don't want to show elided lifetimes as they are compiler-inserted and not + // expressible in surface level Rust. + if !generic_params.is_empty() && !generic_params.iter().all(is_lifetime_elided) { self.word("<"); - self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param)); + self.commasep( + Inconsistent, + generic_params.iter().filter(|gp| !is_lifetime_elided(gp)), + |s, param| s.print_generic_param(param), + ); self.word(">"); } diff --git a/tests/ui/unpretty/debug-fmt-hir.stdout b/tests/ui/unpretty/debug-fmt-hir.stdout index 184c50942858..bd7a7c4463a9 100644 --- a/tests/ui/unpretty/debug-fmt-hir.stdout +++ b/tests/ui/unpretty/debug-fmt-hir.stdout @@ -13,13 +13,13 @@ struct Bar { } impl fmt::Debug for Bar { - fn fmt<'_, '_, '_>(self: &'_ Self, f: &'_ mut fmt::Formatter<'_>) + fn fmt(self: &'_ Self, f: &'_ mut fmt::Formatter<'_>) -> fmt::Result { debug_struct_field2_finish(f, "Bar", "a", &self.a, "b", &&self.b) } } -fn debug_struct_field2_finish<'a, '_, '_, - '_>(name: &'_ str, name1: &'_ str, value1: &'a dyn fmt::Debug, - name2: &'_ str, value2: &'a dyn fmt::Debug) -> fmt::Result { loop { } } +fn debug_struct_field2_finish<'a>(name: &'_ str, name1: &'_ str, + value1: &'a dyn fmt::Debug, name2: &'_ str, value2: &'a dyn fmt::Debug) + -> fmt::Result { loop { } } From d0e7bfd2056cffc7ea0e5f7ed577e987a627ba04 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sat, 22 Feb 2025 14:50:00 +0100 Subject: [PATCH 25/29] Render implicit self with their shorthand syntax in HIR pretty printing --- compiler/rustc_hir_pretty/src/lib.rs | 55 ++++++++++++++++++++------ tests/ui/unpretty/debug-fmt-hir.stdout | 2 +- tests/ui/unpretty/self-hir.rs | 14 +++++++ tests/ui/unpretty/self-hir.stdout | 18 +++++++++ 4 files changed, 75 insertions(+), 14 deletions(-) create mode 100644 tests/ui/unpretty/self-hir.rs create mode 100644 tests/ui/unpretty/self-hir.stdout diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 566502a4896a..56e268aea54d 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -18,7 +18,8 @@ use rustc_ast_pretty::pprust::state::MacHeader; use rustc_ast_pretty::pprust::{Comments, PrintState}; use rustc_hir::{ BindingMode, ByRef, ConstArgKind, GenericArg, GenericBound, GenericParam, GenericParamKind, - HirId, LifetimeParamKind, Node, PatKind, PreciseCapturingArg, RangeEnd, Term, TyPatKind, + HirId, ImplicitSelfKind, LifetimeParamKind, Node, PatKind, PreciseCapturingArg, RangeEnd, Term, + TyPatKind, }; use rustc_span::source_map::SourceMap; use rustc_span::{FileName, Ident, Span, Symbol, kw}; @@ -2086,6 +2087,28 @@ impl<'a> State<'a> { self.print_pat(arg.pat); } + fn print_implicit_self(&mut self, implicit_self_kind: &hir::ImplicitSelfKind) { + match implicit_self_kind { + ImplicitSelfKind::Imm => { + self.word("self"); + } + ImplicitSelfKind::Mut => { + self.print_mutability(hir::Mutability::Mut, false); + self.word("self"); + } + ImplicitSelfKind::RefImm => { + self.word("&"); + self.word("self"); + } + ImplicitSelfKind::RefMut => { + self.word("&"); + self.print_mutability(hir::Mutability::Mut, false); + self.word("self"); + } + ImplicitSelfKind::None => unreachable!(), + } + } + fn print_arm(&mut self, arm: &hir::Arm<'_>) { // I have no idea why this check is necessary, but here it // is :( @@ -2151,27 +2174,33 @@ impl<'a> State<'a> { // Make sure we aren't supplied *both* `arg_names` and `body_id`. assert!(arg_names.is_empty() || body_id.is_none()); let mut i = 0; - let mut print_arg = |s: &mut Self| { - if let Some(arg_name) = arg_names.get(i) { - s.word(arg_name.to_string()); - s.word(":"); - s.space(); - } else if let Some(body_id) = body_id { - s.ann.nested(s, Nested::BodyParamPat(body_id, i)); - s.word(":"); - s.space(); + let mut print_arg = |s: &mut Self, ty: Option<&hir::Ty<'_>>| { + if i == 0 && decl.implicit_self.has_implicit_self() { + s.print_implicit_self(&decl.implicit_self); + } else { + if let Some(arg_name) = arg_names.get(i) { + s.word(arg_name.to_string()); + s.word(":"); + s.space(); + } else if let Some(body_id) = body_id { + s.ann.nested(s, Nested::BodyParamPat(body_id, i)); + s.word(":"); + s.space(); + } + if let Some(ty) = ty { + s.print_type(ty); + } } i += 1; }; self.commasep(Inconsistent, decl.inputs, |s, ty| { s.ibox(INDENT_UNIT); - print_arg(s); - s.print_type(ty); + print_arg(s, Some(ty)); s.end(); }); if decl.c_variadic { self.word(", "); - print_arg(self); + print_arg(self, None); self.word("..."); } self.pclose(); diff --git a/tests/ui/unpretty/debug-fmt-hir.stdout b/tests/ui/unpretty/debug-fmt-hir.stdout index bd7a7c4463a9..2c9c96de9d14 100644 --- a/tests/ui/unpretty/debug-fmt-hir.stdout +++ b/tests/ui/unpretty/debug-fmt-hir.stdout @@ -13,7 +13,7 @@ struct Bar { } impl fmt::Debug for Bar { - fn fmt(self: &'_ Self, f: &'_ mut fmt::Formatter<'_>) + fn fmt(&self, f: &'_ mut fmt::Formatter<'_>) -> fmt::Result { debug_struct_field2_finish(f, "Bar", "a", &self.a, "b", &&self.b) diff --git a/tests/ui/unpretty/self-hir.rs b/tests/ui/unpretty/self-hir.rs new file mode 100644 index 000000000000..448d828d4446 --- /dev/null +++ b/tests/ui/unpretty/self-hir.rs @@ -0,0 +1,14 @@ +//@ compile-flags: -Zunpretty=hir +//@ check-pass + +pub struct Bar { + a: String, + b: u8, +} + +impl Bar { + fn imm_self(self) {} + fn mut_self(mut self) {} + fn refimm_self(&self) {} + fn refmut_self(&mut self) {} +} diff --git a/tests/ui/unpretty/self-hir.stdout b/tests/ui/unpretty/self-hir.stdout new file mode 100644 index 000000000000..4da080dc611e --- /dev/null +++ b/tests/ui/unpretty/self-hir.stdout @@ -0,0 +1,18 @@ +#[prelude_import] +use ::std::prelude::rust_2015::*; +#[macro_use] +extern crate std; +//@ compile-flags: -Zunpretty=hir +//@ check-pass + +struct Bar { + a: String, + b: u8, +} + +impl Bar { + fn imm_self(self) { } + fn mut_self(mut self) { } + fn refimm_self(&self) { } + fn refmut_self(&mut self) { } +} From a8f8b8de66025e254cbed08a53d5084162605d98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sat, 22 Feb 2025 18:29:12 +0000 Subject: [PATCH 26/29] Fix "missing match arm body" suggestion involving `!` Include the match arm guard in the gated span, so that the suggestion to add a body is correct instead of inserting the body before the guard. Make the suggestion verbose. ``` error: `match` arm with no body --> $DIR/feature-gate-never_patterns.rs:43:9 | LL | Some(_) if false, | ^^^^^^^^^^^^^^^^ | help: add a body after the pattern | LL | Some(_) if false => { todo!() }, | ++++++++++++++ ``` --- compiler/rustc_ast_passes/src/errors.rs | 9 ++- compiler/rustc_parse/src/parser/expr.rs | 3 +- .../feature-gate-never_patterns.stderr | 35 ++++++++++-- .../macro/macro-expand-to-match-arm.stderr | 7 ++- tests/ui/parser/match-arm-without-body.stderr | 56 ++++++++++++++++--- 5 files changed, 94 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 0eb2043eaa35..6eb9bb1c0daf 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -804,7 +804,14 @@ pub(crate) struct NegativeBoundWithParentheticalNotation { pub(crate) struct MatchArmWithNoBody { #[primary_span] pub span: Span, - #[suggestion(code = " => todo!(),", applicability = "has-placeholders")] + // We include the braces around `todo!()` so that a comma is optional, and we don't have to have + // any logic looking at the arm being replaced if there was a comma already or not for the + // resulting code to be correct. + #[suggestion( + code = " => {{ todo!() }}", + applicability = "has-placeholders", + style = "verbose" + )] pub suggestion: Span, } diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index e0e6c2177da5..b2e58c942806 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -3125,10 +3125,11 @@ impl<'a> Parser<'a> { let mut result = if armless { // A pattern without a body, allowed for never patterns. arm_body = None; + let span = lo.to(this.prev_token.span); this.expect_one_of(&[exp!(Comma)], &[exp!(CloseBrace)]).map(|x| { // Don't gate twice if !pat.contains_never_pattern() { - this.psess.gated_spans.gate(sym::never_patterns, pat.span); + this.psess.gated_spans.gate(sym::never_patterns, span); } x }) diff --git a/tests/ui/feature-gates/feature-gate-never_patterns.stderr b/tests/ui/feature-gates/feature-gate-never_patterns.stderr index dcd5db56da88..473e263c7965 100644 --- a/tests/ui/feature-gates/feature-gate-never_patterns.stderr +++ b/tests/ui/feature-gates/feature-gate-never_patterns.stderr @@ -58,19 +58,34 @@ error: `match` arm with no body --> $DIR/feature-gate-never_patterns.rs:38:9 | LL | Some(_) - | ^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^ + | +help: add a body after the pattern + | +LL | Some(_) => { todo!() } + | ++++++++++++++ error: `match` arm with no body --> $DIR/feature-gate-never_patterns.rs:43:9 | LL | Some(_) if false, - | ^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^^^^^^^^^^ + | +help: add a body after the pattern + | +LL | Some(_) if false => { todo!() }, + | ++++++++++++++ error: `match` arm with no body --> $DIR/feature-gate-never_patterns.rs:45:9 | LL | Some(_) if false - | ^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^^^^^^^^^^ + | +help: add a body after the pattern + | +LL | Some(_) if false => { todo!() } + | ++++++++++++++ error[E0658]: `!` patterns are experimental --> $DIR/feature-gate-never_patterns.rs:50:13 @@ -96,13 +111,23 @@ error: `match` arm with no body --> $DIR/feature-gate-never_patterns.rs:64:9 | LL | Some(_) - | ^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^ + | +help: add a body after the pattern + | +LL | Some(_) => { todo!() } + | ++++++++++++++ error: `match` arm with no body --> $DIR/feature-gate-never_patterns.rs:70:9 | LL | Some(_) if false - | ^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^^^^^^^^^^ + | +help: add a body after the pattern + | +LL | Some(_) if false => { todo!() } + | ++++++++++++++ error: a guard on a never pattern will never be run --> $DIR/feature-gate-never_patterns.rs:54:19 diff --git a/tests/ui/parser/macro/macro-expand-to-match-arm.stderr b/tests/ui/parser/macro/macro-expand-to-match-arm.stderr index 1927d80fd724..702e76d59f98 100644 --- a/tests/ui/parser/macro/macro-expand-to-match-arm.stderr +++ b/tests/ui/parser/macro/macro-expand-to-match-arm.stderr @@ -14,7 +14,12 @@ error: `match` arm with no body --> $DIR/macro-expand-to-match-arm.rs:14:9 | LL | arm!(None => {}), - | ^^^^^^^^^^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^^^^^^^^^^ + | +help: add a body after the pattern + | +LL | arm!(None => {}) => { todo!() }, + | ++++++++++++++ error: aborting due to 2 previous errors diff --git a/tests/ui/parser/match-arm-without-body.stderr b/tests/ui/parser/match-arm-without-body.stderr index 9df8485972f3..a65875b787a3 100644 --- a/tests/ui/parser/match-arm-without-body.stderr +++ b/tests/ui/parser/match-arm-without-body.stderr @@ -68,49 +68,89 @@ error: `match` arm with no body --> $DIR/match-arm-without-body.rs:7:9 | LL | Some(_) - | ^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^ + | +help: add a body after the pattern + | +LL | Some(_) => { todo!() } + | ++++++++++++++ error: `match` arm with no body --> $DIR/match-arm-without-body.rs:30:9 | LL | Some(_) if true - | ^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^^^^^^^^^ + | +help: add a body after the pattern + | +LL | Some(_) if true => { todo!() } + | ++++++++++++++ error: `match` arm with no body --> $DIR/match-arm-without-body.rs:40:9 | LL | Some(_) if true, - | ^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^^^^^^^^^ + | +help: add a body after the pattern + | +LL | Some(_) if true => { todo!() }, + | ++++++++++++++ error: `match` arm with no body --> $DIR/match-arm-without-body.rs:45:9 | LL | Some(_) if true, - | ^^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^^^^^^^^^ + | +help: add a body after the pattern + | +LL | Some(_) if true => { todo!() }, + | ++++++++++++++ error: `match` arm with no body --> $DIR/match-arm-without-body.rs:51:9 | LL | pat!() - | ^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^ + | +help: add a body after the pattern + | +LL | pat!() => { todo!() } + | ++++++++++++++ error: `match` arm with no body --> $DIR/match-arm-without-body.rs:56:9 | LL | pat!(), - | ^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^ + | +help: add a body after the pattern + | +LL | pat!() => { todo!() }, + | ++++++++++++++ error: `match` arm with no body --> $DIR/match-arm-without-body.rs:61:9 | LL | pat!() if true, - | ^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^^^^^^^^^ + | +help: add a body after the pattern + | +LL | pat!() if true => { todo!() }, + | ++++++++++++++ error: `match` arm with no body --> $DIR/match-arm-without-body.rs:72:9 | LL | pat!(), - | ^^^^^^- help: add a body after the pattern: `=> todo!(),` + | ^^^^^^ + | +help: add a body after the pattern + | +LL | pat!() => { todo!() }, + | ++++++++++++++ error: aborting due to 13 previous errors From 12e3911d81034864314503b9c2d9fba2773c7904 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 20 Feb 2025 18:58:46 +0000 Subject: [PATCH 27/29] Greatly simplify lifetime captures in edition 2024 --- compiler/rustc_abi/src/lib.rs | 2 +- compiler/rustc_ast_lowering/src/lib.rs | 17 ++++++------ .../src/attributes/allow_unstable.rs | 24 ++++++++--------- .../src/diagnostics/conflict_errors.rs | 7 +++-- .../rustc_borrowck/src/member_constraints.rs | 7 ++--- .../src/polonius/loan_liveness.rs | 2 +- .../rustc_borrowck/src/region_infer/mod.rs | 10 +++---- .../src/region_infer/reverse_sccs.rs | 5 +--- .../rustc_borrowck/src/region_infer/values.rs | 24 +++++++---------- .../src/type_check/free_region_relations.rs | 2 +- .../src/type_check/liveness/local_use_map.rs | 8 +++--- .../rustc_borrowck/src/universal_regions.rs | 8 +++--- .../rustc_const_eval/src/interpret/intern.rs | 4 +-- .../src/graph/implementation/mod.rs | 8 +++--- .../src/graph/scc/mod.rs | 2 +- .../src/sorted_map/index_map.rs | 4 +-- compiler/rustc_data_structures/src/sso/map.rs | 2 +- compiler/rustc_data_structures/src/sso/set.rs | 2 +- .../rustc_data_structures/src/sync/vec.rs | 4 +-- .../src/transitive_relation.rs | 2 +- compiler/rustc_expand/src/proc_macro.rs | 2 +- compiler/rustc_hir/src/definitions.rs | 2 +- compiler/rustc_hir/src/lang_items.rs | 2 +- compiler/rustc_hir_analysis/src/collect.rs | 5 ++-- .../src/collect/resolve_bound_vars.rs | 7 ++--- compiler/rustc_index/src/bit_set.rs | 2 +- compiler/rustc_index/src/interval.rs | 4 +-- compiler/rustc_index/src/slice.rs | 6 ++--- compiler/rustc_index/src/vec.rs | 4 +-- .../src/infer/canonical/query_response.rs | 13 +++++----- .../rustc_infer/src/infer/free_regions.rs | 2 +- compiler/rustc_infer/src/infer/mod.rs | 7 ++--- .../rustc_infer/src/infer/outlives/mod.rs | 2 +- compiler/rustc_lexer/src/lib.rs | 2 +- compiler/rustc_lint/src/context.rs | 4 +-- compiler/rustc_metadata/src/rmeta/decoder.rs | 26 ++++++++----------- compiler/rustc_middle/src/hir/map.rs | 13 ++++------ compiler/rustc_middle/src/hir/mod.rs | 16 ++++++------ compiler/rustc_middle/src/hir/place.rs | 2 +- .../interpret/allocation/provenance_map.rs | 2 +- compiler/rustc_middle/src/mir/mod.rs | 9 +++---- compiler/rustc_middle/src/mir/pretty.rs | 2 +- compiler/rustc_middle/src/ty/adt.rs | 3 +-- compiler/rustc_middle/src/ty/closure.rs | 3 +-- compiler/rustc_middle/src/ty/context.rs | 8 +++--- compiler/rustc_middle/src/ty/generic_args.rs | 10 +++---- compiler/rustc_middle/src/ty/mod.rs | 9 +++---- compiler/rustc_middle/src/ty/predicate.rs | 13 ++++------ compiler/rustc_middle/src/ty/sty.rs | 5 ++-- compiler/rustc_middle/src/ty/trait_def.rs | 4 +-- .../rustc_middle/src/ty/typeck_results.rs | 2 +- .../src/builder/expr/as_place.rs | 6 ++--- compiler/rustc_mir_build/src/thir/cx/mod.rs | 6 ++--- .../rustc_mir_dataflow/src/move_paths/mod.rs | 2 +- compiler/rustc_mir_dataflow/src/un_derefer.rs | 2 +- .../rustc_mir_dataflow/src/value_analysis.rs | 6 +---- .../rustc_mir_transform/src/coverage/graph.rs | 3 +-- .../rustc_mir_transform/src/coverage/query.rs | 3 +-- .../rustc_mir_transform/src/coverage/spans.rs | 3 +-- .../rustc_mir_transform/src/jump_threading.rs | 4 +-- compiler/rustc_mir_transform/src/sroa.rs | 2 +- compiler/rustc_mir_transform/src/ssa.rs | 2 +- compiler/rustc_monomorphize/src/collector.rs | 2 +- compiler/rustc_parse/src/parser/mod.rs | 2 +- compiler/rustc_pattern_analysis/src/lib.rs | 10 +++---- .../rustc_pattern_analysis/src/pat_column.rs | 4 +-- compiler/rustc_pattern_analysis/src/rustc.rs | 26 ++++++++----------- .../rustc_pattern_analysis/src/usefulness.rs | 25 ++++++++---------- .../tests/common/mod.rs | 13 +++++----- .../src/dep_graph/serialized.rs | 2 +- compiler/rustc_session/src/parse.rs | 2 +- compiler/rustc_session/src/search_paths.rs | 11 ++++---- .../error_reporting/infer/need_type_info.rs | 2 +- .../src/solve/fulfill.rs | 4 +-- .../src/traits/fulfill.rs | 7 +++-- .../traits/specialize/specialization_graph.rs | 7 ++--- .../src/traits/vtable.rs | 2 +- compiler/rustc_ty_utils/src/implied_bounds.rs | 4 +-- .../rustc_ty_utils/src/layout/invariant.rs | 2 +- compiler/rustc_ty_utils/src/needs_drop.rs | 2 +- .../rustc_type_ir/src/search_graph/mod.rs | 2 +- compiler/stable_mir/src/mir/body.rs | 2 +- compiler/stable_mir/src/ty.rs | 2 +- .../diagnostics/match_check/pat_analysis.rs | 10 +++---- 84 files changed, 223 insertions(+), 294 deletions(-) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 34228912041d..879e4bf64a85 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -1345,7 +1345,7 @@ impl FieldsShape { /// Gets source indices of the fields by increasing offsets. #[inline] - pub fn index_by_increasing_offset(&self) -> impl ExactSizeIterator + '_ { + pub fn index_by_increasing_offset(&self) -> impl ExactSizeIterator { let mut inverse_small = [0u8; 64]; let mut inverse_big = IndexVec::new(); let use_small = self.count() <= inverse_small.len(); diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 1c777111896d..b865cbedbbb7 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -45,7 +45,6 @@ use std::sync::Arc; use rustc_ast::node_id::NodeMap; use rustc_ast::{self as ast, *}; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; @@ -1821,11 +1820,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.new_named_lifetime_with_res(new_id, ident, res) } - fn lower_generic_params_mut<'s>( - &'s mut self, - params: &'s [GenericParam], + fn lower_generic_params_mut( + &mut self, + params: &[GenericParam], source: hir::GenericParamSource, - ) -> impl Iterator> + Captures<'a> + Captures<'s> { + ) -> impl Iterator> { params.iter().map(move |param| self.lower_generic_param(param, source)) } @@ -1986,11 +1985,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx)) } - fn lower_param_bounds_mut<'s>( - &'s mut self, - bounds: &'s [GenericBound], + fn lower_param_bounds_mut( + &mut self, + bounds: &[GenericBound], itctx: ImplTraitContext, - ) -> impl Iterator> + Captures<'s> + Captures<'a> { + ) -> impl Iterator> { bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx)) } diff --git a/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs b/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs index 471168ed4f56..13d246b08a8f 100644 --- a/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs +++ b/compiler/rustc_attr_parsing/src/attributes/allow_unstable.rs @@ -4,25 +4,25 @@ use rustc_span::{Symbol, sym}; use crate::session_diagnostics; -pub fn allow_internal_unstable<'a>( - sess: &'a Session, - attrs: &'a [impl AttributeExt], -) -> impl Iterator + 'a { +pub fn allow_internal_unstable( + sess: &Session, + attrs: &[impl AttributeExt], +) -> impl Iterator { allow_unstable(sess, attrs, sym::allow_internal_unstable) } -pub fn rustc_allow_const_fn_unstable<'a>( - sess: &'a Session, - attrs: &'a [impl AttributeExt], -) -> impl Iterator + 'a { +pub fn rustc_allow_const_fn_unstable( + sess: &Session, + attrs: &[impl AttributeExt], +) -> impl Iterator { allow_unstable(sess, attrs, sym::rustc_allow_const_fn_unstable) } -fn allow_unstable<'a>( - sess: &'a Session, - attrs: &'a [impl AttributeExt], +fn allow_unstable( + sess: &Session, + attrs: &[impl AttributeExt], symbol: Symbol, -) -> impl Iterator + 'a { +) -> impl Iterator { let attrs = filter_by_name(attrs, symbol); let list = attrs .filter_map(move |attr| { diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 94662070db40..f33f2ab58e05 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -8,7 +8,6 @@ use std::ops::ControlFlow; use either::Either; use hir::{ClosureKind, Path}; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::codes::*; use rustc_errors::{Applicability, Diag, MultiSpan, struct_span_code_err}; @@ -3530,10 +3529,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { location: Location, mpi: MovePathIndex, ) -> (Vec, Vec) { - fn predecessor_locations<'a, 'tcx>( - body: &'a mir::Body<'tcx>, + fn predecessor_locations<'tcx>( + body: &mir::Body<'tcx>, location: Location, - ) -> impl Iterator + Captures<'tcx> + 'a { + ) -> impl Iterator { if location.statement_index == 0 { let predecessors = body.basic_blocks.predecessors()[location.block].to_vec(); Either::Left(predecessors.into_iter().map(move |bb| body.terminator_loc(bb))) diff --git a/compiler/rustc_borrowck/src/member_constraints.rs b/compiler/rustc_borrowck/src/member_constraints.rs index a0adf471fd31..bdd0f6fe11e0 100644 --- a/compiler/rustc_borrowck/src/member_constraints.rs +++ b/compiler/rustc_borrowck/src/member_constraints.rs @@ -1,7 +1,6 @@ use std::hash::Hash; use std::ops::Index; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexMap; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::ty::{self, Ty}; @@ -147,9 +146,7 @@ impl<'tcx, R> MemberConstraintSet<'tcx, R> where R: Copy + Hash + Eq, { - pub(crate) fn all_indices( - &self, - ) -> impl Iterator + Captures<'tcx> + '_ { + pub(crate) fn all_indices(&self) -> impl Iterator { self.constraints.indices() } @@ -159,7 +156,7 @@ where pub(crate) fn indices( &self, member_region_vid: R, - ) -> impl Iterator + Captures<'tcx> + '_ { + ) -> impl Iterator { let mut next = self.first_constraints.get(&member_region_vid).cloned(); std::iter::from_fn(move || -> Option { if let Some(current) = next { diff --git a/compiler/rustc_borrowck/src/polonius/loan_liveness.rs b/compiler/rustc_borrowck/src/polonius/loan_liveness.rs index 768c12a97a64..5cd265e0db92 100644 --- a/compiler/rustc_borrowck/src/polonius/loan_liveness.rs +++ b/compiler/rustc_borrowck/src/polonius/loan_liveness.rs @@ -175,7 +175,7 @@ impl LocalizedConstraintGraph { } /// Returns the outgoing edges of a given node, not its transitive closure. - fn outgoing_edges(&self, node: LocalizedNode) -> impl Iterator + use<'_> { + fn outgoing_edges(&self, node: LocalizedNode) -> impl Iterator { // The outgoing edges are: // - the physical edges present at this node, // - the materialized logical edges that exist virtually at all points for this node's diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index e0e3e028c612..a00fce08c9ba 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -576,9 +576,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { } /// Returns an iterator over all the outlives constraints. - pub(crate) fn outlives_constraints( - &self, - ) -> impl Iterator> + '_ { + pub(crate) fn outlives_constraints(&self) -> impl Iterator> { self.constraints.outlives().iter().copied() } @@ -615,10 +613,10 @@ impl<'tcx> RegionInferenceContext<'tcx> { self.scc_values.region_value_str(scc) } - pub(crate) fn placeholders_contained_in<'a>( - &'a self, + pub(crate) fn placeholders_contained_in( + &self, r: RegionVid, - ) -> impl Iterator + 'a { + ) -> impl Iterator { let scc = self.constraint_sccs.scc(r); self.scc_values.placeholders_contained_in(scc) } diff --git a/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs b/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs index d0cfe572d087..b2ed8a358279 100644 --- a/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs +++ b/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs @@ -20,10 +20,7 @@ pub(crate) struct ReverseSccGraph { impl ReverseSccGraph { /// Find all universal regions that are required to outlive the given SCC. - pub(super) fn upper_bounds<'a>( - &'a self, - scc0: ConstraintSccIndex, - ) -> impl Iterator + 'a { + pub(super) fn upper_bounds(&self, scc0: ConstraintSccIndex) -> impl Iterator { let mut duplicates = FxIndexSet::default(); graph::depth_first_search(&self.graph, scc0) .flat_map(move |scc1| { diff --git a/compiler/rustc_borrowck/src/region_infer/values.rs b/compiler/rustc_borrowck/src/region_infer/values.rs index f1bcb353dc61..d9ac5b5cb132 100644 --- a/compiler/rustc_borrowck/src/region_infer/values.rs +++ b/compiler/rustc_borrowck/src/region_infer/values.rs @@ -88,7 +88,7 @@ impl LivenessValues { } /// Iterate through each region that has a value in this set. - pub(crate) fn regions(&self) -> impl Iterator + '_ { + pub(crate) fn regions(&self) -> impl Iterator { self.points.as_ref().expect("use with_specific_points").rows() } @@ -96,7 +96,7 @@ impl LivenessValues { // We are passing query instability implications to the caller. #[rustc_lint_query_instability] #[allow(rustc::potential_query_instability)] - pub(crate) fn live_regions_unordered(&self) -> impl Iterator + '_ { + pub(crate) fn live_regions_unordered(&self) -> impl Iterator { self.live_regions.as_ref().unwrap().iter().copied() } @@ -143,7 +143,7 @@ impl LivenessValues { } /// Returns an iterator of all the points where `region` is live. - fn live_points(&self, region: RegionVid) -> impl Iterator + '_ { + fn live_points(&self, region: RegionVid) -> impl Iterator { let Some(points) = &self.points else { unreachable!( "Should be using LivenessValues::with_specific_points to ask whether live at a location" @@ -340,7 +340,7 @@ impl RegionValues { } /// Returns the locations contained within a given region `r`. - pub(crate) fn locations_outlived_by<'a>(&'a self, r: N) -> impl Iterator + 'a { + pub(crate) fn locations_outlived_by(&self, r: N) -> impl Iterator { self.points.row(r).into_iter().flat_map(move |set| { set.iter() .take_while(move |&p| self.location_map.point_in_range(p)) @@ -349,18 +349,15 @@ impl RegionValues { } /// Returns just the universal regions that are contained in a given region's value. - pub(crate) fn universal_regions_outlived_by<'a>( - &'a self, - r: N, - ) -> impl Iterator + 'a { + pub(crate) fn universal_regions_outlived_by(&self, r: N) -> impl Iterator { self.free_regions.row(r).into_iter().flat_map(|set| set.iter()) } /// Returns all the elements contained in a given region's value. - pub(crate) fn placeholders_contained_in<'a>( - &'a self, + pub(crate) fn placeholders_contained_in( + &self, r: N, - ) -> impl Iterator + 'a { + ) -> impl Iterator { self.placeholders .row(r) .into_iter() @@ -369,10 +366,7 @@ impl RegionValues { } /// Returns all the elements contained in a given region's value. - pub(crate) fn elements_contained_in<'a>( - &'a self, - r: N, - ) -> impl Iterator + 'a { + pub(crate) fn elements_contained_in(&self, r: N) -> impl Iterator { let points_iter = self.locations_outlived_by(r).map(RegionElement::Location); let free_regions_iter = diff --git a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs index efbae1e15353..eaac633b512d 100644 --- a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs +++ b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs @@ -172,7 +172,7 @@ impl UniversalRegionRelations<'_> { } /// Returns the _non-transitive_ set of known `outlives` constraints between free regions. - pub(crate) fn known_outlives(&self) -> impl Iterator + '_ { + pub(crate) fn known_outlives(&self) -> impl Iterator { self.outlives.base_edges() } } diff --git a/compiler/rustc_borrowck/src/type_check/liveness/local_use_map.rs b/compiler/rustc_borrowck/src/type_check/liveness/local_use_map.rs index 6182b68f6f41..9591da83708b 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/local_use_map.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/local_use_map.rs @@ -54,7 +54,7 @@ rustc_index::newtype_index! { fn appearances_iter( first: Option, appearances: &Appearances, -) -> impl Iterator + '_ { +) -> impl Iterator { AppearancesIter { appearances, current: first } } @@ -107,17 +107,17 @@ impl LocalUseMap { local_use_map } - pub(crate) fn defs(&self, local: Local) -> impl Iterator + '_ { + pub(crate) fn defs(&self, local: Local) -> impl Iterator { appearances_iter(self.first_def_at[local], &self.appearances) .map(move |aa| self.appearances[aa].point_index) } - pub(crate) fn uses(&self, local: Local) -> impl Iterator + '_ { + pub(crate) fn uses(&self, local: Local) -> impl Iterator { appearances_iter(self.first_use_at[local], &self.appearances) .map(move |aa| self.appearances[aa].point_index) } - pub(crate) fn drops(&self, local: Local) -> impl Iterator + '_ { + pub(crate) fn drops(&self, local: Local) -> impl Iterator { appearances_iter(self.first_drop_at[local], &self.appearances) .map(move |aa| self.appearances[aa].point_index) } diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index c578eb4dc458..b39ead66e95c 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -308,7 +308,7 @@ impl<'tcx> UniversalRegions<'tcx> { /// Returns an iterator over all the RegionVids corresponding to /// universally quantified free regions. - pub(crate) fn universal_regions_iter(&self) -> impl Iterator + use<> { + pub(crate) fn universal_regions_iter(&self) -> impl Iterator + 'static { (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize) } @@ -332,9 +332,9 @@ impl<'tcx> UniversalRegions<'tcx> { } /// Gets an iterator over all the early-bound regions that have names. - pub(crate) fn named_universal_regions_iter<'s>( - &'s self, - ) -> impl Iterator, ty::RegionVid)> + 's { + pub(crate) fn named_universal_regions_iter( + &self, + ) -> impl Iterator, ty::RegionVid)> { self.indices.indices.iter().map(|(&r, &v)| (r, v)) } diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index e14cc1dad363..43631330f89b 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -61,8 +61,8 @@ impl HasStaticRootDefId for const_eval::CompileTimeMachine<'_> { /// already mutable (as a sanity check). /// /// Returns an iterator over all relocations referred to by this allocation. -fn intern_shallow<'rt, 'tcx, T, M: CompileTimeMachine<'tcx, T>>( - ecx: &'rt mut InterpCx<'tcx, M>, +fn intern_shallow<'tcx, T, M: CompileTimeMachine<'tcx, T>>( + ecx: &mut InterpCx<'tcx, M>, alloc_id: AllocId, mutability: Mutability, ) -> Result + 'tcx, ()> { diff --git a/compiler/rustc_data_structures/src/graph/implementation/mod.rs b/compiler/rustc_data_structures/src/graph/implementation/mod.rs index 7724e9347d82..a80365938b96 100644 --- a/compiler/rustc_data_structures/src/graph/implementation/mod.rs +++ b/compiler/rustc_data_structures/src/graph/implementation/mod.rs @@ -193,11 +193,11 @@ impl Graph { AdjacentEdges { graph: self, direction, next: first_edge } } - pub fn successor_nodes(&self, source: NodeIndex) -> impl Iterator + '_ { + pub fn successor_nodes(&self, source: NodeIndex) -> impl Iterator { self.outgoing_edges(source).targets() } - pub fn predecessor_nodes(&self, target: NodeIndex) -> impl Iterator + '_ { + pub fn predecessor_nodes(&self, target: NodeIndex) -> impl Iterator { self.incoming_edges(target).sources() } @@ -255,11 +255,11 @@ pub struct AdjacentEdges<'g, N, E> { } impl<'g, N: Debug, E: Debug> AdjacentEdges<'g, N, E> { - fn targets(self) -> impl Iterator + 'g { + fn targets(self) -> impl Iterator { self.map(|(_, edge)| edge.target) } - fn sources(self) -> impl Iterator + 'g { + fn sources(self) -> impl Iterator { self.map(|(_, edge)| edge.source) } } diff --git a/compiler/rustc_data_structures/src/graph/scc/mod.rs b/compiler/rustc_data_structures/src/graph/scc/mod.rs index 2241b538738c..e7c4ea3daae4 100644 --- a/compiler/rustc_data_structures/src/graph/scc/mod.rs +++ b/compiler/rustc_data_structures/src/graph/scc/mod.rs @@ -133,7 +133,7 @@ impl Sccs { /// meaning that if `S1 -> S2`, we will visit `S2` first and `S1` after. /// This is convenient when the edges represent dependencies: when you visit /// `S1`, the value for `S2` will already have been computed. - pub fn all_sccs(&self) -> impl Iterator + use { + pub fn all_sccs(&self) -> impl Iterator + 'static { (0..self.scc_data.len()).map(S::new) } diff --git a/compiler/rustc_data_structures/src/sorted_map/index_map.rs b/compiler/rustc_data_structures/src/sorted_map/index_map.rs index e9a5fb519754..1654867739f0 100644 --- a/compiler/rustc_data_structures/src/sorted_map/index_map.rs +++ b/compiler/rustc_data_structures/src/sorted_map/index_map.rs @@ -84,7 +84,7 @@ impl SortedIndexMultiMap { /// If there are multiple items that are equivalent to `key`, they will be yielded in /// insertion order. #[inline] - pub fn get_by_key(&self, key: K) -> impl Iterator + '_ { + pub fn get_by_key(&self, key: K) -> impl Iterator { self.get_by_key_enumerated(key).map(|(_, v)| v) } @@ -94,7 +94,7 @@ impl SortedIndexMultiMap { /// If there are multiple items that are equivalent to `key`, they will be yielded in /// insertion order. #[inline] - pub fn get_by_key_enumerated(&self, key: K) -> impl Iterator + '_ { + pub fn get_by_key_enumerated(&self, key: K) -> impl Iterator { let lower_bound = self.idx_sorted_by_item_key.partition_point(|&i| self.items[i].0 < key); self.idx_sorted_by_item_key[lower_bound..].iter().map_while(move |&i| { let (k, v) = &self.items[i]; diff --git a/compiler/rustc_data_structures/src/sso/map.rs b/compiler/rustc_data_structures/src/sso/map.rs index 3200249a2dc4..827c82fa46a1 100644 --- a/compiler/rustc_data_structures/src/sso/map.rs +++ b/compiler/rustc_data_structures/src/sso/map.rs @@ -165,7 +165,7 @@ impl SsoHashMap { /// Clears the map, returning all key-value pairs as an iterator. Keeps the /// allocated memory for reuse. - pub fn drain(&mut self) -> impl Iterator + '_ { + pub fn drain(&mut self) -> impl Iterator { match self { SsoHashMap::Array(array) => Either::Left(array.drain(..)), SsoHashMap::Map(map) => Either::Right(map.drain()), diff --git a/compiler/rustc_data_structures/src/sso/set.rs b/compiler/rustc_data_structures/src/sso/set.rs index a4b40138933d..e3fa1cbf4cc5 100644 --- a/compiler/rustc_data_structures/src/sso/set.rs +++ b/compiler/rustc_data_structures/src/sso/set.rs @@ -80,7 +80,7 @@ impl SsoHashSet { /// Clears the set, returning all elements in an iterator. #[inline] - pub fn drain(&mut self) -> impl Iterator + '_ { + pub fn drain(&mut self) -> impl Iterator { self.map.drain().map(entry_to_key) } } diff --git a/compiler/rustc_data_structures/src/sync/vec.rs b/compiler/rustc_data_structures/src/sync/vec.rs index 21ec5cf6c13b..afbb0cef9f95 100644 --- a/compiler/rustc_data_structures/src/sync/vec.rs +++ b/compiler/rustc_data_structures/src/sync/vec.rs @@ -45,14 +45,14 @@ impl AppendOnlyVec { self.vec.read().get(i).copied() } - pub fn iter_enumerated(&self) -> impl Iterator + '_ { + pub fn iter_enumerated(&self) -> impl Iterator { (0..) .map(|i| (i, self.get(i))) .take_while(|(_, o)| o.is_some()) .filter_map(|(i, o)| Some((i, o?))) } - pub fn iter(&self) -> impl Iterator + '_ { + pub fn iter(&self) -> impl Iterator { (0..).map(|i| self.get(i)).take_while(|o| o.is_some()).flatten() } } diff --git a/compiler/rustc_data_structures/src/transitive_relation.rs b/compiler/rustc_data_structures/src/transitive_relation.rs index e81ebb9a4be2..33ac279f3e0a 100644 --- a/compiler/rustc_data_structures/src/transitive_relation.rs +++ b/compiler/rustc_data_structures/src/transitive_relation.rs @@ -363,7 +363,7 @@ impl TransitiveRelation { /// Lists all the base edges in the graph: the initial _non-transitive_ set of element /// relations, which will be later used as the basis for the transitive closure computation. - pub fn base_edges(&self) -> impl Iterator + '_ { + pub fn base_edges(&self) -> impl Iterator { self.edges .iter() .map(move |edge| (self.elements[edge.source.0], self.elements[edge.target.0])) diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 814d2b04d8d0..a6cdeaee176f 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -31,7 +31,7 @@ impl pm::bridge::server::MessagePipe for MessagePipe { } } -fn exec_strategy(ecx: &ExtCtxt<'_>) -> impl pm::bridge::server::ExecutionStrategy + use<> { +fn exec_strategy(ecx: &ExtCtxt<'_>) -> impl pm::bridge::server::ExecutionStrategy + 'static { pm::bridge::server::MaybeCrossThread::>::new( ecx.sess.opts.unstable_opts.proc_macro_execution_strategy == ProcMacroExecutionStrategy::CrossThread, diff --git a/compiler/rustc_hir/src/definitions.rs b/compiler/rustc_hir/src/definitions.rs index 08a0a5225e74..c4c309e77e19 100644 --- a/compiler/rustc_hir/src/definitions.rs +++ b/compiler/rustc_hir/src/definitions.rs @@ -93,7 +93,7 @@ impl DefPathTable { pub fn enumerated_keys_and_path_hashes( &self, - ) -> impl Iterator + ExactSizeIterator + '_ { + ) -> impl Iterator + ExactSizeIterator { self.index_to_key .iter_enumerated() .map(move |(index, key)| (index, key, self.def_path_hash(index))) diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index 34c0837b25a5..f5626937ec45 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -60,7 +60,7 @@ impl LanguageItems { self.reverse_items.get(&def_id).copied() } - pub fn iter(&self) -> impl Iterator + '_ { + pub fn iter(&self) -> impl Iterator { self.items .iter() .enumerate() diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 5bb77c096dcf..1a89c9dedc52 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -20,7 +20,6 @@ use std::ops::Bound; use rustc_abi::ExternAbi; use rustc_ast::Recovered; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::unord::UnordMap; use rustc_errors::{ @@ -1690,10 +1689,10 @@ fn polarity_of_impl( /// the lifetimes that are declared. For fns or methods, we have to /// screen out those that do not appear in any where-clauses etc using /// `resolve_lifetime::early_bound_lifetimes`. -fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>( +fn early_bound_lifetimes_from_generics<'a, 'tcx>( tcx: TyCtxt<'tcx>, generics: &'a hir::Generics<'a>, -) -> impl Iterator> + Captures<'tcx> { +) -> impl Iterator> { generics.params.iter().filter(move |param| match param.kind { GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id), _ => false, diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index fee3c6088ede..efd65ba3cc40 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -160,7 +160,7 @@ enum Scope<'a> { impl<'a> Scope<'a> { // A helper for debugging scopes without printing parent scopes - fn debug_truncated(&'a self) -> impl fmt::Debug + 'a { + fn debug_truncated(&self) -> impl fmt::Debug { fmt::from_fn(move |f| match self { Self::Binder { bound_vars, scope_type, hir_id, where_bound_origin, s: _ } => f .debug_struct("Binder") @@ -2159,10 +2159,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { /// Walk the generics of the item for a trait bound whose self type /// corresponds to the expected res, and return the trait def id. - fn for_each_trait_bound_on_res( - &self, - expected_res: Res, - ) -> impl Iterator + use<'tcx, '_> { + fn for_each_trait_bound_on_res(&self, expected_res: Res) -> impl Iterator { std::iter::from_coroutine( #[coroutine] move || { diff --git a/compiler/rustc_index/src/bit_set.rs b/compiler/rustc_index/src/bit_set.rs index d7d90ea16e49..6dc044a6d380 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -1666,7 +1666,7 @@ impl SparseBitMatrix { /// Iterates through all the columns set to true in a given row of /// the matrix. - pub fn iter(&self, row: R) -> impl Iterator + '_ { + pub fn iter(&self, row: R) -> impl Iterator { self.row(row).into_iter().flat_map(|r| r.iter()) } diff --git a/compiler/rustc_index/src/interval.rs b/compiler/rustc_index/src/interval.rs index a3d87f59567f..0225c5c4f329 100644 --- a/compiler/rustc_index/src/interval.rs +++ b/compiler/rustc_index/src/interval.rs @@ -51,7 +51,7 @@ impl IntervalSet { self.map.clear(); } - pub fn iter(&self) -> impl Iterator + '_ + pub fn iter(&self) -> impl Iterator where I: Step, { @@ -59,7 +59,7 @@ impl IntervalSet { } /// Iterates through intervals stored in the set, in order. - pub fn iter_intervals(&self) -> impl Iterator> + '_ + pub fn iter_intervals(&self) -> impl Iterator> where I: Step, { diff --git a/compiler/rustc_index/src/slice.rs b/compiler/rustc_index/src/slice.rs index 956d32c9a694..4636f294f13b 100644 --- a/compiler/rustc_index/src/slice.rs +++ b/compiler/rustc_index/src/slice.rs @@ -63,9 +63,7 @@ impl IndexSlice { } #[inline] - pub fn iter_enumerated( - &self, - ) -> impl DoubleEndedIterator + ExactSizeIterator + '_ { + pub fn iter_enumerated(&self) -> impl DoubleEndedIterator + ExactSizeIterator { self.raw.iter().enumerate().map(|(n, t)| (I::new(n), t)) } @@ -84,7 +82,7 @@ impl IndexSlice { #[inline] pub fn iter_enumerated_mut( &mut self, - ) -> impl DoubleEndedIterator + ExactSizeIterator + '_ { + ) -> impl DoubleEndedIterator + ExactSizeIterator { self.raw.iter_mut().enumerate().map(|(n, t)| (I::new(n), t)) } diff --git a/compiler/rustc_index/src/vec.rs b/compiler/rustc_index/src/vec.rs index 1cb8bc861af9..7f3f3ead5f2a 100644 --- a/compiler/rustc_index/src/vec.rs +++ b/compiler/rustc_index/src/vec.rs @@ -132,7 +132,7 @@ impl IndexVec { } #[inline] - pub fn drain>(&mut self, range: R) -> impl Iterator + '_ { + pub fn drain>(&mut self, range: R) -> impl Iterator { self.raw.drain(range) } @@ -140,7 +140,7 @@ impl IndexVec { pub fn drain_enumerated>( &mut self, range: R, - ) -> impl Iterator + '_ { + ) -> impl Iterator { let begin = match range.start_bound() { std::ops::Bound::Included(i) => *i, std::ops::Bound::Excluded(i) => i.checked_add(1).unwrap(), diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index 23f63af778d0..8a61631c69c0 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -10,7 +10,6 @@ use std::fmt::Debug; use std::iter; -use rustc_data_structures::captures::Captures; use rustc_index::{Idx, IndexVec}; use rustc_middle::arena::ArenaAllocatable; use rustc_middle::mir::ConstraintCategory; @@ -541,13 +540,13 @@ impl<'tcx> InferCtxt<'tcx> { /// Converts the region constraints resulting from a query into an /// iterator of obligations. - fn query_outlives_constraints_into_obligations<'a>( - &'a self, - cause: &'a ObligationCause<'tcx>, + fn query_outlives_constraints_into_obligations( + &self, + cause: &ObligationCause<'tcx>, param_env: ty::ParamEnv<'tcx>, - uninstantiated_region_constraints: &'a [QueryOutlivesConstraint<'tcx>], - result_args: &'a CanonicalVarValues<'tcx>, - ) -> impl Iterator> + 'a + Captures<'tcx> { + uninstantiated_region_constraints: &[QueryOutlivesConstraint<'tcx>], + result_args: &CanonicalVarValues<'tcx>, + ) -> impl Iterator> { uninstantiated_region_constraints.iter().map(move |&constraint| { let predicate = instantiate_value(self.tcx, result_args, constraint); self.query_outlives_constraint_to_obligation(predicate, cause.clone(), param_env) diff --git a/compiler/rustc_infer/src/infer/free_regions.rs b/compiler/rustc_infer/src/infer/free_regions.rs index 5452ba67497b..8fa5361121c6 100644 --- a/compiler/rustc_infer/src/infer/free_regions.rs +++ b/compiler/rustc_infer/src/infer/free_regions.rs @@ -38,7 +38,7 @@ pub struct FreeRegionMap<'tcx> { } impl<'tcx> FreeRegionMap<'tcx> { - pub fn elements(&self) -> impl Iterator> + '_ { + pub fn elements(&self) -> impl Iterator> { self.relation.elements().copied() } diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index de49c246c155..537e8119adaf 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -15,7 +15,6 @@ use region_constraints::{ }; pub use relate::StructurallyRelateAliases; pub use relate::combine::PredicateEmittingRelation; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::undo_log::{Rollback, UndoLogs}; use rustc_data_structures::unify as ut; @@ -233,7 +232,7 @@ impl<'tcx> InferCtxtInner<'tcx> { // while looping through this. pub fn iter_opaque_types( &self, - ) -> impl Iterator, ty::OpaqueHiddenType<'tcx>)> + '_ { + ) -> impl Iterator, ty::OpaqueHiddenType<'tcx>)> { self.opaque_type_storage.opaque_types.iter().map(|(&k, &v)| (k, v)) } } @@ -1295,9 +1294,7 @@ impl<'tcx> InferCtxt<'tcx> { /// The returned function is used in a fast path. If it returns `true` the variable is /// unchanged, `false` indicates that the status is unknown. #[inline] - pub fn is_ty_infer_var_definitely_unchanged<'a>( - &'a self, - ) -> (impl Fn(TyOrConstInferVar) -> bool + Captures<'tcx> + 'a) { + pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar) -> bool { // This hoists the borrow/release out of the loop body. let inner = self.inner.try_borrow(); diff --git a/compiler/rustc_infer/src/infer/outlives/mod.rs b/compiler/rustc_infer/src/infer/outlives/mod.rs index 1afe50e336da..2a4544c1140d 100644 --- a/compiler/rustc_infer/src/infer/outlives/mod.rs +++ b/compiler/rustc_infer/src/infer/outlives/mod.rs @@ -20,7 +20,7 @@ pub(crate) mod verify; #[instrument(level = "debug", skip(param_env), ret)] pub fn explicit_outlives_bounds<'tcx>( param_env: ty::ParamEnv<'tcx>, -) -> impl Iterator> + 'tcx { +) -> impl Iterator> { param_env .caller_bounds() .into_iter() diff --git a/compiler/rustc_lexer/src/lib.rs b/compiler/rustc_lexer/src/lib.rs index c63ab77decac..bf18845a0830 100644 --- a/compiler/rustc_lexer/src/lib.rs +++ b/compiler/rustc_lexer/src/lib.rs @@ -291,7 +291,7 @@ pub fn validate_raw_str(input: &str, prefix_len: u32) -> Result<(), RawStrError> } /// Creates an iterator that produces tokens from the input string. -pub fn tokenize(input: &str) -> impl Iterator + '_ { +pub fn tokenize(input: &str) -> impl Iterator { let mut cursor = Cursor::new(input); std::iter::from_fn(move || { let token = cursor.advance_token(); diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index c74158102c7a..74663e6b4bbe 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -139,9 +139,7 @@ impl LintStore { &self.lints } - pub fn get_lint_groups<'t>( - &'t self, - ) -> impl Iterator, bool)> + 't { + pub fn get_lint_groups(&self) -> impl Iterator, bool)> { self.lint_groups .iter() .filter(|(_, LintGroup { depr, .. })| { diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index e8dcda875e67..0604892e34d5 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -8,7 +8,6 @@ use std::{io, iter, mem}; pub(super) use cstore_impl::provide; use proc_macro::bridge::client::ProcMacro; use rustc_ast as ast; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::owned_slice::OwnedSlice; @@ -963,14 +962,14 @@ impl CrateRoot { pub(crate) fn decode_crate_deps<'a>( &self, metadata: &'a MetadataBlob, - ) -> impl ExactSizeIterator + Captures<'a> { + ) -> impl ExactSizeIterator { self.crate_deps.decode(metadata) } pub(crate) fn decode_target_modifiers<'a>( &self, metadata: &'a MetadataBlob, - ) -> impl ExactSizeIterator + Captures<'a> { + ) -> impl ExactSizeIterator { self.target_modifiers.decode(metadata) } } @@ -1276,7 +1275,7 @@ impl<'a> CrateMetadataRef<'a> { self, id: DefIndex, sess: &'a Session, - ) -> impl Iterator + 'a { + ) -> impl Iterator { iter::from_coroutine( #[coroutine] move || { @@ -1326,10 +1325,7 @@ impl<'a> CrateMetadataRef<'a> { .is_some_and(|ident| ident.name == kw::SelfLower) } - fn get_associated_item_or_field_def_ids( - self, - id: DefIndex, - ) -> impl Iterator + 'a { + fn get_associated_item_or_field_def_ids(self, id: DefIndex) -> impl Iterator { self.root .tables .associated_item_or_field_def_ids @@ -1380,7 +1376,7 @@ impl<'a> CrateMetadataRef<'a> { self, id: DefIndex, sess: &'a Session, - ) -> impl Iterator + 'a { + ) -> impl Iterator { self.root .tables .attributes @@ -1417,12 +1413,12 @@ impl<'a> CrateMetadataRef<'a> { } /// Decodes all traits in the crate (for rustdoc and rustc diagnostics). - fn get_traits(self) -> impl Iterator + 'a { + fn get_traits(self) -> impl Iterator { self.root.traits.decode(self).map(move |index| self.local_def_id(index)) } /// Decodes all trait impls in the crate (for rustdoc). - fn get_trait_impls(self) -> impl Iterator + 'a { + fn get_trait_impls(self) -> impl Iterator { self.cdata.trait_impls.values().flat_map(move |impls| { impls.decode(self).map(move |(impl_index, _)| self.local_def_id(impl_index)) }) @@ -1463,7 +1459,7 @@ impl<'a> CrateMetadataRef<'a> { } } - fn get_native_libraries(self, sess: &'a Session) -> impl Iterator + 'a { + fn get_native_libraries(self, sess: &'a Session) -> impl Iterator { self.root.native_libraries.decode((self, sess)) } @@ -1476,7 +1472,7 @@ impl<'a> CrateMetadataRef<'a> { .decode((self, sess)) } - fn get_foreign_modules(self, sess: &'a Session) -> impl Iterator + 'a { + fn get_foreign_modules(self, sess: &'a Session) -> impl Iterator { self.root.foreign_modules.decode((self, sess)) } @@ -1816,7 +1812,7 @@ impl<'a> CrateMetadataRef<'a> { .decode(self) } - fn get_doc_link_traits_in_scope(self, index: DefIndex) -> impl Iterator + 'a { + fn get_doc_link_traits_in_scope(self, index: DefIndex) -> impl Iterator { self.root .tables .doc_link_traits_in_scope @@ -1887,7 +1883,7 @@ impl CrateMetadata { cdata } - pub(crate) fn dependencies(&self) -> impl Iterator + '_ { + pub(crate) fn dependencies(&self) -> impl Iterator { self.dependencies.iter().copied() } diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index 40dd6aa73fd4..7d632f592aff 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -174,15 +174,12 @@ impl<'tcx> TyCtxt<'tcx> { } #[inline] - pub fn hir_free_items(self) -> impl Iterator + 'tcx { + pub fn hir_free_items(self) -> impl Iterator { self.hir_crate_items(()).free_items.iter().copied() } #[inline] - pub fn hir_module_free_items( - self, - module: LocalModDefId, - ) -> impl Iterator + 'tcx { + pub fn hir_module_free_items(self, module: LocalModDefId) -> impl Iterator { self.hir_module_items(module).free_items() } @@ -283,7 +280,7 @@ impl<'tcx> TyCtxt<'tcx> { }) } - pub fn hir_body_param_names(self, id: BodyId) -> impl Iterator + 'tcx { + pub fn hir_body_param_names(self, id: BodyId) -> impl Iterator { self.hir_body(id).params.iter().map(|arg| match arg.pat.kind { PatKind::Binding(_, _, ident, _) => ident, _ => Ident::empty(), @@ -337,7 +334,7 @@ impl<'tcx> TyCtxt<'tcx> { /// crate. If you would prefer to iterate over the bodies /// themselves, you can do `self.hir().krate().body_ids.iter()`. #[inline] - pub fn hir_body_owners(self) -> impl Iterator + 'tcx { + pub fn hir_body_owners(self) -> impl Iterator { self.hir_crate_items(()).body_owners.iter().copied() } @@ -502,7 +499,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Returns an iterator for the nodes in the ancestor tree of the `current_id` /// until the crate root is reached. Prefer this over your own loop using `parent_id`. #[inline] - pub fn hir_parent_id_iter(self, current_id: HirId) -> impl Iterator + 'tcx { + pub fn hir_parent_id_iter(self, current_id: HirId) -> impl Iterator { ParentHirIterator::new(self, current_id) } diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 2a201e230155..6071a58367ed 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -40,25 +40,25 @@ impl ModuleItems { /// include foreign items. If you want to e.g. get all functions, use `definitions()` below. /// /// However, this does include the `impl` blocks themselves. - pub fn free_items(&self) -> impl Iterator + '_ { + pub fn free_items(&self) -> impl Iterator { self.free_items.iter().copied() } - pub fn trait_items(&self) -> impl Iterator + '_ { + pub fn trait_items(&self) -> impl Iterator { self.trait_items.iter().copied() } /// Returns all items that are associated with some `impl` block (both inherent and trait impl /// blocks). - pub fn impl_items(&self) -> impl Iterator + '_ { + pub fn impl_items(&self) -> impl Iterator { self.impl_items.iter().copied() } - pub fn foreign_items(&self) -> impl Iterator + '_ { + pub fn foreign_items(&self) -> impl Iterator { self.foreign_items.iter().copied() } - pub fn owners(&self) -> impl Iterator + '_ { + pub fn owners(&self) -> impl Iterator { self.free_items .iter() .map(|id| id.owner_id) @@ -67,15 +67,15 @@ impl ModuleItems { .chain(self.foreign_items.iter().map(|id| id.owner_id)) } - pub fn opaques(&self) -> impl Iterator + '_ { + pub fn opaques(&self) -> impl Iterator { self.opaques.iter().copied() } - pub fn nested_bodies(&self) -> impl Iterator + '_ { + pub fn nested_bodies(&self) -> impl Iterator { self.nested_bodies.iter().copied() } - pub fn definitions(&self) -> impl Iterator + '_ { + pub fn definitions(&self) -> impl Iterator { self.owners().map(|id| id.def_id) } diff --git a/compiler/rustc_middle/src/hir/place.rs b/compiler/rustc_middle/src/hir/place.rs index 66b701523b71..316ad80eb985 100644 --- a/compiler/rustc_middle/src/hir/place.rs +++ b/compiler/rustc_middle/src/hir/place.rs @@ -97,7 +97,7 @@ impl<'tcx> Place<'tcx> { /// The types are in the reverse order that they are applied. So if /// `x: &*const u32` and the `Place` is `**x`, then the types returned are ///`*const u32` then `&*const u32`. - pub fn deref_tys(&self) -> impl Iterator> + '_ { + pub fn deref_tys(&self) -> impl Iterator> { self.projections.iter().enumerate().rev().filter_map(move |(index, proj)| { if ProjectionKind::Deref == proj.kind { Some(self.ty_before_projection(index)) diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs index 78196b053619..2f13f9635785 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs @@ -121,7 +121,7 @@ impl ProvenanceMap { } /// Yields all the provenances stored in this map. - pub fn provenances(&self) -> impl Iterator + '_ { + pub fn provenances(&self) -> impl Iterator { let bytes = self.bytes.iter().flat_map(|b| b.values()); self.ptrs.values().chain(bytes).copied() } diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 227cb97c76b5..cf90df1b198b 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -12,7 +12,6 @@ use either::Either; use polonius_engine::Atom; use rustc_abi::{FieldIdx, VariantIdx}; pub use rustc_ast::Mutability; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::graph::dominators::Dominators; use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage, ErrorGuaranteed, IntoDiagArg}; @@ -472,7 +471,7 @@ impl<'tcx> Body<'tcx> { /// Returns an iterator over all user-declared mutable locals. #[inline] - pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator + Captures<'tcx> + 'a { + pub fn mut_vars_iter(&self) -> impl Iterator { (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| { let local = Local::new(index); let decl = &self.local_decls[local]; @@ -482,9 +481,7 @@ impl<'tcx> Body<'tcx> { /// Returns an iterator over all user-declared mutable arguments and locals. #[inline] - pub fn mut_vars_and_args_iter<'a>( - &'a self, - ) -> impl Iterator + Captures<'tcx> + 'a { + pub fn mut_vars_and_args_iter(&self) -> impl Iterator { (1..self.local_decls.len()).filter_map(move |index| { let local = Local::new(index); let decl = &self.local_decls[local]; @@ -514,7 +511,7 @@ impl<'tcx> Body<'tcx> { } #[inline] - pub fn drain_vars_and_temps<'a>(&'a mut self) -> impl Iterator> + 'a { + pub fn drain_vars_and_temps(&mut self) -> impl Iterator> { self.local_decls.drain(self.arg_count + 1..) } diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 1d61cf48ad26..875f5282bf29 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -1523,7 +1523,7 @@ pub fn write_allocations<'tcx>( ) -> io::Result<()> { fn alloc_ids_from_alloc( alloc: ConstAllocation<'_>, - ) -> impl DoubleEndedIterator + '_ { + ) -> impl DoubleEndedIterator { alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id()) } diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index b529d17540a8..3585f28b4a55 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -4,7 +4,6 @@ use std::ops::Range; use std::str; use rustc_abi::{FIRST_VARIANT, ReprOptions, VariantIdx}; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; @@ -540,7 +539,7 @@ impl<'tcx> AdtDef<'tcx> { pub fn discriminants( self, tcx: TyCtxt<'tcx>, - ) -> impl Iterator)> + Captures<'tcx> { + ) -> impl Iterator)> { assert!(self.is_enum()); let repr_type = self.repr().discr_type(); let initial = repr_type.initial_discriminant(tcx); diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index c4d5367e2f03..3605f2402e7f 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -1,6 +1,5 @@ use std::fmt::Write; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexMap; use rustc_hir as hir; use rustc_hir::HirId; @@ -415,7 +414,7 @@ pub fn analyze_coroutine_closure_captures<'a, 'tcx: 'a, T>( parent_captures: impl IntoIterator>, child_captures: impl IntoIterator>, mut for_each: impl FnMut((usize, &'a CapturedPlace<'tcx>), (usize, &'a CapturedPlace<'tcx>)) -> T, -) -> impl Iterator + Captures<'a> + Captures<'tcx> { +) -> impl Iterator { std::iter::from_coroutine( #[coroutine] move || { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 32a9e67f9ad5..d20e8bd42e69 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1939,7 +1939,7 @@ impl<'tcx> TyCtxt<'tcx> { Ok(TyCtxtFeed { key: num, tcx: self }) } - pub fn iter_local_def_id(self) -> impl Iterator + 'tcx { + pub fn iter_local_def_id(self) -> impl Iterator { // Create a dependency to the red node to be sure we re-execute this when the amount of // definitions change. self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE); @@ -2171,14 +2171,14 @@ impl<'tcx> TyCtxt<'tcx> { } /// All traits in the crate graph, including those not visible to the user. - pub fn all_traits(self) -> impl Iterator + 'tcx { + pub fn all_traits(self) -> impl Iterator { iter::once(LOCAL_CRATE) .chain(self.crates(()).iter().copied()) .flat_map(move |cnum| self.traits(cnum).iter().copied()) } /// All traits that are visible within the crate graph (i.e. excluding private dependencies). - pub fn visible_traits(self) -> impl Iterator + 'tcx { + pub fn visible_traits(self) -> impl Iterator { let visible_crates = self.crates(()).iter().copied().filter(move |cnum| self.is_user_visible_dep(*cnum)); @@ -2363,7 +2363,7 @@ macro_rules! sty_debug_print { } impl<'tcx> TyCtxt<'tcx> { - pub fn debug_stats(self) -> impl fmt::Debug + 'tcx { + pub fn debug_stats(self) -> impl fmt::Debug { fmt::from_fn(move |fmt| { sty_debug_print!( fmt, diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index b74ddb817103..ed0b3059d752 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -479,25 +479,23 @@ impl<'tcx> GenericArgs<'tcx> { } #[inline] - pub fn types(&'tcx self) -> impl DoubleEndedIterator> + 'tcx { + pub fn types(&self) -> impl DoubleEndedIterator> { self.iter().filter_map(|k| k.as_type()) } #[inline] - pub fn regions(&'tcx self) -> impl DoubleEndedIterator> + 'tcx { + pub fn regions(&self) -> impl DoubleEndedIterator> { self.iter().filter_map(|k| k.as_region()) } #[inline] - pub fn consts(&'tcx self) -> impl DoubleEndedIterator> + 'tcx { + pub fn consts(&self) -> impl DoubleEndedIterator> { self.iter().filter_map(|k| k.as_const()) } /// Returns generic arguments that are not lifetimes. #[inline] - pub fn non_erasable_generics( - &'tcx self, - ) -> impl DoubleEndedIterator> + 'tcx { + pub fn non_erasable_generics(&self) -> impl DoubleEndedIterator> { self.iter().filter_map(|k| match k.unpack() { ty::GenericArgKind::Lifetime(_) => None, generic => Some(generic), diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index bd1fb0ca41cf..8ed5a118093f 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1798,14 +1798,11 @@ impl<'tcx> TyCtxt<'tcx> { } } - pub fn get_attrs_by_path<'attr>( + pub fn get_attrs_by_path( self, did: DefId, - attr: &'attr [Symbol], - ) -> impl Iterator + 'attr - where - 'tcx: 'attr, - { + attr: &[Symbol], + ) -> impl Iterator { let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr); if let Some(did) = did.as_local() { self.hir().attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn) diff --git a/compiler/rustc_middle/src/ty/predicate.rs b/compiler/rustc_middle/src/ty/predicate.rs index 584cac22ae8d..553de83dfcb4 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -1,6 +1,5 @@ use std::cmp::Ordering; -use rustc_data_structures::captures::Captures; use rustc_data_structures::intern::Interned; use rustc_hir::def_id::DefId; use rustc_macros::{HashStable, extension}; @@ -336,9 +335,9 @@ impl<'tcx> ty::List> { } #[inline] - pub fn projection_bounds<'a>( - &'a self, - ) -> impl Iterator>> + 'a { + pub fn projection_bounds( + &self, + ) -> impl Iterator>> { self.iter().filter_map(|predicate| { predicate .map_bound(|pred| match pred { @@ -350,16 +349,14 @@ impl<'tcx> ty::List> { } #[inline] - pub fn auto_traits<'a>(&'a self) -> impl Iterator + Captures<'tcx> + 'a { + pub fn auto_traits(&self) -> impl Iterator { self.iter().filter_map(|predicate| match predicate.skip_binder() { ExistentialPredicate::AutoTrait(did) => Some(did), _ => None, }) } - pub fn without_auto_traits( - &self, - ) -> impl Iterator> + '_ { + pub fn without_auto_traits(&self) -> impl Iterator> { self.iter().filter(|predicate| { !matches!(predicate.as_ref().skip_binder(), ExistentialPredicate::AutoTrait(_)) }) diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index dd4da2cf4ac3..d5617adf26b4 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -9,7 +9,6 @@ use std::ops::{ControlFlow, Range}; use hir::def::{CtorKind, DefKind}; use rustc_abi::{ExternAbi, FIRST_VARIANT, FieldIdx, VariantIdx}; -use rustc_data_structures::captures::Captures; use rustc_errors::{ErrorGuaranteed, MultiSpan}; use rustc_hir as hir; use rustc_hir::LangItem; @@ -105,7 +104,7 @@ impl<'tcx> ty::CoroutineArgs> { self, def_id: DefId, tcx: TyCtxt<'tcx>, - ) -> impl Iterator)> + Captures<'tcx> { + ) -> impl Iterator)> { self.variant_range(def_id, tcx).map(move |index| { (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) }) }) @@ -139,7 +138,7 @@ impl<'tcx> ty::CoroutineArgs> { self, def_id: DefId, tcx: TyCtxt<'tcx>, - ) -> impl Iterator> + Captures<'tcx>> { + ) -> impl Iterator>> { let layout = tcx.coroutine_layout(def_id, self.kind_ty()).unwrap(); layout.variant_fields.iter().map(move |variant| { variant.iter().map(move |field| { diff --git a/compiler/rustc_middle/src/ty/trait_def.rs b/compiler/rustc_middle/src/ty/trait_def.rs index 17e90c15d413..8fa1c569737a 100644 --- a/compiler/rustc_middle/src/ty/trait_def.rs +++ b/compiler/rustc_middle/src/ty/trait_def.rs @@ -188,7 +188,7 @@ impl<'tcx> TyCtxt<'tcx> { self, trait_def_id: DefId, self_ty: Ty<'tcx>, - ) -> impl Iterator + 'tcx { + ) -> impl Iterator { let impls = self.trait_impls_of(trait_def_id); if let Some(simp) = fast_reject::simplify_type(self, self_ty, TreatParams::InstantiateWithInfer) @@ -204,7 +204,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Returns an iterator containing all impls for `trait_def_id`. /// /// `trait_def_id` MUST BE the `DefId` of a trait. - pub fn all_impls(self, trait_def_id: DefId) -> impl Iterator + 'tcx { + pub fn all_impls(self, trait_def_id: DefId) -> impl Iterator { let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(trait_def_id); blanket_impls.iter().chain(non_blanket_impls.iter().flat_map(|(_, v)| v)).cloned() diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index b8c73d258437..d4484a16fea4 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -575,7 +575,7 @@ impl<'a, V> LocalTableInContext<'a, V> { } pub fn items( - &'a self, + &self, ) -> UnordItems<(hir::ItemLocalId, &'a V), impl Iterator> { self.data.items().map(|(id, value)| (*id, value)) diff --git a/compiler/rustc_mir_build/src/builder/expr/as_place.rs b/compiler/rustc_mir_build/src/builder/expr/as_place.rs index 308ca442b40c..581f45db6c48 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_place.rs @@ -216,11 +216,11 @@ fn to_upvars_resolved_place_builder<'tcx>( /// Supports only HIR projection kinds that represent a path that might be /// captured by a closure or a coroutine, i.e., an `Index` or a `Subslice` /// projection kinds are unsupported. -fn strip_prefix<'a, 'tcx>( +fn strip_prefix<'tcx>( mut base_ty: Ty<'tcx>, - projections: &'a [PlaceElem<'tcx>], + projections: &[PlaceElem<'tcx>], prefix_projections: &[HirProjection<'tcx>], -) -> impl Iterator> + 'a { +) -> impl Iterator> { let mut iter = projections .iter() .copied() diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index 7a9f6e463045..41a642f95b6e 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -159,12 +159,12 @@ impl<'tcx> ThirBuildCx<'tcx> { }) } - fn explicit_params<'a>( - &'a mut self, + fn explicit_params( + &mut self, owner_id: HirId, fn_decl: &'tcx hir::FnDecl<'tcx>, body: &'tcx hir::Body<'tcx>, - ) -> impl Iterator> + 'a { + ) -> impl Iterator> { let fn_sig = self.typeck_results.liberated_fn_sigs()[owner_id]; body.params.iter().enumerate().map(move |(index, param)| { diff --git a/compiler/rustc_mir_dataflow/src/move_paths/mod.rs b/compiler/rustc_mir_dataflow/src/move_paths/mod.rs index 8aea8d2ae3ca..18985ba0da25 100644 --- a/compiler/rustc_mir_dataflow/src/move_paths/mod.rs +++ b/compiler/rustc_mir_dataflow/src/move_paths/mod.rs @@ -343,7 +343,7 @@ impl<'tcx> MovePathLookup<'tcx> { /// `MovePathIndex`es. pub fn iter_locals_enumerated( &self, - ) -> impl DoubleEndedIterator + '_ { + ) -> impl DoubleEndedIterator { self.locals.iter_enumerated().filter_map(|(l, &idx)| Some((l, idx?))) } } diff --git a/compiler/rustc_mir_dataflow/src/un_derefer.rs b/compiler/rustc_mir_dataflow/src/un_derefer.rs index bb15b8106a1e..b38dd9d40f52 100644 --- a/compiler/rustc_mir_dataflow/src/un_derefer.rs +++ b/compiler/rustc_mir_dataflow/src/un_derefer.rs @@ -28,7 +28,7 @@ impl<'tcx> UnDerefer<'tcx> { pub(crate) fn iter_projections( &self, place: PlaceRef<'tcx>, - ) -> impl Iterator, PlaceElem<'tcx>)> + '_ { + ) -> impl Iterator, PlaceElem<'tcx>)> { ProjectionIter::new(self.deref_chain(place.local), place) } } diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 9cba07e15a43..36fb1c2b36d0 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -2,7 +2,6 @@ use std::fmt::{Debug, Formatter}; use std::ops::Range; use rustc_abi::{FieldIdx, VariantIdx}; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashMap, FxIndexSet, StdEntry}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_index::IndexVec; @@ -676,10 +675,7 @@ impl<'tcx> Map<'tcx> { } /// Iterate over all direct children. - fn children( - &self, - parent: PlaceIndex, - ) -> impl Iterator + Captures<'_> + Captures<'tcx> { + fn children(&self, parent: PlaceIndex) -> impl Iterator { Children::new(self, parent) } diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index 6d84248ddfbd..09384defea86 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -2,7 +2,6 @@ use std::cmp::Ordering; use std::ops::{Index, IndexMut}; use std::{mem, slice}; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::graph::dominators::Dominators; use rustc_data_structures::graph::{self, DirectedGraph, StartNode}; @@ -218,7 +217,7 @@ impl CoverageGraph { pub(crate) fn reloop_predecessors( &self, to_bcb: BasicCoverageBlock, - ) -> impl Iterator + Captures<'_> { + ) -> impl Iterator { self.predecessors[to_bcb].iter().copied().filter(move |&pred| self.dominates(to_bcb, pred)) } } diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index ef86358b2057..58461be01f17 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -1,4 +1,3 @@ -use rustc_data_structures::captures::Captures; use rustc_index::bit_set::DenseBitSet; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir::coverage::{BasicCoverageBlock, CoverageIdsInfo, CoverageKind, MappingKind}; @@ -153,7 +152,7 @@ fn coverage_ids_info<'tcx>( fn all_coverage_in_mir_body<'a, 'tcx>( body: &'a Body<'tcx>, -) -> impl Iterator + Captures<'tcx> { +) -> impl Iterator { body.basic_blocks.iter().flat_map(|bb_data| &bb_data.statements).filter_map(|statement| { match statement.kind { StatementKind::Coverage(ref kind) if !is_inlined(body, statement) => Some(kind), diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index 314a86ea52f0..b9ed6984ddb2 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -1,6 +1,5 @@ use std::collections::VecDeque; -use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxHashSet; use rustc_middle::mir; use rustc_span::{DesugaringKind, ExpnKind, MacroKind, Span}; @@ -182,7 +181,7 @@ fn divide_spans_into_buckets(input_covspans: Vec, holes: &[Hole]) -> Ve fn drain_front_while<'a, T>( queue: &'a mut VecDeque, mut pred_fn: impl FnMut(&T) -> bool, -) -> impl Iterator + Captures<'a> { +) -> impl Iterator { std::iter::from_fn(move || if pred_fn(queue.front()?) { queue.pop_front() } else { None }) } diff --git a/compiler/rustc_mir_transform/src/jump_threading.rs b/compiler/rustc_mir_transform/src/jump_threading.rs index bd310b078975..0a72a9d669fe 100644 --- a/compiler/rustc_mir_transform/src/jump_threading.rs +++ b/compiler/rustc_mir_transform/src/jump_threading.rs @@ -172,11 +172,11 @@ impl HasBottom for ConditionSet<'_> { } impl<'a> ConditionSet<'a> { - fn iter(self) -> impl Iterator + 'a { + fn iter(self) -> impl Iterator { self.0.iter().copied() } - fn iter_matches(self, value: ScalarInt) -> impl Iterator + 'a { + fn iter_matches(self, value: ScalarInt) -> impl Iterator { self.iter().filter(move |c| c.matches(value)) } diff --git a/compiler/rustc_mir_transform/src/sroa.rs b/compiler/rustc_mir_transform/src/sroa.rs index 28de99f9193d..7c6ccc89c4f3 100644 --- a/compiler/rustc_mir_transform/src/sroa.rs +++ b/compiler/rustc_mir_transform/src/sroa.rs @@ -185,7 +185,7 @@ impl<'tcx> ReplacementMap<'tcx> { fn place_fragments( &self, place: Place<'tcx>, - ) -> Option, Local)> + '_> { + ) -> Option, Local)>> { let local = place.as_local()?; let fields = self.fragments[local].as_ref()?; Some(fields.iter_enumerated().filter_map(|(field, &opt_ty_local)| { diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index 9f769077e77e..3d512fb064ec 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -138,7 +138,7 @@ impl SsaLocals { pub(super) fn assignments<'a, 'tcx>( &'a self, body: &'a Body<'tcx>, - ) -> impl Iterator, Location)> + 'a { + ) -> impl Iterator, Location)> { self.assignment_order.iter().filter_map(|&local| { if let Set1::One(DefLocation::Assignment(loc)) = self.assignments[local] { let stmt = body.stmt_at(loc).left()?; diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 1195c25e1308..9b652cddc499 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -323,7 +323,7 @@ impl<'tcx> MonoItems<'tcx> { self.items.entry(item.node).or_insert(item.span); } - fn items(&self) -> impl Iterator> + '_ { + fn items(&self) -> impl Iterator> { self.items.keys().cloned() } } diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index bbd73dec2e47..80a33a760059 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -1657,7 +1657,7 @@ impl<'a> Parser<'a> { // Debug view of the parser's token stream, up to `{lookahead}` tokens. // Only used when debugging. #[allow(unused)] - pub(crate) fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug + '_ { + pub(crate) fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug { fmt::from_fn(move |f| { let mut dbg_fmt = f.debug_struct("Parser"); // or at least, one view of diff --git a/compiler/rustc_pattern_analysis/src/lib.rs b/compiler/rustc_pattern_analysis/src/lib.rs index fec44d5af55d..a3400ebb7993 100644 --- a/compiler/rustc_pattern_analysis/src/lib.rs +++ b/compiler/rustc_pattern_analysis/src/lib.rs @@ -61,11 +61,11 @@ pub trait PatCx: Sized + fmt::Debug { fn ctor_arity(&self, ctor: &Constructor, ty: &Self::Ty) -> usize; /// The types of the fields for this constructor. The result must contain `ctor_arity()` fields. - fn ctor_sub_tys<'a>( - &'a self, - ctor: &'a Constructor, - ty: &'a Self::Ty, - ) -> impl Iterator + ExactSizeIterator + Captures<'a>; + fn ctor_sub_tys( + &self, + ctor: &Constructor, + ty: &Self::Ty, + ) -> impl Iterator + ExactSizeIterator; /// The set of all the constructors for `ty`. /// diff --git a/compiler/rustc_pattern_analysis/src/pat_column.rs b/compiler/rustc_pattern_analysis/src/pat_column.rs index eb4e095c1c66..814eb8afcfc0 100644 --- a/compiler/rustc_pattern_analysis/src/pat_column.rs +++ b/compiler/rustc_pattern_analysis/src/pat_column.rs @@ -1,6 +1,6 @@ use crate::constructor::{Constructor, SplitConstructorSet}; use crate::pat::{DeconstructedPat, PatOrWild}; -use crate::{Captures, MatchArm, PatCx}; +use crate::{MatchArm, PatCx}; /// A column of patterns in a match, where a column is the intuitive notion of "subpatterns that /// inspect the same subvalue/place". @@ -41,7 +41,7 @@ impl<'p, Cx: PatCx> PatternColumn<'p, Cx> { pub fn head_ty(&self) -> Option<&Cx::Ty> { self.patterns.first().map(|pat| pat.ty()) } - pub fn iter<'a>(&'a self) -> impl Iterator> + Captures<'a> { + pub fn iter(&self) -> impl Iterator> { self.patterns.iter().copied() } diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 0b1e954d64d4..88194c737a6c 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -25,7 +25,7 @@ use crate::lints::lint_nonexhaustive_missing_variants; use crate::pat_column::PatternColumn; use crate::rustc::print::EnumInfo; use crate::usefulness::{PlaceValidity, compute_match_usefulness}; -use crate::{Captures, PatCx, PrivateUninhabitedField, errors}; +use crate::{PatCx, PrivateUninhabitedField, errors}; mod print; @@ -175,8 +175,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { &self, ty: RevealedTy<'tcx>, variant: &'tcx VariantDef, - ) -> impl Iterator)> + Captures<'p> + Captures<'_> - { + ) -> impl Iterator)> { let ty::Adt(_, args) = ty.kind() else { bug!() }; variant.fields.iter().map(move |field| { let ty = field.ty(self.tcx, args); @@ -203,13 +202,11 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { /// Returns the types of the fields for a given constructor. The result must have a length of /// `ctor.arity()`. - pub(crate) fn ctor_sub_tys<'a>( - &'a self, - ctor: &'a Constructor<'p, 'tcx>, + pub(crate) fn ctor_sub_tys( + &self, + ctor: &Constructor<'p, 'tcx>, ty: RevealedTy<'tcx>, - ) -> impl Iterator, PrivateUninhabitedField)> - + ExactSizeIterator - + Captures<'a> { + ) -> impl Iterator, PrivateUninhabitedField)> + ExactSizeIterator { fn reveal_and_alloc<'a, 'tcx>( cx: &'a RustcPatCtxt<'_, 'tcx>, iter: impl Iterator>, @@ -936,12 +933,11 @@ impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> { fn ctor_arity(&self, ctor: &crate::constructor::Constructor, ty: &Self::Ty) -> usize { self.ctor_arity(ctor, *ty) } - fn ctor_sub_tys<'a>( - &'a self, - ctor: &'a crate::constructor::Constructor, - ty: &'a Self::Ty, - ) -> impl Iterator + ExactSizeIterator + Captures<'a> - { + fn ctor_sub_tys( + &self, + ctor: &crate::constructor::Constructor, + ty: &Self::Ty, + ) -> impl Iterator + ExactSizeIterator { self.ctor_sub_tys(ctor, *ty) } fn ctors_for_ty( diff --git a/compiler/rustc_pattern_analysis/src/usefulness.rs b/compiler/rustc_pattern_analysis/src/usefulness.rs index 1dff76141da5..11ebbea07fa4 100644 --- a/compiler/rustc_pattern_analysis/src/usefulness.rs +++ b/compiler/rustc_pattern_analysis/src/usefulness.rs @@ -719,7 +719,7 @@ use tracing::{debug, instrument}; use self::PlaceValidity::*; use crate::constructor::{Constructor, ConstructorSet, IntRange}; use crate::pat::{DeconstructedPat, PatId, PatOrWild, WitnessPat}; -use crate::{Captures, MatchArm, PatCx, PrivateUninhabitedField}; +use crate::{MatchArm, PatCx, PrivateUninhabitedField}; #[cfg(not(feature = "rustc"))] pub fn ensure_sufficient_stack(f: impl FnOnce() -> R) -> R { f() @@ -902,11 +902,11 @@ struct PlaceInfo { impl PlaceInfo { /// Given a constructor for the current place, we return one `PlaceInfo` for each field of the /// constructor. - fn specialize<'a>( - &'a self, - cx: &'a Cx, - ctor: &'a Constructor, - ) -> impl Iterator + ExactSizeIterator + Captures<'a> { + fn specialize( + &self, + cx: &Cx, + ctor: &Constructor, + ) -> impl Iterator + ExactSizeIterator { let ctor_sub_tys = cx.ctor_sub_tys(ctor, &self.ty); let ctor_sub_validity = self.validity.specialize(ctor); ctor_sub_tys.map(move |(ty, PrivateUninhabitedField(private_uninhabited))| PlaceInfo { @@ -1046,13 +1046,13 @@ impl<'p, Cx: PatCx> PatStack<'p, Cx> { self.pats[0] } - fn iter(&self) -> impl Iterator> + Captures<'_> { + fn iter(&self) -> impl Iterator> { self.pats.iter().copied() } // Expand the first or-pattern into its subpatterns. Only useful if the pattern is an // or-pattern. Panics if `self` is empty. - fn expand_or_pat(&self) -> impl Iterator> + Captures<'_> { + fn expand_or_pat(&self) -> impl Iterator> { self.head().expand_or_pat().into_iter().map(move |pat| { let mut new = self.clone(); new.pats[0] = pat; @@ -1157,15 +1157,12 @@ impl<'p, Cx: PatCx> MatrixRow<'p, Cx> { self.pats.head() } - fn iter(&self) -> impl Iterator> + Captures<'_> { + fn iter(&self) -> impl Iterator> { self.pats.iter() } // Expand the first or-pattern (if any) into its subpatterns. Panics if `self` is empty. - fn expand_or_pat( - &self, - parent_row: usize, - ) -> impl Iterator> + Captures<'_> { + fn expand_or_pat(&self, parent_row: usize) -> impl Iterator> { let is_or_pat = self.pats.head().is_or_pat(); self.pats.expand_or_pat().map(move |patstack| MatrixRow { pats: patstack, @@ -1275,7 +1272,7 @@ impl<'p, Cx: PatCx> Matrix<'p, Cx> { } /// Iterate over the first pattern of each row. - fn heads(&self) -> impl Iterator> + Clone + Captures<'_> { + fn heads(&self) -> impl Iterator> + Clone { self.rows().map(|r| r.head()) } diff --git a/compiler/rustc_pattern_analysis/tests/common/mod.rs b/compiler/rustc_pattern_analysis/tests/common/mod.rs index 23560ad64190..365bc2d863f4 100644 --- a/compiler/rustc_pattern_analysis/tests/common/mod.rs +++ b/compiler/rustc_pattern_analysis/tests/common/mod.rs @@ -2,7 +2,7 @@ use rustc_pattern_analysis::constructor::{ Constructor, ConstructorSet, IntRange, MaybeInfiniteInt, RangeEnd, VariantVisibility, }; use rustc_pattern_analysis::usefulness::{PlaceValidity, UsefulnessReport}; -use rustc_pattern_analysis::{Captures, MatchArm, PatCx, PrivateUninhabitedField}; +use rustc_pattern_analysis::{MatchArm, PatCx, PrivateUninhabitedField}; /// Sets up `tracing` for easier debugging. Tries to look like the `rustc` setup. pub fn init_tracing() { @@ -156,12 +156,11 @@ impl PatCx for Cx { ty.sub_tys(ctor).len() } - fn ctor_sub_tys<'a>( - &'a self, - ctor: &'a Constructor, - ty: &'a Self::Ty, - ) -> impl Iterator + ExactSizeIterator + Captures<'a> - { + fn ctor_sub_tys( + &self, + ctor: &Constructor, + ty: &Self::Ty, + ) -> impl Iterator + ExactSizeIterator { ty.sub_tys(ctor).into_iter().map(|ty| (ty, PrivateUninhabitedField(false))) } diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index a4fb0a5b0722..bc78878a84a2 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -98,7 +98,7 @@ impl SerializedDepGraph { pub fn edge_targets_from( &self, source: SerializedDepNodeIndex, - ) -> impl Iterator + Clone + '_ { + ) -> impl Iterator + Clone { let header = self.edge_list_indices[source]; let mut raw = &self.edge_list_data[header.start()..]; // Figure out where the edge list for `source` ends by getting the start index of the next diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index e0405a71f65a..1fe521bd32d5 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -329,7 +329,7 @@ impl ParseSess { self.proc_macro_quoted_spans.push(span) } - pub fn proc_macro_quoted_spans(&self) -> impl Iterator + '_ { + pub fn proc_macro_quoted_spans(&self) -> impl Iterator { // This is equivalent to `.iter().copied().enumerate()`, but that isn't possible for // AppendOnlyVec, so we resort to this scheme. self.proc_macro_quoted_spans.iter_enumerated() diff --git a/compiler/rustc_session/src/search_paths.rs b/compiler/rustc_session/src/search_paths.rs index b750d870cb6f..00e12b45bafb 100644 --- a/compiler/rustc_session/src/search_paths.rs +++ b/compiler/rustc_session/src/search_paths.rs @@ -20,12 +20,11 @@ pub struct FilesIndex(Vec<(Arc, SearchPathFile)>); impl FilesIndex { /// Look up [SearchPathFile] by (prefix, suffix) pair. - pub fn query<'this, 'prefix, 'suffix>( - &'this self, - prefix: &'prefix str, - suffix: &'suffix str, - ) -> Option + use<'this, 'prefix, 'suffix>> - { + pub fn query<'s>( + &'s self, + prefix: &str, + suffix: &str, + ) -> Option> { let start = self.0.partition_point(|(k, _)| **k < *prefix); if start == self.0.len() { return None; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index 42b8199cb265..bed9734f389c 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -1074,7 +1074,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { &self, path: &'tcx hir::Path<'tcx>, args: GenericArgsRef<'tcx>, - ) -> impl Iterator> + 'a { + ) -> impl Iterator> + 'tcx { let tcx = self.tecx.tcx; let have_turbofish = path.segments.iter().any(|segment| { segment.args.is_some_and(|args| args.args.iter().any(|arg| arg.is_ty_or_const())) diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 51d560d4c43d..704ba6e501d8 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -67,9 +67,7 @@ impl<'tcx> ObligationStorage<'tcx> { obligations } - fn unstalled_for_select( - &mut self, - ) -> impl Iterator> + use<'tcx> { + fn unstalled_for_select(&mut self) -> impl Iterator> + 'tcx { mem::take(&mut self.pending).into_iter() } diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index f2d2dd2f3ce5..e39f8e673dba 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -1,6 +1,5 @@ use std::marker::PhantomData; -use rustc_data_structures::captures::Captures; use rustc_data_structures::obligation_forest::{ Error, ForestObligation, ObligationForest, ObligationProcessor, Outcome, ProcessResult, }; @@ -900,10 +899,10 @@ impl<'a, 'tcx> FulfillProcessor<'a, 'tcx> { } /// Returns the set of inference variables contained in `args`. -fn args_infer_vars<'a, 'tcx>( - selcx: &SelectionContext<'a, 'tcx>, +fn args_infer_vars<'tcx>( + selcx: &SelectionContext<'_, 'tcx>, args: ty::Binder<'tcx, GenericArgsRef<'tcx>>, -) -> impl Iterator + Captures<'tcx> { +) -> impl Iterator { selcx .infcx .resolve_vars_if_possible(args) diff --git a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs index f39c611d19fe..19d3561dd595 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs @@ -200,15 +200,12 @@ impl<'tcx> Children { } } -fn iter_children(children: &Children) -> impl Iterator + '_ { +fn iter_children(children: &Children) -> impl Iterator { let nonblanket = children.non_blanket_impls.iter().flat_map(|(_, v)| v.iter()); children.blanket_impls.iter().chain(nonblanket).cloned() } -fn filtered_children( - children: &mut Children, - st: SimplifiedType, -) -> impl Iterator + '_ { +fn filtered_children(children: &mut Children, st: SimplifiedType) -> impl Iterator { let nonblanket = children.non_blanket_impls.entry(st).or_default().iter(); children.blanket_impls.iter().chain(nonblanket).cloned() } diff --git a/compiler/rustc_trait_selection/src/traits/vtable.rs b/compiler/rustc_trait_selection/src/traits/vtable.rs index 0024316b877c..165174c0bcc1 100644 --- a/compiler/rustc_trait_selection/src/traits/vtable.rs +++ b/compiler/rustc_trait_selection/src/traits/vtable.rs @@ -196,7 +196,7 @@ fn own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> &[Def fn own_existential_vtable_entries_iter( tcx: TyCtxt<'_>, trait_def_id: DefId, -) -> impl Iterator + '_ { +) -> impl Iterator { let trait_methods = tcx .associated_items(trait_def_id) .in_definition_order() diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index cc7baf8daac5..6205578bf747 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -151,7 +151,7 @@ fn assumed_wf_types<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx [(Ty<' } } -fn fn_sig_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator + '_ { +fn fn_sig_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator { let node = tcx.hir_node_by_def_id(def_id); if let Some(decl) = node.fn_decl() { decl.inputs.iter().map(|ty| ty.span).chain(iter::once(decl.output.span())) @@ -160,7 +160,7 @@ fn fn_sig_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator, def_id: LocalDefId) -> impl Iterator + '_ { +fn impl_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator { let item = tcx.hir().expect_item(def_id); if let hir::ItemKind::Impl(impl_) = item.kind { let trait_args = impl_ diff --git a/compiler/rustc_ty_utils/src/layout/invariant.rs b/compiler/rustc_ty_utils/src/layout/invariant.rs index 5ea6716c5ca1..525199801c3a 100644 --- a/compiler/rustc_ty_utils/src/layout/invariant.rs +++ b/compiler/rustc_ty_utils/src/layout/invariant.rs @@ -33,7 +33,7 @@ pub(super) fn layout_sanity_check<'tcx>(cx: &LayoutCx<'tcx>, layout: &TyAndLayou fn non_zst_fields<'tcx, 'a>( cx: &'a LayoutCx<'tcx>, layout: &'a TyAndLayout<'tcx>, - ) -> impl Iterator)> + 'a { + ) -> impl Iterator)> { (0..layout.layout.fields().count()).filter_map(|i| { let field = layout.field(cx, i); // Also checking `align == 1` here leads to test failures in diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 80de7e20951a..52955ec59a4a 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -373,7 +373,7 @@ fn drop_tys_helper<'tcx>( fn adt_consider_insignificant_dtor<'tcx>( tcx: TyCtxt<'tcx>, -) -> impl Fn(ty::AdtDef<'tcx>) -> Option + 'tcx { +) -> impl Fn(ty::AdtDef<'tcx>) -> Option { move |adt_def: ty::AdtDef<'tcx>| { let is_marked_insig = tcx.has_attr(adt_def.did(), sym::rustc_insignificant_dtor); if is_marked_insig { diff --git a/compiler/rustc_type_ir/src/search_graph/mod.rs b/compiler/rustc_type_ir/src/search_graph/mod.rs index 3cc2dcbaca6d..082cfff72e20 100644 --- a/compiler/rustc_type_ir/src/search_graph/mod.rs +++ b/compiler/rustc_type_ir/src/search_graph/mod.rs @@ -285,7 +285,7 @@ impl NestedGoals { #[cfg_attr(feature = "nightly", rustc_lint_query_instability)] #[allow(rustc::potential_query_instability)] - fn iter(&self) -> impl Iterator + '_ { + fn iter(&self) -> impl Iterator { self.nested_goals.iter().map(|(i, p)| (*i, *p)) } diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs index bc2e427f50cb..f8b46f50a529 100644 --- a/compiler/stable_mir/src/mir/body.rs +++ b/compiler/stable_mir/src/mir/body.rs @@ -864,7 +864,7 @@ impl SwitchTargets { } /// The conditional targets which are only taken if the pattern matches the given value. - pub fn branches(&self) -> impl Iterator + '_ { + pub fn branches(&self) -> impl Iterator { self.branches.iter().copied() } diff --git a/compiler/stable_mir/src/ty.rs b/compiler/stable_mir/src/ty.rs index 9ef80edb82a6..b857a735b725 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -809,7 +809,7 @@ impl AdtDef { } /// Iterate over the variants in this ADT. - pub fn variants_iter(&self) -> impl Iterator + '_ { + pub fn variants_iter(&self) -> impl Iterator { (0..self.num_variants()) .map(|idx| VariantDef { idx: VariantIdx::to_val(idx), adt_def: *self }) } diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs index 3312da470c03..91eb59fb3140 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs @@ -361,11 +361,11 @@ impl PatCx for MatchCheckCtx<'_> { } } - fn ctor_sub_tys<'a>( - &'a self, - ctor: &'a rustc_pattern_analysis::constructor::Constructor, - ty: &'a Self::Ty, - ) -> impl ExactSizeIterator + Captures<'a> { + fn ctor_sub_tys( + &self, + ctor: &rustc_pattern_analysis::constructor::Constructor, + ty: &Self::Ty, + ) -> impl ExactSizeIterator { let single = |ty| smallvec![(ty, PrivateUninhabitedField(false))]; let tys: SmallVec<[_; 2]> = match ctor { Struct | Variant(_) | UnionField => match ty.kind(Interner) { From 04c453c4bc4de30b41e3bd3ee7492d37b2cc3d89 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 22 Feb 2025 23:54:08 +0000 Subject: [PATCH 28/29] Fix bugs due to unhandled ControlFlow --- compiler/rustc_lint/src/types.rs | 2 +- compiler/stable_mir/src/visitor.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 68b1f435a4cf..3ec61cdf41a1 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1587,7 +1587,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } impl<'a, 'b, 'tcx> ty::visit::TypeVisitor> for FnPtrFinder<'a, 'b, 'tcx> { - type Result = ControlFlow>; + type Result = (); fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result { if let ty::FnPtr(_, hdr) = ty.kind() diff --git a/compiler/stable_mir/src/visitor.rs b/compiler/stable_mir/src/visitor.rs index 3533ed2e8511..8463174f9a46 100644 --- a/compiler/stable_mir/src/visitor.rs +++ b/compiler/stable_mir/src/visitor.rs @@ -161,7 +161,7 @@ impl Visitable for RigidTy { RigidTy::Slice(inner) => inner.visit(visitor), RigidTy::RawPtr(ty, _) => ty.visit(visitor), RigidTy::Ref(reg, ty, _) => { - reg.visit(visitor); + reg.visit(visitor)?; ty.visit(visitor) } RigidTy::Adt(_, args) From 431b9aa38ff466fbed1b933cd17efa10f6cd03b4 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 23 Feb 2025 04:46:51 +0000 Subject: [PATCH 29/29] Fix missing self subst when rendering Fn* trait with no output type --- compiler/rustc_middle/src/ty/print/pretty.rs | 24 +++++++++++-------- tests/crashes/133597.rs | 11 --------- .../unboxed-closures/existential-printing.rs | 8 +++++++ .../existential-printing.stderr | 17 +++++++++++++ 4 files changed, 39 insertions(+), 21 deletions(-) delete mode 100644 tests/crashes/133597.rs create mode 100644 tests/ui/unboxed-closures/existential-printing.rs create mode 100644 tests/ui/unboxed-closures/existential-printing.stderr diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 11b430dd358d..ed0839f47e69 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -232,7 +232,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { f: F, ) -> Result<(), PrintError> where - T: Print<'tcx, Self> + TypeFoldable>, + T: TypeFoldable>, { f(value.as_ref().skip_binder(), self) } @@ -1056,7 +1056,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !has_sized_bound; - for ((bound_args, is_async), entry) in fn_traits { + for ((bound_args_and_self_ty, is_async), entry) in fn_traits { write!(self, "{}", if first { "" } else { " + " })?; write!(self, "{}", if paren_needed { "(" } else { "" })?; @@ -1067,7 +1067,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { }; if let Some(return_ty) = entry.return_ty { - self.wrap_binder(&bound_args, |args, cx| { + self.wrap_binder(&bound_args_and_self_ty, |(args, _), cx| { define_scoped_cx!(cx); p!(write("{}", tcx.item_name(trait_def_id))); p!("("); @@ -1093,9 +1093,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } else { // Otherwise, render this like a regular trait. traits.insert( - bound_args.map_bound(|args| ty::TraitPredicate { + bound_args_and_self_ty.map_bound(|(args, self_ty)| ty::TraitPredicate { polarity: ty::PredicatePolarity::Positive, - trait_ref: ty::TraitRef::new(tcx, trait_def_id, [Ty::new_tup(tcx, args)]), + trait_ref: ty::TraitRef::new( + tcx, + trait_def_id, + [self_ty, Ty::new_tup(tcx, args)], + ), }), FxIndexMap::default(), ); @@ -1229,7 +1233,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { FxIndexMap>>, >, fn_traits: &mut FxIndexMap< - (ty::Binder<'tcx, &'tcx ty::List>>, bool), + (ty::Binder<'tcx, (&'tcx ty::List>, Ty<'tcx>)>, bool), OpaqueFnEntry<'tcx>, >, ) { @@ -1249,7 +1253,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { && let ty::Tuple(types) = *trait_pred.skip_binder().trait_ref.args.type_at(1).kind() { let entry = fn_traits - .entry((trait_pred.rebind(types), is_async)) + .entry((trait_pred.rebind((types, trait_pred.skip_binder().self_ty())), is_async)) .or_insert_with(|| OpaqueFnEntry { kind, return_ty: None }); if kind.extends(entry.kind) { entry.kind = kind; @@ -2379,7 +2383,7 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { f: C, ) -> Result<(), PrintError> where - T: Print<'tcx, Self> + TypeFoldable>, + T: TypeFoldable>, { self.pretty_wrap_binder(value, f) } @@ -2633,7 +2637,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { value: &ty::Binder<'tcx, T>, ) -> Result<(T, UnordMap>), fmt::Error> where - T: Print<'tcx, Self> + TypeFoldable>, + T: TypeFoldable>, { fn name_by_region_index( index: usize, @@ -2814,7 +2818,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { f: C, ) -> Result<(), fmt::Error> where - T: Print<'tcx, Self> + TypeFoldable>, + T: TypeFoldable>, { let old_region_index = self.region_index; let (new_value, _) = self.name_all_regions(value)?; diff --git a/tests/crashes/133597.rs b/tests/crashes/133597.rs deleted file mode 100644 index f716d5e7bc74..000000000000 --- a/tests/crashes/133597.rs +++ /dev/null @@ -1,11 +0,0 @@ -//@ known-bug: #133597 - -pub trait Foo2 { - fn boxed<'a: 'a>() -> impl Sized + FnOnce<()>; -} - -impl Foo2 for () {} - - -fn f() -> impl FnOnce<()> { || () } -fn main() { () = f(); } diff --git a/tests/ui/unboxed-closures/existential-printing.rs b/tests/ui/unboxed-closures/existential-printing.rs new file mode 100644 index 000000000000..f43373202091 --- /dev/null +++ b/tests/ui/unboxed-closures/existential-printing.rs @@ -0,0 +1,8 @@ +// Make sure we don't ICE printing `impl AsyncFnOnce<()>`. + +#![feature(unboxed_closures, fn_traits)] + +fn f() -> impl FnOnce<()> { || () } + +fn main() { () = f(); } +//~^ ERROR mismatched types diff --git a/tests/ui/unboxed-closures/existential-printing.stderr b/tests/ui/unboxed-closures/existential-printing.stderr new file mode 100644 index 000000000000..95de98878aff --- /dev/null +++ b/tests/ui/unboxed-closures/existential-printing.stderr @@ -0,0 +1,17 @@ +error[E0308]: mismatched types + --> $DIR/existential-printing.rs:7:13 + | +LL | fn f() -> impl FnOnce<()> { || () } + | --------------- the expected opaque type +LL | +LL | fn main() { () = f(); } + | ^^ --- this expression has type `impl FnOnce<()>` + | | + | expected opaque type, found `()` + | + = note: expected opaque type `impl FnOnce<()>` + found unit type `()` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`.