@@ -25,53 +25,35 @@ fileprivate let knownIntTypes = Set(intSizes.map { "Int\($0)" } + intSizes.map {
2525/// Lint: If an initializer-style cast is used on a built-in type known to be expressible by
2626/// that kind of literal type, a lint error is raised.
2727///
28- /// Format: Initializer-style casts between known built-in types will be converted to standard
29- /// casts.
30- ///
3128/// - SeeAlso: https://google.github.io/swift#numeric-and-string-literals
32- public final class AvoidInitializersForLiterals : SyntaxFormatRule {
33- public override func visit( _ node: FunctionCallExprSyntax ) -> ExprSyntax {
29+ public final class AvoidInitializersForLiterals : SyntaxLintRule {
30+ public override func visit( _ node: FunctionCallExprSyntax ) {
3431 // Ensure we're calling a known Integer initializer.
3532 guard let callee = node. calledExpression as? IdentifierExprSyntax else {
3633 // Ensure we properly visit the children of this node, in case we have other function calls
3734 // as parameters to this one.
3835 return super. visit ( node)
3936 }
4037
41- let typeName = callee. identifier. text
42-
43- guard let literal = extractLiteral ( node, typeName) else {
38+ guard node. argumentList. count == 1 else {
4439 return super. visit ( node)
4540 }
4641
47- diagnose ( . avoidInitializerStyleCast, on: callee) {
48- $0. highlight ( callee. sourceRange ( in: self . context. fileURL) )
42+ for arg in node. argumentList {
43+ if arg. label != nil {
44+ return super. visit ( node)
45+ }
4946 }
5047
51- // Construct an 'as' cast, converting `X(y)` to `y as X`.
52- let asExpr = AsExprSyntax {
53- $0. useAsTok ( SyntaxFactory . makeAsKeyword (
54- trailingTrivia: . spaces( 1 )
55- ) )
56- $0. useTypeName (
57- SyntaxFactory . makeSimpleTypeIdentifier (
58- name: callee. identifier,
59- genericArgumentClause: nil
60- )
61- )
62- }
48+ let typeName = callee. identifier. text
6349
64- let newLiteral = replaceTrivia (
65- on: literal,
66- token: literal. firstToken,
67- trailingTrivia: . spaces( 1 )
68- ) as! ExprSyntax
50+ guard let _ = extractLiteral ( node, typeName) else {
51+ return super. visit ( node)
52+ }
6953
70- return SyntaxFactory . makeSequenceExpr (
71- elements: SyntaxFactory . makeExprList ( [
72- newLiteral,
73- asExpr,
74- ] ) )
54+ diagnose ( . avoidInitializerStyleCast( node. description) , on: callee) {
55+ $0. highlight ( callee. sourceRange ( in: self . context. fileURL) )
56+ }
7557 }
7658}
7759
@@ -89,6 +71,7 @@ fileprivate func extractLiteral(_ node: FunctionCallExprSyntax, _ typeName: Stri
8971}
9072
9173extension Diagnostic . Message {
92- static let avoidInitializerStyleCast =
93- Diagnostic . Message ( . warning, " change initializer call with literal argument to an 'as' cast " )
74+ static func avoidInitializerStyleCast( _ name: String ) -> Diagnostic . Message {
75+ return . init( . warning, " change initializer call ' \( name) ' with literal argument to an 'as' cast " )
76+ }
9477}
0 commit comments