Skip to content

Remove @testable import and -enable-testing #137

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

Merged
merged 9 commits into from
Aug 9, 2019
4 changes: 2 additions & 2 deletions Sources/LanguageServerProtocol/TextEdit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@
public struct TextEdit: ResponseType, Hashable {

/// The range of text to be replaced.
var range: PositionRange
public var range: PositionRange

/// The new text.
var newText: String
public var newText: String

public init(range: Range<Position>, newText: String) {
self.range = PositionRange(range)
Expand Down
37 changes: 19 additions & 18 deletions Sources/LanguageServerProtocolJSONRPC/JSONRPCConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ public final class JSONRPCConection {
/// Current state of the connection, used to ensure correct usage.
var state: State

/// Buffer of received bytes that haven't been parsed.
var requestBuffer: [UInt8] = []
/// *Public for testing* Buffer of received bytes that haven't been parsed.
public var _requestBuffer: [UInt8] = []

private var _nextRequestID: Int = 0

Expand Down Expand Up @@ -103,19 +103,19 @@ public final class JSONRPCConection {
}

// Parse and handle any messages in `buffer + data`, leaving any remaining unparsed bytes in `buffer`.
if self.requestBuffer.isEmpty {
if self._requestBuffer.isEmpty {
data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in
let rest = self.parseAndHandleMessages(from: UnsafeBufferPointer(start: pointer, count: data.count))
self.requestBuffer.append(contentsOf: rest)
self._requestBuffer.append(contentsOf: rest)
}
} else {
self.requestBuffer.append(contentsOf: data)
self._requestBuffer.append(contentsOf: data)
var unused = 0
self.requestBuffer.withUnsafeBufferPointer { buffer in
self._requestBuffer.withUnsafeBufferPointer { buffer in
let rest = self.parseAndHandleMessages(from: buffer)
unused = rest.count
}
self.requestBuffer.removeFirst(self.requestBuffer.count - unused)
self._requestBuffer.removeFirst(self._requestBuffer.count - unused)
}
}
}
Expand Down Expand Up @@ -144,19 +144,19 @@ public final class JSONRPCConection {
return nil
}
return outstanding.responseType
} as Message.ResponseTypeCallback
} as JSONRPCMessage.ResponseTypeCallback

var bytes = bytes[...]

MESSAGE_LOOP: while true {
do {
guard let ((messageBytes, _), rest) = try bytes.splitMessage() else {
guard let ((messageBytes, _), rest) = try bytes.jsonrpcSplitMessage() else {
return bytes
}
bytes = rest

let pointer = UnsafeMutableRawPointer(mutating: UnsafeBufferPointer(rebasing: messageBytes).baseAddress!)
let message = try decoder.decode(Message.self, from: Data(bytesNoCopy: pointer, count: messageBytes.count, deallocator: .none))
let message = try decoder.decode(JSONRPCMessage.self, from: Data(bytesNoCopy: pointer, count: messageBytes.count, deallocator: .none))

handle(message)

Expand All @@ -166,7 +166,7 @@ public final class JSONRPCConection {
case .request:
if let id = error.id {
send { encoder in
try encoder.encode(Message.errorResponse(ResponseError(error), id: id))
try encoder.encode(JSONRPCMessage.errorResponse(ResponseError(error), id: id))
}
continue MESSAGE_LOOP
}
Expand Down Expand Up @@ -198,7 +198,7 @@ public final class JSONRPCConection {
}

/// Handle a single message by dispatching it to `receiveHandler` or an appropriate reply handler.
func handle(_ message: Message) {
func handle(_ message: JSONRPCMessage) {
switch message {
case .notification(let notification):
notification._handle(receiveHandler!, connection: self)
Expand All @@ -219,7 +219,8 @@ public final class JSONRPCConection {
}
}

func send(rawData dispatchData: DispatchData) {
/// *Public for testing*.
public func send(_rawData dispatchData: DispatchData) {
guard readyToSend() else { return }

sendIO.write(offset: 0, data: dispatchData, queue: sendQueue) { [weak self] done, _, errorCode in
Expand All @@ -243,7 +244,7 @@ public final class JSONRPCConection {
dispatchData.append(rawBufferPointer)
}

send(rawData: dispatchData)
send(_rawData: dispatchData)
}

func send(encoding: (JSONEncoder) throws -> Data) {
Expand Down Expand Up @@ -289,7 +290,7 @@ extension JSONRPCConection: _IndirectConnection {
public func send<Notification>(_ notification: Notification) where Notification: NotificationType {
guard readyToSend() else { return }
send { encoder in
return try encoder.encode(Message.notification(notification))
return try encoder.encode(JSONRPCMessage.notification(notification))
}
}

Expand All @@ -316,7 +317,7 @@ extension JSONRPCConection: _IndirectConnection {
}

send { encoder in
return try encoder.encode(Message.request(request, id: id))
return try encoder.encode(JSONRPCMessage.request(request, id: id))
}

return id
Expand All @@ -328,9 +329,9 @@ extension JSONRPCConection: _IndirectConnection {
send { encoder in
switch response {
case .success(let result):
return try encoder.encode(Message.response(result, id: id))
return try encoder.encode(JSONRPCMessage.response(result, id: id))
case .failure(let error):
return try encoder.encode(Message.errorResponse(error, id: id))
return try encoder.encode(JSONRPCMessage.errorResponse(error, id: id))
}
}
}
Expand Down
11 changes: 6 additions & 5 deletions Sources/LanguageServerProtocolJSONRPC/MessageCoding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@

import LanguageServerProtocol

enum Message {
/// *Public For Testing*. A single JSONRPC message suitable for encoding/decoding.
public enum JSONRPCMessage {
case notification(NotificationType)
case request(_RequestType, id: RequestID)
case response(ResponseType, id: RequestID)
Expand All @@ -23,11 +24,11 @@ extension CodingUserInfoKey {
public static let responseTypeCallbackKey: CodingUserInfoKey = CodingUserInfoKey(rawValue: "lsp.jsonrpc.responseTypeCallback")!
}

extension Message: Codable {
extension JSONRPCMessage: Codable {

typealias ResponseTypeCallback = (RequestID) -> ResponseType.Type?
public typealias ResponseTypeCallback = (RequestID) -> ResponseType.Type?

public enum CodingKeys: String, CodingKey {
private enum CodingKeys: String, CodingKey {
case jsonrpc
case method
case id
Expand Down Expand Up @@ -120,7 +121,7 @@ extension Message: Codable {
}
}

func encode(to encoder: Encoder) throws {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode("2.0", forKey: .jsonrpc)

Expand Down
36 changes: 21 additions & 15 deletions Sources/LanguageServerProtocolJSONRPC/MessageSplitting.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,37 +13,43 @@
import LanguageServerProtocol
import SKSupport

struct MessageHeader: Hashable {
public struct JSONRPCMessageHeader: Hashable {
static let contentLengthKey: [UInt8] = [UInt8]("Content-Length".utf8)
static let separator: [UInt8] = [UInt8]("\r\n".utf8)
static let colon: UInt8 = ":".utf8.spm_only!
static let invalidKeyBytes: [UInt8] = [colon] + separator

var contentLength: Int? = nil
public var contentLength: Int? = nil

public init(contentLength: Int? = nil) {
self.contentLength = contentLength
}
}

extension RandomAccessCollection where Element == UInt8 {

/// Returns the first message range and header in `self`, or nil.
func splitMessage() throws -> ((SubSequence, header: MessageHeader), SubSequence)? {
guard let (header, rest) = try parseHeader() else { return nil }
public func jsonrpcSplitMessage()
throws -> ((SubSequence, header: JSONRPCMessageHeader), SubSequence)?
{
guard let (header, rest) = try jsonrcpParseHeader() else { return nil }
guard let contentLength = header.contentLength else {
throw MessageDecodingError.parseError("missing Content-Length header")
}
if contentLength > rest.count { return nil }
return ((rest.prefix(contentLength), header: header), rest.dropFirst(contentLength))
}

func parseHeader() throws -> (MessageHeader, SubSequence)? {
var header = MessageHeader()
public func jsonrcpParseHeader() throws -> (JSONRPCMessageHeader, SubSequence)? {
var header = JSONRPCMessageHeader()
var slice = self[...]
while let (kv, rest) = try slice.parseHeaderField() {
while let (kv, rest) = try slice.jsonrpcParseHeaderField() {
guard let (key, value) = kv else {
return (header, rest)
}
slice = rest

if key.elementsEqual(MessageHeader.contentLengthKey) {
if key.elementsEqual(JSONRPCMessageHeader.contentLengthKey) {
guard let count = Int(ascii: value) else {
throw MessageDecodingError.parseError("expected integer value in \(String(bytes: value, encoding: .utf8) ?? "<invalid>")")
}
Expand All @@ -55,21 +61,21 @@ extension RandomAccessCollection where Element == UInt8 {
return nil
}

func parseHeaderField() throws -> ((key: SubSequence, value: SubSequence)?, SubSequence)? {
if starts(with: MessageHeader.separator) {
return (nil, dropFirst(MessageHeader.separator.count))
} else if first == MessageHeader.separator.first {
public func jsonrpcParseHeaderField() throws -> ((key: SubSequence, value: SubSequence)?, SubSequence)? {
if starts(with: JSONRPCMessageHeader.separator) {
return (nil, dropFirst(JSONRPCMessageHeader.separator.count))
} else if first == JSONRPCMessageHeader.separator.first {
return nil
}

guard let keyEnd = firstIndex(where: { MessageHeader.invalidKeyBytes.contains($0) }) else {
guard let keyEnd = firstIndex(where: { JSONRPCMessageHeader.invalidKeyBytes.contains($0) }) else {
return nil
}
if self[keyEnd] != MessageHeader.colon {
if self[keyEnd] != JSONRPCMessageHeader.colon {
throw MessageDecodingError.parseError("expected ':' in message header")
}
let valueStart = index(after:keyEnd)
guard let valueEnd = self[valueStart...].firstIndex(of: MessageHeader.separator) else {
guard let valueEnd = self[valueStart...].firstIndex(of: JSONRPCMessageHeader.separator) else {
return nil
}

Expand Down
7 changes: 7 additions & 0 deletions Sources/SKCore/CompilationDatabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ public struct CompilationDatabaseCompileCommand: Equatable {

/// The name of the build output, or nil.
public var output: String? = nil

public init(directory: String, filename: String, commandLine: [String], output: String? = nil) {
self.directory = directory
self.filename = filename
self.commandLine = commandLine
self.output = output
}
}

extension CompilationDatabase.Command {
Expand Down
4 changes: 3 additions & 1 deletion Sources/SKCore/FallbackBuildSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ import enum SPMUtility.Platform
/// A simple BuildSystem suitable as a fallback when accurate settings are unknown.
public final class FallbackBuildSystem: BuildSystem {

public init() {}

/// The path to the SDK.
lazy var sdkpath: AbsolutePath? = {
public lazy var sdkpath: AbsolutePath? = {
if case .darwin? = Platform.currentPlatform,
let str = try? Process.checkNonZeroExit(
args: "/usr/bin/xcrun", "--show-sdk-path", "--sdk", "macosx"),
Expand Down
4 changes: 2 additions & 2 deletions Sources/SKCore/ToolchainRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public final class ToolchainRegistry {
var queue: DispatchQueue = DispatchQueue(label: "toolchain-registry-queue")

/// The currently selected toolchain identifier on Darwin.
public internal(set) lazy var darwinToolchainOverride: String? = {
public lazy var darwinToolchainOverride: String? = {
if let id = ProcessEnv.vars["TOOLCHAINS"], !id.isEmpty, id != "default" {
return id
}
Expand Down Expand Up @@ -151,7 +151,7 @@ extension ToolchainRegistry {

extension ToolchainRegistry {

enum Error: Swift.Error {
public enum Error: Swift.Error {

/// There is already a toolchain with the given identifier.
case duplicateToolchainIdentifier
Expand Down
15 changes: 10 additions & 5 deletions Sources/SKCore/XCToolchainPlist.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,18 @@ import Basic
import Foundation

/// A helper type for decoding the Info.plist or ToolchainInfo.plist file from an .xctoolchain.
struct XCToolchainPlist {
public struct XCToolchainPlist {

/// The toolchain identifer e.g. "com.apple.dt.toolchain.XcodeDefault".
var identifier: String
public var identifier: String

/// The toolchain's human-readable name.
var displayName: String?
public var displayName: String?

public init(identifier: String, displayName: String? = nil) {
self.identifier = identifier
self.displayName = displayName
}
}

extension XCToolchainPlist {
Expand Down Expand Up @@ -79,7 +84,7 @@ extension XCToolchainPlist: Codable {
case DisplayName
}

init(from decoder: Decoder) throws {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let identifier = try container.decodeIfPresent(String.self, forKey: .Identifier) {
self.identifier = identifier
Expand All @@ -90,7 +95,7 @@ extension XCToolchainPlist: Codable {
}

/// Encode the info plist. **For testing**.
func encode(to encoder: Encoder) throws {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if identifier.starts(with: "com.apple") {
try container.encode(identifier, forKey: .Identifier)
Expand Down
Loading