Skip to content

Commit 1687304

Browse files
committed
Add import declaration builder
1 parent e8f2d02 commit 1687304

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2019 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+
public struct Import: DeclBuildable {
16+
let moduleName: String
17+
18+
public init(_ moduleName: String) {
19+
self.moduleName = moduleName
20+
}
21+
22+
public func buildDecl(format: Format, leadingTrivia: Trivia) -> DeclSyntax {
23+
let importToken = Tokens.import.withLeadingTrivia(leadingTrivia + format.makeIndent())
24+
let moduleNameToken = SyntaxFactory.makeIdentifier(moduleName)
25+
26+
return ImportDeclSyntax {
27+
$0.useImportTok(importToken)
28+
$0.addPathComponent(AccessPathComponentSyntax {
29+
$0.useName(moduleNameToken)
30+
})
31+
}
32+
}
33+
}

Sources/SwiftSyntaxBuilder/Tokens/Tokens.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ enum Tokens {
2222
/// `"var "`
2323
static let `var` = SyntaxFactory.makeVarKeyword().withTrailingTrivia(.spaces(1))
2424

25+
/// `"import "`
26+
static let `import` = SyntaxFactory.makeImportKeyword().withTrailingTrivia(.spaces(1))
27+
2528
/// `"struct "`
2629
static let `struct` = SyntaxFactory.makeStructKeyword().withTrailingTrivia(.spaces(1))
2730

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import XCTest
2+
import SwiftSyntax
3+
4+
@testable import SwiftSyntaxBuilder
5+
6+
final class ImportTests: XCTestCase {
7+
func testImport() {
8+
let format = Format(indentWidth: 2).indented()
9+
10+
let testCases: [UInt: (Import, String)] = [
11+
#line: (Import("SwiftSyntax"),
12+
" import SwiftSyntax"),
13+
]
14+
15+
for (line, testCase) in testCases {
16+
let (builder, expected) = testCase
17+
let syntax = builder.buildSyntax(format: format, leadingTrivia: .zero)
18+
19+
var text = ""
20+
syntax.write(to: &text)
21+
22+
XCTAssertEqual(text, expected, line: line)
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)