From a20866254c6864e49814d6abd47a37fd01bcff0a Mon Sep 17 00:00:00 2001 From: Joshua Liebow-Feeser Date: Thu, 12 Oct 2023 15:35:03 -0700 Subject: [PATCH 01/18] References refer to allocated objects --- library/core/src/primitive_docs.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 380a21b376bde..e73d5f990cbac 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1389,6 +1389,18 @@ mod prim_usize {} /// work on references as well as they do on owned values! The implementations described here are /// meant for generic contexts, where the final type `T` is a type parameter or otherwise not /// locally known. +/// +/// # Safety +/// +/// For all types, `T: ?Sized`, and for all `t: &T` or `t: &mut T`, unsafe code may assume that +/// the following properties hold. It is undefined behavior to produce a `t: &T` or `t: &mut T` +/// which violates any of these properties. +/// +/// * `t` is aligned to `align_of_val(t)` +/// * `t` refers to a valid instance of `T` +/// * `t` refers to a single [allocated object] +/// +/// [allocated object]: ptr#allocated-object #[stable(feature = "rust1", since = "1.0.0")] mod prim_ref {} From 4f0192a756f756db6bd1c25a8dbe6e89f0086661 Mon Sep 17 00:00:00 2001 From: Joshua Liebow-Feeser Date: Thu, 12 Oct 2023 18:55:45 -0700 Subject: [PATCH 02/18] Update primitive_docs.rs --- library/core/src/primitive_docs.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index e73d5f990cbac..04ae8c223f2cb 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1397,7 +1397,6 @@ mod prim_usize {} /// which violates any of these properties. /// /// * `t` is aligned to `align_of_val(t)` -/// * `t` refers to a valid instance of `T` /// * `t` refers to a single [allocated object] /// /// [allocated object]: ptr#allocated-object From 39660c4a77d3dda7f5d57a8d91faa946fff5192b Mon Sep 17 00:00:00 2001 From: Joshua Liebow-Feeser Date: Fri, 13 Oct 2023 09:47:39 -0700 Subject: [PATCH 03/18] Update library/core/src/primitive_docs.rs Co-authored-by: Ralf Jung --- library/core/src/primitive_docs.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 04ae8c223f2cb..cde49aeb687f0 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1397,7 +1397,11 @@ mod prim_usize {} /// which violates any of these properties. /// /// * `t` is aligned to `align_of_val(t)` -/// * `t` refers to a single [allocated object] +/// * `t` is dereferenceable for `size_of_val(t)` many bytes +/// +/// Being "dereferenceable" for N bytes means that the memory range beginning +/// at the address `t` points to and ending N bytes later is all contained within a +/// single [allocated object]. /// /// [allocated object]: ptr#allocated-object #[stable(feature = "rust1", since = "1.0.0")] From 55487e235b106088ced4e5b4710fa8f9674baaf9 Mon Sep 17 00:00:00 2001 From: Joshua Liebow-Feeser Date: Fri, 13 Oct 2023 09:49:23 -0700 Subject: [PATCH 04/18] Update primitive_docs.rs --- library/core/src/primitive_docs.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index cde49aeb687f0..19ff41697d9fc 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1399,9 +1399,8 @@ mod prim_usize {} /// * `t` is aligned to `align_of_val(t)` /// * `t` is dereferenceable for `size_of_val(t)` many bytes /// -/// Being "dereferenceable" for N bytes means that the memory range beginning -/// at the address `t` points to and ending N bytes later is all contained within a -/// single [allocated object]. +/// If `t` points at address `a`, being "dereferenceable" for N bytes means that the memory range +/// `[a, a + N)` is all contained within a single [allocated object]. /// /// [allocated object]: ptr#allocated-object #[stable(feature = "rust1", since = "1.0.0")] From 1a0309afb62b01002c1ac2466a6af0dc69594596 Mon Sep 17 00:00:00 2001 From: Joshua Liebow-Feeser Date: Fri, 3 Nov 2023 06:41:23 -0700 Subject: [PATCH 05/18] Update primitive_docs.rs --- library/core/src/primitive_docs.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 19ff41697d9fc..939342c4d9760 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1393,8 +1393,9 @@ mod prim_usize {} /// # Safety /// /// For all types, `T: ?Sized`, and for all `t: &T` or `t: &mut T`, unsafe code may assume that -/// the following properties hold. It is undefined behavior to produce a `t: &T` or `t: &mut T` -/// which violates any of these properties. +/// the following properties hold. Rust programmers must assume that, unless explicitly stated +/// otherwise, any Rust code they did not author themselves may rely on these properties, and that +/// violating them may cause that code to exhibit undefined behavior. /// /// * `t` is aligned to `align_of_val(t)` /// * `t` is dereferenceable for `size_of_val(t)` many bytes From e95c640ace21ddaebb83d05ac9a2c48838584e54 Mon Sep 17 00:00:00 2001 From: Lieselotte <52315535+she3py@users.noreply.github.com> Date: Thu, 18 Jan 2024 21:43:16 +0100 Subject: [PATCH 06/18] Handle methodcalls & operators in patterns --- compiler/rustc_parse/messages.ftl | 14 ++ compiler/rustc_parse/src/errors.rs | 12 ++ compiler/rustc_parse/src/parser/expr.rs | 13 ++ compiler/rustc_parse/src/parser/mod.rs | 1 + compiler/rustc_parse/src/parser/pat.rs | 152 ++++++++++++++++-- .../range_pat_interactions1.rs | 8 +- .../range_pat_interactions1.stderr | 68 +++++++- .../range_pat_interactions2.rs | 8 +- .../range_pat_interactions2.stderr | 71 +++++++- tests/ui/parser/issues/issue-24197.rs | 2 +- tests/ui/parser/issues/issue-24197.stderr | 6 +- tests/ui/parser/issues/issue-24375.rs | 2 +- tests/ui/parser/issues/issue-24375.stderr | 6 +- tests/ui/parser/pat-lt-bracket-5.rs | 4 +- tests/ui/parser/pat-lt-bracket-5.stderr | 15 +- tests/ui/parser/pat-lt-bracket-6.rs | 3 +- tests/ui/parser/pat-lt-bracket-6.stderr | 30 ++-- tests/ui/parser/pat-ranges-3.rs | 6 +- tests/ui/parser/pat-ranges-3.stderr | 14 +- tests/ui/parser/pat-ranges-4.rs | 6 - tests/ui/parser/pat-ranges-4.stderr | 8 - tests/ui/parser/pat-recover-exprs.rs | 28 ++++ tests/ui/parser/pat-recover-exprs.stderr | 76 +++++++++ tests/ui/parser/pat-recover-methodcalls.rs | 37 +++++ .../ui/parser/pat-recover-methodcalls.stderr | 35 ++++ tests/ui/parser/pat-recover-ranges.rs | 16 ++ tests/ui/parser/pat-recover-ranges.stderr | 84 +++++++++- tests/ui/parser/pat-recover-wildcards.rs | 61 +++++++ tests/ui/parser/pat-recover-wildcards.stderr | 77 +++++++++ 29 files changed, 797 insertions(+), 66 deletions(-) delete mode 100644 tests/ui/parser/pat-ranges-4.rs delete mode 100644 tests/ui/parser/pat-ranges-4.stderr create mode 100644 tests/ui/parser/pat-recover-exprs.rs create mode 100644 tests/ui/parser/pat-recover-exprs.stderr create mode 100644 tests/ui/parser/pat-recover-methodcalls.rs create mode 100644 tests/ui/parser/pat-recover-methodcalls.stderr create mode 100644 tests/ui/parser/pat-recover-wildcards.rs create mode 100644 tests/ui/parser/pat-recover-wildcards.stderr diff --git a/compiler/rustc_parse/messages.ftl b/compiler/rustc_parse/messages.ftl index fb19bb996f922..4daf691ef0dae 100644 --- a/compiler/rustc_parse/messages.ftl +++ b/compiler/rustc_parse/messages.ftl @@ -770,6 +770,20 @@ parse_unexpected_const_param_declaration = unexpected `const` parameter declarat parse_unexpected_default_value_for_lifetime_in_generic_parameters = unexpected default lifetime parameter .label = lifetime parameters cannot have default values +parse_unexpected_expr_in_pat = + expected {$is_bound -> + [true] a pattern range bound + *[false] a pattern + }, found {$is_method_call -> + [true] a method call + *[false] an expression + } + + .label = {$is_method_call -> + [true] method calls + *[false] arbitrary expressions + } are not allowed in patterns + parse_unexpected_if_with_if = unexpected `if` in the condition expression .suggestion = remove the `if` diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index 7dc711d96109d..8c0893007cbc5 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -2402,6 +2402,18 @@ pub(crate) struct ExpectedCommaAfterPatternField { pub span: Span, } +#[derive(Diagnostic)] +#[diag(parse_unexpected_expr_in_pat)] +pub(crate) struct UnexpectedExpressionInPattern { + #[primary_span] + #[label] + pub span: Span, + /// Was a `RangePatternBound` expected? + pub is_bound: bool, + /// Was the unexpected expression a `MethodCallExpression`? + pub is_method_call: bool, +} + #[derive(Diagnostic)] #[diag(parse_unexpected_paren_in_range_pat)] pub(crate) struct UnexpectedParenInRangePat { diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 8ca02452342b2..c46c59243560d 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -445,6 +445,19 @@ impl<'a> Parser<'a> { ) if self.restrictions.contains(Restrictions::CONST_EXPR) => { return None; } + // When recovering patterns as expressions, stop parsing when encountering an assignment `=`, an alternative `|`, or a range `..`. + ( + Some( + AssocOp::Assign + | AssocOp::AssignOp(_) + | AssocOp::BitOr + | AssocOp::DotDot + | AssocOp::DotDotEq, + ), + _, + ) if self.restrictions.contains(Restrictions::IS_PAT) => { + return None; + } (Some(op), _) => (op, self.token.span), (None, Some((Ident { name: sym::and, span }, false))) if self.may_recover() => { self.dcx().emit_err(errors::InvalidLogicalOperator { diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index ff2fb6271a8df..623407eb38003 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -53,6 +53,7 @@ bitflags::bitflags! { const CONST_EXPR = 1 << 2; const ALLOW_LET = 1 << 3; const IN_IF_GUARD = 1 << 4; + const IS_PAT = 1 << 5; } } diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 7918e03750ce3..4347b0debba93 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -1,4 +1,4 @@ -use super::{ForceCollect, Parser, PathStyle, TrailingToken}; +use super::{ForceCollect, Parser, PathStyle, Restrictions, TrailingToken}; use crate::errors::{ self, AmbiguousRangePattern, DotDotDotForRemainingFields, DotDotDotRangeToPatternNotAllowed, DotDotDotRestPattern, EnumPatternInsteadOfIdentifier, ExpectedBindingLeftOfAt, @@ -6,14 +6,14 @@ use crate::errors::{ InclusiveRangeExtraEquals, InclusiveRangeMatchArrow, InclusiveRangeNoEnd, InvalidMutInPattern, PatternOnWrongSideOfAt, RefMutOrderIncorrect, RemoveLet, RepeatedMutInPattern, SwitchRefBoxOrder, TopLevelOrPatternNotAllowed, TopLevelOrPatternNotAllowedSugg, - TrailingVertNotAllowed, UnexpectedLifetimeInPattern, UnexpectedParenInRangePat, - UnexpectedParenInRangePatSugg, UnexpectedVertVertBeforeFunctionParam, - UnexpectedVertVertInPattern, + TrailingVertNotAllowed, UnexpectedExpressionInPattern, UnexpectedLifetimeInPattern, + UnexpectedParenInRangePat, UnexpectedParenInRangePatSugg, + UnexpectedVertVertBeforeFunctionParam, UnexpectedVertVertInPattern, }; use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; use rustc_ast::mut_visit::{noop_visit_pat, MutVisitor}; use rustc_ast::ptr::P; -use rustc_ast::token::{self, Delimiter}; +use rustc_ast::token::{self, BinOpToken, Delimiter, Token}; use rustc_ast::{ self as ast, AttrVec, BindingAnnotation, ByRef, Expr, ExprKind, MacCall, Mutability, Pat, PatField, PatFieldsRest, PatKind, Path, QSelf, RangeEnd, RangeSyntax, @@ -23,7 +23,8 @@ use rustc_errors::{Applicability, DiagnosticBuilder, PResult}; use rustc_session::errors::ExprParenthesesNeeded; use rustc_span::source_map::{respan, Spanned}; use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::Span; +use rustc_span::{ErrorGuaranteed, Span}; +use std::borrow::Cow; use thin_vec::{thin_vec, ThinVec}; #[derive(PartialEq, Copy, Clone)] @@ -336,6 +337,88 @@ impl<'a> Parser<'a> { } } + /// Ensures that the last parsed pattern is not followed by a method call or an operator. + #[must_use = "the pattern must be discarded as `PatKind::Err` if this function returns Some"] + fn maybe_recover_trailing_expr<'b>( + &'b mut self, + pat: Cow<'b, P>, + is_end_bound: bool, + ) -> Option { + if self.prev_token.is_keyword(kw::Underscore) || !self.may_recover() { + // Don't recover anything after an `_` or if recovery is disabled. + return None; + } + + // Check for `.hello()`, but allow `.Hello()` to be recovered as `, Hello()` in `parse_seq_to_before_tokens()`. + let has_trailing_method = self.check_noexpect(&token::Dot) + && self.look_ahead(1, |tok| { + tok.ident() + .and_then(|(ident, _)| ident.name.to_string().chars().next()) + .is_some_and(char::is_lowercase) + }) + && self.look_ahead(2, |tok| tok.kind == token::OpenDelim(Delimiter::Parenthesis)); + + // Check for operators. + // `|` is excluded as it is used in pattern alternatives and lambdas, + // `?` is included for error propagation, + // `[` is included for indexing operations, + // `[]` is excluded as `a[]` isn't an expression and should be recovered as `a, []` (cf. `tests/ui/parser/pat-lt-bracket-7.rs`) + let has_trailing_operator = matches!(self.token.kind, token::BinOp(op) if op != BinOpToken::Or) + || self.token.kind == token::Question + || (self.token.kind == token::OpenDelim(Delimiter::Bracket) + && self.look_ahead(1, |tok| tok.kind != token::CloseDelim(Delimiter::Bracket))); + + if !has_trailing_method && !has_trailing_operator { + // Nothing to recover here. + return None; + } + + // Let's try to parse an expression to emit a better diagnostic. + let pat = pat.into_owned(); + let pat_span = pat.span; + + let mut snapshot = self.create_snapshot_for_diagnostic(); + snapshot.restrictions.insert(Restrictions::IS_PAT); + + // Parse `?`, `.f`, `(arg0, arg1, ...)` or `[expr]` until they've all been eaten. + if let Ok(expr) = snapshot + .parse_expr_dot_or_call_with(pat, pat_span, AttrVec::new()) + .map_err(|err| err.cancel()) + { + let non_assoc_span = expr.span; + + // Parse an associative expression such as `+ expr`, `% expr`, ... + // Assignements, ranges and `|` are disabled by [`Restrictions::IS_PAT`]. + if let Ok(expr) = + snapshot.parse_expr_assoc_with(0, expr.into()).map_err(|err| err.cancel()) + { + // We got a valid expression. + self.restore_snapshot(snapshot); + self.restrictions.remove(Restrictions::IS_PAT); + + let span = expr.span; + + let is_bound = is_end_bound + // is_start_bound: either `..` or `)..` + || self.token.is_range_separator() + || self.token.kind == token::CloseDelim(Delimiter::Parenthesis) + && self.look_ahead(1, Token::is_range_separator); + + // Check that `parse_expr_assoc_with` didn't eat a rhs. + let is_method_call = has_trailing_method && non_assoc_span == span; + + return Some(self.dcx().emit_err(UnexpectedExpressionInPattern { + span, + is_bound, + is_method_call, + })); + } + } + + // We got a trailing method/operator, but we couldn't parse an expression. + None + } + /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are /// allowed). fn parse_pat_with_range_pat( @@ -441,7 +524,11 @@ impl<'a> Parser<'a> { } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) { self.parse_pat_tuple_struct(qself, path)? } else { - PatKind::Path(qself, path) + let pat = self.mk_expr(span, ExprKind::Path(qself.clone(), path.clone())); + match self.maybe_recover_trailing_expr(Cow::Owned(pat), false) { + Some(guar) => PatKind::Err(guar), + None => PatKind::Path(qself, path), + } } } else if matches!(self.token.kind, token::Lifetime(_)) // In pattern position, we're totally fine with using "next token isn't colon" @@ -470,10 +557,18 @@ impl<'a> Parser<'a> { } else { // Try to parse everything else as literal with optional minus match self.parse_literal_maybe_minus() { - Ok(begin) => match self.parse_range_end() { - Some(form) => self.parse_pat_range_begin_with(begin, form)?, - None => PatKind::Lit(begin), - }, + Ok(begin) => { + let begin = match self.maybe_recover_trailing_expr(Cow::Borrowed(&begin), false) + { + Some(_) => self.mk_expr_err(begin.span), + None => begin, + }; + + match self.parse_range_end() { + Some(form) => self.parse_pat_range_begin_with(begin, form)?, + None => PatKind::Lit(begin), + } + } Err(err) => return self.fatal_unexpected_non_pat(err, expected), } }; @@ -615,6 +710,21 @@ impl<'a> Parser<'a> { self.parse_pat_range_begin_with(begin.clone(), form)? } + // recover ranges with parentheses around the `(start)..` + PatKind::Err(_) + if self.may_recover() + && let Some(form) = self.parse_range_end() => + { + self.dcx().emit_err(UnexpectedParenInRangePat { + span: vec![open_paren, close_paren], + sugg: UnexpectedParenInRangePatSugg { + start_span: open_paren, + end_span: close_paren, + }, + }); + + self.parse_pat_range_begin_with(self.mk_expr(pat.span, ExprKind::Err), form)? + } // (pat) with optional parentheses _ => PatKind::Paren(pat), @@ -853,6 +963,8 @@ impl<'a> Parser<'a> { self.parse_literal_maybe_minus() }?; + let recovered = self.maybe_recover_trailing_expr(Cow::Borrowed(&bound), true); + // recover trailing `)` if let Some(open_paren) = open_paren { self.expect(&token::CloseDelim(Delimiter::Parenthesis))?; @@ -866,7 +978,10 @@ impl<'a> Parser<'a> { }); } - Ok(bound) + Ok(match recovered { + Some(_) => self.mk_expr_err(bound.span), + None => bound, + }) } /// Is this the start of a pattern beginning with a path? @@ -929,7 +1044,18 @@ impl<'a> Parser<'a> { .create_err(EnumPatternInsteadOfIdentifier { span: self.prev_token.span })); } - Ok(PatKind::Ident(binding_annotation, ident, sub)) + // Check for method calls after the `ident`, + // but not `ident @ subpat` as `subpat` was already checked and `ident` continues with `@`. + + let expr = self.mk_expr(ident.span, ExprKind::Path(None, Path::from_ident(ident))); + let pat = if sub.is_none() + && let Some(guar) = self.maybe_recover_trailing_expr(Cow::Owned(expr), false) + { + PatKind::Err(guar) + } else { + PatKind::Ident(binding_annotation, ident, sub) + }; + Ok(pat) } /// Parse a struct ("record") pattern (e.g. `Foo { ... }` or `Foo::Bar { ... }`). diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions1.rs b/tests/ui/half-open-range-patterns/range_pat_interactions1.rs index 55353999b6788..0c050c550c4ce 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions1.rs +++ b/tests/ui/half-open-range-patterns/range_pat_interactions1.rs @@ -17,12 +17,18 @@ fn main() { } match x as i32 { 0..5+1 => errors_only.push(x), - //~^ error: expected one of `=>`, `if`, or `|`, found `+` + //~^ error: expected a pattern range bound, found an expression + //~| error: exclusive range pattern syntax is experimental 1 | -3..0 => first_or.push(x), + //~^ error: exclusive range pattern syntax is experimental y @ (0..5 | 6) => or_two.push(y), + //~^ error: exclusive range pattern syntax is experimental y @ 0..const { 5 + 1 } => assert_eq!(y, 5), + //~^ error: exclusive range pattern syntax is experimental + //~| error: inline-const in pattern position is experimental y @ -5.. => range_from.push(y), y @ ..-7 => assert_eq!(y, -8), + //~^ error: exclusive range pattern syntax is experimental y => bottom.push(y), } } diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions1.stderr b/tests/ui/half-open-range-patterns/range_pat_interactions1.stderr index e2fab14ffc235..9399de3e23528 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions1.stderr +++ b/tests/ui/half-open-range-patterns/range_pat_interactions1.stderr @@ -1,8 +1,8 @@ -error: expected one of `=>`, `if`, or `|`, found `+` - --> $DIR/range_pat_interactions1.rs:19:17 +error: expected a pattern range bound, found an expression + --> $DIR/range_pat_interactions1.rs:19:16 | LL | 0..5+1 => errors_only.push(x), - | ^ expected one of `=>`, `if`, or `|` + | ^^^ arbitrary expressions are not allowed in patterns error[E0408]: variable `n` is not bound in all patterns --> $DIR/range_pat_interactions1.rs:10:25 @@ -12,6 +12,16 @@ LL | if let n @ 2..3|4 = x { | | | variable not in all patterns +error[E0658]: inline-const in pattern position is experimental + --> $DIR/range_pat_interactions1.rs:26:20 + | +LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), + | ^^^^^ + | + = note: see issue #76001 for more information + = help: add `#![feature(inline_const_pat)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + error[E0658]: exclusive range pattern syntax is experimental --> $DIR/range_pat_interactions1.rs:10:20 | @@ -32,7 +42,57 @@ LL | } else if let 2..3 | 4 = x { = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error: aborting due to 4 previous errors +error[E0658]: exclusive range pattern syntax is experimental + --> $DIR/range_pat_interactions1.rs:19:13 + | +LL | 0..5+1 => errors_only.push(x), + | ^^^^^^ + | + = note: see issue #37854 for more information + = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: exclusive range pattern syntax is experimental + --> $DIR/range_pat_interactions1.rs:22:17 + | +LL | 1 | -3..0 => first_or.push(x), + | ^^^^^ + | + = note: see issue #37854 for more information + = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: exclusive range pattern syntax is experimental + --> $DIR/range_pat_interactions1.rs:24:18 + | +LL | y @ (0..5 | 6) => or_two.push(y), + | ^^^^ + | + = note: see issue #37854 for more information + = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: exclusive range pattern syntax is experimental + --> $DIR/range_pat_interactions1.rs:26:17 + | +LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), + | ^^^^^^^^^^^^^^^^^^ + | + = note: see issue #37854 for more information + = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: exclusive range pattern syntax is experimental + --> $DIR/range_pat_interactions1.rs:30:17 + | +LL | y @ ..-7 => assert_eq!(y, -8), + | ^^^^ + | + = note: see issue #37854 for more information + = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 10 previous errors Some errors have detailed explanations: E0408, E0658. For more information about an error, try `rustc --explain E0408`. diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions2.rs b/tests/ui/half-open-range-patterns/range_pat_interactions2.rs index 0e96cfe785857..068104c4b1b8c 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions2.rs +++ b/tests/ui/half-open-range-patterns/range_pat_interactions2.rs @@ -8,12 +8,18 @@ fn main() { for x in -9 + 1..=(9 - 2) { match x as i32 { 0..=(5+1) => errors_only.push(x), - //~^ error: expected `)`, found `+` + //~^ error: expected a pattern range bound, found an expression + //~| error: range pattern bounds cannot have parentheses 1 | -3..0 => first_or.push(x), + //~^ error: exclusive range pattern syntax is experimental y @ (0..5 | 6) => or_two.push(y), + //~^ error: exclusive range pattern syntax is experimental y @ 0..const { 5 + 1 } => assert_eq!(y, 5), + //~^ error: inline-const in pattern position is experimental + //~| error: exclusive range pattern syntax is experimental y @ -5.. => range_from.push(y), y @ ..-7 => assert_eq!(y, -8), + //~^ error: exclusive range pattern syntax is experimental y => bottom.push(y), } } diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions2.stderr b/tests/ui/half-open-range-patterns/range_pat_interactions2.stderr index a54f29a3b3263..84103257f0d74 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions2.stderr +++ b/tests/ui/half-open-range-patterns/range_pat_interactions2.stderr @@ -1,8 +1,71 @@ -error: expected `)`, found `+` - --> $DIR/range_pat_interactions2.rs:10:19 +error: expected a pattern range bound, found an expression + --> $DIR/range_pat_interactions2.rs:10:18 | LL | 0..=(5+1) => errors_only.push(x), - | ^ expected `)` + | ^^^ arbitrary expressions are not allowed in patterns -error: aborting due to 1 previous error +error: range pattern bounds cannot have parentheses + --> $DIR/range_pat_interactions2.rs:10:17 + | +LL | 0..=(5+1) => errors_only.push(x), + | ^ ^ + | +help: remove these parentheses + | +LL - 0..=(5+1) => errors_only.push(x), +LL + 0..=5+1 => errors_only.push(x), + | + +error[E0658]: inline-const in pattern position is experimental + --> $DIR/range_pat_interactions2.rs:17:20 + | +LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), + | ^^^^^ + | + = note: see issue #76001 for more information + = help: add `#![feature(inline_const_pat)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: exclusive range pattern syntax is experimental + --> $DIR/range_pat_interactions2.rs:13:17 + | +LL | 1 | -3..0 => first_or.push(x), + | ^^^^^ + | + = note: see issue #37854 for more information + = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: exclusive range pattern syntax is experimental + --> $DIR/range_pat_interactions2.rs:15:18 + | +LL | y @ (0..5 | 6) => or_two.push(y), + | ^^^^ + | + = note: see issue #37854 for more information + = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: exclusive range pattern syntax is experimental + --> $DIR/range_pat_interactions2.rs:17:17 + | +LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), + | ^^^^^^^^^^^^^^^^^^ + | + = note: see issue #37854 for more information + = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: exclusive range pattern syntax is experimental + --> $DIR/range_pat_interactions2.rs:21:17 + | +LL | y @ ..-7 => assert_eq!(y, -8), + | ^^^^ + | + = note: see issue #37854 for more information + = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 7 previous errors +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/parser/issues/issue-24197.rs b/tests/ui/parser/issues/issue-24197.rs index aaf5137461fa6..9bba16e5596ff 100644 --- a/tests/ui/parser/issues/issue-24197.rs +++ b/tests/ui/parser/issues/issue-24197.rs @@ -1,3 +1,3 @@ fn main() { - let buf[0] = 0; //~ ERROR expected one of `:`, `;`, `=`, `@`, or `|`, found `[` + let buf[0] = 0; //~ error: expected a pattern, found an expression } diff --git a/tests/ui/parser/issues/issue-24197.stderr b/tests/ui/parser/issues/issue-24197.stderr index 3ef707f3953cf..7ebbf4ac370d7 100644 --- a/tests/ui/parser/issues/issue-24197.stderr +++ b/tests/ui/parser/issues/issue-24197.stderr @@ -1,8 +1,8 @@ -error: expected one of `:`, `;`, `=`, `@`, or `|`, found `[` - --> $DIR/issue-24197.rs:2:12 +error: expected a pattern, found an expression + --> $DIR/issue-24197.rs:2:9 | LL | let buf[0] = 0; - | ^ expected one of `:`, `;`, `=`, `@`, or `|` + | ^^^^^^ arbitrary expressions are not allowed in patterns error: aborting due to 1 previous error diff --git a/tests/ui/parser/issues/issue-24375.rs b/tests/ui/parser/issues/issue-24375.rs index 1d128d33e4f49..a5e256b7f1554 100644 --- a/tests/ui/parser/issues/issue-24375.rs +++ b/tests/ui/parser/issues/issue-24375.rs @@ -3,7 +3,7 @@ static tmp : [&'static str; 2] = ["hello", "he"]; fn main() { let z = "hello"; match z { - tmp[0] => {} //~ ERROR expected one of `=>`, `@`, `if`, or `|`, found `[` + tmp[0] => {} //~ error: expected a pattern, found an expression _ => {} } } diff --git a/tests/ui/parser/issues/issue-24375.stderr b/tests/ui/parser/issues/issue-24375.stderr index bb1e19e9e6d8d..e6ef07d13fd8d 100644 --- a/tests/ui/parser/issues/issue-24375.stderr +++ b/tests/ui/parser/issues/issue-24375.stderr @@ -1,8 +1,8 @@ -error: expected one of `=>`, `@`, `if`, or `|`, found `[` - --> $DIR/issue-24375.rs:6:12 +error: expected a pattern, found an expression + --> $DIR/issue-24375.rs:6:9 | LL | tmp[0] => {} - | ^ expected one of `=>`, `@`, `if`, or `|` + | ^^^^^^ arbitrary expressions are not allowed in patterns error: aborting due to 1 previous error diff --git a/tests/ui/parser/pat-lt-bracket-5.rs b/tests/ui/parser/pat-lt-bracket-5.rs index aaece1f6bd9cb..6d784494d56a3 100644 --- a/tests/ui/parser/pat-lt-bracket-5.rs +++ b/tests/ui/parser/pat-lt-bracket-5.rs @@ -1,3 +1,5 @@ fn main() { - let v[0] = v[1]; //~ ERROR expected one of `:`, `;`, `=`, `@`, or `|`, found `[` + let v[0] = v[1]; + //~^ error: expected a pattern, found an expression + //~| error: cannot find value `v` in this scope } diff --git a/tests/ui/parser/pat-lt-bracket-5.stderr b/tests/ui/parser/pat-lt-bracket-5.stderr index e556e6c0206fb..18cf2df028216 100644 --- a/tests/ui/parser/pat-lt-bracket-5.stderr +++ b/tests/ui/parser/pat-lt-bracket-5.stderr @@ -1,8 +1,15 @@ -error: expected one of `:`, `;`, `=`, `@`, or `|`, found `[` - --> $DIR/pat-lt-bracket-5.rs:2:10 +error: expected a pattern, found an expression + --> $DIR/pat-lt-bracket-5.rs:2:9 | LL | let v[0] = v[1]; - | ^ expected one of `:`, `;`, `=`, `@`, or `|` + | ^^^^ arbitrary expressions are not allowed in patterns -error: aborting due to 1 previous error +error[E0425]: cannot find value `v` in this scope + --> $DIR/pat-lt-bracket-5.rs:2:16 + | +LL | let v[0] = v[1]; + | ^ not found in this scope + +error: aborting due to 2 previous errors +For more information about this error, try `rustc --explain E0425`. diff --git a/tests/ui/parser/pat-lt-bracket-6.rs b/tests/ui/parser/pat-lt-bracket-6.rs index 7becffa9fe2f7..496525ed5370c 100644 --- a/tests/ui/parser/pat-lt-bracket-6.rs +++ b/tests/ui/parser/pat-lt-bracket-6.rs @@ -3,7 +3,8 @@ fn main() { let x = Test(&0, []); let Test(&desc[..]) = x; - //~^ ERROR: expected one of `)`, `,`, `@`, or `|`, found `[` + //~^ error: expected a pattern, found an expression + //~| error: this pattern has 1 field, but the corresponding tuple struct has 2 fields } const RECOVERY_WITNESS: () = 0; //~ ERROR mismatched types diff --git a/tests/ui/parser/pat-lt-bracket-6.stderr b/tests/ui/parser/pat-lt-bracket-6.stderr index 035d0dbfe06d6..10c638a63e44c 100644 --- a/tests/ui/parser/pat-lt-bracket-6.stderr +++ b/tests/ui/parser/pat-lt-bracket-6.stderr @@ -1,18 +1,30 @@ -error: expected one of `)`, `,`, `@`, or `|`, found `[` - --> $DIR/pat-lt-bracket-6.rs:5:19 +error: expected a pattern, found an expression + --> $DIR/pat-lt-bracket-6.rs:5:15 | LL | let Test(&desc[..]) = x; - | ^ - | | - | expected one of `)`, `,`, `@`, or `|` - | help: missing `,` + | ^^^^^^^^ arbitrary expressions are not allowed in patterns error[E0308]: mismatched types - --> $DIR/pat-lt-bracket-6.rs:9:30 + --> $DIR/pat-lt-bracket-6.rs:10:30 | LL | const RECOVERY_WITNESS: () = 0; | ^ expected `()`, found integer -error: aborting due to 2 previous errors +error[E0023]: this pattern has 1 field, but the corresponding tuple struct has 2 fields + --> $DIR/pat-lt-bracket-6.rs:5:14 + | +LL | struct Test(&'static u8, [u8; 0]); + | ----------- ------- tuple struct has 2 fields +... +LL | let Test(&desc[..]) = x; + | ^^^^^^^^^ expected 2 fields, found 1 + | +help: use `_` to explicitly ignore each field + | +LL | let Test(&desc[..], _) = x; + | +++ + +error: aborting due to 3 previous errors -For more information about this error, try `rustc --explain E0308`. +Some errors have detailed explanations: E0023, E0308. +For more information about an error, try `rustc --explain E0023`. diff --git a/tests/ui/parser/pat-ranges-3.rs b/tests/ui/parser/pat-ranges-3.rs index 8976dcf0d90f9..419768a2a2022 100644 --- a/tests/ui/parser/pat-ranges-3.rs +++ b/tests/ui/parser/pat-ranges-3.rs @@ -1,5 +1,9 @@ // Parsing of range patterns fn main() { - let 10 ..= 10 + 3 = 12; //~ expected one of `:`, `;`, `=`, or `|`, found `+` + let 10 ..= 10 + 3 = 12; + //~^ error: expected a pattern range bound, found an expression + + let 10 - 3 ..= 10 = 8; + //~^ error: expected a pattern range bound, found an expression } diff --git a/tests/ui/parser/pat-ranges-3.stderr b/tests/ui/parser/pat-ranges-3.stderr index 611b35a650280..5e1f35d1b6f9a 100644 --- a/tests/ui/parser/pat-ranges-3.stderr +++ b/tests/ui/parser/pat-ranges-3.stderr @@ -1,8 +1,14 @@ -error: expected one of `:`, `;`, `=`, or `|`, found `+` - --> $DIR/pat-ranges-3.rs:4:19 +error: expected a pattern range bound, found an expression + --> $DIR/pat-ranges-3.rs:4:16 | LL | let 10 ..= 10 + 3 = 12; - | ^ expected one of `:`, `;`, `=`, or `|` + | ^^^^^^ arbitrary expressions are not allowed in patterns -error: aborting due to 1 previous error +error: expected a pattern range bound, found an expression + --> $DIR/pat-ranges-3.rs:7:9 + | +LL | let 10 - 3 ..= 10 = 8; + | ^^^^^^ arbitrary expressions are not allowed in patterns + +error: aborting due to 2 previous errors diff --git a/tests/ui/parser/pat-ranges-4.rs b/tests/ui/parser/pat-ranges-4.rs deleted file mode 100644 index 61188976b028c..0000000000000 --- a/tests/ui/parser/pat-ranges-4.rs +++ /dev/null @@ -1,6 +0,0 @@ -// Parsing of range patterns - -fn main() { - let 10 - 3 ..= 10 = 8; - //~^ error: expected one of `...`, `..=`, `..`, `:`, `;`, `=`, or `|`, found `-` -} diff --git a/tests/ui/parser/pat-ranges-4.stderr b/tests/ui/parser/pat-ranges-4.stderr deleted file mode 100644 index c30160291d608..0000000000000 --- a/tests/ui/parser/pat-ranges-4.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: expected one of `...`, `..=`, `..`, `:`, `;`, `=`, or `|`, found `-` - --> $DIR/pat-ranges-4.rs:4:12 - | -LL | let 10 - 3 ..= 10 = 8; - | ^ expected one of 7 possible tokens - -error: aborting due to 1 previous error - diff --git a/tests/ui/parser/pat-recover-exprs.rs b/tests/ui/parser/pat-recover-exprs.rs new file mode 100644 index 0000000000000..ecd471467e380 --- /dev/null +++ b/tests/ui/parser/pat-recover-exprs.rs @@ -0,0 +1,28 @@ +fn main() { + match u8::MAX { + u8::MAX.abs() => (), + //~^ error: expected a pattern, found a method call + x.sqrt() @ .. => (), + //~^ error: expected a pattern, found a method call + //~| error: left-hand side of `@` must be a binding + z @ w @ v.u() => (), + //~^ error: expected a pattern, found a method call + y.ilog(3) => (), + //~^ error: expected a pattern, found a method call + n + 1 => (), + //~^ error: expected a pattern, found an expression + ("".f() + 14 * 8) => (), + //~^ error: expected a pattern, found an expression + 0 | ((1) | 2) | 3 => (), + f?() => (), + //~^ error: expected a pattern, found an expression + (_ + 1) => (), + //~^ error: expected one of `)`, `,`, or `|`, found `+` + } + + let 1 + 1 = 2; + //~^ error: expected a pattern, found an expression + + let b = matches!(x, (x * x | x.f()) | x[0]); + //~^ error: expected one of `)`, `,`, `@`, or `|`, found `*` +} diff --git a/tests/ui/parser/pat-recover-exprs.stderr b/tests/ui/parser/pat-recover-exprs.stderr new file mode 100644 index 0000000000000..787fd03b0c30d --- /dev/null +++ b/tests/ui/parser/pat-recover-exprs.stderr @@ -0,0 +1,76 @@ +error: expected a pattern, found a method call + --> $DIR/pat-recover-exprs.rs:3:9 + | +LL | u8::MAX.abs() => (), + | ^^^^^^^^^^^^^ method calls are not allowed in patterns + +error: expected a pattern, found a method call + --> $DIR/pat-recover-exprs.rs:5:9 + | +LL | x.sqrt() @ .. => (), + | ^^^^^^^^ method calls are not allowed in patterns + +error: left-hand side of `@` must be a binding + --> $DIR/pat-recover-exprs.rs:5:9 + | +LL | x.sqrt() @ .. => (), + | --------^^^-- + | | | + | | also a pattern + | interpreted as a pattern, not a binding + | + = note: bindings are `x`, `mut x`, `ref x`, and `ref mut x` + +error: expected a pattern, found a method call + --> $DIR/pat-recover-exprs.rs:8:17 + | +LL | z @ w @ v.u() => (), + | ^^^^^ method calls are not allowed in patterns + +error: expected a pattern, found a method call + --> $DIR/pat-recover-exprs.rs:10:9 + | +LL | y.ilog(3) => (), + | ^^^^^^^^^ method calls are not allowed in patterns + +error: expected a pattern, found an expression + --> $DIR/pat-recover-exprs.rs:12:9 + | +LL | n + 1 => (), + | ^^^^^ arbitrary expressions are not allowed in patterns + +error: expected a pattern, found an expression + --> $DIR/pat-recover-exprs.rs:14:10 + | +LL | ("".f() + 14 * 8) => (), + | ^^^^^^^^^^^^^^^ arbitrary expressions are not allowed in patterns + +error: expected a pattern, found an expression + --> $DIR/pat-recover-exprs.rs:17:9 + | +LL | f?() => (), + | ^^^^ arbitrary expressions are not allowed in patterns + +error: expected one of `)`, `,`, or `|`, found `+` + --> $DIR/pat-recover-exprs.rs:19:12 + | +LL | (_ + 1) => (), + | ^ expected one of `)`, `,`, or `|` + +error: expected a pattern, found an expression + --> $DIR/pat-recover-exprs.rs:23:9 + | +LL | let 1 + 1 = 2; + | ^^^^^ arbitrary expressions are not allowed in patterns + +error: expected one of `)`, `,`, `@`, or `|`, found `*` + --> $DIR/pat-recover-exprs.rs:26:28 + | +LL | let b = matches!(x, (x * x | x.f()) | x[0]); + | ^ expected one of `)`, `,`, `@`, or `|` + --> $SRC_DIR/core/src/macros/mod.rs:LL:COL + | + = note: while parsing argument for this `pat` macro fragment + +error: aborting due to 11 previous errors + diff --git a/tests/ui/parser/pat-recover-methodcalls.rs b/tests/ui/parser/pat-recover-methodcalls.rs new file mode 100644 index 0000000000000..54104e9a53559 --- /dev/null +++ b/tests/ui/parser/pat-recover-methodcalls.rs @@ -0,0 +1,37 @@ +struct Foo(String); +struct Bar { baz: String } + +fn foo(foo: Foo) -> bool { + match foo { + Foo("hi".to_owned()) => true, + //~^ error: expected a pattern, found a method call + _ => false + } +} + +fn bar(bar: Bar) -> bool { + match bar { + Bar { baz: "hi".to_owned() } => true, + //~^ error: expected a pattern, found a method call + _ => false + } +} + +fn baz() { // issue #90121 + let foo = vec!["foo".to_string()]; + + match foo.as_slice() { + &["foo".to_string()] => {} + //~^ error: expected a pattern, found a method call + _ => {} + }; +} + +fn main() { + if let (-1.some(4)) = (0, Some(4)) {} + //~^ error: expected a pattern, found a method call + + if let (-1.Some(4)) = (0, Some(4)) {} + //~^ error: expected one of `)`, `,`, `...`, `..=`, `..`, or `|`, found `.` + //~| help: missing `,` +} diff --git a/tests/ui/parser/pat-recover-methodcalls.stderr b/tests/ui/parser/pat-recover-methodcalls.stderr new file mode 100644 index 0000000000000..1f9ae81dc0c55 --- /dev/null +++ b/tests/ui/parser/pat-recover-methodcalls.stderr @@ -0,0 +1,35 @@ +error: expected a pattern, found a method call + --> $DIR/pat-recover-methodcalls.rs:6:13 + | +LL | Foo("hi".to_owned()) => true, + | ^^^^^^^^^^^^^^^ method calls are not allowed in patterns + +error: expected a pattern, found a method call + --> $DIR/pat-recover-methodcalls.rs:14:20 + | +LL | Bar { baz: "hi".to_owned() } => true, + | ^^^^^^^^^^^^^^^ method calls are not allowed in patterns + +error: expected a pattern, found a method call + --> $DIR/pat-recover-methodcalls.rs:24:11 + | +LL | &["foo".to_string()] => {} + | ^^^^^^^^^^^^^^^^^ method calls are not allowed in patterns + +error: expected a pattern, found a method call + --> $DIR/pat-recover-methodcalls.rs:31:13 + | +LL | if let (-1.some(4)) = (0, Some(4)) {} + | ^^^^^^^^^^ method calls are not allowed in patterns + +error: expected one of `)`, `,`, `...`, `..=`, `..`, or `|`, found `.` + --> $DIR/pat-recover-methodcalls.rs:34:15 + | +LL | if let (-1.Some(4)) = (0, Some(4)) {} + | ^ + | | + | expected one of `)`, `,`, `...`, `..=`, `..`, or `|` + | help: missing `,` + +error: aborting due to 5 previous errors + diff --git a/tests/ui/parser/pat-recover-ranges.rs b/tests/ui/parser/pat-recover-ranges.rs index 65a6fc6fe21f3..7d77e950d905a 100644 --- a/tests/ui/parser/pat-recover-ranges.rs +++ b/tests/ui/parser/pat-recover-ranges.rs @@ -8,6 +8,22 @@ fn main() { (0)..=(-4) => (), //~^ error: range pattern bounds cannot have parentheses //~| error: range pattern bounds cannot have parentheses + ..=1 + 2 => (), + //~^ error: expected a pattern range bound, found an expression + (4).. => (), + //~^ error: range pattern bounds cannot have parentheses + (-4 + 0).. => (), + //~^ error: expected a pattern range bound, found an expression + //~| error: range pattern bounds cannot have parentheses + (1 + 4)...1 * 2 => (), + //~^ error: expected a pattern range bound, found an expression + //~| error: expected a pattern range bound, found an expression + //~| error: range pattern bounds cannot have parentheses + //~| warning: `...` range patterns are deprecated + //~| warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! + 0.x()..="y".z() => (), + //~^ error: expected a pattern range bound, found a method call + //~| error: expected a pattern range bound, found a method call }; } diff --git a/tests/ui/parser/pat-recover-ranges.stderr b/tests/ui/parser/pat-recover-ranges.stderr index 0d722b5aa95c8..a7d62bd7f8ad2 100644 --- a/tests/ui/parser/pat-recover-ranges.stderr +++ b/tests/ui/parser/pat-recover-ranges.stderr @@ -46,5 +46,87 @@ LL - (0)..=(-4) => (), LL + (0)..=-4 => (), | -error: aborting due to 4 previous errors +error: expected a pattern range bound, found an expression + --> $DIR/pat-recover-ranges.rs:11:12 + | +LL | ..=1 + 2 => (), + | ^^^^^ arbitrary expressions are not allowed in patterns + +error: range pattern bounds cannot have parentheses + --> $DIR/pat-recover-ranges.rs:13:9 + | +LL | (4).. => (), + | ^ ^ + | +help: remove these parentheses + | +LL - (4).. => (), +LL + 4.. => (), + | + +error: expected a pattern range bound, found an expression + --> $DIR/pat-recover-ranges.rs:15:10 + | +LL | (-4 + 0).. => (), + | ^^^^^^ arbitrary expressions are not allowed in patterns + +error: range pattern bounds cannot have parentheses + --> $DIR/pat-recover-ranges.rs:15:9 + | +LL | (-4 + 0).. => (), + | ^ ^ + | +help: remove these parentheses + | +LL - (-4 + 0).. => (), +LL + -4 + 0.. => (), + | + +error: expected a pattern range bound, found an expression + --> $DIR/pat-recover-ranges.rs:18:10 + | +LL | (1 + 4)...1 * 2 => (), + | ^^^^^ arbitrary expressions are not allowed in patterns + +error: range pattern bounds cannot have parentheses + --> $DIR/pat-recover-ranges.rs:18:9 + | +LL | (1 + 4)...1 * 2 => (), + | ^ ^ + | +help: remove these parentheses + | +LL - (1 + 4)...1 * 2 => (), +LL + 1 + 4...1 * 2 => (), + | + +error: expected a pattern range bound, found an expression + --> $DIR/pat-recover-ranges.rs:18:19 + | +LL | (1 + 4)...1 * 2 => (), + | ^^^^^ arbitrary expressions are not allowed in patterns + +error: expected a pattern range bound, found a method call + --> $DIR/pat-recover-ranges.rs:24:9 + | +LL | 0.x()..="y".z() => (), + | ^^^^^ method calls are not allowed in patterns + +error: expected a pattern range bound, found a method call + --> $DIR/pat-recover-ranges.rs:24:17 + | +LL | 0.x()..="y".z() => (), + | ^^^^^^^ method calls are not allowed in patterns + +warning: `...` range patterns are deprecated + --> $DIR/pat-recover-ranges.rs:18:16 + | +LL | (1 + 4)...1 * 2 => (), + | ^^^ help: use `..=` for an inclusive range + | + = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! + = note: for more information, see + = note: `#[warn(ellipsis_inclusive_range_patterns)]` on by default + +error: aborting due to 13 previous errors; 1 warning emitted diff --git a/tests/ui/parser/pat-recover-wildcards.rs b/tests/ui/parser/pat-recover-wildcards.rs new file mode 100644 index 0000000000000..f506e2223d608 --- /dev/null +++ b/tests/ui/parser/pat-recover-wildcards.rs @@ -0,0 +1,61 @@ +// check that we can't do funny things with wildcards. + +fn a() { + match 1 { + _ + 1 => () //~ error: expected one of `=>`, `if`, or `|`, found `+` + } +} + +fn b() { + match 2 { + (_ % 4) => () //~ error: expected one of `)`, `,`, or `|`, found `%` + } +} + +fn c() { + match 3 { + _.x() => () //~ error: expected one of `=>`, `if`, or `|`, found `.` + } +} + +fn d() { + match 4 { + _..=4 => () //~ error: expected one of `=>`, `if`, or `|`, found `..=` + } +} + +fn e() { + match 5 { + .._ => () //~ error: expected one of `=>`, `if`, or `|`, found reserved identifier `_` + } +} + +fn f() { + match 6 { + 0..._ => () + //~^ error: inclusive range with no end + //~| error: expected one of `=>`, `if`, or `|`, found reserved identifier `_` + } +} + +fn g() { + match 7 { + (_ * 0)..5 => () //~ error: expected one of `)`, `,`, or `|`, found `*` + } +} + +fn h() { + match 8 { + ..(_) => () //~ error: expected one of `=>`, `if`, or `|`, found `(` + } +} + +fn i() { + match 9 { + 4..=(2 + _) => () + //~^ error: expected a pattern range bound, found an expression + //~| error: range pattern bounds cannot have parentheses + } +} + +fn main() {} diff --git a/tests/ui/parser/pat-recover-wildcards.stderr b/tests/ui/parser/pat-recover-wildcards.stderr new file mode 100644 index 0000000000000..2b0c9bbc5be86 --- /dev/null +++ b/tests/ui/parser/pat-recover-wildcards.stderr @@ -0,0 +1,77 @@ +error: expected one of `=>`, `if`, or `|`, found `+` + --> $DIR/pat-recover-wildcards.rs:5:11 + | +LL | _ + 1 => () + | ^ expected one of `=>`, `if`, or `|` + +error: expected one of `)`, `,`, or `|`, found `%` + --> $DIR/pat-recover-wildcards.rs:11:12 + | +LL | (_ % 4) => () + | ^ expected one of `)`, `,`, or `|` + +error: expected one of `=>`, `if`, or `|`, found `.` + --> $DIR/pat-recover-wildcards.rs:17:10 + | +LL | _.x() => () + | ^ expected one of `=>`, `if`, or `|` + +error: expected one of `=>`, `if`, or `|`, found `..=` + --> $DIR/pat-recover-wildcards.rs:23:10 + | +LL | _..=4 => () + | ^^^ expected one of `=>`, `if`, or `|` + +error: expected one of `=>`, `if`, or `|`, found reserved identifier `_` + --> $DIR/pat-recover-wildcards.rs:29:11 + | +LL | .._ => () + | ^ expected one of `=>`, `if`, or `|` + +error[E0586]: inclusive range with no end + --> $DIR/pat-recover-wildcards.rs:35:10 + | +LL | 0..._ => () + | ^^^ help: use `..` instead + | + = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) + +error: expected one of `=>`, `if`, or `|`, found reserved identifier `_` + --> $DIR/pat-recover-wildcards.rs:35:13 + | +LL | 0..._ => () + | ^ expected one of `=>`, `if`, or `|` + +error: expected one of `)`, `,`, or `|`, found `*` + --> $DIR/pat-recover-wildcards.rs:43:12 + | +LL | (_ * 0)..5 => () + | ^ expected one of `)`, `,`, or `|` + +error: expected one of `=>`, `if`, or `|`, found `(` + --> $DIR/pat-recover-wildcards.rs:49:11 + | +LL | ..(_) => () + | ^ expected one of `=>`, `if`, or `|` + +error: expected a pattern range bound, found an expression + --> $DIR/pat-recover-wildcards.rs:55:14 + | +LL | 4..=(2 + _) => () + | ^^^^^ arbitrary expressions are not allowed in patterns + +error: range pattern bounds cannot have parentheses + --> $DIR/pat-recover-wildcards.rs:55:13 + | +LL | 4..=(2 + _) => () + | ^ ^ + | +help: remove these parentheses + | +LL - 4..=(2 + _) => () +LL + 4..=2 + _ => () + | + +error: aborting due to 11 previous errors + +For more information about this error, try `rustc --explain E0586`. From a13fbaa1b6084525427be5266982c3ef5867d732 Mon Sep 17 00:00:00 2001 From: Lieselotte <52315535+she3py@users.noreply.github.com> Date: Fri, 19 Jan 2024 22:53:18 +0100 Subject: [PATCH 07/18] Refactor `maybe_recover_trailing_expr` --- compiler/rustc_parse/src/parser/pat.rs | 45 ++++++++++++++------------ 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 4347b0debba93..d04921dde54b7 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -24,7 +24,6 @@ use rustc_session::errors::ExprParenthesesNeeded; use rustc_span::source_map::{respan, Spanned}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{ErrorGuaranteed, Span}; -use std::borrow::Cow; use thin_vec::{thin_vec, ThinVec}; #[derive(PartialEq, Copy, Clone)] @@ -337,11 +336,19 @@ impl<'a> Parser<'a> { } } - /// Ensures that the last parsed pattern is not followed by a method call or an operator. + /// Ensures that the last parsed pattern (or pattern range bound) is not followed by a method call or an operator. + /// + /// `is_end_bound` indicates whether the last parsed thing was the end bound of a range pattern (see [`parse_pat_range_end`](Self::parse_pat_range_end)) + /// in order to say "expected a pattern range bound" instead of "expected a pattern"; + /// ```text + /// 0..=1 + 2 + /// ^^^^^ + /// ``` + /// Only the end bound is spanned, and this function have no idea if there were a `..=` before `pat_span`, hence the parameter. #[must_use = "the pattern must be discarded as `PatKind::Err` if this function returns Some"] - fn maybe_recover_trailing_expr<'b>( - &'b mut self, - pat: Cow<'b, P>, + fn maybe_recover_trailing_expr( + &mut self, + pat_span: Span, is_end_bound: bool, ) -> Option { if self.prev_token.is_keyword(kw::Underscore) || !self.may_recover() { @@ -353,7 +360,7 @@ impl<'a> Parser<'a> { let has_trailing_method = self.check_noexpect(&token::Dot) && self.look_ahead(1, |tok| { tok.ident() - .and_then(|(ident, _)| ident.name.to_string().chars().next()) + .and_then(|(ident, _)| ident.name.as_str().chars().next()) .is_some_and(char::is_lowercase) }) && self.look_ahead(2, |tok| tok.kind == token::OpenDelim(Delimiter::Parenthesis)); @@ -374,15 +381,16 @@ impl<'a> Parser<'a> { } // Let's try to parse an expression to emit a better diagnostic. - let pat = pat.into_owned(); - let pat_span = pat.span; - let mut snapshot = self.create_snapshot_for_diagnostic(); snapshot.restrictions.insert(Restrictions::IS_PAT); // Parse `?`, `.f`, `(arg0, arg1, ...)` or `[expr]` until they've all been eaten. if let Ok(expr) = snapshot - .parse_expr_dot_or_call_with(pat, pat_span, AttrVec::new()) + .parse_expr_dot_or_call_with( + self.mk_expr_err(pat_span), // equivalent to transforming the parsed pattern into an `Expr` + pat_span, + AttrVec::new(), + ) .map_err(|err| err.cancel()) { let non_assoc_span = expr.span; @@ -396,8 +404,6 @@ impl<'a> Parser<'a> { self.restore_snapshot(snapshot); self.restrictions.remove(Restrictions::IS_PAT); - let span = expr.span; - let is_bound = is_end_bound // is_start_bound: either `..` or `)..` || self.token.is_range_separator() @@ -405,10 +411,10 @@ impl<'a> Parser<'a> { && self.look_ahead(1, Token::is_range_separator); // Check that `parse_expr_assoc_with` didn't eat a rhs. - let is_method_call = has_trailing_method && non_assoc_span == span; + let is_method_call = has_trailing_method && non_assoc_span == expr.span; return Some(self.dcx().emit_err(UnexpectedExpressionInPattern { - span, + span: expr.span, is_bound, is_method_call, })); @@ -524,8 +530,7 @@ impl<'a> Parser<'a> { } else if self.check(&token::OpenDelim(Delimiter::Parenthesis)) { self.parse_pat_tuple_struct(qself, path)? } else { - let pat = self.mk_expr(span, ExprKind::Path(qself.clone(), path.clone())); - match self.maybe_recover_trailing_expr(Cow::Owned(pat), false) { + match self.maybe_recover_trailing_expr(span, false) { Some(guar) => PatKind::Err(guar), None => PatKind::Path(qself, path), } @@ -558,8 +563,7 @@ impl<'a> Parser<'a> { // Try to parse everything else as literal with optional minus match self.parse_literal_maybe_minus() { Ok(begin) => { - let begin = match self.maybe_recover_trailing_expr(Cow::Borrowed(&begin), false) - { + let begin = match self.maybe_recover_trailing_expr(begin.span, false) { Some(_) => self.mk_expr_err(begin.span), None => begin, }; @@ -963,7 +967,7 @@ impl<'a> Parser<'a> { self.parse_literal_maybe_minus() }?; - let recovered = self.maybe_recover_trailing_expr(Cow::Borrowed(&bound), true); + let recovered = self.maybe_recover_trailing_expr(bound.span, true); // recover trailing `)` if let Some(open_paren) = open_paren { @@ -1047,9 +1051,8 @@ impl<'a> Parser<'a> { // Check for method calls after the `ident`, // but not `ident @ subpat` as `subpat` was already checked and `ident` continues with `@`. - let expr = self.mk_expr(ident.span, ExprKind::Path(None, Path::from_ident(ident))); let pat = if sub.is_none() - && let Some(guar) = self.maybe_recover_trailing_expr(Cow::Owned(expr), false) + && let Some(guar) = self.maybe_recover_trailing_expr(ident.span, false) { PatKind::Err(guar) } else { From ab938b9acbf1d5849198cba19e14959d8ad2871f Mon Sep 17 00:00:00 2001 From: Frank Steffahn Date: Tue, 23 Jan 2024 11:29:11 +0100 Subject: [PATCH 08/18] Improve documentation for [A]Rc::into_inner General improvements, and also aims to better encourage the reader to actually check out Arc::try_unwrap. --- library/alloc/src/rc.rs | 7 +++++-- library/alloc/src/sync.rs | 10 +++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index f986df058467b..197d3a6e55ef6 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -938,8 +938,11 @@ impl Rc { /// it is guaranteed that exactly one of the calls returns the inner value. /// This means in particular that the inner value is not dropped. /// - /// This is equivalent to `Rc::try_unwrap(this).ok()`. (Note that these are not equivalent for - /// [`Arc`](crate::sync::Arc), due to race conditions that do not apply to `Rc`.) + /// [`Rc::try_unwrap`] is conceptually similar to `Rc::into_inner`. + /// And while they are meant for different use-cases, `Rc::into_inner(this)` + /// is in fact equivalent to [Rc::try_unwrap]\(this).[ok][Result::ok](). + /// (Note that the same kind of equivalence does **not** hold true for + /// [`Arc`](crate::sync::Arc), due to race conditions that do not apply to `Rc`!) #[inline] #[stable(feature = "rc_into_inner", since = "1.70.0")] pub fn into_inner(this: Self) -> Option { diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index dc82c9c411110..4784a5db17ab5 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -983,9 +983,13 @@ impl Arc { /// it is guaranteed that exactly one of the calls returns the inner value. /// This means in particular that the inner value is not dropped. /// - /// The similar expression `Arc::try_unwrap(this).ok()` does not - /// offer such a guarantee. See the last example below - /// and the documentation of [`Arc::try_unwrap`]. + /// [`Arc::try_unwrap`] is conceptually similar to `Arc::into_inner`, but it + /// is meant for different use-cases. If used as a direct replacement + /// for `Arc::into_inner` anyway, such as with the expression + /// [Arc::try_unwrap]\(this).[ok][Result::ok](), then it does + /// **not** give the same guarantee as described in the previous paragraph. + /// For more information, see the examples below and read the documentation + /// of [`Arc::try_unwrap`]. /// /// # Examples /// From 797cf5927872459a00ca3a2758216c8aa89cef2b Mon Sep 17 00:00:00 2001 From: Lawrence Tang Date: Mon, 22 Jan 2024 11:33:02 +0000 Subject: [PATCH 09/18] Add support for custom JSON targets when using build-std. Currently, when building with `build-std`, some library build scripts check properties of the target by inspecting the target triple at `env::TARGET`, which is simply set to the filename of the JSON file when using JSON target files. This patch alters these build scripts to use `env::CARGO_CFG_*` to fetch target information instead, allowing JSON target files describing platforms without `restricted_std` to build correctly when using `-Z build-std`. Fixes wg-cargo-std-aware/#60. --- library/profiler_builtins/build.rs | 7 +-- library/std/build.rs | 77 ++++++++++++++++-------------- 2 files changed, 45 insertions(+), 39 deletions(-) diff --git a/library/profiler_builtins/build.rs b/library/profiler_builtins/build.rs index d14d0b82229a1..8e7b72f837220 100644 --- a/library/profiler_builtins/build.rs +++ b/library/profiler_builtins/build.rs @@ -12,7 +12,8 @@ fn main() { return; } - let target = env::var("TARGET").expect("TARGET was not set"); + let target_os = env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS was not set"); + let target_env = env::var("CARGO_CFG_TARGET_ENV").expect("CARGO_CFG_TARGET_ENV was not set"); let cfg = &mut cc::Build::new(); // FIXME: `rerun-if-changed` directives are not currently emitted and the build script @@ -40,7 +41,7 @@ fn main() { "InstrProfilingBiasVar.c", ]; - if target.contains("msvc") { + if target_env == "msvc" { // Don't pull in extra libraries on MSVC cfg.flag("/Zl"); profile_sources.push("WindowsMMap.c"); @@ -55,7 +56,7 @@ fn main() { cfg.flag("-fno-builtin"); cfg.flag("-fomit-frame-pointer"); cfg.define("VISIBILITY_HIDDEN", None); - if !target.contains("windows") { + if target_os != "windows" { cfg.flag("-fvisibility=hidden"); cfg.define("COMPILER_RT_HAS_UNAME", Some("1")); } else { diff --git a/library/std/build.rs b/library/std/build.rs index 60c097db2f4bf..b3da198881676 100644 --- a/library/std/build.rs +++ b/library/std/build.rs @@ -2,41 +2,46 @@ use std::env; fn main() { println!("cargo:rerun-if-changed=build.rs"); - let target = env::var("TARGET").expect("TARGET was not set"); - if target.contains("linux") - || target.contains("netbsd") - || target.contains("dragonfly") - || target.contains("openbsd") - || target.contains("freebsd") - || target.contains("solaris") - || target.contains("illumos") - || target.contains("apple-darwin") - || target.contains("apple-ios") - || target.contains("apple-tvos") - || target.contains("apple-watchos") - || target.contains("uwp") - || target.contains("windows") - || target.contains("fuchsia") - || (target.contains("sgx") && target.contains("fortanix")) - || target.contains("hermit") - || target.contains("l4re") - || target.contains("redox") - || target.contains("haiku") - || target.contains("vxworks") - || target.contains("wasm32") - || target.contains("wasm64") - || target.contains("espidf") - || target.contains("solid") - || target.contains("nintendo-3ds") - || target.contains("vita") - || target.contains("aix") - || target.contains("nto") - || target.contains("xous") - || target.contains("hurd") - || target.contains("uefi") - || target.contains("teeos") - || target.contains("zkvm") - // See src/bootstrap/synthetic_targets.rs + let target_arch = env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH was not set"); + let target_os = env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS was not set"); + let target_vendor = + env::var("CARGO_CFG_TARGET_VENDOR").expect("CARGO_CFG_TARGET_VENDOR was not set"); + let target_env = env::var("CARGO_CFG_TARGET_ENV").expect("CARGO_CFG_TARGET_ENV was not set"); + + if target_os == "linux" + || target_os == "netbsd" + || target_os == "dragonfly" + || target_os == "openbsd" + || target_os == "freebsd" + || target_os == "solaris" + || target_os == "illumos" + || target_os == "macos" + || target_os == "ios" + || target_os == "tvos" + || target_os == "watchos" + || target_os == "windows" + || target_os == "fuchsia" + || (target_vendor == "fortranix" && target_env == "sgx") + || target_os == "hermit" + || target_os == "l4re" + || target_os == "redox" + || target_os == "haiku" + || target_os == "vxworks" + || target_arch == "wasm32" + || target_arch == "wasm64" + || target_os == "espidf" + || target_os.starts_with("solid") + || (target_vendor == "nintendo" && target_env == "newlib") + || target_os == "vita" + || target_os == "aix" + || target_os == "nto" + || target_os == "xous" + || target_os == "hurd" + || target_os == "uefi" + || target_os == "teeos" + || target_os == "zkvm" + + // See src/bootstrap/src/core/build_steps/synthetic_targets.rs || env::var("RUSTC_BOOTSTRAP_SYNTHETIC_TARGET").is_ok() { // These platforms don't have any special requirements. @@ -48,7 +53,7 @@ fn main() { // - mipsel-sony-psp // - nvptx64-nvidia-cuda // - arch=avr - // - JSON targets + // - JSON targets not describing an excluded target above. // - Any new targets that have not been explicitly added above. println!("cargo:rustc-cfg=feature=\"restricted-std\""); } From c2c6e333356f53338e6eecd710faf663217a0074 Mon Sep 17 00:00:00 2001 From: Joshua Liebow-Feeser Date: Thu, 25 Jan 2024 06:59:51 -0800 Subject: [PATCH 10/18] Update primitive_docs.rs --- library/core/src/primitive_docs.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 939342c4d9760..fca2d3979ab47 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1403,6 +1403,10 @@ mod prim_usize {} /// If `t` points at address `a`, being "dereferenceable" for N bytes means that the memory range /// `[a, a + N)` is all contained within a single [allocated object]. /// +/// Note that the precise validity invariants for reference types are a work in progress. In the +/// future, new guarantees may be added. However, the guarantees documented in this section will +/// never be removed. +/// /// [allocated object]: ptr#allocated-object #[stable(feature = "rust1", since = "1.0.0")] mod prim_ref {} From 3269513eb0189946c40a67d98724b40321e6e9f3 Mon Sep 17 00:00:00 2001 From: "HTGAzureX1212." <39023054+HTGAzureX1212@users.noreply.github.com> Date: Fri, 26 Jan 2024 20:15:30 +0800 Subject: [PATCH 11/18] fix issue 120040 --- library/std/src/sys/pal/windows/fs.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/library/std/src/sys/pal/windows/fs.rs b/library/std/src/sys/pal/windows/fs.rs index 4248454368644..06a08ea22ebee 100644 --- a/library/std/src/sys/pal/windows/fs.rs +++ b/library/std/src/sys/pal/windows/fs.rs @@ -1068,6 +1068,27 @@ pub fn readdir(p: &Path) -> io::Result { unsafe { let mut wfd = mem::zeroed(); let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd); + + // The status `ERROR_FILE_NOT_FOUND` is returned by the `FindFirstFileW` function + // if no matching files can be found, but not necessarily that the path to find the + // files in does not exist. + // + // Hence, a check for whether the path to search in exists is added when the last + // os error returned by Windows is `ERROR_FILE_NOT_FOUND` to handle this scenario. + // If that is the case, an empty `ReadDir` iterator is returned as it returns `None` + // in the initial `.next()` invocation because `ERROR_NO_MORE_FILES` would have been + // returned by the `FindNextFileW` function. + // + // See issue #120040: https://github.com/rust-lang/rust/issues/120040. + let last_error = Error::last_os_error(); + if last_error.raw_os_error().unwrap() == c::ERROR_FILE_NOT_FOUND && p.exists() { + return Ok(ReadDir { + handle: FindNextFileHandle(file_handle), + root: Arc::new(root), + first: None, + }); + } + if find_handle != c::INVALID_HANDLE_VALUE { Ok(ReadDir { handle: FindNextFileHandle(find_handle), From 8f89e57e9f7fe4a2fccf57161aea39a4e48b6a75 Mon Sep 17 00:00:00 2001 From: "HTGAzureX1212." <39023054+HTGAzureX1212@users.noreply.github.com> Date: Fri, 26 Jan 2024 20:27:20 +0800 Subject: [PATCH 12/18] remove redundant call to Error::last_os_error --- library/std/src/sys/pal/windows/fs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/pal/windows/fs.rs b/library/std/src/sys/pal/windows/fs.rs index 06a08ea22ebee..b5976b87be210 100644 --- a/library/std/src/sys/pal/windows/fs.rs +++ b/library/std/src/sys/pal/windows/fs.rs @@ -1096,7 +1096,7 @@ pub fn readdir(p: &Path) -> io::Result { first: Some(wfd), }) } else { - Err(Error::last_os_error()) + Err(last_error) } } } From 2241d1618960a2d192b2874e925fa51afeb8a83b Mon Sep 17 00:00:00 2001 From: "HTGAzureX1212." <39023054+HTGAzureX1212@users.noreply.github.com> Date: Fri, 26 Jan 2024 20:34:13 +0800 Subject: [PATCH 13/18] fix --- library/std/src/sys/pal/windows/fs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/std/src/sys/pal/windows/fs.rs b/library/std/src/sys/pal/windows/fs.rs index b5976b87be210..38835db7649de 100644 --- a/library/std/src/sys/pal/windows/fs.rs +++ b/library/std/src/sys/pal/windows/fs.rs @@ -1081,9 +1081,9 @@ pub fn readdir(p: &Path) -> io::Result { // // See issue #120040: https://github.com/rust-lang/rust/issues/120040. let last_error = Error::last_os_error(); - if last_error.raw_os_error().unwrap() == c::ERROR_FILE_NOT_FOUND && p.exists() { + if last_error.raw_os_error().unwrap() == c::ERROR_FILE_NOT_FOUND as i32 && p.exists() { return Ok(ReadDir { - handle: FindNextFileHandle(file_handle), + handle: FindNextFileHandle(find_handle), root: Arc::new(root), first: None, }); From e26f213050f451ec3e9c6a3132bc0d5be5123737 Mon Sep 17 00:00:00 2001 From: "HTGAzureX1212." <39023054+HTGAzureX1212@users.noreply.github.com> Date: Sat, 27 Jan 2024 12:28:28 +0800 Subject: [PATCH 14/18] make modifications as per reviews --- library/std/src/sys/pal/windows/fs.rs | 46 +++++++++++++++------------ 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/library/std/src/sys/pal/windows/fs.rs b/library/std/src/sys/pal/windows/fs.rs index 38835db7649de..1a8151479f390 100644 --- a/library/std/src/sys/pal/windows/fs.rs +++ b/library/std/src/sys/pal/windows/fs.rs @@ -1069,26 +1069,6 @@ pub fn readdir(p: &Path) -> io::Result { let mut wfd = mem::zeroed(); let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd); - // The status `ERROR_FILE_NOT_FOUND` is returned by the `FindFirstFileW` function - // if no matching files can be found, but not necessarily that the path to find the - // files in does not exist. - // - // Hence, a check for whether the path to search in exists is added when the last - // os error returned by Windows is `ERROR_FILE_NOT_FOUND` to handle this scenario. - // If that is the case, an empty `ReadDir` iterator is returned as it returns `None` - // in the initial `.next()` invocation because `ERROR_NO_MORE_FILES` would have been - // returned by the `FindNextFileW` function. - // - // See issue #120040: https://github.com/rust-lang/rust/issues/120040. - let last_error = Error::last_os_error(); - if last_error.raw_os_error().unwrap() == c::ERROR_FILE_NOT_FOUND as i32 && p.exists() { - return Ok(ReadDir { - handle: FindNextFileHandle(find_handle), - root: Arc::new(root), - first: None, - }); - } - if find_handle != c::INVALID_HANDLE_VALUE { Ok(ReadDir { handle: FindNextFileHandle(find_handle), @@ -1096,7 +1076,31 @@ pub fn readdir(p: &Path) -> io::Result { first: Some(wfd), }) } else { - Err(last_error) + // The status `ERROR_FILE_NOT_FOUND` is returned by the `FindFirstFileW` function + // if no matching files can be found, but not necessarily that the path to find the + // files in does not exist. + // + // Hence, a check for whether the path to search in exists is added when the last + // os error returned by Windows is `ERROR_FILE_NOT_FOUND` to handle this scenario. + // If that is the case, an empty `ReadDir` iterator is returned as it returns `None` + // in the initial `.next()` invocation because `ERROR_NO_MORE_FILES` would have been + // returned by the `FindNextFileW` function. + // + // See issue #120040: https://github.com/rust-lang/rust/issues/120040. + let last_error = api::get_last_error(); + if last_error.code == c::ERROR_FILE_NOT_FOUND { + return Ok(ReadDir { + handle: FindNextFileHandle(find_handle), + root: Arc::new(root), + first: None, + }); + } + + // Just return the error constructed from the raw OS error if the above is not the case. + // + // Note: `ERROR_PATH_NOT_FOUND` would have been returned by the `FindFirstFileW` function + // when the path to search in does not exist in the first place. + Err(Error::from_raw_os_error(last_error.code as i32)); } } } From 018bf305cdcc2d478998642bc2d9a5613ec902f3 Mon Sep 17 00:00:00 2001 From: "HTGAzureX1212." <39023054+HTGAzureX1212@users.noreply.github.com> Date: Sat, 27 Jan 2024 12:43:38 +0800 Subject: [PATCH 15/18] add extra check for invalid handle in ReadDir::next --- library/std/src/sys/pal/windows/fs.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/library/std/src/sys/pal/windows/fs.rs b/library/std/src/sys/pal/windows/fs.rs index 1a8151479f390..2bdd3d96fa48c 100644 --- a/library/std/src/sys/pal/windows/fs.rs +++ b/library/std/src/sys/pal/windows/fs.rs @@ -112,6 +112,13 @@ impl fmt::Debug for ReadDir { impl Iterator for ReadDir { type Item = io::Result; fn next(&mut self) -> Option> { + if self.handle.0 == c::INVALID_HANDLE_VALUE { + // This iterator was initialized with an `INVALID_HANDLE_VALUE` as its handle. + // Simply return `None` because this is only the case when `FindFirstFileW` in + // the construction of this iterator returns `ERROR_FILE_NOT_FOUND` which means + // no matchhing files can be found. + return None; + } if let Some(first) = self.first.take() { if let Some(e) = DirEntry::new(&self.root, &first) { return Some(Ok(e)); @@ -1100,7 +1107,7 @@ pub fn readdir(p: &Path) -> io::Result { // // Note: `ERROR_PATH_NOT_FOUND` would have been returned by the `FindFirstFileW` function // when the path to search in does not exist in the first place. - Err(Error::from_raw_os_error(last_error.code as i32)); + Err(Error::from_raw_os_error(last_error.code as i32)) } } } From 8d708e55eff9026eb379fe409e9ecc0619962640 Mon Sep 17 00:00:00 2001 From: joboet Date: Sat, 27 Jan 2024 17:24:45 +0100 Subject: [PATCH 16/18] std: always check the result of `pthread_mutex_lock` --- .../src/sys/pal/unix/locks/pthread_mutex.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/library/std/src/sys/pal/unix/locks/pthread_mutex.rs b/library/std/src/sys/pal/unix/locks/pthread_mutex.rs index 8a78bc1fd7399..05caa3f2361a3 100644 --- a/library/std/src/sys/pal/unix/locks/pthread_mutex.rs +++ b/library/std/src/sys/pal/unix/locks/pthread_mutex.rs @@ -1,4 +1,5 @@ use crate::cell::UnsafeCell; +use crate::io::Error; use crate::mem::{forget, MaybeUninit}; use crate::sys::cvt_nz; use crate::sys_common::lazy_box::{LazyBox, LazyInit}; @@ -103,8 +104,24 @@ impl Mutex { #[inline] pub unsafe fn lock(&self) { + #[cold] + #[inline(never)] + fn fail() -> ! { + let error = Error::last_os_error(); + panic!("failed to lock mutex: {error}"); + } + let r = libc::pthread_mutex_lock(raw(self)); - debug_assert_eq!(r, 0); + // As we set the mutex type to `PTHREAD_MUTEX_NORMAL` above, we expect + // the lock call to never fail. Unfortunately however, some platforms + // (Solaris) do not conform to the standard, and instead always provide + // deadlock detection. How kind of them! Unfortunately that means that + // we need to check the error code here. To save us from UB on other + // less well-behaved platforms in the future, we do it even on "good" + // platforms like macOS. See #120147 for more context. + if r != 0 { + fail() + } } #[inline] From b867c7c707be0070beac663a03eb6a797f076f68 Mon Sep 17 00:00:00 2001 From: Joshua Liebow-Feeser Date: Sat, 27 Jan 2024 08:47:14 -0800 Subject: [PATCH 17/18] Update primitive_docs.rs --- library/core/src/primitive_docs.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index fca2d3979ab47..e9c30ce9a23f5 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1392,10 +1392,8 @@ mod prim_usize {} /// /// # Safety /// -/// For all types, `T: ?Sized`, and for all `t: &T` or `t: &mut T`, unsafe code may assume that -/// the following properties hold. Rust programmers must assume that, unless explicitly stated -/// otherwise, any Rust code they did not author themselves may rely on these properties, and that -/// violating them may cause that code to exhibit undefined behavior. +/// For all types, `T: ?Sized`, and for all `t: &T` or `t: &mut T`, when such values cross an API +/// boundary, the following invariants must generally be upheld: /// /// * `t` is aligned to `align_of_val(t)` /// * `t` is dereferenceable for `size_of_val(t)` many bytes @@ -1403,9 +1401,16 @@ mod prim_usize {} /// If `t` points at address `a`, being "dereferenceable" for N bytes means that the memory range /// `[a, a + N)` is all contained within a single [allocated object]. /// -/// Note that the precise validity invariants for reference types are a work in progress. In the -/// future, new guarantees may be added. However, the guarantees documented in this section will -/// never be removed. +/// For instance, this means that unsafe code in a safe function may assume these invariants are +/// ensured of arguments passed by the caller, and it may assume that these invariants are ensured +/// of return values from any safe functions it calls. In most cases, the inverse is also true: +/// unsafe code must not violate these invariants when passing arguments to safe functions or +/// returning values from safe functions; such violations may result in undefined behavior. Where +/// exceptions to this latter requirement exist, they will be called out explicitly in documentation. +/// +/// It is not decided yet whether unsafe code may violate these invariants temporarily on internal +/// data. As a consequence, unsafe code which violates these invariants temporarily on internal data +/// may become unsound in future versions of Rust depending on how this question is decided. /// /// [allocated object]: ptr#allocated-object #[stable(feature = "rust1", since = "1.0.0")] From 75f889b57975149470176834c61964c67ecdc6ee Mon Sep 17 00:00:00 2001 From: yukang Date: Sat, 27 Jan 2024 19:09:55 +0800 Subject: [PATCH 18/18] Supress unhelpful diagnostics for unresolved top level attributes --- compiler/rustc_errors/src/lib.rs | 1 + compiler/rustc_passes/src/check_attr.rs | 12 +++++- compiler/rustc_resolve/src/macros.rs | 31 +++++++------- tests/ui/derives/issue-36617.rs | 10 ++--- tests/ui/derives/issue-36617.stderr | 42 +------------------ tests/ui/extenv/issue-55897.rs | 1 - tests/ui/extenv/issue-55897.stderr | 14 ++----- .../issue-43106-gating-of-bench.rs | 3 +- .../issue-43106-gating-of-bench.stderr | 12 +----- .../issue-43106-gating-of-test.rs | 3 +- .../issue-43106-gating-of-test.stderr | 12 +----- tests/ui/imports/issue-28134.rs | 2 +- tests/ui/imports/issue-28134.stderr | 10 +---- tests/ui/imports/issue-55457.rs | 7 ++-- tests/ui/imports/issue-55457.stderr | 36 +--------------- tests/ui/imports/issue-59764.rs | 1 - tests/ui/imports/issue-59764.stderr | 12 +----- .../derive-helper-legacy-spurious.rs | 2 +- .../derive-helper-legacy-spurious.stderr | 10 +---- .../issue-118455-skip-err-builtin.rs | 6 +++ .../issue-118455-skip-err-builtin.stderr | 8 ++++ ...est-fix-invalid-top-level-macro-attr.fixed | 6 +++ ...uggest-fix-invalid-top-level-macro-attr.rs | 6 +++ ...st-fix-invalid-top-level-macro-attr.stderr | 16 +++++++ tests/ui/reserved/reserved-attr-on-macro.rs | 2 +- .../ui/reserved/reserved-attr-on-macro.stderr | 10 +---- tests/ui/rust-2018/issue-54006.rs | 1 - tests/ui/rust-2018/issue-54006.stderr | 10 +---- tests/ui/span/issue-43927-non-ADT-derive.rs | 3 +- .../ui/span/issue-43927-non-ADT-derive.stderr | 12 +----- 30 files changed, 100 insertions(+), 201 deletions(-) create mode 100644 tests/ui/proc-macro/issue-118455-skip-err-builtin.rs create mode 100644 tests/ui/proc-macro/issue-118455-skip-err-builtin.stderr create mode 100644 tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.fixed create mode 100644 tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.rs create mode 100644 tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.stderr diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index ee831c4f560c0..1decb7b06b8a7 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -509,6 +509,7 @@ pub enum StashKey { MaybeForgetReturn, /// Query cycle detected, stashing in favor of a better error. Cycle, + UndeterminedMacroResolution, } fn default_track_diagnostic(diag: Diagnostic, f: &mut dyn FnMut(Diagnostic)) { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 9d9741bbe8947..5886378c0b76f 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -5,8 +5,10 @@ //! item. use crate::{errors, fluent_generated as fluent}; -use rustc_ast::{ast, AttrStyle, Attribute, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem}; +use rustc_ast::{ast, AttrKind, AttrStyle, Attribute, LitKind}; +use rustc_ast::{MetaItemKind, MetaItemLit, NestedMetaItem}; use rustc_data_structures::fx::FxHashMap; +use rustc_errors::StashKey; use rustc_errors::{Applicability, DiagCtxt, IntoDiagnosticArg, MultiSpan}; use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP}; use rustc_hir as hir; @@ -2530,6 +2532,14 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) { if attr.style == AttrStyle::Inner { for attr_to_check in ATTRS_TO_CHECK { if attr.has_name(*attr_to_check) { + if let AttrKind::Normal(ref p) = attr.kind + && let Some(diag) = tcx.dcx().steal_diagnostic( + p.item.path.span, + StashKey::UndeterminedMacroResolution, + ) + { + diag.cancel(); + } let item = tcx .hir() .items() diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 1c085ddf57bf6..b8b00ddcf43c5 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -1,10 +1,9 @@ //! A bunch of methods and structures more or less related to resolving macros and //! interface provided by `Resolver` to macro expander. -use crate::errors::{ - self, AddAsNonDerive, CannotDetermineMacroResolution, CannotFindIdentInThisScope, - MacroExpectedFound, RemoveSurroundingDerive, -}; +use crate::errors::CannotDetermineMacroResolution; +use crate::errors::{self, AddAsNonDerive, CannotFindIdentInThisScope}; +use crate::errors::{MacroExpectedFound, RemoveSurroundingDerive}; use crate::Namespace::*; use crate::{BuiltinMacroState, Determinacy, MacroData}; use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet}; @@ -15,6 +14,7 @@ use rustc_ast_pretty::pprust; use rustc_attr::StabilityLevel; use rustc_data_structures::intern::Interned; use rustc_data_structures::sync::Lrc; +use rustc_errors::StashKey; use rustc_errors::{struct_span_code_err, Applicability}; use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand}; use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind}; @@ -25,9 +25,8 @@ use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_middle::middle::stability; use rustc_middle::ty::RegisteredTools; use rustc_middle::ty::{TyCtxt, Visibility}; -use rustc_session::lint::builtin::{ - LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE, UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, -}; +use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; +use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE}; use rustc_session::lint::builtin::{UNUSED_MACROS, UNUSED_MACRO_RULES}; use rustc_session::lint::BuiltinLintDiagnostics; use rustc_session::parse::feature_err; @@ -703,21 +702,21 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // situations should be reported as errors, so this is a bug. this.dcx().span_delayed_bug(span, "inconsistent resolution for a macro"); } - } else { + } else if this.tcx.dcx().has_errors().is_none() && this.privacy_errors.is_empty() { // It's possible that the macro was unresolved (indeterminate) and silently // expanded into a dummy fragment for recovery during expansion. // Now, post-expansion, the resolution may succeed, but we can't change the // past and need to report an error. // However, non-speculative `resolve_path` can successfully return private items // even if speculative `resolve_path` returned nothing previously, so we skip this - // less informative error if the privacy error is reported elsewhere. - if this.privacy_errors.is_empty() { - this.dcx().emit_err(CannotDetermineMacroResolution { - span, - kind: kind.descr(), - path: Segment::names_to_string(path), - }); - } + // less informative error if no other error is reported elsewhere. + + let err = this.dcx().create_err(CannotDetermineMacroResolution { + span, + kind: kind.descr(), + path: Segment::names_to_string(path), + }); + err.stash(span, StashKey::UndeterminedMacroResolution); } }; diff --git a/tests/ui/derives/issue-36617.rs b/tests/ui/derives/issue-36617.rs index 08f293d2ebb06..236ec7748cbdd 100644 --- a/tests/ui/derives/issue-36617.rs +++ b/tests/ui/derives/issue-36617.rs @@ -1,16 +1,16 @@ -#![derive(Copy)] //~ ERROR cannot determine resolution for the attribute macro `derive` +#![derive(Copy)] //~^ ERROR `derive` attribute cannot be used at crate level -#![test]//~ ERROR cannot determine resolution for the attribute macro `test` +#![test] //~^ ERROR `test` attribute cannot be used at crate level -#![test_case]//~ ERROR cannot determine resolution for the attribute macro `test_case` +#![test_case] //~^ ERROR `test_case` attribute cannot be used at crate level -#![bench]//~ ERROR cannot determine resolution for the attribute macro `bench` +#![bench] //~^ ERROR `bench` attribute cannot be used at crate level -#![global_allocator]//~ ERROR cannot determine resolution for the attribute macro `global_allocator` +#![global_allocator] //~^ ERROR `global_allocator` attribute cannot be used at crate level fn main() {} diff --git a/tests/ui/derives/issue-36617.stderr b/tests/ui/derives/issue-36617.stderr index 98be7963e5ef9..3de1d87c5046c 100644 --- a/tests/ui/derives/issue-36617.stderr +++ b/tests/ui/derives/issue-36617.stderr @@ -1,43 +1,3 @@ -error: cannot determine resolution for the attribute macro `derive` - --> $DIR/issue-36617.rs:1:4 - | -LL | #![derive(Copy)] - | ^^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - -error: cannot determine resolution for the attribute macro `test` - --> $DIR/issue-36617.rs:4:4 - | -LL | #![test] - | ^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - -error: cannot determine resolution for the attribute macro `test_case` - --> $DIR/issue-36617.rs:7:4 - | -LL | #![test_case] - | ^^^^^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - -error: cannot determine resolution for the attribute macro `bench` - --> $DIR/issue-36617.rs:10:4 - | -LL | #![bench] - | ^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - -error: cannot determine resolution for the attribute macro `global_allocator` - --> $DIR/issue-36617.rs:13:4 - | -LL | #![global_allocator] - | ^^^^^^^^^^^^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - error: `derive` attribute cannot be used at crate level --> $DIR/issue-36617.rs:1:1 | @@ -113,5 +73,5 @@ LL - #![global_allocator] LL + #[global_allocator] | -error: aborting due to 10 previous errors +error: aborting due to 5 previous errors diff --git a/tests/ui/extenv/issue-55897.rs b/tests/ui/extenv/issue-55897.rs index b7533f41351da..b6500e5405933 100644 --- a/tests/ui/extenv/issue-55897.rs +++ b/tests/ui/extenv/issue-55897.rs @@ -4,7 +4,6 @@ mod unresolved_env { use env; //~ ERROR unresolved import `env` include!(concat!(env!("NON_EXISTENT"), "/data.rs")); - //~^ ERROR cannot determine resolution for the macro `env` } mod nonexistent_env { diff --git a/tests/ui/extenv/issue-55897.stderr b/tests/ui/extenv/issue-55897.stderr index 401db827813a9..2e8c05cca867f 100644 --- a/tests/ui/extenv/issue-55897.stderr +++ b/tests/ui/extenv/issue-55897.stderr @@ -1,5 +1,5 @@ error: environment variable `NON_EXISTENT` not defined at compile time - --> $DIR/issue-55897.rs:11:22 + --> $DIR/issue-55897.rs:10:22 | LL | include!(concat!(env!("NON_EXISTENT"), "/data.rs")); | ^^^^^^^^^^^^^^^^^^^^ @@ -8,7 +8,7 @@ LL | include!(concat!(env!("NON_EXISTENT"), "/data.rs")); = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: suffixes on string literals are invalid - --> $DIR/issue-55897.rs:16:22 + --> $DIR/issue-55897.rs:15:22 | LL | include!(concat!("NON_EXISTENT"suffix, "/data.rs")); | ^^^^^^^^^^^^^^^^^^^^ invalid suffix `suffix` @@ -33,14 +33,6 @@ help: consider importing this module instead LL | use std::env; | ~~~~~~~~ -error: cannot determine resolution for the macro `env` - --> $DIR/issue-55897.rs:6:22 - | -LL | include!(concat!(env!("NON_EXISTENT"), "/data.rs")); - | ^^^ - | - = note: import resolution is stuck, try simplifying macro imports - -error: aborting due to 5 previous errors +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0432`. diff --git a/tests/ui/feature-gates/issue-43106-gating-of-bench.rs b/tests/ui/feature-gates/issue-43106-gating-of-bench.rs index 796325b79af66..841383a008f54 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-bench.rs +++ b/tests/ui/feature-gates/issue-43106-gating-of-bench.rs @@ -5,6 +5,5 @@ #![feature(custom_inner_attributes)] #![bench = "4100"] -//~^ ERROR cannot determine resolution for the attribute macro `bench` -//~^^ ERROR `bench` attribute cannot be used at crate level +//~^ ERROR `bench` attribute cannot be used at crate level fn main() {} diff --git a/tests/ui/feature-gates/issue-43106-gating-of-bench.stderr b/tests/ui/feature-gates/issue-43106-gating-of-bench.stderr index 8270d46d492a9..912c2746f3835 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-bench.stderr +++ b/tests/ui/feature-gates/issue-43106-gating-of-bench.stderr @@ -1,17 +1,9 @@ -error: cannot determine resolution for the attribute macro `bench` - --> $DIR/issue-43106-gating-of-bench.rs:7:4 - | -LL | #![bench = "4100"] - | ^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - error: `bench` attribute cannot be used at crate level --> $DIR/issue-43106-gating-of-bench.rs:7:1 | LL | #![bench = "4100"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... +LL | LL | fn main() {} | ---- the inner attribute doesn't annotate this function | @@ -21,5 +13,5 @@ LL - #![bench = "4100"] LL + #[bench = "4100"] | -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/feature-gates/issue-43106-gating-of-test.rs b/tests/ui/feature-gates/issue-43106-gating-of-test.rs index 39835c9268eef..38c92d933fdd8 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-test.rs +++ b/tests/ui/feature-gates/issue-43106-gating-of-test.rs @@ -2,6 +2,5 @@ #![allow(soft_unstable)] #![test = "4200"] -//~^ ERROR cannot determine resolution for the attribute macro `test` -//~^^ ERROR `test` attribute cannot be used at crate level +//~^ ERROR `test` attribute cannot be used at crate level fn main() {} diff --git a/tests/ui/feature-gates/issue-43106-gating-of-test.stderr b/tests/ui/feature-gates/issue-43106-gating-of-test.stderr index 922c9861aa3c1..2fc220dc47bd1 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-test.stderr +++ b/tests/ui/feature-gates/issue-43106-gating-of-test.stderr @@ -1,17 +1,9 @@ -error: cannot determine resolution for the attribute macro `test` - --> $DIR/issue-43106-gating-of-test.rs:4:4 - | -LL | #![test = "4200"] - | ^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - error: `test` attribute cannot be used at crate level --> $DIR/issue-43106-gating-of-test.rs:4:1 | LL | #![test = "4200"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... +LL | LL | fn main() {} | ---- the inner attribute doesn't annotate this function | @@ -21,5 +13,5 @@ LL - #![test = "4200"] LL + #[test = "4200"] | -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/imports/issue-28134.rs b/tests/ui/imports/issue-28134.rs index ef2a5d634a678..0cecdf7a0ec73 100644 --- a/tests/ui/imports/issue-28134.rs +++ b/tests/ui/imports/issue-28134.rs @@ -1,5 +1,5 @@ // compile-flags: --test #![allow(soft_unstable)] -#![test] //~ ERROR cannot determine resolution for the attribute macro `test` +#![test] //~^ ERROR 4:1: 4:9: `test` attribute cannot be used at crate level diff --git a/tests/ui/imports/issue-28134.stderr b/tests/ui/imports/issue-28134.stderr index 5315c2e9fee9c..e47aa15e87a94 100644 --- a/tests/ui/imports/issue-28134.stderr +++ b/tests/ui/imports/issue-28134.stderr @@ -1,11 +1,3 @@ -error: cannot determine resolution for the attribute macro `test` - --> $DIR/issue-28134.rs:4:4 - | -LL | #![test] - | ^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - error: `test` attribute cannot be used at crate level --> $DIR/issue-28134.rs:4:1 | @@ -18,5 +10,5 @@ LL - #![test] LL + #[test] | -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/imports/issue-55457.rs b/tests/ui/imports/issue-55457.rs index c1f048897d9ea..fd08294025587 100644 --- a/tests/ui/imports/issue-55457.rs +++ b/tests/ui/imports/issue-55457.rs @@ -1,10 +1,9 @@ use NonExistent; //~ ERROR unresolved import `NonExistent` use non_existent::non_existent; //~ ERROR unresolved import `non_existent` -#[non_existent] //~ ERROR cannot determine resolution for the attribute macro `non_existent` -#[derive(NonExistent)] //~ ERROR cannot determine resolution for the derive macro `NonExistent` - //~| ERROR cannot determine resolution for the derive macro `NonExistent` - //~| ERROR cannot determine resolution for the derive macro `NonExistent` +#[non_existent] +#[derive(NonExistent)] + struct S; fn main() {} diff --git a/tests/ui/imports/issue-55457.stderr b/tests/ui/imports/issue-55457.stderr index 30d2373652b4c..09bb13a060478 100644 --- a/tests/ui/imports/issue-55457.stderr +++ b/tests/ui/imports/issue-55457.stderr @@ -15,40 +15,6 @@ LL | use non_existent::non_existent; | = help: consider adding `extern crate non_existent` to use the `non_existent` crate -error: cannot determine resolution for the derive macro `NonExistent` - --> $DIR/issue-55457.rs:5:10 - | -LL | #[derive(NonExistent)] - | ^^^^^^^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - -error: cannot determine resolution for the attribute macro `non_existent` - --> $DIR/issue-55457.rs:4:3 - | -LL | #[non_existent] - | ^^^^^^^^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - -error: cannot determine resolution for the derive macro `NonExistent` - --> $DIR/issue-55457.rs:5:10 - | -LL | #[derive(NonExistent)] - | ^^^^^^^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: cannot determine resolution for the derive macro `NonExistent` - --> $DIR/issue-55457.rs:5:10 - | -LL | #[derive(NonExistent)] - | ^^^^^^^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - = 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 E0432`. diff --git a/tests/ui/imports/issue-59764.rs b/tests/ui/imports/issue-59764.rs index 09dee8c273268..91b3ddcd84d57 100644 --- a/tests/ui/imports/issue-59764.rs +++ b/tests/ui/imports/issue-59764.rs @@ -128,7 +128,6 @@ use issue_59764::foo::makro; //~^ ERROR unresolved import `issue_59764::foo::makro` [E0432] makro!(bar); -//~^ ERROR cannot determine resolution for the macro `makro` fn main() { bar(); diff --git a/tests/ui/imports/issue-59764.stderr b/tests/ui/imports/issue-59764.stderr index b969515e2f0e6..fe58eb97b8dbf 100644 --- a/tests/ui/imports/issue-59764.stderr +++ b/tests/ui/imports/issue-59764.stderr @@ -226,21 +226,13 @@ help: a macro with this name exists at the root of the crate LL | use issue_59764::makro; | ~~~~~~~~~~~~~~~~~~ -error: cannot determine resolution for the macro `makro` - --> $DIR/issue-59764.rs:130:1 - | -LL | makro!(bar); - | ^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - error[E0425]: cannot find function `bar` in this scope - --> $DIR/issue-59764.rs:134:5 + --> $DIR/issue-59764.rs:133:5 | LL | bar(); | ^^^ not found in this scope -error: aborting due to 18 previous errors +error: aborting due to 17 previous errors Some errors have detailed explanations: E0425, E0432. For more information about an error, try `rustc --explain E0425`. diff --git a/tests/ui/proc-macro/derive-helper-legacy-spurious.rs b/tests/ui/proc-macro/derive-helper-legacy-spurious.rs index 4a7e48eed46c3..b484b42e56672 100644 --- a/tests/ui/proc-macro/derive-helper-legacy-spurious.rs +++ b/tests/ui/proc-macro/derive-helper-legacy-spurious.rs @@ -5,7 +5,7 @@ #[macro_use] extern crate test_macros; -#[derive(Empty)] //~ ERROR cannot determine resolution for the attribute macro `derive` +#[derive(Empty)] #[empty_helper] //~ ERROR cannot find attribute `empty_helper` in this scope struct Foo {} diff --git a/tests/ui/proc-macro/derive-helper-legacy-spurious.stderr b/tests/ui/proc-macro/derive-helper-legacy-spurious.stderr index fd1ed8a3d0ff3..b34713b8ca68e 100644 --- a/tests/ui/proc-macro/derive-helper-legacy-spurious.stderr +++ b/tests/ui/proc-macro/derive-helper-legacy-spurious.stderr @@ -4,19 +4,11 @@ error: cannot find attribute `dummy` in this scope LL | #![dummy] | ^^^^^ -error: cannot determine resolution for the attribute macro `derive` - --> $DIR/derive-helper-legacy-spurious.rs:8:3 - | -LL | #[derive(Empty)] - | ^^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - error: cannot find attribute `empty_helper` in this scope --> $DIR/derive-helper-legacy-spurious.rs:9:3 | LL | #[empty_helper] | ^^^^^^^^^^^^ -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors diff --git a/tests/ui/proc-macro/issue-118455-skip-err-builtin.rs b/tests/ui/proc-macro/issue-118455-skip-err-builtin.rs new file mode 100644 index 0000000000000..baef020612891 --- /dev/null +++ b/tests/ui/proc-macro/issue-118455-skip-err-builtin.rs @@ -0,0 +1,6 @@ +#![some_nonexistent_attribute] +//~^ ERROR cannot find attribute `some_nonexistent_attribute` in this scope +#[derive(Debug)] +pub struct SomeUserCode; + +fn main() {} diff --git a/tests/ui/proc-macro/issue-118455-skip-err-builtin.stderr b/tests/ui/proc-macro/issue-118455-skip-err-builtin.stderr new file mode 100644 index 0000000000000..fa8af87a3d019 --- /dev/null +++ b/tests/ui/proc-macro/issue-118455-skip-err-builtin.stderr @@ -0,0 +1,8 @@ +error: cannot find attribute `some_nonexistent_attribute` in this scope + --> $DIR/issue-118455-skip-err-builtin.rs:1:4 + | +LL | #![some_nonexistent_attribute] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.fixed b/tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.fixed new file mode 100644 index 0000000000000..ae5f9f86726f3 --- /dev/null +++ b/tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.fixed @@ -0,0 +1,6 @@ +// run-rustfix + +#[derive(Debug)] //~ ERROR `derive` attribute cannot be used at crate level +struct Test {} + +fn main() {} diff --git a/tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.rs b/tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.rs new file mode 100644 index 0000000000000..639c64f8827c5 --- /dev/null +++ b/tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.rs @@ -0,0 +1,6 @@ +// run-rustfix + +#![derive(Debug)] //~ ERROR `derive` attribute cannot be used at crate level +struct Test {} + +fn main() {} diff --git a/tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.stderr b/tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.stderr new file mode 100644 index 0000000000000..f62cdd14b873f --- /dev/null +++ b/tests/ui/proc-macro/issue-89566-suggest-fix-invalid-top-level-macro-attr.stderr @@ -0,0 +1,16 @@ +error: `derive` attribute cannot be used at crate level + --> $DIR/issue-89566-suggest-fix-invalid-top-level-macro-attr.rs:3:1 + | +LL | #![derive(Debug)] + | ^^^^^^^^^^^^^^^^^ +LL | struct Test {} + | ---- the inner attribute doesn't annotate this struct + | +help: perhaps you meant to use an outer attribute + | +LL - #![derive(Debug)] +LL + #[derive(Debug)] + | + +error: aborting due to 1 previous error + diff --git a/tests/ui/reserved/reserved-attr-on-macro.rs b/tests/ui/reserved/reserved-attr-on-macro.rs index 2630db0d09785..5c4657e0ec2e1 100644 --- a/tests/ui/reserved/reserved-attr-on-macro.rs +++ b/tests/ui/reserved/reserved-attr-on-macro.rs @@ -7,5 +7,5 @@ macro_rules! foo { } fn main() { - foo!(); //~ ERROR cannot determine resolution for the macro `foo` + foo!(); } diff --git a/tests/ui/reserved/reserved-attr-on-macro.stderr b/tests/ui/reserved/reserved-attr-on-macro.stderr index e55b58bef2855..066f72367b1a5 100644 --- a/tests/ui/reserved/reserved-attr-on-macro.stderr +++ b/tests/ui/reserved/reserved-attr-on-macro.stderr @@ -4,19 +4,11 @@ error: attributes starting with `rustc` are reserved for use by the `rustc` comp LL | #[rustc_attribute_should_be_reserved] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: cannot determine resolution for the macro `foo` - --> $DIR/reserved-attr-on-macro.rs:10:5 - | -LL | foo!(); - | ^^^ - | - = note: import resolution is stuck, try simplifying macro imports - error: cannot find attribute `rustc_attribute_should_be_reserved` in this scope --> $DIR/reserved-attr-on-macro.rs:1:3 | LL | #[rustc_attribute_should_be_reserved] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors diff --git a/tests/ui/rust-2018/issue-54006.rs b/tests/ui/rust-2018/issue-54006.rs index a7a4770fc02f9..6f929731c7674 100644 --- a/tests/ui/rust-2018/issue-54006.rs +++ b/tests/ui/rust-2018/issue-54006.rs @@ -8,6 +8,5 @@ use alloc::vec; pub fn foo() { let mut xs = vec![]; - //~^ ERROR cannot determine resolution for the macro `vec` xs.push(0); } diff --git a/tests/ui/rust-2018/issue-54006.stderr b/tests/ui/rust-2018/issue-54006.stderr index 1978138a68878..35d4c17d2c7f1 100644 --- a/tests/ui/rust-2018/issue-54006.stderr +++ b/tests/ui/rust-2018/issue-54006.stderr @@ -4,14 +4,6 @@ error[E0432]: unresolved import `alloc` LL | use alloc::vec; | ^^^^^ help: a similar path exists: `core::alloc` -error: cannot determine resolution for the macro `vec` - --> $DIR/issue-54006.rs:10:18 - | -LL | let mut xs = vec![]; - | ^^^ - | - = note: import resolution is stuck, try simplifying macro imports - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0432`. diff --git a/tests/ui/span/issue-43927-non-ADT-derive.rs b/tests/ui/span/issue-43927-non-ADT-derive.rs index 935bfa001bfc6..e50ee36d7de95 100644 --- a/tests/ui/span/issue-43927-non-ADT-derive.rs +++ b/tests/ui/span/issue-43927-non-ADT-derive.rs @@ -1,6 +1,5 @@ #![derive(Debug, PartialEq, Eq)] // should be an outer attribute! -//~^ ERROR cannot determine resolution for the attribute macro `derive` -//~^^ ERROR `derive` attribute cannot be used at crate level +//~^ ERROR `derive` attribute cannot be used at crate level struct DerivedOn; fn main() {} diff --git a/tests/ui/span/issue-43927-non-ADT-derive.stderr b/tests/ui/span/issue-43927-non-ADT-derive.stderr index a22a4d2b40a8e..27ed561f5be8a 100644 --- a/tests/ui/span/issue-43927-non-ADT-derive.stderr +++ b/tests/ui/span/issue-43927-non-ADT-derive.stderr @@ -1,17 +1,9 @@ -error: cannot determine resolution for the attribute macro `derive` - --> $DIR/issue-43927-non-ADT-derive.rs:1:4 - | -LL | #![derive(Debug, PartialEq, Eq)] // should be an outer attribute! - | ^^^^^^ - | - = note: import resolution is stuck, try simplifying macro imports - error: `derive` attribute cannot be used at crate level --> $DIR/issue-43927-non-ADT-derive.rs:1:1 | LL | #![derive(Debug, PartialEq, Eq)] // should be an outer attribute! | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... +LL | LL | struct DerivedOn; | --------- the inner attribute doesn't annotate this struct | @@ -21,5 +13,5 @@ LL - #![derive(Debug, PartialEq, Eq)] // should be an outer attribute! LL + #[derive(Debug, PartialEq, Eq)] // should be an outer attribute! | -error: aborting due to 2 previous errors +error: aborting due to 1 previous error