Skip to content

C#: Unwrap parentheses in pattern matching comparator#7188

Merged
knutwannheden merged 1 commit intomainfrom
agile-hamster
Mar 28, 2026
Merged

C#: Unwrap parentheses in pattern matching comparator#7188
knutwannheden merged 1 commit intomainfrom
agile-hamster

Conversation

@knutwannheden
Copy link
Copy Markdown
Contributor

Motivation

The C# pattern matcher (PatternMatchingComparator) did not ignore optional expression parentheses, so a pattern like Console.WriteLine("hello") would fail to match Console.WriteLine(("hello")), and a parenthesized pattern (x + 1) wouldn't match the unparenthesized x + 1. The JavaScript comparator already handles this via an unwrap() step — this brings parity to C#.

Summary

  • Added a non-generic Parentheses interface (extending Expression) with an InnerTree property, so Parentheses<T> can be type-checked and unwrapped without reflection
  • Parentheses<T> now implements the non-generic Parentheses interface
  • PatternMatchingComparator.UnwrapParentheses() recursively strips Parentheses wrappers using a simple while (node is Parentheses p) loop
  • Both pattern and candidate are unwrapped at the top of MatchNode and in the fast-reject path in CSharpPattern.Match

Test plan

  • MatchesConcreteArgThroughParentheses — pattern without parens matches candidate arg wrapped in parens
  • ParenthesizedPatternMatchesUnparenthesized — parenthesized pattern (x + 1) matches x + 1
  • All 108 existing PatternMatchTests pass (no regressions)

Patterns like `Console.WriteLine("hello")` now match candidates with
extra parentheses like `Console.WriteLine(("hello"))`, and a
parenthesized pattern `(x + 1)` matches the unparenthesized `x + 1`.

Adds a non-generic `Parentheses` interface (extending `Expression`) so
that `Parentheses<T>` can be unwrapped with a simple `is` check — no
reflection needed.
@github-project-automation github-project-automation bot moved this to In Progress in OpenRewrite Mar 28, 2026
@knutwannheden knutwannheden merged commit ec218ce into main Mar 28, 2026
1 check passed
@knutwannheden knutwannheden deleted the agile-hamster branch March 28, 2026 09:29
@github-project-automation github-project-automation bot moved this from In Progress to Done in OpenRewrite Mar 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant