[libc-commits] [libc] 0dcfa3d - [libc][regex] Make derivative iterative (#246333)
via libc-commits
libc-commits at lists.llvm.org
Thu Nov 26 07:49:03 PST 2026
Author: Jeff Bailey
Date: 2026-11-26T15:48:58Z
New Revision: 0dcfa3defd62a85dadecd978f8abd1e9247052a9
URL: https://github.com/llvm/llvm-project/commit/0dcfa3defd62a85dadecd978f8abd1e9247052a9
DIFF: https://github.com/llvm/llvm-project/commit/0dcfa3defd62a85dadecd978f8abd1e9247052a9.diff
LOG: [libc][regex] Make derivative iterative (#246333)
derivative() recursed once per nested node, so a deep expression could
overflow the call stack. Commits d159e4f06b81 and 4c0d3e841c0c removed
the same recursion from ExprPool.
Walk the expression with an explicit stack instead:
* DerivFrame: one pending parent node
* DerivStack: 8 frames inline, then a doubling heap array that match()
reuses across bytes
* derivative_impl: makes the same ExprPool calls in the same order as
the recursive code
derivative() can now also return REG_ESPACE when the stack cannot grow.
Optimised x86-64 frames in regex_matcher.cpp stay at or under 232 bytes.
Also move ExprBuilder into a shared test header.
Compliance: Henry Spencer spencer_tests.txt 268/456 Bool/Err (+0) and
84/456 Full Pos (+0); AT&T testregex 399/400 ERE Bool/Err (+0), 401/473
All Bool/Err (+0), and 18/465 Full Pos (+0); zero regressions.
Assisted-by: Automated tooling, human reviewed.
Added:
libc/test/src/__support/regex/expr_builder.h
libc/test/src/__support/regex/matcher_limits_test.cpp
Modified:
libc/src/__support/regex/CMakeLists.txt
libc/src/__support/regex/regex_matcher.cpp
libc/test/src/__support/regex/CMakeLists.txt
libc/test/src/__support/regex/expr_test.cpp
Removed:
################################################################################
diff --git a/libc/src/__support/regex/CMakeLists.txt b/libc/src/__support/regex/CMakeLists.txt
index 2c88d9b159dc36..71a5c46050e291 100644
--- a/libc/src/__support/regex/CMakeLists.txt
+++ b/libc/src/__support/regex/CMakeLists.txt
@@ -46,10 +46,18 @@ add_object_library(
.regex_expr_pool
.regex_internal
libc.hdr.regex_macros
+ libc.hdr.stdint_proxy
+ libc.hdr.types.size_t
+ libc.src.__support.checked_ptr
+ libc.src.__support.CPP.algorithm
+ libc.src.__support.CPP.new
libc.src.__support.CPP.string_view
+ libc.src.__support.CPP.type_traits
+ libc.src.__support.CPP.unique_ptr
libc.src.__support.error_or
libc.src.__support.libc_assert
libc.src.__support.macros.attributes
+ libc.src.__support.macros.optimization
)
add_object_library(
diff --git a/libc/src/__support/regex/regex_matcher.cpp b/libc/src/__support/regex/regex_matcher.cpp
index a4025ed2e427fc..3bfc1e5bdf4291 100644
--- a/libc/src/__support/regex/regex_matcher.cpp
+++ b/libc/src/__support/regex/regex_matcher.cpp
@@ -15,10 +15,17 @@
#include "src/__support/regex/regex_matcher.h"
#include "hdr/regex_macros.h"
+#include "hdr/stdint_proxy.h"
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/algorithm.h"
#include "src/__support/CPP/string_view.h"
+#include "src/__support/CPP/type_traits.h"
+#include "src/__support/CPP/unique_ptr.h"
+#include "src/__support/checked_ptr.h"
#include "src/__support/error_or.h"
#include "src/__support/libc_assert.h"
#include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h"
#include "src/__support/regex/regex_ast.h"
#include "src/__support/regex/regex_expr_pool.h"
@@ -40,79 +47,244 @@ uint8_t ctx_at(cpp::string_view input, size_t pos, int cflags, int eflags) {
return ctx;
}
-} // namespace
+// One parent node whose derivative is still being computed.
+// d_left is INVALID_EXPR_ID while the node's first child (left or body) is
+// being walked. When a Concat or Alt finishes its left child and must walk its
+// right child next, d_left saves the left-hand term until the right child's
+// result arrives and the two are joined with make_alt.
+// The default constructor is trivial so make_unique_for_overwrite does not zero
+// the heap array.
+struct DerivFrame {
+ ExprId id;
+ ExprId d_left;
-ErrorOr<ExprId> derivative(ExprId id, char c, ExprPool &pool,
- uint8_t ctx_before) {
- if (!pool.is_valid_input(id))
- return Error(REG_BADPAT);
- const Expr e = pool.get(id);
- switch (e.kind) {
- case ExprKind::EmptySet:
- case ExprKind::EmptyStr:
- case ExprKind::Anchor:
- return EMPTY_SET_ID;
- case ExprKind::Literal:
- return (c == e.ch) ? EMPTY_STR_ID : EMPTY_SET_ID;
- case ExprKind::ByteSet:
- return pool.get_byte_set(e.byte_set_id).test(static_cast<uint8_t>(c))
- ? EMPTY_STR_ID
- : EMPTY_SET_ID;
- case ExprKind::Concat: {
- // Product Rule:
- // D_c(L . R) = (D_c(L) . R) | (nullable(L, ctx_before) ? D_c(R) : EmptySet)
- const bool left_nullable = nullable(e.bin.left, ctx_before, pool);
- ErrorOr<ExprId> d_l = derivative(e.bin.left, c, pool, ctx_before);
- if (!d_l.has_value())
- return d_l;
- ErrorOr<ExprId> lhs = pool.make_concat(*d_l, e.bin.right);
- if (!lhs.has_value() || !left_nullable)
- return lhs;
- ErrorOr<ExprId> d_r = derivative(e.bin.right, c, pool, ctx_before);
- if (!d_r.has_value())
- return d_r;
- return pool.make_alt(*lhs, *d_r);
+ DerivFrame() = default;
+ constexpr explicit DerivFrame(ExprId expr_id)
+ : id(expr_id), d_left(INVALID_EXPR_ID) {
+ LIBC_ASSERT(expr_id != INVALID_EXPR_ID);
}
- case ExprKind::Alt: {
- // Sum Rule: D_c(L | R) = D_c(L) | D_c(R)
- ErrorOr<ExprId> d_l = derivative(e.bin.left, c, pool, ctx_before);
- if (!d_l.has_value())
- return d_l;
- ErrorOr<ExprId> d_r = derivative(e.bin.right, c, pool, ctx_before);
- if (!d_r.has_value())
- return d_r;
- return pool.make_alt(*d_l, *d_r);
+};
+static_assert(sizeof(DerivFrame) == 8);
+static_assert(cpp::is_trivially_constructible<DerivFrame>::value);
+
+// Stack of DerivFrames for derivative_impl(). The first INLINE_CAP frames live
+// inside the object; deeper walks move to a heap array that doubles in size.
+// BlockStore is not used because its pop_back() frees a block each time depth
+// drops back across a block boundary, and a tree walk crosses that boundary
+// repeatedly. match() uses one DerivStack for every input byte, so a heap
+// array allocated for one byte is reused for the rest.
+class DerivStack {
+ // 8 frames (64 bytes) keep match()'s own stack frame under 256 bytes.
+ static constexpr size_t INLINE_CAP = 8;
+ static constexpr size_t GROWTH_FACTOR = 2;
+ static_assert(ExprPool::MAX_NODE_LIMIT <= (~size_t(0)) / GROWTH_FACTOR);
+
+ DerivFrame inline_buf[INLINE_CAP];
+ cpp::unique_ptr<DerivFrame[]> heap;
+ size_t len = 0;
+ size_t cap = INLINE_CAP;
+
+ DerivFrame *data() { return heap ? heap.get() : inline_buf; }
+
+ // Moves the frames to a heap array twice the size. Because every pushed
+ // frame has a smaller ExprId than its parent, the stack never needs more than
+ // ExprPool::MAX_NODE_LIMIT frames.
+ [[nodiscard]] bool grow() {
+ LIBC_ASSERT(len == cap && cap < ExprPool::MAX_NODE_LIMIT);
+ const size_t new_cap =
+ cpp::min(cap * GROWTH_FACTOR, ExprPool::MAX_NODE_LIMIT);
+ auto next = make_unique_for_overwrite<DerivFrame[]>(new_cap);
+ if (!next)
+ return false;
+ const DerivFrame *src = data();
+ for (size_t i = 0; i < len; ++i)
+ next[i] = src[i];
+ heap = next.take_unique();
+ cap = new_cap;
+ return true;
}
- case ExprKind::Star: {
- // Kleene Rule: D_c(R*) = D_c(R) . R*
- ErrorOr<ExprId> d_body = derivative(e.body, c, pool, ctx_before);
- if (!d_body.has_value())
- return d_body;
- return pool.make_concat(*d_body, id);
+
+public:
+ DerivStack() = default;
+ // The implicit move operations would move heap while copying len and cap,
+ // leaving the source stack in an inconsistent state.
+ DerivStack(DerivStack &&) = delete;
+ DerivStack &operator=(DerivStack &&) = delete;
+
+ bool empty() const { return len == 0; }
+ void clear() { len = 0; }
+
+ DerivFrame &top() {
+ LIBC_ASSERT(len > 0);
+ return data()[len - 1];
}
- case ExprKind::Repeat: {
- // Bounded Repetition Rule:
- // D_c(R{m,n}) = D_c(R) . R{nullable(R, ctx_before) ? 0 : max(0,m-1), n-1}.
- // When R is nullable at ctx_before (e.g. via '^'), up to m - 1 leading
- // copies may match empty at ctx_before before the copy that consumes c.
- ErrorOr<ExprId> d_body = derivative(e.rep.body, c, pool, ctx_before);
- if (!d_body.has_value() || *d_body == EMPTY_SET_ID)
- return d_body;
- uint16_t next_min =
- (e.rep.min > 1 && !nullable(e.rep.body, ctx_before, pool))
- ? static_cast<uint16_t>(e.rep.min - 1)
- : static_cast<uint16_t>(0);
- uint16_t next_max = (e.rep.max == REPEAT_INF)
- ? REPEAT_INF
- : static_cast<uint16_t>(e.rep.max - 1);
- ErrorOr<ExprId> tail = pool.make_repeat(e.rep.body, next_min, next_max);
- if (!tail.has_value())
- return tail;
- return pool.make_concat(*d_body, *tail);
+
+ void pop() {
+ LIBC_ASSERT(len > 0);
+ --len;
}
+
+ [[nodiscard]] bool push(DerivFrame frame) {
+ if (LIBC_UNLIKELY(len == cap) && !grow())
+ return false;
+ LIBC_ASSERT(len < cap);
+ data()[len] = frame;
+ ++len;
+ return true;
}
- LIBC_ASSERT(false);
- __builtin_unreachable();
+};
+
+// Computes D_c(root) iteratively in post-order. stack is passed in so callers
+// looping over input bytes can reuse one heap buffer across steps instead of
+// reallocating on every byte.
+ErrorOr<ExprId> derivative_impl(ExprId root, char c, ExprPool &pool,
+ uint8_t ctx_before, DerivStack &stack) {
+ if (!pool.is_valid_input(root))
+ return Error(REG_BADPAT);
+
+ // Reset len without freeing stack's heap buffer, discarding any frames left
+ // by an earlier failed call.
+ stack.clear();
+ ExprId cur = root;
+ ExprId res = INVALID_EXPR_ID;
+ do {
+ // Walk down first children until we reach a leaf.
+ while (res == INVALID_EXPR_ID) {
+ const Expr e = pool.get(cur);
+ ExprId next_child = INVALID_EXPR_ID;
+ // ExprPool interns children before their parent, so ids shrink on the way
+ // down: the walk always reaches a leaf, and the stack never holds more
+ // frames than the pool has nodes.
+ switch (e.kind) {
+ case ExprKind::EmptySet:
+ case ExprKind::EmptyStr:
+ case ExprKind::Anchor:
+ res = EMPTY_SET_ID;
+ break;
+ case ExprKind::Literal:
+ res = (c == e.ch) ? EMPTY_STR_ID : EMPTY_SET_ID;
+ break;
+ case ExprKind::ByteSet:
+ res = pool.get_byte_set(e.byte_set_id).test(static_cast<uint8_t>(c))
+ ? EMPTY_STR_ID
+ : EMPTY_SET_ID;
+ break;
+ case ExprKind::Concat:
+ case ExprKind::Alt:
+ LIBC_ASSERT(e.bin.left < cur && e.bin.right < cur);
+ next_child = e.bin.left;
+ break;
+ case ExprKind::Star:
+ LIBC_ASSERT(e.body < cur);
+ next_child = e.body;
+ break;
+ case ExprKind::Repeat:
+ LIBC_ASSERT(e.rep.body < cur);
+ next_child = e.rep.body;
+ break;
+ }
+ if (next_child != INVALID_EXPR_ID) {
+ if (!stack.push(DerivFrame(cur)))
+ return Error(REG_ESPACE);
+ cur = next_child;
+ }
+ }
+
+ // Combine child results back up the stack until a parent needs its right
+ // child walked (res is reset to INVALID_EXPR_ID) or the stack empties.
+ while (!stack.empty() && res != INVALID_EXPR_ID) {
+ DerivFrame &frame = stack.top();
+ if (frame.d_left != INVALID_EXPR_ID) {
+ // Both children of a binary Concat or Alt finished; union their terms.
+ LIBC_ASSERT(pool.get(frame.id).kind == ExprKind::Concat ||
+ pool.get(frame.id).kind == ExprKind::Alt);
+ ErrorOr<ExprId> combined = pool.make_alt(frame.d_left, res);
+ if (!combined.has_value())
+ return combined;
+ res = *combined;
+ } else {
+ // First child finished; either combine now or save the left term and
+ // walk the right child.
+ const Expr pe = pool.get(frame.id);
+ switch (pe.kind) {
+ case ExprKind::Concat: {
+ // Product Rule:
+ // D_c(L . R) = (D_c(L) . R) | (nullable(L, ctx_before) ? D_c(R) : Ø)
+ ErrorOr<ExprId> lhs = pool.make_concat(res, pe.bin.right);
+ if (!lhs.has_value())
+ return lhs;
+ if (nullable(pe.bin.left, ctx_before, pool)) {
+ LIBC_ASSERT(*lhs != INVALID_EXPR_ID);
+ frame.d_left = *lhs;
+ cur = pe.bin.right;
+ res = INVALID_EXPR_ID;
+ continue;
+ }
+ res = *lhs;
+ break;
+ }
+ case ExprKind::Alt:
+ // Sum Rule: D_c(L | R) = D_c(L) | D_c(R)
+ frame.d_left = res;
+ cur = pe.bin.right;
+ res = INVALID_EXPR_ID;
+ continue;
+ case ExprKind::Star: {
+ // Kleene Rule: D_c(R*) = D_c(R) . R*
+ ErrorOr<ExprId> combined = pool.make_concat(res, frame.id);
+ if (!combined.has_value())
+ return combined;
+ res = *combined;
+ break;
+ }
+ case ExprKind::Repeat: {
+ // Bounded Repetition Rule:
+ // D_c(R{m,n}) = D_c(R) . R{nullable(R, ctx_before) ? 0 : max(0,m-1),
+ // n-1}.
+ // When R is nullable at ctx_before (e.g. via '^'), up to m - 1
+ // leading copies may match empty before the copy consuming c.
+ LIBC_ASSERT(pe.rep.max >= 1 && pe.rep.min <= pe.rep.max);
+ if (res != EMPTY_SET_ID) {
+ uint16_t next_min =
+ (pe.rep.min > 1 && !nullable(pe.rep.body, ctx_before, pool))
+ ? static_cast<uint16_t>(pe.rep.min - 1)
+ : static_cast<uint16_t>(0);
+ uint16_t next_max = (pe.rep.max == REPEAT_INF)
+ ? REPEAT_INF
+ : static_cast<uint16_t>(pe.rep.max - 1);
+ ErrorOr<ExprId> tail =
+ pool.make_repeat(pe.rep.body, next_min, next_max);
+ if (!tail.has_value())
+ return tail;
+ ErrorOr<ExprId> combined = pool.make_concat(res, *tail);
+ if (!combined.has_value())
+ return combined;
+ res = *combined;
+ }
+ break;
+ }
+ case ExprKind::EmptySet:
+ case ExprKind::EmptyStr:
+ case ExprKind::Literal:
+ case ExprKind::Anchor:
+ case ExprKind::ByteSet:
+ LIBC_ASSERT(false);
+ __builtin_unreachable();
+ }
+ }
+ stack.pop();
+ }
+ } while (res == INVALID_EXPR_ID);
+ LIBC_ASSERT(stack.empty() && res != INVALID_EXPR_ID);
+ return res;
+}
+
+} // namespace
+
+ErrorOr<ExprId> derivative(ExprId id, char c, ExprPool &pool,
+ uint8_t ctx_before) {
+ DerivStack stack;
+ return derivative_impl(id, c, pool, ctx_before, stack);
}
MatchResult match(ExprPool &pool, const ExprId pattern, cpp::string_view input,
@@ -124,20 +296,27 @@ MatchResult match(ExprPool &pool, const ExprId pattern, cpp::string_view input,
return MatchResult::Match;
// Unanchored substring search: at each byte, step active partial matches via
- // derivative(state, c, pool, ctx) and union with pattern so a new match can
- // begin at the next fencepost (equivalent to matching .* . pattern without
- // constructing a prefix wildcard node).
+ // derivative_impl() and union with pattern so a new match can begin at the
+ // next fencepost (equivalent to matching .* . pattern without constructing a
+ // prefix wildcard node).
+ // One stack serves every byte, so a heap array allocated for one byte is
+ // reused for the rest.
+ DerivStack stack;
ExprId state = pattern;
for (size_t pos = 0; pos < input.size(); ++pos) {
- ErrorOr<ExprId> d = derivative(state, input[pos], pool, ctx);
- if (!d.has_value())
+ ErrorOr<ExprId> d = derivative_impl(state, input[pos], pool, ctx, stack);
+ if (!d.has_value()) {
+ LIBC_ASSERT(d.error() == REG_ESPACE);
return MatchResult::OutOfMemory;
+ }
ctx = ctx_at(input, pos + 1, cflags, eflags);
if (nullable(*d, ctx, pool) || nullable(pattern, ctx, pool))
return MatchResult::Match;
ErrorOr<ExprId> next = pool.make_alt(pattern, *d);
- if (!next.has_value())
+ if (!next.has_value()) {
+ LIBC_ASSERT(next.error() == REG_ESPACE);
return MatchResult::OutOfMemory;
+ }
state = *next;
}
diff --git a/libc/test/src/__support/regex/CMakeLists.txt b/libc/test/src/__support/regex/CMakeLists.txt
index a57bd321504b02..baea3054db2ef6 100644
--- a/libc/test/src/__support/regex/CMakeLists.txt
+++ b/libc/test/src/__support/regex/CMakeLists.txt
@@ -6,18 +6,23 @@ add_libc_test(
LIBOMPTARGET_STACK_SIZE=8192
SUITE
libc-support-tests
+ HDRS
+ expr_builder.h
SRCS
expr_test.cpp
DEPENDS
libc.hdr.regex_macros
+ libc.hdr.stdint_proxy
+ libc.hdr.types.size_t
libc.src.__support.error_or
+ libc.src.__support.macros.config
libc.src.__support.regex.regex_expr_pool
)
add_libc_test(
matcher_test
# The long grouped-repeat and RFC grammar cases need more than the default
- # 3 KiB device stack for recursive parsing and derivative evaluation.
+ # 3 KiB device stack for recursive parsing.
ENV
LIBOMPTARGET_STACK_SIZE=65536
SUITE
@@ -33,3 +38,22 @@ add_libc_test(
libc.src.__support.regex.regex_matcher
libc.src.__support.regex.regex_parser
)
+
+add_libc_test(
+ matcher_limits_test
+ SUITE
+ libc-support-tests
+ HDRS
+ expr_builder.h
+ SRCS
+ matcher_limits_test.cpp
+ DEPENDS
+ libc.hdr.regex_macros
+ libc.hdr.stdint_proxy
+ libc.hdr.types.size_t
+ libc.src.__support.error_or
+ libc.src.__support.macros.config
+ libc.src.__support.regex.regex_expr_pool
+ libc.src.__support.regex.regex_matcher
+ libc.src.__support.regex.regex_parser
+)
diff --git a/libc/test/src/__support/regex/expr_builder.h b/libc/test/src/__support/regex/expr_builder.h
new file mode 100644
index 00000000000000..e2cd432461c803
--- /dev/null
+++ b/libc/test/src/__support/regex/expr_builder.h
@@ -0,0 +1,128 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Compositional ExprPool builder shared across regex unit tests.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_TEST_SRC___SUPPORT_REGEX_EXPR_BUILDER_H
+#define LLVM_LIBC_TEST_SRC___SUPPORT_REGEX_EXPR_BUILDER_H
+
+#include "hdr/stdint_proxy.h"
+#include "hdr/types/size_t.h"
+#include "src/__support/error_or.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/regex/regex_ast.h"
+#include "src/__support/regex/regex_expr_pool.h"
+#include "test/UnitTest/Test.h"
+
+namespace LIBC_NAMESPACE_DECL {
+namespace testing {
+
+// Compositional wrapper around ExprPool that unwraps ErrorOr<ExprId> so regex
+// AST and matcher tests read directly as algebra instead of error boilerplate.
+class ExprBuilder {
+ regex::ExprPool pool;
+
+public:
+ static regex::ExprId unwrap(ErrorOr<regex::ExprId> res) {
+ EXPECT_TRUE(res.has_value());
+ return res.has_value() ? *res : regex::INVALID_EXPR_ID;
+ }
+
+ regex::ExprPool &raw() { return pool; }
+ regex::Expr get(regex::ExprId id) const { return pool.get(id); }
+
+ regex::ExprId lit(char c) { return unwrap(pool.make_lit(c)); }
+ regex::ExprId star(regex::ExprId body) {
+ return unwrap(pool.make_star(body));
+ }
+ regex::ExprId star(char c) { return star(lit(c)); }
+ regex::ExprId rep(regex::ExprId body, uint16_t min, uint16_t max) {
+ return unwrap(pool.make_repeat(body, min, max));
+ }
+ regex::ExprId rep(char c, uint16_t min, uint16_t max) {
+ return rep(lit(c), min, max);
+ }
+ regex::ExprId cat(regex::ExprId l, regex::ExprId r) {
+ return unwrap(pool.make_concat(l, r));
+ }
+ regex::ExprId alt(regex::ExprId l, regex::ExprId r) {
+ return unwrap(pool.make_alt(l, r));
+ }
+
+ template <typename... Rest>
+ regex::ExprId alt(regex::ExprId first, regex::ExprId second, Rest... rest) {
+ return alt(alt(first, second), rest...);
+ }
+
+ // Returns the idx-th distinct two-character literal pair ("a!", "a\"", ...)
+ // for building wide Alt spines without Repeat nodes.
+ regex::ExprId distinct_branch(size_t idx) {
+ return cat(lit(static_cast<char>('a' + (idx / 60))),
+ lit(static_cast<char>('!' + (idx % 60))));
+ }
+
+ // Walks a right-associated Alt spine, verifies right-associativity and
+ // strictly ascending ExprId order, and returns the total branch count.
+ size_t verify_alt_spine(regex::ExprId spine) const {
+ if (spine == regex::INVALID_EXPR_ID)
+ return 0;
+ size_t count = 0;
+ regex::ExprId prev = regex::INVALID_EXPR_ID;
+ regex::ExprId walk = spine;
+ while (walk != regex::EMPTY_SET_ID) {
+ const regex::Expr we = pool.get(walk);
+ const bool is_alt = (we.kind == regex::ExprKind::Alt);
+ const regex::ExprId head = is_alt ? we.bin.left : walk;
+ EXPECT_NE(pool.get(head).kind, regex::ExprKind::Alt);
+ if (prev != regex::INVALID_EXPR_ID)
+ EXPECT_LT(prev, head);
+ prev = head;
+ ++count;
+ walk = is_alt ? we.bin.right : regex::EMPTY_SET_ID;
+ }
+ return count;
+ }
+
+ // Counts occurrences of `target` as a top-level branch of an Alt spine.
+ size_t count_branch(regex::ExprId spine, regex::ExprId target) const {
+ if (spine == regex::INVALID_EXPR_ID)
+ return 0;
+ size_t hits = 0;
+ regex::ExprId walk = spine;
+ while (walk != regex::EMPTY_SET_ID) {
+ const regex::Expr we = pool.get(walk);
+ const bool is_alt = (we.kind == regex::ExprKind::Alt);
+ if ((is_alt ? we.bin.left : walk) == target)
+ ++hits;
+ walk = is_alt ? we.bin.right : regex::EMPTY_SET_ID;
+ }
+ return hits;
+ }
+
+ // Builds a right-associated literal chain cycling `pattern` (`count`
+ // literals) followed by `tail`. A 3-character cycle ("abc") is asymmetric
+ // at both DEPTH and DEPTH - 1, so reversing rebuild order fails immediately.
+ template <size_t N>
+ regex::ExprId cycle_literals(const char (&pattern)[N], size_t count,
+ regex::ExprId tail = regex::EMPTY_STR_ID) {
+ static_assert(N > 1, "pattern must contain at least one character");
+ constexpr size_t PERIOD = N - 1;
+ regex::ExprId acc = tail;
+ for (size_t i = count; i > 0 && acc != regex::INVALID_EXPR_ID; --i)
+ acc = cat(lit(pattern[(i - 1) % PERIOD]), acc);
+ return acc;
+ }
+};
+
+} // namespace testing
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_TEST_SRC___SUPPORT_REGEX_EXPR_BUILDER_H
diff --git a/libc/test/src/__support/regex/expr_test.cpp b/libc/test/src/__support/regex/expr_test.cpp
index c686fb378180e6..164138a8865c00 100644
--- a/libc/test/src/__support/regex/expr_test.cpp
+++ b/libc/test/src/__support/regex/expr_test.cpp
@@ -15,6 +15,7 @@
#include "src/__support/regex/regex_ast.h"
#include "src/__support/regex/regex_expr_pool.h"
#include "test/UnitTest/Test.h"
+#include "test/src/__support/regex/expr_builder.h"
using LIBC_NAMESPACE::regex::ANCHOR_BOL;
using LIBC_NAMESPACE::regex::ANCHOR_EOL;
@@ -27,6 +28,7 @@ using LIBC_NAMESPACE::regex::ExprKind;
using LIBC_NAMESPACE::regex::ExprPool;
using LIBC_NAMESPACE::regex::INVALID_EXPR_ID;
using LIBC_NAMESPACE::regex::REPEAT_INF;
+using LIBC_NAMESPACE::testing::ExprBuilder;
TEST(LlvmLibcRegexExprTest, Interning) {
ExprPool pool;
@@ -457,101 +459,6 @@ TEST(LlvmLibcRegexExprTest, BoundsGuardsAndNullableMask) {
EXPECT_EQ(pool.get(*rep_bol_or_a).nullable_mask, uint8_t(0b1010));
}
-namespace {
-
-// Compositional wrapper around ExprPool that unwraps ErrorOr<ExprId> so spine
-// tests read directly as regex algebra instead of boilerplate assertions.
-class ExprBuilder {
- ExprPool pool;
-
- ExprId unwrap(LIBC_NAMESPACE::ErrorOr<ExprId> res) {
- EXPECT_TRUE(res.has_value());
- return res.has_value() ? *res : INVALID_EXPR_ID;
- }
-
-public:
- ExprPool &raw() { return pool; }
- Expr get(ExprId id) const { return pool.get(id); }
-
- ExprId lit(char c) { return unwrap(pool.make_lit(c)); }
- ExprId star(ExprId body) { return unwrap(pool.make_star(body)); }
- ExprId star(char c) { return star(lit(c)); }
- ExprId rep(ExprId body, uint16_t min, uint16_t max) {
- return unwrap(pool.make_repeat(body, min, max));
- }
- ExprId rep(char c, uint16_t min, uint16_t max) {
- return rep(lit(c), min, max);
- }
- ExprId cat(ExprId l, ExprId r) { return unwrap(pool.make_concat(l, r)); }
- ExprId alt(ExprId l, ExprId r) { return unwrap(pool.make_alt(l, r)); }
-
- template <typename... Rest>
- ExprId alt(ExprId first, ExprId second, Rest... rest) {
- return alt(alt(first, second), rest...);
- }
-
- // Returns the idx-th distinct two-character literal pair ("a!", "a\"", ...)
- // for building wide Alt spines without Repeat nodes.
- ExprId distinct_branch(size_t idx) {
- return cat(lit(static_cast<char>('a' + (idx / 60))),
- lit(static_cast<char>('!' + (idx % 60))));
- }
-
- // Walks a right-associated Alt spine, verifies right-associativity and
- // strictly ascending ExprId order, and returns the total branch count.
- size_t verify_alt_spine(ExprId spine) const {
- if (spine == INVALID_EXPR_ID)
- return 0;
- size_t count = 0;
- ExprId prev = INVALID_EXPR_ID;
- ExprId walk = spine;
- while (walk != EMPTY_SET_ID) {
- const Expr we = pool.get(walk);
- const bool is_alt = (we.kind == ExprKind::Alt);
- const ExprId head = is_alt ? we.bin.left : walk;
- EXPECT_NE(pool.get(head).kind, ExprKind::Alt);
- if (prev != INVALID_EXPR_ID)
- EXPECT_LT(prev, head);
- prev = head;
- ++count;
- walk = is_alt ? we.bin.right : EMPTY_SET_ID;
- }
- return count;
- }
-
- // Counts occurrences of `target` as a top-level branch of an Alt spine.
- size_t count_branch(ExprId spine, ExprId target) const {
- if (spine == INVALID_EXPR_ID)
- return 0;
- size_t hits = 0;
- ExprId walk = spine;
- while (walk != EMPTY_SET_ID) {
- const Expr we = pool.get(walk);
- const bool is_alt = (we.kind == ExprKind::Alt);
- if ((is_alt ? we.bin.left : walk) == target)
- ++hits;
- walk = is_alt ? we.bin.right : EMPTY_SET_ID;
- }
- return hits;
- }
-
- // Builds a right-associated literal chain cycling `pattern` (`count`
- // literals) followed by `tail`. A 3-character cycle ("abc") is asymmetric
- // at both DEPTH and DEPTH - 1, so reversing rebuild order fails immediately.
- template <size_t N>
- ExprId cycle_literals(const char (&pattern)[N], size_t count,
- ExprId tail = EMPTY_STR_ID) {
- static_assert(N > 1, "pattern must contain at least one character");
- constexpr size_t PERIOD = N - 1;
- ExprId acc = tail;
- for (size_t i = count; i > 0 && acc != INVALID_EXPR_ID; --i)
- acc = cat(lit(pattern[(i - 1) % PERIOD]), acc);
- return acc;
- }
-};
-
-} // namespace
-
TEST(LlvmLibcRegexExprTest, DeepConcatFlatteningAndPrefixCoalesce) {
ExprBuilder b;
const ExprId lit_d = b.lit('d');
diff --git a/libc/test/src/__support/regex/matcher_limits_test.cpp b/libc/test/src/__support/regex/matcher_limits_test.cpp
new file mode 100644
index 00000000000000..829944a23970bd
--- /dev/null
+++ b/libc/test/src/__support/regex/matcher_limits_test.cpp
@@ -0,0 +1,124 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Deep-chain tests for iterative derivative evaluation.
+///
+/// These tests build expression chains thousands of nodes deep. They live in
+/// their own binary because the hermetic test heap is a fixed 1 MiB that is
+/// never freed, and matcher_test already uses most of it.
+///
+//===----------------------------------------------------------------------===//
+
+#include "hdr/regex_macros.h"
+#include "hdr/types/size_t.h"
+#include "src/__support/regex/regex_ast.h"
+#include "src/__support/regex/regex_matcher.h"
+#include "src/__support/regex/regex_parser.h"
+#include "test/UnitTest/Test.h"
+#include "test/src/__support/regex/expr_builder.h"
+
+using LIBC_NAMESPACE::regex::derivative;
+using LIBC_NAMESPACE::regex::EMPTY_SET_ID;
+using LIBC_NAMESPACE::regex::EMPTY_STR_ID;
+using LIBC_NAMESPACE::regex::ExprId;
+using LIBC_NAMESPACE::regex::match;
+using LIBC_NAMESPACE::regex::MatchResult;
+using LIBC_NAMESPACE::regex::parse_ere;
+using LIBC_NAMESPACE::regex::REPEAT_INF;
+using LIBC_NAMESPACE::testing::ExprBuilder;
+
+namespace {
+
+// Builds the right-associated chain (a?)(a?)...(a?)b with `count` optional a's.
+ExprId build_nullable_a_chain(ExprBuilder &b, size_t count) {
+ const ExprId opt_a = b.alt(EMPTY_STR_ID, b.lit('a'));
+ ExprId chain = b.lit('b');
+ for (size_t i = 0; i < count; ++i)
+ chain = b.cat(opt_a, chain);
+ return chain;
+}
+
+ExprId deriv(ExprBuilder &b, ExprId id, char ch) {
+ return ExprBuilder::unwrap(derivative(id, ch, b.raw()));
+}
+
+} // namespace
+
+TEST(LlvmLibcRegexMatcherLimitsTest, DeepNullableConcatChain) {
+ // A chain of 2,000 optional 'a's followed by 'b'. Walking it needs about
+ // 2,000 stack frames, far more than DerivStack keeps inline, so the stack
+ // moves to the heap and grows several times.
+ ExprBuilder b;
+ const ExprId chain = build_nullable_a_chain(b, 2000);
+ EXPECT_EQ(deriv(b, chain, 'b'), EMPTY_STR_ID);
+ EXPECT_EQ(deriv(b, chain, 'x'), EMPTY_SET_ID);
+ EXPECT_EQ(match(b.raw(), chain, "b"), MatchResult::Match);
+ EXPECT_EQ(match(b.raw(), chain, "xxxx"), MatchResult::NoMatch);
+}
+
+TEST(LlvmLibcRegexMatcherLimitsTest, MultiByteChainReuseAndAltDerivative) {
+ // A 24-element chain matched over several bytes. The stack outgrows its
+ // inline buffer on the first byte and match() keeps using it for the rest.
+ // D_a produces a non-trivial 24-branch alternation across the grown stack.
+ ExprBuilder b;
+ const ExprId chain = build_nullable_a_chain(b, 24);
+ EXPECT_EQ(b.verify_alt_spine(deriv(b, chain, 'a')), size_t(24));
+ EXPECT_EQ(match(b.raw(), chain, "b"), MatchResult::Match);
+ EXPECT_EQ(match(b.raw(), chain, "aaab"), MatchResult::Match);
+ EXPECT_EQ(match(b.raw(), chain, "xxxx"), MatchResult::NoMatch);
+}
+
+TEST(LlvmLibcRegexMatcherLimitsTest, DeepAltSpine) {
+ // 64 two-letter branches: 0..59 start with 'a', 60..63 with 'b'. The walk
+ // goes down the right side of every Alt with that Alt's left result saved.
+ ExprBuilder b;
+ ExprId spine = EMPTY_SET_ID;
+ for (size_t i = 0; i < 64; ++i)
+ spine = b.alt(spine, b.distinct_branch(i));
+ EXPECT_EQ(b.verify_alt_spine(deriv(b, spine, 'a')), size_t(60));
+ EXPECT_EQ(b.verify_alt_spine(deriv(b, spine, 'b')), size_t(4));
+ EXPECT_EQ(deriv(b, spine, 'x'), EMPTY_SET_ID);
+}
+
+TEST(LlvmLibcRegexMatcherLimitsTest, AsymmetricNestedStackOrder) {
+ // 10 nested (expr{1,2} . ch) wrappers around 'a' (depth 20 down the left
+ // spine, growing DerivStack twice) with distinct suffixes 'b'..'k'.
+ // Reversing or scrambling copied frames on stack growth produces the wrong
+ // suffix order and fails the match checks.
+ ExprBuilder b;
+ ExprId expr = b.lit('a');
+ for (size_t i = 0; i < 10; ++i)
+ expr = b.cat(b.rep(expr, 1, 2), b.lit(static_cast<char>('b' + i)));
+ EXPECT_EQ(match(b.raw(), expr, "abcdefghijk"), MatchResult::Match);
+ EXPECT_EQ(match(b.raw(), expr, "akjihgfedcb"), MatchResult::NoMatch);
+ EXPECT_EQ(match(b.raw(), expr, "abcdefghij"), MatchResult::NoMatch);
+}
+
+TEST(LlvmLibcRegexMatcherLimitsTest, RepeatDerivativeBoundaryRules) {
+ ExprBuilder b;
+
+ // Unbounded repeat preserves REPEAT_INF across
diff erentiation:
+ // D_a(a{3,inf}) == a{2,inf}.
+ EXPECT_EQ(deriv(b, b.rep('a', 3, REPEAT_INF), 'a'),
+ b.rep('a', 2, REPEAT_INF));
+
+ // Conditionally nullable repeat body with a non-nullable suffix: at byte 0
+ // ('^' matches), (^|a) is nullable so leading copies can match empty and
+ // D_a((^|a){2,3}) drops min to 0, letting "ab" match. Without '^'
+ // (REG_NOTBOL or after a leading 'x'), (^|a) is not nullable so min only
+ // drops to 1, rejecting "ab"/"xab" and requiring "aab".
+ const ExprId rep_b =
+ ExprBuilder::unwrap(parse_ere("(^|a){2,3}b", REG_EXTENDED, b.raw()));
+ EXPECT_EQ(match(b.raw(), rep_b, "ab"), MatchResult::Match);
+ EXPECT_EQ(match(b.raw(), rep_b, "ab", REG_EXTENDED, REG_NOTBOL),
+ MatchResult::NoMatch);
+ EXPECT_EQ(match(b.raw(), rep_b, "xab"), MatchResult::NoMatch);
+ EXPECT_EQ(match(b.raw(), rep_b, "aab", REG_EXTENDED, REG_NOTBOL),
+ MatchResult::Match);
+}
More information about the libc-commits
mailing list