#swiftlint #Swift #开源库 SwiftLint 是一个用于检测 Swift 代码风格和一致性的开源工具。它能够自动化实现代码规范、保证代码风格的统一性,避免因为代码风格不同带来的维护问题,同时也能够提供一些代码质量上的反馈,帮助程序员编写更加规范、优雅的 Swift 代码。本文参考 Release 0.52.4: Lid Switch · realm/SwiftLint
extension ArrayInitRule {
private final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: FunctionCallExprSyntax) {
guard let memberAccess = node.calledExpression.as(MemberAccessExprSyntax.self),
memberAccess.name.text == "map",
let (closureParam, closureStatement) = node.singleClosure(),
closureStatement.returnsInput(closureParam)
else {
return
}
violations.append(memberAccess.name.positionAfterSkippingLeadingTrivia)
}
}
}
2.3 ViolationsSyntaxVisitor / SyntaxVisitor
/// A SwiftSyntax `SyntaxVisitor` that produces absolute positions where violations should be reported.
open class ViolationsSyntaxVisitor: SyntaxVisitor {
/// 收集的违规对象
public var violations: [ReasonedRuleViolation] = []
/// 需要跳过的声明语法节点
open var skippableDeclarations: [DeclSyntaxProtocol.Type] { [] }
/// 执行语法树遍历,并返回违规对象
func walk<T, SyntaxType: SyntaxProtocol>(tree: SyntaxType, handler: (Self) -> T) -> T
}
/// Swift-Syntax 中定义的语法树遍历器
open class SyntaxVisitor {
public let viewMode: SyntaxTreeViewMode
/// 执行对传入语法树的遍历
public func walk<SyntaxType: SyntaxProtocol>(_ node: SyntaxType)
/// 访问某个语法节点前调用
open func visit(_ node: T) -> SyntaxVisitorContinueKind
/// 访问语法节点之后调用
open func visitPost(_ node: T)
}
/// A Syntax node represents a tree of nodes with tokens at the leaves.
/// Each node has accessors for its known children, and allows efficient
/// iteration over the children through its `children` property.
public struct Syntax: SyntaxProtocol, SyntaxHashable {
let data: SyntaxData
public var _syntaxNode: Syntax {
return self
}
/// 节点类型
public var kind: SyntaxKind {
return raw.kind
}
/// 字节点
func children(viewMode: SyntaxTreeViewMode) -> SyntaxChildren {
return SyntaxChildren(_syntaxNode, viewMode: viewMode)
}
/// 父节点
var parent: Syntax? {
return data.parent.map(Syntax.init(_:))
}
}
/// 语法节点类型
public enum SyntaxKind {
case token
case accessPathComponent
case accessPath
case accessesEffect
case accessorBlock
case accessorDecl
case accessorEffectSpecifiers
case accessorInitEffects
case accessorList
case accessorParameter
case actorDecl
case arrayElementList
case arrayElement
case arrayExpr
case arrayType
case arrowExpr
case asExpr
case assignmentExpr
case associatedtypeDecl
case attributeList
case attribute
case attributedType
case availabilityArgument
case availabilityCondition
......
}
/// 变量声明 语法
public struct VariableDeclSyntax: DeclSyntaxProtocol, SyntaxHashable {
/// 获取 属性 @objc
public var attributes: AttributeListSyntax?
/// 获取修饰符 public lazy 等
public var modifiers: ModifierListSyntax?
....
}