Skip to content

Commit

Permalink
Not to add computed property into initialisor
Browse files Browse the repository at this point in the history
  • Loading branch information
ShenghaiWang committed Dec 20, 2023
1 parent bc210ec commit dc0db4c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
6 changes: 4 additions & 2 deletions Sources/Macros/AddInit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ public struct AddInit: MemberMacro {
if let patternBinding = member.decl.as(VariableDeclSyntax.self)?.bindings
.as(PatternBindingListSyntax.self)?.first?.as(PatternBindingSyntax.self),
let identifier = patternBinding.pattern.as(IdentifierPatternSyntax.self)?.identifier,
let type = patternBinding.typeAnnotation?.as(TypeAnnotationSyntax.self)?.type {
let type = patternBinding.typeAnnotation?.as(TypeAnnotationSyntax.self)?.type,
patternBinding.accessorBlock == nil {
var parameter = "\(identifier): "
if type.is(FunctionTypeSyntax.self) {
parameter += "@escaping "
Expand All @@ -57,7 +58,8 @@ public struct AddInit: MemberMacro {
guard let patternBinding = member.decl.as(VariableDeclSyntax.self)?.bindings
.as(PatternBindingListSyntax.self)?.first?.as(PatternBindingSyntax.self),
let identifier = patternBinding.pattern.as(IdentifierPatternSyntax.self)?.identifier,
let type = patternBinding.typeAnnotation?.as(TypeAnnotationSyntax.self)?.type else { return nil }
let type = patternBinding.typeAnnotation?.as(TypeAnnotationSyntax.self)?.type,
patternBinding.accessorBlock == nil else { return nil }
let mockValue = type.mockValue(randomValue: randomValue)
?? type.as(OptionalTypeSyntax.self)?.mockValue(randomValue: randomValue)
?? "nil"
Expand Down
29 changes: 29 additions & 0 deletions Tests/MacroTests/AddInitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,35 @@ final class AddInitTests: XCTestCase {
)
}

func testAddInitWithComputedPropertyMacro() {
assertMacroExpansion(
"""
@AddInit
struct A {
let a: Int?
var b: Int {
0
}
}
""",
expandedSource:
"""
struct A {
let a: Int?
var b: Int {
0
}
init(a: Int? = nil) {
self.a = a
}
}
""",
macros: testMacros
)
}

func testAddPublicInitMacro() {
assertMacroExpansion(
"""
Expand Down

0 comments on commit dc0db4c

Please sign in to comment.