Skip to content

Add REPL support #43

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 2 commits into from
Dec 27, 2019
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
18 changes: 18 additions & 0 deletions Sources/SwiftDriver/Driver/Driver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,11 @@ extension Driver {
return
}

if jobs.contains(where: { $0.requiresInPlaceExecution }) {
assert(jobs.count == 1, "Cannot execute in place for multi-job build plans")
return try executeJobInPlace(jobs[0], resolver: resolver)
}

// Create and use the tool execution delegate if one is not provided explicitly.
let executorDelegate = executorDelegate ?? createToolExecutionDelegate()

Expand Down Expand Up @@ -606,6 +611,19 @@ extension Driver {

return ToolExecutionDelegate(mode: mode)
}

/// Execute a single job in-place.
private func executeJobInPlace(_ job: Job, resolver: ArgsResolver) throws {
let tool = try resolver.resolve(.path(job.tool))
let commandLine = try job.commandLine.map{ try resolver.resolve($0) }
let arguments = [tool] + commandLine

for (envVar, value) in job.extraEnvironment {
try ProcessEnv.setVar(envVar, value: value)
}

return try exec(path: tool, args: arguments)
}
}

extension Diagnostic.Message {
Expand Down
11 changes: 11 additions & 0 deletions Sources/SwiftDriver/Jobs/CompileJob.swift
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,17 @@ extension Array where Element == Job.ArgTemplate {
)
appendFlag(isTrue ? trueFlag : falseFlag)
}

var joinedArguments: String {
return self.map {
switch $0 {
case .flag(let string):
return string.spm_shellEscaped()
case .path(let path):
return path.name.spm_shellEscaped()
}
}.joined(separator: " ")
}
}


Expand Down
5 changes: 4 additions & 1 deletion Sources/SwiftDriver/Jobs/FrontendJobHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,10 @@ extension Driver {
commandLine.appendPath(importedObjCHeader)
}

commandLine.appendFlags("-module-name", moduleName)
// Repl Jobs may include -module-name depending on the selected REPL (LLDB or integrated).
if compilerMode != .repl {
commandLine.appendFlags("-module-name", moduleName)
}
}

mutating func addFrontendSupplementaryOutputArguments(commandLine: inout [Job.ArgTemplate], primaryInputs: [TypedVirtualPath]) throws -> [TypedVirtualPath] {
Expand Down
3 changes: 2 additions & 1 deletion Sources/SwiftDriver/Jobs/InterpretJob.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ extension Driver {
commandLine: commandLine,
inputs:inputs,
outputs: [],
extraEnvironment: extraEnvironment
extraEnvironment: extraEnvironment,
requiresInPlaceExecution: true
)
}
}
20 changes: 8 additions & 12 deletions Sources/SwiftDriver/Jobs/Job.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public struct Job: Codable, Equatable {
case autolinkExtract = "autolink-extract"
case emitModule = "emit-module"
case interpret
case repl
}

public enum ArgTemplate: Equatable {
Expand Down Expand Up @@ -49,6 +50,9 @@ public struct Job: Codable, Equatable {
/// Any extra environment variables which should be set while running the job.
public var extraEnvironment: [String: String]

/// Whether or not the job must be executed in place, replacing the current driver process.
public var requiresInPlaceExecution: Bool

/// The kind of job.
public var kind: Kind

Expand All @@ -59,7 +63,8 @@ public struct Job: Codable, Equatable {
displayInputs: [TypedVirtualPath]? = nil,
inputs: [TypedVirtualPath],
outputs: [TypedVirtualPath],
extraEnvironment: [String: String] = [:]
extraEnvironment: [String: String] = [:],
requiresInPlaceExecution: Bool = false
) {
self.kind = kind
self.tool = tool
Expand All @@ -68,22 +73,13 @@ public struct Job: Codable, Equatable {
self.inputs = inputs
self.outputs = outputs
self.extraEnvironment = extraEnvironment
self.requiresInPlaceExecution = requiresInPlaceExecution
}
}

extension Job: CustomStringConvertible {
public var description: String {
var result: String = tool.name

for arg in commandLine {
result += " "
switch arg {
case .flag(let string):
result += string.spm_shellEscaped()
case .path(let path):
result += path.name.spm_shellEscaped()
}
}
var result: String = "\(tool.name) \(commandLine.joinedArguments)"

if !self.extraEnvironment.isEmpty {
result += " #"
Expand Down
17 changes: 16 additions & 1 deletion Sources/SwiftDriver/Jobs/Planning.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

public enum PlanningError: Error, DiagnosticData {
case replReceivedInput

public var description: String {
switch self {
case .replReceivedInput:
return "REPL mode requires no input files"
}
}
}

/// Planning for builds
extension Driver {
/// Plan a standard compilation, which produces jobs for compiling separate
Expand Down Expand Up @@ -145,7 +157,10 @@ extension Driver {
// Plan the build.
switch compilerMode {
case .repl:
fatalError("Not yet supported")
if !inputFiles.isEmpty {
throw PlanningError.replReceivedInput
}
return [try replJob()]

case .immediate:
return [try interpretJob(inputs: inputFiles)]
Expand Down
52 changes: 52 additions & 0 deletions Sources/SwiftDriver/Jobs/ReplJob.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//===--------------- ReplJob.swift - Swift REPL ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

extension Driver {
mutating func replJob() throws -> Job {
var commandLine: [Job.ArgTemplate] = swiftCompilerPrefixArgs.map { Job.ArgTemplate.flag($0) }

try addCommonFrontendOptions(commandLine: &commandLine)
// FIXME: MSVC runtime flags

try commandLine.appendLast(.importObjcHeader, from: &parsedOptions)
try commandLine.appendAll(.l, .framework, .L, from: &parsedOptions)

// Look for -lldb-repl or -deprecated-integrated-repl to determine which
// REPL to use. If neither is provided, prefer LLDB if it can be found.
if parsedOptions.hasFlag(positive: .lldbRepl,
negative: .deprecatedIntegratedRepl,
default: (try? toolchain.getToolPath(.lldb)) != nil) {
// Squash important frontend options into a single argument for LLDB.
let lldbArg = "--repl=\(commandLine.joinedArguments)"
return Job(
kind: .repl,
tool: .absolute(try toolchain.getToolPath(.lldb)),
commandLine: [Job.ArgTemplate.flag(lldbArg)],
inputs: [],
outputs: [],
requiresInPlaceExecution: true
)
} else {
// Invoke the integrated REPL, which is part of the frontend.
commandLine = [.flag("-frontend"), .flag("-repl")] + commandLine
commandLine.appendFlags("-module-name", moduleName)
return Job(
kind: .repl,
tool: .absolute(try toolchain.getToolPath(.swiftCompiler)),
commandLine: commandLine,
inputs: [],
outputs: [],
requiresInPlaceExecution: true
)
}
}
}
2 changes: 2 additions & 0 deletions Sources/SwiftDriver/Toolchains/DarwinToolchain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ public final class DarwinToolchain: Toolchain {
return AbsolutePath(result)
case .swiftAutolinkExtract:
return try lookup(executable: "swift-autolink-extract")
case .lldb:
return try lookup(executable: "lldb")
}
}

Expand Down
2 changes: 2 additions & 0 deletions Sources/SwiftDriver/Toolchains/GenericUnixToolchain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public final class GenericUnixToolchain: Toolchain {
return try lookup(executable: "swift-autolink-extract")
case .dsymutil:
return try lookup(executable: "dsymutil")
case .lldb:
return try lookup(executable: "lldb")
}
}

Expand Down
1 change: 1 addition & 0 deletions Sources/SwiftDriver/Toolchains/Toolchain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public enum Tool {
case clang
case swiftAutolinkExtract
case dsymutil
case lldb
}

/// Describes a toolchain, which includes information about compilers, linkers
Expand Down
1 change: 1 addition & 0 deletions Sources/SwiftDriver/Utilities/Diagnostics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import TSCBasic

public typealias Diagnostic = TSCBasic.Diagnostic
public typealias DiagnosticData = TSCBasic.DiagnosticData

extension Diagnostic.Message {
static var error_static_emit_executable_disallowed: Diagnostic.Message {
Expand Down
66 changes: 66 additions & 0 deletions Tests/SwiftDriverTests/SwiftDriverTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -885,12 +885,76 @@ final class SwiftDriverTests: XCTestCase {

}

func testRepl() throws {

func isLLDBREPLFlag(_ arg: Job.ArgTemplate) -> Bool {
if case .flag(let replString) = arg {
return replString.hasPrefix("--repl=") &&
!replString.contains("-module-name")
}
return false
}

do {
var driver = try Driver(args: ["swift"])
let plannedJobs = try driver.planBuild()
XCTAssertEqual(plannedJobs.count, 1)
let replJob = plannedJobs.first!
XCTAssertTrue(replJob.tool.name.contains("lldb"))
XCTAssertTrue(replJob.requiresInPlaceExecution)
XCTAssert(replJob.commandLine.contains(where: { isLLDBREPLFlag($0) }))
}

do {
var driver = try Driver(args: ["swift", "-repl"])
let plannedJobs = try driver.planBuild()
XCTAssertEqual(plannedJobs.count, 1)
let replJob = plannedJobs.first!
XCTAssertTrue(replJob.tool.name.contains("lldb"))
XCTAssertTrue(replJob.requiresInPlaceExecution)
XCTAssert(replJob.commandLine.contains(where: { isLLDBREPLFlag($0) }))
}

do {
let (mode, args) = try Driver.invocationRunMode(forArgs: ["swift", "repl"])
XCTAssertEqual(mode, .normal(isRepl: true))
var driver = try Driver(args: args)
let plannedJobs = try driver.planBuild()
XCTAssertEqual(plannedJobs.count, 1)
let replJob = plannedJobs.first!
XCTAssertTrue(replJob.tool.name.contains("lldb"))
XCTAssertTrue(replJob.requiresInPlaceExecution)
XCTAssert(replJob.commandLine.contains(where: { isLLDBREPLFlag($0) }))
}

do {
var driver = try Driver(args: ["swift", "-deprecated-integrated-repl"])
let plannedJobs = try driver.planBuild()
XCTAssertEqual(plannedJobs.count, 1)
let replJob = plannedJobs.first!
XCTAssertTrue(replJob.tool.name.contains("swift"))
XCTAssertTrue(replJob.requiresInPlaceExecution)
XCTAssertTrue(replJob.commandLine.count >= 2)
XCTAssertEqual(replJob.commandLine[0], .flag("-frontend"))
XCTAssertEqual(replJob.commandLine[1], .flag("-repl"))
XCTAssert(replJob.commandLine.contains(.flag("-module-name")))
}

do {
var driver = try Driver(args: ["swift", "-repl", "/foo/bar/Test.swift"])
XCTAssertThrowsError(try driver.planBuild()) { error in
XCTAssertEqual(error as? PlanningError, .replReceivedInput)
}
}
}

func testImmediateMode() throws {
do {
var driver = try Driver(args: ["swift", "foo.swift"])
let plannedJobs = try driver.planBuild()
XCTAssertEqual(plannedJobs.count, 1)
let job = plannedJobs[0]
XCTAssertTrue(job.requiresInPlaceExecution)
XCTAssertEqual(job.inputs.count, 1)
XCTAssertEqual(job.inputs[0].file, .relative(RelativePath("foo.swift")))
XCTAssertEqual(job.outputs.count, 0)
Expand All @@ -908,6 +972,7 @@ final class SwiftDriverTests: XCTestCase {
let plannedJobs = try driver.planBuild()
XCTAssertEqual(plannedJobs.count, 1)
let job = plannedJobs[0]
XCTAssertTrue(job.requiresInPlaceExecution)
XCTAssertEqual(job.inputs.count, 1)
XCTAssertEqual(job.inputs[0].file, .relative(RelativePath("foo.swift")))
XCTAssertEqual(job.outputs.count, 0)
Expand All @@ -926,6 +991,7 @@ final class SwiftDriverTests: XCTestCase {
let plannedJobs = try driver.planBuild()
XCTAssertEqual(plannedJobs.count, 1)
let job = plannedJobs[0]
XCTAssertTrue(job.requiresInPlaceExecution)
XCTAssertEqual(job.inputs.count, 1)
XCTAssertEqual(job.inputs[0].file, .relative(RelativePath("foo.swift")))
XCTAssertEqual(job.outputs.count, 0)
Expand Down