hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
67bd9bd8b981bc9a132239e18ff31548088a90e1
567
// // Cache.swift // ForumThreads // // Created by aSqar on 08.05.2018. // Copyright © 2018 Askar Bakirov. All rights reserved. // import Foundation import RealmSwift class Cache { static let `default` = Cache() private init() { } func load<PlainType: RealmMappableProtocol, PKType>(byPK pk: PKType) -> PlainType { let realm = try! Realm() if let realmObject = realm.object(ofType: PlainType.RealmType.self, forPrimaryKey: pk) { return PlainType.mapFromRealmObject(realmObject) } else { return PlainType() } } }
19.551724
92
0.663139
1d3d2a5a610121b85713e3e3d3c0b542f3d94af7
566
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // ExpressRouteCircuitPeeringProtocol is peering in an ExpressRouteCircuit resource. public protocol ExpressRouteCircuitPeeringProtocol : SubResourceProtocol { var properties: ExpressRouteCircuitPeeringPropertiesFormatProtocol? { get set } var name: String? { get set } var etag: String? { get set } }
47.166667
96
0.765018
56e2a0a7b3d9d543849bb85c83cb03c6cfe3a97d
184
// // LGContants.swift // LGModule // // Created by 鲁术光 on 2020/11/19. // import UIKit /// 是不是手机判断 public let jm_isPhone = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.phone
15.333333
79
0.706522
e02c89003d003d62d6f4170d59e4738652eae961
392
// // UISwitch.swift // Rex // // Created by David Rodrigues on 07/04/16. // Copyright © 2016 Neil Pankey. All rights reserved. // import ReactiveCocoa import UIKit extension UISwitch { /// Wraps a switch's `on` value in a bindable property. public var rex_on: MutableProperty<Bool> { return UIControl.rex_value(self, getter: { $0.on }, setter: { $0.on = $1 }) } }
20.631579
83
0.647959
d6ab2f54afa61a9868a8195e7d180f8e2550a6a3
2,878
import UIKit /** Defaults setting values. */ struct CosmosDefaultSettings { init() {} static let defaultColor = UIColor(red: 1, green: 149/255, blue: 0, alpha: 1) // MARK: - Star settings // ----------------------------- /// Border color of an empty star. static let emptyBorderColor = defaultColor /// Width of the border for the empty star. static let emptyBorderWidth: Double = 1 / Double(UIScreen.main.scale) /// Border color of a filled star. static let filledBorderColor = defaultColor /// Width of the border for a filled star. static let filledBorderWidth: Double = 1 / Double(UIScreen.main.scale) /// Background color of an empty star. static let emptyColor = UIColor.clear /// Background color of a filled star. static let filledColor = defaultColor /** Defines how the star is filled when the rating value is not an integer value. It can either show full stars, half stars or stars partially filled according to the rating value. */ static let fillMode = StarFillMode.full /// Rating value that is shown in the storyboard by default. static let rating: Double = 2.718281828 /// Distance between stars. static let starMargin: Double = 5 /** Array of points for drawing the star with size of 100 by 100 pixels. Supply your points if you need to draw a different shape. */ static let starPoints: [CGPoint] = [ CGPoint(x: 49.5, y: 0.0), CGPoint(x: 60.5, y: 35.0), CGPoint(x: 99.0, y: 35.0), CGPoint(x: 67.5, y: 58.0), CGPoint(x: 78.5, y: 92.0), CGPoint(x: 49.5, y: 71.0), CGPoint(x: 20.5, y: 92.0), CGPoint(x: 31.5, y: 58.0), CGPoint(x: 0.0, y: 35.0), CGPoint(x: 38.5, y: 35.0) ] /// Size of a single star. static var starSize: Double = 20 /// The total number of stars to be shown. static let totalStars = 5 // MARK: - Text settings // ----------------------------- /// Color of the text. static let textColor = UIColor(red: 127/255, green: 127/255, blue: 127/255, alpha: 1) /// Font for the text. static let textFont = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.footnote) /// Distance between the text and the stars. static let textMargin: Double = 5 /// Calculates the size of the default text font. It is used for making the text size configurable from the storyboard. static var textSize: Double { get { return Double(textFont.pointSize) } } // MARK: - Touch settings // ----------------------------- /// The lowest rating that user can set by touching the stars. static let minTouchRating: Double = 1 /// When `true` the star fill level is updated when user touches the cosmos view. When `false` the Cosmos view only shows the rating and does not act as the input control. static let updateOnTouch = true }
27.941748
178
0.641418
564e5ac95234016893880ed78f3598f8cbb283c5
1,377
import XCTest import class Foundation.Bundle final class surmagicTests: XCTestCase { func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. // Some of the APIs that we use below are available in macOS 10.13 and above. guard #available(macOS 10.13, *) else { return } let fooBinary = productsDirectory.appendingPathComponent("surmagic") let process = Process() process.executableURL = fooBinary let pipe = Pipe() process.standardOutput = pipe try process.run() process.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: .utf8) XCTAssertEqual(output, "Hello, world!\n") } /// Returns path to the built products directory. var productsDirectory: URL { #if os(macOS) for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") { return bundle.bundleURL.deletingLastPathComponent() } fatalError("couldn't find the products directory") #else return Bundle.main.bundleURL #endif } static var allTests = [ ("testExample", testExample), ] }
28.6875
87
0.635439
de8ab16f48b6e3fb78a1b6eb7183f47eb55f0459
232,812
//// Automatically Generated From SyntaxFactory.swift.gyb. //// Do Not Edit Directly! //===------- SyntaxFactory.swift - Syntax Factory implementations ---------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the SyntaxFactory, one of the most important client-facing // types in lib/Syntax and likely to be very commonly used. // // Effectively a namespace, SyntaxFactory is never instantiated, but is *the* // one-stop shop for making new Syntax nodes. Putting all of these into a // collection of static methods provides a single point of API lookup for // clients' convenience. // //===----------------------------------------------------------------------===// public enum SyntaxFactory { public static func makeToken(_ kind: TokenKind, presence: SourcePresence, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { let raw = RawSyntax.createAndCalcLength(kind: kind, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, presence: presence) let data = SyntaxData.forRoot(raw) return TokenSyntax(data) } public static func makeUnknownSyntax(tokens: [TokenSyntax]) -> UnknownSyntax { let raw = RawSyntax.createAndCalcLength(kind: .unknown, layout: tokens.map { $0.raw }, presence: .present) let data = SyntaxData.forRoot(raw) return UnknownSyntax(data) } /// MARK: Syntax Node Creation APIs public static func makeBlankUnknownDecl() -> UnknownDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .unknownDecl, layout: [ ], length: .zero, presence: .present)) return UnknownDeclSyntax(data) } public static func makeBlankUnknownExpr() -> UnknownExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .unknownExpr, layout: [ ], length: .zero, presence: .present)) return UnknownExprSyntax(data) } public static func makeBlankUnknownStmt() -> UnknownStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .unknownStmt, layout: [ ], length: .zero, presence: .present)) return UnknownStmtSyntax(data) } public static func makeBlankUnknownType() -> UnknownTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .unknownType, layout: [ ], length: .zero, presence: .present)) return UnknownTypeSyntax(data) } public static func makeBlankUnknownPattern() -> UnknownPatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .unknownPattern, layout: [ ], length: .zero, presence: .present)) return UnknownPatternSyntax(data) } public static func makeCodeBlockItem(item: Syntax, semicolon: TokenSyntax?, errorTokens: Syntax?) -> CodeBlockItemSyntax { let layout: [RawSyntax?] = [ item.raw, semicolon?.raw, errorTokens?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.codeBlockItem, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CodeBlockItemSyntax(data) } public static func makeBlankCodeBlockItem() -> CodeBlockItemSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .codeBlockItem, layout: [ RawSyntax.missing(SyntaxKind.unknown), nil, nil, ], length: .zero, presence: .present)) return CodeBlockItemSyntax(data) } public static func makeCodeBlockItemList( _ elements: [CodeBlockItemSyntax]) -> CodeBlockItemListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.codeBlockItemList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CodeBlockItemListSyntax(data) } public static func makeBlankCodeBlockItemList() -> CodeBlockItemListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .codeBlockItemList, layout: [ ], length: .zero, presence: .present)) return CodeBlockItemListSyntax(data) } public static func makeCodeBlock(leftBrace: TokenSyntax, statements: CodeBlockItemListSyntax, rightBrace: TokenSyntax) -> CodeBlockSyntax { let layout: [RawSyntax?] = [ leftBrace.raw, statements.raw, rightBrace.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.codeBlock, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CodeBlockSyntax(data) } public static func makeBlankCodeBlock() -> CodeBlockSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .codeBlock, layout: [ RawSyntax.missingToken(TokenKind.leftBrace), RawSyntax.missing(SyntaxKind.codeBlockItemList), RawSyntax.missingToken(TokenKind.rightBrace), ], length: .zero, presence: .present)) return CodeBlockSyntax(data) } public static func makeInOutExpr(ampersand: TokenSyntax, expression: ExprSyntax) -> InOutExprSyntax { let layout: [RawSyntax?] = [ ampersand.raw, expression.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.inOutExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return InOutExprSyntax(data) } public static func makeBlankInOutExpr() -> InOutExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .inOutExpr, layout: [ RawSyntax.missingToken(TokenKind.prefixAmpersand), RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return InOutExprSyntax(data) } public static func makePoundColumnExpr(poundColumn: TokenSyntax) -> PoundColumnExprSyntax { let layout: [RawSyntax?] = [ poundColumn.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundColumnExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundColumnExprSyntax(data) } public static func makeBlankPoundColumnExpr() -> PoundColumnExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundColumnExpr, layout: [ RawSyntax.missingToken(TokenKind.poundColumnKeyword), ], length: .zero, presence: .present)) return PoundColumnExprSyntax(data) } public static func makeTupleExprElementList( _ elements: [TupleExprElementSyntax]) -> TupleExprElementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tupleExprElementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TupleExprElementListSyntax(data) } public static func makeBlankTupleExprElementList() -> TupleExprElementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tupleExprElementList, layout: [ ], length: .zero, presence: .present)) return TupleExprElementListSyntax(data) } public static func makeArrayElementList( _ elements: [ArrayElementSyntax]) -> ArrayElementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.arrayElementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ArrayElementListSyntax(data) } public static func makeBlankArrayElementList() -> ArrayElementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .arrayElementList, layout: [ ], length: .zero, presence: .present)) return ArrayElementListSyntax(data) } public static func makeDictionaryElementList( _ elements: [DictionaryElementSyntax]) -> DictionaryElementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.dictionaryElementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DictionaryElementListSyntax(data) } public static func makeBlankDictionaryElementList() -> DictionaryElementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .dictionaryElementList, layout: [ ], length: .zero, presence: .present)) return DictionaryElementListSyntax(data) } public static func makeStringLiteralSegments( _ elements: [Syntax]) -> StringLiteralSegmentsSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.stringLiteralSegments, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return StringLiteralSegmentsSyntax(data) } public static func makeBlankStringLiteralSegments() -> StringLiteralSegmentsSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .stringLiteralSegments, layout: [ ], length: .zero, presence: .present)) return StringLiteralSegmentsSyntax(data) } public static func makeTryExpr(tryKeyword: TokenSyntax, questionOrExclamationMark: TokenSyntax?, expression: ExprSyntax) -> TryExprSyntax { let layout: [RawSyntax?] = [ tryKeyword.raw, questionOrExclamationMark?.raw, expression.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tryExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TryExprSyntax(data) } public static func makeBlankTryExpr() -> TryExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tryExpr, layout: [ RawSyntax.missingToken(TokenKind.tryKeyword), nil, RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return TryExprSyntax(data) } public static func makeAwaitExpr(awaitKeyword: TokenSyntax, expression: ExprSyntax) -> AwaitExprSyntax { let layout: [RawSyntax?] = [ awaitKeyword.raw, expression.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.awaitExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AwaitExprSyntax(data) } public static func makeBlankAwaitExpr() -> AwaitExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .awaitExpr, layout: [ RawSyntax.missingToken(TokenKind.awaitKeyword), RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return AwaitExprSyntax(data) } public static func makeDeclNameArgument(name: TokenSyntax, colon: TokenSyntax) -> DeclNameArgumentSyntax { let layout: [RawSyntax?] = [ name.raw, colon.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.declNameArgument, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DeclNameArgumentSyntax(data) } public static func makeBlankDeclNameArgument() -> DeclNameArgumentSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .declNameArgument, layout: [ RawSyntax.missingToken(TokenKind.unknown("")), RawSyntax.missingToken(TokenKind.colon), ], length: .zero, presence: .present)) return DeclNameArgumentSyntax(data) } public static func makeDeclNameArgumentList( _ elements: [DeclNameArgumentSyntax]) -> DeclNameArgumentListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.declNameArgumentList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DeclNameArgumentListSyntax(data) } public static func makeBlankDeclNameArgumentList() -> DeclNameArgumentListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .declNameArgumentList, layout: [ ], length: .zero, presence: .present)) return DeclNameArgumentListSyntax(data) } public static func makeDeclNameArguments(leftParen: TokenSyntax, arguments: DeclNameArgumentListSyntax, rightParen: TokenSyntax) -> DeclNameArgumentsSyntax { let layout: [RawSyntax?] = [ leftParen.raw, arguments.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.declNameArguments, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DeclNameArgumentsSyntax(data) } public static func makeBlankDeclNameArguments() -> DeclNameArgumentsSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .declNameArguments, layout: [ RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.declNameArgumentList), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return DeclNameArgumentsSyntax(data) } public static func makeIdentifierExpr(identifier: TokenSyntax, declNameArguments: DeclNameArgumentsSyntax?) -> IdentifierExprSyntax { let layout: [RawSyntax?] = [ identifier.raw, declNameArguments?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.identifierExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IdentifierExprSyntax(data) } public static func makeBlankIdentifierExpr() -> IdentifierExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .identifierExpr, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return IdentifierExprSyntax(data) } public static func makeSuperRefExpr(superKeyword: TokenSyntax) -> SuperRefExprSyntax { let layout: [RawSyntax?] = [ superKeyword.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.superRefExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SuperRefExprSyntax(data) } public static func makeBlankSuperRefExpr() -> SuperRefExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .superRefExpr, layout: [ RawSyntax.missingToken(TokenKind.superKeyword), ], length: .zero, presence: .present)) return SuperRefExprSyntax(data) } public static func makeNilLiteralExpr(nilKeyword: TokenSyntax) -> NilLiteralExprSyntax { let layout: [RawSyntax?] = [ nilKeyword.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.nilLiteralExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return NilLiteralExprSyntax(data) } public static func makeBlankNilLiteralExpr() -> NilLiteralExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .nilLiteralExpr, layout: [ RawSyntax.missingToken(TokenKind.nilKeyword), ], length: .zero, presence: .present)) return NilLiteralExprSyntax(data) } public static func makeDiscardAssignmentExpr(wildcard: TokenSyntax) -> DiscardAssignmentExprSyntax { let layout: [RawSyntax?] = [ wildcard.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.discardAssignmentExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DiscardAssignmentExprSyntax(data) } public static func makeBlankDiscardAssignmentExpr() -> DiscardAssignmentExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .discardAssignmentExpr, layout: [ RawSyntax.missingToken(TokenKind.wildcardKeyword), ], length: .zero, presence: .present)) return DiscardAssignmentExprSyntax(data) } public static func makeAssignmentExpr(assignToken: TokenSyntax) -> AssignmentExprSyntax { let layout: [RawSyntax?] = [ assignToken.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.assignmentExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AssignmentExprSyntax(data) } public static func makeBlankAssignmentExpr() -> AssignmentExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .assignmentExpr, layout: [ RawSyntax.missingToken(TokenKind.equal), ], length: .zero, presence: .present)) return AssignmentExprSyntax(data) } public static func makeSequenceExpr(elements: ExprListSyntax) -> SequenceExprSyntax { let layout: [RawSyntax?] = [ elements.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.sequenceExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SequenceExprSyntax(data) } public static func makeBlankSequenceExpr() -> SequenceExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .sequenceExpr, layout: [ RawSyntax.missing(SyntaxKind.exprList), ], length: .zero, presence: .present)) return SequenceExprSyntax(data) } public static func makeExprList( _ elements: [ExprSyntax]) -> ExprListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.exprList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ExprListSyntax(data) } public static func makeBlankExprList() -> ExprListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .exprList, layout: [ ], length: .zero, presence: .present)) return ExprListSyntax(data) } public static func makePoundLineExpr(poundLine: TokenSyntax) -> PoundLineExprSyntax { let layout: [RawSyntax?] = [ poundLine.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundLineExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundLineExprSyntax(data) } public static func makeBlankPoundLineExpr() -> PoundLineExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundLineExpr, layout: [ RawSyntax.missingToken(TokenKind.poundLineKeyword), ], length: .zero, presence: .present)) return PoundLineExprSyntax(data) } public static func makePoundFileExpr(poundFile: TokenSyntax) -> PoundFileExprSyntax { let layout: [RawSyntax?] = [ poundFile.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundFileExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundFileExprSyntax(data) } public static func makeBlankPoundFileExpr() -> PoundFileExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundFileExpr, layout: [ RawSyntax.missingToken(TokenKind.poundFileKeyword), ], length: .zero, presence: .present)) return PoundFileExprSyntax(data) } public static func makePoundFileIDExpr(poundFileID: TokenSyntax) -> PoundFileIDExprSyntax { let layout: [RawSyntax?] = [ poundFileID.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundFileIDExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundFileIDExprSyntax(data) } public static func makeBlankPoundFileIDExpr() -> PoundFileIDExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundFileIDExpr, layout: [ RawSyntax.missingToken(TokenKind.poundFileIDKeyword), ], length: .zero, presence: .present)) return PoundFileIDExprSyntax(data) } public static func makePoundFilePathExpr(poundFilePath: TokenSyntax) -> PoundFilePathExprSyntax { let layout: [RawSyntax?] = [ poundFilePath.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundFilePathExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundFilePathExprSyntax(data) } public static func makeBlankPoundFilePathExpr() -> PoundFilePathExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundFilePathExpr, layout: [ RawSyntax.missingToken(TokenKind.poundFilePathKeyword), ], length: .zero, presence: .present)) return PoundFilePathExprSyntax(data) } public static func makePoundFunctionExpr(poundFunction: TokenSyntax) -> PoundFunctionExprSyntax { let layout: [RawSyntax?] = [ poundFunction.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundFunctionExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundFunctionExprSyntax(data) } public static func makeBlankPoundFunctionExpr() -> PoundFunctionExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundFunctionExpr, layout: [ RawSyntax.missingToken(TokenKind.poundFunctionKeyword), ], length: .zero, presence: .present)) return PoundFunctionExprSyntax(data) } public static func makePoundDsohandleExpr(poundDsohandle: TokenSyntax) -> PoundDsohandleExprSyntax { let layout: [RawSyntax?] = [ poundDsohandle.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundDsohandleExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundDsohandleExprSyntax(data) } public static func makeBlankPoundDsohandleExpr() -> PoundDsohandleExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundDsohandleExpr, layout: [ RawSyntax.missingToken(TokenKind.poundDsohandleKeyword), ], length: .zero, presence: .present)) return PoundDsohandleExprSyntax(data) } public static func makeSymbolicReferenceExpr(identifier: TokenSyntax, genericArgumentClause: GenericArgumentClauseSyntax?) -> SymbolicReferenceExprSyntax { let layout: [RawSyntax?] = [ identifier.raw, genericArgumentClause?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.symbolicReferenceExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SymbolicReferenceExprSyntax(data) } public static func makeBlankSymbolicReferenceExpr() -> SymbolicReferenceExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .symbolicReferenceExpr, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return SymbolicReferenceExprSyntax(data) } public static func makePrefixOperatorExpr(operatorToken: TokenSyntax?, postfixExpression: ExprSyntax) -> PrefixOperatorExprSyntax { let layout: [RawSyntax?] = [ operatorToken?.raw, postfixExpression.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.prefixOperatorExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PrefixOperatorExprSyntax(data) } public static func makeBlankPrefixOperatorExpr() -> PrefixOperatorExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .prefixOperatorExpr, layout: [ nil, RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return PrefixOperatorExprSyntax(data) } public static func makeBinaryOperatorExpr(operatorToken: TokenSyntax) -> BinaryOperatorExprSyntax { let layout: [RawSyntax?] = [ operatorToken.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.binaryOperatorExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return BinaryOperatorExprSyntax(data) } public static func makeBlankBinaryOperatorExpr() -> BinaryOperatorExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .binaryOperatorExpr, layout: [ RawSyntax.missingToken(TokenKind.unknown("")), ], length: .zero, presence: .present)) return BinaryOperatorExprSyntax(data) } public static func makeArrowExpr(asyncKeyword: TokenSyntax?, throwsToken: TokenSyntax?, arrowToken: TokenSyntax) -> ArrowExprSyntax { let layout: [RawSyntax?] = [ asyncKeyword?.raw, throwsToken?.raw, arrowToken.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.arrowExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ArrowExprSyntax(data) } public static func makeBlankArrowExpr() -> ArrowExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .arrowExpr, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.arrow), ], length: .zero, presence: .present)) return ArrowExprSyntax(data) } public static func makeFloatLiteralExpr(floatingDigits: TokenSyntax) -> FloatLiteralExprSyntax { let layout: [RawSyntax?] = [ floatingDigits.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.floatLiteralExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return FloatLiteralExprSyntax(data) } public static func makeBlankFloatLiteralExpr() -> FloatLiteralExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .floatLiteralExpr, layout: [ RawSyntax.missingToken(TokenKind.floatingLiteral("")), ], length: .zero, presence: .present)) return FloatLiteralExprSyntax(data) } public static func makeTupleExpr(leftParen: TokenSyntax, elementList: TupleExprElementListSyntax, rightParen: TokenSyntax) -> TupleExprSyntax { let layout: [RawSyntax?] = [ leftParen.raw, elementList.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tupleExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TupleExprSyntax(data) } public static func makeBlankTupleExpr() -> TupleExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tupleExpr, layout: [ RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.tupleExprElementList), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return TupleExprSyntax(data) } public static func makeArrayExpr(leftSquare: TokenSyntax, elements: ArrayElementListSyntax, rightSquare: TokenSyntax) -> ArrayExprSyntax { let layout: [RawSyntax?] = [ leftSquare.raw, elements.raw, rightSquare.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.arrayExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ArrayExprSyntax(data) } public static func makeBlankArrayExpr() -> ArrayExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .arrayExpr, layout: [ RawSyntax.missingToken(TokenKind.leftSquareBracket), RawSyntax.missing(SyntaxKind.arrayElementList), RawSyntax.missingToken(TokenKind.rightSquareBracket), ], length: .zero, presence: .present)) return ArrayExprSyntax(data) } public static func makeDictionaryExpr(leftSquare: TokenSyntax, content: Syntax, rightSquare: TokenSyntax) -> DictionaryExprSyntax { let layout: [RawSyntax?] = [ leftSquare.raw, content.raw, rightSquare.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.dictionaryExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DictionaryExprSyntax(data) } public static func makeBlankDictionaryExpr() -> DictionaryExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .dictionaryExpr, layout: [ RawSyntax.missingToken(TokenKind.leftSquareBracket), RawSyntax.missing(SyntaxKind.unknown), RawSyntax.missingToken(TokenKind.rightSquareBracket), ], length: .zero, presence: .present)) return DictionaryExprSyntax(data) } public static func makeTupleExprElement(label: TokenSyntax?, colon: TokenSyntax?, expression: ExprSyntax, trailingComma: TokenSyntax?) -> TupleExprElementSyntax { let layout: [RawSyntax?] = [ label?.raw, colon?.raw, expression.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tupleExprElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TupleExprElementSyntax(data) } public static func makeBlankTupleExprElement() -> TupleExprElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tupleExprElement, layout: [ nil, nil, RawSyntax.missing(SyntaxKind.expr), nil, ], length: .zero, presence: .present)) return TupleExprElementSyntax(data) } public static func makeArrayElement(expression: ExprSyntax, trailingComma: TokenSyntax?) -> ArrayElementSyntax { let layout: [RawSyntax?] = [ expression.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.arrayElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ArrayElementSyntax(data) } public static func makeBlankArrayElement() -> ArrayElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .arrayElement, layout: [ RawSyntax.missing(SyntaxKind.expr), nil, ], length: .zero, presence: .present)) return ArrayElementSyntax(data) } public static func makeDictionaryElement(keyExpression: ExprSyntax, colon: TokenSyntax, valueExpression: ExprSyntax, trailingComma: TokenSyntax?) -> DictionaryElementSyntax { let layout: [RawSyntax?] = [ keyExpression.raw, colon.raw, valueExpression.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.dictionaryElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DictionaryElementSyntax(data) } public static func makeBlankDictionaryElement() -> DictionaryElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .dictionaryElement, layout: [ RawSyntax.missing(SyntaxKind.expr), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.expr), nil, ], length: .zero, presence: .present)) return DictionaryElementSyntax(data) } public static func makeIntegerLiteralExpr(digits: TokenSyntax) -> IntegerLiteralExprSyntax { let layout: [RawSyntax?] = [ digits.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.integerLiteralExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IntegerLiteralExprSyntax(data) } public static func makeBlankIntegerLiteralExpr() -> IntegerLiteralExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .integerLiteralExpr, layout: [ RawSyntax.missingToken(TokenKind.integerLiteral("")), ], length: .zero, presence: .present)) return IntegerLiteralExprSyntax(data) } public static func makeBooleanLiteralExpr(booleanLiteral: TokenSyntax) -> BooleanLiteralExprSyntax { let layout: [RawSyntax?] = [ booleanLiteral.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.booleanLiteralExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return BooleanLiteralExprSyntax(data) } public static func makeBlankBooleanLiteralExpr() -> BooleanLiteralExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .booleanLiteralExpr, layout: [ RawSyntax.missingToken(TokenKind.trueKeyword), ], length: .zero, presence: .present)) return BooleanLiteralExprSyntax(data) } public static func makeTernaryExpr(conditionExpression: ExprSyntax, questionMark: TokenSyntax, firstChoice: ExprSyntax, colonMark: TokenSyntax, secondChoice: ExprSyntax) -> TernaryExprSyntax { let layout: [RawSyntax?] = [ conditionExpression.raw, questionMark.raw, firstChoice.raw, colonMark.raw, secondChoice.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.ternaryExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TernaryExprSyntax(data) } public static func makeBlankTernaryExpr() -> TernaryExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .ternaryExpr, layout: [ RawSyntax.missing(SyntaxKind.expr), RawSyntax.missingToken(TokenKind.infixQuestionMark), RawSyntax.missing(SyntaxKind.expr), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return TernaryExprSyntax(data) } public static func makeMemberAccessExpr(base: ExprSyntax?, dot: TokenSyntax, name: TokenSyntax, declNameArguments: DeclNameArgumentsSyntax?) -> MemberAccessExprSyntax { let layout: [RawSyntax?] = [ base?.raw, dot.raw, name.raw, declNameArguments?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.memberAccessExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return MemberAccessExprSyntax(data) } public static func makeBlankMemberAccessExpr() -> MemberAccessExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .memberAccessExpr, layout: [ nil, RawSyntax.missingToken(TokenKind.period), RawSyntax.missingToken(TokenKind.unknown("")), nil, ], length: .zero, presence: .present)) return MemberAccessExprSyntax(data) } public static func makeIsExpr(isTok: TokenSyntax, typeName: TypeSyntax) -> IsExprSyntax { let layout: [RawSyntax?] = [ isTok.raw, typeName.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.isExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IsExprSyntax(data) } public static func makeBlankIsExpr() -> IsExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .isExpr, layout: [ RawSyntax.missingToken(TokenKind.isKeyword), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return IsExprSyntax(data) } public static func makeAsExpr(asTok: TokenSyntax, questionOrExclamationMark: TokenSyntax?, typeName: TypeSyntax) -> AsExprSyntax { let layout: [RawSyntax?] = [ asTok.raw, questionOrExclamationMark?.raw, typeName.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.asExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AsExprSyntax(data) } public static func makeBlankAsExpr() -> AsExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .asExpr, layout: [ RawSyntax.missingToken(TokenKind.asKeyword), nil, RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return AsExprSyntax(data) } public static func makeTypeExpr(type: TypeSyntax) -> TypeExprSyntax { let layout: [RawSyntax?] = [ type.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.typeExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TypeExprSyntax(data) } public static func makeBlankTypeExpr() -> TypeExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .typeExpr, layout: [ RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return TypeExprSyntax(data) } public static func makeClosureCaptureItem(specifier: TokenListSyntax?, name: TokenSyntax?, assignToken: TokenSyntax?, expression: ExprSyntax, trailingComma: TokenSyntax?) -> ClosureCaptureItemSyntax { let layout: [RawSyntax?] = [ specifier?.raw, name?.raw, assignToken?.raw, expression.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.closureCaptureItem, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ClosureCaptureItemSyntax(data) } public static func makeBlankClosureCaptureItem() -> ClosureCaptureItemSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .closureCaptureItem, layout: [ nil, nil, nil, RawSyntax.missing(SyntaxKind.expr), nil, ], length: .zero, presence: .present)) return ClosureCaptureItemSyntax(data) } public static func makeClosureCaptureItemList( _ elements: [ClosureCaptureItemSyntax]) -> ClosureCaptureItemListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.closureCaptureItemList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ClosureCaptureItemListSyntax(data) } public static func makeBlankClosureCaptureItemList() -> ClosureCaptureItemListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .closureCaptureItemList, layout: [ ], length: .zero, presence: .present)) return ClosureCaptureItemListSyntax(data) } public static func makeClosureCaptureSignature(leftSquare: TokenSyntax, items: ClosureCaptureItemListSyntax?, rightSquare: TokenSyntax) -> ClosureCaptureSignatureSyntax { let layout: [RawSyntax?] = [ leftSquare.raw, items?.raw, rightSquare.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.closureCaptureSignature, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ClosureCaptureSignatureSyntax(data) } public static func makeBlankClosureCaptureSignature() -> ClosureCaptureSignatureSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .closureCaptureSignature, layout: [ RawSyntax.missingToken(TokenKind.leftSquareBracket), nil, RawSyntax.missingToken(TokenKind.rightSquareBracket), ], length: .zero, presence: .present)) return ClosureCaptureSignatureSyntax(data) } public static func makeClosureParam(name: TokenSyntax, trailingComma: TokenSyntax?) -> ClosureParamSyntax { let layout: [RawSyntax?] = [ name.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.closureParam, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ClosureParamSyntax(data) } public static func makeBlankClosureParam() -> ClosureParamSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .closureParam, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return ClosureParamSyntax(data) } public static func makeClosureParamList( _ elements: [ClosureParamSyntax]) -> ClosureParamListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.closureParamList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ClosureParamListSyntax(data) } public static func makeBlankClosureParamList() -> ClosureParamListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .closureParamList, layout: [ ], length: .zero, presence: .present)) return ClosureParamListSyntax(data) } public static func makeClosureSignature(capture: ClosureCaptureSignatureSyntax?, input: Syntax?, asyncKeyword: TokenSyntax?, throwsTok: TokenSyntax?, output: ReturnClauseSyntax?, inTok: TokenSyntax) -> ClosureSignatureSyntax { let layout: [RawSyntax?] = [ capture?.raw, input?.raw, asyncKeyword?.raw, throwsTok?.raw, output?.raw, inTok.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.closureSignature, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ClosureSignatureSyntax(data) } public static func makeBlankClosureSignature() -> ClosureSignatureSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .closureSignature, layout: [ nil, nil, nil, nil, nil, RawSyntax.missingToken(TokenKind.inKeyword), ], length: .zero, presence: .present)) return ClosureSignatureSyntax(data) } public static func makeClosureExpr(leftBrace: TokenSyntax, signature: ClosureSignatureSyntax?, statements: CodeBlockItemListSyntax, rightBrace: TokenSyntax) -> ClosureExprSyntax { let layout: [RawSyntax?] = [ leftBrace.raw, signature?.raw, statements.raw, rightBrace.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.closureExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ClosureExprSyntax(data) } public static func makeBlankClosureExpr() -> ClosureExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .closureExpr, layout: [ RawSyntax.missingToken(TokenKind.leftBrace), nil, RawSyntax.missing(SyntaxKind.codeBlockItemList), RawSyntax.missingToken(TokenKind.rightBrace), ], length: .zero, presence: .present)) return ClosureExprSyntax(data) } public static func makeUnresolvedPatternExpr(pattern: PatternSyntax) -> UnresolvedPatternExprSyntax { let layout: [RawSyntax?] = [ pattern.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.unresolvedPatternExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return UnresolvedPatternExprSyntax(data) } public static func makeBlankUnresolvedPatternExpr() -> UnresolvedPatternExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .unresolvedPatternExpr, layout: [ RawSyntax.missing(SyntaxKind.pattern), ], length: .zero, presence: .present)) return UnresolvedPatternExprSyntax(data) } public static func makeMultipleTrailingClosureElement(label: TokenSyntax, colon: TokenSyntax, closure: ClosureExprSyntax) -> MultipleTrailingClosureElementSyntax { let layout: [RawSyntax?] = [ label.raw, colon.raw, closure.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.multipleTrailingClosureElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return MultipleTrailingClosureElementSyntax(data) } public static func makeBlankMultipleTrailingClosureElement() -> MultipleTrailingClosureElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .multipleTrailingClosureElement, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.closureExpr), ], length: .zero, presence: .present)) return MultipleTrailingClosureElementSyntax(data) } public static func makeMultipleTrailingClosureElementList( _ elements: [MultipleTrailingClosureElementSyntax]) -> MultipleTrailingClosureElementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.multipleTrailingClosureElementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return MultipleTrailingClosureElementListSyntax(data) } public static func makeBlankMultipleTrailingClosureElementList() -> MultipleTrailingClosureElementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .multipleTrailingClosureElementList, layout: [ ], length: .zero, presence: .present)) return MultipleTrailingClosureElementListSyntax(data) } public static func makeFunctionCallExpr(calledExpression: ExprSyntax, leftParen: TokenSyntax?, argumentList: TupleExprElementListSyntax, rightParen: TokenSyntax?, trailingClosure: ClosureExprSyntax?, additionalTrailingClosures: MultipleTrailingClosureElementListSyntax?) -> FunctionCallExprSyntax { let layout: [RawSyntax?] = [ calledExpression.raw, leftParen?.raw, argumentList.raw, rightParen?.raw, trailingClosure?.raw, additionalTrailingClosures?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.functionCallExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return FunctionCallExprSyntax(data) } public static func makeBlankFunctionCallExpr() -> FunctionCallExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .functionCallExpr, layout: [ RawSyntax.missing(SyntaxKind.expr), nil, RawSyntax.missing(SyntaxKind.tupleExprElementList), nil, nil, nil, ], length: .zero, presence: .present)) return FunctionCallExprSyntax(data) } public static func makeSubscriptExpr(calledExpression: ExprSyntax, leftBracket: TokenSyntax, argumentList: TupleExprElementListSyntax, rightBracket: TokenSyntax, trailingClosure: ClosureExprSyntax?, additionalTrailingClosures: MultipleTrailingClosureElementListSyntax?) -> SubscriptExprSyntax { let layout: [RawSyntax?] = [ calledExpression.raw, leftBracket.raw, argumentList.raw, rightBracket.raw, trailingClosure?.raw, additionalTrailingClosures?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.subscriptExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SubscriptExprSyntax(data) } public static func makeBlankSubscriptExpr() -> SubscriptExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .subscriptExpr, layout: [ RawSyntax.missing(SyntaxKind.expr), RawSyntax.missingToken(TokenKind.leftSquareBracket), RawSyntax.missing(SyntaxKind.tupleExprElementList), RawSyntax.missingToken(TokenKind.rightSquareBracket), nil, nil, ], length: .zero, presence: .present)) return SubscriptExprSyntax(data) } public static func makeOptionalChainingExpr(expression: ExprSyntax, questionMark: TokenSyntax) -> OptionalChainingExprSyntax { let layout: [RawSyntax?] = [ expression.raw, questionMark.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.optionalChainingExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return OptionalChainingExprSyntax(data) } public static func makeBlankOptionalChainingExpr() -> OptionalChainingExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .optionalChainingExpr, layout: [ RawSyntax.missing(SyntaxKind.expr), RawSyntax.missingToken(TokenKind.postfixQuestionMark), ], length: .zero, presence: .present)) return OptionalChainingExprSyntax(data) } public static func makeForcedValueExpr(expression: ExprSyntax, exclamationMark: TokenSyntax) -> ForcedValueExprSyntax { let layout: [RawSyntax?] = [ expression.raw, exclamationMark.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.forcedValueExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ForcedValueExprSyntax(data) } public static func makeBlankForcedValueExpr() -> ForcedValueExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .forcedValueExpr, layout: [ RawSyntax.missing(SyntaxKind.expr), RawSyntax.missingToken(TokenKind.exclamationMark), ], length: .zero, presence: .present)) return ForcedValueExprSyntax(data) } public static func makePostfixUnaryExpr(expression: ExprSyntax, operatorToken: TokenSyntax) -> PostfixUnaryExprSyntax { let layout: [RawSyntax?] = [ expression.raw, operatorToken.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.postfixUnaryExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PostfixUnaryExprSyntax(data) } public static func makeBlankPostfixUnaryExpr() -> PostfixUnaryExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .postfixUnaryExpr, layout: [ RawSyntax.missing(SyntaxKind.expr), RawSyntax.missingToken(TokenKind.postfixOperator("")), ], length: .zero, presence: .present)) return PostfixUnaryExprSyntax(data) } public static func makeSpecializeExpr(expression: ExprSyntax, genericArgumentClause: GenericArgumentClauseSyntax) -> SpecializeExprSyntax { let layout: [RawSyntax?] = [ expression.raw, genericArgumentClause.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.specializeExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SpecializeExprSyntax(data) } public static func makeBlankSpecializeExpr() -> SpecializeExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .specializeExpr, layout: [ RawSyntax.missing(SyntaxKind.expr), RawSyntax.missing(SyntaxKind.genericArgumentClause), ], length: .zero, presence: .present)) return SpecializeExprSyntax(data) } public static func makeStringSegment(content: TokenSyntax) -> StringSegmentSyntax { let layout: [RawSyntax?] = [ content.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.stringSegment, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return StringSegmentSyntax(data) } public static func makeBlankStringSegment() -> StringSegmentSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .stringSegment, layout: [ RawSyntax.missingToken(TokenKind.stringSegment("")), ], length: .zero, presence: .present)) return StringSegmentSyntax(data) } public static func makeExpressionSegment(backslash: TokenSyntax, delimiter: TokenSyntax?, leftParen: TokenSyntax, expressions: TupleExprElementListSyntax, rightParen: TokenSyntax) -> ExpressionSegmentSyntax { let layout: [RawSyntax?] = [ backslash.raw, delimiter?.raw, leftParen.raw, expressions.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.expressionSegment, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ExpressionSegmentSyntax(data) } public static func makeBlankExpressionSegment() -> ExpressionSegmentSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .expressionSegment, layout: [ RawSyntax.missingToken(TokenKind.backslash), nil, RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.tupleExprElementList), RawSyntax.missingToken(TokenKind.stringInterpolationAnchor), ], length: .zero, presence: .present)) return ExpressionSegmentSyntax(data) } public static func makeStringLiteralExpr(openDelimiter: TokenSyntax?, openQuote: TokenSyntax, segments: StringLiteralSegmentsSyntax, closeQuote: TokenSyntax, closeDelimiter: TokenSyntax?) -> StringLiteralExprSyntax { let layout: [RawSyntax?] = [ openDelimiter?.raw, openQuote.raw, segments.raw, closeQuote.raw, closeDelimiter?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.stringLiteralExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return StringLiteralExprSyntax(data) } public static func makeBlankStringLiteralExpr() -> StringLiteralExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .stringLiteralExpr, layout: [ nil, RawSyntax.missingToken(TokenKind.stringQuote), RawSyntax.missing(SyntaxKind.stringLiteralSegments), RawSyntax.missingToken(TokenKind.stringQuote), nil, ], length: .zero, presence: .present)) return StringLiteralExprSyntax(data) } public static func makeKeyPathExpr(backslash: TokenSyntax, rootExpr: ExprSyntax?, expression: ExprSyntax) -> KeyPathExprSyntax { let layout: [RawSyntax?] = [ backslash.raw, rootExpr?.raw, expression.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.keyPathExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return KeyPathExprSyntax(data) } public static func makeBlankKeyPathExpr() -> KeyPathExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .keyPathExpr, layout: [ RawSyntax.missingToken(TokenKind.backslash), nil, RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return KeyPathExprSyntax(data) } public static func makeKeyPathBaseExpr(period: TokenSyntax) -> KeyPathBaseExprSyntax { let layout: [RawSyntax?] = [ period.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.keyPathBaseExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return KeyPathBaseExprSyntax(data) } public static func makeBlankKeyPathBaseExpr() -> KeyPathBaseExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .keyPathBaseExpr, layout: [ RawSyntax.missingToken(TokenKind.period), ], length: .zero, presence: .present)) return KeyPathBaseExprSyntax(data) } public static func makeObjcNamePiece(name: TokenSyntax, dot: TokenSyntax?) -> ObjcNamePieceSyntax { let layout: [RawSyntax?] = [ name.raw, dot?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.objcNamePiece, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ObjcNamePieceSyntax(data) } public static func makeBlankObjcNamePiece() -> ObjcNamePieceSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .objcNamePiece, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return ObjcNamePieceSyntax(data) } public static func makeObjcName( _ elements: [ObjcNamePieceSyntax]) -> ObjcNameSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.objcName, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ObjcNameSyntax(data) } public static func makeBlankObjcName() -> ObjcNameSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .objcName, layout: [ ], length: .zero, presence: .present)) return ObjcNameSyntax(data) } public static func makeObjcKeyPathExpr(keyPath: TokenSyntax, leftParen: TokenSyntax, name: ObjcNameSyntax, rightParen: TokenSyntax) -> ObjcKeyPathExprSyntax { let layout: [RawSyntax?] = [ keyPath.raw, leftParen.raw, name.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.objcKeyPathExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ObjcKeyPathExprSyntax(data) } public static func makeBlankObjcKeyPathExpr() -> ObjcKeyPathExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .objcKeyPathExpr, layout: [ RawSyntax.missingToken(TokenKind.poundKeyPathKeyword), RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.objcName), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return ObjcKeyPathExprSyntax(data) } public static func makeObjcSelectorExpr(poundSelector: TokenSyntax, leftParen: TokenSyntax, kind: TokenSyntax?, colon: TokenSyntax?, name: ExprSyntax, rightParen: TokenSyntax) -> ObjcSelectorExprSyntax { let layout: [RawSyntax?] = [ poundSelector.raw, leftParen.raw, kind?.raw, colon?.raw, name.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.objcSelectorExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ObjcSelectorExprSyntax(data) } public static func makeBlankObjcSelectorExpr() -> ObjcSelectorExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .objcSelectorExpr, layout: [ RawSyntax.missingToken(TokenKind.poundSelectorKeyword), RawSyntax.missingToken(TokenKind.leftParen), nil, nil, RawSyntax.missing(SyntaxKind.expr), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return ObjcSelectorExprSyntax(data) } public static func makeEditorPlaceholderExpr(identifier: TokenSyntax) -> EditorPlaceholderExprSyntax { let layout: [RawSyntax?] = [ identifier.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.editorPlaceholderExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return EditorPlaceholderExprSyntax(data) } public static func makeBlankEditorPlaceholderExpr() -> EditorPlaceholderExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .editorPlaceholderExpr, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), ], length: .zero, presence: .present)) return EditorPlaceholderExprSyntax(data) } public static func makeObjectLiteralExpr(identifier: TokenSyntax, leftParen: TokenSyntax, arguments: TupleExprElementListSyntax, rightParen: TokenSyntax) -> ObjectLiteralExprSyntax { let layout: [RawSyntax?] = [ identifier.raw, leftParen.raw, arguments.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.objectLiteralExpr, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ObjectLiteralExprSyntax(data) } public static func makeBlankObjectLiteralExpr() -> ObjectLiteralExprSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .objectLiteralExpr, layout: [ RawSyntax.missingToken(TokenKind.poundColorLiteralKeyword), RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.tupleExprElementList), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return ObjectLiteralExprSyntax(data) } public static func makeTypeInitializerClause(equal: TokenSyntax, value: TypeSyntax) -> TypeInitializerClauseSyntax { let layout: [RawSyntax?] = [ equal.raw, value.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.typeInitializerClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TypeInitializerClauseSyntax(data) } public static func makeBlankTypeInitializerClause() -> TypeInitializerClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .typeInitializerClause, layout: [ RawSyntax.missingToken(TokenKind.equal), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return TypeInitializerClauseSyntax(data) } public static func makeTypealiasDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, typealiasKeyword: TokenSyntax, identifier: TokenSyntax, genericParameterClause: GenericParameterClauseSyntax?, initializer: TypeInitializerClauseSyntax?, genericWhereClause: GenericWhereClauseSyntax?) -> TypealiasDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, typealiasKeyword.raw, identifier.raw, genericParameterClause?.raw, initializer?.raw, genericWhereClause?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.typealiasDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TypealiasDeclSyntax(data) } public static func makeBlankTypealiasDecl() -> TypealiasDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .typealiasDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.typealiasKeyword), RawSyntax.missingToken(TokenKind.identifier("")), nil, nil, nil, ], length: .zero, presence: .present)) return TypealiasDeclSyntax(data) } public static func makeAssociatedtypeDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, associatedtypeKeyword: TokenSyntax, identifier: TokenSyntax, inheritanceClause: TypeInheritanceClauseSyntax?, initializer: TypeInitializerClauseSyntax?, genericWhereClause: GenericWhereClauseSyntax?) -> AssociatedtypeDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, associatedtypeKeyword.raw, identifier.raw, inheritanceClause?.raw, initializer?.raw, genericWhereClause?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.associatedtypeDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AssociatedtypeDeclSyntax(data) } public static func makeBlankAssociatedtypeDecl() -> AssociatedtypeDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .associatedtypeDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.associatedtypeKeyword), RawSyntax.missingToken(TokenKind.identifier("")), nil, nil, nil, ], length: .zero, presence: .present)) return AssociatedtypeDeclSyntax(data) } public static func makeFunctionParameterList( _ elements: [FunctionParameterSyntax]) -> FunctionParameterListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.functionParameterList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return FunctionParameterListSyntax(data) } public static func makeBlankFunctionParameterList() -> FunctionParameterListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .functionParameterList, layout: [ ], length: .zero, presence: .present)) return FunctionParameterListSyntax(data) } public static func makeParameterClause(leftParen: TokenSyntax, parameterList: FunctionParameterListSyntax, rightParen: TokenSyntax) -> ParameterClauseSyntax { let layout: [RawSyntax?] = [ leftParen.raw, parameterList.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.parameterClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ParameterClauseSyntax(data) } public static func makeBlankParameterClause() -> ParameterClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .parameterClause, layout: [ RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.functionParameterList), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return ParameterClauseSyntax(data) } public static func makeReturnClause(arrow: TokenSyntax, returnType: TypeSyntax) -> ReturnClauseSyntax { let layout: [RawSyntax?] = [ arrow.raw, returnType.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.returnClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ReturnClauseSyntax(data) } public static func makeBlankReturnClause() -> ReturnClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .returnClause, layout: [ RawSyntax.missingToken(TokenKind.arrow), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return ReturnClauseSyntax(data) } public static func makeFunctionSignature(input: ParameterClauseSyntax, asyncKeyword: TokenSyntax?, throwsOrRethrowsKeyword: TokenSyntax?, output: ReturnClauseSyntax?) -> FunctionSignatureSyntax { let layout: [RawSyntax?] = [ input.raw, asyncKeyword?.raw, throwsOrRethrowsKeyword?.raw, output?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.functionSignature, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return FunctionSignatureSyntax(data) } public static func makeBlankFunctionSignature() -> FunctionSignatureSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .functionSignature, layout: [ RawSyntax.missing(SyntaxKind.parameterClause), nil, nil, nil, ], length: .zero, presence: .present)) return FunctionSignatureSyntax(data) } public static func makeIfConfigClause(poundKeyword: TokenSyntax, condition: ExprSyntax?, elements: Syntax) -> IfConfigClauseSyntax { let layout: [RawSyntax?] = [ poundKeyword.raw, condition?.raw, elements.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.ifConfigClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IfConfigClauseSyntax(data) } public static func makeBlankIfConfigClause() -> IfConfigClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .ifConfigClause, layout: [ RawSyntax.missingToken(TokenKind.poundIfKeyword), nil, RawSyntax.missing(SyntaxKind.unknown), ], length: .zero, presence: .present)) return IfConfigClauseSyntax(data) } public static func makeIfConfigClauseList( _ elements: [IfConfigClauseSyntax]) -> IfConfigClauseListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.ifConfigClauseList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IfConfigClauseListSyntax(data) } public static func makeBlankIfConfigClauseList() -> IfConfigClauseListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .ifConfigClauseList, layout: [ ], length: .zero, presence: .present)) return IfConfigClauseListSyntax(data) } public static func makeIfConfigDecl(clauses: IfConfigClauseListSyntax, poundEndif: TokenSyntax) -> IfConfigDeclSyntax { let layout: [RawSyntax?] = [ clauses.raw, poundEndif.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.ifConfigDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IfConfigDeclSyntax(data) } public static func makeBlankIfConfigDecl() -> IfConfigDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .ifConfigDecl, layout: [ RawSyntax.missing(SyntaxKind.ifConfigClauseList), RawSyntax.missingToken(TokenKind.poundEndifKeyword), ], length: .zero, presence: .present)) return IfConfigDeclSyntax(data) } public static func makePoundErrorDecl(poundError: TokenSyntax, leftParen: TokenSyntax, message: StringLiteralExprSyntax, rightParen: TokenSyntax) -> PoundErrorDeclSyntax { let layout: [RawSyntax?] = [ poundError.raw, leftParen.raw, message.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundErrorDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundErrorDeclSyntax(data) } public static func makeBlankPoundErrorDecl() -> PoundErrorDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundErrorDecl, layout: [ RawSyntax.missingToken(TokenKind.poundErrorKeyword), RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.stringLiteralExpr), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return PoundErrorDeclSyntax(data) } public static func makePoundWarningDecl(poundWarning: TokenSyntax, leftParen: TokenSyntax, message: StringLiteralExprSyntax, rightParen: TokenSyntax) -> PoundWarningDeclSyntax { let layout: [RawSyntax?] = [ poundWarning.raw, leftParen.raw, message.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundWarningDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundWarningDeclSyntax(data) } public static func makeBlankPoundWarningDecl() -> PoundWarningDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundWarningDecl, layout: [ RawSyntax.missingToken(TokenKind.poundWarningKeyword), RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.stringLiteralExpr), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return PoundWarningDeclSyntax(data) } public static func makePoundSourceLocation(poundSourceLocation: TokenSyntax, leftParen: TokenSyntax, args: PoundSourceLocationArgsSyntax?, rightParen: TokenSyntax) -> PoundSourceLocationSyntax { let layout: [RawSyntax?] = [ poundSourceLocation.raw, leftParen.raw, args?.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundSourceLocation, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundSourceLocationSyntax(data) } public static func makeBlankPoundSourceLocation() -> PoundSourceLocationSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundSourceLocation, layout: [ RawSyntax.missingToken(TokenKind.poundSourceLocationKeyword), RawSyntax.missingToken(TokenKind.leftParen), nil, RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return PoundSourceLocationSyntax(data) } public static func makePoundSourceLocationArgs(fileArgLabel: TokenSyntax, fileArgColon: TokenSyntax, fileName: TokenSyntax, comma: TokenSyntax, lineArgLabel: TokenSyntax, lineArgColon: TokenSyntax, lineNumber: TokenSyntax) -> PoundSourceLocationArgsSyntax { let layout: [RawSyntax?] = [ fileArgLabel.raw, fileArgColon.raw, fileName.raw, comma.raw, lineArgLabel.raw, lineArgColon.raw, lineNumber.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundSourceLocationArgs, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundSourceLocationArgsSyntax(data) } public static func makeBlankPoundSourceLocationArgs() -> PoundSourceLocationArgsSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundSourceLocationArgs, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missingToken(TokenKind.stringLiteral("")), RawSyntax.missingToken(TokenKind.comma), RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missingToken(TokenKind.integerLiteral("")), ], length: .zero, presence: .present)) return PoundSourceLocationArgsSyntax(data) } public static func makeDeclModifier(name: TokenSyntax, detailLeftParen: TokenSyntax?, detail: TokenSyntax?, detailRightParen: TokenSyntax?) -> DeclModifierSyntax { let layout: [RawSyntax?] = [ name.raw, detailLeftParen?.raw, detail?.raw, detailRightParen?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.declModifier, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DeclModifierSyntax(data) } public static func makeBlankDeclModifier() -> DeclModifierSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .declModifier, layout: [ RawSyntax.missingToken(TokenKind.unknown("")), nil, nil, nil, ], length: .zero, presence: .present)) return DeclModifierSyntax(data) } public static func makeInheritedType(typeName: TypeSyntax, trailingComma: TokenSyntax?) -> InheritedTypeSyntax { let layout: [RawSyntax?] = [ typeName.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.inheritedType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return InheritedTypeSyntax(data) } public static func makeBlankInheritedType() -> InheritedTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .inheritedType, layout: [ RawSyntax.missing(SyntaxKind.type), nil, ], length: .zero, presence: .present)) return InheritedTypeSyntax(data) } public static func makeInheritedTypeList( _ elements: [InheritedTypeSyntax]) -> InheritedTypeListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.inheritedTypeList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return InheritedTypeListSyntax(data) } public static func makeBlankInheritedTypeList() -> InheritedTypeListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .inheritedTypeList, layout: [ ], length: .zero, presence: .present)) return InheritedTypeListSyntax(data) } public static func makeTypeInheritanceClause(colon: TokenSyntax, inheritedTypeCollection: InheritedTypeListSyntax) -> TypeInheritanceClauseSyntax { let layout: [RawSyntax?] = [ colon.raw, inheritedTypeCollection.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.typeInheritanceClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TypeInheritanceClauseSyntax(data) } public static func makeBlankTypeInheritanceClause() -> TypeInheritanceClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .typeInheritanceClause, layout: [ RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.inheritedTypeList), ], length: .zero, presence: .present)) return TypeInheritanceClauseSyntax(data) } public static func makeClassDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, classKeyword: TokenSyntax, identifier: TokenSyntax, genericParameterClause: GenericParameterClauseSyntax?, inheritanceClause: TypeInheritanceClauseSyntax?, genericWhereClause: GenericWhereClauseSyntax?, members: MemberDeclBlockSyntax) -> ClassDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, classKeyword.raw, identifier.raw, genericParameterClause?.raw, inheritanceClause?.raw, genericWhereClause?.raw, members.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.classDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ClassDeclSyntax(data) } public static func makeBlankClassDecl() -> ClassDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .classDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.classKeyword), RawSyntax.missingToken(TokenKind.identifier("")), nil, nil, nil, RawSyntax.missing(SyntaxKind.memberDeclBlock), ], length: .zero, presence: .present)) return ClassDeclSyntax(data) } public static func makeStructDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, structKeyword: TokenSyntax, identifier: TokenSyntax, genericParameterClause: GenericParameterClauseSyntax?, inheritanceClause: TypeInheritanceClauseSyntax?, genericWhereClause: GenericWhereClauseSyntax?, members: MemberDeclBlockSyntax) -> StructDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, structKeyword.raw, identifier.raw, genericParameterClause?.raw, inheritanceClause?.raw, genericWhereClause?.raw, members.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.structDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return StructDeclSyntax(data) } public static func makeBlankStructDecl() -> StructDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .structDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.structKeyword), RawSyntax.missingToken(TokenKind.identifier("")), nil, nil, nil, RawSyntax.missing(SyntaxKind.memberDeclBlock), ], length: .zero, presence: .present)) return StructDeclSyntax(data) } public static func makeProtocolDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, protocolKeyword: TokenSyntax, identifier: TokenSyntax, inheritanceClause: TypeInheritanceClauseSyntax?, genericWhereClause: GenericWhereClauseSyntax?, members: MemberDeclBlockSyntax) -> ProtocolDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, protocolKeyword.raw, identifier.raw, inheritanceClause?.raw, genericWhereClause?.raw, members.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.protocolDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ProtocolDeclSyntax(data) } public static func makeBlankProtocolDecl() -> ProtocolDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .protocolDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.protocolKeyword), RawSyntax.missingToken(TokenKind.identifier("")), nil, nil, RawSyntax.missing(SyntaxKind.memberDeclBlock), ], length: .zero, presence: .present)) return ProtocolDeclSyntax(data) } public static func makeExtensionDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, extensionKeyword: TokenSyntax, extendedType: TypeSyntax, inheritanceClause: TypeInheritanceClauseSyntax?, genericWhereClause: GenericWhereClauseSyntax?, members: MemberDeclBlockSyntax) -> ExtensionDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, extensionKeyword.raw, extendedType.raw, inheritanceClause?.raw, genericWhereClause?.raw, members.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.extensionDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ExtensionDeclSyntax(data) } public static func makeBlankExtensionDecl() -> ExtensionDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .extensionDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.extensionKeyword), RawSyntax.missing(SyntaxKind.type), nil, nil, RawSyntax.missing(SyntaxKind.memberDeclBlock), ], length: .zero, presence: .present)) return ExtensionDeclSyntax(data) } public static func makeMemberDeclBlock(leftBrace: TokenSyntax, members: MemberDeclListSyntax, rightBrace: TokenSyntax) -> MemberDeclBlockSyntax { let layout: [RawSyntax?] = [ leftBrace.raw, members.raw, rightBrace.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.memberDeclBlock, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return MemberDeclBlockSyntax(data) } public static func makeBlankMemberDeclBlock() -> MemberDeclBlockSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .memberDeclBlock, layout: [ RawSyntax.missingToken(TokenKind.leftBrace), RawSyntax.missing(SyntaxKind.memberDeclList), RawSyntax.missingToken(TokenKind.rightBrace), ], length: .zero, presence: .present)) return MemberDeclBlockSyntax(data) } public static func makeMemberDeclList( _ elements: [MemberDeclListItemSyntax]) -> MemberDeclListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.memberDeclList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return MemberDeclListSyntax(data) } public static func makeBlankMemberDeclList() -> MemberDeclListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .memberDeclList, layout: [ ], length: .zero, presence: .present)) return MemberDeclListSyntax(data) } public static func makeMemberDeclListItem(decl: DeclSyntax, semicolon: TokenSyntax?) -> MemberDeclListItemSyntax { let layout: [RawSyntax?] = [ decl.raw, semicolon?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.memberDeclListItem, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return MemberDeclListItemSyntax(data) } public static func makeBlankMemberDeclListItem() -> MemberDeclListItemSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .memberDeclListItem, layout: [ RawSyntax.missing(SyntaxKind.decl), nil, ], length: .zero, presence: .present)) return MemberDeclListItemSyntax(data) } public static func makeSourceFile(statements: CodeBlockItemListSyntax, eofToken: TokenSyntax) -> SourceFileSyntax { let layout: [RawSyntax?] = [ statements.raw, eofToken.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.sourceFile, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SourceFileSyntax(data) } public static func makeBlankSourceFile() -> SourceFileSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .sourceFile, layout: [ RawSyntax.missing(SyntaxKind.codeBlockItemList), RawSyntax.missingToken(TokenKind.unknown("")), ], length: .zero, presence: .present)) return SourceFileSyntax(data) } public static func makeInitializerClause(equal: TokenSyntax, value: ExprSyntax) -> InitializerClauseSyntax { let layout: [RawSyntax?] = [ equal.raw, value.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.initializerClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return InitializerClauseSyntax(data) } public static func makeBlankInitializerClause() -> InitializerClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .initializerClause, layout: [ RawSyntax.missingToken(TokenKind.equal), RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return InitializerClauseSyntax(data) } public static func makeFunctionParameter(attributes: AttributeListSyntax?, firstName: TokenSyntax?, secondName: TokenSyntax?, colon: TokenSyntax?, type: TypeSyntax?, ellipsis: TokenSyntax?, defaultArgument: InitializerClauseSyntax?, trailingComma: TokenSyntax?) -> FunctionParameterSyntax { let layout: [RawSyntax?] = [ attributes?.raw, firstName?.raw, secondName?.raw, colon?.raw, type?.raw, ellipsis?.raw, defaultArgument?.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.functionParameter, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return FunctionParameterSyntax(data) } public static func makeBlankFunctionParameter() -> FunctionParameterSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .functionParameter, layout: [ nil, nil, nil, nil, nil, nil, nil, nil, ], length: .zero, presence: .present)) return FunctionParameterSyntax(data) } public static func makeModifierList( _ elements: [DeclModifierSyntax]) -> ModifierListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.modifierList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ModifierListSyntax(data) } public static func makeBlankModifierList() -> ModifierListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .modifierList, layout: [ ], length: .zero, presence: .present)) return ModifierListSyntax(data) } public static func makeFunctionDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, funcKeyword: TokenSyntax, identifier: TokenSyntax, genericParameterClause: GenericParameterClauseSyntax?, signature: FunctionSignatureSyntax, genericWhereClause: GenericWhereClauseSyntax?, body: CodeBlockSyntax?) -> FunctionDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, funcKeyword.raw, identifier.raw, genericParameterClause?.raw, signature.raw, genericWhereClause?.raw, body?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.functionDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return FunctionDeclSyntax(data) } public static func makeBlankFunctionDecl() -> FunctionDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .functionDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.funcKeyword), RawSyntax.missingToken(TokenKind.identifier("")), nil, RawSyntax.missing(SyntaxKind.functionSignature), nil, nil, ], length: .zero, presence: .present)) return FunctionDeclSyntax(data) } public static func makeInitializerDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, initKeyword: TokenSyntax, optionalMark: TokenSyntax?, genericParameterClause: GenericParameterClauseSyntax?, parameters: ParameterClauseSyntax, throwsOrRethrowsKeyword: TokenSyntax?, genericWhereClause: GenericWhereClauseSyntax?, body: CodeBlockSyntax?) -> InitializerDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, initKeyword.raw, optionalMark?.raw, genericParameterClause?.raw, parameters.raw, throwsOrRethrowsKeyword?.raw, genericWhereClause?.raw, body?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.initializerDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return InitializerDeclSyntax(data) } public static func makeBlankInitializerDecl() -> InitializerDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .initializerDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.initKeyword), nil, nil, RawSyntax.missing(SyntaxKind.parameterClause), nil, nil, nil, ], length: .zero, presence: .present)) return InitializerDeclSyntax(data) } public static func makeDeinitializerDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, deinitKeyword: TokenSyntax, body: CodeBlockSyntax) -> DeinitializerDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, deinitKeyword.raw, body.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.deinitializerDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DeinitializerDeclSyntax(data) } public static func makeBlankDeinitializerDecl() -> DeinitializerDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .deinitializerDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.deinitKeyword), RawSyntax.missing(SyntaxKind.codeBlock), ], length: .zero, presence: .present)) return DeinitializerDeclSyntax(data) } public static func makeSubscriptDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, subscriptKeyword: TokenSyntax, genericParameterClause: GenericParameterClauseSyntax?, indices: ParameterClauseSyntax, result: ReturnClauseSyntax, genericWhereClause: GenericWhereClauseSyntax?, accessor: Syntax?) -> SubscriptDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, subscriptKeyword.raw, genericParameterClause?.raw, indices.raw, result.raw, genericWhereClause?.raw, accessor?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.subscriptDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SubscriptDeclSyntax(data) } public static func makeBlankSubscriptDecl() -> SubscriptDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .subscriptDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.subscriptKeyword), nil, RawSyntax.missing(SyntaxKind.parameterClause), RawSyntax.missing(SyntaxKind.returnClause), nil, nil, ], length: .zero, presence: .present)) return SubscriptDeclSyntax(data) } public static func makeAccessLevelModifier(name: TokenSyntax, leftParen: TokenSyntax?, modifier: TokenSyntax?, rightParen: TokenSyntax?) -> AccessLevelModifierSyntax { let layout: [RawSyntax?] = [ name.raw, leftParen?.raw, modifier?.raw, rightParen?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.accessLevelModifier, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AccessLevelModifierSyntax(data) } public static func makeBlankAccessLevelModifier() -> AccessLevelModifierSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .accessLevelModifier, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), nil, nil, nil, ], length: .zero, presence: .present)) return AccessLevelModifierSyntax(data) } public static func makeAccessPathComponent(name: TokenSyntax, trailingDot: TokenSyntax?) -> AccessPathComponentSyntax { let layout: [RawSyntax?] = [ name.raw, trailingDot?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.accessPathComponent, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AccessPathComponentSyntax(data) } public static func makeBlankAccessPathComponent() -> AccessPathComponentSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .accessPathComponent, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return AccessPathComponentSyntax(data) } public static func makeAccessPath( _ elements: [AccessPathComponentSyntax]) -> AccessPathSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.accessPath, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AccessPathSyntax(data) } public static func makeBlankAccessPath() -> AccessPathSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .accessPath, layout: [ ], length: .zero, presence: .present)) return AccessPathSyntax(data) } public static func makeImportDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, importTok: TokenSyntax, importKind: TokenSyntax?, path: AccessPathSyntax) -> ImportDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, importTok.raw, importKind?.raw, path.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.importDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ImportDeclSyntax(data) } public static func makeBlankImportDecl() -> ImportDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .importDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.importKeyword), nil, RawSyntax.missing(SyntaxKind.accessPath), ], length: .zero, presence: .present)) return ImportDeclSyntax(data) } public static func makeAccessorParameter(leftParen: TokenSyntax, name: TokenSyntax, rightParen: TokenSyntax) -> AccessorParameterSyntax { let layout: [RawSyntax?] = [ leftParen.raw, name.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.accessorParameter, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AccessorParameterSyntax(data) } public static func makeBlankAccessorParameter() -> AccessorParameterSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .accessorParameter, layout: [ RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return AccessorParameterSyntax(data) } public static func makeAccessorDecl(attributes: AttributeListSyntax?, modifier: DeclModifierSyntax?, accessorKind: TokenSyntax, parameter: AccessorParameterSyntax?, body: CodeBlockSyntax?) -> AccessorDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifier?.raw, accessorKind.raw, parameter?.raw, body?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.accessorDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AccessorDeclSyntax(data) } public static func makeBlankAccessorDecl() -> AccessorDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .accessorDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.unknown("")), nil, nil, ], length: .zero, presence: .present)) return AccessorDeclSyntax(data) } public static func makeAccessorList( _ elements: [AccessorDeclSyntax]) -> AccessorListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.accessorList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AccessorListSyntax(data) } public static func makeBlankAccessorList() -> AccessorListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .accessorList, layout: [ ], length: .zero, presence: .present)) return AccessorListSyntax(data) } public static func makeAccessorBlock(leftBrace: TokenSyntax, accessors: AccessorListSyntax, rightBrace: TokenSyntax) -> AccessorBlockSyntax { let layout: [RawSyntax?] = [ leftBrace.raw, accessors.raw, rightBrace.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.accessorBlock, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AccessorBlockSyntax(data) } public static func makeBlankAccessorBlock() -> AccessorBlockSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .accessorBlock, layout: [ RawSyntax.missingToken(TokenKind.leftBrace), RawSyntax.missing(SyntaxKind.accessorList), RawSyntax.missingToken(TokenKind.rightBrace), ], length: .zero, presence: .present)) return AccessorBlockSyntax(data) } public static func makePatternBinding(pattern: PatternSyntax, typeAnnotation: TypeAnnotationSyntax?, initializer: InitializerClauseSyntax?, accessor: Syntax?, trailingComma: TokenSyntax?) -> PatternBindingSyntax { let layout: [RawSyntax?] = [ pattern.raw, typeAnnotation?.raw, initializer?.raw, accessor?.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.patternBinding, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PatternBindingSyntax(data) } public static func makeBlankPatternBinding() -> PatternBindingSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .patternBinding, layout: [ RawSyntax.missing(SyntaxKind.pattern), nil, nil, nil, nil, ], length: .zero, presence: .present)) return PatternBindingSyntax(data) } public static func makePatternBindingList( _ elements: [PatternBindingSyntax]) -> PatternBindingListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.patternBindingList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PatternBindingListSyntax(data) } public static func makeBlankPatternBindingList() -> PatternBindingListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .patternBindingList, layout: [ ], length: .zero, presence: .present)) return PatternBindingListSyntax(data) } public static func makeVariableDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, letOrVarKeyword: TokenSyntax, bindings: PatternBindingListSyntax) -> VariableDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, letOrVarKeyword.raw, bindings.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.variableDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return VariableDeclSyntax(data) } public static func makeBlankVariableDecl() -> VariableDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .variableDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.letKeyword), RawSyntax.missing(SyntaxKind.patternBindingList), ], length: .zero, presence: .present)) return VariableDeclSyntax(data) } public static func makeEnumCaseElement(identifier: TokenSyntax, associatedValue: ParameterClauseSyntax?, rawValue: InitializerClauseSyntax?, trailingComma: TokenSyntax?) -> EnumCaseElementSyntax { let layout: [RawSyntax?] = [ identifier.raw, associatedValue?.raw, rawValue?.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.enumCaseElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return EnumCaseElementSyntax(data) } public static func makeBlankEnumCaseElement() -> EnumCaseElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .enumCaseElement, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), nil, nil, nil, ], length: .zero, presence: .present)) return EnumCaseElementSyntax(data) } public static func makeEnumCaseElementList( _ elements: [EnumCaseElementSyntax]) -> EnumCaseElementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.enumCaseElementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return EnumCaseElementListSyntax(data) } public static func makeBlankEnumCaseElementList() -> EnumCaseElementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .enumCaseElementList, layout: [ ], length: .zero, presence: .present)) return EnumCaseElementListSyntax(data) } public static func makeEnumCaseDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, caseKeyword: TokenSyntax, elements: EnumCaseElementListSyntax) -> EnumCaseDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, caseKeyword.raw, elements.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.enumCaseDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return EnumCaseDeclSyntax(data) } public static func makeBlankEnumCaseDecl() -> EnumCaseDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .enumCaseDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.caseKeyword), RawSyntax.missing(SyntaxKind.enumCaseElementList), ], length: .zero, presence: .present)) return EnumCaseDeclSyntax(data) } public static func makeEnumDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, enumKeyword: TokenSyntax, identifier: TokenSyntax, genericParameters: GenericParameterClauseSyntax?, inheritanceClause: TypeInheritanceClauseSyntax?, genericWhereClause: GenericWhereClauseSyntax?, members: MemberDeclBlockSyntax) -> EnumDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, enumKeyword.raw, identifier.raw, genericParameters?.raw, inheritanceClause?.raw, genericWhereClause?.raw, members.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.enumDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return EnumDeclSyntax(data) } public static func makeBlankEnumDecl() -> EnumDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .enumDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.enumKeyword), RawSyntax.missingToken(TokenKind.identifier("")), nil, nil, nil, RawSyntax.missing(SyntaxKind.memberDeclBlock), ], length: .zero, presence: .present)) return EnumDeclSyntax(data) } public static func makeOperatorDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, operatorKeyword: TokenSyntax, identifier: TokenSyntax, operatorPrecedenceAndTypes: OperatorPrecedenceAndTypesSyntax?) -> OperatorDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, operatorKeyword.raw, identifier.raw, operatorPrecedenceAndTypes?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.operatorDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return OperatorDeclSyntax(data) } public static func makeBlankOperatorDecl() -> OperatorDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .operatorDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.operatorKeyword), RawSyntax.missingToken(TokenKind.unspacedBinaryOperator("")), nil, ], length: .zero, presence: .present)) return OperatorDeclSyntax(data) } public static func makeIdentifierList( _ elements: [TokenSyntax]) -> IdentifierListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.identifierList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IdentifierListSyntax(data) } public static func makeBlankIdentifierList() -> IdentifierListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .identifierList, layout: [ ], length: .zero, presence: .present)) return IdentifierListSyntax(data) } public static func makeOperatorPrecedenceAndTypes(colon: TokenSyntax, precedenceGroupAndDesignatedTypes: IdentifierListSyntax) -> OperatorPrecedenceAndTypesSyntax { let layout: [RawSyntax?] = [ colon.raw, precedenceGroupAndDesignatedTypes.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.operatorPrecedenceAndTypes, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return OperatorPrecedenceAndTypesSyntax(data) } public static func makeBlankOperatorPrecedenceAndTypes() -> OperatorPrecedenceAndTypesSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .operatorPrecedenceAndTypes, layout: [ RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.identifierList), ], length: .zero, presence: .present)) return OperatorPrecedenceAndTypesSyntax(data) } public static func makePrecedenceGroupDecl(attributes: AttributeListSyntax?, modifiers: ModifierListSyntax?, precedencegroupKeyword: TokenSyntax, identifier: TokenSyntax, leftBrace: TokenSyntax, groupAttributes: PrecedenceGroupAttributeListSyntax, rightBrace: TokenSyntax) -> PrecedenceGroupDeclSyntax { let layout: [RawSyntax?] = [ attributes?.raw, modifiers?.raw, precedencegroupKeyword.raw, identifier.raw, leftBrace.raw, groupAttributes.raw, rightBrace.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.precedenceGroupDecl, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PrecedenceGroupDeclSyntax(data) } public static func makeBlankPrecedenceGroupDecl() -> PrecedenceGroupDeclSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .precedenceGroupDecl, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.precedencegroupKeyword), RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.leftBrace), RawSyntax.missing(SyntaxKind.precedenceGroupAttributeList), RawSyntax.missingToken(TokenKind.rightBrace), ], length: .zero, presence: .present)) return PrecedenceGroupDeclSyntax(data) } public static func makePrecedenceGroupAttributeList( _ elements: [Syntax]) -> PrecedenceGroupAttributeListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.precedenceGroupAttributeList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PrecedenceGroupAttributeListSyntax(data) } public static func makeBlankPrecedenceGroupAttributeList() -> PrecedenceGroupAttributeListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .precedenceGroupAttributeList, layout: [ ], length: .zero, presence: .present)) return PrecedenceGroupAttributeListSyntax(data) } public static func makePrecedenceGroupRelation(higherThanOrLowerThan: TokenSyntax, colon: TokenSyntax, otherNames: PrecedenceGroupNameListSyntax) -> PrecedenceGroupRelationSyntax { let layout: [RawSyntax?] = [ higherThanOrLowerThan.raw, colon.raw, otherNames.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.precedenceGroupRelation, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PrecedenceGroupRelationSyntax(data) } public static func makeBlankPrecedenceGroupRelation() -> PrecedenceGroupRelationSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .precedenceGroupRelation, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.precedenceGroupNameList), ], length: .zero, presence: .present)) return PrecedenceGroupRelationSyntax(data) } public static func makePrecedenceGroupNameList( _ elements: [PrecedenceGroupNameElementSyntax]) -> PrecedenceGroupNameListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.precedenceGroupNameList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PrecedenceGroupNameListSyntax(data) } public static func makeBlankPrecedenceGroupNameList() -> PrecedenceGroupNameListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .precedenceGroupNameList, layout: [ ], length: .zero, presence: .present)) return PrecedenceGroupNameListSyntax(data) } public static func makePrecedenceGroupNameElement(name: TokenSyntax, trailingComma: TokenSyntax?) -> PrecedenceGroupNameElementSyntax { let layout: [RawSyntax?] = [ name.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.precedenceGroupNameElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PrecedenceGroupNameElementSyntax(data) } public static func makeBlankPrecedenceGroupNameElement() -> PrecedenceGroupNameElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .precedenceGroupNameElement, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return PrecedenceGroupNameElementSyntax(data) } public static func makePrecedenceGroupAssignment(assignmentKeyword: TokenSyntax, colon: TokenSyntax, flag: TokenSyntax) -> PrecedenceGroupAssignmentSyntax { let layout: [RawSyntax?] = [ assignmentKeyword.raw, colon.raw, flag.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.precedenceGroupAssignment, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PrecedenceGroupAssignmentSyntax(data) } public static func makeBlankPrecedenceGroupAssignment() -> PrecedenceGroupAssignmentSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .precedenceGroupAssignment, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missingToken(TokenKind.trueKeyword), ], length: .zero, presence: .present)) return PrecedenceGroupAssignmentSyntax(data) } public static func makePrecedenceGroupAssociativity(associativityKeyword: TokenSyntax, colon: TokenSyntax, value: TokenSyntax) -> PrecedenceGroupAssociativitySyntax { let layout: [RawSyntax?] = [ associativityKeyword.raw, colon.raw, value.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.precedenceGroupAssociativity, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PrecedenceGroupAssociativitySyntax(data) } public static func makeBlankPrecedenceGroupAssociativity() -> PrecedenceGroupAssociativitySyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .precedenceGroupAssociativity, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missingToken(TokenKind.identifier("")), ], length: .zero, presence: .present)) return PrecedenceGroupAssociativitySyntax(data) } public static func makeTokenList( _ elements: [TokenSyntax]) -> TokenListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tokenList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TokenListSyntax(data) } public static func makeBlankTokenList() -> TokenListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tokenList, layout: [ ], length: .zero, presence: .present)) return TokenListSyntax(data) } public static func makeNonEmptyTokenList( _ elements: [TokenSyntax]) -> NonEmptyTokenListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.nonEmptyTokenList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return NonEmptyTokenListSyntax(data) } public static func makeBlankNonEmptyTokenList() -> NonEmptyTokenListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .nonEmptyTokenList, layout: [ ], length: .zero, presence: .present)) return NonEmptyTokenListSyntax(data) } public static func makeCustomAttribute(atSignToken: TokenSyntax, attributeName: TypeSyntax, leftParen: TokenSyntax?, argumentList: TupleExprElementListSyntax?, rightParen: TokenSyntax?) -> CustomAttributeSyntax { let layout: [RawSyntax?] = [ atSignToken.raw, attributeName.raw, leftParen?.raw, argumentList?.raw, rightParen?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.customAttribute, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CustomAttributeSyntax(data) } public static func makeBlankCustomAttribute() -> CustomAttributeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .customAttribute, layout: [ RawSyntax.missingToken(TokenKind.atSign), RawSyntax.missing(SyntaxKind.type), nil, nil, nil, ], length: .zero, presence: .present)) return CustomAttributeSyntax(data) } public static func makeAttribute(atSignToken: TokenSyntax, attributeName: TokenSyntax, leftParen: TokenSyntax?, argument: Syntax?, rightParen: TokenSyntax?, tokenList: TokenListSyntax?) -> AttributeSyntax { let layout: [RawSyntax?] = [ atSignToken.raw, attributeName.raw, leftParen?.raw, argument?.raw, rightParen?.raw, tokenList?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.attribute, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AttributeSyntax(data) } public static func makeBlankAttribute() -> AttributeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .attribute, layout: [ RawSyntax.missingToken(TokenKind.atSign), RawSyntax.missingToken(TokenKind.unknown("")), nil, nil, nil, nil, ], length: .zero, presence: .present)) return AttributeSyntax(data) } public static func makeAttributeList( _ elements: [Syntax]) -> AttributeListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.attributeList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AttributeListSyntax(data) } public static func makeBlankAttributeList() -> AttributeListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .attributeList, layout: [ ], length: .zero, presence: .present)) return AttributeListSyntax(data) } public static func makeSpecializeAttributeSpecList( _ elements: [Syntax]) -> SpecializeAttributeSpecListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.specializeAttributeSpecList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SpecializeAttributeSpecListSyntax(data) } public static func makeBlankSpecializeAttributeSpecList() -> SpecializeAttributeSpecListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .specializeAttributeSpecList, layout: [ ], length: .zero, presence: .present)) return SpecializeAttributeSpecListSyntax(data) } public static func makeLabeledSpecializeEntry(label: TokenSyntax, colon: TokenSyntax, value: TokenSyntax, trailingComma: TokenSyntax?) -> LabeledSpecializeEntrySyntax { let layout: [RawSyntax?] = [ label.raw, colon.raw, value.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.labeledSpecializeEntry, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return LabeledSpecializeEntrySyntax(data) } public static func makeBlankLabeledSpecializeEntry() -> LabeledSpecializeEntrySyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .labeledSpecializeEntry, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missingToken(TokenKind.unknown("")), nil, ], length: .zero, presence: .present)) return LabeledSpecializeEntrySyntax(data) } public static func makeNamedAttributeStringArgument(nameTok: TokenSyntax, colon: TokenSyntax, stringOrDeclname: Syntax) -> NamedAttributeStringArgumentSyntax { let layout: [RawSyntax?] = [ nameTok.raw, colon.raw, stringOrDeclname.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.namedAttributeStringArgument, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return NamedAttributeStringArgumentSyntax(data) } public static func makeBlankNamedAttributeStringArgument() -> NamedAttributeStringArgumentSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .namedAttributeStringArgument, layout: [ RawSyntax.missingToken(TokenKind.unknown("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.unknown), ], length: .zero, presence: .present)) return NamedAttributeStringArgumentSyntax(data) } public static func makeDeclName(declBaseName: Syntax, declNameArguments: DeclNameArgumentsSyntax?) -> DeclNameSyntax { let layout: [RawSyntax?] = [ declBaseName.raw, declNameArguments?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.declName, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DeclNameSyntax(data) } public static func makeBlankDeclName() -> DeclNameSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .declName, layout: [ RawSyntax.missing(SyntaxKind.unknown), nil, ], length: .zero, presence: .present)) return DeclNameSyntax(data) } public static func makeImplementsAttributeArguments(type: SimpleTypeIdentifierSyntax, comma: TokenSyntax, declBaseName: Syntax, declNameArguments: DeclNameArgumentsSyntax?) -> ImplementsAttributeArgumentsSyntax { let layout: [RawSyntax?] = [ type.raw, comma.raw, declBaseName.raw, declNameArguments?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.implementsAttributeArguments, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ImplementsAttributeArgumentsSyntax(data) } public static func makeBlankImplementsAttributeArguments() -> ImplementsAttributeArgumentsSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .implementsAttributeArguments, layout: [ RawSyntax.missing(SyntaxKind.simpleTypeIdentifier), RawSyntax.missingToken(TokenKind.comma), RawSyntax.missing(SyntaxKind.unknown), nil, ], length: .zero, presence: .present)) return ImplementsAttributeArgumentsSyntax(data) } public static func makeObjCSelectorPiece(name: TokenSyntax?, colon: TokenSyntax?) -> ObjCSelectorPieceSyntax { let layout: [RawSyntax?] = [ name?.raw, colon?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.objCSelectorPiece, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ObjCSelectorPieceSyntax(data) } public static func makeBlankObjCSelectorPiece() -> ObjCSelectorPieceSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .objCSelectorPiece, layout: [ nil, nil, ], length: .zero, presence: .present)) return ObjCSelectorPieceSyntax(data) } public static func makeObjCSelector( _ elements: [ObjCSelectorPieceSyntax]) -> ObjCSelectorSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.objCSelector, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ObjCSelectorSyntax(data) } public static func makeBlankObjCSelector() -> ObjCSelectorSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .objCSelector, layout: [ ], length: .zero, presence: .present)) return ObjCSelectorSyntax(data) } public static func makeDifferentiableAttributeArguments(diffParams: DifferentiabilityParamsClauseSyntax?, diffParamsComma: TokenSyntax?, whereClause: GenericWhereClauseSyntax?) -> DifferentiableAttributeArgumentsSyntax { let layout: [RawSyntax?] = [ diffParams?.raw, diffParamsComma?.raw, whereClause?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.differentiableAttributeArguments, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DifferentiableAttributeArgumentsSyntax(data) } public static func makeBlankDifferentiableAttributeArguments() -> DifferentiableAttributeArgumentsSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .differentiableAttributeArguments, layout: [ nil, nil, nil, ], length: .zero, presence: .present)) return DifferentiableAttributeArgumentsSyntax(data) } public static func makeDifferentiabilityParamsClause(wrtLabel: TokenSyntax, colon: TokenSyntax, parameters: Syntax) -> DifferentiabilityParamsClauseSyntax { let layout: [RawSyntax?] = [ wrtLabel.raw, colon.raw, parameters.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.differentiabilityParamsClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DifferentiabilityParamsClauseSyntax(data) } public static func makeBlankDifferentiabilityParamsClause() -> DifferentiabilityParamsClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .differentiabilityParamsClause, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.unknown), ], length: .zero, presence: .present)) return DifferentiabilityParamsClauseSyntax(data) } public static func makeDifferentiabilityParams(leftParen: TokenSyntax, diffParams: DifferentiabilityParamListSyntax, rightParen: TokenSyntax) -> DifferentiabilityParamsSyntax { let layout: [RawSyntax?] = [ leftParen.raw, diffParams.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.differentiabilityParams, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DifferentiabilityParamsSyntax(data) } public static func makeBlankDifferentiabilityParams() -> DifferentiabilityParamsSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .differentiabilityParams, layout: [ RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.differentiabilityParamList), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return DifferentiabilityParamsSyntax(data) } public static func makeDifferentiabilityParamList( _ elements: [DifferentiabilityParamSyntax]) -> DifferentiabilityParamListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.differentiabilityParamList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DifferentiabilityParamListSyntax(data) } public static func makeBlankDifferentiabilityParamList() -> DifferentiabilityParamListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .differentiabilityParamList, layout: [ ], length: .zero, presence: .present)) return DifferentiabilityParamListSyntax(data) } public static func makeDifferentiabilityParam(parameter: Syntax, trailingComma: TokenSyntax?) -> DifferentiabilityParamSyntax { let layout: [RawSyntax?] = [ parameter.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.differentiabilityParam, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DifferentiabilityParamSyntax(data) } public static func makeBlankDifferentiabilityParam() -> DifferentiabilityParamSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .differentiabilityParam, layout: [ RawSyntax.missing(SyntaxKind.unknown), nil, ], length: .zero, presence: .present)) return DifferentiabilityParamSyntax(data) } public static func makeDerivativeRegistrationAttributeArguments(ofLabel: TokenSyntax, colon: TokenSyntax, originalDeclName: QualifiedDeclNameSyntax, period: TokenSyntax?, accessorKind: TokenSyntax?, comma: TokenSyntax?, diffParams: DifferentiabilityParamsClauseSyntax?) -> DerivativeRegistrationAttributeArgumentsSyntax { let layout: [RawSyntax?] = [ ofLabel.raw, colon.raw, originalDeclName.raw, period?.raw, accessorKind?.raw, comma?.raw, diffParams?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.derivativeRegistrationAttributeArguments, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DerivativeRegistrationAttributeArgumentsSyntax(data) } public static func makeBlankDerivativeRegistrationAttributeArguments() -> DerivativeRegistrationAttributeArgumentsSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .derivativeRegistrationAttributeArguments, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.qualifiedDeclName), nil, nil, nil, nil, ], length: .zero, presence: .present)) return DerivativeRegistrationAttributeArgumentsSyntax(data) } public static func makeQualifiedDeclName(baseType: TypeSyntax?, dot: TokenSyntax?, name: TokenSyntax, arguments: DeclNameArgumentsSyntax?) -> QualifiedDeclNameSyntax { let layout: [RawSyntax?] = [ baseType?.raw, dot?.raw, name.raw, arguments?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.qualifiedDeclName, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return QualifiedDeclNameSyntax(data) } public static func makeBlankQualifiedDeclName() -> QualifiedDeclNameSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .qualifiedDeclName, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return QualifiedDeclNameSyntax(data) } public static func makeFunctionDeclName(name: Syntax, arguments: DeclNameArgumentsSyntax?) -> FunctionDeclNameSyntax { let layout: [RawSyntax?] = [ name.raw, arguments?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.functionDeclName, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return FunctionDeclNameSyntax(data) } public static func makeBlankFunctionDeclName() -> FunctionDeclNameSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .functionDeclName, layout: [ RawSyntax.missing(SyntaxKind.unknown), nil, ], length: .zero, presence: .present)) return FunctionDeclNameSyntax(data) } public static func makeContinueStmt(continueKeyword: TokenSyntax, label: TokenSyntax?) -> ContinueStmtSyntax { let layout: [RawSyntax?] = [ continueKeyword.raw, label?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.continueStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ContinueStmtSyntax(data) } public static func makeBlankContinueStmt() -> ContinueStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .continueStmt, layout: [ RawSyntax.missingToken(TokenKind.continueKeyword), nil, ], length: .zero, presence: .present)) return ContinueStmtSyntax(data) } public static func makeWhileStmt(labelName: TokenSyntax?, labelColon: TokenSyntax?, whileKeyword: TokenSyntax, conditions: ConditionElementListSyntax, body: CodeBlockSyntax) -> WhileStmtSyntax { let layout: [RawSyntax?] = [ labelName?.raw, labelColon?.raw, whileKeyword.raw, conditions.raw, body.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.whileStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return WhileStmtSyntax(data) } public static func makeBlankWhileStmt() -> WhileStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .whileStmt, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.whileKeyword), RawSyntax.missing(SyntaxKind.conditionElementList), RawSyntax.missing(SyntaxKind.codeBlock), ], length: .zero, presence: .present)) return WhileStmtSyntax(data) } public static func makeDeferStmt(deferKeyword: TokenSyntax, body: CodeBlockSyntax) -> DeferStmtSyntax { let layout: [RawSyntax?] = [ deferKeyword.raw, body.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.deferStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DeferStmtSyntax(data) } public static func makeBlankDeferStmt() -> DeferStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .deferStmt, layout: [ RawSyntax.missingToken(TokenKind.deferKeyword), RawSyntax.missing(SyntaxKind.codeBlock), ], length: .zero, presence: .present)) return DeferStmtSyntax(data) } public static func makeExpressionStmt(expression: ExprSyntax) -> ExpressionStmtSyntax { let layout: [RawSyntax?] = [ expression.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.expressionStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ExpressionStmtSyntax(data) } public static func makeBlankExpressionStmt() -> ExpressionStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .expressionStmt, layout: [ RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return ExpressionStmtSyntax(data) } public static func makeSwitchCaseList( _ elements: [Syntax]) -> SwitchCaseListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.switchCaseList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SwitchCaseListSyntax(data) } public static func makeBlankSwitchCaseList() -> SwitchCaseListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .switchCaseList, layout: [ ], length: .zero, presence: .present)) return SwitchCaseListSyntax(data) } public static func makeRepeatWhileStmt(labelName: TokenSyntax?, labelColon: TokenSyntax?, repeatKeyword: TokenSyntax, body: CodeBlockSyntax, whileKeyword: TokenSyntax, condition: ExprSyntax) -> RepeatWhileStmtSyntax { let layout: [RawSyntax?] = [ labelName?.raw, labelColon?.raw, repeatKeyword.raw, body.raw, whileKeyword.raw, condition.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.repeatWhileStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return RepeatWhileStmtSyntax(data) } public static func makeBlankRepeatWhileStmt() -> RepeatWhileStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .repeatWhileStmt, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.repeatKeyword), RawSyntax.missing(SyntaxKind.codeBlock), RawSyntax.missingToken(TokenKind.whileKeyword), RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return RepeatWhileStmtSyntax(data) } public static func makeGuardStmt(guardKeyword: TokenSyntax, conditions: ConditionElementListSyntax, elseKeyword: TokenSyntax, body: CodeBlockSyntax) -> GuardStmtSyntax { let layout: [RawSyntax?] = [ guardKeyword.raw, conditions.raw, elseKeyword.raw, body.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.guardStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GuardStmtSyntax(data) } public static func makeBlankGuardStmt() -> GuardStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .guardStmt, layout: [ RawSyntax.missingToken(TokenKind.guardKeyword), RawSyntax.missing(SyntaxKind.conditionElementList), RawSyntax.missingToken(TokenKind.elseKeyword), RawSyntax.missing(SyntaxKind.codeBlock), ], length: .zero, presence: .present)) return GuardStmtSyntax(data) } public static func makeWhereClause(whereKeyword: TokenSyntax, guardResult: ExprSyntax) -> WhereClauseSyntax { let layout: [RawSyntax?] = [ whereKeyword.raw, guardResult.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.whereClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return WhereClauseSyntax(data) } public static func makeBlankWhereClause() -> WhereClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .whereClause, layout: [ RawSyntax.missingToken(TokenKind.whereKeyword), RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return WhereClauseSyntax(data) } public static func makeForInStmt(labelName: TokenSyntax?, labelColon: TokenSyntax?, forKeyword: TokenSyntax, caseKeyword: TokenSyntax?, pattern: PatternSyntax, typeAnnotation: TypeAnnotationSyntax?, inKeyword: TokenSyntax, sequenceExpr: ExprSyntax, whereClause: WhereClauseSyntax?, body: CodeBlockSyntax) -> ForInStmtSyntax { let layout: [RawSyntax?] = [ labelName?.raw, labelColon?.raw, forKeyword.raw, caseKeyword?.raw, pattern.raw, typeAnnotation?.raw, inKeyword.raw, sequenceExpr.raw, whereClause?.raw, body.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.forInStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ForInStmtSyntax(data) } public static func makeBlankForInStmt() -> ForInStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .forInStmt, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.forKeyword), nil, RawSyntax.missing(SyntaxKind.pattern), nil, RawSyntax.missingToken(TokenKind.inKeyword), RawSyntax.missing(SyntaxKind.expr), nil, RawSyntax.missing(SyntaxKind.codeBlock), ], length: .zero, presence: .present)) return ForInStmtSyntax(data) } public static func makeSwitchStmt(labelName: TokenSyntax?, labelColon: TokenSyntax?, switchKeyword: TokenSyntax, expression: ExprSyntax, leftBrace: TokenSyntax, cases: SwitchCaseListSyntax, rightBrace: TokenSyntax) -> SwitchStmtSyntax { let layout: [RawSyntax?] = [ labelName?.raw, labelColon?.raw, switchKeyword.raw, expression.raw, leftBrace.raw, cases.raw, rightBrace.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.switchStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SwitchStmtSyntax(data) } public static func makeBlankSwitchStmt() -> SwitchStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .switchStmt, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.switchKeyword), RawSyntax.missing(SyntaxKind.expr), RawSyntax.missingToken(TokenKind.leftBrace), RawSyntax.missing(SyntaxKind.switchCaseList), RawSyntax.missingToken(TokenKind.rightBrace), ], length: .zero, presence: .present)) return SwitchStmtSyntax(data) } public static func makeCatchClauseList( _ elements: [CatchClauseSyntax]) -> CatchClauseListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.catchClauseList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CatchClauseListSyntax(data) } public static func makeBlankCatchClauseList() -> CatchClauseListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .catchClauseList, layout: [ ], length: .zero, presence: .present)) return CatchClauseListSyntax(data) } public static func makeDoStmt(labelName: TokenSyntax?, labelColon: TokenSyntax?, doKeyword: TokenSyntax, body: CodeBlockSyntax, catchClauses: CatchClauseListSyntax?) -> DoStmtSyntax { let layout: [RawSyntax?] = [ labelName?.raw, labelColon?.raw, doKeyword.raw, body.raw, catchClauses?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.doStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DoStmtSyntax(data) } public static func makeBlankDoStmt() -> DoStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .doStmt, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.doKeyword), RawSyntax.missing(SyntaxKind.codeBlock), nil, ], length: .zero, presence: .present)) return DoStmtSyntax(data) } public static func makeReturnStmt(returnKeyword: TokenSyntax, expression: ExprSyntax?) -> ReturnStmtSyntax { let layout: [RawSyntax?] = [ returnKeyword.raw, expression?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.returnStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ReturnStmtSyntax(data) } public static func makeBlankReturnStmt() -> ReturnStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .returnStmt, layout: [ RawSyntax.missingToken(TokenKind.returnKeyword), nil, ], length: .zero, presence: .present)) return ReturnStmtSyntax(data) } public static func makeYieldStmt(yieldKeyword: TokenSyntax, yields: Syntax) -> YieldStmtSyntax { let layout: [RawSyntax?] = [ yieldKeyword.raw, yields.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.yieldStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return YieldStmtSyntax(data) } public static func makeBlankYieldStmt() -> YieldStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .yieldStmt, layout: [ RawSyntax.missingToken(TokenKind.yield), RawSyntax.missing(SyntaxKind.unknown), ], length: .zero, presence: .present)) return YieldStmtSyntax(data) } public static func makeYieldList(leftParen: TokenSyntax, elementList: ExprListSyntax, trailingComma: TokenSyntax?, rightParen: TokenSyntax) -> YieldListSyntax { let layout: [RawSyntax?] = [ leftParen.raw, elementList.raw, trailingComma?.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.yieldList, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return YieldListSyntax(data) } public static func makeBlankYieldList() -> YieldListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .yieldList, layout: [ RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.exprList), nil, RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return YieldListSyntax(data) } public static func makeFallthroughStmt(fallthroughKeyword: TokenSyntax) -> FallthroughStmtSyntax { let layout: [RawSyntax?] = [ fallthroughKeyword.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.fallthroughStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return FallthroughStmtSyntax(data) } public static func makeBlankFallthroughStmt() -> FallthroughStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .fallthroughStmt, layout: [ RawSyntax.missingToken(TokenKind.fallthroughKeyword), ], length: .zero, presence: .present)) return FallthroughStmtSyntax(data) } public static func makeBreakStmt(breakKeyword: TokenSyntax, label: TokenSyntax?) -> BreakStmtSyntax { let layout: [RawSyntax?] = [ breakKeyword.raw, label?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.breakStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return BreakStmtSyntax(data) } public static func makeBlankBreakStmt() -> BreakStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .breakStmt, layout: [ RawSyntax.missingToken(TokenKind.breakKeyword), nil, ], length: .zero, presence: .present)) return BreakStmtSyntax(data) } public static func makeCaseItemList( _ elements: [CaseItemSyntax]) -> CaseItemListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.caseItemList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CaseItemListSyntax(data) } public static func makeBlankCaseItemList() -> CaseItemListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .caseItemList, layout: [ ], length: .zero, presence: .present)) return CaseItemListSyntax(data) } public static func makeCatchItemList( _ elements: [CatchItemSyntax]) -> CatchItemListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.catchItemList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CatchItemListSyntax(data) } public static func makeBlankCatchItemList() -> CatchItemListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .catchItemList, layout: [ ], length: .zero, presence: .present)) return CatchItemListSyntax(data) } public static func makeConditionElement(condition: Syntax, trailingComma: TokenSyntax?) -> ConditionElementSyntax { let layout: [RawSyntax?] = [ condition.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.conditionElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ConditionElementSyntax(data) } public static func makeBlankConditionElement() -> ConditionElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .conditionElement, layout: [ RawSyntax.missing(SyntaxKind.unknown), nil, ], length: .zero, presence: .present)) return ConditionElementSyntax(data) } public static func makeAvailabilityCondition(poundAvailableKeyword: TokenSyntax, leftParen: TokenSyntax, availabilitySpec: AvailabilitySpecListSyntax, rightParen: TokenSyntax) -> AvailabilityConditionSyntax { let layout: [RawSyntax?] = [ poundAvailableKeyword.raw, leftParen.raw, availabilitySpec.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.availabilityCondition, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AvailabilityConditionSyntax(data) } public static func makeBlankAvailabilityCondition() -> AvailabilityConditionSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .availabilityCondition, layout: [ RawSyntax.missingToken(TokenKind.poundAvailableKeyword), RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.availabilitySpecList), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return AvailabilityConditionSyntax(data) } public static func makeMatchingPatternCondition(caseKeyword: TokenSyntax, pattern: PatternSyntax, typeAnnotation: TypeAnnotationSyntax?, initializer: InitializerClauseSyntax) -> MatchingPatternConditionSyntax { let layout: [RawSyntax?] = [ caseKeyword.raw, pattern.raw, typeAnnotation?.raw, initializer.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.matchingPatternCondition, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return MatchingPatternConditionSyntax(data) } public static func makeBlankMatchingPatternCondition() -> MatchingPatternConditionSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .matchingPatternCondition, layout: [ RawSyntax.missingToken(TokenKind.caseKeyword), RawSyntax.missing(SyntaxKind.pattern), nil, RawSyntax.missing(SyntaxKind.initializerClause), ], length: .zero, presence: .present)) return MatchingPatternConditionSyntax(data) } public static func makeOptionalBindingCondition(letOrVarKeyword: TokenSyntax, pattern: PatternSyntax, typeAnnotation: TypeAnnotationSyntax?, initializer: InitializerClauseSyntax) -> OptionalBindingConditionSyntax { let layout: [RawSyntax?] = [ letOrVarKeyword.raw, pattern.raw, typeAnnotation?.raw, initializer.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.optionalBindingCondition, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return OptionalBindingConditionSyntax(data) } public static func makeBlankOptionalBindingCondition() -> OptionalBindingConditionSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .optionalBindingCondition, layout: [ RawSyntax.missingToken(TokenKind.letKeyword), RawSyntax.missing(SyntaxKind.pattern), nil, RawSyntax.missing(SyntaxKind.initializerClause), ], length: .zero, presence: .present)) return OptionalBindingConditionSyntax(data) } public static func makeConditionElementList( _ elements: [ConditionElementSyntax]) -> ConditionElementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.conditionElementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ConditionElementListSyntax(data) } public static func makeBlankConditionElementList() -> ConditionElementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .conditionElementList, layout: [ ], length: .zero, presence: .present)) return ConditionElementListSyntax(data) } public static func makeDeclarationStmt(declaration: DeclSyntax) -> DeclarationStmtSyntax { let layout: [RawSyntax?] = [ declaration.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.declarationStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DeclarationStmtSyntax(data) } public static func makeBlankDeclarationStmt() -> DeclarationStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .declarationStmt, layout: [ RawSyntax.missing(SyntaxKind.decl), ], length: .zero, presence: .present)) return DeclarationStmtSyntax(data) } public static func makeThrowStmt(throwKeyword: TokenSyntax, expression: ExprSyntax) -> ThrowStmtSyntax { let layout: [RawSyntax?] = [ throwKeyword.raw, expression.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.throwStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ThrowStmtSyntax(data) } public static func makeBlankThrowStmt() -> ThrowStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .throwStmt, layout: [ RawSyntax.missingToken(TokenKind.throwKeyword), RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return ThrowStmtSyntax(data) } public static func makeIfStmt(labelName: TokenSyntax?, labelColon: TokenSyntax?, ifKeyword: TokenSyntax, conditions: ConditionElementListSyntax, body: CodeBlockSyntax, elseKeyword: TokenSyntax?, elseBody: Syntax?) -> IfStmtSyntax { let layout: [RawSyntax?] = [ labelName?.raw, labelColon?.raw, ifKeyword.raw, conditions.raw, body.raw, elseKeyword?.raw, elseBody?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.ifStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IfStmtSyntax(data) } public static func makeBlankIfStmt() -> IfStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .ifStmt, layout: [ nil, nil, RawSyntax.missingToken(TokenKind.ifKeyword), RawSyntax.missing(SyntaxKind.conditionElementList), RawSyntax.missing(SyntaxKind.codeBlock), nil, nil, ], length: .zero, presence: .present)) return IfStmtSyntax(data) } public static func makeElseIfContinuation(ifStatement: IfStmtSyntax) -> ElseIfContinuationSyntax { let layout: [RawSyntax?] = [ ifStatement.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.elseIfContinuation, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ElseIfContinuationSyntax(data) } public static func makeBlankElseIfContinuation() -> ElseIfContinuationSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .elseIfContinuation, layout: [ RawSyntax.missing(SyntaxKind.ifStmt), ], length: .zero, presence: .present)) return ElseIfContinuationSyntax(data) } public static func makeElseBlock(elseKeyword: TokenSyntax, body: CodeBlockSyntax) -> ElseBlockSyntax { let layout: [RawSyntax?] = [ elseKeyword.raw, body.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.elseBlock, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ElseBlockSyntax(data) } public static func makeBlankElseBlock() -> ElseBlockSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .elseBlock, layout: [ RawSyntax.missingToken(TokenKind.elseKeyword), RawSyntax.missing(SyntaxKind.codeBlock), ], length: .zero, presence: .present)) return ElseBlockSyntax(data) } public static func makeSwitchCase(unknownAttr: AttributeSyntax?, label: Syntax, statements: CodeBlockItemListSyntax) -> SwitchCaseSyntax { let layout: [RawSyntax?] = [ unknownAttr?.raw, label.raw, statements.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.switchCase, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SwitchCaseSyntax(data) } public static func makeBlankSwitchCase() -> SwitchCaseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .switchCase, layout: [ nil, RawSyntax.missing(SyntaxKind.unknown), RawSyntax.missing(SyntaxKind.codeBlockItemList), ], length: .zero, presence: .present)) return SwitchCaseSyntax(data) } public static func makeSwitchDefaultLabel(defaultKeyword: TokenSyntax, colon: TokenSyntax) -> SwitchDefaultLabelSyntax { let layout: [RawSyntax?] = [ defaultKeyword.raw, colon.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.switchDefaultLabel, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SwitchDefaultLabelSyntax(data) } public static func makeBlankSwitchDefaultLabel() -> SwitchDefaultLabelSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .switchDefaultLabel, layout: [ RawSyntax.missingToken(TokenKind.defaultKeyword), RawSyntax.missingToken(TokenKind.colon), ], length: .zero, presence: .present)) return SwitchDefaultLabelSyntax(data) } public static func makeCaseItem(pattern: PatternSyntax, whereClause: WhereClauseSyntax?, trailingComma: TokenSyntax?) -> CaseItemSyntax { let layout: [RawSyntax?] = [ pattern.raw, whereClause?.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.caseItem, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CaseItemSyntax(data) } public static func makeBlankCaseItem() -> CaseItemSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .caseItem, layout: [ RawSyntax.missing(SyntaxKind.pattern), nil, nil, ], length: .zero, presence: .present)) return CaseItemSyntax(data) } public static func makeCatchItem(pattern: PatternSyntax?, whereClause: WhereClauseSyntax?, trailingComma: TokenSyntax?) -> CatchItemSyntax { let layout: [RawSyntax?] = [ pattern?.raw, whereClause?.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.catchItem, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CatchItemSyntax(data) } public static func makeBlankCatchItem() -> CatchItemSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .catchItem, layout: [ nil, nil, nil, ], length: .zero, presence: .present)) return CatchItemSyntax(data) } public static func makeSwitchCaseLabel(caseKeyword: TokenSyntax, caseItems: CaseItemListSyntax, colon: TokenSyntax) -> SwitchCaseLabelSyntax { let layout: [RawSyntax?] = [ caseKeyword.raw, caseItems.raw, colon.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.switchCaseLabel, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SwitchCaseLabelSyntax(data) } public static func makeBlankSwitchCaseLabel() -> SwitchCaseLabelSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .switchCaseLabel, layout: [ RawSyntax.missingToken(TokenKind.caseKeyword), RawSyntax.missing(SyntaxKind.caseItemList), RawSyntax.missingToken(TokenKind.colon), ], length: .zero, presence: .present)) return SwitchCaseLabelSyntax(data) } public static func makeCatchClause(catchKeyword: TokenSyntax, catchItems: CatchItemListSyntax?, body: CodeBlockSyntax) -> CatchClauseSyntax { let layout: [RawSyntax?] = [ catchKeyword.raw, catchItems?.raw, body.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.catchClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CatchClauseSyntax(data) } public static func makeBlankCatchClause() -> CatchClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .catchClause, layout: [ RawSyntax.missingToken(TokenKind.catchKeyword), nil, RawSyntax.missing(SyntaxKind.codeBlock), ], length: .zero, presence: .present)) return CatchClauseSyntax(data) } public static func makePoundAssertStmt(poundAssert: TokenSyntax, leftParen: TokenSyntax, condition: ExprSyntax, comma: TokenSyntax?, message: TokenSyntax?, rightParen: TokenSyntax) -> PoundAssertStmtSyntax { let layout: [RawSyntax?] = [ poundAssert.raw, leftParen.raw, condition.raw, comma?.raw, message?.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.poundAssertStmt, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return PoundAssertStmtSyntax(data) } public static func makeBlankPoundAssertStmt() -> PoundAssertStmtSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .poundAssertStmt, layout: [ RawSyntax.missingToken(TokenKind.poundAssertKeyword), RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.expr), nil, nil, RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return PoundAssertStmtSyntax(data) } public static func makeGenericWhereClause(whereKeyword: TokenSyntax, requirementList: GenericRequirementListSyntax) -> GenericWhereClauseSyntax { let layout: [RawSyntax?] = [ whereKeyword.raw, requirementList.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.genericWhereClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GenericWhereClauseSyntax(data) } public static func makeBlankGenericWhereClause() -> GenericWhereClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .genericWhereClause, layout: [ RawSyntax.missingToken(TokenKind.whereKeyword), RawSyntax.missing(SyntaxKind.genericRequirementList), ], length: .zero, presence: .present)) return GenericWhereClauseSyntax(data) } public static func makeGenericRequirementList( _ elements: [GenericRequirementSyntax]) -> GenericRequirementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.genericRequirementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GenericRequirementListSyntax(data) } public static func makeBlankGenericRequirementList() -> GenericRequirementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .genericRequirementList, layout: [ ], length: .zero, presence: .present)) return GenericRequirementListSyntax(data) } public static func makeGenericRequirement(body: Syntax, trailingComma: TokenSyntax?) -> GenericRequirementSyntax { let layout: [RawSyntax?] = [ body.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.genericRequirement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GenericRequirementSyntax(data) } public static func makeBlankGenericRequirement() -> GenericRequirementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .genericRequirement, layout: [ RawSyntax.missing(SyntaxKind.unknown), nil, ], length: .zero, presence: .present)) return GenericRequirementSyntax(data) } public static func makeSameTypeRequirement(leftTypeIdentifier: TypeSyntax, equalityToken: TokenSyntax, rightTypeIdentifier: TypeSyntax) -> SameTypeRequirementSyntax { let layout: [RawSyntax?] = [ leftTypeIdentifier.raw, equalityToken.raw, rightTypeIdentifier.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.sameTypeRequirement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SameTypeRequirementSyntax(data) } public static func makeBlankSameTypeRequirement() -> SameTypeRequirementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .sameTypeRequirement, layout: [ RawSyntax.missing(SyntaxKind.type), RawSyntax.missingToken(TokenKind.spacedBinaryOperator("")), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return SameTypeRequirementSyntax(data) } public static func makeGenericParameterList( _ elements: [GenericParameterSyntax]) -> GenericParameterListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.genericParameterList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GenericParameterListSyntax(data) } public static func makeBlankGenericParameterList() -> GenericParameterListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .genericParameterList, layout: [ ], length: .zero, presence: .present)) return GenericParameterListSyntax(data) } public static func makeGenericParameter(attributes: AttributeListSyntax?, name: TokenSyntax, colon: TokenSyntax?, inheritedType: TypeSyntax?, trailingComma: TokenSyntax?) -> GenericParameterSyntax { let layout: [RawSyntax?] = [ attributes?.raw, name.raw, colon?.raw, inheritedType?.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.genericParameter, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GenericParameterSyntax(data) } public static func makeBlankGenericParameter() -> GenericParameterSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .genericParameter, layout: [ nil, RawSyntax.missingToken(TokenKind.identifier("")), nil, nil, nil, ], length: .zero, presence: .present)) return GenericParameterSyntax(data) } public static func makeGenericParameterClause(leftAngleBracket: TokenSyntax, genericParameterList: GenericParameterListSyntax, rightAngleBracket: TokenSyntax) -> GenericParameterClauseSyntax { let layout: [RawSyntax?] = [ leftAngleBracket.raw, genericParameterList.raw, rightAngleBracket.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.genericParameterClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GenericParameterClauseSyntax(data) } public static func makeBlankGenericParameterClause() -> GenericParameterClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .genericParameterClause, layout: [ RawSyntax.missingToken(TokenKind.leftAngle), RawSyntax.missing(SyntaxKind.genericParameterList), RawSyntax.missingToken(TokenKind.rightAngle), ], length: .zero, presence: .present)) return GenericParameterClauseSyntax(data) } public static func makeConformanceRequirement(leftTypeIdentifier: TypeSyntax, colon: TokenSyntax, rightTypeIdentifier: TypeSyntax) -> ConformanceRequirementSyntax { let layout: [RawSyntax?] = [ leftTypeIdentifier.raw, colon.raw, rightTypeIdentifier.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.conformanceRequirement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ConformanceRequirementSyntax(data) } public static func makeBlankConformanceRequirement() -> ConformanceRequirementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .conformanceRequirement, layout: [ RawSyntax.missing(SyntaxKind.type), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return ConformanceRequirementSyntax(data) } public static func makeSimpleTypeIdentifier(name: TokenSyntax, genericArgumentClause: GenericArgumentClauseSyntax?) -> SimpleTypeIdentifierSyntax { let layout: [RawSyntax?] = [ name.raw, genericArgumentClause?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.simpleTypeIdentifier, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SimpleTypeIdentifierSyntax(data) } public static func makeBlankSimpleTypeIdentifier() -> SimpleTypeIdentifierSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .simpleTypeIdentifier, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return SimpleTypeIdentifierSyntax(data) } public static func makeMemberTypeIdentifier(baseType: TypeSyntax, period: TokenSyntax, name: TokenSyntax, genericArgumentClause: GenericArgumentClauseSyntax?) -> MemberTypeIdentifierSyntax { let layout: [RawSyntax?] = [ baseType.raw, period.raw, name.raw, genericArgumentClause?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.memberTypeIdentifier, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return MemberTypeIdentifierSyntax(data) } public static func makeBlankMemberTypeIdentifier() -> MemberTypeIdentifierSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .memberTypeIdentifier, layout: [ RawSyntax.missing(SyntaxKind.type), RawSyntax.missingToken(TokenKind.period), RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return MemberTypeIdentifierSyntax(data) } public static func makeClassRestrictionType(classKeyword: TokenSyntax) -> ClassRestrictionTypeSyntax { let layout: [RawSyntax?] = [ classKeyword.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.classRestrictionType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ClassRestrictionTypeSyntax(data) } public static func makeBlankClassRestrictionType() -> ClassRestrictionTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .classRestrictionType, layout: [ RawSyntax.missingToken(TokenKind.classKeyword), ], length: .zero, presence: .present)) return ClassRestrictionTypeSyntax(data) } public static func makeArrayType(leftSquareBracket: TokenSyntax, elementType: TypeSyntax, rightSquareBracket: TokenSyntax) -> ArrayTypeSyntax { let layout: [RawSyntax?] = [ leftSquareBracket.raw, elementType.raw, rightSquareBracket.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.arrayType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ArrayTypeSyntax(data) } public static func makeBlankArrayType() -> ArrayTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .arrayType, layout: [ RawSyntax.missingToken(TokenKind.leftSquareBracket), RawSyntax.missing(SyntaxKind.type), RawSyntax.missingToken(TokenKind.rightSquareBracket), ], length: .zero, presence: .present)) return ArrayTypeSyntax(data) } public static func makeDictionaryType(leftSquareBracket: TokenSyntax, keyType: TypeSyntax, colon: TokenSyntax, valueType: TypeSyntax, rightSquareBracket: TokenSyntax) -> DictionaryTypeSyntax { let layout: [RawSyntax?] = [ leftSquareBracket.raw, keyType.raw, colon.raw, valueType.raw, rightSquareBracket.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.dictionaryType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return DictionaryTypeSyntax(data) } public static func makeBlankDictionaryType() -> DictionaryTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .dictionaryType, layout: [ RawSyntax.missingToken(TokenKind.leftSquareBracket), RawSyntax.missing(SyntaxKind.type), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.type), RawSyntax.missingToken(TokenKind.rightSquareBracket), ], length: .zero, presence: .present)) return DictionaryTypeSyntax(data) } public static func makeMetatypeType(baseType: TypeSyntax, period: TokenSyntax, typeOrProtocol: TokenSyntax) -> MetatypeTypeSyntax { let layout: [RawSyntax?] = [ baseType.raw, period.raw, typeOrProtocol.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.metatypeType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return MetatypeTypeSyntax(data) } public static func makeBlankMetatypeType() -> MetatypeTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .metatypeType, layout: [ RawSyntax.missing(SyntaxKind.type), RawSyntax.missingToken(TokenKind.period), RawSyntax.missingToken(TokenKind.identifier("")), ], length: .zero, presence: .present)) return MetatypeTypeSyntax(data) } public static func makeOptionalType(wrappedType: TypeSyntax, questionMark: TokenSyntax) -> OptionalTypeSyntax { let layout: [RawSyntax?] = [ wrappedType.raw, questionMark.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.optionalType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return OptionalTypeSyntax(data) } public static func makeBlankOptionalType() -> OptionalTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .optionalType, layout: [ RawSyntax.missing(SyntaxKind.type), RawSyntax.missingToken(TokenKind.postfixQuestionMark), ], length: .zero, presence: .present)) return OptionalTypeSyntax(data) } public static func makeSomeType(someSpecifier: TokenSyntax, baseType: TypeSyntax) -> SomeTypeSyntax { let layout: [RawSyntax?] = [ someSpecifier.raw, baseType.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.someType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return SomeTypeSyntax(data) } public static func makeBlankSomeType() -> SomeTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .someType, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return SomeTypeSyntax(data) } public static func makeImplicitlyUnwrappedOptionalType(wrappedType: TypeSyntax, exclamationMark: TokenSyntax) -> ImplicitlyUnwrappedOptionalTypeSyntax { let layout: [RawSyntax?] = [ wrappedType.raw, exclamationMark.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.implicitlyUnwrappedOptionalType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ImplicitlyUnwrappedOptionalTypeSyntax(data) } public static func makeBlankImplicitlyUnwrappedOptionalType() -> ImplicitlyUnwrappedOptionalTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .implicitlyUnwrappedOptionalType, layout: [ RawSyntax.missing(SyntaxKind.type), RawSyntax.missingToken(TokenKind.exclamationMark), ], length: .zero, presence: .present)) return ImplicitlyUnwrappedOptionalTypeSyntax(data) } public static func makeCompositionTypeElement(type: TypeSyntax, ampersand: TokenSyntax?) -> CompositionTypeElementSyntax { let layout: [RawSyntax?] = [ type.raw, ampersand?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.compositionTypeElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CompositionTypeElementSyntax(data) } public static func makeBlankCompositionTypeElement() -> CompositionTypeElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .compositionTypeElement, layout: [ RawSyntax.missing(SyntaxKind.type), nil, ], length: .zero, presence: .present)) return CompositionTypeElementSyntax(data) } public static func makeCompositionTypeElementList( _ elements: [CompositionTypeElementSyntax]) -> CompositionTypeElementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.compositionTypeElementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CompositionTypeElementListSyntax(data) } public static func makeBlankCompositionTypeElementList() -> CompositionTypeElementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .compositionTypeElementList, layout: [ ], length: .zero, presence: .present)) return CompositionTypeElementListSyntax(data) } public static func makeCompositionType(elements: CompositionTypeElementListSyntax) -> CompositionTypeSyntax { let layout: [RawSyntax?] = [ elements.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.compositionType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return CompositionTypeSyntax(data) } public static func makeBlankCompositionType() -> CompositionTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .compositionType, layout: [ RawSyntax.missing(SyntaxKind.compositionTypeElementList), ], length: .zero, presence: .present)) return CompositionTypeSyntax(data) } public static func makeTupleTypeElement(inOut: TokenSyntax?, name: TokenSyntax?, secondName: TokenSyntax?, colon: TokenSyntax?, type: TypeSyntax, ellipsis: TokenSyntax?, initializer: InitializerClauseSyntax?, trailingComma: TokenSyntax?) -> TupleTypeElementSyntax { let layout: [RawSyntax?] = [ inOut?.raw, name?.raw, secondName?.raw, colon?.raw, type.raw, ellipsis?.raw, initializer?.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tupleTypeElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TupleTypeElementSyntax(data) } public static func makeBlankTupleTypeElement() -> TupleTypeElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tupleTypeElement, layout: [ nil, nil, nil, nil, RawSyntax.missing(SyntaxKind.type), nil, nil, nil, ], length: .zero, presence: .present)) return TupleTypeElementSyntax(data) } public static func makeTupleTypeElementList( _ elements: [TupleTypeElementSyntax]) -> TupleTypeElementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tupleTypeElementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TupleTypeElementListSyntax(data) } public static func makeBlankTupleTypeElementList() -> TupleTypeElementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tupleTypeElementList, layout: [ ], length: .zero, presence: .present)) return TupleTypeElementListSyntax(data) } public static func makeTupleType(leftParen: TokenSyntax, elements: TupleTypeElementListSyntax, rightParen: TokenSyntax) -> TupleTypeSyntax { let layout: [RawSyntax?] = [ leftParen.raw, elements.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tupleType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TupleTypeSyntax(data) } public static func makeBlankTupleType() -> TupleTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tupleType, layout: [ RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.tupleTypeElementList), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return TupleTypeSyntax(data) } public static func makeFunctionType(leftParen: TokenSyntax, arguments: TupleTypeElementListSyntax, rightParen: TokenSyntax, asyncKeyword: TokenSyntax?, throwsOrRethrowsKeyword: TokenSyntax?, arrow: TokenSyntax, returnType: TypeSyntax) -> FunctionTypeSyntax { let layout: [RawSyntax?] = [ leftParen.raw, arguments.raw, rightParen.raw, asyncKeyword?.raw, throwsOrRethrowsKeyword?.raw, arrow.raw, returnType.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.functionType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return FunctionTypeSyntax(data) } public static func makeBlankFunctionType() -> FunctionTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .functionType, layout: [ RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.tupleTypeElementList), RawSyntax.missingToken(TokenKind.rightParen), nil, nil, RawSyntax.missingToken(TokenKind.arrow), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return FunctionTypeSyntax(data) } public static func makeAttributedType(specifier: TokenSyntax?, attributes: AttributeListSyntax?, baseType: TypeSyntax) -> AttributedTypeSyntax { let layout: [RawSyntax?] = [ specifier?.raw, attributes?.raw, baseType.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.attributedType, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AttributedTypeSyntax(data) } public static func makeBlankAttributedType() -> AttributedTypeSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .attributedType, layout: [ nil, nil, RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return AttributedTypeSyntax(data) } public static func makeGenericArgumentList( _ elements: [GenericArgumentSyntax]) -> GenericArgumentListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.genericArgumentList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GenericArgumentListSyntax(data) } public static func makeBlankGenericArgumentList() -> GenericArgumentListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .genericArgumentList, layout: [ ], length: .zero, presence: .present)) return GenericArgumentListSyntax(data) } public static func makeGenericArgument(argumentType: TypeSyntax, trailingComma: TokenSyntax?) -> GenericArgumentSyntax { let layout: [RawSyntax?] = [ argumentType.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.genericArgument, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GenericArgumentSyntax(data) } public static func makeBlankGenericArgument() -> GenericArgumentSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .genericArgument, layout: [ RawSyntax.missing(SyntaxKind.type), nil, ], length: .zero, presence: .present)) return GenericArgumentSyntax(data) } public static func makeGenericArgumentClause(leftAngleBracket: TokenSyntax, arguments: GenericArgumentListSyntax, rightAngleBracket: TokenSyntax) -> GenericArgumentClauseSyntax { let layout: [RawSyntax?] = [ leftAngleBracket.raw, arguments.raw, rightAngleBracket.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.genericArgumentClause, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return GenericArgumentClauseSyntax(data) } public static func makeBlankGenericArgumentClause() -> GenericArgumentClauseSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .genericArgumentClause, layout: [ RawSyntax.missingToken(TokenKind.leftAngle), RawSyntax.missing(SyntaxKind.genericArgumentList), RawSyntax.missingToken(TokenKind.rightAngle), ], length: .zero, presence: .present)) return GenericArgumentClauseSyntax(data) } public static func makeTypeAnnotation(colon: TokenSyntax, type: TypeSyntax) -> TypeAnnotationSyntax { let layout: [RawSyntax?] = [ colon.raw, type.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.typeAnnotation, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TypeAnnotationSyntax(data) } public static func makeBlankTypeAnnotation() -> TypeAnnotationSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .typeAnnotation, layout: [ RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return TypeAnnotationSyntax(data) } public static func makeEnumCasePattern(type: TypeSyntax?, period: TokenSyntax, caseName: TokenSyntax, associatedTuple: TuplePatternSyntax?) -> EnumCasePatternSyntax { let layout: [RawSyntax?] = [ type?.raw, period.raw, caseName.raw, associatedTuple?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.enumCasePattern, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return EnumCasePatternSyntax(data) } public static func makeBlankEnumCasePattern() -> EnumCasePatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .enumCasePattern, layout: [ nil, RawSyntax.missingToken(TokenKind.period), RawSyntax.missingToken(TokenKind.identifier("")), nil, ], length: .zero, presence: .present)) return EnumCasePatternSyntax(data) } public static func makeIsTypePattern(isKeyword: TokenSyntax, type: TypeSyntax) -> IsTypePatternSyntax { let layout: [RawSyntax?] = [ isKeyword.raw, type.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.isTypePattern, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IsTypePatternSyntax(data) } public static func makeBlankIsTypePattern() -> IsTypePatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .isTypePattern, layout: [ RawSyntax.missingToken(TokenKind.isKeyword), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return IsTypePatternSyntax(data) } public static func makeOptionalPattern(subPattern: PatternSyntax, questionMark: TokenSyntax) -> OptionalPatternSyntax { let layout: [RawSyntax?] = [ subPattern.raw, questionMark.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.optionalPattern, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return OptionalPatternSyntax(data) } public static func makeBlankOptionalPattern() -> OptionalPatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .optionalPattern, layout: [ RawSyntax.missing(SyntaxKind.pattern), RawSyntax.missingToken(TokenKind.postfixQuestionMark), ], length: .zero, presence: .present)) return OptionalPatternSyntax(data) } public static func makeIdentifierPattern(identifier: TokenSyntax) -> IdentifierPatternSyntax { let layout: [RawSyntax?] = [ identifier.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.identifierPattern, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return IdentifierPatternSyntax(data) } public static func makeBlankIdentifierPattern() -> IdentifierPatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .identifierPattern, layout: [ RawSyntax.missingToken(TokenKind.selfKeyword), ], length: .zero, presence: .present)) return IdentifierPatternSyntax(data) } public static func makeAsTypePattern(pattern: PatternSyntax, asKeyword: TokenSyntax, type: TypeSyntax) -> AsTypePatternSyntax { let layout: [RawSyntax?] = [ pattern.raw, asKeyword.raw, type.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.asTypePattern, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AsTypePatternSyntax(data) } public static func makeBlankAsTypePattern() -> AsTypePatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .asTypePattern, layout: [ RawSyntax.missing(SyntaxKind.pattern), RawSyntax.missingToken(TokenKind.asKeyword), RawSyntax.missing(SyntaxKind.type), ], length: .zero, presence: .present)) return AsTypePatternSyntax(data) } public static func makeTuplePattern(leftParen: TokenSyntax, elements: TuplePatternElementListSyntax, rightParen: TokenSyntax) -> TuplePatternSyntax { let layout: [RawSyntax?] = [ leftParen.raw, elements.raw, rightParen.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tuplePattern, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TuplePatternSyntax(data) } public static func makeBlankTuplePattern() -> TuplePatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tuplePattern, layout: [ RawSyntax.missingToken(TokenKind.leftParen), RawSyntax.missing(SyntaxKind.tuplePatternElementList), RawSyntax.missingToken(TokenKind.rightParen), ], length: .zero, presence: .present)) return TuplePatternSyntax(data) } public static func makeWildcardPattern(wildcard: TokenSyntax, typeAnnotation: TypeAnnotationSyntax?) -> WildcardPatternSyntax { let layout: [RawSyntax?] = [ wildcard.raw, typeAnnotation?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.wildcardPattern, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return WildcardPatternSyntax(data) } public static func makeBlankWildcardPattern() -> WildcardPatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .wildcardPattern, layout: [ RawSyntax.missingToken(TokenKind.wildcardKeyword), nil, ], length: .zero, presence: .present)) return WildcardPatternSyntax(data) } public static func makeTuplePatternElement(labelName: TokenSyntax?, labelColon: TokenSyntax?, pattern: PatternSyntax, trailingComma: TokenSyntax?) -> TuplePatternElementSyntax { let layout: [RawSyntax?] = [ labelName?.raw, labelColon?.raw, pattern.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tuplePatternElement, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TuplePatternElementSyntax(data) } public static func makeBlankTuplePatternElement() -> TuplePatternElementSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tuplePatternElement, layout: [ nil, nil, RawSyntax.missing(SyntaxKind.pattern), nil, ], length: .zero, presence: .present)) return TuplePatternElementSyntax(data) } public static func makeExpressionPattern(expression: ExprSyntax) -> ExpressionPatternSyntax { let layout: [RawSyntax?] = [ expression.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.expressionPattern, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ExpressionPatternSyntax(data) } public static func makeBlankExpressionPattern() -> ExpressionPatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .expressionPattern, layout: [ RawSyntax.missing(SyntaxKind.expr), ], length: .zero, presence: .present)) return ExpressionPatternSyntax(data) } public static func makeTuplePatternElementList( _ elements: [TuplePatternElementSyntax]) -> TuplePatternElementListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.tuplePatternElementList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return TuplePatternElementListSyntax(data) } public static func makeBlankTuplePatternElementList() -> TuplePatternElementListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .tuplePatternElementList, layout: [ ], length: .zero, presence: .present)) return TuplePatternElementListSyntax(data) } public static func makeValueBindingPattern(letOrVarKeyword: TokenSyntax, valuePattern: PatternSyntax) -> ValueBindingPatternSyntax { let layout: [RawSyntax?] = [ letOrVarKeyword.raw, valuePattern.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.valueBindingPattern, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return ValueBindingPatternSyntax(data) } public static func makeBlankValueBindingPattern() -> ValueBindingPatternSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .valueBindingPattern, layout: [ RawSyntax.missingToken(TokenKind.letKeyword), RawSyntax.missing(SyntaxKind.pattern), ], length: .zero, presence: .present)) return ValueBindingPatternSyntax(data) } public static func makeAvailabilitySpecList( _ elements: [AvailabilityArgumentSyntax]) -> AvailabilitySpecListSyntax { let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.availabilitySpecList, layout: elements.map { $0.raw }, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AvailabilitySpecListSyntax(data) } public static func makeBlankAvailabilitySpecList() -> AvailabilitySpecListSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .availabilitySpecList, layout: [ ], length: .zero, presence: .present)) return AvailabilitySpecListSyntax(data) } public static func makeAvailabilityArgument(entry: Syntax, trailingComma: TokenSyntax?) -> AvailabilityArgumentSyntax { let layout: [RawSyntax?] = [ entry.raw, trailingComma?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.availabilityArgument, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AvailabilityArgumentSyntax(data) } public static func makeBlankAvailabilityArgument() -> AvailabilityArgumentSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .availabilityArgument, layout: [ RawSyntax.missing(SyntaxKind.unknown), nil, ], length: .zero, presence: .present)) return AvailabilityArgumentSyntax(data) } public static func makeAvailabilityLabeledArgument(label: TokenSyntax, colon: TokenSyntax, value: Syntax) -> AvailabilityLabeledArgumentSyntax { let layout: [RawSyntax?] = [ label.raw, colon.raw, value.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.availabilityLabeledArgument, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AvailabilityLabeledArgumentSyntax(data) } public static func makeBlankAvailabilityLabeledArgument() -> AvailabilityLabeledArgumentSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .availabilityLabeledArgument, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missingToken(TokenKind.colon), RawSyntax.missing(SyntaxKind.unknown), ], length: .zero, presence: .present)) return AvailabilityLabeledArgumentSyntax(data) } public static func makeAvailabilityVersionRestriction(platform: TokenSyntax, version: VersionTupleSyntax) -> AvailabilityVersionRestrictionSyntax { let layout: [RawSyntax?] = [ platform.raw, version.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.availabilityVersionRestriction, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return AvailabilityVersionRestrictionSyntax(data) } public static func makeBlankAvailabilityVersionRestriction() -> AvailabilityVersionRestrictionSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .availabilityVersionRestriction, layout: [ RawSyntax.missingToken(TokenKind.identifier("")), RawSyntax.missing(SyntaxKind.versionTuple), ], length: .zero, presence: .present)) return AvailabilityVersionRestrictionSyntax(data) } public static func makeVersionTuple(majorMinor: Syntax, patchPeriod: TokenSyntax?, patchVersion: TokenSyntax?) -> VersionTupleSyntax { let layout: [RawSyntax?] = [ majorMinor.raw, patchPeriod?.raw, patchVersion?.raw, ] let raw = RawSyntax.createAndCalcLength(kind: SyntaxKind.versionTuple, layout: layout, presence: SourcePresence.present) let data = SyntaxData.forRoot(raw) return VersionTupleSyntax(data) } public static func makeBlankVersionTuple() -> VersionTupleSyntax { let data = SyntaxData.forRoot(RawSyntax.create(kind: .versionTuple, layout: [ RawSyntax.missing(SyntaxKind.unknown), nil, nil, ], length: .zero, presence: .present)) return VersionTupleSyntax(data) } /// MARK: Token Creation APIs public static func makeAssociatedtypeKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.associatedtypeKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeClassKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.classKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeDeinitKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.deinitKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeEnumKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.enumKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeExtensionKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.extensionKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeFuncKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.funcKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeImportKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.importKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeInitKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.initKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeInoutKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.inoutKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeLetKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.letKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeOperatorKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.operatorKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePrecedencegroupKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.precedencegroupKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeProtocolKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.protocolKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeStructKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.structKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeSubscriptKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.subscriptKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeTypealiasKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.typealiasKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeVarKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.varKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeFileprivateKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.fileprivateKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeInternalKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.internalKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePrivateKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.privateKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePublicKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.publicKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeStaticKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.staticKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeDeferKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.deferKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeIfKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.ifKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeGuardKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.guardKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeDoKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.doKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeRepeatKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.repeatKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeElseKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.elseKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeForKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.forKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeInKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.inKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeWhileKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.whileKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeReturnKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.returnKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeBreakKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.breakKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeContinueKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.continueKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeFallthroughKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.fallthroughKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeSwitchKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.switchKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeCaseKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.caseKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeDefaultKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.defaultKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeWhereKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.whereKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeCatchKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.catchKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeThrowKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.throwKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeAsKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.asKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeAnyKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.anyKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeFalseKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.falseKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeIsKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.isKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeNilKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.nilKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeRethrowsKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.rethrowsKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeSuperKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.superKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeSelfKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.selfKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeCapitalSelfKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.capitalSelfKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeTrueKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.trueKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeTryKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.tryKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeThrowsKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.throwsKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeAwaitKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.awaitKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func make__FILE__Keyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.__file__Keyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func make__LINE__Keyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.__line__Keyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func make__COLUMN__Keyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.__column__Keyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func make__FUNCTION__Keyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.__function__Keyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func make__DSO_HANDLE__Keyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.__dso_handle__Keyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeWildcardKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.wildcardKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeLeftParenToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.leftParen, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeRightParenToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.rightParen, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeLeftBraceToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.leftBrace, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeRightBraceToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.rightBrace, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeLeftSquareBracketToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.leftSquareBracket, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeRightSquareBracketToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.rightSquareBracket, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeLeftAngleToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.leftAngle, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeRightAngleToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.rightAngle, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePeriodToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.period, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePrefixPeriodToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.prefixPeriod, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeCommaToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.comma, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeEllipsisToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.ellipsis, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeColonToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.colon, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeSemicolonToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.semicolon, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeEqualToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.equal, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeAtSignToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.atSign, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.pound, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePrefixAmpersandToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.prefixAmpersand, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeArrowToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.arrow, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeBacktickToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.backtick, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeBackslashToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.backslash, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeExclamationMarkToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.exclamationMark, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePostfixQuestionMarkToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.postfixQuestionMark, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeInfixQuestionMarkToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.infixQuestionMark, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeStringQuoteToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.stringQuote, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeSingleQuoteToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.singleQuote, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeMultilineStringQuoteToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.multilineStringQuote, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundKeyPathKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundKeyPathKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundLineKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundLineKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundSelectorKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundSelectorKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundFileKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundFileKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundFileIDKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundFileIDKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundFilePathKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundFilePathKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundColumnKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundColumnKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundFunctionKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundFunctionKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundDsohandleKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundDsohandleKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundAssertKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundAssertKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundSourceLocationKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundSourceLocationKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundWarningKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundWarningKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundErrorKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundErrorKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundIfKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundIfKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundElseKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundElseKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundElseifKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundElseifKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundEndifKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundEndifKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundAvailableKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundAvailableKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundFileLiteralKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundFileLiteralKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundImageLiteralKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundImageLiteralKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePoundColorLiteralKeyword(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.poundColorLiteralKeyword, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeIntegerLiteral(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.integerLiteral(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeFloatingLiteral(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.floatingLiteral(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeStringLiteral(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.stringLiteral(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeUnknown(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.unknown(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeIdentifier(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.identifier(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeUnspacedBinaryOperator(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.unspacedBinaryOperator(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeSpacedBinaryOperator(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.spacedBinaryOperator(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePostfixOperator(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.postfixOperator(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makePrefixOperator(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.prefixOperator(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeDollarIdentifier(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.dollarIdentifier(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeContextualKeyword(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.contextualKeyword(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeRawStringDelimiter(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.rawStringDelimiter(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeStringSegment(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.stringSegment(text), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeStringInterpolationAnchorToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.stringInterpolationAnchor, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeYieldToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.yield, presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } /// MARK: Convenience APIs public static func makeVoidTupleType() -> TupleTypeSyntax { return makeTupleType(leftParen: makeLeftParenToken(), elements: makeBlankTupleTypeElementList(), rightParen: makeRightParenToken()) } public static func makeTupleTypeElement(name: TokenSyntax?, colon: TokenSyntax?, type: TypeSyntax, trailingComma: TokenSyntax?) -> TupleTypeElementSyntax { return makeTupleTypeElement(inOut: nil, name: name, secondName: nil, colon: colon, type: type, ellipsis: nil, initializer: nil, trailingComma: trailingComma) } public static func makeTupleTypeElement(type: TypeSyntax, trailingComma: TokenSyntax?) -> TupleTypeElementSyntax { return makeTupleTypeElement(name: nil, colon: nil, type: type, trailingComma: trailingComma) } public static func makeGenericParameter(name: TokenSyntax, trailingComma: TokenSyntax) -> GenericParameterSyntax { return makeGenericParameter(attributes: nil, name: name, colon: nil, inheritedType: nil, trailingComma: trailingComma) } public static func makeTypeIdentifier(_ name: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TypeSyntax { let identifier = makeIdentifier(name, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) let typeIdentifier = makeSimpleTypeIdentifier(name: identifier, genericArgumentClause: nil) return TypeSyntax(typeIdentifier) } public static func makeAnyTypeIdentifier(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TypeSyntax { return makeTypeIdentifier("Any", leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeSelfTypeIdentifier(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TypeSyntax { return makeTypeIdentifier("Self", leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeTypeToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeIdentifier("Type", leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeProtocolToken(leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeIdentifier("Protocol", leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeBinaryOperator(_ name: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> TokenSyntax { return makeToken(.spacedBinaryOperator(name), presence: .present, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) } public static func makeStringLiteralExpr(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> StringLiteralExprSyntax { let string = makeStringSegment(text) let segment = makeStringSegment(content: string) let segments = makeStringLiteralSegments([Syntax(segment)]) let openQuote = makeStringQuoteToken(leadingTrivia: leadingTrivia) let closeQuote = makeStringQuoteToken(trailingTrivia: trailingTrivia) return makeStringLiteralExpr(openDelimiter: nil, openQuote: openQuote, segments: segments, closeQuote: closeQuote, closeDelimiter: nil) } public static func makeVariableExpr(_ text: String, leadingTrivia: Trivia = [], trailingTrivia: Trivia = []) -> IdentifierExprSyntax { let string = makeIdentifier(text, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) return makeIdentifierExpr(identifier: string, declNameArguments: nil) } }
41.677766
387
0.711656
287209f2727347786573f32f2ca64def79b13940
4,060
import Foundation /* Usage: - Create an instance of DownloadTask to keep track on it. - Use DownloadQueue to handle multiple DownloadTasks ``` let request = createRequest(from:, as:, timeout:, authorization:, parameters:) let downloadTask = DownloadQueue.shared.downloadTask(from: request) downloadTask.completionHandler = { ... } downloadTask.progressHandler = { ... } downloadTask.resume() ``` */ public protocol DownloadTask { var completionHandler: Networking.DownloadHandler? { get set } var progressHandler: Networking.ProcessHandler? { get set } func resume() func suspend() func cancel() } extension Networking { public typealias DownloadHandler = (Result<Data, Error>) -> () public typealias ProcessHandler = (Double) -> Void class GenericDownloadTask: DownloadTask { var completionHandler: DownloadHandler? var progressHandler: ProcessHandler? private(set) var task: URLSessionDataTask var expectedContentLength: Int64 = 0 /// A buffer that stores the downloaded data. var buffer = Data() init(_ task: URLSessionDataTask) { self.task = task } deinit { #if DEBUG debugPrint("Deiniting: \(task.originalRequest?.url?.absoluteString ?? "no url")") #endif } /// This will start or resume the download task func resume() { task.resume() } /// This will suspend the download task without terminal it func suspend() { task.suspend() } // this will cancel and terminal the download task func cancel() { task.cancel() } } } extension Networking { public final class DownloadQueue: NSObject { private var session: URLSession! private var queue: [GenericDownloadTask] = [] public static let shared = DownloadQueue() private override init() { super.init() let configuration = URLSessionConfiguration.default session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) } public func downloadTask(from request: URLRequest) -> DownloadTask { let task = self.session.dataTask(with: request) let downloadTask = GenericDownloadTask(task) queue.append(downloadTask) return downloadTask } } } extension Networking.DownloadQueue: URLSessionDataDelegate { public func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void ) { guard let task = queue.first(where: { $0.task == dataTask }) else { completionHandler(.cancel) return } task.expectedContentLength = response.expectedContentLength completionHandler(.allow) } public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { guard let task = queue.first(where: { $0.task == dataTask }) else { return } task.buffer.append(data) let percentage = Double(task.buffer.count) / Double(task.expectedContentLength) DispatchQueue.main.async { task.progressHandler?(percentage) } } public func urlSession( _ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error? ) { guard let index = queue.firstIndex(where: { $0.task == task }) else { return } let task = queue.remove(at: index) DispatchQueue.main.async { guard let error = error else { task.completionHandler?(.success(task.buffer)) return } task.completionHandler?(.failure(error)) } } }
29.208633
104
0.603448
72d405f8a739eaa88ab29862840ed6134f11e700
504
// // YelpCategory.swift // RestaurantReviews // // Created by Pasan Premaratne on 5/9/17. // Copyright © 2017 Treehouse. All rights reserved. // import Foundation struct YelpCategory { let alias: String let title: String } extension YelpCategory: JSONDecodable { init?(json: [String : Any]) { guard let aliasValue = json["alias"] as? String, let titleValue = json["title"] as? String else { return nil } self.alias = aliasValue self.title = titleValue } }
21.913043
118
0.65873
6931fa8d664d5e3538b9111d7d121d8f62a93dbd
1,271
import Sentry import XCTest class SentryTransportFactoryTests: XCTestCase { private static let dsnAsString = TestConstants.dsnAsString(username: "SentryTransportFactoryTests") func testIntegration_UrlSessionDelegate_PassedToRequestManager() { let urlSessionDelegateSpy = UrlSessionDelegateSpy() let expect = expectation(description: "UrlSession Delegate of Options called in RequestManager") urlSessionDelegateSpy.delegateCallback = { expect.fulfill() } let options = Options() options.dsn = SentryTransportFactoryTests.dsnAsString options.urlSessionDelegate = urlSessionDelegateSpy let fileManager = try! SentryFileManager(options: options, andCurrentDateProvider: TestCurrentDateProvider()) let transport = TransportInitializer.initTransport(options, sentryFileManager: fileManager) let requestManager = Dynamic(transport).requestManager.asObject as! SentryQueueableRequestManager let imgUrl = URL(string: "https://github.com")! let request = URLRequest(url: imgUrl) requestManager.add(request) { _, _ in /* We don't care about the result */ } wait(for: [expect], timeout: 10) } }
41
117
0.702596
e45388be9f6872ed4778345447638eb0361b22b4
25,839
// // BaseExpressionCompiler.swift // SnapCore // // Created by Andrew Fox on 7/28/20. // Copyright © 2020 Andrew Fox. All rights reserved. // import TurtleCore public class BaseExpressionCompiler: NSObject { public let isBoundsCheckEnabled = true public let symbols: SymbolTable public let labelMaker: LabelMaker public let temporaryStack: CompilerTemporariesStack public let temporaryAllocator: CompilerTemporariesAllocator let kFramePointerAddressHi = Int(SnapCompilerMetrics.kFramePointerAddressHi) let kFramePointerAddressLo = Int(SnapCompilerMetrics.kFramePointerAddressLo) let kStackPointerAddress: Int = Int(SnapCompilerMetrics.kStackPointerAddressHi) let kSliceBaseAddressOffset = 0 let kSliceBaseAddressSize = 2 let kSliceCountOffset = 2 let kSliceCountSize = 2 let kSliceSize = 4 // kSliceBaseAddressSize + kSliceCountSize let memoryLayoutStrategy: MemoryLayoutStrategy public init(symbols: SymbolTable, labelMaker: LabelMaker, memoryLayoutStrategy: MemoryLayoutStrategy, temporaryStack: CompilerTemporariesStack, temporaryAllocator: CompilerTemporariesAllocator) { self.symbols = symbols self.labelMaker = labelMaker self.memoryLayoutStrategy = memoryLayoutStrategy self.temporaryStack = temporaryStack self.temporaryAllocator = temporaryAllocator } public func compile(expression: Expression) throws -> [CrackleInstruction] { return [] // stub } public func rvalueContext() -> RvalueExpressionCompiler { return RvalueExpressionCompiler(symbols: symbols, labelMaker: labelMaker, memoryLayoutStrategy: memoryLayoutStrategy, temporaryStack: temporaryStack, temporaryAllocator: temporaryAllocator) } public func lvalueContext() -> LvalueExpressionCompiler { return LvalueExpressionCompiler(symbols: symbols, labelMaker: labelMaker, memoryLayoutStrategy: memoryLayoutStrategy, temporaryStack: temporaryStack, temporaryAllocator: temporaryAllocator) } public func unsupportedError(expression: Expression) -> Error { return CompilerError(sourceAnchor: expression.sourceAnchor, message: "unsupported expression: \(expression)") } public func loadStaticSymbol(_ symbol: Symbol) -> [CrackleInstruction] { return loadStaticValue(type: symbol.type, offset: symbol.offset) } public func loadStaticValue(type: SymbolType, offset: Int) -> [CrackleInstruction] { let size = memoryLayoutStrategy.sizeof(type: type) let dst = temporaryAllocator.allocate(size: size) temporaryStack.push(dst) var instructions: [CrackleInstruction] = [] instructions += [.copyWords(dst.address, offset, size)] return instructions } public func loadStackSymbol(_ symbol: Symbol, _ depth: Int) -> [CrackleInstruction] { assert(depth >= 0) return loadStackValue(type: symbol.type, offset: symbol.offset, depth: depth) } public func loadStackValue(type: SymbolType, offset: Int, depth: Int) -> [CrackleInstruction] { assert(depth >= 0) var instructions: [CrackleInstruction] = [] instructions += computeAddressOfLocalVariable(offset: offset, depth: depth) let src = temporaryStack.pop() let size = memoryLayoutStrategy.sizeof(type: type) let dst = temporaryAllocator.allocate(size: size) instructions += [.copyWordsIndirectSource(dst.address, src.address, size)] src.consume() temporaryStack.push(dst) return instructions } public func computeAddressOfLocalVariable(_ symbol: Symbol, _ depth: Int) -> [CrackleInstruction] { assert(depth >= 0) return computeAddressOfLocalVariable(offset: symbol.offset, depth: depth) } public func computeAddressOfLocalVariable(offset: Int, depth: Int) -> [CrackleInstruction] { assert(depth >= 0) var instructions: [CrackleInstruction] = [] let temp_framePointer = temporaryAllocator.allocate() instructions += [.copyWords(temp_framePointer.address, kFramePointerAddressHi, 2)] // Follow the frame pointer `depth' times. for _ in 0..<depth { instructions += [ .copyWordsIndirectSource(temp_framePointer.address, temp_framePointer.address, 2) ] } let temp_result = temporaryAllocator.allocate() if offset >= 0 { instructions += [.subi16(temp_result.address, temp_framePointer.address, offset)] } else { instructions += [.addi16(temp_result.address, temp_framePointer.address, -offset)] } temporaryStack.push(temp_result) temp_framePointer.consume() return instructions } // Compute and push the address of the specified symbol. public func computeAddressOfSymbol(_ symbol: Symbol, _ depth: Int) -> [CrackleInstruction] { assert(depth >= 0) var instructions: [CrackleInstruction] = [] switch symbol.storage { case .staticStorage: let temp = temporaryAllocator.allocate() temporaryStack.push(temp) instructions += [.storeImmediate16(temp.address, symbol.offset)] case .automaticStorage: instructions += computeAddressOfLocalVariable(symbol, depth) } return instructions } public func compile(subscript expr: Expression.Subscript) throws -> [CrackleInstruction] { var instructions: [CrackleInstruction] = [] let symbolType = try rvalueContext().typeChecker.check(expression: expr.subscriptable) switch symbolType { case .array: let argumentType = try rvalueContext().typeChecker.check(expression: expr.argument) if argumentType.isArithmeticType { instructions += try arraySubscript(expr) } else { switch argumentType { case .structType, .constStructType: instructions += try arraySlice(expr) default: abort() } } case .constDynamicArray, .dynamicArray: let argumentType = try rvalueContext().typeChecker.check(expression: expr.argument) if argumentType.isArithmeticType { instructions += try dynamicArraySubscript(expr) } else { switch argumentType { case .structType, .constStructType: instructions += try dynamicArraySlice(expr) default: abort() } } default: abort() } return instructions } private func arraySlice(_ expr: Expression.Subscript) throws -> [CrackleInstruction] { var instructions: [CrackleInstruction] = [] guard let symbolType = try lvalueContext().typeChecker.check(expression: expr.subscriptable) else { throw CompilerError(sourceAnchor: expr.subscriptable.sourceAnchor, message: "lvalue required in array slice") } let tempSlice = temporaryAllocator.allocate(size: kSliceSize) let kRangeBeginOffset = 0 let kRangeLimitOffset = memoryLayoutStrategy.sizeof(type: .u16) // Evaluate the range expression first. instructions += try compile(expression: expr.argument) let tempRangeStruct = temporaryStack.pop() let tempArrayCount = temporaryAllocator.allocate() let tempIsUnacceptable = temporaryAllocator.allocate() // Check the range begin index to make sure it's in bounds, else panic. let labelRangeBeginIsValid = labelMaker.next() instructions += [ .storeImmediate16(tempArrayCount.address, symbolType.arrayCount!), .ge16(tempIsUnacceptable.address, tempRangeStruct.address + kRangeBeginOffset, tempArrayCount.address), .jz(labelRangeBeginIsValid, tempIsUnacceptable.address) ] if isBoundsCheckEnabled { instructions += try panicOutOfBoundsError(sourceAnchor: expr.sourceAnchor) } instructions += [ .label(labelRangeBeginIsValid) ] // Check the range limit index to make sure it's in bounds, else panic. let labelRangeLimitIsValid = labelMaker.next() instructions += [ .gt16(tempIsUnacceptable.address, tempRangeStruct.address + kRangeLimitOffset, tempArrayCount.address), .jz(labelRangeLimitIsValid, tempIsUnacceptable.address) ] if isBoundsCheckEnabled { instructions += try panicOutOfBoundsError(sourceAnchor: expr.sourceAnchor) } instructions += [ .label(labelRangeLimitIsValid) ] tempIsUnacceptable.consume() tempArrayCount.consume() // Compute the array slice count from the range value. instructions += [ .sub16(tempSlice.address + kSliceCountOffset, tempRangeStruct.address + kRangeLimitOffset, tempRangeStruct.address + kRangeBeginOffset) ] // Compute the base address of the array slice. This is an offset from // the original array's base address. instructions += try lvalueContext().compile(expression: expr.subscriptable) let tempArrayBaseAddress = temporaryStack.pop() let arrayElementSize = memoryLayoutStrategy.sizeof(type: symbolType.arrayElementType) instructions += [ .muli16(tempSlice.address + kSliceBaseAddressOffset, tempRangeStruct.address + kRangeBeginOffset, arrayElementSize), .add16(tempSlice.address + kSliceBaseAddressOffset, tempSlice.address + kSliceBaseAddressOffset, tempArrayBaseAddress.address) ] tempArrayBaseAddress.consume() tempRangeStruct.consume() // Leave the slice value on the stack on leaving this function. temporaryStack.push(tempSlice) return instructions } // Compile an array element lookup through the subscript operator. public func arraySubscript(_ expr: Expression.Subscript) throws -> [CrackleInstruction] { abort() // override in a subclass } // Compile an array element lookup in a dynamic array through the subscript operator. public func dynamicArraySubscript(_ expr: Expression.Subscript) throws -> [CrackleInstruction] { abort() // override in a subclass } private func dynamicArraySlice(_ expr: Expression.Subscript) throws -> [CrackleInstruction] { var instructions: [CrackleInstruction] = [] guard let symbolType = try lvalueContext().typeChecker.check(expression: expr.subscriptable) else { throw CompilerError(sourceAnchor: expr.subscriptable.sourceAnchor, message: "lvalue required in array slice") } // Get the address of the dynamic array symbol. instructions += try lvalueContext().compile(expression: expr.subscriptable) let tempDynamicArrayAddress = temporaryStack.pop() // Evaluate the range expression to get the range value. let kRangeBeginOffset = 0 let kRangeLimitOffset = memoryLayoutStrategy.sizeof(type: .u16) instructions += try compile(expression: expr.argument) let tempRangeStruct = temporaryStack.pop() // Extract the array count from the dynamic array structure. let tempArrayCount = temporaryAllocator.allocate() instructions += [ .copyWords(tempArrayCount.address, tempDynamicArrayAddress.address, kSliceSize), .addi16(tempArrayCount.address, tempArrayCount.address, kSliceCountOffset), .copyWordsIndirectSource(tempArrayCount.address, tempArrayCount.address, kSliceSize) ] // Check the range begin index to make sure it's in bounds, else panic. let tempIsUnacceptable = temporaryAllocator.allocate() let labelRangeBeginIsValid = labelMaker.next() instructions += [ .ge16(tempIsUnacceptable.address, tempRangeStruct.address + kRangeBeginOffset, tempArrayCount.address), .jz(labelRangeBeginIsValid, tempIsUnacceptable.address) ] if isBoundsCheckEnabled { instructions += try panicOutOfBoundsError(sourceAnchor: expr.sourceAnchor) } instructions += [ .label(labelRangeBeginIsValid) ] // Check the range limit index to make sure it's in bounds, else panic. let labelRangeLimitIsValid = labelMaker.next() instructions += [ .gt16(tempIsUnacceptable.address, tempRangeStruct.address + kRangeLimitOffset, tempArrayCount.address), .jz(labelRangeLimitIsValid, tempIsUnacceptable.address) ] if isBoundsCheckEnabled { instructions += try panicOutOfBoundsError(sourceAnchor: expr.sourceAnchor) } instructions += [ .label(labelRangeLimitIsValid) ] tempIsUnacceptable.consume() tempArrayCount.consume() let tempSlice = temporaryAllocator.allocate(size: kSliceSize) // Compute the array slice count from the range value. instructions += [ .sub16(tempSlice.address + kSliceCountOffset, tempRangeStruct.address + kRangeLimitOffset, tempRangeStruct.address + kRangeBeginOffset) ] // Compute the base address of the array slice. let tempArrayBaseAddress = temporaryAllocator.allocate() let arrayElementSize = memoryLayoutStrategy.sizeof(type: symbolType.arrayElementType) instructions += [ .copyWordsIndirectSource(tempArrayBaseAddress.address, tempDynamicArrayAddress.address, memoryLayoutStrategy.sizeof(type: .u16)), .muli16(tempSlice.address + kSliceBaseAddressOffset, tempRangeStruct.address + kRangeBeginOffset, arrayElementSize), .add16(tempSlice.address + kSliceBaseAddressOffset, tempSlice.address + kSliceBaseAddressOffset, tempArrayBaseAddress.address) ] tempArrayBaseAddress.consume() tempRangeStruct.consume() tempDynamicArrayAddress.consume() // Leave the slice value on the stack on leaving this function. temporaryStack.push(tempSlice) return instructions } public func arraySubscriptLvalue(_ expr: Expression.Subscript) throws -> [CrackleInstruction] { var instructions: [CrackleInstruction] = [] let context = lvalueContext() guard let symbolType = try context.typeChecker.check(expression: expr.subscriptable) else { throw CompilerError(sourceAnchor: expr.subscriptable.sourceAnchor, message: "lvalue required in array subscript") } let elementType = symbolType.arrayElementType instructions += try context.compile(expression: expr.subscriptable) instructions += try computeAddressOfArrayElement(expr, elementType) instructions += try arrayBoundsCheck(expr) return instructions } // Assuming the top of the stack holds an address, verify that the address // is within the specified fixed array. If so then leave the address on the // stack as it was before this check. Else, panic with an appropriate // error message. private func arrayBoundsCheck(_ expr: Expression.Subscript) throws -> [CrackleInstruction] { let label = labelMaker.next() var instructions: [CrackleInstruction] = [] let context = lvalueContext() guard let symbolType = try context.typeChecker.check(expression: expr.subscriptable) else { throw CompilerError(sourceAnchor: expr.subscriptable.sourceAnchor, message: "lvalue required in array subscript") } let tempAccessAddress = temporaryStack.peek() instructions += try context.compile(expression: expr.subscriptable) let tempBaseAddress = temporaryStack.pop() let tempArrayCount = temporaryAllocator.allocate() instructions += [.storeImmediate16(tempArrayCount.address, symbolType.arrayCount!)] let tempArraySize = temporaryAllocator.allocate() let arrayElementSize = memoryLayoutStrategy.sizeof(type: symbolType.arrayElementType) instructions += [.muli16(tempArraySize.address, tempArrayCount.address, arrayElementSize)] tempArrayCount.consume() let tempArrayLimit = temporaryAllocator.allocate() instructions += [.add16(tempArrayLimit.address, tempBaseAddress.address, tempArraySize.address)] tempBaseAddress.consume() tempArraySize.consume() // Subtract one so we can avoid a limit which might wrap around the // bottom of the stack from 0xffff to 0x0000. instructions += [.subi16(tempArrayLimit.address, tempArrayLimit.address, 1)] // If (limit-1) < (access address) then the access is unacceptable. let tempIsUnacceptable = temporaryAllocator.allocate() instructions += [.lt16(tempIsUnacceptable.address, tempArrayLimit.address, tempAccessAddress.address)] // Specifically do not conusme tempAccessAddress as we need to leave // that in place on the stack when we're done. tempArrayLimit.consume() // If the access is not unacceptable (that is, the access is acceptable) // then take the branch to skip the panic. instructions += [.jz(label, tempIsUnacceptable.address)] tempIsUnacceptable.consume() if isBoundsCheckEnabled { instructions += try panicOutOfBoundsError(sourceAnchor: expr.sourceAnchor) } instructions += [.label(label)] return instructions } private func panicOutOfBoundsError(sourceAnchor: SourceAnchor?) throws -> [CrackleInstruction] { let panic = Expression.Call(sourceAnchor: sourceAnchor, callee: Expression.Identifier("__oob"), arguments: []) let instructions = try rvalueContext().compile(expression: panic) return instructions } public func dynamicArraySubscriptLvalue(_ expr: Expression.Subscript) throws -> [CrackleInstruction] { var instructions: [CrackleInstruction] = [] let context = lvalueContext() guard let symbolType = try context.typeChecker.check(expression: expr.subscriptable) else { throw CompilerError(sourceAnchor: expr.subscriptable.sourceAnchor, message: "lvalue required in dynamic array subscript") } let elementType = symbolType.arrayElementType instructions += try context.compile(expression: expr.subscriptable) let sliceAddress = temporaryStack.pop() // Extract the array base address from the slice structure. let baseAddress = temporaryAllocator.allocate() temporaryStack.push(baseAddress) instructions += [.copyWordsIndirectSource(baseAddress.address, sliceAddress.address, 2)] sliceAddress.consume() instructions += try computeAddressOfArrayElement(expr, elementType) instructions += try dynamicArrayBoundsCheck(expr) return instructions } // Assuming the top of the stack holds an address, verify that the address // is within the specified dynamic array. If so then leave the address on // the stack as it was before this check. Else, panic with an appropriate // error message. private func dynamicArrayBoundsCheck(_ expr: Expression.Subscript) throws -> [CrackleInstruction] { let label = labelMaker.next() var instructions: [CrackleInstruction] = [] let context = lvalueContext() guard let symbolType = try context.typeChecker.check(expression: expr.subscriptable) else { throw CompilerError(sourceAnchor: expr.subscriptable.sourceAnchor, message: "lvalue required in dynamic array subscript") } let tempAccessAddress = temporaryStack.peek() instructions += try lvalueContext().compile(expression: expr.subscriptable) let tempSliceAddress = temporaryStack.pop() // Extract the array base address from the slice structure. let tempBaseAddress = temporaryAllocator.allocate() instructions += [.copyWordsIndirectSource(tempBaseAddress.address, tempSliceAddress.address, 2)] // Extract the count from the slice structure too. let tempTwo = temporaryAllocator.allocate() instructions += [.storeImmediate16(tempTwo.address, 2)] let tempArrayCountAddress = temporaryAllocator.allocate() instructions += [.add16(tempArrayCountAddress.address, tempSliceAddress.address, tempTwo.address)] tempTwo.consume() let tempArrayCount = temporaryAllocator.allocate() instructions += [.copyWordsIndirectSource(tempArrayCount.address, tempArrayCountAddress.address, 2)] tempArrayCountAddress.consume() let tempArrayElementSize = temporaryAllocator.allocate() let arrayElementSize = memoryLayoutStrategy.sizeof(type: symbolType.arrayElementType) instructions += [.storeImmediate16(tempArrayElementSize.address, arrayElementSize)] let tempArraySize = temporaryAllocator.allocate() instructions += [.mul16(tempArraySize.address, tempArrayCount.address, tempArrayElementSize.address)] tempArrayElementSize.consume() tempArrayCount.consume() let tempArrayLimit = temporaryAllocator.allocate() instructions += [.add16(tempArrayLimit.address, tempBaseAddress.address, tempArraySize.address)] tempArraySize.consume() tempBaseAddress.consume() // Subtract one so we can avoid a limit which might wrap around the // bottom of the stack from 0xffff to 0x0000. instructions += [.subi16(tempArrayLimit.address, tempArrayLimit.address, 1)] // If (limit-1) < (access address) then the access is unacceptable. let tempIsUnacceptable = temporaryAllocator.allocate() instructions += [.lt16(tempIsUnacceptable.address, tempArrayLimit.address, tempAccessAddress.address)] tempArrayLimit.consume() // If the access is not unacceptable (that is, the access is acceptable) // then take the branch to skip the panic. instructions += [.jz(label, tempIsUnacceptable.address)] tempIsUnacceptable.consume() if isBoundsCheckEnabled { instructions += try panicOutOfBoundsError(sourceAnchor: expr.sourceAnchor) } instructions += [.label(label)] // Specifically do not consume tempAccessAddress as we need to leave // that in place on the stack when we're done. return instructions } // Given an array address on the compiler temporaries stack, determine the // address of the array element at an index determined by the expression, // and push to the stack. public func computeAddressOfArrayElement(_ expr: Expression.Subscript, _ elementType: SymbolType) throws -> [CrackleInstruction] { var instructions: [CrackleInstruction] = [] // Assume that the temporary which holds the array base address is on // top of the compiler temporaries stack. let baseAddress = temporaryStack.pop() // Compute the array subscript index. // This must be converted to u16 so we can do math with the address. instructions += try rvalueContext().compileAndConvertExpressionForExplicitCast(rexpr: expr.argument, ltype: .u16) let subscriptIndex = temporaryStack.pop() let elementSize = temporaryAllocator.allocate() let sizeOfElementType = memoryLayoutStrategy.sizeof(type: elementType) instructions += [.storeImmediate16(elementSize.address, sizeOfElementType)] let accessOffset = temporaryAllocator.allocate() instructions += [.mul16(accessOffset.address, subscriptIndex.address, elementSize.address)] elementSize.consume() subscriptIndex.consume() let accessAddress = temporaryAllocator.allocate() instructions += [.add16(accessAddress.address, baseAddress.address, accessOffset.address)] accessOffset.consume() baseAddress.consume() temporaryStack.push(accessAddress) // At this point, the temporary which holds the address of the array // access is on top of the compiler temporaries stack. return instructions } }
45.173077
134
0.650064
7533a69d28b5faf06b611df4f365f9c8739b9ded
10,114
// // ViewController.swift // GPSLogger // // Created by koogawa on 2018/12/02. // Copyright (c) 2018 Kosuke Ogawa. All rights reserved. // import UIKit import MapKit import FirebaseFirestore struct Location { let latitude: Double let longitude: Double let createdAt: Date init(latitude: Double, longitude: Double, createdAt: Date = Date()) { self.latitude = latitude self.longitude = longitude self.createdAt = createdAt } init(document: [String: Any]) { latitude = document["latitude"] as? Double ?? 0 longitude = document["longitude"] as? Double ?? 0 createdAt = document["createdAt"] as? Date ?? Date() } } class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var tableView: UITableView! let kLocationsCollectionName = "locations" var locationManager: CLLocationManager! var listener: ListenerRegistration! var isUpdating = false var locations: [Location] = [] { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.locationManager = CLLocationManager() self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.distanceFilter = 100 // Delete old location objects self.deleteOldLocations() // Load stored location objects self.loadStoredLocations() // Drop pins for location in self.locations { self.dropPin(at: location) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Private methods @IBAction func startButtonDidTap(_ sender: AnyObject) { self.toggleLocationUpdate() } @IBAction func clearButtonDidTap(_ sender: AnyObject) { self.deleteAllLocations() self.removeAllAnnotations() } // Load stored locations on firebase fileprivate func loadStoredLocations() { let db = Firestore.firestore() db.collection(kLocationsCollectionName) .order(by: "createdAt", descending: false) .getDocuments { [weak self] snapshot, error in if let error = error { print("Error getting documents: \(error)") } else { self?.locations = snapshot?.documents.map { Location(document: $0.data()) } ?? [] } } } // Start or Stop location update fileprivate func toggleLocationUpdate() { if self.isUpdating { // Stop self.isUpdating = false self.locationManager.stopUpdatingLocation() self.startButton.setTitle("Start", for: UIControl.State()) // Remove Realtime Update self.listener.remove() } else { // Start self.isUpdating = true self.locationManager.startUpdatingLocation() self.startButton.setTitle("Stop", for: UIControl.State()) // Cloud Firestore Realtime Update let db = Firestore.firestore() self.listener = db.collection(kLocationsCollectionName) .addSnapshotListener(includeMetadataChanges: true) { [weak self] documentSnapshot, error in guard let document = documentSnapshot else { print("Error fetching document: \(error!)") return } print("Current data: \(document.description)") self?.loadStoredLocations() } } } // Add a new document in collection "locations" fileprivate func add(location: CLLocation) { let db = Firestore.firestore() var ref: DocumentReference? = nil ref = db.collection(kLocationsCollectionName).addDocument(data: [ "latitude": location.coordinate.latitude, "longitude": location.coordinate.longitude, "createdAt": FieldValue.serverTimestamp() ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") } } } // Delete specific document from collection fileprivate func delete(documentID: String) { let db = Firestore.firestore() db.collection(self.kLocationsCollectionName) .document(documentID) .delete() { err in if let err = err { print("Error removing document: \(err)") } else { print("Document successfully removed!") } } } // Delete old (-1 day) objects fileprivate func deleteOldLocations() { let db = Firestore.firestore() db.collection(kLocationsCollectionName) .whereField("createdAt", isLessThanOrEqualTo: Date().addingTimeInterval(-86400)) .getDocuments { snapshot, error in if let error = error { print("Error getting documents: \(error)") return } for document in snapshot?.documents ?? [] { print("Deleting document", document) self.delete(documentID: document.documentID) } } } // Delete all location objects from realm fileprivate func deleteAllLocations() { let db = Firestore.firestore() db.collection(kLocationsCollectionName) .getDocuments { snapshot, error in if let error = error { print("Error getting documents: \(error)") return } for document in snapshot?.documents ?? [] { print("Deleting document", document) self.delete(documentID: document.documentID) } } } // Drop pin on the map fileprivate func dropPin(at location: Location) { let annotation = MKPointAnnotation() annotation.coordinate = CLLocationCoordinate2DMake(location.latitude, location.longitude) annotation.title = "\(location.latitude),\(location.longitude)" annotation.subtitle = location.createdAt.description self.mapView.addAnnotation(annotation) } // Remove all pins on the map fileprivate func removeAllAnnotations() { let annotations = self.mapView.annotations.filter { $0 !== self.mapView.userLocation } self.mapView.removeAnnotations(annotations) } } // MARK: - CLLocationManager delegate extension ViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.notDetermined { locationManager.requestAlwaysAuthorization() } else if status == CLAuthorizationStatus.authorizedAlways || status == CLAuthorizationStatus.authorizedWhenInUse { // Center user location on the map let span = MKCoordinateSpan.init(latitudeDelta: 0.003, longitudeDelta: 0.003) let region = MKCoordinateRegion.init(center: self.mapView.userLocation.coordinate, span: span) self.mapView.setRegion(region, animated:true) self.mapView.userTrackingMode = MKUserTrackingMode.followWithHeading } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]) { guard let newLocation = locations.last else { return } if !CLLocationCoordinate2DIsValid(newLocation.coordinate) { return } self.add(location: newLocation) let location = Location(latitude: newLocation.coordinate.latitude, longitude: newLocation.coordinate.longitude) self.dropPin(at: location) } } // MARK: - MKMapView delegate extension ViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation { return nil } let reuseId = "annotationIdentifier" var pinView = self.mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView?.canShowCallout = true pinView?.animatesDrop = true } else { pinView?.annotation = annotation } return pinView } } // MARK: - Table view data source extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { // Return the number of sections. return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return self.locations.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath) let location = self.locations[indexPath.row] cell.textLabel?.text = "\(location.latitude),\(location.longitude)" cell.detailTextLabel?.text = location.createdAt.description return cell } } // MARK: - Table view delegate extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
33.713333
121
0.614495
f72871de2c724fbd1c27cde117dbeeb2ef207cc4
38,659
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension CloudControlApi { // MARK: Enums public enum HandlerErrorCode: String, CustomStringConvertible, Codable { case accessdenied = "AccessDenied" case alreadyexists = "AlreadyExists" case generalserviceexception = "GeneralServiceException" case internalfailure = "InternalFailure" case invalidcredentials = "InvalidCredentials" case invalidrequest = "InvalidRequest" case networkfailure = "NetworkFailure" case notfound = "NotFound" case notstabilized = "NotStabilized" case notupdatable = "NotUpdatable" case resourceconflict = "ResourceConflict" case serviceinternalerror = "ServiceInternalError" case servicelimitexceeded = "ServiceLimitExceeded" case servicetimeout = "ServiceTimeout" case throttling = "Throttling" public var description: String { return self.rawValue } } public enum Operation: String, CustomStringConvertible, Codable { case create = "CREATE" case delete = "DELETE" case update = "UPDATE" public var description: String { return self.rawValue } } public enum OperationStatus: String, CustomStringConvertible, Codable { case cancelComplete = "CANCEL_COMPLETE" case cancelInProgress = "CANCEL_IN_PROGRESS" case failed = "FAILED" case inProgress = "IN_PROGRESS" case pending = "PENDING" case success = "SUCCESS" public var description: String { return self.rawValue } } // MARK: Shapes public struct CancelResourceRequestInput: AWSEncodableShape { /// The RequestToken of the ProgressEvent object returned by the resource operation request. public let requestToken: String public init(requestToken: String) { self.requestToken = requestToken } public func validate(name: String) throws { try self.validate(self.requestToken, name: "requestToken", parent: name, max: 128) try self.validate(self.requestToken, name: "requestToken", parent: name, min: 1) try self.validate(self.requestToken, name: "requestToken", parent: name, pattern: "[-A-Za-z0-9+/=]+") } private enum CodingKeys: String, CodingKey { case requestToken = "RequestToken" } } public struct CancelResourceRequestOutput: AWSDecodableShape { public let progressEvent: ProgressEvent? public init(progressEvent: ProgressEvent? = nil) { self.progressEvent = progressEvent } private enum CodingKeys: String, CodingKey { case progressEvent = "ProgressEvent" } } public struct CreateResourceInput: AWSEncodableShape { /// A unique identifier to ensure the idempotency of the resource request. As a best practice, specify this token to ensure idempotency, so that Amazon Web Services Cloud Control API can accurately distinguish between request retries and new resource requests. You might retry a resource request to ensure that it was successfully received. A client token is valid for 36 hours once used. After that, a resource request with the same client token is treated as a new request. If you do not specify a client token, one is generated for inclusion in the request. For more information, see Ensuring resource operation requests are unique in the Amazon Web Services Cloud Control API User Guide. public let clientToken: String? /// Structured data format representing the desired state of the resource, consisting of that resource's properties and their desired values. Cloud Control API currently supports JSON as a structured data format. Specify the desired state as one of the following: A JSON blob A local path containing the desired state in JSON data format For more information, see Composing the desired state of the resource in the Amazon Web Services Cloud Control API User Guide. For more information about the properties of a specific resource, refer to the related topic for the resource in the Resource and property types reference in the Amazon Web Services CloudFormation Users Guide. public let desiredState: String /// The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. public let roleArn: String? /// The name of the resource type. public let typeName: String /// For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. public let typeVersionId: String? public init(clientToken: String? = CreateResourceInput.idempotencyToken(), desiredState: String, roleArn: String? = nil, typeName: String, typeVersionId: String? = nil) { self.clientToken = clientToken self.desiredState = desiredState self.roleArn = roleArn self.typeName = typeName self.typeVersionId = typeVersionId } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 128) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "[-A-Za-z0-9+/=]+") try self.validate(self.desiredState, name: "desiredState", parent: name, max: 16384) try self.validate(self.desiredState, name: "desiredState", parent: name, min: 1) try self.validate(self.desiredState, name: "desiredState", parent: name, pattern: "(.|\\s)*") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:.+:iam::[0-9]{12}:role/.+") try self.validate(self.typeName, name: "typeName", parent: name, max: 196) try self.validate(self.typeName, name: "typeName", parent: name, min: 10) try self.validate(self.typeName, name: "typeName", parent: name, pattern: "[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}") try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, max: 128) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, min: 1) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, pattern: "[A-Za-z0-9-]+") } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case desiredState = "DesiredState" case roleArn = "RoleArn" case typeName = "TypeName" case typeVersionId = "TypeVersionId" } } public struct CreateResourceOutput: AWSDecodableShape { /// Represents the current status of the resource creation request. After you have initiated a resource creation request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent returned by CreateResource. public let progressEvent: ProgressEvent? public init(progressEvent: ProgressEvent? = nil) { self.progressEvent = progressEvent } private enum CodingKeys: String, CodingKey { case progressEvent = "ProgressEvent" } } public struct DeleteResourceInput: AWSEncodableShape { /// A unique identifier to ensure the idempotency of the resource request. As a best practice, specify this token to ensure idempotency, so that Amazon Web Services Cloud Control API can accurately distinguish between request retries and new resource requests. You might retry a resource request to ensure that it was successfully received. A client token is valid for 36 hours once used. After that, a resource request with the same client token is treated as a new request. If you do not specify a client token, one is generated for inclusion in the request. For more information, see Ensuring resource operation requests are unique in the Amazon Web Services Cloud Control API User Guide. public let clientToken: String? /// The identifier for the resource. You can specify the primary identifier, or any secondary identifier defined for the resource type in its resource schema. You can only specify one identifier. Primary identifiers can be specified as a string or JSON; secondary identifiers must be specified as JSON. For compound primary identifiers (that is, one that consists of multiple resource properties strung together), to specify the primary identifier as a string, list the property values in the order they are specified in the primary identifier definition, separated by |. For more information, see Identifying resources in the Amazon Web Services Cloud Control API User Guide. public let identifier: String /// The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. public let roleArn: String? /// The name of the resource type. public let typeName: String /// For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. public let typeVersionId: String? public init(clientToken: String? = DeleteResourceInput.idempotencyToken(), identifier: String, roleArn: String? = nil, typeName: String, typeVersionId: String? = nil) { self.clientToken = clientToken self.identifier = identifier self.roleArn = roleArn self.typeName = typeName self.typeVersionId = typeVersionId } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 128) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "[-A-Za-z0-9+/=]+") try self.validate(self.identifier, name: "identifier", parent: name, max: 1024) try self.validate(self.identifier, name: "identifier", parent: name, min: 1) try self.validate(self.identifier, name: "identifier", parent: name, pattern: ".+") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:.+:iam::[0-9]{12}:role/.+") try self.validate(self.typeName, name: "typeName", parent: name, max: 196) try self.validate(self.typeName, name: "typeName", parent: name, min: 10) try self.validate(self.typeName, name: "typeName", parent: name, pattern: "[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}") try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, max: 128) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, min: 1) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, pattern: "[A-Za-z0-9-]+") } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case identifier = "Identifier" case roleArn = "RoleArn" case typeName = "TypeName" case typeVersionId = "TypeVersionId" } } public struct DeleteResourceOutput: AWSDecodableShape { /// Represents the current status of the resource deletion request. After you have initiated a resource deletion request, you can monitor the progress of your request by calling GetResourceRequestStatus using the RequestToken of the ProgressEvent returned by DeleteResource. public let progressEvent: ProgressEvent? public init(progressEvent: ProgressEvent? = nil) { self.progressEvent = progressEvent } private enum CodingKeys: String, CodingKey { case progressEvent = "ProgressEvent" } } public struct GetResourceInput: AWSEncodableShape { /// The identifier for the resource. You can specify the primary identifier, or any secondary identifier defined for the resource type in its resource schema. You can only specify one identifier. Primary identifiers can be specified as a string or JSON; secondary identifiers must be specified as JSON. For compound primary identifiers (that is, one that consists of multiple resource properties strung together), to specify the primary identifier as a string, list the property values in the order they are specified in the primary identifier definition, separated by |. For more information, see Identifying resources in the Amazon Web Services Cloud Control API User Guide. public let identifier: String /// The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. public let roleArn: String? /// The name of the resource type. public let typeName: String /// For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. public let typeVersionId: String? public init(identifier: String, roleArn: String? = nil, typeName: String, typeVersionId: String? = nil) { self.identifier = identifier self.roleArn = roleArn self.typeName = typeName self.typeVersionId = typeVersionId } public func validate(name: String) throws { try self.validate(self.identifier, name: "identifier", parent: name, max: 1024) try self.validate(self.identifier, name: "identifier", parent: name, min: 1) try self.validate(self.identifier, name: "identifier", parent: name, pattern: ".+") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:.+:iam::[0-9]{12}:role/.+") try self.validate(self.typeName, name: "typeName", parent: name, max: 196) try self.validate(self.typeName, name: "typeName", parent: name, min: 10) try self.validate(self.typeName, name: "typeName", parent: name, pattern: "[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}") try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, max: 128) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, min: 1) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, pattern: "[A-Za-z0-9-]+") } private enum CodingKeys: String, CodingKey { case identifier = "Identifier" case roleArn = "RoleArn" case typeName = "TypeName" case typeVersionId = "TypeVersionId" } } public struct GetResourceOutput: AWSDecodableShape { public let resourceDescription: ResourceDescription? /// The name of the resource type. public let typeName: String? public init(resourceDescription: ResourceDescription? = nil, typeName: String? = nil) { self.resourceDescription = resourceDescription self.typeName = typeName } private enum CodingKeys: String, CodingKey { case resourceDescription = "ResourceDescription" case typeName = "TypeName" } } public struct GetResourceRequestStatusInput: AWSEncodableShape { /// A unique token used to track the progress of the resource operation request. Request tokens are included in the ProgressEvent type returned by a resource operation request. public let requestToken: String public init(requestToken: String) { self.requestToken = requestToken } public func validate(name: String) throws { try self.validate(self.requestToken, name: "requestToken", parent: name, max: 128) try self.validate(self.requestToken, name: "requestToken", parent: name, min: 1) try self.validate(self.requestToken, name: "requestToken", parent: name, pattern: "[-A-Za-z0-9+/=]+") } private enum CodingKeys: String, CodingKey { case requestToken = "RequestToken" } } public struct GetResourceRequestStatusOutput: AWSDecodableShape { /// Represents the current status of the resource operation request. public let progressEvent: ProgressEvent? public init(progressEvent: ProgressEvent? = nil) { self.progressEvent = progressEvent } private enum CodingKeys: String, CodingKey { case progressEvent = "ProgressEvent" } } public struct ListResourceRequestsInput: AWSEncodableShape { /// The maximum number of results to be returned with a single call. If the number of available results exceeds this maximum, the response includes a NextToken value that you can assign to the NextToken request parameter to get the next set of results. The default is 20. public let maxResults: Int? /// If the previous paginated request didn't return all of the remaining results, the response object's NextToken parameter value is set to a token. To retrieve the next set of results, call this action again and assign that token to the request object's NextToken parameter. If there are no remaining results, the previous response object's NextToken parameter is set to null. public let nextToken: String? /// The filter criteria to apply to the requests returned. public let resourceRequestStatusFilter: ResourceRequestStatusFilter? public init(maxResults: Int? = nil, nextToken: String? = nil, resourceRequestStatusFilter: ResourceRequestStatusFilter? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.resourceRequestStatusFilter = resourceRequestStatusFilter } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[-A-Za-z0-9+/=]+") } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" case resourceRequestStatusFilter = "ResourceRequestStatusFilter" } } public struct ListResourceRequestsOutput: AWSDecodableShape { /// If the request doesn't return all of the remaining results, NextToken is set to a token. To retrieve the next set of results, call ListResources again and assign that token to the request object's NextToken parameter. If the request returns all results, NextToken is set to null. public let nextToken: String? /// The requests that match the specified filter criteria. public let resourceRequestStatusSummaries: [ProgressEvent]? public init(nextToken: String? = nil, resourceRequestStatusSummaries: [ProgressEvent]? = nil) { self.nextToken = nextToken self.resourceRequestStatusSummaries = resourceRequestStatusSummaries } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case resourceRequestStatusSummaries = "ResourceRequestStatusSummaries" } } public struct ListResourcesInput: AWSEncodableShape { /// The maximum number of results to be returned with a single call. If the number of available results exceeds this maximum, the response includes a NextToken value that you can assign to the NextToken request parameter to get the next set of results. The default is 20. public let maxResults: Int? /// If the previous paginated request didn't return all of the remaining results, the response object's NextToken parameter value is set to a token. To retrieve the next set of results, call this action again and assign that token to the request object's NextToken parameter. If there are no remaining results, the previous response object's NextToken parameter is set to null. public let nextToken: String? /// The resource model to use to select the resources to return. public let resourceModel: String? /// The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. public let roleArn: String? /// The name of the resource type. public let typeName: String /// For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. public let typeVersionId: String? public init(maxResults: Int? = nil, nextToken: String? = nil, resourceModel: String? = nil, roleArn: String? = nil, typeName: String, typeVersionId: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.resourceModel = resourceModel self.roleArn = roleArn self.typeName = typeName self.typeVersionId = typeVersionId } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: ".+") try self.validate(self.resourceModel, name: "resourceModel", parent: name, max: 16384) try self.validate(self.resourceModel, name: "resourceModel", parent: name, min: 1) try self.validate(self.resourceModel, name: "resourceModel", parent: name, pattern: "(.|\\s)*") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:.+:iam::[0-9]{12}:role/.+") try self.validate(self.typeName, name: "typeName", parent: name, max: 196) try self.validate(self.typeName, name: "typeName", parent: name, min: 10) try self.validate(self.typeName, name: "typeName", parent: name, pattern: "[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}") try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, max: 128) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, min: 1) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, pattern: "[A-Za-z0-9-]+") } private enum CodingKeys: String, CodingKey { case maxResults = "MaxResults" case nextToken = "NextToken" case resourceModel = "ResourceModel" case roleArn = "RoleArn" case typeName = "TypeName" case typeVersionId = "TypeVersionId" } } public struct ListResourcesOutput: AWSDecodableShape { /// If the request doesn't return all of the remaining results, NextToken is set to a token. To retrieve the next set of results, call ListResources again and assign that token to the request object's NextToken parameter. If the request returns all results, NextToken is set to null. public let nextToken: String? /// Information about the specified resources, including primary identifier and resource model. public let resourceDescriptions: [ResourceDescription]? /// The name of the resource type. public let typeName: String? public init(nextToken: String? = nil, resourceDescriptions: [ResourceDescription]? = nil, typeName: String? = nil) { self.nextToken = nextToken self.resourceDescriptions = resourceDescriptions self.typeName = typeName } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case resourceDescriptions = "ResourceDescriptions" case typeName = "TypeName" } } public struct ProgressEvent: AWSDecodableShape { /// For requests with a status of FAILED, the associated error code. For error code definitions, see Handler error codes in the CloudFormation Command Line Interface User Guide for Extension Development. public let errorCode: HandlerErrorCode? /// When the resource operation request was initiated. public let eventTime: Date? /// The primary identifier for the resource. In some cases, the resource identifier may be available before the resource operation has reached a status of SUCCESS. public let identifier: String? /// The resource operation type. public let operation: Operation? /// The current status of the resource operation request. PENDING: The resource operation has not yet started. IN_PROGRESS: The resource operation is currently in progress. SUCCESS: The resource operation has successfully completed. FAILED: The resource operation has failed. Refer to the error code and status message for more information. CANCEL_IN_PROGRESS: The resource operation is in the process of being canceled. CANCEL_COMPLETE: The resource operation has been canceled. public let operationStatus: OperationStatus? /// The unique token representing this resource operation request. Use the RequestToken with GetResourceRequestStatus to return the current status of a resource operation request. public let requestToken: String? /// A JSON string containing the resource model, consisting of each resource property and its current value. public let resourceModel: String? /// When to next request the status of this resource operation request. public let retryAfter: Date? /// Any message explaining the current status. public let statusMessage: String? /// The name of the resource type used in the operation. public let typeName: String? public init(errorCode: HandlerErrorCode? = nil, eventTime: Date? = nil, identifier: String? = nil, operation: Operation? = nil, operationStatus: OperationStatus? = nil, requestToken: String? = nil, resourceModel: String? = nil, retryAfter: Date? = nil, statusMessage: String? = nil, typeName: String? = nil) { self.errorCode = errorCode self.eventTime = eventTime self.identifier = identifier self.operation = operation self.operationStatus = operationStatus self.requestToken = requestToken self.resourceModel = resourceModel self.retryAfter = retryAfter self.statusMessage = statusMessage self.typeName = typeName } private enum CodingKeys: String, CodingKey { case errorCode = "ErrorCode" case eventTime = "EventTime" case identifier = "Identifier" case operation = "Operation" case operationStatus = "OperationStatus" case requestToken = "RequestToken" case resourceModel = "ResourceModel" case retryAfter = "RetryAfter" case statusMessage = "StatusMessage" case typeName = "TypeName" } } public struct ResourceDescription: AWSDecodableShape { /// The primary identifier for the resource. For more information, see Identifying resources in the Amazon Web Services Cloud Control API User Guide. public let identifier: String? /// A list of the resource properties and their current values. public let properties: String? public init(identifier: String? = nil, properties: String? = nil) { self.identifier = identifier self.properties = properties } private enum CodingKeys: String, CodingKey { case identifier = "Identifier" case properties = "Properties" } } public struct ResourceRequestStatusFilter: AWSEncodableShape { /// The operation types to include in the filter. public let operations: [Operation]? /// The operation statuses to include in the filter. PENDING: The operation has been requested, but not yet initiated. IN_PROGRESS: The operation is currently in progress. SUCCESS: The operation has successfully completed. FAILED: The operation has failed. CANCEL_IN_PROGRESS: The operation is currently in the process of being canceled. CANCEL_COMPLETE: The operation has been canceled. public let operationStatuses: [OperationStatus]? public init(operations: [Operation]? = nil, operationStatuses: [OperationStatus]? = nil) { self.operations = operations self.operationStatuses = operationStatuses } private enum CodingKeys: String, CodingKey { case operations = "Operations" case operationStatuses = "OperationStatuses" } } public struct UpdateResourceInput: AWSEncodableShape { /// A unique identifier to ensure the idempotency of the resource request. As a best practice, specify this token to ensure idempotency, so that Amazon Web Services Cloud Control API can accurately distinguish between request retries and new resource requests. You might retry a resource request to ensure that it was successfully received. A client token is valid for 36 hours once used. After that, a resource request with the same client token is treated as a new request. If you do not specify a client token, one is generated for inclusion in the request. For more information, see Ensuring resource operation requests are unique in the Amazon Web Services Cloud Control API User Guide. public let clientToken: String? /// The identifier for the resource. You can specify the primary identifier, or any secondary identifier defined for the resource type in its resource schema. You can only specify one identifier. Primary identifiers can be specified as a string or JSON; secondary identifiers must be specified as JSON. For compound primary identifiers (that is, one that consists of multiple resource properties strung together), to specify the primary identifier as a string, list the property values in the order they are specified in the primary identifier definition, separated by |. For more information, see Identifying resources in the Amazon Web Services Cloud Control API User Guide. public let identifier: String /// A JavaScript Object Notation (JSON) document listing the patch operations that represent the updates to apply to the current resource properties. For details, see Composing the patch document in the Amazon Web Services Cloud Control API User Guide. public let patchDocument: String /// The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) for Cloud Control API to use when performing this resource operation. The role specified must have the permissions required for this operation. The necessary permissions for each event handler are defined in the handlers section of the resource type definition schema. If you do not specify a role, Cloud Control API uses a temporary session created using your Amazon Web Services user credentials. For more information, see Specifying credentials in the Amazon Web Services Cloud Control API User Guide. public let roleArn: String? /// The name of the resource type. public let typeName: String /// For private resource types, the type version to use in this resource operation. If you do not specify a resource version, CloudFormation uses the default version. public let typeVersionId: String? public init(clientToken: String? = UpdateResourceInput.idempotencyToken(), identifier: String, patchDocument: String, roleArn: String? = nil, typeName: String, typeVersionId: String? = nil) { self.clientToken = clientToken self.identifier = identifier self.patchDocument = patchDocument self.roleArn = roleArn self.typeName = typeName self.typeVersionId = typeVersionId } public func validate(name: String) throws { try self.validate(self.clientToken, name: "clientToken", parent: name, max: 128) try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1) try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "[-A-Za-z0-9+/=]+") try self.validate(self.identifier, name: "identifier", parent: name, max: 1024) try self.validate(self.identifier, name: "identifier", parent: name, min: 1) try self.validate(self.identifier, name: "identifier", parent: name, pattern: ".+") try self.validate(self.patchDocument, name: "patchDocument", parent: name, max: 65536) try self.validate(self.patchDocument, name: "patchDocument", parent: name, min: 1) try self.validate(self.patchDocument, name: "patchDocument", parent: name, pattern: "(.|\\s)*") try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20) try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:.+:iam::[0-9]{12}:role/.+") try self.validate(self.typeName, name: "typeName", parent: name, max: 196) try self.validate(self.typeName, name: "typeName", parent: name, min: 10) try self.validate(self.typeName, name: "typeName", parent: name, pattern: "[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}") try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, max: 128) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, min: 1) try self.validate(self.typeVersionId, name: "typeVersionId", parent: name, pattern: "[A-Za-z0-9-]+") } private enum CodingKeys: String, CodingKey { case clientToken = "ClientToken" case identifier = "Identifier" case patchDocument = "PatchDocument" case roleArn = "RoleArn" case typeName = "TypeName" case typeVersionId = "TypeVersionId" } } public struct UpdateResourceOutput: AWSDecodableShape { /// Represents the current status of the resource update request. Use the RequestToken of the ProgressEvent with GetResourceRequestStatus to return the current status of a resource operation request. public let progressEvent: ProgressEvent? public init(progressEvent: ProgressEvent? = nil) { self.progressEvent = progressEvent } private enum CodingKeys: String, CodingKey { case progressEvent = "ProgressEvent" } } }
67.822807
699
0.688585
8aecc5dec92094ed6f3a34de796e7da75aceacec
703
// // RepoInfoCell.swift // YZGithubClient // // Created by 张凯 on 16/8/12. // Copyright © 2016年 Zheng. All rights reserved. // import UIKit class RepoInfoCell: UITableViewCell { @IBOutlet var imageIcon: UIImageView! @IBOutlet var actionName: UILabel! func customUI(image:UIImage,actionName:String) { imageIcon.image = image self.actionName.text = actionName } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
20.676471
63
0.647226
11b918a8a7f7e5d545d470059f4fba1f152a68da
5,424
// // CreatorRequestBuilderTests.swift // MarvelClient // // Copyright (c) 2016 Eduardo Arenas <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import XCTest @testable import MarvelClient class CreatorRequestBuilderTests: XCTestCase { let marvelClient = MarvelClient(privateKey: "private", publicKey: "public") var requestBuilder: CreatorRequestBuilder? override func setUp() { super.setUp() self.requestBuilder = self.marvelClient.requestCreators() } func testGetsInitializedWithCreatorsEntityType() { XCTAssertEqual(self.requestBuilder?.entityType, "creators") } func testDefaultRequestContainsAuthParameters() { XCTAssertNotNil(self.requestBuilder!.parameters["ts"]) XCTAssertEqual(self.requestBuilder!.parameters["apikey"] as? String, "public") XCTAssertNotNil(self.requestBuilder!.parameters["hash"]) } func testFirstNameTitleGetsSetOnRequest() { let builder = self.requestBuilder!.firstName("Stan") XCTAssertEqual(builder.parameters["firstName"] as? String, "Stan") } func testMiddleNameWithGetsSetOnRequest() { let builder = self.requestBuilder!.middleName("Martin") XCTAssertEqual(builder.parameters["middleName"] as? String, "Martin") } func testLastNameWithGetsSetOnRequest() { let builder = self.requestBuilder!.lastName("Lee") XCTAssertEqual(builder.parameters["lastName"] as? String, "Lee") } func testSuffixWithGetsSetOnRequest() { let builder = self.requestBuilder!.suffix("Jr") XCTAssertEqual(builder.parameters["suffix"] as? String, "Jr") } func testFirstNameStartsWithTitleGetsSetOnRequest() { let builder = self.requestBuilder!.firstNameStartsWith("Stan") XCTAssertEqual(builder.parameters["firstNameStartsWith"] as? String, "Stan") } func testMiddleNameStartsWithWithGetsSetOnRequest() { let builder = self.requestBuilder!.middleNameStartsWith("Martin") XCTAssertEqual(builder.parameters["middleNameStartsWith"] as? String, "Martin") } func testLastNameStartsWithWithGetsSetOnRequest() { let builder = self.requestBuilder!.lastNameStartsWith("Lee") XCTAssertEqual(builder.parameters["lastNameStartsWith"] as? String, "Lee") } func testComicsGetsSetOnRequest() { let builder = self.requestBuilder!.comics([1, 2, 3]) XCTAssertEqual(builder.parameters["comics"] as? String, "1,2,3") } func testSeriesGetsSetOnRequest() { let builder = self.requestBuilder!.series([1, 2, 3]) XCTAssertEqual(builder.parameters["series"] as? String, "1,2,3") } func testEventsGetsSetOnRequest() { let builder = self.requestBuilder!.events([1, 2, 3]) XCTAssertEqual(builder.parameters["events"] as? String, "1,2,3") } func testStoriesGetsSetOnRequest() { let builder = self.requestBuilder!.stories([1, 2, 3]) XCTAssertEqual(builder.parameters["stories"] as? String, "1,2,3") } func testOrderByGetsSetOnRequest() { let builder = self.requestBuilder!.orderBy([.LastName]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "lastName") builder.orderBy([.FirstName]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "firstName") builder.orderBy([.MiddleName]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "middleName") builder.orderBy([.Suffix]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "suffix") builder.orderBy([.Modified]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "modified") builder.orderBy([.LastNameDescending]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "-lastName") builder.orderBy([.FirstNameDescending]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "-firstName") builder.orderBy([.MiddleNameDescending]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "-middleName") builder.orderBy([.SuffixDescending]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "-suffix") builder.orderBy([.ModifiedDescending]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "-modified") } func testOrderByGetsSetOnRequestWithMultipleCriteria() { let builder = self.requestBuilder!.orderBy([.FirstName, .SuffixDescending]) XCTAssertEqual(builder.parameters["orderBy"] as? String, "firstName,-suffix") } }
38.197183
83
0.72806
48baebfe9ee1bb318e6761884b77ed6b93321ee5
596
// // ProfileViewController.swift // Instagram // // Created by Lily on 2/28/16. // Copyright © 2016 yyclaire. All rights reserved. // import UIKit import Parse let logoutNotification = "logoutNotification" class ProfileViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func Logout(sender: AnyObject) { PFUser.logOut() NSNotificationCenter.defaultCenter().postNotificationName(logoutNotification, object: nil) } }
20.551724
98
0.669463
1e9ab7f6ec98841baa4def00d28d72d7d53ca8df
875
// // DiscordDesktopRPC.swift // Accord // // Created by evelyn on 2022-01-06. // import Foundation final class DiscordDesktopRPC { class func update(guildName: String? = nil, channelName: String) { guard DiscordDesktopRPCEnabled else { return } try? wss.updatePresence(status: MediaRemoteWrapper.status ?? "dnd", since: Int(Date().timeIntervalSince1970) * 1000) { Activity.current! Activity( applicationID: discordDesktopRPCAppID, flags: 1, name: "Discord Desktop", type: 0, timestamp: Int(Date().timeIntervalSince1970) * 1000, state: guildName != nil ? "In \(guildName!)" : "Direct Messages", details: guildName != nil ? "Reading #\(channelName)" : "Speaking with \(channelName)" ) } } }
32.407407
126
0.577143
164b21c1306ce1a405a8e9921d9528cbd85b99fa
8,185
// // DecodingTests.swift // // // Created by Eduardo Arenas on 8/8/20. // import XCTest @testable import ScryfallSDK /// This teset suite tests decoding for a large data set located in `Tests/ScryfallSDKTests/Data`. In order to run the tests /// the data has to be decompressed first. This can be done running the script `Scripts/decompress_test_data.sh` once. final class DecodingTests: XCTestCase { func testListDecode() throws { let testFilePath = #file let testDataFilePath = URL(fileURLWithPath: testFilePath).deletingLastPathComponent().appendingPathComponent("Data/Decompressed/list.json") let testData = try Data(contentsOf: testDataFilePath) let list = try JSONDecoder.scryfallDecoder.decode(List<Card>.self, from: testData) XCTAssertNotNil(list.nextPage) XCTAssertNil(list.warnings) } func testSetDecode() throws { let testFilePath = #file let testDataFilePath = URL(fileURLWithPath: testFilePath).deletingLastPathComponent().appendingPathComponent("Data/Decompressed/all_sets.json") let testData = try Data(contentsOf: testDataFilePath) XCTAssertNoThrow(try JSONDecoder.scryfallDecoder.decode([Set].self, from: testData)) } func testCardsDecode() throws { let testFilePath = #file // all_cards.json contains every single card object in Scryfall and can be used to test successful decoding of all cardsin the database, but running // the test with this data set can take a long time. some_cards.json contains a sample of 10,000 of the same cards. Use some_cards.json for quick // test runs in iteration, and use all_cards.json to confirm all cards will successfully decode. do { // let testDataFilePath = URL(fileURLWithPath: testFilePath).deletingLastPathComponent().appendingPathComponent("Data/Decompressed/some_cards.json") let testDataFilePath = URL(fileURLWithPath: testFilePath).deletingLastPathComponent().appendingPathComponent("Data/Decompressed/all_cards.json") let testData = try Data(contentsOf: testDataFilePath) let allCards = try JSONDecoder.scryfallDecoder.decode([Card].self, from: testData) // Make sure no optional field is always `nil`, as this might indicate silent decoding issues XCTAssertTrue(allCards.contains(where: { $0.arenaId != nil })) XCTAssertTrue(allCards.contains(where: { $0.mtgoId != nil })) XCTAssertTrue(allCards.contains(where: { $0.mtgoFoilId != nil })) XCTAssertTrue(allCards.contains(where: { $0.multiverseIds != nil })) XCTAssertTrue(allCards.contains(where: { $0.tcgplayerId != nil })) XCTAssertTrue(allCards.contains(where: { $0.allParts != nil })) XCTAssertTrue(allCards.contains(where: { $0.cardFaces != nil })) XCTAssertTrue(allCards.contains(where: { $0.colorIndicator != nil })) XCTAssertTrue(allCards.contains(where: { $0.colors != nil })) XCTAssertTrue(allCards.contains(where: { $0.edhrecRank != nil })) XCTAssertTrue(allCards.contains(where: { $0.handModifier != nil })) XCTAssertTrue(allCards.contains(where: { $0.lifeModifier != nil })) XCTAssertTrue(allCards.contains(where: { $0.loyalty != nil })) XCTAssertTrue(allCards.contains(where: { $0.manaCost != nil })) XCTAssertTrue(allCards.contains(where: { $0.oracleText != nil })) XCTAssertTrue(allCards.contains(where: { $0.power != nil })) XCTAssertTrue(allCards.contains(where: { $0.producedMana != nil })) XCTAssertTrue(allCards.contains(where: { $0.toughness != nil })) XCTAssertTrue(allCards.contains(where: { $0.artist != nil })) XCTAssertTrue(allCards.contains(where: { $0.contentWarning != nil })) XCTAssertTrue(allCards.contains(where: { $0.flavorName != nil })) XCTAssertTrue(allCards.contains(where: { $0.flavorText != nil })) XCTAssertTrue(allCards.contains(where: { $0.frameEffects != nil })) XCTAssertTrue(allCards.contains(where: { $0.illustrationId != nil })) XCTAssertTrue(allCards.contains(where: { $0.lifeModifier != nil })) XCTAssertTrue(allCards.contains(where: { $0.imageUris != nil })) XCTAssertTrue(allCards.contains(where: { $0.printedName != nil })) XCTAssertTrue(allCards.contains(where: { $0.printedText != nil })) XCTAssertTrue(allCards.contains(where: { $0.printedTypeLine != nil })) XCTAssertTrue(allCards.contains(where: { $0.promoTypes != nil })) XCTAssertTrue(allCards.contains(where: { $0.variationOf != nil })) XCTAssertTrue(allCards.contains(where: { $0.watermark != nil })) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.artist != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.colorIndicator != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.colors != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.flavorText != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.illustrationId != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.imageUris != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.loyalty != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.oracleText != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.power != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.colorIndicator != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.printedName != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.printedText != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.printedTypeLine != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.toughness != nil }) ?? false)})) XCTAssertTrue(allCards.contains(where: { card in (card.cardFaces?.contains(where: { face in face.watermark != nil }) ?? false)})) } catch let error { print(error) } } func testRulingsDecode() throws { let testFilePath = #file let testDataFilePath = URL(fileURLWithPath: testFilePath).deletingLastPathComponent().appendingPathComponent("Data/Decompressed/rulings.json") let testData = try Data(contentsOf: testDataFilePath) XCTAssertNoThrow(try JSONDecoder.scryfallDecoder.decode([Ruling].self, from: testData)) } func testSymbolsDecode() throws { let testFilePath = #file let testDataFilePath = URL(fileURLWithPath: testFilePath).deletingLastPathComponent().appendingPathComponent("Data/Decompressed/all_symbols.json") let testData = try Data(contentsOf: testDataFilePath) let allSymbols = try JSONDecoder.scryfallDecoder.decode([CardSymbol].self, from: testData) XCTAssertTrue(allSymbols.contains(where: { $0.looseVariant != nil })) XCTAssertTrue(allSymbols.contains(where: { $0.cmc != nil })) XCTAssertTrue(allSymbols.contains(where: { $0.gathererAlternates != nil })) } static var allTests = [ ("testCardsDecode", testCardsDecode), ("testRulingsDecode", testRulingsDecode) ] }
68.208333
160
0.670006
7a1ff76945e06c44d59400ac08fa5f65e2bad1ca
747
// // mbBooksContentModel.swift // mbBooks // // Created by Mélodie Borel on 30/04/2019. // Copyright © 2019 KF Interactive. All rights reserved. // import Foundation import CoreData class mbBooksContentModel: NSManagedObject { var metaData: NSMutableDictionary = [:] var manifest: NSMutableDictionary = [:] var spine: [String] = [] var guide: [Any] = [] @NSManaged var mbBookTitle: String? @NSManaged var mbBookPath: String? @NSManaged var mbBookType: Int16 @NSManaged var mbBookEncryption: Int16 @NSManaged var coverPath: String? @NSManaged var chapters: NSSet @NSManaged var isRTL: Bool @NSManaged var bookMark: Int32 @NSManaged var bookMarkIntra: Float }
22.636364
57
0.674699
91d8ae1eb3c6904c626fdfef0c848d78ef7d8886
3,131
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Cocoa import CoreWLAN import FlutterMacOS import Reachability import SystemConfiguration.CaptiveNetwork public class ConnectivityPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { var reach: Reachability? var eventSink: FlutterEventSink? var cwinterface: CWInterface? public override init() { cwinterface = CWWiFiClient.shared().interface() } public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel( name: "plugins.flutter.io/connectivity", binaryMessenger: registrar.messenger) let streamChannel = FlutterEventChannel( name: "plugins.flutter.io/connectivity_status", binaryMessenger: registrar.messenger) let instance = ConnectivityPlugin() streamChannel.setStreamHandler(instance) registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "check": result(statusFromReachability(reachability: Reachability.forInternetConnection())) case "wifiName": result(cwinterface?.ssid()) case "wifiBSSID": result(cwinterface?.bssid()) case "wifiIPAddress": result(getWifiIP()) default: result(FlutterMethodNotImplemented) } } /// Returns a string describing connection type /// /// - Parameters: /// - reachability: an instance of reachability /// - Returns: connection type string private func statusFromReachability(reachability: Reachability?) -> String { // checks any non-WWAN connection if reachability?.isReachableViaWiFi() ?? false { return "wifi" } return "none" } public func onListen( withArguments _: Any?, eventSink events: @escaping FlutterEventSink ) -> FlutterError? { reach = Reachability.forInternetConnection() eventSink = events NotificationCenter.default.addObserver( self, selector: #selector(reachabilityChanged), name: NSNotification.Name.reachabilityChanged, object: reach) reach?.startNotifier() return nil } @objc private func reachabilityChanged(notification: NSNotification) { let reach = notification.object let reachability = statusFromReachability(reachability: reach as? Reachability) eventSink?(reachability) } public func onCancel(withArguments _: Any?) -> FlutterError? { reach?.stopNotifier() NotificationCenter.default.removeObserver(self) eventSink = nil return nil } }
29.819048
88
0.725647
16bd3198466e88268eef67201b23426dd28af5e4
468
func solve(_ arr: [Int]) { var chips = arr.sorted(by: >) var days = 0 while chips[0] > 0 && (chips[1] > 0 || chips[2] > 0) { days += 1 if chips[1] > 0 { chips[1] -= 1 } else if chips[2] > 0 { chips[2] -= 1 } chips[0] -= 1 } print(days) } solve([1, 1, 1]) // 1 solve([1, 2, 1]) // 2 solve([1, 3, 1]) // 2 solve([4, 2, 1]) // 3 solve([0, 4, 2]) // 2
18.72
58
0.365385
75fffda6ee6e38f59755bc13f84f35a7e732a3e3
2,907
/* * Copyright © 2017 Naeem G Shaikh. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit final class PostUIController { fileprivate var view: UIView fileprivate let loadingView: LoadingView fileprivate let tableViewDataSource: TableViewDataSource<PostCellController, PostCell> fileprivate let tableViewDelegate: TableViewDelegate<PostCellController, PostCell> var state: UIState = .loading { willSet(newState) { update(newState) } } init(view: UIView, tableView: UITableView) { self.view = view self.loadingView = LoadingView(frame: CGRect(origin: .zero, size: tableView.frame.size)) self.tableViewDataSource = TableViewDataSource<PostCellController, PostCell>(tableView: tableView) self.tableViewDelegate = TableViewDelegate<PostCellController, PostCell>(tableView: tableView) tableView.dataSource = tableViewDataSource tableView.delegate = tableViewDelegate update(state) } } extension PostUIController: PostDelegate { func update(_ newState: UIState) { switch(state, newState) { case (.loading, .loading): loadingToLoading() case (.loading, .success(let post)): loadingToSuccess(post) case (.loading, .failure(let error)): loadingToFailure(error) default: fatalError("Not yet implemented \(state) to \(newState)") } } func loadingToLoading() { view.addSubview(loadingView) loadingView.frame = CGRect(origin: .zero, size: view.frame.size) } func loadingToSuccess(_ post: [Post]) { loadingView.removeFromSuperview() tableViewDataSource.dataSource = post.map(PostCellController.init) tableViewDelegate.dataSource = post.map(PostCellController.init) } func loadingToFailure(_ error: MyError) { loadingView.removeFromSuperview() print(error.localizedDescription) } }
35.888889
102
0.739938
46481724f94dc2139c7a9a18e6ae2201fb7aa69d
599
// // Vitamin iOS // Apache License 2.0 // import UIKit import VitaminCore enum ShadowsModel { struct Item: Identifiable { var id: String { name } let name: String let value: VitaminShadow } static let items = [ ShadowsModel.Item(name: "Shadow 100", value: .shadow100), ShadowsModel.Item(name: "Shadow 200", value: .shadow200), ShadowsModel.Item(name: "Shadow 300", value: .shadow300), ShadowsModel.Item(name: "Shadow 400", value: .shadow400), ShadowsModel.Item(name: "None", value: .none) ] }
23.038462
65
0.599332
29a1297427fe17826b4f320cbc3b5d99cdd1cb1c
328
// // ViewController.swift // DouYu_ZB // // Created by Ruotao Lin on 5/23/20. // Copyright © 2020 Ruotao Lin. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
15.619048
58
0.655488
20bea7cc0771367b99ab2211be4c8f79834b63f0
2,272
// // AppDelegate.swift // Yelp // // Created by Timothy Lee on 9/19/14. // Copyright (c) 2014 Timothy Lee. All rights reserved. // // swiftlint:disable line_length // swiftlint:disable trailing_whitespace // swiftline:disable trailing_newline import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active //to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS //message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.44
218
0.75044
e8ed4b7a5cb7b6767d9c554b9f79503b3a848712
536
// // MainReducer.swift // Titan // // Created by Nghia Tran on 10/11/16. // Copyright © 2016 fe. All rights reserved. // import Foundation import ReSwift struct MainReducer { } // MARK - // MARK: Reducer Protocol extension MainReducer: Reducer { func handleAction(action: Action, state: MainAppState?) -> MainAppState { // Repo state let repoState = RepoState.reducer(action: action, state: state?.repoState) // return return MainAppState(repoState: repoState) } }
19.142857
82
0.63806
28158c23ce53496979b7f93b9b88a87fd73379b3
461
// // Team.swift // FootballNow! // // Created by Fredrick Ohen on 12/4/17. // Copyright © 2017 geeoku. All rights reserved. // import Foundation struct Team: Decodable { let name: String let code: String let shortName: String let crestUrl: String let links: Link enum CodingKeys: String, CodingKey { case name case code case shortName case crestUrl case links = "_links" } }
16.464286
49
0.600868
bbb32440f9470d10e130b89fb833f2f460c40696
404
// // ComposeMenu.swift // TYImageTextMixedButton // // Created by thomasTY on 16/11/16. // Copyright © 2016年 thomasTY. All rights reserved. // import UIKit class ComposeMenu: NSObject { // 类名 var className: String? // 图片名 var icon: String? // 标题 var title: String? init(dict:[String:Any]) { super.init() setValuesForKeys(dict) } }
14.428571
52
0.581683
7a8569a5ce55b2c11b337c1d178eb52b67a6cf82
8,174
import UIKit /// APIs for animating the camera. public final class CameraAnimationsManager { private let impl: CameraAnimationsManagerProtocol internal init(impl: CameraAnimationsManagerProtocol) { self.impl = impl } /// List of animators currently alive public var cameraAnimators: [CameraAnimator] { return impl.cameraAnimators } /// Interrupts all `active` animation. /// The camera remains at the last point before the cancel request was invoked, i.e., /// the camera is not reset or fast-forwarded to the end of the transition. /// Canceled animations cannot be restarted / resumed. The animator must be recreated. public func cancelAnimations() { impl.cancelAnimations() } // MARK: High-Level Animation APIs /// Moves the viewpoint to a different location using a transition animation that /// evokes powered flight and an optional transition duration and timing function /// It seamlessly incorporates zooming and panning to help /// the user find his or her bearings even after traversing a great distance. /// /// - Parameters: /// - to: The camera options at the end of the animation. Any camera parameters that are nil will /// not be animated. /// - duration: Duration of the animation, measured in seconds. If nil, a suitable calculated /// duration is used. /// - completion: Completion handler called when the animation stops /// - Returns: An instance of `Cancelable` which can be canceled if necessary @discardableResult public func fly(to: CameraOptions, duration: TimeInterval? = nil, completion: AnimationCompletion? = nil) -> Cancelable? { return impl.fly(to: to, duration: duration, completion: completion) } /// Ease the camera to a destination /// - Parameters: /// - to: the target camera after animation; if `camera.anchor` is non-nil, it is use for both /// the `fromValue` and the `toValue` of the underlying animation such that the /// value specified will not be interpolated, but will be passed as-is to each camera update /// during the animation. To animate `anchor` itself, use the `makeAnimator` APIs. /// - duration: duration of the animation /// - curve: the easing curve for the animation /// - completion: completion to be called after animation /// - Returns: An instance of `Cancelable` which can be canceled if necessary @discardableResult public func ease(to: CameraOptions, duration: TimeInterval, curve: UIView.AnimationCurve = .easeOut, completion: AnimationCompletion? = nil) -> Cancelable? { return impl.ease( to: to, duration: duration, curve: curve, completion: completion) } // MARK: Low-Level Animation APIs /// Creates a ``BasicCameraAnimator``. /// /// - Note: `CameraAnimationsManager` only keeps animators alive while their /// ``CameraAnimator/state`` is `.active`. /// /// - Parameters: /// - duration: The duration of the animation. /// - timingParameters: The object providing the timing information. This object must adopt /// the `UITimingCurveProvider` protocol. /// - animationOwner: An `AnimationOwner` that can be used to identify what component /// initiated an animation. /// - animations: a closure that configures the animation's to and from values via a /// ``CameraTransition``. /// - Returns: A new ``BasicCameraAnimator``. public func makeAnimator(duration: TimeInterval, timingParameters: UITimingCurveProvider, animationOwner: AnimationOwner = .unspecified, animations: @escaping (inout CameraTransition) -> Void) -> BasicCameraAnimator { return impl.makeAnimator( duration: duration, timingParameters: timingParameters, animationOwner: animationOwner, animations: animations) } /// Creates a ``BasicCameraAnimator``. /// /// - Note: `CameraAnimationsManager` only keeps animators alive while their /// ``CameraAnimator/state`` is `.active`. /// /// - Parameters: /// - duration: The duration of the animation. /// - curve: One of UIKit's predefined timing curves to apply to the animation. /// - animationOwner: An `AnimationOwner` that can be used to identify what component /// initiated an animation. /// - animations: a closure that configures the animation's to and from values via a /// ``CameraTransition``. /// - Returns: A new ``BasicCameraAnimator``. public func makeAnimator(duration: TimeInterval, curve: UIView.AnimationCurve, animationOwner: AnimationOwner = .unspecified, animations: @escaping (inout CameraTransition) -> Void) -> BasicCameraAnimator { return impl.makeAnimator( duration: duration, curve: curve, animationOwner: animationOwner, animations: animations) } /// Creates a ``BasicCameraAnimator``. /// /// - Note: `CameraAnimationsManager` only keeps animators alive while their /// ``CameraAnimator/state`` is `.active`. /// /// - Parameters: /// - duration: The duration of the animation. /// - controlPoint1: The first control point for the cubic Bézier timing curve. /// - controlPoint2: The second control point for the cubic Bézier timing curve. /// - animationOwner: An `AnimationOwner` that can be used to identify what component /// initiated an animation. /// - animations: a closure that configures the animation's to and from values via a /// ``CameraTransition``. /// - Returns: A new ``BasicCameraAnimator``. public func makeAnimator(duration: TimeInterval, controlPoint1: CGPoint, controlPoint2: CGPoint, animationOwner: AnimationOwner = .unspecified, animations: @escaping (inout CameraTransition) -> Void) -> BasicCameraAnimator { return impl.makeAnimator( duration: duration, controlPoint1: controlPoint1, controlPoint2: controlPoint2, animationOwner: animationOwner, animations: animations) } /// Creates a ``BasicCameraAnimator``. /// /// - Note: `CameraAnimationsManager` only keeps animators alive while their /// ``CameraAnimator/state`` is `.active`. /// /// - Parameters: /// - duration: The duration of the animation. /// - dampingRatio: The damping ratio to apply to the initial acceleration and oscillation. To /// smoothly decelerate the animation without oscillation, specify a value of 1. /// Specify values closer to 0 to create less damping and more oscillation. /// - animationOwner: An `AnimationOwner` that can be used to identify what component /// initiated an animation. /// - animations: a closure that configures the animation's to and from values via a /// ``CameraTransition``. /// - Returns: A new ``BasicCameraAnimator``. public func makeAnimator(duration: TimeInterval, dampingRatio: CGFloat, animationOwner: AnimationOwner = .unspecified, animations: @escaping (inout CameraTransition) -> Void) -> BasicCameraAnimator { return impl.makeAnimator( duration: duration, dampingRatio: dampingRatio, animationOwner: animationOwner, animations: animations) } }
47.523256
109
0.611573
e2fae86278aa5aab6abaa1bb5e4b0b659e783444
4,940
import Foundation final class Generator { let chart: Chart let jsonPath: String init(jsonPath: String) { self.chart = Chart() self.jsonPath = jsonPath } func generate() { let json = getJson() let info = getInfo(fromJson: json) let html = chart.generate(info: info) save(html: html) } func getJson() -> [String: Any] { let jsonUrl = URL(fileURLWithPath: jsonPath) do { let jsonData = try Data(contentsOf: jsonUrl) let object = try JSONSerialization.jsonObject(with: jsonData, options: []) guard let json = object as? [String: Any] else { fail("Failed to cast \(object) to a Dictionary.") } return json } catch { fail(error.localizedDescription) } } func getInfo(fromJson json: [String: Any]) -> [ProviderInfo] { guard let data = json["data"] as? [[String: Any]] else { fail("Failed to get `data`: It looks like the JSON isn't in the right format.") } let rawInfo = data.flatMap { data -> [ProviderInfo] in let hardcodedInfoKey = "swiftinfo_run_project_info" let infoDict = data[hardcodedInfoKey] as? [String: Any] return data.compactMap { dict -> ProviderInfo? in let key = dict.key guard key != hardcodedInfoKey else { return nil } guard key != "swiftinfo_run_description_key" else { return nil } guard let valueDict = dict.value as? [String: Any] else { fail("Data output value from \(key) isn't a dictionary! \(dict.value)") } let summary = valueDict["summary"] as? [String: Any] ?? [:] let color = summary["color"] as? String ?? "#000000" let tooltip = summary["text"] as? String ?? "No summary." let data = valueDict["data"] as? [String: Any] ?? [:] let description = data["description"] as? String ?? "No description." guard let value = summary["numericValue"] as? Float else { print("Ignoring a \(key) entry as it has no Float numericValue. This is likely because this SwiftInfo-Reader version doesn't support the SwiftInfo version that generated this entry.") return nil } let stringValue = summary["stringValue"] as? String ?? "\(value)" // let versionString = (infoDict?["versionString"] as? String) ?? "?" let buildNumber = (infoDict?["buildNumber"] as? String) ?? "?" let target = (infoDict?["target"] as? String) ?? "?" let projectDescription = (infoDict?["description"] as? String) ?? "?" let timestamp = infoDict?["timestamp"] as? Double let project = Xcodeproj(target: target, versionString: versionString, buildNumber: buildNumber, description: projectDescription, timestamp: timestamp) // let run = Run(project: project, value: value, stringValue: stringValue, tooltip: tooltip, color: color) return ProviderInfo(key: key, description: description, runs: [run]) } } var mergedInfo = [String: ProviderInfo]() rawInfo.forEach { let current = mergedInfo[$0.key] mergedInfo[$0.key] = ProviderInfo(key: current?.key ?? $0.key, description: current?.description ?? $0.description, runs: $0.runs + (current?.runs ?? [])) } return mergedInfo.map { $0.value } } func save(html: String) { let url = URL(fileURLWithPath: jsonPath) let folderToSave = url.deletingLastPathComponent() .appendingPathComponent("page") .appendingPathComponent("public") do { try FileManager.default.createDirectory(atPath: folderToSave.relativePath, withIntermediateDirectories: true, attributes: nil) let indexUrl = folderToSave.appendingPathComponent("index.html") try html.write(to: indexUrl, atomically: true, encoding: .utf8) print("Page generated succesfully at \(folderToSave.relativePath)!") } catch { fail(error.localizedDescription) } } }
45.321101
203
0.507085
bf87d8907806558ef0a7d46aa3517acebceca4bd
3,877
// // Orientation.swift // vigour-native // // Created by Alexander van der Werff on 21/12/15. // Copyright © 2015 RxSwift. All rights reserved. // import Foundation import UIKit import VigourCore enum VigourOrientationMethod: String { case Init="init", Orientation="orientation", Locked="locked" } class Orientation:NSObject, VigourPluginProtocol { override init() { super.init() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(orientationChanged), name: UIDeviceOrientationDidChangeNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } static let sharedInstance = Orientation() static let pluginId = "orientation" weak var delegate: VigourBridgeViewController? func callMethodWithName(name: String, andArguments args:NSDictionary?, completionHandler:PluginResult) throws { guard let method = VigourOrientationMethod.init(rawValue: name) else { throw VigourBridgeError.PluginError("Unsupported method!", pluginId: Orientation.pluginId) } switch method { case .Init: completionHandler(nil, JSValue(mapOrientationValue(UIDevice.currentDevice().orientation))) case .Orientation: if let orientation = args?.objectForKey("orientation") as? String where orientation == "portrait", let d = delegate { //force rotation d.autoRotate = true UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation") //force lock d.autoRotate = false completionHandler(nil, JSValue(true)) } else if let orientation = args?.objectForKey("orientation") as? String where orientation == "landscape", let d = delegate { //force rotation d.autoRotate = true UIDevice.currentDevice().setValue(UIInterfaceOrientation.LandscapeLeft.rawValue, forKey: "orientation") d.autoRotate = false completionHandler(nil, JSValue(true)) } else { completionHandler(JSError(title: "Orientation error", description: "wrong param for method orientation", todo: ""), JSValue(false)) } case .Locked: if let locked = args?.objectForKey("locked") as? Bool, let d = delegate { d.autoRotate = !locked } completionHandler(nil, JSValue(true)) } } static func instance() -> VigourPluginProtocol { return Orientation.sharedInstance } func onReady() throws -> JSValue { return JSValue([Orientation.pluginId:"ready"]) } ///private func mapOrientationValue(o:UIDeviceOrientation) -> String { if UIDeviceOrientationIsLandscape(o) { return "landscape" } else if UIDeviceOrientationIsPortrait(o) { return "portrait" } else { return "unknown" } } //MARK:- orientationChanged func orientationChanged(notification:NSNotification) { if let d = delegate where d.autoRotate == true { let orientation = mapOrientationValue(UIDevice.currentDevice().orientation) d.vigourBridge.sendJSMessage(VigourBridgeSendMessage.Receive(error: nil, event: "change", message: JSValue(orientation), pluginId: Orientation.pluginId)) } } }
33.713043
165
0.580088
08b237b8bdd396235a9268e9963e77c404a53a68
957
// // ImageViewExtension.swift // Flicks // // Created by Xie Kesong on 1/14/17. // Copyright © 2017 Xie Kesong. All rights reserved. // import Foundation import UIKit extension UIImageView{ func loadBusinessImage(business: Business){ if let url = business.imageURL{ let urlRequest = URLRequest(url: url) self.setImageWith(urlRequest, placeholderImage: nil, success: { (request, response, image) in if(response == nil){ //from cache self.image = image }else{ self.alpha = 0.0 self.image = image UIView.animate(withDuration: 0.3, animations: { self.alpha = 1.0 }) } }, failure: { (request, response, error) in print(error.localizedDescription) }) } } }
26.583333
105
0.497388
5b6d5e7b63912054524a07941968a8420fa12e97
375
// // FirebaseKeys.swift // RateTracker // // Created by Sitora Guliamova on 4/5/20. // Copyright © 2020 Sitora Guliamova. All rights reserved. // import Foundation struct FirebaseKeys { struct Users { static let usersTableName = "users" static let name = "name" static let birthDate = "birthDate" static let email = "email" } }
19.736842
59
0.637333
33068f6ad72be894f5f51616121ea290737418a8
2,287
// // SceneDelegate.swift // Prework // // Created by Kieran King on 2/1/22. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.150943
147
0.712287
149943609af8face7f0e4d57820c78f08260cb51
1,858
// // HexagonParameters.swift // swift-ui-training // // Created by Serg Liamthev on 6/9/19. // Copyright © 2019 serglam. All rights reserved. // import SwiftUI struct HexagonParameters { struct Segment { let useWidth: (CGFloat, CGFloat, CGFloat) let xFactors: (CGFloat, CGFloat, CGFloat) let useHeight: (CGFloat, CGFloat, CGFloat) let yFactors: (CGFloat, CGFloat, CGFloat) } static let adjustment: CGFloat = 0.085 static let points = [ Segment( useWidth: (1.00, 1.00, 1.00), xFactors: (0.60, 0.40, 0.50), useHeight: (1.00, 1.00, 0.00), yFactors: (0.05, 0.05, 0.00) ), Segment( useWidth: (1.00, 1.00, 0.00), xFactors: (0.05, 0.00, 0.00), useHeight: (1.00, 1.00, 1.00), yFactors: (0.20 + adjustment, 0.30 + adjustment, 0.25 + adjustment) ), Segment( useWidth: (1.00, 1.00, 0.00), xFactors: (0.00, 0.05, 0.00), useHeight: (1.00, 1.00, 1.00), yFactors: (0.70 - adjustment, 0.80 - adjustment, 0.75 - adjustment) ), Segment( useWidth: (1.00, 1.00, 1.00), xFactors: (0.40, 0.60, 0.50), useHeight: (1.00, 1.00, 1.00), yFactors: (0.95, 0.95, 1.00) ), Segment( useWidth: (1.00, 1.00, 1.00), xFactors: (0.95, 1.00, 1.00), useHeight: (1.00, 1.00, 1.00), yFactors: (0.80 - adjustment, 0.70 - adjustment, 0.75 - adjustment) ), Segment( useWidth: (1.00, 1.00, 1.00), xFactors: (1.00, 0.95, 1.00), useHeight: (1.00, 1.00, 1.00), yFactors: (0.30 + adjustment, 0.20 + adjustment, 0.25 + adjustment) ) ] }
30.966667
80
0.484392
5615ff7c9b6043b3ad5683533461d713f3d36dc4
1,133
// // KueskiCustomButton.swift // KueskiClientPod // // Created by Pablo de la Rosa Michicol on 9/25/19. // Copyright © 2019 CraftCode. All rights reserved. // import Foundation import UIKit class KueskiCustomButton: UIView { let kueskiButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1) button.setTitle("KUESKI", for: .normal) button.heightAnchor.constraint(equalToConstant: 50).isActive = true button.widthAnchor.constraint(equalToConstant: 200).isActive = true return button }() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .white self.addSubview(kueskiButton) kueskiButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true kueskiButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true } required init?(coder: NSCoder) { super.init(coder: coder) } }
32.371429
116
0.686673
db2078f6b28a80ee7ea2a9eb52213ad0709aec8e
18,913
// // Zip.swift // Zip // // Created by Roy Marmelstein on 13/12/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation import Minizip /// Zip error type public enum ZipError: Error { /// File not found case fileNotFound /// Unzip fail case unzipFail /// Zip fail case zipFail /// User readable description public var description: String { switch self { case .fileNotFound: return NSLocalizedString("File not found.", comment: "") case .unzipFail: return NSLocalizedString("Failed to unzip file.", comment: "") case .zipFail: return NSLocalizedString("Failed to zip file.", comment: "") } } } public enum ZipCompression: Int { case NoCompression case BestSpeed case DefaultCompression case BestCompression internal var minizipCompression: Int32 { switch self { case .NoCompression: return Z_NO_COMPRESSION case .BestSpeed: return Z_BEST_SPEED case .DefaultCompression: return Z_DEFAULT_COMPRESSION case .BestCompression: return Z_BEST_COMPRESSION } } } /// Data in memory that will be archived as a file. public struct ArchiveFile { var filename:String var data:NSData var modifiedTime:Date? public init(filename:String, data:NSData, modifiedTime:Date?) { self.filename = filename self.data = data self.modifiedTime = modifiedTime } } /// Zip class public class Zip { // MARK: Lifecycle /** Init - returns: Zip object */ public init () { } // MARK: Unzip /** Unzip file - parameter zipFilePath: Local file path of zipped file. NSURL. - parameter destination: Local file path to unzip to. NSURL. - parameter overwrite: Overwrite bool. - parameter password: Optional password if file is protected. - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if unzipping fails or if fail is not found. Can be printed with a description variable. - notes: Supports implicit progress composition */ public class func unzipFile(_ zipFilePath: URL, destination: URL, overwrite: Bool, password: String?, progress: ((_ progress: Double) -> ())? = nil, fileOutputHandler: ((_ unzippedFile: URL) -> Void)? = nil) throws { // File manager let fileManager = FileManager.default // Check whether a zip file exists at path. let path = zipFilePath.path if fileManager.fileExists(atPath: path) == false { throw ZipError.fileNotFound } // Unzip set up var ret: Int32 = 0 var crc_ret: Int32 = 0 let bufferSize: UInt32 = 4096 var buffer = Array<CUnsignedChar>(repeating: 0, count: Int(bufferSize)) // Progress handler set up var totalSize: Double = 0.0 var currentPosition: Double = 0.0 let fileAttributes = try fileManager.attributesOfItem(atPath: path) if let attributeFileSize = fileAttributes[FileAttributeKey.size] as? Double { totalSize += attributeFileSize } let progressTracker = Progress(totalUnitCount: Int64(totalSize)) progressTracker.isCancellable = false progressTracker.isPausable = false progressTracker.kind = ProgressKind.file // Begin unzipping let zip = unzOpen64(path) defer { unzClose(zip) } if unzGoToFirstFile(zip) != UNZ_OK { throw ZipError.unzipFail } repeat { if let cPassword = password?.cString(using: String.Encoding.ascii) { ret = unzOpenCurrentFilePassword(zip, cPassword) } else { ret = unzOpenCurrentFile(zip); } if ret != UNZ_OK { throw ZipError.unzipFail } var fileInfo = unz_file_info64() memset(&fileInfo, 0, MemoryLayout<unz_file_info>.size) ret = unzGetCurrentFileInfo64(zip, &fileInfo, nil, 0, nil, 0, nil, 0) if ret != UNZ_OK { unzCloseCurrentFile(zip) throw ZipError.unzipFail } currentPosition += Double(fileInfo.compressed_size) let fileNameSize = Int(fileInfo.size_filename) + 1 //let fileName = UnsafeMutablePointer<CChar>(allocatingCapacity: fileNameSize) let fileName = UnsafeMutablePointer<CChar>.allocate(capacity: fileNameSize) unzGetCurrentFileInfo64(zip, &fileInfo, fileName, UInt(fileNameSize), nil, 0, nil, 0) fileName[Int(fileInfo.size_filename)] = 0 var pathString = String(cString: fileName) guard pathString.count > 0 else { throw ZipError.unzipFail } var isDirectory = false let fileInfoSizeFileName = Int(fileInfo.size_filename-1) if (fileName[fileInfoSizeFileName] == "/".cString(using: String.Encoding.utf8)?.first || fileName[fileInfoSizeFileName] == "\\".cString(using: String.Encoding.utf8)?.first) { isDirectory = true; } free(fileName) if pathString.rangeOfCharacter(from: CharacterSet(charactersIn: "/\\")) != nil { pathString = pathString.replacingOccurrences(of: "\\", with: "/") } let fullPath = destination.appendingPathComponent(pathString).path let creationDate = Date() let directoryAttributes: [FileAttributeKey: Any]? #if os(Linux) // On Linux, setting attributes is not yet really implemented. // In Swift 4.2, the only settable attribute is `.posixPermissions`. // See https://github.com/apple/swift-corelibs-foundation/blob/swift-4.2-branch/Foundation/FileManager.swift#L182-L196 directoryAttributes = nil #else directoryAttributes = [.creationDate : creationDate, .modificationDate : creationDate] #endif do { if isDirectory { try fileManager.createDirectory(atPath: fullPath, withIntermediateDirectories: true, attributes: directoryAttributes) } else { let parentDirectory = (fullPath as NSString).deletingLastPathComponent try fileManager.createDirectory(atPath: parentDirectory, withIntermediateDirectories: true, attributes: directoryAttributes) } } catch {} if fileManager.fileExists(atPath: fullPath) && !isDirectory && !overwrite { unzCloseCurrentFile(zip) ret = unzGoToNextFile(zip) } var writeBytes: UInt64 = 0 var filePointer: UnsafeMutablePointer<FILE>? filePointer = fopen(fullPath, "wb") while filePointer != nil { let readBytes = unzReadCurrentFile(zip, &buffer, bufferSize) if readBytes > 0 { guard fwrite(buffer, Int(readBytes), 1, filePointer) == 1 else { throw ZipError.unzipFail } writeBytes += UInt64(readBytes) } else { break } } if let fp = filePointer { fclose(fp) } crc_ret = unzCloseCurrentFile(zip) if crc_ret == UNZ_CRCERROR { throw ZipError.unzipFail } guard writeBytes == fileInfo.uncompressed_size else { throw ZipError.unzipFail } //Set file permissions from current fileInfo if fileInfo.external_fa != 0 { let permissions = (fileInfo.external_fa >> 16) & 0x1FF //We will devifne a valid permission range between Owner read only to full access if permissions >= 0o400 && permissions <= 0o777 { do { try fileManager.setAttributes([.posixPermissions : permissions], ofItemAtPath: fullPath) } catch { print("Failed to set permissions to file \(fullPath), error: \(error)") } } } ret = unzGoToNextFile(zip) // Update progress handler if let progressHandler = progress{ progressHandler((currentPosition/totalSize)) } if let fileHandler = fileOutputHandler, let encodedString = fullPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let fileUrl = URL(string: encodedString) { fileHandler(fileUrl) } progressTracker.completedUnitCount = Int64(currentPosition) } while (ret == UNZ_OK && ret != UNZ_END_OF_LIST_OF_FILE) // Completed. Update progress handler. if let progressHandler = progress{ progressHandler(1.0) } progressTracker.completedUnitCount = Int64(totalSize) } // MARK: Zip /** Zip files. - parameter paths: Array of NSURL filepaths. - parameter zipFilePath: Destination NSURL, should lead to a .zip filepath. - parameter password: Password string. Optional. - parameter compression: Compression strategy - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if zipping fails. - notes: Supports implicit progress composition */ public class func zipFiles(paths: [URL], zipFilePath: URL, password: String?, compression: ZipCompression = .DefaultCompression, progress: ((_ progress: Double) -> ())?) throws { // File manager let fileManager = FileManager.default // Check whether a zip file exists at path. let destinationPath = zipFilePath.path // Process zip paths let processedPaths = ZipUtilities().processZipPaths(paths) // Zip set up let chunkSize: Int = 16384 // Progress handler set up var currentPosition: Double = 0.0 var totalSize: Double = 0.0 // Get totalSize for progress handler for path in processedPaths { do { let filePath = path.filePath() let fileAttributes = try fileManager.attributesOfItem(atPath: filePath) let fileSize = fileAttributes[FileAttributeKey.size] as? Double if let fileSize = fileSize { totalSize += fileSize } } catch {} } let progressTracker = Progress(totalUnitCount: Int64(totalSize)) progressTracker.isCancellable = false progressTracker.isPausable = false progressTracker.kind = ProgressKind.file // Begin Zipping let zip = zipOpen(destinationPath, APPEND_STATUS_CREATE) for path in processedPaths { let filePath = path.filePath() var isDirectory: ObjCBool = false _ = fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory) if !isDirectory.boolValue { let input = fopen(filePath, "r") if input == nil { throw ZipError.zipFail } let fileName = path.fileName var zipInfo: zip_fileinfo = zip_fileinfo(tmz_date: tm_zip(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0), dosDate: 0, internal_fa: 0, external_fa: 0) do { let fileAttributes = try fileManager.attributesOfItem(atPath: filePath) if let fileDate = fileAttributes[FileAttributeKey.modificationDate] as? Date { let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fileDate) zipInfo.tmz_date.tm_sec = UInt32(components.second!) zipInfo.tmz_date.tm_min = UInt32(components.minute!) zipInfo.tmz_date.tm_hour = UInt32(components.hour!) zipInfo.tmz_date.tm_mday = UInt32(components.day!) zipInfo.tmz_date.tm_mon = UInt32(components.month!) - 1 zipInfo.tmz_date.tm_year = UInt32(components.year!) } if let fileSize = fileAttributes[FileAttributeKey.size] as? Double { currentPosition += fileSize } } catch {} let buffer = malloc(chunkSize) if let password = password, let fileName = fileName { zipOpenNewFileInZip3(zip, fileName, &zipInfo, nil, 0, nil, 0, nil,Z_DEFLATED, compression.minizipCompression, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password, 0) } else if let fileName = fileName { zipOpenNewFileInZip3(zip, fileName, &zipInfo, nil, 0, nil, 0, nil,Z_DEFLATED, compression.minizipCompression, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, nil, 0) } else { throw ZipError.zipFail } var length: Int = 0 while (feof(input) == 0) { length = fread(buffer, 1, chunkSize, input) zipWriteInFileInZip(zip, buffer, UInt32(length)) } // Update progress handler, only if progress is not 1, because // if we call it when progress == 1, the user will receive // a progress handler call with value 1.0 twice. if let progressHandler = progress, currentPosition / totalSize != 1 { progressHandler(currentPosition/totalSize) } progressTracker.completedUnitCount = Int64(currentPosition) zipCloseFileInZip(zip) if let buffer = buffer { free(buffer) } fclose(input) } } zipClose(zip, nil) // Completed. Update progress handler. if let progressHandler = progress{ progressHandler(1.0) } progressTracker.completedUnitCount = Int64(totalSize) } /** Zip data in memory. - parameter archiveFiles:Array of Archive Files. - parameter zipFilePath: Destination NSURL, should lead to a .zip filepath. - parameter password: Password string. Optional. - parameter compression: Compression strategy - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if zipping fails. - notes: Supports implicit progress composition */ public class func zipData(archiveFiles:[ArchiveFile], zipFilePath:URL, password: String?, compression: ZipCompression = .DefaultCompression, progress: ((_ progress: Double) -> ())?) throws { let destinationPath = zipFilePath.path // Progress handler set up var currentPosition: Int = 0 var totalSize: Int = 0 for archiveFile in archiveFiles { totalSize += archiveFile.data.length } let progressTracker = Progress(totalUnitCount: Int64(totalSize)) progressTracker.isCancellable = false progressTracker.isPausable = false progressTracker.kind = ProgressKind.file // Begin Zipping let zip = zipOpen(destinationPath, APPEND_STATUS_CREATE) for archiveFile in archiveFiles { // Skip empty data if archiveFile.data.length == 0 { continue } // Setup the zip file info var zipInfo = zip_fileinfo(tmz_date: tm_zip(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0), dosDate: 0, internal_fa: 0, external_fa: 0) if let modifiedTime = archiveFile.modifiedTime { let calendar = Calendar.current zipInfo.tmz_date.tm_sec = UInt32(calendar.component(.second, from: modifiedTime)) zipInfo.tmz_date.tm_min = UInt32(calendar.component(.minute, from: modifiedTime)) zipInfo.tmz_date.tm_hour = UInt32(calendar.component(.hour, from: modifiedTime)) zipInfo.tmz_date.tm_mday = UInt32(calendar.component(.day, from: modifiedTime)) zipInfo.tmz_date.tm_mon = UInt32(calendar.component(.month, from: modifiedTime)) zipInfo.tmz_date.tm_year = UInt32(calendar.component(.year, from: modifiedTime)) } // Write the data as a file to zip zipOpenNewFileInZip3(zip, archiveFile.filename, &zipInfo, nil, 0, nil, 0, nil, Z_DEFLATED, compression.minizipCompression, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password, 0) zipWriteInFileInZip(zip, archiveFile.data.bytes, UInt32(archiveFile.data.length)) zipCloseFileInZip(zip) // Update progress handler currentPosition += archiveFile.data.length if let progressHandler = progress{ progressHandler((Double(currentPosition/totalSize))) } progressTracker.completedUnitCount = Int64(currentPosition) } zipClose(zip, nil) // Completed. Update progress handler. if let progressHandler = progress{ progressHandler(1.0) } progressTracker.completedUnitCount = Int64(totalSize) } }
38.835729
220
0.56136
8a63981107e2e7499450f1fcf012fac32e837f55
1,834
// // ZLUserTableViewCellData.swift // ZLGitHubClient // // Created by 朱猛 on 2020/5/9. // Copyright © 2020 ZM. All rights reserved. // import UIKit class ZLUserTableViewCellData: ZLGithubItemTableViewCellData { let userModel : ZLGithubUserModel weak var cell : ZLUserTableViewCell? init(userModel : ZLGithubUserModel){ self.userModel = userModel super.init() } override func bindModel(_ targetModel: Any?, andView targetView: UIView) { guard let cell : ZLUserTableViewCell = targetView as? ZLUserTableViewCell else { return } self.cell = cell cell.fillWithData(data: self) cell.delegate = self } override func getCellHeight() -> CGFloat { return UITableView.automaticDimension } override func getCellReuseIdentifier() -> String { return "ZLUserTableViewCell" } override func onCellSingleTap() { if let userInfoVC = ZLUIRouter.getUserInfoViewController(loginName:self.userModel.loginName ?? ""){ userInfoVC.hidesBottomBarWhenPushed = true self.viewController?.navigationController?.pushViewController(userInfoVC, animated: true) } } } extension ZLUserTableViewCellData:ZLUserTableViewCellDelegate{ func getName() -> String? { return self.userModel.name } func getLoginName() -> String? { return self.userModel.loginName } func getAvatarUrl() -> String? { return self.userModel.avatar_url } func getCompany() -> String? { return self.userModel.company } func getLocation() -> String? { return self.userModel.location } func desc() -> String? { return self.userModel.bio } }
23.818182
107
0.627045
d768a5f1aa801c974844778d2db36dd2132acdb0
218
public extension Svg { static var gitPullRequest: Svg { .icon([ Circle(cx: 18, cy: 18, r: 3), Circle(cx: 6, cy: 6, r: 3), Path("M13 6h3a2 2 0 0 1 2 2v7"), Line(x1: 6, y1: 9, x2: 6, y2: 21), ]) } }
19.818182
37
0.527523
9cac2b77ddedf02a1acac660c5bc481dc4281ffe
719
// // FriendRequestCreated.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation open class FriendRequestCreated: Codable { public var id: Int64 public init(id: Int64) { self.id = id } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: String.self) try container.encode(id, forKey: "id") } // Decodable protocol methods public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) id = try container.decode(Int64.self, forKey: "id") } }
17.536585
67
0.649513
62214e83ec479405c32d7d23229917e71180bf89
575
// // CGColorExtensions.swift // SwifterSwift // // Created by Omar Albeik on 03/02/2017. // Copyright © 2017 SwifterSwift // #if canImport(CoreGraphics) import CoreGraphics #if canImport(UIKit) import UIKit #endif #if canImport(Cocoa) import Cocoa #endif // MARK: - Properties public extension CGColor { #if canImport(UIKit) /// SwifterSwift: UIColor. public var uiColor: UIColor? { return UIColor(cgColor: self) } #endif #if canImport(Cocoa) /// SwifterSwift: NSColor. public var nsColor: NSColor? { return NSColor(cgColor: self) } #endif } #endif
14.74359
41
0.709565
64cfea4d9fb0f80e4ac33d6c5d2fffbe1be417b6
49,471
import XCTest import GRDB private struct A: TableRecord, FetchableRecord, Decodable, Equatable { var cola1: Int64 var cola2: String } private struct B: TableRecord, FetchableRecord, Decodable, Equatable, Hashable { var colb1: Int64 var colb2: Int64? var colb3: String } private struct C: TableRecord, FetchableRecord, Decodable, Equatable { var colc1: Int64 var colc2: Int64 } private struct D: TableRecord, FetchableRecord, Decodable, Equatable { var cold1: Int64 var cold2: Int64? var cold3: String } class AssociationPrefetchingCodableRecordTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") t.column("cola2", .text) } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("colb1") t.column("colb2", .integer).references("a") t.column("colb3", .text) } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("colc1") t.column("colc2", .integer).references("a") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("cold1") t.column("cold2", .integer).references("c") t.column("cold3", .text) } try db.execute( sql: """ INSERT INTO a (cola1, cola2) VALUES (?, ?); INSERT INTO a (cola1, cola2) VALUES (?, ?); INSERT INTO a (cola1, cola2) VALUES (?, ?); INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?); INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?); INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?); INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?); INSERT INTO c (colc1, colc2) VALUES (?, ?); INSERT INTO c (colc1, colc2) VALUES (?, ?); INSERT INTO c (colc1, colc2) VALUES (?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); """, arguments: [ 1, "a1", 2, "a2", 3, "a3", 4, 1, "b1", 5, 1, "b2", 6, 2, "b3", 14, nil, "b4", 7, 1, 8, 2, 9, 2, 10, 7, "d1", 11, 8, "d2", 12, 8, "d3", 13, 9, "d4", 14, nil, "d5", ]) } } func testIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in // Plain request do { let request = A .including(all: A .hasMany(B.self) .orderByPrimaryKey()) .orderByPrimaryKey() // Array do { struct Record: FetchableRecord, Decodable, Equatable { var a: A var bs: [B] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), ]), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), bs: [ B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), ]), Record( a: A(row: ["cola1": 3, "cola2": "a3"]), bs: []), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), ])) } } // Set do { struct Record: FetchableRecord, Decodable, Equatable { var a: A var bs: Set<B> } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), ]), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), bs: [ B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), ]), Record( a: A(row: ["cola1": 3, "cola2": "a3"]), bs: []), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), ])) } } } // Request with filters do { let request = A .filter(Column("cola1") != 3) .including(all: A .hasMany(B.self) .filter(Column("colb1") == 4) .orderByPrimaryKey() .forKey("bs1")) .including(all: A .hasMany(B.self) .filter(Column("colb1") != 4) .orderByPrimaryKey() .forKey("bs2")) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { var a: A var bs1: [B] var bs2: [B] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs1: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), ], bs2: [ B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), ]), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), bs1: [], bs2: [ B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), ]), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), bs1: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), ], bs2: [ B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), ])) } } } } func testIncludingAllHasManyIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in // Plain request do { let request = A .including(all: A .hasMany(C.self) .including(all: C .hasMany(D.self) .orderByPrimaryKey()) .orderByPrimaryKey()) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { struct CInfo: Decodable, Equatable { var c: C var ds: [D] } var a: A var cs: [CInfo] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ Record.CInfo( c: C(row: ["colc1": 7, "colc2": 1]), ds: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), ]), ]), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), cs: [ Record.CInfo( c: C(row: ["colc1": 8, "colc2": 2]), ds: [ D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), ]), Record.CInfo( c: C(row: ["colc1": 9, "colc2": 2]), ds: [ D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"]), ]), ]), Record( a: A(row: ["cola1": 3, "cola2": "a3"]), cs: []), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ Record.CInfo( c: C(row: ["colc1": 7, "colc2": 1]), ds: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), ]), ])) } } // Request with avoided prefetch do { let request = A .including(all: A .hasMany(C.self) .none() .including(all: C .hasMany(D.self) .orderByPrimaryKey()) .orderByPrimaryKey()) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { struct CInfo: Decodable, Equatable { var c: C var ds: [D] } var a: A var cs: [CInfo] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: []), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), cs: []), Record( a: A(row: ["cola1": 3, "cola2": "a3"]), cs: []), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [])) } } // Request with filters do { let request = A .filter(Column("cola1") != 3) .including(all: A .hasMany(C.self) .filter(Column("colc1") > 7) .including(all: C .hasMany(D.self) .filter(Column("cold1") == 11) .orderByPrimaryKey() .forKey("ds1")) .including(all: C .hasMany(D.self) .filter(Column("cold1") != 11) .orderByPrimaryKey() .forKey("ds2")) .orderByPrimaryKey() .forKey("cs1")) .including(all: A .hasMany(C.self) .filter(Column("colc1") < 9) .including(all: C .hasMany(D.self) .filter(Column("cold1") == 11) .orderByPrimaryKey() .forKey("ds1")) .including(all: C .hasMany(D.self) .filter(Column("cold1") != 11) .orderByPrimaryKey() .forKey("ds2")) .orderByPrimaryKey() .forKey("cs2")) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { struct CInfo: Decodable, Equatable { var c: C var ds1: [D] var ds2: [D] } var a: A var cs1: [CInfo] var cs2: [CInfo] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ Record.CInfo( c: C(row: ["colc1": 7, "colc2": 1]), ds1: [], ds2: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), ]), ]), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), cs1: [ Record.CInfo( c: C(row: ["colc1": 8, "colc2": 2]), ds1: [ D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), ], ds2: [ D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), ]), Record.CInfo( c: C(row: ["colc1": 9, "colc2": 2]), ds1: [], ds2: [ D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"]), ]), ], cs2: [ Record.CInfo( c: C(row: ["colc1": 8, "colc2": 2]), ds1: [ D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), ], ds2: [ D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), ]), ]), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ Record.CInfo( c: C(row: ["colc1": 7, "colc2": 1]), ds1: [], ds2: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), ]), ])) } } } } func testIncludingAllHasManyIncludingRequiredOrOptionalHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in // Plain request do { let request = A .including(all: A .hasMany(C.self) .including(required: C .hasMany(D.self) .orderByPrimaryKey()) .orderByPrimaryKey()) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { struct CInfo: Decodable, Equatable { var c: C var d: D } var a: A var cs: [CInfo] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ Record.CInfo( c: C(row: ["colc1": 7, "colc2": 1]), d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"])), ]), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), cs: [ Record.CInfo( c: C(row: ["colc1": 8, "colc2": 2]), d: D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"])), Record.CInfo( c: C(row: ["colc1": 8, "colc2": 2]), d: D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"])), Record.CInfo( c: C(row: ["colc1": 9, "colc2": 2]), d: D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"])), ]), Record( a: A(row: ["cola1": 3, "cola2": "a3"]), cs: []), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ Record.CInfo( c: C(row: ["colc1": 7, "colc2": 1]), d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"])), ])) } } // Request with avoided prefetch do { let request = A .including(all: A .hasMany(C.self) .none() .including(required: C .hasMany(D.self) .orderByPrimaryKey()) .orderByPrimaryKey()) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { struct CInfo: Decodable, Equatable { var c: C var d: D } var a: A var cs: [CInfo] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: []), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), cs: []), Record( a: A(row: ["cola1": 3, "cola2": "a3"]), cs: []), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [])) } } // Request with filters do { let request = A .filter(Column("cola1") != 3) .including(all: A .hasMany(C.self) .filter(Column("colc1") > 7) .including(optional: C .hasMany(D.self) .filter(Column("cold1") == 11) .orderByPrimaryKey() .forKey("ds1")) .including(required: C .hasMany(D.self) .filter(Column("cold1") != 11) .orderByPrimaryKey() .forKey("ds2")) .orderByPrimaryKey() .forKey("cs1")) .including(all: A .hasMany(C.self) .filter(Column("colc1") < 9) .including(optional: C .hasMany(D.self) .filter(Column("cold1") == 11) .orderByPrimaryKey() .forKey("ds1")) .including(required: C .hasMany(D.self) .filter(Column("cold1") != 11) .orderByPrimaryKey() .forKey("ds2")) .orderByPrimaryKey() .forKey("cs2")) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { struct CInfo: Decodable, Equatable { var c: C var d1: D? var d2: D } var a: A var cs1: [CInfo] var cs2: [CInfo] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ Record.CInfo( c: C(row: ["colc1": 7, "colc2": 1]), d1: nil, d2: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"])), ]), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), cs1: [ Record.CInfo( c: C(row: ["colc1": 8, "colc2": 2]), d1: D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), d2: D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"])), Record.CInfo( c: C(row: ["colc1": 9, "colc2": 2]), d1: nil, d2: D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"])), ], cs2: [ Record.CInfo( c: C(row: ["colc1": 8, "colc2": 2]), d1: D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), d2: D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"])), ]), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ Record.CInfo( c: C(row: ["colc1": 7, "colc2": 1]), d1: nil, d2: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"])), ])) } } } } func testIncludingAllHasManyThroughHasManyUsingHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in // Plain request do { let request = A .including(all: A .hasMany(D.self, through: A.hasMany(C.self), using: C.hasMany(D.self)) .orderByPrimaryKey()) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { var a: A var ds: [D] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), ]), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), ds: [ D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"]), ]), Record( a: A(row: ["cola1": 3, "cola2": "a3"]), ds: []), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), ])) } } // Request with filters do { let request = A .filter(Column("cola1") != 3) .including(all: A .hasMany(D.self, through: A.hasMany(C.self).filter(Column("colc1") == 8).forKey("cs1"), using: C.hasMany(D.self)) .orderByPrimaryKey() .forKey("ds1")) .including(all: A .hasMany(D.self, through: A.hasMany(C.self).forKey("cs2"), using: C.hasMany(D.self)) .filter(Column("cold1") != 11) .orderByPrimaryKey() .forKey("ds2")) .including(all: A .hasMany(D.self, through: A.hasMany(C.self).forKey("cs2"), using: C.hasMany(D.self)) .filter(Column("cold1") == 11) .orderByPrimaryKey() .forKey("ds3")) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { var a: A var ds1: [D] var ds2: [D] var ds3: [D] } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds1: [], ds2: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), ], ds3: []), Record( a: A(row: ["cola1": 2, "cola2": "a2"]), ds1: [ D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), ], ds2: [ D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"]), ], ds3: [ D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), ]), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( a: A(row: ["cola1": 1, "cola2": "a1"]), ds1: [], ds2: [ D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), ], ds3: [])) } } } } func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in // Plain request do { let request = B .including(optional: B .belongsTo(A.self) .including(all: A .hasMany(C.self) .orderByPrimaryKey()) ) .orderByPrimaryKey() // Record (nested) do { struct Record: FetchableRecord, Decodable, Equatable { struct AInfo: Decodable, Equatable { var a: A var cs: [C] } var b: B var a: AInfo? } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ C(row: ["colc1": 7, "colc2": 1]), ])), Record( b: B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), a: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ C(row: ["colc1": 7, "colc2": 1]), ])), Record( b: B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), a: Record.AInfo( a: A(row: ["cola1": 2, "cola2": "a2"]), cs: [ C(row: ["colc1": 8, "colc2": 2]), C(row: ["colc1": 9, "colc2": 2]), ])), Record( b: B(row: ["colb1": 14, "colb2": nil, "colb3": "b4"]), a: nil), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ C(row: ["colc1": 7, "colc2": 1]), ]))) } } // Record (flat) do { struct Record: FetchableRecord, Decodable, Equatable { var b: B var a: A? var cs: [C] // not optional } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ C(row: ["colc1": 7, "colc2": 1]), ]), Record( b: B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ C(row: ["colc1": 7, "colc2": 1]), ]), Record( b: B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), a: A(row: ["cola1": 2, "cola2": "a2"]), cs: [ C(row: ["colc1": 8, "colc2": 2]), C(row: ["colc1": 9, "colc2": 2]), ]), Record( b: B(row: ["colb1": 14, "colb2": nil, "colb3": "b4"]), a: nil, cs: []), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a: A(row: ["cola1": 1, "cola2": "a1"]), cs: [ C(row: ["colc1": 7, "colc2": 1]), ])) } } } // Request with filters do { let request = B .including(optional: B .belongsTo(A.self) .filter(Column("cola2") == "a1") .including(all: A .hasMany(C.self) .filter(Column("colc1") == 9) .orderByPrimaryKey() .forKey("cs1")) .including(all: A .hasMany(C.self) .filter(Column("colc1") != 9) .orderByPrimaryKey() .forKey("cs2")) .forKey("a1")) .including(optional: B .belongsTo(A.self) .filter(Column("cola2") == "a2") .including(all: A .hasMany(C.self) .filter(Column("colc1") == 9) .orderByPrimaryKey() .forKey("cs1")) .including(all: A .hasMany(C.self) .filter(Column("colc1") != 9) .orderByPrimaryKey() .forKey("cs2")) .forKey("a2")) .orderByPrimaryKey() struct Record: FetchableRecord, Decodable, Equatable { struct AInfo: Decodable, Equatable { var a: A var cs1: [C] var cs2: [C] } var b: B var a1: AInfo? var a2: AInfo? } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a1: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ C(row: ["colc1": 7, "colc2": 1]), ]), a2: nil), Record( b: B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), a1: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ C(row: ["colc1": 7, "colc2": 1]), ]), a2: nil), Record( b: B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), a1: nil, a2: Record.AInfo( a: A(row: ["cola1": 2, "cola2": "a2"]), cs1: [ C(row: ["colc1": 9, "colc2": 2]), ], cs2: [ C(row: ["colc1": 8, "colc2": 2]), ])), Record( b: B(row: ["colb1": 14, "colb2": nil, "colb3": "b4"]), a1: nil, a2: nil), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), a1: Record.AInfo( a: A(row: ["cola1": 1, "cola2": "a1"]), cs1: [], cs2: [ C(row: ["colc1": 7, "colc2": 1]), ]), a2: nil)) } } } } func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in // Plain request do { let request = D .joining(optional: D .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) .including(all: A .hasMany(B.self) .orderByPrimaryKey())) .orderByPrimaryKey() // Record (flat) do { struct Record: FetchableRecord, Decodable, Equatable { var d: D var bs: [B] // not optional } // Record.fetchAll do { let records = try Record.fetchAll(db, request) XCTAssertEqual(records, [ Record( d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), ]), Record( d: D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), bs: [ B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), ]), Record( d: D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), bs: [ B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), ]), Record( d: D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"]), bs: [ B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), ]), Record( d: D(row: ["cold1": 14, "cold2": nil, "cold3": "d5"]), bs: []), ]) } // Record.fetchOne do { let record = try Record.fetchOne(db, request)! XCTAssertEqual(record, Record( d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), bs: [ B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), ])) } } } } } func testSelfJoin() throws { struct Employee: TableRecord, FetchableRecord, Decodable, Hashable { static let subordinates = hasMany(Employee.self, key: "subordinates") static let manager = belongsTo(Employee.self, key: "manager") var id: Int64 var managerId: Int64? var name: String } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "employee") { t in t.autoIncrementedPrimaryKey("id") t.column("managerId", .integer) .indexed() .references("employee", onDelete: .restrict) t.column("name", .text) } try db.execute(sql: """ INSERT INTO employee (id, managerId, name) VALUES (1, NULL, 'Arthur'); INSERT INTO employee (id, managerId, name) VALUES (2, 1, 'Barbara'); INSERT INTO employee (id, managerId, name) VALUES (3, 1, 'Craig'); INSERT INTO employee (id, managerId, name) VALUES (4, 2, 'David'); INSERT INTO employee (id, managerId, name) VALUES (5, NULL, 'Eve'); """) struct EmployeeInfo: FetchableRecord, Decodable, Equatable { var employee: Employee var manager: Employee? var subordinates: Set<Employee> } let request = Employee .including(optional: Employee.manager) .including(all: Employee.subordinates) .orderByPrimaryKey() let employeeInfos: [EmployeeInfo] = try EmployeeInfo.fetchAll(db, request) XCTAssertEqual(employeeInfos, [ EmployeeInfo( employee: Employee(id: 1, managerId: nil, name: "Arthur"), manager: nil, subordinates: [ Employee(id: 2, managerId: 1, name: "Barbara"), Employee(id: 3, managerId: 1, name: "Craig"), ]), EmployeeInfo( employee: Employee(id: 2, managerId: 1, name: "Barbara"), manager: Employee(id: 1, managerId: nil, name: "Arthur"), subordinates: [ Employee(id: 4, managerId: 2, name: "David"), ]), EmployeeInfo( employee: Employee(id: 3, managerId: 1, name: "Craig"), manager: Employee(id: 1, managerId: nil, name: "Arthur"), subordinates: []), EmployeeInfo( employee: Employee(id: 4, managerId: 2, name: "David"), manager: Employee(id: 2, managerId: 1, name: "Barbara"), subordinates: []), EmployeeInfo( employee: Employee(id: 5, managerId: nil, name: "Eve"), manager: nil, subordinates: []), ]) } } }
43.130776
137
0.292434
1d0aefaa6f1160c539ed2e37eb20009e857b4440
319
// // ViewController.swift // Valine // // Created by xu on 2020/7/2. // Copyright © 2020 xaoxuu.com. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
15.190476
58
0.648903
0ed7077e9b5ce31c7c008bd902e89e405b0db16a
27,513
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Dispatch #if SQLITE_SWIFT_STANDALONE import sqlite3 #elseif SQLITE_SWIFT_SQLCIPHER import SQLCipher #elseif os(Linux) import CSQLite #else import SQLite3 #endif /// A connection to SQLite. public final class SQLConnection { /// The location of a SQLite database. public enum SQLLocation { /// An in-memory database (equivalent to `.uri(":memory:")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#sharedmemdb> case inMemory /// A temporary, file-backed database (equivalent to `.uri("")`). /// /// See: <https://www.sqlite.org/inmemorydb.html#temp_db> case temporary /// A database located at the given URI filename (or path). /// /// See: <https://www.sqlite.org/uri.html> /// /// - Parameter filename: A URI filename case uri(String) } /// An SQL operation passed to update callbacks. public enum SQLOperation { /// An INSERT operation. case insert /// An UPDATE operation. case update /// A DELETE operation. case delete fileprivate init(rawValue:Int32) { switch rawValue { case SQLITE_INSERT: self = .insert case SQLITE_UPDATE: self = .update case SQLITE_DELETE: self = .delete default: fatalError("unhandled operation code: \(rawValue)") } } } public var handle: OpaquePointer { return _handle! } fileprivate var _handle: OpaquePointer? = nil /// Initializes a new SQLite connection. /// /// - Parameters: /// /// - location: The location of the database. Creates a new database if it /// doesn’t already exist (unless in read-only mode). /// /// Default: `.inMemory`. /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Returns: A new database connection. public init(_ location: SQLLocation = .inMemory, readonly: Bool = false) throws { let flags = readonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE try check(sqlite3_open_v2(location.description, &_handle, flags | SQLITE_OPEN_FULLMUTEX, nil)) queue.setSpecific(key: SQLConnection.queueKey, value: queueContext) } /// Initializes a new connection to a database. /// /// - Parameters: /// /// - filename: The location of the database. Creates a new database if /// it doesn’t already exist (unless in read-only mode). /// /// - readonly: Whether or not to open the database in a read-only state. /// /// Default: `false`. /// /// - Throws: `Result.Error` iff a connection cannot be established. /// /// - Returns: A new database connection. public convenience init(_ filename: String, readonly: Bool = false) throws { try self.init(.uri(filename), readonly: readonly) } deinit { sqlite3_close(handle) } // MARK: - /// Whether or not the database was opened in a read-only state. public var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 } /// The last rowid inserted into the database via this connection. public var lastInsertRowid: Int64 { return sqlite3_last_insert_rowid(handle) } /// The last number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var changes: Int { return Int(sqlite3_changes(handle)) } /// The total number of changes (inserts, updates, or deletes) made to the /// database via this connection. public var totalChanges: Int { return Int(sqlite3_total_changes(handle)) } // MARK: - Execute /// Executes a batch of SQL statements. /// /// - Parameter SQL: A batch of zero or more semicolon-separated SQL /// statements. /// /// - Throws: `Result.Error` if query execution fails. public func execute(_ SQL: String) throws { _ = try sync { try self.check(sqlite3_exec(self.handle, SQL, nil, nil, nil)) } } // MARK: - Prepare /// Prepares a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. public func prepare(_ statement: String, _ bindings: SQLBinding?...) throws -> SQLStatement { if !bindings.isEmpty { return try prepare(statement, bindings) } return try SQLStatement(self, statement) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: A prepared statement. public func prepare(_ statement: String, _ bindings: [SQLBinding?]) throws -> SQLStatement { return try prepare(statement).bind(bindings) } /// Prepares a single SQL statement and binds parameters to it. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: A prepared statement. public func prepare(_ statement: String, _ bindings: [String: SQLBinding?]) throws -> SQLStatement { return try prepare(statement).bind(bindings) } // MARK: - Run /// Runs a single SQL statement (with optional parameter bindings). /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. @discardableResult public func run(_ statement: String, _ bindings: SQLBinding?...) throws -> SQLStatement { return try run(statement, bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. @discardableResult public func run(_ statement: String, _ bindings: [SQLBinding?]) throws -> SQLStatement { return try prepare(statement).run(bindings) } /// Prepares, binds, and runs a single SQL statement. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Throws: `Result.Error` if query execution fails. /// /// - Returns: The statement. @discardableResult public func run(_ statement: String, _ bindings: [String: SQLBinding?]) throws -> SQLStatement { return try prepare(statement).run(bindings) } // MARK: - Scalar /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ statement: String, _ bindings: SQLBinding?...) throws -> SQLBinding? { return try scalar(statement, bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A list of parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ statement: String, _ bindings: [SQLBinding?]) throws -> SQLBinding? { return try prepare(statement).scalar(bindings) } /// Runs a single SQL statement (with optional parameter bindings), /// returning the first value of the first row. /// /// - Parameters: /// /// - statement: A single SQL statement. /// /// - bindings: A dictionary of named parameters to bind to the statement. /// /// - Returns: The first value of the first row returned. public func scalar(_ statement: String, _ bindings: [String: SQLBinding?]) throws -> SQLBinding? { return try prepare(statement).scalar(bindings) } // MARK: - Transactions /// The mode in which a transaction acquires a lock. public enum TransactionMode : String { /// Defers locking the database till the first read/write executes. case deferred = "DEFERRED" /// Immediately acquires a reserved lock on the database. case immediate = "IMMEDIATE" /// Immediately acquires an exclusive lock on all databases. case exclusive = "EXCLUSIVE" } // TODO: Consider not requiring a throw to roll back? /// Runs a transaction with the given mode. /// /// - Note: Transactions cannot be nested. To nest transactions, see /// `savepoint()`, instead. /// /// - Parameters: /// /// - mode: The mode in which a transaction acquires a lock. /// /// Default: `.deferred` /// /// - block: A closure to run SQL statements within the transaction. /// The transaction will be committed when the block returns. The block /// must throw to roll the transaction back. /// /// - Throws: `Result.Error`, and rethrows. public func transaction(_ mode: TransactionMode = .deferred, block: () throws -> Void) throws { try transaction("BEGIN \(mode.rawValue) TRANSACTION", block, "COMMIT TRANSACTION", or: "ROLLBACK TRANSACTION") } // TODO: Consider not requiring a throw to roll back? // TODO: Consider removing ability to set a name? /// Runs a transaction with the given savepoint name (if omitted, it will /// generate a UUID). /// /// - SeeAlso: `transaction()`. /// /// - Parameters: /// /// - savepointName: A unique identifier for the savepoint (optional). /// /// - block: A closure to run SQL statements within the transaction. /// The savepoint will be released (committed) when the block returns. /// The block must throw to roll the savepoint back. /// /// - Throws: `SQLite.Result.Error`, and rethrows. public func savepoint(_ name: String = UUID().uuidString, block: () throws -> Void) throws { let name = name.quote("'") let savepoint = "SAVEPOINT \(name)" try transaction(savepoint, block, "RELEASE \(savepoint)", or: "ROLLBACK TO \(savepoint)") } fileprivate func transaction(_ begin: String, _ block: () throws -> Void, _ commit: String, or rollback: String) throws { return try sync { try self.run(begin) do { try block() try self.run(commit) } catch { try self.run(rollback) throw error } } } /// Interrupts any long-running queries. public func interrupt() { sqlite3_interrupt(handle) } // MARK: - Handlers /// The number of seconds a connection will attempt to retry a statement /// after encountering a busy signal (lock). public var busyTimeout: Double = 0 { didSet { sqlite3_busy_timeout(handle, Int32(busyTimeout * 1_000)) } } /// Sets a handler to call after encountering a busy signal (lock). /// /// - Parameter callback: This block is executed during a lock in which a /// busy error would otherwise be returned. It’s passed the number of /// times it’s been called for this lock. If it returns `true`, it will /// try again. If it returns `false`, no further attempts will be made. public func busyHandler(_ callback: ((_ tries: Int) -> Bool)?) { guard let callback = callback else { sqlite3_busy_handler(handle, nil, nil) busyHandler = nil return } let box: BusyHandler = { callback(Int($0)) ? 1 : 0 } sqlite3_busy_handler(handle, { callback, tries in unsafeBitCast(callback, to: BusyHandler.self)(tries) }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self)) busyHandler = box } fileprivate typealias BusyHandler = @convention(block) (Int32) -> Int32 fileprivate var busyHandler: BusyHandler? /// Sets a handler to call when a statement is executed with the compiled /// SQL. /// /// - Parameter callback: This block is invoked when a statement is executed /// with the compiled SQL as its argument. /// /// db.trace { SQL in print(SQL) } public func trace(_ callback: ((String) -> Void)?) { #if SQLITE_SWIFT_SQLCIPHER || os(Linux) trace_v1(callback) #else if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { trace_v2(callback) } else { trace_v1(callback) } #endif } fileprivate func trace_v1(_ callback: ((String) -> Void)?) { guard let callback = callback else { sqlite3_trace(handle, nil /* xCallback */, nil /* pCtx */) trace = nil return } let box: Trace = { (pointer: UnsafeRawPointer) in callback(String(cString: pointer.assumingMemoryBound(to: UInt8.self))) } sqlite3_trace(handle, { (C: UnsafeMutableRawPointer?, SQL: UnsafePointer<Int8>?) in if let C = C, let SQL = SQL { unsafeBitCast(C, to: Trace.self)(SQL) } }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self) ) trace = box } fileprivate typealias Trace = @convention(block) (UnsafeRawPointer) -> Void fileprivate var trace: Trace? /// Registers a callback to be invoked whenever a row is inserted, updated, /// or deleted in a rowid table. /// /// - Parameter callback: A callback invoked with the `Operation` (one of /// `.Insert`, `.Update`, or `.Delete`), database name, table name, and /// rowid. public func updateHook(_ callback: ((_ operation: SQLOperation, _ db: String, _ table: String, _ rowid: Int64) -> Void)?) { guard let callback = callback else { sqlite3_update_hook(handle, nil, nil) updateHook = nil return } let box: UpdateHook = { callback( SQLOperation(rawValue: $0), String(cString: $1), String(cString: $2), $3 ) } sqlite3_update_hook(handle, { callback, operation, db, table, rowid in unsafeBitCast(callback, to: UpdateHook.self)(operation, db!, table!, rowid) }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self)) updateHook = box } fileprivate typealias UpdateHook = @convention(block) (Int32, UnsafePointer<Int8>, UnsafePointer<Int8>, Int64) -> Void fileprivate var updateHook: UpdateHook? /// Registers a callback to be invoked whenever a transaction is committed. /// /// - Parameter callback: A callback invoked whenever a transaction is /// committed. If this callback throws, the transaction will be rolled /// back. public func commitHook(_ callback: (() throws -> Void)?) { guard let callback = callback else { sqlite3_commit_hook(handle, nil, nil) commitHook = nil return } let box: CommitHook = { do { try callback() } catch { return 1 } return 0 } sqlite3_commit_hook(handle, { callback in unsafeBitCast(callback, to: CommitHook.self)() }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self)) commitHook = box } fileprivate typealias CommitHook = @convention(block) () -> Int32 fileprivate var commitHook: CommitHook? /// Registers a callback to be invoked whenever a transaction rolls back. /// /// - Parameter callback: A callback invoked when a transaction is rolled /// back. public func rollbackHook(_ callback: (() -> Void)?) { guard let callback = callback else { sqlite3_rollback_hook(handle, nil, nil) rollbackHook = nil return } let box: RollbackHook = { callback() } sqlite3_rollback_hook(handle, { callback in unsafeBitCast(callback, to: RollbackHook.self)() }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self)) rollbackHook = box } fileprivate typealias RollbackHook = @convention(block) () -> Void fileprivate var rollbackHook: RollbackHook? /// Creates or redefines a custom SQL function. /// /// - Parameters: /// /// - function: The name of the function to create or redefine. /// /// - argumentCount: The number of arguments that the function takes. If /// `nil`, the function may take any number of arguments. /// /// Default: `nil` /// /// - deterministic: Whether or not the function is deterministic (_i.e._ /// the function always returns the same result for a given input). /// /// Default: `false` /// /// - block: A block of code to run when the function is called. The block /// is called with an array of raw SQL values mapped to the function’s /// parameters and should return a raw SQL value (or nil). public func createFunction(_ function: String, argumentCount: UInt? = nil, deterministic: Bool = false, _ block: @escaping (_ args: [SQLBinding?]) -> SQLBinding?) { let argc = argumentCount.map { Int($0) } ?? -1 let box: Function = { context, argc, argv in let arguments: [SQLBinding?] = (0..<Int(argc)).map { idx in let value = argv![idx] switch sqlite3_value_type(value) { case SQLITE_BLOB: return SQLBlob(bytes: sqlite3_value_blob(value), length: Int(sqlite3_value_bytes(value))) case SQLITE_FLOAT: return sqlite3_value_double(value) case SQLITE_INTEGER: return sqlite3_value_int64(value) case SQLITE_NULL: return nil case SQLITE_TEXT: return String(cString: UnsafePointer(sqlite3_value_text(value))) case let type: fatalError("unsupported value type: \(type)") } } let result = block(arguments) if let result = result as? SQLBlob { sqlite3_result_blob(context, result.bytes, Int32(result.bytes.count), nil) } else if let result = result as? Double { sqlite3_result_double(context, result) } else if let result = result as? Int64 { sqlite3_result_int64(context, result) } else if let result = result as? String { sqlite3_result_text(context, result, Int32(result.count), SQLITE_TRANSIENT) } else if result == nil { sqlite3_result_null(context) } else { fatalError("unsupported result type: \(String(describing: result))") } } var flags = SQLITE_UTF8 #if !os(Linux) if deterministic { flags |= SQLITE_DETERMINISTIC } #endif sqlite3_create_function_v2(handle, function, Int32(argc), flags, unsafeBitCast(box, to: UnsafeMutableRawPointer.self), { context, argc, value in let function = unsafeBitCast(sqlite3_user_data(context), to: Function.self) function(context, argc, value) }, nil, nil, nil) if functions[function] == nil { self.functions[function] = [:] } functions[function]?[argc] = box } fileprivate typealias Function = @convention(block) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void fileprivate var functions = [String: [Int: Function]]() /// Defines a new collating sequence. /// /// - Parameters: /// /// - collation: The name of the collation added. /// /// - block: A collation function that takes two strings and returns the /// comparison result. public func createCollation(_ collation: String, _ block: @escaping (_ lhs: String, _ rhs: String) -> ComparisonResult) throws { let box: Collation = { (lhs: UnsafeRawPointer, rhs: UnsafeRawPointer) in let lstr = String(cString: lhs.assumingMemoryBound(to: UInt8.self)) let rstr = String(cString: rhs.assumingMemoryBound(to: UInt8.self)) return Int32(block(lstr, rstr).rawValue) } try check(sqlite3_create_collation_v2(handle, collation, SQLITE_UTF8, unsafeBitCast(box, to: UnsafeMutableRawPointer.self), { (callback: UnsafeMutableRawPointer?, _, lhs: UnsafeRawPointer?, _, rhs: UnsafeRawPointer?) in /* xCompare */ if let lhs = lhs, let rhs = rhs { return unsafeBitCast(callback, to: Collation.self)(lhs, rhs) } else { fatalError("sqlite3_create_collation_v2 callback called with NULL pointer") } }, nil /* xDestroy */)) collations[collation] = box } fileprivate typealias Collation = @convention(block) (UnsafeRawPointer, UnsafeRawPointer) -> Int32 fileprivate var collations = [String: Collation]() // MARK: - Error Handling func sync<T>(_ block: () throws -> T) rethrows -> T { if DispatchQueue.getSpecific(key: SQLConnection.queueKey) == queueContext { return try block() } else { return try queue.sync(execute: block) } } @discardableResult func check(_ resultCode: Int32, statement: SQLStatement? = nil) throws -> Int32 { guard let error = Result(errorCode: resultCode, connection: self, statement: statement) else { return resultCode } throw error } fileprivate var queue = DispatchQueue(label: "SQLite.Database", attributes: []) fileprivate static let queueKey = DispatchSpecificKey<Int>() fileprivate lazy var queueContext: Int = unsafeBitCast(self, to: Int.self) } extension SQLConnection : CustomStringConvertible { public var description: String { return String(cString: sqlite3_db_filename(handle, nil)) } } extension SQLConnection.SQLLocation : CustomStringConvertible { public var description: String { switch self { case .inMemory: return ":memory:" case .temporary: return "" case .uri(let URI): return URI } } } public enum Result : Error { fileprivate static let successCodes: Set = [SQLITE_OK, SQLITE_ROW, SQLITE_DONE] /// Represents a SQLite specific [error code](https://sqlite.org/rescode.html) /// /// - message: English-language text that describes the error /// /// - code: SQLite [error code](https://sqlite.org/rescode.html#primary_result_code_list) /// /// - statement: the statement which produced the error case error(message: String, code: Int32, statement: SQLStatement?) init?(errorCode: Int32, connection: SQLConnection, statement: SQLStatement? = nil) { guard !Result.successCodes.contains(errorCode) else { return nil } let message = String(cString: sqlite3_errmsg(connection.handle)) self = .error(message: message, code: errorCode, statement: statement) } } extension Result : CustomStringConvertible { public var description: String { switch self { case let .error(message, errorCode, statement): if let statement = statement { return "\(message) (\(statement)) (code: \(errorCode))" } else { return "\(message) (code: \(errorCode))" } } } } #if !SQLITE_SWIFT_SQLCIPHER && !os(Linux) @available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) extension SQLConnection { fileprivate func trace_v2(_ callback: ((String) -> Void)?) { guard let callback = callback else { // If the X callback is NULL or if the M mask is zero, then tracing is disabled. sqlite3_trace_v2(handle, 0 /* mask */, nil /* xCallback */, nil /* pCtx */) trace = nil return } let box: Trace = { (pointer: UnsafeRawPointer) in callback(String(cString: pointer.assumingMemoryBound(to: UInt8.self))) } sqlite3_trace_v2(handle, UInt32(SQLITE_TRACE_STMT) /* mask */, { // A trace callback is invoked with four arguments: callback(T,C,P,X). // The T argument is one of the SQLITE_TRACE constants to indicate why the // callback was invoked. The C argument is a copy of the context pointer. // The P and X arguments are pointers whose meanings depend on T. (T: UInt32, C: UnsafeMutableRawPointer?, P: UnsafeMutableRawPointer?, X: UnsafeMutableRawPointer?) in if let P = P, let expandedSQL = sqlite3_expanded_sql(OpaquePointer(P)) { unsafeBitCast(C, to: Trace.self)(expandedSQL) sqlite3_free(expandedSQL) } return Int32(0) // currently ignored }, unsafeBitCast(box, to: UnsafeMutableRawPointer.self) /* pCtx */ ) trace = box } } #endif
36.635153
168
0.605387
5da98dd83810cf5d379dd9dfb7093ab028eda6aa
2,695
// // RomPickerViewController.swift // Chip8tvOS // // Created by Ryan Grey on 20/02/2021. // import Foundation import UIKit import Chip8Emulator class RomPickerViewController: UIViewController { @IBOutlet weak var romTableView: UITableView! private lazy var platformInputMappingService: TVInputMappingService = { return TVInputMappingService() }() private lazy var supportedRomService: PlatformSupportedRomService = { return PlatformSupportedRomService(inputMappingService: platformInputMappingService) }() private lazy var inputMapper: InputMapper<TVInputMappingService> = { return InputMapper(platformInputMappingService: platformInputMappingService) }() override func viewDidLoad() { super.viewDidLoad() romTableView.dataSource = self romTableView.delegate = self } private func navigateToChip8ViewController(with romName: RomName) { let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) let chip8ViewController = storyboard.instantiateViewController(identifier: "chip8ViewController") as! Chip8ViewController chip8ViewController.romName = romName chip8ViewController.inputMapper = self.inputMapper present(chip8ViewController, animated: true) } } extension RomPickerViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let roms = supportedRomService.supportedRoms return roms.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: RomCell.identifier, for: indexPath) as! RomCell let romName = supportedRomService.supportedRoms[indexPath.row] cell.romLabel.text = romName.rawValue return cell } } extension RomPickerViewController: UITableViewDelegate { override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { if let nextFocusedCell = context.nextFocusedView as? RomCell{ nextFocusedCell.backgroundColor = .white nextFocusedCell.romLabel.textColor = .black } if let previousFocusedCell = context.previouslyFocusedView as? RomCell{ previousFocusedCell.backgroundColor = .clear previousFocusedCell.romLabel.textColor = .white } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let romName = supportedRomService.supportedRoms[indexPath.row] navigateToChip8ViewController(with: romName) } }
35.933333
129
0.732839
613d9fd3fda22d2eac212d2ef277417fad624f99
3,393
// // JXSegmentedIndicatorBackgroundView.swift // JXSegmentedView // // Created by jiaxin on 2018/12/28. // Copyright © 2018 jiaxin. All rights reserved. // import UIKit /// 不支持indicatorPosition、verticalOffset。默认垂直居中。 open class JXSegmentedIndicatorBackgroundView: JXSegmentedIndicatorBaseView { @available(*, deprecated, renamed: "indicatorWidthIncrement") open var backgroundWidthIncrement: CGFloat = 20 { didSet { indicatorWidthIncrement = backgroundWidthIncrement } } open override func commonInit() { super.commonInit() indicatorWidthIncrement = 20 indicatorHeight = 26 indicatorColor = .lightGray } open override func refreshIndicatorState(model: JXSegmentedIndicatorSelectedParams) { super.refreshIndicatorState(model: model) backgroundColor = indicatorColor layer.cornerRadius = getIndicatorCornerRadius(itemFrame: model.currentSelectedItemFrame) let width = getIndicatorWidth(itemFrame: model.currentSelectedItemFrame, itemContentWidth: model.currentItemContentWidth) let height = getIndicatorHeight(itemFrame: model.currentSelectedItemFrame) let x = model.currentSelectedItemFrame.origin.x + (model.currentSelectedItemFrame.size.width - width)/2 let y = (model.currentSelectedItemFrame.size.height - height)/2 frame = CGRect(x: x, y: y, width: width, height: height) } open override func contentScrollViewDidScroll(model: JXSegmentedIndicatorTransitionParams) { super.contentScrollViewDidScroll(model: model) guard canHandleTransition(model: model) else { return } let rightItemFrame = model.rightItemFrame let leftItemFrame = model.leftItemFrame let percent = model.percent var targetWidth = getIndicatorWidth(itemFrame: leftItemFrame, itemContentWidth: model.leftItemContentWidth) let leftWidth = targetWidth let rightWidth = getIndicatorWidth(itemFrame: rightItemFrame, itemContentWidth: model.rightItemContentWidth) let leftX = leftItemFrame.origin.x + (leftItemFrame.size.width - leftWidth)/2 let rightX = rightItemFrame.origin.x + (rightItemFrame.size.width - rightWidth)/2 let targetX = JXSegmentedViewTool.interpolate(from: leftX, to: rightX, percent: CGFloat(percent)) if indicatorWidth == JXSegmentedViewAutomaticDimension { targetWidth = JXSegmentedViewTool.interpolate(from: leftWidth, to: rightWidth, percent: CGFloat(percent)) } self.frame.origin.x = targetX self.frame.size.width = targetWidth } open override func selectItem(model: JXSegmentedIndicatorSelectedParams) { super.selectItem(model: model) let width = getIndicatorWidth(itemFrame: model.currentSelectedItemFrame, itemContentWidth: model.currentItemContentWidth) var toFrame = self.frame toFrame.origin.x = model.currentSelectedItemFrame.origin.x + (model.currentSelectedItemFrame.size.width - width)/2 toFrame.size.width = width if canSelectedWithAnimation(model: model) { UIView.animate(withDuration: scrollAnimationDuration, delay: 0, options: .curveEaseOut, animations: { self.frame = toFrame }) { (_) in } }else { frame = toFrame } } }
40.879518
129
0.705865
fc21238b432b4ed7ef8ebf10cce5c5c32254d0b5
240
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { struct B { var b = 1 a { } class a { struct B { func a<H : a
18.461538
87
0.708333
50e071b052615daa2fa627d436bfd50851bcfb81
2,755
//: [Previous](@previous) //: For this page, make sure your build target is set to ParseSwift (macOS) and targeting //: `My Mac` or whatever the name of your mac is. Also be sure your `Playground Settings` //: in the `File Inspector` is `Platform = macOS`. This is because //: Keychain in iOS Playgrounds behaves differently. Every page in Playgrounds should //: be set to build for `macOS` unless specified. import PlaygroundSupport import Foundation import ParseSwift PlaygroundPage.current.needsIndefiniteExecution = true initializeParse() struct GameScore: ParseObject { //: These are required by ParseObject. var objectId: String? var createdAt: Date? var updatedAt: Date? var ACL: ParseACL? //: Your own properties. var score: Int? = 0 } //: It's recommended to place custom initializers in an extension //: to preserve the convenience initializer. extension GameScore { //: Custom initializer. init(score: Int) { self.score = score } init(objectId: String?) { self.objectId = objectId } } //: You can have the server do operations on your `ParseObject`'s for you. //: First lets create another GameScore. let savedScore: GameScore! do { savedScore = try GameScore(score: 102).save() } catch { savedScore = nil assertionFailure("Error saving: \(error)") } //: Then we will increment the score. let incrementOperation = savedScore .operation.increment("score", by: 1) incrementOperation.save { result in switch result { case .success: print("Original score: \(String(describing: savedScore)). Check the new score on Parse Dashboard.") case .failure(let error): assertionFailure("Error saving: \(error)") } } //: You can increment the score again syncronously. do { _ = try incrementOperation.save() print("Original score: \(String(describing: savedScore)). Check the new score on Parse Dashboard.") } catch { print(error) } //: You can also remove a value for a property using unset. let unsetOperation = savedScore .operation.unset(("score", \.score)) do { let updatedScore = try unsetOperation.save() print("Updated score: \(updatedScore). Check the new score on Parse Dashboard.") } catch { print(error) } //: There are other operations: set/forceSet/unset/add/remove, etc. objects from `ParseObject`s. //: In fact, the `users` and `roles` relations from `ParseRoles` used the add/remove operations. //: Multiple operations can be chained together. See: //: https://github.com/parse-community/Parse-Swift/pull/268#issuecomment-955714414 let operations = savedScore.operation //: Example: operations.add("hello", objects: ["test"]). PlaygroundPage.current.finishExecution() //: [Next](@next)
29.945652
107
0.7049
e5eac0be4712ba0f51ea370e3eb8e03dfa51b340
5,351
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // DNSCheckerTests.swift // // Created by Joshua Liebowitz on 12/21/21. import Foundation import Nimble import XCTest @testable import RevenueCat class DNSCheckerTests: XCTestCase { let apiURL = URL(string: "https://api.revenuecat.com")! let fakeSubscribersURL1 = URL(string: "https://0.0.0.0/subscribers")! let fakeSubscribersURL2 = URL(string: "https://127.0.0.1/subscribers")! let fakeOffersURL = URL(string: "https://0.0.0.0/offers")! func testResolvedHost() { let host = DNSChecker.resolvedHost(fromURL: apiURL) // swiftlint:disable:next line_length let validIPAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" expect(host!.range(of: validIPAddressRegex, options: .regularExpression)).toNot(beNil()) expect(DNSChecker.invalidHosts.contains(host!)).to(equal(false)) } func testIsBlockedURL() throws { let blockedURLs = ["https://127.0.0.1/subscribers", "https://0.0.0.0/offers"] for urlString in blockedURLs { expect(DNSChecker.isBlockedURL(try XCTUnwrap(URL(string: urlString)))) == true } expect(DNSChecker.isBlockedURL(try XCTUnwrap(URL(string: "https://api.revenuecat.com/offers")))) == false } func testIsBlockedLocalHostFromError() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) let error = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo as Error) let expectedError = DNSError.blocked(failedURL: fakeSubscribersURL2, resolvedHost: "127.0.0.1") expect(expectedError).to(equal(error)) } func testIsBlockedHostIPAPIError() { let userInfo: [String: Any] = [ NSURLErrorFailingURLErrorKey: fakeSubscribersURL1 ] let nsErrorWithUserInfo = NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) expect(DNSChecker.isBlockedAPIError(nsErrorWithUserInfo as Error)) == true let maybeBlockedHostError = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo) expect(maybeBlockedHostError) == DNSError.blocked(failedURL: fakeSubscribersURL1, resolvedHost: "0.0.0.0") } func testWrongErrorCode() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: NSURLErrorDomain, code: -1, userInfo: userInfo as [String: Any]) expect(DNSChecker.isBlockedAPIError(nsErrorWithUserInfo as Error)) == false } func testWrongErrorDomain() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: "FakeDomain", code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) expect(DNSChecker.isBlockedAPIError(nsErrorWithUserInfo as Error)) == false let maybeBlockedError = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo) expect(maybeBlockedError) == nil } func testWrongErrorDomainAndWrongErrorCode() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: "FakeDomain", code: -1, userInfo: userInfo as [String: Any]) let maybeBlockedError = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo) expect(maybeBlockedError) == nil } func testIsOnlyValidForCorrectErrorDomainAnd() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL2] let nsErrorWithUserInfo = NSError(domain: "FakeDomain", code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) let maybeBlockedError = DNSChecker.errorWithBlockedHostFromError(nsErrorWithUserInfo) expect(maybeBlockedError) == nil } func testIsBlockedZerosIPHostAPIError() { let userInfo: [String: Any] = [NSURLErrorFailingURLErrorKey: fakeSubscribersURL1] let nsErrorWithUserInfo = NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotConnectToHost, userInfo: userInfo as [String: Any]) expect(DNSChecker.isBlockedAPIError(nsErrorWithUserInfo as Error)) == true } }
46.530435
142
0.627172
89d330e1b94d314b6dfeb494757c46fbd8af0b2a
1,738
// // ThemeManager+ApplyTheme.swift // Thematic // // Created by Pircate on 08/17/2021. // Copyright (c) 2021 [email protected]. All rights reserved. // import Foundation public extension ThemeManager { /// 当前UI主题 var currentUserInterfaceTheme: UserInterfaceTheme { UserInterfaceTheme.current } /// 设置UI主题,支持默认几种主题的设置 /// - Parameter theme: UI主题 func applyUserInterfaceTheme(_ theme: UserInterfaceTheme) { guard theme != .unspecified else { assertionFailure("Unspecified theme please use applyDynamicTheme(_:).") return } UserInterfaceTheme.current = theme applyTheme(theme.theme) } /// 设置动态主题,一般用于从云端下载主题资源文件生成DynamicTheme来配置动态主题 /// - Parameter theme: 动态主题 func applyDynamicTheme(_ theme: DynamicTheme) { UserInterfaceTheme.current = .unspecified applyTheme(theme) } /// 设置自动主题,跟随系统自动切换,APP进入激活状态的时候切换主题 /// - Parameter automatic: 自动主题 @available(iOS 13.0, *) func applyAutomaticTheme(_ automatic: Bool) { let notificationName = UIApplication.didBecomeActiveNotification guard automatic else { NotificationCenter.default.removeObserver(self, name: notificationName, object: nil) return } applyUserInterfaceTheme(.automatic) NotificationCenter.default.addObserver( self, selector: #selector(applicationDidBecomeActive), name: notificationName, object: nil ) } @available(iOS 13.0, *) @objc private func applicationDidBecomeActive() { applyUserInterfaceTheme(.automatic) } }
27.15625
96
0.63061
d9607d1f01475b07873828a5efa872a0944e191f
3,766
// // Reusables+extension.swift // Baxta // // Created by Ankit Karna on 5/2/19. // Copyright © 2019 EBPearls. All rights reserved. // import UIKit extension UITableView { public func registerCell<T: UITableViewCell>(_ cellClass: T.Type) { self.register(cellClass, forCellReuseIdentifier: String(describing: T.self)) } public func dequeueCell<T: UITableViewCell>(_ cellClass: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: String(describing: T.self), for: indexPath) as? T else { fatalError("Unable to dequeue \(String(describing: cellClass)) with reuseId of \(String(describing: T.self))") } return cell } } extension UICollectionView { /// Registers a particular cell using its reuse-identifier public func registerCell<T: UICollectionViewCell>(_ cellClass: T.Type) { register(cellClass, forCellWithReuseIdentifier: String(describing: T.self)) } func registerWithNib<T: UICollectionViewCell>(_ cell: T.Type) { register(UINib(nibName: String(describing: T.self), bundle: nil), forCellWithReuseIdentifier: String(describing: T.self)) } /// Registers a reusable view for a specific SectionKind public func registerReusableView<T: UICollectionReusableView>(_ reusableViewClass: T.Type, forSupplementaryViewOfKind kind: String) { register(reusableViewClass, forSupplementaryViewOfKind: kind, withReuseIdentifier: String(describing: T.self)) } /// Registers a nib with reusable view for a specific SectionKind public func registerReusableView<T: UICollectionReusableView>(_ nib: UINib? = UINib(nibName: String(describing: T.self), bundle: nil), headerFooterClassOfNib headerFooterClass: T.Type, forSupplementaryViewOfKind kind: String) { register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: String(describing: T.self)) } /// Generically dequeues a cell of the correct type allowing you to avoid scattering your code with guard-let-else-fatal public func dequeueCell<T: UICollectionViewCell>(_ cellClass: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withReuseIdentifier: String(describing: T.self), for: indexPath) as? T else { fatalError("Unable to dequeue \(String(describing: cellClass)) with reuseId of \(String(describing: T.self))") } return cell } /// Generically dequeues a header of the correct type allowing you to avoid scattering your code with guard-let-else-fatal public func dequeueHeaderView<T: UICollectionReusableView>(_ viewClass: T.Type, for indexPath: IndexPath) -> T { let view = dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: String(describing: T.self), for: indexPath) guard let viewType = view as? T else { fatalError("Unable to dequeue \(String(describing: viewClass)) with reuseId of \(String(describing: T.self))") } return viewType } /// Generically dequeues a footer of the correct type allowing you to avoid scattering your code with guard-let-else-fatal public func dequeueFooterView<T: UICollectionReusableView>(_ viewClass: T.Type, for indexPath: IndexPath) -> T { let view = dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: String(describing: T.self), for: indexPath) guard let viewType = view as? T else { fatalError("Unable to dequeue \(String(describing: viewClass)) with reuseId of \(String(describing: T.self))") } return viewType } }
50.891892
231
0.707913
ab05f34fead877162af4e5f8aee80bb66ca206e6
981
// // FlicksTests.swift // FlicksTests // // Created by Abhijeet Chakrabarti on 2/6/17. // Copyright © 2017 Abhijeet Chakrabarti. All rights reserved. // import XCTest @testable import Flicks class FlicksTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.513514
111
0.636086
d5c1c0b4742c761e2aaa5db6ddf161d4a0608b20
1,139
// // User.swift // Modelo_Tests // // Created by Ephraim Russo on 1/25/20. // Copyright © 2020 CocoaPods. All rights reserved. // import Foundation import Modelo final class User: ModelType { let id: Int let name: String let email: String } extension User { static var unsafeModelMap: [Int : User] = [:] static func fetchModel(identifier: Int, completion: @escaping (Result<User, Error>) -> Void) { print(#function) let request = URLRequest(url: URL(string: "https://jsonplaceholder.typicode.com/users/\(identifier)")!) let session = URLSession(configuration: .default) let task = session.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { completion(.failure(error!)); return } print("Successfully fetched from network") do { let user = try JSONDecoder().decode(User.self, from: data) completion(.success(user)) } catch { completion(.failure(error)) } } task.resume() } }
26.488372
111
0.582968
e55d2ccb3e4a3f0f3782a2e696b0be90bd87dc9e
1,836
// // RoundedCorners.swift // Recipe Book // // Created by Jonas Frey on 13.10.19. // Copyright © 2019 Jonas Frey. All rights reserved. // import Foundation import SwiftUI /// Represents a `Rectangle` where each corner is rounded individually /// /// Text("Hello, world!") /// .background(RoundedCorners(tl: 0, tr: 30, bl: 30, br: 0).fill(Color.blue)) /// struct RoundedCorners: Shape { var tl: CGFloat = 0.0 var tr: CGFloat = 0.0 var bl: CGFloat = 0.0 var br: CGFloat = 0.0 func path(in rect: CGRect) -> Path { var path = Path() let w = rect.size.width let h = rect.size.height // Make sure we do not exceed the size of the rectangle let tr = min(min(self.tr, h/2), w/2) let tl = min(min(self.tl, h/2), w/2) let bl = min(min(self.bl, h/2), w/2) let br = min(min(self.br, h/2), w/2) path.move(to: CGPoint(x: w / 2.0, y: 0)) path.addLine(to: CGPoint(x: w - tr, y: 0)) path.addArc(center: CGPoint(x: w - tr, y: tr), radius: tr, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false) path.addLine(to: CGPoint(x: w, y: h - br)) path.addArc(center: CGPoint(x: w - br, y: h - br), radius: br, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 90), clockwise: false) path.addLine(to: CGPoint(x: bl, y: h)) path.addArc(center: CGPoint(x: bl, y: h - bl), radius: bl, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 180), clockwise: false) path.addLine(to: CGPoint(x: 0, y: tl)) path.addArc(center: CGPoint(x: tl, y: tl), radius: tl, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 270), clockwise: false) return path } }
33.381818
101
0.571351
14c1757853b7702b402a48c8cd6447809339af3f
994
// // StoryForgeTests.swift // StoryForgeTests // // Created by Martin Vytrhlík on 28/03/16. // Copyright © 2016 Martin Vytrhlík. All rights reserved. // import XCTest @testable import StoryForge class StoryForgeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
26.864865
111
0.640845
8fd591abf241fb65951a3ad653fb8568adddb2b2
272
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct S{var d=F>:enum A{class A{struct a{class A{class A{{}class A{enum S{enum S<T where g:a{var d=a<T
54.4
103
0.746324
08dfd1d95676ae0fe95468aa1b3d38432bfa9b9b
1,726
// Copyright (c) 2021 Payoneer Germany GmbH // https://www.payoneer.com // // This file is open source and available under the MIT license. // See the LICENSE file for more information. import Foundation extension Input.Field { final class IBAN: BasicText { let patternFormatter: InputPatternFormatter? override init(from inputElement: InputElement, translator: TranslationProvider, validationRule: Validation.Rule?) { // Pattern formatter let maxLength = validationRule?.maxLength ?? 34 let patternFormatter = InputPatternFormatter(maxStringLength: maxLength, separator: " ", every: 4) patternFormatter.inputModifiers = [UppercaseInputModifier()] self.patternFormatter = patternFormatter super.init(from: inputElement, translator: translator, validationRule: validationRule) } } } extension Input.Field.IBAN: Validatable { func localize(error: Input.Field.Validation.ValidationError) -> String { switch error { case .invalidValue, .incorrectLength: return translator.translation(forKey: "error.INVALID_IBAN") case .missingValue: return translator.translation(forKey: "error.MISSING_IBAN") } } var isPassedCustomValidation: Bool { return Input.Field.Validation.IBAN.isValid(iban: value) } } #if canImport(UIKit) import UIKit extension Input.Field.IBAN: CellRepresentable, DefinesKeyboardStyle { var keyboardType: UIKeyboardType { .asciiCapable } var autocapitalizationType: UITextAutocapitalizationType { .allCharacters } } extension Input.Field.IBAN: TextInputField { var allowedCharacters: CharacterSet? { return .alphanumerics } } #endif
34.52
123
0.717845
1defe8329f5a3d18e8235e3a7f22ca830e26e59a
6,005
import UIKit import RxSwift import Moya enum BidCheckingError: String { case PollingExceeded } extension BidCheckingError: Swift.Error { } protocol BidCheckingNetworkModelType { var bidDetails: BidDetails { get } var bidIsResolved: Variable<Bool> { get } var isHighestBidder: Variable<Bool> { get } var reserveNotMet: Variable<Bool> { get } func waitForBidResolution (bidderPositionId: String, provider: AuthorizedNetworking) -> Observable<Void> } class BidCheckingNetworkModel: NSObject, BidCheckingNetworkModelType { fileprivate var pollInterval = TimeInterval(1) fileprivate var maxPollRequests = 20 fileprivate var pollRequests = 0 // inputs let provider: Networking let bidDetails: BidDetails // outputs var bidIsResolved = Variable(false) var isHighestBidder = Variable(false) var reserveNotMet = Variable(false) fileprivate var mostRecentSaleArtwork: SaleArtwork? init(provider: Networking, bidDetails: BidDetails) { self.provider = provider self.bidDetails = bidDetails } func waitForBidResolution (bidderPositionId: String, provider: AuthorizedNetworking) -> Observable<Void> { return self .poll(forUpdatedBidderPosition: bidderPositionId, provider: provider) .then { return self.getUpdatedSaleArtwork() .flatMap { saleArtwork -> Observable<Void> in // This is an updated model – hooray! self.mostRecentSaleArtwork = saleArtwork self.bidDetails.saleArtwork?.updateWithValues(saleArtwork) self.reserveNotMet.value = ReserveStatus.initOrDefault(saleArtwork.reserveStatus).reserveNotMet return .just(Void()) } .do(onError: { _ in logger.log("Bidder position was processed but corresponding saleArtwork was not found") }) .catchErrorJustReturn(Void()) .flatMap { _ -> Observable<Void> in return self.checkForMaxBid(provider: provider) } }.do(onNext: { _ in self.bidIsResolved.value = true // If polling fails, we can still show bid confirmation. Do not error. }).catchErrorJustReturn() } fileprivate func poll(forUpdatedBidderPosition bidderPositionId: String, provider: AuthorizedNetworking) -> Observable<Void> { let updatedBidderPosition = getUpdatedBidderPosition(bidderPositionId: bidderPositionId, provider: provider) .flatMap { bidderPositionObject -> Observable<Void> in self.pollRequests += 1 logger.log("Polling \(self.pollRequests) of \(self.maxPollRequests) for updated sale artwork") if let processedAt = bidderPositionObject.processedAt { logger.log("BidPosition finished processing at \(processedAt), proceeding...") return .just(Void()) } else { // The backend hasn't finished processing the bid yet guard self.pollRequests < self.maxPollRequests else { // We have exceeded our max number of polls, fail. throw BidCheckingError.PollingExceeded } // We didn't get an updated value, so let's try again. return Observable<Int>.interval(self.pollInterval, scheduler: MainScheduler.instance) .take(1) .map(void) .then { return self.poll(forUpdatedBidderPosition: bidderPositionId, provider: provider) } } } return Observable<Int>.interval(pollInterval, scheduler: MainScheduler.instance) .take(1) .map(void) .then { updatedBidderPosition } } fileprivate func checkForMaxBid(provider: AuthorizedNetworking) -> Observable<Void> { return getMyBidderPositions(provider: provider) .do(onNext: { newBidderPositions in if let topBidID = self.mostRecentSaleArtwork?.saleHighestBid?.id { for position in newBidderPositions where position.highestBid?.id == topBidID { self.isHighestBidder.value = true } } }) .map(void) } fileprivate func getMyBidderPositions(provider: AuthorizedNetworking) -> Observable<[BidderPosition]> { let artworkID = bidDetails.saleArtwork!.artwork.id; let auctionID = bidDetails.saleArtwork!.auctionID! let endpoint = ArtsyAuthenticatedAPI.myBidPositionsForAuctionArtwork(auctionID: auctionID, artworkID: artworkID) return provider .request(endpoint) .filterSuccessfulStatusCodes() .mapJSON() .mapTo(arrayOf: BidderPosition.self) } fileprivate func getUpdatedSaleArtwork() -> Observable<SaleArtwork> { let artworkID = bidDetails.saleArtwork!.artwork.id; let auctionID = bidDetails.saleArtwork!.auctionID! let endpoint: ArtsyAPI = ArtsyAPI.auctionInfoForArtwork(auctionID: auctionID, artworkID: artworkID) return provider .request(endpoint) .filterSuccessfulStatusCodes() .mapJSON() .mapTo(object: SaleArtwork.self) } fileprivate func getUpdatedBidderPosition(bidderPositionId: String, provider: AuthorizedNetworking) -> Observable<BidderPosition> { let endpoint = ArtsyAuthenticatedAPI.myBidPosition(id: bidderPositionId) return provider .request(endpoint) .filterSuccessfulStatusCodes() .mapJSON() .mapTo(object: BidderPosition.self) } }
39.248366
135
0.613322
bbf1d9ca4f3342556cd49cd03c5e16f6816d0455
1,760
// // Payload.swift // SpaceXAPI-Swift // // Created by Sami Sharafeddine on 5/26/19. // Copyright © 2019 Sami Sharafeddine. All rights reserved. // import Foundation public class Payload: Codable { public let payloadID: String? public let noradID: [SXNumber]? public let reused: Bool? public let customers: [String]? public let nationality: String? public let manufacturer: String? public let payloadType: String? public let payloadMassKg: SXNumber? public let payloadMassLbs: SXNumber? public let orbit: String? public let orbitParams: OrbitParams? enum CodingKeys: String, CodingKey { case payloadID = "payload_id" case noradID = "norad_id" case reused = "reused" case customers = "customers" case nationality = "nationality" case manufacturer = "manufacturer" case payloadType = "payload_type" case payloadMassKg = "payload_mass_kg" case payloadMassLbs = "payload_mass_lbs" case orbit = "orbit" case orbitParams = "orbit_params" } init(payloadID: String?, noradID: [SXNumber]?, reused: Bool?, customers: [String]?, nationality: String?, manufacturer: String?, payloadType: String?, payloadMassKg: SXNumber?, payloadMassLbs: SXNumber?, orbit: String?, orbitParams: OrbitParams?) { self.payloadID = payloadID self.noradID = noradID self.reused = reused self.customers = customers self.nationality = nationality self.manufacturer = manufacturer self.payloadType = payloadType self.payloadMassKg = payloadMassKg self.payloadMassLbs = payloadMassLbs self.orbit = orbit self.orbitParams = orbitParams } }
33.207547
252
0.665341
cc61e962ae134a7a16ac5dfa5e338b88263f56ec
2,443
// // ComplicationController.swift // Diabetapp WatchApp Extension // // Created by Alex Telek on 05/12/2015. // Copyright © 2015 Diabetapp. All rights reserved. // import ClockKit class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Timeline Configuration func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) { handler([.Forward, .Backward]) } func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) { handler(nil) } func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) { handler(nil) } func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) { handler(.ShowOnLockScreen) } // MARK: - Timeline Population func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) { // Call the handler with the current timeline entry handler(nil) } func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) { // Call the handler with the timeline entries prior to the given date handler(nil) } func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) { // Call the handler with the timeline entries after to the given date handler(nil) } // MARK: - Update Scheduling func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) { // Call the handler with the date when you would next like to be given the opportunity to update your complication content handler(nil); } // MARK: - Placeholder Templates func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) { // This method will be called once per supported complication, and the results will be cached handler(nil) } }
38.171875
178
0.710192
f82b46245b8c79f0c74d2a1daf5dceb505a92c93
2,097
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest import RiotSwiftUI @available(iOS 14.0, *) class OnboardingCongratulationsUITests: MockScreenTest { override class var screenType: MockScreenState.Type { return MockOnboardingCongratulationsScreenState.self } override class func createTest() -> MockScreenTest { return OnboardingCongratulationsUITests(selector: #selector(verifyOnboardingCongratulationsScreen)) } func verifyOnboardingCongratulationsScreen() throws { guard let screenState = screenState as? MockOnboardingCongratulationsScreenState else { fatalError("no screen") } switch screenState { case .regular: verifyButtons() case .personalizationDisabled: verifyButtonsWhenPersonalizationIsDisabled() } } func verifyButtons() { let personalizeButton = app.buttons["personalizeButton"] XCTAssertTrue(personalizeButton.exists, "The personalization button should be shown.") let homeButton = app.buttons["homeButton"] XCTAssertTrue(homeButton.exists, "The home button should always be shown.") } func verifyButtonsWhenPersonalizationIsDisabled() { let personalizeButton = app.buttons["personalizeButton"] XCTAssertFalse(personalizeButton.exists, "The personalization button should be hidden.") let homeButton = app.buttons["homeButton"] XCTAssertTrue(homeButton.exists, "The home button should always be shown.") } }
36.789474
121
0.718646
e5fae94a626220fcb114639527a0af0ea3288525
11,379
@testable import Bagbutik import XCTest #if canImport(FoundationNetworking) // Linux support import FoundationNetworking #endif final class BagbutikServiceTests: XCTestCase { var service: BagbutikService! var jwt: JWT! var mockURLSession: MockURLSession! let jsonEncoder = JSONEncoder() let errorResponse = ErrorResponse(errors: [ .init(code: "some-code", detail: "some-detail", status: "some-status", title: "some-title"), ]) func setUpService(expiredJWT: Bool = false) throws { mockURLSession = .init() if expiredJWT { DateFactory.fromTimeIntervalSinceNow = { _ in Date.distantPast } } jwt = try JWT(keyId: JWTTests.keyId, issuerId: JWTTests.issuerId, privateKey: JWTTests.privateKey) DateFactory.reset() let fetchData = mockURLSession.data(for:delegate:) service = .init(jwt: jwt, fetchData: fetchData) } func testRequest_PlainResponse() async throws { try setUpService() let request: Request<AppResponse, ErrorResponse> = .getApp(id: "app-id") let expectedResponse = AppResponse(data: .init(id: "app-id", links: .init(self: "")), links: .init(self: "")) mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: try jsonEncoder.encode(expectedResponse), type: .http(statusCode: 200)) let response = try await service.request(request) XCTAssertEqual(response, expectedResponse) } func testRequest_GzipResponse() async throws { try setUpService() let request: Request<GzipResponse, ErrorResponse> = .getAwesomeReports() let data = GunzipTests.gzipData mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: data, type: .http(statusCode: 200)) let response = try await service.request(request) XCTAssertEqual(response.data, data) } func testRequest_EmptyResponse() async throws { try setUpService() let request: Request<EmptyResponse, ErrorResponse> = .deleteBundleId(id: "some-id") mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: Data(), type: .http(statusCode: 200)) let response = try await service.request(request) XCTAssertEqual(response, EmptyResponse()) } func testRequest_StatusCodeMapping() async throws { try setUpService() let data = try jsonEncoder.encode(errorResponse) let responses: [(statusCode: Int, error: ServiceError)] = [ (statusCode: 400, error: .badRequest(errorResponse)), (statusCode: 401, error: .unauthorized(errorResponse)), (statusCode: 403, error: .forbidden(errorResponse)), (statusCode: 404, error: .notFound(errorResponse)), (statusCode: 409, error: .conflict(errorResponse)), (statusCode: 418, error: .unknownHTTPError(statusCode: 418, data: data)), ] for response in responses { let request: Request<AppsResponse, ErrorResponse> = .listApps() mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: data, type: .http(statusCode: response.statusCode)) await XCTAssertAsyncThrowsError(try await service.request(request)) { error in XCTAssertEqual(error as! ServiceError, response.error) } } } func testRequest_UnknownResponseType() async throws { try setUpService() let request: Request<AppsResponse, ErrorResponse> = .listApps() let data = Data("Test".utf8) mockURLSession.wrapInHTTPURLResponse = false mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: data, type: .url) await XCTAssertAsyncThrowsError(try await service.request(.listApps())) { error in XCTAssertEqual(error as! ServiceError, .unknown(data: data)) } } func testRequestAllPages() async throws { try setUpService() let request: Request<AppsResponse, ErrorResponse> = .listApps() let responses: [AppsResponse] = [ .init(data: [.init(id: "app1", links: .init(self: ""))], links: .init(next: "https://next1", self: "")), .init(data: [.init(id: "app2", links: .init(self: ""))], links: .init(next: "https://next2", self: "")), .init(data: [.init(id: "app3", links: .init(self: ""))], links: .init(next: nil, self: "")), ] mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: try jsonEncoder.encode(responses[0]), type: .http(statusCode: 200)) mockURLSession.responsesByUrl[URL(string: responses[0].links.next!)!] = (data: try jsonEncoder.encode(responses[1]), type: .http(statusCode: 200)) mockURLSession.responsesByUrl[URL(string: responses[1].links.next!)!] = (data: try jsonEncoder.encode(responses[2]), type: .http(statusCode: 200)) let response = try await service.requestAllPages(request) XCTAssertEqual(response.data, responses.map(\.data).flatMap { $0 }) } func testDateDecoding_ISO8601() async throws { try setUpService() let dateString = "2021-09-13T13:01:52-07:00" let dateFormatter = ISO8601DateFormatter() let date = dateFormatter.date(from: dateString)! let jsonString = """ { "date": "\(dateString)" } """ let request: Request<CrazyDatesResponse, ErrorResponse> = .getCrazyDates() mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: Data(jsonString.utf8), type: .http(statusCode: 200)) let response = try await service.request(request) XCTAssertEqual(response.date, date) } func testDateDecoding_CustomDate() async throws { try setUpService() let dateString = "2021-07-31T21:49:11.000+00:00" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" let date = dateFormatter.date(from: dateString)! let jsonString = """ { "date": "\(dateString)" } """ let request: Request<CrazyDatesResponse, ErrorResponse> = .getCrazyDates() mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: Data(jsonString.utf8), type: .http(statusCode: 200)) let response = try await service.request(request) XCTAssertEqual(response.date, date) } func testDateDecoding_InvalidDate() async throws { try setUpService() let jsonString = """ { "date": "invalid-date" } """ let request: Request<CrazyDatesResponse, ErrorResponse> = .getCrazyDates() mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: Data(jsonString.utf8), type: .http(statusCode: 200)) await XCTAssertAsyncThrowsError(try await service.request(request)) { error in XCTAssertEqual(error as! ServiceError, .wrongDateFormat(dateString: "invalid-date")) } } func testJWTRenewal() async throws { try setUpService(expiredJWT: true) XCTAssertTrue(service.jwt.isExpired) let request: Request<AppResponse, ErrorResponse> = .getApp(id: "app-id") let expectedResponse = AppResponse(data: .init(id: "app-id", links: .init(self: "")), links: .init(self: "")) mockURLSession.responsesByUrl[request.asUrlRequest().url!] = (data: try jsonEncoder.encode(expectedResponse), type: .http(statusCode: 200)) _ = try await service.request(request) XCTAssertFalse(service.jwt.isExpired) } } class MockURLSession { var responsesByUrl: [URL: (data: Data, type: ResponseType)] = [:] var wrapInHTTPURLResponse = true enum ResponseType { case http(statusCode: Int) case url } func data(for request: URLRequest, delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse) { XCTAssertTrue(request.allHTTPHeaderFields?.contains(where: { $0.key == "Authorization" }) ?? false) let response = responsesByUrl[request.url!]! switch response.type { case .http(let statusCode): return (response.data, HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: nil, headerFields: nil)!) case .url: return (response.data, URLResponse(url: request.url!, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)) } } } extension AppResponse: Equatable { public static func == (lhs: AppResponse, rhs: AppResponse) -> Bool { lhs.data.id == rhs.data.id } } extension App: Equatable { public static func == (lhs: App, rhs: App) -> Bool { lhs.id == rhs.id } } extension EmptyResponse: Equatable { public static func == (lhs: EmptyResponse, rhs: EmptyResponse) -> Bool { true } } extension ErrorResponse.Errors: Equatable { public static func == (lhs: ErrorResponse.Errors, rhs: ErrorResponse.Errors) -> Bool { lhs.code == rhs.code && lhs.detail == rhs.detail && lhs.status == rhs.status && lhs.title == rhs.title } } extension ErrorResponse: Equatable { public static func == (lhs: ErrorResponse, rhs: ErrorResponse) -> Bool { lhs.errors == rhs.errors } } extension ServiceError: Equatable { public static func == (lhs: ServiceError, rhs: ServiceError) -> Bool { switch (lhs, rhs) { case (.badRequest(let lhsResponse), .badRequest(let rhsResponse)): return lhsResponse == rhsResponse case (.unauthorized(let lhsResponse), .unauthorized(let rhsResponse)): return lhsResponse == rhsResponse case (.forbidden(let lhsResponse), .forbidden(let rhsResponse)): return lhsResponse == rhsResponse case (.notFound(let lhsResponse), .notFound(let rhsResponse)): return lhsResponse == rhsResponse case (.conflict(let lhsResponse), .conflict(let rhsResponse)): return lhsResponse == rhsResponse case (.wrongDateFormat(let lhsDateString), .wrongDateFormat(let rhsDateString)): return lhsDateString == rhsDateString case (.unknownHTTPError(let lhsStatusCode, let lhsData), .unknownHTTPError(let rhsStatusCode, let rhsData)): return lhsStatusCode == rhsStatusCode && lhsData == rhsData case (.unknown(let lhsData), .unknown(let rhsData)): return lhsData == rhsData default: return false } } } struct CrazyDatesResponse: Decodable { let date: Date } struct GzipResponse: BinaryResponse { let data: Data public static func from(data: Data) -> Self { Self(data: data) } } extension Request { static func getCrazyDates() -> Request<CrazyDatesResponse, ErrorResponse> { .init(path: "/v1/crazyDates", method: .get) } static func getAwesomeReports() -> Request<GzipResponse, ErrorResponse> { .init(path: "/v1/awesomeReports", method: .get) } }
43.102273
132
0.627032
227afe376fd1cd03d3887c6f4210cabbcee7bbe8
32,653
// Copyright DApps Platform Inc. All rights reserved. import UIKit import WebKit import APIKit import BigInt import JSONRPCKit import PromiseKit import RealmSwift import Result protocol DappBrowserCoordinatorDelegate: class { func didSentTransaction(transaction: SentTransaction, inCoordinator coordinator: DappBrowserCoordinator) func importUniversalLink(url: URL, forCoordinator coordinator: DappBrowserCoordinator) func handleUniversalLink(_ url: URL, forCoordinator coordinator: DappBrowserCoordinator) func handleCustomUrlScheme(_ url: URL, forCoordinator coordinator: DappBrowserCoordinator) } final class DappBrowserCoordinator: NSObject, Coordinator { private var session: WalletSession { return sessions[server] } private let sessions: ServerDictionary<WalletSession> private let keystore: Keystore private let config: Config private let analyticsCoordinator: AnalyticsCoordinator private var browserNavBar: DappBrowserNavigationBar? { return navigationController.navigationBar as? DappBrowserNavigationBar } private lazy var historyViewController: BrowserHistoryViewController = { let controller = BrowserHistoryViewController(store: historyStore) controller.configure(viewModel: HistoriesViewModel(store: historyStore)) controller.delegate = self return controller }() private lazy var browserViewController: BrowserViewController = { let controller = BrowserViewController(account: session.account, server: server) controller.delegate = self controller.webView.uiDelegate = self return controller }() private let sharedRealm: Realm private let browserOnly: Bool private let nativeCryptoCurrencyPrices: ServerDictionary<Subscribable<Double>> private lazy var bookmarksStore: BookmarksStore = { return BookmarksStore(realm: sharedRealm) }() private lazy var historyStore: HistoryStore = { return HistoryStore(realm: sharedRealm) }() private lazy var preferences: PreferencesController = { return PreferencesController() }() private var urlParser: BrowserURLParser { let engine = SearchEngine(rawValue: preferences.get(for: .browserSearchEngine)) ?? .default return BrowserURLParser(engine: engine) } private var server: RPCServer { get { let selected = RPCServer(chainID: Config.getChainId()) let enabled = config.enabledServers if enabled.contains(selected) { return selected } else { let fallback = enabled[0] Config.setChainId(fallback.chainID) return fallback } } set { Config.setChainId(newValue.chainID) } } private var enableToolbar: Bool = true { didSet { navigationController.isToolbarHidden = !enableToolbar } } private var currentUrl: URL? { return browserViewController.webView.url } private var hasWebPageLoaded: Bool { return currentUrl != nil } var coordinators: [Coordinator] = [] let navigationController: UINavigationController lazy var rootViewController: DappsHomeViewController = { let vc = DappsHomeViewController(bookmarksStore: bookmarksStore) vc.delegate = self return vc }() weak var delegate: DappBrowserCoordinatorDelegate? init( sessions: ServerDictionary<WalletSession>, keystore: Keystore, config: Config, sharedRealm: Realm, browserOnly: Bool, nativeCryptoCurrencyPrices: ServerDictionary<Subscribable<Double>>, analyticsCoordinator: AnalyticsCoordinator ) { self.navigationController = UINavigationController(navigationBarClass: DappBrowserNavigationBar.self, toolbarClass: nil) self.sessions = sessions self.keystore = keystore self.config = config self.sharedRealm = sharedRealm self.browserOnly = browserOnly self.nativeCryptoCurrencyPrices = nativeCryptoCurrencyPrices self.analyticsCoordinator = analyticsCoordinator super.init() //Necessary so that some sites don't bleed into (under) navigation bar after we tweak global styles for navigationBars after adding large title support self.navigationController.navigationBar.isTranslucent = false browserNavBar?.navigationBarDelegate = self browserNavBar?.configure(server: server) } func start() { navigationController.viewControllers = [rootViewController] } @objc func dismiss() { removeAllCoordinators() navigationController.dismiss(animated: true) } private enum PendingTransaction { case none case data(callbackID: Int) } private var pendingTransaction: PendingTransaction = .none private func executeTransaction(account: AlphaWallet.Address, action: DappAction, callbackID: Int, transaction: UnconfirmedTransaction, type: ConfirmType, server: RPCServer) { pendingTransaction = .data(callbackID: callbackID) let ethPrice = nativeCryptoCurrencyPrices[server] let coordinator = TransactionConfirmationCoordinator(navigationController: navigationController, session: session, transaction: transaction, configuration: .dappTransaction(confirmType: type, keystore: keystore, ethPrice: ethPrice), analyticsCoordinator: analyticsCoordinator) coordinator.delegate = self addCoordinator(coordinator) coordinator.start(fromSource: .browser) } private func ethCall(callbackID: Int, from: AlphaWallet.Address?, to: AlphaWallet.Address?, data: String, server: RPCServer) { let request = EthCallRequest(from: from, to: to, data: data) firstly { Session.send(EtherServiceRequest(server: server, batch: BatchFactory().create(request))) }.done { result in let callback = DappCallback(id: callbackID, value: .ethCall(result)) self.browserViewController.notifyFinish(callbackID: callbackID, value: .success(callback)) }.catch { error in if case let SessionTaskError.responseError(JSONRPCError.responseError(e)) = error { self.browserViewController.notifyFinish(callbackID: callbackID, value: .failure(.nodeError(e.message))) } else { //TODO better handle. User didn't cancel self.browserViewController.notifyFinish(callbackID: callbackID, value: .failure(.cancelled)) } } } func open(url: URL, animated: Bool = true, forceReload: Bool = false) { //If users tap on the verified button in the import MagicLink UI, we don't want to treat it as a MagicLink to import and show the UI again. Just open in browser. This check means when we tap MagicLinks in browserOnly mode, the import UI doesn't show up; which is probably acceptable if !browserOnly && isMagicLink(url) { delegate?.importUniversalLink(url: url, forCoordinator: self) return } //TODO maybe not the best idea to check like this. Because it will always create the browserViewController twice the first time (or maybe it's ok. Just once) if navigationController.topViewController != browserViewController { browserViewController = BrowserViewController(account: session.account, server: server) browserViewController.delegate = self browserViewController.webView.uiDelegate = self pushOntoNavigationController(viewController: browserViewController, animated: animated) } browserNavBar?.display(url: url) if browserOnly { browserNavBar?.makeBrowserOnly() } browserViewController.goTo(url: url) } func signMessage(with type: SignMessageType, account: AlphaWallet.Address, callbackID: Int) { firstly { SignMessageCoordinator.promise(analyticsCoordinator: analyticsCoordinator, navigationController: navigationController, keystore: keystore, coordinator: self, signType: type, account: account, source: .dappBrowser) }.done { data in let callback: DappCallback switch type { case .message: callback = DappCallback(id: callbackID, value: .signMessage(data)) case .personalMessage: callback = DappCallback(id: callbackID, value: .signPersonalMessage(data)) case .typedMessage: callback = DappCallback(id: callbackID, value: .signTypedMessage(data)) case .eip712v3And4: callback = DappCallback(id: callbackID, value: .signTypedMessageV3(data)) } self.browserViewController.notifyFinish(callbackID: callbackID, value: .success(callback)) }.catch { _ in self.browserViewController.notifyFinish(callbackID: callbackID, value: .failure(DAppError.cancelled)) } } private func makeMoreAlertSheet(sender: UIView) -> UIAlertController { let alertController = UIAlertController( title: nil, message: nil, preferredStyle: .actionSheet ) alertController.popoverPresentationController?.sourceView = sender alertController.popoverPresentationController?.sourceRect = sender.centerRect let reloadAction = UIAlertAction(title: R.string.localizable.reload(), style: .default) { [weak self] _ in self?.logReload() self?.browserViewController.reload() } reloadAction.isEnabled = hasWebPageLoaded let shareAction = UIAlertAction(title: R.string.localizable.share(), style: .default) { [weak self] _ in self?.share(sender: sender) } shareAction.isEnabled = hasWebPageLoaded let addBookmarkAction = UIAlertAction(title: R.string.localizable.browserAddbookmarkButtonTitle(), style: .default) { [weak self] _ in self?.addCurrentPageAsBookmark() } addBookmarkAction.isEnabled = hasWebPageLoaded let switchNetworkAction = UIAlertAction(title: R.string.localizable.dappBrowserSwitchServer(server.name), style: .default) { [weak self] _ in self?.showServers() } let scanQrCodeAction = UIAlertAction(title: R.string.localizable.browserScanQRCodeButtonTitle(), style: .default) { [weak self] _ in self?.scanQrCode() } let cancelAction = UIAlertAction(title: R.string.localizable.cancel(), style: .cancel) { _ in } alertController.addAction(reloadAction) alertController.addAction(shareAction) alertController.addAction(addBookmarkAction) alertController.addAction(switchNetworkAction) if browserOnly { //no-op } else { alertController.addAction(scanQrCodeAction) } alertController.addAction(cancelAction) return alertController } private func share(sender: UIView) { logShare() guard let url = currentUrl else { return } rootViewController.displayLoading() rootViewController.showShareActivity(fromSource: .view(sender), with: [url]) { [weak self] in self?.rootViewController.hideLoading() } } private func openDappInBrowser(_ dapp: Dapp) { guard let url = URL(string: dapp.url) else { return } open(url: url, animated: false) } private func openDappInBrowser(_ dapp: Bookmark) { guard let url = URL(string: dapp.url) else { return } open(url: url, animated: false) } private func pushOntoNavigationController(viewController: UIViewController, animated: Bool) { viewController.navigationItem.setHidesBackButton(true, animated: false) viewController.navigationItem.largeTitleDisplayMode = .never navigationController.pushViewController(viewController, animated: animated) } private func deleteDappFromMyDapp(_ dapp: Bookmark) { bookmarksStore.delete(bookmarks: [dapp]) refreshDapps() } //TODO can we animate changes better? func refreshDapps() { rootViewController.configure(viewModel: .init(bookmarksStore: bookmarksStore)) for each in navigationController.viewControllers { guard let vc = each as? MyDappsViewController else { continue } vc.configure(viewModel: .init(bookmarksStore: bookmarksStore)) } } private func addCurrentPageAsBookmark() { logAddDapp() if let url = currentUrl?.absoluteString, let title = browserViewController.webView.title { let bookmark = Bookmark(url: url, title: title) bookmarksStore.add(bookmarks: [bookmark]) refreshDapps() UINotificationFeedbackGenerator.show(feedbackType: .success) } else { UINotificationFeedbackGenerator.show(feedbackType: .error) } } private func scanQrCode() { guard navigationController.ensureHasDeviceAuthorization() else { return } let coordinator = ScanQRCodeCoordinator(analyticsCoordinator: analyticsCoordinator, navigationController: navigationController, account: session.account) coordinator.delegate = self addCoordinator(coordinator) coordinator.start(fromSource: .browserScreen) } private func showServers() { logSwitchServer() let coordinator = ServersCoordinator(defaultServer: server, config: config, navigationController: navigationController) coordinator.delegate = self coordinator.start() addCoordinator(coordinator) browserNavBar?.setBrowserBar(hidden: true) } private func withCurrentUrl(handler: (URL?) -> Void) { handler(browserNavBar?.url) } func isMagicLink(_ url: URL) -> Bool { return RPCServer.allCases.contains { $0.magicLinkHost == url.host } } func `switch`(toServer server: RPCServer, url: URL? = nil) { self.server = server withCurrentUrl { previousUrl in //TODO extract method? Clean up browserNavBar?.clearDisplay() browserNavBar?.configure(server: server) start() guard let url = url ?? previousUrl else { return } open(url: url, animated: false) } } } extension DappBrowserCoordinator: TransactionConfirmationCoordinatorDelegate { func coordinator(_ coordinator: TransactionConfirmationCoordinator, didFailTransaction error: AnyError) { coordinator.close { [weak self] in guard let strongSelf = self else { return } switch strongSelf.pendingTransaction { case .data(let callbackID): strongSelf.browserViewController.notifyFinish(callbackID: callbackID, value: .failure(DAppError.cancelled)) case .none: break } strongSelf.removeCoordinator(coordinator) strongSelf.navigationController.dismiss(animated: true) } } func didClose(in coordinator: TransactionConfirmationCoordinator) { switch pendingTransaction { case .data(let callbackID): browserViewController.notifyFinish(callbackID: callbackID, value: .failure(DAppError.cancelled)) case .none: break } removeCoordinator(coordinator) navigationController.dismiss(animated: true) } func coordinator(_ coordinator: TransactionConfirmationCoordinator, didCompleteTransaction result: TransactionConfirmationResult) { coordinator.close { [weak self] in guard let strongSelf = self, let delegate = strongSelf.delegate else { return } switch (strongSelf.pendingTransaction, result) { case (.data(let callbackID), .confirmationResult(let type)): switch type { case .signedTransaction(let data): let callback = DappCallback(id: callbackID, value: .signTransaction(data)) strongSelf.browserViewController.notifyFinish(callbackID: callbackID, value: .success(callback)) //TODO do we need to do this for a pending transaction? // strongSelf.delegate?.didSentTransaction(transaction: transaction, inCoordinator: strongSelf) case .sentTransaction(let transaction): // on send transaction we pass transaction ID only. let data = Data(_hex: transaction.id) let callback = DappCallback(id: callbackID, value: .sentTransaction(data)) strongSelf.browserViewController.notifyFinish(callbackID: callbackID, value: .success(callback)) delegate.didSentTransaction(transaction: transaction, inCoordinator: strongSelf) case .sentRawTransaction: break } case (.none, .noData), (.none, .confirmationResult), (.data, .noData): break } strongSelf.removeCoordinator(coordinator) strongSelf.navigationController.dismiss(animated: true) } } } extension DappBrowserCoordinator: BrowserViewControllerDelegate { func didCall(action: DappAction, callbackID: Int, inBrowserViewController viewController: BrowserViewController) { guard case .real(let account) = session.account.type else { browserViewController.notifyFinish(callbackID: callbackID, value: .failure(DAppError.cancelled)) navigationController.topViewController?.displayError(error: InCoordinatorError.onlyWatchAccount) return } switch action { case .signTransaction(let unconfirmedTransaction): executeTransaction(account: account, action: action, callbackID: callbackID, transaction: unconfirmedTransaction, type: .signThenSend, server: server) case .sendTransaction(let unconfirmedTransaction): executeTransaction(account: account, action: action, callbackID: callbackID, transaction: unconfirmedTransaction, type: .signThenSend, server: server) case .signMessage(let hexMessage): signMessage(with: .message(hexMessage.toHexData), account: account, callbackID: callbackID) case .signPersonalMessage(let hexMessage): signMessage(with: .personalMessage(hexMessage.toHexData), account: account, callbackID: callbackID) case .signTypedMessage(let typedData): signMessage(with: .typedMessage(typedData), account: account, callbackID: callbackID) case .signTypedMessageV3(let typedData): signMessage(with: .eip712v3And4(typedData), account: account, callbackID: callbackID) case .ethCall(from: let from, to: let to, data: let data): //Must use unchecked form for `Address `because `from` and `to` might be 0x0..0. We assume the dapp author knows what they are doing let from = AlphaWallet.Address(uncheckedAgainstNullAddress: from) let to = AlphaWallet.Address(uncheckedAgainstNullAddress: to) ethCall(callbackID: callbackID, from: from, to: to, data: data, server: server) case .unknown, .sendRawTransaction: break } } func didVisitURL(url: URL, title: String, inBrowserViewController viewController: BrowserViewController) { browserNavBar?.display(url: url) if let mostRecentUrl = historyStore.histories.first?.url, mostRecentUrl == url.absoluteString { } else { historyStore.record(url: url, title: title) } } func dismissKeyboard(inBrowserViewController viewController: BrowserViewController) { browserNavBar?.cancelEditing() } func forceUpdate(url: URL, inBrowserViewController viewController: BrowserViewController) { browserNavBar?.display(url: url) } func handleUniversalLink(_ url: URL, inBrowserViewController viewController: BrowserViewController) { delegate?.handleUniversalLink(url, forCoordinator: self) } func handleCustomUrlScheme(_ url: URL, inBrowserViewController viewController: BrowserViewController) { delegate?.handleCustomUrlScheme(url, forCoordinator: self) } } extension DappBrowserCoordinator: BrowserHistoryViewControllerDelegate { func didSelect(history: History, inViewController controller: BrowserHistoryViewController) { guard let url = history.URL else { return } open(url: url) } func clearHistory(inViewController viewController: BrowserHistoryViewController) { historyStore.clearAll() viewController.configure(viewModel: HistoriesViewModel(store: historyStore)) } func dismissKeyboard(inViewController viewController: BrowserHistoryViewController) { browserNavBar?.cancelEditing() } } extension DappBrowserCoordinator: WKUIDelegate { func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if navigationAction.targetFrame == nil { browserViewController.webView.load(navigationAction.request) } return nil } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alertController = UIAlertController.alertController( title: .none, message: message, style: .alert, in: navigationController ) alertController.addAction(UIAlertAction(title: R.string.localizable.oK(), style: .default, handler: { _ in completionHandler() })) navigationController.present(alertController, animated: true, completion: nil) } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alertController = UIAlertController.alertController( title: .none, message: message, style: .alert, in: navigationController ) alertController.addAction(UIAlertAction(title: R.string.localizable.oK(), style: .default, handler: { _ in completionHandler(true) })) alertController.addAction(UIAlertAction(title: R.string.localizable.cancel(), style: .default, handler: { _ in completionHandler(false) })) navigationController.present(alertController, animated: true, completion: nil) } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let alertController = UIAlertController.alertController( title: .none, message: prompt, style: .alert, in: navigationController ) alertController.addTextField { (textField) in textField.text = defaultText } alertController.addAction(UIAlertAction(title: R.string.localizable.oK(), style: .default, handler: { _ in if let text = alertController.textFields?.first?.text { completionHandler(text) } else { completionHandler(defaultText) } })) alertController.addAction(UIAlertAction(title: R.string.localizable.cancel(), style: .default, handler: { _ in completionHandler(nil) })) navigationController.present(alertController, animated: true, completion: nil) } } extension DappBrowserCoordinator: DappsHomeViewControllerDelegate { func didTapShowMyDappsViewController(inViewController viewController: DappsHomeViewController) { logShowDapps() let viewController = MyDappsViewController(bookmarksStore: bookmarksStore) viewController.configure(viewModel: .init(bookmarksStore: bookmarksStore)) viewController.delegate = self pushOntoNavigationController(viewController: viewController, animated: true) } func didTapShowBrowserHistoryViewController(inViewController viewController: DappsHomeViewController) { logShowHistory() pushOntoNavigationController(viewController: historyViewController, animated: true) } func didTapShowDiscoverDappsViewController(inViewController viewController: DappsHomeViewController) { let viewController = DiscoverDappsViewController(bookmarksStore: bookmarksStore) viewController.configure(viewModel: .init()) viewController.delegate = self pushOntoNavigationController(viewController: viewController, animated: true) } func didTap(dapp: Bookmark, inViewController viewController: DappsHomeViewController) { openDappInBrowser(dapp) } func delete(dapp: Bookmark, inViewController viewController: DappsHomeViewController) { deleteDappFromMyDapp(dapp) } func viewControllerWillAppear(_ viewController: DappsHomeViewController) { browserNavBar?.enableButtons() } func dismissKeyboard(inViewController viewController: DappsHomeViewController) { browserNavBar?.cancelEditing() } } extension DappBrowserCoordinator: DiscoverDappsViewControllerDelegate { func didTap(dapp: Dapp, inViewController viewController: DiscoverDappsViewController) { openDappInBrowser(dapp) } func didAdd(dapp: Dapp, inViewController viewController: DiscoverDappsViewController) { refreshDapps() } func didRemove(dapp: Dapp, inViewController viewController: DiscoverDappsViewController) { refreshDapps() } func dismissKeyboard(inViewController viewController: DiscoverDappsViewController) { browserNavBar?.cancelEditing() } } extension DappBrowserCoordinator: MyDappsViewControllerDelegate { func didTapToEdit(dapp: Bookmark, inViewController viewController: MyDappsViewController) { let viewController = EditMyDappViewController() viewController.delegate = self viewController.configure(viewModel: .init(dapp: dapp)) viewController.hidesBottomBarWhenPushed = true browserNavBar?.setBrowserBar(hidden: true) navigationController.pushViewController(viewController, animated: true) } func didTapToSelect(dapp: Bookmark, inViewController viewController: MyDappsViewController) { openDappInBrowser(dapp) } func delete(dapp: Bookmark, inViewController viewController: MyDappsViewController) { deleteDappFromMyDapp(dapp) viewController.configure(viewModel: .init(bookmarksStore: bookmarksStore)) } func dismissKeyboard(inViewController viewController: MyDappsViewController) { browserNavBar?.cancelEditing() } func didReorderDapps(inViewController viewController: MyDappsViewController) { refreshDapps() } } extension DappBrowserCoordinator: DappsAutoCompletionViewControllerDelegate { func didTap(dapp: Dapp, inViewController viewController: DappsAutoCompletionViewController) { openDappInBrowser(dapp) } func dismissKeyboard(inViewController viewController: DappsAutoCompletionViewController) { browserNavBar?.cancelEditing() } } extension DappBrowserCoordinator: DappBrowserNavigationBarDelegate { func didTapBack(inNavigationBar navigationBar: DappBrowserNavigationBar) { if let browserVC = navigationController.topViewController as? BrowserViewController, browserVC.webView.canGoBack { browserViewController.webView.goBack() } else if !(browserNavBar?.isBrowserOnly ?? false) { navigationController.popViewController(animated: true) if let viewController = navigationController.topViewController as? DappsAutoCompletionViewController { browserNavBar?.display(string: viewController.text) } else if navigationController.topViewController is DappsHomeViewController { browserNavBar?.clearDisplay() } } } func didTapForward(inNavigationBar navigationBar: DappBrowserNavigationBar) { guard let browserVC = navigationController.topViewController as? BrowserViewController, browserVC.webView.canGoForward else { return } browserViewController.webView.goForward() } func didTapMore(sender: UIView, inNavigationBar navigationBar: DappBrowserNavigationBar) { logTapMore() let alertController = makeMoreAlertSheet(sender: sender) navigationController.present(alertController, animated: true, completion: nil) } func didTapClose(inNavigationBar navigationBar: DappBrowserNavigationBar) { dismiss() } func didTapChangeServer(inNavigationBar navigationBar: DappBrowserNavigationBar) { showServers() } func didTyped(text: String, inNavigationBar navigationBar: DappBrowserNavigationBar) { let text = text.trimmed if text.isEmpty { if navigationController.topViewController as? DappsAutoCompletionViewController != nil { navigationController.popViewController(animated: false) } } } func didEnter(text: String, inNavigationBar navigationBar: DappBrowserNavigationBar) { logEnterUrl() guard let url = urlParser.url(from: text.trimmed) else { return } open(url: url, animated: false) } } extension DappBrowserCoordinator: EditMyDappViewControllerDelegate { func didTapSave(dapp: Bookmark, withTitle title: String, url: String, inViewController viewController: EditMyDappViewController) { try? sharedRealm.write { dapp.title = title dapp.url = url } browserNavBar?.setBrowserBar(hidden: false) navigationController.popViewController(animated: true) refreshDapps() } func didTapCancel(inViewController viewController: EditMyDappViewController) { browserNavBar?.setBrowserBar(hidden: false) navigationController.popViewController(animated: true) } } extension DappBrowserCoordinator: ScanQRCodeCoordinatorDelegate { func didCancel(in coordinator: ScanQRCodeCoordinator) { removeCoordinator(coordinator) } func didScan(result: String, in coordinator: ScanQRCodeCoordinator) { removeCoordinator(coordinator) guard let url = URL(string: result) else { return } open(url: url, animated: false) } } extension DappBrowserCoordinator: ServersCoordinatorDelegate { func didSelectServer(server: RPCServerOrAuto, in coordinator: ServersCoordinator) { browserNavBar?.setBrowserBar(hidden: false) switch server { case .auto: break case .server(let server): coordinator.navigationController.popViewController(animated: true) removeCoordinator(coordinator) `switch`(toServer: server) } } func didSelectDismiss(in coordinator: ServersCoordinator) { browserNavBar?.setBrowserBar(hidden: false) coordinator.navigationController.popViewController(animated: true) removeCoordinator(coordinator) } } //MARK: Analytics extension DappBrowserCoordinator { private func logReload() { analyticsCoordinator.log(action: Analytics.Action.reloadBrowser) } private func logShare() { analyticsCoordinator.log(action: Analytics.Action.shareUrl, properties: [Analytics.Properties.source.rawValue: "browser"]) } private func logAddDapp() { analyticsCoordinator.log(action: Analytics.Action.addDapp) } private func logSwitchServer() { analyticsCoordinator.log(navigation: Analytics.Navigation.switchServers, properties: [Analytics.Properties.source.rawValue: "browser"]) } private func logShowDapps() { analyticsCoordinator.log(navigation: Analytics.Navigation.showDapps) } private func logShowHistory() { analyticsCoordinator.log(navigation: Analytics.Navigation.showHistory) } private func logTapMore() { analyticsCoordinator.log(navigation: Analytics.Navigation.tapBrowserMore) } private func logEnterUrl() { analyticsCoordinator.log(action: Analytics.Action.enterUrl) } }
41.280657
290
0.693811
bfde66be12df369f6a69e05d10e3e21291d5882c
3,700
import XCTest @testable import Urolog final class EndBasicTest: XCTestCase { func testEndSeverity_With_SufficientMinimalSeverity() { let expectation = XCTestExpectation(description: """ Text stream must be written only \ if minimalSeverity of an \ endpoint is sufficient. """ ) expectation.isInverted = true let ts = TsTest() ts.expectation = expectation let end = BasicEndpoint(minimalSeverity: .info, textStream: ts) let event = Event.test(minimalSeverity: .debug) event.send(to: end, format: DefaultFormat()) wait(for: [expectation], timeout: 0.1) } func testEndSeverity_With_InsufficientMinimalSeverity() { let expectation = XCTestExpectation(description: """ Text stream must be written only \ if minimalSeverity of an \ endpoint is sufficient. """ ) let ts = TsTest() ts.expectation = expectation let end = BasicEndpoint(minimalSeverity: .info, textStream: ts) let event = Event.test(minimalSeverity: .info) event.send(to: end, format: DefaultFormat()) wait(for: [expectation], timeout: 0.1) } func testEndSeverityMute() { let expectation = XCTestExpectation(description: """ Text stream must be written only \ if an endpoint is unmuted. """ ) expectation.isInverted = true let ts = TsTest() ts.expectation = expectation let end = BasicEndpoint(minimalSeverity: .info, textStream: ts) let event = Event.test(minimalSeverity: .info) end.mute() event.send(to: end, format: DefaultFormat()) wait(for: [expectation], timeout: 0.1) } func testEndSeverityUnmute_After_Mute() { let expectation = XCTestExpectation(description: """ Text stream must be written only \ if an endpoint is unmuted. """ ) let ts = TsTest() ts.expectation = expectation let end = BasicEndpoint(minimalSeverity: .info, textStream: ts) let event = Event.test(minimalSeverity: .info) end.mute() event.send(to: end, format: DefaultFormat()) end.unmute() event.send(to: end, format: DefaultFormat()) wait(for: [expectation], timeout: 0.1) } } // MARK: - Test Additions final class TsTest: TextStream { // MARK: Test var expectation: XCTestExpectation? // MARK: TextStream func write(_ text: String) { expectation?.fulfill() } } extension Event { static func test(minimalSeverity: Severity = .debug) -> Event { Event( severity: minimalSeverity , message: "Test Message" , context: Context.test ) } } extension Context { static var test: Context { Context( identifier: "Test Identifier" , date: Date(timeIntervalSince1970: 1337) , lineNumber: 9 , functionName: "Test Function Name" , filePath: "Test File Path" , threadName: "Test Thread Name" , isMainThread: true ) } }
24.503311
71
0.517297
11f5a8e098c770821748b18aab50b711878c4b4d
2,919
// // PushupsTest.swift // reverseapftTests // // Created by Zachary Gorak on 3/2/18. // Copyright © 2018 twodayslate. All rights reserved. // import XCTest class PushupTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testScore() { Score.age = 21 Score.gender = .male var score = Score.score(forPushups: 72) XCTAssert(score == 100, "72: \(score) != 100") XCTAssert(Score.score(forPushups: 71) == 100) XCTAssert(Score.score(forPushups: 70) == 99) score = Score.score(forPushups: 69) XCTAssert(score == 97, "69: \(score) != 97") score = Score.score(forPushups: 68) XCTAssert(score == 96, "68: \(score) != 96") score = Score.score(forPushups: 67) XCTAssert(score == 94, "67: \(score) != 94") XCTAssert(Score.score(forPushups: 21) == 31) XCTAssert(Score.score(forPushups: 20) == 30) } func testPushups() { Score.age = 21 Score.gender = .male XCTAssert(Score.pushups(forScore: 100) == 71, "\(Score.pushups(forScore: 100))") XCTAssert(Score.pushups(forScore: 99) == 70, "\(Score.pushups(forScore: 99))") XCTAssert(Score.pushups(forScore: 98) == 70, "\(Score.pushups(forScore: 98))") XCTAssert(Score.pushups(forScore: 97) == 69, "\(Score.pushups(forScore: 97))") XCTAssert(Score.pushups(forScore: 96) == 68, "\(Score.pushups(forScore: 96))") XCTAssert(Score.pushups(forScore: 95) == 68, "\(Score.pushups(forScore: 95))") XCTAssert(Score.pushups(forScore: 94) == 67, "\(Score.pushups(forScore: 93))") XCTAssert(Score.pushups(forScore: 93) == 66, "\(Score.pushups(forScore: 92))") XCTAssert(Score.pushups(forScore: 92) == 65, "\(Score.pushups(forScore: 91))") XCTAssert(Score.pushups(forScore: 38) == 26, "\(Score.pushups(forScore: 38))") XCTAssert(Score.pushups(forScore: 37) == 25, "\(Score.pushups(forScore: 37))") XCTAssert(Score.pushups(forScore: 36) == 25, "\(Score.pushups(forScore: 36))") XCTAssert(Score.pushups(forScore: 35) == 24, "\(Score.pushups(forScore: 35))") XCTAssert(Score.pushups(forScore: 34) == 23, "\(Score.pushups(forScore: 34))") XCTAssert(Score.pushups(forScore: 33) == 23, "\(Score.pushups(forScore: 33))") XCTAssert(Score.pushups(forScore: 32) == 22, "\(Score.pushups(forScore: 32))") XCTAssert(Score.pushups(forScore: 31) == 21, "\(Score.pushups(forScore: 31))") XCTAssert(Score.pushups(forScore: 30) == 20, "\(Score.pushups(forScore: 30))") XCTAssert(Score.pushups(forScore: 9) == 5, "\(Score.pushups(forScore: 9))") XCTAssert(Score.pushups(forScore: 8) == 5, "\(Score.pushups(forScore: 8))") XCTAssert(Score.pushups(forScore: 0) == 0, "\(Score.pushups(forScore: 0))") } }
42.926471
111
0.661185
8ad40e35d485f88ac916ef6604cde4faf7919787
115
import XCTest import PetitioTests var tests = [XCTestCaseEntry]() tests += PetitioTests.allTests() XCTMain(tests)
16.428571
32
0.782609
6a5b093f3c673d53e87e714f0d16d63bd41dd294
1,098
// // ViewController.swift // Prework // // Created by Prasun Pahadi on 9/10/21. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billAmountTextField: UITextField! @IBOutlet weak var tipAmountLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var totalLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func calculateTip(_ sender: Any) { // Get bill amount from text field input let bill = Double(billAmountTextField.text!) ?? 0 // Get total tip by multiplying tip * tipPercentage let tipPercentages = [0.15, 0.18, 0.2] let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] let total = bill + tip //Updated Tip Amount Label tipAmountLabel.text = String(format: "$%.2f", tip) //Update Total Amount totalLabel.text = String(format: "$%.2f", total) } }
24.4
59
0.615665
9018334bd04e0383566fbce3c1d9df8cad25620d
827
// // ElasticHeaderTableViewController.swift // PullToRefreshKit // // Created by huangwenchen on 16/7/30. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import PullToRefreshKit import UIKit class ElasticHeaderTableViewController:BaseTableViewController{ override func viewDidLoad() { super.viewDidLoad() let elasticHeader = ElasticRefreshHeader() self.tableView.configRefreshHeader(with: elasticHeader,container:self) { [weak self] in delay(1.5, closure: { guard let vc = self else{ return; } vc.models = vc.models.map{_ in random100()} vc.tableView.reloadData() vc.tableView.switchRefreshHeader(to: .normal(.success, 0.5)); }) }; } }
28.517241
95
0.614268
1c10b53982dfb6a9297421d2523849c1e42d89f0
10,353
// // AirlockCalculateFeaturesFunctions.swift // AirLockSDK // // Created by Vladislav Rybak on 06/11/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest @testable import AirLockSDK class AirlockPullCalculateFeaturesFunctions: XCTestCase { fileprivate var airlock:Airlock = Airlock.sharedInstance; fileprivate var lastSyncDate:Date = Date() fileprivate var lastRecalculateDate:Date = Date() fileprivate var lastPullDate:Date = Date() var featureStates:[(name: String, isOn: Bool, source: Source)] = [ // ------------------- first level features ------------------------------------------// ("headsup.HeadsUp", false, Source.DEFAULT), ("modules.Airlock Control Over Modules", false, Source.DEFAULT), // ------------------- headsup namespace ------------------------------------------// ("headsup.Breaking News Video", false, Source.DEFAULT), ("headsup.Real Time Lightning", false, Source.DEFAULT), ("headsup.Winter Storm Impacted Now", false, Source.DEFAULT), ("headsup.Radar", false, Source.DEFAULT), ("headsup.Top Video", false, Source.DEFAULT), ("headsup.Precip Start", false, Source.DEFAULT), ("headsup.Precip End", false, Source.DEFAULT), ("headsup.Forecasted Snow Accumulation", false, Source.DEFAULT), ("headsup.Winter Storm Forecast", false, Source.DEFAULT), ("headsup.Road Conditions", false, Source.DEFAULT), ("headsup.Feels Like Message", false, Source.DEFAULT), ("headsup.Tomorrow Forecast", false, Source.DEFAULT), ("headsup.Weekend Forecast", false, Source.DEFAULT), ("headsup.Sunrise Sunset Message", false, Source.DEFAULT), // ------------------- modules namespace ------------------------------------------// ("modules.Current Conditions", false, Source.DEFAULT), ("modules.Breaking News", false, Source.DEFAULT), ("modules.Right Now", false, Source.DEFAULT), ("modules.Hourly", false, Source.DEFAULT), ("modules.Daily", false, Source.DEFAULT), ("modules.Video", false, Source.DEFAULT), ("modules.Radar Maps", false, Source.DEFAULT), ("modules.Road Conditions", false, Source.DEFAULT), ("modules.News", false, Source.DEFAULT), ("modules.Health", false, Source.DEFAULT), ("modules.Outdoor", false, Source.DEFAULT), // ------------------- not existing feature------------------------------------------// ("headsup.NonExisting Feature", false, Source.MISSING) ] override func setUp() { sleep(2) super.setUp() airlock.reset(clearDeviceData: true, clearFeaturesRandom: false) let testBundle = Bundle(for: type(of: self)) let defaultFileRemotePath = TestUtils.readProductDefaultFileURL(testBundle: testBundle, name: "TimeFunctions") guard !defaultFileRemotePath.0 else { self.continueAfterFailure = false XCTFail(defaultFileRemotePath.1) return } var defaultFileLocalPath: String = "" let downloadDefaultFileEx = self.expectation(description: "Download default product file") TestUtils.downloadRemoteDefaultFile(url: defaultFileRemotePath.1, temporalFileName: "Airlock_TimeFunctions_temp.json",jwt:nil, onCompletion: {(fail:Bool, error:Error?, path) in if (!fail){ defaultFileLocalPath = path downloadDefaultFileEx.fulfill() } else { //TODO stop test execution if file downloads fails self.continueAfterFailure = false XCTFail("Failed to download default file from \(defaultFileRemotePath)") downloadDefaultFileEx.fulfill() } }) waitForExpectations(timeout: 300, handler: nil) print("Temporal default file location is \(defaultFileLocalPath)") do { try airlock.loadConfiguration(configFilePath: defaultFileLocalPath, productVersion: "8.11", isDirectURL: true) } catch { XCTFail("Wasn't able to load the configuration propertly, the error receive was: \(error)") } UserGroups.setUserGroups(groups: ["QA","DEV"]) let pullOperationCompleteEx = self.expectation(description: "Perform pull operation") Airlock.sharedInstance.pullFeatures(onCompletion: {(sucess:Bool,error:Error?) in if (sucess){ print("Successfully pulled runtime from server") } else { print("fail: \(String(describing: error))") } pullOperationCompleteEx.fulfill() }) waitForExpectations(timeout: 300, handler: nil) //let pullFeaturesStatus: (Bool, String) = TestUtils.pullFeatures(); //continueAfterFailure = false //XCTAssertFalse(pullFeaturesStatus.0, pullFeaturesStatus.1) let contextFilePath = Bundle(for: type(of: self)).bundlePath + "/ProfileForTimeFunctionsTests.json" do { let contextFileJSON = try String(contentsOfFile: contextFilePath) let errors = try airlock.calculateFeatures(deviceContextJSON: contextFileJSON) if errors.count > 0 { let errorSeparator = "\n------------------------------------------------------\n" var list:String = errorSeparator for error in errors { list += error.nicePrint(printRule: true) + errorSeparator } XCTFail("Received errors from calculateFeatures function, the following errors there received:\n \(list)") } } catch (let error) { XCTFail("Feature calculation error: \(error.localizedDescription)") } continueAfterFailure = true } func testGetLastPullTime(){ let rDate:Date = airlock.getLastPullTime() as Date print("Expected to be pulled before \(lastPullDate), and pulled at \(rDate)") XCTAssertTrue(lastPullDate.compare(rDate) == ComparisonResult.orderedAscending, "Expected to be pulled after \(lastPullDate), but was reportedly pulled at \(rDate)") } func testGetLastRecalculateTime(){ let rDate:Date = airlock.getLastCalculateTime() as Date print("Expected to be recalculated before \(lastRecalculateDate), and recalculated at \(rDate)") XCTAssertTrue(lastRecalculateDate.compare(rDate) == ComparisonResult.orderedAscending, "Expected to be refereshed after \(lastRecalculateDate), but was reportedly refreshed at \(rDate)") } func testLastSyncTime(){ let rDate:Date = airlock.getLastSyncTime() as Date print("Expected to be updated before \(lastSyncDate), and updated at \(rDate)") XCTAssertTrue(lastSyncDate.compare(rDate) == ComparisonResult.orderedDescending, "Expected to be synced before \(lastSyncDate), but was reportedly synced at \(rDate)") } func testIsFeatureNotNull(){ for (featureName, isOn, _) in featureStates { print(featureName + " expected to be "+String(isOn)) let feature = airlock.getFeature(featureName: featureName) XCTAssertNotNil(feature, "Feature "+featureName+" returned null") } } func testIsFeatureOn(){ for (featureName, isOn, _) in featureStates { print(featureName + " expected to be "+String(isOn)) let feature = airlock.getFeature(featureName: featureName) let isFeatureOn:Bool = feature.isOn() let featureTrace = feature.getTrace() XCTAssertEqual(isFeatureOn,isOn,"featureName: \"\(featureName)\" with trace: \"\(featureTrace)\", source: \"\(TestUtils.sourceToString(feature.getSource()))\", branch name:\(airlock.currentBranchName()), experiment: \(airlock.currentExperimentName()), variant: \(airlock.currentVariantName())") } } func testIsFeatureSourceNotNil(){ for (featureName, _, _) in featureStates { print("Checking if feature name \(featureName) exists"); let sourceValue = airlock.getFeature(featureName: featureName).getSource() XCTAssertNotNil(sourceValue, "Found feature with nil source value") } } func testIsFeatureSourceAsExpected(){ for (featureName, _, source) in featureStates { print("Checking if feature name \(featureName) exists") let feature = airlock.getFeature(featureName: featureName) let sourceValue = feature.getSource() XCTAssertEqual(TestUtils.sourceToString(source), TestUtils.sourceToString(sourceValue), "Feature's \(featureName) source is not as expected, trace was: \(feature.getTrace())") } } }
47.709677
306
0.533179
87ac648133eaac32946ff521dc570e74d9a0fd54
548
// // RandomAccessCollectionExtensionsTests.swift // SwifterSwift // // Created by Luciano Almeida on 7/14/18. // Copyright © 2018 SwifterSwift // import XCTest @testable import SwifterSwift final class RandomAccessCollectionExtensionsTests: XCTestCase { func testIndices() { XCTAssertEqual([].indices(of: 5), []) XCTAssertEqual([1, 1, 2, 3, 4, 1, 2, 1].indices(of: 5), []) XCTAssertEqual([1, 1, 2, 3, 4, 1, 2, 1].indices(of: 1), [0, 1, 5, 7]) XCTAssertEqual(["a", "b", "c", "b", "4", "1", "2", "1"].indices(of: "b"), [1, 3]) } }
24.909091
83
0.629562
f5a23a0bf40a369ac23285420a0ebdd399858c05
993
// // TypeDefinition.swift // XCParseCore // // Created by Alex Botkin on 10/4/19. // Copyright © 2019 ChargePoint, Inc. All rights reserved. // import Foundation open class TypeDefinition : Codable { public let name: String public let supertype: TypeDefinition? enum TypeDefinitionCodingKeys: String, CodingKey { case name case supertype } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: TypeDefinitionCodingKeys.self) name = try container.decodeXCResultType(forKey: .name) supertype = try container.decodeXCResultObjectIfPresent(forKey: .supertype) } public func getType() -> AnyObject.Type { if let type = XCResultTypeFamily(rawValue: self.name) { return type.getType() } else if let parentType = self.supertype { return parentType.getType() } else { return XCResultObjectType.self } } }
27.583333
85
0.659617
c1a8ccc46cbd159380c74ef061bd9dd66cb570bf
3,957
// Copyright (C) 2019 Parrot Drones SAS // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import Foundation /// Copilot source description. @objc(GSCopilotSource) public enum CopilotSource: Int { /// Use the SkyController joysticks. case remoteControl /// Use the application controls /// Disables the SkyController joysticks case application /// Debug description. public var description: String { switch self { case .remoteControl: return "remoteControl" case .application: return "application" } } /// Set containing all possible sources. public static let allCases: Set<CopilotSource> = [.remoteControl, .application] } /// Peripheral managing copilot /// /// Copilot allows to select the source of piloting commands, either the remote control (default) or the application. /// Selecting a source prevents the other one from sending any piloting command. /// The piloting source is automatically reset to {@link Source#REMOTE_CONTROL remote control} when this one is /// disconnected from the phone. /// /// This peripheral can be retrieved by: /// ``` /// device.getPeripheral(Peripherals.coPilot) /// ``` public protocol Copilot: Peripheral { /// Copilot setting var setting: CopilotSetting { get } } /// Setting to change the piloting source public protocol CopilotSetting: AnyObject { /// Tells if the setting value has been changed and is waiting for change confirmation. var updating: Bool { get } /// Current source setting. var source: CopilotSource { get set } } /// Peripheral managing copilot /// - Note: this protocol is for Objective-C compatibility only. @objc public protocol GSCopilot { /// Copilot setting @objc(setting) var gsSetting: GSCopilotSetting { get } } /// Setting to change the piloting source /// - Note: this protocol is for Objective-C compatibility only. @objc public protocol GSCopilotSetting { /// Tells if a setting value has been changed and is waiting for change confirmation. var updating: Bool { get } /// Current source setting. var source: CopilotSource { get set } } /// :nodoc: /// CoPilot description @objc(GSCoPilotDesc) public class CopilotDesc: NSObject, PeripheralClassDesc { public typealias ApiProtocol = Copilot public let uid = PeripheralUid.copilot.rawValue public let parent: ComponentDescriptor? = nil }
36.638889
117
0.716452
67fe280f328934c1d3040ecdd0c78cd841826b86
996
// // PadForOSCHINATests.swift // PadForOSCHINATests // // Created by hulianghai on 16/7/26. // Copyright © 2016年 hulianghai. All rights reserved. // import XCTest @testable import PadForOSCHINA class PadForOSCHINATests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
26.918919
111
0.643574
211bf17255c45e0fd8be1fd0210efbdea1688bae
691
// // ReleaseCell.swift // SwiftHub // // Created by Sygnoos9 on 4/12/19. // Copyright © 2019 Khoren Markosyan. All rights reserved. // import UIKit class ReleaseCell: DefaultTableViewCell { override func makeUI() { super.makeUI() leftImageView.cornerRadius = 25 secondDetailLabel.numberOfLines = 0 } override func bind(to viewModel: DefaultTableViewCellViewModel) { super.bind(to: viewModel) guard let viewModel = viewModel as? ReleaseCellViewModel else { return } leftImageView.rx.tap().map { _ in viewModel.release.author }.filterNil() .bind(to: viewModel.userSelected).disposed(by: cellDisposeBag) } }
25.592593
80
0.675832
f4a5aad1ab97ef9c27cc849cd5af1bc9cf9de77a
4,486
import UIKit import MonorailSwift open class MonorailFileViewer: UITableViewController, UISearchResultsUpdating { public init(_ jsonFile: URL) { reader = APIServiceReader(file: jsonFile) super.init(style: .plain) } @available(*, unavailable) required public init?(coder aDecoder: NSCoder) { fatalError("Never happen!") } enum Order: String { case ascendant = "⇡" case descendant = "⇣" mutating func toggle() { self = .ascendant == self ? .descendant : .ascendant } } private var reader: APIServiceReader! private var selectedIndex: Int? private var order: Order = .ascendant private var orderButton: UIBarButtonItem! private var searchText: String? private let searchController = UISearchController(searchResultsController: nil) private var interactions: [Interaction] = [] override open func viewDidLoad() { super.viewDidLoad() title = reader.fileName interactions = reader.interactions orderButton = UIBarButtonItem(title: order.rawValue, style: .plain, target: self, action: #selector(didTapOrder)) let searchButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.search, target: self, action: #selector(didTapSearch)) navigationItem.rightBarButtonItems = [orderButton, searchButton] searchController.searchResultsUpdater = self if #available(iOS 9.1, *) { searchController.obscuresBackgroundDuringPresentation = false } if #available(iOS 11.0, *) { navigationItem.searchController = searchController } else { navigationItem.titleView = searchController.searchBar } definesPresentationContext = true } // MARK: - Table view data source override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return interactions.count } override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "Interaction" let cell: UITableViewCell if let reuseCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) { cell = reuseCell } else { cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier) } let interaction = interactions[indexPath.row] cell.textLabel?.text = "\(interaction.path ?? "")" cell.accessoryType = .disclosureIndicator cell.detailTextLabel?.text = interaction.details return cell } override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let interaction = interactions[indexPath.row] let vc = InteractionViewer.init(interaction) navigationController?.pushViewController(vc, animated: true) } @objc func didTapOrder(sender: AnyObject) { order.toggle() updateInteractions() } @objc func didTapSearch(sender: AnyObject) { searchController.searchBar.becomeFirstResponder() } func updateInteractions() { orderButton.title = order.rawValue interactions = reader.interactions if let searchText = searchText, !searchText.isEmpty { interactions = reader.interactions.filter() { $0.path?.range(of: searchText, options: .caseInsensitive) != nil ? true : false } } if case Order.descendant = order { interactions.reverse() } tableView.reloadData() } public func updateSearchResults(for searchController: UISearchController) { searchText = searchController.searchBar.text updateInteractions() } } extension Interaction { var details: String { guard let response = responseObjects().0 else { return "-" } return "\(response.statusCode), \(timeStampString)" } var timeStampString: String { return timeStamp?.asString(format: "dd/MM/yyyy HH:mm:ss") ?? "" } } extension Date { func asString(format: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: self) } }
32.042857
145
0.636202
dee2f50f8b90fead05b8d1dcbb890a66c1273fda
592
// // AppDelegate.swift // DouyuTV // // Created by 陈伟涵 on 2016/10/11. // Copyright © 2016年 cweihan. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UITabBar.appearance().tintColor = UIColor.orange return true } }
19.096774
144
0.66723
f851a6f617ecc0a3d42fdc394705618e6b1f09e2
1,236
// // Tests_macOS.swift // Tests macOS // // Created by BJ Miller on 7/26/20. // import XCTest class TestsmacOS: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } }
30.9
178
0.709547
1ab092fb4069b7cdd243aaddc71794ec1ed01971
168
import UIKit.UIViewController public protocol ScheduleComponentFactory { func makeScheduleComponent(_ delegate: ScheduleComponentDelegate) -> UIViewController }
21
89
0.833333
0eb067f2fb456de8c885decf0f383a4cf2d322b9
1,700
import UIKit /** Data that will be directed out of the `PurchaseMenuPresenter` to the `PurchaseMenuViewController`. This protocol stores the presentation logic methods. */ protocol PurchaseMenuPresenterOutput: class { /// Triggers an update with the new view model. /// /// - parameter viewModel: View model which will be applied. func update(with viewModel: PurchaseMenuViewModel) } /** Formats the response into a `PurchaseMenuViewModel` and pass the result back to the `PurchaseMenuViewController`. The `PurchaseMenuPresenter` will be in charge of the presentation logic. This component decides how the data will be presented to the user. Also, when there is a need for transition, it will communicate with the `PurchaseMenuRouter`. */ final class PurchaseMenuPresenter { private(set) unowned var output: PurchaseMenuPresenterOutput private(set) var router: PurchaseMenuRouterProtocol // MARK: - Initializers /// This will initialize the `PurchaseMenuPresenter` using /// a given `PurchaseMenuPresenterOutput` and `PurchaseMenuRouter`. /// /// - Parameter output: A reference to the used output. /// - Parameter router: A reference to the used router. init(output: PurchaseMenuPresenterOutput, router: PurchaseMenuRouterProtocol) { self.output = output self.router = router } } // MARK: - PurchaseMenuInteractorOutput extension PurchaseMenuPresenter: PurchaseMenuInteractorOutput { // MARK: - Presentation logic func update(with viewModel: PurchaseMenuViewModel) { output.update(with: viewModel) } func closePurchaseMenu() { router.dismissPurchaseMenu() } }
30.909091
83
0.728824
e64b6764a3adb1e4d824b98772b57f41a2a1f225
1,435
import Foundation import XCTest @testable import Alembic final class JSONTest: XCTestCase { private let jsonString = "{\"key\": \"value\"}" private lazy var jsonData: Data = self.jsonString.data(using: .utf8)! func testInitializeFromAny() { let json: JSON = ["key": "value"] XCTAssertEqual(json.rawValue, ["key": "value"]) } func testInitializeFromData() { do { let json = try JSON(data: self.jsonData) XCTAssertEqual(json.rawValue, ["key": "value"]) } catch { XCTFail("error: \(error)") } } func testInitializeFromString() { do { let json = try JSON(string: self.jsonString) XCTAssertEqual(json.rawValue, ["key": "value"]) } catch { XCTFail("error: \(error)") } } } private func XCTAssertEqual<T, U: Equatable>(_ expression1: Any, _ expression2: [T : U], file: StaticString = #file, line: UInt = #line) { let equal = (expression1 as? [T: U]).map { $0 == expression2 } ?? false XCTAssert(equal, file: file, line: line) } extension JSONTest { static var allTests: [(String, (JSONTest) -> () throws -> Void)] { return [ ("testInitializeFromAny", testInitializeFromAny), ("testInitializeFromData", testInitializeFromData), ("testInitializeFromString", testInitializeFromString) ] } }
30.531915
138
0.583972
bf3579af2659b7f2c7e7ab2e6177494e8c9d0bdf
1,844
// // AppDelegate.swift // CamKit // // Created by riajur-bitsmedia on 09/16/2021. // Copyright (c) 2021 riajur-bitsmedia. All rights reserved. // import UIKit import CamKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
39.234043
285
0.746204
fe2d6acc1512345ef4b9d1f7ae048f0eaad60538
1,247
// // GameType.swift // Thirteen // // Created by Wilhelm Thieme on 20/10/2020. // Copyright © 2020 Wilhelm Thieme. All rights reserved. // import Foundation enum GameType: String, CaseIterable { case classic case hardcore case big var boardType: Board.Type { switch self { case .classic: return ClassicBoard.self case .hardcore: return HardcoreBoard.self case .big: return BigBoard.self } } var localizedTitle: String { return localizedString("\(rawValue)GameType")} var highscore: Int { get { UserDefaults.standard.integer(forKey: "\(rawValue)Highscore") } set { UserDefaults.standard.set(newValue, forKey: "\(rawValue)Highscore")} } static var current: GameType { get { GameType(rawValue: UserDefaults.standard.string(forKey: "currentGametype") ?? "") ?? .classic } set { UserDefaults.standard.set(newValue.rawValue, forKey: "currentGametype") } } var scoreboardId: String { switch self { case .classic: return "com.wjthieme.Thirteen" case .hardcore: return "com.wjthieme.Thirteen.Hardcore" case .big: return "com.wjthieme.Thirteen.Big" } } }
27.108696
109
0.631917
87b1efeb2cea73dcf8e5c2b8700a093673f22a75
1,048
// // JumpComponent.swift // MyGame // // Created by Ramires Moreira on 01/03/19. // Copyright © 2019 Ramires Moreira. All rights reserved. // import GameKit class JumpComponent: GKComponent { let node : SKSpriteNode private var animationComponent: MovementComponent? var soundFileName : String? init(withNode node: SKSpriteNode, animation : MovementComponent? = nil) { self.node = node self.animationComponent = animation super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func jump(_ vector: CGVector) { if node.physicsBody?.velocity.dy == 0 { node.physicsBody?.applyImpulse(vector) } if let file = soundFileName { let sound = SKAction.playSoundFileNamed(file, waitForCompletion: false) node.run(sound) } } func jump(y : CGFloat) { let vector = CGVector(dx: 0, dy: y) jump(vector) } }
23.818182
83
0.605916
230e03cd2c69fe73ecc686154577b884b9af8b52
1,104
import Foundation class PluginRTCPeerConnectionConfig { private var iceServers: [RTCICEServer] = [] init(pcConfig: NSDictionary?) { NSLog("PluginRTCPeerConnectionConfig#init()") let iceServers = pcConfig?.objectForKey("iceServers") as? [NSDictionary] if iceServers == nil { return } for iceServer: NSDictionary in iceServers! { let url = iceServer.objectForKey("url") as? String let username = iceServer.objectForKey("username") as? String ?? "" let password = iceServer.objectForKey("credential") as? String ?? "" if (url != nil) { NSLog("PluginRTCPeerConnectionConfig#init() | adding ICE server [url:'%@', username:'%@', password:'******']", String(url!), String(username)) self.iceServers.append(RTCICEServer( URI: NSURL(string: url!), username: username, password: password )) } } } deinit { NSLog("PluginRTCPeerConnectionConfig#deinit()") } func getIceServers() -> [RTCICEServer] { NSLog("PluginRTCPeerConnectionConfig#getIceServers()") return self.iceServers } }
23.489362
115
0.652174
75ae2aee19cd38793c5cf77882cbbde3c4075d42
3,741
// Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // A copy of the License is located at // // http://www.apache.org/licenses/LICENSE-2.0 // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. // // OperationHandler+blockingWithInputWithOutput.swift // SmokeOperations // import Foundation import LoggerAPI public extension OperationHandler { /** Initializer for blocking operation handler that has input returns a result body. - Parameters: - inputProvider: function that obtains the input from the request. - operation: the handler method for the operation. - outputHandler: function that completes the response with the provided output. - allowedErrors: the errors that can be serialized as responses from the operation and their error codes. - operationDelegate: optionally an operation-specific delegate to use when handling the operation. */ init<InputType: Validatable, OutputType: Validatable, ErrorType: ErrorIdentifiableByDescription, OperationDelegateType: OperationDelegate>( operationIdentifer: OperationIdentifer, inputProvider: @escaping (RequestHeadType, Data?) throws -> InputType, operation: @escaping (InputType, ContextType) throws -> OutputType, outputHandler: @escaping ((RequestHeadType, OutputType, ResponseHandlerType) -> Void), allowedErrors: [(ErrorType, Int)], operationDelegate: OperationDelegateType) where RequestHeadType == OperationDelegateType.RequestHeadType, ResponseHandlerType == OperationDelegateType.ResponseHandlerType { /** * The wrapped input handler takes the provided operation handler and wraps it so that if it * returns, the responseHandler is called with the result. If the provided operation * throws an error, the responseHandler is called with that error. */ let wrappedInputHandler = { (input: InputType, requestHead: RequestHeadType, context: ContextType, responseHandler: OperationDelegateType.ResponseHandlerType) in let handlerResult: WithOutputOperationHandlerResult<OutputType, ErrorType> do { let output = try operation(input, context) handlerResult = .success(output) } catch let smokeReturnableError as SmokeReturnableError { handlerResult = .smokeReturnableError(smokeReturnableError, allowedErrors) } catch SmokeOperationsError.validationError(reason: let reason) { handlerResult = .validationError(reason) } catch { handlerResult = .internalServerError(error) } OperationHandler.handleWithOutputOperationHandlerResult( handlerResult: handlerResult, operationDelegate: operationDelegate, requestHead: requestHead, responseHandler: responseHandler, outputHandler: outputHandler) } self.init(operationIdentifer: operationIdentifer, inputHandler: wrappedInputHandler, inputProvider: inputProvider, operationDelegate: operationDelegate) } }
46.7625
106
0.672547
1117240cbab50fb8a6669d6273c009644880eaa6
1,286
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation public class Interval: APIModel { public var stopId: String? public var timeToArrival: Double? public init(stopId: String? = nil, timeToArrival: Double? = nil) { self.stopId = stopId self.timeToArrival = timeToArrival } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) stopId = try container.decodeIfPresent("stopId") timeToArrival = try container.decodeIfPresent("timeToArrival") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(stopId, forKey: "stopId") try container.encodeIfPresent(timeToArrival, forKey: "timeToArrival") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Interval else { return false } guard self.stopId == object.stopId else { return false } guard self.timeToArrival == object.timeToArrival else { return false } return true } public static func == (lhs: Interval, rhs: Interval) -> Bool { return lhs.isEqual(to: rhs) } }
29.227273
77
0.674961
90b26e8ea090c577b2eec51838e96e7aa5af18cf
552
// // WorkerScheduler.swift // My Octocat // // Created by Daniele Vitali on 3/2/16. // Copyright © 2016 Daniele Vitali. All rights reserved. // import Foundation import RxSwift class ComputationalScheduler: ConcurrentDispatchQueueScheduler { private static let instance = ComputationalScheduler() class func sharedInstance() -> ComputationalScheduler { return instance } private init() { let queue = dispatch_queue_create("Worker Scheduler Queue", nil) super.init(queue: queue) } }
22.08
72
0.679348
3318ea4c6673ad6ad24522b8735f1072f5b7b57c
3,222
// // InfiniteScrollingController.swift // InstantSearchCore // // Created by Vladislav Fitc on 05/06/2019. // Copyright © 2019 Algolia. All rights reserved. // import Foundation class InfiniteScrollingController: InfiniteScrollable { public var lastPageIndex: Int? public weak var pageLoader: PageLoadable? private let pendingPageIndexes: SynchronizedSet<Int> public init() { pendingPageIndexes = SynchronizedSet() } public func notifyPending(pageIndex: Int) { pendingPageIndexes.remove(pageIndex) } public func notifyPendingAll() { pendingPageIndexes.removeAll() } internal func isLoadedOrPending<T>(pageIndex: PageMap<T>.PageIndex, pageMap: PageMap<T>) -> Bool { let pageIsLoaded = pageMap.containsPage(atIndex: pageIndex) let pageIsPending = pendingPageIndexes.contains(pageIndex) return pageIsLoaded || pageIsPending } private func pagesToLoad<T>(in range: [Int], from pageMap: PageMap<T>) -> Set<Int> { let pagesContainingRequiredRows = Set(range.map(pageMap.pageIndex(for:))) let pagesToLoad = pagesContainingRequiredRows.filter { !isLoadedOrPending(pageIndex: $0, pageMap: pageMap) } return pagesToLoad } func calculatePagesAndLoad<T>(currentRow: Int, offset: Int, pageMap: PageMap<T>) { guard let pageLoader = pageLoader else { assertionFailure("Missing Page Loader") return } let previousPagesToLoad = computePreviousPagesToLoad(currentRow: currentRow, offset: offset, pageMap: pageMap) let nextPagesToLoad = computeNextPagesToLoad(currentRow: currentRow, offset: offset, pageMap: pageMap) let pagesToLoad = previousPagesToLoad.union(nextPagesToLoad) for pageIndex in pagesToLoad { pendingPageIndexes.insert(pageIndex) pageLoader.loadPage(atIndex: pageIndex) } } func computePreviousPagesToLoad<T>(currentRow: Int, offset: Int, pageMap: PageMap<T>) -> Set<PageMap<T>.PageIndex> { let computedLowerBoundRow = currentRow - offset let lowerBoundRow: Int if computedLowerBoundRow < pageMap.startIndex { lowerBoundRow = pageMap.startIndex } else { lowerBoundRow = computedLowerBoundRow } let requiredRows = Array(lowerBoundRow..<currentRow) return pagesToLoad(in: requiredRows, from: pageMap) } func computeNextPagesToLoad<T>(currentRow: Int, offset: Int, pageMap: PageMap<T>) -> Set<PageMap<T>.PageIndex> { let computedUpperBoundRow = currentRow + offset let upperBoundRow: Int if let lastPageIndex = lastPageIndex { let lastPageSize = pageMap.page(atIndex: lastPageIndex)?.items.count ?? pageMap.pageSize let totalPagesButLastCount = lastPageIndex let lastRowIndex = (totalPagesButLastCount * pageMap.pageSize + lastPageSize) - 1 upperBoundRow = computedUpperBoundRow > lastRowIndex ? lastRowIndex : computedUpperBoundRow } else { upperBoundRow = computedUpperBoundRow } let nextRow = currentRow + 1 guard nextRow <= upperBoundRow else { return [] } let requiredRows = Array(nextRow...upperBoundRow) return pagesToLoad(in: requiredRows, from: pageMap) } }
30.980769
118
0.709497
d6adfe5be7a4de59c6ba2066d63bfb113a923db0
6,978
// // AppDelegate.swift // MTMR // // Created by Anton Palgunov on 16/03/2018. // Copyright © 2018 Anton Palgunov. All rights reserved. // import Cocoa import Sparkle @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) var isBlockedApp: Bool = false private var fileSystemSource: DispatchSourceFileSystemObject? func applicationDidFinishLaunching(_: Notification) { // Configure Sparkle SUUpdater.shared().automaticallyDownloadsUpdates = false SUUpdater.shared().automaticallyChecksForUpdates = true SUUpdater.shared().checkForUpdatesInBackground() AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true] as NSDictionary) TouchBarController.shared.setupControlStripPresence() if let button = statusItem.button { button.image = #imageLiteral(resourceName: "StatusImage") } createMenu() reloadOnDefaultConfigChanged() NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(updateIsBlockedApp), name: NSWorkspace.didLaunchApplicationNotification, object: nil) NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(updateIsBlockedApp), name: NSWorkspace.didTerminateApplicationNotification, object: nil) NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(updateIsBlockedApp), name: NSWorkspace.didActivateApplicationNotification, object: nil) } func applicationWillTerminate(_: Notification) {} @objc func updateIsBlockedApp() { var blacklistAppIdentifiers: [String] = [] if let blackListed = UserDefaults.standard.stringArray(forKey: "com.toxblh.mtmr.blackListedApps") { blacklistAppIdentifiers = blackListed } var frontmostApplicationIdentifier: String? { guard let frontmostId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier else { return nil } return frontmostId } if frontmostApplicationIdentifier != nil { isBlockedApp = blacklistAppIdentifiers.index(of: frontmostApplicationIdentifier!) != nil } else { isBlockedApp = false } createMenu() } @objc func openPreferences(_: Any?) { let task = Process() let appSupportDirectory = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!.appending("/MTMR") let presetPath = appSupportDirectory.appending("/items.json") task.launchPath = "/usr/bin/open" task.arguments = [presetPath] task.launch() } @objc func toggleControlStrip(_: Any?) { TouchBarController.shared.showControlStripState = !TouchBarController.shared.showControlStripState TouchBarController.shared.resetControlStrip() createMenu() } @objc func toggleBlackListedApp(_: Any?) { let appIdentifier = TouchBarController.shared.frontmostApplicationIdentifier if appIdentifier != nil { if let index = TouchBarController.shared.blacklistAppIdentifiers.index(of: appIdentifier!) { TouchBarController.shared.blacklistAppIdentifiers.remove(at: index) } else { TouchBarController.shared.blacklistAppIdentifiers.append(appIdentifier!) } UserDefaults.standard.set(TouchBarController.shared.blacklistAppIdentifiers, forKey: "com.toxblh.mtmr.blackListedApps") UserDefaults.standard.synchronize() TouchBarController.shared.updateActiveApp() updateIsBlockedApp() } } @objc func openPreset(_: Any?) { let dialog = NSOpenPanel() dialog.title = "Choose a items.json file" dialog.showsResizeIndicator = true dialog.showsHiddenFiles = true dialog.canChooseDirectories = false dialog.canCreateDirectories = false dialog.allowsMultipleSelection = false dialog.allowedFileTypes = ["json"] dialog.directoryURL = NSURL.fileURL(withPath: NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!.appending("/MTMR"), isDirectory: true) if dialog.runModal() == .OK, let path = dialog.url?.path { TouchBarController.shared.reloadPreset(path: path) } } @objc func toggleStartAtLogin(_: Any?) { LaunchAtLoginController().setLaunchAtLogin(!LaunchAtLoginController().launchAtLogin, for: NSURL.fileURL(withPath: Bundle.main.bundlePath)) createMenu() } func createMenu() { let menu = NSMenu() let startAtLogin = NSMenuItem(title: "Start at login", action: #selector(toggleStartAtLogin(_:)), keyEquivalent: "L") startAtLogin.state = LaunchAtLoginController().launchAtLogin ? .on : .off let toggleBlackList = NSMenuItem(title: "Toggle current app in blacklist", action: #selector(toggleBlackListedApp(_:)), keyEquivalent: "B") toggleBlackList.state = isBlockedApp ? .on : .off let hideControlStrip = NSMenuItem(title: "Hide Control Strip", action: #selector(toggleControlStrip(_:)), keyEquivalent: "T") hideControlStrip.state = TouchBarController.shared.showControlStripState ? .off : .on let settingSeparator = NSMenuItem(title: "Settings", action: nil, keyEquivalent: "") settingSeparator.isEnabled = false menu.addItem(withTitle: "Preferences", action: #selector(openPreferences(_:)), keyEquivalent: ",") menu.addItem(withTitle: "Open preset", action: #selector(openPreset(_:)), keyEquivalent: "O") menu.addItem(withTitle: "Check for Updates...", action: #selector(SUUpdater.checkForUpdates(_:)), keyEquivalent: "").target = SUUpdater.shared() menu.addItem(NSMenuItem.separator()) menu.addItem(settingSeparator) menu.addItem(hideControlStrip) menu.addItem(toggleBlackList) menu.addItem(startAtLogin) menu.addItem(NSMenuItem.separator()) menu.addItem(withTitle: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") statusItem.menu = menu } func reloadOnDefaultConfigChanged() { let file = NSURL.fileURL(withPath: standardConfigPath) let fd = open(file.path, O_EVTONLY) fileSystemSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: .write, queue: DispatchQueue(label: "DefaultConfigChanged")) fileSystemSource?.setEventHandler(handler: { print("Config changed, reloading...") DispatchQueue.main.async { TouchBarController.shared.reloadPreset(path: file.path) } }) fileSystemSource?.setCancelHandler(handler: { close(fd) }) fileSystemSource?.resume() } }
42.290909
188
0.693895
235e8a71ca77342886fc913d15e773edb64b5d56
2,910
// // UIViewController+Rx.swift // Spin.UIKit.Demo // // Created by Thibault Wittemberg on 2020-01-01. // Copyright © 2020 Spinners. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit import RxCocoa import RxSwift public extension Reactive where Base: UIViewController { var viewDidLoad: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.viewDidLoad)).map { _ in } return ControlEvent(events: source) } var viewWillAppear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewWillAppear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } var viewDidAppear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewDidAppear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } var viewWillDisappear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewWillDisappear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } var viewDidDisappear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewDidDisappear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } var viewWillLayoutSubviews: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.viewWillLayoutSubviews)).map { _ in } return ControlEvent(events: source) } var viewDidLayoutSubviews: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.viewDidLayoutSubviews)).map { _ in } return ControlEvent(events: source) } var willMoveToParentViewController: ControlEvent<UIViewController?> { let source = self.methodInvoked(#selector(Base.willMove)).map { $0.first as? UIViewController } return ControlEvent(events: source) } var didMoveToParentViewController: ControlEvent<UIViewController?> { let source = self.methodInvoked(#selector(Base.didMove)).map { $0.first as? UIViewController } return ControlEvent(events: source) } var didReceiveMemoryWarning: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.didReceiveMemoryWarning)).map { _ in } return ControlEvent(events: source) } /// Rx observable, triggered when the ViewController appearance state changes (true if the View is being displayed, false otherwise) var isVisible: Observable<Bool> { let viewDidAppearObservable = self.base.rx.viewDidAppear.map { _ in true } let viewWillDisappearObservable = self.base.rx.viewWillDisappear.map { _ in false } return Observable<Bool>.merge(viewDidAppearObservable, viewWillDisappearObservable) } /// Rx observable, triggered when the ViewController is being dismissed var isDismissing: ControlEvent<Bool> { let source = self.sentMessage(#selector(Base.dismiss)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } } #endif
37.792208
134
0.732302
5ddc6f7b9bc2af224af6b5e6e1a588434d5f7978
767
// // ExpressionTests.swift // iFlexCocoaDemoTests // // Created by Thriller on 6/11/20. // Copyright © 2020 CocoaPods. All rights reserved. // import XCTest @testable import iFlexCocoa class ExpressionTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testJSScript() throws { let jsScript = "js:onClick" let e = Expression.init(raw: jsScript) e.execute { (r) in XCTAssertNotNil(r) } } }
23.242424
111
0.642764
dbd1c93217f878288f28127809cc598a6220c85a
4,304
// // domain.swift // ScrapeMESwiftly // // Created by Samuel Barthelemy on 5/25/16. // Copyright © 2016 Samuel Barthelemy. All rights reserved. // import Foundation class Domain { var domain: String var html: String var noNewLineElements: [String] var subPages: [String] init(domain: String) { self.domain = domain self.html = "" self.noNewLineElements = [String]() self.subPages = [String]() } func connectToDomain(page: String?) -> String { var site: NSURL! var status = "Running...." if let page = page { if page.containsString("http") { site = NSURL(string:page) } else if !page.containsString("http") && page.containsString("/") { site = NSURL(string:self.domain+page) } else { site = NSURL(string:self.domain+"/"+page) } } else { site = NSURL(string:self.domain) } status = "Querying: \(site)" if site != nil { do { html = try String(contentsOfURL: site, encoding: NSUTF8StringEncoding) } catch _{ status = "Could not query \(site) have you tried https?" } } else { status = "Invalid Website" } return status } func linkParser(html: String) { var elementStarted = false var elements = [String]() var elementString = "" for char in html.characters { if char == "<" && elementStarted == true { elementStarted = false elements.append(elementString) elementString = "" } elementString += String(char) if char == "<" && elementStarted == false { elementStarted = true } } for element in elements { let noWhiteSpace = element.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) noNewLineElements.append(noWhiteSpace.stringByReplacingOccurrencesOfString("\n", withString: "", options: NSStringCompareOptions.LiteralSearch, range:nil)) } } func grabLinks() -> String { var grabbedElements = "" var linkArray = [String]() for element in Array(Set(noNewLineElements)) { if element.containsString("href") { if let found = element.rangeOfString("(?<=\")[^\"]+", options: .RegularExpressionSearch) { if element.substringWithRange(found).containsString("/") || element.substringWithRange(found).containsString(".html"){ subPages.append(element.substringWithRange(found)) } linkArray.append((element.substringWithRange(found))) } } } subPages = Array(Set(subPages)) linkArray = Array(Set(linkArray)) for link in linkArray { grabbedElements += (link+"\n") } return grabbedElements } func grabEmail() -> [String] { var grabbedElements = [String]() for element in Array(Set(noNewLineElements)) { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" if let found = element.rangeOfString(emailRegEx, options:.RegularExpressionSearch) { grabbedElements.append(element.substringWithRange(found)) } } return grabbedElements } func spiderPages() -> String { var emailAddresses = "" var emails = [String]() for page in subPages { _ = connectToDomain(page) linkParser(html) emails = grabEmail() } emails = Array(Set(emails)) for email in emails { emailAddresses += email+"\n" } return emailAddresses } func delay(delay: Double, closure: ()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure ) } }
31.188406
168
0.523467
724334b2daa1583fd93feffd7226f07445638ca5
2,617
// // UserCell.swift // custom_iMessage_clone // // Created by William X. on 2/21/19. // Copyright © 2019 Will Xu . All rights reserved. // import UIKit import Firebase class UserCell: UITableViewCell { var message: Message? { didSet { setupName() } } private func setupName() { if let toId = message?.chatPartnerId() { let ref = Database.database().reference().child("users").child(toId) ref.observeSingleEvent(of: .value) { (snapshot) in if let dic = snapshot.value as? [String: Any] { self.textLabel?.text = dic["name"] as? String } } } detailTextLabel?.text = message?.text if let seconds = message?.timestamp?.doubleValue { let ts = Date(timeIntervalSince1970: seconds) let dateFormat = DateFormatter() dateFormat.dateFormat = "h:mm a" timeLabel.text = dateFormat.string(from: ts) } } let timeLabel: UILabel = { let label = UILabel() // label.text = "HH:MM" label.translatesAutoresizingMaskIntoConstraints = false label.textColor = UIColor.lightGray label.textAlignment = .right label.font = UIFont.systemFont(ofSize: 14) return label }() override func layoutSubviews() { super.layoutSubviews() textLabel?.frame = CGRect(x: 16, y: 5, width: textLabel!.frame.width, height: textLabel!.frame.height) textLabel?.font = UIFont.systemFont(ofSize: (textLabel?.font.pointSize)!, weight: UIFont.Weight.semibold) detailTextLabel?.frame = CGRect(x: 16, y: 27, width: detailTextLabel!.frame.width, height: detailTextLabel!.frame.height) detailTextLabel?.textColor = UIColor.gray detailTextLabel?.font = UIFont.systemFont(ofSize: (textLabel?.font.pointSize)! - 2) } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) self.layoutSubviews() addSubview(timeLabel) timeLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -16).isActive = true timeLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true timeLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true timeLabel.heightAnchor.constraint(equalTo: (textLabel?.heightAnchor)!).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init not declared") } }
36.347222
129
0.6282
5be9ce0d8a4f686b2f7628dd97046b88e40003f5
3,396
import QuartzCore import simd //public extension float4 { // var xyz: SIMD3<Float> { // return SIMD3<Float>(x, y, z) // } // // init(_ v: SIMD3<Float>, _ w: Float) { // self.init(v.x, v.y, v.z, w) // } //} // https://stackoverflow.com/questions/59915812/how-to-translate-float3-to-simd3float-xcode-11-swift-5-giving-depreciation-wa extension SIMD4 { var xyz: SIMD3<Scalar> { SIMD3(x, y, z) } init(_ v: SIMD3<Scalar>, _ w: Scalar) { self.init(v.x, v.y, v.z, w) } } public struct packed_float3 { var x, y, z: Float init(_ x: Float, _ y: Float, _ z: Float) { self.x = x self.y = y self.z = z } init(_ v: SIMD3<Float>) { self.x = v.x self.y = v.y self.z = v.z } } public extension float3x3 { init(affineTransform m: CGAffineTransform) { self.init(SIMD3<Float>(Float( m.a), Float( m.b), 0), SIMD3<Float>(Float( m.c), Float( m.d), 0), SIMD3<Float>(Float(m.tx), Float(m.ty), 1)) } } public extension float4x4 { init(translationBy t: SIMD3<Float>) { self.init(SIMD4<Float>(1, 0, 0, 0), SIMD4<Float>(0, 1, 0, 0), SIMD4<Float>(0, 0, 1, 0), SIMD4<Float>(t.x, t.y, t.z, 1)) } init(rotationFrom q: simd_quatf) { let (x, y, z) = (q.imag.x, q.imag.y, q.imag.z) let w = q.real self.init(SIMD4<Float>( 1 - 2*y*y - 2*z*z, 2*x*y + 2*z*w, 2*x*z - 2*y*w, 0), SIMD4<Float>( 2*x*y - 2*z*w, 1 - 2*x*x - 2*z*z, 2*y*z + 2*x*w, 0), SIMD4<Float>( 2*x*z + 2*y*w, 2*y*z - 2*x*w, 1 - 2*x*x - 2*y*y, 0), SIMD4<Float>( 0, 0, 0, 1)) } init(rotationFromEulerAngles v: SIMD3<Float>) { let sx = sin(v.x) let cx = cos(v.x) let sy = sin(v.y) let cy = cos(v.y) let sz = sin(v.z) let cz = cos(v.z) let columns = [ SIMD4<Float>( cy*cz, cy*sz, -sy, 0), SIMD4<Float>(cz*sx*sy - cx*sz, cx*cz + sx*sy*sz, cy*sx, 0), SIMD4<Float>(cx*cz*sy + sx*sz, -cz*sx + cx*sy*sz, cx*cy, 0), SIMD4<Float>( 0, 0, 0, 1) ] self.init(columns) } init(scaleBy s: SIMD3<Float>) { self.init([SIMD4<Float>(s.x, 0, 0, 0), SIMD4<Float>(0, s.y, 0, 0), SIMD4<Float>(0, 0, s.z, 0), SIMD4<Float>(0, 0, 0, 1)]) } var upperLeft: float3x3 { return float3x3(self[0].xyz, self[1].xyz, self[2].xyz) } // public init(perspectiveProjectionFOV fov: Float, near: Float, far: Float) { // let s = 1 / tanf(fov * 0.5) // let q = -far / (far - near) // // let columns = [ float4(s, 0, 0, 0), // float4(0, s, 0, 0), // float4(0, 0, q, -1), // float4(0, 0, q * near, 0) ] // self.init(columns) // } } public extension float3x3 { func decomposeToEulerAngles() -> SIMD3<Float> { let rotX = atan2( self[1][2], self[2][2]) let rotY = atan2(-self[0][2], hypot(self[1][2], self[2][2])) let rotZ = atan2( self[0][1], self[0][0]) return SIMD3<Float>(rotX, rotY, rotZ) } }
30.872727
129
0.457597
87199c337528394305ba6202e358d30a3fb817de
1,127
import Cocoa class Trie { var children = Array<Trie?>(repeating: nil, count: 26) var isEnd = false init() { } func insert(_ word: String) { var node = self for ch in word.unicodeScalars { let index = Int(ch.value - "a".unicodeScalars.first!.value) if node.children[index] == nil { node.children[index] = Trie() } node = node.children[index]! } node.isEnd = true } func searchPrefix(_ word: String) -> Trie? { var node = self for ch in word.unicodeScalars { let index = Int(ch.value - "a".unicodeScalars.first!.value) if node.children[index] == nil { return nil } node = node.children[index]! } return node } func search(_ word: String) -> Bool { let node = self.searchPrefix(word) return node != nil && node!.isEnd == true } func startsWith(_ prefix: String) -> Bool { return self.searchPrefix(prefix) != nil } }
23.978723
71
0.501331
75ede94343698b28d6f4f31b8cef2c480c475742
1,300
// // ProcessAdTask.swift // AwesomeAdsDemo // // Created by Gabriel Coman on 10/10/2017. // Copyright © 2017 Gabriel Coman. All rights reserved. // import UIKit import SuperAwesome import RxSwift class ProcessAdTask: Task { typealias Input = ProcessAdRequest typealias Output = SAResponse typealias Result = Single<Output> func execute(withInput input: ProcessAdRequest) -> Single<SAResponse> { let payload = input.ad.jsonPreetyStringRepresentation() let testPlacement = 10000; let loader: SALoader = SALoader () let session: SASession = SASession () return Single.create { subscriber -> Disposable in loader.processAd(testPlacement, andData: payload, andStatus: 200, andSession: session, andResult: { (response: SAResponse?) in if let response = response, response.isValid () { (response.ads?.firstObject as? SAAd)?.isPadlockVisible = true subscriber(.success(response)) } else { subscriber(.error(AAError.ParseError)) } }) return Disposables.create() } } }
28.26087
138
0.566923
ede3818b2fc5a08dcfe54ff983d20993b6484d4d
3,849
// // soupCategoryViewController.swift // Pizza // // Created by Eva on 27/06/2017. // Copyright © 2017 Eva. All rights reserved. // import UIKit class soupCategoryViewController: UIViewController { @IBOutlet weak var firstSoupItemName: UILabel! @IBOutlet weak var firstSoupItemImage: UIImageView! @IBOutlet weak var firstSoupItemPrice: UILabel! @IBOutlet weak var secondSoupItemName: UILabel! @IBOutlet weak var secondSoupItemImage: UIImageView! @IBOutlet weak var secondSoupItemPrice: UILabel! @IBOutlet weak var thirdSoupItemName: UILabel! @IBOutlet weak var thirdSoupItemImage: UIImageView! @IBOutlet weak var thirdSoupItemPrice: UILabel! @IBOutlet weak var fourthSoupItemName: UILabel! @IBOutlet weak var fourthSoupItemImage: UIImageView! @IBOutlet weak var fourthSoupItemPrice: UILabel! @IBOutlet weak var totalItemsInCart: UILabel! override func viewDidLoad() { super.viewDidLoad() //Assigning Values firstSoupItemName.text = "Egusi Soup" firstSoupItemImage.image = #imageLiteral(resourceName: "egusi_soup") firstSoupItemPrice.text = "N300" secondSoupItemName.text = "Okro Soup" secondSoupItemImage.image = #imageLiteral(resourceName: "okro_soup") secondSoupItemPrice.text = "N350" thirdSoupItemName.text = "Ogbono Soup" thirdSoupItemImage.image = #imageLiteral(resourceName: "ogbono_soup2") thirdSoupItemPrice.text = "N150" fourthSoupItemName.text = "Eforiro Soup" fourthSoupItemImage.image = #imageLiteral(resourceName: "eforiro_soup") fourthSoupItemPrice.text = "N600" totalItemsInCart.text = String(anonymousUser.numberOfItemsInCart()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onClick_AddToCartButton(_ sender: UIButton) { let whichAddToCartButtonClicked = sender.title(for: .normal) switch whichAddToCartButtonClicked { case "addToCartButton1"?: let item = firstSoupItemName.text!.lowercased() _ = anonymousUser.addToCart(itemNameAndQuantity: [item: 1]) totalItemsInCart.text = String(anonymousUser.numberOfItemsInCart()) break case "addToCartButton2"?: let item = secondSoupItemName.text!.lowercased() _ = anonymousUser.addToCart(itemNameAndQuantity: [item: 1]) totalItemsInCart.text = String(anonymousUser.numberOfItemsInCart()) break case "addToCartButton3"?: let item = thirdSoupItemName.text!.lowercased() _ = anonymousUser.addToCart(itemNameAndQuantity: [item: 1]) totalItemsInCart.text = String(anonymousUser.numberOfItemsInCart()) break case "addToCartButton4"?: let item = fourthSoupItemName.text!.lowercased() _ = anonymousUser.addToCart(itemNameAndQuantity: [item: 1]) totalItemsInCart.text = String(anonymousUser.numberOfItemsInCart()) break default: totalItemsInCart.text = String(anonymousUser.numberOfItemsInCart()) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
31.040323
106
0.645622
64ea90aa75ccb1cda60907904199abbaa7829a00
1,656
// // MeTableViewController.swift // meinv // // Created by tropsci on 16/3/15. // Copyright © 2016年 topsci. All rights reserved. // import UIKit class MeTableViewController: UITableViewController { var dataList = [String]() weak var centerViewController: CenterViewController? override func viewDidLoad() { super.viewDidLoad() setupDataList() tableView.tableFooterView = UIView() } // MARK: - Private Methods func setupDataList() { dataList.append("我点过的赞") dataList.append("退出登录") dataList.append("关于") } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataList.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("me_cell_id", forIndexPath: indexPath) cell.textLabel?.text = dataList[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
28.551724
118
0.677536
edc7a602a6d3e02b23741b3714c2c0bdaebb480f
3,776
// // CPYSnippetsEditorCell.swift // // Clipy // GitHub: https://github.com/clipy // HP: https://clipy-app.com // // Created by Econa77 on 2016/07/02. // // Copyright © 2015-2018 Clipy Project. // import Foundation import Cocoa final class CPYSnippetsEditorCell: NSTextFieldCell { // MARK: - Properties var iconType = IconType.folder var isItemEnabled = false override var cellSize: NSSize { var size = super.cellSize size.width += 3.0 + 16.0 return size } // MARK: - Enums enum IconType { case folder, none } // MARK: - Initialize required init(coder: NSCoder) { super.init(coder: coder) font = NSFont.systemFont(ofSize: 14) } override func copy(with zone: NSZone?) -> Any { guard let cell = super.copy(with: zone) as? CPYSnippetsEditorCell else { return super.copy(with: zone) } cell.iconType = iconType return cell } // MARK: - Draw override func draw(withFrame cellFrame: NSRect, in controlView: NSView) { var newFrame: NSRect switch iconType { case .folder: var imageFrame = NSRect.zero var cellFrame = cellFrame NSDivideRect(cellFrame, &imageFrame, &cellFrame, 15, .minX) imageFrame.origin.x += 5 imageFrame.origin.y += 5 imageFrame.size = NSSize(width: 16, height: 13) let drawImage = (isHighlighted) ? NSImage(assetIdentifier: .snippetsIconFolderWhite) : NSImage(assetIdentifier: .snippetsIconFolder) drawImage.size = NSSize(width: 16, height: 13) drawImage.draw(in: imageFrame, from: NSRect.zero, operation: .sourceOver, fraction: 1.0, respectFlipped: true, hints: nil) newFrame = cellFrame newFrame.origin.x += 8 newFrame.origin.y += 2 newFrame.size.height -= 2 case .none: newFrame = cellFrame newFrame.origin.y += 2 newFrame.size.height -= 2 } textColor = (!isItemEnabled) ? .lightGray : (isHighlighted) ? .white : .titleColor() super.draw(withFrame: newFrame, in: controlView) } // MARK: - Frame override func select(withFrame aRect: NSRect, in controlView: NSView, editor textObj: NSText, delegate anObject: Any?, start selStart: Int, length selLength: Int) { let textFrame = titleRect(forBounds: aRect) textColor = .titleColor() super.select(withFrame: textFrame, in: controlView, editor: textObj, delegate: anObject, start: selStart, length: selLength) } override func edit(withFrame aRect: NSRect, in controlView: NSView, editor textObj: NSText, delegate anObject: Any?, event theEvent: NSEvent?) { let textFrame = titleRect(forBounds: aRect) super.edit(withFrame: textFrame, in: controlView, editor: textObj, delegate: anObject, event: theEvent) } override func titleRect(forBounds theRect: NSRect) -> NSRect { switch iconType { case .folder: var imageFrame = NSRect.zero var cellRect = NSRect.zero NSDivideRect(theRect, &imageFrame, &cellRect, 15, .minX) imageFrame.origin.x += 5 imageFrame.origin.y += 4 imageFrame.size = CGSize(width: 16, height: 15) imageFrame.origin.y += ceil((cellRect.size.height - imageFrame.size.height) / 2) var newFrame = cellRect newFrame.origin.x += 10 newFrame.origin.y += 2 newFrame.size.height -= 2 return newFrame case .none: var newFrame = theRect newFrame.origin.y += 2 newFrame.size.height -= 2 return newFrame } } }
32
168
0.608581
0a6930a02a00e57dbd9c4e82d5861da008a3d4a7
597
import Foundation /** A class that encapsulates information about an example, including the index at which the example was executed, as well as the example itself. */ public final class ExampleMetadata: NSObject { /** The example for which this metadata was collected. */ public let example: Example /** The index at which this example was executed in the test suite. */ public let exampleIndex: Int internal init(example: Example, exampleIndex: Int) { self.example = example self.exampleIndex = exampleIndex } }
23.88
60
0.666667