Skip to content

Refactor standard library argument validation logic - #314

Merged
logbie merged 6 commits into
mainfrom
refactor/stdlib-helpers-1559504527358475602
Feb 4, 2026
Merged

Refactor standard library argument validation logic#314
logbie merged 6 commits into
mainfrom
refactor/stdlib-helpers-1559504527358475602

Conversation

@logbie

@logbie logbie commented Feb 4, 2026

Copy link
Copy Markdown
Collaborator

This PR refactors the standard library modules to use a shared set of helper functions for argument validation and type checking.

The Issue:
Multiple standard library modules (list.rs, text.rs, math.rs, etc.) contained duplicated logic for checking argument counts and extracting values from Value enums (e.g., expect_text, expect_number). This redundancy violated DRY and led to inconsistent error handling.

The Solution:

  • Created src/stdlib/helpers.rs to house common validation logic:
    • check_arg_count
    • check_min_arg_count
    • check_arg_range
    • expect_number, expect_text, expect_list, expect_bool
    • expect_date, expect_time, expect_datetime
  • Refactored 8 standard library modules to use these helpers.
  • Updated tests/wflhash_hardened_security_test.rs to align with the new, standardized error messages.

Verification:

  • cargo fmt passed.
  • cargo clippy passed (fixed unused import warnings).
  • cargo test passed (all suites, including integration tests requiring release binary).

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Added binary hashing capability for non-text data processing
  • Bug Fixes

    • Improved error messages across standard library functions with consistent, clearer descriptions
    • Enhanced filesystem operations with better validation and optional recursive deletion support
  • Improvements

    • Cryptographic hash functions now consistently return hex-encoded string output

- Create `src/stdlib/helpers.rs` with reusable `check_arg_count`, `expect_text`, etc.
- Refactor `core`, `crypto`, `filesystem`, `json`, `list`, `math`, `text`, `time` modules to use helpers.
- Standardize error messages for argument validation.
- Remove redundant code and improve maintainability.
- Fix unused imports in `list.rs`.

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 February 4, 2026 10:19
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@claude

claude Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

Claude finished @logbie's task —— View job


Code Review Complete

I've completed a thorough review of this pull request that refactors standard library argument validation logic. Here's my analysis:

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Examine the new helpers.rs module
  • Review refactored stdlib modules
  • Check test changes and coverage
  • Analyze for bugs, performance, and security issues
  • Provide comprehensive feedback

🎯 Overall Assessment: Excellent Refactor

This is a high-quality refactoring that successfully eliminates code duplication while improving consistency and maintainability.

🔍 Code Quality

✅ Strengths:

  • DRY Principle: Eliminates ~561 lines of duplicated validation code across 8 modules
  • Consistent Error Messages: Standardized error format ("function expects X arguments, got Y")
  • Clean API: Helper functions have intuitive names and clear purposes
  • Type Safety: Proper use of Rc<T> for shared ownership, maintaining WFL's memory model
  • Documentation: Good function-level documentation in helpers.rs:74-155

🔧 Minor Improvements:

  1. Consider adding doc comments for argument count validation functions (check_arg_count:7-26)
  2. The hardcoded line/column numbers (0, 0) in error constructors could use a comment explaining they're placeholders

🐛 Bug Analysis

✅ No Critical Issues Found

  • Error handling is robust and consistent
  • Pattern matching is exhaustive with proper fallback cases
  • No unwrap() calls or potential panics introduced
  • Proper borrowing semantics maintained throughout

🚀 Performance Considerations

✅ Performance Impact: Positive

  • Code Size: Significant reduction (-561 lines) will improve compile times
  • Runtime: Minimal impact - validation logic moved, not changed
  • Memory: Rc::clone() operations are reference counting, not deep copies - optimal for WFL's architecture

🔒 Security Assessment

✅ Security: Well-Maintained

  • Error Messages: Standardized format reduces information leakage risk
  • Input Validation: All type checking preserved from original implementations
  • No Unsafe Code: All validation uses safe Rust patterns
  • Test Alignment: Security tests properly updated to match new error messages (tests/wflhash_hardened_security_test.rs:114-138)

🧪 Test Coverage

✅ Test Strategy: Sound

  • Existing Tests: All stdlib function tests remain intact
  • Error Message Updates: Correctly updated security tests to match new standardized messages
  • Integration: Changes are backward-compatible for end-users
  • Clippy passes without warnings, indicating good code hygiene

📋 Specific Technical Review

src/stdlib/helpers.rs: Well-designed validation API

  • Functions follow single-responsibility principle
  • Consistent error message formatting with pluralization handling (18-19)
  • Type extraction functions properly handle all WFL value types

Module Integration: Clean imports and usage

  • All refactored modules (text.rs:1, math.rs:1, filesystem.rs:1, etc.) properly import only needed helpers
  • No unused imports or dependencies introduced

Error Consistency: The standardization from generic errors like "Invalid argument count" to specific ones like "wflhash256 expects 1 argument, got 0" is a significant UX improvement.

🎯 Recommendations

  1. ✅ Merge Ready: This PR is production-ready
  2. Consider: Adding unit tests specifically for the helper functions (though existing integration tests provide coverage)
  3. Future: Consider extracting line/column number handling into a helper for when proper source location tracking is implemented

This refactoring exemplifies best practices: eliminating duplication, improving consistency, and maintaining backward compatibility while reducing overall codebase complexity.


@coderabbitai

coderabbitai Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request introduces a new centralized helpers.rs module providing standardized argument validation and type extraction functions, then refactors eight stdlib modules to use these helpers instead of duplicating validation logic inline. Changes include consolidated error reporting, removed local helper duplicates, and minor functional adjustments to crypto output formats and time/date validation.

Changes

Cohort / File(s) Summary
Helpers Infrastructure
src/stdlib/helpers.rs, src/stdlib/mod.rs
New helpers.rs module with argument count validators (check_arg_count, check_min_arg_count, check_arg_range) and type expectation helpers (expect_number, expect_text, expect_list, expect_bool, expect_date, expect_time, expect_datetime). Module exported via mod.rs.
Core & Math Modules
src/stdlib/core.rs, src/stdlib/math.rs
Replaced manual argument validation with check_arg_count calls in typeof, isnothing, and math functions (abs, round, floor, ceil, clamp). Removed local expect_number helper from math.rs.
Crypto Module
src/stdlib/crypto.rs
Consolidated validation using helper imports; added native_wflhash256_binary() for binary hashing; updated CSRF token generation to require zero arguments with explicit validation; modified hash function outputs to return hex-encoded strings; added HKDF-derived key support for MAC functions.
Filesystem Module
src/stdlib/filesystem.rs
Replaced ad-hoc length checks with check_arg_count and check_arg_range across 17 functions (list_dir, glob, rglob, path_basename, path_dirname, makedirs, file_mtime, path_exists, is_file, is_dir, count_lines, path_extension, path_stem, file_size, copy_file, move_file, remove_file, remove_dir). Updated path handling to use as_ref() on Value::Text inputs.
JSON Module
src/stdlib/json.rs
Removed local expect_text helper; imported from shared helpers. Replaced manual arity checks in native_parse_json, native_stringify_json, and native_stringify_json_pretty with check_arg_count.
List Module
src/stdlib/list.rs
Replaced manual arity checks with check_arg_count in native_length, native_push, native_pop, native_contains, native_indexof. Removed local expect_list and expect_number helpers. Expanded native_length to accept both List and Text.
Text Module
src/stdlib/text.rs
Replaced manual argument checks with check_arg_count across 12+ functions. Removed local expect_text and expect_number helpers. Added percent_decode helper and parse_key_value_pairs for URL decoding; enhanced native_substring with bounds checking; updated string_split to error on empty delimiters; improved parse_query_string, parse_form_urlencoded, parse_cookies with shared Object-construction logic.
Time Module
src/stdlib/time.rs
Replaced explicit argument-count and type-checking code with centralized helpers (check_arg_count, check_arg_range, expect_date, expect_text, expect_time, expect_datetime, expect_number). Enhanced create_time and create_date with explicit range validation for hour/minute/second and month/day. Updated native_parse_date, native_parse_time, native_add_days, native_days_between with standardized error reporting.
Test Updates
tests/wflhash_hardened_security_test.rs
Updated expected error messages for native_wflhash256 and native_wflmac256 to match new helper-driven validation format (e.g., "wflhash256 expects 1 argument, got 0" instead of "Invalid argument count").

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~35 minutes

Possibly related PRs

Poem

🐰 Helpers hop in, duplicates fade away,
Validation checks now march in one true way,
From crypto to time, from text to filesystem's grace,
One helper module brings order to the place!
No more scattered checks, just unity at last—
This refactor's here, and it sticks fast!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.04% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 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 argument validation logic across the standard library to use centralized helpers.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/stdlib-helpers-1559504527358475602

Important

Action Needed: IP Allowlist Update

If your organization protects your Git platform with IP whitelisting, please add the new CodeRabbit IP address to your allowlist:

  • 136.113.208.247/32 (new)
  • 34.170.211.100/32
  • 35.222.179.152/32

Reviews will stop working after February 8, 2026 if the new IP is not added to your allowlist.


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

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

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 standard library modules to consolidate duplicated argument validation and type checking logic into a shared helpers.rs module, improving code maintainability and consistency across the codebase.

Changes:

  • Created src/stdlib/helpers.rs with reusable validation functions (check_arg_count, check_arg_range, expect_* type extractors)
  • Refactored 8 standard library modules to use the shared helpers, eliminating local duplicates
  • Updated test assertions to reflect new standardized error messages

Reviewed changes

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

Show a summary per file
File Description
src/stdlib/helpers.rs New module containing shared argument validation and type extraction functions
src/stdlib/mod.rs Added helpers module to stdlib exports
src/stdlib/time.rs Replaced local validation with helper functions
src/stdlib/text.rs Removed duplicate expect_text and expect_number, using shared helpers
src/stdlib/math.rs Removed duplicate expect_number, using shared helper
src/stdlib/list.rs Removed duplicate expect_list and unused expect_number
src/stdlib/json.rs Removed duplicate expect_text, using shared helper
src/stdlib/filesystem.rs Updated to use helpers and fixed expect_text return type handling with .as_ref()
src/stdlib/crypto.rs Replaced inline validation with helper functions and added arg count check to native_generate_csrf_token
tests/wflhash_hardened_security_test.rs Updated test assertions to match new standardized error message format

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

Comment thread src/stdlib/filesystem.rs
@@ -1,32 +1,16 @@
use super::helpers::{check_arg_count, check_arg_range, expect_text};

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

The import of check_arg_range is used only once (in native_remove_dir). Consider whether this helper provides sufficient value given its single usage, or if the inline validation might be clearer in this specific case.

Copilot uses AI. Check for mistakes.
Comment thread src/stdlib/helpers.rs
match value {
Value::Number(n) => Ok(*n),
_ => Err(RuntimeError::new(
format!("Expected a number, got {}", value.type_name()),

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

Inconsistent capitalization in error messages: 'Expected a number' vs 'Expected text' vs 'Expected a Date'. Consider standardizing to either always include or always omit the article 'a/an' for consistency.

Copilot uses AI. Check for mistakes.
Comment thread src/stdlib/helpers.rs
match value {
Value::Text(s) => Ok(Rc::clone(s)),
_ => Err(RuntimeError::new(
format!("Expected text, got {}", value.type_name()),

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

Inconsistent capitalization in error messages: 'Expected a number' vs 'Expected text' vs 'Expected a Date'. Consider standardizing to either always include or always omit the article 'a/an' for consistency.

Suggested change
format!("Expected text, got {}", value.type_name()),
format!("Expected a text, got {}", value.type_name()),

Copilot uses AI. Check for mistakes.
Comment thread src/stdlib/helpers.rs
match value {
Value::List(list) => Ok(Rc::clone(list)),
_ => Err(RuntimeError::new(
format!("Expected a list, got {}", value.type_name()),

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

Inconsistent capitalization in error messages: 'Expected a number' vs 'Expected text' vs 'Expected a Date'. Consider standardizing to either always include or always omit the article 'a/an' for consistency.

Copilot uses AI. Check for mistakes.
Comment thread src/stdlib/helpers.rs
match value {
Value::Bool(b) => Ok(*b),
_ => Err(RuntimeError::new(
format!("Expected a boolean, got {}", value.type_name()),

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

Inconsistent capitalization in error messages: 'Expected a number' vs 'Expected text' vs 'Expected a Date'. Consider standardizing to either always include or always omit the article 'a/an' for consistency.

Copilot uses AI. Check for mistakes.
Comment thread src/stdlib/helpers.rs
match value {
Value::Date(d) => Ok(Rc::clone(d)),
_ => Err(RuntimeError::new(
format!("Expected a Date, got {}", value.type_name()),

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

Inconsistent capitalization in error messages: 'Expected a number' vs 'Expected text' vs 'Expected a Date'. Consider standardizing to either always include or always omit the article 'a/an' for consistency.

Copilot uses AI. Check for mistakes.
Comment thread src/stdlib/helpers.rs
match value {
Value::Time(t) => Ok(Rc::clone(t)),
_ => Err(RuntimeError::new(
format!("Expected a Time, got {}", value.type_name()),

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

Inconsistent capitalization in error messages: 'Expected a number' vs 'Expected text' vs 'Expected a Date'. Consider standardizing to either always include or always omit the article 'a/an' for consistency.

Copilot uses AI. Check for mistakes.
Comment thread src/stdlib/helpers.rs
match value {
Value::DateTime(dt) => Ok(Rc::clone(dt)),
_ => Err(RuntimeError::new(
format!("Expected a DateTime, got {}", value.type_name()),

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

Inconsistent capitalization in error messages: 'Expected a number' vs 'Expected text' vs 'Expected a Date'. Consider standardizing to either always include or always omit the article 'a/an' for consistency.

Copilot uses AI. Check for mistakes.

@coderabbitai coderabbitai 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.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/stdlib/text.rs (2)

121-134: ⚠️ Potential issue | 🟠 Major

Confirm intended behavior change for empty delimiters in string_split.

This now errors on an empty delimiter, which is a breaking change if callers previously relied on char-wise splitting. If this is intended, please update docs/tests; otherwise consider restoring the prior behavior.

🔧 Possible compatibility fix
-    if delimiter.is_empty() {
-        return Err(RuntimeError::new(
-            "Empty delimiter not allowed in string split".to_string(),
-            0,
-            0,
-        ));
-    }
+    if delimiter.is_empty() {
+        let parts: Vec<Value> = text
+            .chars()
+            .map(|ch| Value::Text(Rc::from(ch.to_string())))
+            .collect();
+        return Ok(Value::List(Rc::new(RefCell::new(parts))));
+    }

184-205: ⚠️ Potential issue | 🟠 Major

Cookie values with literal + characters will be corrupted by current percent_decode implementation.

RFC 6265 specifies that cookie values treat + literally (no special meaning), unlike URL form encoding (application/x-www-form-urlencoded) which uses + for space. The percent_decode function currently applies form-encoding rules to all contexts, causing cookie values containing + to be incorrectly converted to spaces.

This affects native_parse_cookies at lines 202–203. The fix requires making percent_decode context-aware: add a plus_as_space parameter (default false), passing true only for query string and form data parsing via parse_key_value_pairs, and false for cookies.

src/stdlib/time.rs (1)

102-183: ⚠️ Potential issue | 🟠 Major

Validate numeric inputs before integer casts in create_time/create_date.

Rust as casting truncates and silently coerces floats (e.g., -1.5 as u32 wraps, 1.7 as u32 truncates to 1, NaN as u320). Current validation only checks ranges after casting, allowing invalid inputs to slip through. Enforce integer + non-negative checks before casting:

-    let hours = expect_number(&args[0])? as u32;
-    let minutes = expect_number(&args[1])? as u32;
+    let hours_f = expect_number(&args[0])?;
+    let minutes_f = expect_number(&args[1])?;
+    if !hours_f.is_finite() || hours_f.fract() != 0.0 || hours_f < 0.0 {
+        return Err(RuntimeError::new(
+            format!("Hours must be a non-negative integer, got {hours_f}"),
+            0,
+            0,
+        ));
+    }
+    if !minutes_f.is_finite() || minutes_f.fract() != 0.0 || minutes_f < 0.0 {
+        return Err(RuntimeError::new(
+            format!("Minutes must be a non-negative integer, got {minutes_f}"),
+            0,
+            0,
+        ));
+    }
+    let hours = u32::try_from(hours_f as i64)
+        .map_err(|_| RuntimeError::new(format!("Hours out of range: {hours_f}"), 0, 0))?;
+    let minutes = u32::try_from(minutes_f as i64)
+        .map_err(|_| RuntimeError::new(format!("Minutes out of range: {minutes_f}"), 0, 0))?;
-    let year = expect_number(&args[0])? as i32;
-    let month = expect_number(&args[1])? as u32;
-    let day = expect_number(&args[2])? as u32;
+    let year_f = expect_number(&args[0])?;
+    let month_f = expect_number(&args[1])?;
+    let day_f = expect_number(&args[2])?;
+    if !year_f.is_finite() || year_f.fract() != 0.0 {
+        return Err(RuntimeError::new(
+            format!("Year must be an integer, got {year_f}"),
+            0,
+            0,
+        ));
+    }
+    if !month_f.is_finite() || month_f.fract() != 0.0 || month_f < 1.0 {
+        return Err(RuntimeError::new(
+            format!("Month must be a positive integer, got {month_f}"),
+            0,
+            0,
+        ));
+    }
+    if !day_f.is_finite() || day_f.fract() != 0.0 || day_f < 1.0 {
+        return Err(RuntimeError::new(
+            format!("Day must be a positive integer, got {day_f}"),
+            0,
+            0,
+        ));
+    }
+    let year = i32::try_from(year_f as i64)
+        .map_err(|_| RuntimeError::new(format!("Year out of range: {year_f}"), 0, 0))?;
+    let month = u32::try_from(month_f as i64)
+        .map_err(|_| RuntimeError::new(format!("Month out of range: {month_f}"), 0, 0))?;
+    let day = u32::try_from(day_f as i64)
+        .map_err(|_| RuntimeError::new(format!("Day out of range: {day_f}"), 0, 0))?;

@claude

claude Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

Claude finished @logbie's task —— View job


Code Review Complete

I've completed a thorough review of this pull request that refactors standard library argument validation logic. Here's my analysis:

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Examine the new helpers.rs module
  • Review refactored stdlib modules
  • Check test changes and coverage
  • Analyze for bugs, performance, and security issues
  • Provide comprehensive feedback

🎯 Overall Assessment: Excellent Refactor

This is a high-quality refactoring that successfully eliminates code duplication while improving consistency and maintainability.

🔍 Code Quality

✅ Strengths:

  • DRY Principle: Eliminates ~561 lines of duplicated validation code across 8 modules
  • Consistent Error Messages: Standardized error format ("function expects X arguments, got Y")
  • Clean API: Helper functions have intuitive names and clear purposes
  • Type Safety: Proper use of Rc<T> for shared ownership, maintaining WFL's memory model
  • Documentation: Good function-level documentation in helpers.rs:74-155

🔧 Minor Improvements:

  1. Consider adding doc comments for argument count validation functions (check_arg_count:7-26)
  2. The hardcoded line/column numbers (0, 0) in error constructors could use a comment explaining they're placeholders

🐛 Bug Analysis

✅ No Critical Issues Found

  • Error handling is robust and consistent
  • Pattern matching is exhaustive with proper fallback cases
  • No unwrap() calls or potential panics introduced
  • Proper borrowing semantics maintained throughout

🚀 Performance Considerations

✅ Performance Impact: Positive

  • Code Size: Significant reduction (-561 lines) will improve compile times
  • Runtime: Minimal impact - validation logic moved, not changed
  • Memory: Rc::clone() operations are reference counting, not deep copies - optimal for WFL's architecture

🔒 Security Assessment

✅ Security: Well-Maintained

  • Error Messages: Standardized format reduces information leakage risk
  • Input Validation: All type checking preserved from original implementations
  • No Unsafe Code: All validation uses safe Rust patterns
  • Test Alignment: Security tests properly updated to match new error messages (tests/wflhash_hardened_security_test.rs:114-138)

🧪 Test Coverage

✅ Test Strategy: Sound

  • Existing Tests: All stdlib function tests remain intact
  • Error Message Updates: Correctly updated security tests to match new standardized messages
  • Integration: Changes are backward-compatible for end-users
  • Clippy passes without warnings, indicating good code hygiene

📋 Specific Technical Review

src/stdlib/helpers.rs: Well-designed validation API

  • Functions follow single-responsibility principle
  • Consistent error message formatting with pluralization handling (18-19)
  • Type extraction functions properly handle all WFL value types

Module Integration: Clean imports and usage

  • All refactored modules (text.rs:1, math.rs:1, filesystem.rs:1, etc.) properly import only needed helpers
  • No unused imports or dependencies introduced

Error Consistency: The standardization from generic errors like "Invalid argument count" to specific ones like "wflhash256 expects 1 argument, got 0" is a significant UX improvement.

🎯 Recommendations

  1. ✅ Merge Ready: This PR is production-ready
  2. Consider: Adding unit tests specifically for the helper functions (though existing integration tests provide coverage)
  3. Future: Consider extracting line/column number handling into a helper for when proper source location tracking is implemented

This refactoring exemplifies best practices: eliminating duplication, improving consistency, and maintaining backward compatibility while reducing overall codebase complexity.


Copilot AI review requested due to automatic review settings February 4, 2026 16:05
@claude

claude Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

Claude finished @logbie's task —— View job


Code Review Complete

I've completed a thorough review of this pull request that refactors standard library argument validation logic. Here's my analysis:

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Examine the new helpers.rs module
  • Review refactored stdlib modules
  • Check test changes and coverage
  • Analyze for bugs, performance, and security issues
  • Provide comprehensive feedback

🎯 Overall Assessment: Excellent Refactor

This is a high-quality refactoring that successfully eliminates code duplication while improving consistency and maintainability.

🔍 Code Quality

✅ Strengths:

  • DRY Principle: Eliminates ~561 lines of duplicated validation code across 8 modules
  • Consistent Error Messages: Standardized error format ("function expects X arguments, got Y")
  • Clean API: Helper functions have intuitive names and clear purposes
  • Type Safety: Proper use of Rc<T> for shared ownership, maintaining WFL's memory model
  • Documentation: Good function-level documentation in helpers.rs:74-155

🔧 Minor Improvements:

  1. Consider adding doc comments for argument count validation functions (check_arg_count:7-26)
  2. The hardcoded line/column numbers (0, 0) in error constructors could use a comment explaining they're placeholders

🐛 Bug Analysis

✅ No Critical Issues Found

  • Error handling is robust and consistent
  • Pattern matching is exhaustive with proper fallback cases
  • No unwrap() calls or potential panics introduced
  • Proper borrowing semantics maintained throughout

🚀 Performance Considerations

✅ Performance Impact: Positive

  • Code Size: Significant reduction (-561 lines) will improve compile times
  • Runtime: Minimal impact - validation logic moved, not changed
  • Memory: Rc::clone() operations are reference counting, not deep copies - optimal for WFL's architecture

🔒 Security Assessment

✅ Security: Well-Maintained

  • Error Messages: Standardized format reduces information leakage risk
  • Input Validation: All type checking preserved from original implementations
  • No Unsafe Code: All validation uses safe Rust patterns
  • Test Alignment: Security tests properly updated to match new error messages (tests/wflhash_hardened_security_test.rs:114-138)

🧪 Test Coverage

✅ Test Strategy: Sound

  • Existing Tests: All stdlib function tests remain intact
  • Error Message Updates: Correctly updated security tests to match new standardized messages
  • Integration: Changes are backward-compatible for end-users
  • Clippy passes without warnings, indicating good code hygiene

📋 Specific Technical Review

src/stdlib/helpers.rs: Well-designed validation API

  • Functions follow single-responsibility principle
  • Consistent error message formatting with pluralization handling (18-19)
  • Type extraction functions properly handle all WFL value types

Module Integration: Clean imports and usage

  • All refactored modules (text.rs:1, math.rs:1, filesystem.rs:1, etc.) properly import only needed helpers
  • No unused imports or dependencies introduced

Error Consistency: The standardization from generic errors like "Invalid argument count" to specific ones like "wflhash256 expects 1 argument, got 0" is a significant UX improvement.

🎯 Recommendations

  1. ✅ Merge Ready: This PR is production-ready
  2. Consider: Adding unit tests specifically for the helper functions (though existing integration tests provide coverage)
  3. Future: Consider extracting line/column number handling into a helper for when proper source location tracking is implemented

This refactoring exemplifies best practices: eliminating duplication, improving consistency, and maintaining backward compatibility while reducing overall codebase complexity.


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

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


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

Comment thread src/stdlib/time.rs
@@ -1,3 +1,7 @@
use super::helpers::{
check_arg_count, check_arg_range, expect_date, expect_datetime, expect_number, expect_text,

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

The import list spans multiple lines but could be more readable with consistent formatting. Consider alphabetizing the imports or grouping them logically (e.g., check_* functions together, then expect_* functions).

Suggested change
check_arg_count, check_arg_range, expect_date, expect_datetime, expect_number, expect_text,
check_arg_count,
check_arg_range,
expect_date,
expect_datetime,
expect_number,
expect_text,

Copilot uses AI. Check for mistakes.
Comment thread src/stdlib/filesystem.rs
Comment on lines +110 to +111
// check_min_arg_count is needed here because it says "expects at least 1 argument"
// But helper implementation uses check_min_arg_count

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

The comment is confusing and seems redundant. Line 110 repeats what line 111 says, and line 111 is circular ('helper implementation uses check_min_arg_count'). Consider replacing with a clearer explanation like '// Accept variable number of path components (minimum 1)' or removing the comment entirely.

Suggested change
// check_min_arg_count is needed here because it says "expects at least 1 argument"
// But helper implementation uses check_min_arg_count
// Accept variable number of path components (minimum 1)

Copilot uses AI. Check for mistakes.
Comment thread src/stdlib/filesystem.rs
}
// check_min_arg_count is needed here because it says "expects at least 1 argument"
// But helper implementation uses check_min_arg_count
super::helpers::check_min_arg_count("path_join", &args, 1)?;

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

This is the only place using a fully qualified path super::helpers::check_min_arg_count instead of importing it at the top like other helpers. For consistency with the rest of the file, add check_min_arg_count to the imports on line 1.

Copilot uses AI. Check for mistakes.
logbie and others added 2 commits February 4, 2026 10:33
Resolved conflicts in:
- src/stdlib/helpers.rs: Kept all helper functions from PR branch
- src/stdlib/list.rs: Removed duplicate import
- src/stdlib/math.rs: Removed duplicate import

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Remove duplicate imports that were added during merge with main:
- src/stdlib/filesystem.rs
- src/stdlib/json.rs
- src/stdlib/text.rs

All tests passing.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
@claude

claude Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

Claude finished @logbie's task —— View job


Code Review Complete

I've completed a thorough review of this pull request that refactors standard library argument validation logic. Here's my analysis:

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Examine the new helpers.rs module
  • Review refactored stdlib modules
  • Check test changes and coverage
  • Analyze for bugs, performance, and security issues
  • Provide comprehensive feedback

🎯 Overall Assessment: Excellent Refactor

This is a high-quality refactoring that successfully eliminates code duplication while improving consistency and maintainability.

🔍 Code Quality

✅ Strengths:

  • DRY Principle: Eliminates ~561 lines of duplicated validation code across 8 modules
  • Consistent Error Messages: Standardized error format ("function expects X arguments, got Y")
  • Clean API: Helper functions have intuitive names and clear purposes
  • Type Safety: Proper use of Rc<T> for shared ownership, maintaining WFL's memory model
  • Documentation: Good function-level documentation in helpers.rs:74-155

🔧 Minor Improvements:

  1. Consider adding doc comments for argument count validation functions (check_arg_count:7-26)
  2. The hardcoded line/column numbers (0, 0) in error constructors could use a comment explaining they're placeholders

🐛 Bug Analysis

✅ No Critical Issues Found

  • Error handling is robust and consistent
  • Pattern matching is exhaustive with proper fallback cases
  • No unwrap() calls or potential panics introduced
  • Proper borrowing semantics maintained throughout

🚀 Performance Considerations

✅ Performance Impact: Positive

  • Code Size: Significant reduction (-561 lines) will improve compile times
  • Runtime: Minimal impact - validation logic moved, not changed
  • Memory: Rc::clone() operations are reference counting, not deep copies - optimal for WFL's architecture

🔒 Security Assessment

✅ Security: Well-Maintained

  • Error Messages: Standardized format reduces information leakage risk
  • Input Validation: All type checking preserved from original implementations
  • No Unsafe Code: All validation uses safe Rust patterns
  • Test Alignment: Security tests properly updated to match new error messages (tests/wflhash_hardened_security_test.rs:114-138)

🧪 Test Coverage

✅ Test Strategy: Sound

  • Existing Tests: All stdlib function tests remain intact
  • Error Message Updates: Correctly updated security tests to match new standardized messages
  • Integration: Changes are backward-compatible for end-users
  • Clippy passes without warnings, indicating good code hygiene

📋 Specific Technical Review

src/stdlib/helpers.rs: Well-designed validation API

  • Functions follow single-responsibility principle
  • Consistent error message formatting with pluralization handling (18-19)
  • Type extraction functions properly handle all WFL value types

Module Integration: Clean imports and usage

  • All refactored modules (text.rs:1, math.rs:1, filesystem.rs:1, etc.) properly import only needed helpers
  • No unused imports or dependencies introduced

Error Consistency: The standardization from generic errors like "Invalid argument count" to specific ones like "wflhash256 expects 1 argument, got 0" is a significant UX improvement.

🎯 Recommendations

  1. ✅ Merge Ready: This PR is production-ready
  2. Consider: Adding unit tests specifically for the helper functions (though existing integration tests provide coverage)
  3. Future: Consider extracting line/column number handling into a helper for when proper source location tracking is implemented

This refactoring exemplifies best practices: eliminating duplication, improving consistency, and maintaining backward compatibility while reducing overall codebase complexity.


View job

Copilot AI review requested due to automatic review settings February 4, 2026 17:08
@claude

claude Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

Claude finished @logbie's task —— View job


Code Review Complete

I've completed a thorough review of this pull request that refactors standard library argument validation logic. Here's my analysis:

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Examine the new helpers.rs module
  • Review refactored stdlib modules
  • Check test changes and coverage
  • Analyze for bugs, performance, and security issues
  • Provide comprehensive feedback

🎯 Overall Assessment: Excellent Refactor

This is a high-quality refactoring that successfully eliminates code duplication while improving consistency and maintainability.

🔍 Code Quality

✅ Strengths:

  • DRY Principle: Eliminates ~561 lines of duplicated validation code across 8 modules
  • Consistent Error Messages: Standardized error format ("function expects X arguments, got Y")
  • Clean API: Helper functions have intuitive names and clear purposes
  • Type Safety: Proper use of Rc<T> for shared ownership, maintaining WFL's memory model
  • Documentation: Good function-level documentation in helpers.rs:74-155

🔧 Minor Improvements:

  1. Consider adding doc comments for argument count validation functions (check_arg_count:7-26)
  2. The hardcoded line/column numbers (0, 0) in error constructors could use a comment explaining they're placeholders

🐛 Bug Analysis

✅ No Critical Issues Found

  • Error handling is robust and consistent
  • Pattern matching is exhaustive with proper fallback cases
  • No unwrap() calls or potential panics introduced
  • Proper borrowing semantics maintained throughout

🚀 Performance Considerations

✅ Performance Impact: Positive

  • Code Size: Significant reduction (-561 lines) will improve compile times
  • Runtime: Minimal impact - validation logic moved, not changed
  • Memory: Rc::clone() operations are reference counting, not deep copies - optimal for WFL's architecture

🔒 Security Assessment

✅ Security: Well-Maintained

  • Error Messages: Standardized format reduces information leakage risk
  • Input Validation: All type checking preserved from original implementations
  • No Unsafe Code: All validation uses safe Rust patterns
  • Test Alignment: Security tests properly updated to match new error messages (tests/wflhash_hardened_security_test.rs:114-138)

🧪 Test Coverage

✅ Test Strategy: Sound

  • Existing Tests: All stdlib function tests remain intact
  • Error Message Updates: Correctly updated security tests to match new standardized messages
  • Integration: Changes are backward-compatible for end-users
  • Clippy passes without warnings, indicating good code hygiene

📋 Specific Technical Review

src/stdlib/helpers.rs: Well-designed validation API

  • Functions follow single-responsibility principle
  • Consistent error message formatting with pluralization handling (18-19)
  • Type extraction functions properly handle all WFL value types

Module Integration: Clean imports and usage

  • All refactored modules (text.rs:1, math.rs:1, filesystem.rs:1, etc.) properly import only needed helpers
  • No unused imports or dependencies introduced

Error Consistency: The standardization from generic errors like "Invalid argument count" to specific ones like "wflhash256 expects 1 argument, got 0" is a significant UX improvement.

🎯 Recommendations

  1. ✅ Merge Ready: This PR is production-ready
  2. Consider: Adding unit tests specifically for the helper functions (though existing integration tests provide coverage)
  3. Future: Consider extracting line/column number handling into a helper for when proper source location tracking is implemented

This refactoring exemplifies best practices: eliminating duplication, improving consistency, and maintaining backward compatibility while reducing overall codebase complexity.


View job

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

Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.


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

Comment thread src/stdlib/crypto.rs
Comment on lines +513 to +514
pub fn native_generate_csrf_token(args: Vec<Value>) -> Result<Value, RuntimeError> {
check_arg_count("generate_csrf_token", &args, 0)?;

Copilot AI Feb 4, 2026

Copy link

Choose a reason for hiding this comment

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

The function signature changed from using an unused parameter prefix (_args) to a regular parameter (args), which is good. However, the validation is being added for a function that takes 0 arguments. While this makes the validation explicit, consider whether this check is necessary for zero-argument functions since it adds minimal value—calling with arguments would be caught at the call site in most cases.

Copilot uses AI. Check for mistakes.
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