Skip to content

[JULES] Refactor Pattern Standard Library Functions to Eliminate Redundancy - #483

Closed
logbie wants to merge 1 commit into
mainfrom
optimize-pattern-funcs-201104489420881395
Closed

[JULES] Refactor Pattern Standard Library Functions to Eliminate Redundancy#483
logbie wants to merge 1 commit into
mainfrom
optimize-pattern-funcs-201104489420881395

Conversation

@logbie

@logbie logbie commented May 4, 2026

Copy link
Copy Markdown
Collaborator

Summary of Changes

  • The Issue: The native pattern functions (pattern_matches_native, pattern_find_native, pattern_find_all_native, native_pattern_replace, and native_pattern_split) in src/stdlib/pattern.rs contained highly redundant code for matching on Value enums to extract texts and compiled patterns. They also manually checked argument lengths and constructed repetitive error strings using .to_string(), generating unnecessary allocations.
  • The Rational: Eliminating this boilerplate improves the maintainability and DRYness of the pattern module. It also removes the performance debt and technical debt associated with the repetitive allocations and manual boilerplate checks, replacing them with the project's standard extraction mechanisms.
  • The Solution: Added a new macro-generated helper, expect_pattern, to src/stdlib/helpers.rs alongside the other standardized type extractors. Refactored all functions in src/stdlib/pattern.rs to use check_arg_count, expect_text, and expect_pattern. Furthermore, in native_pattern_split and native_pattern_replace, Arc::from was replaced with the zero-allocation Arc::clone using the extracted arcs. Tests in src/stdlib/pattern_test.rs were updated to assert against the new, unified error messages.

Verification Checklist

  • cargo fmt executed and passed.
  • cargo clippy --all-targets -- -D warnings returned no warnings or errors.
  • All cargo test suites passed (100% success rate).

PR created automatically by Jules for task 201104489420881395 started by @logbie


Open in Devin Review

Summary by CodeRabbit

  • Refactor
    • Consolidated internal error handling in pattern operations for improved consistency and maintainability.

The Issue: The pattern functions (pattern_matches_native, pattern_find_native,
pattern_find_all_native, native_pattern_replace, native_pattern_split) contained
duplicated code for matching on Value enum variants to extract strings and patterns,
and used manual arg length checks. Furthermore, they had unnecessary to_string()
allocations for error messages.

The Rational: Eliminating boilerplate through expect helpers improves
maintainability and removes performance debt introduced by redundant format!/to_string() calls.

The Solution: Implemented a new expect_pattern helper using the generate_expect! macro.
Refactored all pattern native functions to use expect_text, expect_pattern, and
check_arg_count instead of manual pattern matching and string cloning.

Co-authored-by: logbie <1138960+logbie@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

Copilot AI review requested due to automatic review settings May 4, 2026 09:05
@coderabbitai

coderabbitai Bot commented May 4, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c5456aa4-1e5f-40a3-8685-7b90999963b8

📥 Commits

Reviewing files that changed from the base of the PR and between 68d08ee and c761436.

📒 Files selected for processing (3)
  • src/stdlib/helpers.rs
  • src/stdlib/pattern.rs
  • src/stdlib/pattern_test.rs

📝 Walkthrough

Walkthrough

A new expect_pattern extractor is added to helpers.rs, and pattern native functions are refactored to use shared validation helpers (check_arg_count, expect_text, expect_pattern) instead of manual argument checks, with test assertions updated to match new error messages.

Changes

Pattern Validation Helper Refactoring

Layer / File(s) Summary
New Helper
src/stdlib/helpers.rs
expect_pattern extractor added via generate_expect! to validate and extract Value::Pattern as Rc<CompiledPattern>.
Pattern Native Refactoring
src/stdlib/pattern.rs
pattern_matches_native, pattern_find_native, pattern_find_all_native, native_pattern_replace, and native_pattern_split refactored to use check_arg_count, expect_text, and expect_pattern for validation while preserving all existing logic and behavior.
Test Updates
src/stdlib/pattern_test.rs
Error message assertions updated: wrong argument count tests now expect "expects 2 arguments" instead of "exactly 2 arguments"; wrong first argument type test now expects "Expected text" instead of "First argument".

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

Patterns now extract with grace,
No more checks in every place,
Helpers shared across the code,
Cleaner paths, a lighter load. 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: refactoring pattern standard library functions to eliminate code redundancy by introducing helper functions and consolidating argument validation.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch optimize-pattern-funcs-201104489420881395

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no potential bugs to report.

View in Devin Review to see 3 additional findings.

Open in Devin Review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors the stdlib pattern native functions to use the shared stdlib argument/type extraction helpers, reducing repetitive Value matching and standardizing error messages across the pattern API.

Changes:

  • Added a new expect_pattern extractor to the stdlib helpers (macro-generated via generate_expect!).
  • Refactored pattern_matches_native, pattern_find_native, pattern_find_all_native, native_pattern_replace, and native_pattern_split to use check_arg_count, expect_text, and expect_pattern.
  • Updated unit tests to assert against the new unified “expects N arguments” / “Expected …, got …” error message formats, and replaced unnecessary Arc::from(...) with Arc::clone(...) where applicable.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
src/stdlib/pattern.rs Swaps manual argument/type matching for shared helpers; reduces allocation by cloning extracted Arc values where possible.
src/stdlib/helpers.rs Introduces expect_pattern extractor to standardize pattern value extraction and error messages.
src/stdlib/pattern_test.rs Updates assertions to match the standardized error message phrasing produced by the shared helpers.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/stdlib/pattern.rs
Comment on lines +115 to +122
check_arg_count("pattern_replace", &args, 3)
.map_err(|e| RuntimeError::new(e.message, line, column))?;

let _replacement = match &args[2] {
Value::Text(t) => t.as_ref(),
_ => {
return Err(RuntimeError::new(
"Third argument must be text".to_string(),
line,
column,
));
}
};
let text = expect_text(&args[0]).map_err(|e| RuntimeError::new(e.message, line, column))?;
let _pattern =
expect_pattern(&args[1]).map_err(|e| RuntimeError::new(e.message, line, column))?;
let _replacement =
expect_text(&args[2]).map_err(|e| RuntimeError::new(e.message, line, column))?;
Comment thread src/stdlib/pattern.rs
Comment on lines +134 to +140
check_arg_count("pattern_split", &args, 2)
.map_err(|e| RuntimeError::new(e.message, line, column))?;

let text = match &args[0] {
Value::Text(t) => t.as_ref(),
_ => {
return Err(RuntimeError::new(
"First argument must be text".to_string(),
line,
column,
));
}
};

let pattern = match &args[1] {
Value::Pattern(p) => p,
_ => {
return Err(RuntimeError::new(
"Second argument must be a pattern".to_string(),
line,
column,
));
}
};
let text_arc = expect_text(&args[0]).map_err(|e| RuntimeError::new(e.message, line, column))?;
let text = text_arc.as_ref();
let pattern =
expect_pattern(&args[1]).map_err(|e| RuntimeError::new(e.message, line, column))?;
Comment thread src/stdlib/helpers.rs
Comment on lines +600 to +607
generate_expect!(
/// Extracts a compiled pattern value from a WFL Value, returning it as a reference-counted CompiledPattern.
expect_pattern,
Pattern,
Rc<CompiledPattern>,
"a pattern",
|p: &Rc<CompiledPattern>| Rc::clone(p)
);
@logbie logbie closed this May 22, 2026
@logbie
logbie deleted the optimize-pattern-funcs-201104489420881395 branch June 19, 2026 04:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants