Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse the TargetResolver from assemblies #94

Merged
merged 4 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Example/KnitExample.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/usr/bin/xcrun --sdk macosx swift run knit gen \\\n--assembly-input-path KnitExample/KnitExampleAssembly.swift \\\n--assembly-input-path KnitExample/KnitExampleUserAssembly.swift \\\n--type-safety-extensions-output-path KnitExample/KnitDITypeSafety.swift \\\n--unit-test-output-path KnitExampleTests/KnitDIRegistrationTests.swift\n";
shellScript = "/usr/bin/xcrun --sdk macosx swift run knit-cli gen \\\n--assembly-input-path KnitExample/KnitExampleAssembly.swift \\\n--assembly-input-path KnitExample/KnitExampleUserAssembly.swift \\\n--type-safety-extensions-output-path KnitExample/KnitDITypeSafety.swift \\\n--unit-test-output-path KnitExampleTests/KnitDIRegistrationTests.swift\n";
};
/* End PBXShellScriptBuildPhase section */

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-syntax.git",
"state" : {
"revision" : "2c49d66d34dfd6f8130afdba889de77504b58ec0",
"version" : "508.0.1"
"revision" : "6ad4ea24b01559dde0773e3d091f1b9e36175036",
"version" : "509.0.2"
}
},
{
Expand Down
42 changes: 38 additions & 4 deletions Sources/KnitCodeGen/AssemblyParsing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import Foundation
import SwiftSyntax
import SwiftParser

public func parseAssemblies(at paths: [String]) throws -> ConfigurationSet {
public func parseAssemblies(
at paths: [String],
defaultTargetResolver: String,
useTargetResolver: Bool
) throws -> ConfigurationSet {
var configs = [Configuration]()
for path in paths {
let url = URL(fileURLWithPath: path, isDirectory: false)
Expand All @@ -15,7 +19,12 @@ public func parseAssemblies(at paths: [String]) throws -> ConfigurationSet {
throw AssemblyParsingError.fileReadError(error, path: path)
}
let syntaxTree = Parser.parse(source: source)
let configuration = try parseSyntaxTree(syntaxTree, errorsToPrint: &errorsToPrint)
let configuration = try parseSyntaxTree(
syntaxTree,
errorsToPrint: &errorsToPrint,
defaultTargetResolver: defaultTargetResolver,
useTargetResolver: useTargetResolver
)
configs.append(configuration)
printErrors(errorsToPrint, filePath: path, syntaxTree: syntaxTree)
}
Expand All @@ -24,7 +33,9 @@ public func parseAssemblies(at paths: [String]) throws -> ConfigurationSet {

func parseSyntaxTree(
_ syntaxTree: SyntaxProtocol,
errorsToPrint: inout [Error]
errorsToPrint: inout [Error],
defaultTargetResolver: String,
useTargetResolver: Bool
) throws -> Configuration {
let assemblyFileVisitor = AssemblyFileVisitor()
assemblyFileVisitor.walk(syntaxTree)
Expand All @@ -36,11 +47,19 @@ func parseSyntaxTree(
errorsToPrint.append(contentsOf: assemblyFileVisitor.assemblyErrors)
errorsToPrint.append(contentsOf: assemblyFileVisitor.registrationErrors)

let targetResolver: String
if useTargetResolver {
targetResolver = assemblyFileVisitor.targetResolver ?? defaultTargetResolver
} else {
targetResolver = defaultTargetResolver
}

return Configuration(
name: name,
registrations: assemblyFileVisitor.registrations,
registrationsIntoCollections: assemblyFileVisitor.registrationsIntoCollections,
imports: assemblyFileVisitor.imports
imports: assemblyFileVisitor.imports,
targetResolver: targetResolver
)
}

Expand All @@ -67,6 +86,10 @@ private class AssemblyFileVisitor: SyntaxVisitor {
return classDeclVisitor?.registrationErrors ?? []
}

var targetResolver: String? {
return classDeclVisitor?.targetResolver
}

init() {
super.init(viewMode: .fixedUp)
}
Expand Down Expand Up @@ -116,6 +139,8 @@ private class ClassDeclVisitor: SyntaxVisitor {

private(set) var registrationErrors = [Error]()

private(set) var targetResolver: String?

init(viewMode: SyntaxTreeViewMode, directives: KnitDirectives) {
self.directives = directives
super.init(viewMode: viewMode)
Expand All @@ -138,6 +163,15 @@ private class ClassDeclVisitor: SyntaxVisitor {
return .skipChildren
}

override func visit(_ node: TypeAliasDeclSyntax) -> SyntaxVisitorContinueKind {
if node.name.text == "TargetResolver",
let identifier = node.initializer.value.as(IdentifierTypeSyntax.self) {
self.targetResolver = identifier.name.text
}

return .skipChildren
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just as a curiosity I wonder if it is possible for TypeAliasDecl nodes to have child nodes 🤔

}

}

extension NamedDeclSyntax {
Expand Down
7 changes: 5 additions & 2 deletions Sources/KnitCodeGen/Configuration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,20 @@ public struct Configuration: Encodable {
public var registrationsIntoCollections: [RegistrationIntoCollection]

public var imports: [ImportDeclSyntax] = []
public var targetResolver: String

public init(
name: String,
registrations: [Registration],
registrationsIntoCollections: [RegistrationIntoCollection],
imports: [ImportDeclSyntax] = []
imports: [ImportDeclSyntax] = [],
targetResolver: String
) {
self.name = name
self.registrations = registrations
self.registrationsIntoCollections = registrationsIntoCollections
self.imports = imports
self.targetResolver = targetResolver
}

public enum CodingKeys: CodingKey {
Expand All @@ -35,7 +38,7 @@ public extension Configuration {
func makeTypeSafetySourceFile() throws -> SourceFileSyntax {
return try TypeSafetySourceFile.make(
assemblyName: "\(name)Assembly",
extensionTarget: "Resolver",
extensionTarget: targetResolver,
registrations: registrations
)
}
Expand Down
13 changes: 12 additions & 1 deletion Sources/KnitCommand/GenCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,23 @@ struct GenCommand: ParsableCommand {
""")
var jsonDataOutputPath: String?

// This flag was added to allow backwards compatibility. This may prove to be unnecessary.
@Flag(help: "When parsing assembly files, generate type safe methods against the target resolver")
var useTargetResolver: Bool = false

@Option(help: "Default type to extend when generating Resolver type safety methods")
var defaultExtensionTargetResolver = "Resolver"

public init() {}

public func run() throws {
let parsedConfig: ConfigurationSet
do {
parsedConfig = try parseAssemblies(at: assemblyInputPath)
parsedConfig = try parseAssemblies(
at: assemblyInputPath,
defaultTargetResolver: defaultExtensionTargetResolver,
useTargetResolver: useTargetResolver
)
if let jsonDataOutputPath {
let data = try JSONEncoder().encode(parsedConfig.assemblies)
try data.write(to: URL(fileURLWithPath: jsonDataOutputPath))
Expand Down
33 changes: 32 additions & 1 deletion Tests/KnitCodeGenTests/AssemblyParsingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ final class AssemblyParsingTests: XCTestCase {

let config = try assertParsesSyntaxTree(sourceFile)
XCTAssertEqual(config.name, "Example")
XCTAssertEqual(config.targetResolver, "Resolver")
XCTAssertEqual(
config.registrations,
[
Expand Down Expand Up @@ -244,17 +245,47 @@ final class AssemblyParsingTests: XCTestCase {
)
}

func testCustomResolver() throws {
let sourceFile: SourceFileSyntax = """
class MyAssembly: Assembly {
typealias TargetResolver = TestResolver
}
"""

let config = try assertParsesSyntaxTree(sourceFile)
XCTAssertEqual(config.name, "My")
XCTAssertEqual(config.targetResolver, "TestResolver")
}

func testCustomResolverWhenDisabled() throws {
let sourceFile: SourceFileSyntax = """
class MyAssembly: Assembly {
typealias TargetResolver = TestResolver
}
"""

let config = try assertParsesSyntaxTree(sourceFile, useTargetResolver: false)
XCTAssertEqual(config.name, "My")
XCTAssertEqual(config.targetResolver, "Resolver")
}

}

private func assertParsesSyntaxTree(
_ sourceFile: SourceFileSyntax,
assertErrorsToPrint assertErrorsCallback: (([Error]) -> Void)? = nil,
useTargetResolver: Bool = true,
file: StaticString = #filePath,
line: UInt = #line
) throws -> Configuration {
var errorsToPrint = [Error]()

let configuration = try parseSyntaxTree(sourceFile, errorsToPrint: &errorsToPrint)
let configuration = try parseSyntaxTree(
sourceFile,
errorsToPrint: &errorsToPrint,
defaultTargetResolver: "Resolver",
useTargetResolver: useTargetResolver
)

if let assertErrorsCallback {
assertErrorsCallback(errorsToPrint)
Expand Down
9 changes: 6 additions & 3 deletions Tests/KnitCodeGenTests/ConfigurationSetTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ private enum Factory {
],
imports: [
.init(moduleName: "Dependency1")
]
],
targetResolver: "Resolver"
)

static let config2 = Configuration(
Expand All @@ -160,7 +161,8 @@ private enum Factory {
registrationsIntoCollections: [],
imports: [
.init(moduleName: "Dependency2")
]
],
targetResolver: "Resolver"
)

static let config3 = Configuration(
Expand All @@ -171,6 +173,7 @@ private enum Factory {
registrationsIntoCollections: [],
imports: [
.init(moduleName: "Dependency2")
]
],
targetResolver: "Resolver"
)
}
3 changes: 2 additions & 1 deletion Tests/KnitCodeGenTests/UnitTestSourceFileTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ private extension UnitTestSourceFile {
name: name,
registrations: registrations,
registrationsIntoCollections: registrationsIntoCollections,
imports: importDecls
imports: importDecls,
targetResolver: "Resolver"
)
return try UnitTestSourceFile.make(configuration: configuration)
}
Expand Down