Skip to content

Commit e6a57cb

Browse files
authored
Unrolled build for rust-lang#122843
Rollup merge of rust-lang#122843 - WaffleLapkin:semicolon-vs-the-never, r=compiler-errors Add a never type option to make diverging blocks `()` More experiments for ~~the blood god~~ T-lang! Usage example: ```rust #![allow(internal_features)] #![feature(never_type, rustc_attrs)] #![rustc_never_type_options(diverging_block_default = "unit")] fn main() { let _: u8 = { //~ error: expected `u8`, found `()` return; }; } ``` r? compiler-errors I'm not sure how I feel about parsing the attribute every time we create `FnCtxt`. There must be a better way to do this, right?
2 parents 0ad927c + 93297bf commit e6a57cb

File tree

5 files changed

+111
-41
lines changed

5 files changed

+111
-41
lines changed

compiler/rustc_feature/src/builtin_attrs.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -597,9 +597,12 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
597597
),
598598

599599
rustc_attr!(
600-
rustc_never_type_mode, Normal, template!(NameValueStr: "fallback_to_unit|fallback_to_niko|fallback_to_never|no_fallback"), ErrorFollowing,
600+
rustc_never_type_options,
601+
Normal,
602+
template!(List: r#"/*opt*/ fallback = "unit|niko|never|no""#),
603+
ErrorFollowing,
601604
EncodeCrossCrate::No,
602-
"`rustc_never_type_fallback` is used to experiment with never type fallback and work on \
605+
"`rustc_never_type_options` is used to experiment with never type fallback and work on \
603606
never type stabilization, and will never be stable"
604607
),
605608

compiler/rustc_hir_typeck/src/fallback.rs

+4-32
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,11 @@ use rustc_data_structures::{
44
graph::{iterate::DepthFirstSearch, vec_graph::VecGraph},
55
unord::{UnordBag, UnordMap, UnordSet},
66
};
7-
use rustc_hir::def_id::CRATE_DEF_ID;
87
use rustc_infer::infer::{DefineOpaqueTypes, InferOk};
98
use rustc_middle::ty::{self, Ty};
10-
use rustc_span::sym;
119

12-
enum DivergingFallbackBehavior {
10+
#[derive(Copy, Clone)]
11+
pub enum DivergingFallbackBehavior {
1312
/// Always fallback to `()` (aka "always spontaneous decay")
1413
FallbackToUnit,
1514
/// Sometimes fallback to `!`, but mainly fallback to `()` so that most of the crates are not broken.
@@ -78,9 +77,8 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
7877
return false;
7978
}
8079

81-
let diverging_behavior = self.diverging_fallback_behavior();
82-
let diverging_fallback =
83-
self.calculate_diverging_fallback(&unresolved_variables, diverging_behavior);
80+
let diverging_fallback = self
81+
.calculate_diverging_fallback(&unresolved_variables, self.diverging_fallback_behavior);
8482

8583
// We do fallback in two passes, to try to generate
8684
// better error messages.
@@ -94,32 +92,6 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
9492
fallback_occurred
9593
}
9694

97-
fn diverging_fallback_behavior(&self) -> DivergingFallbackBehavior {
98-
let Some((mode, span)) = self
99-
.tcx
100-
.get_attr(CRATE_DEF_ID, sym::rustc_never_type_mode)
101-
.map(|attr| (attr.value_str().unwrap(), attr.span))
102-
else {
103-
if self.tcx.features().never_type_fallback {
104-
return DivergingFallbackBehavior::FallbackToNiko;
105-
}
106-
107-
return DivergingFallbackBehavior::FallbackToUnit;
108-
};
109-
110-
match mode {
111-
sym::fallback_to_unit => DivergingFallbackBehavior::FallbackToUnit,
112-
sym::fallback_to_niko => DivergingFallbackBehavior::FallbackToNiko,
113-
sym::fallback_to_never => DivergingFallbackBehavior::FallbackToNever,
114-
sym::no_fallback => DivergingFallbackBehavior::NoFallback,
115-
_ => {
116-
self.tcx.dcx().span_err(span, format!("unknown never type mode: `{mode}` (supported: `fallback_to_unit`, `fallback_to_niko`, `fallback_to_never` and `no_fallback`)"));
117-
118-
DivergingFallbackBehavior::FallbackToUnit
119-
}
120-
}
121-
}
122-
12395
fn fallback_effects(&self) -> bool {
12496
let unsolved_effects = self.unsolved_effects();
12597

compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs

+26-1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,29 @@ use rustc_trait_selection::traits::{self, ObligationCauseCode, SelectionContext}
4545
use std::iter;
4646
use std::mem;
4747

48+
#[derive(Clone, Copy, Default)]
49+
pub enum DivergingBlockBehavior {
50+
/// This is the current stable behavior:
51+
///
52+
/// ```rust
53+
/// {
54+
/// return;
55+
/// } // block has type = !, even though we are supposedly dropping it with `;`
56+
/// ```
57+
#[default]
58+
Never,
59+
60+
/// Alternative behavior:
61+
///
62+
/// ```ignore (very-unstable-new-attribute)
63+
/// #![rustc_never_type_options(diverging_block_default = "unit")]
64+
/// {
65+
/// return;
66+
/// } // block has type = (), since we are dropping `!` from `return` with `;`
67+
/// ```
68+
Unit,
69+
}
70+
4871
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
4972
pub(in super::super) fn check_casts(&mut self) {
5073
// don't hold the borrow to deferred_cast_checks while checking to avoid borrow checker errors
@@ -1710,7 +1733,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
17101733
//
17111734
// #41425 -- label the implicit `()` as being the
17121735
// "found type" here, rather than the "expected type".
1713-
if !self.diverges.get().is_always() {
1736+
if !self.diverges.get().is_always()
1737+
|| matches!(self.diverging_block_behavior, DivergingBlockBehavior::Unit)
1738+
{
17141739
// #50009 -- Do not point at the entire fn block span, point at the return type
17151740
// span, as it is the cause of the requirement, and
17161741
// `consider_hint_about_removing_semicolon` will point at the last expression

compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs

+72-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ mod checks;
55
mod suggestions;
66

77
use crate::coercion::DynamicCoerceMany;
8+
use crate::fallback::DivergingFallbackBehavior;
9+
use crate::fn_ctxt::checks::DivergingBlockBehavior;
810
use crate::{CoroutineTypes, Diverges, EnclosingBreakables, Inherited};
11+
use hir::def_id::CRATE_DEF_ID;
912
use rustc_errors::{DiagCtxt, ErrorGuaranteed};
1013
use rustc_hir as hir;
1114
use rustc_hir::def_id::{DefId, LocalDefId};
@@ -18,7 +21,7 @@ use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKin
1821
use rustc_middle::ty::{self, Const, Ty, TyCtxt, TypeVisitableExt};
1922
use rustc_session::Session;
2023
use rustc_span::symbol::Ident;
21-
use rustc_span::{self, Span, DUMMY_SP};
24+
use rustc_span::{self, sym, Span, DUMMY_SP};
2225
use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt};
2326

2427
use std::cell::{Cell, RefCell};
@@ -108,6 +111,9 @@ pub struct FnCtxt<'a, 'tcx> {
108111
pub(super) inh: &'a Inherited<'tcx>,
109112

110113
pub(super) fallback_has_occurred: Cell<bool>,
114+
115+
pub(super) diverging_fallback_behavior: DivergingFallbackBehavior,
116+
pub(super) diverging_block_behavior: DivergingBlockBehavior,
111117
}
112118

113119
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
@@ -116,6 +122,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
116122
param_env: ty::ParamEnv<'tcx>,
117123
body_id: LocalDefId,
118124
) -> FnCtxt<'a, 'tcx> {
125+
let (diverging_fallback_behavior, diverging_block_behavior) =
126+
parse_never_type_options_attr(inh.tcx);
119127
FnCtxt {
120128
body_id,
121129
param_env,
@@ -131,6 +139,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
131139
}),
132140
inh,
133141
fallback_has_occurred: Cell::new(false),
142+
diverging_fallback_behavior,
143+
diverging_block_behavior,
134144
}
135145
}
136146

@@ -374,3 +384,64 @@ impl<'tcx> LoweredTy<'tcx> {
374384
LoweredTy { raw, normalized }
375385
}
376386
}
387+
388+
fn parse_never_type_options_attr(
389+
tcx: TyCtxt<'_>,
390+
) -> (DivergingFallbackBehavior, DivergingBlockBehavior) {
391+
use DivergingFallbackBehavior::*;
392+
393+
// Error handling is dubious here (unwraps), but that's probably fine for an internal attribute.
394+
// Just don't write incorrect attributes <3
395+
396+
let mut fallback = None;
397+
let mut block = None;
398+
399+
let items = tcx
400+
.get_attr(CRATE_DEF_ID, sym::rustc_never_type_options)
401+
.map(|attr| attr.meta_item_list().unwrap())
402+
.unwrap_or_default();
403+
404+
for item in items {
405+
if item.has_name(sym::fallback) && fallback.is_none() {
406+
let mode = item.value_str().unwrap();
407+
match mode {
408+
sym::unit => fallback = Some(FallbackToUnit),
409+
sym::niko => fallback = Some(FallbackToNiko),
410+
sym::never => fallback = Some(FallbackToNever),
411+
sym::no => fallback = Some(NoFallback),
412+
_ => {
413+
tcx.dcx().span_err(item.span(), format!("unknown never type fallback mode: `{mode}` (supported: `unit`, `niko`, `never` and `no`)"));
414+
}
415+
};
416+
continue;
417+
}
418+
419+
if item.has_name(sym::diverging_block_default) && fallback.is_none() {
420+
let mode = item.value_str().unwrap();
421+
match mode {
422+
sym::unit => block = Some(DivergingBlockBehavior::Unit),
423+
sym::never => block = Some(DivergingBlockBehavior::Never),
424+
_ => {
425+
tcx.dcx().span_err(item.span(), format!("unknown diverging block default: `{mode}` (supported: `unit` and `never`)"));
426+
}
427+
};
428+
continue;
429+
}
430+
431+
tcx.dcx().span_err(
432+
item.span(),
433+
format!(
434+
"unknown never type option: `{}` (supported: `fallback`)",
435+
item.name_or_empty()
436+
),
437+
);
438+
}
439+
440+
let fallback = fallback.unwrap_or_else(|| {
441+
if tcx.features().never_type_fallback { FallbackToNiko } else { FallbackToUnit }
442+
});
443+
444+
let block = block.unwrap_or_default();
445+
446+
(fallback, block)
447+
}

compiler/rustc_span/src/symbol.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,7 @@ symbols! {
690690
dispatch_from_dyn,
691691
div,
692692
div_assign,
693+
diverging_block_default,
693694
do_not_recommend,
694695
doc,
695696
doc_alias,
@@ -815,9 +816,7 @@ symbols! {
815816
fadd_algebraic,
816817
fadd_fast,
817818
fake_variadic,
818-
fallback_to_never,
819-
fallback_to_niko,
820-
fallback_to_unit,
819+
fallback,
821820
fdiv_algebraic,
822821
fdiv_fast,
823822
feature,
@@ -1228,6 +1227,7 @@ symbols! {
12281227
new_v1,
12291228
new_v1_formatted,
12301229
next,
1230+
niko,
12311231
nll,
12321232
no,
12331233
no_builtins,
@@ -1236,7 +1236,6 @@ symbols! {
12361236
no_crate_inject,
12371237
no_debug,
12381238
no_default_passes,
1239-
no_fallback,
12401239
no_implicit_prelude,
12411240
no_inline,
12421241
no_link,
@@ -1554,7 +1553,7 @@ symbols! {
15541553
rustc_mir,
15551554
rustc_must_implement_one_of,
15561555
rustc_never_returns_null_ptr,
1557-
rustc_never_type_mode,
1556+
rustc_never_type_options,
15581557
rustc_no_mir_inline,
15591558
rustc_nonnull_optimization_guaranteed,
15601559
rustc_nounwind,

0 commit comments

Comments
 (0)