atllbuild.swift 19.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
// Copyright (c) 2016 Anarchy Tools Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Drew's avatar
Drew committed
14

Drew's avatar
Drew committed
15
import Foundation
16
import atpkg
Drew's avatar
Drew committed
17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
 /**Synthesize a module map.
 - parameter name: The name of the module to synthesize
 - parameter umbrellaHeader: A path to the umbrella header.  The path must be relative to the exported module map file.
 - returns String contents of the synthesized modulemap
 */
 private func synthesizeModuleMap(name: String, umbrellaHeader: String?) -> String {
     var s = ""
     s += "module \(name) {\n"
     if let u = umbrellaHeader {
         s += "  umbrella header \"\(u)\"\n"
     }
     s += "\n"
     s += "}\n"
     return s
 }
Drew's avatar
Drew committed
33

Drew's avatar
Drew committed
34

Drew's avatar
Drew committed
35 36
/**The ATllbuild tool builds a swift module via llbuild.
For more information on this tool, see `docs/attllbuild.md` */
Drew's avatar
Drew committed
37 38
final class ATllbuild : Tool {
    
39 40 41 42 43 44 45 46 47
    /**We inject this sourcefile in xctestify=true on OSX
    On Linux, the API requires you to explicitly list tests
    which is not required on OSX.  Injecting this file into test targets
    will enforce that API on OSX as well */
    private static let xcTestCaseProvider: String = { () -> String in
        var s = ""
        s += "import XCTest\n"
        s += "\n"
        s += "protocol XCTestCaseProvider {\n"
48
        s += "    var allTests : [(String, () throws -> Void)] { get }\n"
49 50 51 52 53 54 55 56 57 58
        s += "}\n"
        s += "\n"
        s += "public func XCTMain(testCases: [XCTestCase]) {\n"
        s += "    fatalError(\"Can't get here.\")\n"
        s += "}\n"
        s += "\n"
        s += "extension XCTestCase {\n"
        s += "    private func implementAllTests() {\n"
        s += "        print(\"Make sure to implement allTests via\")\n"
        s += "        print(\"extension \\(self.dynamicType) : XCTestCaseProvider {\")\n"
59
        s += "        print(\"    var allTests : [(String, () throws -> Void)] {\")\n"
60 61
        s += "        print(\"        return [\")\n"
        s += "        print(\"        (\\\"testFoo\\\", testFoo)\")\n"
Drew's avatar
Drew committed
62
        s += "        print(\"        ]\")\n"
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        s += "        print(\"    }\")\n"
        s += "        print(\"}\")\n"
        s += "        print(\"(Or disable xctestStrict.)\")\n"
        s += "        print(\"Cheers! -- Anarchy Tools Team\")\n"
        s += "    }\n"
        s += "    override public func tearDown() {\n"
        s += "        if let provider = self as? XCTestCaseProvider {\n"
        s += "            let contains = provider.allTests.contains({ test in\n"
        s += "                return test.0 == invocation!.selector.description\n"
        s += "            })\n"
        s += "            if !contains {\n"
        s += "               XCTFail(\"Test \\(name) is missing from \\(self.dynamicType)\")\n"
        s += "               implementAllTests()\n"
        s += "            }\n"
        s += "        }\n"
        s += "        else {\n"
        s += "            XCTFail(\"Whoops!  \\(self.dynamicType) doesn't conform to XCTestCaseProvider.\")\n"
        s += "            implementAllTests()\n"
        s += "        }\n"
        s += "        super.tearDown()\n"
        s += "    }\n"
        s += "}\n"
        s += "\n"
        return s
    }()
    
89 90 91 92
    enum OutputType {
        case Executable
        case StaticLibrary
    }
Drew's avatar
Drew committed
93 94 95 96 97

    enum ModuleMapType {
        case None
        case Synthesized
    }
98
    
99 100 101 102 103 104 105
    /**
     * Calculates the llbuild.yaml contents for the given configuration options
     *   - parameter sources: A resolved list of swift sources
     *   - parameter workdir: A temporary working directory for `atllbuild` to use
     *   - parameter modulename: The name of the module to be built.
     *   - returns: The string contents for llbuild.yaml suitable for processing by swift-build-tool
     */
Drew's avatar
Drew committed
106
    func llbuildyaml(sources: [String], workdir: String, modulename: String, linkSDK: Bool, compileOptions: [String], linkOptions: [String], outputType: OutputType, linkWithProduct:[String], swiftCPath: String) -> String {
107
        let productPath = workdir + "products/"
Drew's avatar
Drew committed
108 109
        //this format is largely undocumented, but I reverse-engineered it from SwiftPM.
        var yaml = "client:\n  name: swift-build\n\n"
Drew's avatar
Drew committed
110 111 112 113
        
        yaml += "tools: {}\n\n"

        
Drew's avatar
Drew committed
114
        yaml += "targets:\n"
Drew's avatar
Drew committed
115 116 117
        yaml += "  \"\": [<atllbuild>]\n"
        yaml += "  atllbuild: [<atllbuild>]\n"
        
Drew's avatar
Drew committed
118
        //this is the "compile" command
Drew's avatar
Drew committed
119 120 121 122
        
        yaml += "commands:\n"
        yaml += "  <atllbuild-swiftc>:\n"
        yaml += "     tool: swift-compiler\n"
Drew's avatar
Drew committed
123
        yaml += "     executable: \"\(swiftCPath)\"\n"
Drew's avatar
Drew committed
124 125 126 127 128
        yaml += "     inputs: \(sources)\n"
        yaml += "     sources: \(sources)\n"
        
        //swiftPM wants "objects" which is just a list of %.swift.o files.  We have to put them in a temp directory though.
        let objects = sources.map { (source) -> String in
Drew's avatar
Drew committed
129
            workdir + "objects/" + source.toNSString.lastPathComponent + ".o"
Drew's avatar
Drew committed
130 131
        }
        yaml += "     objects: \(objects)\n"
Drew's avatar
Drew committed
132 133 134 135
        //this crazy syntax is how llbuild specifies outputs
        var llbuild_outputs = ["<atllbuild-swiftc>"]
        llbuild_outputs.appendContentsOf(objects)
        yaml += "     outputs: \(llbuild_outputs)\n"
136 137 138 139 140 141 142
        
        switch(outputType) {
        case .Executable:
            break
        case .StaticLibrary:
            yaml += "     is-library: true\n" //I have no idea what the effect of this is, but swiftPM does it, so I'm including it.
        }
Drew's avatar
Drew committed
143 144
        
        yaml += "     module-name: \(modulename)\n"
145 146
        let swiftModulePath = "\(productPath + modulename).swiftmodule"
        yaml += "     module-output-path: \(swiftModulePath)\n"
Drew's avatar
Drew committed
147 148 149
        yaml += "     temps-path: \(workdir)/llbuildtmp\n"
        
        var args : [String] = []
Drew's avatar
Drew committed
150
        args.appendContentsOf(["-j8", "-D","ATBUILD","-I",workdir+"products/"])
151 152
        
        if linkSDK {
Drew's avatar
Drew committed
153
            #if os(OSX) //we don't have SDKPath on linux
154
            args.appendContentsOf(["-sdk", SDKPath])
Drew's avatar
Drew committed
155
            #endif
156
        }
Drew's avatar
Drew committed
157
        args.appendContentsOf(compileOptions)
Drew's avatar
Drew committed
158 159
        
        yaml += "     other-args: \(args)\n"
Drew's avatar
Drew committed
160 161 162
        
        //and this is the "link" command
        yaml += "  <atllbuild>:\n"
163 164 165 166 167 168
        switch(outputType) {
        case .Executable:
            yaml += "    tool: shell\n"
            //this crazy syntax is how sbt declares a dependency
            var llbuild_inputs = ["<atllbuild-swiftc>"]
            llbuild_inputs.appendContentsOf(objects)
Drew's avatar
Drew committed
169 170
            let builtProducts = linkWithProduct.map {workdir+"products/"+$0}
            llbuild_inputs.appendContentsOf(builtProducts)
171
            let executablePath = productPath+modulename
172
            yaml += "    inputs: \(llbuild_inputs)\n"
173
            yaml += "    outputs: [\"<atllbuild>\", \"\(executablePath)\"]\n"
174
            //and now we have the crazy 'args'
Drew's avatar
Drew committed
175
            args = [swiftCPath, "-o",executablePath]
176
            args.appendContentsOf(objects)
Drew's avatar
Drew committed
177
            args.appendContentsOf(builtProducts)
Drew's avatar
Drew committed
178
            args.appendContentsOf(linkOptions)
179
            yaml += "    args: \(args)\n"
180 181
            yaml += "    description: Linking executable \(executablePath)\n"
            return yaml
Drew's avatar
Drew committed
182

183 184 185 186 187 188
        
        case .StaticLibrary:
            yaml += "    tool: shell\n"
            var llbuild_inputs = ["<atllbuild-swiftc>"]
            llbuild_inputs.appendContentsOf(objects)
            yaml += "    inputs: \(llbuild_inputs)\n"
189
            let libPath = productPath + modulename + ".a"
190 191 192 193 194 195 196 197 198 199
            yaml += "    outputs: [\"<atllbuild>\", \"\(libPath)\"]\n"
            
            //build the crazy args, mostly consisting of an `ar` shell command
            var shellCmd = "rm -rf \(libPath); ar cr '\(libPath)'"
            for obj in objects {
                shellCmd += " '\(obj)'"
            }
            let args = "[\"/bin/sh\",\"-c\",\(shellCmd)]"
            yaml += "    args: \(args)\n"
            yaml += "    description: \"Linking Library:  \(libPath)\""
200
            return yaml
201
        }
202
     }
Drew's avatar
Drew committed
203
    
Drew's avatar
Drew committed
204 205 206 207
    private enum Options: String {
        case Tool = "tool"
        case Name = "name"
        case Dependencies = "dependencies"
208 209 210
        case OutputType = "output-type"
        case Source = "sources"
        case BootstrapOnly = "bootstrap-only"
Drew's avatar
Drew committed
211
        case llBuildYaml = "llbuildyaml"
212 213 214 215 216
        case CompileOptions = "compile-options"
        case LinkOptions = "link-options"
        case LinkSDK = "link-sdk"
        case LinkWithProduct = "link-with"
        case SwiftCPath = "swiftc-path"
Drew's avatar
Drew committed
217
        case XCTestify = "xctestify"
218
        case XCTestStrict = "xctest-strict"
219
		case IncludeWithUser = "include-with-user"
220
        case PublishProduct = "publish-product"
221
        case UmbrellaHeader = "umbrella-header"
Drew's avatar
Drew committed
222
        case ModuleMap = "module-map"
223

Drew's avatar
Drew committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        
        static var allOptions : [Options] {
            return [
                Name,
                Dependencies,
                OutputType,
                Source,
                BootstrapOnly,
                llBuildYaml,
                CompileOptions,
                LinkOptions,
                LinkSDK,
                LinkWithProduct,
                SwiftCPath,
                XCTestify,
                XCTestStrict,
240
				IncludeWithUser,
241
                PublishProduct,
242
				UmbrellaHeader
Drew's avatar
Drew committed
243 244 245 246
            ]
        }
    }
    
247
    func run(task: Task) {
248 249
        
        //warn if we don't understand an option
250 251 252 253
        var knownOptions = Options.allOptions.map({$0.rawValue})
        for option in Task.Option.allOptions.map({$0.rawValue}) {
            knownOptions.append(option)
        }
254
        for key in task.allKeys {
255
            if !knownOptions.contains(key) {
Drew's avatar
Drew committed
256
                print("Warning: unknown option \(key) for task \(task.qualifiedName)")
257 258 259
            }
        }
        
Drew's avatar
Drew committed
260 261 262
        //create the working directory
        let workDirectory = ".atllbuild/"
        let manager = NSFileManager.defaultManager()
Drew's avatar
Drew committed
263 264 265 266 267
        
        //NSFileManager is pretty anal about throwing errors if we try to remove something that doesn't exist, etc.
        //We just want to create a state where .atllbuild/objects and .atllbuild/llbuildtmp and .atllbuild/products exists.
        //and in particular, without erasing the product directory, since that accumulates build products across
        //multiple invocations of atllbuild.
Drew's avatar
Drew committed
268 269 270 271
        if Process.arguments.contains("--clean") {
            let _ = try? manager.removeItemAtPath(workDirectory + "/objects")
            let _ = try? manager.removeItemAtPath(workDirectory + "/llbuildtmp")
        }
272 273
        let _ = try? manager.removeItemAtPath(workDirectory + "/include")

Drew's avatar
Drew committed
274 275


Drew's avatar
Drew committed
276 277
        let _ = try? manager.createDirectoryAtPath(workDirectory, withIntermediateDirectories: false, attributes: nil)
        let _ = try? manager.createDirectoryAtPath(workDirectory + "/products", withIntermediateDirectories: false, attributes: nil)
278
        let _ = try? manager.createDirectoryAtPath(workDirectory + "/objects", withIntermediateDirectories: false, attributes: nil)
279
        let _ = try? manager.createDirectoryAtPath(workDirectory + "/include", withIntermediateDirectories: false, attributes: nil)
Drew's avatar
Drew committed
280

Drew's avatar
Drew committed
281
        //parse arguments
Drew's avatar
Drew committed
282
        var linkWithProduct: [String] = []
Drew's avatar
Drew committed
283
        if let arr = task[Options.LinkWithProduct.rawValue]?.vector {
Drew's avatar
Drew committed
284
            for product in arr {
285
                guard let p = product.string else { fatalError("non-string product \(product)") }
Drew's avatar
Drew committed
286 287 288
                linkWithProduct.append(p)
            }
        }
289
        let outputType: OutputType
Drew's avatar
Drew committed
290
        if task[Options.OutputType.rawValue]?.string == "static-library" {
291 292
            outputType = .StaticLibrary
        }
Drew's avatar
Drew committed
293
        else if task[Options.OutputType.rawValue]?.string == "executable" {
294 295 296
            outputType = .Executable
        }
        else {
297
            fatalError("Unknown \(Options.OutputType.rawValue) \(task["outputType"])")
298 299
        }
        
Drew's avatar
Drew committed
300
        var compileOptions: [String] = []
Drew's avatar
Drew committed
301
        if let opts = task[Options.CompileOptions.rawValue]?.vector {
Drew's avatar
Drew committed
302
            for o in opts {
303
                guard let os = o.string else { fatalError("Compile option \(o) is not a string") }
Drew's avatar
Drew committed
304 305 306
                compileOptions.append(os)
            }
        }
307
        if let includePaths = task[Options.IncludeWithUser.rawValue]?.vector {
Drew's avatar
Drew committed
308 309 310 311 312 313
            for path_s in includePaths {
                guard let path = path_s.string else { fatalError("Non-string path \(path_s)") }
                compileOptions.append("-I")
                compileOptions.append(userPath() + "/" + path)
            }
        }
Drew's avatar
Drew committed
314
        var linkOptions: [String] = []
Drew's avatar
Drew committed
315
        if let opts = task[Options.LinkOptions.rawValue]?.vector {
Drew's avatar
Drew committed
316 317 318 319 320
            for o in opts {
                guard let os = o.string else { fatalError("Link option \(o) is not a string") }
                linkOptions.append(os)
            }
        }
Drew's avatar
Drew committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337

        //check for modulemaps
        for product in linkWithProduct {
            let productName = product.componentsSeparatedByString(".")[0]
            let moduleMapPath = workDirectory + "/products/\(productName).modulemap"
            if manager.fileExistsAtPath(moduleMapPath) {
                /*per http://clang.llvm.org/docs/Modules.html#command-line-parameters, pretty much
                the only way to do this is to create a file called `module.modulemap`.  That
                potentially conflicts with other modulemaps, so we give it its own directory, namespaced
                by the product name. */
                let pathName = workDirectory + "/include/\(productName)"
                try! manager.createDirectoryAtPath(pathName, withIntermediateDirectories:false, attributes: nil)
                try! manager.copyItemAtPath_SWIFTBUG(moduleMapPath, toPath: pathName + "/module.modulemap")
                compileOptions.appendContentsOf(["-I",pathName])
            }
        }

Drew's avatar
Drew committed
338
        guard let sourceDescriptions = task[Options.Source.rawValue]?.vector?.flatMap({$0.string}) else { fatalError("Can't find sources for atllbuild.") }
Drew's avatar
Drew committed
339
        var sources = collectSources(sourceDescriptions, taskForCalculatingPath: task)
340
        
Drew's avatar
Drew committed
341
        //xctestify
Drew's avatar
Drew committed
342
        if task[Options.XCTestify.rawValue]?.bool == true {
343
            precondition(outputType == .Executable, "You must use :\(Options.OutputType.rawValue) executable with xctestify.")
Drew's avatar
Drew committed
344 345
            //inject platform-specific flags
            #if os(OSX)
346 347 348 349
                compileOptions.appendContentsOf(["-F", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/"])
                linkOptions.appendContentsOf(["-F", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/", "-target", "x86_64-apple-macosx10.11", "-Xlinker", "-rpath", "-Xlinker", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/", "-Xlinker", "-bundle"])
            #endif
        }
Drew's avatar
Drew committed
350
        if task[Options.XCTestStrict.rawValue]?.bool == true {
351 352 353 354 355 356 357 358
            #if os(OSX)
            //inject XCTestCaseProvider.swift
            var xcTestCaseProviderPath = "/tmp/XXXXXXX"
            var template = xcTestCaseProviderPath.cStringUsingEncoding(NSUTF8StringEncoding)!
            xcTestCaseProviderPath = String(CString: mkdtemp(&template), encoding: NSUTF8StringEncoding)!
            xcTestCaseProviderPath += "/XCTestCaseProvider.swift"
            try! ATllbuild.xcTestCaseProvider.writeToFile(xcTestCaseProviderPath, atomically: false, encoding: NSUTF8StringEncoding)
            sources.append(xcTestCaseProviderPath)
Drew's avatar
Drew committed
359 360
            #endif
        }
Drew's avatar
Drew committed
361 362 363 364 365 366 367
        let moduleMap: ModuleMapType
        if task[Options.ModuleMap.rawValue]?.string == "synthesized" {
            moduleMap = .Synthesized
        }
        else {
            moduleMap = .None
        }
Drew's avatar
Drew committed
368

Drew's avatar
Drew committed
369
        guard let name = task[Options.Name.rawValue]?.string else { fatalError("No name for atllbuild task") }
Drew's avatar
Drew committed
370
        
371
        if let umbrellaHeader = task[Options.UmbrellaHeader.rawValue]?.string {
Drew's avatar
Drew committed
372 373
            precondition(moduleMap == .Synthesized, ":\(Options.UmbrellaHeader.rawValue) \"synthesized\" must be used with the \(Options.UmbrellaHeader.rawValue) option")
            let s = synthesizeModuleMap(name, umbrellaHeader: "Umbrella.h")
374
            try! s.writeToFile(workDirectory+"/include/module.modulemap", atomically: false, encoding: NSUTF8StringEncoding)
Drew's avatar
Drew committed
375
            try! manager.copyItemAtPath_SWIFTBUG(task.importedPath + umbrellaHeader, toPath: workDirectory + "/include/Umbrella.h")
376 377 378 379 380
            compileOptions.append("-I")
            compileOptions.append(workDirectory + "/include/")
            compileOptions.append("-import-underlying-module")
        }
        
Drew's avatar
Drew committed
381
        let bootstrapOnly: Bool
Drew's avatar
Drew committed
382

Drew's avatar
Drew committed
383
        if task[Options.BootstrapOnly.rawValue]?.bool == true {
Drew's avatar
Drew committed
384 385 386 387 388 389
            bootstrapOnly = true
        }
        else {
            bootstrapOnly = false
        }
        
390
        let sdk: Bool
Drew's avatar
Drew committed
391
        if task[Options.LinkSDK.rawValue]?.bool == false {
392 393 394 395
            sdk = false
        }
        else { sdk = true }
        
Drew's avatar
Drew committed
396
        let llbuildyamlpath : String
Drew's avatar
Drew committed
397

Drew's avatar
Drew committed
398
        if let value = task[Options.llBuildYaml.rawValue]?.string {
399
            llbuildyamlpath = value
Drew's avatar
Drew committed
400 401 402 403
        }
        else {
            llbuildyamlpath = workDirectory + "llbuild.yaml"
        }
Drew's avatar
Drew committed
404 405

        let swiftCPath: String
Drew's avatar
Drew committed
406
        if let c = task[Options.SwiftCPath.rawValue]?.string {
Drew's avatar
Drew committed
407 408 409 410 411
            swiftCPath = c
        }
        else {
            swiftCPath = SwiftCPath
        }
Drew's avatar
Drew committed
412
        
Drew's avatar
Drew committed
413
        let yaml = llbuildyaml(sources, workdir: workDirectory, modulename: name, linkSDK: sdk, compileOptions: compileOptions, linkOptions: linkOptions, outputType: outputType, linkWithProduct: linkWithProduct, swiftCPath: swiftCPath)
414
        let _ = try? yaml.writeToFile(llbuildyamlpath, atomically: false, encoding: NSUTF8StringEncoding)
Drew's avatar
Drew committed
415
        if bootstrapOnly { return }
Drew's avatar
Drew committed
416 417 418 419 420 421 422 423

        switch moduleMap {
                case .None:
                break
                case .Synthesized:
                let s = synthesizeModuleMap(name, umbrellaHeader: nil)
                try! s.writeToFile(workDirectory + "/products/\(name).modulemap", atomically: false, encoding: NSUTF8StringEncoding)
        }
Drew's avatar
Drew committed
424
        
Drew's avatar
Drew committed
425 426 427 428
        //SR-566
        let cmd = "\(SwiftBuildToolpath) -f \(llbuildyamlpath)"
        if system(cmd) != 0 {
            fatalError(cmd)
Drew's avatar
Drew committed
429
        }
Drew's avatar
Drew committed
430
        if task[Options.PublishProduct.rawValue]?.bool == true {
Drew's avatar
Drew committed
431 432 433 434 435 436 437 438 439 440
            if !manager.fileExistsAtPath("bin") {
                try! manager.createDirectoryAtPath("bin", withIntermediateDirectories: false, attributes: nil)
            }
            try! copyByOverwriting("\(workDirectory)/products/\(name).swiftmodule", toPath: "bin/\(name).swiftmodule")
            switch outputType {
            case .Executable:
                try! copyByOverwriting("\(workDirectory)/products/\(name)", toPath: "bin/\(name)")
            case .StaticLibrary:
                try! copyByOverwriting("\(workDirectory)/products/\(name).a", toPath: "bin/\(name).a")
            }
Drew's avatar
Drew committed
441 442 443 444 445 446 447 448

            switch moduleMap {
                case .None:
                break
                case .Synthesized:
                try! copyByOverwriting("\(workDirectory)/products/\(name).modulemap", toPath: "bin/\(name).modulemap")
            }

Drew's avatar
Drew committed
449 450 451 452 453 454 455 456
        }
    }
}

private func copyByOverwriting(fromPath: String, toPath: String) throws {
    let manager = NSFileManager.defaultManager()
    if manager.fileExistsAtPath(toPath) {
        try manager.removeItemAtPath(toPath)
Drew's avatar
Drew committed
457
    }
458
    try! manager.copyItemAtPath_SWIFTBUG(fromPath, toPath: toPath)
Drew's avatar
Drew committed
459
}