Skip to content

[JULES] Refactor pattern stdlib boilerplate and eliminate redundant string allocations - #479

Closed
logbie wants to merge 1 commit into
mainfrom
jules-pattern-refactor-13034455029881876816
Closed

logbie wants to merge 1 commit into
mainfrom
jules-pattern-refactor-13034455029881876816

Conversation

@logbie

@logbie logbie commented May 2, 2026

Copy link
Copy Markdown
Collaborator

Summary of Changes

  • The Issue: The src/stdlib/pattern.rs file contained highly redundant argument validation and type extraction logic using manual match blocks for Value::Text and Value::Pattern. Additionally, there was a performance debt where pattern_split unnecessarily allocated a new Arc<str> from a text slice that it already owned an Arc reference to (Arc::from(text) instead of Arc::clone(&text)).
  • The Rational: Consolidating the manual matching logic significantly improves readability and reduces boilerplate by relying on standard repository helpers. Resolving the unnecessary Arc::from conversion eliminates a redundant heap allocation, reducing overhead during pattern splitting operations and satisfying clippy::useless_conversion warnings.
  • The Solution: Added expect_pattern to src/stdlib/helpers.rs using generate_expect!. Refactored all native pattern functions (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. Fixed the performance debt by updating Arc::from to Arc::clone in the pattern_split fast-path and updated the standard library tests to expect the new error message formats.

Verification Checklist

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

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


Open in Devin Review

Summary by CodeRabbit

  • Bug Fixes

    • Improved error messaging for pattern operations to provide clearer validation feedback.
  • Refactor

    • Introduced shared helper utilities for argument validation and type checking, reducing code duplication across pattern functions.

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 2, 2026 09:28
@coderabbitai

coderabbitai Bot commented May 2, 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: 52d57abf-21e3-410a-9913-6720dea5161d

📥 Commits

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

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

📝 Walkthrough

Walkthrough

This PR refactors pattern stdlib functions to use centralized type-extraction helpers. A new expect_pattern helper is added to helpers.rs, and five pattern native functions are updated to use shared validation utilities (check_arg_count, expect_text, expect_pattern) instead of manual argument validation. Tests are updated to assert on the new error message formats.

Changes

Pattern Helper Consolidation

Layer / File(s) Summary
New Helper Definition
src/stdlib/helpers.rs
Imports CompiledPattern and exports new expect_pattern helper via generate_expect! macro, which validates Value is a Pattern variant and returns Rc<CompiledPattern> or raises RuntimeError with expected/actual type names.
Core Function Refactoring
src/stdlib/pattern.rs
Five native functions (pattern_matches_native, pattern_find_native, pattern_find_all_native, native_pattern_replace, native_pattern_split) are updated to use check_arg_count, expect_text, and expect_pattern helpers, replacing manual args.len() checks and per-argument match blocks. Text results now use Arc::clone() instead of constructing new Arc instances.
Test Updates
src/stdlib/pattern_test.rs
Assertions in "wrong arg count" tests updated to expect "expects 2 arguments" instead of "exactly 2 arguments"; "wrong first arg type" test updated to assert on precise error format ("Expected text, got Number").

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Poem

Hop, hop! A helper hops into place,
Five pattern functions embrace the trace,
No more duplication in sight,
Refactored code shines ever bright,
Shared validation makes it right! 🐰✨

🚥 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 clearly and concisely summarizes the two main changes: refactoring boilerplate in the pattern stdlib and eliminating redundant string allocations.
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 jules-pattern-refactor-13034455029881876816

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 pattern stdlib to use the shared argument-validation helpers, adds a new expect_pattern extractor, and removes a redundant Arc<str> allocation in the pattern split fast path. It fits into the broader stdlib cleanup work by standardizing native-function validation and aligning pattern helpers with the rest of the repository’s stdlib conventions.

Changes:

  • Added expect_pattern in src/stdlib/helpers.rs and reused shared validation helpers in pattern natives.
  • Simplified pattern_matches, pattern_find, pattern_find_all, pattern_replace, and pattern_split argument/type extraction.
  • Updated pattern stdlib tests to assert the new standardized error-message format.

Reviewed changes

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

File Description
src/stdlib/pattern.rs Refactors pattern native functions to use shared helpers and optimizes Arc<str> reuse in no-op paths.
src/stdlib/helpers.rs Adds the new shared expect_pattern extractor for Value::Pattern.
src/stdlib/pattern_test.rs Updates unit tests to match the new helper-driven validation messages.

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

Comment thread src/stdlib/pattern.rs
Comment on lines 20 to +23
/// Native function: pattern_matches(text, pattern) -> boolean
/// Tests if text matches the given compiled pattern
pub fn pattern_matches_native(args: Vec<Value>) -> Result<Value, RuntimeError> {
if args.len() != 2 {
return Err(RuntimeError::new(
"pattern_matches requires exactly 2 arguments (text, pattern)".to_string(),
0,
0,
));
}

let text_str = match &args[0] {
Value::Text(s) => s.as_ref(),
_ => {
return Err(RuntimeError::new(
"First argument to pattern_matches must be text".to_string(),
0,
0,
));
}
};
check_arg_count("pattern_matches", &args, 2)?;
Comment thread src/stdlib/pattern.rs
Comment on lines 31 to +34
/// Native function: pattern_find(text, pattern) -> object or null
/// Finds the first match of pattern in text
pub fn pattern_find_native(args: Vec<Value>) -> Result<Value, RuntimeError> {
if args.len() != 2 {
return Err(RuntimeError::new(
"pattern_find requires exactly 2 arguments (text, pattern)".to_string(),
0,
0,
));
}
check_arg_count("pattern_find", &args, 2)?;
.to_string()
.contains("Expected text, got Number")
);
}
Comment thread src/stdlib/pattern.rs
Comment on lines +121 to +122
let _replacement =
expect_text(&args[2]).map_err(|e| RuntimeError::new(e.message, line, column))?;
Comment thread src/stdlib/helpers.rs
Comment on lines +645 to +658
/// Extracts a Pattern value from a WFL Value, returning it as a reference-counted CompiledPattern.
///
/// # Arguments
///
/// * `value` - The WFL Value to extract from
///
/// # Returns
///
/// Returns an `Rc<CompiledPattern>` clone (incrementing the reference count) if the value
/// is a Pattern variant.
///
/// # Errors
///
/// Returns `RuntimeError` if the value is not a Pattern.
Comment thread src/stdlib/helpers.rs
Comment on lines +659 to +663
expect_pattern,
Pattern,
Rc<CompiledPattern>,
"a Pattern",
|p: &Rc<CompiledPattern>| Rc::clone(p)
Comment thread src/stdlib/pattern.rs
Comment on lines +72 to +74
check_arg_count("pattern_find_all", &args, 2)?;
let text = expect_text(&args[0])?;
let compiled_pattern = expect_pattern(&args[1])?;
Comment thread src/stdlib/pattern.rs
Comment on lines 69 to +72
/// Native function: pattern_find_all(text, pattern) -> list
/// Finds all matches of pattern in text
pub fn pattern_find_all_native(args: Vec<Value>) -> Result<Value, RuntimeError> {
if args.len() != 2 {
return Err(RuntimeError::new(
"pattern_find_all requires exactly 2 arguments (text, pattern)".to_string(),
0,
0,
));
}

let text_str = match &args[0] {
Value::Text(s) => s.as_ref(),
_ => {
return Err(RuntimeError::new(
"First argument to pattern_find_all must be text".to_string(),
0,
0,
));
}
};
check_arg_count("pattern_find_all", &args, 2)?;
@logbie logbie closed this May 22, 2026
@logbie
logbie deleted the jules-pattern-refactor-13034455029881876816 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