[libc-commits] [libc] [libc][regex] Add ERE {m, n} interval quantifiers (PR #236569)
Jeff Bailey via libc-commits
libc-commits at lists.llvm.org
Thu Nov 12 13:01:27 PST 2026
================
@@ -281,16 +290,61 @@ ErrorOr<ExprId> ExprPool::make_byte_set(const ByteSet &bs) {
return id;
}
+namespace {
+
+// Multiplies a subexpression's repeat expansion factor by an enclosing repeat
+// bound, saturating at MAX_REPEAT_EXPANSION + 1 so nested bounds checks never
+// overflow uint16_t.
+uint16_t scale_exp(uint16_t base, uint16_t factor) {
+ if (factor <= 1)
+ return base;
+ uint32_t prod = static_cast<uint32_t>(base) * static_cast<uint32_t>(factor);
+ return static_cast<uint16_t>(
+ cpp::min<uint32_t>(prod, MAX_REPEAT_EXPANSION + 1));
+}
+
+} // namespace
+
ErrorOr<ExprId> ExprPool::make_star(ExprId body) {
if (body == INVALID_EXPR_ID)
return Error(REG_BADPAT);
// Ø* = ε and ε* = ε
if (body == EMPTY_SET_ID || body == EMPTY_STR_ID)
return empty_str();
- // (R*)* = R* (Idempotency)
- if (get(body).kind == ExprKind::Star)
+ // (R*)* = R* and (R{m,n})* = R* iff m <= 1 (since R^1 is in R{m,n} iff
+ // m <= 1, whereas (a{2,3})* excludes "a").
+ const Expr be = get(body);
+ if (be.kind == ExprKind::Star)
return body;
- return intern(Expr::make_star(body, has_anchors(body)));
+ if (be.kind == ExprKind::Repeat && be.rep.min <= 1)
+ return make_star(be.rep.body);
+ return intern(
+ Expr::make_star(body, be.has_anchors, be.has_repeat, be.rep_expansion));
+}
+
+ErrorOr<ExprId> ExprPool::make_repeat(ExprId body, uint16_t min, uint16_t max) {
+ if (body == INVALID_EXPR_ID || min > max || min == REPEAT_INF)
+ return Error(REG_BADPAT);
+ // Normalize R{0,0} = ε, ε{m,n} = ε, Ø{m,n}, R{1,1} = R, and
+ // R{0,REPEAT_INF} = R*.
+ if (max == 0 || body == EMPTY_STR_ID)
+ return empty_str();
+ if (body == EMPTY_SET_ID)
+ return (min == 0) ? empty_str() : empty_set();
+ if (min == 1 && max == 1)
+ return body;
+ if (min == 0 && max == REPEAT_INF)
+ return make_star(body);
+ const Expr be = get(body);
+ if (be.kind == ExprKind::Star)
+ return body;
+ if (be.kind == ExprKind::Repeat && be.rep.min == 1 &&
+ be.rep.max == REPEAT_INF && min == 1 && max == REPEAT_INF)
----------------
kaladron wrote:
Thanks. I can take that one step further, since be is R{1, inf} and max >= 1 is already guaranteed after the max == 0 check above, repeating R{1, inf} between min and max times matches any k >= min copies of R for any min:
* min == 0: (R{1,}){0, max} -> R* (make_repeat(be.rep.body, 0, REPEAT_INF))
* min == 1: (R{1,}){1, max} -> R{1,} (make_repeat(be.rep.body, 1, REPEAT_INF))
* min >= 2: (R{1,}){min, max} -> R{min,} (make_repeat(be.rep.body, min, REPEAT_INF))
Simplified this to return make_repeat(be.rep.body, min, REPEAT_INF); whenever be.rep.min == 1 && be.rep.max == REPEAT_INF.
https://github.com/llvm/llvm-project/pull/236569
More information about the libc-commits
mailing list