Skip to content

Commit

Permalink
add: recursive function to find FunctionDeclSyntax
Browse files Browse the repository at this point in the history
  • Loading branch information
u-abyss committed Sep 12, 2024
1 parent 337358f commit af9a0ca
Showing 1 changed file with 38 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,20 @@ struct VoidFunctionInTernaryConditionRule: Rule {
return hoge
}
"""),
Example("""
func exampleNestedIfExpr() -> String {
if true {
if true {
isTrue ↓? defaultValue() : defaultValue()
} else {
return "False"
}
} else {
return "Default"
}
return hoge
}
"""),
]
)
}
Expand Down Expand Up @@ -263,20 +277,35 @@ private extension CodeBlockItemSyntax {

return parent.children(viewMode: .sourceAccurate).count == 1
}

var isIfExprImplicitReturn: Bool {
guard let parent = parent?.as(CodeBlockItemListSyntax.self),
let ifExprSytax = parent.parent?.parent?.as(IfExprSyntax.self) else {
return false

func getFunctionDeclSyntax(parent: CodeBlockItemListSyntax) -> FunctionDeclSyntax? {
let targetSyntax = parent.parent?.parent
if let targetSyntax = targetSyntax?.as(FunctionDeclSyntax.self) {
return targetSyntax
}
if let ifExprSyntax = targetSyntax?.as(IfExprSyntax.self) {
guard let codeBlockItemListSyntax = ifExprSyntax.parent?.parent?.parent?.as(CodeBlockItemListSyntax.self) else {
return nil
}
guard let funcDecl = ifExprSytax.parent?.parent?.parent?.parent?.parent?.as(FunctionDeclSyntax.self) else {
return false
return getFunctionDeclSyntax(parent: codeBlockItemListSyntax)
}
if let swichExprSyntax = targetSyntax?.parent?.as(SwitchExprSyntax.self) {
guard let codeBlockItemListSyntax = swichExprSyntax.parent?.parent?.parent?.as(CodeBlockItemListSyntax.self) else {
return nil
}
if let codeBlockItemListSyntax = ifExprSytax.parent?.parent?.parent?.as(CodeBlockItemListSyntax.self),
return getFunctionDeclSyntax(parent: codeBlockItemListSyntax)
}
return nil
}

var isIfExprImplicitReturn: Bool {
guard let parent = parent?.as(CodeBlockItemListSyntax.self) else { return false }
guard let result = getFunctionDeclSyntax(parent: parent) else { return false }
if let codeBlockItemListSyntax = result.body?.statements,
let expressionStmtSyntax = codeBlockItemListSyntax.last?.item.as(ExpressionStmtSyntax.self) {
return parent.children(viewMode: .sourceAccurate).count == 1 &&
( codeBlockItemListSyntax.count == 1 || expressionStmtSyntax.expression.is(IfExprSyntax.self)) &&
funcDecl.signature.allowsImplicitReturns
result.signature.allowsImplicitReturns
}
return false
}
Expand Down

0 comments on commit af9a0ca

Please sign in to comment.