Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion compiler/rustc_ast_lowering/src/path.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::sync::Arc;

use rustc_ast::{self as ast, *};
use rustc_errors::StashKey;
use rustc_hir::def::{DefKind, PartialRes, PerNS, Res};
use rustc_hir::def_id::DefId;
use rustc_hir::{self as hir, GenericArg};
Expand Down Expand Up @@ -298,7 +299,7 @@ impl<'hir, R: ResolverAstLoweringExt<'hir>> LoweringContext<'_, 'hir, R> {
sym::return_type_notation,
);
}
err.emit();
err.stash(path_span, StashKey::ReturnTypeNotation);
(
GenericArgsCtor {
args: Default::default(),
Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_attr_parsing/src/attributes/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ use rustc_span::{ErrorGuaranteed, Span, Symbol, sym};
use thin_vec::ThinVec;

use crate::context::{AcceptContext, ShouldEmit, Stage};
use crate::parser::{ArgParser, MetaItemListParser, MetaItemOrLitParser, NameValueParser};
use crate::parser::{
AllowExprMetavar, ArgParser, MetaItemListParser, MetaItemOrLitParser, NameValueParser,
};
use crate::session_diagnostics::{
AttributeParseError, AttributeParseErrorReason, CfgAttrBadDelim, MetaBadDelimSugg,
ParsedDescription,
Expand Down Expand Up @@ -363,6 +365,7 @@ fn parse_cfg_attr_internal<'a>(
let meta = MetaItemOrLitParser::parse_single(
parser,
ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
AllowExprMetavar::Yes,
)?;
let pred_span = pred_start.with_hi(parser.token.span.hi());

Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_attr_parsing/src/attributes/cfg_select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use rustc_session::lint::BuiltinLintDiag;
use rustc_session::lint::builtin::UNREACHABLE_CFG_SELECT_PREDICATES;
use rustc_span::{ErrorGuaranteed, Span, Symbol, sym};

use crate::parser::MetaItemOrLitParser;
use crate::parser::{AllowExprMetavar, MetaItemOrLitParser};
use crate::{AttributeParser, ParsedDescription, ShouldEmit, parse_cfg_entry};

#[derive(Clone)]
Expand Down Expand Up @@ -94,6 +94,7 @@ pub fn parse_cfg_select(
let meta = MetaItemOrLitParser::parse_single(
p,
ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
AllowExprMetavar::Yes,
)
.map_err(|diag| diag.emit())?;
let cfg_span = meta.span();
Expand Down
7 changes: 4 additions & 3 deletions compiler/rustc_attr_parsing/src/attributes/diagnostic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,11 +470,12 @@ fn parse_filter(input: Symbol) -> FilterFormatString {
// if the integer type has been resolved, to allow targeting all integers.
// `"{integer}"` and `"{float}"` come from numerics that haven't been inferred yet,
// from the `Display` impl of `InferTy` to be precise.
// `"{union|enum|struct}"` is used as a special selector for ADTs.
//
// Don't try to format these later!
Position::ArgumentNamed(arg @ ("integer" | "integral" | "float")) => {
LitOrArg::Lit(Symbol::intern(&format!("{{{arg}}}")))
}
Position::ArgumentNamed(
arg @ ("integer" | "integral" | "float" | "union" | "enum" | "struct"),
) => LitOrArg::Lit(Symbol::intern(&format!("{{{arg}}}"))),

Position::ArgumentNamed(arg) => LitOrArg::Arg(Symbol::intern(arg)),
Position::ArgumentImplicitlyIs(_) => LitOrArg::Lit(sym::empty_braces),
Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_attr_parsing/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use rustc_span::{DUMMY_SP, Span, Symbol, sym};

use crate::context::{AcceptContext, FinalizeContext, FinalizeFn, SharedContext, Stage};
use crate::early_parsed::{EARLY_PARSED_ATTRIBUTES, EarlyParsedState};
use crate::parser::{ArgParser, PathParser, RefPathParser};
use crate::parser::{AllowExprMetavar, ArgParser, PathParser, RefPathParser};
use crate::session_diagnostics::ParsedDescription;
use crate::{Early, Late, OmitDoc, ShouldEmit};

Expand Down Expand Up @@ -139,6 +139,7 @@ impl<'sess> AttributeParser<'sess, Early> {
emit_errors: ShouldEmit,
parse_fn: fn(cx: &mut AcceptContext<'_, '_, Early>, item: &ArgParser) -> Option<T>,
template: &AttributeTemplate,
allow_expr_metavar: AllowExprMetavar,
) -> Option<T> {
let ast::AttrKind::Normal(normal_attr) = &attr.kind else {
panic!("parse_single called on a doc attr")
Expand All @@ -152,6 +153,7 @@ impl<'sess> AttributeParser<'sess, Early> {
&parts,
&sess.psess,
emit_errors,
allow_expr_metavar,
)?;
Self::parse_single_args(
sess,
Expand Down Expand Up @@ -333,6 +335,7 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
&parts,
&self.sess.psess,
self.stage.should_emit(),
AllowExprMetavar::No,
) else {
continue;
};
Expand Down
102 changes: 79 additions & 23 deletions compiler/rustc_attr_parsing/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ impl ArgParser {
parts: &[Symbol],
psess: &'sess ParseSess,
should_emit: ShouldEmit,
allow_expr_metavar: AllowExprMetavar,
) -> Option<Self> {
Some(match value {
AttrArgs::Empty => Self::NoArgs,
Expand All @@ -122,6 +123,7 @@ impl ArgParser {
args.dspan.entire(),
psess,
ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden },
allow_expr_metavar,
) {
Ok(p) => return Some(ArgParser::List(p)),
Err(e) => {
Expand All @@ -147,9 +149,15 @@ impl ArgParser {
}

Self::List(
MetaItemListParser::new(&args.tokens, args.dspan.entire(), psess, should_emit)
.map_err(|e| should_emit.emit_err(e))
.ok()?,
MetaItemListParser::new(
&args.tokens,
args.dspan.entire(),
psess,
should_emit,
allow_expr_metavar,
)
.map_err(|e| should_emit.emit_err(e))
.ok()?,
)
}
AttrArgs::Eq { eq_span, expr } => Self::NameValue(NameValueParser {
Expand Down Expand Up @@ -217,8 +225,9 @@ impl MetaItemOrLitParser {
pub fn parse_single<'sess>(
parser: &mut Parser<'sess>,
should_emit: ShouldEmit,
allow_expr_metavar: AllowExprMetavar,
) -> PResult<'sess, MetaItemOrLitParser> {
let mut this = MetaItemListParserContext { parser, should_emit };
let mut this = MetaItemListParserContext { parser, should_emit, allow_expr_metavar };
this.parse_meta_item_inner()
}

Expand Down Expand Up @@ -404,9 +413,19 @@ fn expr_to_lit<'sess>(
}
}

/// Whether expansions of `expr` metavariables from decrarative macros
/// are permitted. Used when parsing meta items; currently, only `cfg` predicates
/// enable this option
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AllowExprMetavar {
No,
Yes,
}

struct MetaItemListParserContext<'a, 'sess> {
parser: &'a mut Parser<'sess>,
should_emit: ShouldEmit,
allow_expr_metavar: AllowExprMetavar,
}

impl<'a, 'sess> MetaItemListParserContext<'a, 'sess> {
Expand Down Expand Up @@ -447,20 +466,44 @@ impl<'a, 'sess> MetaItemListParserContext<'a, 'sess> {
Ok(lit)
}

fn parse_attr_item(&mut self) -> PResult<'sess, MetaItemParser> {
if let Some(MetaVarKind::Meta { has_meta_form }) = self.parser.token.is_metavar_seq() {
return if has_meta_form {
let attr_item = self
.parser
.eat_metavar_seq(MetaVarKind::Meta { has_meta_form: true }, |this| {
MetaItemListParserContext { parser: this, should_emit: self.should_emit }
.parse_attr_item()
})
.unwrap();
Ok(attr_item)
} else {
self.parser.unexpected_any()
};
fn parse_meta_item(&mut self) -> PResult<'sess, MetaItemParser> {
if let Some(metavar) = self.parser.token.is_metavar_seq() {
match (metavar, self.allow_expr_metavar) {
(kind @ MetaVarKind::Expr { .. }, AllowExprMetavar::Yes) => {
return self
.parser
.eat_metavar_seq(kind, |this| {
MetaItemListParserContext {
parser: this,
should_emit: self.should_emit,
allow_expr_metavar: AllowExprMetavar::Yes,
}
.parse_meta_item()
})
.ok_or_else(|| {
self.parser.unexpected_any::<core::convert::Infallible>().unwrap_err()
});
}
(MetaVarKind::Meta { has_meta_form }, _) => {
return if has_meta_form {
let attr_item = self
.parser
.eat_metavar_seq(MetaVarKind::Meta { has_meta_form: true }, |this| {
MetaItemListParserContext {
parser: this,
should_emit: self.should_emit,
allow_expr_metavar: self.allow_expr_metavar,
}
.parse_meta_item()
})
.unwrap();
Ok(attr_item)
} else {
self.parser.unexpected_any()
};
}
_ => {}
}
}

let path = self.parser.parse_path(PathStyle::Mod)?;
Expand All @@ -469,8 +512,12 @@ impl<'a, 'sess> MetaItemListParserContext<'a, 'sess> {
let args = if self.parser.check(exp!(OpenParen)) {
let start = self.parser.token.span;
let (sub_parsers, _) = self.parser.parse_paren_comma_seq(|parser| {
MetaItemListParserContext { parser, should_emit: self.should_emit }
.parse_meta_item_inner()
MetaItemListParserContext {
parser,
should_emit: self.should_emit,
allow_expr_metavar: self.allow_expr_metavar,
}
.parse_meta_item_inner()
})?;
let end = self.parser.prev_token.span;
ArgParser::List(MetaItemListParser { sub_parsers, span: start.with_hi(end.hi()) })
Expand All @@ -492,7 +539,7 @@ impl<'a, 'sess> MetaItemListParserContext<'a, 'sess> {
Ok(MetaItemOrLitParser::Lit(self.unsuffixed_meta_item_from_lit(token_lit)?))
} else {
let prev_pros = self.parser.approx_token_stream_pos();
match self.parse_attr_item() {
match self.parse_meta_item() {
Ok(item) => Ok(MetaItemOrLitParser::MetaItemParser(item)),
Err(err) => {
// If `parse_attr_item` made any progress, it likely has a more precise error we should prefer
Expand Down Expand Up @@ -580,13 +627,15 @@ impl<'a, 'sess> MetaItemListParserContext<'a, 'sess> {
psess: &'sess ParseSess,
span: Span,
should_emit: ShouldEmit,
allow_expr_metavar: AllowExprMetavar,
) -> PResult<'sess, MetaItemListParser> {
let mut parser = Parser::new(psess, tokens, None);
if let ShouldEmit::ErrorsAndLints { recovery } = should_emit {
parser = parser.recovery(recovery);
}

let mut this = MetaItemListParserContext { parser: &mut parser, should_emit };
let mut this =
MetaItemListParserContext { parser: &mut parser, should_emit, allow_expr_metavar };

// Presumably, the majority of the time there will only be one attr.
let mut sub_parsers = ThinVec::with_capacity(1);
Expand Down Expand Up @@ -618,8 +667,15 @@ impl MetaItemListParser {
span: Span,
psess: &'sess ParseSess,
should_emit: ShouldEmit,
allow_expr_metavar: AllowExprMetavar,
) -> Result<Self, Diag<'sess>> {
MetaItemListParserContext::parse(tokens.clone(), psess, span, should_emit)
MetaItemListParserContext::parse(
tokens.clone(),
psess,
span,
should_emit,
allow_expr_metavar,
)
}

/// Lets you pick and choose as what you want to parse each element in the list
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_builtin_macros/src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
use rustc_ast::tokenstream::TokenStream;
use rustc_ast::{AttrStyle, token};
use rustc_attr_parsing as attr;
use rustc_attr_parsing::parser::MetaItemOrLitParser;
use rustc_attr_parsing::parser::{AllowExprMetavar, MetaItemOrLitParser};
use rustc_attr_parsing::{
AttributeParser, CFG_TEMPLATE, ParsedDescription, ShouldEmit, parse_cfg_entry,
self as attr, AttributeParser, CFG_TEMPLATE, ParsedDescription, ShouldEmit, parse_cfg_entry,
};
use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult};
use rustc_hir::attrs::CfgEntry;
Expand Down Expand Up @@ -44,6 +43,7 @@ fn parse_cfg(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream) -> Result<CfgEntry,
let meta = MetaItemOrLitParser::parse_single(
&mut parser,
ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
AllowExprMetavar::Yes,
)
.map_err(|diag| diag.emit())?;
let cfg = AttributeParser::parse_single_args(
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@ pub enum StashKey {
/// it's a method call without parens. If later on in `hir_typeck` we find out that this is
/// the case we suppress this message and we give a better suggestion.
GenericInFieldExpr,
ReturnTypeNotation,
}

fn default_track_diagnostic<R>(diag: DiagInner, f: &mut dyn FnMut(DiagInner) -> R) -> R {
Expand Down
6 changes: 4 additions & 2 deletions compiler/rustc_expand/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ use rustc_ast::{
self as ast, AttrItemKind, AttrKind, AttrStyle, Attribute, DUMMY_NODE_ID, EarlyParsedAttribute,
HasAttrs, HasTokens, MetaItem, MetaItemInner, NodeId, NormalAttr,
};
use rustc_attr_parsing as attr;
use rustc_attr_parsing::parser::AllowExprMetavar;
use rustc_attr_parsing::{
AttributeParser, CFG_TEMPLATE, EvalConfigResult, ShouldEmit, eval_config_entry, parse_cfg,
self as attr, AttributeParser, CFG_TEMPLATE, EvalConfigResult, ShouldEmit, eval_config_entry,
parse_cfg,
};
use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
use rustc_errors::msg;
Expand Down Expand Up @@ -402,6 +403,7 @@ impl<'a> StripUnconfigured<'a> {
emit_errors,
parse_cfg,
&CFG_TEMPLATE,
AllowExprMetavar::Yes,
) else {
// Cfg attribute was not parsable, give up
return EvalConfigResult::True;
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_expand/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use rustc_ast::{
TyKind, token,
};
use rustc_ast_pretty::pprust;
use rustc_attr_parsing::parser::AllowExprMetavar;
use rustc_attr_parsing::{
AttributeParser, CFG_TEMPLATE, Early, EvalConfigResult, ShouldEmit, eval_config_entry,
parse_cfg, validate_attr,
Expand Down Expand Up @@ -2224,6 +2225,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
parse_cfg,
&CFG_TEMPLATE,
AllowExprMetavar::Yes,
) else {
// Cfg attribute was not parsable, give up
return EvalConfigResult::True;
Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_hir_analysis/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1807,6 +1807,13 @@ pub(crate) struct CmseImplTrait {
pub(crate) struct BadReturnTypeNotation {
#[primary_span]
pub span: Span,
#[suggestion(
"furthermore, argument types not allowed with return type notation",
applicability = "maybe-incorrect",
code = "(..)",
style = "verbose"
)]
pub suggestion: Option<Span>,
}

#[derive(Diagnostic)]
Expand Down
Loading
Loading