content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if os(Windows)\n\nimport WinSDK\nimport SwiftRemoteMirror\nimport Foundation\nimport SwiftInspectClientInterface\n\ninternal var WAIT_TIMEOUT_MS: DWORD {\n DWORD(SwiftInspectClientInterface.WAIT_TIMEOUT_MS)\n}\n\ninternal final class WindowsRemoteProcess: RemoteProcess {\n public typealias ProcessIdentifier = DWORD\n public typealias ProcessHandle = HANDLE\n\n public private(set) var process: ProcessHandle\n public private(set) var context: SwiftReflectionContextRef!\n public private(set) var processIdentifier: ProcessIdentifier\n public private(set) var processName: String = "<unknown process>"\n\n private var hSwiftCore: HMODULE = HMODULE(bitPattern: -1)!\n\n static var QueryDataLayout: QueryDataLayoutFunction {\n return { (context, type, _, output) in\n let _ = WindowsRemoteProcess.fromOpaque(context!)\n\n switch type {\n case DLQ_GetPointerSize:\n let size = UInt8(MemoryLayout<UnsafeRawPointer>.stride)\n output?.storeBytes(of: size, toByteOffset: 0, as: UInt8.self)\n return 1\n\n case DLQ_GetSizeSize:\n // FIXME(compnerd) support 32-bit processes\n let size = UInt8(MemoryLayout<UInt64>.stride)\n output?.storeBytes(of: size, toByteOffset: 0, as: UInt8.self)\n return 1\n\n case DLQ_GetLeastValidPointerValue:\n let value: UInt64 = 0x1000\n output?.storeBytes(of: value, toByteOffset: 0, as: UInt64.self)\n return 1\n\n default:\n return 0\n }\n }\n }\n\n static var Free: FreeFunction? {\n return { (_, bytes, _) in\n free(UnsafeMutableRawPointer(mutating: bytes))\n }\n }\n\n static var ReadBytes: ReadBytesFunction {\n return { (context, address, size, _) in\n let process: WindowsRemoteProcess =\n WindowsRemoteProcess.fromOpaque(context!)\n\n guard let buffer = malloc(Int(size)) else { return nil }\n if !ReadProcessMemory(\n process.process, LPVOID(bitPattern: UInt(address)),\n buffer, size, nil)\n {\n free(buffer)\n return nil\n }\n return UnsafeRawPointer(buffer)\n }\n }\n\n static var GetStringLength: GetStringLengthFunction {\n return { (context, address) in\n let process: WindowsRemoteProcess =\n WindowsRemoteProcess.fromOpaque(context!)\n\n var information: WIN32_MEMORY_REGION_INFORMATION =\n WIN32_MEMORY_REGION_INFORMATION()\n if !QueryVirtualMemoryInformation(\n process.process,\n LPVOID(bitPattern: UInt(address)),\n MemoryRegionInfo, &information,\n SIZE_T(MemoryLayout.size(ofValue: information)),\n nil)\n {\n return 0\n }\n\n // FIXME(compnerd) mapping in the memory region from the remote process\n // would be ideal to avoid a round-trip for each byte. This seems to work\n // well enough for now in practice, but we should fix this to provide a\n // proper remote `strlen` implementation.\n //\n // Read 64-bytes, though limit it to the size of the memory region.\n let length: Int = Int(\n min(\n UInt(information.RegionSize)\n - (UInt(address) - UInt(bitPattern: information.AllocationBase)), 64))\n let string: String = [CChar](unsafeUninitializedCapacity: length) {\n $1 = 0\n var NumberOfBytesRead: SIZE_T = 0\n if ReadProcessMemory(\n process.process, LPVOID(bitPattern: UInt(address)),\n $0.baseAddress, SIZE_T($0.count), &NumberOfBytesRead)\n {\n $1 = Int(NumberOfBytesRead)\n }\n }.withUnsafeBufferPointer {\n String(cString: $0.baseAddress!)\n }\n\n return UInt64(string.count)\n }\n }\n\n static var GetSymbolAddress: GetSymbolAddressFunction {\n return { (context, symbol, length) in\n let process: WindowsRemoteProcess =\n WindowsRemoteProcess.fromOpaque(context!)\n\n guard let symbol = symbol else { return 0 }\n let name: String = symbol.withMemoryRebound(to: UInt8.self, capacity: Int(length)) {\n let buffer = UnsafeBufferPointer(start: $0, count: Int(length))\n return String(decoding: buffer, as: UTF8.self)\n }\n\n return unsafeBitCast(GetProcAddress(process.hSwiftCore, name), to: swift_addr_t.self)\n }\n }\n\n init?(processId: ProcessIdentifier) {\n self.processIdentifier = processId\n // Get process handle.\n self.process =\n OpenProcess(\n DWORD(\n PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION),\n false,\n processId)\n\n // Initialize SwiftReflectionContextRef\n guard\n let context =\n swift_reflection_createReflectionContextWithDataLayout(\n self.toOpaqueRef(),\n Self.QueryDataLayout,\n Self.Free,\n Self.ReadBytes,\n Self.GetStringLength,\n Self.GetSymbolAddress)\n else {\n // FIXME(compnerd) log error\n return nil\n }\n self.context = context\n\n // Locate swiftCore.dll in the target process and load modules.\n modules(of: processId) { (entry, module) in\n // FIXME(compnerd) support static linking at some point\n if module == "swiftCore.dll" { self.hSwiftCore = entry.hModule }\n _ = swift_reflection_addImage(context,\n unsafeBitCast(entry.modBaseAddr,\n to: swift_addr_t.self))\n }\n if self.hSwiftCore == HMODULE(bitPattern: -1) {\n // FIXME(compnerd) log error\n return nil\n }\n\n // Initialize DbgHelp.\n if !SymInitialize(self.process, nil, true) {\n // FIXME(compnerd) log error\n return nil\n }\n }\n\n deinit {\n swift_reflection_destroyReflectionContext(self.context)\n _ = SymCleanup(self.process)\n _ = CloseHandle(self.process)\n self.release()\n }\n\n func symbolicate(_ address: swift_addr_t) -> (module: String?, symbol: String?) {\n let kMaxSymbolNameLength: Int = 1024\n\n let byteCount = MemoryLayout<SYMBOL_INFO>.size + kMaxSymbolNameLength + 1\n\n let buffer: UnsafeMutableRawPointer =\n UnsafeMutableRawPointer.allocate(byteCount: byteCount, alignment: 1)\n defer { buffer.deallocate() }\n\n let pSymbolInfo: UnsafeMutablePointer<SYMBOL_INFO> =\n buffer.bindMemory(to: SYMBOL_INFO.self, capacity: 1)\n pSymbolInfo.pointee.SizeOfStruct = ULONG(MemoryLayout<SYMBOL_INFO>.size)\n pSymbolInfo.pointee.MaxNameLen = ULONG(kMaxSymbolNameLength)\n\n guard SymFromAddr(self.process, DWORD64(address), nil, pSymbolInfo) else {\n return (nil, nil)\n }\n\n let symbol: String = withUnsafePointer(to: &pSymbolInfo.pointee.Name) {\n String(cString: $0)\n }\n\n var context: (DWORD64, String?) = (pSymbolInfo.pointee.ModBase, nil)\n _ = withUnsafeMutablePointer(to: &context) {\n SymEnumerateModules64(self.process, { (ModuleName, BaseOfDll, UserContext) -> WindowsBool in\n if let pContext = UserContext?.bindMemory(to: (DWORD64, String?).self, capacity: 1) {\n if pContext.pointee.0 == BaseOfDll {\n pContext.pointee.1 = String(cString: ModuleName!)\n return false\n }\n }\n return true\n }, $0)\n }\n\n return (context.1, symbol)\n }\n\n internal func iterateHeap(_ body: (swift_addr_t, UInt64) -> Void) {\n let dwProcessId: DWORD = GetProcessId(self.process)\n if dwProcessId == 0 {\n // FIXME(compnerd) log error\n return\n }\n\n // We use a shared memory and two event objects to send heap entries data\n // from the remote process to this process. A high-level structure looks\n // like below:\n //\n // Swift inspect (this process):\n //\n // Setup the shared memory and event objects\n // Create a remote thread to invoke the heap walk on the remote process\n // Loop {\n // Wait on ReadEvent to wait for heap entries in the shared memory\n // If no entries, break\n // Inspect and dump heap entries from the shared memory\n // Notify (SetEvent) on WriteEvent to have more heap entries written\n // }\n //\n // Remote process:\n //\n // Open the shared memory and event objects\n // Heap walk loop {\n // Write heap entries in the shared memory until full or done\n // Notify (SetEvent) ReadEvent to have them read\n // Wait on WriteEvent until they are read\n // }\n //\n\n // Exclude the self-inspect case. We use IPC + HeapWalk in the remote\n // process, which doesn't work on itself.\n if dwProcessId == GetCurrentProcessId() {\n print("Cannot inspect the process itself")\n return\n }\n\n // The size of the shared memory buffer and the names of shared\n // memory and event objects\n let bufSize = Int(BUF_SIZE)\n let sharedMemoryName = "\(SHARED_MEM_NAME_PREFIX)-\(String(dwProcessId))"\n\n // Set up the shared memory\n let hMapFile = CreateFileMappingA(\n INVALID_HANDLE_VALUE,\n nil,\n DWORD(PAGE_READWRITE),\n 0,\n DWORD(bufSize),\n sharedMemoryName)\n if hMapFile == HANDLE(bitPattern: 0) {\n print("CreateFileMapping failed \(GetLastError())")\n return\n }\n defer { CloseHandle(hMapFile) }\n let buf: LPVOID = MapViewOfFile(\n hMapFile,\n FILE_MAP_ALL_ACCESS,\n 0,\n 0,\n SIZE_T(bufSize))\n if buf == LPVOID(bitPattern: 0) {\n print("MapViewOfFile failed \(GetLastError())")\n return\n }\n defer { UnmapViewOfFile(buf) }\n\n // Set up the event objects\n guard let (hReadEvent, hWriteEvent) = createEventPair(dwProcessId) else {\n return\n }\n defer {\n CloseHandle(hReadEvent)\n CloseHandle(hWriteEvent)\n }\n\n // Allocate the dll path string in the remote process.\n guard let dllPathRemote = allocateDllPathRemote() else {\n return\n }\n\n guard let aEntryPoints = find(module: "KERNEL32.DLL",\n symbols: ["LoadLibraryW", "FreeLibrary"],\n in: dwProcessId)?.map({\n unsafeBitCast($0, to: LPTHREAD_START_ROUTINE.self)\n }) else {\n print("Failed to find remote LoadLibraryW/FreeLibrary addresses")\n return\n }\n\n let (pfnLoadLibraryW, pfnFreeLibrary) = (aEntryPoints[0], aEntryPoints[1])\n let hThread: HANDLE = CreateRemoteThread(\n self.process, nil, 0, pfnLoadLibraryW, dllPathRemote, 0, nil)\n if hThread == HANDLE(bitPattern: 0) {\n print("CreateRemoteThread failed \(GetLastError())")\n return\n }\n defer { CloseHandle(hThread) }\n\n defer {\n // Always perform the code ejection process even if the heap walk fails.\n // The module cannot re-execute the heap walk and will leave a retain\n // count behind, preventing the module from being unlinked on the file\n // system as well as leave code in the inspected process. This will\n // eventually be an issue for treating the injected code as a resource\n // which is extracted temporarily.\n if !eject(module: dllPathRemote, from: dwProcessId, pfnFreeLibrary) {\n print("Failed to unload the remote dll")\n }\n }\n\n // The main heap iteration loop.\n outer: while true {\n let wait = WaitForSingleObject(hReadEvent, WAIT_TIMEOUT_MS)\n if wait != WAIT_OBJECT_0 {\n print("WaitForSingleObject failed \(wait)")\n return\n }\n\n let entryCount = bufSize / MemoryLayout<HeapEntry>.size\n\n for entry in UnsafeMutableBufferPointer(\n start: buf.bindMemory(\n to: HeapEntry.self,\n capacity: entryCount),\n count: entryCount)\n {\n if entry.Address == UInt.max {\n // The buffer containing zero entries, indicated by the first entry\n // contains -1, means, we are done. Break out of loop.\n if !SetEvent(hWriteEvent) {\n print("SetEvent failed: \(GetLastError())")\n return\n }\n break outer\n }\n if entry.Address == 0 {\n // Done. Break out of loop.\n break\n }\n body(swift_addr_t(entry.Address), UInt64(entry.Size))\n }\n\n if !SetEvent(hWriteEvent) {\n print("SetEvent failed \(GetLastError())")\n return\n }\n }\n\n let wait = WaitForSingleObject(hThread, WAIT_TIMEOUT_MS)\n if wait != WAIT_OBJECT_0 {\n print("WaitForSingleObject on LoadLibrary failed \(wait)")\n return\n }\n\n var threadExitCode: DWORD = 0\n GetExitCodeThread(hThread, &threadExitCode)\n if threadExitCode == 0 {\n print("LoadLibraryW failed \(threadExitCode)")\n return\n }\n }\n\n private func allocateDllPathRemote() -> UnsafeMutableRawPointer? {\n URL(fileURLWithPath: ProcessInfo.processInfo.arguments[0])\n .deletingLastPathComponent()\n .appendingPathComponent("SwiftInspectClient.dll")\n .path\n .withCString(encodedAs: UTF16.self) { pwszPath in\n let dwLength = GetFullPathNameW(pwszPath, 0, nil, nil)\n return withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(dwLength)) {\n guard GetFullPathNameW(pwszPath, dwLength, $0.baseAddress, nil) == dwLength - 1 else { return nil }\n\n var faAttributes: WIN32_FILE_ATTRIBUTE_DATA = .init()\n guard GetFileAttributesExW($0.baseAddress, GetFileExInfoStandard, &faAttributes) else {\n print("\(String(decodingCString: $0.baseAddress!, as: UTF16.self)) doesn't exist")\n return nil\n }\n guard faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == 0 else {\n print("\(String(decodingCString: $0.baseAddress!, as: UTF16.self)) doesn't exist")\n return nil\n }\n\n let szLength = SIZE_T(Int(dwLength) * MemoryLayout<WCHAR>.size)\n guard let pAllocation =\n VirtualAllocEx(self.process, nil, szLength,\n DWORD(MEM_COMMIT), DWORD(PAGE_READWRITE)) else {\n print("VirtualAllocEx failed \(GetLastError())")\n return nil\n }\n\n if !WriteProcessMemory(self.process, pAllocation, $0.baseAddress, szLength, nil) {\n print("WriteProcessMemory failed \(GetLastError())")\n _ = VirtualFreeEx(self.process, pAllocation, 0, DWORD(MEM_RELEASE))\n return nil\n }\n\n return pAllocation\n }\n }\n }\n\n /// Eject the injected code from the instrumented process.\n ///\n /// Performs the necessary clean up to remove the injected code from the\n /// instrumented process once the heap walk is complete.\n private func eject(module pwszModule: UnsafeMutableRawPointer,\n from process: DWORD,\n _ pfnFunction: LPTHREAD_START_ROUTINE) -> Bool {\n // Deallocate the dll path string in the remote process\n if !VirtualFreeEx(self.process, pwszModule, 0, DWORD(MEM_RELEASE)) {\n print("VirtualFreeEx failed: \(GetLastError())")\n }\n\n // Get the dll module handle in the remote process to use it to unload it\n // below. `GetExitCodeThread` returns a `DWORD` (32-bit) but the `HMODULE`\n // pointer-sized and may be truncated, so, search for it using the snapshot\n // instead.\n guard let hModule = find(module: "SwiftInspectClient.dll", in: process) else {\n print("Failed to find the client dll")\n return false\n }\n\n // Unload the dll from the remote process\n guard let hThread = CreateRemoteThread(self.process, nil, 0, pfnFunction,\n hModule, 0, nil) else {\n print("CreateRemoteThread for unload failed \(GetLastError())")\n return false\n }\n defer { CloseHandle(hThread) }\n\n guard WaitForSingleObject(hThread, WAIT_TIMEOUT_MS) == WAIT_OBJECT_0 else {\n print("WaitForSingleObject on FreeLibrary failed \(GetLastError())")\n return false\n }\n\n var dwExitCode: DWORD = 0\n guard GetExitCodeThread(hThread, &dwExitCode) else {\n print("GetExitCodeThread for unload failed \(GetLastError())")\n return false\n }\n\n if dwExitCode == 0 {\n print("FreeLibrary failed \(dwExitCode)")\n return false\n }\n\n return true\n }\n\n private func modules(of dwProcessId: DWORD, _ closure: (MODULEENTRY32W, String) -> Void) {\n let hModuleSnapshot: HANDLE =\n CreateToolhelp32Snapshot(DWORD(TH32CS_SNAPMODULE), dwProcessId)\n if hModuleSnapshot == INVALID_HANDLE_VALUE {\n print("CreateToolhelp32Snapshot failed \(GetLastError())")\n return\n }\n defer { CloseHandle(hModuleSnapshot) }\n var entry: MODULEENTRY32W = MODULEENTRY32W()\n entry.dwSize = DWORD(MemoryLayout<MODULEENTRY32W>.size)\n guard Module32FirstW(hModuleSnapshot, &entry) else {\n print("Module32FirstW failed \(GetLastError())")\n return\n }\n repeat {\n let module: String = withUnsafePointer(to: entry.szModule) {\n $0.withMemoryRebound(\n to: WCHAR.self,\n capacity: MemoryLayout.size(ofValue: $0) / MemoryLayout<WCHAR>.size\n ) {\n String(decodingCString: $0, as: UTF16.self)\n }\n }\n closure(entry, module)\n } while Module32NextW(hModuleSnapshot, &entry)\n }\n\n private func find(module named: String, in dwProcessId: DWORD) -> HMODULE? {\n var hModule: HMODULE?\n modules(of: dwProcessId) { (entry, module) in\n if module == named { hModule = entry.hModule }\n }\n return hModule\n }\n\n private func find(module: String, symbols: [String], in process: DWORD) -> [FARPROC]? {\n guard let hModule = find(module: module, in: process) else {\n print("Failed to find remote module \(module)")\n return nil\n }\n return symbols.map { GetProcAddress(hModule, $0) }\n }\n\n private func createEventPair(_ dwProcessId: DWORD) -> (HANDLE, HANDLE)? {\n let hReadEvent = CreateEvent("\(READ_EVENT_NAME_PREFIX)-\(dwProcessId)")\n guard let hReadEvent else { return nil }\n let hWriteEvent = CreateEvent("\(WRITE_EVENT_NAME_PREFIX)-\(dwProcessId)")\n guard let hWriteEvent else { CloseHandle(hReadEvent); return nil }\n return (hReadEvent, hWriteEvent)\n }\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_WindowsRemoteProcess.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_WindowsRemoteProcess.swift
Swift
18,345
0.95
0.077922
0.169492
vue-tools
945
2024-11-08T09:00:27.358289
BSD-3-Clause
false
884fd4cf35d75bdfdd3acc996aef1915
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if os(Windows)\n\nimport WinSDK\n\ninternal var FILE_MAP_ALL_ACCESS: DWORD {\n DWORD(STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |\n SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE |\n SECTION_EXTEND_SIZE)\n}\n\ninternal func CreateEvent(_ name: String, bManualReset: Bool = false,\n bInitialState: Bool = false) -> HANDLE? {\n let hEvent: HANDLE = CreateEventA(LPSECURITY_ATTRIBUTES(bitPattern: 0),\n bManualReset, bInitialState, name)\n if hEvent == HANDLE(bitPattern: 0) {\n print("CreateEvent failed \(GetLastError())")\n return nil\n }\n return hEvent\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_WinSDK+Extentions.swift
cpp_apple_swift_tools_swift-inspect_Sources_swift-inspect_WinSDK+Extentions.swift
Swift
1,163
0.95
0.117647
0.448276
python-kit
942
2024-10-30T16:54:20.122935
MIT
false
9504b651265775af6dea668b34e087ea
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport LinuxSystemHeaders\n\n// TODO: replace this implementation with general purpose ELF parsing support\n// currently private to swift/stdlib/public/Backtrace.\nclass ElfFile {\n public enum ELFError: Error {\n case notELF64(_ filePath: String, _ description: String = "")\n case malformedFile(_ filePath: String, _ description: String = "")\n }\n\n public typealias SymbolMap = [String: (start: UInt64, end: UInt64)]\n\n let filePath: String\n let fileData: Data\n let ehdr: Elf64_Ehdr\n\n public init(filePath: String) throws {\n self.filePath = filePath\n\n self.fileData = try Data(contentsOf: URL(fileURLWithPath: filePath), options: .alwaysMapped)\n\n let ident = fileData.prefix(upTo: Int(EI_NIDENT))\n\n guard String(bytes: ident.prefix(Int(SELFMAG)), encoding: .utf8) == ELFMAG else {\n throw ELFError.notELF64(filePath, "\(ident.prefix(Int(SELFMAG))) != ELFMAG")\n }\n\n guard ident[Int(EI_CLASS)] == ELFCLASS64 else {\n throw ELFError.notELF64(filePath, "\(ident[Int(EI_CLASS)]) != ELFCLASS64")\n }\n\n let ehdrSize = MemoryLayout<Elf64_Ehdr>.size\n self.ehdr = fileData[0..<ehdrSize].withUnsafeBytes { $0.load(as: Elf64_Ehdr.self) }\n }\n\n // returns a map of symbol names to their offset range in file (+ baseAddress)\n public func loadSymbols(baseAddress: UInt64 = 0) throws -> SymbolMap {\n guard let sectionCount = UInt(exactly: self.ehdr.e_shnum) else {\n throw ELFError.malformedFile(\n self.filePath, "invalid Elf64_Ehdr.e_shnum: \(self.ehdr.e_shnum)")\n }\n\n var symbols: SymbolMap = [:]\n for sectionIndex in 0..<sectionCount {\n let shdr: Elf64_Shdr = try self.loadShdr(index: sectionIndex)\n guard shdr.sh_type == SHT_SYMTAB || shdr.sh_type == SHT_DYNSYM else { continue }\n\n let symTableData: Data = try self.loadSection(shdr)\n let symTable: [Elf64_Sym] = symTableData.withUnsafeBytes {\n Array($0.bindMemory(to: Elf64_Sym.self))\n }\n\n guard shdr.sh_entsize == MemoryLayout<Elf64_Sym>.size else {\n throw ELFError.malformedFile(self.filePath, "invalid Elf64_Shdr.sh_entsize")\n }\n\n // the link field in the section header for a symbol table section refers\n // to the index of the string table section containing the symbol names\n guard let linkIndex = UInt(exactly: shdr.sh_link) else {\n throw ELFError.malformedFile(self.filePath, "invalid Elf64_Shdr.sh_link: \(shdr.sh_link)")\n }\n\n let shdrLink: Elf64_Shdr = try self.loadShdr(index: UInt(linkIndex))\n guard shdrLink.sh_type == SHT_STRTAB else {\n throw ELFError.malformedFile(self.filePath, "linked section not SHT_STRTAB")\n }\n\n // load the entire contents of the string table into memory\n let strTableData: Data = try self.loadSection(shdrLink)\n let strTable: [UInt8] = strTableData.withUnsafeBytes {\n Array($0.bindMemory(to: UInt8.self))\n }\n\n let symCount = Int(shdr.sh_size / shdr.sh_entsize)\n for symIndex in 0..<symCount {\n let sym = symTable[symIndex]\n guard sym.st_shndx != SHN_UNDEF, sym.st_value != 0, sym.st_size != 0 else { continue }\n\n // sym.st_name is a byte offset into the string table\n guard let strStart = Int(exactly: sym.st_name), strStart < strTable.count else {\n throw ELFError.malformedFile(self.filePath, "invalid string table offset: \(sym.st_name)")\n }\n\n guard let strEnd = strTable[strStart...].firstIndex(of: 0),\n let symName = String(bytes: strTable[strStart..<strEnd], encoding: .utf8)\n else {\n throw ELFError.malformedFile(self.filePath, "invalid string @ offset \(strStart)")\n }\n\n // rebase the symbol value on the base address provided by the caller\n let symStart = sym.st_value + baseAddress\n symbols[symName] = (start: symStart, end: symStart + sym.st_size)\n }\n }\n\n return symbols\n }\n\n // returns the Elf64_Shdr at the specified index\n internal func loadShdr(index: UInt) throws -> Elf64_Shdr {\n guard index < self.ehdr.e_shnum else {\n throw ELFError.malformedFile(\n self.filePath, "section index \(index) >= Elf64_Ehdr.e_shnum \(self.ehdr.e_shnum))")\n }\n\n let shdrSize = MemoryLayout<Elf64_Shdr>.size\n guard shdrSize == self.ehdr.e_shentsize else {\n throw ELFError.malformedFile(self.filePath, "Elf64_Ehdr.e_shentsize != \(shdrSize)")\n }\n\n let shdrOffset = Int(self.ehdr.e_shoff) + Int(index) * shdrSize\n let shdrData = self.fileData[shdrOffset..<(shdrOffset + shdrSize)]\n return shdrData.withUnsafeBytes { $0.load(as: Elf64_Shdr.self) }\n }\n\n // returns all data in the specified section\n internal func loadSection(_ shdr: Elf64_Shdr) throws -> Data {\n guard let sectionSize = Int(exactly: shdr.sh_size) else {\n throw ELFError.malformedFile(self.filePath, "Elf64_Shdr.sh_size too large \(shdr.sh_size)")\n }\n\n guard let fileOffset = Int(exactly: shdr.sh_offset) else {\n throw ELFError.malformedFile(\n self.filePath, "Elf64_Shdr.sh_offset too large \(shdr.sh_offset)")\n }\n\n return self.fileData[fileOffset..<(fileOffset + sectionSize)]\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_ElfFile.swift
cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_ElfFile.swift
Swift
5,651
0.95
0.077465
0.184211
python-kit
357
2023-12-21T13:07:45.917061
MIT
false
041cc0667f30bb9b723599275c581767
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport LinuxSystemHeaders\n\nclass LinkMap {\n public enum LinkMapError: Error {\n case failedLoadingAuxVec(for: pid_t)\n case missingAuxVecEntry(for: pid_t, _ tag: Int32)\n case malformedELF(for: pid_t, _ description: String)\n }\n\n public struct Entry {\n let baseAddress: UInt64\n let moduleName: String\n }\n\n public let entries: [Entry]\n\n public init(for process: Process) throws {\n let auxVec = try Self.loadAuxVec(for: process.pid)\n guard let phdrAddr = auxVec[AT_PHDR] else {\n throw LinkMapError.missingAuxVecEntry(for: process.pid, AT_PHDR)\n }\n\n guard let phdrSize = auxVec[AT_PHENT] else {\n throw LinkMapError.missingAuxVecEntry(for: process.pid, AT_PHENT)\n }\n\n guard let phdrCount = auxVec[AT_PHNUM] else {\n throw LinkMapError.missingAuxVecEntry(for: process.pid, AT_PHNUM)\n }\n\n guard phdrSize == MemoryLayout<Elf64_Phdr>.size else {\n throw LinkMapError.malformedELF(for: process.pid, "AT_PHENT invalid size: \(phdrSize)")\n }\n\n // determine the base load address for the executable file and locate the\n // dynamic segment\n var dynamicSegment: Elf64_Phdr? = nil\n var baseLoadSegment: Elf64_Phdr? = nil\n for i in 0...phdrCount {\n let address: UInt64 = phdrAddr + i * phdrSize\n let phdr: Elf64_Phdr = try process.readStruct(address: address)\n\n switch phdr.p_type {\n case UInt32(PT_LOAD):\n // chose the PT_LOAD segment with the lowest p_vaddr value, which will\n // typically be zero\n if let loadSegment = baseLoadSegment {\n if phdr.p_vaddr < loadSegment.p_vaddr { baseLoadSegment = phdr }\n } else {\n baseLoadSegment = phdr\n }\n\n case UInt32(PT_DYNAMIC):\n guard dynamicSegment == nil else {\n throw LinkMapError.malformedELF(for: process.pid, "multiple PT_DYNAMIC segments found")\n }\n dynamicSegment = phdr\n\n default: continue\n }\n }\n\n guard let dynamicSegment = dynamicSegment else {\n throw LinkMapError.malformedELF(for: process.pid, "PT_DYNAMIC segment not found")\n }\n\n guard let baseLoadSegment = baseLoadSegment else {\n throw LinkMapError.malformedELF(for: process.pid, "PT_LOAD segment not found")\n }\n\n let ehdrSize = MemoryLayout<Elf64_Ehdr>.size\n let loadAddr: UInt64 = phdrAddr - UInt64(ehdrSize)\n let baseAddr: UInt64 = loadAddr - baseLoadSegment.p_vaddr\n let dynamicSegmentAddr: UInt64 = baseAddr + dynamicSegment.p_vaddr\n\n // parse through the dynamic segment to find the location of the .debug section\n var rDebugEntry: Elf64_Dyn? = nil\n let entrySize = MemoryLayout<Elf64_Dyn>.size\n let dynamicEntryCount = UInt(dynamicSegment.p_memsz / UInt64(entrySize))\n for i in 0...dynamicEntryCount {\n let address: UInt64 = dynamicSegmentAddr + UInt64(i) * UInt64(entrySize)\n let dyn: Elf64_Dyn = try process.readStruct(address: address)\n if dyn.d_tag == DT_DEBUG {\n rDebugEntry = dyn\n break\n }\n }\n\n guard let rDebugEntry = rDebugEntry else {\n throw LinkMapError.malformedELF(for: process.pid, "DT_DEBUG not found in dynamic segment")\n }\n\n let rDebugAddr: UInt64 = rDebugEntry.d_un.d_val\n let rDebug: r_debug = try process.readStruct(address: rDebugAddr)\n\n var entries: [Entry] = []\n var linkMapAddr = UInt(bitPattern: rDebug.r_map)\n while linkMapAddr != 0 {\n let linkMap: link_map = try process.readStruct(address: UInt64(linkMapAddr))\n let nameAddr = UInt(bitPattern: linkMap.l_name)\n let name = try process.readString(address: UInt64(nameAddr))\n entries.append(Entry(baseAddress: linkMap.l_addr, moduleName: name))\n\n linkMapAddr = UInt(bitPattern: linkMap.l_next)\n }\n\n self.entries = entries\n }\n\n // loads the auxiliary vector for a 64-bit process\n static func loadAuxVec(for pid: pid_t) throws -> [Int32: UInt64] {\n guard let data = ProcFS.loadFile(for: pid, "auxv") else {\n throw LinkMapError.failedLoadingAuxVec(for: pid)\n }\n\n return data.withUnsafeBytes {\n // in a 64-bit process, aux vector is an array of 8-byte pairs\n let count = $0.count / MemoryLayout<(UInt64, UInt64)>.stride\n let auxVec = Array($0.bindMemory(to: (UInt64, UInt64).self)[..<count])\n\n var entries: [Int32: UInt64] = [:]\n for (rawTag, value) in auxVec {\n // the AT_ constants defined in linux/auxv.h are imported as Int32\n guard let tag = Int32(exactly: rawTag) else { continue }\n entries[tag] = UInt64(value)\n }\n\n return entries\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_LinkMap.swift
cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_LinkMap.swift
Swift
5,071
0.95
0.243056
0.159664
awesome-app
580
2025-04-10T09:59:27.266029
MIT
false
9283c1de5baf0b16a2d28adddcffc782
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic class MemoryMap {\n public enum MemoryMapError: Error {\n case failedLoadingMapsFile(for: pid_t)\n }\n\n public struct Entry {\n public let startAddr: UInt64\n public let endAddr: UInt64\n public let permissions: String\n public let offset: UInt64\n public let device: String\n public let inode: UInt64\n public let pathname: String?\n }\n\n public let entries: [Entry]\n\n public init(for pid: pid_t) throws {\n guard let content = ProcFS.loadFileAsString(for: pid, "maps") else {\n throw MemoryMapError.failedLoadingMapsFile(for: pid)\n }\n\n var entries: [Entry] = []\n\n content.enumerateLines { (line, _) in\n let components = line.split(separator: " ", omittingEmptySubsequences: true)\n guard components.count >= 5 else { return }\n let addrParts = components[0].split(separator: "-")\n let entry = Entry(\n startAddr: UInt64(addrParts[0], radix: 16) ?? 0,\n endAddr: UInt64(addrParts[1], radix: 16) ?? 0, permissions: String(components[1]),\n offset: UInt64(components[2], radix: 16) ?? 0, device: String(components[3]),\n inode: UInt64(components[4]) ?? 0,\n pathname: components.count == 6 ? String(components[5]) : nil)\n entries.append(entry)\n }\n\n self.entries = entries\n }\n\n public func findEntry(containing addr: UInt64) -> Entry? {\n // The map array returned by loadMaps will be ordered the same as the\n // contents of /proc/<pid>/maps, which is in ascending address order.\n // Binary search it to find the entry containing the target address.\n var lowerBound = 0\n var upperBound = self.entries.count\n while lowerBound < upperBound {\n let currentIndex = (lowerBound + upperBound) / 2\n let entry = self.entries[currentIndex]\n if entry.startAddr > addr {\n upperBound = currentIndex\n } else if entry.endAddr <= addr {\n lowerBound = currentIndex + 1\n } else {\n precondition(addr >= entry.startAddr)\n precondition(addr < entry.endAddr)\n return entry\n }\n }\n return nil\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_MemoryMap.swift
cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_MemoryMap.swift
Swift
2,600
0.95
0.131579
0.208955
vue-tools
501
2025-01-07T15:15:53.456503
Apache-2.0
false
4b08ef8cbccffa37f5d4f0e405637349
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport LinuxSystemHeaders\n\n// The Android version of iovec defineds iov_len as __kernel_size_t, while the\n// standard Linux definition is size_t. This extension makes the difference\n// easier to deal with.\nextension iovec {\n public init<T: BinaryInteger>(iov_base: UnsafeMutableRawPointer?, iov_len: T) {\n self.init()\n self.iov_base = iov_base\n #if os(Android)\n self.iov_len = __kernel_size_t(iov_len)\n #else\n self.iov_len = size_t(iov_len)\n #endif\n }\n}\n\npublic class Process {\n public enum ProcessError: Error {\n case processVmReadFailure(pid: pid_t, address: UInt64, size: UInt64)\n case processVmWriteFailure(pid: pid_t, address: UInt64, size: UInt64)\n case malformedString(address: UInt64)\n }\n\n let pid: pid_t\n let elfFile: ElfFile\n\n public init(_ pid: pid_t) throws {\n self.pid = pid\n let executableFilePath = "/proc/\(pid)/exe"\n self.elfFile = try ElfFile(filePath: executableFilePath)\n }\n\n // read a struct of type T from the target process\n public func readStruct<T>(address: UInt64) throws -> T {\n let result: [T] = try readArray(address: address, upToCount: 1)\n return result.first!\n }\n\n // read a null-terminated string from the target process\n public func readString(address: UInt64, encoding: String.Encoding = .utf8) throws -> String {\n let rawBytes = try readRawString(address: address)\n guard let result = String(bytes: rawBytes, encoding: encoding) else {\n throw ProcessError.malformedString(address: address)\n }\n\n return result\n }\n\n // read bytes from the remote process until a zero-byte is encountered; the\n // zero-byte is not included in the result\n public func readRawString(address: UInt64) throws -> [UInt8] {\n var readAddress: UInt64 = address\n let chunkSize: UInt = 64\n var result: [UInt8] = []\n\n while true {\n let chunk: [UInt8] = try readArray(address: readAddress, upToCount: chunkSize)\n\n if let nullIndex = chunk.firstIndex(of: 0) {\n result.append(contentsOf: chunk.prefix(nullIndex))\n break\n }\n\n result.append(contentsOf: chunk)\n readAddress += UInt64(chunkSize)\n }\n\n return result\n }\n\n // read an array of type T elements from the target process\n public func readArray<T>(address: UInt64, upToCount: UInt) throws -> [T] {\n guard upToCount > 0 else { return [] }\n\n let maxSize = upToCount * UInt(MemoryLayout<T>.stride)\n let array: [T] = Array(unsafeUninitializedCapacity: Int(upToCount)) { buffer, initCount in\n var local = iovec(iov_base: buffer.baseAddress!, iov_len: maxSize)\n var remote = iovec(\n iov_base: UnsafeMutableRawPointer(bitPattern: UInt(address)), iov_len: maxSize)\n let bytesRead = process_vm_readv(self.pid, &local, 1, &remote, 1, 0)\n initCount = bytesRead / MemoryLayout<T>.stride\n }\n\n guard array.count > 0 else {\n throw ProcessError.processVmReadFailure(\n pid: self.pid, address: address, size: UInt64(maxSize))\n }\n\n return array\n }\n\n // simple wrapper around process_vm_readv\n public func readMem(remoteAddr: UInt64, localAddr: UnsafeRawPointer, len: UInt) throws {\n var local = iovec(iov_base: UnsafeMutableRawPointer(mutating: localAddr), iov_len: len)\n var remote = iovec(\n iov_base: UnsafeMutableRawPointer(bitPattern: UInt(remoteAddr)), iov_len: len)\n\n let bytesRead = process_vm_readv(self.pid, &local, 1, &remote, 1, 0)\n guard bytesRead == len else {\n throw ProcessError.processVmReadFailure(pid: self.pid, address: remoteAddr, size: UInt64(len))\n }\n }\n\n // simple wrapper around process_vm_writev\n public func writeMem(remoteAddr: UInt64, localAddr: UnsafeRawPointer, len: UInt) throws {\n var local = iovec(iov_base: UnsafeMutableRawPointer(mutating: localAddr), iov_len: len)\n var remote = iovec(\n iov_base: UnsafeMutableRawPointer(bitPattern: UInt(remoteAddr)), iov_len: len)\n\n let bytesWritten = process_vm_writev(self.pid, &local, 1, &remote, 1, 0)\n guard bytesWritten == len else {\n throw ProcessError.processVmWriteFailure(\n pid: self.pid, address: remoteAddr, size: UInt64(len))\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_Process.swift
cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_Process.swift
Swift
4,660
0.95
0.084615
0.220183
python-kit
916
2024-06-11T04:58:32.562307
Apache-2.0
false
9da333903694c746d3437a4acaf1914b
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport LinuxSystemHeaders\n\n// utility for reading files under /proc\npublic enum ProcFS {\n public static func loadFile(for pid: pid_t, _ fileName: String) -> Data? {\n let filePath = "/proc/\(pid)/\(fileName)"\n // Loading contents of files under /proc may not work correctly using\n // Data(contentsOf:) or String(contentsOfFile:) because the files may\n // appear empty from stat(2) and may not be seekable. FileHandle.readToEnd\n // handles these cases.\n guard let fileHandle = FileHandle(forReadingAtPath: filePath) else { return nil }\n defer { fileHandle.closeFile() }\n guard let data = try? fileHandle.readToEnd() else { return nil }\n return data\n }\n\n public static func loadFileAsString(\n for pid: pid_t, _ fileName: String, encoding: String.Encoding = .utf8\n ) -> String? {\n guard let data = Self.loadFile(for: pid, fileName) else { return nil }\n return String(data: data, encoding: encoding)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_ProcFS.swift
cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_ProcFS.swift
Swift
1,479
0.95
0.194444
0.484848
awesome-app
579
2024-04-13T02:40:35.094767
BSD-3-Clause
false
5e42e8128fd666ddc3d58b4a7ac8affa
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport LinuxSystemHeaders\n\n// Provides scoped access to a PTrace object.\npublic func withPTracedProcess(pid: pid_t, _ closure: (consuming PTrace) throws -> Void) throws {\n let ptrace = try PTrace(pid)\n try closure(ptrace)\n}\n\npublic struct PTrace: ~Copyable {\n enum PTraceError: Error {\n case operationFailure(_ command: CInt, pid: pid_t, errno: CInt = get_errno())\n case waitFailure(pid: pid_t, errno: CInt = get_errno())\n case unexpectedWaitStatus(pid: pid_t, status: CInt, sigInfo: siginfo_t? = nil)\n }\n\n let pid: pid_t\n\n // Initializing a PTrace instance attaches to the target process, waits for\n // it to stop, and leaves it in a stopped state. The caller may resume the\n // process by calling cont().\n // NOTE: clients must use withPTracedProcess instead of direct initialization.\n fileprivate init(_ pid: pid_t) throws {\n self.pid = pid\n\n guard ptrace_attach(self.pid) != -1 else {\n throw PTraceError.operationFailure(PTRACE_ATTACH, pid: self.pid)\n }\n\n while true {\n var status: CInt = 0\n let result = waitpid(self.pid, &status, 0)\n if result == -1 {\n if get_errno() == EINTR { continue }\n throw PTraceError.waitFailure(pid: self.pid)\n }\n\n precondition(self.pid == result,\n "waitpid returned unexpected value \(result)")\n\n if wIfStopped(status) { break }\n }\n }\n\n deinit { _ = ptrace_detach(self.pid) }\n\n public func cont() throws {\n if ptrace_cont(self.pid) == -1 {\n throw PTraceError.operationFailure(PTRACE_CONT, pid: self.pid)\n }\n }\n\n public func interrupt() throws {\n if ptrace_interrupt(self.pid) == -1 {\n throw PTraceError.operationFailure(PTRACE_INTERRUPT, pid: self.pid)\n }\n }\n\n public func getSigInfo() throws -> siginfo_t {\n var sigInfo = siginfo_t()\n if ptrace_getsiginfo(self.pid, &sigInfo) == -1 {\n throw PTraceError.operationFailure(PTRACE_GETSIGINFO, pid: self.pid)\n }\n\n return sigInfo\n }\n\n public func pokeData(addr: UInt64, value: UInt64) throws {\n if ptrace_pokedata(self.pid, UInt(addr), UInt(value)) == -1 {\n throw PTraceError.operationFailure(PTRACE_POKEDATA, pid: self.pid)\n }\n }\n\n public func getRegSet() throws -> RegisterSet {\n var regSet = RegisterSet()\n try withUnsafeMutableBytes(of: &regSet) {\n var vec = iovec(iov_base: $0.baseAddress!, iov_len: MemoryLayout<RegisterSet>.size)\n if ptrace_getregset(self.pid, NT_PRSTATUS, &vec) == -1 {\n throw PTraceError.operationFailure(PTRACE_GETREGSET, pid: self.pid)\n }\n }\n\n return regSet\n }\n\n public func setRegSet(regSet: RegisterSet) throws {\n var regSetCopy = regSet\n try withUnsafeMutableBytes(of: &regSetCopy) {\n var vec = iovec(iov_base: $0.baseAddress!, iov_len: MemoryLayout<RegisterSet>.size)\n if ptrace_setregset(self.pid, NT_PRSTATUS, &vec) == -1 {\n throw PTraceError.operationFailure(PTRACE_SETREGSET, pid: self.pid)\n }\n }\n }\n\n // Call the function at the specified address in the attached process with the\n // provided argument array. The optional callback is invoked when the process\n // is stopped with a SIGTRAP signal. In this case, the caller is responsible\n // for taking action on the signal.\n public func jump(\n to address: UInt64, with args: [UInt64] = [],\n _ callback: ((borrowing PTrace) throws -> Void)? = nil\n ) throws -> UInt64 {\n let origRegs = try self.getRegSet()\n defer { try? self.setRegSet(regSet: origRegs) }\n\n // Set the return address to 0. This forces the function to return to 0 on\n // completion, resulting in a SIGSEGV with address 0 which will interrupt\n // the process and notify us (the tracer) via waitpid(). At that point, we\n // will restore the original state and continue the process.\n let returnAddr: UInt64 = 0\n\n var newRegs = try origRegs.setupCall(self, to: address, with: args, returnTo: returnAddr)\n try self.setRegSet(regSet: newRegs)\n try self.cont()\n\n var status: CInt = 0\n while true {\n let result = waitpid(self.pid, &status, 0)\n guard result != -1 else {\n if get_errno() == EINTR { continue }\n throw PTraceError.waitFailure(pid: self.pid)\n }\n\n precondition(self.pid == result, "waitpid returned unexpected value \(result)")\n\n guard wIfStopped(status) && !wIfExited(status) && !wIfSignaled(status) else {\n throw PTraceError.unexpectedWaitStatus(pid: self.pid, status: status)\n }\n\n guard wStopSig(status) == SIGTRAP, let callback = callback else { break }\n\n // give the caller the opportunity to handle SIGTRAP\n try callback(self)\n }\n\n let sigInfo = try self.getSigInfo()\n newRegs = try self.getRegSet()\n\n guard wStopSig(status) == SIGSEGV, siginfo_si_addr(sigInfo) == nil else {\n throw PTraceError.unexpectedWaitStatus(pid: self.pid, status: status, sigInfo: sigInfo)\n }\n\n return UInt64(newRegs.returnValue())\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_PTrace.swift
cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_PTrace.swift
Swift
5,456
0.95
0.189873
0.193798
node-utils
729
2023-10-26T21:11:28.428474
Apache-2.0
false
37c34e1e20a9fa4d88005f9539df0294
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport LinuxSystemHeaders\n\n#if arch(arm64)\npublic typealias RegisterSet = user_pt_regs\n\nextension RegisterSet {\n public static var trapInstructionSize: UInt { return 4 } // brk #0x0\n\n public func setupCall(\n _ ptrace: borrowing PTrace, to funcAddr: UInt64, with args: [UInt64],\n returnTo returnAddr: UInt64\n ) throws -> RegisterSet {\n // The first 8 arguments are passed in regsters. Any additional arguments\n // must be pushed on the stack, which is not implemented.\n precondition(args.count <= 8)\n\n var registers = self\n registers.regs.0 = args.count > 0 ? args[0] : 0\n registers.regs.1 = args.count > 1 ? args[1] : 0\n registers.regs.2 = args.count > 2 ? args[2] : 0\n registers.regs.3 = args.count > 3 ? args[3] : 0\n registers.regs.4 = args.count > 4 ? args[4] : 0\n registers.regs.5 = args.count > 5 ? args[5] : 0\n registers.regs.6 = args.count > 6 ? args[6] : 0\n registers.regs.7 = args.count > 7 ? args[7] : 0\n registers.pc = funcAddr\n registers.regs.30 = returnAddr // link register (x30)\n return registers\n }\n\n public func returnValue() -> UInt64 {\n return self.regs.0\n }\n\n public mutating func step(_ bytes: UInt) {\n self.pc += UInt64(bytes)\n }\n}\n\n#elseif arch(x86_64)\npublic typealias RegisterSet = pt_regs\n\nextension RegisterSet {\n public static var trapInstructionSize: UInt { return 1 } // int3\n\n public func setupCall(\n _ ptrace: borrowing PTrace, to funcAddr: UInt64, with args: [UInt64],\n returnTo returnAddr: UInt64\n ) throws -> RegisterSet {\n // The first 6 arguments are passed in registers. Any additional arguments\n // must be pushed on the stack, which is not implemented.\n precondition(args.count <= 6)\n\n var registers = self\n registers.rdi = UInt(args.count > 0 ? args[0] : 0)\n registers.rsi = UInt(args.count > 1 ? args[1] : 0)\n registers.rdx = UInt(args.count > 2 ? args[2] : 0)\n registers.rcx = UInt(args.count > 3 ? args[3] : 0)\n registers.r8 = UInt(args.count > 4 ? args[4] : 0)\n registers.r9 = UInt(args.count > 5 ? args[5] : 0)\n registers.rip = UInt(funcAddr)\n registers.rax = 0 // rax is the number of args in a va_args function\n\n // push the return address onto the stack\n registers.rsp -= UInt(MemoryLayout<UInt64>.size)\n try ptrace.pokeData(addr: UInt64(registers.rsp), value: returnAddr)\n\n return registers\n }\n\n public func returnValue() -> UInt64 {\n return UInt64(self.rax)\n }\n\n public mutating func step(_ bytes: UInt) {\n self.rip += UInt(bytes)\n }\n}\n#else\n#error("Only arm64 and x86_64 architectures are supported")\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_RegisterSet.swift
cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_RegisterSet.swift
Swift
3,135
0.95
0.053191
0.265823
awesome-app
461
2024-02-18T04:03:23.078743
GPL-3.0
false
ab9e9594b6c2cc767490df3c548979b8
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport LinuxSystemHeaders\n\npublic class SymbolCache {\n public typealias SymbolRange = (start: UInt64, end: UInt64)\n public typealias SymbolInfo = (start: UInt64, end: UInt64, module: String, name: String)\n public typealias SymbolLookup = [String: [String: SymbolRange]]\n\n public let symbolLookup: SymbolLookup\n let linkMap: LinkMap\n\n // an array of all symbols sorted by their start address\n lazy var sortedAddressLookup: [SymbolInfo] = {\n var addressLookup: [SymbolInfo] = []\n for (module, symbols) in self.symbolLookup {\n for (name, (start, end)) in symbols {\n addressLookup.append((start: start, end: end, module: module, name: name))\n }\n }\n addressLookup.sort { $0.start < $1.start }\n return addressLookup\n }()\n\n public init(for process: Process) throws {\n self.linkMap = try LinkMap(for: process)\n var symbolLookup: SymbolLookup = [:]\n for linkMapEntry in linkMap.entries {\n guard let elfFile = try? ElfFile(filePath: linkMapEntry.moduleName) else { continue }\n let symbolMap = try elfFile.loadSymbols(baseAddress: linkMapEntry.baseAddress)\n symbolLookup[linkMapEntry.moduleName] = symbolMap\n }\n self.symbolLookup = symbolLookup\n }\n\n // find the address range for the requested symbol\n public func address(of symbol: String) -> SymbolRange? {\n for (_, symbols) in symbolLookup { if let range = symbols[symbol] { return range } }\n return nil\n }\n\n // find and return symbol that contains the specified address\n public func symbol(for address: UInt64) -> SymbolInfo? {\n var lowerBound = 0\n var upperBound = self.sortedAddressLookup.count\n while lowerBound < upperBound {\n let currentIndex = (lowerBound + upperBound) / 2\n let entry = self.sortedAddressLookup[currentIndex]\n if entry.start > address {\n upperBound = currentIndex\n } else if entry.end <= address {\n lowerBound = currentIndex + 1\n } else {\n precondition(address >= entry.start)\n precondition(address < entry.end)\n return entry\n }\n }\n return nil\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_SymbolCache.swift
cpp_apple_swift_tools_swift-inspect_Sources_SwiftInspectLinux_SymbolCache.swift
Swift
2,617
0.95
0.25
0.215385
vue-tools
503
2024-12-17T03:15:39.792459
Apache-2.0
false
a790a68995e1961765ae78479561e74d
// swift-tools-version: 5.9\n\nimport PackageDescription\n\nlet package = Package(\n name: "swift-plugin-server",\n platforms: [\n .macOS(.v13)\n ],\n products: [\n .executable(name: "swift-plugin-server", targets: ["swift-plugin-server"]),\n .library(name: "SwiftInProcPluginServer", type: .dynamic, targets: ["SwiftInProcPluginServer"]),\n ],\n dependencies: [\n .package(path: "../../../swift-syntax"),\n ],\n targets: [\n .executableTarget(\n name: "swift-plugin-server",\n dependencies: [\n .product(name: "_SwiftCompilerPluginMessageHandling", package: "swift-syntax"),\n .product(name: "_SwiftLibraryPluginProvider", package: "swift-syntax"),\n ]\n ),\n .target(\n name: "SwiftInProcPluginServer",\n dependencies: [\n .product(name: "_SwiftCompilerPluginMessageHandling", package: "swift-syntax"),\n .product(name: "_SwiftLibraryPluginProvider", package: "swift-syntax"),\n ]\n ),\n ],\n cxxLanguageStandard: .cxx17\n)\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-plugin-server_Package.swift
cpp_apple_swift_tools_swift-plugin-server_Package.swift
Swift
985
0.95
0
0.03125
python-kit
807
2024-09-25T21:30:02.279994
GPL-3.0
false
c0b67955275f693999da7e2ae33c6acd
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(PluginMessage) import SwiftCompilerPluginMessageHandling\n@_spi(PluginMessage) import SwiftLibraryPluginProvider\n\n@main\nfinal class SwiftPluginServer {\n static func main() throws {\n let connection = try StandardIOMessageConnection()\n let listener = CompilerPluginMessageListener(\n connection: connection,\n provider: LibraryPluginProvider.shared\n )\n try listener.main()\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-plugin-server_Sources_swift-plugin-server_swift-plugin-server.swift
cpp_apple_swift_tools_swift-plugin-server_Sources_swift-plugin-server_swift-plugin-server.swift
Swift
910
0.95
0.192308
0.458333
node-utils
766
2024-01-31T01:26:02.523541
Apache-2.0
false
0e0971bf11d01f57541238b5e65d577c
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(PluginMessage) import SwiftCompilerPluginMessageHandling\n@_spi(PluginMessage) import SwiftLibraryPluginProvider\n\n#if canImport(Darwin)\nimport Darwin\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Bionic)\nimport Bionic\n#elseif canImport(Musl)\nimport Musl\n#elseif canImport(ucrt)\nimport ucrt\n#else\n#error("'malloc' not found")\n#endif\n\n/// Entry point.\n///\n/// Compiler 'dlopen' this 'SwiftInProcPluginServer' library, and 'dlsym' this\n/// function. When the compiler wants to use dylib plugins, it calls this\n/// function with the same message as `swift-plugin-server`.\n///\n/// The caller must `free` the returned buffer\n@_cdecl("swift_inproc_plugins_handle_message")\n@MainActor\npublic func handleMessage(\n _ inputData: UnsafePointer<UInt8>!,\n _ inputLength: Int,\n _ outputData: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>!,\n _ outputLength: UnsafeMutablePointer<Int>!\n) -> Bool {\n do {\n let input = UnsafeBufferPointer(start: inputData, count: inputLength)\n let output = try InProcPluginServer.shared.handleMessage(input)\n output.withUnsafeBufferPointer(fillOutput(_:))\n return false // Success.\n } catch {\n var message = "Internal Error: \(error)"\n message.withUTF8(fillOutput(_:))\n return true // Error.\n }\n\n func fillOutput(_ responseData: UnsafeBufferPointer<UInt8>) {\n // NOTE: Use 'malloc' instead of 'UnsafeMutablePointer.allocate()' so that\n // C/C++ clients can deallocate it without using Swift.\n let buffer = malloc(responseData.count)!\n buffer.initializeMemory(\n as: UInt8.self,\n from: responseData.baseAddress!,\n count: responseData.count\n )\n outputData.pointee = buffer.assumingMemoryBound(to: UInt8.self)\n outputLength.pointee = responseData.count\n }\n}\n\n/// Singleton "plugin server".\nstruct InProcPluginServer {\n private let handler: PluginProviderMessageHandler<LibraryPluginProvider>\n\n @MainActor\n private init() {\n self.handler = PluginProviderMessageHandler(\n provider: LibraryPluginProvider.shared\n )\n }\n\n func handleMessage(_ input: UnsafeBufferPointer<UInt8>) throws -> [UInt8] {\n let request = try JSON.decode(HostToPluginMessage.self, from: input)\n let response = handler.handleMessage(request)\n return try JSON.encode(response)\n }\n\n @MainActor\n static let shared = Self()\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_tools_swift-plugin-server_Sources_SwiftInProcPluginServer_InProcPluginServer.swift
cpp_apple_swift_tools_swift-plugin-server_Sources_SwiftInProcPluginServer_InProcPluginServer.swift
Swift
2,824
0.95
0.1
0.358025
node-utils
776
2024-11-17T17:45:20.304677
BSD-3-Clause
false
471ed16a2f9d5ca81de99847e5c84135
// swift-tools-version:5.6\n\nimport PackageDescription\n\nlet package = Package(\n name: "GenUnicodeData",\n platforms: [.macOS(.v12)],\n targets: [\n .target(\n name: "GenUtils",\n dependencies: []\n ),\n .executableTarget(\n name: "GenGraphemeBreakProperty",\n dependencies: ["GenUtils"]\n ),\n .executableTarget(\n name: "GenNormalization",\n dependencies: ["GenUtils"]\n ),\n .executableTarget(\n name: "GenScalarProps",\n dependencies: ["GenUtils"]\n ),\n .executableTarget(\n name: "GenWordBreak",\n dependencies: ["GenUtils"]\n ),\n .executableTarget(\n name: "GenCaseFolding",\n dependencies: ["GenUtils"]\n ),\n .executableTarget(\n name: "GenScripts",\n dependencies: ["GenUtils"]\n )\n ]\n)\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Package.swift
cpp_apple_swift_utils_gen-unicode-data_Package.swift
Swift
782
0.95
0
0.027778
awesome-app
742
2025-06-16T23:58:08.610326
MIT
false
34a9fad7d9368c754a07af9b233906ea
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nextension Unicode {\n enum GraphemeBreakProperty: UInt32 {\n // We don't store the other properties, so we really don't care about them\n // here.\n\n case control = 0\n case extend = 1\n case prepend = 2\n case spacingMark = 3\n case extendedPictographic = 4\n\n init?(_ str: String) {\n switch str {\n case "Extend":\n self = .extend\n\n // Although CR and LF are distinct properties, we have fast paths in place\n // for those cases, so combine them here to allow for more contiguous\n // ranges.\n case "Control",\n "CR",\n "LF":\n self = .control\n case "Prepend":\n self = .prepend\n case "SpacingMark":\n self = .spacingMark\n case "Extended_Pictographic":\n self = .extendedPictographic\n default:\n return nil\n }\n }\n }\n\n enum IndicConjunctBreakProperty: String {\n case consonant = "Consonant"\n case extend = "Extend"\n // we just manually check for linker in StringGraphemeBreaking.swift\n }\n}\n\nstruct GraphemeBreakEntry : Comparable {\n static func < (lhs: GraphemeBreakEntry, rhs: GraphemeBreakEntry) -> Bool {\n return lhs.index < rhs.index\n }\n \n let index: Int\n let range: ClosedRange<UInt32>\n let property: Unicode.GraphemeBreakProperty\n}\n\n// Given a path to one of the Unicode data files, reads it and returns the\n// unflattened list of scalar & grapheme break property.\n//\n// Each line in one of these data files is formatted like the following:\n//\n// 007F..009F ; Control # Cc [33] <control-007F>..<control-009F>\n// 00AD ; Control # Cf SOFT HYPHEN\n//\n// Where each section is split by a ';'. The first section informs us of either\n// the range of scalars who conform to this property or the singular scalar\n// who does. The second section tells us what grapheme break property these\n// scalars conform to. There are extra comments telling us what general\n// category these scalars are a part of, how many scalars are in a range, and\n// the name of the scalars.\nfunc getGraphemeBreakPropertyData(\n for path: String\n) -> [(ClosedRange<UInt32>, Unicode.GraphemeBreakProperty)] {\n let data = readFile(path)\n\n var unflattened: [(ClosedRange<UInt32>, Unicode.GraphemeBreakProperty)] = []\n\n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n\n // Each line in this file is broken up into two sections:\n // 1: Either the singular scalar or a range of scalars who conform to said\n // grapheme break property.\n // 2: The grapheme break property that said scalar(s) conform to (with\n // additional comments noting the character category, name and amount of\n // scalars the range represents).\n let components = line.split(separator: ";")\n\n // Get the property first because it may be one we don't care about.\n let splitProperty = components[1].split(separator: "#")\n let filteredProperty = splitProperty[0].filter { !$0.isWhitespace }\n\n guard let gbp = Unicode.GraphemeBreakProperty(filteredProperty) else {\n continue\n }\n\n let scalars: ClosedRange<UInt32>\n\n let filteredScalars = components[0].filter { !$0.isWhitespace }\n\n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n\n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n\n scalars = scalar ... scalar\n }\n\n unflattened.append((scalars, gbp))\n }\n\n return unflattened\n}\n\nfunc getInCB(\n _ incb: Unicode.IndicConjunctBreakProperty,\n from data: String\n) -> [ClosedRange<UInt32>] {\n var unflattened: [(ClosedRange<UInt32>, Unicode.IndicConjunctBreakProperty)] = []\n \n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let components = line.split(separator: ";")\n \n // Get the property first because it may be one we don't care about.\n let filteredProperty = components[1].filter { !$0.isWhitespace }\n \n // We only care about 'InCB' properties.\n guard filteredProperty == "InCB" else {\n continue\n }\n\n let splitInCBProperty = components[2].split(separator: "#")\n let filteredInCBProperty = splitInCBProperty[0].filter { !$0.isWhitespace }\n\n guard filteredInCBProperty == incb.rawValue else {\n continue\n }\n\n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n unflattened.append((scalars, incb))\n }\n \n return flatten(unflattened).map { $0.0 }\n}\n\n// Takes the flattened data and writes it as a static C array.\nfunc emit(\n _ data: [GraphemeBreakEntry],\n into result: inout String\n) {\n result += """\n #define GRAPHEME_BREAK_DATA_COUNT \(data.count)\n \n static const __swift_uint32_t _swift_stdlib_graphemeBreakProperties[\(data.count)] = {\n\n """\n\n formatCollection(data, into: &result) { (entry) -> String in\n let range = entry.range\n let gbp = entry.property\n // Our value uses the 21 bits to represent the scalar, 8 bits to represent\n // the range's count, and finally the last three bits to represent the\n // grapheme break property enum.\n\n // E.g. for the top 3 bits:\n // 000 = control\n // 001 = extend\n // 010 = prepend\n // 011 = spacingMark\n // 100 = extendedPictographic (not using the extra range bit)\n // 101 = extendedPictographic (using the extra range bit)\n // 110 = not used (will never occur)\n // 111 = not used (will never occur)\n\n var value = range.lowerBound\n value |= UInt32(range.count - 1) << 21\n value |= gbp.rawValue << 29\n\n // However, for extendedPictographic because we don't use second to top bit,\n // we can use an extra bit for the range value to store more.\n if gbp == .extendedPictographic {\n value = range.lowerBound\n value |= UInt32(range.count - 1) << 21\n value |= 1 << 31\n }\n\n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n\n result += """\n \n };\n \n \n """\n}\n\nfunc emitInCB(\n _ incb: Unicode.IndicConjunctBreakProperty,\n _ data: [ClosedRange<UInt32>],\n into result: inout String\n) {\n // 64 bit arrays * 8 bytes = .512 KB\n var bitArrays: [BitArray] = .init(repeating: .init(size: 64), count: 64)\n \n let chunkSize = 0x110000 / 64 / 64\n \n var chunks: [Int] = []\n \n for i in 0 ..< 64 * 64 {\n let lower = i * chunkSize\n let upper = lower + chunkSize - 1\n \n let idx = i / 64\n let bit = i % 64\n \n for scalar in lower ... upper {\n if data.contains(where: { $0.contains(UInt32(scalar)) }) {\n chunks.append(i)\n \n bitArrays[idx][bit] = true\n break\n }\n }\n }\n \n // Remove the trailing 0s. Currently this reduces quick look size down to\n // 96 bytes from 512 bytes.\n var reducedBA = Array(bitArrays.reversed())\n reducedBA = Array(reducedBA.drop {\n $0.words == [0x0]\n })\n \n bitArrays = reducedBA.reversed()\n \n // Keep a record of every rank for all the bitarrays.\n var ranks: [UInt16] = []\n \n // Record our quick look ranks.\n var lastRank: UInt16 = 0\n for (i, _) in bitArrays.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(bitArrays[i - 1].words[0].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n \n lastRank = rank\n }\n \n // Insert our quick look size at the beginning.\n var size = BitArray(size: 64)\n size.words = [UInt64(bitArrays.count)]\n bitArrays.insert(size, at: 0)\n \n for chunk in chunks {\n var chunkBA = BitArray(size: chunkSize)\n \n let lower = chunk * chunkSize\n let upper = lower + chunkSize\n \n for scalar in lower ..< upper {\n if data.contains(where: { $0.contains(UInt32(scalar)) }) {\n chunkBA[scalar % chunkSize] = true\n }\n }\n \n // Append our chunk bit array's rank.\n var lastRank: UInt16 = 0\n for (i, _) in chunkBA.words.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(chunkBA.words[i - 1].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n lastRank = rank\n }\n \n bitArrays += chunkBA.words.map {\n var ba = BitArray(size: 64)\n ba.words = [$0]\n return ba\n }\n }\n \n emitCollection(\n ranks,\n name: "_swift_stdlib_InCB_\(incb.rawValue)_ranks",\n into: &result\n )\n \n emitCollection(\n bitArrays,\n name: "_swift_stdlib_InCB_\(incb.rawValue)",\n type: "__swift_uint64_t",\n into: &result\n ) {\n assert($0.words.count == 1)\n return "0x\(String($0.words[0], radix: 16, uppercase: true))"\n }\n}\n\nfunc emitInCB(into result: inout String, _ platform: String) {\n let derviedCoreProperties: String\n \n switch platform {\n case "Apple":\n derviedCoreProperties = readFile("Data/16/Apple/DerivedCoreProperties.txt")\n default:\n derviedCoreProperties = readFile("Data/16/DerivedCoreProperties.txt")\n }\n\n let consonants = getInCB(.consonant, from: derviedCoreProperties)\n\n emitInCB(.consonant, consonants, into: &result)\n}\n\n// Main entry point into the grapheme break property generator.\nfunc generateGraphemeBreakProperty(for platform: String) {\n var result = readFile("Input/GraphemeData.h")\n\n let baseData = getGraphemeBreakPropertyData(\n for: "Data/16/GraphemeBreakProperty.txt"\n )\n let emojiData = getGraphemeBreakPropertyData(for: "Data/16/emoji-data.txt")\n\n let flattened = flatten(baseData + emojiData)\n\n var data: [GraphemeBreakEntry] = []\n\n for (range, gbp) in flattened {\n guard range.count < 0x200 else {\n let lower = String(range.lowerBound, radix: 16)\n let upper = String(range.upperBound, radix: 16)\n\n print("Manual range: 0x\(lower) ... 0x\(upper) for \(gbp)")\n continue\n }\n\n data.append(GraphemeBreakEntry(\n index: data.count,\n range: range,\n property: gbp\n ))\n }\n\n data = eytzingerize(data, dummy: GraphemeBreakEntry(\n index: 0,\n range: 0...0,\n property: .control\n ))\n\n emit(data, into: &result)\n\n // Handle the InCB properties:\n emitInCB(into: &result, platform)\n\n result += """\n #endif // #ifndef GRAPHEME_DATA_H\n\n """\n\n write(result, to: "Output/\(platform)/GraphemeData.h")\n}\n\nfor platform in ["Common", "Apple"] {\n generateGraphemeBreakProperty(for: platform)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenGraphemeBreakProperty_main.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenGraphemeBreakProperty_main.swift
Swift
11,413
0.95
0.077482
0.222222
awesome-app
122
2025-06-18T23:44:06.371461
GPL-3.0
false
1df4d4cb18400ca95997adecb5808a5a
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\n// Given a string to the UnicodeData file, return the flattened list of scalar\n// to Canonical Combining Class.\n//\n// Each line in this data file is formatted like the following:\n//\n// 0000;<control>;Cc;0;BN;;;;;N;NULL;;;;\n//\n// Where each section is split by a ';'. The first section informs us of the\n// scalar in the line with the various properties. For the purposes of CCC data,\n// we only need the 0 in between the Cc and BN (index 3) which is the raw value\n// for the CCC.\nfunc getCCCData(from data: String, with dict: inout [UInt32: UInt16]) {\n for line in data.split(separator: "\n") {\n let components = line.split(separator: ";", omittingEmptySubsequences: false)\n \n let ccc = UInt16(components[3])!\n \n // For the most part, CCC 0 is the default case, so we can save much more\n // space by not keeping this information and making it the fallback case.\n if ccc == 0 {\n continue\n }\n \n let scalarStr = components[0]\n let scalar = UInt32(scalarStr, radix: 16)!\n\n var newValue = dict[scalar, default: 0]\n \n // Store our ccc past the 3rd bit.\n newValue |= ccc << 3\n \n dict[scalar] = newValue\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_CCC.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_CCC.swift
Swift
1,693
0.95
0.104167
0.625
node-utils
521
2025-01-05T09:37:00.224636
BSD-3-Clause
false
d00950ca6edd8b5e23f1165c532914bd
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nfunc getCompExclusions(from data: String) -> [ClosedRange<UInt32>] {\n var result: [ClosedRange<UInt32>] = []\n \n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let info = line.split(separator: "#")\n let components = info[0].split(separator: ";")\n \n // Get the property first because we only care about Full_Composition_Exclusion\n let filteredProperty = components[1].filter { !$0.isWhitespace }\n \n guard filteredProperty == "Full_Composition_Exclusion" else {\n continue\n }\n \n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n result.append(scalars)\n }\n \n return result\n}\n\nfunc emitComp(_ mph: Mph, _ data: [(UInt32, [UInt32])], into result: inout String) {\n emitMph(\n mph,\n name: "_swift_stdlib_nfc_comp",\n defineLabel: "NFC_COMP",\n into: &result\n )\n \n emitCompComps(mph, data, into: &result)\n}\n\nfunc emitCompComps(\n _ mph: Mph,\n _ data: [(UInt32, [UInt32])],\n into result: inout String\n) {\n let uniqueKeys = Set(data.map { $0.1[1] })\n var sortedData: [[(UInt32, UInt32)]] = .init(\n repeating: [],\n count: uniqueKeys.count\n )\n \n for (scalar, comp) in data {\n let idx = mph.index(for: UInt64(comp[1]))\n \n if sortedData[idx].isEmpty {\n sortedData[idx].append((comp[1], .max))\n }\n \n sortedData[idx].append((comp[0], scalar))\n }\n \n // Go back and sort each array as well as putting the size information of each\n // in the first element (who contains the original y scalar that was hashed).\n for i in sortedData.indices {\n sortedData[i][1...].sort { $0.0 < $1.0 }\n \n sortedData[i][0].0 = sortedData[i][0].0 | UInt32(sortedData[i].count << 21)\n }\n \n for i in sortedData.indices {\n result += """\n static const __swift_uint32_t _swift_stdlib_nfc_comp\(i)[\(sortedData[i].count)] = {\n \n """\n \n formatCollection(sortedData[i], into: &result) { (comp, scalar) in\n // This only occurs for the first element who stores the original y scalar\n // in the composition and the size of the array.\n if scalar == .max {\n return "0x\(String(comp, radix: 16, uppercase: true))"\n }\n \n // Make sure that these scalars don't exceed past 17 bits. We need the other\n // 15 bits to store the range to the final composition. Although Unicode\n // scalars can go up to 21 bits, none of the compositions with this scalar\n // go that high.\n assert(comp <= 0x1FFFF)\n var value = comp\n \n // Calculate the distance from our current composition scalar to our final\n // composed scalar.\n let distance = Int(scalar) - Int(comp)\n // Make sure that our distance doesn't exceed 14 bits. Although the above\n // assertion gives us 15 bits, we use the last bit to indicate negative\n // or not.\n assert(distance <= 0x3FFF)\n \n value |= UInt32(distance.magnitude) << 17\n \n if distance < 0 {\n value |= 1 << 31\n }\n \n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n \n result += "\n};\n\n"\n }\n \n result += """\n static const __swift_uint32_t * const _swift_stdlib_nfc_comp_indices[\(sortedData.count)] = {\n \n """\n \n formatCollection(sortedData.indices, into: &result) { i in\n return "_swift_stdlib_nfc_comp\(i)"\n }\n \n result += "\n};\n\n"\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_Comp.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_Comp.swift
Swift
4,407
0.95
0.082192
0.25
node-utils
801
2025-06-02T13:59:02.369321
MIT
false
6082a8bc39aee4c267c47a1ee3ece04d
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\n// Given a string to the UnicodeData file, return the flattened list of scalar\n// to Canonical Decompositions.\n//\n// Each line in this data file is formatted like the following:\n//\n// 1B06;BALINESE LETTER AKARA TEDUNG;Lo;0;L;1B05 1B35;;;;N;;;;;\n//\n// Where each section is split by a ';'. The first section informs us of the\n// scalar in the line with the various properties. For the purposes of\n// decomposition data, we only need the 1B05 1B35 after the L (index 5) which is\n// the array of scalars that the scalars decomposes to.\nfunc getDecompData(\n from data: String\n) -> [(UInt32, [UInt32])] {\n var unflattened: [(UInt32, [UInt32])] = []\n \n for line in data.split(separator: "\n") {\n let components = line.split(separator: ";", omittingEmptySubsequences: false)\n \n let decomp = components[5]\n \n // We either 1. don't have decompositions, or 2. the decompositions is for\n // compatible forms. We only care about NFD, so ignore these cases.\n if decomp == "" || decomp.hasPrefix("<") {\n continue\n }\n \n let decomposedScalars = decomp.split(separator: " ").map {\n UInt32($0, radix: 16)!\n }\n \n let scalarStr = components[0]\n let scalar = UInt32(scalarStr, radix: 16)!\n \n unflattened.append((scalar, decomposedScalars))\n }\n \n return unflattened\n}\n\n// Takes a mph for the keys and the data values and writes the required data into\n// static C arrays.\nfunc emitDecomp(\n _ mph: Mph,\n _ data: [(UInt32, [UInt32])],\n into result: inout String\n) {\n emitMph(\n mph,\n name: "_swift_stdlib_nfd_decomp",\n defineLabel: "NFD_DECOMP",\n into: &result\n )\n \n // Fixup the decomposed scalars first for fully decompositions.\n \n var data = data\n \n func decompose(_ scalar: UInt32, into result: inout [UInt32]) {\n if scalar <= 0x7F {\n result.append(scalar)\n return\n }\n \n if let decomp = data.first(where: { $0.0 == scalar }) {\n for scalar in decomp.1 {\n decompose(scalar, into: &result)\n }\n } else {\n result.append(scalar)\n }\n }\n \n for (i, (_, rawDecomposed)) in data.enumerated() {\n var newDecomposed: [UInt32] = []\n \n for rawScalar in rawDecomposed {\n decompose(rawScalar, into: &newDecomposed)\n }\n \n data[i].1 = newDecomposed\n }\n \n var sortedData: [(UInt32, UInt16)] = []\n \n for (scalar, _) in data {\n sortedData.append((scalar, UInt16(mph.index(for: UInt64(scalar)))))\n }\n \n sortedData.sort { $0.1 < $1.1 }\n \n let indices = emitDecompDecomp(data, sortedData, into: &result)\n emitDecompIndices(indices, into: &result)\n}\n\nfunc emitDecompDecomp(\n _ data: [(UInt32, [UInt32])],\n _ sortedData: [(UInt32, UInt16)],\n into result: inout String\n) -> [(UInt32, UInt16)] {\n var indices: [(UInt32, UInt16)] = []\n var decompResult: [UInt8] = []\n \n // Keep a record of decompositions because some scalars share the same\n // decomposition, so instead of emitting it twice, both scalars just point at\n // the same decomposition index.\n var uniqueDecomps: [[UInt32]: UInt16] = [:]\n \n for (scalar, _) in sortedData {\n let decomp = data.first(where: { $0.0 == scalar })!.1\n \n // If we've seen this decomp before, use it.\n if let idx = uniqueDecomps[decomp] {\n indices.append((scalar, idx))\n continue\n }\n \n indices.append((scalar, UInt16(decompResult.count)))\n \n // This is our NFD decomposition utf8 string count.\n decompResult.append(0)\n let sizeIdx = decompResult.count - 1\n \n uniqueDecomps[decomp] = UInt16(sizeIdx)\n \n for scalar in decomp {\n let realScalar = Unicode.Scalar(scalar)!\n \n decompResult[sizeIdx] += UInt8(realScalar.utf8.count)\n \n for utf8 in realScalar.utf8 {\n decompResult.append(utf8)\n }\n }\n }\n \n result += """\n static const __swift_uint8_t _swift_stdlib_nfd_decomp[\(decompResult.count)] = {\n\n """\n \n formatCollection(decompResult, into: &result) { value -> String in\n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n \n result += "\n};\n\n"\n \n return indices\n}\n\nfunc emitDecompIndices(\n _ indices: [(UInt32, UInt16)],\n into result: inout String\n) {\n result += """\n static const __swift_uint32_t _swift_stdlib_nfd_decomp_indices[\(indices.count)] = {\n\n """\n \n formatCollection(indices, into: &result) { (scalar, idx) -> String in\n // Make sure that these scalars don't exceed past 18 bits. We need the other\n // 14 bits to store the index into decomp array. Although Unicode scalars\n // can go up to 21 bits, none of the higher scalars actually decompose into\n // anything or aren't assigned yet.\n assert(scalar <= 0x3FFFF)\n var value = scalar\n value |= UInt32(idx) << 18\n \n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n \n result += "\n};\n\n"\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_Decomp.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_Decomp.swift
Swift
5,324
0.95
0.096257
0.246575
node-utils
998
2023-11-21T05:06:51.668971
Apache-2.0
false
1506102895d6bf94eee553bd9daa9d18
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\n// Main entry point into the normalization generator.\nfunc generateNormalization(for platform: String) {\n var result = readFile("Input/NormalizationData.h")\n \n let derivedNormalizationProps = readFile("Data/16/DerivedNormalizationProps.txt")\n \n let unicodeData: String\n \n switch platform {\n case "Apple":\n unicodeData = readFile("Data/16/Apple/UnicodeData.txt")\n default:\n unicodeData = readFile("Data/16/UnicodeData.txt")\n }\n \n // Get all NFX_QC information and put it together with CCC info.\n var normData: [UInt32: UInt16] = [:]\n getQCData(from: derivedNormalizationProps, with: &normData)\n getCCCData(from: unicodeData, with: &normData)\n \n // Take the NFX_QC info and CCC and emit it as a singular "normData".\n let flattenedNormData = flatten(Array(normData))\n emitNormData(flattenedNormData, into: &result)\n \n // Get and emit decomposition data.\n let decompData = getDecompData(from: unicodeData)\n let decompMph = mph(for: decompData.map { UInt64($0.0) })\n emitDecomp(decompMph, decompData, into: &result)\n \n // Get and emit composition data. (Remove composition exclusions)\n let compExclusions = getCompExclusions(from: derivedNormalizationProps)\n let filteredDecomp = decompData.filter { (scalar, _) in\n !compExclusions.contains {\n $0.contains(scalar)\n }\n }\n let compMph = mph(for: Array(Set(filteredDecomp.map { UInt64($0.1[1]) })))\n emitComp(compMph, filteredDecomp, into: &result)\n \n result += """\n #endif // #ifndef NORMALIZATION_DATA_H\n \n """\n \n // Finally, write it out.\n write(result, to: "Output/\(platform)/NormalizationData.h")\n}\n\nfor platform in ["Common", "Apple"] {\n generateNormalization(for: platform)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_main.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_main.swift
Swift
2,213
0.95
0.123077
0.346154
node-utils
884
2024-05-07T16:36:53.684818
Apache-2.0
false
1c42680de132f27c3ae0911586999611
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\n// Given a string to the DerivedNormalizationProps Unicode file, return the\n// flattened list of scalar to NFC Quick Check.\n//\n// Each line in one of these data files is formatted like the following:\n//\n// 0343..0344 ; NFC_QC; N # Mn [2] COMBINING GREEK KORONIS..COMBINING GREEK DIALYTIKA TONOS\n// 0374 ; NFC_QC; N # Lm GREEK NUMERAL SIGN\n//\n// Where each section is split by a ';'. The first section informs us of either\n// the range of scalars who conform to this property or the singular scalar\n// who does. The second section tells us what normalization property these\n// scalars conform to. There are extra comments telling us what general\n// category these scalars are a part of, how many scalars are in a range, and\n// the name of the scalars.\nfunc getQCData(from data: String, with dict: inout [UInt32: UInt16]) {\n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let info = line.split(separator: "#")\n let components = info[0].split(separator: ";")\n \n // Get the property first because we only care about NFC_QC or NFD_QC.\n let filteredProperty = components[1].filter { !$0.isWhitespace }\n \n guard filteredProperty == "NFD_QC" || filteredProperty == "NFC_QC" else {\n continue\n }\n \n let scalars: ClosedRange<UInt32>\n\n let filteredScalars = components[0].filter { !$0.isWhitespace }\n\n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n\n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n\n scalars = scalar ... scalar\n }\n \n // Special case: Do not store hangul NFD_QC.\n if scalars == 0xAC00...0xD7A3, filteredProperty == "NFD_QC" {\n continue\n }\n \n let filteredNFCQC = components[2].filter { !$0.isWhitespace }\n \n for scalar in scalars {\n var newValue = dict[scalar, default: 0]\n \n switch filteredProperty {\n case "NFD_QC":\n // NFD_QC is the first bit in the data value and is set if a scalar is\n // NOT qc.\n newValue |= 1 << 0\n case "NFC_QC":\n // If our scalar is NOT NFC_QC, then set the 2nd bit in our data value.\n // Otherwise, this scalar is MAYBE NFC_QC, so set the 3rd bit. A scalar\n // who IS NFC_QC has a value of 0.\n if filteredNFCQC == "N" {\n newValue |= 1 << 1\n } else {\n newValue |= 1 << 2\n }\n default:\n fatalError("Unknown NFC_QC type?")\n }\n \n dict[scalar] = newValue\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_NFX_QC.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_NFX_QC.swift
Swift
3,291
0.95
0.096774
0.448718
vue-tools
800
2025-03-28T16:59:48.772686
MIT
false
6b4757ac9ea2aed4900fd28b8e679039
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nfunc emitNormData(\n _ data: [(ClosedRange<UInt32>, UInt16)],\n into result: inout String\n) {\n let uniqueData = Array(Set(data.map { $0.1 }))\n \n // 64 bit arrays * 8 bytes = .512 KB\n var bitArrays: [BitArray] = .init(repeating: .init(size: 64), count: 64)\n \n let chunkSize = 0x110000 / 64 / 64\n \n var chunks: [Int] = []\n \n for i in 0 ..< 64 * 64 {\n let lower = i * chunkSize\n let upper = lower + chunkSize - 1\n \n let idx = i / 64\n let bit = i % 64\n \n for scalar in lower ... upper {\n if data.contains(where: { $0.0.contains(UInt32(scalar)) }) {\n chunks.append(i)\n\n bitArrays[idx][bit] = true\n break\n }\n }\n }\n \n // Remove the trailing 0s. Currently this reduces quick look size down to\n // 96 bytes from 512 bytes.\n var reducedBA = Array(bitArrays.reversed())\n reducedBA = Array(reducedBA.drop {\n $0.words == [0x0]\n })\n \n bitArrays = reducedBA.reversed()\n \n // Keep a record of every rank for all the bitarrays.\n var ranks: [UInt16] = []\n \n // Record our quick look ranks.\n var lastRank: UInt16 = 0\n for (i, _) in bitArrays.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(bitArrays[i - 1].words[0].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n \n lastRank = rank\n }\n \n // Insert our quick look size at the beginning.\n var size = BitArray(size: 64)\n size.words = [UInt64(bitArrays.count)]\n bitArrays.insert(size, at: 0)\n \n var dataIndices: [UInt8] = []\n \n for chunk in chunks {\n var chunkBA = BitArray(size: chunkSize)\n \n let lower = chunk * chunkSize\n let upper = lower + chunkSize\n \n let chunkDataIdx = UInt64(dataIndices.endIndex)\n \n // Insert our chunk's data index in the upper bits of the last word of our\n // bit array.\n chunkBA.words[chunkBA.words.endIndex - 1] |= chunkDataIdx << 16\n \n for scalar in lower ..< upper {\n if data.contains(where: { $0.0.contains(UInt32(scalar)) }) {\n chunkBA[scalar % chunkSize] = true\n \n let data = data[data.firstIndex {\n $0.0.contains(UInt32(scalar))\n }!].1\n \n let dataIdx = uniqueData.firstIndex(of: data)!\n \n dataIndices.append(UInt8(dataIdx))\n }\n }\n \n // Append our chunk bit array's rank.\n var lastRank: UInt16 = 0\n for (i, _) in chunkBA.words.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(chunkBA.words[i - 1].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n lastRank = rank\n }\n \n bitArrays += chunkBA.words.map {\n var ba = BitArray(size: 64)\n ba.words = [$0]\n return ba\n }\n }\n \n emitCollection(\n uniqueData,\n name: "_swift_stdlib_normData_data",\n into: &result\n )\n \n emitCollection(\n dataIndices,\n name: "_swift_stdlib_normData_data_indices",\n into: &result\n )\n \n emitCollection(\n ranks,\n name: "_swift_stdlib_normData_ranks",\n into: &result\n )\n \n emitCollection(\n bitArrays,\n name: "_swift_stdlib_normData",\n type: "__swift_uint64_t",\n into: &result\n ) {\n assert($0.words.count == 1)\n return "0x\(String($0.words[0], radix: 16, uppercase: true))"\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_NormData.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenNormalization_NormData.swift
Swift
3,826
0.95
0.070968
0.165289
node-utils
993
2025-03-31T05:30:00.598341
GPL-3.0
false
ab1d6fdab845a5c9c6447dcd65c773c6
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nfunc getAge(\n from data: String,\n into result: inout [(ClosedRange<UInt32>, [UInt8])]\n) {\n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let info = line.split(separator: "#")\n let components = info[0].split(separator: ";")\n \n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n let version = components[1].filter { !$0.isWhitespace }\n let parts = version.split(separator: ".")\n \n let major = UInt8(parts[0])!\n let minor = UInt8(parts[1])!\n \n result.append((scalars, [major, minor]))\n }\n}\n\nfunc emitAge(\n data: [(ClosedRange<UInt32>, [UInt8])],\n into result: inout String\n) {\n var uniqueAges: Set<[UInt8]> = []\n \n for (_, age) in data {\n uniqueAges.insert(age)\n }\n \n let ages = uniqueAges.map {\n UInt16($0[0]) | (UInt16($0[1]) << 8)\n }\n\n result += """\n #define AGE_COUNT \(data.count)\n\n\n """\n\n emitCollection(ages, name: "_swift_stdlib_ages_data", into: &result)\n \n emitCollection(\n data,\n name: "_swift_stdlib_ages",\n type: "__swift_uint64_t",\n into: &result\n ) {\n var value: UInt64 = UInt64($0.0.lowerBound)\n \n let age = UInt16($0.1[0]) | (UInt16($0.1[1]) << 8)\n let ageIndex = ages.firstIndex(of: age)!\n \n value |= UInt64(ageIndex) << 21\n \n value |= UInt64($0.0.count - 1) << 32\n \n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n}\n\nfunc generateAgeProp(into result: inout String) {\n let derivedAge = readFile("Data/16/DerivedAge.txt")\n \n var ageData: [(ClosedRange<UInt32>, [UInt8])] = []\n \n getAge(from: derivedAge, into: &ageData)\n \n emitAge(data: flatten(ageData), into: &result)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_Age.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_Age.swift
Swift
2,687
0.95
0.048544
0.197368
react-lib
802
2024-10-26T00:26:09.286881
MIT
false
2fdad43d0d46efe32dde20efe9457b66
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\n// WARNING: The values below must be kept in-sync with the stdlib code that\n// retrieves these properties. If one should ever update this list below, be\n// it reordering bits, adding new properties, etc., please update the\n// stdlib code found at:\n// 'stdlib/public/core/UnicodeScalarProperties.swift'.\ninternal struct BinProps: OptionSet {\n let rawValue: UInt64\n\n init(_ rawValue: UInt64) {\n self.rawValue = rawValue\n }\n\n // Because we defined the labelless init, we lose the memberwise one\n // generated, so define that here to satisfy the 'OptionSet' requirement.\n init(rawValue: UInt64) {\n self.rawValue = rawValue\n }\n\n static var changesWhenCaseFolded : Self { Self(1 &<< 0) }\n static var changesWhenCaseMapped : Self { Self(1 &<< 1) }\n static var changesWhenLowercased : Self { Self(1 &<< 2) }\n static var changesWhenNFKCCaseFolded : Self { Self(1 &<< 3) }\n static var changesWhenTitlecased : Self { Self(1 &<< 4) }\n static var changesWhenUppercased : Self { Self(1 &<< 5) }\n static var isASCIIHexDigit : Self { Self(1 &<< 6) }\n static var isAlphabetic : Self { Self(1 &<< 7) }\n static var isBidiControl : Self { Self(1 &<< 8) }\n static var isBidiMirrored : Self { Self(1 &<< 9) }\n static var isCaseIgnorable : Self { Self(1 &<< 10) }\n static var isCased : Self { Self(1 &<< 11) }\n static var isDash : Self { Self(1 &<< 12) }\n static var isDefaultIgnorableCodePoint : Self { Self(1 &<< 13) }\n static var isDeprecated : Self { Self(1 &<< 14) }\n static var isDiacritic : Self { Self(1 &<< 15) }\n static var isEmoji : Self { Self(1 &<< 16) }\n static var isEmojiModifier : Self { Self(1 &<< 17) }\n static var isEmojiModifierBase : Self { Self(1 &<< 18) }\n static var isEmojiPresentation : Self { Self(1 &<< 19) }\n static var isExtender : Self { Self(1 &<< 20) }\n static var isFullCompositionExclusion : Self { Self(1 &<< 21) }\n static var isGraphemeBase : Self { Self(1 &<< 22) }\n static var isGraphemeExtend : Self { Self(1 &<< 23) }\n static var isHexDigit : Self { Self(1 &<< 24) }\n static var isIDContinue : Self { Self(1 &<< 25) }\n static var isIDSBinaryOperator : Self { Self(1 &<< 26) }\n static var isIDSTrinaryOperator : Self { Self(1 &<< 27) }\n static var isIDStart : Self { Self(1 &<< 28) }\n static var isIdeographic : Self { Self(1 &<< 29) }\n static var isJoinControl : Self { Self(1 &<< 30) }\n static var isLogicalOrderException : Self { Self(1 &<< 31) }\n static var isLowercase : Self { Self(1 &<< 32) }\n static var isMath : Self { Self(1 &<< 33) }\n static var isNoncharacterCodePoint : Self { Self(1 &<< 34) }\n static var isPatternSyntax : Self { Self(1 &<< 35) }\n static var isPatternWhitespace : Self { Self(1 &<< 36) }\n static var isQuotationMark : Self { Self(1 &<< 37) }\n static var isRadical : Self { Self(1 &<< 38) }\n static var isSentenceTerminal : Self { Self(1 &<< 39) }\n static var isSoftDotted : Self { Self(1 &<< 40) }\n static var isTerminalPunctuation : Self { Self(1 &<< 41) }\n static var isUnifiedIdeograph : Self { Self(1 &<< 42) }\n static var isUppercase : Self { Self(1 &<< 43) }\n static var isVariationSelector : Self { Self(1 &<< 44) }\n static var isWhitespace : Self { Self(1 &<< 45) }\n static var isXIDContinue : Self { Self(1 &<< 46) }\n static var isXIDStart : Self { Self(1 &<< 47) }\n}\n\nextension BinProps: Hashable {}\n\nlet binPropMappings: [String: BinProps] = [\n "Alphabetic": .isAlphabetic,\n "ASCII_Hex_Digit": .isASCIIHexDigit,\n "Bidi_Control": .isBidiControl,\n "Bidi_Mirrored": .isBidiMirrored,\n "Cased": .isCased,\n "Case_Ignorable": .isCaseIgnorable,\n "Changes_When_Casefolded": .changesWhenCaseFolded,\n "Changes_When_Casemapped": .changesWhenCaseMapped,\n "Changes_When_Lowercased": .changesWhenLowercased,\n "Changes_When_NFKC_Casefolded": .changesWhenNFKCCaseFolded,\n "Changes_When_Titlecased": .changesWhenTitlecased,\n "Changes_When_Uppercased": .changesWhenUppercased,\n "Dash": .isDash,\n "Default_Ignorable_Code_Point": .isDefaultIgnorableCodePoint,\n "Deprecated": .isDeprecated,\n "Diacritic": .isDiacritic,\n "Emoji": .isEmoji,\n "Emoji_Modifier": .isEmojiModifier,\n "Emoji_Modifier_Base": .isEmojiModifierBase,\n "Emoji_Presentation": .isEmojiPresentation,\n "Extender": .isExtender,\n "Full_Composition_Exclusion": .isFullCompositionExclusion,\n "Grapheme_Base": .isGraphemeBase,\n "Grapheme_Extend": .isGraphemeExtend,\n "Hex_Digit": .isHexDigit,\n "ID_Continue": .isIDContinue,\n "ID_Start": .isIDStart,\n "Ideographic": .isIdeographic,\n "IDS_Binary_Operator": .isIDSBinaryOperator,\n "IDS_Trinary_Operator": .isIDSTrinaryOperator,\n "Join_Control": .isJoinControl,\n "Logical_Order_Exception": .isLogicalOrderException,\n "Lowercase": .isLowercase,\n "Math": .isMath,\n "Noncharacter_Code_Point": .isNoncharacterCodePoint,\n "Other_Alphabetic": .isAlphabetic,\n "Other_Default_Ignorable_Code_Point": .isDefaultIgnorableCodePoint,\n "Other_Grapheme_Extend": .isGraphemeExtend,\n "Other_ID_Continue": .isIDContinue,\n "Other_ID_Start": .isIDStart,\n "Other_Lowercase": .isLowercase,\n "Other_Math": .isMath,\n "Other_Uppercase": .isUppercase,\n "Pattern_Syntax": .isPatternSyntax,\n "Pattern_White_Space": .isPatternWhitespace,\n "Quotation_Mark": .isQuotationMark,\n "Radical": .isRadical,\n "Sentence_Terminal": .isSentenceTerminal,\n "Soft_Dotted": .isSoftDotted,\n "Terminal_Punctuation": .isTerminalPunctuation,\n "Unified_Ideograph": .isUnifiedIdeograph,\n "Uppercase": .isUppercase,\n "Variation_Selector": .isVariationSelector,\n "White_Space": .isWhitespace,\n "XID_Continue": .isXIDContinue,\n "XID_Start": .isXIDStart\n]\n\nfunc getBinaryProperties(\n from data: String,\n into result: inout [UInt32: BinProps]\n) {\n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n\n let info = line.split(separator: "#")\n let components = info[0].split(separator: ";")\n \n // Get the property first because we may not care about it.\n let filteredProperty = components[1].filter { !$0.isWhitespace }\n \n guard binPropMappings.keys.contains(filteredProperty) else {\n continue\n }\n \n let scalars: ClosedRange<UInt32>\n\n let filteredScalars = components[0].filter { !$0.isWhitespace }\n\n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n\n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n\n scalars = scalar ... scalar\n }\n \n for scalar in scalars {\n result[scalar, default: []].insert(binPropMappings[filteredProperty]!)\n }\n }\n}\n\nfunc emitBinaryProps(\n _ data: [(ClosedRange<UInt32>, BinProps)],\n into result: inout String\n) {\n result += """\n #define BIN_PROPS_COUNT \(data.count)\n \n \n """\n \n let combinations = Array(Set(data.map { $0.1 })).map { $0.rawValue }\n \n // Data combinations array\n \n emitCollection(\n combinations,\n name: "_swift_stdlib_scalar_binProps_data",\n into: &result\n )\n \n // Actual scalar + index array\n \n emitCollection(\n data,\n name: "_swift_stdlib_scalar_binProps",\n type: "__swift_uint32_t",\n into: &result\n ) {\n var value = $0.0.lowerBound\n value |= UInt32(combinations.firstIndex(of: $0.1.rawValue)!) << 21\n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n}\n\nfunc generateBinaryProps(for platform: String, into result: inout String) {\n let derivedCoreProps: String\n \n switch platform {\n case "Apple":\n derivedCoreProps = readFile("Data/16/Apple/DerivedCoreProperties.txt")\n default:\n derivedCoreProps = readFile("Data/16/DerivedCoreProperties.txt")\n }\n \n let bidiMirrored = readFile("Data/16/DerivedBinaryProperties.txt")\n let normalization = readFile("Data/16/DerivedNormalizationProps.txt")\n let emoji = readFile("Data/16/emoji-data.txt")\n let propList = readFile("Data/16/PropList.txt")\n \n var binProps: [UInt32: BinProps] = [:]\n getBinaryProperties(from: derivedCoreProps, into: &binProps)\n getBinaryProperties(from: bidiMirrored, into: &binProps)\n getBinaryProperties(from: normalization, into: &binProps)\n getBinaryProperties(from: emoji, into: &binProps)\n getBinaryProperties(from: propList, into: &binProps)\n \n // This loop inserts the ranges of scalars who have no binary properties to\n // fill in the holes for binary search.\n for i in 0x0 ... 0x10FFFF {\n guard let scalar = Unicode.Scalar(i) else {\n continue\n }\n \n if !binProps.keys.contains(scalar.value) {\n binProps[scalar.value] = []\n }\n }\n \n let data = flatten(Array(binProps))\n \n emitBinaryProps(data, into: &result)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_BinProps.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_BinProps.swift
Swift
9,814
0.95
0.038911
0.120536
python-kit
455
2024-08-17T00:06:34.354468
MIT
false
1cbea715383d26f3e2317fc22636fb69
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nenum GeneralCategory: String {\n case uppercaseLetter = "Lu"\n case lowercaseLetter = "Ll"\n case titlecaseLetter = "Lt"\n case modifierLetter = "Lm"\n case otherLetter = "Lo"\n case nonspacingMark = "Mn"\n case spacingMark = "Mc"\n case enclosingMark = "Me"\n case decimalNumber = "Nd"\n case letterNumber = "Nl"\n case otherNumber = "No"\n case connectorPunctuation = "Pc"\n case dashPunctuation = "Pd"\n case openPunctuation = "Ps"\n case closePunctuation = "Pe"\n case initialPunctuation = "Pi"\n case finalPunctuation = "Pf"\n case otherPunctuation = "Po"\n case mathSymbol = "Sm"\n case currencySymbol = "Sc"\n case modifierSymbol = "Sk"\n case otherSymbol = "So"\n case spaceSeparator = "Zs"\n case lineSeparator = "Zl"\n case paragraphSeparator = "Zp"\n case control = "Cc"\n case format = "Cf"\n case surrogate = "Cs"\n case privateUse = "Co"\n case unassigned = "Cn"\n \n var binaryRepresentation: UInt8 {\n switch self {\n case .uppercaseLetter:\n return 0\n case .lowercaseLetter:\n return 1\n case .titlecaseLetter:\n return 2\n case .modifierLetter:\n return 3\n case .otherLetter:\n return 4\n case .nonspacingMark:\n return 5\n case .spacingMark:\n return 6\n case .enclosingMark:\n return 7\n case .decimalNumber:\n return 8\n case .letterNumber:\n return 9\n case .otherNumber:\n return 10\n case .connectorPunctuation:\n return 11\n case .dashPunctuation:\n return 12\n case .openPunctuation:\n return 13\n case .closePunctuation:\n return 14\n case .initialPunctuation:\n return 15\n case .finalPunctuation:\n return 16\n case .otherPunctuation:\n return 17\n case .mathSymbol:\n return 18\n case .currencySymbol:\n return 19\n case .modifierSymbol:\n return 20\n case .otherSymbol:\n return 21\n case .spaceSeparator:\n return 22\n case .lineSeparator:\n return 23\n case .paragraphSeparator:\n return 24\n case .control:\n return 25\n case .format:\n return 26\n case .surrogate:\n return 27\n case .privateUse:\n return 28\n case .unassigned:\n return 29\n }\n }\n}\n\nfunc getGeneralCategory(\n from data: String,\n into result: inout [(ClosedRange<UInt32>, GeneralCategory)]\n) {\n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let info = line.split(separator: "#")\n let components = info[0].split(separator: ";")\n \n let filteredCategory = components[1].filter { !$0.isWhitespace }\n \n guard let gc = GeneralCategory(rawValue: filteredCategory) else {\n continue\n }\n \n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n result.append((scalars, gc))\n }\n}\n\nfunc emitGeneralCategory(\n _ data: [(ClosedRange<UInt32>, GeneralCategory)],\n into result: inout String\n) {\n result += """\n #define GENERAL_CATEGORY_COUNT \(data.count)\n\n\n """\n\n emitCollection(\n data,\n name: "_swift_stdlib_generalCategory",\n type: "__swift_uint64_t",\n into: &result\n ) {\n var value: UInt64 = UInt64($0.0.lowerBound)\n \n let generalCategory = $0.1.binaryRepresentation\n \n value |= UInt64(generalCategory) << 21\n \n value |= UInt64($0.0.count - 1) << 32\n \n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n}\n\nfunc generateGeneralCategory(into result: inout String) {\n let derivedGeneralCategory = readFile("Data/16/DerivedGeneralCategory.txt")\n \n var data: [(ClosedRange<UInt32>, GeneralCategory)] = []\n \n getGeneralCategory(from: derivedGeneralCategory, into: &data)\n \n emitGeneralCategory(flatten(data), into: &result)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_GeneralCategory.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_GeneralCategory.swift
Swift
4,674
0.95
0.026596
0.092025
python-kit
486
2024-03-15T20:26:39.671841
GPL-3.0
false
21a8ae7605029afc949e57b2592fd4a3
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nfunc generateScalarProps(for platform: String) {\n var result = readFile("Input/ScalarPropData.h")\n \n generateBinaryProps(for: platform, into: &result)\n generateNumericProps(into: &result)\n generateNameAliasProp(into: &result)\n generateMappingProps(for: platform, into: &result)\n generateNameProp(into: &result)\n generateAgeProp(into: &result)\n generateGeneralCategory(into: &result)\n \n result += """\n #endif // #ifndef SCALAR_PROP_DATA_H\n \n """\n \n write(result, to: "Output/\(platform)/ScalarPropData.h")\n}\n\nfor platform in ["Common", "Apple"] {\n generateScalarProps(for: platform)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_main.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_main.swift
Swift
1,131
0.95
0.194444
0.413793
react-lib
309
2024-05-27T21:25:50.126067
MIT
false
7b8699d68f3e4e63a1439b53da91417c
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nfunc getMappings(\n from data: String,\n into dict: inout [UInt32: (Int?, Int?, Int?)]\n) {\n for line in data.split(separator: "\n") {\n let components = line.split(separator: ";", omittingEmptySubsequences: false)\n \n let uppercaseMapping = Int(components[12], radix: 16)\n let lowercaseMapping = Int(components[13], radix: 16)\n let titlecaseMapping = Int(components[14], radix: 16)\n \n guard uppercaseMapping != nil ||\n lowercaseMapping != nil ||\n titlecaseMapping != nil else {\n continue\n }\n \n let scalarStr = components[0]\n let scalar = UInt32(scalarStr, radix: 16)!\n \n dict[scalar] = (uppercaseMapping, lowercaseMapping, titlecaseMapping)\n }\n}\n\nfunc getSpecialMappings(\n from data: String,\n into dict: inout [UInt32: ([UInt32], [UInt32], [UInt32])]\n) {\n for line in data.split(separator: "\n") {\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let components = line.split(separator: ";", omittingEmptySubsequences: false)\n \n // Conditional mappings have an extra component with the conditional name.\n // Ignore those.\n guard components.count == 5 else {\n continue\n }\n \n let scalar = UInt32(components[0], radix: 16)!\n \n let lowercaseMapping = components[1].split(separator: " ").map {\n UInt32($0, radix: 16)!\n }\n \n let titlecaseMapping = components[2].split(separator: " ").map {\n UInt32($0, radix: 16)!\n }\n \n let uppercaseMapping = components[3].split(separator: " ").map {\n UInt32($0, radix: 16)!\n }\n \n dict[scalar] = (uppercaseMapping, lowercaseMapping, titlecaseMapping)\n }\n}\n\nfunc emitMappings(\n _ data: [UInt32: (Int?, Int?, Int?)],\n into result: inout String\n) {\n var uniqueDistances: Set<Int> = []\n\n for (scalar, mappings) in data {\n if let uppercaseMapping = mappings.0 {\n uniqueDistances.insert(uppercaseMapping - Int(scalar))\n }\n \n if let lowercaseMapping = mappings.1 {\n uniqueDistances.insert(lowercaseMapping - Int(scalar))\n }\n \n if let titlecaseMapping = mappings.2 {\n uniqueDistances.insert(titlecaseMapping - Int(scalar))\n }\n }\n \n let distances = Array(uniqueDistances)\n \n // 64 bit arrays * 8 bytes = .512 KB\n var bitArrays: [BitArray] = .init(repeating: .init(size: 64), count: 64)\n \n let chunkSize = 0x110000 / 64 / 64\n \n var chunks: [Int] = []\n \n for i in 0 ..< 64 * 64 {\n let lower = i * chunkSize\n let upper = lower + chunkSize - 1\n \n let idx = i / 64\n let bit = i % 64\n \n for scalar in lower ... upper {\n if data.contains(where: { $0.0 == scalar }) {\n chunks.append(i)\n \n bitArrays[idx][bit] = true\n break\n }\n }\n }\n \n // Remove the trailing 0s. Currently this reduces quick look size down to\n // 96 bytes from 512 bytes.\n var reducedBA = Array(bitArrays.reversed())\n reducedBA = Array(reducedBA.drop {\n $0.words == [0x0]\n })\n \n bitArrays = reducedBA.reversed()\n \n // Keep a record of every rank for all the bitarrays.\n var ranks: [UInt16] = []\n \n // Record our quick look ranks.\n var lastRank: UInt16 = 0\n for (i, _) in bitArrays.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(bitArrays[i - 1].words[0].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n \n lastRank = rank\n }\n \n // Insert our quick look size at the beginning.\n var size = BitArray(size: 64)\n size.words = [UInt64(bitArrays.count)]\n bitArrays.insert(size, at: 0)\n \n var dataIndices: [UInt32] = []\n \n for chunk in chunks {\n var chunkBA = BitArray(size: chunkSize)\n \n let lower = chunk * chunkSize\n let upper = lower + chunkSize\n \n let chunkDataIdx = UInt64(dataIndices.endIndex)\n \n // Insert our chunk's data index in the upper bits of the last word of our\n // bit array.\n chunkBA.words[chunkBA.words.endIndex - 1] |= chunkDataIdx << 16\n \n for scalar in lower ..< upper {\n if data.contains(where: { $0.0 == scalar }) {\n chunkBA[scalar % chunkSize] = true\n \n let mappings = data[UInt32(scalar)]!\n \n var dataIdx: UInt32 = 0\n \n if let uppercaseMapping = mappings.0 {\n let distance = uppercaseMapping - scalar\n let uppercaseIdx = distances.firstIndex(of: distance)!\n \n dataIdx = UInt32(uppercaseIdx)\n } else {\n dataIdx = UInt32(UInt8.max)\n }\n \n if let lowercaseMapping = mappings.1 {\n let distance = lowercaseMapping - scalar\n let lowercaseIdx = distances.firstIndex(of: distance)!\n \n dataIdx |= UInt32(lowercaseIdx) << 8\n } else {\n dataIdx |= UInt32(UInt8.max) << 8\n }\n \n if let titlecaseMapping = mappings.2 {\n let distance = titlecaseMapping - scalar\n let titlecaseIdx = distances.firstIndex(of: distance)!\n \n dataIdx |= UInt32(titlecaseIdx) << 16\n } else {\n dataIdx |= UInt32(UInt8.max) << 16\n }\n \n dataIndices.append(dataIdx)\n }\n }\n \n // Append our chunk bit array's rank.\n var lastRank: UInt16 = 0\n for (i, _) in chunkBA.words.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(chunkBA.words[i - 1].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n lastRank = rank\n }\n \n bitArrays += chunkBA.words.map {\n var ba = BitArray(size: 64)\n ba.words = [$0]\n return ba\n }\n }\n \n emitCollection(\n distances,\n name: "_swift_stdlib_mappings_data",\n type: "__swift_int32_t",\n into: &result\n ) {\n "\($0)"\n }\n \n emitCollection(\n dataIndices,\n name: "_swift_stdlib_mappings_data_indices",\n into: &result\n )\n \n emitCollection(\n ranks,\n name: "_swift_stdlib_mappings_ranks",\n into: &result\n )\n \n emitCollection(\n bitArrays,\n name: "_swift_stdlib_mappings",\n type: "__swift_uint64_t",\n into: &result\n ) {\n assert($0.words.count == 1)\n return "0x\(String($0.words[0], radix: 16, uppercase: true))"\n }\n}\n\nfunc emitSpecialMappings(\n _ data: [UInt32: ([UInt32], [UInt32], [UInt32])],\n into result: inout String\n) {\n var specialMappings: [UInt8] = []\n var index: UInt32 = 0\n var scalarIndices: [UInt32: UInt32] = [:]\n \n for (scalar, (uppercase, lowercase, titlecase)) in data {\n scalarIndices[scalar] = index\n \n index += 1\n if uppercase.count == 1 {\n specialMappings.append(0)\n } else {\n let uppercase = uppercase.map { Unicode.Scalar($0)! }\n \n var utf8Length: UInt8 = 0\n \n for scalar in uppercase {\n utf8Length += UInt8(scalar.utf8.count)\n }\n \n specialMappings.append(utf8Length)\n \n for scalar in uppercase {\n for byte in String(scalar).utf8 {\n specialMappings.append(byte)\n index += 1\n }\n }\n }\n \n index += 1\n if lowercase.count == 1 {\n specialMappings.append(0)\n } else {\n let lowercase = lowercase.map { Unicode.Scalar($0)! }\n \n var utf8Length: UInt8 = 0\n \n for scalar in lowercase {\n utf8Length += UInt8(scalar.utf8.count)\n }\n \n specialMappings.append(utf8Length)\n \n for scalar in lowercase {\n for byte in String(scalar).utf8 {\n specialMappings.append(byte)\n index += 1\n }\n }\n }\n \n index += 1\n if titlecase.count == 1 {\n specialMappings.append(0)\n } else {\n let titlecase = titlecase.map { Unicode.Scalar($0)! }\n \n var utf8Length: UInt8 = 0\n \n for scalar in titlecase {\n utf8Length += UInt8(scalar.utf8.count)\n }\n \n specialMappings.append(utf8Length)\n \n for scalar in titlecase {\n for byte in String(scalar).utf8 {\n specialMappings.append(byte)\n index += 1\n }\n }\n }\n }\n \n // 64 bit arrays * 8 bytes = .512 KB\n var bitArrays: [BitArray] = .init(repeating: .init(size: 64), count: 64)\n \n let chunkSize = 0x110000 / 64 / 64\n \n var chunks: [Int] = []\n \n for i in 0 ..< 64 * 64 {\n let lower = i * chunkSize\n let upper = lower + chunkSize - 1\n \n let idx = i / 64\n let bit = i % 64\n \n for scalar in lower ... upper {\n if data.contains(where: { $0.0 == scalar }) {\n chunks.append(i)\n \n bitArrays[idx][bit] = true\n break\n }\n }\n }\n \n // Remove the trailing 0s. Currently this reduces quick look size down to\n // 96 bytes from 512 bytes.\n var reducedBA = Array(bitArrays.reversed())\n reducedBA = Array(reducedBA.drop {\n $0.words == [0x0]\n })\n \n bitArrays = reducedBA.reversed()\n \n // Keep a record of every rank for all the bitarrays.\n var ranks: [UInt16] = []\n \n // Record our quick look ranks.\n var lastRank: UInt16 = 0\n for (i, _) in bitArrays.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(bitArrays[i - 1].words[0].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n \n lastRank = rank\n }\n \n // Insert our quick look size at the beginning.\n var size = BitArray(size: 64)\n size.words = [UInt64(bitArrays.count)]\n bitArrays.insert(size, at: 0)\n \n var dataIndices: [UInt16] = []\n \n for chunk in chunks {\n var chunkBA = BitArray(size: chunkSize)\n \n let lower = chunk * chunkSize\n let upper = lower + chunkSize\n \n let chunkDataIdx = UInt64(dataIndices.endIndex)\n \n // Insert our chunk's data index in the upper bits of the last word of our\n // bit array.\n chunkBA.words[chunkBA.words.endIndex - 1] |= chunkDataIdx << 16\n \n for scalar in lower ..< upper {\n if data.contains(where: { $0.0 == scalar }) {\n chunkBA[scalar % chunkSize] = true\n \n let dataIdx = UInt16(scalarIndices[UInt32(scalar)]!)\n dataIndices.append(dataIdx)\n }\n }\n \n // Append our chunk bit array's rank.\n var lastRank: UInt16 = 0\n for (i, _) in chunkBA.words.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(chunkBA.words[i - 1].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n lastRank = rank\n }\n \n bitArrays += chunkBA.words.map {\n var ba = BitArray(size: 64)\n ba.words = [$0]\n return ba\n }\n }\n \n emitCollection(\n specialMappings,\n name: "_swift_stdlib_special_mappings_data",\n into: &result\n )\n \n emitCollection(\n dataIndices,\n name: "_swift_stdlib_special_mappings_data_indices",\n into: &result\n )\n \n emitCollection(\n ranks,\n name: "_swift_stdlib_special_mappings_ranks",\n into: &result\n )\n \n emitCollection(\n bitArrays,\n name: "_swift_stdlib_special_mappings",\n type: "__swift_uint64_t",\n into: &result\n ) {\n assert($0.words.count == 1)\n return "0x\(String($0.words[0], radix: 16, uppercase: true))"\n }\n}\n\nfunc generateMappingProps(for platform: String, into result: inout String) {\n let unicodeData: String\n \n switch platform {\n case "Apple":\n unicodeData = readFile("Data/16/Apple/UnicodeData.txt")\n default:\n unicodeData = readFile("Data/16/UnicodeData.txt")\n }\n \n let specialCasing = readFile("Data/16/SpecialCasing.txt")\n \n var data: [UInt32: (Int?, Int?, Int?)] = [:]\n getMappings(from: unicodeData, into: &data)\n emitMappings(data, into: &result)\n \n var specialMappings: [UInt32: ([UInt32], [UInt32], [UInt32])] = [:]\n getSpecialMappings(from: specialCasing, into: &specialMappings)\n emitSpecialMappings(specialMappings, into: &result)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_Mappings.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_Mappings.swift
Swift
12,250
0.95
0.090164
0.081794
python-kit
516
2024-03-10T20:10:14.111996
BSD-3-Clause
false
87592850168919d0218c6df29ab02259
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nfunc getNameAliases(from data: String, into result: inout [(UInt32, String)]) {\n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let info = line.split(separator: "#")\n let components = info[0].split(separator: ";")\n \n // Name aliases are only found with correction attribute.\n guard components[2] == "correction" else {\n continue\n }\n \n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n let nameAlias = String(components[1])\n \n result.append((scalars.lowerBound, nameAlias))\n }\n}\n\nfunc emitNameAliases(_ data: [(UInt32, String)], into result: inout String) {\n // 64 bit arrays * 8 bytes = .512 KB\n var bitArrays: [BitArray] = .init(repeating: .init(size: 64), count: 64)\n \n let chunkSize = 0x110000 / 64 / 64\n \n var chunks: [Int] = []\n \n for i in 0 ..< 64 * 64 {\n let lower = i * chunkSize\n let upper = lower + chunkSize - 1\n \n let idx = i / 64\n let bit = i % 64\n \n for scalar in lower ... upper {\n if data.contains(where: { $0.0 == scalar }) {\n chunks.append(i)\n \n bitArrays[idx][bit] = true\n break\n }\n }\n }\n \n // Remove the trailing 0s. Currently this reduces quick look size down to\n // 96 bytes from 512 bytes.\n var reducedBA = Array(bitArrays.reversed())\n reducedBA = Array(reducedBA.drop {\n $0.words == [0x0]\n })\n \n bitArrays = reducedBA.reversed()\n \n // Keep a record of every rank for all the bitarrays.\n var ranks: [UInt16] = []\n \n // Record our quick look ranks.\n var lastRank: UInt16 = 0\n for (i, _) in bitArrays.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(bitArrays[i - 1].words[0].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n \n lastRank = rank\n }\n \n // Insert our quick look size at the beginning.\n var size = BitArray(size: 64)\n size.words = [UInt64(bitArrays.count)]\n bitArrays.insert(size, at: 0)\n \n var nameAliasData: [String] = []\n \n for chunk in chunks {\n var chunkBA = BitArray(size: chunkSize)\n \n let lower = chunk * chunkSize\n let upper = lower + chunkSize\n \n let chunkDataIdx = UInt64(nameAliasData.endIndex)\n \n // Insert our chunk's data index in the upper bits of the last word of our\n // bit array.\n chunkBA.words[chunkBA.words.endIndex - 1] |= chunkDataIdx << 16\n \n for scalar in lower ..< upper {\n if data.contains(where: { $0.0 == scalar }) {\n chunkBA[scalar % chunkSize] = true\n \n let data = data[data.firstIndex {\n $0.0 == scalar\n }!].1\n \n nameAliasData.append(data)\n }\n }\n \n // Append our chunk bit array's rank.\n var lastRank: UInt16 = 0\n for (i, _) in chunkBA.words.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(chunkBA.words[i - 1].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n lastRank = rank\n }\n \n bitArrays += chunkBA.words.map {\n var ba = BitArray(size: 64)\n ba.words = [$0]\n return ba\n }\n }\n \n emitCollection(\n nameAliasData,\n name: "_swift_stdlib_nameAlias_data",\n type: "char * const",\n into: &result\n ) {\n "\"\($0)\""\n }\n \n emitCollection(\n ranks,\n name: "_swift_stdlib_nameAlias_ranks",\n into: &result\n )\n \n emitCollection(\n bitArrays,\n name: "_swift_stdlib_nameAlias",\n type: "__swift_uint64_t",\n into: &result\n ) {\n assert($0.words.count == 1)\n return "0x\(String($0.words[0], radix: 16, uppercase: true))"\n }\n}\n\nfunc generateNameAliasProp(into result: inout String) {\n let nameAliases = readFile("Data/16/NameAliases.txt")\n \n var data: [(UInt32, String)] = []\n \n getNameAliases(from: nameAliases, into: &data)\n \n emitNameAliases(data, into: &result)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_NameAlias.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_NameAlias.swift
Swift
4,916
0.95
0.067708
0.163265
awesome-app
26
2024-07-15T04:06:56.212508
BSD-3-Clause
false
a7b1ec3029842e484beae72827361eb1
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nfunc getName(\n from data: String,\n into result: inout [(UInt32, String)],\n words: inout [String]\n) {\n var uniqueWords: Set<String> = []\n \n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let info = line.split(separator: "#")\n let components = info[0].split(separator: ";")\n \n let name = String(components[1].dropFirst())\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n if filteredScalars.contains(".") {\n continue\n }\n \n let scalar = UInt32(filteredScalars, radix: 16)!\n \n // Variation selectors are handled in code.\n if (0xE0100...0xE01EF).contains(scalar) {\n continue\n }\n \n // Hanguel is handled in code.\n if scalar >= 0xAC00, scalar <= 0xD7A3 {\n continue\n }\n \n result.append((scalar, name))\n \n for word in name.split(separator: " ") {\n uniqueWords.insert(String(word))\n }\n }\n \n words = Array(uniqueWords)\n}\n\nfunc sortWords(\n _ words: inout [String],\n from data: [(UInt32, String)]\n) {\n var popularity: [String: Int] = [:]\n \n for (_, name) in data {\n let scalarWords = name.split(separator: " ")\n \n for word in scalarWords {\n popularity[String(word), default: 0] += 1\n }\n }\n \n let sortedPopularity = Array(popularity).sorted { $0.value > $1.value }\n \n \n words = sortedPopularity.map { $0.key }\n}\n\nfunc emitWords(\n _ words: [String],\n into result: inout String\n) -> [String: UInt32] {\n var wordIndices: [String: UInt32] = [:]\n var bytes: [UInt8] = []\n \n var index: UInt32 = 0\n \n for word in words {\n wordIndices[word] = index\n \n for (i, byte) in word.utf8.enumerated() {\n var element = byte\n \n if i == word.utf8.count - 1 {\n element |= 0x80\n }\n \n bytes.append(element)\n index += 1\n }\n }\n \n emitCollection(bytes, name: "_swift_stdlib_words", into: &result)\n \n return wordIndices\n}\n\nfunc emitWordOffsets(\n _ wordOffsets: [String: UInt32],\n into result: inout String\n) -> [String: UInt32] {\n let sortedWordOffsets = Array(wordOffsets).sorted { $0.value < $1.value }\n \n var wordIndices: [String: UInt32] = [:]\n \n for (i, (word, _)) in sortedWordOffsets.enumerated() {\n wordIndices[word] = UInt32(i)\n }\n \n emitCollection(\n sortedWordOffsets.map { $0.value },\n name: "_swift_stdlib_word_indices",\n into: &result\n )\n \n return wordIndices\n}\n\nfunc emitScalarNames(\n _ names: [(UInt32, String)],\n _ wordIndices: [String: UInt32],\n into result: inout String\n) -> [UInt32: UInt32] {\n var nameBytes: [UInt8] = []\n \n var scalarNameIndices: [UInt32: UInt32] = [:]\n \n var index: UInt32 = 0\n \n for (scalar, name) in names.sorted(by: { $0.0 < $1.0 }) {\n scalarNameIndices[scalar] = index\n \n for word in name.split(separator: " ") {\n let wordIndex = wordIndices[String(word)]!\n \n // If the word index is smaller than 0xFF, then we don't need to add the\n // extra byte to represent the index.\n if wordIndex < 0xFF {\n nameBytes.append(UInt8(wordIndex))\n index += 1\n } else {\n assert(wordIndex <= UInt16.max)\n \n nameBytes.append(0xFF)\n nameBytes.append(UInt8(wordIndex & 0xFF))\n nameBytes.append(UInt8(wordIndex >> 8))\n index += 3\n }\n }\n }\n \n result += """\n #define NAMES_LAST_SCALAR_OFFSET \(nameBytes.count)\n \n \n """\n \n emitCollection(nameBytes, name: "_swift_stdlib_names", into: &result)\n \n return scalarNameIndices\n}\n\nfunc emitScalars(\n _ scalarNameIndices: [UInt32: UInt32],\n into result: inout String\n) -> [UInt32: UInt16] {\n var scalars: [UInt32] = []\n var scalarSetIndices: [UInt32: UInt16] = [:]\n var index: UInt16 = 0\n \n for i in 0x0 ... 0x10FFFF >> 7 {\n let scalarRange = i << 7 ..< i << 7 + 128\n let filteredRange = scalarRange.filter {\n scalarNameIndices.keys.contains(UInt32($0))\n }\n \n scalarSetIndices[UInt32(i)] = index\n \n if filteredRange.count >= 1 {\n scalarSetIndices[UInt32(i)] = index\n \n for scalar in scalarRange {\n index += 1\n \n guard let index = scalarNameIndices[UInt32(scalar)] else {\n scalars.append(0)\n continue\n }\n \n scalars.append(index)\n }\n } else {\n scalarSetIndices[UInt32(i)] = UInt16.max\n }\n }\n \n result += """\n #define NAMES_SCALARS_MAX_INDEX \(scalars.count - 1)\n \n \n """\n \n emitCollection(scalars, name: "_swift_stdlib_names_scalars", into: &result)\n \n return scalarSetIndices\n}\n\nfunc emitScalarSets(\n _ scalarSetIndices: [UInt32: UInt16],\n into result: inout String\n) {\n var scalarSets: [UInt16] = []\n \n for i in 0x0 ... 0x10FFFF >> 7 {\n let index = scalarSetIndices[UInt32(i)]!\n \n guard index != .max else {\n scalarSets.append(index)\n continue\n }\n \n scalarSets.append(index >> 7)\n }\n \n emitCollection(scalarSets, name: "_swift_stdlib_names_scalar_sets", into: &result)\n}\n\nfunc emitLargestNameCount(_ names: [(UInt32, String)], into result: inout String) {\n var largestCount = 0\n \n for (_, name) in names {\n largestCount = Swift.max(largestCount, name.count)\n }\n \n print("""\n Please copy and paste the following into 'stdlib/public/SwiftShims/swift/shims/UnicodeData.h':\n \n #define SWIFT_STDLIB_LARGEST_NAME_COUNT \(largestCount)\n \n """)\n}\n\nfunc generateNameProp(into result: inout String) {\n let derivedName = readFile("Data/16/DerivedName.txt")\n \n var names: [(UInt32, String)] = []\n var words: [String] = []\n \n getName(from: derivedName, into: &names, words: &words)\n \n sortWords(&words, from: names)\n \n emitLargestNameCount(names, into: &result)\n \n let wordOffsets = emitWords(words, into: &result)\n let wordIndices = emitWordOffsets(wordOffsets, into: &result)\n \n let scalarNameIndices = emitScalarNames(names, wordIndices, into: &result)\n let scalarSetIndices = emitScalars(scalarNameIndices, into: &result)\n emitScalarSets(scalarSetIndices, into: &result)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_Names.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_Names.swift
Swift
6,562
0.95
0.076923
0.095
vue-tools
878
2023-12-13T10:05:27.199638
GPL-3.0
false
400fffecf3a21e178c8cfb35ea7604db
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nenum NumericType: String {\n case numeric = "Numeric"\n case digit = "Digit"\n case decimal = "Decimal"\n \n var binaryRepresentation: UInt32 {\n switch self {\n case .numeric:\n return 0\n case .digit:\n return 1\n case .decimal:\n return 2\n }\n }\n}\n\nfunc getNumericTypes(\n from data: String,\n into result: inout [(ClosedRange<UInt32>, NumericType)]\n) {\n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let info = line.split(separator: "#")\n let components = info[0].split(separator: ";")\n \n let filteredProperty = components[1].filter { !$0.isWhitespace }\n \n guard let numericType = NumericType(rawValue: filteredProperty) else {\n continue\n }\n \n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n result.append((scalars, numericType))\n }\n}\n\nfunc getNumericValues(\n from data: String,\n into result: inout [(ClosedRange<UInt32>, String)]\n) {\n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n let info = line.split(separator: "#")\n let components = info[0].split(separator: ";")\n \n let filteredValue = components[3].filter { !$0.isWhitespace }\n \n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n result.append((scalars, filteredValue))\n }\n}\n\nfunc emitNumericData(\n types: [(ClosedRange<UInt32>, NumericType)],\n values: [(ClosedRange<UInt32>, String)],\n into result: inout String\n) {\n result += """\n #define NUMERIC_TYPE_COUNT \(types.count)\n\n\n """\n\n emitCollection(\n types,\n name: "_swift_stdlib_numeric_type",\n type: "__swift_uint32_t",\n into: &result\n ) { range, type in\n var value = range.lowerBound\n assert(range.count - 1 <= UInt8.max)\n value |= UInt32(range.count - 1) << 21\n \n value |= type.binaryRepresentation << 29\n \n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n \n let uniqueValues = Array(Set(values.map { $0.1 }))\n \n emitCollection(\n uniqueValues,\n name: "_swift_stdlib_numeric_values",\n type: "double",\n into: &result\n ) {\n "(double) \($0)"\n }\n \n var allScalars: [UInt64] = []\n \n for (range, _) in values {\n for scalar in range {\n allScalars.append(UInt64(scalar))\n }\n }\n \n let valueMph = mph(for: allScalars)\n \n emitMph(\n valueMph,\n name: "_swift_stdlib_numeric_values",\n defineLabel: "NUMERIC_VALUES",\n into: &result\n )\n \n var valueIndices: [UInt8] = .init(repeating: 0, count: allScalars.count)\n \n for scalar in allScalars {\n let idx = valueMph.index(for: scalar)\n \n let value = values.first { $0.0.contains(UInt32(scalar)) }!\n let valueIdx = uniqueValues.firstIndex(of: value.1)!\n \n valueIndices[idx] = UInt8(valueIdx)\n }\n \n emitCollection(\n valueIndices,\n name: "_swift_stdlib_numeric_values_indices",\n into: &result\n )\n}\n\nfunc generateNumericProps(into result: inout String) {\n let derivedNumericType = readFile("Data/16/DerivedNumericType.txt")\n let derivedNumericValues = readFile("Data/16/DerivedNumericValues.txt")\n \n var numericTypes: [(ClosedRange<UInt32>, NumericType)] = []\n var numericValues: [(ClosedRange<UInt32>, String)] = []\n \n getNumericTypes(from: derivedNumericType, into: &numericTypes)\n getNumericValues(from: derivedNumericValues, into: &numericValues)\n \n emitNumericData(\n types: flatten(numericTypes),\n values: flatten(numericValues),\n into: &result\n )\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_Numeric.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenScalarProps_Numeric.swift
Swift
4,975
0.95
0.062176
0.12
react-lib
373
2023-12-03T23:35:22.971585
GPL-3.0
false
66b8c8050fe2ff3e8035ca4f0531fb59
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2022-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nextension Unicode {\n /// Character script types.\n ///\n /// Note this includes the "meta" script type "Katakana_Or_Hiragana", which\n /// isn't defined by https://www.unicode.org/Public/UCD/latest/ucd/Scripts.txt,\n /// but is defined by https://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt.\n /// We may want to split it out, as it's the only case that is a union of\n /// other script types.\n public enum Script: String, Hashable, CaseIterable {\n case adlam = "Adlam"\n case ahom = "Ahom"\n case anatolianHieroglyphs = "Anatolian_Hieroglyphs"\n case arabic = "Arabic"\n case armenian = "Armenian"\n case avestan = "Avestan"\n case balinese = "Balinese"\n case bamum = "Bamum"\n case bassaVah = "Bassa_Vah"\n case batak = "Batak"\n case bengali = "Bengali"\n case bhaiksuki = "Bhaiksuki"\n case bopomofo = "Bopomofo"\n case brahmi = "Brahmi"\n case braille = "Braille"\n case buginese = "Buginese"\n case buhid = "Buhid"\n case canadianAboriginal = "Canadian_Aboriginal"\n case carian = "Carian"\n case caucasianAlbanian = "Caucasian_Albanian"\n case chakma = "Chakma"\n case cham = "Cham"\n case cherokee = "Cherokee"\n case chorasmian = "Chorasmian"\n case common = "Common"\n case coptic = "Coptic"\n case cuneiform = "Cuneiform"\n case cypriot = "Cypriot"\n case cyrillic = "Cyrillic"\n case cyproMinoan = "Cypro_Minoan"\n case deseret = "Deseret"\n case devanagari = "Devanagari"\n case divesAkuru = "Dives_Akuru"\n case dogra = "Dogra"\n case duployan = "Duployan"\n case egyptianHieroglyphs = "Egyptian_Hieroglyphs"\n case elbasan = "Elbasan"\n case elymaic = "Elymaic"\n case ethiopic = "Ethiopic"\n case garay = "Garay"\n case georgian = "Georgian"\n case glagolitic = "Glagolitic"\n case gothic = "Gothic"\n case grantha = "Grantha"\n case greek = "Greek"\n case gujarati = "Gujarati"\n case gunjalaGondi = "Gunjala_Gondi"\n case gurmukhi = "Gurmukhi"\n case gurungKhema = "Gurung_Khema"\n case han = "Han"\n case hangul = "Hangul"\n case hanifiRohingya = "Hanifi_Rohingya"\n case hanunoo = "Hanunoo"\n case hatran = "Hatran"\n case hebrew = "Hebrew"\n case hiragana = "Hiragana"\n case imperialAramaic = "Imperial_Aramaic"\n case inherited = "Inherited"\n case inscriptionalPahlavi = "Inscriptional_Pahlavi"\n case inscriptionalParthian = "Inscriptional_Parthian"\n case javanese = "Javanese"\n case kaithi = "Kaithi"\n case kannada = "Kannada"\n case katakana = "Katakana"\n case katakanaOrHiragana = "Katakana_Or_Hiragana"\n case kawi = "Kawi"\n case kayahLi = "Kayah_Li"\n case kharoshthi = "Kharoshthi"\n case khitanSmallScript = "Khitan_Small_Script"\n case khmer = "Khmer"\n case khojki = "Khojki"\n case khudawadi = "Khudawadi"\n case lao = "Lao"\n case latin = "Latin"\n case lepcha = "Lepcha"\n case limbu = "Limbu"\n case linearA = "Linear_A"\n case linearB = "Linear_B"\n case lisu = "Lisu"\n case lycian = "Lycian"\n case lydian = "Lydian"\n case kiratRai = "Kirat_Rai"\n case mahajani = "Mahajani"\n case makasar = "Makasar"\n case malayalam = "Malayalam"\n case mandaic = "Mandaic"\n case manichaean = "Manichaean"\n case marchen = "Marchen"\n case masaramGondi = "Masaram_Gondi"\n case medefaidrin = "Medefaidrin"\n case meeteiMayek = "Meetei_Mayek"\n case mendeKikakui = "Mende_Kikakui"\n case meroiticCursive = "Meroitic_Cursive"\n case meroiticHieroglyphs = "Meroitic_Hieroglyphs"\n case miao = "Miao"\n case modi = "Modi"\n case mongolian = "Mongolian"\n case mro = "Mro"\n case multani = "Multani"\n case myanmar = "Myanmar"\n case nabataean = "Nabataean"\n case nagMundari = "Nag_Mundari"\n case nandinagari = "Nandinagari"\n case newa = "Newa"\n case newTaiLue = "New_Tai_Lue"\n case nko = "Nko"\n case nushu = "Nushu"\n case nyiakengPuachueHmong = "Nyiakeng_Puachue_Hmong"\n case ogham = "Ogham"\n case olChiki = "Ol_Chiki"\n case oldHungarian = "Old_Hungarian"\n case oldItalic = "Old_Italic"\n case oldNorthArabian = "Old_North_Arabian"\n case oldPermic = "Old_Permic"\n case oldPersian = "Old_Persian"\n case oldSogdian = "Old_Sogdian"\n case oldSouthArabian = "Old_South_Arabian"\n case oldTurkic = "Old_Turkic"\n case oldUyghur = "Old_Uyghur"\n case olOnal = "Ol_Onal"\n case oriya = "Oriya"\n case osage = "Osage"\n case osmanya = "Osmanya"\n case pahawhHmong = "Pahawh_Hmong"\n case palmyrene = "Palmyrene"\n case pauCinHau = "Pau_Cin_Hau"\n case phagsPa = "Phags_Pa"\n case phoenician = "Phoenician"\n case psalterPahlavi = "Psalter_Pahlavi"\n case rejang = "Rejang"\n case runic = "Runic"\n case samaritan = "Samaritan"\n case saurashtra = "Saurashtra"\n case sharada = "Sharada"\n case shavian = "Shavian"\n case siddham = "Siddham"\n case signWriting = "SignWriting"\n case sinhala = "Sinhala"\n case sogdian = "Sogdian"\n case soraSompeng = "Sora_Sompeng"\n case soyombo = "Soyombo"\n case sundanese = "Sundanese"\n case sunuwar = "Sunuwar"\n case sylotiNagri = "Syloti_Nagri"\n case syriac = "Syriac"\n case tagalog = "Tagalog"\n case tagbanwa = "Tagbanwa"\n case taiLe = "Tai_Le"\n case taiTham = "Tai_Tham"\n case taiViet = "Tai_Viet"\n case takri = "Takri"\n case tamil = "Tamil"\n case tangsa = "Tangsa"\n case tangut = "Tangut"\n case telugu = "Telugu"\n case thaana = "Thaana"\n case thai = "Thai"\n case tibetan = "Tibetan"\n case tifinagh = "Tifinagh"\n case tirhuta = "Tirhuta"\n case todhri = "Todhri"\n case toto = "Toto"\n case tuluTigalari = "Tulu_Tigalari"\n case ugaritic = "Ugaritic"\n case unknown = "Unknown"\n case vai = "Vai"\n case vithkuqi = "Vithkuqi"\n case wancho = "Wancho"\n case warangCiti = "Warang_Citi"\n case yezidi = "Yezidi"\n case yi = "Yi"\n case zanabazarSquare = "Zanabazar_Square"\n }\n}\n\nfunc scriptAbbr2Enum(_ str: String) -> Unicode.Script {\n switch str {\n case "Adlm", "adlam": return .adlam\n case "Aghb", "caucasianalbanian": return .caucasianAlbanian\n case "Ahom": return .ahom\n case "Arab", "arabic": return .arabic\n case "Armi", "imperialaramaic": return .imperialAramaic\n case "Armn", "armenian": return .armenian\n case "Avst", "avestan": return .avestan\n case "Bali", "balinese": return .balinese\n case "Bamu", "bamum": return .bamum\n case "Bass", "bassavah": return .bassaVah\n case "Batk", "batak": return .batak\n case "Beng", "bengali": return .bengali\n case "Bhks", "bhaiksuki": return .bhaiksuki\n case "Bopo", "bopomofo": return .bopomofo\n case "Brah", "brahmi": return .brahmi\n case "Brai", "braille": return .braille\n case "Bugi", "buginese": return .buginese\n case "Buhd", "buhid": return .buhid\n case "Cakm", "chakma": return .chakma\n case "Cans", "canadianaboriginal": return .canadianAboriginal\n case "Cari", "carian": return .carian\n case "Cham": return .cham\n case "Cher", "cherokee": return .cherokee\n case "Chrs", "chorasmian": return .chorasmian\n case "Copt", "coptic", "qaac": return .coptic\n case "Cpmn", "cyprominoan": return .cyproMinoan\n case "Cprt", "cypriot": return .cypriot\n case "Cyrl", "cyrillic": return .cyrillic\n case "Deva", "devanagari": return .devanagari\n case "Diak", "divesakuru": return .divesAkuru\n case "Dogr", "dogra": return .dogra\n case "Dsrt", "deseret": return .deseret\n case "Dupl", "duployan": return .duployan\n case "Egyp", "egyptianhieroglyphs": return .egyptianHieroglyphs\n case "Elba", "elbasan": return .elbasan\n case "Elym", "elymaic": return .elymaic\n case "Ethi", "ethiopic": return .ethiopic\n case "Gara": return .garay\n case "Geor", "georgian": return .georgian\n case "Glag", "glagolitic": return .glagolitic\n case "Gong", "gunjalagondi": return .gunjalaGondi\n case "Gonm", "masaramgondi": return .masaramGondi\n case "Goth", "gothic": return .gothic\n case "Gran", "grantha": return .grantha\n case "Grek", "greek": return .greek\n case "Gujr", "gujarati": return .gujarati\n case "Gukh": return .gurungKhema\n case "Guru", "gurmukhi": return .gurmukhi\n case "Hang", "hangul": return .hangul\n case "Hani", "han": return .han\n case "Hano", "hanunoo": return .hanunoo\n case "Hatr", "hatran": return .hatran\n case "Hebr", "hebrew": return .hebrew\n case "Hira", "hiragana": return .hiragana\n case "Hluw", "anatolianhieroglyphs": return .anatolianHieroglyphs\n case "Hmng", "pahawhhmong": return .pahawhHmong\n case "Hmnp", "nyiakengpuachuehmong": return .nyiakengPuachueHmong\n case "Hrkt", "katakanaorhiragana": return .katakanaOrHiragana\n case "Hung", "oldhungarian": return .oldHungarian\n case "Ital", "olditalic": return .oldItalic\n case "Java", "javanese": return .javanese\n case "Kali", "kayahli": return .kayahLi\n case "Kawi": return .kawi\n case "Kana", "katakana": return .katakana\n case "Khar", "kharoshthi": return .kharoshthi\n case "Khmr", "khmer": return .khmer\n case "Khoj", "khojki": return .khojki\n case "Kits", "khitansmallscript": return .khitanSmallScript\n case "Knda", "kannada": return .kannada\n case "Krai": return .kiratRai\n case "Kthi", "kaithi": return .kaithi\n case "Lana", "taitham": return .taiTham\n case "Laoo", "lao": return .lao\n case "Latn", "latin": return .latin\n case "Lepc", "lepcha": return .lepcha\n case "Limb", "limbu": return .limbu\n case "Lina", "lineara": return .linearA\n case "Linb", "linearb": return .linearB\n case "Lisu": return .lisu\n case "Lyci", "lycian": return .lycian\n case "Lydi", "lydian": return .lydian\n case "Mahj", "mahajani": return .mahajani\n case "Maka", "makasar": return .makasar\n case "Mand", "mandaic": return .mandaic\n case "Mani", "manichaean": return .manichaean\n case "Marc", "marchen": return .marchen\n case "Medf", "medefaidrin": return .medefaidrin\n case "Mend", "mendekikakui": return .mendeKikakui\n case "Merc", "meroiticcursive": return .meroiticCursive\n case "Mero", "meroitichieroglyphs": return .meroiticHieroglyphs\n case "Mlym", "malayalam": return .malayalam\n case "Modi": return .modi\n case "Mong", "mongolian": return .mongolian\n case "Mroo", "mro": return .mro\n case "Mtei", "meeteimayek": return .meeteiMayek\n case "Mult", "multani": return .multani\n case "Mymr", "myanmar": return .myanmar\n case "Nagm": return .nagMundari\n case "Nand", "nandinagari": return .nandinagari\n case "Narb", "oldnortharabian": return .oldNorthArabian\n case "Nbat", "nabataean": return .nabataean\n case "Newa": return .newa\n case "Nkoo", "nko": return .nko\n case "Nshu", "nushu": return .nushu\n case "Ogam", "ogham": return .ogham\n case "Olck", "olchiki": return .olChiki\n case "Onao": return .olOnal\n case "Orkh", "oldturkic": return .oldTurkic\n case "Orya", "oriya": return .oriya\n case "Osge", "osage": return .osage\n case "Osma", "osmanya": return .osmanya\n case "Ougr", "olduyghur": return .oldUyghur\n case "Palm", "palmyrene": return .palmyrene\n case "Pauc", "paucinhau": return .pauCinHau\n case "Perm", "oldpermic": return .oldPermic\n case "Phag", "phagspa": return .phagsPa\n case "Phli", "inscriptionalpahlavi": return .inscriptionalPahlavi\n case "Phlp", "psalterpahlavi": return .psalterPahlavi\n case "Phnx", "phoenician": return .phoenician\n case "Plrd", "miao": return .miao\n case "Prti", "inscriptionalparthian": return .inscriptionalParthian\n case "Rjng", "rejang": return .rejang\n case "Rohg", "hanifirohingya": return .hanifiRohingya\n case "Runr", "runic": return .runic\n case "Samr", "samaritan": return .samaritan\n case "Sarb", "oldsoutharabian": return .oldSouthArabian\n case "Saur", "saurashtra": return .saurashtra\n case "Sgnw", "signwriting": return .signWriting\n case "Shaw", "shavian": return .shavian\n case "Shrd", "sharada": return .sharada\n case "Sidd", "siddham": return .siddham\n case "Sind", "khudawadi": return .khudawadi\n case "Sinh", "sinhala": return .sinhala\n case "Sogd", "sogdian": return .sogdian\n case "Sogo", "oldsogdian": return .oldSogdian\n case "Sora", "sorasompeng": return .soraSompeng\n case "Soyo", "soyombo": return .soyombo\n case "Sund", "sundanese": return .sundanese\n case "Sunu": return .sunuwar\n case "Sylo", "sylotinagri": return .sylotiNagri\n case "Syrc", "syriac": return .syriac\n case "Tagb", "tagbanwa": return .tagbanwa\n case "Takr", "takri": return .takri\n case "Tale", "taile": return .taiLe\n case "Talu", "newtailue": return .newTaiLue\n case "Taml", "tamil": return .tamil\n case "Tang", "tangut": return .tangut\n case "Tavt", "taiviet": return .taiViet\n case "Telu", "telugu": return .telugu\n case "Tfng", "tifinagh": return .tifinagh\n case "Tglg", "tagalog": return .tagalog\n case "Thaa", "thaana": return .thaana\n case "Thai": return .thai\n case "Tibt", "tibetan": return .tibetan\n case "Tirh", "tirhuta": return .tirhuta\n case "Tnsa", "tangsa": return .tangsa\n case "Todr": return .todhri\n case "Toto": return .toto\n case "Tutg": return .tuluTigalari\n case "Ugar", "ugaritic": return .ugaritic\n case "Vaii", "vai": return .vai\n case "Vith", "vithkuqi": return .vithkuqi\n case "Wara", "warangciti": return .warangCiti\n case "Wcho", "wancho": return .wancho\n case "Xpeo", "oldpersian": return .oldPersian\n case "Xsux", "cuneiform": return .cuneiform\n case "Yezi", "yezidi": return .yezidi\n case "Yiii", "yi": return .yi\n case "Zanb", "zanabazarsquare": return .zanabazarSquare\n case "Zinh", "inherited", "qaai": return .inherited\n case "Zyyy", "common": return .common\n case "Zzzz", "unknown": return .unknown\n default: fatalError("Unknown script: \(str)")\n }\n}\n\nfunc getScriptData(\n for path: String\n) -> [(ClosedRange<UInt32>, String)] {\n let data = readFile(path)\n \n var unflattened: [(ClosedRange<UInt32>, String)] = []\n \n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n // Each line in this file is broken up into two sections:\n // 1: Either the singular scalar or a range of scalars who conform to said\n // grapheme break property.\n // 2: The script that said scalar(s) conforms to.\n let components = line.split(separator: ";")\n \n // Get the script first because it may be one we don't care about.\n let splitProperty = components[1].split(separator: "#")\n let filteredProperty = splitProperty[0].filter { !$0.isWhitespace }\n \n guard Unicode.Script(rawValue: filteredProperty) != nil else {\n fatalError("Please add the following script: \(filteredProperty)")\n }\n\n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n unflattened.append((scalars, filteredProperty))\n }\n \n return flatten(unflattened)\n}\n\nfunc getScriptExtensionData(\n for path: String\n) -> [(ClosedRange<UInt32>, [String])] {\n let data = readFile(path)\n \n var unflattened: [(ClosedRange<UInt32>, [String])] = []\n \n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n // Each line in this file is broken up into two sections:\n // 1: Either the singular scalar or a range of scalars who conform to said\n // grapheme break property.\n // 2: The grapheme break property that said scalar(s) conform to (with\n // additional comments noting the character category, name and amount of\n // scalars the range represents).\n let components = line.split(separator: ";")\n \n // Get the property first because it may be one we don't care about.\n let splitProperty = components[1].split(separator: "#")\n let scripts = splitProperty[0].split(separator: " ").map { String($0) }\n \n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n unflattened.append((scalars, scripts))\n }\n \n return flatten(unflattened)\n}\n\nfunc emitScriptData(\n _ data: [(ClosedRange<UInt32>, String)],\n into result: inout String\n) {\n var scriptData: [UInt32: Unicode.Script] = [:]\n \n for (range, property) in data {\n for scalar in range {\n scriptData[scalar] = Unicode.Script(rawValue: property)\n }\n }\n \n for i in 0x0 ... 0x10FFFF {\n guard let scalar = Unicode.Scalar(i) else {\n continue\n }\n \n if !scriptData.keys.contains(scalar.value) {\n scriptData[scalar.value] = .unknown\n }\n }\n \n let data = flatten(Array(scriptData))\n\n result += """\n #define SCRIPTS_COUNT \(data.count)\n\n \n """\n\n emitCollection(\n data,\n name: "_swift_stdlib_scripts",\n type: "__swift_uint32_t",\n into: &result\n ) {\n var value = $0.0.lowerBound\n value |= UInt32(unsafeBitCast($0.1, to: UInt8.self)) << 21\n \n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n}\n\nfunc emitScriptExtensionData(\n _ data: [(ClosedRange<UInt32>, [String])],\n into result: inout String\n) {\n var indices: [[String]: UInt16] = [:]\n var bytes: [UInt8] = []\n var currentIndex: UInt16 = 0\n \n for (_, scripts) in data {\n guard !indices.keys.contains(scripts) else {\n continue\n }\n \n indices[scripts] = currentIndex | (UInt16(scripts.count) << 11)\n \n for script in scripts {\n let scriptEnum = scriptAbbr2Enum(script)\n let byte = unsafeBitCast(scriptEnum, to: UInt8.self)\n \n bytes.append(byte)\n currentIndex += 1\n }\n }\n \n // 64 bit arrays * 8 bytes = .512 KB\n var bitArrays: [BitArray] = .init(repeating: .init(size: 64), count: 64)\n \n let chunkSize = 0x110000 / 64 / 64\n \n var chunks: [Int] = []\n \n for i in 0 ..< 64 * 64 {\n let lower = i * chunkSize\n let upper = lower + chunkSize - 1\n \n let idx = i / 64\n let bit = i % 64\n \n for scalar in lower ... upper {\n if data.contains(where: { $0.0.contains(UInt32(scalar)) }) {\n chunks.append(i)\n \n bitArrays[idx][bit] = true\n break\n }\n }\n }\n \n // Remove the trailing 0s. Currently this reduces quick look size down to\n // 96 bytes from 512 bytes.\n var reducedBA = Array(bitArrays.reversed())\n reducedBA = Array(reducedBA.drop {\n $0.words == [0x0]\n })\n \n bitArrays = reducedBA.reversed()\n \n // Keep a record of every rank for all the bitarrays.\n var ranks: [UInt16] = []\n \n // Record our quick look ranks.\n var lastRank: UInt16 = 0\n for (i, _) in bitArrays.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(bitArrays[i - 1].words[0].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n \n lastRank = rank\n }\n \n // Insert our quick look size at the beginning.\n var size = BitArray(size: 64)\n size.words = [UInt64(bitArrays.count)]\n bitArrays.insert(size, at: 0)\n \n var dataIndices: [UInt16] = []\n \n for chunk in chunks {\n var chunkBA = BitArray(size: chunkSize)\n \n let lower = chunk * chunkSize\n let upper = lower + chunkSize\n \n let chunkDataIdx = UInt64(dataIndices.endIndex)\n \n // Insert our chunk's data index in the upper bits of the last word of our\n // bit array.\n chunkBA.words[chunkBA.words.endIndex - 1] |= chunkDataIdx << 16\n \n for scalar in lower ..< upper {\n if data.contains(where: { $0.0.contains(UInt32(scalar)) }) {\n chunkBA[scalar % chunkSize] = true\n \n let data = data[data.firstIndex {\n $0.0.contains(UInt32(scalar))\n }!].1\n \n dataIndices.append(indices[data]!)\n }\n }\n \n // Append our chunk bit array's rank.\n var lastRank: UInt16 = 0\n for (i, _) in chunkBA.words.enumerated() {\n guard i != 0 else {\n ranks.append(0)\n continue\n }\n \n var rank = UInt16(chunkBA.words[i - 1].nonzeroBitCount)\n rank += lastRank\n \n ranks.append(rank)\n lastRank = rank\n }\n \n bitArrays += chunkBA.words.map {\n var ba = BitArray(size: 64)\n ba.words = [$0]\n return ba\n }\n }\n \n emitCollection(\n bytes,\n name: "_swift_stdlib_script_extensions_data",\n into: &result\n )\n \n emitCollection(\n dataIndices,\n name: "_swift_stdlib_script_extensions_data_indices",\n into: &result\n )\n \n emitCollection(\n ranks,\n name: "_swift_stdlib_script_extensions_ranks",\n into: &result\n )\n \n emitCollection(\n bitArrays,\n name: "_swift_stdlib_script_extensions",\n type: "__swift_uint64_t",\n into: &result\n ) {\n assert($0.words.count == 1)\n return "0x\(String($0.words[0], radix: 16, uppercase: true))"\n }\n}\n\nfunc generateScriptProperties() {\n var result = readFile("Input/ScriptData.h")\n \n let data = getScriptData(for: "Data/16/Scripts.txt")\n emitScriptData(data, into: &result)\n \n let extensionData = getScriptExtensionData(for: "Data/16/ScriptExtensions.txt")\n emitScriptExtensionData(extensionData, into: &result)\n\n result += """\n #endif // #ifndef SCRIPT_DATA_H\n\n """\n\n write(result, to: "Output/Common/ScriptData.h")\n}\n\ngenerateScriptProperties()\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenScripts_main.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenScripts_main.swift
Swift
24,627
0.95
0.037627
0.077049
react-lib
521
2024-07-14T01:45:09.559233
GPL-3.0
false
8be7dede89b554bda9ce9fb478a7309b
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct BitArray {\n public var words: [UInt64]\n public var size: UInt16\n \n public init(size: Int) {\n self.words = .init(repeating: 0, count: (size + 63) / 64)\n self.size = UInt16(size)\n }\n \n public subscript(_ bit: Int) -> Bool {\n get {\n return words[bit / 64] & (1 << (bit % 64)) != 0\n }\n \n set {\n if newValue {\n words[bit / 64] |= 1 << (bit % 64)\n } else {\n words[bit / 64] &= ~(1 << (bit % 64))\n }\n }\n }\n \n public mutating func insert(_ bit: Int) -> Bool {\n let oldData = words[bit / 64]\n words[bit / 64] |= 1 << (bit % 64)\n return oldData & (1 << (bit % 64)) == 0\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_BitArray.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_BitArray.swift
Swift
1,167
0.8
0.073171
0.305556
python-kit
878
2024-03-27T11:52:07.267505
MIT
false
717465ca2432b75dc605bc2c91c62f8b
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nfunc _eytzingerize<C: Collection>(_ collection: C, result: inout [C.Element], sourceIndex: Int, resultIndex: Int) -> Int where C.Element: Comparable, C.Index == Int {\n var sourceIndex = sourceIndex\n if resultIndex < result.count {\n sourceIndex = _eytzingerize(collection, result: &result, sourceIndex: sourceIndex, resultIndex: 2 * resultIndex)\n result[resultIndex] = collection[sourceIndex]\n sourceIndex = _eytzingerize(collection, result: &result, sourceIndex: sourceIndex + 1, resultIndex: 2 * resultIndex + 1)\n }\n return sourceIndex\n}\n\n/*\n Takes a sorted collection and reorders it to an array-encoded binary search tree, as originally developed by Michaël Eytzinger in the 16th century.\n This allows binary searching the array later to touch roughly 4x fewer cachelines, significantly speeding it up.\n */\npublic func eytzingerize<C: Collection>(_ collection: C, dummy: C.Element) -> [C.Element] where C.Element: Comparable, C.Index == Int {\n var result = Array(repeating: dummy, count: collection.count + 1)\n _ = _eytzingerize(collection, result: &result, sourceIndex: 0, resultIndex: 1)\n return result\n}\n\npublic func emitCollection<C: Collection>(\n _ collection: C,\n name: String,\n type: String,\n into result: inout String,\n formatter: (C.Element) -> String\n) {\n result += """\n static const \(type) \(name)[\(collection.count)] = {\n \n """\n \n formatCollection(collection, into: &result, using: formatter)\n \n result += "\n};\n\n"\n}\n\npublic func emitCollection<C: Collection>(\n _ collection: C,\n name: String,\n into result: inout String\n) where C.Element: FixedWidthInteger {\n emitCollection(\n collection,\n name: name,\n type: "__swift_\(C.Element.isSigned ? "" : "u")int\(C.Element.bitWidth)_t",\n into: &result\n ) {\n "0x\(String($0, radix: 16, uppercase: true))"\n }\n}\n\n// Emits an abstract minimal perfect hash function into C arrays.\npublic func emitMph(\n _ mph: Mph,\n name: String,\n defineLabel: String,\n into result: inout String\n) {\n result += """\n #define \(defineLabel)_LEVEL_COUNT \(mph.bitArrays.count)\n \n \n """\n \n emitMphSizes(mph, name, into: &result)\n emitMphBitarrays(mph, name, into: &result)\n emitMphRanks(mph, name, into: &result)\n}\n\n// BitArray sizes\nfunc emitMphSizes(_ mph: Mph, _ name: String, into result: inout String) {\n emitCollection(\n mph.bitArrays,\n name: "\(name)_sizes",\n type: "__swift_uint16_t",\n into: &result\n ) {\n "0x\(String($0.size, radix: 16, uppercase: true))"\n }\n}\n\nfunc emitMphBitarrays(_ mph: Mph, _ name: String, into result: inout String) {\n // Individual bitarrays\n \n for (i, ba) in mph.bitArrays.enumerated() {\n emitCollection(ba.words, name: "\(name)_keys\(i)", into: &result)\n }\n \n // Overall bitarrays\n \n emitCollection(\n mph.bitArrays.indices,\n name: "\(name)_keys",\n type: "__swift_uint64_t * const",\n into: &result\n ) {\n "\(name)_keys\($0)"\n }\n}\n\nfunc emitMphRanks(_ mph: Mph, _ name: String, into result: inout String) {\n // Individual ranks\n \n for (i, rank) in mph.ranks.enumerated() {\n emitCollection(rank, name: "\(name)_ranks\(i)", into: &result)\n }\n \n // Overall ranks\n \n emitCollection(\n mph.ranks.indices,\n name: "\(name)_ranks",\n type: "__swift_uint16_t * const",\n into: &result\n ) {\n "\(name)_ranks\($0)"\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Emit.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Emit.swift
Swift
3,824
0.95
0.045802
0.18018
python-kit
532
2024-05-31T18:02:42.256413
Apache-2.0
false
910d95a0b1713f4523ad84cfa1968e5b
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic func readFile(_ path: String) -> String {\n do {\n return try String(contentsOfFile: path, encoding: .utf8)\n } catch {\n fatalError(error.localizedDescription)\n }\n}\n\npublic func write(_ data: String, to path: String) {\n do {\n try data.write(toFile: path, atomically: false, encoding: .utf8)\n } catch {\n fatalError(error.localizedDescription)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Files.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Files.swift
Swift
901
0.95
0.206897
0.423077
node-utils
755
2025-04-03T20:25:31.129619
Apache-2.0
false
d75755a16333941c0cb3742c64b1e578
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Takes an unflattened array of scalar ranges and some Equatable property and\n// attempts to merge ranges who share the same Equatable property. E.g:\n//\n// 0x0 ... 0xA = .control\n// 0xB ... 0xB = .control\n// 0xC ... 0x1F = .control\n//\n// into:\n//\n// 0x0 ... 0x1F = .control\npublic func flatten<T: Equatable>(\n _ unflattened: [(ClosedRange<UInt32>, T)]\n) -> [(ClosedRange<UInt32>, T)] {\n var result: [(ClosedRange<UInt32>, T)] = []\n\n for elt in unflattened.sorted(by: { $0.0.lowerBound < $1.0.lowerBound }) {\n guard !result.isEmpty, result.last!.1 == elt.1 else {\n result.append(elt)\n continue\n }\n \n if elt.0.lowerBound == result.last!.0.upperBound + 1 {\n result[result.count - 1].0 = result.last!.0.lowerBound ... elt.0.upperBound\n } else {\n result.append(elt)\n }\n }\n\n return result\n}\n\n// Takes an unflattened array of scalars and some Equatable property and\n// attempts to merge scalars into ranges who share the same Equatable\n// property. E.g:\n//\n// 0x9 = .control\n// 0xA = .control\n// 0xB = .control\n// 0xC = .control\n//\n// into:\n//\n// 0x9 ... 0xC = .control\npublic func flatten<T: Equatable>(\n _ unflattened: [(UInt32, T)]\n) -> [(ClosedRange<UInt32>, T)] {\n var result: [(ClosedRange<UInt32>, T)] = []\n \n for elt in unflattened.sorted(by: { $0.0 < $1.0 }) {\n guard !result.isEmpty, result.last!.1 == elt.1 else {\n result.append((elt.0 ... elt.0, elt.1))\n continue\n }\n \n if elt.0 == result.last!.0.upperBound + 1 {\n result[result.count - 1].0 = result.last!.0.lowerBound ... elt.0\n } else {\n result.append((elt.0 ... elt.0, elt.1))\n }\n }\n \n return result\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Flatten.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Flatten.swift
Swift
2,205
0.8
0.08
0.492537
react-lib
946
2024-04-11T01:32:59.468687
MIT
false
426bf66c640cf9b524d11d6c4aa7e804
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Given a collection, format it into a string within 80 columns and fitting as\n// many elements in a row as possible.\npublic func formatCollection<C: Collection>(\n _ c: C,\n into result: inout String,\n using handler: (C.Element) -> String\n) {\n // Our row length always starts at 2 for the initial indentation.\n var rowLength = 2\n\n for element in c {\n let string = handler(element)\n\n if rowLength == 2 {\n result += " "\n }\n\n if rowLength + string.count + 1 > 100 {\n result += "\n "\n\n rowLength = 2\n } else {\n result += rowLength == 2 ? "" : " "\n }\n\n result += "\(string),"\n\n // string.count + , + space\n rowLength += string.count + 1 + 1\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Formatting.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Formatting.swift
Swift
1,210
0.8
0.139535
0.416667
awesome-app
622
2023-12-15T18:56:37.599982
MIT
false
58b8f89872b832642091d9e1d937297d
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nfunc hash(_ key: UInt64, _ n: UInt64, seed: UInt64) -> UInt64 {\n let key = key | (n << 32)\n let hash = UInt64(murmur3(key, seed: UInt32(seed)))\n \n return hash % n\n}\n\nfunc scramble(_ key: UInt32) -> UInt32 {\n var key = key\n key &*= 0xCC9E2D51\n key = (key << 15) | (key >> 17)\n key &*= 0x1B873593\n return key\n}\n\nfunc murmur3(_ key: UInt64, seed: UInt32) -> UInt32 {\n var hash = seed\n var k: UInt32\n var key = key\n \n for _ in 0 ..< 2 {\n k = UInt32((key << 32) >> 32)\n key >>= 32\n \n hash ^= scramble(k)\n hash = (hash << 13) | (hash >> 19)\n hash = hash &* 5 &+ 0xE6546B64\n }\n \n hash ^= 8\n hash ^= hash >> 16\n hash &*= 0x85EBCA6B\n hash ^= hash >> 13\n hash &*= 0xC2B2AE35\n hash ^= hash >> 16\n \n return hash\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Hashing.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Hashing.swift
Swift
1,257
0.8
0.06
0.261905
vue-tools
335
2025-04-26T02:56:30.958439
BSD-3-Clause
false
b50e29c4682b4d3e7be7a113c5fcd0ed
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct Mph {\n public var bitArrays: [BitArray] = []\n public var ranks: [[UInt16]] = []\n \n init(gamma: Double, keys: [UInt64]) {\n var size: Int\n var a: BitArray\n var collide: Set<Int>\n var redoKeys: [UInt64] = keys\n var i: UInt64 = 0\n \n repeat {\n size = Swift.max(64, Int(gamma * Double(redoKeys.count)))\n a = BitArray(size: size)\n collide = []\n \n for key in redoKeys {\n let idx = Int(hash(key, UInt64(size), seed: i))\n \n if !collide.contains(idx), !a.insert(idx) {\n collide.insert(idx)\n }\n }\n \n var tmpRedo: [UInt64] = []\n \n for key in redoKeys {\n let idx = Int(hash(key, UInt64(size), seed: i))\n \n if collide.contains(idx) {\n a[idx] = false\n tmpRedo.append(key)\n }\n }\n \n bitArrays.append(a)\n redoKeys = tmpRedo\n i += 1\n } while !redoKeys.isEmpty\n \n computeRanks()\n }\n \n mutating func computeRanks() {\n var pop: UInt16 = 0\n \n for bitArray in bitArrays {\n var rank: [UInt16] = []\n \n for i in 0 ..< bitArray.words.count {\n let v = bitArray.words[i]\n \n if i % 8 == 0 {\n rank.append(pop)\n }\n \n pop += UInt16(v.nonzeroBitCount)\n }\n \n ranks.append(rank)\n }\n }\n \n public func index(for key: UInt64) -> Int {\n for i in 0 ..< bitArrays.count {\n let b = bitArrays[i]\n let idx = Int(hash(key, UInt64(b.size), seed: UInt64(i)))\n \n if b[idx] {\n var rank = ranks[i][idx / 512]\n \n for j in (idx / 64) & ~7 ..< idx / 64 {\n rank += UInt16(b.words[j].nonzeroBitCount)\n }\n \n let finalWord = b.words[idx / 64]\n \n if idx % 64 > 0 {\n rank += UInt16((finalWord << (64 - (idx % 64))).nonzeroBitCount)\n }\n \n return Int(rank)\n }\n }\n \n return -1\n }\n}\n\n\npublic func mph(for keys: [UInt64]) -> Mph {\n Mph(gamma: 1, keys: keys)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Mph.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenUtils_Mph.swift
Swift
2,545
0.8
0.152381
0.1375
python-kit
548
2024-09-18T23:11:11.531356
Apache-2.0
false
50643aa9b6d90b8f765d4d1d6fc9400a
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport GenUtils\n\nextension Unicode {\n enum WordBreakProperty: UInt8 {\n // We don't store the other properties, so we really don't care about them\n // here.\n \n case extend = 0\n case format = 1\n case katakana = 2\n case hebrewLetter = 3\n case aLetter = 4\n case midNumLet = 5\n case midLetter = 6\n case midNum = 7\n case numeric = 8\n case extendNumLet = 9\n case wSegSpace = 10\n case extendedPictographic = 11\n \n init?(_ str: String) {\n switch str {\n case "Extend":\n self = .extend\n case "Format":\n self = .format\n case "Katakana":\n self = .katakana\n case "Hebrew_Letter":\n self = .hebrewLetter\n case "ALetter":\n self = .aLetter\n case "MidNumLet":\n self = .midNumLet\n case "MidLetter":\n self = .midLetter\n case "MidNum":\n self = .midNum\n case "Numeric":\n self = .numeric\n case "ExtendNumLet":\n self = .extendNumLet\n case "WSegSpace":\n self = .wSegSpace\n case "Extended_Pictographic":\n self = .extendedPictographic\n default:\n return nil\n }\n }\n }\n}\n\nstruct WordBreakEntry : Comparable {\n static func < (lhs: WordBreakEntry, rhs: WordBreakEntry) -> Bool {\n return lhs.index < rhs.index\n }\n \n let index: Int\n let range: ClosedRange<UInt32>\n let property: Unicode.WordBreakProperty\n}\n\nfunc getWordBreakPropertyData(\n for path: String\n) -> [(ClosedRange<UInt32>, Unicode.WordBreakProperty)] {\n let data = readFile(path)\n \n var unflattened: [(ClosedRange<UInt32>, Unicode.WordBreakProperty)] = []\n \n for line in data.split(separator: "\n") {\n // Skip comments\n guard !line.hasPrefix("#") else {\n continue\n }\n \n // Each line in this file is broken up into two sections:\n // 1: Either the singular scalar or a range of scalars who conform to said\n // grapheme break property.\n // 2: The grapheme break property that said scalar(s) conform to (with\n // additional comments noting the character category, name and amount of\n // scalars the range represents).\n let components = line.split(separator: ";")\n \n // Get the property first because it may be one we don't care about.\n let splitProperty = components[1].split(separator: "#")\n let filteredProperty = splitProperty[0].filter { !$0.isWhitespace }\n \n guard let gbp = Unicode.WordBreakProperty(filteredProperty) else {\n continue\n }\n \n let scalars: ClosedRange<UInt32>\n \n let filteredScalars = components[0].filter { !$0.isWhitespace }\n \n // If we have . appear, it means we have a legitimate range. Otherwise,\n // it's a singular scalar.\n if filteredScalars.contains(".") {\n let range = filteredScalars.split(separator: ".")\n \n scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!\n } else {\n let scalar = UInt32(filteredScalars, radix: 16)!\n \n scalars = scalar ... scalar\n }\n \n unflattened.append((scalars, gbp))\n }\n \n return flatten(unflattened)\n}\n\nfunc emit(\n _ data: [WordBreakEntry],\n into result: inout String\n) {\n \n result += """\n #define WORD_BREAK_DATA_COUNT \(data.count)\n \n """\n \n emitCollection(\n data,\n name: "_swift_stdlib_words",\n type: "__swift_uint32_t",\n into: &result\n ) {\n var value = $0.range.lowerBound\n value |= UInt32($0.range.count) << 21\n \n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n \n emitCollection(\n data,\n name: "_swift_stdlib_words_data",\n type: "__swift_uint8_t",\n into: &result\n ) {\n let value = $0.property.rawValue\n \n return "0x\(String(value, radix: 16, uppercase: true))"\n }\n}\n\n// Main entry point into the word break generator.\nfunc generateWordBreak() {\n var result = readFile("Input/WordData.h")\n \n let baseData = getWordBreakPropertyData(for: "Data/16/WordBreakProperty.txt")\n let emojiData = getWordBreakPropertyData(for: "Data/16/emoji-data.txt")\n \n var idx = 0\n let data = flatten(baseData + emojiData).map { (values) -> WordBreakEntry in\n idx += 1\n return WordBreakEntry(\n index: idx,\n range: values.0,\n property: values.1\n )\n }\n \n let reorderedData = eytzingerize(data, dummy: WordBreakEntry(\n index: 0,\n range: 0...0,\n property: .extend\n ))\n \n emit(reorderedData, into: &result)\n \n result += """\n #endif // #ifndef WORD_DATA_H\n \n """\n \n write(result, to: "Output/Common/WordData.h")\n}\n\ngenerateWordBreak()\n
dataset_sample\swift\swift\cpp_apple_swift_utils_gen-unicode-data_Sources_GenWordBreak_main.swift
cpp_apple_swift_utils_gen-unicode-data_Sources_GenWordBreak_main.swift
Swift
5,028
0.95
0.041237
0.163522
react-lib
277
2023-09-26T05:38:04.092096
GPL-3.0
false
95d40cb60bb44fff9c600483cafed7d6
// --- sourcekit_fuzzer.swift - a simple code completion fuzzer ---------------\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n// ----------------------------------------------------------------------------\n//\n// The idea here is we start with a source file and proceed to place the cursor\n// at random locations in the file, eventually visiting all locations exactly\n// once in a shuffled random order.\n//\n// If completion at a location crashes, we run the test case through 'creduce'\n// to find a minimal reproducer that also crashes (possibly with a different\n// crash, but in practice all the examples I've seen continue to crash in the\n// same way as creduce performs its reduction).\n//\n// Once creduce fully reduces a test case, we save it to a file named\n// 'crash-NNN.swift', with a RUN: line suitable for placing the test case in\n// 'validation-tests/IDE/crashers_2'.\n//\n// The overall script execution stops once all source locations in the file\n// have been tested.\n//\n// You must first install creduce <https://embed.cs.utah.edu/creduce/>\n// somewhere in your $PATH. Then, run this script as follows:\n//\n// swift utils/sourcekit_fuzzer/sourcekit_fuzzer.swift <build dir> <source file>\n//\n// - <build dir> is your Swift build directory (the one with subdirectories\n// named swift-macosx-x86_64 and llvm-macosx-x86_64).\n//\n// - <source file> is the source file to fuzz. Try any complex but\n// self-contained Swift file that exercises a variety of language features;\n// for example, I've had good results with the files in test/Prototypes/.\n//\n// TODO:\n// - Add fuzzing for CursorInfo and RangeInfo\n// - Get it running on Linux\n// - Better error handling\n// - More user-friendly output\n\nimport Darwin\nimport Foundation\n\n// https://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift/24029847\nextension MutableCollection {\n /// Shuffles the contents of this collection.\n mutating func shuffle() {\n let c = count\n guard c > 1 else { return }\n\n for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {\n let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount)))\n guard d != 0 else { continue }\n let i = index(firstUnshuffled, offsetBy: d)\n swapAt(firstUnshuffled, i)\n }\n }\n}\n\nextension String {\n func write(to path: String) throws {\n try write(to: URL(fileURLWithPath: path), atomically: true, encoding: String.Encoding.utf8)\n }\n}\n\n// Gross\nenum ProcessError : Error {\n case failed\n}\n\nfunc run(_ args: [String]) throws -> Int32 {\n var pid: pid_t = 0\n\n let argv = args.map {\n $0.withCString(strdup)\n }\n defer { argv.forEach { free($0) } }\n\n let envp = ProcessInfo.processInfo.environment.map {\n "\($0.0)=\($0.1)".withCString(strdup)\n }\n defer { envp.forEach { free($0) } }\n\n let result = posix_spawn(&pid, argv[0], nil, nil, argv + [nil], envp + [nil])\n if result != 0 { throw ProcessError.failed }\n\n var stat: Int32 = 0\n waitpid(pid, &stat, 0)\n\n return stat\n}\n\nvar arguments = CommandLine.arguments\n\n// Workaround for behavior of CommandLine in script mode, where we don't drop\n// the filename argument from the list.\nif arguments.first == "sourcekit_fuzzer.swift" {\n arguments = Array(arguments[1...])\n}\n\nif arguments.count != 2 {\n print("Usage: sourcekit_fuzzer <build directory> <file>")\n exit(1)\n}\n\nlet buildDir = arguments[0]\n\nlet notPath = "\(buildDir)/llvm-macosx-x86_64/bin/not"\nlet swiftIdeTestPath = "\(buildDir)/swift-macosx-x86_64/bin/swift-ide-test"\nlet creducePath = "/usr/local/bin/creduce"\n\nlet file = arguments[1]\n\nlet contents = try! String(contentsOfFile: file)\n\nvar offsets = Array(0...contents.count)\noffsets.shuffle()\n\nvar good = 0\nvar bad = 0\n\nfor offset in offsets {\n print("TOTAL FAILURES: \(bad) out of \(bad + good)")\n\n let index = contents.index(contents.startIndex, offsetBy: offset)\n let prefix = contents[..<index]\n let suffix = contents[index...]\n let newContents = String(prefix + "#^A^#" + suffix)\n\n let sourcePath = "out\(offset).swift"\n try! newContents.write(to: sourcePath)\n\n let shellScriptPath = "out\(offset).sh"\n let shellScript = """\n #!/bin/sh\n \(notPath) --crash \(swiftIdeTestPath) -code-completion -code-completion-token=A -source-filename=\(sourcePath)\n """\n try! shellScript.write(to: shellScriptPath)\n\n defer {\n unlink(shellScriptPath)\n unlink(sourcePath)\n }\n\n do {\n let result = chmod(shellScriptPath, 0o700)\n if result != 0 {\n print("chmod failed")\n exit(1)\n }\n }\n\n do {\n let result = try! run(["./\(shellScriptPath)"])\n if result != 0 {\n good += 1\n continue\n }\n }\n\n do {\n // Because we invert the exit code with 'not', an exit code for 0 actually\n // indicates failure\n print("Failed at offset \(offset)")\n print("Reducing...")\n\n let result = try! run([creducePath, shellScriptPath, sourcePath])\n if result != 0 {\n print("creduce failed")\n exit(1)\n }\n\n bad += 1\n }\n\n do {\n let reduction = try! String(contentsOfFile: sourcePath)\n\n let testcasePath = "crash-\(bad).swift"\n let testcase = """\n // RUN: \(notPath) --crash \(swiftIdeTestPath) -code-completion -code-completion-token=A -source-filename=%s\n // REQUIRES: asserts\n\n \(reduction)\n """\n\n try! testcase.write(to: testcasePath)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_sourcekit_fuzzer_sourcekit_fuzzer.swift
cpp_apple_swift_utils_sourcekit_fuzzer_sourcekit_fuzzer.swift
Swift
5,619
0.95
0.117949
0.341615
node-utils
455
2023-11-01T09:19:27.913605
BSD-3-Clause
false
7afd2753ab26a3aa8dd8a280d2ef03a3
// swift-tools-version: 5.8\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\nimport class Foundation.ProcessInfo\n\nlet package = Package(\n name: "swift-xcodegen",\n platforms: [.macOS(.v13)],\n targets: [\n .target(name: "Xcodeproj", exclude: ["README.md"]),\n .target(\n name: "SwiftXcodeGen",\n dependencies: [\n .product(name: "ArgumentParser", package: "swift-argument-parser"),\n .product(name: "SwiftOptions", package: "swift-driver"),\n "Xcodeproj"\n ],\n swiftSettings: [\n .enableExperimentalFeature("StrictConcurrency")\n ]\n ),\n .executableTarget(\n name: "swift-xcodegen",\n dependencies: [\n .product(name: "ArgumentParser", package: "swift-argument-parser"),\n "SwiftXcodeGen"\n ],\n swiftSettings: [\n .enableExperimentalFeature("StrictConcurrency")\n ]\n ),\n .testTarget(\n name: "SwiftXcodeGenTest",\n dependencies: ["SwiftXcodeGen"]\n )\n ]\n)\n\nif ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {\n package.dependencies += [\n .package(url: "https://github.com/apple/swift-argument-parser", from: "1.4.0"),\n .package(url: "https://github.com/swiftlang/swift-driver", branch: "main"),\n ]\n} else {\n package.dependencies += [\n .package(path: "../../../swift-argument-parser"),\n .package(path: "../../../swift-driver"),\n ]\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Package.swift
cpp_apple_swift_utils_swift-xcodegen_Package.swift
Swift
1,585
0.95
0.04
0.042553
python-kit
764
2024-07-14T04:45:37.213090
MIT
false
6a0bf1a3998fb87e8bbd5ede97e21f0b
//===--- Options.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport SwiftXcodeGen\n\nenum LogLevelOption: String, CaseIterable {\n case debug, info, note, warning, error\n}\nextension LogLevelOption: ExpressibleByArgument {\n init?(argument: String) {\n self.init(rawValue: argument)\n }\n}\nextension Logger.LogLevel {\n init(_ option: LogLevelOption) {\n self = switch option {\n case .debug: .debug\n case .info: .info\n case .note: .note\n case .warning: .warning\n case .error: .error\n }\n }\n}\n\nextension ArgumentHelp {\n static func hidden(_ abstract: String) -> Self {\n .init(abstract, visibility: .hidden)\n }\n}\n\nstruct LLVMProjectOptions: ParsableArguments {\n @Flag(\n name: .customLong("clang"), inversion: .prefixedNo,\n help: "Generate an xcodeproj for Clang"\n )\n var addClang: Bool = false\n\n @Flag(\n name: .customLong("clang-tools-extra"), inversion: .prefixedNo,\n help: """\n When generating a project for Clang, whether to include clang-tools-extra\n """\n )\n var addClangToolsExtra: Bool = true\n\n // FIXME: Semantic functionality is currently not supported, unhide when\n // fixed.\n @Flag(\n name: .customLong("compiler-rt"), inversion: .prefixedNo,\n help: .hidden("""\n When generating a project for LLVM, whether to include compiler-rt.\n """)\n )\n var addCompilerRT: Bool = false\n\n @Flag(\n name: .customLong("lldb"), inversion: .prefixedNo,\n help: "Generate an xcodeproj for LLDB"\n )\n var addLLDB: Bool = false\n\n @Flag(\n name: .customLong("llvm"), inversion: .prefixedNo,\n help: "Generate an xcodeproj for LLVM"\n )\n var addLLVM: Bool = false\n}\n\nstruct SwiftTargetOptions: ParsableArguments {\n @Flag(\n name: .customLong("swift-targets"), inversion: .prefixedNo,\n help: """\n Generate targets for Swift files, e.g ASTGen, SwiftCompilerSources. Note\n this by default excludes the standard library, see '--stdlib-swift'.\n """\n )\n var addSwiftTargets: Bool = true\n\n @Flag(\n name: .customLong("swift-dependencies"), inversion: .prefixedNo,\n help: """\n When generating Swift targets, add dependencies (e.g swift-syntax) to the\n generated project. This makes build times slower, but improves syntax\n highlighting for targets that depend on them.\n """\n )\n var addSwiftDependencies: Bool = true\n}\n\nstruct RunnableTargetOptions: ParsableArguments {\n @Option(\n name: .customLong("runnable-build-dir"),\n help: """\n If specified, runnable targets will use this build directory. Useful for\n configurations where a separate debug build directory is used.\n """\n )\n var runnableBuildDir: AnyPath?\n\n @Flag(\n name: .customLong("runnable-targets"), inversion: .prefixedNo,\n help: """\n Whether to add runnable targets for e.g swift-frontend. This is useful\n for debugging in Xcode.\n """\n )\n var addRunnableTargets: Bool = true\n\n @Flag(\n name: .customLong("build-runnable-targets"), inversion: .prefixedNo,\n help: """\n If runnable targets are enabled, whether to add a build action for them.\n If false, they will be added as freestanding schemes.\n """\n )\n var addBuildForRunnableTargets: Bool = true\n}\n\nstruct ProjectOptions: ParsableArguments {\n // Hidden as mostly only useful for testing purposes.\n @Flag(\n name: .customLong("clang-targets"), inversion: .prefixedNo,\n help: .hidden\n )\n var addClangTargets: Bool = true\n\n @Flag(\n name: .customLong("compiler-libs"), inversion: .prefixedNo,\n help: "Generate targets for compiler libraries"\n )\n var addCompilerLibs: Bool = true\n\n @Flag(\n name: .customLong("compiler-tools"), inversion: .prefixedNo,\n help: "Generate targets for compiler tools"\n )\n var addCompilerTools: Bool = true\n\n @Flag(\n name: .customLong("docs"), inversion: .prefixedNo,\n help: "Add doc groups to the generated projects"\n )\n var addDocs: Bool = true\n\n @Flag(\n name: [.customLong("stdlib"), .customLong("stdlib-cxx")],\n inversion: .prefixedNo,\n help: "Generate a target for C/C++ files in the standard library"\n )\n var addStdlibCxx: Bool = true\n\n @Flag(\n name: .customLong("stdlib-swift"), inversion: .prefixedNo,\n help: """\n Generate targets for Swift files in the standard library. This requires\n using Xcode with a main development Swift snapshot, and as such is\n disabled by default. \n \n A development snapshot is necessary to avoid spurious build/live issues\n due to the fact that the stdlib is built using the just-built Swift\n compiler, which may support features not yet supported by the Swift\n compiler in Xcode's toolchain.\n """\n )\n var addStdlibSwift: Bool = false\n\n @Flag(\n name: .customLong("test-folders"), inversion: .prefixedNo,\n help: "Add folder references for test files"\n )\n var addTestFolders: Bool = true\n\n @Flag(\n name: .customLong("unittests"), inversion: .prefixedNo,\n help: "Generate a target for the unittests"\n )\n var addUnitTests: Bool = true\n\n @Flag(\n name: .customLong("infer-args"), inversion: .prefixedNo,\n help: """\n Whether to infer build arguments for files that don't have any, based\n on the build arguments of surrounding files. This is mainly useful for\n files that aren't built in the default config, but are still useful to\n edit (e.g sourcekitdAPI-InProc.cpp).\n """\n )\n var inferArgs: Bool = true\n\n @Flag(\n name: .customLong("prefer-folder-refs"), inversion: .prefixedNo,\n help: """\n Whether to prefer folder references for groups containing non-source\n files\n """\n )\n var preferFolderRefs: Bool = true\n\n @Flag(\n name: .customLong("buildable-folders"), inversion: .prefixedNo,\n help: """\n Requires Xcode 16: Enables the use of "buildable folders", allowing\n folder references to be used for compatible targets. This allows new\n source files to be added to a target without needing to regenerate the\n project.\n \n Only supported for targets that have no per-file build settings. This\n unfortunately means some Clang targes such as 'lib/Basic' and 'stdlib' \n cannot currently use buildable folders.\n """\n )\n var useBuildableFolders: Bool = true\n\n @Option(\n name: .customLong("runtimes-build-dir"),\n help: """\n Experimental: The path to a build directory for the new 'Runtimes/'\n stdlib CMake build. This creates a separate 'SwiftRuntimes' project, along\n with a 'Swift+Runtimes' workspace.\n \n Note: This requires passing '-DCMAKE_EXPORT_COMPILE_COMMANDS=YES' to\n CMake.\n """\n )\n var runtimesBuildDir: AnyPath?\n\n @Option(help: .hidden)\n var blueFolders: String = ""\n}\n\nstruct MiscOptions: ParsableArguments {\n @Option(help: """\n The project root directory, which is the parent directory of the Swift repo.\n By default this is inferred from the build directory path.\n """)\n var projectRootDir: AnyPath?\n\n @Option(help: """\n The output directory to write the Xcode project to. Defaults to the project\n root directory.\n """)\n var outputDir: AnyPath?\n\n @Option(help: "The log level verbosity (default: info)")\n var logLevel: LogLevelOption?\n\n @Flag(\n name: .long, inversion: .prefixedNo,\n help: "Parallelize generation of projects"\n )\n var parallel: Bool = true\n\n @Flag(\n name: .shortAndLong,\n help: "Quiet output; equivalent to --log-level warning"\n )\n var quiet: Bool = false\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_swift-xcodegen_Options.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_swift-xcodegen_Options.swift
Swift
7,917
0.95
0.100372
0.059574
python-kit
953
2025-05-25T03:24:12.355680
Apache-2.0
false
4fe38a4d3d41e78b1ad03041f216b986
//===--- SwiftXcodegen.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Foundation\nimport SwiftXcodeGen\n\n@main\n@dynamicMemberLookup\nstruct SwiftXcodegen: AsyncParsableCommand, Sendable {\n // MARK: Options\n\n @OptionGroup(title: "LLVM Projects")\n var llvmProjectOpts: LLVMProjectOptions\n\n subscript<T>(dynamicMember kp: KeyPath<LLVMProjectOptions, T>) -> T {\n llvmProjectOpts[keyPath: kp]\n }\n\n @OptionGroup(title: "Swift targets")\n var swiftTargetOpts: SwiftTargetOptions\n\n subscript<T>(dynamicMember kp: KeyPath<SwiftTargetOptions, T>) -> T {\n swiftTargetOpts[keyPath: kp]\n }\n\n @OptionGroup(title: "Runnable targets")\n var runnableTargetOptions: RunnableTargetOptions\n\n subscript<T>(dynamicMember kp: KeyPath<RunnableTargetOptions, T>) -> T {\n runnableTargetOptions[keyPath: kp]\n }\n\n @OptionGroup(title: "Project configuration")\n var projectOpts: ProjectOptions\n\n subscript<T>(dynamicMember kp: KeyPath<ProjectOptions, T>) -> T {\n projectOpts[keyPath: kp]\n }\n\n @OptionGroup(title: "Misc")\n var miscOptions: MiscOptions\n\n subscript<T>(dynamicMember kp: KeyPath<MiscOptions, T>) -> T {\n miscOptions[keyPath: kp]\n }\n\n @Argument(help: "The path to the Ninja build directory to generate for")\n var buildDir: AnyPath\n\n // MARK: Command\n\n private func newProjectSpec(\n _ name: String, for buildDir: RepoBuildDir,\n runnableBuildDir: RepoBuildDir? = nil,\n mainRepoDir: RelativePath? = nil\n ) -> ProjectSpec {\n ProjectSpec(\n name, for: buildDir, runnableBuildDir: runnableBuildDir ?? buildDir,\n addClangTargets: self.addClangTargets,\n addSwiftTargets: self.addSwiftTargets,\n addSwiftDependencies: self.addSwiftDependencies,\n addRunnableTargets: false,\n addBuildForRunnableTargets: self.addBuildForRunnableTargets,\n inferArgs: self.inferArgs, preferFolderRefs: self.preferFolderRefs,\n useBuildableFolders: self.useBuildableFolders, mainRepoDir: mainRepoDir\n )\n }\n\n @discardableResult\n func writeSwiftXcodeProject(\n for ninja: NinjaBuildDir, into outputDir: AbsolutePath\n ) throws -> GeneratedProject {\n let buildDir = try ninja.buildDir(for: .swift)\n\n // Check to see if we have a separate runnable build dir.\n let runnableBuildDirPath = \n self.runnableBuildDir?.absoluteInWorkingDir.resolvingSymlinks\n let runnableBuildDir = try runnableBuildDirPath.map {\n try NinjaBuildDir(at: $0, projectRootDir: ninja.projectRootDir)\n .buildDir(for: .swift)\n }\n\n var spec = newProjectSpec(\n "Swift", for: buildDir, runnableBuildDir: runnableBuildDir\n )\n if self.addDocs {\n spec.addTopLevelDocs()\n spec.addDocsGroup(at: "docs")\n spec.addDocsGroup(at: "userdocs")\n }\n\n spec.addHeaders(in: "include")\n\n if self.addCompilerLibs {\n spec.addClangTargets(below: "lib", addingPrefix: "swift")\n\n spec.addClangTarget(at: "SwiftCompilerSources")\n spec.addSwiftTargets(below: "lib")\n spec.addSwiftTargets(below: "SwiftCompilerSources")\n }\n\n if self.addCompilerTools {\n spec.addClangTargets(below: "tools")\n spec.addSwiftTargets(below: "tools")\n }\n\n if self.addStdlibCxx || self.addStdlibSwift {\n // These are headers copied from LLVM, avoid including them in the project\n // to avoid confusion.\n spec.addExcludedPath("stdlib/include/llvm")\n }\n if self.addStdlibCxx {\n // This doesn't build with Clang 15, it does build with ToT Clang though.\n spec.addUnbuildableFile(\n "stdlib/tools/swift-reflection-test/swift-reflection-test.c"\n )\n\n // Add a single target for all the C/C++ files in the stdlib. We may have\n // unbuildable files, which will be added to the Unbuildables target.\n spec.addClangTarget(at: "stdlib", mayHaveUnbuildableFiles: true)\n }\n if self.addStdlibSwift {\n // Add any Swift targets in the stdlib.\n spec.addSwiftTargets(below: "stdlib")\n }\n\n if self.addUnitTests {\n // Create a single 'unittests' target.\n spec.addClangTarget(at: "unittests")\n }\n if self.addTestFolders {\n spec.addReference(to: "test")\n spec.addReference(to: "validation-test")\n }\n\n for blueFolder in self.blueFolders.components(separatedBy: ",") \n where !blueFolder.isEmpty {\n spec.addReference(to: RelativePath(blueFolder))\n }\n\n // Only enable runnable targets for Swift for now.\n if self.addRunnableTargets {\n spec.addRunnableTargets = true\n\n // If we don't have debug info, warn.\n if let config = try spec.runnableBuildDir.buildConfiguration,\n !config.hasDebugInfo {\n log.warning("""\n Specified build directory '\(spec.runnableBuildDir.path)' does not \\n have debug info; runnable targets will not be debuggable with LLDB. \\n Either build with debug info enabled, or specify a separate debug \\n build directory with '--runnable-build-dir'. Runnable targets may be \\n disabled by passing '--no-runnable-targets'.\n """)\n }\n }\n return try spec.generateAndWrite(into: outputDir)\n }\n\n func writeSwiftRuntimesXcodeProject(\n for ninja: NinjaBuildDir, into outputDir: AbsolutePath\n ) throws -> GeneratedProject {\n let buildDir = try ninja.buildDir(for: .swiftRuntimes)\n var spec = newProjectSpec("SwiftRuntimes", for: buildDir)\n\n spec.addClangTarget(at: "core", mayHaveUnbuildableFiles: true)\n spec.addSwiftTargets(below: "core")\n\n if self.addDocs {\n spec.addTopLevelDocs()\n }\n return try spec.generateAndWrite(into: outputDir)\n }\n\n @discardableResult\n func writeClangXcodeProject(\n for ninja: NinjaBuildDir, into outputDir: AbsolutePath\n ) throws -> GeneratedProject {\n var spec = newProjectSpec(\n "Clang", for: try ninja.buildDir(for: .llvm), mainRepoDir: "clang"\n )\n if self.addDocs {\n spec.addTopLevelDocs()\n spec.addDocsGroup(at: "docs")\n }\n spec.addHeaders(in: "include")\n\n if self.addCompilerLibs {\n spec.addClangTargets(below: "lib", addingPrefix: "clang")\n }\n if self.addCompilerTools {\n spec.addClangTargets(below: "tools")\n\n if self.addClangToolsExtra {\n spec.addClangTargets(\n below: "../clang-tools-extra", addingPrefix: "extra-",\n mayHaveUnbuildableFiles: true\n )\n if self.addTestFolders {\n spec.addReference(to: "../clang-tools-extra/test")\n } else {\n // Avoid adding any headers present in the test folder.\n spec.addExcludedPath("../clang-tools-extra/test")\n }\n }\n }\n if self.addUnitTests {\n spec.addClangTarget(at: "unittests")\n }\n if self.addTestFolders {\n spec.addReference(to: "test")\n }\n return try spec.generateAndWrite(into: outputDir)\n }\n\n @discardableResult\n func writeLLDBXcodeProject(\n for ninja: NinjaBuildDir, into outputDir: AbsolutePath\n ) throws -> GeneratedProject {\n var spec = newProjectSpec("LLDB", for: try ninja.buildDir(for: .lldb))\n if self.addDocs {\n spec.addTopLevelDocs()\n spec.addDocsGroup(at: "docs")\n }\n spec.addHeaders(in: "include")\n\n if self.addCompilerLibs {\n spec.addClangTargets(below: "source", addingPrefix: "lldb")\n }\n if self.addCompilerTools {\n spec.addClangTargets(below: "tools")\n }\n if self.addUnitTests {\n spec.addClangTarget(at: "unittests")\n }\n if self.addTestFolders {\n spec.addReference(to: "test")\n }\n return try spec.generateAndWrite(into: outputDir)\n }\n\n @discardableResult\n func writeLLVMXcodeProject(\n for ninja: NinjaBuildDir, into outputDir: AbsolutePath\n ) throws -> GeneratedProject {\n var spec = newProjectSpec(\n "LLVM", for: try ninja.buildDir(for: .llvm), mainRepoDir: "llvm"\n )\n if self.addDocs {\n spec.addTopLevelDocs()\n spec.addDocsGroup(at: "docs")\n }\n spec.addHeaders(in: "include")\n\n if self.addCompilerLibs {\n spec.addClangTargets(below: "lib", addingPrefix: "llvm")\n }\n if self.addCompilerTools {\n spec.addClangTargets(below: "tools")\n }\n if self.addTestFolders {\n spec.addReference(to: "test")\n }\n // FIXME: Looks like compiler-rt has its own build directory\n // llvm-macosx-arm64/tools/clang/runtime/compiler-rt-bins/build.ninja\n if self.addCompilerRT {\n spec.addClangTargets(\n below: "../compiler-rt", addingPrefix: "extra-"\n )\n if self.addTestFolders {\n spec.addReference(to: "../compiler-rt/test")\n } else {\n // Avoid adding any headers present in the test folder.\n spec.addExcludedPath("../compiler-rt/test")\n }\n }\n return try spec.generateAndWrite(into: outputDir)\n }\n\n func getWorkspace(for proj: GeneratedProject) throws -> WorkspaceGenerator {\n var generator = WorkspaceGenerator()\n generator.addProject(proj)\n return generator\n }\n\n func runTask<R>(\n _ body: @escaping @Sendable () throws -> R\n ) async throws -> Task<R, Error> {\n let task = Task(operation: body)\n if !self.parallel {\n _ = try await task.value\n }\n return task\n }\n\n func showCaveatsIfNeeded() {\n guard log.logLevel <= .note else { return }\n\n var notes: [String] = []\n if projectOpts.useBuildableFolders {\n notes.append("""\n - Buildable folders are enabled by default, which requires Xcode 16. You\n can pass '--no-buildable-folders' to disable this. See the '--help'\n entry for more info.\n """)\n }\n\n if !projectOpts.addStdlibSwift {\n notes.append("""\n - Swift standard library targets are disabled by default since they require\n using a development snapshot of Swift with Xcode. You can pass '--stdlib-swift'\n to enable. See the '--help' entry for more info.\n """)\n }\n guard !notes.isEmpty else { return }\n log.note("Caveats:")\n for note in notes {\n for line in note.components(separatedBy: .newlines) {\n log.note(line)\n }\n }\n }\n\n func generate() async throws {\n let buildDirPath = buildDir.absoluteInWorkingDir.resolvingSymlinks\n log.info("Generating project for '\(buildDirPath)'...")\n\n let projectRootDir = self.projectRootDir?.absoluteInWorkingDir\n let buildDir = try NinjaBuildDir(at: buildDirPath, projectRootDir: projectRootDir)\n let outputDir = miscOptions.outputDir?.absoluteInWorkingDir ?? buildDir.projectRootDir\n\n let swiftProj = try await runTask {\n try writeSwiftXcodeProject(for: buildDir, into: outputDir)\n }\n let runtimesProj = try await runTask { () -> GeneratedProject? in\n guard let runtimesBuildDir = self.runtimesBuildDir?.absoluteInWorkingDir else {\n return nil\n }\n let buildDir = try NinjaBuildDir(\n at: runtimesBuildDir, projectRootDir: projectRootDir\n )\n return try writeSwiftRuntimesXcodeProject(for: buildDir, into: outputDir)\n }\n let llvmProj = try await runTask {\n self.addLLVM ? try writeLLVMXcodeProject(for: buildDir, into: outputDir) : nil\n }\n let clangProj = try await runTask {\n self.addClang ? try writeClangXcodeProject(for: buildDir, into: outputDir) : nil\n }\n let lldbProj = try await runTask {\n self.addLLDB ? try writeLLDBXcodeProject(for: buildDir, into: outputDir) : nil\n }\n\n var swiftWorkspace = try await getWorkspace(for: swiftProj.value)\n\n if let runtimesProj = try await runtimesProj.value {\n swiftWorkspace.addProject(runtimesProj)\n try swiftWorkspace.write("Swift+Runtimes", into: outputDir)\n }\n\n if let llvmProj = try await llvmProj.value {\n var swiftLLVMWorkspace = swiftWorkspace\n swiftLLVMWorkspace.addProject(llvmProj)\n try swiftLLVMWorkspace.write("Swift+LLVM", into: outputDir)\n }\n\n if let clangProj = try await clangProj.value,\n let llvmProj = try await llvmProj.value {\n var clangLLVMWorkspace = WorkspaceGenerator()\n clangLLVMWorkspace.addProject(clangProj)\n clangLLVMWorkspace.addProject(llvmProj)\n try clangLLVMWorkspace.write("Clang+LLVM", into: outputDir)\n\n var allWorkspace = swiftWorkspace\n allWorkspace.addProject(clangProj)\n allWorkspace.addProject(llvmProj)\n try allWorkspace.write("Swift+Clang+LLVM", into: outputDir)\n }\n\n if let lldbProj = try await lldbProj.value {\n var swiftLLDBWorkspace = swiftWorkspace\n swiftLLDBWorkspace.addProject(lldbProj)\n try swiftLLDBWorkspace.write("Swift+LLDB", into: outputDir)\n\n if let llvmProj = try await llvmProj.value {\n var lldbLLVMWorkspace = WorkspaceGenerator()\n lldbLLVMWorkspace.addProject(lldbProj)\n lldbLLVMWorkspace.addProject(llvmProj)\n try lldbLLVMWorkspace.write("LLDB+LLVM", into: outputDir)\n }\n }\n }\n\n func printingTimeTaken<T>(_ fn: () async throws -> T) async rethrows -> T {\n let start = Date()\n let result = try await fn()\n\n // Note we don't print the time taken when we fail.\n let delta = Date().timeIntervalSince(start)\n log.info("Successfully generated in \(Int((delta * 1000).rounded()))ms")\n\n return result\n }\n\n func run() async {\n // Set the log level\n log.logLevel = .init(self.logLevel ?? (self.quiet ? .warning : .info))\n do {\n try await printingTimeTaken {\n try await generate()\n }\n showCaveatsIfNeeded()\n } catch {\n log.error("\(error)")\n }\n if log.hadError {\n Darwin.exit(1)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_swift-xcodegen_SwiftXcodegen.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_swift-xcodegen_SwiftXcodegen.swift
Swift
13,847
0.95
0.276744
0.077748
vue-tools
873
2024-03-05T17:37:22.196421
BSD-3-Clause
false
398ecc72d5c6d5c43b13804e00121bdc
//===--- BuildArgs.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nstruct BuildArgs {\n let command: KnownCommand\n private var topLevelArgs: [Command.Argument] = []\n private var subOptArgs: [SubOptionArgs] = []\n\n init(for command: KnownCommand, args: [Command.Argument] = []) {\n self.command = command\n self += args\n }\n}\n\nextension BuildArgs {\n struct SubOptionArgs {\n var flag: Command.Flag\n var args: BuildArgs\n\n var command: KnownCommand {\n args.command\n }\n }\n}\n\nextension BuildArgs {\n typealias Element = Command.Argument\n\n /// Whether both the arguments and sub-option arguments are empty.\n var isEmpty: Bool {\n topLevelArgs.isEmpty && subOptArgs.isEmpty\n }\n\n /// Whether the argument have a given flag.\n func hasFlag(_ flag: Command.Flag) -> Bool {\n topLevelArgs.contains(where: { $0.flag == flag })\n }\n\n /// Retrieve the flag in a given list of flags.\n func lastFlag(in flags: [Command.Flag]) -> Command.Flag? {\n for arg in topLevelArgs.reversed() {\n guard let flag = arg.flag, flags.contains(flag) else { continue }\n return flag\n }\n return nil\n }\n\n /// Retrieve the flag in a given list of flags.\n func lastFlag(in flags: Command.Flag...) -> Command.Flag? {\n lastFlag(in: flags)\n }\n\n /// Retrieve the last value for a given flag, unescaped.\n func lastValue(for flag: Command.Flag) -> String? {\n topLevelArgs.last(where: { $0.flag == flag })?.value\n }\n\n /// Retrieve the last printed value for a given flag, escaping as needed.\n func lastPrintedValue(for flag: Command.Flag) -> String? {\n lastValue(for: flag)?.escaped\n }\n\n /// Retrieve the printed values for a given flag, escaping as needed.\n func printedValues(for flag: Command.Flag) -> [String] {\n topLevelArgs.compactMap { $0.option(for: flag)?.value.escaped }\n }\n\n var printedArgs: [String] {\n topLevelArgs.flatMap(\.printedArgs) + subOptArgs.flatMap { subArgs in\n let printedFlag = subArgs.flag.printed\n return subArgs.args.printedArgs.flatMap { [printedFlag, $0] }\n }\n }\n\n var printed: String {\n printedArgs.joined(separator: " ")\n }\n\n func hasSubOptions(for command: KnownCommand) -> Bool {\n subOptArgs.contains(where: { $0.command == command })\n }\n\n /// Retrieve a set of sub-options for a given command.\n func subOptions(for command: KnownCommand) -> BuildArgs {\n hasSubOptions(for: command) ? self[subOptions: command] : .init(for: command)\n }\n\n subscript(subOptions command: KnownCommand) -> BuildArgs {\n _read {\n let index = subOptArgs.firstIndex(where: { $0.command == command })!\n yield subOptArgs[index].args\n }\n _modify {\n let index = subOptArgs.firstIndex(where: { $0.command == command })!\n yield &subOptArgs[index].args\n }\n }\n\n /// Apply a transform to the set of arguments. Note this doesn't include any\n /// sub-options.\n func map(_ transform: (Element) throws -> Element) rethrows -> Self {\n var result = self\n result.topLevelArgs = try topLevelArgs.map(transform)\n return result\n }\n\n /// Apply a filter to the set of arguments. Note this doesn't include any\n /// sub-options.\n func filter(_ predicate: (Element) throws -> Bool) rethrows -> Self {\n var result = self\n result.topLevelArgs = try topLevelArgs.filter(predicate)\n return result\n }\n\n /// Remove a set of flags from the arguments.\n mutating func exclude(_ flags: [Command.Flag]) {\n topLevelArgs.removeAll { arg in\n guard let f = arg.flag else { return false }\n return flags.contains(f)\n }\n }\n\n /// Remove a set of flags from the arguments.\n mutating func exclude(_ flags: Command.Flag...) {\n exclude(flags)\n }\n\n /// Remove a set of flags from the arguments.\n func excluding(_ flags: [Command.Flag]) -> Self {\n var result = self\n result.exclude(flags)\n return result\n }\n\n /// Remove a set of flags from the arguments.\n func excluding(_ flags: Command.Flag...) -> Self {\n excluding(flags)\n }\n\n /// Take the last unescaped value for a given flag, removing all occurances\n /// of the flag from the arguments.\n mutating func takeLastValue(for flag: Command.Flag) -> String? {\n guard let value = lastValue(for: flag) else { return nil }\n exclude(flag)\n return value\n }\n\n /// Take the last printed value for a given flag, escaping as needed, and\n /// removing all occurances of the flag from the arguments\n mutating func takePrintedLastValue(for flag: Command.Flag) -> String? {\n guard let value = lastPrintedValue(for: flag) else { return nil }\n exclude(flag)\n return value\n }\n\n /// Take a set of printed values for a given flag, escaping as needed.\n mutating func takePrintedValues(for flag: Command.Flag) -> [String] {\n let result = topLevelArgs.compactMap { $0.option(for: flag)?.value.escaped }\n exclude(flag)\n return result\n }\n\n /// Take a flag, returning `true` if it was removed, `false` if it isn't\n /// present.\n mutating func takeFlag(_ flag: Command.Flag) -> Bool {\n guard hasFlag(flag) else { return false }\n exclude(flag)\n return true\n }\n\n /// Takes a set of flags, returning `true` if the flags were removed, `false`\n /// if they aren't present.\n mutating func takeFlags(_ flags: Command.Flag...) -> Bool {\n guard flags.contains(where: self.hasFlag) else { return false }\n exclude(flags)\n return true\n }\n\n /// Takes a set of related flags, returning the last one encountered, or `nil`\n /// if no flags in the group are present.\n mutating func takeFlagGroup(_ flags: Command.Flag...) -> Command.Flag? {\n guard let value = lastFlag(in: flags) else { return nil }\n exclude(flags)\n return value\n }\n\n private mutating func appendSubOptArg(\n _ value: String, for command: KnownCommand, flag: Command.Flag\n ) {\n let idx = subOptArgs.firstIndex(where: { $0.command == command }) ?? {\n subOptArgs.append(.init(flag: flag, args: .init(for: command)))\n return subOptArgs.endIndex - 1\n }()\n subOptArgs[idx].args.append(value.escaped)\n }\n\n mutating func append(_ element: Element) {\n if let flag = element.flag, let command = flag.subOptionCommand,\n let value = element.value {\n appendSubOptArg(value, for: command, flag: flag)\n } else if let last = topLevelArgs.last, case .flag(let flag) = last,\n case .value(let value) = element {\n // If the last element is a flag, and this is a value, we may need to\n // merge.\n topLevelArgs.removeLast()\n topLevelArgs += try! CommandParser.parseArguments(\n "\(flag) \(value.escaped)", for: command\n )\n } else {\n topLevelArgs.append(element)\n }\n }\n\n mutating func append<S: Sequence>(contentsOf seq: S) where S.Element == Element {\n for element in seq {\n append(element)\n }\n }\n\n static func += <S: Sequence> (lhs: inout Self, rhs: S) where S.Element == Element {\n lhs.append(contentsOf: rhs)\n }\n\n mutating func append(_ input: String) {\n self += try! CommandParser.parseArguments(input, for: command)\n }\n\n /// Apply a transform to the values of any options present. If\n /// `includeSubOptions` is `true`, the transform will also be applied to any\n /// sub-options present.\n mutating func transformValues(\n for flag: Command.Flag? = nil, includeSubOptions: Bool,\n _ fn: (String) throws -> String\n ) rethrows {\n topLevelArgs = try topLevelArgs.map { arg in\n guard flag == nil || arg.flag == flag else { return arg }\n return try arg.mapValue(fn)\n }\n if includeSubOptions {\n for idx in subOptArgs.indices {\n try subOptArgs[idx].args.transformValues(\n for: flag, includeSubOptions: true, fn\n )\n }\n }\n }\n\n struct PathSubstitution: Hashable {\n var oldPath: AbsolutePath\n var newPath: AnyPath\n }\n\n /// Apply a substitution to any paths present in the option values, returning\n /// the substitutions made. If `includeSubOptions` is `true`, the substitution\n /// will also be applied to any sub-options present.\n mutating func substitutePaths<Path: PathProtocol>(\n for flag: Command.Flag? = nil, includeSubOptions: Bool,\n _ fn: (AbsolutePath) throws -> Path?\n ) rethrows -> [BuildArgs.PathSubstitution] {\n var subs: [BuildArgs.PathSubstitution] = []\n try transformValues(for: flag,\n includeSubOptions: includeSubOptions) { value in\n guard case .absolute(let path) = AnyPath(value),\n let newPath = try fn(path) else { return value }\n let subst = PathSubstitution(oldPath: path, newPath: AnyPath(newPath))\n subs.append(subst)\n return subst.newPath.rawPath\n }\n return subs\n }\n}\n\nextension BuildArgs: CustomStringConvertible {\n var description: String { printed }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_BuildArgs.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_BuildArgs.swift
Swift
9,153
0.8
0.190141
0.186992
vue-tools
547
2023-10-12T16:27:48.818779
Apache-2.0
false
6e2772d5a40bde96395f006ff0db1e7f
//===--- ClangBuildArgsProvider.swift -------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct ClangBuildArgsProvider {\n private var args = CommandArgTree()\n private var outputs: [RelativePath: AbsolutePath] = [:]\n\n init(for buildDir: RepoBuildDir) throws {\n let buildDirPath = buildDir.path\n let repoPath = buildDir.repoPath\n\n // TODO: Should we get Clang build args from the build.ninja? We're already\n // parsing that to get the Swift targets, seems unfortunate to have 2\n // sources of truth.\n let fileName = buildDirPath.appending("compile_commands.json")\n guard fileName.exists else {\n throw XcodeGenError.pathNotFound(fileName)\n }\n log.debug("[*] Reading Clang build args from '\(fileName)'")\n let parsed = try JSONDecoder().decode(\n CompileCommands.self, from: try fileName.read()\n )\n // Gather the candidates for each file to get build arguments for. We may\n // have multiple outputs, in which case, pick the first one that exists.\n var commandsToAdd: [RelativePath:\n (output: AbsolutePath?, args: [Command.Argument])] = [:]\n for command in parsed {\n guard command.command.executable.knownCommand == .clang,\n let relFilePath = command.file.removingPrefix(repoPath)\n else {\n continue\n }\n let output = command.output.map { command.directory.appending($0) }\n if let existing = commandsToAdd[relFilePath],\n let existingOutput = existing.output,\n output == nil || existingOutput.exists || !output!.exists {\n continue\n }\n commandsToAdd[relFilePath] = (output, command.command.args)\n }\n for (path, (output, commandArgs)) in commandsToAdd {\n // Only include arguments that have known flags.\n args.insert(commandArgs.filter({ $0.flag != nil }), for: path)\n outputs[path] = output\n }\n }\n\n /// Retrieve the arguments at a given path, including those in the parent.\n func getArgs(for path: RelativePath) -> BuildArgs {\n // Sort the arguments to get a deterministic ordering.\n // FIXME: We ought to get the command from the arg tree.\n .init(for: .clang, args: args.getArgs(for: path).sorted())\n }\n\n /// Retrieve the arguments at a given path, excluding those already covered\n /// by a parent.\n func getUniqueArgs(\n for path: RelativePath, parent: RelativePath, infer: Bool = false\n ) -> BuildArgs {\n var fileArgs: Set<Command.Argument> = []\n if hasBuildArgs(for: path) {\n fileArgs = args.getUniqueArgs(for: path, parent: parent)\n } else if infer {\n // If we can infer arguments, walk up to the nearest parent with args.\n if let component = path.stackedComponents\n .reversed().dropFirst().first(where: hasBuildArgs) {\n fileArgs = args.getUniqueArgs(for: component, parent: parent)\n }\n }\n // Sort the arguments to get a deterministic ordering.\n // FIXME: We ought to get the command from the arg tree.\n return .init(for: .clang, args: fileArgs.sorted())\n }\n\n /// Whether the given path has any unique args not covered by `parent`.\n func hasUniqueArgs(for path: RelativePath, parent: RelativePath) -> Bool {\n args.hasUniqueArgs(for: path, parent: parent)\n }\n\n /// Whether the given file has build arguments.\n func hasBuildArgs(for path: RelativePath) -> Bool {\n !args.getArgs(for: path).isEmpty\n }\n\n func isObjectFilePresent(for path: RelativePath) -> Bool {\n outputs[path]?.exists == true\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_ClangBuildArgsProvider.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_ClangBuildArgsProvider.swift
Swift
3,909
0.95
0.272727
0.3
react-lib
619
2024-12-30T16:02:25.920700
BSD-3-Clause
false
a1262cdf6ca1dfc189301e1f7872709b
//===--- CommandArgTree.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A tree of compile command arguments, indexed by path such that those unique\n/// to a particular file can be queried, with common arguments associated\n/// with a common parent.\nstruct CommandArgTree {\n private var storage: [RelativePath: Set<Command.Argument>]\n\n init() {\n self.storage = [:]\n }\n\n mutating func insert(_ args: [Command.Argument], for path: RelativePath) {\n let args = Set(args)\n for component in path.stackedComponents {\n // If we haven't added any arguments, add them. If we're adding arguments\n // for the file itself, this is the only way we'll add arguments,\n // otherwise we can form an intersection with the other arguments.\n let inserted = storage.insertValue(args, for: component)\n guard !inserted && component != path else { continue }\n\n // We use subscript(_:default:) to mutate in-place without CoW.\n storage[component, default: []].formIntersection(args)\n }\n }\n\n /// Retrieve the arguments at a given path, including those in the parent.\n func getArgs(for path: RelativePath) -> Set<Command.Argument> {\n storage[path] ?? []\n }\n\n /// Retrieve the arguments at a given path, excluding those already covered\n /// by a given parent.\n func getUniqueArgs(\n for path: RelativePath, parent: RelativePath\n ) -> Set<Command.Argument> {\n getArgs(for: path).subtracting(getArgs(for: parent))\n }\n\n /// Whether the given path has any unique args not covered by `parent`.\n func hasUniqueArgs(for path: RelativePath, parent: RelativePath) -> Bool {\n let args = getArgs(for: path)\n guard !args.isEmpty else { return false }\n // Assuming `parent` is an ancestor of path, the arguments for parent is\n // guaranteed to be a subset of the arguments for `path`. As such, we\n // only have to compare sizes here.\n return args.count != getArgs(for: parent).count\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_CommandArgTree.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_CommandArgTree.swift
Swift
2,377
0.8
0.254237
0.480769
react-lib
568
2023-08-04T04:53:45.138599
GPL-3.0
false
5eeb346f61952f9638622bef9e1614c6
//===--- RunnableTargets.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A target that defines a runnable executable.\nstruct RunnableTarget: Hashable {\n var name: String\n var ninjaTargetName: String\n var path: AbsolutePath\n}\n\nstruct RunnableTargets {\n private var addedPaths: Set<RelativePath> = []\n private var targets: [RunnableTarget] = []\n\n init(from buildDir: RepoBuildDir) throws {\n for rule in try buildDir.ninjaFile.buildEdges {\n tryAddTarget(rule, buildDir: buildDir)\n }\n }\n}\n\nextension RunnableTargets: RandomAccessCollection {\n typealias Element = RunnableTarget\n typealias Index = Int\n\n var startIndex: Int { targets.startIndex }\n var endIndex: Int { targets.endIndex }\n\n func index(_ i: Int, offsetBy distance: Int) -> Int {\n targets.index(i, offsetBy: distance)\n }\n\n subscript(position: Int) -> RunnableTarget {\n targets[position]\n }\n}\n\nextension RunnableTargets {\n private func getRunnablePath(\n for outputs: [String]\n ) -> (String, RelativePath)? {\n // We're only interested in rules with the path 'bin/<executable>'.\n for output in outputs {\n guard case let .relative(r) = AnyPath(output),\n r.components.count == 2, r.components.first == "bin"\n else { return nil }\n return (output, r)\n }\n return nil\n }\n\n private mutating func tryAddTarget(\n _ rule: NinjaBuildFile.BuildEdge, buildDir: RepoBuildDir\n ) {\n guard let (name, path) = getRunnablePath(for: rule.outputs),\n addedPaths.insert(path).inserted else { return }\n\n let absPath = buildDir.path.appending(path)\n guard absPath.exists, absPath.isExecutable else { return }\n\n let target = RunnableTarget(\n name: path.fileName, ninjaTargetName: name, path: absPath\n )\n targets.append(target)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_RunnableTargets.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_RunnableTargets.swift
Swift
2,219
0.8
0.093333
0.203125
node-utils
774
2025-04-12T19:44:36.789261
BSD-3-Clause
false
d213d1bf7726d863698e3c3bf2e04866
//===--- SwiftTargets.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nstruct SwiftTargets {\n private var targets: [SwiftTarget] = []\n\n private var outputAliases: [String: [String]] = [:]\n private var dependenciesByTargetName: [String: Set<String>] = [:]\n private var targetsByName: [String: SwiftTarget] = [:]\n private var targetsByOutput: [String: SwiftTarget] = [:]\n private var addedFiles: Set<RelativePath> = []\n\n // Track some state for debugging\n private var debugLogUnknownFlags: Set<String> = []\n\n init(for buildDir: RepoBuildDir) throws {\n log.debug("[*] Reading Swift targets from build.ninja")\n for rule in try buildDir.ninjaFile.buildEdges {\n try tryAddTarget(for: rule, buildDir: buildDir)\n }\n targets.sort(by: { $0.name < $1.name })\n\n log.debug("-------- SWIFT TARGET DEPS --------")\n for target in targets {\n var deps: Set<SwiftTarget> = []\n for dep in dependenciesByTargetName[target.name] ?? [] {\n for output in allOutputs(for: dep) {\n guard let depTarget = targetsByOutput[output] else { continue }\n deps.insert(depTarget)\n }\n }\n target.dependencies = deps.sorted(by: \.name)\n log.debug("| '\(target.name)' has deps: \(target.dependencies)")\n }\n log.debug("-----------------------------------")\n if !debugLogUnknownFlags.isEmpty {\n log.debug("---------- UNKNOWN FLAGS ----------")\n for flag in debugLogUnknownFlags.sorted() {\n log.debug("| \(flag)")\n }\n log.debug("-----------------------------------")\n }\n }\n\n private func allOutputs(for output: String) -> Set<String> {\n // TODO: Should we attempt to do canonicalization instead?\n var stack: [String] = [output]\n var results: Set<String> = []\n while let last = stack.popLast() {\n guard results.insert(last).inserted else { continue }\n for alias in outputAliases[last] ?? [] {\n stack.append(alias)\n }\n }\n return results\n }\n\n private mutating func computeBuildArgs(\n for edge: NinjaBuildFile.BuildEdge,\n in ninja: NinjaBuildFile\n ) throws -> BuildArgs? {\n let commandLine = try ninja.commandLine(for: edge)\n let command = try CommandParser.parseKnownCommandOnly(commandLine)\n guard let command, command.executable.knownCommand == .swiftc else {\n return nil\n }\n\n var buildArgs = BuildArgs(for: .swiftc, args: command.args)\n\n // Only include known flags for now.\n buildArgs = buildArgs.filter { arg in\n if arg.flag != nil {\n return true\n }\n if log.logLevel <= .debug {\n // Note the unknown flags.\n guard let value = arg.value, value.hasPrefix("-") else { return false }\n debugLogUnknownFlags.insert(value)\n }\n return false\n }\n\n return buildArgs\n }\n\n /// Check to see if this is a forced-XXX-dep.swift file, which is only used\n /// to hack around CMake dependencies, and can be dropped.\n private func isForcedDepSwiftFile(_ path: AbsolutePath) -> Bool {\n path.fileName.scanningUTF8 { scanner in\n guard scanner.tryEat(utf8: "forced-") else {\n return false\n }\n while scanner.tryEat() {\n if scanner.tryEat(utf8: "-dep.swift"), !scanner.hasInput {\n return true\n }\n }\n return false\n }\n }\n\n func getSources(\n from edge: NinjaBuildFile.BuildEdge, buildDir: RepoBuildDir\n ) throws -> SwiftTarget.Sources {\n let files: [AnyPath] = edge.inputs.map(AnyPath.init)\n\n // Split the files into repo sources and external sources. Repo sources\n // are those under the repo path, external sources are outside that path,\n // and are either for dependencies such as swift-syntax, or are generated\n // from e.g de-gyb'ing.\n var sources = SwiftTarget.Sources()\n\n for input in files where input.language == .swift {\n switch input {\n case .relative(let r):\n // A relative path is for a file in the build directory, it's external.\n let abs = buildDir.path.appending(r)\n guard abs.exists else { continue }\n sources.externalSources.append(abs)\n\n case .absolute(let a):\n guard a.exists, let rel = a.removingPrefix(buildDir.repoPath) else {\n sources.externalSources.append(a)\n continue\n }\n sources.repoSources.append(rel)\n }\n }\n // Avoid adding forced dependency files.\n sources.externalSources = sources.externalSources\n .filter { !isForcedDepSwiftFile($0) }\n return sources\n }\n\n private mutating func tryAddTarget(\n for edge: NinjaBuildFile.BuildEdge,\n buildDir: RepoBuildDir\n ) throws {\n // Phonies are only used to track aliases.\n if edge.isPhony {\n for output in edge.outputs {\n outputAliases[output, default: []] += edge.inputs\n }\n return\n }\n\n // Ignore build rules that don't have object file or swiftmodule outputs.\n let forBuild = edge.outputs.contains(\n where: { $0.hasExtension(.o) }\n )\n let forModule = edge.outputs.contains(\n where: { $0.hasExtension(.swiftmodule) }\n )\n guard forBuild || forModule else {\n return\n }\n let primaryOutput = edge.outputs.first!\n let sources = try getSources(from: edge, buildDir: buildDir)\n let repoSources = sources.repoSources\n let externalSources = sources.externalSources\n\n // Is this for a build (producing a '.o'), we need to have at least one\n // repo source. Module dependencies can use external sources.\n guard !repoSources.isEmpty || (forModule && !externalSources.isEmpty) else {\n return\n }\n\n guard let buildArgs = try computeBuildArgs(for: edge, in: buildDir.ninjaFile) else { return }\n\n // Pick up the module name from the arguments, or use an explicitly\n // specified module name if we have one. The latter might be invalid so\n // may not be part of the build args (e.g 'swift-plugin-server'), but is\n // fine for generation.\n let moduleName = buildArgs.lastValue(for: .moduleName) ?? edge.bindings[.swiftModuleName]\n guard let moduleName else {\n log.debug("! Skipping Swift target with output \(primaryOutput); no module name")\n return\n }\n let moduleLinkName = buildArgs.lastValue(for: .moduleLinkName) ?? edge.bindings[.swiftLibraryName]\n let name = moduleLinkName ?? moduleName\n\n // Add the dependencies. We track dependencies for any input files, along\n // with any recorded swiftmodule dependencies.\n dependenciesByTargetName.withValue(for: name, default: []) { deps in\n deps.formUnion(\n edge.inputs.filter {\n $0.hasExtension(.swiftmodule) || $0.hasExtension(.o)\n }\n )\n deps.formUnion(\n edge.dependencies.filter { $0.hasExtension(.swiftmodule) }\n )\n }\n\n var buildRule: SwiftTarget.BuildRule?\n var emitModuleRule: SwiftTarget.EmitModuleRule?\n if forBuild && !repoSources.isEmpty {\n // Bail if we've already recorded a target with one of these inputs.\n // TODO: Attempt to merge?\n // TODO: Should we be doing this later?\n for input in repoSources {\n guard addedFiles.insert(input).inserted else {\n log.debug("""\n ! Skipping '\(name)' with output '\(primaryOutput)'; \\n contains input '\(input)' already added\n """)\n return\n }\n }\n // We've already ensured that `repoSources` is non-empty.\n let parent = repoSources.commonAncestor!\n buildRule = .init(\n parentPath: parent, sources: sources, buildArgs: buildArgs\n )\n }\n if forModule {\n emitModuleRule = .init(sources: sources, buildArgs: buildArgs)\n }\n let target = targetsByName[name] ?? {\n log.debug("+ Discovered Swift target '\(name)' with output '\(primaryOutput)'")\n let target = SwiftTarget(name: name, moduleName: moduleName)\n targetsByName[name] = target\n targets.append(target)\n return target\n }()\n for output in edge.outputs {\n targetsByOutput[output] = target\n }\n if buildRule == nil || target.buildRule == nil {\n if let buildRule {\n target.buildRule = buildRule\n }\n } else {\n log.debug("""\n ! Skipping '\(name)' build rule for \\n '\(primaryOutput)'; already added\n """)\n }\n if emitModuleRule == nil || target.emitModuleRule == nil {\n if let emitModuleRule {\n target.emitModuleRule = emitModuleRule\n }\n } else {\n log.debug("""\n ! Skipping '\(name)' emit module rule for \\n '\(primaryOutput)'; already added\n """)\n }\n }\n\n func getTargets(below path: RelativePath) -> [SwiftTarget] {\n targets.filter { target in\n guard let parent = target.buildRule?.parentPath, parent.starts(with: path) \n else {\n return false\n }\n return true\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_SwiftTargets.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_BuildArgs_SwiftTargets.swift
Swift
9,219
0.8
0.208178
0.150407
node-utils
137
2025-04-11T10:04:30.452597
MIT
false
838a6b79e2fafc30530454dc55c03846
//===--- Command.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nstruct Command: Hashable {\n var executable: AnyPath\n var args: [Argument]\n\n init(executable: AnyPath, args: [Argument]) {\n self.executable = executable\n self.args = args\n }\n}\n\nextension Command: Decodable {\n init(from decoder: Decoder) throws {\n let command = try decoder.singleValueContainer().decode(String.self)\n self = try CommandParser.parseCommand(command)\n }\n}\n\nextension Command {\n var printedArgs: [String] {\n [executable.rawPath.escaped] + args.flatMap(\.printedArgs)\n }\n\n var printed: String {\n printedArgs.joined(separator: " ")\n }\n}\n\n// MARK: Argument\n\nextension Command {\n enum Argument: Hashable {\n case option(Option)\n case flag(Flag)\n case value(String)\n }\n}\n\nextension Command.Argument {\n static func option(\n _ flag: Command.Flag, spacing: Command.OptionSpacing, value: String\n ) -> Self {\n .option(.init(flag, spacing: spacing, value: value))\n }\n\n var flag: Command.Flag? {\n switch self {\n case .option(let opt):\n opt.flag\n case .flag(let flag):\n flag\n case .value:\n nil\n }\n }\n\n var value: String? {\n switch self {\n case .option(let opt):\n opt.value\n case .value(let value):\n value\n case .flag:\n nil\n }\n }\n\n var printedArgs: [String] {\n switch self {\n case .option(let opt):\n opt.printedArgs\n case .value(let value):\n [value.escaped]\n case .flag(let f):\n [f.printed]\n }\n }\n\n var printed: String {\n printedArgs.joined(separator: " ")\n }\n\n func option(for flag: Command.Flag) -> Command.Option? {\n switch self {\n case .option(let opt) where opt.flag == flag:\n opt\n default:\n nil\n }\n }\n\n /// If there is a value, apply a transform to it.\n func mapValue(_ fn: (String) throws -> String) rethrows -> Self {\n switch self {\n case .option(let opt):\n .option(try opt.mapValue(fn))\n case .value(let value):\n .value(try fn(value))\n case .flag:\n // Nothing to map.\n self\n }\n }\n}\n\n// MARK: Flag\n\nextension Command {\n struct Flag: Hashable {\n var dash: Dash\n var name: Name\n }\n}\n\nextension Command.Flag {\n static func dash(_ name: Name) -> Self {\n .init(dash: .single, name: name)\n }\n static func doubleDash(_ name: Name) -> Self {\n .init(dash: .double, name: name)\n }\n\n var printed: String {\n "\(dash.printed)\(name.rawValue)"\n }\n}\n\nextension Command.Flag {\n enum Dash: Int, CaseIterable, Comparable {\n case single = 1, double\n static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue }\n }\n}\n\nextension Command.Flag.Dash {\n init?(numDashes: Int) {\n self.init(rawValue: numDashes)\n }\n\n var printed: String {\n switch self {\n case .single:\n return "-"\n case .double:\n return "--"\n }\n }\n}\n\nextension DefaultStringInterpolation {\n mutating func appendInterpolation(_ flag: Command.Flag) {\n appendInterpolation(flag.printed)\n }\n}\n\n// MARK: Option\n\nextension Command {\n struct Option: Hashable {\n var flag: Flag\n var spacing: OptionSpacing\n var value: String\n\n init(_ flag: Flag, spacing: OptionSpacing, value: String) {\n self.flag = flag\n self.spacing = spacing\n self.value = value\n }\n }\n}\n\nextension Command.Option {\n func withValue(_ newValue: String) -> Self {\n var result = self\n result.value = newValue\n return result\n }\n\n func mapValue(_ fn: (String) throws -> String) rethrows -> Self {\n withValue(try fn(value))\n }\n\n var printedArgs: [String] {\n switch spacing {\n case .equals, .unspaced:\n ["\(flag)\(spacing)\(value.escaped)"]\n case .spaced:\n ["\(flag)", value.escaped]\n }\n }\n\n var printed: String {\n printedArgs.joined(separator: " ")\n }\n}\n\n// MARK: OptionSpacing\n\nextension Command {\n enum OptionSpacing: Comparable {\n case equals, unspaced, spaced\n }\n}\n\nextension Command.OptionSpacing {\n var printed: String {\n switch self {\n case .equals: "="\n case .unspaced: ""\n case .spaced: " "\n }\n }\n}\n\n// MARK: CustomStringConvertible\n\nextension Command.Argument: CustomStringConvertible {\n var description: String { printed }\n}\n\nextension Command.OptionSpacing: CustomStringConvertible {\n var description: String { printed }\n}\n\nextension Command.Flag: CustomStringConvertible {\n var description: String { printed }\n}\n\nextension Command.Option: CustomStringConvertible {\n var description: String { printed }\n}\n\n// MARK: Comparable\n// We sort the resulting command-line arguments to ensure deterministic\n// ordering.\n\nextension Command.Flag: Comparable {\n static func < (lhs: Self, rhs: Self) -> Bool {\n guard lhs.dash == rhs.dash else {\n return lhs.dash < rhs.dash\n }\n return lhs.name.rawValue < rhs.name.rawValue\n }\n}\n\nextension Command.Option: Comparable {\n static func < (lhs: Self, rhs: Self) -> Bool {\n guard lhs.flag == rhs.flag else {\n return lhs.flag < rhs.flag\n }\n guard lhs.spacing == rhs.spacing else {\n return lhs.spacing < rhs.spacing\n }\n return lhs.value < rhs.value\n }\n}\n\nextension Command.Argument: Comparable {\n static func < (lhs: Self, rhs: Self) -> Bool {\n switch (lhs, rhs) {\n // Sort flags < options < values\n case (.flag, .option): true\n case (.flag, .value): true\n case (.option, .value): true\n\n case (.option, .flag): false\n case (.value, .flag): false\n case (.value, .option): false\n\n case (.flag(let lhs), .flag(let rhs)): lhs < rhs\n case (.option(let lhs), .option(let rhs)): lhs < rhs\n case (.value(let lhs), .value(let rhs)): lhs < rhs\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_Command.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_Command.swift
Swift
6,085
0.8
0.059441
0.090535
python-kit
29
2025-04-20T02:27:40.950813
Apache-2.0
false
1429007b4cac0b9f2f8500a33ab973aa
//===--- CommandParser.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nstruct CommandParser {\n private var input: ByteScanner\n private var knownCommand: KnownCommand?\n\n private init(_ input: UnsafeBufferPointer<UInt8>) {\n self.input = ByteScanner(input)\n }\n\n static func parseCommand(_ input: String) throws -> Command {\n var input = input\n return try input.withUTF8 { bytes in\n var parser = Self(bytes)\n return try parser.parseCommand()\n }\n }\n\n static func parseKnownCommandOnly(_ input: String) throws -> Command? {\n var input = input\n return try input.withUTF8 { bytes in\n var parser = Self(bytes)\n guard let executable = try parser.consumeExecutable(\n dropPrefixBeforeKnownCommand: true\n ) else {\n return nil\n }\n return Command(executable: executable, args: try parser.consumeArguments())\n }\n }\n\n static func parseArguments(\n _ input: String, for command: KnownCommand\n ) throws -> [Command.Argument] {\n var input = input\n return try input.withUTF8 { bytes in\n var parser = Self(bytes)\n parser.knownCommand = command\n return try parser.consumeArguments()\n }\n }\n\n private mutating func parseCommand() throws -> Command {\n guard let executable = try consumeExecutable() else {\n throw CommandParserError.expectedCommand\n }\n return Command(executable: executable, args: try consumeArguments())\n }\n\n private mutating func consumeExecutable(\n dropPrefixBeforeKnownCommand: Bool = false\n ) throws -> AnyPath? {\n var executable: AnyPath\n repeat {\n guard let executableUTF8 = try input.consumeElement() else {\n return nil\n }\n executable = AnyPath(String(utf8: executableUTF8))\n self.knownCommand = executable.knownCommand\n\n // If we want to drop the prefix before a known command, keep dropping\n // elements until we find the known command.\n } while dropPrefixBeforeKnownCommand && knownCommand == nil\n return executable\n }\n\n private mutating func consumeArguments() throws -> [Command.Argument] {\n var args = [Command.Argument]()\n while let arg = try consumeArgument() {\n args.append(arg)\n }\n return args\n }\n}\n\nenum CommandParserError: Error, CustomStringConvertible {\n case expectedCommand\n case unterminatedStringLiteral\n\n var description: String {\n switch self {\n case .expectedCommand:\n return "expected command in command line"\n case .unterminatedStringLiteral:\n return "unterminated string literal in command line"\n }\n }\n}\n\nfileprivate extension ByteScanner.Consumer {\n /// Consumes a character, unescaping if needed.\n mutating func consumeUnescaped() -> Bool {\n if peek == "\\" {\n skip()\n }\n return eat()\n }\n\n mutating func consumeStringLiteral() throws {\n assert(peek == "\"")\n skip()\n repeat {\n if peek == "\"" {\n skip()\n return\n }\n } while consumeUnescaped()\n throw CommandParserError.unterminatedStringLiteral\n }\n}\n\nfileprivate extension ByteScanner {\n mutating func consumeElement() throws -> Bytes? {\n // Eat any leading whitespace.\n skip(while: \.isSpaceOrTab)\n\n // If we're now at the end of the input, nothing can be parsed.\n guard hasInput else { return nil }\n\n // Consume the element, stopping at the first space.\n return try consume(using: { consumer in\n switch consumer.peek {\n case \.isSpaceOrTab:\n return false\n case "\"":\n try consumer.consumeStringLiteral()\n return true\n default:\n return consumer.consumeUnescaped()\n }\n })\n }\n}\n\nextension CommandParser {\n mutating func tryConsumeOption(\n _ option: ByteScanner, for flagSpec: Command.FlagSpec.Element\n ) throws -> Command.Argument? {\n var option = option\n let flag = flagSpec.flag\n guard option.tryEat(utf8: flag.name.rawValue) else {\n return nil\n }\n func makeOption(\n spacing: Command.OptionSpacing, _ value: String\n ) -> Command.Argument {\n .option(flag, spacing: spacing, value: value)\n }\n let spacing = flagSpec.spacing\n do {\n var option = option\n if spacing.contains(.equals), option.tryEat("="), option.hasInput {\n return makeOption(spacing: .equals, String(utf8: option.remaining))\n }\n }\n if spacing.contains(.unspaced), option.hasInput {\n return makeOption(spacing: .unspaced, String(utf8: option.remaining))\n }\n if spacing.contains(.spaced), !option.hasInput,\n let value = try input.consumeElement() {\n return makeOption(spacing: .spaced, String(utf8: value))\n }\n return option.empty ? .flag(flag) : nil\n }\n\n mutating func consumeOption(\n _ option: ByteScanner, dash: Command.Flag.Dash\n ) throws -> Command.Argument? {\n // NOTE: If we ever expand the list of flags, we'll likely want to use a\n // trie or something here.\n guard let knownCommand else { return nil }\n for spec in knownCommand.flagSpec.flags where spec.flag.dash == dash {\n if let option = try tryConsumeOption(option, for: spec) {\n return option\n }\n }\n return nil\n }\n\n mutating func consumeArgument() throws -> Command.Argument? {\n guard let element = try input.consumeElement() else { return nil }\n return try element.withUnsafeBytes { bytes in\n var option = ByteScanner(bytes)\n var numDashes = 0\n if option.tryEat("-") { numDashes += 1 }\n if option.tryEat("-") { numDashes += 1 }\n guard let dash = Command.Flag.Dash(numDashes: numDashes),\n let result = try consumeOption(option, dash: dash) else {\n return .value(String(utf8: option.whole))\n }\n return result\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_CommandParser.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_CommandParser.swift
Swift
6,123
0.8
0.191176
0.102703
awesome-app
405
2023-12-23T03:36:14.275873
MIT
false
508a934c85c5d932ae157bd41af3296f
//===--- CompileCommands.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A Decodable representation of compile_commands.json.\nstruct CompileCommands: Decodable {\n public var commands: [Element]\n\n init(_ commands: [Element]) {\n self.commands = commands\n }\n\n public init(from decoder: Decoder) throws {\n self.init(try decoder.singleValueContainer().decode([Element].self))\n }\n}\n\nextension CompileCommands {\n struct Element: Decodable {\n var directory: AbsolutePath\n var file: AbsolutePath\n var output: RelativePath?\n var command: Command\n }\n}\n\nextension CompileCommands: RandomAccessCollection {\n typealias Index = Int\n\n var startIndex: Index { commands.startIndex }\n var endIndex: Index { commands.endIndex }\n\n func index(_ i: Int, offsetBy distance: Int) -> Int {\n commands.index(i, offsetBy: distance)\n }\n subscript(position: Index) -> Element {\n commands[position]\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_CompileCommands.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_CompileCommands.swift
Swift
1,354
0.8
0.06383
0.3
react-lib
240
2023-11-07T16:44:39.083882
Apache-2.0
false
b7d1fbdd1ba8158fa4863e57ceaef7c5
//===--- CompileLanguage.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nenum CompileLanguage: Hashable {\n case swift, cxx, c\n}\n\nextension PathProtocol {\n var language: CompileLanguage? {\n if hasExtension(.swift) {\n return .swift\n }\n if hasExtension(.cpp) {\n return .cxx\n }\n if hasExtension(.c) {\n return .c\n }\n return nil\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_CompileLanguage.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_CompileLanguage.swift
Swift
807
0.8
0.166667
0.392857
react-lib
779
2025-03-20T13:54:09.521747
BSD-3-Clause
false
83be0db2c61422a00a968d92999d7f83
//===--- FlagSpec.swift ---------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension Command {\n struct FlagSpec {\n let flags: [Element]\n\n init(_ flags: [Element]) {\n // Sort by shortest first, except in cases where one is a prefix of\n // another, in which case we need the longer one first to ensure we prefer\n // it when parsing.\n self.flags = flags.sorted(by: { lhs, rhs in\n let lhs = lhs.flag.name.rawValue\n let rhs = rhs.flag.name.rawValue\n guard lhs.count != rhs.count else {\n return false\n }\n if lhs.count < rhs.count {\n // RHS should be ordered first if it has LHS as a prefix.\n return !rhs.hasPrefix(lhs)\n } else {\n // LHS should be ordered first if it has RHS as a prefix.\n return lhs.hasPrefix(rhs)\n }\n })\n }\n }\n}\n\nextension Command {\n struct OptionSpacingSpec: OptionSet {\n var rawValue: Int\n init(rawValue: Int) {\n self.rawValue = rawValue\n }\n init(_ rawValue: Int) {\n self.rawValue = rawValue\n }\n init(_ optionSpacing: OptionSpacing) {\n switch optionSpacing {\n case .equals:\n self = .equals\n case .unspaced:\n self = .unspaced\n case .spaced:\n self = .spaced\n }\n }\n static let equals = Self(1 << 0)\n static let unspaced = Self(1 << 1)\n static let spaced = Self(1 << 2)\n }\n}\n\nextension Command.FlagSpec {\n typealias Flag = Command.Flag\n typealias OptionSpacingSpec = Command.OptionSpacingSpec\n\n struct Element {\n let flag: Flag\n let spacing: OptionSpacingSpec\n\n init(_ flag: Flag, option: [OptionSpacingSpec]) {\n self.flag = flag\n self.spacing = option.reduce([], { $0.union($1) })\n }\n\n init(_ flag: Flag, option: OptionSpacingSpec...) {\n self.init(flag, option: option)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_FlagSpec.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_FlagSpec.swift
Swift
2,286
0.8
0.074074
0.216216
react-lib
495
2024-01-30T03:36:50.760387
GPL-3.0
false
a21a89d308372fc09d6aec6d24c4f43e
//===--- KnownCommand.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@preconcurrency import SwiftOptions\n\nenum KnownCommand {\n case clang, swiftc, swiftFrontend\n}\n\nextension PathProtocol {\n var knownCommand: KnownCommand? {\n switch fileName {\n case "clang", "clang++", "c++", "cc", "clang-cache":\n .clang\n case "swiftc":\n .swiftc\n case "swift-frontend":\n .swiftFrontend\n default:\n nil\n }\n }\n}\n\nextension Command.Flag {\n /// If this spec is for a suboption, returns the command that it is for, or\n /// `nil` if it is not for a suboption\n var subOptionCommand: KnownCommand? {\n switch self {\n case .Xcc:\n .clang\n case .Xfrontend:\n .swiftFrontend\n default:\n nil\n }\n }\n}\n\nextension Command.Flag {\n struct Name: Hashable {\n let rawValue: String\n\n // Fileprivate because definitions should be added below.\n fileprivate init(_ rawValue: String) {\n self.rawValue = rawValue\n }\n }\n\n fileprivate static func dash(_ name: String) -> Self {\n dash(.init(name))\n }\n\n fileprivate static func doubleDash(_ name: String) -> Self {\n doubleDash(.init(name))\n }\n\n fileprivate static func swiftc(_ opt: SwiftOptions.Option) -> Self {\n let dashes = opt.spelling.prefix(while: { $0 == "-" }).count\n guard let dash = Command.Flag.Dash(numDashes: dashes) else {\n fatalError("Dash count not handled")\n }\n let name = String(opt.spelling.dropFirst(dashes))\n return .init(dash: dash, name: .init(name))\n }\n}\n\nextension SwiftOptions.Option {\n fileprivate static let optionsWithJoinedEquals: Set<String> = {\n // Make a note of all flags that are equal joined.\n var result = Set<String>()\n for opt in SwiftOptions.Option.allOptions {\n switch opt.kind {\n case .separate, .input, .flag, .remaining, .multiArg:\n continue\n case .joined, .joinedOrSeparate, .commaJoined:\n if opt.spelling.hasSuffix("=") {\n result.insert(String(opt.spelling.dropLast()))\n }\n }\n }\n return result\n }()\n\n fileprivate var spacingSpec: Command.FlagSpec.OptionSpacingSpec {\n var spacing = Command.OptionSpacingSpec()\n switch kind {\n case .input, .remaining:\n fatalError("Not handled")\n case .flag:\n break\n case .joined, .commaJoined:\n spacing.insert(.unspaced)\n case .separate, .multiArg:\n spacing.insert(.spaced)\n case .joinedOrSeparate:\n spacing.insert([.unspaced, .spaced])\n }\n if Self.optionsWithJoinedEquals.contains(spelling) {\n spacing.insert(.equals)\n }\n return spacing\n }\n}\n\nextension Command.FlagSpec {\n fileprivate init(_ options: [SwiftOptions.Option]) {\n self.init(options.map { .init(.swiftc($0), option: $0.spacingSpec) })\n }\n}\n\nextension Command.Flag {\n // Swift + Clang\n static let D = dash("D")\n static let I = dash("I")\n static let target = dash("target")\n\n // Clang\n static let isystem = dash("isystem")\n static let isysroot = dash("isysroot")\n static let f = dash("f")\n static let U = dash("U")\n static let W = dash("W")\n static let std = dash("std")\n\n // Swift\n static let cxxInteroperabilityMode = \n swiftc(.cxxInteroperabilityMode)\n static let enableExperimentalCxxInterop = \n swiftc(.enableExperimentalCxxInterop)\n static let enableExperimentalFeature =\n swiftc(.enableExperimentalFeature)\n static let enableLibraryEvolution =\n swiftc(.enableLibraryEvolution)\n static let experimentalSkipAllFunctionBodies =\n swiftc(.experimentalSkipAllFunctionBodies)\n static let experimentalSkipNonInlinableFunctionBodies =\n swiftc(.experimentalSkipNonInlinableFunctionBodies)\n static let experimentalSkipNonInlinableFunctionBodiesWithoutTypes = \n swiftc(.experimentalSkipNonInlinableFunctionBodiesWithoutTypes)\n static let F =\n swiftc(.F)\n static let Fsystem =\n swiftc(.Fsystem)\n static let moduleName =\n swiftc(.moduleName)\n static let moduleLinkName =\n swiftc(.moduleLinkName)\n static let nostdimport =\n swiftc(.nostdimport)\n static let O =\n swiftc(.O)\n static let Onone =\n swiftc(.Onone)\n static let packageName =\n swiftc(.packageName)\n static let parseAsLibrary =\n swiftc(.parseAsLibrary)\n static let parseStdlib =\n swiftc(.parseStdlib)\n static let runtimeCompatibilityVersion =\n swiftc(.runtimeCompatibilityVersion)\n static let sdk =\n swiftc(.sdk)\n static let swiftVersion =\n swiftc(.swiftVersion)\n static let wholeModuleOptimization =\n swiftc(.wholeModuleOptimization)\n static let wmo =\n swiftc(.wmo)\n static let Xcc =\n swiftc(.Xcc)\n static let Xfrontend =\n swiftc(.Xfrontend)\n static let Xllvm =\n swiftc(.Xllvm)\n}\n\nextension KnownCommand {\n private static let clangSpec = Command.FlagSpec([\n .init(.I, option: .equals, .unspaced, .spaced),\n .init(.D, option: .unspaced, .spaced),\n .init(.U, option: .unspaced, .spaced),\n .init(.W, option: .unspaced),\n\n // This isn't an actual Clang flag, but it allows us to scoop up all the\n // -f[...] flags.\n // FIXME: We ought to see if we can get away with preserving unknown flags.\n .init(.f, option: .unspaced),\n\n // FIXME: Really we ought to map to Xcode's SDK\n .init(.isystem, option: .unspaced, .spaced),\n .init(.isysroot, option: .unspaced, .spaced),\n\n .init(.std, option: .equals),\n .init(.target, option: .spaced),\n ])\n\n // FIXME: We currently only parse a small subset of the supported driver\n // options. This is because:\n //\n // - It avoids including incompatible options (e.g options only suitable when\n // emitting modules when we want to do a regular build).\n // - It avoids including options that produce unnecessary outputs (e.g\n // dependencies, object files), especially as they would be outputting into\n // the Ninja build, which needs to be left untouched (maybe we could filter\n // out options that have paths that point into the build dir?).\n // - It avoids including options that do unnecessary work (e.g emitting debug\n // info, code coverage).\n // - It's quicker.\n //\n // This isn't great though, and we probably ought to revisit this, especially\n // if the driver starts categorizing its options such that we can better\n // reason about which we want to use. It should also be noted that we\n // currently allow arbitrary options to be passed through -Xfrontend, we may\n // want to reconsider that.\n // NOTE: You can pass '--log-level debug' to see the options that are\n // currently being missed.\n private static let swiftOptions: [SwiftOptions.Option] = [\n .cxxInteroperabilityMode,\n .D,\n .disableAutolinkingRuntimeCompatibilityDynamicReplacements,\n .enableBuiltinModule,\n .enableExperimentalCxxInterop,\n .enableExperimentalFeature,\n .enableLibraryEvolution,\n .experimentalSkipAllFunctionBodies,\n .experimentalSkipNonInlinableFunctionBodies,\n .experimentalSkipNonInlinableFunctionBodiesWithoutTypes,\n .F,\n .Fsystem,\n .I,\n .nostdimport,\n .O,\n .Onone,\n .moduleName,\n .moduleLinkName,\n .packageName,\n .parseAsLibrary,\n .parseStdlib,\n .runtimeCompatibilityVersion,\n .target,\n .sdk,\n .swiftVersion,\n .wholeModuleOptimization,\n .wmo,\n .Xcc,\n .Xfrontend,\n .Xllvm,\n ]\n\n private static let swiftcSpec = Command.FlagSpec(\n swiftOptions.filter { !$0.attributes.contains(.noDriver) } + [\n // Not currently listed as a driver option, but it used to be. Include\n // for better compatibility.\n .enableExperimentalCxxInterop\n ]\n )\n\n private static let swiftFrontendSpec = Command.FlagSpec(\n swiftOptions.filter { $0.attributes.contains(.frontend) }\n )\n\n var flagSpec: Command.FlagSpec {\n switch self {\n case .clang:\n Self.clangSpec\n case .swiftc:\n Self.swiftcSpec\n case .swiftFrontend:\n Self.swiftFrontendSpec\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_KnownCommand.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Command_KnownCommand.swift
Swift
8,267
0.95
0.063604
0.169231
react-lib
263
2024-03-10T11:57:59.966863
Apache-2.0
false
940b1027c486796be7c01bd5d783ef9b
//===--- Lock.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport os\n\nfinal class Lock: @unchecked Sendable {\n private let lockPtr: UnsafeMutablePointer<os_unfair_lock>\n init() {\n self.lockPtr = UnsafeMutablePointer<os_unfair_lock>.allocate(capacity: 1)\n self.lockPtr.initialize(to: os_unfair_lock())\n }\n\n func lock() {\n os_unfair_lock_lock(self.lockPtr)\n }\n\n func unlock() {\n os_unfair_lock_unlock(self.lockPtr)\n }\n\n @inline(__always)\n func withLock<R>(_ body: () throws -> R) rethrows -> R {\n lock()\n defer {\n unlock()\n }\n return try body()\n }\n\n deinit {\n self.lockPtr.deinitialize(count: 1)\n self.lockPtr.deallocate()\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Concurrency_Lock.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Concurrency_Lock.swift
Swift
1,119
0.95
0.093023
0.297297
react-lib
963
2023-11-01T20:41:32.352068
BSD-3-Clause
false
cb279594293bf4e3d4c136cfc359dabc
//===--- MutexBox.swift ---------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nfinal class MutexBox<T>: @unchecked Sendable {\n private let lock = Lock()\n private var value: T\n\n init(_ value: T) {\n self.value = value\n }\n\n @inline(__always)\n func withLock<R>(_ body: (inout T) throws -> R) rethrows -> R {\n try lock.withLock {\n try body(&value)\n }\n }\n}\n\nextension MutexBox {\n convenience init<U>() where T == U? {\n self.init(nil)\n }\n convenience init<U, V>() where T == [U: V] {\n self.init([:])\n }\n convenience init<U>() where T == [U] {\n self.init([])\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Concurrency_MutexBox.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Concurrency_MutexBox.swift
Swift
1,026
0.95
0.128205
0.314286
awesome-app
591
2025-06-23T08:52:44.354736
Apache-2.0
false
393e70fba0bc3d96b02b45aac181abcf
//===--- Error.swift ------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nenum XcodeGenError: Error, CustomStringConvertible {\n case pathNotFound(AbsolutePath)\n case noSwiftBuildDir(AbsolutePath, couldBeParent: Bool)\n case couldNotInferProjectRoot(reason: String)\n\n var description: String {\n switch self {\n case .pathNotFound(let basePath):\n return "'\(basePath)' not found"\n case .noSwiftBuildDir(let basePath, let couldBeParent):\n let base = "no swift build directory found in '\(basePath)'"\n let note = "; did you mean to pass the path of the parent?"\n return couldBeParent ? "\(base)\(note)" : base\n case .couldNotInferProjectRoot(let reason):\n return """\n could not infer project root path; \(reason); please manually specify \\n using '--project-root-dir' instead\n """\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Error.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Error.swift
Swift
1,288
0.8
0.090909
0.354839
react-lib
39
2023-07-23T01:36:44.142031
MIT
false
02c8eb484d2c7651f80028a27d08bc29
//===--- ClangTarget.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nstruct ClangTarget {\n var name: String\n var parentPath: RelativePath\n var sources: [RelativePath]\n var unbuildableSources: [RelativePath]\n var headers: [RelativePath]\n\n init(\n name: String, parentPath: RelativePath,\n sources: [RelativePath], unbuildableSources: [RelativePath] = [],\n headers: [RelativePath]\n ) {\n self.name = name\n self.parentPath = parentPath\n self.sources = sources\n self.unbuildableSources = unbuildableSources\n self.headers = headers\n }\n}\n\nextension RepoBuildDir {\n func getCSourceFilePaths(for path: RelativePath) throws -> [RelativePath] {\n try getAllRepoSubpaths(of: path).filter(\.isCSourceLike)\n }\n\n func getHeaderFilePaths(for path: RelativePath) throws -> [RelativePath] {\n try getAllRepoSubpaths(of: path).filter(\.isHeaderLike)\n }\n\n func getClangTarget(\n for target: ClangTargetSource, knownUnbuildables: Set<RelativePath>\n ) throws -> ClangTarget? {\n let path = target.path\n let name = target.name\n\n let sourcePaths = try getCSourceFilePaths(for: path)\n let headers = try getHeaderFilePaths(for: path)\n if sourcePaths.isEmpty && headers.isEmpty {\n return nil\n }\n\n var sources: [RelativePath] = []\n var unbuildableSources: [RelativePath] = []\n for path in sourcePaths {\n // If we have no arguments, or have a known unbuildable, treat as not\n // buildable. We'll still include it in the project, but in a separate\n // target that isn't built by default.\n if try !clangArgs.hasBuildArgs(for: path) ||\n knownUnbuildables.contains(path) {\n unbuildableSources.append(path)\n continue\n }\n // If we have no '.o' present for a given file, assume it's not buildable.\n // The 'mayHaveUnbuildableFiles' condition is really only used here to\n // reduce IO and only check targets we know are problematic.\n if target.mayHaveUnbuildableFiles,\n try !clangArgs.isObjectFilePresent(for: path) {\n log.debug("! Treating '\(path)' as unbuildable; no '.o' file")\n unbuildableSources.append(path)\n continue\n }\n sources.append(path)\n }\n\n return ClangTarget(\n name: name, parentPath: path, sources: sources,\n unbuildableSources: unbuildableSources, headers: headers\n )\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_ClangTarget.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_ClangTarget.swift
Swift
2,798
0.8
0.243902
0.22973
react-lib
749
2025-02-22T09:15:55.637352
BSD-3-Clause
false
cde8666727af17f4f89c7519707c1727
//===--- ClangTargetSource.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The path at which to find source files for a particular target.\nstruct ClangTargetSource {\n var name: String\n var path: RelativePath\n var mayHaveUnbuildableFiles: Bool\n\n init(\n at path: RelativePath, named name: String,\n mayHaveUnbuildableFiles: Bool\n ) {\n self.name = name\n self.path = path\n self.mayHaveUnbuildableFiles = mayHaveUnbuildableFiles\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_ClangTargetSource.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_ClangTargetSource.swift
Swift
891
0.8
0.111111
0.48
react-lib
577
2023-12-31T13:01:02.407004
GPL-3.0
false
1acf592f08b4e9107574fff6b64597ab
//===--- GeneratedProject.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct GeneratedProject: Sendable {\n public let path: AbsolutePath\n let allBuildTargets: [Scheme.BuildTarget]\n\n init(at path: AbsolutePath, allBuildTargets: [Scheme.BuildTarget]) {\n self.path = path\n self.allBuildTargets = allBuildTargets\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_GeneratedProject.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_GeneratedProject.swift
Swift
774
0.8
0.095238
0.578947
vue-tools
578
2025-03-16T02:08:41.913567
BSD-3-Clause
false
704f86f6bc237aac6108c94682748089
//===--- ProjectGenerator.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Xcodeproj\nimport Darwin\n\nextension Xcode.Reference {\n fileprivate var displayName: String {\n name ?? RelativePath(path).fileName\n }\n}\n\nfileprivate final class ProjectGenerator {\n let spec: ProjectSpec\n\n private var project = Xcode.Project()\n private let allTarget: Xcode.Target\n\n enum CachedGroup {\n /// Covered by a parent folder reference.\n case covered\n /// Present in the project.\n case present(Xcode.Group)\n }\n private var groups: [RelativePath: CachedGroup] = [:]\n private var files: [RelativePath: Xcode.FileReference] = [:]\n private var targets: [String: Xcode.Target] = [:]\n private var unbuildableSources: [RelativePath] = []\n private var runnableBuildTargets: [RunnableTarget: Xcode.Target] = [:]\n\n /// The group in which external files are stored.\n private var externalsGroup: Xcode.Group {\n if let _externalsGroup {\n return _externalsGroup\n }\n let group = project.mainGroup.addGroup(\n path: "", pathBase: .groupDir, name: "external"\n )\n _externalsGroup = group\n return group\n }\n private var _externalsGroup: Xcode.Group?\n\n private lazy var includeSubstitutionTarget = {\n project.addTarget(name: "swift-include-substitutions")\n }()\n private var includeSubstitutions: Set<BuildArgs.PathSubstitution> = []\n\n /// The main repo dir relative to the project.\n private lazy var mainRepoDirInProject: RelativePath? =\n spec.mainRepoDir.map { repoRelativePath.appending($0) }\n\n private var generated: Bool = false\n\n var name: String {\n spec.name\n }\n var buildDir: RepoBuildDir {\n spec.buildDir\n }\n var addSwiftDependencies: Bool {\n spec.addSwiftDependencies\n }\n\n var repoPath: AbsolutePath {\n buildDir.repoPath\n }\n\n var repoRelativePath: RelativePath {\n buildDir.repoRelativePath\n }\n\n var projectRootDir: AbsolutePath {\n buildDir.projectRootDir\n }\n\n var pathName: RelativePath {\n "\(name).xcodeproj"\n }\n\n var runnableTargets: RunnableTargets {\n get throws {\n try spec.runnableBuildDir.runnableTargets\n }\n }\n\n init(for spec: ProjectSpec) {\n self.spec = spec\n\n // Create an 'ALL' meta-target that depends on everything.\n self.allTarget = project.addTarget(name: "ALL")\n\n // Setup the project root.\n self.project.mainGroup.path = projectRootDir.rawPath\n self.project.mainGroup.pathBase = .absolute\n self.project.buildSettings.common.PROJECT_DIR = projectRootDir.rawPath\n }\n\n /// Computes both the parent group along with the relative child path\n /// for a file path relative to the project root.\n private func parentGroup(\n for path: RelativePath\n ) -> (parentGroup: Xcode.Group, childPath: RelativePath)? {\n guard let parent = path.parentDir else {\n // We've already handled paths under the repo, so this must be for\n // paths outside the repo.\n return (externalsGroup, path)\n }\n // We avoid adding a parent for paths above the repo, e.g we want a\n // top-level 'lib', not 'swift/lib'.\n if parent == repoRelativePath || parent == mainRepoDirInProject {\n return (project.mainGroup, path)\n }\n guard let parentGroup = group(for: parent) else { return nil }\n return (parentGroup, RelativePath(path.fileName))\n }\n\n /// Returns the group for a given path, or `nil` if the path is covered\n /// by a parent folder reference.\n private func group(for path: RelativePath) -> Xcode.Group? {\n if let result = groups[path] {\n switch result {\n case .covered:\n return nil\n case .present(let g):\n return g\n }\n }\n guard\n files[path] == nil, let (parentGroup, childPath) = parentGroup(for: path)\n else {\n groups[path] = .covered\n return nil\n }\n let group = parentGroup.addGroup(\n path: childPath.rawPath, pathBase: .groupDir, name: path.fileName\n )\n groups[path] = .present(group)\n return group\n }\n\n private func checkNotExcluded(\n _ path: RelativePath?, for description: String? = nil\n ) -> Bool {\n guard let path else { return true }\n\n // Not very efficient, but excludedPaths should be small in practice.\n guard let excluded = spec.excludedPaths.first(\n where: { path.starts(with: $0.path) }\n ) else {\n return true\n }\n if let description, let reason = excluded.reason {\n log.note("""\n Skipping \(description) at \\n '\(repoRelativePath.appending(path))'; \(reason)\n """)\n }\n return false\n }\n\n @discardableResult\n private func getOrCreateProjectRef(\n _ ref: ProjectSpec.PathReference\n ) -> Xcode.FileReference? {\n let path = ref.path\n if let file = files[path] {\n return file\n }\n assert(\n projectRootDir.appending(path).exists, "File '\(path)' does not exist"\n )\n // If this is a folder reference, make sure we haven't already created a\n // group there.\n if ref.kind == .folder {\n guard groups[path] == nil else {\n return nil\n }\n }\n guard let (parentGroup, childPath) = parentGroup(for: path) else {\n return nil\n }\n let file = parentGroup.addFileReference(\n path: childPath.rawPath, isDirectory: ref.kind == .folder,\n pathBase: .groupDir, name: path.fileName\n )\n files[path] = file\n return file\n }\n\n @discardableResult\n private func getOrCreateRepoRef(\n _ ref: ProjectSpec.PathReference\n ) -> Xcode.FileReference? {\n let path = ref.path\n guard checkNotExcluded(path) else { return nil }\n return getOrCreateProjectRef(ref.withPath(repoRelativePath.appending(path)))\n }\n\n func getAllRepoSubpaths(of parent: RelativePath) throws -> [RelativePath] {\n try buildDir.getAllRepoSubpaths(of: parent)\n }\n\n func generateBaseTarget(\n _ name: String, at parentPath: RelativePath?, canUseBuildableFolder: Bool,\n productType: Xcode.Target.ProductType?, includeInAllTarget: Bool\n ) -> Xcode.Target? {\n let name = {\n // If we have a same-named target, disambiguate.\n if targets[name] == nil {\n return name\n }\n var i = 2\n var newName: String { "\(name)\(i)" }\n while targets[newName] != nil {\n i += 1\n }\n return newName\n }()\n var buildableFolder: Xcode.FileReference?\n if let parentPath, !parentPath.components.isEmpty {\n // If we've been asked to use buildable folders, see if we can create\n // a folder reference at the parent path. Otherwise, create a group at\n // the parent path. If we can't create either a folder or group, this is\n // nested in a folder reference and there's nothing we can do.\n if spec.useBuildableFolders && canUseBuildableFolder {\n buildableFolder = getOrCreateRepoRef(.folder(parentPath))\n }\n guard buildableFolder != nil ||\n group(for: repoRelativePath.appending(parentPath)) != nil else {\n // If this isn't a child of an explicitly added reference, something\n // has probably gone wrong.\n if !spec.referencesToAdd.contains(\n where: { parentPath.starts(with: $0.path) }\n ) {\n log.warning("""\n Target '\(name)' at '\(repoRelativePath.appending(parentPath))' is \\n nested in a folder reference; skipping. This is likely an xcodegen bug.\n """)\n }\n return nil\n }\n }\n let target = project.addTarget(productType: productType, name: name)\n targets[name] = target\n if includeInAllTarget {\n allTarget.addDependency(on: target)\n }\n if let buildableFolder {\n target.addBuildableFolder(buildableFolder)\n }\n target.buildSettings.common.ONLY_ACTIVE_ARCH = "YES"\n target.buildSettings.common.USE_HEADERMAP = "NO"\n // The product name needs to be unique across every project we generate\n // (to allow the combined workspaces to work), so add in the project name.\n target.buildSettings.common.PRODUCT_NAME = "\(self.name)_\(name)"\n return target\n }\n\n func replacingToolchainPath(_ str: String) -> String? {\n // Replace a toolchain path with the toolchain being used by Xcode.\n // TODO: Can we do better than a scan here? Could we get the old\n // toolchain path from the build args?\n str.scanningUTF8 { scanner in\n repeat {\n if scanner.tryEat(utf8: ".xctoolchain") {\n return "${TOOLCHAIN_DIR}\(String(utf8: scanner.remaining))"\n }\n } while scanner.tryEat()\n return nil\n }\n }\n\n func replacingProjectDir(_ str: String) -> String {\n // Replace paths within the project directory with PROJECT_DIR.\n str.replacing(projectRootDir.rawPath, with: "${PROJECT_DIR}")\n }\n\n func applyBaseSubstitutions(to buildArgs: inout BuildArgs) {\n buildArgs.transformValues(includeSubOptions: true) { value in\n if let replacement = replacingToolchainPath(value) {\n return replacement\n }\n return replacingProjectDir(value)\n }\n }\n\n /// Checks whether a target can be represented using a buildable folder.\n func canUseBuildableFolder(\n at parentPath: RelativePath, sources: [RelativePath]\n ) throws -> Bool {\n // To use a buildable folder, all child sources need to be accounted for\n // in the target. If we have any stray sources not part of the target,\n // attempting to use a buildable folder would incorrectly include them.\n // Additionally, special targets like "Unbuildables" have an empty parent\n // path, avoid buildable folders for them.\n guard spec.useBuildableFolders, !parentPath.isEmpty else { return false }\n let sources = Set(sources)\n return try getAllRepoSubpaths(of: parentPath)\n .allSatisfy { !$0.isSourceLike || sources.contains($0) }\n }\n\n /// Checks whether a given Clang target can be represented using a buildable\n /// folder.\n func canUseBuildableFolder(for clangTarget: ClangTarget) throws -> Bool {\n // In addition to the standard checking, we also must not have any\n // unbuildable sources or sources with unique arguments.\n // TODO: To improve the coverage of buildable folders, we ought to start\n // automatically splitting umbrella Clang targets like 'stdlib', since\n // they currently always have files with unique args.\n guard spec.useBuildableFolders, clangTarget.unbuildableSources.isEmpty else {\n return false\n }\n let parent = clangTarget.parentPath\n let hasConsistentArgs = try clangTarget.sources.allSatisfy {\n try !buildDir.clangArgs.hasUniqueArgs(for: $0, parent: parent)\n }\n guard hasConsistentArgs else { return false }\n return try canUseBuildableFolder(at: parent, sources: clangTarget.sources)\n }\n\n func canUseBuildableFolder(\n for buildRule: SwiftTarget.BuildRule\n ) throws -> Bool {\n guard let parentPath = buildRule.parentPath else { return false }\n return try canUseBuildableFolder(\n at: parentPath, sources: buildRule.sources.repoSources\n )\n }\n\n func generateClangTarget(\n _ targetInfo: ClangTarget, includeInAllTarget: Bool = true\n ) throws {\n let targetPath = targetInfo.parentPath\n guard checkNotExcluded(targetPath, for: "Clang target") else {\n return\n }\n unbuildableSources += targetInfo.unbuildableSources\n\n // Need to defer the addition of headers since the target may want to use\n // a buildable folder.\n defer {\n for header in targetInfo.headers {\n getOrCreateRepoRef(.file(header))\n }\n }\n\n // If we have no sources, we're done.\n if targetInfo.sources.isEmpty {\n // Inform the user if the target was completely empty.\n if targetInfo.headers.isEmpty && targetInfo.unbuildableSources.isEmpty {\n log.note("""\n Skipping '\(repoRelativePath)/\(targetPath)'; has no sources with \\n build args\n """)\n }\n return\n }\n let target = generateBaseTarget(\n targetInfo.name, at: targetPath,\n canUseBuildableFolder: try canUseBuildableFolder(for: targetInfo),\n productType: .staticArchive,\n includeInAllTarget: includeInAllTarget\n )\n guard let target else { return }\n\n // Don't optimize or generate debug info, that will only slow down\n // compilation; we don't actually care about the binary.\n target.buildSettings.common.GCC_OPTIMIZATION_LEVEL = "0"\n target.buildSettings.common.GCC_GENERATE_DEBUGGING_SYMBOLS = "NO"\n target.buildSettings.common.GCC_WARN_64_TO_32_BIT_CONVERSION = "NO"\n\n var libBuildArgs = try buildDir.clangArgs.getArgs(for: targetPath)\n applyBaseSubstitutions(to: &libBuildArgs)\n\n target.buildSettings.common.HEADER_SEARCH_PATHS = \n libBuildArgs.takePrintedValues(for: .I)\n\n target.buildSettings.common.CLANG_CXX_LANGUAGE_STANDARD =\n libBuildArgs.takeLastValue(for: .std)\n\n target.buildSettings.common.OTHER_CPLUSPLUSFLAGS = libBuildArgs.printedArgs\n\n let sourcesToBuild = target.addSourcesBuildPhase()\n\n for source in targetInfo.sources {\n guard let sourceRef = getOrCreateRepoRef(.file(source)) else {\n continue\n }\n let buildFile = sourcesToBuild.addBuildFile(fileRef: sourceRef)\n\n // Add any per-file settings.\n var fileArgs = try buildDir.clangArgs.getUniqueArgs(\n for: source, parent: targetPath, infer: spec.inferArgs\n )\n if !fileArgs.isEmpty {\n applyBaseSubstitutions(to: &fileArgs)\n buildFile.settings.COMPILER_FLAGS = fileArgs.printed\n }\n }\n }\n\n /// Record path substitutions for a given target.\n func recordPathSubstitutions(\n for target: Xcode.Target, _ substitutions: [BuildArgs.PathSubstitution]\n ) {\n guard !substitutions.isEmpty else { return }\n includeSubstitutions.formUnion(substitutions)\n target.addDependency(on: includeSubstitutionTarget)\n }\n\n /// Add the script phase to populate the substituted includes if needed.\n func addSubstitutionPhaseIfNeeded() {\n guard !includeSubstitutions.isEmpty else { return }\n\n let subs = includeSubstitutions.sorted(by: \.oldPath.rawPath).map { sub in\n (oldPath: replacingProjectDir(sub.oldPath.rawPath),\n newPath: sub.newPath.rawPath)\n }\n\n let rsyncs = subs.map { sub in\n let oldPath = sub.oldPath.escaped\n let newPath = sub.newPath.escaped\n return """\n mkdir -p \(newPath)\n rsync -aqm --delete --exclude='*.swift*' --exclude '*.o' --exclude '*.d' \\n --exclude '*.dylib' --exclude '*.a' --exclude '*.cmake' --exclude '*.json' \\n \(oldPath)/ \(newPath)/\n """\n }.joined(separator: "\n")\n\n let command = """\n set -e\n if [ -z "${SYMROOT}" ]; then\n echo 'SYMROOT not defined'\n exit 1\n fi\n \(rsyncs)\n """\n\n includeSubstitutionTarget.addShellScriptBuildPhase(\n script: command,\n inputs: subs.map(\.oldPath),\n outputs: subs.map(\.newPath),\n alwaysRun: false\n )\n }\n\n func applySubstitutions(\n to buildArgs: inout BuildArgs, target: Xcode.Target, targetInfo: SwiftTarget\n ) {\n // First force -Onone. Running optimizations only slows down build times, we\n // don't actually care about the compiled binary.\n buildArgs.append(.flag(.Onone))\n\n // Exclude the experimental skipping function bodies flags, we specify\n // -experimental-skip-all-function bodies for modules, and if we promote\n // an emit module rule to a build rule, these would cause issues.\n buildArgs.exclude(\n .experimentalSkipNonInlinableFunctionBodies,\n .experimentalSkipNonInlinableFunctionBodiesWithoutTypes\n )\n if buildArgs.hasSubOptions(for: .swiftFrontend) {\n buildArgs[subOptions: .swiftFrontend].exclude(\n .experimentalSkipAllFunctionBodies,\n .experimentalSkipNonInlinableFunctionBodies,\n .experimentalSkipNonInlinableFunctionBodiesWithoutTypes\n )\n }\n\n // Then inject includes for the dependencies.\n for dep in targetInfo.dependencies {\n // TODO: The escaping here is easy to miss, maybe we should invest in\n // a custom interpolation type to make it clearer.\n buildArgs.append("-I \(getModuleDir(for: dep).escaped)")\n }\n\n // Replace references to the sdk with $SDKROOT.\n if let sdk = buildArgs.takeLastValue(for: .sdk) {\n buildArgs.transformValues(includeSubOptions: true) { value in\n value.replacing(sdk, with: "${SDKROOT}")\n }\n }\n buildArgs = buildArgs.map { arg in\n // -enable-experimental-cxx-interop was removed as a driver option in 5.9,\n // to maintain the broadest compatibility with different toolchains, use\n // the frontend option.\n guard arg.flag == .enableExperimentalCxxInterop else { return arg }\n return .option(\n .Xfrontend, spacing: .spaced, value: "\(.enableExperimentalCxxInterop)"\n )\n }\n // Replace includes that point into the build folder since they can\n // reference swiftmodules that expect a mismatched compiler. We'll\n // instead point them to a directory that has the swiftmodules removed,\n // and the modules will be picked up from the DerivedData products.\n let subs = buildArgs.substitutePaths(\n for: .I, includeSubOptions: true) { include -> RelativePath? in\n // NOTE: If llvm/clang ever start having swift targets, this will need\n // changing to encompass the parent. For now, avoid copying the extra\n // files.\n guard let suffix = include.removingPrefix(buildDir.path) else {\n return nil\n }\n return includeSubstDirectory.appending(suffix)\n }\n recordPathSubstitutions(for: target, subs)\n applyBaseSubstitutions(to: &buildArgs)\n }\n\n func getModuleDir(for target: SwiftTarget) -> RelativePath {\n "${SYMROOT}/Modules/\(target.name)"\n }\n\n var includeSubstDirectory: RelativePath {\n "${SYMROOT}/swift-includes"\n }\n\n @discardableResult\n func generateSwiftTarget(\n _ targetInfo: SwiftTarget, emitModuleRule: SwiftTarget.EmitModuleRule,\n includeInAllTarget: Bool = true\n ) throws -> Xcode.Target? {\n if addSwiftDependencies {\n // Produce a BuildRule and generate it.\n let buildRule = SwiftTarget.BuildRule(\n parentPath: nil, sources: emitModuleRule.sources,\n buildArgs: emitModuleRule.buildArgs\n )\n return try generateSwiftTarget(\n targetInfo, buildRule: buildRule, includeInAllTarget: includeInAllTarget\n )\n }\n let target = generateBaseTarget(\n targetInfo.name, at: nil, canUseBuildableFolder: false, productType: nil,\n includeInAllTarget: includeInAllTarget\n )\n guard let target else { return nil }\n\n var buildArgs = emitModuleRule.buildArgs\n for secondary in emitModuleRule.sources.externalSources {\n buildArgs.append(.value(secondary.rawPath))\n }\n applySubstitutions(to: &buildArgs, target: target, targetInfo: targetInfo)\n\n let targetDir = getModuleDir(for: targetInfo)\n let destModule = targetDir.appending("\(targetInfo.moduleName).swiftmodule")\n\n target.addShellScriptBuildPhase(\n script: """\n mkdir -p \(targetDir.escaped)\n run() {\n echo "$ $@"\n exec "$@"\n }\n run xcrun swiftc -sdk "${SDKROOT}" \\n -emit-module -emit-module-path \(destModule.escaped) \\n -Xfrontend -experimental-skip-all-function-bodies \\n \(buildArgs.printed)\n """,\n inputs: [],\n outputs: [destModule.rawPath],\n alwaysRun: true\n )\n return target\n }\n\n @discardableResult\n func generateSwiftTarget(\n _ targetInfo: SwiftTarget, buildRule: SwiftTarget.BuildRule,\n includeInAllTarget: Bool = true\n ) throws -> Xcode.Target? {\n guard checkNotExcluded(buildRule.parentPath, for: "Swift target") else {\n return nil\n }\n // Create the target.\n let target = generateBaseTarget(\n targetInfo.name, at: buildRule.parentPath,\n canUseBuildableFolder: try canUseBuildableFolder(for: buildRule),\n productType: .staticArchive,\n includeInAllTarget: includeInAllTarget\n )\n guard let target else { return nil }\n\n // Explicit modules currently fails to build with:\n // Invalid argument '-std=c++17' not allowed with 'Objective-C'\n target.buildSettings.common.SWIFT_ENABLE_EXPLICIT_MODULES = "NO"\n\n let buildSettings = target.buildSettings\n var buildArgs = buildRule.buildArgs\n\n applySubstitutions(to: &buildArgs, target: target, targetInfo: targetInfo)\n\n // Follow the same logic as swift-driver and set the module name to 'main'\n // if we don't have one.\n let moduleName = buildArgs.takePrintedLastValue(for: .moduleName)\n buildSettings.common.PRODUCT_MODULE_NAME = moduleName ?? "main"\n\n // Emit a module if we need to.\n // TODO: This currently just uses the build rule command args, should we\n // diff/merge the args? Or do it separately if they differ?\n if targetInfo.emitModuleRule != nil {\n buildSettings.common.DEFINES_MODULE = "YES"\n }\n\n // Disable the Obj-C bridging header; we don't currently use this, and\n // even if we did, we'd probably want to use the one in the Ninja build\n // folder.\n // This also works around a compiler crash\n // (https://github.com/swiftlang/swift/issues/78190).\n buildSettings.common.SWIFT_OBJC_INTERFACE_HEADER_NAME = ""\n\n if let last = buildArgs.takeFlagGroup(.O, .Onone) {\n buildSettings.common.SWIFT_OPTIMIZATION_LEVEL = last.printed\n }\n\n // Respect '-wmo' if passed.\n // TODO: Should we try force batch mode where we can? Unfortunately the\n // stdlib currently doesn't build with batch mode, so we'd need to special\n // case it.\n if buildArgs.takeFlags(.wmo, .wholeModuleOptimization) {\n buildSettings.common.SWIFT_COMPILATION_MODE = "wholemodule"\n }\n\n let swiftVersion = buildArgs.takeLastValue(for: .swiftVersion)\n buildSettings.common.SWIFT_VERSION = swiftVersion ?? "5.0"\n\n if let targetStr = buildArgs.takeLastValue(for: .target),\n let ver = targetStr.firstMatch(of: #/macosx?(\d+(?:\.\d+)?)/#) {\n buildSettings.common.MACOSX_DEPLOYMENT_TARGET = String(ver.1)\n }\n\n // Each target gets their own product dir. Add the search paths for\n // dependencies individually, so that we don't accidentally pull in a\n // module we don't need (e.g swiftCore for targets that don't want the\n // just-built stdlib).\n let productDir = getModuleDir(for: targetInfo).rawPath\n buildSettings.common.TARGET_BUILD_DIR = productDir\n buildSettings.common.BUILT_PRODUCTS_DIR = productDir\n\n buildSettings.common.SWIFT_INCLUDE_PATHS =\n buildArgs.takePrintedValues(for: .I)\n\n buildSettings.common.OTHER_SWIFT_FLAGS = buildArgs.printedArgs\n\n // Add compile sources phase.\n let sourcesToBuild = target.addSourcesBuildPhase()\n for source in buildRule.sources.repoSources {\n guard let sourceRef = getOrCreateRepoRef(.file(source)) else {\n continue\n }\n sourcesToBuild.addBuildFile(fileRef: sourceRef)\n }\n for absSource in buildRule.sources.externalSources {\n guard let source = absSource.removingPrefix(projectRootDir) else {\n log.warning("""\n Source file '\(absSource)' is outside the project directory; ignoring\n """)\n continue\n }\n guard let sourceRef = getOrCreateProjectRef(.file(source)) else {\n continue\n }\n sourcesToBuild.addBuildFile(fileRef: sourceRef)\n }\n // Finally add any .swift.gyb files.\n if let parentPath = buildRule.parentPath {\n for gyb in try getAllRepoSubpaths(of: parentPath) where gyb.isSwiftGyb {\n getOrCreateRepoRef(.file(gyb))\n }\n }\n return target\n }\n\n @discardableResult\n func generateSwiftTarget(\n _ target: SwiftTarget, includeInAllTarget: Bool = true\n ) throws -> Xcode.Target? {\n if let buildRule = target.buildRule {\n return try generateSwiftTarget(target, buildRule: buildRule)\n }\n if let emitModuleRule = target.emitModuleRule {\n return try generateSwiftTarget(target, emitModuleRule: emitModuleRule)\n }\n return nil\n }\n\n func sortGroupChildren(_ group: Xcode.Group) {\n group.subitems.sort { lhs, rhs in\n // The 'externals' group is special, sort it first.\n if (lhs === _externalsGroup) != (rhs === _externalsGroup) {\n return lhs === _externalsGroup\n }\n // Sort directories first.\n if lhs.isDirectoryLike != rhs.isDirectoryLike {\n return lhs.isDirectoryLike\n }\n // Then alphabetically.\n return lhs.displayName.lowercased() < rhs.displayName.lowercased()\n }\n for case let sub as Xcode.Group in group.subitems {\n sortGroupChildren(sub)\n }\n }\n\n func generateIfNeeded() throws {\n guard !generated else { return }\n generated = true\n\n // First add file/folder references.\n for ref in spec.referencesToAdd {\n getOrCreateRepoRef(ref)\n }\n\n // Gather the Swift targets to generate, including any dependencies.\n var swiftTargets: Set<SwiftTarget> = []\n for targetSource in spec.swiftTargetSources {\n for target in try buildDir.getSwiftTargets(for: targetSource) {\n swiftTargets.insert(target)\n swiftTargets.formUnion(target.dependencies)\n }\n }\n let sortedTargets = swiftTargets.sorted(by: \.name)\n if !sortedTargets.isEmpty {\n log.debug("---- SWIFT TARGETS TO GENERATE ----")\n log.debug("\(sortedTargets.map(\.name).joined(separator: ", "))")\n log.debug("-----------------------------------")\n }\n // Generate the Swift targets.\n var generatedSwiftTargets: [SwiftTarget: Xcode.Target] = [:]\n for target in sortedTargets {\n generatedSwiftTargets[target] = try generateSwiftTarget(target)\n }\n // Wire up the dependencies.\n for (targetInfo, target) in generatedSwiftTargets {\n for dep in targetInfo.dependencies {\n guard let depTarget = generatedSwiftTargets[dep] else { continue }\n target.addDependency(on: depTarget)\n }\n }\n\n // Add substitutions phase if any Swift targets need it.\n addSubstitutionPhaseIfNeeded()\n\n // Generate the Clang targets.\n for targetSource in spec.clangTargetSources.sorted(by: \.name) {\n let target = try buildDir.getClangTarget(\n for: targetSource, knownUnbuildables: spec.knownUnbuildables\n )\n guard let target else { continue }\n try generateClangTarget(target)\n }\n\n if !unbuildableSources.isEmpty {\n let target = ClangTarget(\n name: "Unbuildables", \n parentPath: ".",\n sources: unbuildableSources,\n headers: []\n )\n try generateClangTarget(target, includeInAllTarget: false)\n }\n\n // Add targets for runnable targets if needed.\n if spec.addRunnableTargets && spec.addBuildForRunnableTargets {\n // We need to preserve PATH to find Ninja, which could e.g be in a\n // homebrew prefix, which isn't in the launchd environment (and therefore\n // Xcode doesn't have it).\n let path = getenv("PATH").map { String(cString: $0) }\n\n for runnable in try runnableTargets {\n // TODO: Can/should we use the external build tool target kind?\n let target = project.addTarget(name: "ninja-build-\(runnable.name)")\n var script = ""\n if let path {\n script += """\n export PATH="\(path)"\n\n """\n }\n script += """\n ninja -C \(spec.runnableBuildDir.path.escaped) -- \\n \(runnable.ninjaTargetName.escaped)\n """\n target.addShellScriptBuildPhase(\n script: script, inputs: [], outputs: [], alwaysRun: true\n )\n runnableBuildTargets[runnable] = target\n }\n }\n\n // Sort the groups.\n sortGroupChildren(project.mainGroup)\n }\n\n func generateAndWrite(\n into outputDir: AbsolutePath\n ) throws -> GeneratedProject {\n try generateIfNeeded()\n\n let projDir = outputDir.appending(pathName)\n\n let projDataPath = projDir.appending("project.pbxproj")\n try projDataPath.write(project.generatePlist().serialize())\n log.info("Generated '\(projDataPath)'")\n\n // Add the ALL meta-target as a scheme (we use a suffix to disambiguate it\n // from the ALL workspace scheme we generate).\n let allBuildTargets = [Scheme.BuildTarget(allTarget, in: pathName)]\n var schemes = SchemeGenerator(in: projDir)\n schemes.add(Scheme(\n "ALL-\(name)", replaceExisting: true, buildTargets: allBuildTargets\n ))\n\n // Add schemes for runnable targets.\n if spec.addRunnableTargets {\n for runnable in try runnableTargets {\n // Avoid replacing an existing scheme if it exists.\n // FIXME: Really we ought to be reading in the existing scheme, and\n // updating any values that need changing.\n var scheme = Scheme(runnable.name, replaceExisting: false)\n if let target = runnableBuildTargets[runnable] {\n scheme.buildAction.targets.append(.init(target, in: pathName))\n }\n // FIXME: Because we can't update an existing scheme, use a symlink to\n // refer to the run destination, allowing us to change it if needed.\n let link = projDir.appending(\n ".swift-xcodegen/runnable/\(runnable.name)"\n )\n try link.symlink(to: runnable.path)\n\n scheme.runAction = .init(path: link)\n schemes.add(scheme)\n }\n }\n try schemes.write()\n return GeneratedProject(at: projDir, allBuildTargets: allBuildTargets)\n }\n}\n\nextension ProjectSpec {\n public func generateAndWrite(\n into outputDir: AbsolutePath\n ) throws -> GeneratedProject {\n let generator = ProjectGenerator(for: self)\n return try generator.generateAndWrite(into: outputDir)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_ProjectGenerator.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_ProjectGenerator.swift
Swift
29,856
0.95
0.177363
0.168848
node-utils
938
2024-10-28T00:34:36.856761
MIT
false
c84c81aa797ea4dd6a7599739139d35f
//===--- ProjectSpec.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The specification for a project to generate.\npublic struct ProjectSpec {\n public var name: String\n public var buildDir: RepoBuildDir\n public var runnableBuildDir: RepoBuildDir\n\n /// Whether to include Clang targets.\n public var addClangTargets: Bool\n\n /// Whether to include Swift targets.\n public var addSwiftTargets: Bool\n\n /// Whether to add Swift dependencies to the project.\n public var addSwiftDependencies: Bool\n\n /// Whether to add targets for runnable executables.\n public var addRunnableTargets: Bool\n\n /// Whether to add a build target for runnable targets, if false they will\n /// be added as freestanding schemes.\n public var addBuildForRunnableTargets: Bool\n\n /// Whether to infer build arguments for files that don't have any, based\n /// on the build arguments of surrounding files.\n public var inferArgs: Bool\n\n /// Whether to prefer using folder references for groups containing non-source\n /// files.\n public var preferFolderRefs: Bool\n\n /// Whether to enable the use of buildable folders for targets.\n public var useBuildableFolders: Bool\n\n /// If provided, the paths added will be implicitly appended to this path.\n let mainRepoDir: RelativePath?\n\n private(set) var clangTargetSources: [ClangTargetSource] = []\n private(set) var swiftTargetSources: [SwiftTargetSource] = []\n\n private(set) var referencesToAdd: [PathReference] = []\n private(set) var excludedPaths: [ExcludedPath] = []\n private(set) var knownUnbuildables: Set<RelativePath> = []\n\n public init(\n _ name: String, for buildDir: RepoBuildDir, runnableBuildDir: RepoBuildDir,\n addClangTargets: Bool, addSwiftTargets: Bool,\n addSwiftDependencies: Bool, addRunnableTargets: Bool,\n addBuildForRunnableTargets: Bool, inferArgs: Bool, preferFolderRefs: Bool,\n useBuildableFolders: Bool, mainRepoDir: RelativePath? = nil\n ) {\n self.name = name\n self.buildDir = buildDir\n self.runnableBuildDir = runnableBuildDir\n self.addClangTargets = addClangTargets\n self.addSwiftTargets = addSwiftTargets\n self.addSwiftDependencies = addSwiftDependencies\n self.addRunnableTargets = addRunnableTargets\n self.addBuildForRunnableTargets = addBuildForRunnableTargets\n self.inferArgs = inferArgs\n self.preferFolderRefs = preferFolderRefs\n self.useBuildableFolders = useBuildableFolders\n self.mainRepoDir = mainRepoDir\n }\n\n var repoRoot: AbsolutePath {\n buildDir.repoPath\n }\n}\n\nextension ProjectSpec {\n public struct ExcludedPath {\n var path: RelativePath\n var reason: String?\n }\n\n struct PathReference {\n enum Kind {\n case file, folder\n }\n var kind: Kind\n var path: RelativePath\n\n static func file(_ path: RelativePath) -> Self {\n .init(kind: .file, path: path)\n }\n static func folder(_ path: RelativePath) -> Self {\n .init(kind: .folder, path: path)\n }\n\n func withPath(_ newPath: RelativePath) -> Self {\n var result = self\n result.path = newPath\n return result\n }\n }\n}\n\nextension ProjectSpec {\n private var mainRepoPath: AbsolutePath {\n // Add the main repo dir if we were asked to.\n if let mainRepoDir {\n repoRoot.appending(mainRepoDir)\n } else {\n repoRoot\n }\n }\n\n private func mapKnownPath(_ path: RelativePath) -> RelativePath {\n // Add the main repo dir if we were asked to.\n if let mainRepoDir {\n mainRepoDir.appending(path)\n } else {\n path\n }\n }\n\n private func mapPath(\n _ path: RelativePath, for description: String\n ) -> RelativePath? {\n let path = mapKnownPath(path)\n let absPath = repoRoot.appending(path)\n guard absPath.exists else {\n log.warning("Skipping \(description) at '\(absPath)'; does not exist")\n return nil\n }\n return path\n }\n}\n\nextension ProjectSpec {\n public mutating func addExcludedPath(\n _ path: RelativePath, reason: String? = nil\n ) {\n guard let path = mapPath(path, for: "exclusion") else { return }\n excludedPaths.append(.init(path: path, reason: reason))\n }\n\n public mutating func addUnbuildableFile(_ path: RelativePath) {\n guard let path = mapPath(path, for: "unbuildable file") else { return }\n self.knownUnbuildables.insert(path)\n }\n\n public mutating func addReference(to path: RelativePath) {\n guard let path = mapPath(path, for: "file") else { return }\n let isDir = repoRoot.appending(path).isDirectory\n referencesToAdd.append(isDir ? .folder(path) : .file(path))\n }\n\n public mutating func addHeaders(in path: RelativePath) {\n guard let path = mapPath(path, for: "headers") else { return }\n if preferFolderRefs {\n referencesToAdd.append(.folder(path))\n return\n }\n do {\n for header in try buildDir.getHeaderFilePaths(for: path) {\n referencesToAdd.append(.file(header))\n }\n } catch {\n log.warning("Skipping headers in \(path); '\(error)'")\n }\n }\n\n public mutating func addTopLevelDocs() {\n do {\n for doc in try mainRepoPath.getDirContents() where doc.isDocLike {\n referencesToAdd.append(.file(mapKnownPath(doc)))\n }\n } catch {\n log.warning("Skipping top-level docs for \(repoRoot); '\(error)'")\n }\n }\n\n public mutating func addDocsGroup(at path: RelativePath) {\n guard let path = mapPath(path, for: "docs") else { return }\n if preferFolderRefs {\n referencesToAdd.append(.folder(path))\n return\n }\n do {\n for doc in try buildDir.getAllRepoSubpaths(of: path) where doc.isDocLike {\n referencesToAdd.append(.file(doc))\n }\n } catch {\n log.warning("Skipping docs in \(path); '\(error)'")\n }\n }\n\n public mutating func addClangTarget(\n at path: RelativePath, named name: String? = nil,\n mayHaveUnbuildableFiles: Bool = false\n ) {\n guard addClangTargets else { return }\n guard let path = mapPath(path, for: "Clang target") else { return }\n let name = name ?? path.fileName\n clangTargetSources.append(ClangTargetSource(\n at: path, named: name, mayHaveUnbuildableFiles: mayHaveUnbuildableFiles\n ))\n }\n\n public mutating func addClangTargets(\n below path: RelativePath, addingPrefix prefix: String? = nil,\n mayHaveUnbuildableFiles: Bool = false\n ) {\n guard addClangTargets else { return }\n let originalPath = path\n guard let path = mapPath(path, for: "Clang targets") else { return }\n let absPath = repoRoot.appending(path)\n do {\n for child in try absPath.getDirContents() {\n guard absPath.appending(child).isDirectory else {\n continue\n }\n var name = child.fileName\n if let prefix = prefix {\n name = prefix + name\n }\n addClangTarget(\n at: originalPath.appending(child), named: name,\n mayHaveUnbuildableFiles: mayHaveUnbuildableFiles\n )\n }\n } catch {\n log.warning("Skipping Clang targets in \(path); '\(error)'")\n }\n }\n\n public mutating func addSwiftTargets(\n below path: RelativePath\n ) {\n guard addSwiftTargets else { return }\n guard let path = mapPath(path, for: "Swift targets") else { return }\n swiftTargetSources.append(SwiftTargetSource(below: path))\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_ProjectSpec.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_ProjectSpec.swift
Swift
7,637
0.8
0.161943
0.119816
vue-tools
101
2024-02-29T05:06:13.002468
Apache-2.0
false
3fd6a74a427e154de399b8e3d80484e6
//===--- SchemeGenerator.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Xcodeproj\n\nstruct Scheme {\n var name: String\n var buildAction: BuildAction\n var runAction: RunAction?\n var replaceExisting: Bool\n\n init(_ name: String, replaceExisting: Bool, buildTargets: [BuildTarget]) {\n self.name = name\n self.replaceExisting = replaceExisting\n self.buildAction = .init(targets: buildTargets)\n }\n\n init(_ name: String, replaceExisting: Bool, buildTargets: BuildTarget...) {\n self.init(\n name, replaceExisting: replaceExisting, buildTargets: buildTargets\n )\n }\n\n mutating func addBuildTarget(\n _ target: Xcode.Target, in path: RelativePath\n ) {\n buildAction.targets.append(.init(target, in: path))\n }\n}\n\nextension Scheme {\n struct BuildAction {\n var targets: [BuildTarget]\n }\n\n struct BuildTarget {\n var name: String\n var container: RelativePath\n\n init(_ target: Xcode.Target, in path: RelativePath) {\n self.name = target.name\n self.container = path\n }\n\n init(_ name: String, in path: RelativePath) {\n self.name = name\n self.container = path\n }\n }\n\n struct RunAction {\n var path: AbsolutePath\n }\n}\n\nstruct SchemeGenerator {\n let containerDir: AbsolutePath\n let disableAutoCreation: Bool\n\n var schemes: [Scheme] = []\n\n init(in containerDir: AbsolutePath, disableAutoCreation: Bool = true) {\n self.containerDir = containerDir\n self.disableAutoCreation = disableAutoCreation\n }\n}\n\nextension SchemeGenerator {\n mutating func add(_ scheme: Scheme) {\n schemes.append(scheme)\n }\n}\n\nextension SchemeGenerator {\n private func disableAutoCreationIfNeeded() throws {\n guard disableAutoCreation else { return }\n\n var relPath: RelativePath = "xcshareddata/WorkspaceSettings.xcsettings"\n if containerDir.hasExtension(.xcodeproj) {\n relPath = "project.xcworkspace/\(relPath)"\n }\n let settingsPath = containerDir.appending(relPath)\n\n let workspaceSettings = """\n <?xml version="1.0" encoding="UTF-8"?>\n <plist version="1.0">\n <dict>\n <key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>\n <false/>\n </dict>\n </plist>\n """\n\n try settingsPath.write(workspaceSettings)\n log.info("Generated '\(settingsPath)'")\n }\n\n private func writeScheme(_ scheme: Scheme) throws {\n let path = containerDir.appending(\n "xcshareddata/xcschemes/\(scheme.name).xcscheme"\n )\n\n // Don't overwrite if we haven't been asked to.\n if !scheme.replaceExisting && path.exists {\n return\n }\n\n var plist = """\n <?xml version="1.0" encoding="UTF-8"?>\n <Scheme LastUpgradeVersion = "9999" version = "1.3">\n <BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES">\n <BuildActionEntries>\n\n """\n for buildTarget in scheme.buildAction.targets {\n plist += """\n <BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES">\n <BuildableReference\n BuildableIdentifier = "primary"\n BuildableName = "\(buildTarget.name)"\n BlueprintName = "\(buildTarget.name)"\n ReferencedContainer = "container:\(buildTarget.container)">\n </BuildableReference>\n </BuildActionEntry>\n\n """\n }\n plist += """\n </BuildActionEntries>\n </BuildAction>\n\n """\n\n if let runAction = scheme.runAction {\n plist += """\n <LaunchAction>\n <PathRunnable\n FilePath = "\(runAction.path.escaped(addQuotesIfNeeded: false))">\n </PathRunnable>\n </LaunchAction>\n\n """\n }\n\n plist += """\n </Scheme>\n """\n\n try path.write(plist)\n log.info("Generated '\(path)'")\n }\n\n private func writeSchemes() throws {\n for scheme in schemes {\n try writeScheme(scheme)\n }\n }\n\n func write() throws {\n try disableAutoCreationIfNeeded()\n try writeSchemes()\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_SchemeGenerator.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_SchemeGenerator.swift
Swift
4,454
0.95
0.075581
0.084507
node-utils
419
2024-07-18T22:16:53.863755
BSD-3-Clause
false
2e2bccd21b14060862ae9907739ffa84
//===--- SwiftTarget.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nfinal class SwiftTarget {\n let name: String\n let moduleName: String\n\n var buildRule: BuildRule?\n var emitModuleRule: EmitModuleRule?\n\n var dependencies: [SwiftTarget] = []\n\n init(name: String, moduleName: String) {\n self.name = name\n self.moduleName = moduleName\n }\n}\n\nextension SwiftTarget: Hashable {\n static func == (lhs: SwiftTarget, rhs: SwiftTarget) -> Bool {\n ObjectIdentifier(lhs) == ObjectIdentifier(rhs)\n }\n func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n}\n\nextension SwiftTarget: CustomDebugStringConvertible {\n var debugDescription: String {\n name\n }\n}\n\nextension SwiftTarget {\n struct Sources {\n var repoSources: [RelativePath] = []\n var externalSources: [AbsolutePath] = []\n }\n struct BuildRule {\n var parentPath: RelativePath?\n var sources: Sources\n var buildArgs: BuildArgs\n }\n struct EmitModuleRule {\n var sources: Sources\n var buildArgs: BuildArgs\n }\n}\n\nextension SwiftTarget {\n var buildArgs: BuildArgs {\n buildRule?.buildArgs ?? emitModuleRule?.buildArgs ?? .init(for: .swiftc)\n }\n}\n\nextension RepoBuildDir {\n func getSwiftTargets(for source: SwiftTargetSource) throws -> [SwiftTarget] {\n try swiftTargets.getTargets(below: source.path)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_SwiftTarget.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_SwiftTarget.swift
Swift
1,775
0.95
0.086957
0.183333
python-kit
955
2024-10-01T03:16:17.474454
GPL-3.0
false
4b1e16743d97749079106eb07b6c24c7
//===--- SwiftTargetSource.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nstruct SwiftTargetSource {\n var path: RelativePath\n\n init(below path: RelativePath) {\n self.path = path\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_SwiftTargetSource.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_SwiftTargetSource.swift
Swift
628
0.8
0.105263
0.647059
vue-tools
270
2024-01-11T08:05:15.375825
GPL-3.0
false
425ec4dc7928e4240ed37a5315877eab
//===--- WorkspaceGenerator.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct WorkspaceGenerator {\n var elements: [Element] = []\n public init() {}\n}\n\npublic extension WorkspaceGenerator {\n enum Element {\n case xcodeProj(GeneratedProject)\n case group(RelativePath, targets: [String])\n }\n\n mutating func addProject(_ proj: GeneratedProject) {\n elements.append(.xcodeProj(proj))\n }\n mutating func addGroup(at path: RelativePath, targets: [String]) {\n elements.append(.group(path, targets: targets))\n }\n\n func write(_ name: String, into dir: AbsolutePath) throws {\n var contents = """\n <?xml version="1.0" encoding="UTF-8"?>\n <Workspace version = "1.0">\n\n """\n for element in elements {\n contents += "<FileRef location = "\n switch element {\n case .xcodeProj(let proj):\n // FIXME: This is assuming the workspace will be siblings with the\n // project.\n contents += "\"container:\(proj.path.fileName)\""\n case .group(let path, _):\n contents += "\"group:\(path)\""\n }\n contents += "></FileRef>\n"\n }\n contents += "</Workspace>"\n\n let workspaceDir = dir.appending("\(name).xcworkspace")\n\n // Skip generating if there's only a single container and it doesn't already\n // exist.\n guard elements.count > 1 || workspaceDir.exists else { return }\n\n let dataPath = workspaceDir.appending("contents.xcworkspacedata")\n try dataPath.write(contents)\n log.info("Generated '\(dataPath)'")\n\n var schemes = SchemeGenerator(in: workspaceDir)\n let buildTargets = elements\n .sorted(by: {\n // Sort project schemes first.\n switch ($0, $1) {\n case (.xcodeProj, .group):\n return true\n default:\n return false\n }\n })\n .flatMap { elt in\n switch elt {\n case .xcodeProj(let proj):\n return proj.allBuildTargets\n case .group(let path, let targets):\n return targets.map { target in\n Scheme.BuildTarget(target, in: path)\n }\n }\n }\n schemes.add(Scheme(\n "ALL", replaceExisting: true, buildTargets: buildTargets\n ))\n try schemes.write()\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_WorkspaceGenerator.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Generator_WorkspaceGenerator.swift
Swift
2,634
0.8
0.103448
0.205128
node-utils
370
2025-02-07T07:57:44.240584
Apache-2.0
false
66c93e5391fc243df12f5856b5138f0d
//===--- AnsiColor.swift - ANSI formatting control codes ------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2022-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Provides ANSI support via Swift string interpolation.\n//\n//===----------------------------------------------------------------------===//\n\n// https://github.com/apple/swift/blob/f08f86c7/stdlib/public/libexec/swift-backtrace/AnsiColor.swift\nenum AnsiColor {\n case normal\n case black\n case red\n case green\n case yellow\n case blue\n case magenta\n case cyan\n case white\n case gray\n case brightRed\n case brightGreen\n case brightYellow\n case brightBlue\n case brightMagenta\n case brightCyan\n case brightWhite\n case rgb(r: Int, g: Int, b: Int)\n case grayscale(Int)\n\n var foregroundCode: String {\n switch self {\n case .normal: return "39"\n case .black: return "30"\n case .red: return "31"\n case .green: return "32"\n case .yellow: return "33"\n case .blue: return "34"\n case .cyan: return "35"\n case .magenta: return "36"\n case .white: return "37"\n case .gray: return "90"\n case .brightRed: return "91"\n case .brightGreen: return "92"\n case .brightYellow: return "93"\n case .brightBlue: return "94"\n case .brightCyan: return "95"\n case .brightMagenta: return "96"\n case .brightWhite: return "97"\n case let .rgb(r, g, b):\n let ndx = 16 + 36 * r + 6 * g + b\n return "38;5;\(ndx)"\n case let .grayscale(g):\n let ndx = 232 + g\n return "38;5;\(ndx)"\n }\n }\n\n var backgroundCode: String {\n switch self {\n case .normal: return "49"\n case .black: return "40"\n case .red: return "41"\n case .green: return "42"\n case .yellow: return "43"\n case .blue: return "44"\n case .cyan: return "45"\n case .magenta: return "46"\n case .white: return "47"\n case .gray: return "100"\n case .brightRed: return "101"\n case .brightGreen: return "102"\n case .brightYellow: return "103"\n case .brightBlue: return "104"\n case .brightCyan: return "105"\n case .brightMagenta: return "106"\n case .brightWhite: return "107"\n case let .rgb(r, g, b):\n let ndx = 16 + 36 * r + 6 * g + b\n return "48;5;\(ndx)"\n case let .grayscale(g):\n let ndx = 232 + g\n return "48;5;\(ndx)"\n }\n }\n}\n\nenum AnsiWeight {\n case normal\n case bold\n case faint\n\n var code: String {\n switch self {\n case .normal: "22"\n case .bold: "1"\n case .faint: "2"\n }\n }\n}\n\nenum AnsiAttribute {\n case fg(AnsiColor)\n case bg(AnsiColor)\n case weight(AnsiWeight)\n case inverse(Bool)\n}\n\nextension DefaultStringInterpolation {\n mutating func appendInterpolation(ansi attrs: AnsiAttribute...) {\n var code = "\u{1b}["\n var first = true\n for attr in attrs {\n if first {\n first = false\n } else {\n code += ";"\n }\n\n switch attr {\n case let .fg(color):\n code += color.foregroundCode\n case let .bg(color):\n code += color.backgroundCode\n case let .weight(weight):\n code += weight.code\n case let .inverse(enabled):\n if enabled {\n code += "7"\n } else {\n code += "27"\n }\n }\n }\n code += "m"\n\n appendInterpolation(code)\n }\n\n mutating func appendInterpolation(fg: AnsiColor) {\n appendInterpolation(ansi: .fg(fg))\n }\n mutating func appendInterpolation(bg: AnsiColor) {\n appendInterpolation(ansi: .bg(bg))\n }\n mutating func appendInterpolation(weight: AnsiWeight) {\n appendInterpolation(ansi: .weight(weight))\n }\n mutating func appendInterpolation(inverse: Bool) {\n appendInterpolation(ansi: .inverse(inverse))\n }\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Logging_AnsiColor.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Logging_AnsiColor.swift
Swift
4,320
0.8
0.055901
0.106667
python-kit
265
2024-01-01T18:51:23.630018
Apache-2.0
false
a08144c028ac9c7f622b6ec8b431ae3b
//===--- Logger.swift -----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic final class Logger: @unchecked Sendable {\n private let stateLock = Lock()\n private let outputLock = Lock()\n\n private var _hadError = false\n public var hadError: Bool {\n get { stateLock.withLock { _hadError } }\n set { stateLock.withLock { _hadError = newValue } }\n }\n\n private var _logLevel: LogLevel = .debug\n public var logLevel: LogLevel {\n get { stateLock.withLock { _logLevel } }\n set { stateLock.withLock { _logLevel = newValue } }\n }\n\n private var _useColor: Bool = true\n public var useColor: Bool {\n get { stateLock.withLock { _useColor } }\n set { stateLock.withLock { _useColor = newValue } }\n }\n\n private var _output: LoggableStream?\n public var output: LoggableStream? {\n get { stateLock.withLock { _output } }\n set { stateLock.withLock { _output = newValue } }\n }\n\n public init() {}\n}\n\nextension Logger {\n public enum LogLevel: Comparable {\n /// A message with information that isn't useful to the user, but is\n /// useful when debugging issues.\n case debug\n\n /// A message with mundane information that may be useful to know if\n /// you're interested in verbose output, but is otherwise unimportant.\n case info\n\n /// A message with information that does not require any intervention from\n /// the user, but is nonetheless something they may want to be aware of.\n case note\n\n /// A message that describes an issue that ought to be resolved by the\n /// user, but still allows the program to exit successfully.\n case warning\n\n /// A message that describes an issue where the program cannot exit\n /// successfully.\n case error\n }\n\n private func log(_ message: @autoclosure () -> String, level: LogLevel) {\n guard level >= logLevel else { return }\n let output = self.output ?? FileHandleStream.stderr\n let useColor = self.useColor && output.supportsColor\n outputLock.withLock {\n level.write(to: output, useColor: useColor)\n output.write(": \(message())\n")\n }\n }\n\n public func debug(_ message: @autoclosure () -> String) {\n log(message(), level: .debug)\n }\n\n public func info(_ message: @autoclosure () -> String) {\n log(message(), level: .info)\n }\n\n public func note(_ message: @autoclosure () -> String) {\n log(message(), level: .note)\n }\n\n public func warning(_ message: @autoclosure () -> String) {\n log(message(), level: .warning)\n }\n\n public func error(_ message: @autoclosure () -> String) {\n hadError = true\n log(message(), level: .error)\n }\n}\n\npublic protocol Loggable {\n func write(to stream: LoggableStream, useColor: Bool)\n}\n\nextension Logger.LogLevel: Loggable, CustomStringConvertible {\n public var description: String {\n switch self {\n case .debug: "debug"\n case .info: "info"\n case .note: "note"\n case .warning: "warning"\n case .error: "error"\n }\n }\n private var ansiColor: AnsiColor {\n switch self {\n case .debug: .magenta\n case .info: .blue\n case .note: .brightCyan\n case .warning: .brightYellow\n case .error: .brightRed\n }\n }\n public func write(to stream: LoggableStream, useColor: Bool) {\n let str = useColor \n ? "\(fg: ansiColor)\(weight: .bold)\(self)\(fg: .normal)\(weight: .normal)"\n : "\(self)"\n stream.write(str)\n }\n}\n\npublic protocol LoggableStream: Sendable {\n var supportsColor: Bool { get }\n func write(_: String)\n}\n\n/// Check whether $TERM supports color. Ideally we'd consult terminfo, but\n/// there aren't any particularly nice APIs for that in the SDK AFAIK. We could\n/// shell out to tput, but that adds ~100ms of overhead which I don't think is\n/// worth it. This simple check (taken from LLVM) is good enough for now.\nfileprivate let termSupportsColor: Bool = {\n guard let termEnv = getenv("TERM") else { return false }\n switch String(cString: termEnv) {\n case "ansi", "cygwin", "linux":\n return true\n case let term where\n term.hasPrefix("screen") ||\n term.hasPrefix("xterm") ||\n term.hasPrefix("vt100") ||\n term.hasPrefix("rxvt") ||\n term.hasSuffix("color"):\n return true\n default:\n return false\n }\n}()\n\npublic struct FileHandleStream: LoggableStream, @unchecked Sendable {\n public let handle: UnsafeMutablePointer<FILE>\n public let supportsColor: Bool\n\n public init(_ handle: UnsafeMutablePointer<FILE>) {\n self.handle = handle\n self.supportsColor = isatty(fileno(handle)) != 0 && termSupportsColor\n }\n public func write(_ string: String) {\n fputs(string, handle)\n }\n}\n\nextension FileHandleStream {\n static let stdout = Self(Darwin.stdout)\n static let stderr = Self(Darwin.stderr)\n}\n\npublic let log = Logger()\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Logging_Logger.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Logging_Logger.swift
Swift
5,170
0.95
0.051136
0.166667
react-lib
534
2024-03-26T22:28:00.743283
BSD-3-Clause
false
3b76444c307d8823ec5c0dbd5707e3ed
//===--- BuildConfiguration.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic enum BuildConfiguration: String {\n case release = "Release"\n case releaseWithDebugInfo = "RelWithDebInfo"\n case debug = "Debug"\n}\n\nextension BuildConfiguration {\n public var hasDebugInfo: Bool {\n switch self {\n case .release:\n false\n case .releaseWithDebugInfo, .debug:\n true\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Ninja_BuildConfiguration.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Ninja_BuildConfiguration.swift
Swift
831
0.8
0.107143
0.423077
awesome-app
168
2024-10-15T18:14:14.234625
GPL-3.0
false
b9de3fad7f34e83591865598f004c444
//===--- NinjaBuildDir.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic final class NinjaBuildDir: Sendable {\n public let path: AbsolutePath\n public let projectRootDir: AbsolutePath\n private let _tripleSuffix: Result<String, Error>\n\n private let repoBuildDirs = MutexBox<[Repo: RepoBuildDir]>()\n\n private static func detectTripleSuffix(\n buildDir: AbsolutePath\n ) -> Result<String, Error> {\n Result {\n for dir in try buildDir.getDirContents() {\n guard buildDir.appending(dir).isDirectory,\n let triple = dir.fileName.tryDropPrefix("swift-") else {\n continue\n }\n return triple\n }\n let couldBeParent = buildDir.fileName.hasPrefix("swift-")\n throw XcodeGenError.noSwiftBuildDir(buildDir, couldBeParent: couldBeParent)\n }\n }\n\n public var tripleSuffix: String {\n get throws {\n try _tripleSuffix.get()\n }\n }\n\n // We can infer the project root from the location of swift-xcodegen itself.\n // 1 2 3 4 5 6 7\n // #filePath = <root>/swift/utils/swift-xcodegen/Sources/SwiftXcodeGen/Ninja/NinjaBuildDir.swift\n private static let inferredProjectRootPath = AbsolutePath(#filePath).dropLast(7)\n\n private static func detectProjectRoot() throws -> AbsolutePath {\n let inferredSwiftPath = inferredProjectRootPath.appending(Repo.swift.relativePath)\n guard inferredSwiftPath.exists else {\n throw XcodeGenError.couldNotInferProjectRoot(\n reason: "expected swift repo at '\(inferredSwiftPath)'"\n )\n }\n return inferredProjectRootPath\n }\n \n public init(at path: AbsolutePath, projectRootDir: AbsolutePath?) throws {\n guard path.exists else {\n throw XcodeGenError.pathNotFound(path)\n }\n self.path = path\n self._tripleSuffix = Self.detectTripleSuffix(buildDir: path)\n self.projectRootDir = try projectRootDir ?? Self.detectProjectRoot()\n }\n \n public func buildDir(for repo: Repo) throws -> RepoBuildDir {\n try repoBuildDirs.withLock { repoBuildDirs in\n if let buildDir = repoBuildDirs[repo] {\n return buildDir\n }\n let dir = try RepoBuildDir(repo, for: self)\n repoBuildDirs[repo] = dir\n return dir\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Ninja_NinjaBuildDir.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Ninja_NinjaBuildDir.swift
Swift
2,682
0.95
0.157895
0.205882
node-utils
92
2023-08-19T03:05:29.532455
BSD-3-Clause
false
349b53a671ad27a56ec910c0154f8970
//===--- NinjaParser.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct NinjaParser {\n private let filePath: AbsolutePath\n private let fileReader: (AbsolutePath) throws -> Data\n private var lexer: Lexer\n\n private init(input: UnsafeRawBufferPointer, filePath: AbsolutePath, fileReader: @escaping (AbsolutePath) throws -> Data) throws {\n self.filePath = filePath\n self.fileReader = fileReader\n self.lexer = Lexer(ByteScanner(input))\n }\n\n static func parse(filePath: AbsolutePath, fileReader: @escaping (AbsolutePath) throws -> Data = { try $0.read() }) throws -> NinjaBuildFile {\n\n try fileReader(filePath).withUnsafeBytes { bytes in\n var parser = try Self(input: bytes, filePath: filePath, fileReader: fileReader)\n return try parser.parse()\n }\n }\n}\n\nfileprivate enum NinjaParseError: Error {\n case expected(NinjaParser.Lexeme)\n}\n\nfileprivate extension ByteScanner {\n mutating func consumeUnescaped(\n while pred: (Byte) -> Bool\n ) -> String? {\n let bytes = consume(using: { consumer in\n guard let c = consumer.peek, pred(c) else { return false }\n\n // Ninja uses '$' as the escape character.\n if c == "$" {\n switch consumer.peek(ahead: 1) {\n case "$", ":", \.isSpaceOrTab:\n // Skip the '$' and take the unescaped character.\n consumer.skip()\n return consumer.eat()\n case \.isNewline:\n // This is a line continuation, skip the newline, and strip any\n // following space.\n consumer.skip(untilAfter: \.isNewline)\n consumer.skip(while: \.isSpaceOrTab)\n return true\n default:\n // Unknown escape sequence, treat the '$' literally.\n break\n }\n }\n return consumer.eat()\n })\n return bytes.isEmpty ? nil : String(utf8: bytes)\n }\n}\n\nfileprivate extension NinjaParser {\n typealias Rule = NinjaBuildFile.Rule\n typealias BuildEdge = NinjaBuildFile.BuildEdge\n\n struct ParsedBinding: Hashable {\n var key: String\n var value: String\n }\n\n enum Lexeme: Hashable {\n case binding(ParsedBinding)\n case element(String)\n case rule\n case build\n case include\n case newline\n case colon\n case equal\n case pipe\n case doublePipe\n }\n\n struct Lexer {\n private var input: ByteScanner\n private(set) var lexeme: Lexeme?\n private(set) var isAtStartOfLine = true\n private(set) var leadingTriviaCount = 0\n\n init(_ input: ByteScanner) {\n self.input = input\n self.lexeme = lex()\n }\n }\n\n var peek: Lexeme? { lexer.lexeme }\n\n @discardableResult\n mutating func tryEat(_ lexeme: Lexeme) -> Bool {\n guard peek == lexeme else { return false }\n eat()\n return true\n }\n\n mutating func tryEatElement() -> String? {\n guard case .element(let str) = peek else { return nil }\n eat()\n return str\n }\n\n @discardableResult\n mutating func eat() -> Lexeme? {\n defer {\n lexer.eat()\n }\n return peek\n }\n}\n\nfileprivate extension Byte {\n var isNinjaOperator: Bool {\n switch self {\n case ":", "|", "=":\n true\n default:\n false\n }\n }\n}\n\nextension NinjaParser.Lexer {\n typealias Lexeme = NinjaParser.Lexeme\n\n private mutating func consumeOperator() -> Lexeme {\n switch input.eat() {\n case ":":\n return .colon\n case "=":\n return .equal\n case "|":\n if input.tryEat("|") {\n return .doublePipe\n }\n return .pipe\n default:\n fatalError("Invalid operator character")\n }\n }\n\n private mutating func consumeElement() -> String? {\n input.consumeUnescaped(while: { char in\n switch char {\n case \.isNinjaOperator, \.isSpaceTabOrNewline:\n false\n default:\n true\n }\n })\n }\n\n private mutating func tryConsumeBinding(key: String) -> Lexeme? {\n input.tryEating { input in\n input.skip(while: \.isSpaceOrTab)\n guard input.tryEat("=") else { return nil }\n input.skip(while: \.isSpaceOrTab)\n guard let value = input.consumeUnescaped(while: { !$0.isNewline }) else {\n return nil\n }\n return .binding(.init(key: key, value: value))\n }\n }\n\n private mutating func lex() -> Lexeme? {\n while true {\n isAtStartOfLine = input.previous?.isNewline ?? true\n leadingTriviaCount = input.eat(while: \.isSpaceOrTab)?.count ?? 0\n\n guard let c = input.peek else { return nil }\n if c == "#" {\n input.skip(untilAfter: \.isNewline)\n continue\n }\n if c.isNewline {\n input.skip(untilAfter: \.isNewline)\n if isAtStartOfLine {\n // Ignore empty lines, newlines are only semantically meaningful\n // when they delimit non-empty lines.\n continue\n }\n return .newline\n }\n if c.isNinjaOperator {\n return consumeOperator()\n }\n if isAtStartOfLine {\n // decl keywords.\n if input.tryEat(utf8: "build") {\n return .build\n }\n if input.tryEat(utf8: "rule") {\n return .rule\n }\n if input.tryEat(utf8: "include") {\n return .include\n }\n }\n guard let element = consumeElement() else { return nil }\n\n // If we're on a newline, check to see if we can lex a binding.\n if isAtStartOfLine {\n if let binding = tryConsumeBinding(key: element) {\n return binding\n }\n }\n return .element(element)\n }\n }\n\n @discardableResult\n mutating func eat() -> Lexeme? {\n defer {\n lexeme = lex()\n }\n return lexeme\n }\n}\n\nfileprivate extension NinjaParser {\n mutating func skipLine() {\n while let lexeme = eat(), lexeme != .newline {}\n }\n\n mutating func parseBinding() throws -> ParsedBinding? {\n guard case let .binding(binding) = peek else { return nil }\n eat()\n tryEat(.newline)\n return binding\n }\n\n /// ```\n /// rule rulename\n /// command = ...\n /// var = ...\n /// ```\n mutating func parseRule() throws -> Rule? {\n let indent = lexer.leadingTriviaCount\n guard tryEat(.rule) else { return nil }\n\n guard let ruleName = tryEatElement() else {\n throw NinjaParseError.expected(.element("<rule name>"))\n }\n guard tryEat(.newline) else {\n throw NinjaParseError.expected(.newline)\n }\n\n var bindings: [String: String] = [:]\n while indent < lexer.leadingTriviaCount, let binding = try parseBinding() {\n bindings[binding.key] = binding.value\n }\n\n return Rule(name: ruleName, bindings: bindings)\n }\n\n /// ```\n /// build out1... | implicit-out... : rulename input... | dep... || order-only-dep...\n /// var = ...\n /// ```\n mutating func parseBuildEdge() throws -> BuildEdge? {\n let indent = lexer.leadingTriviaCount\n guard tryEat(.build) else { return nil }\n\n var outputs: [String] = []\n while let str = tryEatElement() {\n outputs.append(str)\n }\n\n // Ignore implicit outputs for now.\n if tryEat(.pipe) {\n while tryEatElement() != nil {}\n }\n\n guard tryEat(.colon) else {\n throw NinjaParseError.expected(.colon)\n }\n\n guard let ruleName = tryEatElement() else {\n throw NinjaParseError.expected(.element("<rule name>"))\n }\n\n var inputs: [String] = []\n while let str = tryEatElement() {\n inputs.append(str)\n }\n\n if ruleName == "phony" {\n skipLine()\n return .phony(for: outputs, inputs: inputs)\n }\n\n var dependencies: [String] = []\n while true {\n if let str = tryEatElement() {\n dependencies.append(str)\n continue\n }\n if tryEat(.pipe) || tryEat(.doublePipe) {\n // Currently we don't distinguish between implicit deps and order-only deps.\n continue\n }\n break\n }\n\n // We're done with the line, skip to the next.\n skipLine()\n\n var bindings: [String: String] = [:]\n while indent < lexer.leadingTriviaCount, let binding = try parseBinding() {\n bindings[binding.key] = binding.value\n }\n\n return BuildEdge(\n ruleName: ruleName,\n inputs: inputs,\n outputs: outputs,\n dependencies: dependencies,\n bindings: bindings\n )\n }\n\n /// ```\n /// include path/to/sub.ninja\n /// ```\n mutating func parseInclude() throws -> NinjaBuildFile? {\n guard tryEat(.include) else { return nil }\n\n guard let fileName = tryEatElement() else {\n throw NinjaParseError.expected(.element("<path>"))\n }\n\n let baseDirectory = self.filePath.parentDir!\n let path = AnyPath(fileName).absolute(in: baseDirectory)\n return try NinjaParser.parse(filePath: path, fileReader: fileReader)\n }\n\n mutating func parse() throws -> NinjaBuildFile {\n var bindings: [String: String] = [:]\n var rules: [String: Rule] = [:]\n var buildEdges: [BuildEdge] = []\n while peek != nil {\n if let rule = try parseRule() {\n rules[rule.name] = rule\n continue\n }\n if let edge = try parseBuildEdge() {\n buildEdges.append(edge)\n continue\n }\n if let binding = try parseBinding() {\n bindings[binding.key] = binding.value\n continue\n }\n if let included = try parseInclude() {\n bindings.merge(included.bindings.values, uniquingKeysWith: { _, other in other })\n rules.merge(included.rules, uniquingKeysWith: { _, other in other })\n buildEdges.append(contentsOf: included.buildEdges)\n continue\n }\n // Ignore unknown bits of syntax like 'subninja' for now.\n eat()\n }\n return NinjaBuildFile(bindings: bindings, rules: rules, buildEdges: buildEdges)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Ninja_NinjaParser.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Ninja_NinjaParser.swift
Swift
9,961
0.95
0.149606
0.107784
vue-tools
696
2024-04-12T08:31:42.928061
MIT
false
8626a45991c496f5860f09f3de9e0e99
//===--- RepoBuildDir.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic final class RepoBuildDir: Sendable {\n public let projectRootDir: AbsolutePath\n public let repo: Repo\n public let path: AbsolutePath\n public let repoPath: AbsolutePath\n public let repoRelativePath: RelativePath\n\n private let repoDirCache: DirectoryCache\n\n private let _ninjaFile = MutexBox<NinjaBuildFile?>()\n private let _runnableTargets = MutexBox<RunnableTargets?>()\n private let _clangArgs = MutexBox<ClangBuildArgsProvider?>()\n private let _swiftTargets = MutexBox<SwiftTargets?>()\n\n init(_ repo: Repo, for parent: NinjaBuildDir) throws {\n self.projectRootDir = parent.projectRootDir\n self.repo = repo\n self.path = try repo.buildDirPrefix.map { prefix in\n parent.path.appending("\(prefix)-\(try parent.tripleSuffix)")\n } ?? parent.path\n self.repoRelativePath = repo.relativePath\n self.repoPath = projectRootDir.appending(repo.relativePath)\n self.repoDirCache = DirectoryCache(root: repoPath)\n\n guard self.path.exists else {\n throw XcodeGenError.pathNotFound(self.path)\n }\n guard self.repoPath.exists else {\n throw XcodeGenError.pathNotFound(self.repoPath)\n }\n }\n}\n\nextension RepoBuildDir {\n var clangArgs: ClangBuildArgsProvider {\n get throws {\n try _clangArgs.withLock { _clangArgs in\n if let clangArgs = _clangArgs {\n return clangArgs\n }\n let clangArgs = try ClangBuildArgsProvider(for: self)\n _clangArgs = clangArgs\n return clangArgs\n }\n }\n }\n\n var swiftTargets: SwiftTargets {\n get throws {\n try _swiftTargets.withLock { _swiftTargets in\n if let swiftTargets = _swiftTargets {\n return swiftTargets\n }\n let swiftTargets = try SwiftTargets(for: self)\n _swiftTargets = swiftTargets\n return swiftTargets\n }\n }\n }\n\n var ninjaFile: NinjaBuildFile {\n get throws {\n try _ninjaFile.withLock { _ninjaFile in\n if let ninjaFile = _ninjaFile {\n return ninjaFile\n }\n let fileName = path.appending("build.ninja")\n guard fileName.exists else {\n throw XcodeGenError.pathNotFound(fileName)\n }\n\n log.debug("[*] Reading '\(fileName)'")\n let ninjaFile = try NinjaParser.parse(filePath: fileName)\n _ninjaFile = ninjaFile\n return ninjaFile\n }\n }\n }\n\n var runnableTargets: RunnableTargets {\n get throws {\n try _runnableTargets.withLock { _runnableTargets in\n if let runnableTargets = _runnableTargets {\n return runnableTargets\n }\n\n let runnableTargets = try RunnableTargets(from: self)\n _runnableTargets = runnableTargets\n return runnableTargets\n }\n }\n }\n\n public var buildConfiguration: BuildConfiguration? {\n get throws {\n try ninjaFile.buildConfiguration\n }\n }\n\n func getAllRepoSubpaths(of parent: RelativePath) throws -> [RelativePath] {\n try repoDirCache.getAllSubpaths(of: parent)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Ninja_RepoBuildDir.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Ninja_RepoBuildDir.swift
Swift
3,459
0.95
0.191304
0.107843
python-kit
503
2024-04-29T17:07:31.726715
GPL-3.0
false
2b9856dc904f6be2939b5943cf9798b8
//===--- AbsolutePath.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport System\n\npublic struct AbsolutePath: PathProtocol, Sendable {\n public let storage: FilePath\n public init(_ storage: FilePath) {\n precondition(\n storage.isAbsolute, "'Expected \(storage)' to be an absolute path"\n )\n self.storage = storage.lexicallyNormalized()\n }\n public var asAnyPath: AnyPath {\n .absolute(self)\n }\n}\n\npublic extension AbsolutePath {\n var isDirectory: Bool {\n var isDir: ObjCBool = false\n guard FileManager.default.fileExists(atPath: rawPath, isDirectory: &isDir)\n else {\n return false\n }\n return isDir.boolValue\n }\n\n func getDirContents() throws -> [RelativePath] {\n try FileManager.default.contentsOfDirectory(atPath: rawPath).map { .init($0) }\n }\n\n var exists: Bool {\n FileManager.default.fileExists(atPath: rawPath)\n }\n\n var isExecutable: Bool {\n FileManager.default.isExecutableFile(atPath: rawPath)\n }\n\n var isSymlink: Bool {\n (try? FileManager.default.destinationOfSymbolicLink(atPath: rawPath)) != nil\n }\n\n var resolvingSymlinks: Self {\n guard let resolved = realpath(rawPath, nil) else { return self }\n defer {\n free(resolved)\n }\n return Self(String(cString: resolved))\n }\n\n func makeDir(withIntermediateDirectories: Bool = true) throws {\n try FileManager.default.createDirectory(\n atPath: rawPath, withIntermediateDirectories: withIntermediateDirectories)\n }\n\n func remove() {\n try? FileManager.default.removeItem(atPath: rawPath)\n }\n\n func symlink(to dest: AbsolutePath) throws {\n try parentDir?.makeDir()\n if isSymlink {\n remove()\n }\n try FileManager.default.createSymbolicLink(\n atPath: rawPath, withDestinationPath: dest.rawPath\n )\n }\n\n func read() throws -> Data {\n try Data(contentsOf: URL(fileURLWithPath: rawPath))\n }\n\n func write(_ data: Data, as encoding: String.Encoding = .utf8) throws {\n try parentDir?.makeDir()\n FileManager.default.createFile(atPath: rawPath, contents: data)\n }\n\n func write(_ contents: String, as encoding: String.Encoding = .utf8) throws {\n try write(contents.data(using: encoding)!)\n }\n}\n\nextension AbsolutePath: ExpressibleByStringLiteral, ExpressibleByStringInterpolation {\n public init(stringLiteral value: StringLiteralType) {\n self.init(value)\n }\n}\n\nextension AbsolutePath: Decodable {\n public init(from decoder: Decoder) throws {\n let storage = FilePath(\n try decoder.singleValueContainer().decode(String.self)\n )\n guard storage.isAbsolute else {\n struct NotAbsoluteError: Error, Sendable {\n let path: FilePath\n }\n throw NotAbsoluteError(path: storage)\n }\n self.init(storage)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_AbsolutePath.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_AbsolutePath.swift
Swift
3,178
0.95
0.113043
0.111111
python-kit
764
2023-08-16T10:04:16.543237
BSD-3-Clause
false
57d7e31bc1c3ada62cd3b0a4bb678459
//===--- AnyPath.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport System\n\npublic enum AnyPath: PathProtocol, Sendable {\n case relative(RelativePath)\n case absolute(AbsolutePath)\n\n public init<P: PathProtocol>(_ path: P) {\n self = path.asAnyPath\n }\n\n public init(_ storage: FilePath) {\n if storage.isAbsolute {\n self = .absolute(.init(storage))\n } else {\n self = .relative(.init(storage))\n }\n }\n\n public var storage: FilePath {\n switch self {\n case .relative(let r):\n r.storage\n case .absolute(let a):\n a.storage\n }\n }\n\n public var asAnyPath: AnyPath {\n self\n }\n}\n\nextension AnyPath {\n public var absoluteInWorkingDir: AbsolutePath {\n switch self {\n case .relative(let r):\n r.absoluteInWorkingDir\n case .absolute(let a):\n a\n }\n }\n\n public func absolute(in base: AbsolutePath) -> AbsolutePath {\n switch self {\n case .relative(let r):\n r.absolute(in: base)\n case .absolute(let a):\n a\n }\n }\n}\n\nextension AnyPath: Decodable {\n public init(from decoder: Decoder) throws {\n self.init(try decoder.singleValueContainer().decode(String.self))\n }\n}\n\nextension AnyPath: ExpressibleByArgument {\n public init(argument rawPath: String) {\n self.init(rawPath)\n }\n}\n\nextension StringProtocol {\n func hasExtension(_ ext: FileExtension) -> Bool {\n FilePath(String(self)).extension == ext.rawValue\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_AnyPath.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_AnyPath.swift
Swift
1,878
0.95
0.085366
0.15493
awesome-app
267
2025-05-12T22:38:11.351100
GPL-3.0
false
1f773c2d53f47c5f9669063cde600d4b
//===--- DirectoryCache.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A simple cache for the recursive contents of a directory under a given\n/// root path. This is pretty basic and doesn't handle cases where we've already\n/// cached the parent.\nstruct DirectoryCache {\n private let root: AbsolutePath\n private let storage = MutexBox<[RelativePath: [RelativePath]]>()\n\n init(root: AbsolutePath) {\n self.root = root\n }\n\n func getAllSubpaths(of path: RelativePath) throws -> [RelativePath] {\n if let result = storage.withLock(\.[path]) {\n return result\n }\n let absPath = root.appending(path).rawPath\n let result = try FileManager.default.subpathsOfDirectory(atPath: absPath)\n .map { path.appending($0) }\n storage.withLock { storage in\n storage[path] = result\n }\n return result\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_DirectoryCache.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_DirectoryCache.swift
Swift
1,290
0.95
0.131579
0.411765
node-utils
480
2024-09-07T10:48:01.479416
Apache-2.0
false
b5d7aa3fc5d83c8394705e08531dad76
//===--- FileExtension.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic enum FileExtension: String {\n case c\n case cpp\n case def\n case gyb\n case h\n case m\n case md\n case mm\n case modulemap\n case o\n case rst\n case swift\n case swiftmodule\n case td\n case xcodeproj\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_FileExtension.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_FileExtension.swift
Swift
727
0.8
0.103448
0.392857
node-utils
576
2024-09-27T23:34:52.466295
GPL-3.0
false
135ebf932ffeaad86b71a08c2d3a0797
//===--- PathProtocol.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport System\n\npublic protocol PathProtocol: Hashable, CustomStringConvertible {\n var storage: FilePath { get }\n var asAnyPath: AnyPath { get }\n init(_ storage: FilePath)\n}\n\npublic extension PathProtocol {\n typealias Component = FilePath.Component\n\n var parentDir: Self? {\n // Remove the last component and check to see if it's empty.\n var result = storage\n guard result.removeLastComponent(), !result.isEmpty else { return nil }\n return Self(result)\n }\n\n /// Drops the last `n` components, or all components if `n` is greater\n /// than the number of components.\n func dropLast(_ n: Int = 1) -> Self {\n Self(FilePath(root: storage.root, storage.components.dropLast(n)))\n }\n\n var fileName: String {\n storage.lastComponent?.string ?? ""\n }\n\n var isEmpty: Bool {\n storage.isEmpty\n }\n\n func appending(_ relPath: RelativePath) -> Self {\n Self(storage.pushing(relPath.storage))\n }\n\n func appending(_ str: String) -> Self {\n Self(storage.appending(str))\n }\n\n func commonAncestor(with other: Self) -> Self {\n precondition(storage.root == other.storage.root)\n var result = [Component]()\n for (comp, otherComp) in zip(components, other.components) {\n guard comp == otherComp else { break }\n result.append(comp)\n }\n return Self(FilePath(root: storage.root, result))\n }\n\n /// Attempt to remove `other` as a prefix of `self`, or `nil` if `other` is\n /// not a prefix of `self`.\n func removingPrefix(_ other: Self) -> RelativePath? {\n var result = storage\n guard result.removePrefix(other.storage) else { return nil }\n return RelativePath(result)\n }\n\n func hasExtension(_ ext: FileExtension) -> Bool {\n storage.extension == ext.rawValue\n }\n func hasExtension(_ exts: FileExtension...) -> Bool {\n // Note that querying `.extension` involves re-parsing, so only do it\n // once here.\n let ext = storage.extension\n return exts.contains(where: { ext == $0.rawValue })\n }\n\n func starts(with other: Self) -> Bool {\n self.storage.starts(with: other.storage)\n }\n\n var components: FilePath.ComponentView {\n storage.components\n }\n\n var description: String { storage.string }\n\n init(stringLiteral value: String) {\n self.init(value)\n }\n\n init(_ rawPath: String) {\n self.init(FilePath(rawPath))\n }\n\n var rawPath: String {\n storage.string\n }\n\n func escaped(addQuotesIfNeeded: Bool) -> String {\n rawPath.escaped(addQuotesIfNeeded: addQuotesIfNeeded)\n }\n\n var escaped: String {\n rawPath.escaped\n }\n}\n\nextension PathProtocol {\n /// Whether this is a .swift.gyb file.\n var isSwiftGyb: Bool {\n hasExtension(.gyb) && rawPath.dropLast(4).hasExtension(.swift)\n }\n\n var isHeaderLike: Bool {\n if hasExtension(.h, .def, .td, .modulemap) {\n return true\n }\n // Consider all gyb files to be header-like, except .swift.gyb, which\n // will be handled separately when creating Swift targets.\n if hasExtension(.gyb) && !isSwiftGyb {\n return true\n }\n return false\n }\n\n var isCSourceLike: Bool {\n hasExtension(.c, .cpp, .m, .mm)\n }\n\n var isSourceLike: Bool {\n isCSourceLike || hasExtension(.swift)\n }\n\n var isDocLike: Bool {\n hasExtension(.md, .rst) || fileName.starts(with: "README")\n }\n}\n\nextension Collection where Element: PathProtocol {\n /// Computes the common parent for a collection of paths. If there is only\n /// a single unique path, this returns the parent for that path.\n var commonAncestor: Element? {\n guard let first = self.first else { return nil }\n let result = dropFirst().reduce(first, { $0.commonAncestor(with: $1) })\n return result == first ? result.parentDir : result\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_PathProtocol.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_PathProtocol.swift
Swift
4,167
0.95
0.072848
0.184
node-utils
843
2024-03-22T08:56:45.051842
Apache-2.0
false
65bcc96e8fd2257783c6d9dbe3f973be
//===--- RelativePath.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport System\n\npublic struct RelativePath: PathProtocol, Sendable {\n public let storage: FilePath\n public init(_ storage: FilePath) {\n precondition(\n storage.isRelative, "Expected '\(storage)' to be a relative path"\n )\n self.storage = storage.lexicallyNormalized()\n }\n\n private init(normalizedComponents: FilePath.ComponentView.SubSequence) {\n // Already normalized, no need to do it ourselves.\n self.storage = FilePath(root: nil, normalizedComponents)\n }\n\n public var asAnyPath: AnyPath {\n .relative(self)\n }\n}\n\npublic extension RelativePath {\n var absoluteInWorkingDir: AbsolutePath {\n .init(FileManager.default.currentDirectoryPath).appending(self)\n }\n\n func absolute(in base: AbsolutePath) -> AbsolutePath {\n precondition(base.isDirectory, "Expected '\(base)' to be a directory")\n return base.appending(self)\n }\n\n init(_ component: Component) {\n self.init(FilePath(root: nil, components: component))\n }\n\n /// Incrementally stacked components of the path, starting at the parent.\n /// e.g for a/b/c, returns [a, a/b, a/b/c].\n @inline(__always)\n var stackedComponents: [RelativePath] {\n let components = self.components\n var stackedComponents: [RelativePath] = []\n var index = components.startIndex\n while index != components.endIndex {\n stackedComponents.append(\n RelativePath(normalizedComponents: components[...index])\n )\n components.formIndex(after: &index)\n }\n return stackedComponents\n }\n}\n\nextension RelativePath: ExpressibleByStringLiteral, ExpressibleByStringInterpolation {\n public init(stringLiteral value: String) {\n self.init(value)\n }\n}\n\nextension RelativePath: Decodable {\n public init(from decoder: Decoder) throws {\n self.init(try decoder.singleValueContainer().decode(String.self))\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_RelativePath.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Path_RelativePath.swift
Swift
2,341
0.95
0.065789
0.212121
node-utils
196
2023-11-19T12:34:43.863776
BSD-3-Clause
false
aff96b24e0089bcebae2b0ac1ed7ca12
//===--- Repo.swift -------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// TODO: This really ought to be defined in swift-xcodegen\npublic enum Repo: CaseIterable, Sendable {\n case swift\n case swiftRuntimes\n case lldb\n case llvm\n case cmark\n\n public var relativePath: RelativePath {\n switch self {\n case .swift: "swift"\n case .swiftRuntimes: "swift/Runtimes"\n case .cmark: "cmark"\n case .lldb: "llvm-project/lldb"\n case .llvm: "llvm-project"\n }\n }\n\n public var buildDirPrefix: String? {\n switch self {\n case .swift: "swift"\n case .swiftRuntimes: nil\n case .cmark: "cmark"\n case .lldb: "lldb"\n case .llvm: "llvm"\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Repo.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Repo.swift
Swift
1,115
0.8
0.1
0.324324
react-lib
192
2023-11-05T16:47:41.758347
MIT
false
22e72e1d5dbd9419576df8de8b5489be
//===--- Byte.swift -------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nstruct Byte: Hashable {\n var rawValue: UInt8\n init(_ rawValue: UInt8) {\n self.rawValue = rawValue\n }\n}\n\nextension Byte: ExpressibleByUnicodeScalarLiteral {\n init(unicodeScalarLiteral value: UnicodeScalar) {\n self.init(UInt8(ascii: value))\n }\n}\n\nextension Byte: Comparable {\n static func < (lhs: Self, rhs: Self) -> Bool {\n lhs.rawValue < rhs.rawValue\n }\n}\n\nextension Byte {\n var isSpaceOrTab: Bool {\n self == " " || self == "\t"\n }\n var isNewline: Bool {\n self == "\n" || self == "\r"\n }\n var isSpaceTabOrNewline: Bool {\n isSpaceOrTab || isNewline\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Scanner_Byte.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Scanner_Byte.swift
Swift
1,097
0.8
0.047619
0.289474
react-lib
422
2024-09-05T03:24:50.377749
Apache-2.0
false
10bb74e3e57dde473af41866c5297d73
//===--- ByteScanner.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Helper for eating bytes.\nstruct ByteScanner {\n typealias Cursor = UnsafeRawBufferPointer.Index\n\n private let input: UnsafeRawBufferPointer\n fileprivate(set) var cursor: Cursor\n\n init(_ input: UnsafeRawBufferPointer) {\n self.input = input\n self.cursor = input.startIndex\n }\n\n init(_ input: UnsafeBufferPointer<UInt8>) {\n self.init(UnsafeRawBufferPointer(input))\n }\n\n var hasInput: Bool { cursor != input.endIndex }\n var empty: Bool { !hasInput }\n\n var previous: Byte? {\n cursor > input.startIndex ? Byte(input[cursor - 1]) : nil\n }\n\n var peek: Byte? {\n hasInput ? Byte(input[cursor]) : nil\n }\n\n func peek(ahead n: Int) -> Byte? {\n precondition(n > 0)\n guard n < input.endIndex - cursor else { return nil }\n return Byte(input[cursor + n])\n }\n\n var whole: UnsafeRawBufferPointer {\n input\n }\n\n var remaining: UnsafeRawBufferPointer {\n .init(rebasing: input[cursor...])\n }\n\n func decodeUTF8<R: RangeExpression>(\n _ range: R\n ) -> String where R.Bound == Cursor {\n String(utf8: whole[range])\n }\n\n mutating func eat() -> Byte? {\n guard let byte = peek else { return nil }\n cursor += 1\n return byte\n }\n\n mutating func tryEat() -> Bool {\n eat() != nil\n }\n\n mutating func tryEat(where pred: (Byte) throws -> Bool) rethrows -> Bool {\n guard let c = peek, try pred(c) else { return false }\n cursor += 1\n return true\n }\n\n mutating func tryEat(_ byte: Byte) -> Bool {\n tryEat(where: { $0 == byte })\n }\n\n mutating func tryEat<S: Sequence>(_ seq: S) -> Bool where S.Element == UInt8 {\n let start = cursor\n for byte in seq {\n guard tryEat(Byte(byte)) else {\n cursor = start\n return false\n }\n }\n return true\n }\n\n mutating func tryEat(utf8 str: StaticString) -> Bool {\n str.withUTF8Buffer { utf8 in\n tryEat(utf8)\n }\n }\n\n // Prefer the StaticString overload where we can.\n @_disfavoredOverload\n mutating func tryEat(utf8 str: String) -> Bool {\n tryEat(str.utf8)\n }\n\n mutating func tryEating<T>(\n _ body: (inout ByteScanner) -> T?\n ) -> T? {\n var tmp = self\n guard let result = body(&tmp) else { return nil }\n self = tmp\n return result\n }\n\n mutating func skip(while pred: (Byte) throws -> Bool) rethrows {\n while try tryEat(where: pred) {}\n }\n\n mutating func skip(until pred: (Byte) throws -> Bool) rethrows {\n try skip(while: { try !pred($0) })\n }\n\n mutating func skip(untilAfter pred: (Byte) throws -> Bool) rethrows {\n if let char = peek, try !pred(char) {\n try skip(until: pred)\n }\n try skip(while: pred)\n }\n\n mutating func eat(\n while pred: (Byte) throws -> Bool\n ) rethrows -> UnsafeRawBufferPointer? {\n let start = cursor\n while try tryEat(where: pred) {}\n return start == cursor\n ? nil : UnsafeRawBufferPointer(rebasing: input[start ..< cursor])\n }\n\n /// Use a byte consumer to eat a series of bytes, returning `true` in `body`\n /// to continue consuming, `false` to end.\n mutating func consume(\n using body: (inout Consumer) throws -> Bool\n ) rethrows -> Bytes {\n var consumer = Consumer(self)\n while try body(&consumer) {}\n self = consumer.scanner\n return consumer.takeResult()\n }\n\n /// Similar to `consume(while:)`, but eats a character each time the body\n /// returns, and consumes the entire input.\n mutating func consumeWhole(\n _ body: (inout Consumer) throws -> Void\n ) rethrows -> Bytes {\n var consumer = Consumer(self, consumesWhole: true)\n repeat {\n guard consumer.hasInput else { break }\n try body(&consumer)\n } while consumer.eat()\n self = consumer.scanner\n return consumer.takeResult()\n }\n}\n\nextension ByteScanner {\n /// A wrapper type for a series of bytes consumed by Consumer, which uses\n /// a backing buffer to handle cases where intermediate bytes have been\n /// skipped. This must not outlive the underlying bytes being processed.\n struct Bytes {\n private enum Storage {\n case array\n case slice(Range<ByteScanner.Cursor>)\n }\n /// The array being stored when `storage == .array`. Defined out of line\n /// to avoid COW on mutation.\n private var _array: [UInt8] = []\n private var array: [UInt8] {\n _read {\n guard case .array = storage else {\n fatalError("Must be .array")\n }\n yield _array\n }\n _modify {\n guard case .array = storage else {\n fatalError("Must be .array")\n }\n yield &_array\n }\n }\n private var storage: Storage\n\n /// The underlying buffer being scanned.\n private let buffer: UnsafeRawBufferPointer\n\n /// The starting cursor.\n private let start: ByteScanner.Cursor\n\n /// The past-the-end position for the last cursor that was added.\n private var lastCursor: ByteScanner.Cursor\n\n /// If true, we're expecting to consume the entire buffer.\n private let consumesWhole: Bool\n\n fileprivate init(for scanner: ByteScanner, consumesWhole: Bool) {\n self.storage = .slice(scanner.cursor ..< scanner.cursor)\n self.buffer = scanner.whole\n self.start = scanner.cursor\n self.lastCursor = scanner.cursor\n self.consumesWhole = consumesWhole\n }\n }\n}\n\nextension ByteScanner.Bytes {\n fileprivate mutating func skip(_ range: Range<ByteScanner.Cursor>) {\n append(upTo: range.lowerBound)\n lastCursor = range.upperBound\n assert(lastCursor <= buffer.endIndex)\n }\n\n fileprivate mutating func skip(at cursor: ByteScanner.Cursor) {\n skip(cursor ..< cursor + 1)\n }\n\n @inline(__always)\n fileprivate mutating func switchToArray() {\n guard case .slice(let range) = storage else {\n fatalError("Must be a slice")\n }\n storage = .array\n if consumesWhole {\n array.reserveCapacity(buffer.count)\n }\n array += buffer[range]\n }\n\n fileprivate mutating func prepareToAppend(at cursor: ByteScanner.Cursor) {\n append(upTo: cursor)\n if case .slice = storage {\n // This must switch to owned storage, since it's not something present in\n // the underlying buffer.\n switchToArray()\n }\n }\n\n fileprivate mutating func append<S: Sequence>(\n contentsOf chars: S, at cursor: ByteScanner.Cursor\n ) where S.Element == UInt8 {\n prepareToAppend(at: cursor)\n array.append(contentsOf: chars)\n }\n\n fileprivate mutating func append(\n _ char: UInt8, at cursor: ByteScanner.Cursor\n ) {\n prepareToAppend(at: cursor)\n array.append(char)\n }\n\n fileprivate mutating func append(upTo cursor: ByteScanner.Cursor) {\n assert(cursor <= buffer.endIndex)\n guard cursor > lastCursor else { return }\n defer {\n lastCursor = cursor\n }\n switch storage {\n case .array:\n array += buffer[lastCursor ..< cursor]\n case .slice(var range):\n if range.isEmpty {\n // The slice is empty, we can move the start to the last cursor.\n range = lastCursor ..< lastCursor\n }\n if lastCursor == range.endIndex {\n // The slice is continuing from the last cursor, extend it.\n storage = .slice(range.startIndex ..< cursor)\n } else {\n // The last cursor is past the slice, we need to allocate.\n switchToArray()\n array += buffer[lastCursor ..< cursor]\n }\n }\n }\n\n var isEmpty: Bool {\n switch storage {\n case .array:\n array.isEmpty\n case .slice(let range):\n range.isEmpty\n }\n }\n\n /// Whether the set of bytes is known to be the same as the input. It is\n /// assumed that if a backing buffer were allocated, the result has changed.\n var isUnchanged: Bool {\n switch storage {\n case .array:\n false\n case .slice(let r):\n // Known to be the same if we're slicing the same input that we were\n // created with.\n r == start ..< buffer.endIndex\n }\n }\n\n var count: Int {\n switch storage {\n case .array:\n array.count\n case .slice(let range):\n range.count\n }\n }\n\n func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n switch storage {\n case .array:\n try array.withUnsafeBytes(body)\n case .slice(let range):\n try body(.init(rebasing: buffer[range]))\n }\n }\n}\n\nextension ByteScanner {\n /// A simplified ByteScanner inferface that allows for efficient skipping\n /// while producing a continguous Bytes output. Additionally, it allows for\n /// injecting values into the output through calls to `append`.\n struct Consumer {\n fileprivate var scanner: ByteScanner\n private var result: ByteScanner.Bytes\n\n fileprivate init(_ scanner: ByteScanner, consumesWhole: Bool = false) {\n self.scanner = scanner\n self.result = .init(for: scanner, consumesWhole: consumesWhole)\n }\n\n var peek: Byte? {\n scanner.peek\n }\n\n func peek(ahead n: Int) -> Byte? {\n scanner.peek(ahead: n)\n }\n\n var hasInput: Bool {\n scanner.hasInput\n }\n\n var remaining: UnsafeRawBufferPointer {\n scanner.remaining\n }\n\n mutating func append(_ byte: Byte) {\n result.append(byte.rawValue, at: scanner.cursor)\n }\n\n mutating func append(utf8 str: String) {\n result.append(contentsOf: str.utf8, at: scanner.cursor)\n }\n\n mutating func takeResult() -> ByteScanner.Bytes {\n result.append(upTo: scanner.cursor)\n return result\n }\n\n mutating func eat() -> Bool {\n scanner.tryEat()\n }\n\n mutating func eatRemaining() {\n scanner.cursor = scanner.input.endIndex\n }\n\n mutating func skip() {\n result.skip(at: scanner.cursor)\n _ = scanner.eat()\n }\n\n private mutating func _skip(\n using body: (inout ByteScanner) throws -> Void\n ) rethrows {\n let start = scanner.cursor\n defer {\n if scanner.cursor != start {\n result.skip(start ..< scanner.cursor)\n }\n }\n try body(&scanner)\n }\n\n mutating func skip(while pred: (Byte) throws -> Bool) rethrows {\n try _skip(using: { try $0.skip(while: pred) })\n }\n\n mutating func skip(until pred: (Byte) throws -> Bool) rethrows {\n try _skip(using: { try $0.skip(until: pred) })\n }\n\n mutating func skip(untilAfter pred: (Byte) throws -> Bool) rethrows {\n try _skip(using: { try $0.skip(untilAfter: pred) })\n }\n\n mutating func trySkip<S: Sequence>(_ seq: S) -> Bool where S.Element == UInt8 {\n let start = scanner.cursor\n guard scanner.tryEat(seq) else { return false }\n result.skip(start ..< scanner.cursor)\n return true\n }\n\n mutating func trySkip(utf8 str: String) -> Bool {\n trySkip(str.utf8)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Scanner_ByteScanner.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Scanner_ByteScanner.swift
Swift
11,049
0.8
0.132212
0.106742
awesome-app
210
2025-01-30T11:24:17.579644
Apache-2.0
false
a3d24b5debebc9ca2342e57298c311d7
//===--- Utils.swift ------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension Dictionary {\n @inline(__always)\n mutating func withValue<R>(\n for key: Key, default defaultValue: Value, body: (inout Value) throws -> R\n ) rethrows -> R {\n try body(&self[key, default: defaultValue])\n }\n\n mutating func insertValue(\n _ newValue: @autoclosure () -> Value, for key: Key\n ) -> Bool {\n if self[key] == nil {\n self[key] = newValue()\n return true\n }\n return false\n }\n}\nextension Sequence {\n func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] {\n sorted(by: { $0[keyPath: keyPath] < $1[keyPath: keyPath] })\n }\n}\n\nextension String {\n init(utf8 buffer: UnsafeRawBufferPointer) {\n guard !buffer.isEmpty else {\n self = ""\n return\n }\n self = String(unsafeUninitializedCapacity: buffer.count,\n initializingUTF8With: { dest in\n _ = dest.initialize(from: buffer)\n return buffer.count\n })\n }\n\n init(utf8 buffer: UnsafeBufferPointer<UInt8>) {\n self.init(utf8: UnsafeRawBufferPointer(buffer))\n }\n\n init(utf8 slice: Slice<UnsafeRawBufferPointer>) {\n self = String(utf8: .init(rebasing: slice))\n }\n\n init(utf8 buffer: ByteScanner.Bytes) {\n self = buffer.withUnsafeBytes(String.init(utf8:))\n }\n\n func scanningUTF8<R>(_ scan: (inout ByteScanner) throws -> R) rethrows -> R {\n var tmp = self\n return try tmp.withUTF8 { utf8 in\n var scanner = ByteScanner(utf8)\n return try scan(&scanner)\n }\n }\n\n func tryDropPrefix(_ prefix: String) -> String? {\n guard hasPrefix(prefix) else { return nil }\n return String(dropFirst(prefix.count))\n }\n\n func escaped(addQuotesIfNeeded: Bool) -> String {\n scanningUTF8 { scanner in\n var needsQuotes = false\n let result = scanner.consumeWhole { consumer in\n switch consumer.peek {\n case "\\", "\"":\n consumer.append("\\")\n case " ", "$": // $ is potentially a variable reference\n needsQuotes = true\n default:\n break\n }\n }\n let escaped = result.isUnchanged ? self : String(utf8: result)\n return addQuotesIfNeeded && needsQuotes ? "\"\(escaped)\"" : escaped\n }\n }\n\n var escaped: String {\n escaped(addQuotesIfNeeded: true)\n }\n\n init(_ str: StaticString) {\n self = str.withUTF8Buffer { utf8 in\n String(utf8: utf8)\n }\n }\n\n var isASCII: Bool {\n // Thanks, @testable interface!\n _classify()._isASCII\n }\n\n /// A more efficient version of replacingOccurrences(of:with:)/replacing(_:with:),\n /// since the former involves bridging, and the latter currently has no fast\n /// paths for strings.\n func replacing(_ other: String, with replacement: String) -> String {\n guard !other.isEmpty else { \n return self\n }\n guard isASCII else {\n // Not ASCII, fall back to slower method.\n return replacingOccurrences(of: other, with: replacement)\n }\n let otherUTF8 = other.utf8\n return scanningUTF8 { scanner in\n let bytes = scanner.consumeWhole { consumer in\n guard otherUTF8.count <= consumer.remaining.count else {\n // If there's no way we can eat the string, eat the remaining.\n consumer.eatRemaining()\n return\n }\n while consumer.trySkip(otherUTF8) {\n consumer.append(utf8: replacement)\n }\n }\n return bytes.isUnchanged ? self : String(utf8: bytes)\n }\n }\n}\n\n/// Pattern match by `is` property. E.g. `case \.isNewline: ...`\nfunc ~= <T>(keyPath: KeyPath<T, Bool>, subject: T) -> Bool {\n return subject[keyPath: keyPath]\n}\n\nfunc ~= <T>(keyPath: KeyPath<T, Bool>, subject: T?) -> Bool {\n return subject?[keyPath: keyPath] == true\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Utils.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_SwiftXcodeGen_Utils.swift
Swift
4,153
0.8
0.076923
0.140625
react-lib
50
2023-10-03T23:21:00.844158
Apache-2.0
false
e1704a072589174890d44df697f3001f
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct InternalError: Error {\n private let description: String\n public init(_ description: String) {\n assertionFailure(description)\n self.description = description\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_Errors.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_Errors.swift
Swift
692
0.8
0.105263
0.611111
react-lib
10
2024-03-27T23:47:57.338570
GPL-3.0
false
5d1bef7d8ad00dab12c0658996a79bc1
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A enum representing data types for legacy PropertyList type.\n/// Note that the `identifier` enum is not strictly necessary,\n/// but useful to semantically distinguish the strings that\n/// represents object identifiers from those that are just data.\n/// see: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html\npublic enum PropertyList {\n case identifier(String)\n case string(String)\n case array([PropertyList])\n case dictionary([String: PropertyList])\n\n var string: String? {\n if case .string(let string) = self {\n return string\n }\n return nil\n }\n\n var array: [PropertyList]? {\n if case .array(let array) = self {\n return array\n }\n return nil\n }\n}\n\nextension PropertyList: CustomStringConvertible {\n public var description: String {\n String(decoding: serialize(), as: UTF8.self)\n }\n}\n\nextension PropertyList {\n /// Serializes the Plist enum.\n public func serialize() -> Data {\n var writer = UTF8Writer()\n writePlistRepresentation(to: &writer)\n return Data(writer.bytes)\n }\n}\n\nfileprivate extension PropertyList {\n struct UTF8Writer {\n private(set) var level: Int = 0\n private(set) var bytes: [UInt8] = []\n init() {\n self += "// !$*UTF8*$!\n"\n }\n\n mutating func withIndent(body: (inout Self) -> Void) {\n level += 1\n body(&self)\n level -= 1\n }\n\n mutating func append(_ byte: UInt8) {\n bytes.append(byte)\n }\n\n static func += (writer: inout UTF8Writer, str: StaticString) {\n str.withUTF8Buffer { utf8 in\n writer.bytes += utf8\n }\n }\n\n @_disfavoredOverload\n static func += (writer: inout UTF8Writer, str: String) {\n writer.bytes += str.utf8\n }\n\n mutating func indent() {\n for _ in 0 ..< level {\n self += " "\n }\n }\n\n /// Appends the given string, with instances of quote (") and backward slash\n /// (\) characters escaped with a backslash.\n mutating func appendEscaped(_ string: String) {\n for char in string.utf8 {\n if char == UInt8(ascii: "\\") || char == UInt8(ascii: "\"") {\n append(UInt8(ascii: "\\"))\n }\n append(char)\n }\n }\n }\n\n /// Private function to generate OPENSTEP-style plist representation.\n func writePlistRepresentation(to writer: inout UTF8Writer) {\n // Do the appropriate thing for each type of plist node.\n switch self {\n case .identifier(let ident):\n // FIXME: we should assert that the identifier doesn't need quoting\n writer += ident\n\n case .string(let string):\n writer += "\""\n writer.appendEscaped(string)\n writer += "\""\n\n case .array(let array):\n writer += "(\n"\n writer.withIndent { writer in\n for (i, item) in array.enumerated() {\n writer.indent()\n item.writePlistRepresentation(to: &writer)\n writer += (i != array.count - 1) ? ",\n" : "\n"\n }\n }\n writer.indent()\n writer += ")"\n\n case .dictionary(let dict):\n let dict = dict.sorted(by: {\n // Make `isa` sort first (just for readability purposes).\n switch ($0.key, $1.key) {\n case ("isa", "isa"): return false\n case ("isa", _): return true\n case (_, "isa"): return false\n default: return $0.key < $1.key\n }\n })\n writer += "{\n"\n writer.withIndent { writer in\n for (key, value) in dict {\n writer.indent()\n writer += key\n writer += " = "\n value.writePlistRepresentation(to: &writer)\n writer += ";\n"\n }\n }\n writer.indent()\n writer += "}"\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_PropertyList.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_PropertyList.swift
Swift
4,194
0.95
0.098684
0.17037
node-utils
803
2023-09-30T07:51:48.448709
MIT
false
0cf2a1bcb2a5be8c663dfb98ef23d7ab
//===--- PropertyListEncoder.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension PropertyList {\n static func encode<T: Encodable>(_ x: T) throws -> PropertyList {\n let encoder = _Encoder()\n try x.encode(to: encoder)\n return encoder.result.value\n }\n}\n\nfileprivate extension PropertyList {\n final class Result {\n enum Underlying {\n case empty\n case string(String)\n case array([PropertyList])\n case dictionary([String: PropertyList])\n }\n fileprivate var underlying: Underlying = .empty\n\n var isEmpty: Bool {\n if case .empty = underlying { return true } else { return false }\n }\n\n @discardableResult\n func makeDictionary() -> Self {\n precondition(isEmpty)\n underlying = .dictionary([:])\n return self\n }\n\n @discardableResult\n func makeArray() -> Self {\n precondition(isEmpty)\n underlying = .array([])\n return self\n }\n\n @discardableResult\n func makeString(_ str: String) -> Self {\n precondition(isEmpty)\n underlying = .string(str)\n return self\n }\n\n var value: PropertyList {\n switch underlying {\n case .empty:\n fatalError("Didn't encode anything?")\n case .array(let array):\n return .array(array)\n case .dictionary(let dictionary):\n return .dictionary(dictionary)\n case .string(let str):\n return .string(str)\n }\n }\n\n private var _array: [PropertyList] {\n guard case .array(let arr) = underlying else {\n fatalError("Must be array")\n }\n return arr\n }\n\n var array: [PropertyList] {\n _read {\n yield _array\n }\n _modify {\n // Avoid a COW.\n var arr = _array\n underlying = .empty\n defer {\n underlying = .array(arr)\n }\n yield &arr\n }\n }\n\n private var _dictionary: [String: PropertyList] {\n guard case .dictionary(let dict) = underlying else {\n fatalError("Must be dictionary")\n }\n return dict\n }\n\n var dictionary: [String: PropertyList] {\n _read {\n yield _dictionary\n }\n _modify {\n // Avoid a COW.\n var dict = _dictionary\n underlying = .empty\n defer {\n underlying = .dictionary(dict)\n }\n yield &dict\n }\n }\n }\n\n struct _Encoder: Encoder {\n var userInfo: [CodingUserInfoKey: Any] { [:] }\n var codingPath: [CodingKey] { fatalError("Unsupported") }\n\n var result = Result()\n init() {}\n\n func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {\n .init(KeyedContainer<Key>(result: result.makeDictionary()))\n }\n\n func unkeyedContainer() -> UnkeyedEncodingContainer {\n UnkeyedContainer(result: result.makeArray())\n }\n func singleValueContainer() -> SingleValueEncodingContainer {\n SingleValueContainer(result: result)\n }\n }\n}\n\nextension PropertyList {\n fileprivate struct KeyedContainer<Key: CodingKey>: KeyedEncodingContainerProtocol {\n var codingPath: [CodingKey] { fatalError("Unsupported") }\n var result: Result\n\n mutating func encode(_ value: String, forKey key: Key) {\n result.dictionary[key.stringValue] = .string(value)\n }\n\n mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws {\n result.dictionary[key.stringValue] = try .encode(value)\n }\n\n mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { fatalError("Unsupported") }\n mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { fatalError("Unsupported") }\n mutating func superEncoder(forKey key: Key) -> Encoder { fatalError("Unsupported") }\n mutating func superEncoder() -> Encoder { fatalError("Unsupported") }\n mutating func encodeNil(forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: Bool, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: Double, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: Float, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: Int, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: Int8, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: Int16, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: Int32, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: Int64, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt8, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt16, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt32, forKey key: Key) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt64, forKey key: Key) { fatalError("Unsupported") }\n }\n\n fileprivate struct UnkeyedContainer: UnkeyedEncodingContainer {\n var codingPath: [CodingKey] { fatalError("Unsupported") }\n\n var result: Result\n var count: Int {\n result.array.count\n }\n\n mutating func encode(_ value: String) {\n result.array.append(.string(value))\n }\n\n mutating func encode<T: Encodable>(_ value: T) throws {\n result.array.append(try .encode(value))\n }\n\n mutating func nestedContainer<NestedKey: CodingKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { fatalError("Unsupported") }\n mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { fatalError("Unsupported") }\n mutating func superEncoder() -> Encoder { fatalError("Unsupported") }\n mutating func encodeNil() { fatalError("Unsupported") }\n mutating func encode(_ value: Bool) { fatalError("Unsupported") }\n mutating func encode(_ value: Double) { fatalError("Unsupported") }\n mutating func encode(_ value: Float) { fatalError("Unsupported") }\n mutating func encode(_ value: Int) { fatalError("Unsupported") }\n mutating func encode(_ value: Int8) { fatalError("Unsupported") }\n mutating func encode(_ value: Int16) { fatalError("Unsupported") }\n mutating func encode(_ value: Int32) { fatalError("Unsupported") }\n mutating func encode(_ value: Int64) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt8) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt16) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt32) { fatalError("Unsupported") }\n mutating func encode(_ value: UInt64) { fatalError("Unsupported") }\n }\n\n fileprivate struct SingleValueContainer: SingleValueEncodingContainer {\n var codingPath: [CodingKey] { fatalError("Unsupported") }\n var result: Result\n\n mutating func encode<T: Encodable>(_ value: T) throws {\n let encoder = _Encoder()\n try value.encode(to: encoder)\n result.underlying = encoder.result.underlying\n }\n\n mutating func encode(_ value: String) throws {\n result.makeString(value)\n }\n\n mutating func encodeNil() throws { fatalError("Unsupported") }\n mutating func encode(_ value: Bool) throws { fatalError("Unsupported") }\n mutating func encode(_ value: Double) throws { fatalError("Unsupported") }\n mutating func encode(_ value: Float) throws { fatalError("Unsupported") }\n mutating func encode(_ value: Int) throws { fatalError("Unsupported") }\n mutating func encode(_ value: Int8) throws { fatalError("Unsupported") }\n mutating func encode(_ value: Int16) throws { fatalError("Unsupported") }\n mutating func encode(_ value: Int32) throws { fatalError("Unsupported") }\n mutating func encode(_ value: Int64) throws { fatalError("Unsupported") }\n mutating func encode(_ value: UInt) throws { fatalError("Unsupported") }\n mutating func encode(_ value: UInt8) throws { fatalError("Unsupported") }\n mutating func encode(_ value: UInt16) throws { fatalError("Unsupported") }\n mutating func encode(_ value: UInt32) throws { fatalError("Unsupported") }\n mutating func encode(_ value: UInt64) throws { fatalError("Unsupported") }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_PropertyListEncoder.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_PropertyListEncoder.swift
Swift
8,708
0.95
0.038961
0.064039
python-kit
207
2025-03-13T00:01:57.514058
Apache-2.0
false
fd06027b5b8c974f2e6d05f88af5a486
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/*\n A very simple rendition of the Xcode project model. There is only sufficient\n functionality to allow creation of Xcode projects in a somewhat readable way,\n and serialization to .xcodeproj plists. There is no consistency checking to\n ensure, for example, that build settings have valid values, dependency cycles\n are not created, etc.\n \n Everything here is geared toward supporting project generation. The intended\n usage model is for custom logic to build up a project using Xcode terminology\n (e.g. "group", "reference", "target", "build phase"), but there is almost no\n provision for modifying the model after it has been built up. The intent is\n to create it as desired from the start.\n \n Rather than try to represent everything that Xcode's project model supports,\n the approach is to start small and to add functionality as needed.\n \n Note that this API represents only the project model — there is no notion of\n workspaces, schemes, etc (although schemes are represented individually in a\n separate API). The notion of build settings is also somewhat different from\n what it is in Xcode: instead of an open-ended mapping of build configuration\n names to dictionaries of build settings, here there is a single set of common\n build settings plus two overlay sets for debug and release. The generated\n project has just the two Debug and Release configurations, created by merging\n the common set into the release and debug sets. This allows a more natural\n configuration of the settings, since most values are the same between Debug\n and Release. Also, the build settings themselves are represented as structs\n of named fields, instead of dictionaries with arbitrary name strings as keys.\n \n It is expected that some of these simplifications will need to be lifted over\n time, based on need. That should be done carefully, however, to avoid ending\n up with an overly complicated model.\n \n Some things that are incomplete in even this first model:\n - copy files build phases are incomplete\n - shell script build phases are incomplete\n - file types in file references are specified using strings; should be enums\n so that the client doesn't have to hardcode the mapping to Xcode file type\n identifiers\n - debug and release settings override common settings; they should be merged\n in a way that respects `$(inhertied)` when the same setting is defined in\n common and in debug or release\n - there is no good way to control the ordering of the `Products` group in the\n main group; it needs to be added last in order to appear after the other\n references\n */\n\npublic struct Xcode {\n \n /// An Xcode project, consisting of a tree of groups and file references,\n /// a list of targets, and some additional information. Note that schemes\n /// are outside of the project data model.\n public class Project {\n public let mainGroup: Group\n public var buildSettings: BuildSettingsTable\n public var productGroup: Group?\n public var projectDir: String\n public var targets: [Target]\n public init() {\n self.mainGroup = Group(path: "")\n self.buildSettings = BuildSettingsTable()\n self.productGroup = nil\n self.projectDir = ""\n self.targets = []\n }\n \n /// Creates and adds a new target (which does not initially have any\n /// build phases).\n public func addTarget(objectID: String? = nil, productType: Target.ProductType? = nil, name: String) -> Target {\n let target = Target(objectID: objectID ?? "TARGET_\(name)", productType: productType, name: name)\n targets.append(target)\n return target\n }\n }\n\n /// Abstract base class for all items in the group hierarchy.\n public class Reference {\n /// Relative path of the reference. It is usually a literal, but may\n /// in fact contain build settings.\n public var path: String\n /// Determines the base path for the reference's relative path.\n public var pathBase: RefPathBase\n /// Name of the reference, if different from the last path component\n /// (if not set, Xcode will use the last path component as the name).\n public var name: String?\n \n /// Determines the base path for a reference's relative path (this is\n /// what for some reason is called a "source tree" in Xcode).\n public enum RefPathBase: String {\n /// An absolute path\n case absolute = "<absolute>"\n /// Indicates that the path is relative to the source root (i.e.\n /// the "project directory").\n case projectDir = "SOURCE_ROOT"\n /// Indicates that the path is relative to the path of the parent\n /// group.\n case groupDir = "<group>"\n /// Indicates that the path is relative to the effective build\n /// directory (which varies depending on active scheme, active run\n /// destination, or even an overridden build setting.\n case buildDir = "BUILT_PRODUCTS_DIR"\n }\n \n init(path: String, pathBase: RefPathBase = .groupDir, name: String? = nil) {\n self.path = path\n self.pathBase = pathBase\n self.name = name\n }\n \n /// Whether this is either a group or directory reference (blue folder).\n public var isDirectoryLike: Bool {\n if self is Xcode.Group {\n return true\n }\n if let ref = self as? Xcode.FileReference {\n return ref.isDirectory\n }\n return false\n }\n }\n \n /// A reference to a file system entity (a file, folder, etc).\n public final class FileReference: Reference {\n public var objectID: String?\n public var fileType: String?\n public var isDirectory: Bool\n public fileprivate(set) var isBuildableFolder: Bool = false\n\n init(\n path: String, isDirectory: Bool, pathBase: RefPathBase = .groupDir,\n name: String? = nil, fileType: String? = nil, objectID: String? = nil\n ) {\n self.isDirectory = isDirectory\n super.init(path: path, pathBase: pathBase, name: name)\n self.objectID = objectID\n self.fileType = fileType\n }\n }\n \n /// A group that can contain References (FileReferences and other Groups).\n /// The resolved path of a group is used as the base path for any child\n /// references whose source tree type is GroupRelative.\n public final class Group: Reference {\n public var subitems = [Reference]()\n \n /// Creates and appends a new Group to the list of subitems.\n /// The new group is returned so that it can be configured.\n @discardableResult\n public func addGroup(\n path: String,\n pathBase: RefPathBase = .groupDir,\n name: String? = nil\n ) -> Group {\n let group = Group(path: path, pathBase: pathBase, name: name)\n subitems.append(group)\n return group\n }\n \n /// Creates and appends a new FileReference to the list of subitems.\n @discardableResult\n public func addFileReference(\n path: String,\n isDirectory: Bool,\n pathBase: RefPathBase = .groupDir,\n name: String? = nil,\n fileType: String? = nil,\n objectID: String? = nil\n ) -> FileReference {\n let fref = FileReference(path: path, isDirectory: isDirectory, pathBase: pathBase, name: name, fileType: fileType, objectID: objectID)\n subitems.append(fref)\n return fref\n }\n }\n\n /// An Xcode target, representing a single entity to build.\n public final class Target {\n public var objectID: String?\n public var name: String\n public var productName: String\n public var productType: ProductType?\n public var buildSettings: BuildSettingsTable\n public var buildPhases: [BuildPhase]\n public var productReference: FileReference?\n public var dependencies: [TargetDependency]\n public private(set) var buildableFolders: [FileReference]\n public enum ProductType: String {\n case application = "com.apple.product-type.application"\n case staticArchive = "com.apple.product-type.library.static"\n case dynamicLibrary = "com.apple.product-type.library.dynamic"\n case framework = "com.apple.product-type.framework"\n case executable = "com.apple.product-type.tool"\n case unitTest = "com.apple.product-type.bundle.unit-test"\n }\n init(objectID: String?, productType: ProductType?, name: String) {\n self.objectID = objectID\n self.name = name\n self.productType = productType\n self.productName = name\n self.buildSettings = BuildSettingsTable()\n self.buildPhases = []\n self.dependencies = []\n self.buildableFolders = []\n }\n \n // FIXME: There's a lot repetition in these methods; using generics to\n // try to avoid that raised other issues in terms of requirements on\n // the Reference class, though.\n \n /// Adds a "headers" build phase, i.e. one that copies headers into a\n /// directory of the product, after suitable processing.\n @discardableResult\n public func addHeadersBuildPhase() -> HeadersBuildPhase {\n let phase = HeadersBuildPhase()\n buildPhases.append(phase)\n return phase\n }\n \n /// Adds a "sources" build phase, i.e. one that compiles sources and\n /// provides them to be linked into the executable code of the product.\n @discardableResult\n public func addSourcesBuildPhase() -> SourcesBuildPhase {\n let phase = SourcesBuildPhase()\n buildPhases.append(phase)\n return phase\n }\n \n /// Adds a "frameworks" build phase, i.e. one that links compiled code\n /// and libraries into the executable of the product.\n @discardableResult\n public func addFrameworksBuildPhase() -> FrameworksBuildPhase {\n let phase = FrameworksBuildPhase()\n buildPhases.append(phase)\n return phase\n }\n \n /// Adds a "copy files" build phase, i.e. one that copies files to an\n /// arbitrary location relative to the product.\n @discardableResult\n public func addCopyFilesBuildPhase(dstDir: String) -> CopyFilesBuildPhase {\n let phase = CopyFilesBuildPhase(dstDir: dstDir)\n buildPhases.append(phase)\n return phase\n }\n \n /// Adds a "shell script" build phase, i.e. one that runs a custom\n /// shell script as part of the build.\n @discardableResult\n public func addShellScriptBuildPhase(\n script: String, inputs: [String], outputs: [String], alwaysRun: Bool\n ) -> ShellScriptBuildPhase {\n let phase = ShellScriptBuildPhase(\n script: script, inputs: inputs, outputs: outputs, alwaysRun: alwaysRun\n )\n buildPhases.append(phase)\n return phase\n }\n \n /// Adds a dependency on another target.\n /// FIXME: We do not check for cycles. Should we? This is an extremely\n /// minimal API so it's not clear that we should.\n public func addDependency(on target: Target) {\n dependencies.append(TargetDependency(target: target))\n }\n\n /// Turn a given folder reference into a buildable folder for this target.\n public func addBuildableFolder(_ fileRef: FileReference) {\n precondition(fileRef.isDirectory)\n fileRef.isBuildableFolder = true\n buildableFolders.append(fileRef)\n }\n\n /// A simple wrapper to prevent ownership cycles in the `dependencies`\n /// property.\n public struct TargetDependency {\n public unowned var target: Target\n }\n }\n \n /// Abstract base class for all build phases in a target.\n public class BuildPhase {\n public var files: [BuildFile] = []\n \n /// Adds a new build file that refers to `fileRef`.\n @discardableResult\n public func addBuildFile(fileRef: FileReference) -> BuildFile {\n let buildFile = BuildFile(fileRef: fileRef)\n files.append(buildFile)\n return buildFile\n }\n }\n \n /// A "headers" build phase, i.e. one that copies headers into a directory\n /// of the product, after suitable processing.\n public final class HeadersBuildPhase: BuildPhase {\n // Nothing extra yet.\n }\n \n /// A "sources" build phase, i.e. one that compiles sources and provides\n /// them to be linked into the executable code of the product.\n public final class SourcesBuildPhase: BuildPhase {\n // Nothing extra yet.\n }\n \n /// A "frameworks" build phase, i.e. one that links compiled code and\n /// libraries into the executable of the product.\n public final class FrameworksBuildPhase: BuildPhase {\n // Nothing extra yet.\n }\n \n /// A "copy files" build phase, i.e. one that copies files to an arbitrary\n /// location relative to the product.\n public final class CopyFilesBuildPhase: BuildPhase {\n public var dstDir: String\n init(dstDir: String) {\n self.dstDir = dstDir\n }\n }\n \n /// A "shell script" build phase, i.e. one that runs a custom shell script.\n public final class ShellScriptBuildPhase: BuildPhase {\n public var script: String\n public var inputs: [String]\n public var outputs: [String]\n public var alwaysRun: Bool\n init(script: String, inputs: [String], outputs: [String], alwaysRun: Bool) {\n self.script = script\n self.inputs = inputs\n self.outputs = outputs\n self.alwaysRun = alwaysRun\n }\n }\n \n /// A build file, representing the membership of a file reference in a\n /// build phase of a target.\n public final class BuildFile {\n public var fileRef: FileReference?\n init(fileRef: FileReference) {\n self.fileRef = fileRef\n }\n \n public var settings = Settings()\n \n /// A set of file settings.\n public struct Settings: Encodable {\n public var ATTRIBUTES: [String]?\n public var COMPILER_FLAGS: String?\n \n public init() {\n }\n }\n }\n \n /// A table of build settings, which for the sake of simplicity consists\n /// (in this simplified model) of a set of common settings, and a set of\n /// overlay settings for Debug and Release builds. There can also be a\n /// file reference to an .xcconfig file on which to base the settings.\n public final class BuildSettingsTable {\n /// Common build settings are in both generated configurations (Debug\n /// and Release).\n public var common = BuildSettings()\n \n /// Debug build settings are overlaid over the common settings in the\n /// generated Debug configuration.\n public var debug = BuildSettings()\n \n /// Release build settings are overlaid over the common settings in the\n /// generated Release configuration.\n public var release = BuildSettings()\n \n /// An optional file reference to an .xcconfig file.\n public var xcconfigFileRef: FileReference?\n \n public init() {\n }\n \n /// A set of build settings, which is represented as a struct of optional\n /// build settings. This is not optimally efficient, but it is great for\n /// code completion and type-checking.\n public struct BuildSettings: Encodable {\n // Note: although some of these build settings sound like booleans,\n // they are all either strings or arrays of strings, because even\n // a boolean may be a macro reference expression.\n public var BUILT_PRODUCTS_DIR: String?\n public var CLANG_CXX_LANGUAGE_STANDARD: String?\n public var CLANG_ENABLE_MODULES: String?\n public var CLANG_ENABLE_OBJC_ARC: String?\n public var COMBINE_HIDPI_IMAGES: String?\n public var COPY_PHASE_STRIP: String?\n public var CURRENT_PROJECT_VERSION: String?\n public var DEBUG_INFORMATION_FORMAT: String?\n public var DEFINES_MODULE: String?\n public var DYLIB_INSTALL_NAME_BASE: String?\n public var EMBEDDED_CONTENT_CONTAINS_SWIFT: String?\n public var ENABLE_NS_ASSERTIONS: String?\n public var ENABLE_TESTABILITY: String?\n public var FRAMEWORK_SEARCH_PATHS: [String]?\n public var GCC_C_LANGUAGE_STANDARD: String?\n public var GCC_OPTIMIZATION_LEVEL: String?\n public var GCC_PREPROCESSOR_DEFINITIONS: [String]?\n public var GCC_GENERATE_DEBUGGING_SYMBOLS: String?\n public var GCC_WARN_64_TO_32_BIT_CONVERSION: String?\n public var HEADER_SEARCH_PATHS: [String]?\n public var INFOPLIST_FILE: String?\n public var LD_RUNPATH_SEARCH_PATHS: [String]?\n public var LIBRARY_SEARCH_PATHS: [String]?\n public var MACOSX_DEPLOYMENT_TARGET: String?\n public var IPHONEOS_DEPLOYMENT_TARGET: String?\n public var TVOS_DEPLOYMENT_TARGET: String?\n public var WATCHOS_DEPLOYMENT_TARGET: String?\n public var DRIVERKIT_DEPLOYMENT_TARGET: String?\n public var MODULEMAP_FILE: String?\n public var ONLY_ACTIVE_ARCH: String?\n public var OTHER_CFLAGS: [String]?\n public var OTHER_CPLUSPLUSFLAGS: [String]?\n public var OTHER_LDFLAGS: [String]?\n public var OTHER_SWIFT_FLAGS: [String]?\n public var PRODUCT_BUNDLE_IDENTIFIER: String?\n public var PRODUCT_MODULE_NAME: String?\n public var PRODUCT_NAME: String?\n public var PROJECT_DIR: String?\n public var PROJECT_NAME: String?\n public var SDKROOT: String?\n public var SKIP_INSTALL: String?\n public var SUPPORTED_PLATFORMS: [String]?\n public var SUPPORTS_MACCATALYST: String?\n public var SWIFT_ACTIVE_COMPILATION_CONDITIONS: [String]?\n public var SWIFT_COMPILATION_MODE: String?\n public var SWIFT_ENABLE_EXPLICIT_MODULES: String?\n public var SWIFT_FORCE_STATIC_LINK_STDLIB: String?\n public var SWIFT_FORCE_DYNAMIC_LINK_STDLIB: String?\n public var SWIFT_INCLUDE_PATHS: [String]?\n public var SWIFT_MODULE_ALIASES: [String: String]?\n public var SWIFT_OBJC_INTERFACE_HEADER_NAME: String?\n public var SWIFT_OPTIMIZATION_LEVEL: String?\n public var SWIFT_VERSION: String?\n public var TARGET_NAME: String?\n public var TARGET_BUILD_DIR: String?\n public var USE_HEADERMAP: String?\n public var LD: String?\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_XcodeProjectModel.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_XcodeProjectModel.swift
Swift
18,071
0.95
0.086093
0.235294
awesome-app
999
2024-04-30T01:07:20.201594
MIT
false
ab3bfa18bc7a7c8b67eb99b04abd5118
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/*\n An extemely simple rendition of the Xcode project model into a plist. There\n is only enough functionality to allow serialization of Xcode projects.\n */\n\nextension Xcode.Project {\n fileprivate enum MinVersion {\n case xcode8, xcode16\n\n var objectVersion: Int {\n switch self {\n case .xcode8: 46\n case .xcode16: 77\n }\n }\n }\n\n fileprivate var hasBuildableFolders: Bool {\n var worklist: [Xcode.Reference] = []\n worklist.append(mainGroup)\n while let ref = worklist.popLast() {\n if let fileRef = ref as? Xcode.FileReference, fileRef.isBuildableFolder {\n return true\n }\n if let group = ref as? Xcode.Group {\n worklist += group.subitems\n }\n }\n return false\n }\n}\n\nextension Xcode.Project: PropertyListSerializable {\n\n /// Generates and returns the contents of a `project.pbxproj` plist. Does\n /// not generate any ancillary files, such as a set of schemes.\n ///\n /// Many complexities of the Xcode project model are not represented; we\n /// should not add functionality to this model unless it's needed, since\n /// implementation of the full Xcode project model would be unnecessarily\n /// complex.\n public func generatePlist() throws -> PropertyList {\n // The project plist is a bit special in that it's the archive for the\n // whole file. We create a plist serializer and serialize the entire\n // object graph to it, and then return an archive dictionary containing\n // the serialized object dictionaries.\n let serializer = PropertyListSerializer()\n try serializer.serialize(object: self)\n var minVersion = MinVersion.xcode8\n if hasBuildableFolders {\n minVersion = .xcode16\n }\n return .dictionary([\n "archiveVersion": .string("1"),\n "objectVersion": .string(String(minVersion.objectVersion)),\n "rootObject": .identifier(serializer.id(of: self)),\n "objects": .dictionary(serializer.idsToDicts),\n ])\n }\n\n /// Called by the Serializer to serialize the Project.\n fileprivate func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n // Create a `PBXProject` plist dictionary.\n // Note: we skip things like the `Products` group; they get autocreated\n // by Xcode when it opens the project and notices that they are missing.\n // Note: we also skip schemes, since they are not in the project plist.\n var dict = [String: PropertyList]()\n dict["isa"] = .string("PBXProject")\n // Since the project file is generated, we opt out of upgrade-checking.\n // FIXME: Should we really? Why would we not want to get upgraded?\n dict["attributes"] = .dictionary(["LastUpgradeCheck": .string("9999"),\n "LastSwiftMigration": .string("9999")])\n dict["compatibilityVersion"] = .string("Xcode 3.2")\n dict["developmentRegion"] = .string("en")\n // Build settings are a bit tricky; in Xcode, each is stored in a named\n // XCBuildConfiguration object, and the list of build configurations is\n // in turn stored in an XCConfigurationList. In our simplified model,\n // we have a BuildSettingsTable, with three sets of settings: one for\n // the common settings, and one each for the Debug and Release overlays.\n // So we consider the BuildSettingsTable to be the configuration list.\n dict["buildConfigurationList"] = try .identifier(serializer.serialize(object: buildSettings))\n dict["mainGroup"] = try .identifier(serializer.serialize(object: mainGroup))\n dict["hasScannedForEncodings"] = .string("0")\n dict["knownRegions"] = .array([.string("en")])\n if let productGroup = productGroup {\n dict["productRefGroup"] = .identifier(serializer.id(of: productGroup))\n }\n dict["projectDirPath"] = .string(projectDir)\n // Ensure that targets are output in a sorted order.\n let sortedTargets = targets.sorted(by: { $0.name < $1.name })\n dict["targets"] = try .array(sortedTargets.map({ target in\n try .identifier(serializer.serialize(object: target))\n }))\n return dict\n }\n}\n\nextension Xcode.Reference: PropertyListSerializable {\n fileprivate dynamic func serialize(\n to serializer: PropertyListSerializer\n ) throws -> [String : PropertyList] {\n var dict = [String: PropertyList]()\n dict["path"] = .string(path)\n if let name = name {\n dict["name"] = .string(name)\n }\n dict["sourceTree"] = .string(pathBase.rawValue)\n\n let xcodeClassName: String\n switch self {\n case let group as Xcode.Group:\n xcodeClassName = "PBXGroup"\n dict["children"] = try .array(group.subitems.map({ reference in\n try .identifier(serializer.serialize(object: reference))\n }))\n case let fileRef as Xcode.FileReference:\n xcodeClassName = fileRef.isBuildableFolder \n ? "PBXFileSystemSynchronizedRootGroup" : "PBXFileReference"\n if let fileType = fileRef.fileType {\n dict["explicitFileType"] = .string(fileType)\n }\n // FileReferences don't need to store a name if it's the same as the path.\n if name == path {\n dict["name"] = nil\n }\n default:\n fatalError("Unhandled subclass")\n }\n dict["isa"] = .string(xcodeClassName)\n return dict\n }\n}\n\nextension Xcode.Target: PropertyListSerializable {\n\n /// Called by the Serializer to serialize the Target.\n fileprivate func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n // Create either a `PBXNativeTarget` or an `PBXAggregateTarget` plist\n // dictionary (depending on whether or not we have a product type).\n var dict = [String: PropertyList]()\n dict["isa"] = .string(productType == nil ? "PBXAggregateTarget" : "PBXNativeTarget")\n dict["name"] = .string(name)\n // Build settings are a bit tricky; in Xcode, each is stored in a named\n // XCBuildConfiguration object, and the list of build configurations is\n // in turn stored in an XCConfigurationList. In our simplified model,\n // we have a BuildSettingsTable, with three sets of settings: one for\n // the common settings, and one each for the Debug and Release overlays.\n // So we consider the BuildSettingsTable to be the configuration list.\n // This is the same situation as for Project.\n dict["buildConfigurationList"] = try .identifier(serializer.serialize(object: buildSettings))\n dict["buildPhases"] = try .array(buildPhases.map({ phase in\n // Here we have the same problem as for Reference; we cannot inherit\n // functionality since we're in an extension.\n try .identifier(serializer.serialize(object: phase as! PropertyListSerializable))\n }))\n /// Private wrapper class for a target dependency relation. This is\n /// glue between our value-based settings structures and the Xcode\n /// project model's identity-based TargetDependency objects.\n class TargetDependency: PropertyListSerializable {\n var target: Xcode.Target\n init(target: Xcode.Target) {\n self.target = target\n }\n func serialize(to serializer: PropertyListSerializer) -> [String: PropertyList] {\n // Create a `PBXTargetDependency` plist dictionary.\n var dict = [String: PropertyList]()\n dict["isa"] = .string("PBXTargetDependency")\n dict["target"] = .identifier(serializer.id(of: target))\n return dict\n }\n }\n dict["dependencies"] = try .array(dependencies.map({ dep in\n // In the Xcode project model, target dependencies are objects,\n // so we need a helper class here.\n try .identifier(serializer.serialize(object: TargetDependency(target: dep.target)))\n }))\n if !buildableFolders.isEmpty {\n dict["fileSystemSynchronizedGroups"] = .array(\n buildableFolders.map { .identifier(serializer.id(of: $0)) }\n )\n }\n dict["productName"] = .string(productName)\n if let productType = productType {\n dict["productType"] = .string(productType.rawValue)\n }\n if let productReference = productReference {\n dict["productReference"] = .identifier(serializer.id(of: productReference))\n }\n return dict\n }\n}\n\n/// Private helper function that constructs and returns a partial property list\n/// dictionary for build phases. The caller can add to the returned dictionary.\n/// FIXME: It would be nicer to be able to use inheritance to serialize the\n/// attributes inherited from BuildPhase, but but in Swift 3.0 we get an error\n/// that "declarations in extensions cannot override yet".\nfileprivate func makeBuildPhaseDict(\n buildPhase: Xcode.BuildPhase,\n serializer: PropertyListSerializer,\n xcodeClassName: String\n) throws -> [String: PropertyList] {\n var dict = [String: PropertyList]()\n dict["isa"] = .string(xcodeClassName)\n dict["files"] = try .array(buildPhase.files.map({ file in\n try .identifier(serializer.serialize(object: file))\n }))\n return dict\n}\n\nextension Xcode.HeadersBuildPhase: PropertyListSerializable {\n\n /// Called by the Serializer to serialize the HeadersBuildPhase.\n fileprivate func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n // Create a `PBXHeadersBuildPhase` plist dictionary.\n // FIXME: It would be nicer to be able to use inheritance for the code\n // inherited from BuildPhase, but but in Swift 3.0 we get an error that\n // "declarations in extensions cannot override yet".\n return try makeBuildPhaseDict(buildPhase: self, serializer: serializer, xcodeClassName: "PBXHeadersBuildPhase")\n }\n}\n\nextension Xcode.SourcesBuildPhase: PropertyListSerializable {\n\n /// Called by the Serializer to serialize the SourcesBuildPhase.\n fileprivate func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n // Create a `PBXSourcesBuildPhase` plist dictionary.\n // FIXME: It would be nicer to be able to use inheritance for the code\n // inherited from BuildPhase, but but in Swift 3.0 we get an error that\n // "declarations in extensions cannot override yet".\n return try makeBuildPhaseDict(buildPhase: self, serializer: serializer, xcodeClassName: "PBXSourcesBuildPhase")\n }\n}\n\nextension Xcode.FrameworksBuildPhase: PropertyListSerializable {\n\n /// Called by the Serializer to serialize the FrameworksBuildPhase.\n fileprivate func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n // Create a `PBXFrameworksBuildPhase` plist dictionary.\n // FIXME: It would be nicer to be able to use inheritance for the code\n // inherited from BuildPhase, but but in Swift 3.0 we get an error that\n // "declarations in extensions cannot override yet".\n return try makeBuildPhaseDict(buildPhase: self, serializer: serializer, xcodeClassName: "PBXFrameworksBuildPhase")\n }\n}\n\nextension Xcode.CopyFilesBuildPhase: PropertyListSerializable {\n\n /// Called by the Serializer to serialize the FrameworksBuildPhase.\n fileprivate func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n // Create a `PBXCopyFilesBuildPhase` plist dictionary.\n // FIXME: It would be nicer to be able to use inheritance for the code\n // inherited from BuildPhase, but but in Swift 3.0 we get an error that\n // "declarations in extensions cannot override yet".\n var dict = try makeBuildPhaseDict(\n buildPhase: self,\n serializer: serializer,\n xcodeClassName: "PBXCopyFilesBuildPhase"\n )\n dict["dstPath"] = .string("") // FIXME: needs to be real\n dict["dstSubfolderSpec"] = .string("") // FIXME: needs to be real\n return dict\n }\n}\n\nextension Xcode.ShellScriptBuildPhase: PropertyListSerializable {\n\n /// Called by the Serializer to serialize the ShellScriptBuildPhase.\n fileprivate func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n // Create a `PBXShellScriptBuildPhase` plist dictionary.\n // FIXME: It would be nicer to be able to use inheritance for the code\n // inherited from BuildPhase, but but in Swift 3.0 we get an error that\n // "declarations in extensions cannot override yet".\n var dict = try makeBuildPhaseDict(\n buildPhase: self,\n serializer: serializer,\n xcodeClassName: "PBXShellScriptBuildPhase")\n dict["shellPath"] = .string("/bin/sh") // FIXME: should be settable\n dict["shellScript"] = .string(script)\n dict["inputPaths"] = .array(inputs.map { .string($0) })\n dict["outputPaths"] = .array(outputs.map { .string($0) })\n dict["alwaysOutOfDate"] = .string(alwaysRun ? "1" : "0")\n return dict\n }\n}\n\nextension Xcode.BuildFile: PropertyListSerializable {\n\n /// Called by the Serializer to serialize the BuildFile.\n fileprivate func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n // Create a `PBXBuildFile` plist dictionary.\n var dict = [String: PropertyList]()\n dict["isa"] = .string("PBXBuildFile")\n if let fileRef = fileRef {\n dict["fileRef"] = .identifier(serializer.id(of: fileRef))\n }\n\n let settingsDict = try PropertyList.encode(settings)\n if !settingsDict.isEmpty {\n dict["settings"] = settingsDict\n }\n\n return dict\n }\n}\n\nextension Xcode.BuildSettingsTable: PropertyListSerializable {\n\n /// Called by the Serializer to serialize the BuildFile. It is serialized\n /// as an XCBuildConfigurationList and two additional XCBuildConfiguration\n /// objects (one for debug and one for release).\n fileprivate func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n /// Private wrapper class for BuildSettings structures. This is glue\n /// between our value-based settings structures and the Xcode project\n /// model's identity-based XCBuildConfiguration objects.\n class BuildSettingsDictWrapper: PropertyListSerializable {\n let name: String\n var baseSettings: BuildSettings\n var overlaySettings: BuildSettings\n let xcconfigFileRef: Xcode.FileReference?\n\n init(\n name: String,\n baseSettings: BuildSettings,\n overlaySettings: BuildSettings,\n xcconfigFileRef: Xcode.FileReference?\n ) {\n self.name = name\n self.baseSettings = baseSettings\n self.overlaySettings = overlaySettings\n self.xcconfigFileRef = xcconfigFileRef\n }\n\n func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList] {\n // Create a `XCBuildConfiguration` plist dictionary.\n var dict = [String: PropertyList]()\n dict["isa"] = .string("XCBuildConfiguration")\n dict["name"] = .string(name)\n // Combine the base settings and the overlay settings.\n dict["buildSettings"] = try combineBuildSettingsPropertyLists(\n baseSettings: .encode(baseSettings),\n overlaySettings: .encode(overlaySettings)\n )\n // Add a reference to the base configuration, if there is one.\n if let xcconfigFileRef = xcconfigFileRef {\n dict["baseConfigurationReference"] = .identifier(serializer.id(of: xcconfigFileRef))\n }\n return dict\n }\n }\n\n // Create a `XCConfigurationList` plist dictionary.\n var dict = [String: PropertyList]()\n dict["isa"] = .string("XCConfigurationList")\n dict["buildConfigurations"] = .array([\n // We use a private wrapper to "objectify" our two build settings\n // structures (which, being structs, are value types).\n try .identifier(serializer.serialize(object: BuildSettingsDictWrapper(\n name: "Debug",\n baseSettings: common,\n overlaySettings: debug,\n xcconfigFileRef: xcconfigFileRef))),\n try .identifier(serializer.serialize(object: BuildSettingsDictWrapper(\n name: "Release",\n baseSettings: common,\n overlaySettings: release,\n xcconfigFileRef: xcconfigFileRef))),\n ])\n // FIXME: What is this, and why are we setting it?\n dict["defaultConfigurationIsVisible"] = .string("0")\n // FIXME: Should we allow this to be set in the model?\n dict["defaultConfigurationName"] = .string("Release")\n return dict\n }\n}\n\n/// Private helper function that combines a base property list and an overlay\n/// property list, respecting the semantics of `$(inherited)` as we go.\nfileprivate func combineBuildSettingsPropertyLists(\n baseSettings: PropertyList,\n overlaySettings: PropertyList\n) throws -> PropertyList {\n // Extract the base and overlay dictionaries.\n guard case let .dictionary(baseDict) = baseSettings else {\n throw InternalError("base settings plist must be a dictionary")\n }\n guard case let .dictionary(overlayDict) = overlaySettings else {\n throw InternalError("overlay settings plist must be a dictionary")\n }\n\n // Iterate over the overlay values and apply them to the base.\n var resultDict = baseDict\n for (name, value) in overlayDict {\n if let array = baseDict[name]?.array, let overlayArray = value.array, overlayArray.first?.string == "$(inherited)" {\n resultDict[name] = .array(array + overlayArray.dropFirst())\n } else {\n resultDict[name] = value\n }\n }\n return .dictionary(resultDict)\n}\n\n/// A simple property list serializer with the same semantics as the Xcode\n/// property list serializer. Not generally reusable at this point, but only\n/// because of implementation details (architecturally it isn't tied to Xcode).\nfileprivate class PropertyListSerializer {\n\n /// Private struct that represents a strong reference to a serializable\n /// object. This prevents any temporary objects from being deallocated\n /// during the serialization and replaced with other objects having the\n /// same object identifier (a violation of our assumptions)\n struct SerializedObjectRef: Hashable, Equatable {\n let object: PropertyListSerializable\n\n init(_ object: PropertyListSerializable) {\n self.object = object\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(object))\n }\n\n static func == (lhs: SerializedObjectRef, rhs: SerializedObjectRef) -> Bool {\n return lhs.object === rhs.object\n }\n }\n\n /// Maps objects to the identifiers that have been assigned to them. The\n /// next identifier to be assigned is always one greater than the number\n /// of entries in the mapping.\n var objsToIds = [SerializedObjectRef: String]()\n\n /// Maps serialized objects ids to dictionaries. This may contain fewer\n /// entries than `objsToIds`, since ids are assigned upon reference, but\n /// plist dictionaries are created only upon actual serialization. This\n /// dictionary is what gets written to the property list.\n var idsToDicts = [String: PropertyList]()\n\n /// Returns the quoted identifier for the object, assigning one if needed.\n func id(of object: PropertyListSerializable) -> String {\n // We need a "serialized object ref" wrapper for the `objsToIds` map.\n let serObjRef = SerializedObjectRef(object)\n if let id = objsToIds[serObjRef] {\n return "\"\(id)\""\n }\n // We currently always assign identifiers starting at 1 and going up.\n // FIXME: This is a suboptimal format for object identifier strings;\n // for debugging purposes they should at least sort in numeric order.\n let id = object.objectID ?? "OBJ_\(objsToIds.count + 1)"\n objsToIds[serObjRef] = id\n return "\"\(id)\""\n }\n\n /// Serializes `object` by asking it to construct a plist dictionary and\n /// then adding that dictionary to the serializer. This may in turn cause\n /// recursive invocations of `serialize(object:)`; the closure of these\n /// invocations end up serializing the whole object graph.\n @discardableResult\n func serialize(object: PropertyListSerializable) throws -> String {\n // Assign an id for the object, if it doesn't already have one.\n let id = self.id(of: object)\n\n // If that id is already in `idsToDicts`, we've detected recursion or\n // repeated serialization.\n guard idsToDicts[id] == nil else {\n throw InternalError("tried to serialize \(object) twice")\n }\n\n // Set a sentinel value in the `idsToDicts` mapping to detect recursion.\n idsToDicts[id] = .dictionary([:])\n\n // Now recursively serialize the object, and store the result (replacing\n // the sentinel).\n idsToDicts[id] = try .dictionary(object.serialize(to: self))\n\n // Finally, return the identifier so the caller can store it (usually in\n // an attribute in its own serialization dictionary).\n return id\n }\n}\n\nfileprivate protocol PropertyListSerializable: AnyObject {\n /// Called by the Serializer to construct and return a dictionary for a\n /// serializable object. The entries in the dictionary should represent\n /// the receiver's attributes and relationships, as PropertyList values.\n ///\n /// Every object that is written to the Serializer is assigned an id (an\n /// arbitrary but unique string). Forward references can use `id(of:)`\n /// of the Serializer to assign and access the id before the object is\n /// actually written.\n ///\n /// Implementations can use the Serializer's `serialize(object:)` method\n /// to serialize owned objects (getting an id to the serialized object,\n /// which can be stored in one of the attributes) or can use the `id(of:)`\n /// method to store a reference to an unowned object.\n ///\n /// The implementation of this method for each serializable objects looks\n /// something like this:\n ///\n /// // Create a `PBXSomeClassOrOther` plist dictionary.\n /// var dict = [String: PropertyList]()\n /// dict["isa"] = .string("PBXSomeClassOrOther")\n /// dict["name"] = .string(name)\n /// if let path = path { dict["path"] = .string(path) }\n /// dict["mainGroup"] = .identifier(serializer.serialize(object: mainGroup))\n /// dict["subitems"] = .array(subitems.map({ .string($0.id) }))\n /// dict["cross-ref"] = .identifier(serializer.id(of: unownedObject))\n /// return dict\n ///\n /// FIXME: I'm not totally happy with how this looks. It's far too clunky\n /// and could be made more elegant. However, since the Xcode project model\n /// is static, this is not something that will need to evolve over time.\n /// What does need to evolve, which is how the project model is constructed\n /// from the package contents, is where the elegance and simplicity really\n /// matters. So this is acceptable for now in the interest of getting it\n /// done.\n\n /// A custom ID to use for the instance, if enabled.\n ///\n /// This ID must be unique across the entire serialized graph.\n var objectID: String? { get }\n\n /// Should create and return a property list dictionary of the object's\n /// attributes. This function may also use the serializer's `serialize()`\n /// function to serialize other objects, and may use `id(of:)` to access\n /// ids of objects that either have or will be serialized.\n func serialize(to serializer: PropertyListSerializer) throws -> [String: PropertyList]\n}\n\nextension PropertyListSerializable {\n var objectID: String? {\n return nil\n }\n}\n\nextension PropertyList {\n var isEmpty: Bool {\n switch self {\n case let .identifier(string): return string.isEmpty\n case let .string(string): return string.isEmpty\n case let .array(array): return array.isEmpty\n case let .dictionary(dictionary): return dictionary.isEmpty\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_XcodeProjectModelSerialization.swift
cpp_apple_swift_utils_swift-xcodegen_Sources_Xcodeproj_XcodeProjectModelSerialization.swift
Swift
23,739
0.95
0.157989
0.353755
node-utils
427
2023-08-14T13:27:25.756800
MIT
false
6ceb2d4e9512e7b0025375fac4985f8e
// swift-tools-version: 5.10.0\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n name: "swift_snapshot_tool",\n platforms: [.macOS(.v14)],\n products: [\n // Products define the executables and libraries a package produces, making them visible to other packages.\n .executable(\n name: "swift_snapshot_tool",\n targets: ["swift_snapshot_tool"]),\n ],\n dependencies: [\n // other dependencies\n .package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0"),\n ],\n targets: [\n // Targets are the basic building blocks of a package, defining a module or a test suite.\n // Targets can depend on other targets in this package and products from dependencies.\n .executableTarget(\n name: "swift_snapshot_tool",\n dependencies: [.product(name: "ArgumentParser", package: "swift-argument-parser")]),\n .testTarget(\n name: "swift_snapshot_toolTests",\n dependencies: ["swift_snapshot_tool"]\n ),\n ]\n)\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Package.swift
cpp_apple_swift_utils_swift_snapshot_tool_Package.swift
Swift
1,057
0.95
0
0.214286
awesome-app
854
2025-01-08T04:20:55.502351
Apache-2.0
false
12c04625485b84cda0481c5daec7b0c2
//===--- bisect_toolchains.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Foundation\n\nstruct BisectToolchains: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: "bisect",\n discussion: """\n Bisects on exit status of attached script. Passes in name of swift as the\n environment variables \(environmentVariables).\n """)\n\n @Flag var platform: Platform = .osx\n\n @Flag(help: "The specific branch of toolchains we should download")\n var branch: Branch = .development\n\n @Option(\n help: """\n The directory where toolchains should be downloaded to.\n """)\n var workspace: String = "/tmp/swift_snapshot_tool_workspace_v1"\n\n @Option(\n help: """\n The script that should be run. It runs a specific swift compilation and\n optionally program using the passed in environment variables\n \(environmentVariables)\n """)\n var script: String\n\n @Option(help: "Oldest Date. Expected to Pass. We use the first snapshot produced before the given date")\n var oldDate: String\n\n var oldDateAsDate: Date {\n let d = DateFormatter()\n d.dateFormat = "yyyy-MM-dd"\n guard let result = d.date(from: oldDate) else {\n log("Improperly formatted date: \(oldDate)! Expected format: yyyy_MM_dd.")\n fatalError()\n }\n return result\n }\n\n @Option(help: """\n Newest Date. Expected to fail. If not set, use newest snapshot. We use the\n first snapshot after new date\n """)\n var newDate: String?\n\n var newDateAsDate: Date? {\n guard let newDate = self.newDate else { return nil }\n let d = DateFormatter()\n d.dateFormat = "yyyy-MM-dd"\n guard let result = d.date(from: newDate) else {\n log("Improperly formatted date: \(newDate)! Expected format: yyyy_MM_dd.")\n fatalError()\n }\n return result\n }\n\n @Flag(help: "Invert the test so that we assume the newest succeeds")\n var invert = false\n\n @Argument(help: "Extra constant arguments to pass to the test")\n var extraArgs: [String] = []\n\n mutating func run() async throws {\n if !FileManager.default.fileExists(atPath: workspace) {\n do {\n log("[INFO] Creating workspace: \(workspace)")\n try FileManager.default.createDirectory(\n atPath: workspace,\n withIntermediateDirectories: true, attributes: nil)\n } catch {\n log(error.localizedDescription)\n }\n }\n\n // Load our tags from swift's github repo\n let tags = try! await getTagsFromSwiftRepo(branch: branch)\n\n // Newest is first. So 0 maps to the newest tag. We do this so someone can\n // just say 50 toolchains ago. To get a few weeks worth. This is easier than\n // writing dates a lot.\n let oldDateAsDate = self.oldDateAsDate\n guard let goodTagIndex = tags.firstIndex(where: { $0.tag.date(branch: self.branch) <= oldDateAsDate }) else {\n log("Failed to find tag with date: \(oldDateAsDate)")\n fatalError()\n }\n\n let badTagIndex: Int\n if let newDateAsDate = self.newDateAsDate {\n let b = tags.firstIndex(where: { $0.tag.date(branch: self.branch) < newDateAsDate })\n guard let b else {\n log("Failed to find tag newer than date: \(newDateAsDate)")\n fatalError()\n }\n badTagIndex = b\n } else {\n badTagIndex = 0\n }\n\n let totalTags = goodTagIndex - badTagIndex\n if totalTags < 0 {\n log("Good tag is newer than bad tag... good tag expected to be older than bad tag")\n fatalError()\n }\n\n var startIndex = goodTagIndex\n var endIndex = badTagIndex\n\n // First check if the newest toolchain succeeds. We assume this in our bisection.\n do {\n log("Testing that Oldest Tag Succeeds: \(tags[startIndex].tag))")\n let result = try! await downloadToolchainAndRunTest(\n platform: platform, tag: tags[startIndex].tag, branch: branch, workspace: workspace, script: script,\n extraArgs: extraArgs)\n var success = result == 0\n if self.invert {\n success = !success\n }\n if !success {\n log("[INFO] Oldest assumed good snapshot fails! Did you forget to pass --invert?")\n fatalError()\n } else {\n log("[INFO] Oldest snapshot passes test. Snapshot: \(tags[startIndex])")\n }\n }\n\n do {\n log("Testing that Newest Tag Fails: \(tags[endIndex].tag))")\n let result = try! await downloadToolchainAndRunTest(\n platform: platform, tag: tags[endIndex].tag, branch: branch, workspace: workspace, script: script,\n extraArgs: extraArgs)\n var success = result != 0\n if self.invert {\n success = !success\n }\n if !success {\n log("[INFO] Newest assumed bad snapshot succeeds! Did you forget to pass --invert?")\n fatalError()\n } else {\n log("[INFO] Newest snapshot passes test. Snapshot: \(tags[endIndex])")\n }\n }\n\n log("[INFO] Testing \(totalTags) toolchains")\n while startIndex != endIndex && startIndex != endIndex {\n let mid = (startIndex + endIndex) / 2\n\n let midValue = tags[mid].tag\n log(\n "[INFO] Visiting Mid: \(mid) with (Start, End) = (\(startIndex),\(endIndex)). Tag: \(midValue)"\n )\n let result = try! await downloadToolchainAndRunTest(\n platform: platform, tag: midValue, branch: branch, workspace: workspace, script: script,\n extraArgs: extraArgs)\n\n var success = result == 0\n if self.invert {\n success = !success\n }\n\n let midIsEndIndex = mid == endIndex\n\n if success {\n log("[INFO] PASSES! Setting start to mid!")\n startIndex = mid\n } else {\n log("[INFO] FAILS! Setting end to mid")\n endIndex = mid\n }\n\n if midIsEndIndex {\n log("Last successful value: \(tags[mid+1])")\n break\n }\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_bisect_toolchains.swift
cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_bisect_toolchains.swift
Swift
6,237
0.95
0.104167
0.096386
react-lib
568
2023-10-22T08:31:42.963917
MIT
false
929e4d38d95e8eea3db3c9cf27072272
//===--- download_toolchain.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nprivate let SWIFT_BASE_URL = "https://swift.org/builds"\n\nprivate func fileExists(_ path: String) -> Bool {\n FileManager.default.fileExists(atPath: path)\n}\n\nenum DownloadFileError: Error {\n case failedToGetURL\n}\n\nprivate func downloadFile(url: URL, localPath: URL, verboseDownload: Bool = true) async throws {\n let config = URLSessionConfiguration.`default`\n let session = URLSession(configuration: config)\n return try await withCheckedThrowingContinuation { continuation in\n let task = session.downloadTask(with: url) {\n urlOrNil, responseOrNil, errorOrNil in\n // check for and handle errors:\n // * errorOrNil should be nil\n // * responseOrNil should be an HTTPURLResponse with statusCode in 200..<299\n\n guard let fileURL = urlOrNil else {\n continuation.resume(throwing: DownloadFileError.failedToGetURL)\n return\n }\n\n do {\n // Remove it if it is already there. Swallow the error if it is not\n // there.\n try FileManager.default.removeItem(at: localPath)\n } catch {}\n\n do {\n // Then move it... not swalling any errors.\n try FileManager.default.moveItem(at: fileURL, to: localPath)\n } catch let e {\n continuation.resume(throwing: e)\n return\n }\n\n continuation.resume()\n }\n\n task.resume()\n while task.state != URLSessionTask.State.completed {\n sleep(1)\n if verboseDownload {\n let percent = String(\n format: "%.2f",\n Float(task.countOfBytesReceived) / Float(task.countOfBytesExpectedToReceive) * 100)\n log("\(percent)%. Bytes \(task.countOfBytesReceived)/\(task.countOfBytesExpectedToReceive)")\n }\n }\n }\n}\n\nprivate func shell(_ command: String, environment: [String: String] = [:],\n mustSucceed: Bool = true,verbose: Bool = false,\n extraArgs: [String] = []) -> (\n stdout: String, stderr: String, exitCode: Int\n) {\n let task = Process()\n let stdout = Pipe()\n let stderr = Pipe()\n\n task.standardOutput = stdout\n task.standardError = stderr\n var newCommand = command\n if extraArgs.count != 0 {\n newCommand = newCommand.appending(" ").appending(extraArgs.joined(separator: " "))\n }\n task.arguments = ["-c", newCommand]\n if !environment.isEmpty {\n if let e = task.environment {\n log("Task Env: \(e)")\n log("Passed in Env: \(environment)")\n task.environment = e.merging(\n environment,\n uniquingKeysWith: {\n (current, _) in current\n })\n } else {\n task.environment = environment\n }\n }\n if verbose {\n log("Command: \(command)\n")\n }\n task.launchPath = "/bin/zsh"\n task.standardInput = nil\n task.launch()\n task.waitUntilExit()\n\n let stderrData = String(\n decoding: stderr.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)\n let stdoutData = String(\n decoding: stdout.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)\n if verbose {\n log("StdErr:\n\(stderrData)\n")\n log("StdOut:\n\(stdoutData)\n")\n }\n if mustSucceed && task.terminationStatus != 0 {\n log("Command Failed!")\n fatalError()\n }\n return (stdout: stdoutData, stderr: stderrData, Int(task.terminationStatus))\n}\n\nfunc downloadToolchainAndRunTest(\n platform: Platform, tag: Tag, branch: Branch,\n workspace: String, script: String,\n extraArgs: [String],\n verbose: Bool = false\n) async throws -> Int {\n let fileType = platform.fileType\n let toolchainType = platform.toolchainType\n\n let realBranch = branch != .development ? "swift-\(branch)-branch" : branch.rawValue\n let toolchainDir = "\(workspace)/\(tag.name)-\(platform)"\n let downloadPath = URL(fileURLWithPath: "\(workspace)/\(tag.name)-\(platform).\(fileType)")\n if !fileExists(toolchainDir) {\n let downloadURL = URL(\n string:\n "\(SWIFT_BASE_URL)/\(realBranch)/\(toolchainType)/\(tag.name)/\(tag.name)-\(platform).\(fileType)"\n )!\n log("[INFO] Starting Download: \(downloadURL) -> \(downloadPath)")\n try await downloadFile(url: downloadURL, localPath: downloadPath)\n log("[INFO] Finished Download: \(downloadURL) -> \(downloadPath)")\n } else {\n log("[INFO] File exists! No need to download! Path: \(downloadPath)")\n }\n\n switch platform {\n case .osx:\n if !fileExists(toolchainDir) {\n log("[INFO] Installing: \(downloadPath)")\n _ = shell("pkgutil --expand \(downloadPath.path) \(toolchainDir)")\n let payloadPath = "\(toolchainDir)/\(tag.name)-osx-package.pkg/Payload"\n _ = shell("tar -xf \(payloadPath) -C \(toolchainDir)")\n } else {\n log("[INFO] No need to install: \(downloadPath)")\n }\n\n let swiftcPath = "\(toolchainDir)/usr/bin/swiftc"\n let swiftFrontendPath = "\(toolchainDir)/usr/bin/swift-frontend"\n // Just for now just support macosx.\n let platform = "macosx"\n let swiftLibraryPath = "\(toolchainDir)/usr/lib/swift/\(platform)"\n log(shell("\(swiftcPath) --version").stdout)\n let exitCode = shell(\n "\(script)", environment: ["SWIFTC": swiftcPath, "SWIFT_FRONTEND": swiftFrontendPath,\n "SWIFT_LIBRARY_PATH": swiftLibraryPath],\n mustSucceed: false,\n verbose: verbose,\n extraArgs: extraArgs\n ).exitCode\n log("[INFO] Exit code: \(exitCode). Tag: \(tag.name). Script: \(script)")\n return exitCode\n case .ubuntu1404, .ubuntu1604, .ubuntu1804:\n fatalError("Unsupported platform: \(platform)")\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_download_toolchain.swift
cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_download_toolchain.swift
Swift
5,926
0.95
0.131429
0.113924
react-lib
658
2024-09-20T13:44:10.733769
MIT
false
e7a27686caacc726a0c7e20d2bcb1c97
//===--- get_tags.swift ---------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct CommitInfo: Decodable {\n let sha: String\n let type: String\n let url: String\n}\n\nstruct Tag: Decodable {\n let ref: String\n let nodeId: String\n let object: CommitInfo\n let url: String\n var name: Substring {\n ref.dropFirst(10)\n }\n\n func dateString(_ branch: Branch) -> Substring {\n // FIXME: If we ever actually use interesting a-b builds, we should capture this information\n // would be better to do it sooner than later.\n return name.dropFirst("swift-".count + branch.rawValue.count + "-SNAPSHOT-".count).dropLast(2)\n }\n\n func date(branch: Branch) -> Date {\n // TODO: I think that d might be a class... if so, we really want to memoize\n // this.\n let d = DateFormatter()\n d.dateFormat = "yyyy-MM-dd"\n return d.date(from: String(dateString(branch)))!\n }\n}\n\n\nextension Tag: CustomDebugStringConvertible {\n var debugDescription: String {\n String(name)\n }\n}\n\n/// A pair of a branch and a tag\nstruct BranchTag {\n var tag: Tag\n var branch: Branch\n}\n\nextension BranchTag: CustomDebugStringConvertible {\n var debugDescription: String {\n tag.debugDescription\n }\n}\n\nfunc getTagsFromSwiftRepo(branch: Branch, dryRun: Bool = false) async throws -> [BranchTag] {\n let github_tag_list_url: URL\n if !dryRun {\n github_tag_list_url = URL(string: "https://api.github.com/repos/apple/swift/git/refs/tags")!\n } else {\n github_tag_list_url = URL(string: "file:///Users/gottesmm/triage/github_data")!\n }\n\n let decoder = JSONDecoder()\n decoder.keyDecodingStrategy = .convertFromSnakeCase\n\n log("[INFO] Starting to download snapshot information from github.")\n async let data = URLSession.shared.data(from: github_tag_list_url).0\n let allTags = try! decoder.decode([Tag].self, from: await data)\n log("[INFO] Finished downloading snapshot information from github.")\n\n let snapshotTagPrefix = "swift-\(branch.rawValue.uppercased())"\n\n // Then filter the tags to just include the specific snapshot branch\n // prefix. Add the branch to an aggregate BranchTag.\n var filteredTags: [BranchTag] = allTags.filter {\n $0.name.starts(with: snapshotTagPrefix)\n }.map {\n BranchTag(tag: $0, branch: branch)\n }\n\n // Then sort so that the newest branch prefix \n filteredTags.sort { $0.tag.ref < $1.tag.ref }\n filteredTags.reverse()\n\n return filteredTags\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_get_tags.swift
cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_get_tags.swift
Swift
2,843
0.95
0.063158
0.240506
vue-tools
926
2023-11-15T15:48:27.183055
BSD-3-Clause
false
0dbc114dc5584b7f844f0095d8e2b388
//===--- github_repository.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nenum Platform: String, EnumerableFlag {\n case osx\n case ubuntu1404\n case ubuntu1604\n case ubuntu1804\n\n var fileType: String {\n switch self {\n case .osx:\n return "pkg"\n case .ubuntu1404,\n .ubuntu1604,\n .ubuntu1804:\n return "tar.gz"\n }\n }\n\n var toolchainType: String {\n switch self {\n case .osx:\n return "xcode"\n case .ubuntu1404,\n .ubuntu1604,\n .ubuntu1804:\n return self.rawValue\n }\n }\n}\n\nenum Branch: String, EnumerableFlag {\n case development\n case release50 = "5.0"\n case release60 = "6.0"\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_github_repository.swift
cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_github_repository.swift
Swift
1,112
0.95
0.083333
0.255814
vue-tools
460
2024-02-29T16:00:38.134888
BSD-3-Clause
false
467dcec22372d2888bc87f303ded7c57
//===--- list_snapshots.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nstruct ListSnapshots: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: "list")\n\n @Flag var platform: Platform = .osx\n\n @Flag(help: "The specific branch of toolchains we should download")\n var branch: Branch = .development\n\n mutating func run() async throws {\n // Load our tags from swift's github repo\n let tags = try! await getTagsFromSwiftRepo(branch: branch)\n for t in tags.enumerated() {\n print(t.0, t.1)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_list_snapshots.swift
cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_list_snapshots.swift
Swift
1,024
0.95
0.129032
0.461538
node-utils
550
2024-09-13T01:09:52.752258
GPL-3.0
false
f0d6809639c920111ea3f55570aba2e6
//===--- logging.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nfunc log(_ msg: String) {\n let msgWithSpace = "\(msg)\n"\n msgWithSpace.data(using: .utf8)\n .map(FileHandle.standardError.write)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_logging.swift
cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_logging.swift
Swift
674
0.95
0.105263
0.647059
python-kit
764
2024-01-23T12:03:17.205237
GPL-3.0
false
95a6698f5aac2254d01b74b4902fbf7f
//===--- misc_global_strings.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nlet environmentVariables = "SWIFTC, SWIFT_FRONTEND, and SWIFT_LIBRARY_PATH"\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_misc_global_strings.swift
cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_misc_global_strings.swift
Swift
596
0.8
0.153846
0.916667
vue-tools
26
2024-08-12T05:30:25.019423
MIT
false
ecee12c06beceae33da6b3277af9052a
//===--- run_toolchain.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Foundation\n\nstruct RunToolchains: AsyncParsableCommand {\n static let configuration = CommandConfiguration(\n commandName: "run",\n discussion: """\n Run a toolchain like bisect would. Passed the environment variables:\n \(environmentVariables)\n """)\n\n @Flag var platform: Platform = .osx\n\n @Flag(help: "The specific branch of toolchains we should download")\n var branch: Branch = .development\n\n @Option(\n help: """\n The directory where toolchains should be downloaded to.\n """)\n var workspace: String = "/tmp/swift_snapshot_tool_workspace_v1"\n\n @Option(\n help: """\n The script that should be run. The environment variable\n SWIFT_EXEC is used by the script to know where swift-frontend is\n """)\n var script: String\n\n @Option(help: "Date. We use the first snapshot produced before the given date")\n var date: String\n\n var dateAsDate: Date {\n let d = DateFormatter()\n d.dateFormat = "yyyy-MM-dd"\n guard let result = d.date(from: date) else {\n log("Improperly formatted date: \(date)! Expected format: yyyy_MM_dd.")\n fatalError()\n }\n return result\n }\n\n @Flag(help: "Invert the test so that we assume the newest succeeds")\n var invert = false\n\n @Argument(help: "Extra constant arguments to pass to the test")\n var extraArgs: [String] = []\n\n @Flag(help: "Attempt to use the snapshot tag that is immediately younger than the selected")\n var offset_by_one = false\n\n @Flag(help: "Emit verbose logging")\n var verbose = false\n\n mutating func run() async throws {\n if !FileManager.default.fileExists(atPath: workspace) {\n do {\n log("[INFO] Creating workspace: \(workspace)")\n try FileManager.default.createDirectory(\n atPath: workspace,\n withIntermediateDirectories: true, attributes: nil)\n } catch {\n log(error.localizedDescription)\n }\n }\n\n // Load our tags from swift's github repo\n let tags = try! await getTagsFromSwiftRepo(branch: branch)\n\n let date = self.dateAsDate\n guard var tagIndex = tags.firstIndex(where: { $0.tag.date(branch: self.branch) <= date }) else {\n log("Failed to find tag with date: \(date)")\n fatalError()\n }\n\n if self.offset_by_one {\n if tagIndex == tags.startIndex {\n log("[INFO] Cannot run one tag earlier than the first snapshot tag?!")\n fatalError()\n }\n tagIndex = tagIndex - 1\n }\n\n // Newest is first. So 0 maps to the newest tag. We do this so someone can\n // just say 50 toolchains ago. To get a few weeks worth. This is easier than\n // writing dates a lot.\n\n let result = try! await downloadToolchainAndRunTest(\n platform: platform, tag: tags[tagIndex].tag, branch: branch, workspace: workspace, script: script,\n extraArgs: extraArgs, verbose: verbose)\n var success = result == 0\n if self.invert {\n success = !success\n }\n if success {\n log("[INFO] Snapshot succeeds!")\n //fatalError()\n } else {\n log("[INFO] Snapshot fails!")\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_run_toolchain.swift
cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_run_toolchain.swift
Swift
3,574
0.95
0.096491
0.166667
react-lib
605
2024-12-19T23:37:08.415918
MIT
false
d6ac08d9c35adc110436a9373202a162
//===--- swift_snapshot_tool.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nstruct SwiftSnapshotTool: ParsableCommand {\n static let configuration = CommandConfiguration(\n abstract: "A utility for working with swift snapshots from swift.org.",\n subcommands: [\n BisectToolchains.self,\n ListSnapshots.self,\n RunToolchains.self,\n ])\n}\n\n@main\nstruct AsyncMain: AsyncMainProtocol {\n typealias Command = SwiftSnapshotTool\n}\n
dataset_sample\swift\swift\cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_swift_snapshot_tool.swift
cpp_apple_swift_utils_swift_snapshot_tool_Sources_swift_snapshot_tool_swift_snapshot_tool.swift
Swift
910
0.95
0.107143
0.44
python-kit
947
2023-11-27T05:07:17.439379
MIT
false
99c8d1d2039ec835f9ac73d8cc9b4b8b
// swift-tools-version:5.3\n// Copyright 2019-2024 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n\nimport PackageDescription\n\nlet package = Package(\n name: "Tauri",\n platforms: [\n .macOS(.v10_13),\n .iOS(.v11),\n ],\n products: [\n // Products define the executables and libraries a package produces, and make them visible to other packages.\n .library(\n name: "Tauri",\n type: .static,\n targets: ["Tauri"])\n ],\n dependencies: [\n // Dependencies declare other packages that this package depends on.\n .package(name: "SwiftRs", url: "https://github.com/Brendonovich/swift-rs", from: "1.0.0")\n ],\n targets: [\n // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n // Targets can depend on other targets in this package, and on products in packages this package depends on.\n .target(\n name: "Tauri",\n dependencies: [\n .byName(name: "SwiftRs")\n ],\n path: "Sources"\n ),\n .testTarget(\n name: "TauriTests",\n dependencies: ["Tauri"]\n ),\n ]\n)\n
dataset_sample\swift\tauri-apps_tauri\crates\tauri\mobile\ios-api\Package.swift
Package.swift
Swift
1,142
0.95
0
0.210526
node-utils
498
2025-03-20T06:49:30.851902
MIT
false
bf2ebd98811d30292386e57a8d9da468
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n\nimport Foundation\n\nlet CHANNEL_PREFIX = "__CHANNEL__:"\nlet channelDataKey = CodingUserInfoKey(rawValue: "sendChannelData")!\n\npublic class Channel: Decodable {\n public let id: UInt64\n let handler: (UInt64, String) -> Void\n\n public required init(from decoder: Decoder) throws {\n let container = try decoder.singleValueContainer()\n let channelDef = try container.decode(String.self)\n\n let components = channelDef.components(separatedBy: CHANNEL_PREFIX)\n if components.count < 2 {\n throw DecodingError.dataCorruptedError(\n in: container,\n debugDescription: "Invalid channel definition from \(channelDef)"\n )\n\n }\n guard let channelId = UInt64(components[1]) else {\n throw DecodingError.dataCorruptedError(\n in: container,\n debugDescription: "Invalid channel ID from \(channelDef)"\n )\n }\n\n guard let handler = decoder.userInfo[channelDataKey] as? (UInt64, String) -> Void else {\n throw DecodingError.dataCorruptedError(\n in: container,\n debugDescription: "missing userInfo for Channel handler. This is a Tauri issue"\n )\n }\n\n self.id = channelId\n self.handler = handler\n }\n\n func serialize(_ data: JsonValue) -> String {\n do {\n return try data.jsonRepresentation() ?? "\"Failed to serialize payload\""\n } catch {\n return "\"\(error)\""\n }\n }\n\n public func send(_ data: JsonObject) {\n send(.dictionary(data))\n }\n\n public func send(_ data: JsonValue) {\n handler(id, serialize(data))\n }\n\n public func send<T: Encodable>(_ data: T) throws {\n let json = try JSONEncoder().encode(data)\n handler(id, String(decoding: json, as: UTF8.self))\n }\n\n}\n
dataset_sample\swift\tauri-apps_tauri\crates\tauri\mobile\ios-api\Sources\Tauri\Channel.swift
Channel.swift
Swift
1,821
0.95
0.123077
0.057692
awesome-app
543
2024-10-11T09:42:16.474915
GPL-3.0
false
949c652c9a1126e43168b795dc0619dc
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n\nimport Foundation\nimport UIKit\n\n@objc public class Invoke: NSObject {\n public let command: String\n let callback: UInt64\n let error: UInt64\n let data: String\n let sendResponse: (UInt64, String?) -> Void\n let sendChannelData: (UInt64, String) -> Void\n\n public init(\n command: String, callback: UInt64, error: UInt64,\n sendResponse: @escaping (UInt64, String?) -> Void,\n sendChannelData: @escaping (UInt64, String) -> Void, data: String\n ) {\n self.command = command\n self.callback = callback\n self.error = error\n self.data = data\n self.sendResponse = sendResponse\n self.sendChannelData = sendChannelData\n }\n\n public func getRawArgs() -> String {\n return self.data\n }\n\n public func getArgs() throws -> JSObject {\n let jsonData = self.data.data(using: .utf8)!\n let data = try JSONSerialization.jsonObject(with: jsonData, options: [])\n return JSTypes.coerceDictionaryToJSObject(\n (data as! NSDictionary), formattingDatesAsStrings: true)!\n }\n\n public func parseArgs<T: Decodable>(_ type: T.Type) throws -> T {\n let jsonData = self.data.data(using: .utf8)!\n let decoder = JSONDecoder()\n decoder.userInfo[channelDataKey] = sendChannelData\n return try decoder.decode(type, from: jsonData)\n }\n\n func serialize(_ data: JsonValue) -> String {\n do {\n return try data.jsonRepresentation() ?? "\"Failed to serialize payload\""\n } catch {\n return "\"\(error)\""\n }\n }\n\n public func resolve() {\n sendResponse(callback, nil)\n }\n\n public func resolve(_ data: JsonObject) {\n resolve(.dictionary(data))\n }\n\n public func resolve(_ data: JsonValue) {\n sendResponse(callback, serialize(data))\n }\n\n public func resolve<T: Encodable>(_ data: T) {\n do {\n let json = try JSONEncoder().encode(data)\n sendResponse(callback, String(decoding: json, as: UTF8.self))\n } catch {\n sendResponse(self.error, "\"\(error)\"")\n }\n }\n\n public func reject(\n _ message: String, code: String? = nil, error: Error? = nil, data: JsonValue? = nil\n ) {\n let payload: NSMutableDictionary = [\n "message": message\n ]\n\n if let code = code {\n payload["code"] = code\n }\n\n if let error = error {\n payload["error"] = error\n }\n\n if let data = data {\n switch data {\n case .dictionary(let dict):\n for entry in dict {\n payload[entry.key] = entry.value\n }\n }\n }\n\n sendResponse(self.error, serialize(.dictionary(payload as! JsonObject)))\n }\n\n public func unimplemented() {\n unimplemented("not implemented")\n }\n\n public func unimplemented(_ message: String) {\n reject(message)\n }\n\n public func unavailable() {\n unavailable("not available")\n }\n\n public func unavailable(_ message: String) {\n reject(message)\n }\n}\n
dataset_sample\swift\tauri-apps_tauri\crates\tauri\mobile\ios-api\Sources\Tauri\Invoke.swift
Invoke.swift
Swift
2,928
0.95
0.101695
0.030612
react-lib
768
2023-09-25T01:25:52.831786
MIT
false
64b944a96b7dc28c1dfa594c44c80526
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n\nimport Foundation\n\npublic typealias JsonObject = [String: Any?]\n\npublic enum JsonValue {\n case dictionary(JsonObject)\n\n enum SerializationError: Error {\n case invalidObject\n }\n\n public func jsonRepresentation(includingFields: JsonObject? = nil) throws -> String? {\n switch self {\n case .dictionary(var dictionary):\n if let fields = includingFields {\n dictionary.merge(fields) { (current, _) in current }\n }\n dictionary = prepare(dictionary: dictionary)\n guard JSONSerialization.isValidJSONObject(dictionary) else {\n throw SerializationError.invalidObject\n }\n let data = try JSONSerialization.data(withJSONObject: dictionary, options: [])\n return String(data: data, encoding: .utf8)\n }\n }\n\n private static let formatter = ISO8601DateFormatter()\n\n private func prepare(dictionary: JsonObject) -> JsonObject {\n return dictionary.mapValues { (value) -> Any in\n if let date = value as? Date {\n return JsonValue.formatter.string(from: date)\n } else if let aDictionary = value as? JsonObject {\n return prepare(dictionary: aDictionary)\n } else if let anArray = value as? [Any] {\n return prepare(array: anArray)\n }\n return value\n }\n }\n\n private func prepare(array: [Any]) -> [Any] {\n return array.map { (value) -> Any in\n if let date = value as? Date {\n return JsonValue.formatter.string(from: date)\n } else if let aDictionary = value as? JsonObject {\n return prepare(dictionary: aDictionary)\n } else if let anArray = value as? [Any] {\n return prepare(array: anArray)\n }\n return value\n }\n }\n}\n
dataset_sample\swift\tauri-apps_tauri\crates\tauri\mobile\ios-api\Sources\Tauri\JsonValue.swift
JsonValue.swift
Swift
1,692
0.95
0.155172
0.06
vue-tools
183
2025-06-22T14:11:43.989563
MIT
false
04ea51d2b6468096d97369265a83b6c8