Skip to content

Commit 4003a73

Browse files
authored
Rollup merge of rust-lang#79819 - Aaron1011:feature/macro-trailing-semicolon, r=petrochenkov
Add `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint cc rust-lang#79813 This PR adds an allow-by-default future-compatibility lint `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS`. It fires when a trailing semicolon in a macro body is ignored due to the macro being used in expression position: ```rust macro_rules! foo { () => { true; // WARN } } fn main() { let val = match true { true => false, _ => foo!() }; } ``` The lint takes its level from the macro call site, and can be allowed for a particular macro by adding `#[allow(macro_trailing_semicolon)]`. The lint is set to warn for all internal rustc crates (when being built by a stage1 compiler). After the next beta bump, we can enable the lint for the bootstrap compiler as well.
2 parents d9e56f4 + f902551 commit 4003a73

File tree

10 files changed

+150
-1
lines changed

10 files changed

+150
-1
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -3746,6 +3746,7 @@ dependencies = [
37463746
"rustc_errors",
37473747
"rustc_feature",
37483748
"rustc_lexer",
3749+
"rustc_lint_defs",
37493750
"rustc_macros",
37503751
"rustc_parse",
37513752
"rustc_serialize",

compiler/rustc_expand/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ rustc_attr = { path = "../rustc_attr" }
1818
rustc_data_structures = { path = "../rustc_data_structures" }
1919
rustc_errors = { path = "../rustc_errors" }
2020
rustc_feature = { path = "../rustc_feature" }
21+
rustc_lint_defs = { path = "../rustc_lint_defs" }
2122
rustc_macros = { path = "../rustc_macros" }
2223
rustc_lexer = { path = "../rustc_lexer" }
2324
rustc_parse = { path = "../rustc_parse" }

compiler/rustc_expand/src/mbe/macro_rules.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@ use crate::mbe::transcribe::transcribe;
1111
use rustc_ast as ast;
1212
use rustc_ast::token::{self, NonterminalKind, NtTT, Token, TokenKind::*};
1313
use rustc_ast::tokenstream::{DelimSpan, TokenStream};
14+
use rustc_ast::NodeId;
1415
use rustc_ast_pretty::pprust;
1516
use rustc_attr::{self as attr, TransparencyError};
1617
use rustc_data_structures::fx::FxHashMap;
1718
use rustc_data_structures::sync::Lrc;
1819
use rustc_errors::{Applicability, DiagnosticBuilder};
1920
use rustc_feature::Features;
21+
use rustc_lint_defs::builtin::SEMICOLON_IN_EXPRESSIONS_FROM_MACROS;
2022
use rustc_parse::parser::Parser;
2123
use rustc_session::parse::ParseSess;
2224
use rustc_session::Session;
@@ -37,6 +39,7 @@ crate struct ParserAnyMacro<'a> {
3739
site_span: Span,
3840
/// The ident of the macro we're parsing
3941
macro_ident: Ident,
42+
lint_node_id: NodeId,
4043
arm_span: Span,
4144
}
4245

@@ -110,7 +113,8 @@ fn emit_frag_parse_err(
110113

111114
impl<'a> ParserAnyMacro<'a> {
112115
crate fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
113-
let ParserAnyMacro { site_span, macro_ident, ref mut parser, arm_span } = *self;
116+
let ParserAnyMacro { site_span, macro_ident, ref mut parser, lint_node_id, arm_span } =
117+
*self;
114118
let snapshot = &mut parser.clone();
115119
let fragment = match parse_ast_fragment(parser, kind) {
116120
Ok(f) => f,
@@ -124,6 +128,12 @@ impl<'a> ParserAnyMacro<'a> {
124128
// `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
125129
// but `m!()` is allowed in expression positions (cf. issue #34706).
126130
if kind == AstFragmentKind::Expr && parser.token == token::Semi {
131+
parser.sess.buffer_lint(
132+
SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
133+
parser.token.span,
134+
lint_node_id,
135+
"trailing semicolon in macro used in expression position",
136+
);
127137
parser.bump();
128138
}
129139

@@ -276,6 +286,7 @@ fn generic_extension<'cx>(
276286

277287
let mut p = Parser::new(sess, tts, false, None);
278288
p.last_type_ascription = cx.current_expansion.prior_type_ascription;
289+
let lint_node_id = cx.resolver.lint_node_id(cx.current_expansion.id);
279290

280291
// Let the context choose how to interpret the result.
281292
// Weird, but useful for X-macros.
@@ -287,6 +298,7 @@ fn generic_extension<'cx>(
287298
// macro leaves unparsed tokens.
288299
site_span: sp,
289300
macro_ident: name,
301+
lint_node_id,
290302
arm_span,
291303
});
292304
}

compiler/rustc_lint_defs/src/builtin.rs

+48
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// ignore-tidy-filelength
12
//! Some lints that are built in to the compiler.
23
//!
34
//! These are the built-in lints that are emitted direct in the main
@@ -2833,6 +2834,52 @@ declare_lint! {
28332834
"detects `#[unstable]` on stable trait implementations for stable types"
28342835
}
28352836

2837+
declare_lint! {
2838+
/// The `semicolon_in_expressions_from_macros` lint detects trailing semicolons
2839+
/// in macro bodies when the macro is invoked in expression position.
2840+
/// This was previous accepted, but is being phased out.
2841+
///
2842+
/// ### Example
2843+
///
2844+
/// ```rust,compile_fail
2845+
/// #![deny(semicolon_in_expressions_from_macros)]
2846+
/// macro_rules! foo {
2847+
/// () => { true; }
2848+
/// }
2849+
///
2850+
/// fn main() {
2851+
/// let val = match true {
2852+
/// true => false,
2853+
/// _ => foo!()
2854+
/// };
2855+
/// }
2856+
/// ```
2857+
///
2858+
/// {{produces}}
2859+
///
2860+
/// ### Explanation
2861+
///
2862+
/// Previous, Rust ignored trailing semicolon in a macro
2863+
/// body when a macro was invoked in expression position.
2864+
/// However, this makes the treatment of semicolons in the language
2865+
/// inconsistent, and could lead to unexpected runtime behavior
2866+
/// in some circumstances (e.g. if the macro author expects
2867+
/// a value to be dropped).
2868+
///
2869+
/// This is a [future-incompatible] lint to transition this
2870+
/// to a hard error in the future. See [issue #79813] for more details.
2871+
///
2872+
/// [issue #79813]: https://github.com/rust-lang/rust/issues/79813
2873+
/// [future-incompatible]: ../index.md#future-incompatible-lints
2874+
pub SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
2875+
Allow,
2876+
"trailing semicolon in macro body used as expression",
2877+
@future_incompatible = FutureIncompatibleInfo {
2878+
reference: "issue #79813 <https://github.com/rust-lang/rust/issues/79813>",
2879+
edition: None,
2880+
};
2881+
}
2882+
28362883
declare_lint_pass! {
28372884
/// Does nothing as a lint pass, but registers some `Lint`s
28382885
/// that are used by other parts of the compiler.
@@ -2920,6 +2967,7 @@ declare_lint_pass! {
29202967
USELESS_DEPRECATED,
29212968
UNSUPPORTED_NAKED_FUNCTIONS,
29222969
MISSING_ABI,
2970+
SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
29232971
]
29242972
}
29252973

compiler/rustc_resolve/src/macros.rs

+2
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,8 @@ impl<'a> ResolverExpand for Resolver<'a> {
344344
}
345345

346346
fn lint_node_id(&mut self, expn_id: ExpnId) -> NodeId {
347+
// FIXME - make this more precise. This currently returns the NodeId of the
348+
// nearest closing item - we should try to return the closest parent of the ExpnId
347349
self.invocation_parents
348350
.get(&expn_id)
349351
.map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[*id])

src/bootstrap/bootstrap.py

+1
Original file line numberDiff line numberDiff line change
@@ -833,6 +833,7 @@ def build_bootstrap(self):
833833
target_linker = self.get_toml("linker", build_section)
834834
if target_linker is not None:
835835
env["RUSTFLAGS"] += " -C linker=" + target_linker
836+
# cfg(bootstrap): Add `-Wsemicolon_in_expressions_from_macros` after the next beta bump
836837
env["RUSTFLAGS"] += " -Wrust_2018_idioms -Wunused_lifetimes"
837838
if self.get_toml("deny-warnings", "rust") != "false":
838839
env["RUSTFLAGS"] += " -Dwarnings"

src/bootstrap/builder.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1258,6 +1258,12 @@ impl<'a> Builder<'a> {
12581258
// some code doesn't go through this `rustc` wrapper.
12591259
lint_flags.push("-Wrust_2018_idioms");
12601260
lint_flags.push("-Wunused_lifetimes");
1261+
// cfg(bootstrap): unconditionally enable this warning after the next beta bump
1262+
// This is currently disabled for the stage1 libstd, since build scripts
1263+
// will end up using the bootstrap compiler (which doesn't yet support this lint)
1264+
if compiler.stage != 0 && mode != Mode::Std {
1265+
lint_flags.push("-Wsemicolon_in_expressions_from_macros");
1266+
}
12611267

12621268
if self.config.deny_warnings {
12631269
lint_flags.push("-Dwarnings");
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// check-pass
2+
// Ensure that trailing semicolons are allowed by default
3+
4+
macro_rules! foo {
5+
() => {
6+
true;
7+
}
8+
}
9+
10+
fn main() {
11+
let val = match true {
12+
true => false,
13+
_ => foo!()
14+
};
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// check-pass
2+
#![warn(semicolon_in_expressions_from_macros)]
3+
4+
#[allow(dead_code)]
5+
macro_rules! foo {
6+
($val:ident) => {
7+
true; //~ WARN trailing
8+
//~| WARN this was previously
9+
//~| WARN trailing
10+
//~| WARN this was previously
11+
}
12+
}
13+
14+
fn main() {
15+
// This `allow` doesn't work
16+
#[allow(semicolon_in_expressions_from_macros)]
17+
let _ = {
18+
foo!(first)
19+
};
20+
21+
// This 'allow' doesn't work either
22+
#[allow(semicolon_in_expressions_from_macros)]
23+
let _ = foo!(second);
24+
25+
// But this 'allow' does
26+
#[allow(semicolon_in_expressions_from_macros)]
27+
fn inner() {
28+
let _ = foo!(third);
29+
}
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
warning: trailing semicolon in macro used in expression position
2+
--> $DIR/semicolon-in-expressions-from-macros.rs:7:13
3+
|
4+
LL | true;
5+
| ^
6+
...
7+
LL | foo!(first)
8+
| ----------- in this macro invocation
9+
|
10+
note: the lint level is defined here
11+
--> $DIR/semicolon-in-expressions-from-macros.rs:2:9
12+
|
13+
LL | #![warn(semicolon_in_expressions_from_macros)]
14+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15+
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
16+
= note: for more information, see issue #79813 <https://github.com/rust-lang/rust/issues/79813>
17+
= note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
18+
19+
warning: trailing semicolon in macro used in expression position
20+
--> $DIR/semicolon-in-expressions-from-macros.rs:7:13
21+
|
22+
LL | true;
23+
| ^
24+
...
25+
LL | let _ = foo!(second);
26+
| ------------ in this macro invocation
27+
|
28+
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
29+
= note: for more information, see issue #79813 <https://github.com/rust-lang/rust/issues/79813>
30+
= note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
31+
32+
warning: 2 warnings emitted
33+

0 commit comments

Comments
 (0)