|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import SwiftSyntax |
| 14 | + |
| 15 | +/// Single-expression functions, closures, subscripts can omit `return` statement. |
| 16 | +/// |
| 17 | +/// Lint: `func <name>() { return ... }` and similar single expression constructs will yield a lint error. |
| 18 | +/// |
| 19 | +/// Format: `func <name>() { return ... }` constructs will be replaced with |
| 20 | +/// equivalent `func <name>() { ... }` constructs. |
| 21 | +@_spi(Rules) |
| 22 | +public final class OmitReturns: SyntaxFormatRule { |
| 23 | + public override class var isOptIn: Bool { return true } |
| 24 | + |
| 25 | + public override func visit(_ node: FunctionDeclSyntax) -> DeclSyntax { |
| 26 | + let decl = super.visit(node) |
| 27 | + |
| 28 | + // func <name>() -> <Type> { return ... } |
| 29 | + if var funcDecl = decl.as(FunctionDeclSyntax.self), |
| 30 | + let body = funcDecl.body, |
| 31 | + let `return` = containsSingleReturn(body.statements) { |
| 32 | + funcDecl.body?.statements = unwrapReturnStmt(`return`) |
| 33 | + diagnose(.omitReturnStatement, on: `return`, severity: .refactoring) |
| 34 | + return DeclSyntax(funcDecl) |
| 35 | + } |
| 36 | + |
| 37 | + return decl |
| 38 | + } |
| 39 | + |
| 40 | + private func containsSingleReturn(_ body: CodeBlockItemListSyntax) -> ReturnStmtSyntax? { |
| 41 | + if let element = body.firstAndOnly?.as(CodeBlockItemSyntax.self), |
| 42 | + let ret = element.item.as(ReturnStmtSyntax.self), |
| 43 | + !ret.children(viewMode: .all).isEmpty, ret.expression != nil { |
| 44 | + return ret |
| 45 | + } |
| 46 | + |
| 47 | + return nil |
| 48 | + } |
| 49 | + |
| 50 | + private func unwrapReturnStmt(_ `return`: ReturnStmtSyntax) -> CodeBlockItemListSyntax { |
| 51 | + CodeBlockItemListSyntax([ |
| 52 | + CodeBlockItemSyntax( |
| 53 | + leadingTrivia: `return`.leadingTrivia, |
| 54 | + item: .expr(`return`.expression!), |
| 55 | + semicolon: nil, |
| 56 | + trailingTrivia: `return`.trailingTrivia) |
| 57 | + ]) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +extension Finding.Message { |
| 62 | + public static let omitReturnStatement: Finding.Message = |
| 63 | + "`return` can be omitted because body consists of a single expression" |
| 64 | +} |
0 commit comments