diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 96684a56505f9..c69331ed187fa 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -1597,7 +1597,7 @@ impl Expr { | ExprKind::UnsafeBinderCast(..) | ExprKind::While(..) | ExprKind::Yield(YieldKind::Postfix(..)) - | ExprKind::GcaMacro(..) + | ExprKind::Gca(..) | ExprKind::Err(_) | ExprKind::Dummy => prefix_attrs_precedence(&self.attrs), } @@ -1838,7 +1838,7 @@ pub enum ExprKind { /// Output of the `asm!()` macro. InlineAsm(Box), - /// An `offset_of` expression (e.g., `k#offset_of(Struct, field)`). + /// An offset-of expression (e.g., `k#offset_of(Struct, field)`). /// /// Usually not written directly in user code but /// indirectly via the macro `core::mem::offset_of!(...)`. @@ -1894,8 +1894,11 @@ pub enum ExprKind { UnsafeBinderCast(UnsafeBinderCastKind, Box, Option>), - /// An mGCA `gca!()` expression. - GcaMacro(Box), + /// An mGCA expression (e.g., `k#gca(0)`). + /// + /// Usually not written directly in user code but indirectly via the macro + /// `std::gca` (`core::marker::gca`). + Gca(Box), /// Placeholder for an expression that wasn't syntactically well formed in some way. Err(ErrorGuaranteed), @@ -2544,8 +2547,11 @@ pub enum TyKind { FieldOf(Box, Option, Ident), /// A view of a type. `T.{ field_1, field_2 }`. View(Box, #[visitable(ignore)] ThinVec), - /// An mGCA `gca!()` expression. - GcaMacro(Box), + /// An mGCA expression (e.g., `k#gca(0)`), not a real type. + /// + /// Usually not written directly in user code but indirectly via the macro + /// `std::gca` (`core::marker::gca`). + Gca(Box), /// Sometimes we need a dummy value when no error has occurred. Dummy, /// Placeholder for a kind that has failed to be defined. diff --git a/compiler/rustc_ast/src/util/classify.rs b/compiler/rustc_ast/src/util/classify.rs index 86a4073bd100f..b27e77a90cfb1 100644 --- a/compiler/rustc_ast/src/util/classify.rs +++ b/compiler/rustc_ast/src/util/classify.rs @@ -158,7 +158,7 @@ pub fn leading_labeled_expr(mut expr: &ast::Expr) -> bool { | Yeet(..) | Yield(..) | UnsafeBinderCast(..) - | GcaMacro(..) + | Gca(..) | Err(..) | Dummy => return false, } @@ -244,7 +244,7 @@ pub fn expr_trailing_brace(mut expr: &ast::Expr) -> Option> { | Try(_) | Yeet(None) | UnsafeBinderCast(..) - | GcaMacro(..) + | Gca(..) | Err(_) | Dummy => { break None; @@ -307,7 +307,7 @@ fn type_trailing_braced_mac_call(mut ty: &ast::Ty) -> Option<&ast::MacCall> { | ast::TyKind::Pat(..) | ast::TyKind::FieldOf(..) | ast::TyKind::View(..) - | ast::TyKind::GcaMacro(..) + | ast::TyKind::Gca(..) | ast::TyKind::Dummy | ast::TyKind::Err(..) => break None, } diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index 9dc55686c7494..05f16b981f320 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -1113,7 +1113,7 @@ macro_rules! common_visitor_and_walkers { visit_visitable!(vis, bytes), ExprKind::UnsafeBinderCast(kind, expr, ty) => visit_visitable!(vis, kind, expr, ty), - ExprKind::GcaMacro(expr) => + ExprKind::Gca(expr) => visit_visitable!(vis, expr), ExprKind::Err(_guar) => {} ExprKind::Dummy => {} diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 26e3f88614efc..93c9b218c17d2 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -544,7 +544,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span), - ExprKind::GcaMacro(expr) => { + ExprKind::Gca(expr) => { let e = self.emit_bad_gca_macro(e.span, expr, "expression"); hir::ExprKind::Err(e) } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index a452c5f11285d..3a2d1768d5a66 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -378,6 +378,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { tcx.sess, tcx.features(), tcx.registered_attr_tools(()), + tcx.registered_lint_tools(()), ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, ), } @@ -1463,7 +1464,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let ct = self.arena.alloc(ct); return GenericArg::Const(ct.try_as_ambig_ct().unwrap()); } - TyKind::GcaMacro(expr) if self.tcx.features().gca() => { + TyKind::Gca(expr) if self.tcx.features().gca() => { let ct = match self.can_lower_expr_to_const_arg_direct( expr, self.direct_const_arg_context_enabled_by_gca_macro(), @@ -1782,7 +1783,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let fields = self.arena.alloc_slice(fields); hir::TyKind::View(ty, fields) } - TyKind::GcaMacro(expr) => { + TyKind::Gca(expr) => { let e = self.emit_bad_gca_macro(t.span, expr, "type"); hir::TyKind::Err(e) } @@ -2892,7 +2893,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::ConstBlock(_) if context.contains(DirectConstArgContext::CONST_BLOCK) => { Ok(()) } - ExprKind::GcaMacro(_) if context.contains(DirectConstArgContext::GCA_MACRO) => { + ExprKind::Gca(_) if context.contains(DirectConstArgContext::GCA_MACRO) => { // Always report this as able to be represented directly. If it turns out not to be, // `lower_expr_to_const_arg_direct` will report an error. Ok(()) @@ -3073,9 +3074,9 @@ impl<'hir> LoweringContext<'_, 'hir> { span, } } - ExprKind::GcaMacro(expr) => { + ExprKind::Gca(expr) => { // `can_lower_expr_to_const_arg_direct` always returns success upon encountering a - // ExprKind::GcaMacro, which effectively forces the expression to be lowered as a + // `ExprKind::Gca`, which effectively forces the expression to be lowered as a // direct arg. If it actually turns out to not be possible, emit an error instead. match self.can_lower_expr_to_const_arg_direct( expr, diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index a312865619d24..869bab20135b7 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -1468,8 +1468,8 @@ impl<'a> State<'a> { self.print_view(fields); self.pclose(); } - ast::TyKind::GcaMacro(expr) => { - self.word_nbsp("core::gca!"); + ast::TyKind::Gca(expr) => { + self.word("k#gca"); self.popen(); self.print_expr(expr, FixupContext::default()); self.pclose(); diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index 51e3988577827..03eb52150b131 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -882,8 +882,8 @@ impl<'a> State<'a> { self.word("/*DUMMY*/"); self.pclose(); } - ast::ExprKind::GcaMacro(expr) => { - self.word_nbsp("core::gca!"); + ast::ExprKind::Gca(expr) => { + self.word("k#gca"); self.popen(); self.print_expr(expr, FixupContext::default()); self.pclose() diff --git a/compiler/rustc_attr_ir/src/lint.rs b/compiler/rustc_attr_ir/src/lint.rs index 2dafadf4cb2a9..7ce2c000419e1 100644 --- a/compiler/rustc_attr_ir/src/lint.rs +++ b/compiler/rustc_attr_ir/src/lint.rs @@ -1,6 +1,6 @@ +use rustc_lint_defs::LintName; use rustc_macros::{Decodable, Encodable, PrintAttribute, StableHash}; use rustc_span::{Span, Symbol, sym}; -use rustc_structures::LintName; use crate::{HashIgnoredAttrId, PrintAttribute}; @@ -45,7 +45,12 @@ impl LintCheckKind { /// ``` #[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)] pub struct LintCheck { - pub lint_name: LintName, + /// The full normalized lint name of an existing lint, including the tool name. + /// This may not be what the user wrote down, in case of renamed lints the new lint name is here. + /// The above implies that `LintStore::find_lints` is guaranteed to find this lint using this symbol. + /// + /// For example, `single_use_lifetime` is changed to `single_use_lifetimes`. + pub lint_name_normalized: LintName, pub kind: LintCheckKind, pub reason: Option, /// Needed by `LintExpectationId` to track fulfilled expectations @@ -61,5 +66,4 @@ pub struct LintCheck { /// #[deny(foo::bar::baz)] /// ^^^^^^^^^^^^^ pub lint_span: Span, - pub tool_span: Option, } diff --git a/compiler/rustc_attr_ir/src/pretty_printing.rs b/compiler/rustc_attr_ir/src/pretty_printing.rs index 04e5b94921860..61c2cb838bf27 100644 --- a/compiler/rustc_attr_ir/src/pretty_printing.rs +++ b/compiler/rustc_attr_ir/src/pretty_printing.rs @@ -11,13 +11,11 @@ use rustc_ast::token::{CommentKind, DocFragmentKind}; use rustc_ast::{AttrId, AttrStyle, IntTy, UintTy}; use rustc_ast_pretty::pp::Printer; use rustc_data_structures::fx::FxIndexMap; -use rustc_lint_defs::{Reflectiveness, ToolOptions}; +use rustc_lint_defs::{LintName, Reflectiveness, ToolOptions}; use rustc_span::def_id::DefId; use rustc_span::hygiene::Transparency; use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol}; -use rustc_structures::{ - CollapseMacroDebuginfo, CrateType, Limit, LintName, NativeLibKind, SanitizerSet, -}; +use rustc_structures::{CollapseMacroDebuginfo, CrateType, Limit, NativeLibKind, SanitizerSet}; use thin_vec::ThinVec; use crate::HashIgnoredAttrId; diff --git a/compiler/rustc_attr_parsing/src/attributes/lint.rs b/compiler/rustc_attr_parsing/src/attributes/lint.rs index 45cbcf4664404..ae37d5d4b41be 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint.rs @@ -1,14 +1,19 @@ +use rustc_ast::join_path_syms; use rustc_attr_ir::AttributeKind; use rustc_attr_ir::lint::{LintCheck, LintCheckKind}; use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target}; -use rustc_lint_defs::builtin::UNUSED_ATTRIBUTES; -use rustc_span::sym; -use rustc_structures::LintName; +use rustc_lint_defs::builtin::{RENAMED_AND_REMOVED_LINTS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES}; +use rustc_lint_defs::{CheckLintNameResult, LintId, LintName}; +use rustc_span::{Span, Symbol, sym}; use thin_vec::ThinVec; use crate::attributes::{AcceptMapping, AttributeParser, AttributeStability}; use crate::context::{AcceptContext, ExpectStringLiteral, FinalizeContext}; -use crate::diagnostics::{MalformedLintAttributeInput, MalformedLintAttributeInputHelp}; +use crate::diagnostics::{ + DeprecatedLintName, MalformedLintAttributeInput, MalformedLintAttributeInputHelp, RemovedLint, + RenamedLint, RenamedLintSuggestion, UnknownLint, UnknownLintSuggestion, + UnknownToolInScopedLint, +}; use crate::parser::{ArgParser, MetaItemOrLitParser}; use crate::target_checking::AllowedTargets; use crate::target_checking::Policy::{Allow, Warn}; @@ -28,6 +33,7 @@ impl LintParser { fn parse(&mut self, kind: LintCheckKind, cx: &mut AcceptContext<'_, '_>, args: &ArgParser) { let attr_span = cx.attr_span; let attr_id = cx.attr_id.expect("no `AttrId` for lint attribute"); + let mut has_invalid_reason_key = false; if let Some(list) = cx.expect_list(args, cx.attr_span) { let mut parsers = list.sub_parsers(); @@ -37,16 +43,16 @@ impl LintParser { let p = parsers.last()?.meta_item()?; let nv = p.args().as_name_value()?; if !p.path().word_is(sym::reason) { - // FIXME: We should recommend `reason` here + has_invalid_reason_key = true; cx.emit_err(MalformedLintAttributeInput { span: p.span(), - help: MalformedLintAttributeInputHelp::Other { kind: kind.sym() }, + help: MalformedLintAttributeInputHelp::Reason { + reason_span: p.path().span(), + }, kind: kind.sym(), }); - } else { - parsers = &parsers[..(parsers.len() - 1)]; } - + parsers = &parsers[..(parsers.len() - 1)]; let reason = nv.expect_string_literal(cx)?; reason }; @@ -55,21 +61,47 @@ impl LintParser { match item { MetaItemOrLitParser::MetaItemParser(p) => { match p.args() { - ArgParser::NoArgs => self.lints.push(LintCheck { - lint_name: LintName::new( - p.path().0.segments.iter().map(|s| s.ident.name), - ), - kind, - attr_id, - reason, - attr_span, - lint_span: p.span(), - tool_span: if let [tool, _, ..] = &*p.path().0.segments { - Some(tool.span()) + ArgParser::NoArgs => { + let (tool, lint_name) = match &*p.path().0.segments { + [] => unreachable!(), + [lint_name] => (None, lint_name.ident.name), + [tool, lint_name] => (Some(tool.ident), lint_name.ident.name), + // Not reachable for any builtin lints, + // but reachable using `register_tool`. + [tool, multi_segment_lint_name @ ..] => ( + Some(tool.ident), + Symbol::intern(&join_path_syms( + multi_segment_lint_name + .iter() + .map(|seg| seg.ident.name), + )), + ), + }; + let lint_name = + LintName { tool: tool.map(|tool| tool.name), name: lint_name }; + + let lint_name_normalized = if let Some((_lint_ids, new_lint_name)) = + LintParser::check_lint_name( + lint_name, + tool.map(|tool| tool.span), + p.span(), + cx, + ) { + new_lint_name } else { - None - }, - }), + // Discard lint attributes with unknown lints in them + continue; + }; + + self.lints.push(LintCheck { + lint_name_normalized, + lint_span: p.span(), + kind, + attr_id, + reason, + attr_span, + }) + } // We've found a `reason = "reason"` but we're not the last element. ArgParser::NameValue(nv) if p.path().word_is(sym::reason) => { cx.emit_err(diagnostics::MalformedAttribute { @@ -110,7 +142,7 @@ impl LintParser { // FIXME(164898) Lint attributes are unique because they're parsed twice with `ShouldEmit::ErrorsAndLints` // To avoid emitting the lint twice, we check `cx.parse_filter`, which will be `Some` during AST linting - if parsers.is_empty() && cx.parse_filter.is_none() { + if parsers.is_empty() && cx.parse_filter.is_none() && !has_invalid_reason_key { cx.emit_lint( UNUSED_ATTRIBUTES, diagnostics::Unused { @@ -126,6 +158,133 @@ impl LintParser { } } } + + fn check_lint_name<'sess>( + lint_name: LintName, + tool_span: Option, + lint_span: Span, + cx: &mut AcceptContext<'_, 'sess>, + ) -> Option<(&'sess [LintId], LintName)> { + let lint_result = cx + .sess + .lint_store + .as_ref() + .unwrap() + .check_attribute_lint_name(lint_name, cx.lint_tools.unwrap()); + + // FIXME(164898) Lint attributes are parsed twice, once on the AST and once on the HIR + // Both times emit diagnostics, for historic reasons + // We only want to emit these lints once, on the HIR. + // On the AST the parse filter will be `Some` (since we're only parsing lint attributes then) + // #164898 will fix this, after that PR this check can be removed + let should_lint = cx.parse_filter.is_none(); + + let (ids, name) = match lint_result { + CheckLintNameResult::Ok(ids) => (ids, lint_name), + + CheckLintNameResult::Tool(ids, new_lint_name) => { + let name = match new_lint_name { + None => lint_name, + Some(replacement) => { + if should_lint { + cx.emit_lint( + RENAMED_AND_REMOVED_LINTS, + DeprecatedLintName { + lint_name, + suggestion: lint_span, + replacement, + }, + lint_span, + ); + } + replacement + } + }; + (ids, name) + } + + CheckLintNameResult::MissingTool => { + // If `MissingTool` is returned, then either the lint does not + // exist in the tool or the code was not compiled with the tool and + // therefore the lint was never added to the `LintStore`. To detect + // this is the responsibility of the lint tool. + return None; + } + + CheckLintNameResult::NoTool(tool_name) => { + if should_lint { + cx.emit_err(UnknownToolInScopedLint { + span: Some(tool_span.unwrap()), + tool_name, + lint_name, + is_nightly_build: cx.sess.is_nightly_build(), + }); + } + return None; + } + + CheckLintNameResult::Renamed(replacement) => { + if should_lint { + let suggestion = + RenamedLintSuggestion::WithSpan { suggestion: lint_span, replacement }; + cx.emit_lint( + RENAMED_AND_REMOVED_LINTS, + RenamedLint { name: lint_name, replacement, suggestion }, + lint_span, + ); + } + + // If this lint was renamed, apply the new lint instead of ignoring the + // attribute. Ignore any errors or warnings that happen because the new + // name is inaccurate. + let replace_check = cx + .sess + .lint_store + .as_ref() + .unwrap() + .check_attribute_lint_name(replacement, cx.lint_tools.unwrap()); + let (CheckLintNameResult::Ok(ids) | CheckLintNameResult::Tool(ids, _)) = + replace_check + else { + panic!( + "renamed lint does not exist: {lint_name} => {replacement}\n{replace_check:?}" + ); + }; + + (ids, replacement) + } + + CheckLintNameResult::Removed(reason) => { + if should_lint { + cx.emit_lint( + RENAMED_AND_REMOVED_LINTS, + RemovedLint { name: lint_name, reason }, + lint_span, + ); + } + return None; + } + + CheckLintNameResult::NoLint(suggestion) => { + if should_lint { + let suggestion = suggestion.map(|(replacement, from_rustc)| { + UnknownLintSuggestion::WithSpan { + suggestion: lint_span, + replacement, + from_rustc, + } + }); + cx.emit_lint( + UNKNOWN_LINTS, + UnknownLint { name: lint_name, suggestion }, + lint_span, + ); + } + return None; + } + }; + Some((ids, name)) + } } impl AttributeParser for LintParser { diff --git a/compiler/rustc_attr_parsing/src/diagnostics.rs b/compiler/rustc_attr_parsing/src/diagnostics.rs index 12b2fe8cff6e8..a63238592dbc6 100644 --- a/compiler/rustc_attr_parsing/src/diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/diagnostics.rs @@ -5,6 +5,7 @@ use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, E0264, Level, MultiSpan, }; +use rustc_lint_defs::LintName; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Ident, Span, Symbol}; use rustc_target::spec::TargetTuple; @@ -2233,6 +2234,16 @@ pub(crate) struct MalformedLintAttributeInput { pub(crate) enum MalformedLintAttributeInputHelp { #[help("try using `#[{$kind}({$sym})]`")] StrLit { sym: Symbol, kind: Symbol }, + #[suggestion( + "to provide a reason, use `reason = \"\"`", + code = "reason", + applicability = "machine-applicable", + style = "verbose" + )] + Reason { + #[primary_span] + reason_span: Span, + }, #[help("for example, write `#[{$kind}(dead_code)]` for `dead_code`")] Other { kind: Symbol }, } @@ -2293,3 +2304,84 @@ pub(crate) enum BuiltinUnusedDocCommentSub { #[help("use `/* */` for a plain comment")] BlockHelp, } + +#[derive(Diagnostic)] +#[diag("lint name `{$lint_name}` is deprecated and may not have an effect in the future")] +pub(crate) struct DeprecatedLintName { + pub lint_name: LintName, + #[suggestion("change it to", code = "{replacement}", applicability = "machine-applicable")] + pub suggestion: Span, + pub replacement: LintName, +} + +#[derive(Diagnostic)] +#[diag("unknown tool name `{$tool_name}` found in scoped lint: `{$lint_name}`", code = E0710)] +pub(crate) struct UnknownToolInScopedLint { + #[primary_span] + pub span: Option, + pub tool_name: Symbol, + pub lint_name: LintName, + #[help("add `#![register_tool({$tool_name})]` to the crate root")] + pub is_nightly_build: bool, +} + +#[derive(Diagnostic)] +#[diag("lint `{$name}` has been renamed to `{$replacement}`")] +pub(crate) struct RenamedLint { + pub name: LintName, + pub replacement: LintName, + #[subdiagnostic] + pub suggestion: RenamedLintSuggestion, +} + +#[derive(Subdiagnostic)] +pub enum RenamedLintSuggestion { + #[suggestion("use the new name", code = "{replacement}", applicability = "machine-applicable")] + WithSpan { + #[primary_span] + suggestion: Span, + replacement: LintName, + }, + #[help("use the new name `{$replacement}`")] + WithoutSpan { replacement: LintName }, +} + +#[derive(Diagnostic)] +#[diag("unknown lint: `{$name}`")] +pub(crate) struct UnknownLint { + pub name: LintName, + #[subdiagnostic] + pub suggestion: Option, +} + +#[derive(Subdiagnostic)] +pub enum UnknownLintSuggestion { + #[suggestion( + "{$from_rustc -> + [true] a lint with a similar name exists in `rustc` lints + *[false] did you mean + }", + code = "{replacement}", + applicability = "maybe-incorrect" + )] + WithSpan { + #[primary_span] + suggestion: Span, + replacement: LintName, + from_rustc: bool, + }, + #[help( + "{$from_rustc -> + [true] a lint with a similar name exists in `rustc` lints: `{$replacement}` + *[false] did you mean: `{$replacement}` + }" + )] + WithoutSpan { replacement: LintName, from_rustc: bool }, +} + +#[derive(Diagnostic)] +#[diag("lint `{$name}` has been removed: {$reason}")] +pub(crate) struct RemovedLint { + pub name: LintName, + pub reason: String, +} diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 4274c21ffd26f..8788e22a5b05c 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -41,6 +41,7 @@ pub struct EmitAttribute( /// context, through which all attributes can be lowered. pub struct AttributeParser<'sess> { pub(crate) attr_tools: Option<&'sess RegisteredTools>, + pub(crate) lint_tools: Option<&'sess RegisteredTools>, pub(crate) features: Option<&'sess Features>, pub(crate) sess: &'sess Session, pub(crate) should_emit: ShouldEmit, @@ -116,6 +117,7 @@ impl<'sess> AttributeParser<'sess> { features, should_emit, None, + None, ); assert!(parsed.len() <= 1); parsed.pop() @@ -158,8 +160,10 @@ impl<'sess> AttributeParser<'sess> { features: Option<&'sess Features>, should_emit: ShouldEmit, attr_tools: Option<&'sess RegisteredTools>, + lint_tools: Option<&'sess RegisteredTools>, ) -> Vec { - let mut p = AttributeParser { features, attr_tools, parse_filter, sess, should_emit }; + let mut p = + AttributeParser { features, attr_tools, lint_tools, parse_filter, sess, should_emit }; p.parse_attribute_list( attrs, target_span, @@ -237,7 +241,14 @@ impl<'sess> AttributeParser<'sess> { parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &I) -> T, template: &AttributeTemplate, ) -> T { - let mut parser = Self { features, attr_tools: None, parse_filter: None, sess, should_emit }; + let mut parser = Self { + features, + attr_tools: None, + lint_tools: None, + parse_filter: None, + sess, + should_emit, + }; let mut emit_lint = |lint_id: LintId, span: MultiSpan, kind: EmitAttribute| { sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0) }; @@ -280,11 +291,13 @@ impl<'sess> AttributeParser<'sess> { sess: &'sess Session, features: &'sess Features, attr_tools: &'sess RegisteredTools, + lint_tools: &'sess RegisteredTools, should_emit: ShouldEmit, ) -> Self { Self { features: Some(features), attr_tools: Some(attr_tools), + lint_tools: Some(lint_tools), parse_filter: None, sess, should_emit, diff --git a/compiler/rustc_attr_parsing/src/lib.rs b/compiler/rustc_attr_parsing/src/lib.rs index 009ea86b762b2..d2b8ac6cd2db1 100644 --- a/compiler/rustc_attr_parsing/src/lib.rs +++ b/compiler/rustc_attr_parsing/src/lib.rs @@ -119,7 +119,9 @@ pub use attributes::cfg_select::*; pub use attributes::crate_level::PREDEFINED_TOOLS; pub use attributes::util::{is_builtin_attr, parse_version}; pub use context::ShouldEmit; -pub use diagnostics::{DuplicateAttribute, ParsedDescription}; +pub use diagnostics::{ + DuplicateAttribute, ParsedDescription, RenamedLintSuggestion, UnknownLintSuggestion, +}; pub use interface::{AttributeParser, EmitAttribute}; pub use rustc_parse::parser::Recovery; pub use template::AttributeTemplate; diff --git a/compiler/rustc_builtin_macros/src/assert/context.rs b/compiler/rustc_builtin_macros/src/assert/context.rs index 799d2594152ae..64a2b2cd67dfa 100644 --- a/compiler/rustc_builtin_macros/src/assert/context.rs +++ b/compiler/rustc_builtin_macros/src/assert/context.rs @@ -320,7 +320,7 @@ impl<'cx, 'a> Context<'cx, 'a> { | ExprKind::Yeet(_) | ExprKind::Become(_) | ExprKind::Yield(_) - | ExprKind::GcaMacro(_) + | ExprKind::Gca(_) | ExprKind::UnsafeBinderCast(..) => {} } } diff --git a/compiler/rustc_builtin_macros/src/gca.rs b/compiler/rustc_builtin_macros/src/gca.rs deleted file mode 100644 index 9e117e06ea9fd..0000000000000 --- a/compiler/rustc_builtin_macros/src/gca.rs +++ /dev/null @@ -1,26 +0,0 @@ -use rustc_ast::ast; -use rustc_ast::tokenstream::TokenStream; -use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; -use rustc_span::Span; - -use crate::util::get_single_expr_from_tts; - -pub(crate) fn expand<'cx>( - cx: &'cx mut ExtCtxt<'_>, - span: Span, - tts: TokenStream, -) -> MacroExpanderResult<'cx> { - let ExpandResult::Ready(expr) = get_single_expr_from_tts(cx, span, tts, "gca!") else { - return ExpandResult::Retry(()); - }; - let expr = match expr { - Ok(expr) => expr, - Err(err) => return ExpandResult::Ready(DummyResult::any(span, err)), - }; - - ExpandResult::Ready(Box::new(base::MacEager { - expr: Some(cx.expr(span, ast::ExprKind::GcaMacro(expr.clone()))), - ty: Some(cx.ty(span, ast::TyKind::GcaMacro(expr))), - ..Default::default() - })) -} diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs index b2089f9b4567a..554a4579cb02d 100644 --- a/compiler/rustc_builtin_macros/src/lib.rs +++ b/compiler/rustc_builtin_macros/src/lib.rs @@ -40,7 +40,6 @@ mod eii; mod env; mod format; mod format_foreign; -mod gca; mod global_allocator; mod iter; mod log_syntax; @@ -87,7 +86,6 @@ pub fn register_builtin_macros(resolver: &mut dyn ResolverExpand) { file: source_util::expand_file, format_args: format::expand_format_args, format_args_nl: format::expand_format_args_nl, - gca: gca::expand, global_asm: asm::expand_global_asm, include: source_util::expand_include, include_bytes: source_util::expand_include_bytes, diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index d53c3de10e923..d20fc611e8c56 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -44,7 +44,7 @@ use rustc_interface::passes::collect_crate_types; use rustc_interface::util::{self, get_codegen_backend}; use rustc_interface::{Linker, create_and_enter_global_ctxt, interface, passes}; use rustc_lint::unerased_lint_store; -use rustc_lint_defs::{Lint, LintId}; +use rustc_lint_defs::{Lint, LintId, LintName}; use rustc_metadata::creader::MetadataLoader; use rustc_metadata::locator; use rustc_middle::ty::TyCtxt; @@ -59,7 +59,7 @@ use rustc_session::output::{ErrorOutputType, OutputType, invalid_output_for_targ use rustc_session::{EarlyDiagCtxt, Session, config}; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::{DUMMY_SP, FileName}; -use rustc_structures::{CrateType, LintName}; +use rustc_structures::CrateType; use rustc_target::json::ToJson; use rustc_target::spec::{Target, TargetTuple}; use tracing::trace; diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index e60b1829e56de..5486e7ed77079 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -2238,6 +2238,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { Some(self.cx.ecfg.features), ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, Some(self.cx.resolver.registered_attr_tools()), + Some(self.cx.resolver.registered_lint_tools()), ); } diff --git a/compiler/rustc_hir_typeck/src/diagnostics.rs b/compiler/rustc_hir_typeck/src/diagnostics.rs index a1e5bf711a674..c69839aae011e 100644 --- a/compiler/rustc_hir_typeck/src/diagnostics.rs +++ b/compiler/rustc_hir_typeck/src/diagnostics.rs @@ -1402,3 +1402,15 @@ pub(crate) struct DelegationInvalidAdtForReturnWrapping { pub span: Span, pub adt_name: String, } + +#[derive(Diagnostic)] +#[diag("field `{$field}` cannot be accessed")] +pub(crate) struct FieldNotPartOfView<'tcx> { + pub(crate) field: Symbol, + #[primary_span] + pub(crate) span: Span, + #[note("this expression has type {$ty}, of which only {$fields} can be accessed")] + pub(crate) note: Span, + pub(crate) ty: Ty<'tcx>, + pub(crate) fields: DiagSymbolList, +} diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 7356f8f94615b..98f0d92c382c8 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -6,6 +6,7 @@ //! See [`rustc_hir_analysis::check`] for more context on type checking in general. use std::borrow::Cow; +use std::ops::ControlFlow; use rustc_abi::{FIRST_VARIANT, FieldIdx}; use rustc_ast as ast; @@ -20,7 +21,9 @@ use rustc_errors::{ }; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; +use rustc_hir::def_id::DefId; use rustc_hir::{ExprKind, HirId, QPath, is_range_literal}; +use rustc_hir_analysis::autoderef::Autoderef; use rustc_hir_analysis::diagnostics::NoVariantNamed; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _; use rustc_infer::infer::{self, RegionVariableOrigin}; @@ -28,7 +31,9 @@ use rustc_infer::traits::WellFormedLoc; use rustc_infer::traits::query::NoSolution; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::{self, AdtKind, ConstKind, GenericArgs, Ty, TypeVisitableExt, Unnormalized}; +use rustc_middle::ty::{ + self, AdtKind, ConstKind, FieldInfo, GenericArgs, Ty, TypeVisitableExt, Unnormalized, +}; use rustc_session::diagnostics::feature_err; use rustc_span::hygiene::DesugaringKind; use rustc_span::{Ident, Span, Spanned, Symbol, bug, kw, span_bug, sym}; @@ -42,9 +47,9 @@ use crate::coercion::CoerceMany; use crate::diagnostics::{ AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr, BaseExpressionDoubleDotRemove, CantDereference, DelegationInvalidAdtForReturnWrapping, - ExprParenthesesNeeded, FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct, - NakedAsmOutsideNakedFn, NoFieldOnVariant, ReturnLikeStatementKind, StructExprNonExhaustive, - YieldExprOutsideOfCoroutine, + ExprParenthesesNeeded, FieldMultiplySpecifiedInInitializer, FieldNotPartOfView, + FunctionalRecordUpdateOnNonStruct, NakedAsmOutsideNakedFn, NoFieldOnVariant, + ReturnLikeStatementKind, StructExprNonExhaustive, YieldExprOutsideOfCoroutine, }; use crate::op::contains_let_in_chain; use crate::{ @@ -2326,48 +2331,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut autoderef = self.autoderef(expr.span, base_ty); while let Some((deref_base_ty, _)) = autoderef.next() { debug!("deref_base_ty: {:?}", deref_base_ty); - match deref_base_ty.kind() { - ty::Adt(base_def, args) if !base_def.is_enum() => { - debug!("struct named {:?}", deref_base_ty); - // we don't care to report errors for a struct if the struct itself is tainted - if let Err(guar) = base_def.non_enum_variant().has_errors() { - return Ty::new_error(self.tcx(), guar); - } - - let (ident, def_scope) = - self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.mod_id); - - if let Some((idx, field)) = self.find_adt_field(*base_def, ident) { - self.write_field_index(expr.hir_id, idx); - - let adjustments = self.adjust_steps(&autoderef); - if field.vis.is_accessible_from(def_scope, self.tcx) { - self.apply_adjustments(base, adjustments); - self.register_predicates(autoderef.into_obligations()); - - self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None); - return self.field_ty(expr.span, field, *args); - } - - // The field is not accessible, fall through to error reporting. - private_candidate = Some((adjustments, base_def.did())); - } + match self.check_field_access_for_deref_step( + expr, + base, + field, + &autoderef, + deref_base_ty, + base_ty, + ) { + ControlFlow::Continue(private_candidate_) => { + private_candidate = private_candidate.xor(private_candidate_); } - ty::Tuple(tys) => { - if let Ok(index) = field.as_str().parse::() { - if field.name == sym::integer(index) { - if let Some(&field_ty) = tys.get(index) { - let adjustments = self.adjust_steps(&autoderef); - self.apply_adjustments(base, adjustments); - self.register_predicates(autoderef.into_obligations()); - - self.write_field_index(expr.hir_id, FieldIdx::from_usize(index)); - return field_ty; - } - } - } + ControlFlow::Break(ty) => { + self.register_predicates(autoderef.into_obligations()); + return ty; } - _ => {} } } // We failed to check the expression, report an error. @@ -2480,6 +2458,104 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ty::new_error(self.tcx(), guar) } + fn check_field_access_for_deref_step( + &self, + expr: &'tcx rustc_hir::Expr<'tcx>, + base: &'tcx rustc_hir::Expr<'tcx>, + field: Ident, + autoderef: &Autoderef<'_, 'tcx>, + deref_base_ty: Ty<'tcx>, + base_ty: Ty<'tcx>, + ) -> ControlFlow, Option<(Vec>, DefId)>> { + let (field_ty, field_idx) = match deref_base_ty.kind() { + ty::Adt(base_def, args) | ty::View(base_def, args, _) if !base_def.is_enum() => { + debug!("struct named {:?}", deref_base_ty); + // we don't care to report errors for a struct if the struct itself is tainted + if let Err(guar) = base_def.non_enum_variant().has_errors() { + return ControlFlow::Break(Ty::new_error(self.tcx(), guar)); + } + + let (ident, def_scope) = + self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.mod_id); + + let Some((idx, field)) = self.find_adt_field(*base_def, ident) else { + return ControlFlow::Continue(None); + }; + + if !field.vis.is_accessible_from(def_scope, self.tcx) { + // The field is not accessible, fall through to error reporting. + let adjustments = self.adjust_steps(autoderef); + return ControlFlow::Continue(Some((adjustments, base_def.did()))); + } + + self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None); + + (self.field_ty(expr.span, field, *args), idx) + } + + ty::Tuple(tys) => { + let Ok(index) = field.as_str().parse::() else { + return ControlFlow::Continue(None); + }; + + if field.name != sym::integer(index) { + return ControlFlow::Continue(None); + } + + let Some(&field_ty) = tys.get(index) else { + return ControlFlow::Continue(None); + }; + + (field_ty, FieldIdx::from_usize(index)) + } + + _ => return ControlFlow::Continue(None), + }; + + if let ty::View(_, _, fields) = deref_base_ty.kind() { + // check that the field we are accessing is part of the view + let tuple_elems = match fields.kind() { + ty::Tuple(fields) => fields, + // FIXME(scrabsha): can we still have inferred views? + _ => bug!("malformed view type viewed field set"), + }; + let extract_frt = |ty: Ty<'tcx>| -> FieldInfo<_> { + match ty.kind() { + ty::Adt(base_def_, args_) + if let Some(frt) = + base_def_.field_representing_type_info(self.tcx(), *args_) => + { + // sanity check: view types on enums are not a thing. + debug_assert!(frt.variant.is_none()); + frt + } + + _ => bug!("malformed view type viewed field set"), + } + }; + + let mut field_idxs = tuple_elems.iter().map(extract_frt).map(|field| field.field_idx); + if field_idxs.all(|viewed_idx| viewed_idx != field_idx) { + let fields = tuple_elems.iter().map(extract_frt).map(|frt| frt.name).collect(); + let guar = self.tcx.dcx().emit_err(FieldNotPartOfView { + field: field.name, + span: field.span, + fields, + note: base.span, + ty: base_ty, + }); + return ControlFlow::Break(Ty::new_error(self.tcx, guar)); + } + } + + let adjustments = self.adjust_steps(autoderef); + self.apply_adjustments(base, adjustments); + + self.write_field_index(expr.hir_id, field_idx); + + ControlFlow::Break(field_ty) + } + fn check_expr_index( &self, base: &'tcx hir::Expr<'tcx>, diff --git a/compiler/rustc_interface/src/limits.rs b/compiler/rustc_interface/src/limits.rs index 2027ae7ad4bfd..b72d813fbef26 100644 --- a/compiler/rustc_interface/src/limits.rs +++ b/compiler/rustc_interface/src/limits.rs @@ -39,6 +39,7 @@ pub fn get_limits(krate_attrs: &[ast::Attribute], sess: &Session, features: &Fea // So, no lints here to avoid duplicates. ShouldEmit::EarlyFatal { also_emit_lints: false }, None, + None, ); let attrs = &attrs; Limits { diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index da0c8a195cf1a..dc676b16d0745 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -19,8 +19,8 @@ use rustc_hir::def_id::{CrateNum, DefId}; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_hir::{Pat, PatKind}; use rustc_lint_defs::{ - FutureIncompatibleInfo, Lint, LintExpectationId, LintId, StableLintExpectationId, - UnstableLintExpectationId, + CheckLintNameResult, FutureIncompatibleInfo, Lint, LintExpectationId, LintId, LintName, + StableLintExpectationId, UnstableLintExpectationId, }; use rustc_middle::lint::{LevelSpec, StableLevelSpec, UnstableLevelSpec}; use rustc_middle::middle::privacy::EffectiveVisibilities; @@ -30,7 +30,6 @@ use rustc_middle::ty::{self, RegisteredTools, Ty, TyCtxt, TypingEnv, TypingMode, use rustc_session::{DynLintStore, Session}; use rustc_span::edit_distance::find_best_match_for_names; use rustc_span::{Ident, Span, Symbol, bug, sym}; -use rustc_structures::LintName; use tracing::debug; use self::TargetLint::*; @@ -90,6 +89,14 @@ impl DynLintStore for LintStore { rustc_session::LintGroup { name, lints, is_externally_loaded } })) } + + fn check_attribute_lint_name( + &self, + lint_name: LintName, + lint_tools: &RegisteredTools, + ) -> CheckLintNameResult<'_> { + self.check_lint_name(lint_name, lint_tools) + } } /// The target of the `by_name` map, which accounts for renaming/deprecation. @@ -124,29 +131,6 @@ struct LintGroup { depr: Option, } -#[derive(Debug)] -pub enum CheckLintNameResult<'a> { - Ok(&'a [LintId]), - /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name. - NoLint(Option<(LintName, bool)>), - /// The lint refers to a tool that has not been registered. - NoTool(Symbol), - /// The lint has been renamed to a new name. - Renamed(LintName), - /// The lint has been removed due to the given reason. - Removed(String), - - /// The lint is from a tool. The `LintId` will be returned as if it were a - /// rustc lint. The `Option` indicates if the lint has been - /// renamed. - Tool(&'a [LintId], Option), - - /// The lint is from a tool. Either the lint does not exist in the tool or - /// the code was not compiled with the tool and therefore the lint was - /// never added to the `LintStore`. - MissingTool, -} - impl LintStore { pub fn new() -> LintStore { LintStore { diff --git a/compiler/rustc_lint/src/diagnostics.rs b/compiler/rustc_lint/src/diagnostics.rs index b10cd5b4cf6d7..e9ad23b98c48d 100644 --- a/compiler/rustc_lint/src/diagnostics.rs +++ b/compiler/rustc_lint/src/diagnostics.rs @@ -2,6 +2,7 @@ use std::num::NonZero; use rustc_attr_ir::find_attr; +use rustc_attr_parsing::{RenamedLintSuggestion, UnknownLintSuggestion}; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::codes::*; use rustc_errors::formatting::DiagMessageAddArg; @@ -12,13 +13,13 @@ use rustc_errors::{ use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::Visitor; +use rustc_lint_defs::LintName; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_middle::ty::inhabitedness::InhabitedPredicate; use rustc_middle::ty::{Clause, PolyExistentialTraitRef, Ty, TyCtxt}; use rustc_session::Session; use rustc_span::edition::Edition; use rustc_span::{Ident, Span, Symbol, sym}; -use rustc_structures::LintName; use crate::LateContext; use crate::builtin::{InitError, ShorthandAssocTyCollector, TypeAliasBounds}; @@ -66,17 +67,6 @@ impl Subdiagnostic for OverruledAttributeSub { } } -#[derive(Diagnostic)] -#[diag("unknown tool name `{$tool_name}` found in scoped lint: `{$lint_name}`", code = E0710)] -pub(crate) struct UnknownToolInScopedLint { - #[primary_span] - pub span: Option, - pub tool_name: Symbol, - pub lint_name: LintName, - #[help("add `#![register_tool({$tool_name})]` to the crate root")] - pub is_nightly_build: bool, -} - #[derive(Diagnostic)] #[diag("functions generic over types or consts must be mangled")] pub(crate) struct BuiltinNoMangleGeneric { @@ -1412,15 +1402,6 @@ pub(crate) struct OverruledAttributeLint<'a> { pub sub: OverruledAttributeSub, } -#[derive(Diagnostic)] -#[diag("lint name `{$lint_name}` is deprecated and may not have an effect in the future")] -pub(crate) struct DeprecatedLintName { - pub lint_name: LintName, - #[suggestion("change it to", code = "{replacement}", applicability = "machine-applicable")] - pub suggestion: Span, - pub replacement: LintName, -} - #[derive(Diagnostic)] #[diag("lint name `{$lint_name}` is deprecated and may not have an effect in the future")] #[help("change it to {$replacement}")] @@ -1431,27 +1412,6 @@ pub(crate) struct DeprecatedLintNameFromCommandLine { pub requested_level: RequestedLevel, } -#[derive(Diagnostic)] -#[diag("lint `{$name}` has been renamed to `{$replacement}`")] -pub(crate) struct RenamedLint { - pub name: LintName, - pub replacement: LintName, - #[subdiagnostic] - pub suggestion: RenamedLintSuggestion, -} - -#[derive(Subdiagnostic)] -pub(crate) enum RenamedLintSuggestion { - #[suggestion("use the new name", code = "{replacement}", applicability = "machine-applicable")] - WithSpan { - #[primary_span] - suggestion: Span, - replacement: LintName, - }, - #[help("use the new name `{$replacement}`")] - WithoutSpan { replacement: LintName }, -} - #[derive(Diagnostic)] #[diag("lint `{$lint_name}` has been renamed to `{$replacement}`")] pub(crate) struct RenamedLintFromCommandLine { @@ -1463,13 +1423,6 @@ pub(crate) struct RenamedLintFromCommandLine { pub requested_level: RequestedLevel, } -#[derive(Diagnostic)] -#[diag("lint `{$name}` has been removed: {$reason}")] -pub(crate) struct RemovedLint<'a> { - pub name: LintName, - pub reason: &'a str, -} - #[derive(Diagnostic)] #[diag("lint `{$lint_name}` has been removed: {$reason}")] pub(crate) struct RemovedLintFromCommandLine<'a> { @@ -1479,39 +1432,6 @@ pub(crate) struct RemovedLintFromCommandLine<'a> { pub requested_level: RequestedLevel, } -#[derive(Diagnostic)] -#[diag("unknown lint: `{$name}`")] -pub(crate) struct UnknownLint { - pub name: LintName, - #[subdiagnostic] - pub suggestion: Option, -} - -#[derive(Subdiagnostic)] -pub(crate) enum UnknownLintSuggestion { - #[suggestion( - "{$from_rustc -> - [true] a lint with a similar name exists in `rustc` lints - *[false] did you mean - }", - code = "{replacement}", - applicability = "maybe-incorrect" - )] - WithSpan { - #[primary_span] - suggestion: Span, - replacement: LintName, - from_rustc: bool, - }, - #[help( - "{$from_rustc -> - [true] a lint with a similar name exists in `rustc` lints: `{$replacement}` - *[false] did you mean: `{$replacement}` - }" - )] - WithoutSpan { replacement: LintName, from_rustc: bool }, -} - #[derive(Diagnostic)] #[diag("unknown lint: `{$lint_name}`", code = E0602)] pub(crate) struct UnknownLintFromCommandLine { diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index fd9a4ee74f5d7..1335c2156134f 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -5,7 +5,9 @@ use rustc_ast::CRATE_NODE_ID; use rustc_attr_ir::lint::{LintCheck, LintCheckKind}; use rustc_attr_ir::target::{AstTarget, Target}; use rustc_attr_ir::{Attribute, DocAttribute, find_attr}; -use rustc_attr_parsing::{AttributeParser, Recovery, ShouldEmit}; +use rustc_attr_parsing::{ + AttributeParser, Recovery, RenamedLintSuggestion, ShouldEmit, UnknownLintSuggestion, +}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::unord::UnordSet; use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, MultiSpan, msg}; @@ -19,7 +21,8 @@ use rustc_lint_defs::builtin::{ UNFULFILLED_LINT_EXPECTATIONS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES, }; use rustc_lint_defs::{ - Level, Lint, LintExpectationId, LintId, StableLintExpectationId, UnstableLintExpectationId, + CheckLintNameResult, Level, Lint, LintExpectationId, LintId, LintName, StableLintExpectationId, + UnstableLintExpectationId, }; use rustc_middle::hir::nested_filter; use rustc_middle::lint::{ @@ -31,17 +34,14 @@ use rustc_middle::ty::{RegisteredTools, TyCtxt}; use rustc_session::Session; use rustc_span::def_id::CRATE_MOD_ID; use rustc_span::{AttrId, DUMMY_SP, Span, Symbol, sym}; -use rustc_structures::LintName; use tracing::{debug, instrument}; use crate::builtin::MISSING_DOCS; -use crate::context::{CheckLintNameResult, LintStore}; +use crate::context::LintStore; use crate::diagnostics::{ - CheckNameUnknownTool, DeprecatedLintName, DeprecatedLintNameFromCommandLine, - IgnoredUnlessCrateSpecified, OverruledAttribute, OverruledAttributeLint, OverruledAttributeSub, - RemovedLint, RemovedLintFromCommandLine, RenamedLint, RenamedLintFromCommandLine, - RenamedLintSuggestion, RequestedLevel, UnknownLint, UnknownLintFromCommandLine, - UnknownLintSuggestion, UnknownToolInScopedLint, UnsupportedGroup, + CheckNameUnknownTool, DeprecatedLintNameFromCommandLine, IgnoredUnlessCrateSpecified, + OverruledAttribute, OverruledAttributeLint, OverruledAttributeSub, RemovedLintFromCommandLine, + RenamedLintFromCommandLine, RequestedLevel, UnknownLintFromCommandLine, UnsupportedGroup, }; use crate::late::unerased_lint_store; @@ -704,6 +704,7 @@ where CRATE_NODE_ID, Some(self.features), ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, + None, Some(self.registered_lint_tools), ); self.add_hir_inner(&parsed, is_crate_node) @@ -728,13 +729,9 @@ where return; }; - let sess = self.sess; - - // FIXME: consider performing these checks in attribute parsing instead for (lint_index, lint_check) in lint_checks.into_iter().enumerate() { - let LintCheck { lint_name, kind, reason, attr_id, attr_span: _, lint_span, tool_span } = + let LintCheck { lint_name_normalized, lint_span, kind, reason, attr_id, attr_span: _ } = lint_check; - let LintName { tool, name: _ } = lint_name; let level = match kind { LintCheckKind::Allow => Level::Allow, @@ -749,105 +746,9 @@ where let lint_id = (level == Level::Expect) .then(|| self.provider.mk_lint_expectation_id(attr_id.attr_id, lint_index as u16)); - let lint_result = self.store.check_lint_name(lint_name, self.registered_lint_tools); - - let (ids, name): (_, LintName) = match lint_result { - CheckLintNameResult::Ok(ids) => (ids, lint_name), - - CheckLintNameResult::Tool(ids, new_lint_name) => { - let name = match new_lint_name { - None => lint_name, - Some(replacement) => { - self.emit_span_lint( - builtin::RENAMED_AND_REMOVED_LINTS, - lint_span.into(), - DeprecatedLintName { - lint_name, - suggestion: lint_span, - replacement, - }, - ); - replacement - } - }; - (ids, name) - } - - CheckLintNameResult::MissingTool => { - // If `MissingTool` is returned, then either the lint does not - // exist in the tool or the code was not compiled with the tool and - // therefore the lint was never added to the `LintStore`. To detect - // this is the responsibility of the lint tool. - continue; - } - - CheckLintNameResult::NoTool(tool_name) => { - sess.dcx().emit_err(UnknownToolInScopedLint { - span: Some(tool_span.unwrap()), - tool_name, - lint_name, - is_nightly_build: sess.is_nightly_build(), - }); - continue; - } - - CheckLintNameResult::Renamed(replacement) => { - if self.lint_added_lints { - let suggestion = - RenamedLintSuggestion::WithSpan { suggestion: lint_span, replacement }; - - self.emit_span_lint( - RENAMED_AND_REMOVED_LINTS, - lint_span.into(), - RenamedLint { name: lint_name, replacement, suggestion }, - ); - } - - // If this lint was renamed, apply the new lint instead of ignoring the - // attribute. Ignore any errors or warnings that happen because the new - // name is inaccurate. - let replace_check = - self.store.check_lint_name(replacement, self.registered_lint_tools); - let (CheckLintNameResult::Ok(ids) | CheckLintNameResult::Tool(ids, _)) = - replace_check - else { - panic!("renamed lint does not exist: {replacement} :{replace_check:?}"); - }; - - (ids, replacement) - } - - CheckLintNameResult::Removed(ref reason) => { - if self.lint_added_lints { - self.emit_span_lint( - RENAMED_AND_REMOVED_LINTS, - lint_span.into(), - RemovedLint { name: lint_name, reason }, - ); - } - continue; - } - - CheckLintNameResult::NoLint(suggestion) => { - if self.lint_added_lints { - let suggestion = suggestion.map(|(replacement, from_rustc)| { - UnknownLintSuggestion::WithSpan { - suggestion: lint_span, - replacement, - from_rustc, - } - }); - self.emit_span_lint( - UNKNOWN_LINTS, - lint_span.into(), - UnknownLint { name: lint_name, suggestion }, - ); - } - continue; - } - }; + let src = LintLevelSource::Node { name: lint_name_normalized, span: lint_span, reason }; + let ids = self.store.find_lints(lint_name_normalized).unwrap(); - let src = LintLevelSource::Node { name, span: lint_span, reason }; for &id in ids { if self.check_gated_lint(id, lint_span, false) { self.insert_spec(id, LevelSpec::new(level, lint_id, src)); @@ -869,7 +770,12 @@ where }; self.provider.push_expectation( expect_id, - LintExpectation::new(reason, lint_span, is_unfulfilled_lint_expectations, tool), + LintExpectation::new( + reason, + lint_span, + is_unfulfilled_lint_expectations, + lint_name_normalized.tool, + ), ); } } diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 971c75608f73e..d68e47d198769 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -139,7 +139,7 @@ use unused::*; #[rustfmt::skip] pub use builtin::MissingDoc; -pub use context::{CheckLintNameResult, EarlyContext, LateContext, LintContext, LintStore}; +pub use context::{EarlyContext, LateContext, LintContext, LintStore}; pub use early::diagnostics::DiagAndSess; pub use early::{EarlyCheckNode, check_ast_node}; pub use late::{check_crate, late_lint_mod, unerased_lint_store}; diff --git a/compiler/rustc_lint/src/tests.rs b/compiler/rustc_lint/src/tests.rs index b4f789564600d..78e94e0352624 100644 --- a/compiler/rustc_lint/src/tests.rs +++ b/compiler/rustc_lint/src/tests.rs @@ -1,7 +1,7 @@ #![allow(rustc::symbol_intern_string_literal)] +use rustc_lint_defs::LintName; use rustc_span::{Symbol, create_default_session_globals_then, sym}; -use rustc_structures::LintName; use crate::builtin::is_hexagon_register_span; diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 1e879da282b2d..9490143bc58b9 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -199,7 +199,7 @@ trait UnusedDelimLint { | Become(_) => true, Call(..) | MethodCall(_) | Let(..) | Field(..) | MacCall(_) | FormatArgs(_) => false, // `gca!()` is invalid in function/method argument position. - GcaMacro(_) => false, + Gca(_) => false, // don't lint for placeholder/error-recovery Underscore | Err(_) | Dummy => false, } diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 019bb098e99a2..e3366c518c7e3 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -7,6 +7,7 @@ use std::borrow::Cow; use std::fmt::Display; +pub use lint_name::LintName; use rustc_ast::attr::version::RustcVersion; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hash::{StableCompare, StableHash, StableHashCtxt, StableHasher}; @@ -21,6 +22,7 @@ pub use self::Level::*; use crate::Reflectiveness::{NonReflective, Reflective}; pub mod builtin; +mod lint_name; #[macro_export] macro_rules! pluralize { @@ -635,6 +637,29 @@ impl ToolOptions { pub type RegisteredTools = FxIndexMap; +#[derive(Debug)] +pub enum CheckLintNameResult<'a> { + Ok(&'a [LintId]), + /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name. + NoLint(Option<(LintName, bool)>), + /// The lint refers to a tool that has not been registered. + NoTool(Symbol), + /// The lint has been renamed to a new name. + Renamed(LintName), + /// The lint has been removed due to the given reason. + Removed(String), + + /// The lint is from a tool. The `LintId` will be returned as if it were a + /// rustc lint. The `Option` indicates if the lint has been + /// renamed. + Tool(&'a [LintId], Option), + + /// The lint is from a tool. Either the lint does not exist in the tool or + /// the code was not compiled with the tool and therefore the lint was + /// never added to the `LintStore`. + MissingTool, +} + /// Declares a static item of type `&'static Lint`. /// /// See for diff --git a/compiler/rustc_structures/src/lint.rs b/compiler/rustc_lint_defs/src/lint_name.rs similarity index 95% rename from compiler/rustc_structures/src/lint.rs rename to compiler/rustc_lint_defs/src/lint_name.rs index b76390c47ac4f..329ec6c62a1f4 100644 --- a/compiler/rustc_structures/src/lint.rs +++ b/compiler/rustc_lint_defs/src/lint_name.rs @@ -1,11 +1,10 @@ use std::fmt; -#[cfg(feature = "nightly")] use rustc_macros::{Decodable, Encodable, StableHash}; use rustc_span::{Symbol, sym}; #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)] -#[cfg_attr(feature = "nightly", derive(StableHash, Encodable, Decodable))] +#[derive(StableHash, Encodable, Decodable)] pub struct LintName { /// The lint's tool name, if present. pub tool: Option, @@ -82,7 +81,6 @@ impl fmt::Display for LintName { } } -#[cfg(feature = "nightly")] impl rustc_error_messages::IntoDiagArg for LintName { fn into_diag_arg( self, diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 94acf8e303a03..08ba9b132c89d 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -5,13 +5,12 @@ use rustc_data_structures::sorted_map::SortedMap; use rustc_errors::{Diag, Diagnostic, EmissionOverride, MultiSpan}; use rustc_hir::{HirId, ItemLocalId}; use rustc_lint_defs::{ - EditionFcw, FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId, + EditionFcw, FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId, LintName, StableLintExpectationId, UnstableLintExpectationId, builtin, }; use rustc_macros::{Decodable, Encodable, StableHash}; use rustc_session::Session; use rustc_span::{DUMMY_SP, ExpnKind, Span, Symbol, kw, sym}; -use rustc_structures::LintName; use tracing::instrument; use crate::ty::TyCtxt; diff --git a/compiler/rustc_middle/src/mir/statement.rs b/compiler/rustc_middle/src/mir/statement.rs index a53f51fc9512a..170886097b350 100644 --- a/compiler/rustc_middle/src/mir/statement.rs +++ b/compiler/rustc_middle/src/mir/statement.rs @@ -144,7 +144,7 @@ impl<'tcx> PlaceTy<'tcx> { } } else { match self_ty.kind() { - ty::Adt(adt_def, args) if !adt_def.is_enum() => { + ty::Adt(adt_def, args) | ty::View(adt_def, args, _) if !adt_def.is_enum() => { adt_def.non_enum_variant().fields[f].ty(tcx, *args) } ty::Closure(_, args) => Unnormalized::dummy( diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index cb26e7b14e0ff..43db79026f08a 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2598,6 +2598,41 @@ impl<'tcx> TyCtxt<'tcx> { } } + /// with `cfg(debug_assertions)`, assert that the encoded representation of viewed fields is + /// valid for a given ADT, and ICEs if not. + pub fn debug_assert_encoded_viewed_fields_compatible( + self, + base_def: AdtDef<'tcx>, + base_args: ty::GenericArgs<'tcx>, + fields: Ty<'tcx>, + ) { + if cfg!(debug_assertions) { + let base_ty = Ty::new_adt(self, base_def, base_args); + + let ty::Tuple(fields) = fields.kind() else { + bug!("incompatible encoded viewed fields type: {fields:?}"); + }; + + for field in *fields { + let frt_args = match field.kind() { + ty::Adt(def, args) + if def.flags().contains(ty::AdtFlags::IS_FIELD_REPRESENTING_TYPE) => + { + args + } + _ => bug!("malformed encoded viewed field type: {field:?}"), + }; + + let referred_ty = frt_args[0].as_type().expect("first FRT arg is type"); + + assert_eq!( + referred_ty, base_ty, + "viewed field ({referred_ty:?}) does not refer to the base type ({base_ty:?})" + ); + } + } + } + fn emit_bug_args_compatible( self, def_id: DefId, diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index a14dfbd995db1..1b97d7bb2c399 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -835,9 +835,6 @@ impl<'tcx> Ty<'tcx> { args: GenericArgs<'tcx>, fields: &[FieldIdx], ) -> Ty<'tcx> { - tcx.debug_assert_args_compatible(def.did(), args); - tcx.debug_assert_adt_def_kind_compatible(def); - let base = Ty::new_adt(tcx, def, args); let fields = fields @@ -845,6 +842,19 @@ impl<'tcx> Ty<'tcx> { .map(|field| Ty::new_field_representing_type(tcx, base, FIRST_VARIANT, *field)); let fields = Ty::new_tup_from_iter(tcx, fields); + Ty::new_encoded_view(tcx, def, args, fields) + } + + fn new_encoded_view( + tcx: TyCtxt<'tcx>, + def: AdtDef<'tcx>, + args: GenericArgs<'tcx>, + fields: Ty<'tcx>, + ) -> Ty<'tcx> { + tcx.debug_assert_args_compatible(def.did(), args); + tcx.debug_assert_adt_def_kind_compatible(def); + tcx.debug_assert_encoded_viewed_fields_compatible(def, args, fields); + tcx.interners.intern_view(def, args, fields) } @@ -974,6 +984,15 @@ impl<'tcx> rustc_type_ir::inherent::Ty> for Ty<'tcx> { Ty::new_adt(interner, adt_def, args) } + fn new_view( + interner: TyCtxt<'tcx>, + adt_def: ty::AdtDef<'tcx>, + args: ty::GenericArgs<'tcx>, + fields: Ty<'tcx>, + ) -> Self { + Ty::new_encoded_view(interner, adt_def, args, fields) + } + fn new_foreign(interner: TyCtxt<'tcx>, def_id: DefId) -> Self { Ty::new_foreign(interner, def_id) } diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 8c648bfee9f27..ade64d0a29c9d 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1383,6 +1383,8 @@ impl<'a> Parser<'a> { return Ok(expr); } Ok(this.mk_expr(this.prev_token.span, ExprKind::Underscore)) + } else if this.eat_forced_keyword_noexpect(kw::Gca) { + this.parse_expr_gca(lo) } else if this.eat_forced_keyword_noexpect(kw::OffsetOf) { this.parse_expr_offset_of(lo) } else if this.eat_forced_keyword_noexpect(kw::TypeAscribe) { @@ -1832,7 +1834,16 @@ impl<'a> Parser<'a> { self.maybe_recover_from_bad_qpath(expr) } - pub(crate) fn parse_expr_offset_of(&mut self, lo: Span) -> PResult<'a, Box> { + fn parse_expr_gca(&mut self, lo: Span) -> PResult<'a, Box> { + self.expect(exp!(OpenParen))?; + let expr = self.parse_expr()?; + self.expect(exp!(CloseParen))?; + let span = lo.to(self.prev_token.span); + self.psess.gated_spans.gate(sym::internal_syntax, span); + Ok(self.mk_expr(span, ExprKind::Gca(expr))) + } + + fn parse_expr_offset_of(&mut self, lo: Span) -> PResult<'a, Box> { self.expect(exp!(OpenParen))?; let container = self.parse_ty()?; @@ -1867,7 +1878,7 @@ impl<'a> Parser<'a> { Ok(self.mk_expr(span, ExprKind::OffsetOf(container, fields))) } - pub(crate) fn parse_expr_type_ascribe(&mut self, lo: Span) -> PResult<'a, Box> { + fn parse_expr_type_ascribe(&mut self, lo: Span) -> PResult<'a, Box> { self.expect(exp!(OpenParen))?; let expr = self.parse_expr()?; self.expect(exp!(Comma))?; @@ -1880,7 +1891,7 @@ impl<'a> Parser<'a> { Ok(self.mk_expr(span, ExprKind::Type(expr, ty))) } - pub(crate) fn parse_expr_unsafe_binder_cast( + fn parse_expr_unsafe_binder_cast( &mut self, lo: Span, kind: UnsafeBinderCastKind, @@ -4217,7 +4228,7 @@ impl MutVisitor for CondChecker<'_> { | ExprKind::IncludedBytes(_) | ExprKind::FormatArgs(_) | ExprKind::Err(_) - | ExprKind::GcaMacro(_) + | ExprKind::Gca(_) | ExprKind::Dummy => { // These would forbid any let expressions they contain already. } diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index f3e9dc00cd5ed..2f035530cc85c 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -423,6 +423,8 @@ impl<'a> Parser<'a> { self.parse_unsafe_binder_ty()? } else if self.eat_forced_keyword_noexpect(kw::FieldOf) { self.parse_ty_field_of(lo)? + } else if self.eat_forced_keyword_noexpect(kw::Gca) { + self.parse_ty_gca(lo)? } else if self.eat_forced_keyword_noexpect(kw::PatternType) { self.parse_pat_ty(lo)? } else if self.eat_forced_keyword_noexpect(kw::ViewType) { @@ -875,6 +877,14 @@ impl<'a> Parser<'a> { } } + fn parse_ty_gca(&mut self, lo: Span) -> PResult<'a, TyKind> { + self.expect(exp!(OpenParen))?; + let expr = self.parse_expr()?; + self.expect(exp!(CloseParen))?; + self.psess.gated_spans.gate(sym::internal_syntax, lo.to(self.prev_token.span)); + Ok(TyKind::Gca(expr)) + } + fn parse_pat_ty(&mut self, lo: Span) -> PResult<'a, TyKind> { self.expect(exp!(OpenParen))?; diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index a20dc90f72908..891908315b97c 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1339,8 +1339,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } fn check_lint_check(&self, hir_id: HirId, lints: &[LintCheck]) { - for LintCheck { lint_name, lint_span, .. } in lints { - if lint_name.is(sym::dead_code_pub_in_binary) { + for LintCheck { lint_name_normalized, lint_span, .. } in lints { + if lint_name_normalized.is(sym::dead_code_pub_in_binary) { if !self.tcx.crate_types().contains(&CrateType::Executable) { self.tcx.emit_node_span_lint( UNUSED_ATTRIBUTES, @@ -1354,7 +1354,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - if lint_name.is(sym::linker_messages) | lint_name.is(sym::linker_info) { + if lint_name_normalized.is(sym::linker_messages) + | lint_name_normalized.is(sym::linker_info) + { if hir_id == CRATE_HIR_ID && self .tcx diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 7698a92a29417..dfa06f2555f19 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -285,7 +285,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) { match self.typeck_results().expr_ty_adjusted(lhs).kind() { - ty::Adt(def, _) => { + ty::Adt(def, _) | ty::View(def, _, _) => { let index = self.typeck_results().field_index(hir_id); self.insert_def_id(def.non_enum_variant().fields[index].did); } diff --git a/compiler/rustc_passes/src/input_stats.rs b/compiler/rustc_passes/src/input_stats.rs index bdd300aee372a..58e2c9f5ccb1c 100644 --- a/compiler/rustc_passes/src/input_stats.rs +++ b/compiler/rustc_passes/src/input_stats.rs @@ -669,7 +669,7 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { If, While, ForLoop, Loop, Match, Closure, Block, Await, Move, Use, TryBlock, Assign, AssignOp, Field, Index, Range, Underscore, Path, AddrOf, Break, Continue, Ret, InlineAsm, FormatArgs, OffsetOf, MacCall, Struct, Repeat, Paren, Try, Yield, Yeet, - Become, IncludedBytes, Gen, UnsafeBinderCast, GcaMacro, Err, Dummy + Become, IncludedBytes, Gen, UnsafeBinderCast, Gca, Err, Dummy ] ); ast_visit::walk_expr(self, e) @@ -699,7 +699,7 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { CVarArgs, FieldOf, View, - GcaMacro, + Gca, Dummy, Err ] diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index 37068c3b55d6d..601245f9e9fec 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -177,6 +177,7 @@ impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> { &self.r.tcx.sess, self.r.features, self.r.tcx().registered_attr_tools(()), + self.r.tcx().registered_lint_tools(()), ShouldEmit::Nothing, ); let attrs = parser.parse_attribute_list( diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 3510c62d3651f..8c4e68fc09e3a 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -1080,7 +1080,7 @@ impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tc self.visit_ty(element_ty); self.resolve_anon_const(length, AnonConstKind::ArrayLength); } - TyKind::GcaMacro(expr) => self.resolve_anon_const_manual( + TyKind::Gca(expr) => self.resolve_anon_const_manual( true, AnonConstKind::ConstArg(IsRepeatExpr::No), |this| this.resolve_expr(expr, None), diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 195a370707497..e7b3fa8737700 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -21,12 +21,13 @@ use rustc_errors::{ Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, PResult, TerminalUrl, }; use rustc_feature::UnstableFeatures; +use rustc_lint_defs::{CheckLintNameResult, LintName, RegisteredTools}; use rustc_macros::StableHash; pub use rustc_span::def_id::StableCrateId; use rustc_span::edition::Edition; use rustc_span::source_map::{FilePathMapping, SourceMap}; use rustc_span::{RealFileName, Span, Symbol}; -use rustc_structures::{CrateType, Limit, LintName}; +use rustc_structures::{CrateType, Limit}; use rustc_target::asm::InlineAsmArch; use rustc_target::spec::{ Arch, CfgAbi, CodeModel, DebuginfoKind, MergeFunctions, Os, PanicStrategy, RelocModel, @@ -84,6 +85,12 @@ pub struct CompilerIO { pub trait DynLintStore: Any + DynSync + DynSend { /// Provides a way to access lint groups without depending on `rustc_lint` fn lint_groups_iter(&self) -> Box + '_>; + + fn check_attribute_lint_name( + &self, + lint_name: LintName, + lint_tools: &RegisteredTools, + ) -> CheckLintNameResult<'_>; } /// Hardware pointer-signing keys in ARM8.3. diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 839c7952b9096..e5a3686d3dc7d 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -131,6 +131,7 @@ symbols! { Default: "default", Deref: "deref", FieldOf: "field_of", + Gca: "gca", MacroRules: "macro_rules", OffsetOf: "offset_of", PatternType: "pattern_type", @@ -1077,7 +1078,6 @@ symbols! { future_output, future_trait, fxsr, - gca, gca_adts, gca_const_items, gca_macroless_args, diff --git a/compiler/rustc_structures/src/lib.rs b/compiler/rustc_structures/src/lib.rs index caa3cdae45acc..cb5dccdfcd180 100644 --- a/compiler/rustc_structures/src/lib.rs +++ b/compiler/rustc_structures/src/lib.rs @@ -5,14 +5,12 @@ mod collapse_macro_debug_info; mod crate_type; mod limit; -mod lint; mod native_lib_kind; mod sanitizer_set; pub use collapse_macro_debug_info::CollapseMacroDebuginfo; pub use crate_type::CrateType; pub use limit::Limit; -pub use lint::LintName; pub use native_lib_kind::NativeLibKind; pub use sanitizer_set::SanitizerSet; diff --git a/compiler/rustc_target/src/spec/base/linux_musl.rs b/compiler/rustc_target/src/spec/base/linux_musl.rs index 6d3124b559b11..c7286f79ea124 100644 --- a/compiler/rustc_target/src/spec/base/linux_musl.rs +++ b/compiler/rustc_target/src/spec/base/linux_musl.rs @@ -6,6 +6,7 @@ pub(crate) fn opts() -> TargetOptions { pre_link_objects_self_contained: crt_objects::pre_musl_self_contained(), post_link_objects_self_contained: crt_objects::post_musl_self_contained(), link_self_contained: LinkSelfContainedDefault::InferredForMusl, + static_position_independent_executables: true, ..base::linux::opts() } } diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs index a664f22479913..8c82639c599ac 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs @@ -9,7 +9,6 @@ pub(crate) fn target() -> Target { base.max_atomic_width = Some(64); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64"]); base.stack_probes = StackProbeType::Inline; - base.static_position_independent_executables = true; base.supported_sanitizers = SanitizerSet::ADDRESS | SanitizerSet::CFI | SanitizerSet::LEAK diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index e547eb9a51239..7b1f3c6897218 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -87,6 +87,8 @@ pub trait Ty>: fn new_adt(interner: I, adt_def: I::AdtDef, args: I::GenericArgs) -> Self; + fn new_view(interner: I, adt_def: I::AdtDef, args: I::GenericArgs, fields: I::Ty) -> Self; + fn new_foreign(interner: I, def_id: I::ForeignId) -> Self; fn new_dynamic(interner: I, preds: I::BoundExistentialPredicates, region: Region) -> Self; diff --git a/compiler/rustc_type_ir/src/relate.rs b/compiler/rustc_type_ir/src/relate.rs index e87b584ebcb6b..e1d80d512a0fe 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -392,6 +392,16 @@ pub fn structurally_relate_tys>( } } + (ty::View(a_def, a_args, a_fields), ty::View(b_def, b_args, b_fields)) + if a_def == b_def => + { + let fields = relation.tys(a_fields, b_fields)?; + + relation.relate_ty_args(a, b, a_def.def_id().into(), a_args, b_args, |args| { + Ty::new_view(cx, a_def, args, fields) + }) + } + (ty::Foreign(a_id), ty::Foreign(b_id)) if a_id == b_id => Ok(Ty::new_foreign(cx, a_id)), (ty::Dynamic(a_obj, a_region), ty::Dynamic(b_obj, b_region)) => Ok(Ty::new_dynamic( diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 6c87013a83dd8..cdbd7bf9b9501 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -475,21 +475,7 @@ impl fmt::Debug for TyKind { Int(i) => write!(f, "{i:?}"), Uint(u) => write!(f, "{u:?}"), Float(float) => write!(f, "{float:?}"), - Adt(d, s) => { - write!(f, "{d:?}")?; - let mut s = s.iter(); - let first = s.next(); - match first { - Some(first) => write!(f, "<{:?}", first)?, - None => return Ok(()), - }; - - for arg in s { - write!(f, ", {:?}", arg)?; - } - - write!(f, ">") - } + Adt(d, s) => debug_adt::(f, d, s), Foreign(d) => f.debug_tuple("Foreign").field(d).finish(), Str => write!(f, "str"), Array(t, c) => write!(f, "[{t:?}; {c:?}]"), @@ -523,19 +509,43 @@ impl fmt::Debug for TyKind { } write!(f, ")") } + ty::View(d, s, fields) => { + write!( + f, + "view_type!({}.{{ {fields:?} }})", + fmt::from_fn(|f| debug_adt::(f, d, s)) + ) + } Alias(is_rigid, a) => f.debug_tuple("Alias").field(&is_rigid).field(&a).finish(), Param(p) => write!(f, "{p:?}"), Bound(d, b) => crate::debug_bound_var(f, *d, b), Placeholder(p) => write!(f, "{p:?}"), Infer(t) => write!(f, "{:?}", t), TyKind::Error(_) => write!(f, "{{type error}}"), - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } } +fn debug_adt( + f: &mut fmt::Formatter<'_>, + d: &::AdtDef, + s: &::GenericArgs, +) -> Result<(), fmt::Error> { + write!(f, "{d:?}")?; + let mut s = s.iter(); + let first = s.next(); + match first { + Some(first) => write!(f, "<{:?}", first)?, + None => return Ok(()), + }; + + for arg in s { + write!(f, ", {:?}", arg)?; + } + + write!(f, ">") +} + impl AliasTy { pub fn new_from_args(interner: I, kind: AliasTyKind, args: I::GenericArgs) -> AliasTy { if cfg!(debug_assertions) { diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index d1d15c974c0d4..d1295a9fb85fe 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -248,6 +248,9 @@ pub use crate::macros::cfg_select; #[macro_use] mod internal_macros; +#[unstable(feature = "gca_min_const_items", issue = "132980", implied_by = "gca_adts")] +pub use crate::marker::gca; + #[path = "num/shells/legacy_int_modules.rs"] mod legacy_int_modules; #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 804e0c0c1f73c..40274bbc679f0 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -1085,15 +1085,13 @@ struct HackGcaAdtsFeature; /// const BAR: usize = gca!(N); /// const FOO: usize = gca!(BAR::); /// ``` -#[rustc_builtin_macro(gca)] +#[allow_internal_unstable(internal_syntax)] // HACK: abuse implied_by, this should be enabled if gca_min_const_items or gca_adts is enabled, // neither one is more particularly special than the other #[unstable(feature = "gca_min_const_items", issue = "132980", implied_by = "gca_adts")] -#[macro_export] -macro_rules! gca { - ($($arg:tt)*) => { - /* compiler built-in */ - }; +#[diagnostic::opaque] +pub macro gca($($arg:tt)*) { + k#gca($($arg)*) } /// A marker for types which can be used as types of `const` generic parameters. diff --git a/src/tools/clippy/clippy_lints/src/collapsible_if.rs b/src/tools/clippy/clippy_lints/src/collapsible_if.rs index e334eae38c0dc..48fec57d0066e 100644 --- a/src/tools/clippy/clippy_lints/src/collapsible_if.rs +++ b/src/tools/clippy/clippy_lints/src/collapsible_if.rs @@ -11,7 +11,7 @@ use rustc_hir::{Block, Expr, ExprKind, StmtKind}; use rustc_lexer::TokenKind; use rustc_lint::{LateContext, LateLintPass, impl_lint_pass}; use rustc_span::{BytePos, Span, Symbol}; -use rustc_structures::LintName; +use rustc_lint_defs::LintName; declare_clippy_lint! { /// ### What it does @@ -248,7 +248,7 @@ impl CollapsibleIf { matches!( lint, LintCheck { - lint_name: LintName { + lint_name_normalized: LintName { tool: Some(sym::clippy), .. }, @@ -257,7 +257,7 @@ impl CollapsibleIf { } ) }) - .any(|lint| [expected_lint_name, sym::style, sym::all].contains(&lint.lint_name.name)) => + .any(|lint| [expected_lint_name, sym::style, sym::all].contains(&lint.lint_name_normalized.name)) => { let attr_span = lints.first().unwrap().attr_span.to(lints.last().unwrap().attr_span); // There is an `expect` attribute -- check that there is no _other_ significant text diff --git a/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index c8f10f7ba37ed..06dd5246c0b22 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/clippy_lints/src/lib.rs @@ -36,6 +36,7 @@ extern crate rustc_index; extern crate rustc_infer; extern crate rustc_lexer; extern crate rustc_lint; +extern crate rustc_lint_defs; extern crate rustc_middle; extern crate rustc_parse_format; extern crate rustc_resolve; diff --git a/src/tools/clippy/clippy_lints/src/returns/needless_return.rs b/src/tools/clippy/clippy_lints/src/returns/needless_return.rs index 915211d74fc1b..677b907a1fb2c 100644 --- a/src/tools/clippy/clippy_lints/src/returns/needless_return.rs +++ b/src/tools/clippy/clippy_lints/src/returns/needless_return.rs @@ -14,7 +14,7 @@ use rustc_hir::{Body, Expr, ExprKind, HirId, MatchSource, StmtKind}; use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::{self, Ty}; use rustc_span::{BytePos, Pos as _, Span}; -use rustc_structures::LintName; +use rustc_lint_defs::LintName; use std::borrow::Cow; use std::fmt::Display; @@ -189,7 +189,7 @@ fn check_final_expr<'tcx>( matches!( lint, LintCheck { - lint_name: LintName { + lint_name_normalized: LintName { tool: Some(sym::clippy), name: sym::needless_return | sym::style | sym::all | sym::warnings }, diff --git a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs index 63e83f4a7a75b..3adaa599dcfff 100644 --- a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs +++ b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs @@ -539,7 +539,7 @@ fn ast_ty_search_pat(ty: &ast::Ty) -> (Pat, Pat) { | TyKind::Pat(..) | TyKind::FieldOf(..) | TyKind::View(..) - | TyKind::GcaMacro(..) + | TyKind::Gca(..) // unused | TyKind::CVarArgs diff --git a/src/tools/clippy/clippy_utils/src/sugg.rs b/src/tools/clippy/clippy_utils/src/sugg.rs index f725d2d7c2103..93c4c6d70d6f9 100644 --- a/src/tools/clippy/clippy_utils/src/sugg.rs +++ b/src/tools/clippy/clippy_utils/src/sugg.rs @@ -248,7 +248,7 @@ impl<'a> Sugg<'a> { | ast::ExprKind::Array(..) | ast::ExprKind::While(..) | ast::ExprKind::Await(..) - | ast::ExprKind::GcaMacro(..) + | ast::ExprKind::Gca(..) | ast::ExprKind::Err(_) | ast::ExprKind::Dummy | ast::ExprKind::UnsafeBinderCast(..) => Sugg::NonParen(snippet(expr.span)), diff --git a/src/tools/rust-analyzer/.github/workflows/autopublish.yaml b/src/tools/rust-analyzer/.github/workflows/autopublish.yaml index ec5671b10bf37..56cbde5ef5cb9 100644 --- a/src/tools/rust-analyzer/.github/workflows/autopublish.yaml +++ b/src/tools/rust-analyzer/.github/workflows/autopublish.yaml @@ -23,6 +23,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 + persist-credentials: false # https://github.com/jlumbroso/free-disk-space/blob/main/action.yml - name: Free up some disk space diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index eb8863ce783bd..02440e0ea109d 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -31,6 +31,8 @@ jobs: typescript: ${{ steps.filter.outputs.typescript }} steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: filter with: @@ -52,6 +54,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false - name: Install rustup-toolchain-install-master run: cargo install --locked rustup-toolchain-install-master@1.11.0 @@ -95,6 +98,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false - name: Install Rust toolchain run: | @@ -145,6 +149,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -173,6 +179,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -189,6 +197,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false # Note that clippy output is currently dependent on whether rust-src is installed, # https://github.com/rust-lang/rust-clippy/issues/14625 @@ -211,6 +221,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -241,19 +253,27 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | rustup update --no-self-update stable - rustup target add ${{ matrix.target }} + rustup target add ${TARGET} + env: + TARGET: ${{ matrix.target }} # - name: Cache Dependencies # uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 - - run: cargo check --target=${{ matrix.target }} --all-targets -p ide + - run: cargo check --target=${TARGET} --all-targets -p ide if: ${{ matrix.ide-only }} - - run: cargo check --target=${{ matrix.target }} --all-targets + env: + TARGET: ${{ matrix.target }} + - run: cargo check --target=${TARGET} --all-targets if: ${{ !matrix.ide-only }} + env: + TARGET: ${{ matrix.target }} typescript: needs: changes @@ -269,6 +289,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Nodejs uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 @@ -330,6 +352,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false - name: check for typos run: typos @@ -360,9 +383,11 @@ jobs: - name: Conclusion run: | # Print the dependent jobs to see them in the CI log - jq -C <<< '${{ toJson(needs) }}' + jq -C <<< "${JSON_NEEDS}" # Check if all jobs that we depend on (in the needs array) were successful (or have been skipped). - jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< '${{ toJson(needs) }}' + jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< "${JSON_NEEDS}" + env: + JSON_NEEDS: ${{ toJson(needs) }} cancel-if-matrix-failed: needs: rust @@ -371,13 +396,16 @@ jobs: steps: - name: Cancel parallel jobs run: | - if jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< '${{ toJson(needs) }}'; then + if jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< "${JSON_NEEDS}"; then exit 0 fi # https://docs.github.com/en/rest/actions/workflow-runs?apiVersion=2022-11-28#cancel-a-workflow-run curl -L \ -X POST \ -H "Accept: application/vnd.github.v3+json" \ - -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \ + -H "Authorization: Bearer ${GITHUB_TOKEN}" \ -H "X-GitHub-Api-Version: 2022-11-28" \ - https://api.github.com/repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/cancel + "https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/cancel" + env: + JSON_NEEDS: ${{ toJson(needs) }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/src/tools/rust-analyzer/.github/workflows/coverage.yaml b/src/tools/rust-analyzer/.github/workflows/coverage.yaml index 19a132a496778..875335bccac51 100644 --- a/src/tools/rust-analyzer/.github/workflows/coverage.yaml +++ b/src/tools/rust-analyzer/.github/workflows/coverage.yaml @@ -16,6 +16,8 @@ jobs: RUSTC_BOOTSTRAP: 1 steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | diff --git a/src/tools/rust-analyzer/.github/workflows/fuzz.yml b/src/tools/rust-analyzer/.github/workflows/fuzz.yml index 8742cdf6103a3..15ac3007d7bab 100644 --- a/src/tools/rust-analyzer/.github/workflows/fuzz.yml +++ b/src/tools/rust-analyzer/.github/workflows/fuzz.yml @@ -31,6 +31,7 @@ jobs: with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 1 + persist-credentials: false - name: Install Rust toolchain run: | diff --git a/src/tools/rust-analyzer/.github/workflows/metrics.yaml b/src/tools/rust-analyzer/.github/workflows/metrics.yaml index 413e97dadad6d..d75455c628e74 100644 --- a/src/tools/rust-analyzer/.github/workflows/metrics.yaml +++ b/src/tools/rust-analyzer/.github/workflows/metrics.yaml @@ -24,6 +24,8 @@ jobs: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Cache cargo uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 @@ -67,6 +69,8 @@ jobs: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Restore target cache uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 @@ -75,7 +79,9 @@ jobs: key: ${{ runner.os }}-target-${{ github.sha }} - name: Collect metrics - run: cargo xtask metrics "${{ matrix.names }}" + run: cargo xtask metrics "${NAMES}" + env: + NAMES: ${{ matrix.names }} - name: Upload metrics uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -90,6 +96,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Download metrics uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 @@ -100,7 +108,7 @@ jobs: - name: Combine json run: | mkdir ~/.ssh - echo "${{ secrets.METRICS_DEPLOY_KEY }}" > ~/.ssh/id_ed25519 + echo "${METRICS_DEPLOY_KEY}" > ~/.ssh/id_ed25519 chmod 600 ~/.ssh/id_ed25519 chmod 700 ~/.ssh @@ -110,3 +118,5 @@ jobs: git add . git -c user.name=Bot -c user.email=dummy@example.com commit --message 📈 git push origin master + env: + METRICS_DEPLOY_KEY: ${{ secrets.METRICS_DEPLOY_KEY }} diff --git a/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml b/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml index 4b459d6a96704..2c11073bfa95f 100644 --- a/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml +++ b/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml @@ -21,6 +21,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 + persist-credentials: false - name: Install Rust toolchain run: rustup update --no-self-update stable diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 29a4020baf743..88afab204d6ec 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -10,6 +10,8 @@ on: - release - trigger-nightly +permissions: {} + env: CARGO_INCREMENTAL: 0 CARGO_NET_RETRY: 10 @@ -72,8 +74,13 @@ jobs: runs-on: ${{ matrix.os }} container: ${{ matrix.container }} + defaults: + run: + shell: bash + env: RA_TARGET: ${{ matrix.target }} + CODE_TARGET: ${{ matrix.code-target }} ALLOCATOR_FLAG: ${{ matrix.allocator != 'system' && format('--{0}', matrix.allocator) || '' }} steps: @@ -81,6 +88,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - name: Install target dependencies if: ${{ matrix.target == 'arm-unknown-linux-gnueabihf' }} @@ -106,23 +114,27 @@ jobs: run: | rustup update --no-self-update stable # llvm-tools contain the llvm-profdata tool which is needed for PGO - rustup component add rust-src ${{ matrix.pgo && 'llvm-tools' || '' }} - rustup target add ${{ matrix.target }} + rustup component add rust-src ${MAYBE_LLVM_TOOLS} + rustup target add ${RA_TARGET} + env: + MAYBE_LLVM_TOOLS: ${{ matrix.pgo && 'llvm-tools' || '' }} - name: Dist - run: cargo xtask dist --client-patch-version ${{ github.run_number }} ${{ env.ALLOCATOR_FLAG }} ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} + run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} ${ALLOCATOR_FLAG} ${MAYBE_PGO} + env: + MAYBE_PGO: ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} - run: npm ci working-directory: editors/code - name: Package Extension (release) if: github.ref == 'refs/heads/release' && matrix.code-target - run: npx vsce package -o "../../dist/rust-analyzer-${{ matrix.code-target }}.vsix" --target ${{ matrix.code-target }} + run: npx vsce package -o "../../dist/rust-analyzer-${CODE_TARGET}.vsix" --target ${CODE_TARGET} working-directory: editors/code - name: Package Extension (nightly) if: github.ref != 'refs/heads/release' && matrix.code-target - run: npx vsce package -o "../../dist/rust-analyzer-${{ matrix.code-target }}.vsix" --target ${{ matrix.code-target }} --pre-release + run: npx vsce package -o "../../dist/rust-analyzer-${CODE_TARGET}.vsix" --target ${CODE_TARGET} --pre-release working-directory: editors/code - if: matrix.target == 'x86_64-unknown-linux-gnu' @@ -138,13 +150,13 @@ jobs: - name: Run analysis-stats on rust-analyzer if: matrix.target == 'x86_64-unknown-linux-gnu' - run: target/${{ matrix.target }}/release/rust-analyzer analysis-stats . -q + run: target/${RA_TARGET}/release/rust-analyzer analysis-stats . -q - name: Run analysis-stats on rust std library if: matrix.target == 'x86_64-unknown-linux-gnu' env: RUSTC_BOOTSTRAP: 1 - run: target/${{ matrix.target }}/release/rust-analyzer analysis-stats --with-deps --no-sysroot --no-test $(rustc --print sysroot)/lib/rustlib/src/rust/library/std -q + run: target/${RA_TARGET}/release/rust-analyzer analysis-stats --with-deps --no-sysroot --no-test $(rustc --print sysroot)/lib/rustlib/src/rust/library/std -q - name: Upload artifacts uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -173,9 +185,10 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - name: Dist - run: cargo xtask dist --client-patch-version ${{ github.run_number }} --jemalloc + run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} --jemalloc - run: npm ci working-directory: editors/code @@ -201,16 +214,19 @@ jobs: publish: if: ${{ github.repository == 'rust-lang/rust-analyzer' || github.event_name == 'workflow_dispatch' }} runs-on: ubuntu-latest + permissions: + contents: write needs: ["dist", "dist-x86_64-unknown-linux-musl"] steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - name: Set release tag run: | - if [ "${{ github.ref }}" = "refs/heads/release" ]; then + if [ "${GITHUB_REF}" = "refs/heads/release" ]; then git fetch --tags today=$(date --iso -u) last_tag=$(git tag -l "${today}*" | sort -V | tail -n1) @@ -248,12 +264,18 @@ jobs: name: publish-extension (${{ matrix.cmd }}) runs-on: ubuntu-latest needs: publish + environment: publish-extension + permissions: + contents: read + id-token: write strategy: fail-fast: false matrix: include: - cmd: vsce + authentication: --oidc - cmd: ovsx + authentication: --trusted-publishing steps: - name: Install Nodejs uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 @@ -264,6 +286,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: @@ -277,7 +300,9 @@ jobs: - name: Publish Extension if: github.repository == 'rust-lang/rust-analyzer' env: - PUBLISH_PAT: ${{ (matrix.cmd == 'vsce' && secrets.MARKETPLACE_TOKEN) || (matrix.cmd == 'ovsx' && secrets.OPENVSX_TOKEN) }} + COMMAND: ${{ matrix.cmd }} + MAYBE_PRE_RELEASE: ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} + AUTHENTICATION: ${{ matrix.authentication }} working-directory: ./editors/code - run: npx ${{ matrix.cmd }} publish --skip-duplicate --pat "$PUBLISH_PAT" --packagePath ../../dist/rust-analyzer-*.vsix ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} + run: npx ${COMMAND} publish --skip-duplicate ${AUTHENTICATION} --packagePath ../../dist/rust-analyzer-*.vsix ${MAYBE_PRE_RELEASE} timeout-minutes: 2 diff --git a/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml b/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml index 29f03ffcc92fb..2458f64caed70 100644 --- a/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml +++ b/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml @@ -22,6 +22,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: rustup update --no-self-update stable diff --git a/src/tools/rust-analyzer/.github/workflows/update-generated.yml b/src/tools/rust-analyzer/.github/workflows/update-generated.yml index 611d7d40bc6a2..963645b02d7be 100644 --- a/src/tools/rust-analyzer/.github/workflows/update-generated.yml +++ b/src/tools/rust-analyzer/.github/workflows/update-generated.yml @@ -19,6 +19,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install nightly run: rustup default nightly diff --git a/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs b/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs index 84559b46cc5b7..b54fb90b8ec84 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs @@ -1411,6 +1411,7 @@ fn next_doc_expr(it: &mut Peekable) -> Option { return None; } } + Some(NodeOrToken::Node(_)) if name == "notable_trait" => DocAtom::Flag(name), Some(NodeOrToken::Node(subtree)) => { if name != "alias" { return None; diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs index 01363f5f2105a..97f7532b017d2 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs @@ -2,7 +2,7 @@ //! //! This attribute to tell the compiler about semi built-in std library //! features, such as Fn family of traits. -use base_db::SourceDatabase; +use base_db::{SourceDatabase, TargetKind}; use hir_expand::name::Name; use intern::{Symbol, sym}; use rustc_hash::FxHashMap; @@ -108,6 +108,8 @@ pub fn crate_lang_items(db: &dyn SourceDatabase, krate: Crate) -> Option Box<[Cra // Some crates declares themselves as extern crate like `extern crate self as core`. // Ignore these to prevent cycles. krate != start_crate + // Exclude proc macro dependencies, they have their own sysroot that could conflict. + && krate.data(db).target_kind != TargetKind::Lib { is_proc_macro: true } }) .collect() } @@ -393,6 +397,16 @@ impl LangItems { self.solver_adt[lang_item as usize] = Some(def); self.reverse_solver_adt.insert(def, lang_item); } + + /// FIXME: Remove this when we have MSRV >= 1.102.0. + /// See comments on [`LangItems::Rust1_102PartialEqHack`]. + fn rust_1_102_partial_eq_hack(&mut self) { + if self.Rust1_102PartialEqHack.is_none() { + return; + } + self.Eq = self.PartialEq; + self.PartialEq = self.Rust1_102PartialEqHack; + } } #[salsa::tracked(returns(as_deref))] @@ -851,6 +865,10 @@ language_item_table! { $ LangItems => AsyncGenReady, sym::AsyncGenReady, FunctionId; PartialEq, sym::eq, TraitId; + // FIXME: `PartialEq`'s lang item attribute has been changed into `partial_eq` and `eq` has + // been assigned to `Eq` in 1.102.0. Remove this and move `Eq` here once we bump our + // MSRV >= 1.102.0. + Rust1_102PartialEqHack, sym::partial_eq, TraitId; PartialOrd, sym::partial_ord, TraitId; CVoid, sym::c_void, EnumId; @@ -1046,10 +1064,66 @@ language_item_table! { $ LangItems => PartialOrd_ge, FunctionId; PartialOrd_gt, FunctionId; Drop_drop, FunctionId; - Drop_pin_drop, FunctionId; + Drop_pin_drop, FunctionId; Debug_fmt, FunctionId; Deref_deref, FunctionId; DerefMut_deref_mut, FunctionId; Index_index, FunctionId; IndexMut_index_mut, FunctionId; } + +#[cfg(test)] +mod tests { + use base_db::all_crates; + use rustc_hash::FxHashMap; + use test_fixture::WithFixture; + + use crate::{test_db::TestDB, unstable_features::UnstableFeatures}; + + /// Ensures each crate can only have up to one transitive dependency with `#![feature(lang_items)]`. + /// + /// In reality there can be multiple (std, alloc, core) but this is a representative of bugs we had. + fn ensure_single_lang_items_owner(#[rust_analyzer::rust_fixture] ra_fixture: &str) { + let mut lang_items_owner_count = FxHashMap::default(); + + let db = TestDB::with_files(ra_fixture); + // `all_crates()` is in topological order, so we can just loop over it. + for &krate in all_crates(&db).iter() { + let mut lang_items_count = u32::from(UnstableFeatures::query(&db, krate).lang_items); + lang_items_count += super::crate_extern_prelude(&db, krate) + .iter() + .map(|dep| lang_items_owner_count[dep]) + .sum::(); + lang_items_owner_count.insert(krate, lang_items_count); + } + + let invalid_crates = lang_items_owner_count + .iter() + .filter(|(_, count)| **count > 1) + .map(|(krate, _)| match &krate.extra_data(&db).display_name { + Some(name) => name.crate_name().to_string(), + None => format!("{krate:?}"), + }) + .collect::>(); + if !invalid_crates.is_empty() { + panic!("crates [{}] have more than one lang items owner", invalid_crates.join(", ")); + } + } + + #[test] + fn proc_macros_not_included() { + ensure_single_lang_items_owner( + r#" +//- /core1.rs crate:core1 +#![feature(lang_items)] + +//- /proc_macro.rs crate:proc-macro:proc_macro deps:core1 + +//- /core2.rs crate:core2 +#![feature(lang_items)] + +//- /main.rs crate:main deps:core2,proc_macro + "#, + ); + } +} diff --git a/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs b/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs index 7db1e8c947665..52b9a79684268 100644 --- a/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs +++ b/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs @@ -44,7 +44,7 @@ use crate::{ Adjustment, InferBodyId, InferenceDiagnostic, InferenceResult, db::{AnonConstId, HirDatabase}, display::{DisplayTarget, HirDisplay}, - next_solver::Ty, + next_solver::{TermRefId, Ty}, setup_tracing, test_db::TestDB, }; @@ -196,6 +196,7 @@ fn check_impl( let mut had_annotations = false; let mut mismatches = FxHashMap::default(); let mut types = FxHashMap::default(); + let mut consts = FxHashMap::default(); let mut adjustments = FxHashMap::default(); for (file_id, annotations) in db.extract_annotations() { for (range, expected) in annotations { @@ -204,6 +205,8 @@ fn check_impl( types.insert(file_range, expected); } else if let Some(ty) = expected.strip_prefix("type: ") { types.insert(file_range, ty.to_owned()); + } else if let Some(const_) = expected.strip_prefix("const: ") { + consts.insert(file_range, const_.to_owned()); } else if expected.starts_with("expected") { mismatches.insert(file_range, expected); } else if let Some(adjs) = expected.strip_prefix("adjustments:") { @@ -300,21 +303,27 @@ fn check_impl( } } - for (type_ref, ty) in inference_result.placeholder_types() { - let node = match type_node(source_map, type_ref, &db) { - Some(value) => value, - None => continue, + for (term_ref, term) in inference_result.term_of_term_placeholders() { + let node = match term_ref.unpack() { + TermRefId::TypeRefId(type_ref) => type_node(source_map, type_ref, &db), + TermRefId::ConstRef(const_ref) => expr_node(source_map, const_ref.expr, &db), }; + let Some(node) = node else { continue }; let range = node.as_ref().original_file_range_rooted(&db); - if let Some(expected) = types.remove(&range) { + if let Some(expected) = types.remove(&range).or_else(|| consts.remove(&range)) { let actual = salsa::attach(&db, || { if display_source { - ty.display_source_code(&db, def.module(&db), true).unwrap() + term.display_source_code(&db, def.module(&db), true).unwrap() } else { - ty.display_test(&db, display_target).to_string() + term.display_test(&db, display_target).to_string() } }); assert_eq!(actual, expected, "type annotation differs at {:#?}", range.range); + assert_eq!( + actual, expected, + "placeholder annotation differs at {:#?}", + range.range + ); } } } @@ -335,6 +344,12 @@ fn check_impl( format_to!(buf, "{:?}: type {}\n", t.0.range, t.1); } } + if !consts.is_empty() { + format_to!(buf, "Unchecked const annotations:\n"); + for c in consts { + format_to!(buf, "{:?}: const {}\n", c.0.range, c.1); + } + } if !adjustments.is_empty() { format_to!(buf, "Unchecked adjustments annotations:\n"); for t in adjustments { diff --git a/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs b/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs index db21c4cf949aa..bee40d74f5298 100644 --- a/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs +++ b/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs @@ -1,4 +1,4 @@ -use super::check_types_source_code; +use super::{check, check_types_source_code}; #[test] fn qualify_path_to_submodule() { @@ -261,19 +261,21 @@ fn test() { } #[test] -fn type_placeholder_type() { - check_types_source_code( +fn term_placeholders() { + check( r#" -struct S(T); +struct S([T; N]); fn test() { - let f: S<_> = S(3); - //^ i32 + let f: S<_, _> = S([1, 2]); + //^ type: i32 + //^ const: 2 let f: [_; _] = [4_u32, 5, 6]; - //^ u32 + //^ type: u32 + //^ const: 3 let f: (_, _, _) = (1_u32, 1_i32, false); - //^ u32 - //^ i32 - //^ bool + //^ type: u32 + //^ type: i32 + //^ type: bool } "#, ); diff --git a/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs b/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs index 5332bebae4d0d..f027dd9b223de 100644 --- a/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs +++ b/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs @@ -1422,7 +1422,7 @@ fn foo() -> (impl FnOnce(&str, T), impl Trait) { } "#, expect![[r#" - 134..165 '{ ...(C)) }': (impl FnOnce(&'? str, T), impl Trait) + 134..165 '{ ...(C)) }': (impl FnOnce(&'? str, T), Bar) 140..163 '(|inpu...ar(C))': (impl FnOnce(&'? str, T), Bar) 141..154 '|input, t| {}': impl FnOnce(&'? str, T) 142..147 'input': &'? str diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs index d044fbb22ae53..31c8f28fb694c 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs @@ -102,7 +102,7 @@ use crate::{ method_resolution::CandidateId, next_solver::{ AliasTy, Const, ConstKind, DbInterner, GenericArgs, Region, StoredFnSig, StoredGenericArg, - StoredGenericArgs, StoredTy, StoredTys, Term, Ty, TyKind, Tys, + StoredGenericArgs, StoredTerm, StoredTy, StoredTys, Term, TermRefIdPacked, Ty, TyKind, Tys, abi::Safety, default_types, infer::{InferCtxt, ObligationInspector, traits::ObligationCause}, @@ -778,7 +778,7 @@ pub struct InferenceResult<'db> { /// unresolved or missing subpatterns or subpatterns of mismatched types. pub type_of_pat: ArenaMap, pub type_of_binding: ArenaMap, - pub type_of_type_placeholder: ThinFxHashMap, + pub term_of_term_placeholders: ThinFxHashMap, pub type_of_opaque: ThinFxHashMap, StoredTy>, /// Whether there are any type-mismatching errors in the result. @@ -1134,7 +1134,7 @@ impl<'db> InferenceResult<'db> { type_of_expr: Default::default(), type_of_pat: Default::default(), type_of_binding: Default::default(), - type_of_type_placeholder: Default::default(), + term_of_term_placeholders: Default::default(), type_of_opaque: Default::default(), skipped_ref_pats: Default::default(), has_errors: Default::default(), @@ -1201,11 +1201,13 @@ impl<'db> InferenceResult<'db> { pub fn has_type_mismatches(&self) -> bool { !self.nodes_with_type_mismatches.is_empty() } - pub fn placeholder_types<'a>(&self) -> impl Iterator)> { - self.type_of_type_placeholder.iter().map(|(&type_ref, ty)| (type_ref, ty.as_ref())) + pub fn term_of_term_placeholders<'a>( + &self, + ) -> impl Iterator)> { + self.term_of_term_placeholders.iter().map(|(&term_ref, term)| (term_ref, term.as_ref())) } - pub fn type_of_type_placeholder<'a>(&self, type_ref: TypeRefId) -> Option> { - self.type_of_type_placeholder.get(&type_ref).map(|ty| ty.as_ref()) + pub fn term_of_term_placeholder<'a>(&self, term_ref: TermRefIdPacked) -> Option> { + self.term_of_term_placeholders.get(&term_ref).map(|term| term.as_ref()) } pub fn type_of_expr_or_pat<'a>(&self, id: ExprOrPatId) -> Option> { match id { @@ -1484,7 +1486,7 @@ impl<'db> InferenceContext<'db> { type_of_expr, type_of_pat, type_of_binding, - type_of_type_placeholder, + term_of_term_placeholders: placeholders, type_of_opaque, has_errors: _, diagnostics: _, @@ -1514,7 +1516,7 @@ impl<'db> InferenceContext<'db> { merge_arena_maps(type_of_expr, &other.type_of_expr); merge_arena_maps(type_of_pat, &other.type_of_pat); merge_arena_maps(type_of_binding, &other.type_of_binding); - merge_thin_hash_maps(type_of_type_placeholder, &other.type_of_type_placeholder); + merge_thin_hash_maps(placeholders, &other.term_of_term_placeholders); merge_thin_hash_maps(type_of_opaque, &other.type_of_opaque); merge_hash_maps(expr_adjustments, &other.expr_adjustments); merge_thin_hash_maps(pat_adjustments, &other.pat_adjustments); @@ -1662,7 +1664,7 @@ impl<'db> InferenceContext<'db> { type_of_expr, type_of_pat, type_of_binding, - type_of_type_placeholder, + term_of_term_placeholders, type_of_opaque, skipped_ref_pats, closures_data, @@ -1696,10 +1698,10 @@ impl<'db> InferenceContext<'db> { resolver.resolve_completely(ty); } type_of_binding.shrink_to_fit(); - for ty in type_of_type_placeholder.values_mut() { - resolver.resolve_completely(ty); + for term in term_of_term_placeholders.values_mut() { + resolver.resolve_completely(term); } - type_of_type_placeholder.shrink_to_fit(); + term_of_term_placeholders.shrink_to_fit(); type_of_opaque.shrink_to_fit(); if !nodes_with_type_mismatches.is_empty() { @@ -1955,7 +1957,7 @@ impl<'db> InferenceContext<'db> { fn with_ty_lowering(&mut self, f: impl FnOnce(&mut TyLoweringContext<'db, '_>) -> R) -> R { let mut infer_vars = InferenceTyLoweringVarsCtx { table: &mut self.table, - type_of_type_placeholder: &mut self.result.type_of_type_placeholder, + term_of_term_placeholders: &mut self.result.term_of_term_placeholders, }; let mut ctx = TyLoweringContext::new( self.db, @@ -2262,7 +2264,7 @@ impl<'db> InferenceContext<'db> { let interner = self.interner(); let mut vars_ctx = InferenceTyLoweringVarsCtx { table: &mut self.table, - type_of_type_placeholder: &mut self.result.type_of_type_placeholder, + term_of_term_placeholders: &mut self.result.term_of_term_placeholders, }; let mut ctx = TyLoweringContext::new( self.db, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs index f3bea3a653c8c..965ff8954106d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs @@ -6,9 +6,10 @@ use std::cell::{OnceCell, RefCell}; use std::ops::{Deref, DerefMut}; use either::Either; +use hir_def::expr_store::ExpressionStore; use hir_def::expr_store::path::Path; +use hir_def::type_ref::ConstRef; use hir_def::{ExpressionStoreOwnerId, GenericDefId}; -use hir_def::{expr_store::ExpressionStore, type_ref::TypeRefId}; use hir_def::{ hir::{ExprId, ExprOrPatIdPacked}, resolver::Resolver, @@ -16,6 +17,7 @@ use hir_def::{ use la_arena::RawIdx; use thin_vec::ThinVec; +use crate::next_solver::{StoredTerm, Term}; use crate::{ InferenceDiagnostic, Span, ThinFxHashMap, TyLoweringDiagnostic, db::{AnonConstId, HirDatabase}, @@ -26,7 +28,7 @@ use crate::{ TyLoweringInferVarsCtx, path::{PathDiagnosticCallback, PathLoweringContext}, }, - next_solver::{Const, Region, StoredTy, Ty}, + next_solver::{Const, Region, TermRefIdPacked, Ty}, }; // Unfortunately, this struct needs to use interior mutability (but we encapsulate it) @@ -63,7 +65,7 @@ pub(crate) struct PathDiagnosticCallbackData<'a> { pub(super) struct InferenceTyLoweringVarsCtx<'a, 'db> { pub(super) table: &'a mut InferenceTable<'db>, - pub(super) type_of_type_placeholder: &'a mut ThinFxHashMap, + pub(super) term_of_term_placeholders: &'a mut ThinFxHashMap, } impl<'db> TyLoweringInferVarsCtx<'db> for InferenceTyLoweringVarsCtx<'_, 'db> { @@ -71,13 +73,24 @@ impl<'db> TyLoweringInferVarsCtx<'db> for InferenceTyLoweringVarsCtx<'_, 'db> { let ty = self.table.infer_ctxt.next_ty_var(span); if let Span::TypeRefId(type_ref) = span { - self.type_of_type_placeholder.insert(type_ref, ty.store()); + self.term_of_term_placeholders.insert(type_ref.into(), Term::from(ty).store()); } ty } fn next_const_var(&mut self, span: Span) -> Const<'db> { - self.table.infer_ctxt.next_const_var(span) + let const_ = self.table.infer_ctxt.next_const_var(span); + + let term_ref = match span { + Span::ExprId(expr) => Some(ConstRef { expr }.into()), + Span::TypeRefId(type_ref) => Some(type_ref.into()), + _ => None, + }; + if let Some(key) = term_ref { + self.term_of_term_placeholders.insert(key, Term::from(const_).store()); + } + + const_ } fn next_region_var(&mut self, span: Span) -> Region<'db> { self.table.infer_ctxt.next_region_var(span) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs index ec0788b43b573..47c06891202bf 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs @@ -152,7 +152,7 @@ impl<'db> InferenceContext<'db> { // Don't use `self.make_ty()` here as we need `orig_ns`. let mut vars_ctx = InferenceTyLoweringVarsCtx { table: &mut self.table, - type_of_type_placeholder: &mut self.result.type_of_type_placeholder, + term_of_term_placeholders: &mut self.result.term_of_term_placeholders, }; let mut ctx = TyLoweringContext::new( self.db, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs index 23cf4fbe38599..cf056fdebc03e 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs @@ -1288,23 +1288,16 @@ pub(crate) fn substs_from_args_and_bindings<'db>( params.next(); force_infer_lt = Some((arg_idx as u32, param_id)); } - (HirGenericArg::Type(type_ref), GenericParamDataRef::ConstParamData(_)) => { - if let Some(konst) = type_looks_like_const(store, *type_ref) { - let GenericParamId::ConstParamId(param_id) = param_id else { - panic!("unmatching param kinds"); - }; - let const_ty = const_param_ty(db, param_id); - substs - .push(ctx.provided_type_like_const(*type_ref, const_ty, konst).into()); - args.next(); - params.next(); - } else { - // See the `_ => { ... }` branch. - if !had_count_error { - ctx.report_arg_mismatch(param_id, arg_idx as u32, has_self_arg); - } - while args.next().is_some() {} - } + (HirGenericArg::Type(type_ref), GenericParamDataRef::ConstParamData(_)) + if let Some(konst) = type_looks_like_const(store, *type_ref) => + { + let GenericParamId::ConstParamId(param_id) = param_id else { + panic!("unmatching param kinds"); + }; + let const_ty = const_param_ty(db, param_id); + substs.push(ctx.provided_type_like_const(*type_ref, const_ty, konst).into()); + args.next(); + params.next(); } _ => { // We expected one kind of parameter, but the user provided diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs index c45387b6894bc..dc609b0cff26d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs @@ -4,10 +4,12 @@ use hir_def::{ AdtId, AttrDefId, BuiltinDeriveImplId, CallableDefId, ConstId, DefWithBodyId, EnumId, EnumVariantId, ExpressionStoreOwnerId, FunctionId, GenericDefId, ImplId, StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId, + hir::ExprId, signatures::{ ConstSignature, EnumSignature, FunctionSignature, StaticSignature, StructSignature, TraitSignature, TypeAliasSignature, UnionSignature, }, + type_ref::{ConstRef, TypeRefId}, }; use rustc_type_ir::inherent; use salsa::SalsaValue; @@ -541,6 +543,58 @@ impl<'db> From for SolverDefId<'db> { } } +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum TermRefId { + TypeRefId(TypeRefId), + ConstRef(ConstRef), +} +impl_from!(TypeRefId, ConstRef for TermRefId); + +#[derive(Copy, Clone, Hash, PartialEq, Eq)] +pub struct TermRefIdPacked(u32); + +const _: () = assert!(std::mem::size_of::() == std::mem::size_of::()); + +impl TermRefIdPacked { + const CONST_REF_BIT: u32 = 1 << (u32::BITS - 1); + const INDEX_MASK: u32 = !Self::CONST_REF_BIT; + + pub fn unpack(self) -> TermRefId { + let is_const_ref = self.0 & Self::CONST_REF_BIT != 0; + match is_const_ref { + true => { + let expr = ExprId::from_raw((self.0 & Self::INDEX_MASK).into()); + TermRefId::ConstRef(ConstRef { expr }) + } + false => TermRefId::TypeRefId(TypeRefId::from_raw(self.0.into())), + } + } +} + +impl std::fmt::Debug for TermRefIdPacked { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.unpack().fmt(f) + } +} + +impl From for TermRefIdPacked { + fn from(value: TypeRefId) -> Self { + let value = value.into_raw().into_u32(); + // virtually impossible to have IDs that high + debug_assert_eq!(value & Self::CONST_REF_BIT, 0); + Self(value) + } +} + +impl From for TermRefIdPacked { + fn from(value: ConstRef) -> Self { + let value = value.expr.into_raw().into_u32(); + // virtually impossible to have IDs that high + debug_assert_eq!(value & Self::CONST_REF_BIT, 0); + Self(value | Self::CONST_REF_BIT) + } +} + #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct GeneralConstIdWrapper<'db>(pub GeneralConstId<'db>); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs index 81d36c2bb037c..db93276f7e32f 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs @@ -280,6 +280,57 @@ impl<'db> From> for GenericArg<'db> { } } +#[derive(PartialEq, Eq, Hash)] +pub struct StoredTerm { + ptr: GenericArgImpl<'static>, +} + +impl Clone for StoredTerm { + #[inline] + fn clone(&self) -> Self { + match self.ptr.term_kind() { + TermKind::Ty(it) => std::mem::forget(it.interned.to_owned()), + TermKind::Const(it) => std::mem::forget(it.interned.to_owned()), + } + Self { ptr: self.ptr } + } +} + +impl Drop for StoredTerm { + #[inline] + fn drop(&mut self) { + unsafe { + match self.ptr.term_kind() { + TermKind::Ty(it) => it.interned.decrement_refcount(), + TermKind::Const(it) => it.interned.decrement_refcount(), + } + } + } +} + +impl StoredTerm { + #[inline] + fn new(value: Term<'_>) -> Self { + let result = Self { ptr: GenericArgImpl { ptr: value.ptr.ptr, _marker: PhantomData } }; + // Increase refcount. + std::mem::forget(result.clone()); + result + } + + #[inline] + pub fn as_ref<'db>(&self) -> Term<'db> { + Term { ptr: self.ptr } + } +} + +impl std::fmt::Debug for StoredTerm { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.as_ref().fmt(f) + } +} + +impl_foldable_for_stored_type!(StoredTerm); + #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Term<'db> { ptr: GenericArgImpl<'db>, @@ -295,6 +346,11 @@ impl<'db> std::fmt::Debug for Term<'db> { } impl<'db> Term<'db> { + #[inline] + pub fn store(self) -> StoredTerm { + StoredTerm::new(self) + } + #[inline] pub fn kind(self) -> TermKind<'db> { self.ptr.term_kind() diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs index fb652d035eaca..6709da7afb212 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs @@ -97,7 +97,7 @@ impl<'db> SolverDelegate for SolverContext<'db> { >, > { // FIXME(next-solver): - None + Some(Vec::new()) } fn make_deduplicated_region_constraints( diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs b/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs index 621eed47be4ec..38e6eb54ba826 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs @@ -116,7 +116,7 @@ static AARCH64_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ &[], ), // FEAT_FP8 - ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["faminmax", "lut", "bf16"]), + ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["neon"]), // FEAT_FP8DOT2 ("fp8dot2", Unstable(sym::aarch64_unstable_target_feature), &["fp8dot4"]), // FEAT_FP8DOT4 diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index b4223a72ad723..68d625b588042 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -1530,7 +1530,7 @@ impl Function { // because it has not `CallableDefId`. // FIXME: This does not account for replacing `Self`. Do we really need that? let Some(trait_method) = method.trait_method(db, impl_) else { - return Type::unknown(); + return Type::unknown(db); }; Function::from(trait_method).ty(db) } @@ -1551,7 +1551,7 @@ impl Function { // because it has not `CallableDefId`. // FIXME: This does not account for replacing `Self`. Do we really need that? let Some(trait_method) = method.trait_method(db, impl_) else { - return Type::unknown(); + return Type::unknown(db); }; Function::from(trait_method).fn_ptr_type(db) } @@ -4506,7 +4506,7 @@ impl<'db> Type<'db> { fn from_value_def(db: &'db dyn HirDatabase, def: impl Into) -> Self { let def = def.into(); let Some(ty) = db.value_ty(def) else { - return Type::unknown(); + return Type::unknown(db); }; let def = match def { ValueTyDefId::ConstId(it) => GenericDefId::ConstId(it), @@ -4524,8 +4524,8 @@ impl<'db> Type<'db> { } /// Replace any generic parameters with error types. - pub fn instantiate_with_errors(&self) -> Self { - let interner = DbInterner::conjure(); + pub fn instantiate_with_errors(&self, db: &'db dyn HirDatabase) -> Self { + let interner = DbInterner::new_no_crate(db); let krate = self.krate(interner.db()); let args = match self.owner { TypeOwnerId::GenericDefId(def) => GenericArgs::error_for_item(interner, def.into()), @@ -4538,8 +4538,12 @@ impl<'db> Type<'db> { } // FIXME: Find some way with const params, maybe even lifetimes? - pub fn instantiate(&self, args: impl IntoIterator>>) -> Type<'db> { - let interner = DbInterner::conjure(); + pub fn instantiate( + &self, + db: &'db dyn HirDatabase, + args: impl IntoIterator>>, + ) -> Type<'db> { + let interner = DbInterner::new_no_crate(db); let (args, owner) = match self.owner { TypeOwnerId::GenericDefId(def) => generic_args_from_tys(interner, def.into(), args), TypeOwnerId::BuiltinDeriveImplId(def) => { @@ -4596,7 +4600,7 @@ impl<'db> Type<'db> { db: &'db dyn HirDatabase, rebase_into: &Type<'db>, ) -> Type<'db> { - self.try_rebase_into(db, rebase_into).unwrap_or_else(|| self.instantiate_with_errors()) + self.try_rebase_into(db, rebase_into).unwrap_or_else(|| self.instantiate_with_errors(db)) } pub fn try_rebase_into_owner( @@ -4617,15 +4621,13 @@ impl<'db> Type<'db> { db: &'db dyn HirDatabase, new_owner: GenericDef, ) -> Self { - self.try_rebase_into_owner(db, new_owner).unwrap_or_else(|| self.instantiate_with_errors()) + self.try_rebase_into_owner(db, new_owner) + .unwrap_or_else(|| self.instantiate_with_errors(db)) } - pub fn unknown() -> Self { - let interner = DbInterner::conjure(); - Type::no_params( - Self::builtin_type_crate(interner.db()), - Ty::new_error(interner, ErrorGuaranteed), - ) + pub fn unknown(db: &'db dyn HirDatabase) -> Self { + let interner = DbInterner::new_no_crate(db); + Type::no_params(Self::builtin_type_crate(db), Ty::new_error(interner, ErrorGuaranteed)) } pub fn new_slice(db: &'db dyn HirDatabase, ty: Self) -> Self { @@ -4657,9 +4659,9 @@ impl<'db> Type<'db> { Type { owner, ty } } - pub fn new_unit() -> Self { - let interner = DbInterner::conjure(); - Type::no_params(Self::builtin_type_crate(interner.db()), Ty::new_unit(interner)) + pub fn new_unit(db: &'db dyn HirDatabase) -> Self { + let interner = DbInterner::new_no_crate(db); + Type::no_params(Self::builtin_type_crate(db), Ty::new_unit(interner)) } pub fn is_unit(&self) -> bool { diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index ff9fa659a928e..888a4ca84dd66 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -25,7 +25,7 @@ use hir_def::{ lang_item::LangItems, nameres::MacroSubNs, resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs, resolver_for_scope}, - type_ref::{Mutability, TypeRefId}, + type_ref::{ConstRef, Mutability, TypeRefId}, visibility::Visibility, }; use hir_expand::{ @@ -53,7 +53,7 @@ use itertools::Itertools; use rustc_hash::FxHashSet; use rustc_type_ir::{ AliasTyKind, - inherent::{IntoKind, Ty as _}, + inherent::{IntoKind, Term as _, Ty as _}, }; use smallvec::SmallVec; use stdx::never; @@ -481,17 +481,27 @@ impl<'db> SourceAnalyzer<'db> { impl<'db> TyLoweringInferVarsCtx<'db> for VarsCtx<'_, 'db> { fn next_ty_var(&mut self, span: hir_ide::Span) -> Ty<'db> { - if let hir_ide::Span::TypeRefId(type_ref) = span - && let Some(ty) = - self.infer.and_then(|infer| infer.type_of_type_placeholder(type_ref)) - { - ty - } else { - self.types.types.error - } + let term_ref = match span { + hir_ide::Span::TypeRefId(type_ref) => type_ref.into(), + _ => return self.types.types.error, + }; + + self.infer + .and_then(|infer| infer.term_of_term_placeholder(term_ref)) + .and_then(|term| term.as_type()) + .unwrap_or(self.types.types.error) } - fn next_const_var(&mut self, _span: hir_ide::Span) -> hir_ide::next_solver::Const<'db> { - self.types.consts.error + fn next_const_var(&mut self, span: hir_ide::Span) -> hir_ide::next_solver::Const<'db> { + let term_ref = match span { + hir_ide::Span::TypeRefId(type_ref) => type_ref.into(), + hir_ide::Span::ExprId(expr) => ConstRef { expr }.into(), + _ => return self.types.consts.error, + }; + + self.infer + .and_then(|infer| infer.term_of_term_placeholder(term_ref)) + .and_then(|generic_arg| generic_arg.as_const()) + .unwrap_or(self.types.consts.error) } fn next_region_var(&mut self, _span: hir_ide::Span) -> Region<'db> { self.types.regions.error diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search.rs b/src/tools/rust-analyzer/crates/hir/src/term_search.rs index 37cad14ea2d39..072f495f81912 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search.rs @@ -87,8 +87,9 @@ impl<'db> AlternativeExprs<'db> { /// iteration as well as keeping track of which `ScopeDef` items have been used. /// Both of them are to speed up the term search by leaving out types / ScopeDefs that likely do /// not produce any new results. -#[derive(Default, Debug)] +#[derive(Debug)] struct LookupTable<'db> { + db: &'db dyn HirDatabase, /// All the `Expr`s in "value" produce the type of "key" data: FxHashMap, AlternativeExprs<'db>>, /// New types reached since last query by the `NewTypesKey` @@ -101,20 +102,25 @@ struct LookupTable<'db> { impl<'db> LookupTable<'db> { /// Initialize lookup table - fn new(many_threshold: usize, goal: Type<'db>) -> Self { - let mut res = Self { many_threshold, ..Default::default() }; - res.new_types.insert(NewTypesKey::ImplMethod, Vec::new()); - res.new_types.insert(NewTypesKey::StructProjection, Vec::new()); - res.types_wishlist.insert(goal); - res + fn new(db: &'db dyn HirDatabase, many_threshold: usize, goal: Type<'db>) -> Self { + Self { + db, + many_threshold, + data: Default::default(), + types_wishlist: FxHashSet::from_iter([goal]), + new_types: FxHashMap::from_iter([ + (NewTypesKey::ImplMethod, Vec::new()), + (NewTypesKey::StructProjection, Vec::new()), + ]), + } } /// Find all `Expr`s that unify with the `ty` - fn find(&mut self, db: &'db dyn HirDatabase, ty: &Type<'db>) -> Option>> { + fn find(&mut self, ty: &Type<'db>) -> Option>> { let res = self .data .get_key_value(ty) - .or_else(|| self.data.iter().find(|(t, _)| t.could_unify_with_deeply(db, ty))) + .or_else(|| self.data.iter().find(|(t, _)| t.could_unify_with_deeply(self.db, ty))) .map(|(t, tts)| tts.exprs(t)); if res.is_none() { @@ -175,7 +181,7 @@ impl<'db> LookupTable<'db> { /// transitive. For example `Vec` and `FxHashSet` both unify with `Iterator`, /// but they clearly do not unify themselves. fn insert(&mut self, ty: Type<'db>, exprs: impl Iterator>) { - let ty = ty.instantiate_with_errors(); + let ty = ty.instantiate_with_errors(self.db); match self.data.get_mut(&ty) { Some(it) => { it.extend_with_threshold(self.many_threshold, exprs); @@ -271,7 +277,8 @@ pub fn term_search<'db, DB: HirDatabase>(ctx: &TermSearchCtx<'_, 'db, DB>) -> Ve defs.insert(def); }); - let mut lookup = LookupTable::new(ctx.config.many_alternatives_threshold, ctx.goal.clone()); + let mut lookup = + LookupTable::new(ctx.sema.db, ctx.config.many_alternatives_threshold, ctx.goal.clone()); let fuel = std::cell::Cell::new(ctx.config.fuel); let should_continue = &|| { diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs index dc6a6b269744c..6ea1f4e2a2b41 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs @@ -310,18 +310,20 @@ impl<'db> Expr<'db> { Expr::Local(it) => it.ty(db), Expr::ConstParam(it) => it.ty(db), Expr::FamousType { ty, .. } => ty.clone(), - Expr::Function { func, generics, .. } => func.ret_type(db).instantiate(generics), + Expr::Function { func, generics, .. } => func.ret_type(db).instantiate(db, generics), Expr::Method { func, generics, target, .. } => func .ret_type(db) - .instantiate(target.ty(db).type_arguments().chain(generics.iter().cloned())), + .instantiate(db, target.ty(db).type_arguments().chain(generics.iter().cloned())), Expr::Variant { variant, generics, .. } => { - Adt::from(variant.parent_enum(db)).ty(db).instantiate(generics) + Adt::from(variant.parent_enum(db)).ty(db).instantiate(db, generics) } Expr::Struct { strukt, generics, .. } => { - Adt::from(*strukt).ty(db).instantiate(generics) + Adt::from(*strukt).ty(db).instantiate(db, generics) } Expr::Tuple { ty, .. } => ty.clone(), - Expr::Field { expr, field } => field.ty(db).instantiate(expr.ty(db).type_arguments()), + Expr::Field { expr, field } => { + field.ty(db).instantiate(db, expr.ty(db).type_arguments()) + } Expr::Reference(it) => it.ty(db), Expr::Many(ty) => ty.clone(), } diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs index dab80c28c4c3b..6059220bb0e00 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs @@ -57,7 +57,7 @@ pub(super) fn trivial<'a, 'lt, 'db, DB: HirDatabase>( lookup.insert(ty.clone(), std::iter::once(expr.clone())); - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(expr) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(expr) }) } @@ -107,7 +107,7 @@ pub(super) fn assoc_const<'a, 'lt, 'db, DB: HirDatabase>( lookup.insert(ty.clone(), std::iter::once(expr.clone())); - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(expr) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(expr) }) } @@ -169,7 +169,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( let param_exprs: Vec>> = fields .into_iter() .map(|field| { - lookup.find(db, &field.ty(db).instantiate(generics.iter().cloned())) + lookup.find(&field.ty(db).instantiate(db, generics.iter().cloned())) }) .collect::>()?; @@ -215,7 +215,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( .fields(db) .into_iter() .map(|field| { - lookup.find(db, &field.ty(db).instantiate(generics.iter().cloned())) + lookup.find(&field.ty(db).instantiate(db, generics.iter().cloned())) }) .collect::>()?; @@ -249,7 +249,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( Adt::Union(_) => None, }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -329,7 +329,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( }) .collect::>()?; - let ret_ty = it.ret_type(db).instantiate(generics.iter().cloned()); + let ret_ty = it.ret_type(db).instantiate(db, generics.iter().cloned()); // Filter out private and unsafe functions if !it.is_visible_from(db, module) || it.is_unsafe_to_call( @@ -348,7 +348,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( .params_without_self(db) .into_iter() .map(|field| { - let ty = &field.ty().instantiate(&generics); + let ty = &field.ty().instantiate(db, &generics); match ty.is_mutable_reference() { true => None, false => lookup.find_autoref(db, ty), @@ -383,7 +383,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( }) .flatten() .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -459,28 +459,33 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( return None; } - let ret_ty = it.ret_type(db).instantiate(ty.type_arguments()); + let ret_ty = it.ret_type(db).instantiate(db, ty.type_arguments()); // Ignore functions that do not change the type - if ty.instantiate_with_errors().could_unify_with_deeply(db, &ret_ty) { + if ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ret_ty) { return None; } - let self_ty = - it.self_param(db).expect("No self param").ty(db).instantiate(ty.type_arguments()); + let self_ty = it + .self_param(db) + .expect("No self param") + .ty(db) + .instantiate(db, ty.type_arguments()); // Ignore functions that have different self type if !self_ty.autoderef(db).any(|s_ty| ty == s_ty) { return None; } - let target_type_exprs = lookup.find(db, &ty).expect("Type not in lookup"); + let target_type_exprs = lookup.find(&ty).expect("Type not in lookup"); // Early exit if some param cannot be filled from lookup let param_exprs: Vec>> = it .params_without_self(db) .into_iter() - .map(|field| lookup.find_autoref(db, &field.ty().instantiate(ty.type_arguments()))) + .map(|field| { + lookup.find_autoref(db, &field.ty().instantiate(db, ty.type_arguments())) + }) .collect::>()?; let generics: Vec<_> = ty.type_arguments().collect(); @@ -502,7 +507,7 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( Some((ret_ty, fn_exprs)) }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -530,7 +535,7 @@ pub(super) fn struct_projection<'a, 'lt, 'db, DB: HirDatabase>( lookup .new_types(NewTypesKey::StructProjection) .into_iter() - .map(|ty| (ty.clone(), lookup.find(db, &ty).expect("Expr not in lookup"))) + .map(|ty| (ty.clone(), lookup.find(&ty).expect("Expr not in lookup"))) .filter(|_| should_continue()) .flat_map(move |(ty, targets)| { ty.fields(db).into_iter().filter_map(move |(field, filed_ty)| { @@ -545,7 +550,7 @@ pub(super) fn struct_projection<'a, 'lt, 'db, DB: HirDatabase>( }) }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -570,7 +575,7 @@ pub(super) fn famous_types<'a, 'lt, 'db, DB: HirDatabase>( ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { let db = ctx.sema.db; let bool_ty = BuiltinType::bool().ty(db); - let unit_ty = Type::new_unit(); + let unit_ty = Type::new_unit(db); [ Expr::FamousType { ty: bool_ty.clone(), value: "true" }, Expr::FamousType { ty: bool_ty, value: "false" }, @@ -580,7 +585,7 @@ pub(super) fn famous_types<'a, 'lt, 'db, DB: HirDatabase>( .inspect(|exprs| { lookup.insert(exprs.ty(db), std::iter::once(exprs.clone())); }) - .filter(|expr| expr.ty(db).instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal)) + .filter(|expr| expr.ty(db).instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal)) } /// # Impl static method (without self type) tactic @@ -654,13 +659,15 @@ pub(super) fn impl_static_method<'a, 'lt, 'db, DB: HirDatabase>( return None; } - let ret_ty = it.ret_type(db).instantiate(ty.type_arguments()); + let ret_ty = it.ret_type(db).instantiate(db, ty.type_arguments()); // Early exit if some param cannot be filled from lookup let param_exprs: Vec>> = it .params_without_self(db) .into_iter() - .map(|field| lookup.find_autoref(db, &field.ty().instantiate(ty.type_arguments()))) + .map(|field| { + lookup.find_autoref(db, &field.ty().instantiate(db, ty.type_arguments())) + }) .collect::>()?; // Note that we need special case for 0 param constructors because of multi cartesian @@ -681,7 +688,7 @@ pub(super) fn impl_static_method<'a, 'lt, 'db, DB: HirDatabase>( Some((ret_ty, fn_exprs)) }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -720,7 +727,7 @@ pub(super) fn make_tuple<'a, 'lt, 'db, DB: HirDatabase>( // Early exit if some param cannot be filled from lookup let param_exprs: Vec>> = - ty.type_arguments().map(|field| lookup.find(db, &field)).collect::>()?; + ty.type_arguments().map(|field| lookup.find(&field)).collect::>()?; let exprs: Vec> = param_exprs .into_iter() @@ -741,7 +748,7 @@ pub(super) fn make_tuple<'a, 'lt, 'db, DB: HirDatabase>( .flatten() .filter_map(|expr| { expr.ty(db) - .instantiate_with_errors() + .instantiate_with_errors(db) .could_unify_with_deeply(db, &ctx.goal) .then_some(expr) }) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs index dd082476d2d62..95052faf93d31 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs @@ -293,7 +293,7 @@ pub(crate) fn relevance_score( if let Some(ty) = ty { if ty == *expected { score = 100000; - } else if ty.could_unify_with(ctx.db(), &expected.instantiate_with_errors()) { + } else if ty.could_unify_with(ctx.db(), &expected.instantiate_with_errors(ctx.db())) { score = 10000; } } @@ -2093,4 +2093,44 @@ fn main() { "#, ); } + + #[test] + fn carries_cfg_attr_from_macro() { + check_assist( + auto_import, + r#" +//- /lib.rs crate:std +pub mod time { + pub struct Instant; +} + +//- /main.rs crate:main deps:std +// comment comment comment comment + +macro_rules! m { + ($t: path) => { + #[cfg(anything)] + fn f() -> $t {} + }; +} + +m! {Instant$0} +"#, + r#" +// comment comment comment comment + +#[cfg(anything)] +use std::time::Instant; + +macro_rules! m { + ($t: path) => { + #[cfg(anything)] + fn f() -> $t {} + }; +} + +m! {Instant} +"#, + ); + } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs index a378256b598aa..b95fab4fe88c8 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs @@ -426,6 +426,48 @@ fn main() { ) } + #[test] + fn inferred_array_length() { + check_assist( + extract_type_alias, + r#" +fn main() { + let a: $0[i32; _]$0 = [1, 2, 3]; +} + "#, + r#" +type $0Type = [i32; 3]; + +fn main() { + let a: Type = [1, 2, 3]; +} + "#, + ) + } + + #[test] + fn inferred_generic_const_parameter() { + check_assist( + extract_type_alias, + r#" +struct Wrap([i32; N]); + +fn main() { + let wrap: $0Wrap<_>$0 = Wrap([1, 2, 3]); +} + "#, + r#" +struct Wrap([i32; N]); + +type $0Type = Wrap<3>; + +fn main() { + let wrap: Type = Wrap([1, 2, 3]); +} + "#, + ) + } + #[test] fn inferred_type() { check_assist( diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs index a414db0a6c8d0..1ccc8917f0c65 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs @@ -72,7 +72,7 @@ pub(crate) fn replace_with_lazy_method( .is_some_and(|result| { result .ty(ctx.db()) - .instantiate_with_errors() + .instantiate_with_errors(ctx.db()) .could_unify_with(ctx.db(), &receiver_ty) }), _ => false, diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs index 032cc28858c29..867d71deb097a 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs @@ -92,7 +92,9 @@ pub(crate) fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_, '_>) - }; let semantic_ty = ty_constructor .map(|ty_constructor| { - hir::Adt::from(ty_constructor).ty(ctx.db()).instantiate([ty.clone()]) + hir::Adt::from(ty_constructor) + .ty(ctx.db()) + .instantiate(ctx.db(), [ty.clone()]) }) .unwrap_or_else(|| ty.clone()); (ast_ty, semantic_ty) @@ -255,8 +257,9 @@ fn wrapper_alias<'db>( make.path_segment_generics(make.name_ref(name.as_str()), generic_arg_list), ); - let new_ty = - hir::Adt::from(enum_ty).ty(ctx.db()).instantiate([semantic_ret_type.clone()]); + let new_ty = hir::Adt::from(enum_ty) + .ty(ctx.db()) + .instantiate(ctx.db(), [semantic_ret_type.clone()]); Some((make.ty_path(path), new_ty)) }) diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs index 6937d241b7b77..a6fd2e8042fd0 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs @@ -185,7 +185,7 @@ pub(crate) fn complete_expr_path<'db>( }; // Note: this is not *required* here, we do it to also find methods that require // the type to be instantiated with specific types. - let ty = ty.instantiate_with_errors(); + let ty = ty.instantiate_with_errors(ctx.db); if let Some(hir::Adt::Enum(e)) = ty.as_adt() { cov_mark::hit!(completes_variant_through_alias); diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/context.rs b/src/tools/rust-analyzer/crates/ide-completion/src/context.rs index 80e07ff9323df..e397e95503b13 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/context.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/context.rs @@ -791,7 +791,7 @@ impl<'db> CompletionContext<'_, 'db> { self.scope .generic_def() .and_then(|def| ty.try_rebase_into_owner(self.db, def)) - .unwrap_or_else(|| ty.instantiate_with_errors()) + .unwrap_or_else(|| ty.instantiate_with_errors(self.db)) } } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs index 9330e70b1cb02..4aed1e514f57f 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs @@ -658,7 +658,7 @@ fn expected_type_and_name<'db>( let def = *generic_def .get_or_insert_with(|| sema.scope(&node).and_then(|scope| scope.generic_def())); def.and_then(|def| ty.try_rebase_into_owner(sema.db, def)) - .unwrap_or_else(|| ty.instantiate_with_errors()) + .unwrap_or_else(|| ty.instantiate_with_errors(sema.db)) } }; let (ty, name) = loop { diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs b/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs index 0e9b5d0086f84..a4fb3e97d1b86 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs @@ -246,8 +246,11 @@ pub(super) fn add_call_parens<'b>( Some(n) => { let smol_str = n.display_no_db(ctx.edition).to_smolstr(); let text = smol_str.as_str().trim_start_matches('_'); - let ref_ = - ref_of_param(ctx, text, ¶m.ty().instantiate_with_errors()); + let ref_ = ref_of_param( + ctx, + text, + ¶m.ty().instantiate_with_errors(ctx.db), + ); f(&format_args!("${{{}:{ref_}{text}}}", index + offset)) } None => { diff --git a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs index 119af3ab8615b..3403e41247029 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs @@ -5403,6 +5403,22 @@ The tracking issue for this feature is: [#87555] [#87555]: https://github.com/rust-lang/rust/issues/87555 +------------------------ +"##, + default_severity: Severity::Allow, + warn_since: None, + deny_since: None, + }, + Lint { + label: "const_abort", + description: r##"# `const_abort` + + + +The tracking issue for this feature is: [#166193] + +[#166193]: https://github.com/rust-lang/rust/issues/166193 + ------------------------ "##, default_severity: Severity::Allow, @@ -8525,6 +8541,22 @@ The tracking issue for this feature is: [#164793] [#164793]: https://github.com/rust-lang/rust/issues/164793 +------------------------ +"##, + default_severity: Severity::Allow, + warn_since: None, + deny_since: None, + }, + Lint { + label: "extern_item_default_impls", + description: r##"# `extern_item_default_impls` + +Externally implementable items with default impls + +The tracking issue for this feature is: [#125418] + +[#125418]: https://github.com/rust-lang/rust/issues/125418 + ------------------------ "##, default_severity: Severity::Allow, @@ -10550,22 +10582,6 @@ The tracking issue for this feature is: [#157081] [#157081]: https://github.com/rust-lang/rust/issues/157081 ------------------------- -"##, - default_severity: Severity::Allow, - warn_since: None, - deny_since: None, - }, - Lint { - label: "int_from_ascii", - description: r##"# `int_from_ascii` - - - -The tracking issue for this feature is: [#134821] - -[#134821]: https://github.com/rust-lang/rust/issues/134821 - ------------------------ "##, default_severity: Severity::Allow, @@ -18119,6 +18135,22 @@ The tracking issue for this feature is: [#148227] [#148227]: https://github.com/rust-lang/rust/issues/148227 +------------------------ +"##, + default_severity: Severity::Allow, + warn_since: None, + deny_since: None, + }, + Lint { + label: "vec_repeat", + description: r##"# `vec_repeat` + + + +The tracking issue for this feature is: [#164215] + +[#164215]: https://github.com/rust-lang/rust/issues/164215 + ------------------------ "##, default_severity: Severity::Allow, diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs index 4256b7dae51c5..af6c9de8fcabc 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs @@ -198,7 +198,7 @@ fn add_missing_ok_or_some( let variant_name = if Some(expected_enum) == core_result { "Ok" } else { "Some" }; - let wrapped_actual_ty = expected_adt.ty(ctx.db()).instantiate([d.actual.clone()]); + let wrapped_actual_ty = expected_adt.ty(ctx.db()).instantiate(ctx.db(), [d.actual.clone()]); if !d.expected.could_unify_with(ctx.db(), &wrapped_actual_ty) { return None; @@ -296,7 +296,7 @@ fn remove_unnecessary_wrapper( return None; } - let inner_type = variant.fields(db).first()?.ty(db).instantiate(d.actual.type_arguments()); + let inner_type = variant.fields(db).first()?.ty(db).instantiate(db, d.actual.type_arguments()); if !d.expected.could_unify_with(db, &inner_type) { return None; } diff --git a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs index e14e9d512b7bf..5c35b9e26559c 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs @@ -9580,7 +9580,7 @@ fn notable_ranged() { r#" //- minicore: future, iterator struct S; -#[doc(notable_trait)] +#[doc(notable_trait(color = "transparent"))] trait Notable {} impl Notable for S {} impl core::future::Future for S { diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs index 566dde7775c84..6e77f182bf36b 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs @@ -868,16 +868,22 @@ fn hint_iterator<'db>( let db = sema.db; let strukt = ty.strip_references().as_adt()?; let krate = strukt.module(db).krate(db); - if krate != famous_defs.core()? { - return None; - } let iter_trait = famous_defs.core_iter_Iterator()?; let iter_mod = famous_defs.core_iter()?; - // Assert that this struct comes from `core::iter`. - if !(strukt.visibility(db) == hir::Visibility::Public - && strukt.module(db).path_to_root(db).contains(&iter_mod)) - { + let is_core_adapter = Some(krate) == famous_defs.core() + && strukt.visibility(db) == hir::Visibility::Public + && strukt.module(db).path_to_root(db).contains(&iter_mod); + let is_custom_adapter = || { + let params = hir::GenericDef::Adt(strukt).type_or_const_params(db); + params + .iter() + .filter_map(|it| it.as_type_param(db)) + .any(|it| it.trait_bounds(db).contains(&iter_trait)) + }; + + // Assert that this struct iterator adapter, excludes like `Range`. + if !is_core_adapter && !is_custom_adapter() { return None; } diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs index e008a7b940662..c818a1ef5fe10 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs @@ -775,4 +775,123 @@ fn make() -> Foo { "#]], ); } + + #[test] + fn custom_iterator_adapter_chaining() { + check_expect_clear_loc( + InlayHintsConfig { chaining_hints: true, ..DISABLED_CONFIG }, + r#" +//- minicore: iterators +fn main() { + [1, 2, 3].into_iter() + .merge_by([2, 4, 6], |a,b|a { + left: I, + right: J, + cmp_fn: F, +} +impl Iterator for MergeBy +where + I: Iterator, + J: Iterator, + F: FnMut(&I::Item, &J::Item) -> bool, +{ + type Item = I::Item; + + fn next(&mut self) -> Option { loop {} } +} + +trait Itertools: Iterator { + fn merge_by(self, other: J, is_first: F) -> MergeBy + where + Self: Sized, + J: IntoIterator, + F: FnMut(&Self::Item, &Self::Item) -> bool, + { + MergeBy { left: self, right: other.into_iter(), cmp_fn: is_first } + } +} +impl Itertools for I {} +"#, + expect![[r#" + [ + ( + 16..76, + [ + "impl ", + InlayHintLabelPart { + text: "Iterator", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + "<", + InlayHintLabelPart { + text: "Item", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + " = i32>", + ], + ), + ( + 16..37, + [ + "impl ", + InlayHintLabelPart { + text: "Iterator", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + "<", + InlayHintLabelPart { + text: "Item", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + " = i32>", + ], + ), + ] + "#]], + ); + } } diff --git a/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs b/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs index e33446e4a148b..dfa8aef3012b9 100644 --- a/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs +++ b/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs @@ -475,6 +475,7 @@ define_symbols! { panic, Param, parse, + partial_eq, partial_ord, PartialEq, PartialOrd, diff --git a/src/tools/rust-analyzer/crates/paths/src/lib.rs b/src/tools/rust-analyzer/crates/paths/src/lib.rs index d6d9ed4676c16..5ded23c149bbb 100644 --- a/src/tools/rust-analyzer/crates/paths/src/lib.rs +++ b/src/tools/rust-analyzer/crates/paths/src/lib.rs @@ -308,6 +308,12 @@ impl AbsPath { self.0.components() } // endregion:delegate-methods + + /// `"/a/b/c/d/e".short_relative_by("b/c")` -> `"d/e"` + pub fn short_relative_by(&self, dummy: impl AsRef) -> Option<&RelPath> { + let prefix = self.0.ancestors().find(|prefix| prefix.ends_with(&dummy))?; + self.strip_prefix(AbsPath::assert(prefix)) + } } impl fmt::Display for AbsPath { diff --git a/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs b/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs index 126c0b41bb9f4..8ad210724cd0b 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs @@ -196,7 +196,8 @@ pub(crate) fn make_lockfile_copy( let temp_dir = NamedTempDir::new("rust-analyzer").ok()?; let path = temp_dir.path().join("Cargo.lock"); - std::fs::copy(lockfile_path.as_std_path(), &path).ok()?; + // `fs::read` + `fs::write` instead of `fs::copy` to avoid copying permission bits. + std::fs::write(&path, std::fs::read(lockfile_path.as_std_path()).ok()?).ok()?; Some(LockfileCopy { path: Utf8PathBuf::from_path_buf(path).ok()?, usage, _temp_dir: temp_dir }) } diff --git a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs index db3cecb5b2a31..56c1b8ff1acd8 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs @@ -791,7 +791,7 @@ impl ProjectWorkspace { RustLibSrcWorkspace::Json(project_json) => project_json .crates() .map(|(_, krate)| PackageRoot { - is_local: false, + is_local: krate.is_workspace_member, include: krate.include.clone(), exclude: krate.exclude.clone(), }) diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs index 3cd7a9ac9282e..68d7164698a2b 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs @@ -1034,11 +1034,15 @@ impl GlobalState { let mut message = format!("{n_done}/{n_total}"); if let Some(dir) = dir { + let common_std = "lib/rustlib/src/rust"; message += &format!( ": {}", match dir.strip_prefix(self.config.workspace_root_for(&dir)) { Some(relative_path) => relative_path.as_utf8_path(), - None => dir.as_ref(), + None => match dir.short_relative_by(common_std) { + Some(short) => short.as_ref(), + None => dir.as_ref(), + }, } ); } diff --git a/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs b/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs index 1ef6954e5a6ce..932dec3b37d85 100644 --- a/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs +++ b/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs @@ -37,6 +37,7 @@ pub struct Pool { struct Job { requested_intent: ThreadIntent, f: Box, + wg: Option, } impl Pool { @@ -67,6 +68,7 @@ impl Pool { // discard the panic, we should've logged the backtrace already drop(panic::catch_unwind(job.f)); extant_tasks.fetch_sub(1, Ordering::SeqCst); + drop(job.wg); } } }) @@ -89,7 +91,7 @@ impl Pool { f(); }); - let job = Job { requested_intent: intent, f }; + let job = Job { requested_intent: intent, f, wg: None }; self.extant_tasks.fetch_add(1, Ordering::SeqCst); self.job_sender.send(job).unwrap(); } @@ -127,15 +129,14 @@ impl<'scope> Scope<'_, 'scope> { where F: 'scope + FnOnce() + Send + UnwindSafe, { - let wg = self.wg.clone(); let f = Box::new(move || { if cfg!(debug_assertions) { intent.assert_is_used_on_current_thread(); } f(); - drop(wg); }); + let wg = self.wg.clone(); let job = Job { requested_intent: intent, f: unsafe { @@ -144,8 +145,134 @@ impl<'scope> Scope<'_, 'scope> { Box, >(f) }, + wg: Some(wg), }; self.pool.extant_tasks.fetch_add(1, Ordering::SeqCst); self.pool.job_sender.send(job).unwrap(); } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }; + + fn spawn_scoped_worker(pool: &Pool) { + pool.scoped(|scope| scope.spawn(ThreadIntent::Worker, || {})); + } + + #[test] + fn new_creates_empty_pool() { + let pool = Pool::new(2); + assert_eq!(pool.len(), 0); + assert!(pool.is_empty()); + } + + #[test] + fn spawn_executes_function() { + let pool = Pool::new(1); + let executed = Arc::new(AtomicBool::new(false)); + let executed_clone = Arc::clone(&executed); + pool.spawn(ThreadIntent::Worker, move || { + executed_clone.store(true, Ordering::SeqCst); + }); + spawn_scoped_worker(&pool); + assert!(executed.load(Ordering::SeqCst)); + } + + #[test] + fn spawn_changes_thread_intent() { + let pool = Pool::new(1); + let count = Arc::new(AtomicUsize::new(0)); + let first = Arc::clone(&count); + pool.spawn(ThreadIntent::Worker, move || { + first.fetch_add(669, Ordering::SeqCst); + }); + let second = Arc::clone(&count); + pool.spawn(ThreadIntent::LatencySensitive, move || { + second.fetch_add(668, Ordering::SeqCst); + }); + spawn_scoped_worker(&pool); + assert_eq!(count.load(Ordering::SeqCst), 1337); + } + + #[test] + fn spawn_handles_panicking_function() { + let pool = Pool::new(1); + pool.spawn(ThreadIntent::Worker, || panic!()); + let executed = Arc::new(AtomicBool::new(false)); + let executed_clone = Arc::clone(&executed); + pool.spawn(ThreadIntent::Worker, move || { + executed_clone.store(true, Ordering::SeqCst); + }); + spawn_scoped_worker(&pool); + assert!(executed.load(Ordering::SeqCst)); + } + + #[test] + fn scoped_executes_borrowing_function() { + let pool = Pool::new(1); + let value = 42; + let ran = AtomicBool::new(false); + let result = pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || { + ran.store(true, Ordering::SeqCst); + }); + value + 1 + }); + assert_eq!(result, 43); + assert!(ran.load(Ordering::SeqCst)); + } + + #[test] + fn scoped_executes_multiple_functions() { + let pool = Pool::new(2); + let value = AtomicUsize::new(0); + pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || { + value.fetch_add(9, Ordering::SeqCst); + }); + scope.spawn(ThreadIntent::LatencySensitive, || { + value.fetch_add(10, Ordering::SeqCst); + }); + }); + assert_eq!(value.load(Ordering::SeqCst), 19); + } + + #[test] + fn scoped_handles_panicking_function() { + let pool = Pool::new(1); + pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || panic!()); + }); + let ran = AtomicBool::new(false); + pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || ran.store(true, Ordering::SeqCst)); + }); + assert!(ran.load(Ordering::SeqCst)); + } + + #[test] + fn scoped_returns_result_after_tasks_finish() { + let pool = Pool::new(2); + let value = AtomicUsize::new(0); + let result = pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || { + value.store(19991005, Ordering::SeqCst); + }); + 0xC0FFEE + }); + assert_eq!(result, 0xC0FFEE); + assert_eq!(value.load(Ordering::SeqCst), 19991005); + } + + #[test] + fn zero_thread_pool_starts_empty() { + let pool = Pool::new(0); + assert_eq!(pool.len(), 0); + assert!(pool.is_empty()); + } +} diff --git a/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs b/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs index 7c2ba4d53d913..237bb64e8e771 100644 --- a/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs +++ b/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs @@ -1317,7 +1317,7 @@ pub mod range { pub mod cmp { use crate::marker::PointeeSized; - #[lang = "eq"] + #[lang = "partial_eq"] pub trait PartialEq: PointeeSized { fn eq(&self, other: &Rhs) -> bool; fn ne(&self, other: &Rhs) -> bool { @@ -1325,6 +1325,7 @@ pub mod cmp { } } + #[lang = "eq"] pub trait Eq: PartialEq + PointeeSized {} // region:builtin_impls diff --git a/src/tools/rust-analyzer/josh-sync.toml b/src/tools/rust-analyzer/josh-sync.toml index a12cfa1b5cbd5..5cd30792f9aac 100644 --- a/src/tools/rust-analyzer/josh-sync.toml +++ b/src/tools/rust-analyzer/josh-sync.toml @@ -4,3 +4,6 @@ filter = ":rev(55d9a533b309119c8acd13061581b43ae8840823:prefix=src/tools/rust-an [[post-pull]] cmd = ["cargo", "fmt"] commit-message = "Format code" + +[push-pr] +suffix = "r? @ghost" diff --git a/src/tools/rust-analyzer/rust-version b/src/tools/rust-analyzer/rust-version index 2ab8919989008..188d50ebbcd66 100644 --- a/src/tools/rust-analyzer/rust-version +++ b/src/tools/rust-analyzer/rust-version @@ -1 +1 @@ -4c46afa63688fb473618f9b3553d70b0c15a88eb +e3b9a8345a8a58fda3ac9446c532625d5a59acd8 diff --git a/src/tools/rustfmt/src/expr.rs b/src/tools/rustfmt/src/expr.rs index a9eccf1c7785a..924ac2cc2c56b 100644 --- a/src/tools/rustfmt/src/expr.rs +++ b/src/tools/rustfmt/src/expr.rs @@ -430,7 +430,7 @@ pub(crate) fn format_expr( | ast::ExprKind::IncludedBytes(..) | ast::ExprKind::OffsetOf(..) | ast::ExprKind::UnsafeBinderCast(..) - | ast::ExprKind::GcaMacro(..) => { + | ast::ExprKind::Gca(..) => { // These don't normally occur in the AST because macros aren't expanded. However, // rustfmt tries to parse macro arguments when formatting macros, so it's not totally // impossible for rustfmt to come across one of these nodes when formatting a file. diff --git a/src/tools/rustfmt/src/types.rs b/src/tools/rustfmt/src/types.rs index 6451595449046..f24f62d23d2e0 100644 --- a/src/tools/rustfmt/src/types.rs +++ b/src/tools/rustfmt/src/types.rs @@ -1042,7 +1042,7 @@ impl Rewrite for ast::Ty { Ok(result) } ast::TyKind::FieldOf(..) - | ast::TyKind::GcaMacro(..) + | ast::TyKind::Gca(..) | ast::TyKind::Pat(..) | ast::TyKind::View(..) => { // These don't normally occur in the AST because macros aren't expanded. However, diff --git a/src/tools/rustfmt/src/utils.rs b/src/tools/rustfmt/src/utils.rs index f7933ac52f75c..c0762dd6232d9 100644 --- a/src/tools/rustfmt/src/utils.rs +++ b/src/tools/rustfmt/src/utils.rs @@ -562,7 +562,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Unary(_, ref expr) | ast::ExprKind::Try(ref expr) | ast::ExprKind::Yield(YieldKind::Prefix(Some(ref expr))) - | ast::ExprKind::GcaMacro(ref expr) => is_block_expr(context, expr, repr), + | ast::ExprKind::Gca(ref expr) => is_block_expr(context, expr, repr), ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr), // This can only be a string lit ast::ExprKind::Lit(_) => { diff --git a/tests/pretty/delegation/generics.pp b/tests/pretty/delegation/generics.pp index f5b42b351633d..dce3886a4f15c 100644 --- a/tests/pretty/delegation/generics.pp +++ b/tests/pretty/delegation/generics.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] #![attr = Feature([fn_delegation#0])] extern crate std; diff --git a/tests/pretty/delegation/inherit-attributes.pp b/tests/pretty/delegation/inherit-attributes.pp index 53f977ebbb7ac..b08a2f37eb4b2 100644 --- a/tests/pretty/delegation/inherit-attributes.pp +++ b/tests/pretty/delegation/inherit-attributes.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] #![attr = Feature([fn_delegation#0])] extern crate std; diff --git a/tests/pretty/delegation/inline-attribute.pp b/tests/pretty/delegation/inline-attribute.pp index 8787a9e167405..faaacfbc6a4b5 100644 --- a/tests/pretty/delegation/inline-attribute.pp +++ b/tests/pretty/delegation/inline-attribute.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] #![attr = Feature([fn_delegation#0])] extern crate std; diff --git a/tests/pretty/gca-macro.pp b/tests/pretty/gca-macro.pp index 271b92b0e319e..90ff2b10f8321 100644 --- a/tests/pretty/gca-macro.pp +++ b/tests/pretty/gca-macro.pp @@ -2,6 +2,7 @@ #![no_std] //@ pretty-mode:expanded //@ pp-exact:gca-macro.pp +//@ pretty-compare-only (expands to internal syntax) #![feature(gca_min_const_items)] extern crate std; #[prelude_import] @@ -11,4 +12,4 @@ fn f() {} -fn main() { f::(); f::<{ core::gca! (2) }>(); } +fn main() { f::(); f::<{ k#gca(2) }>(); } diff --git a/tests/pretty/gca-macro.rs b/tests/pretty/gca-macro.rs index decc72e18b4bf..8b5f9449bfd87 100644 --- a/tests/pretty/gca-macro.rs +++ b/tests/pretty/gca-macro.rs @@ -1,5 +1,6 @@ //@ pretty-mode:expanded //@ pp-exact:gca-macro.pp +//@ pretty-compare-only (expands to internal syntax) #![feature(gca_min_const_items)] use std::gca; diff --git a/tests/pretty/hir-delegation.pp b/tests/pretty/hir-delegation.pp index 97364da0e02d8..1b74b8f8ba911 100644 --- a/tests/pretty/hir-delegation.pp +++ b/tests/pretty/hir-delegation.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] #![attr = Feature([fn_delegation#0])] extern crate std; diff --git a/tests/pretty/hir-lifetimes.pp b/tests/pretty/hir-lifetimes.pp index daee41b37889d..85b36fba7ef3c 100644 --- a/tests/pretty/hir-lifetimes.pp +++ b/tests/pretty/hir-lifetimes.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "unused" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "unused" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] diff --git a/tests/pretty/lint-attrs-filtered-out.pp b/tests/pretty/lint-attrs-filtered-out.pp new file mode 100644 index 0000000000000..796fa2fe239b0 --- /dev/null +++ b/tests/pretty/lint-attrs-filtered-out.pp @@ -0,0 +1,11 @@ +extern crate std; +#[attr = PreludeImport] +use ::std::prelude::rust_2015::*; +//@ pretty-compare-only +//@ pretty-mode:hir +//@ pp-exact:lint-attrs-filtered-out.pp + +// `does_not_exist` is filtered out on the hir +#[attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, +kind: Deny}])] +fn main() { } diff --git a/tests/pretty/lint-attrs-filtered-out.rs b/tests/pretty/lint-attrs-filtered-out.rs new file mode 100644 index 0000000000000..9dc4898f3ff41 --- /dev/null +++ b/tests/pretty/lint-attrs-filtered-out.rs @@ -0,0 +1,7 @@ +//@ pretty-compare-only +//@ pretty-mode:hir +//@ pp-exact:lint-attrs-filtered-out.pp + +// `does_not_exist` is filtered out on the hir +#[deny(dead_code, does_not_exist)] +fn main() {} diff --git a/tests/pretty/pin-ergonomics-hir.pp b/tests/pretty/pin-ergonomics-hir.pp index 624cd37ce5fc4..11b4a87b1c4ce 100644 --- a/tests/pretty/pin-ergonomics-hir.pp +++ b/tests/pretty/pin-ergonomics-hir.pp @@ -1,7 +1,7 @@ #![attr = Feature([pin_ergonomics#0])] -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "dead_code" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, kind: Allow}, -LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] diff --git a/tests/ui/attributes/malformed-lint-reason.rs b/tests/ui/attributes/malformed-lint-reason.rs new file mode 100644 index 0000000000000..05d4e5d9c6f89 --- /dev/null +++ b/tests/ui/attributes/malformed-lint-reason.rs @@ -0,0 +1,7 @@ +// Test that an invalid name-value argument suggests `reason`. +#![allow(dead_code, note = "testing")] +//~^ ERROR malformed `allow` attribute input +//~| ERROR malformed `allow` attribute input +//~| ERROR malformed `allow` attribute input + +fn main() {} diff --git a/tests/ui/attributes/malformed-lint-reason.stderr b/tests/ui/attributes/malformed-lint-reason.stderr new file mode 100644 index 0000000000000..c18f9b0ef4729 --- /dev/null +++ b/tests/ui/attributes/malformed-lint-reason.stderr @@ -0,0 +1,40 @@ +error: malformed `allow` attribute input + --> $DIR/malformed-lint-reason.rs:2:21 + | +LL | #![allow(dead_code, note = "testing")] + | ^^^^^^^^^^^^^^^^ not the name of a lint + | +help: to provide a reason, use `reason = ""` + | +LL - #![allow(dead_code, note = "testing")] +LL + #![allow(dead_code, reason = "testing")] + | + +error: malformed `allow` attribute input + --> $DIR/malformed-lint-reason.rs:2:21 + | +LL | #![allow(dead_code, note = "testing")] + | ^^^^^^^^^^^^^^^^ not the name of a lint + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: to provide a reason, use `reason = ""` + | +LL - #![allow(dead_code, note = "testing")] +LL + #![allow(dead_code, reason = "testing")] + | + +error: malformed `allow` attribute input + --> $DIR/malformed-lint-reason.rs:2:21 + | +LL | #![allow(dead_code, note = "testing")] + | ^^^^^^^^^^^^^^^^ not the name of a lint + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: to provide a reason, use `reason = ""` + | +LL - #![allow(dead_code, note = "testing")] +LL + #![allow(dead_code, reason = "testing")] + | + +error: aborting due to 3 previous errors + diff --git a/tests/ui/const-generics/mgca/gca-macro-correct-rib.rs b/tests/ui/const-generics/mgca/gca-macro-correct-rib.rs index b8ac0c86f51cb..235fd50f0d892 100644 --- a/tests/ui/const-generics/mgca/gca-macro-correct-rib.rs +++ b/tests/ui/const-generics/mgca/gca-macro-correct-rib.rs @@ -1,4 +1,4 @@ -//! make sure TyKind::GcaMacro resolves properly with the correct ribs and doesn't ICE +//! Make sure `TyKind::Gca` resolves properly with the correct ribs and doesn't ICE. #![feature(gca_min_const_items)] use std::gca; diff --git a/tests/ui/const-generics/mgca/gca-macro-multiple-exprs.rs b/tests/ui/const-generics/mgca/gca-macro-multiple-exprs.rs index 3ca7243c97a63..e57e7828a16e0 100644 --- a/tests/ui/const-generics/mgca/gca-macro-multiple-exprs.rs +++ b/tests/ui/const-generics/mgca/gca-macro-multiple-exprs.rs @@ -2,5 +2,6 @@ use std::gca; struct S; fn foo(_: S) {} -//~^ ERROR gca! takes 1 argument +//~^ ERROR expected one of +//~| ERROR type provided when a constant was expected fn main() {} diff --git a/tests/ui/const-generics/mgca/gca-macro-multiple-exprs.stderr b/tests/ui/const-generics/mgca/gca-macro-multiple-exprs.stderr index 992d981624924..397815096db09 100644 --- a/tests/ui/const-generics/mgca/gca-macro-multiple-exprs.stderr +++ b/tests/ui/const-generics/mgca/gca-macro-multiple-exprs.stderr @@ -1,8 +1,15 @@ -error: gca! takes 1 argument +error: expected one of `!`, `)`, `.`, `::`, `?`, `{`, or an operator, found `,` + --> $DIR/gca-macro-multiple-exprs.rs:4:51 + | +LL | fn foo(_: S) {} + | ^ expected one of 7 possible tokens + +error[E0747]: type provided when a constant was expected --> $DIR/gca-macro-multiple-exprs.rs:4:45 | LL | fn foo(_: S) {} | ^^^^^^^^^^ -error: aborting due to 1 previous error +error: aborting due to 2 previous errors +For more information about this error, try `rustc --explain E0747`. diff --git a/tests/ui/eii/cfg_on_eii.stdout b/tests/ui/eii/cfg_on_eii.stdout index 8d3e892b0867d..74922ab51f3f0 100644 --- a/tests/ui/eii/cfg_on_eii.stdout +++ b/tests/ui/eii/cfg_on_eii.stdout @@ -1,5 +1,5 @@ #![attr = Feature([extern_item_impls#0, extern_item_default_impls#0])] -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "deprecated" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "deprecated" }, kind: Deny}])] extern crate std; #[attr = PreludeImport] diff --git a/tests/ui/error-codes/E0452.rs b/tests/ui/error-codes/E0452.rs index 6a0437df7b14e..947f8f1237bf5 100644 --- a/tests/ui/error-codes/E0452.rs +++ b/tests/ui/error-codes/E0452.rs @@ -1,8 +1,6 @@ -#![allow(foo = "")] //~ ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed -fn main() { -} +#![allow(foo = "")] +//~^ ERROR malformed +//~| ERROR malformed +//~| ERROR malformed + +fn main() {} diff --git a/tests/ui/error-codes/E0452.stderr b/tests/ui/error-codes/E0452.stderr index c34d9a2a01b28..0244de4a7bc81 100644 --- a/tests/ui/error-codes/E0452.stderr +++ b/tests/ui/error-codes/E0452.stderr @@ -4,16 +4,11 @@ error: malformed `allow` attribute input LL | #![allow(foo = "")] | ^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - -error: malformed `allow` attribute input - --> $DIR/E0452.rs:1:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(foo = "")] - | ^^^^^^^^ not the name of a lint +LL - #![allow(foo = "")] +LL + #![allow(reason = "")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: malformed `allow` attribute input --> $DIR/E0452.rs:1:10 @@ -21,17 +16,12 @@ error: malformed `allow` attribute input LL | #![allow(foo = "")] | ^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/E0452.rs:1:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(foo = "")] - | ^^^^^^^^ not the name of a lint +LL - #![allow(foo = "")] +LL + #![allow(reason = "")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: malformed `allow` attribute input --> $DIR/E0452.rs:1:10 @@ -39,17 +29,12 @@ error: malformed `allow` attribute input LL | #![allow(foo = "")] | ^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/E0452.rs:1:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(foo = "")] - | ^^^^^^^^ not the name of a lint +LL - #![allow(foo = "")] +LL + #![allow(reason = "")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 6 previous errors +error: aborting due to 3 previous errors diff --git a/tests/ui/feature-gates/feature-gate-strict_provenance_lints.stderr b/tests/ui/feature-gates/feature-gate-strict_provenance_lints.stderr index 4e7c835b57912..d14e7328c308c 100644 --- a/tests/ui/feature-gates/feature-gate-strict_provenance_lints.stderr +++ b/tests/ui/feature-gates/feature-gate-strict_provenance_lints.stderr @@ -10,14 +10,6 @@ LL | #![deny(implicit_provenance_casts)] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date = note: `#[warn(unknown_lints)]` on by default -warning: lint `fuzzy_provenance_casts` has been renamed to `implicit_provenance_casts` - --> $DIR/feature-gate-strict_provenance_lints.rs:7:9 - | -LL | #![deny(fuzzy_provenance_casts)] - | ^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `implicit_provenance_casts` - | - = note: `#[warn(renamed_and_removed_lints)]` on by default - warning: unknown lint: `implicit_provenance_casts` --> $DIR/feature-gate-strict_provenance_lints.rs:7:9 | @@ -29,12 +21,6 @@ LL | #![deny(fuzzy_provenance_casts)] = help: add `#![feature(strict_provenance_lints)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -warning: lint `lossy_provenance_casts` has been renamed to `implicit_provenance_casts` - --> $DIR/feature-gate-strict_provenance_lints.rs:10:9 - | -LL | #![deny(lossy_provenance_casts)] - | ^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `implicit_provenance_casts` - warning: unknown lint: `implicit_provenance_casts` --> $DIR/feature-gate-strict_provenance_lints.rs:10:9 | @@ -46,5 +32,19 @@ LL | #![deny(lossy_provenance_casts)] = help: add `#![feature(strict_provenance_lints)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date +warning: lint `fuzzy_provenance_casts` has been renamed to `implicit_provenance_casts` + --> $DIR/feature-gate-strict_provenance_lints.rs:7:9 + | +LL | #![deny(fuzzy_provenance_casts)] + | ^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `implicit_provenance_casts` + | + = note: `#[warn(renamed_and_removed_lints)]` on by default + +warning: lint `lossy_provenance_casts` has been renamed to `implicit_provenance_casts` + --> $DIR/feature-gate-strict_provenance_lints.rs:10:9 + | +LL | #![deny(lossy_provenance_casts)] + | ^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `implicit_provenance_casts` + warning: 5 warnings emitted diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr index f685a989c0aa6..9b091ff4fbf91 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr @@ -12,6 +12,27 @@ warning: `#[macro_escape]` is a deprecated synonym for `#[macro_use]` LL | #[macro_escape] | ^^^^^^^^^^^^^^^ +warning: the feature `rust1` has been stable since 1.0.0 and no longer requires an attribute to enable + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:101:12 + | +LL | #![feature(rust1)] + | ^^^^^ + | + = note: `#[warn(stable_features)]` on by default + +warning: unused attribute + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:257:9 + | +LL | #![path="3800"] + | ^^^^^^^^^^^^^^^ help: remove this attribute + | + = note: `#[path]` is unused on this inline module +note: the lint level is defined here + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:35:9 + | +LL | #![warn(unused_attributes, unknown_lints)] + | ^^^^^^^^^^^^^^^^^ + warning: unknown lint: `x5400` --> $DIR/issue-43106-gating-of-builtin-attrs.rs:41:9 | @@ -42,6 +63,87 @@ warning: unknown lint: `x5100` LL | #![deny(x5100)] | ^^^^^ +warning: the `macro_use` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:45:4 + | +LL | #![macro_use] + | ^^^^^^^^^ + | + = help: the `macro_use` attribute can be applied to extern crates and modules + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `should_panic` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:51:4 + | +LL | #![should_panic] + | ^^^^^^^^^^^^ + | + = help: the `should_panic` attribute can only be applied to functions + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `ignore` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:55:4 + | +LL | #![ignore] + | ^^^^^^ + | + = help: the `ignore` attribute can only be applied to functions + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `proc_macro_derive` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:63:4 + | +LL | #![proc_macro_derive(Test)] + | ^^^^^^^^^^^^^^^^^ + | + = help: the `proc_macro_derive` attribute can only be applied to functions + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `cold` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:68:4 + | +LL | #![cold] + | ^^^^ + | + = help: the `cold` attribute can only be applied to functions + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `link` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:72:4 + | +LL | #![link(name = "x")] + | ^^^^ + | + = help: the `link` attribute can only be applied to foreign modules + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `link_name` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:76:4 + | +LL | #![link_name = "1900"] + | ^^^^^^^^^ + | + = help: the `link_name` attribute can be applied to foreign functions and foreign statics + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `link_section` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:81:4 + | +LL | #![link_section = ",1800"] + | ^^^^^^^^^^^^ + | + = help: the `link_section` attribute can be applied to functions and statics + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `must_use` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:86:4 + | +LL | #![must_use] + | ^^^^^^^^ + | + = help: the `must_use` attribute can be applied to data types, functions, and traits + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + warning: unknown lint: `x5400` --> $DIR/issue-43106-gating-of-builtin-attrs.rs:112:8 | @@ -186,108 +288,6 @@ warning: unknown lint: `x5100` LL | #[deny(x5100)] impl S { } | ^^^^^ -warning: the feature `rust1` has been stable since 1.0.0 and no longer requires an attribute to enable - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:101:12 - | -LL | #![feature(rust1)] - | ^^^^^ - | - = note: `#[warn(stable_features)]` on by default - -warning: unused attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:257:9 - | -LL | #![path="3800"] - | ^^^^^^^^^^^^^^^ help: remove this attribute - | - = note: `#[path]` is unused on this inline module -note: the lint level is defined here - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:35:9 - | -LL | #![warn(unused_attributes, unknown_lints)] - | ^^^^^^^^^^^^^^^^^ - -warning: the `macro_use` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:45:4 - | -LL | #![macro_use] - | ^^^^^^^^^ - | - = help: the `macro_use` attribute can be applied to extern crates and modules - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `should_panic` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:51:4 - | -LL | #![should_panic] - | ^^^^^^^^^^^^ - | - = help: the `should_panic` attribute can only be applied to functions - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `ignore` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:55:4 - | -LL | #![ignore] - | ^^^^^^ - | - = help: the `ignore` attribute can only be applied to functions - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `proc_macro_derive` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:63:4 - | -LL | #![proc_macro_derive(Test)] - | ^^^^^^^^^^^^^^^^^ - | - = help: the `proc_macro_derive` attribute can only be applied to functions - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `cold` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:68:4 - | -LL | #![cold] - | ^^^^ - | - = help: the `cold` attribute can only be applied to functions - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `link` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:72:4 - | -LL | #![link(name = "x")] - | ^^^^ - | - = help: the `link` attribute can only be applied to foreign modules - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `link_name` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:76:4 - | -LL | #![link_name = "1900"] - | ^^^^^^^^^ - | - = help: the `link_name` attribute can be applied to foreign functions and foreign statics - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `link_section` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:81:4 - | -LL | #![link_section = ",1800"] - | ^^^^^^^^^^^^ - | - = help: the `link_section` attribute can be applied to functions and statics - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `must_use` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:86:4 - | -LL | #![must_use] - | ^^^^^^^^ - | - = help: the `must_use` attribute can be applied to data types, functions, and traits - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - warning: the `macro_use` attribute cannot be used on functions --> $DIR/issue-43106-gating-of-builtin-attrs.rs:192:7 | diff --git a/tests/ui/lint/lint-check-on-macro.rs b/tests/ui/lint/lint-check-on-macro.rs new file mode 100644 index 0000000000000..047b024dbab20 --- /dev/null +++ b/tests/ui/lint/lint-check-on-macro.rs @@ -0,0 +1,15 @@ +macro_rules! identity { ($( $tt:tt )*) => { $( $tt )* } } + +fn main() { + #[expect(wat::doesnt_exist)] + //~^ WARN cannot be used on + //~| ERROR unknown tool name + println!(); + + identity!{ + #[expect(wat::doesnt_exist)] + //~^ WARN cannot be used on + //~| ERROR unknown tool name + println!(); + } +} diff --git a/tests/ui/lint/lint-check-on-macro.stderr b/tests/ui/lint/lint-check-on-macro.stderr new file mode 100644 index 0000000000000..0dac7bed002da --- /dev/null +++ b/tests/ui/lint/lint-check-on-macro.stderr @@ -0,0 +1,42 @@ +error[E0710]: unknown tool name `wat` found in scoped lint: `wat::doesnt_exist` + --> $DIR/lint-check-on-macro.rs:4:14 + | +LL | #[expect(wat::doesnt_exist)] + | ^^^ + | + = help: add `#![register_tool(wat)]` to the crate root + +error[E0710]: unknown tool name `wat` found in scoped lint: `wat::doesnt_exist` + --> $DIR/lint-check-on-macro.rs:10:18 + | +LL | #[expect(wat::doesnt_exist)] + | ^^^ + | + = help: add `#![register_tool(wat)]` to the crate root + +warning: the `expect` attribute cannot be used on macro calls + --> $DIR/lint-check-on-macro.rs:4:7 + | +LL | #[expect(wat::doesnt_exist)] + | ^^^^^^ +... +LL | println!(); + | + = help: the `expect` attribute can be applied to associated consts, associated types, break expressions, const parameters, constants, crates, data types, enum variants, extern crates, for loops, foreign modules, foreign statics, function params, functions, global asms, impl blocks, lifetime parameters, loops, macro defs, match arms, modules, pattern fields, statics, struct fields, trait aliases, traits, type aliases, type parameters, use statements, and while loops + = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion + = note: requested on the command line with `-W unused-attributes` + +warning: the `expect` attribute cannot be used on macro calls + --> $DIR/lint-check-on-macro.rs:10:11 + | +LL | #[expect(wat::doesnt_exist)] + | ^^^^^^ +... +LL | println!(); + | + = help: the `expect` attribute can be applied to associated consts, associated types, break expressions, const parameters, constants, crates, data types, enum variants, extern crates, for loops, foreign modules, foreign statics, function params, functions, global asms, impl blocks, lifetime parameters, loops, macro defs, match arms, modules, pattern fields, statics, struct fields, trait aliases, traits, type aliases, type parameters, use statements, and while loops + = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion + +error: aborting due to 2 previous errors; 2 warnings emitted + +For more information about this error, try `rustc --explain E0710`. diff --git a/tests/ui/lint/lint-malformed.rs b/tests/ui/lint/lint-malformed.rs index 5fd92170363f0..e5a64cbf764f9 100644 --- a/tests/ui/lint/lint-malformed.rs +++ b/tests/ui/lint/lint-malformed.rs @@ -1,8 +1,7 @@ #![deny = "foo"] //~ ERROR malformed `deny` attribute input -#![allow(bar = "baz")] //~ ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed -fn main() { } +#![allow(bar = "baz")] +//~^ ERROR malformed +//~| ERROR malformed +//~| ERROR malformed + +fn main() {} diff --git a/tests/ui/lint/lint-malformed.stderr b/tests/ui/lint/lint-malformed.stderr index ceb7fe105bcd3..8afd9ac54e438 100644 --- a/tests/ui/lint/lint-malformed.stderr +++ b/tests/ui/lint/lint-malformed.stderr @@ -4,16 +4,11 @@ error: malformed `allow` attribute input LL | #![allow(bar = "baz")] | ^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - -error: malformed `allow` attribute input - --> $DIR/lint-malformed.rs:2:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^ not the name of a lint +LL - #![allow(bar = "baz")] +LL + #![allow(reason = "baz")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: malformed `allow` attribute input --> $DIR/lint-malformed.rs:2:10 @@ -21,17 +16,12 @@ error: malformed `allow` attribute input LL | #![allow(bar = "baz")] | ^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/lint-malformed.rs:2:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^ not the name of a lint +LL - #![allow(bar = "baz")] +LL + #![allow(reason = "baz")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0539]: malformed `deny` attribute input --> $DIR/lint-malformed.rs:1:4 @@ -60,18 +50,13 @@ error: malformed `allow` attribute input LL | #![allow(bar = "baz")] | ^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/lint-malformed.rs:2:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^ not the name of a lint +LL - #![allow(bar = "baz")] +LL + #![allow(reason = "baz")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 7 previous errors +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0539`. diff --git a/tests/ui/lint/reasons-erroneous.stderr b/tests/ui/lint/reasons-erroneous.stderr index 3c52a0d8e25b4..1288a9fa5d601 100644 --- a/tests/ui/lint/reasons-erroneous.stderr +++ b/tests/ui/lint/reasons-erroneous.stderr @@ -35,7 +35,11 @@ error: malformed `warn` attribute input LL | #![warn(bare_trait_objects, reasons = "leaders to no sure land, guides their bearings lost")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[warn(dead_code)]` for `dead_code` +help: to provide a reason, use `reason = ""` + | +LL - #![warn(bare_trait_objects, reasons = "leaders to no sure land, guides their bearings lost")] +LL + #![warn(bare_trait_objects, reason = "leaders to no sure land, guides their bearings lost")] + | error: malformed `warn` attribute input --> $DIR/reasons-erroneous.rs:13:22 @@ -43,7 +47,11 @@ error: malformed `warn` attribute input LL | #![warn(unsafe_code, blerp = "or in league with robbers have reversed the signposts")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[warn(dead_code)]` for `dead_code` +help: to provide a reason, use `reason = ""` + | +LL - #![warn(unsafe_code, blerp = "or in league with robbers have reversed the signposts")] +LL + #![warn(unsafe_code, reason = "or in league with robbers have reversed the signposts")] + | error: malformed `warn` attribute input --> $DIR/reasons-erroneous.rs:16:36 diff --git a/tests/ui/lint/register-tool-lint.rs b/tests/ui/lint/register-tool-lint.rs index 17d3afbf6e26e..f56d9a0a8c362 100644 --- a/tests/ui/lint/register-tool-lint.rs +++ b/tests/ui/lint/register-tool-lint.rs @@ -5,5 +5,3 @@ #![warn(abc::my_lint)] //~^ ERROR unknown tool name `abc` found in scoped lint //~| HELP add `#![register_tool(abc)]` -//~| ERROR unknown tool name `abc` -//~| HELP add `#![register_tool(abc)]` diff --git a/tests/ui/lint/register-tool-lint.stderr b/tests/ui/lint/register-tool-lint.stderr index 7ebdbdec92972..98b4af935d340 100644 --- a/tests/ui/lint/register-tool-lint.stderr +++ b/tests/ui/lint/register-tool-lint.stderr @@ -6,15 +6,6 @@ LL | #![warn(abc::my_lint)] | = help: add `#![register_tool(abc)]` to the crate root -error[E0710]: unknown tool name `abc` found in scoped lint: `abc::my_lint` - --> $DIR/register-tool-lint.rs:5:9 - | -LL | #![warn(abc::my_lint)] - | ^^^ - | - = help: add `#![register_tool(abc)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0710`. diff --git a/tests/ui/lint/renamed-lints-still-apply.stderr b/tests/ui/lint/renamed-lints-still-apply.stderr index 9eaf711293388..5e4dae1e21be7 100644 --- a/tests/ui/lint/renamed-lints-still-apply.stderr +++ b/tests/ui/lint/renamed-lints-still-apply.stderr @@ -1,11 +1,3 @@ -warning: lint `single_use_lifetime` has been renamed to `single_use_lifetimes` - --> $DIR/renamed-lints-still-apply.rs:2:9 - | -LL | #![deny(single_use_lifetime)] - | ^^^^^^^^^^^^^^^^^^^ help: use the new name: `single_use_lifetimes` - | - = note: `#[warn(renamed_and_removed_lints)]` on by default - error: lifetime parameter `'a` only used once --> $DIR/renamed-lints-still-apply.rs:6:9 | @@ -25,5 +17,13 @@ LL - fn _foo<'a>(_x: &'a u32) {} LL + fn _foo(_x: &u32) {} | +warning: lint `single_use_lifetime` has been renamed to `single_use_lifetimes` + --> $DIR/renamed-lints-still-apply.rs:2:9 + | +LL | #![deny(single_use_lifetime)] + | ^^^^^^^^^^^^^^^^^^^ help: use the new name: `single_use_lifetimes` + | + = note: `#[warn(renamed_and_removed_lints)]` on by default + error: aborting due to 1 previous error; 1 warning emitted diff --git a/tests/ui/tool-attributes/cross-crate.rs b/tests/ui/tool-attributes/cross-crate.rs index 1992174aca3e1..11c594de02aa3 100644 --- a/tests/ui/tool-attributes/cross-crate.rs +++ b/tests/ui/tool-attributes/cross-crate.rs @@ -5,6 +5,4 @@ extern crate use_tool; #[foo::bar] //~ ERROR cannot find module or crate `foo` in this scope #[allow(foo::baz)] //~ ERROR unknown tool name `foo` - //~| ERROR unknown tool name `foo` - //~| ERROR unknown tool name `foo` fn main() {} diff --git a/tests/ui/tool-attributes/cross-crate.stderr b/tests/ui/tool-attributes/cross-crate.stderr index 051a1b05405e9..6b669601f24f2 100644 --- a/tests/ui/tool-attributes/cross-crate.stderr +++ b/tests/ui/tool-attributes/cross-crate.stderr @@ -1,11 +1,3 @@ -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::baz` - --> $DIR/cross-crate.rs:7:9 - | -LL | #[allow(foo::baz)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - error[E0433]: cannot find module or crate `foo` in this scope --> $DIR/cross-crate.rs:6:3 | @@ -19,18 +11,8 @@ LL | #[allow(foo::baz)] | ^^^ | = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::baz` - --> $DIR/cross-crate.rs:7:9 - | -LL | #[allow(foo::baz)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 4 previous errors +error: aborting due to 2 previous errors Some errors have detailed explanations: E0433, E0710. For more information about an error, try `rustc --explain E0433`. diff --git a/tests/ui/tool-attributes/tool_lints.rs b/tests/ui/tool-attributes/tool_lints.rs index 9e4aa7a939acb..0a9be75681ca5 100644 --- a/tests/ui/tool-attributes/tool_lints.rs +++ b/tests/ui/tool-attributes/tool_lints.rs @@ -1,5 +1,3 @@ #[warn(foo::bar)] //~^ ERROR unknown tool name `foo` found in scoped lint: `foo::bar` -//~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` -//~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` fn main() {} diff --git a/tests/ui/tool-attributes/tool_lints.stderr b/tests/ui/tool-attributes/tool_lints.stderr index eee0a9784ece8..a0c5316d95b07 100644 --- a/tests/ui/tool-attributes/tool_lints.stderr +++ b/tests/ui/tool-attributes/tool_lints.stderr @@ -6,24 +6,6 @@ LL | #[warn(foo::bar)] | = help: add `#![register_tool(foo)]` to the crate root -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/tool_lints.rs:1:8 - | -LL | #[warn(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/tool_lints.rs:1:8 - | -LL | #[warn(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 3 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0710`. diff --git a/tests/ui/tool-attributes/unknown-lint-tool-name.rs b/tests/ui/tool-attributes/unknown-lint-tool-name.rs index 84ab7c1944ab2..cf26341d8b588 100644 --- a/tests/ui/tool-attributes/unknown-lint-tool-name.rs +++ b/tests/ui/tool-attributes/unknown-lint-tool-name.rs @@ -1,8 +1,4 @@ #![deny(foo::bar)] //~ ERROR unknown tool name `foo` found in scoped lint: `foo::bar` - //~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` - //~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` #[allow(foo::bar)] //~ ERROR unknown tool name `foo` found in scoped lint: `foo::bar` - //~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` - //~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` fn main() {} diff --git a/tests/ui/tool-attributes/unknown-lint-tool-name.stderr b/tests/ui/tool-attributes/unknown-lint-tool-name.stderr index 91baf88273756..8ef80efdbcf51 100644 --- a/tests/ui/tool-attributes/unknown-lint-tool-name.stderr +++ b/tests/ui/tool-attributes/unknown-lint-tool-name.stderr @@ -7,49 +7,13 @@ LL | #![deny(foo::bar)] = help: add `#![register_tool(foo)]` to the crate root error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:5:9 + --> $DIR/unknown-lint-tool-name.rs:3:9 | LL | #[allow(foo::bar)] | ^^^ | = help: add `#![register_tool(foo)]` to the crate root -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:1:9 - | -LL | #![deny(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:5:9 - | -LL | #[allow(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:1:9 - | -LL | #![deny(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:5:9 - | -LL | #[allow(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 6 previous errors +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0710`. diff --git a/tests/ui/unpretty/exhaustive.hir.stdout b/tests/ui/unpretty/exhaustive.hir.stdout index 4726e9aa762e7..f9816034b065b 100644 --- a/tests/ui/unpretty/exhaustive.hir.stdout +++ b/tests/ui/unpretty/exhaustive.hir.stdout @@ -3,9 +3,9 @@ coroutines#0, decl_macro#0, deref_patterns#0, explicit_tail_calls#0, forced_keywords#0, gen_blocks#0, more_qualified_paths#0, never_patterns#0, pattern_types#0, prelude_import#0, specialization#0, trace_macros#0, trait_alias#0, try_blocks#0, try_blocks_heterogeneous#0, yeet_expr#0])] -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}, -LintCheck {lint_name: LintName { tool: None, name: "unused_attributes" }, +LintCheck {lint_name_normalized: LintName { tool: None, name: "unused_attributes" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] @@ -41,9 +41,9 @@ use self::prelude::*; * inner multi-line doc comment */ #[doc = "inner doc attribute"] -#[attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "dead_code" }, +#[attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, kind: Allow}, -LintCheck {lint_name: LintName { tool: None, name: "unused_variables" }, +LintCheck {lint_name_normalized: LintName { tool: None, name: "unused_variables" }, kind: Allow}])] #[attr = NoStd] mod attributes { diff --git a/tests/ui/unpretty/struct-exprs-tuple-call-pretty-printing.stdout b/tests/ui/unpretty/struct-exprs-tuple-call-pretty-printing.stdout index d94a76fb882e1..aa1567fdb0d1c 100644 --- a/tests/ui/unpretty/struct-exprs-tuple-call-pretty-printing.stdout +++ b/tests/ui/unpretty/struct-exprs-tuple-call-pretty-printing.stdout @@ -1,6 +1,6 @@ #![attr = Feature([adt_const_params#0, gca_adts#0, gca_min_const_items#0, gca_macroless_args#0])] -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "dead_code" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] diff --git a/tests/ui/unpretty/unpretty-expr-fn-arg.stdout b/tests/ui/unpretty/unpretty-expr-fn-arg.stdout index d80b073e52b73..93938fed46d47 100644 --- a/tests/ui/unpretty/unpretty-expr-fn-arg.stdout +++ b/tests/ui/unpretty/unpretty-expr-fn-arg.stdout @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "dead_code" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] diff --git a/tests/ui/view-types/field-access.illegal.stderr b/tests/ui/view-types/field-access.illegal.stderr new file mode 100644 index 0000000000000..2001fb7e0b43c --- /dev/null +++ b/tests/ui/view-types/field-access.illegal.stderr @@ -0,0 +1,62 @@ +error: field `b` cannot be accessed + --> $DIR/field-access.rs:36:17 + | +LL | let _ = foo.b; + | ^ + | +note: this expression has type &view_type!(Foo.{ a }), of which only `a` can be accessed + --> $DIR/field-access.rs:36:13 + | +LL | let _ = foo.b; + | ^^^ + +error: field `1` cannot be accessed + --> $DIR/field-access.rs:43:18 + | +LL | let _ = &bar.1; + | ^ + | +note: this expression has type &view_type!(Bar.{ 0 }), of which only `0` can be accessed + --> $DIR/field-access.rs:43:14 + | +LL | let _ = &bar.1; + | ^^^ + +error: field `c` cannot be accessed + --> $DIR/field-access.rs:53:17 + | +LL | let _ = foo.c; + | ^ + | +note: this expression has type &&view_type!(Foo.{ a, b }), of which only `a` and `b` can be accessed + --> $DIR/field-access.rs:53:13 + | +LL | let _ = foo.c; + | ^^^ + +error: field `2` cannot be accessed + --> $DIR/field-access.rs:60:18 + | +LL | let _ = &bar.2; + | ^ + | +note: this expression has type &&view_type!(Bar.{ 0, 1 }), of which only `0` and `1` can be accessed + --> $DIR/field-access.rs:60:14 + | +LL | let _ = &bar.2; + | ^^^ + +error: field `b` cannot be accessed + --> $DIR/field-access.rs:71:17 + | +LL | let _ = baz.b; + | ^ + | +note: this expression has type Baz, of which only `a` can be accessed + --> $DIR/field-access.rs:71:13 + | +LL | let _ = baz.b; + | ^^^ + +error: aborting due to 5 previous errors + diff --git a/tests/ui/view-types/field-access.rs b/tests/ui/view-types/field-access.rs new file mode 100644 index 0000000000000..50fad120f21f3 --- /dev/null +++ b/tests/ui/view-types/field-access.rs @@ -0,0 +1,76 @@ +//@ revisions: legal illegal +//@[legal] check-pass + +#![feature(view_types)] + +use std::ops::Deref; +use std::view::view_type; + +struct Foo { + a: (), + b: (), + c: (), +} + +struct Bar((), (), ()); + +struct Baz {} +struct Baz_ { + a: (), + b: (), +} + +impl Deref for Baz { + type Target = &'static view_type!(Baz_.{ a }); + + fn deref(&self) -> &&'static view_type!(Baz_.{ a }) { + todo!() + } +} + +// Basic access +fn f(foo: &view_type!(Foo.{ a }), bar: &view_type!(Bar.{ 0 })) { + #[cfg(legal)] + let _ = foo.a; + #[cfg(illegal)] + let _ = foo.b; + //[illegal]~^ ERROR field `b` cannot be accessed + //[illegal]~| NOTE this expression has type &view_type!(Foo.{ a }), of which only `a` can be accessed + + #[cfg(legal)] + let _ = &bar.0; + #[cfg(illegal)] + let _ = &bar.1; + //[illegal]~^ ERROR field `1` cannot be accessed + //[illegal]~| NOTE this expression has type &view_type!(Bar.{ 0 }), of which only `0` can be accessed +} + +// Works with multiple deref +fn g(foo: &&view_type!(Foo.{ a, b }), bar: &&view_type!(Bar.{ 0, 1 })) { + #[cfg(legal)] + let _ = foo.a; + #[cfg(illegal)] + let _ = foo.c; + //[illegal]~^ ERROR field `c` cannot be accessed + //[illegal]~| NOTE this expression has type &&view_type!(Foo.{ a, b }), of which only `a` and `b` can be accessed + + #[cfg(legal)] + let _ = &bar.0; + #[cfg(illegal)] + let _ = &bar.2; + //[illegal]~^ ERROR field `2` cannot be accessed + //[illegal]~| NOTE this expression has type &&view_type!(Bar.{ 0, 1 }), of which only `0` and `1` can be accessed +} + +// Works with manual deref implementation +fn h(baz: Baz) { + #[cfg(legal)] + let _ = baz.a; + + #[cfg(illegal)] + let _ = baz.b; + //[illegal]~^ ERROR field `b` cannot be accessed + //[illegal]~| NOTE this expression has type Baz, of which only `a` can be accessed +} + +fn main() {}