Skip to content

Refactor parenthesis and comma handling in parse_parenthesized_list to reuse shared logic #93

@sourcery-ai

Description

@sourcery-ai

The current implementation of parse_parenthesized_list largely duplicates the logic found in extract_parenthesized, particularly around handling nested parentheses and splitting on commas. This results in unnecessary code complexity and maintenance overhead.

Suggested Refactor:

  • Refactor extract_parenthesized to return the inner string (excluding the outer parentheses).
  • Introduce a helper function, split_top_level, which splits a string on top-level commas while preserving nested parentheses. Example implementation:
/// Splits `s` on top-level commas, preserving nested parentheses.
fn split_top_level(s: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0;
    let mut start = 0;
    for (i, c) in s.char_indices() {
        match c {
            '(' => depth += 1,
            ')' if depth > 0 => depth -= 1,
            ',' if depth == 0 => {
                parts.push(s[start..i].trim());
                start = i + 1;
            }
            _ => {}
        }
    }
    parts.push(s[start..].trim());
    parts
}
  • Simplify parse_parenthesized_list to reuse these helpers:
pub fn parse_parenthesized_list(
    tokens: impl Iterator<Item = SyntaxElement<DdlogLanguage>>,
) -> Vec<String> {
    // reuse existing helper for extracting "(...)"
    let inner = extract_parenthesized(tokens);
    split_top_level(&inner)
        .iter()
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect()
}
  • Remove the inlined depth/count loop in parse_parenthesized_list so that there is only one shared implementation of parenthesis-handling logic.

Action Items:

  1. Refactor extract_parenthesized as described.
  2. Add the split_top_level helper.
  3. Update parse_parenthesized_list to use these helpers.
  4. Remove redundant or duplicated logic.

This will improve code maintainability and reduce complexity.


I created this issue for @leynos from #89 (comment).

Tips and commands

Getting Help

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions