[libc-commits] [libc] [libc][regex] Make ExprPool concat and star iterative (PR #244953)

Jeff Bailey via libc-commits libc-commits at lists.llvm.org
Mon Nov 23 09:57:52 PST 2026


================
@@ -356,81 +385,128 @@ ErrorOr<ExprId> ExprPool::make_concat(ExprId l, ExprId r) {
     return (l == EMPTY_STR_ID) ? r : l;
   }
   // (A · B) · C = A · (B · C) (Right-associative canonical form)
-  const Expr le = get(l);
-  if (le.kind == ExprKind::Concat) {
-    ErrorOr<ExprId> tail = make_concat(le.bin.right, r);
-    if (!tail.has_value())
-      return tail;
-    return make_concat(le.bin.left, *tail);
+  Expr ce = get(l);
+  if (ce.kind != ExprKind::Concat)
+    return intern_concat_node(l, r);
+
+  // Flatten the right-associated left spine iteratively so long concatenations
+  // never recurse on the call stack: (A · (B · C)) · D -> [A, B], C, D.
+  ReverseExprIdStack lefts;
+  ExprId cur = l;
+  while (ce.kind == ExprKind::Concat) {
+    if (!lefts.push_back(ce.bin.left))
+      return Error(REG_ESPACE);
+    cur = ce.bin.right;
+    ce = get(cur);
   }
-  const Expr re = get(r);
-  return intern(Expr::make_concat(
-      l, r, static_cast<uint8_t>(le.nullable_mask & re.nullable_mask),
-      le.has_repeat || re.has_repeat,
-      cpp::max(le.rep_expansion, re.rep_expansion)));
+
+  // Rebuild right-to-left (LIFO): A · (B · (C · D)).
+  ErrorOr<ExprId> acc = intern_concat_node(cur, r);
+  if (!acc.has_value())
+    return acc;
+  for (ExprId id : lefts) {
+    acc = intern_concat_node(id, *acc);
+    if (!acc.has_value())
+      return acc;
+  }
+  return acc;
 }
 
 namespace {
 
+ErrorOr<ExprId> coalesce_repeat_leaves(ExprId a, ExprId b, ExprPool &pool);
+
 // Coalesces R{m1,n1} | R{m2,n2} (and shared-prefix/shared-suffix Concat nodes)
 // when their repetition intervals overlap or are adjacent.  Returns
 // INVALID_EXPR_ID when the pair cannot be coalesced.
 ErrorOr<ExprId> coalesce_repeat_pair(ExprId a, ExprId b, ExprPool &pool) {
-  const Expr ae = pool.get(a);
-  const Expr be = pool.get(b);
+  // Scan past matching left Concat prefixes (A · X) | (A · Y) -> A · (X | Y)
+  // without allocating; collect prefixes only if the suffixes coalesce.
+  const ExprId orig_a = a;
+  size_t prefix_depth = 0;
+  Expr ae = pool.get(a);
+  Expr be = pool.get(b);
+  while ((ae.has_repeat || be.has_repeat) && ae.kind == ExprKind::Concat &&
+         be.kind == ExprKind::Concat && ae.bin.right != be.bin.right &&
----------------
kaladron wrote:

Oh, that's a nice catch.  I'll include that in the 13f patch.  Thank you!

https://github.com/llvm/llvm-project/pull/244953


More information about the libc-commits mailing list