Skip to content

Commit

Permalink
Allow parentheses for unclear precedence with range operator (#5143)
Browse files Browse the repository at this point in the history
Follow-up to #4881 to allow parentheses clarifying usage of the range operator (`..`). Since for example `IntRange` has a `plus(Int)` operator function, the expression `a..b +c` could be ambiguous (but is interpreted as `a..(b + c)`). We can allow clarifying parentheses for such cases.
  • Loading branch information
dzirbel committed Aug 1, 2022
1 parent 01063dc commit fe731ab
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
Expand Up @@ -99,8 +99,13 @@ class UnnecessaryParentheses(config: Config = Config.empty) : Rule(config) {
Precedence.SIMPLE_NAME, // (a to b) to c
),

// (a * b) + c
Precedence.MULTIPLICATIVE to arrayOf(Precedence.ADDITIVE),
Precedence.MULTIPLICATIVE to arrayOf(
Precedence.ADDITIVE, // (a * b) + c
Precedence.RANGE, // (a / b)..(c * d)
),

// (a + b)..(c + d)
Precedence.ADDITIVE to arrayOf(Precedence.RANGE),

// (a && b) || c
Precedence.CONJUNCTION to arrayOf(Precedence.DISJUNCTION),
Expand Down
Expand Up @@ -306,6 +306,19 @@ class UnnecessaryParenthesesSpec {
assertThat(testCase.rule.lint(code)).hasSize(if (testCase.allowForUnclearPrecedence) 0 else 4)
}

@ParameterizedTest
@MethodSource("cases")
fun `range operator when precedence is unclear`(testCase: RuleTestCase) {
val code = """
val a = (1 - 2)..(3 + 4)
val b = (1 / 2)..(3 * 4)
val c = (1 ?: 2)..(3 ?: 4) // parens required
val d = (1 to 2)..(3 to 4) // parens required
"""

assertThat(testCase.rule.lint(code)).hasSize(if (testCase.allowForUnclearPrecedence) 0 else 4)
}

@ParameterizedTest
@MethodSource("cases")
fun `multiple wrapping parentheses`(testCase: RuleTestCase) {
Expand Down

0 comments on commit fe731ab

Please sign in to comment.