Skip to content

Commit

Permalink
Improve ternary simplification (#541)
Browse files Browse the repository at this point in the history
* Handle ternary simplification when nil is used

* Fix error :|
  • Loading branch information
ketkarameya committed Jul 14, 2023
1 parent f5bacb9 commit d984013
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/cleanup_rules/swift/rules.toml
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,54 @@ replace_node = "ternary_block"
replace = "@block_false"
is_seed_rule = false


# A hack to handle the scenario when `nil` is used in the ternary expression
# TODO: Track https://github.com/alex-pinkus/tree-sitter-swift/issues/303 to remove this hack
# var v = false ? x : nil
#
# After
# var v = nil
#
[[rules]]
name = "ternary_false_alternative_nil"
query = """(
(ternary_expression
condition:[(boolean_literal) @false
(tuple_expression
value: (boolean_literal) @false)]
) @ternary_block
(#eq? @false "false")
(#match? @ternary_block ":[\\\\n\\\\r\\\\s]*nil\\\\b")
)"""
groups = ["if_cleanup"]
replace_node = "ternary_block"
replace = "nil"
is_seed_rule = false


## A hack to handle the scenario when `nil` is used in the ternary expression
# TODO: Track https://github.com/alex-pinkus/tree-sitter-swift/issues/303 to remove this hack
# var v = true ? nil : x
#
# After
# var v = nil
#
[[rules]]
name = "ternary_true_consequent_nil"
query = """(
(ternary_expression
condition:[(boolean_literal) @true
(tuple_expression
value: (boolean_literal) @true)]
) @ternary_block
(#eq? @true "true")
(#match? @ternary_block "\\\\?[\\\\n\\\\r\\\\s]*nil[\\\\n\\\\r\\\\s]*:")
)"""
groups = ["if_cleanup"]
replace_node = "ternary_block"
replace = "nil"
is_seed_rule = false

# delete variables declared in a function scope
[[rules]]
name = "delete_variable_declaration"
Expand Down
2 changes: 2 additions & 0 deletions test-resources/swift/cleanup_rules/expected/SampleClass.swift
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ class SampleClass {
func checkTernary() {
var value = 2
var value2 = 3
var value3 = nil
var value4 = nil
}

func checkIfBooleanWithComments(){
Expand Down
5 changes: 5 additions & 0 deletions test-resources/swift/cleanup_rules/input/SampleClass.swift
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,11 @@ class SampleClass {
func checkTernary() {
var value = TestEnum.stale_flag_one.isEnabled || v2 ? 2 : 3
var value2 = placeholder_false ? 2 : 3
var value3 = placeholder_false ? 2 : nil
var value4 = !placeholder_false
?
nil
: 2
}

func checkIfBooleanWithComments(){
Expand Down

0 comments on commit d984013

Please sign in to comment.