Skip to content

Commit bbb0ab3

Browse files
Add new pattern_complexity attribute to add possibility to limit and check recursion in pattern matching
1 parent 5257aee commit bbb0ab3

File tree

8 files changed

+57
-6
lines changed

8 files changed

+57
-6
lines changed

compiler/rustc_feature/src/builtin_attrs.rs

+4
Original file line numberDiff line numberDiff line change
@@ -929,6 +929,10 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
929929
omit_gdb_pretty_printer_section, Normal, template!(Word), WarnFollowing,
930930
"the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
931931
),
932+
rustc_attr!(
933+
TEST, pattern_complexity, CrateLevel, template!(NameValueStr: "N"),
934+
ErrorFollowing, @only_local: true,
935+
),
932936
];
933937

934938
pub fn deprecated_attributes() -> Vec<&'static BuiltinAttribute> {

compiler/rustc_feature/src/unstable.rs

+2
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,8 @@ declare_features! (
213213
(internal, negative_bounds, "1.71.0", None),
214214
/// Allows using `#[omit_gdb_pretty_printer_section]`.
215215
(internal, omit_gdb_pretty_printer_section, "1.5.0", None),
216+
/// Set the maximum pattern complexity allowed (not limited by default).
217+
(internal, pattern_complexity, "CURRENT_RUSTC_VERSION", None),
216218
/// Allows using `#[prelude_import]` on glob `use` items.
217219
(internal, prelude_import, "1.2.0", None),
218220
/// Used to identify crates that contain the profiler runtime.

compiler/rustc_middle/src/middle/limits.rs

+9-2
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,21 @@ pub fn get_recursion_limit(krate_attrs: &[Attribute], sess: &Session) -> Limit {
4040
}
4141

4242
fn get_limit(krate_attrs: &[Attribute], sess: &Session, name: Symbol, default: usize) -> Limit {
43+
match get_limit_size(krate_attrs, sess, name) {
44+
Some(size) => Limit::new(size),
45+
None => Limit::new(default),
46+
}
47+
}
48+
49+
pub fn get_limit_size(krate_attrs: &[Attribute], sess: &Session, name: Symbol) -> Option<usize> {
4350
for attr in krate_attrs {
4451
if !attr.has_name(name) {
4552
continue;
4653
}
4754

4855
if let Some(s) = attr.value_str() {
4956
match s.as_str().parse() {
50-
Ok(n) => return Limit::new(n),
57+
Ok(n) => return Some(n),
5158
Err(e) => {
5259
let value_span = attr
5360
.meta()
@@ -69,5 +76,5 @@ fn get_limit(krate_attrs: &[Attribute], sess: &Session, name: Symbol, default: u
6976
}
7077
}
7178
}
72-
return Limit::new(default);
79+
None
7380
}

compiler/rustc_mir_build/src/thir/pattern/check_match.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use rustc_hir as hir;
1717
use rustc_hir::def::*;
1818
use rustc_hir::def_id::LocalDefId;
1919
use rustc_hir::HirId;
20+
use rustc_middle::middle::limits::get_limit_size;
2021
use rustc_middle::thir::visit::Visitor;
2122
use rustc_middle::thir::*;
2223
use rustc_middle::ty::print::with_no_trimmed_paths;
@@ -26,7 +27,7 @@ use rustc_session::lint::builtin::{
2627
};
2728
use rustc_session::Session;
2829
use rustc_span::hygiene::DesugaringKind;
29-
use rustc_span::Span;
30+
use rustc_span::{sym, Span};
3031

3132
pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
3233
let typeck_results = tcx.typeck(def_id);
@@ -403,8 +404,11 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
403404
arms: &[MatchArm<'p, 'tcx>],
404405
scrut_ty: Ty<'tcx>,
405406
) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
407+
let pattern_complexity_limit =
408+
get_limit_size(cx.tcx.hir().krate_attrs(), cx.tcx.sess, sym::pattern_complexity);
406409
let report =
407-
rustc_pattern_analysis::analyze_match(&cx, &arms, scrut_ty).map_err(|err| {
410+
rustc_pattern_analysis::analyze_match(&cx, &arms, scrut_ty, pattern_complexity_limit)
411+
.map_err(|err| {
408412
self.error = Err(err);
409413
err
410414
})?;

compiler/rustc_pattern_analysis/src/lib.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,9 @@ pub trait TypeCx: Sized + fmt::Debug {
142142
_overlaps_with: &[&DeconstructedPat<Self>],
143143
) {
144144
}
145+
146+
/// The maximum pattern complexity limit was reached.
147+
fn complexity_exceeded(&self) -> Result<(), Self::Error>;
145148
}
146149

147150
/// The arm of a match expression.
@@ -167,10 +170,12 @@ pub fn analyze_match<'p, 'tcx>(
167170
tycx: &RustcMatchCheckCtxt<'p, 'tcx>,
168171
arms: &[rustc::MatchArm<'p, 'tcx>],
169172
scrut_ty: Ty<'tcx>,
173+
pattern_complexity_limit: Option<usize>,
170174
) -> Result<rustc::UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
171175
let scrut_ty = tycx.reveal_opaque_ty(scrut_ty);
172176
let scrut_validity = ValidityConstraint::from_bool(tycx.known_valid_scrutinee);
173-
let report = compute_match_usefulness(tycx, arms, scrut_ty, scrut_validity)?;
177+
let report =
178+
compute_match_usefulness(tycx, arms, scrut_ty, scrut_validity, pattern_complexity_limit)?;
174179

175180
// Run the non_exhaustive_omitted_patterns lint. Only run on refutable patterns to avoid hitting
176181
// `if let`s. Only run if the match is exhaustive otherwise the error is redundant.

compiler/rustc_pattern_analysis/src/rustc.rs

+5
Original file line numberDiff line numberDiff line change
@@ -895,6 +895,11 @@ impl<'p, 'tcx: 'p> TypeCx for RustcMatchCheckCtxt<'p, 'tcx> {
895895
errors::OverlappingRangeEndpoints { overlap: overlaps, range: pat_span },
896896
);
897897
}
898+
899+
fn complexity_exceeded(&self) -> Result<(), Self::Error> {
900+
let span = self.whole_match_span.unwrap_or(self.scrut_span);
901+
Err(self.tcx.dcx().span_err(span, "reached pattern complexity limit"))
902+
}
898903
}
899904

900905
/// Recursively expand this pattern into its subpatterns. Only useful for or-patterns.

compiler/rustc_pattern_analysis/src/usefulness.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -734,6 +734,22 @@ struct UsefulnessCtxt<'a, Cx: TypeCx> {
734734
/// Collect the patterns found useful during usefulness checking. This is used to lint
735735
/// unreachable (sub)patterns.
736736
useful_subpatterns: FxHashSet<PatId>,
737+
complexity_limit: Option<usize>,
738+
complexity_level: usize,
739+
}
740+
741+
impl<'a, Cx: TypeCx> UsefulnessCtxt<'a, Cx> {
742+
fn increase_complexity_level(&mut self, complexity_add: usize) -> Result<(), Cx::Error> {
743+
self.complexity_level += complexity_add;
744+
if self
745+
.complexity_limit
746+
.map(|complexity_limit| complexity_limit < self.complexity_level)
747+
.unwrap_or(false)
748+
{
749+
return self.tycx.complexity_exceeded();
750+
}
751+
Ok(())
752+
}
737753
}
738754

739755
/// Context that provides information local to a place under investigation.
@@ -1552,6 +1568,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: TypeCx>(
15521568
}
15531569

15541570
let Some(place) = matrix.head_place() else {
1571+
mcx.increase_complexity_level(matrix.rows().len())?;
15551572
// The base case: there are no columns in the matrix. We are morally pattern-matching on ().
15561573
// A row is useful iff it has no (unguarded) rows above it.
15571574
let mut useful = true; // Whether the next row is useful.
@@ -1690,8 +1707,14 @@ pub fn compute_match_usefulness<'p, Cx: TypeCx>(
16901707
arms: &[MatchArm<'p, Cx>],
16911708
scrut_ty: Cx::Ty,
16921709
scrut_validity: ValidityConstraint,
1710+
complexity_limit: Option<usize>,
16931711
) -> Result<UsefulnessReport<'p, Cx>, Cx::Error> {
1694-
let mut cx = UsefulnessCtxt { tycx, useful_subpatterns: FxHashSet::default() };
1712+
let mut cx = UsefulnessCtxt {
1713+
tycx,
1714+
useful_subpatterns: FxHashSet::default(),
1715+
complexity_limit,
1716+
complexity_level: 0,
1717+
};
16951718
let mut matrix = Matrix::new(arms, scrut_ty, scrut_validity);
16961719
let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(&mut cx, &mut matrix)?;
16971720

compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1273,6 +1273,7 @@ symbols! {
12731273
pat,
12741274
pat_param,
12751275
path,
1276+
pattern_complexity,
12761277
pattern_parentheses,
12771278
phantom_data,
12781279
pic,

0 commit comments

Comments
 (0)