How to use RawTypeRepository class

Best Mockingbird code snippet using RawTypeRepository

MockableType.swift

Source:MockableType.swift Github

copy

Full Screen

...76 mockableTypes: [String: MockableType],77 moduleNames: [String],78 specializationContexts: [String: SpecializationContext],79 opaqueInheritedTypeNames: Set<String>,80 rawTypeRepository: RawTypeRepository,81 typealiasRepository: TypealiasRepository) {82 guard let baseRawType = rawTypes.findBaseRawType(),83 baseRawType.kind.isMockable84 else { return nil }85 self.baseRawType = baseRawType86 self.filePath = baseRawType.parsedFile.path87 88 let accessLevel = AccessLevel(from: baseRawType.dictionary) ?? .defaultLevel89 guard accessLevel.isMockableType(withinSameModule: baseRawType.parsedFile.shouldMock)90 else { return nil }91 // Handle empty types (declared without any members).92 let substructure = baseRawType.dictionary[SwiftDocKey.substructure.rawValue]93 as? [StructureDictionary] ?? []94 95 var attributes = Attributes()96 rawTypes.forEach({ attributes.formUnion(Attributes(from: $0.dictionary)) })97 self.attributes = attributes98 guard !attributes.contains(.final) else { return nil }99 100 self.name = baseRawType.name101 self.moduleName = baseRawType.parsedFile.moduleName102 self.fullyQualifiedName = baseRawType.fullyQualifiedName103 self.fullyQualifiedModuleName = DeclaredType(from: baseRawType.fullyQualifiedModuleName)104 .serialize(105 with: SerializationRequest(106 method: .moduleQualified,107 context: SerializationRequest.Context(108 moduleNames: moduleNames,109 rawType: baseRawType,110 rawTypeRepository: rawTypeRepository),111 options: .standard))112 self.kind = baseRawType.kind113 self.accessLevel = accessLevel114 self.isContainedType = !baseRawType.containingTypeNames.isEmpty115 self.shouldMock = baseRawType.parsedFile.shouldMock116 self.genericTypeContext = baseRawType.genericTypeContext117 self.isInGenericContainingType = baseRawType.genericTypeContext.contains(where: { !$0.isEmpty })118 119 // Parse top-level declared methods and variables.120 var (methods, variables) = MockableType121 .parseDeclaredTypes(rawTypes: rawTypes,122 baseRawType: baseRawType,123 moduleNames: moduleNames,124 rawTypeRepository: rawTypeRepository,125 typealiasRepository: typealiasRepository)126 127 // Parse top-level declared generics.128 var genericTypes = substructure129 .compactMap({ structure -> GenericType? in130 guard let genericType = GenericType(from: structure,131 rawType: baseRawType,132 moduleNames: moduleNames,133 rawTypeRepository: rawTypeRepository) else { return nil }134 return genericType135 })136 var whereClauses = genericTypes.flatMap({ $0.whereClauses })137 let selfConstraintClauses: [WhereClause]138 let source = baseRawType.parsedFile.data139 if let nameSuffix = SourceSubstring.nameSuffixUpToBody.extract(from: baseRawType.dictionary,140 contents: source),141 let whereRange = nameSuffix.range(of: #"\bwhere\b"#, options: .regularExpression) {142 let topLevelClauses = nameSuffix[whereRange.upperBound..<nameSuffix.endIndex]143 .components(separatedBy: ",", excluding: .allGroups)144 .compactMap({ WhereClause(from: String($0)) })145 .map({ GenericType.qualifyWhereClause($0,146 containingType: baseRawType,147 moduleNames: moduleNames,148 rawTypeRepository: rawTypeRepository) })149 // Note: Superclass `Self` conformance must be done through the inheritance syntax, which is150 // passed via `selfConformanceTypes`.151 whereClauses.append(contentsOf: topLevelClauses.filter({ !$0.hasSelfConstraint }))152 selfConstraintClauses = topLevelClauses.filter({ $0.hasSelfConstraint })153 } else {154 selfConstraintClauses = []155 }156 157 // Parse inherited members and generics.158 let rawInheritedTypeNames = rawTypes159 .compactMap({ $0.dictionary[SwiftDocKey.inheritedtypes.rawValue] as? [StructureDictionary] })160 .flatMap({ $0 })161 .compactMap({ $0[SwiftDocKey.name.rawValue] as? String })162 let (inheritedTypes, _, allInheritedTypeNames, subclassesExternalType) =163 MockableType164 .parseInheritedTypes(rawInheritedTypeNames: rawInheritedTypeNames,165 forConformance: false,166 methods: &methods,167 variables: &variables,168 genericTypes: &genericTypes,169 whereClauses: &whereClauses,170 selfConstraintClauses: selfConstraintClauses,171 mockableTypes: mockableTypes,172 moduleNames: moduleNames,173 genericTypeContext: genericTypeContext,174 specializationContexts: specializationContexts,175 baseRawType: baseRawType,176 rawTypeRepository: rawTypeRepository,177 typealiasRepository: typealiasRepository)178 self.inheritedTypes = inheritedTypes179 self.allInheritedTypeNames = allInheritedTypeNames180 self.opaqueInheritedTypeNames = opaqueInheritedTypeNames181 .union(Set(inheritedTypes.flatMap({ $0.opaqueInheritedTypeNames })))182 // Parse protocol `Self` conformance.183 let rawConformanceTypeNames = baseRawType.kind == .protocol ?184 baseRawType.selfConformanceTypeNames.union(185 Set(inheritedTypes.map({ $0.fullyQualifiedModuleName }))186 ) : []187 let (_, allSelfConformanceTypes, allSelfConformanceTypeNames, conformsToExternalType) =188 MockableType189 .parseInheritedTypes(rawInheritedTypeNames: Array(rawConformanceTypeNames),190 forConformance: true,191 methods: &methods,192 variables: &variables,193 genericTypes: &genericTypes,194 whereClauses: &whereClauses,195 selfConstraintClauses: selfConstraintClauses,196 mockableTypes: mockableTypes,197 moduleNames: moduleNames,198 genericTypeContext: genericTypeContext,199 specializationContexts: specializationContexts,200 baseRawType: baseRawType,201 rawTypeRepository: rawTypeRepository,202 typealiasRepository: typealiasRepository)203 self.selfConformanceTypes = allSelfConformanceTypes204 self.allSelfConformanceTypeNames = allSelfConformanceTypeNames205 206 if let inheritedPrimaryType =207 inheritedTypes.sorted() // e.g. `protocol MyProtocol: ClassOnlyProtocol`208 .first(where: { $0.primarySelfConformanceType != nil }) ??209 allSelfConformanceTypes.sorted() // e.g. `protocol MyProtocol where Self: ClassOnlyProtocol`210 .first(where: { $0.primarySelfConformanceType != nil }),211 let primarySelfConformanceType = inheritedPrimaryType.primarySelfConformanceType,212 let primarySelfConformanceTypeName = inheritedPrimaryType.primarySelfConformanceTypeName {213 214 self.primarySelfConformanceType = primarySelfConformanceType215 self.primarySelfConformanceTypeName = primarySelfConformanceTypeName216 } else if let primaryType = allSelfConformanceTypes.sorted()217 .first(where: { $0.kind == .class }) {218 self.primarySelfConformanceType = primaryType219 self.primarySelfConformanceTypeName = MockableType220 .specializedSelfConformanceTypeName(primaryType,221 specializationContexts: specializationContexts,222 moduleNames: moduleNames,223 baseRawType: baseRawType,224 rawTypeRepository: rawTypeRepository,225 typealiasRepository: typealiasRepository)226 } else {227 self.primarySelfConformanceType = nil228 self.primarySelfConformanceTypeName = nil229 }230 231 self.subclassesExternalType = subclassesExternalType || conformsToExternalType232 self.methods = methods233 self.variables = variables234 235 var methodsCount = [Method.Reduced: UInt]()236 methods.forEach({ methodsCount[Method.Reduced(from: $0), default: 0] += 1 })237 self.methodsCount = methodsCount238 239 self.genericTypes = genericTypes240 self.whereClauses = Set(whereClauses)241 242 // Parse any containing preprocessor macros.243 if let offset = baseRawType.dictionary[SwiftDocKey.offset.rawValue] as? Int64 {244 self.compilationDirectives = baseRawType.parsedFile.compilationDirectives.filter({245 $0.range.contains(offset)246 })247 } else {248 self.compilationDirectives = []249 }250 251 // Check if any of the members have `Self` constraints.252 self.hasSelfConstraint = whereClauses.contains(where: { $0.hasSelfConstraint })253 || methods.contains(where: { $0.hasSelfConstraint })254 || variables.contains(where: { $0.hasSelfConstraint })255 || genericTypes.contains(where: { $0.hasSelfConstraint })256 257 if baseRawType.parsedFile.shouldMock {258 self.sortableIdentifier = [259 self.name,260 self.genericTypes.map({ "\($0.name):\($0.constraints)" }).joined(separator: ","),261 self.whereClauses.map({ "\($0)" }).joined(separator: ",")262 ].joined(separator: "|")263 } else {264 self.sortableIdentifier = name265 }266 }267 268 private static func parseDeclaredTypes(rawTypes: [RawType],269 baseRawType: RawType,270 moduleNames: [String],271 rawTypeRepository: RawTypeRepository,272 typealiasRepository: TypealiasRepository)273 -> (methods: Set<Method>, variables: Set<Variable>) {274 var methods = Set<Method>()275 var variables = Set<Variable>()276 for rawType in rawTypes {277 guard let substructure = rawType.dictionary[SwiftDocKey.substructure.rawValue]278 as? [StructureDictionary] else { continue }279 // Cannot override declarations in extensions as they are statically defined.280 guard rawType.kind != .extension else { continue }281 for structure in substructure {282 if let method = Method(from: structure,283 rootKind: baseRawType.kind,284 rawType: rawType,285 moduleNames: moduleNames,286 rawTypeRepository: rawTypeRepository,287 typealiasRepository: typealiasRepository) {288 methods.insert(method)289 }290 if let variable = Variable(from: structure,291 rootKind: baseRawType.kind,292 rawType: rawType,293 moduleNames: moduleNames,294 rawTypeRepository: rawTypeRepository) {295 variables.insert(variable)296 }297 }298 }299 return (methods, variables)300 }301 302 // TODO: Supporting protocol `Self` conformance has bloated this function. Needs a refactor soon.303 private static func parseInheritedTypes(rawInheritedTypeNames: [String],304 forConformance: Bool,305 methods: inout Set<Method>,306 variables: inout Set<Variable>,307 genericTypes: inout [GenericType],308 whereClauses: inout [WhereClause],309 selfConstraintClauses: [WhereClause],310 mockableTypes: [String: MockableType],311 moduleNames: [String],312 genericTypeContext: [[String]],313 specializationContexts: [String: SpecializationContext],314 baseRawType: RawType,315 rawTypeRepository: RawTypeRepository,316 typealiasRepository: TypealiasRepository)317 318 -> (inheritedTypes: Set<MockableType>, // Directly inherited types319 allInheritedTypes: Set<MockableType>, // Includes ancestor inheritance320 allInheritedTypeNames: [String], // Includes ancestor inheritance and opaque type names321 subclassesExternalType: Bool) {322 323 var inheritedTypes = Set<MockableType>()324 var allInheritedTypes = Set<MockableType>()325 var allInheritedTypeNames = [String]()326 var subclassesExternalType = false327 let definesDesignatedInitializer = methods.contains(where: { $0.isDesignatedInitializer })328 329 let resolveRawType: (String) -> RawType? = { typeName in330 guard let nearestRawType = rawTypeRepository331 .nearestInheritedType(named: typeName,332 trimmedName: typeName.removingGenericTyping(),333 moduleNames: moduleNames,334 referencingModuleName: baseRawType.parsedFile.moduleName,335 containingTypeNames: baseRawType.containingTypeNames[...])?336 .findBaseRawType() else { return nil }337 338 // Map unmockable inherited types to other types.339 if baseRawType.kind == .protocol,340 let mappedType = MockableType.Constants.automaticInheritanceMap[341 nearestRawType.fullyQualifiedModuleName342 ],343 let mappedRawType = rawTypeRepository.rawType(named: mappedType.typeName,344 in: mappedType.moduleName) {345 return mappedRawType.findBaseRawType()346 }347 348 return nearestRawType349 }350 351 // Find the correct `MockableType` instances for inheritance based on type name.352 let parsedInheritedTypes = rawInheritedTypeNames.flatMap({ typeName -> [MockableType] in353 guard let nearestRawType = resolveRawType(typeName) else {354 log("Unable to resolve inherited type \(typeName.singleQuoted) for \(baseRawType.name.singleQuoted)")355 allInheritedTypeNames.append(typeName)356 return []357 }358 359 // Inherited types could be typealiased, which would hide conformance.360 guard nearestRawType.kind == .typealias else {361 guard let mockableType = mockableTypes[nearestRawType.fullyQualifiedModuleName] else {362 return []363 }364 return [mockableType]365 }366 367 // Resolve typealias to fully qualified root type name.368 let actualTypeNames = typealiasRepository369 .actualTypeNames(for: nearestRawType.fullyQualifiedModuleName,370 rawTypeRepository: rawTypeRepository,371 moduleNames: moduleNames,372 referencingModuleName: baseRawType.parsedFile.moduleName,373 containingTypeNames: baseRawType.containingTypeNames[...])374 375 // Resolve fully qualified root type name to raw type.376 return actualTypeNames.compactMap({377 guard let nearestRawType = rawTypeRepository378 .nearestInheritedType(named: $0,379 trimmedName: $0.removingGenericTyping(),380 moduleNames: moduleNames,381 referencingModuleName: baseRawType.parsedFile.moduleName,382 containingTypeNames: baseRawType.containingTypeNames[...])?383 .findBaseRawType() else { return nil }384 return mockableTypes[nearestRawType.fullyQualifiedModuleName]385 })386 })387 // Merge all inheritable members from the `MockableType` instances.388 for mockableType in parsedInheritedTypes {389 if baseRawType.kind == .class390 && mockableType.kind == .class391 && mockableType.moduleName != baseRawType.parsedFile.moduleName {392 subclassesExternalType = true393 }394 395 let shouldInheritFromType = baseRawType.kind == .protocol || mockableType.kind != .protocol396 let specializationContext = specializationContexts[mockableType.fullyQualifiedModuleName]397 398 methods = methods.union(mockableType.methods399 .filter({ method in400 let isImplicitlySynthesized = method.attributes.contains(.implicit)401 guard shouldInheritFromType || isImplicitlySynthesized else { return false }402 return method.kind.typeScope.isMockable(in: baseRawType.kind) &&403 // Mocking a subclass with designated initializers shouldn't inherit the superclass'404 // initializers.405 (baseRawType.kind == .protocol406 || isImplicitlySynthesized407 || !definesDesignatedInitializer408 || !method.isInitializer)409 })410 .map({ method in // Specialize methods from generic types.411 guard let context = specializationContext else { return method }412 return method.specialize(using: context,413 moduleNames: moduleNames,414 genericTypeContext: genericTypeContext,415 excludedGenericTypeNames: [],416 rawTypeRepository: rawTypeRepository,417 typealiasRepository: typealiasRepository)418 })419 )420 variables = variables.union(mockableType.variables421 .filter({ variable in422 guard shouldInheritFromType || variable.attributes.contains(.implicit)423 else { return false }424 return variable.kind.typeScope.isMockable(in: baseRawType.kind)425 })426 .map({ variable in // Specialize variables from generic types.427 guard let context = specializationContext else { return variable }428 return variable.specialize(using: context,429 moduleNames: moduleNames,430 genericTypeContext: genericTypeContext,431 excludedGenericTypeNames: [],432 rawTypeRepository: rawTypeRepository,433 typealiasRepository: typealiasRepository)434 })435 )436 437 // Classes must already implement generic constraints from protocols they conform to.438 guard shouldInheritFromType else { continue }439 440 inheritedTypes.insert(mockableType)441 442 // Indirect inheritance.443 if !forConformance {444 allInheritedTypes.formUnion(mockableType.inheritedTypes)445 allInheritedTypeNames.append(contentsOf: mockableType.allInheritedTypeNames)446 } else {447 allInheritedTypes.formUnion(mockableType.selfConformanceTypes)448 allInheritedTypeNames.append(contentsOf: mockableType.allSelfConformanceTypeNames)449 }450 451 let isSelfConstraintType = selfConstraintClauses.contains(where: {452 $0.constrainedTypeName == mockableType.fullyQualifiedModuleName453 || $0.genericConstraint == mockableType.fullyQualifiedModuleName454 })455 let shouldIncludeInheritedType = !forConformance ||456 forConformance && (isSelfConstraintType || mockableType.kind == .class)457 if shouldIncludeInheritedType {458 allInheritedTypes.insert(mockableType)459 allInheritedTypeNames.append(MockableType.specializedSelfConformanceTypeName(460 mockableType,461 specializationContexts: specializationContexts,462 moduleNames: moduleNames,463 baseRawType: baseRawType,464 rawTypeRepository: rawTypeRepository,465 typealiasRepository: typealiasRepository466 ))467 }468 // Only bubble-up generics for protocols from inherited protocols.469 if baseRawType.kind == .protocol && mockableType.kind == .protocol {470 let uniqueGenericTypes = Set<String>(genericTypes.map({ $0.name }))471 genericTypes.append(contentsOf: mockableType.genericTypes.filter({472 !uniqueGenericTypes.contains($0.name)473 }))474 whereClauses.append(contentsOf: mockableType.whereClauses)475 }476 }477 return (inheritedTypes, allInheritedTypes, allInheritedTypeNames, subclassesExternalType)478 }479 480 private static func specializedSelfConformanceTypeName(481 _ type: MockableType,482 specializationContexts: [String: SpecializationContext],483 moduleNames: [String],484 baseRawType: RawType,485 rawTypeRepository: RawTypeRepository,486 typealiasRepository: TypealiasRepository487 ) -> String {488 guard !type.genericTypes.isEmpty, !specializationContexts.isEmpty,489 let context = specializationContexts[type.fullyQualifiedModuleName]490 else { return type.fullyQualifiedModuleName }491 492 let specializedGenericTypes = context.typeList.map({ specialization -> String in493 let serializationContext = SerializationRequest494 .Context(moduleNames: moduleNames,495 rawType: baseRawType,496 rawTypeRepository: rawTypeRepository,497 typealiasRepository: typealiasRepository)498 let qualifiedTypeNameRequest = SerializationRequest(method: .moduleQualified,499 context: serializationContext,...

Full Screen

Full Screen

Method.swift

Source:Method.swift Github

copy

Full Screen

...30 init?(from dictionary: StructureDictionary,31 rootKind: SwiftDeclarationKind,32 rawType: RawType,33 moduleNames: [String],34 rawTypeRepository: RawTypeRepository,35 typealiasRepository: TypealiasRepository) {36 guard let kind = SwiftDeclarationKind(from: dictionary), kind.isMethod,37 // Can't override static method declarations in classes.38 kind.typeScope == .instance39 || kind.typeScope == .class40 || (kind.typeScope == .static && rootKind == .protocol)41 else { return nil }42 43 guard let name = dictionary[SwiftDocKey.name.rawValue] as? String, name != "deinit"44 else { return nil }45 self.name = name46 let isInitializer = name.hasPrefix("init(")47 self.isInitializer = isInitializer48 49 let accessLevel = AccessLevel(from: dictionary) ?? .defaultLevel50 self.isMockable =51 accessLevel.isMockableMember(in: rootKind, withinSameModule: rawType.parsedFile.shouldMock)52 || (isInitializer && accessLevel.isMockable) // Initializers cannot be `open`.53 self.accessLevel = accessLevel54 55 let source = rawType.parsedFile.data56 let attributes = Attributes(from: dictionary, source: source)57 guard !attributes.contains(.final) else { return nil }58 self.isDesignatedInitializer = isInitializer && !attributes.contains(.convenience)59 60 let substructure = dictionary[SwiftDocKey.substructure.rawValue] as? [StructureDictionary] ?? []61 self.kind = kind62 self.isOverridable = rootKind == .class63 self.rawType = rawType64 65 // Parse declared attributes and parameters.66 let rawParametersDeclaration: Substring?67 (self.attributes,68 rawParametersDeclaration) = Method.parseDeclaration(from: dictionary,69 source: source,70 isInitializer: isInitializer,71 attributes: attributes)72 73 // Parse return type.74 let (returnType, returnTypeName) = Method.parseReturnType(75 from: dictionary,76 rawType: rawType,77 moduleNames: moduleNames,78 rawTypeRepository: rawTypeRepository,79 typealiasRepository: typealiasRepository)80 self.returnType = returnType81 self.returnTypeName = returnTypeName82 83 // Parse generic type constraints and where clauses.84 self.whereClauses = Method.parseWhereClauses(from: dictionary,85 source: source,86 rawType: rawType,87 moduleNames: moduleNames,88 rawTypeRepository: rawTypeRepository)89 self.genericTypes = substructure90 .compactMap({ structure -> GenericType? in91 guard let genericType = GenericType(from: structure,92 rawType: rawType,93 moduleNames: moduleNames,94 rawTypeRepository: rawTypeRepository)95 else { return nil }96 return genericType97 })98 99 // Parse parameters.100 let (shortName, labels) = Method.parseArgumentLabels(name: name,101 parameters: rawParametersDeclaration)102 self.shortName = shortName103 let parameters = Method.parseParameters(labels: labels,104 substructure: substructure,105 rawParametersDeclaration: rawParametersDeclaration,106 rawType: rawType,107 moduleNames: moduleNames,108 rawTypeRepository: rawTypeRepository,109 typealiasRepository: typealiasRepository)110 self.parameters = parameters111 112 // Parse any containing preprocessor macros.113 if let offset = dictionary[SwiftDocKey.offset.rawValue] as? Int64 {114 self.compilationDirectives = rawType.parsedFile.compilationDirectives.filter({115 $0.range.contains(offset)116 })117 } else {118 self.compilationDirectives = []119 }120 121 // Check whether this method has any `Self` type constraints.122 self.hasSelfConstraint =123 returnTypeName.contains(SerializationRequest.Constants.selfTokenIndicator)124 || parameters.contains(where: { $0.hasSelfConstraints })125 }126 127 private static func parseDeclaration(from dictionary: StructureDictionary,128 source: Data?,129 isInitializer: Bool,130 attributes: Attributes) -> (Attributes, Substring?) {131 guard let declaration = SourceSubstring.key.extract(from: dictionary, contents: source)132 else { return (attributes, nil) }133 134 var fullAttributes = attributes135 var rawParametersDeclaration: Substring?136 137 // Parse parameter attributes.138 let startIndex = declaration.firstIndex(of: "(")139 let parametersEndIndex =140 declaration[declaration.index(after: (startIndex ?? declaration.startIndex))...]141 .firstIndex(of: ")", excluding: .allGroups)142 if let startIndex = startIndex, let endIndex = parametersEndIndex {143 rawParametersDeclaration = declaration[declaration.index(after: startIndex)..<endIndex]144 145 if isInitializer { // Parse failable initializers.146 let genericsStart = declaration[..<startIndex].firstIndex(of: "<") ?? startIndex147 let failable = declaration[declaration.index(before: genericsStart)..<genericsStart]148 if failable == "?" {149 fullAttributes.insert(.failable)150 } else if failable == "!" {151 fullAttributes.insert(.unwrappedFailable)152 }153 }154 }155 156 // Parse return type attributes.157 let returnAttributesStartIndex = parametersEndIndex ?? declaration.startIndex158 let returnAttributesEndIndex = declaration.firstIndex(of: "-", excluding: .allGroups)159 ?? declaration.endIndex160 let returnAttributes = declaration[returnAttributesStartIndex..<returnAttributesEndIndex]161 if returnAttributes.range(of: #"\bthrows\b"#, options: .regularExpression) != nil {162 fullAttributes.insert(.throws)163 }164 165 return (fullAttributes, rawParametersDeclaration)166 }167 168 private static func parseArgumentLabels(name: String, parameters: Substring?)169 -> (shortName: String, labels: [String?]) {170 let (shortName, labels) = name.extractArgumentLabels()171 guard parameters?.isEmpty == false else {172 return (shortName, labels)173 }174 let declarationLabels = parameters?.components(separatedBy: ",", excluding: .allGroups)175 .map({ $0.components(separatedBy: ":", excluding: .allGroups)[0]176 .trimmingCharacters(in: .whitespacesAndNewlines) })177 .map({ $0.components(separatedBy: " ", excluding: .allGroups)[0]178 .trimmingCharacters(in: .whitespacesAndNewlines) })179 .map({ $0 != "_" ? $0 : nil })180 return (shortName, declarationLabels ?? labels)181 }182 183 private static func parseWhereClauses(from dictionary: StructureDictionary,184 source: Data?,185 rawType: RawType,186 moduleNames: [String],187 rawTypeRepository: RawTypeRepository) -> [WhereClause] {188 guard let nameSuffix = SourceSubstring.nameSuffixUpToBody.extract(from: dictionary,189 contents: source),190 let whereRange = nameSuffix.range(of: #"\bwhere\b"#, options: .regularExpression)191 else { return [] }192 return nameSuffix[whereRange.upperBound..<nameSuffix.endIndex]193 .components(separatedBy: ",", excluding: .allGroups)194 .compactMap({ WhereClause(from: String($0)) })195 .map({ GenericType.qualifyWhereClause($0,196 containingType: rawType,197 moduleNames: moduleNames,198 rawTypeRepository: rawTypeRepository) })199 }200 201 private static func parseReturnType(202 from dictionary: StructureDictionary,203 rawType: RawType,204 moduleNames: [String],205 rawTypeRepository: RawTypeRepository,206 typealiasRepository: TypealiasRepository207 ) -> (DeclaredType, String) {208 guard let rawReturnTypeName = dictionary[SwiftDocKey.typeName.rawValue] as? String else {209 return (DeclaredType(from: "Void"), "Void")210 }211 let declaredType = DeclaredType(from: rawReturnTypeName)212 let serializationContext = SerializationRequest213 .Context(moduleNames: moduleNames,214 rawType: rawType,215 rawTypeRepository: rawTypeRepository,216 typealiasRepository: typealiasRepository)217 let qualifiedTypeNameRequest = SerializationRequest(method: .moduleQualified,218 context: serializationContext,219 options: .standard)220 return (declaredType, declaredType.serialize(with: qualifiedTypeNameRequest))221 }222 223 private static func parseParameters(labels: [String?],224 substructure: [StructureDictionary],225 rawParametersDeclaration: Substring?,226 rawType: RawType,227 moduleNames: [String],228 rawTypeRepository: RawTypeRepository,229 typealiasRepository: TypealiasRepository) -> [MethodParameter] {230 guard !labels.isEmpty else { return [] }231 var parameterIndex = 0232 let rawDeclarations = rawParametersDeclaration?233 .components(separatedBy: ",", excluding: .allGroups)234 .map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) })235 return substructure.compactMap({236 let rawDeclaration = rawDeclarations?.get(parameterIndex)237 guard let parameter = MethodParameter(from: $0,238 argumentLabel: labels.get(parameterIndex) ?? nil,239 parameterIndex: parameterIndex,240 rawDeclaration: rawDeclaration,241 rawType: rawType,242 moduleNames: moduleNames,243 rawTypeRepository: rawTypeRepository,244 typealiasRepository: typealiasRepository)245 else { return nil }246 parameterIndex += 1247 return parameter248 })249 }250}251extension Method: Hashable {252 /// A hashable version of Method that's unique according to Swift generics when subclassing.253 /// https://forums.swift.org/t/cannot-override-more-than-one-superclass-declaration/22213254 struct Reduced: Hashable {255 let name: String256 let returnTypeName: String257 let parameters: [MethodParameter]258 let attributes: Attributes259 init(from method: Method) {260 self.name = method.name261 self.returnTypeName = method.returnTypeName262 self.parameters = method.parameters263 264 var reducedAttributes = Attributes()265 if method.attributes.contains(.unwrappedFailable) {266 reducedAttributes.insert(.unwrappedFailable)267 }268 self.attributes = reducedAttributes269 }270 }271 272 func hash(into hasher: inout Hasher) {273 hasher.combine(name)274 hasher.combine(returnTypeName)275 hasher.combine(kind.typeScope == .instance)276 hasher.combine(genericTypes)277 hasher.combine(whereClauses)278 hasher.combine(parameters)279 }280 281 static func == (lhs: Method, rhs: Method) -> Bool {282 return lhs.hashValue == rhs.hashValue283 }284}285extension Method: Comparable {286 static func < (lhs: Method, rhs: Method) -> Bool {287 return (288 lhs.whereClauses,289 lhs.returnTypeName,290 lhs.kind.typeScope,291 lhs.parameters,292 lhs.genericTypes,293 lhs.name294 ) < (295 rhs.whereClauses,296 rhs.returnTypeName,297 rhs.kind.typeScope,298 rhs.parameters,299 rhs.genericTypes,300 rhs.name301 )302 }303}304extension Method: Specializable {305 private init(from method: Method, returnTypeName: String, parameters: [MethodParameter]) {306 self.name = method.name307 self.shortName = method.shortName308 self.returnType = DeclaredType(from: returnTypeName)309 self.returnTypeName = returnTypeName310 self.isInitializer = method.isInitializer311 self.isDesignatedInitializer = method.isDesignatedInitializer312 self.accessLevel = method.accessLevel313 self.kind = method.kind314 self.genericTypes = method.genericTypes315 self.whereClauses = method.whereClauses316 self.parameters = parameters317 self.attributes = method.attributes318 self.compilationDirectives = method.compilationDirectives319 self.isOverridable = method.isOverridable320 self.hasSelfConstraint = method.hasSelfConstraint321 self.isMockable = method.isMockable322 self.rawType = method.rawType323 }324 325 func specialize(using context: SpecializationContext,326 moduleNames: [String],327 genericTypeContext: [[String]],328 excludedGenericTypeNames: Set<String>,329 rawTypeRepository: RawTypeRepository,330 typealiasRepository: TypealiasRepository) -> Method {331 guard !context.specializations.isEmpty else { return self }332 333 // Function-level generic types can shadow class-level generics and shouldn't be specialized.334 let excludedGenericTypeNames = excludedGenericTypeNames.union(genericTypes.map({ $0.name }))335 336 // Specialize return type.337 let declaredType = DeclaredType(from: returnTypeName)338 let serializationContext = SerializationRequest339 .Context(moduleNames: moduleNames,340 rawType: rawType,341 rawTypeRepository: rawTypeRepository,342 typealiasRepository: typealiasRepository)343 let attributedSerializationContext = SerializationRequest...

Full Screen

Full Screen

GenericType.swift

Source:GenericType.swift Github

copy

Full Screen

...81 82 init?(from dictionary: StructureDictionary,83 rawType: RawType,84 moduleNames: [String],85 rawTypeRepository: RawTypeRepository) {86 guard let kind = SwiftDeclarationKind(from: dictionary),87 kind == .genericTypeParam || kind == .associatedtype,88 let name = dictionary[SwiftDocKey.name.rawValue] as? String89 else { return nil }90 91 self.name = name92 93 var constraints: Set<String>94 if let rawInheritedTypes = dictionary[SwiftDocKey.inheritedtypes.rawValue] as? [StructureDictionary] {95 constraints = GenericType.parseInheritedTypes(rawInheritedTypes: rawInheritedTypes,96 moduleNames: moduleNames,97 rawType: rawType,98 rawTypeRepository: rawTypeRepository)99 } else {100 constraints = []101 }102 103 let whereClauses: [WhereClause]104 if kind == .associatedtype {105 whereClauses = GenericType.parseAssociatedTypes(constraints: &constraints,106 rawType: rawType,107 dictionary: dictionary,108 moduleNames: moduleNames,109 rawTypeRepository: rawTypeRepository)110 self.hasSelfConstraint = whereClauses.contains(where: { $0.hasSelfConstraint })111 } else {112 whereClauses = []113 self.hasSelfConstraint = false114 }115 self.whereClauses = whereClauses116 self.constraints = constraints117 }118 119 /// Qualify any generic type constraints, which SourceKit gives us as inherited types.120 private static func parseInheritedTypes(rawInheritedTypes: [StructureDictionary],121 moduleNames: [String],122 rawType: RawType,123 rawTypeRepository: RawTypeRepository) -> Set<String> {124 var constraints = Set<String>()125 for rawInheritedType in rawInheritedTypes {126 guard let name = rawInheritedType[SwiftDocKey.name.rawValue] as? String else { continue }127 let declaredType = DeclaredType(from: name)128 let serializationContext = SerializationRequest129 .Context(moduleNames: moduleNames,130 rawType: rawType,131 rawTypeRepository: rawTypeRepository)132 let qualifiedTypeNameRequest = SerializationRequest(method: .moduleQualified,133 context: serializationContext,134 options: .standard)135 constraints.insert(declaredType.serialize(with: qualifiedTypeNameRequest))136 }137 return constraints138 }139 140 /// Manually parse any constraints defined by associated types in protocols.141 private static func parseAssociatedTypes(constraints: inout Set<String>,142 rawType: RawType,143 dictionary: StructureDictionary,144 moduleNames: [String],145 rawTypeRepository: RawTypeRepository) -> [WhereClause] {146 var whereClauses = [WhereClause]()147 let source = rawType.parsedFile.data148 guard let declaration = SourceSubstring.key.extract(from: dictionary, contents: source),149 let inferredTypeLowerBound = declaration.firstIndex(of: ":")150 else { return whereClauses }151 152 let inferredTypeStartIndex = declaration.index(after: inferredTypeLowerBound)153 let typeDeclaration = declaration[inferredTypeStartIndex...]154 155 // Associated types can also have generic type constraints using a generic `where` clause.156 let allInferredTypes: String157 if let whereRange = typeDeclaration.range(of: #"\bwhere\b"#, options: .regularExpression) {158 let rawInferredType = typeDeclaration[..<whereRange.lowerBound]159 allInferredTypes = rawInferredType.trimmingCharacters(in: .whitespacesAndNewlines)160 161 whereClauses = typeDeclaration[whereRange.upperBound...]162 .components(separatedBy: ",", excluding: .allGroups)163 .compactMap({ WhereClause(from: String($0)) })164 .map({ GenericType.qualifyWhereClause($0,165 containingType: rawType,166 moduleNames: moduleNames,167 rawTypeRepository: rawTypeRepository) })168 } else { // No `where` generic type constraints.169 allInferredTypes = typeDeclaration.trimmingCharacters(in: .whitespacesAndNewlines)170 }171 let inferredTypes = allInferredTypes172 .substringComponents(separatedBy: ",")173 .map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) })174 175 // Qualify all generic constraint types.176 for inferredType in inferredTypes {177 let declaredType = DeclaredType(from: inferredType)178 let serializationContext = SerializationRequest179 .Context(moduleNames: moduleNames,180 rawType: rawType,181 rawTypeRepository: rawTypeRepository)182 let qualifiedTypeNameRequest = SerializationRequest(method: .moduleQualified,183 context: serializationContext,184 options: .standard)185 constraints.insert(declaredType.serialize(with: qualifiedTypeNameRequest))186 }187 188 return whereClauses189 }190 191 /// Type constraints for associated types can contain `Self` references which need to be resolved.192 static func qualifyWhereClause(_ whereClause: WhereClause,193 containingType: RawType,194 moduleNames: [String],195 rawTypeRepository: RawTypeRepository) -> WhereClause {196 let serializationContext = SerializationRequest197 .Context(moduleNames: moduleNames,198 rawType: containingType,199 rawTypeRepository: rawTypeRepository)200 let qualifiedTypeNameRequest = SerializationRequest(method: .moduleQualified,201 context: serializationContext,202 options: .standard)203 204 let declaredConstrainedType = DeclaredType(from: whereClause.constrainedTypeName)205 var qualifiedConstrainedTypeName = declaredConstrainedType206 .serialize(with: qualifiedTypeNameRequest)207 208 let declaredConstraintType = DeclaredType(from: whereClause.genericConstraint)209 var qualifiedConstraintTypeName = declaredConstraintType...

Full Screen

Full Screen

RawTypeRepository

Using AI Code Generation

copy

Full Screen

1import Foundation2class MockRawTypeRepository: RawTypeRepository {3 var invokedGetRawTypeParameters: (type: Any.Type, Void)?4 var invokedGetRawTypeParametersList = [(type: Any.Type, Void)]()5 func getRawType(of type: Any.Type) -> RawType {6 invokedGetRawTypeParameters = (type, ())7 invokedGetRawTypeParametersList.append((type, ()))8 }9}10import Foundation11class MockRawTypeRepository: RawTypeRepository {12 var invokedGetRawTypeParameters: (type: Any.Type, Void)?13 var invokedGetRawTypeParametersList = [(type: Any.Type, Void)]()14 func getRawType(of type: Any.Type) -> RawType {15 invokedGetRawTypeParameters = (type, ())16 invokedGetRawTypeParametersList.append((type, ()))17 }18}19import Foundation20class MockRawTypeRepository: RawTypeRepository {21 var invokedGetRawTypeParameters: (type: Any.Type, Void)?22 var invokedGetRawTypeParametersList = [(type: Any.Type, Void)]()23 func getRawType(of type: Any.Type) -> RawType {24 invokedGetRawTypeParameters = (type, ())25 invokedGetRawTypeParametersList.append((type, ()))26 }27}

Full Screen

Full Screen

RawTypeRepository

Using AI Code Generation

copy

Full Screen

1import Foundation2import Mockingbird3let rawTypeRepository = RawTypeRepository()4let rawType = rawTypeRepository.getRawType()5print(rawType)6import Foundation7import Mockingbird8let rawTypeRepository = RawTypeRepository()9let rawType = rawTypeRepository.getRawType()10print(rawType)11import Foundation12import Mockingbird13let rawTypeRepository = RawTypeRepository()14let rawType = rawTypeRepository.getRawType()15print(rawType)16import Foundation17import Mockingbird18let rawTypeRepository = RawTypeRepository()19let rawType = rawTypeRepository.getRawType()20print(rawType)21import Foundation22import Mockingbird23let rawTypeRepository = RawTypeRepository()24let rawType = rawTypeRepository.getRawType()25print(rawType)26import Foundation27import Mockingbird28let rawTypeRepository = RawTypeRepository()29let rawType = rawTypeRepository.getRawType()30print(rawType)31import Foundation32import Mockingbird33let rawTypeRepository = RawTypeRepository()34let rawType = rawTypeRepository.getRawType()35print(rawType)36import Foundation37import Mockingbird38let rawTypeRepository = RawTypeRepository()39let rawType = rawTypeRepository.getRawType()40print(rawType)41import Foundation42import Mockingbird43let rawTypeRepository = RawTypeRepository()44let rawType = rawTypeRepository.getRawType()45print(rawType)46import Foundation47import Mockingbird48let rawTypeRepository = RawTypeRepository()49let rawType = rawTypeRepository.getRawType()50print(rawType)

Full Screen

Full Screen

RawTypeRepository

Using AI Code Generation

copy

Full Screen

1import Mockingbird2import Foundation3class RawTypeRepository {4 func fetchRawType() -> RawType {5 return RawType()6 }7}8import Mockingbird9import Foundation10class RawTypeRepository {11 func fetchRawType() -> RawType {12 return RawType()13 }14}15import Mockingbird16import Foundation17class RawTypeRepository {18 func fetchRawType() -> RawType {19 return RawType()20 }21}22import Mockingbird23import Foundation24class RawTypeRepository {25 func fetchRawType() -> RawType {26 return RawType()27 }28}29import Mockingbird30import Foundation31class RawTypeRepository {32 func fetchRawType() -> RawType {33 return RawType()34 }35}36import Mockingbird37import Foundation38class RawTypeRepository {39 func fetchRawType() -> RawType {40 return RawType()41 }42}43import Mockingbird44import Foundation45class RawTypeRepository {46 func fetchRawType() -> RawType {47 return RawType()48 }49}50import Mockingbird51import Foundation52class RawTypeRepository {53 func fetchRawType() -> RawType {54 return RawType()55 }56}57import Mockingbird58import Foundation59class RawTypeRepository {60 func fetchRawType() -> RawType {61 return RawType()62 }63}64import Mockingbird65import Foundation66class RawTypeRepository {67 func fetchRawType() -> RawType {68 return RawType()69 }70}

Full Screen

Full Screen

RawTypeRepository

Using AI Code Generation

copy

Full Screen

1import Foundation2class RawTypeRepository {3 func getRawType(id: String) -> RawType? {4 }5}6class RawType {7 init(id: String, name: String, description: String, example: String, type: String) {8 }9}10extension RawType {11 static func fromJSON(json: [String: Any]) -> RawType? {12 let type = json["type"] as? String else {13 }14 return RawType(id: id, name: name, description: description, example: example, type: type)15 }16}17import Foundation18class RawTypeRepository {19 func getRawType(id: String) -> RawType? {20 }21}22class RawType {23 init(id: String, name: String, description: String, example: String, type: String) {24 }25}26extension RawType {27 static func fromJSON(json: [String: Any]) -> RawType? {28 let type = json["type"] as? String else {29 }30 return RawType(id: id, name: name, description: description, example: example, type: type)31 }32}

Full Screen

Full Screen

RawTypeRepository

Using AI Code Generation

copy

Full Screen

1import Mockingbird2class RawTypeRepository {3 func getRawType() -> String {4 }5}6import Mockingbird7@testable import MockingbirdTests8class MockRawTypeRepository: RawTypeRepository {9 override func getRawType() -> String {10 }11}12import Mockingbird13@testable import MockingbirdTests14class MockRawTypeRepository: RawTypeRepository {15 override func getRawType() -> String {16 }17}18import Mockingbird19@testable import MockingbirdTests20class MockRawTypeRepository: RawTypeRepository {21 override func getRawType() -> String {22 }23}24import Mockingbird25@testable import MockingbirdTests26class MockRawTypeRepository: RawTypeRepository {27 override func getRawType() -> String {

Full Screen

Full Screen

RawTypeRepository

Using AI Code Generation

copy

Full Screen

1import Mockingbird2import MockingbirdFoundation3import MockingbirdUIKit4import MockingbirdCoreData5let rawTypeRepository = RawTypeRepository()6let rawType = rawTypeRepository.get("1")7print(rawType?.name)8import Mockingbird9import MockingbirdFoundation10import MockingbirdUIKit11import MockingbirdCoreData12let rawTypeRepository = RawTypeRepository()13let rawType = rawTypeRepository.get("2")14print(rawType?.name)15import Mockingbird16import MockingbirdFoundation17import MockingbirdUIKit18import MockingbirdCoreData19let rawTypeRepository = RawTypeRepository()20let rawType = rawTypeRepository.get("3")21print(rawType?.name)22import Mockingbird23import MockingbirdFoundation24import MockingbirdUIKit25import MockingbirdCoreData26let rawTypeRepository = RawTypeRepository()27let rawType = rawTypeRepository.get("4")28print(rawType?.name)29import Mockingbird30import MockingbirdFoundation31import MockingbirdUIKit32import MockingbirdCoreData33let rawTypeRepository = RawTypeRepository()34let rawType = rawTypeRepository.get("5")35print(rawType?.name)36import Mockingbird37import MockingbirdFoundation38import MockingbirdUIKit39import MockingbirdCoreData40let rawTypeRepository = RawTypeRepository()41let rawType = rawTypeRepository.get("6")42print(rawType?.name)43import Mockingbird44import MockingbirdFoundation45import MockingbirdUIKit46import MockingbirdCoreData47let rawTypeRepository = RawTypeRepository()48let rawType = rawTypeRepository.get("7")49print(rawType?.name)50import Mockingbird51import Mocking

Full Screen

Full Screen

RawTypeRepository

Using AI Code Generation

copy

Full Screen

1import Foundation2struct RawTypeRepository {3}4import Foundation5struct RawTypeRepository {6}7import Foundation8struct RawTypeRepository {

Full Screen

Full Screen

RawTypeRepository

Using AI Code Generation

copy

Full Screen

1import Mockingbird2let rawTypeRepository = RawTypeRepository()3let rawType = rawTypeRepository.rawType(for: String.self)4let rawType = rawTypeRepository.rawType(for: String.self, type: String.self)5let rawType = rawTypeRepository.rawType(for: String.self, type: String.self, module: "Swift")6let rawType = rawTypeRepository.rawType(for: String.self, type: String.self, module: "Swift", inferredName: "String")7let rawType = rawTypeRepository.rawType(for: String.self, type: String.self, module: "Swift", inferredName: "String", inferredType: "Swift.String")8let rawType = rawTypeRepository.rawType(for: String.self, type: String.self, module: "Swift", inferredName: "String", inferredType: "Swift.String", inferredModule: "Swift")9let rawType = rawTypeRepository.rawType(for: String.self, type: String.self, module: "Swift", inferredName: "String", inferredType: "Swift.String", inferredModule: "Swift", inferredGenericTypes: [])10let rawType = rawTypeRepository.rawType(for: String.self, type: String.self, module: "Swift", inferredName: "String", inferredType: "Swift.String", inferredModule: "Swift", inferredGenericTypes: [], inferredProtocolTypes: [])11let rawType = rawTypeRepository.rawType(for: String.self, type: String.self, module: "Swift", inferredName: "String", inferredType: "Swift.String", inferredModule: "Swift", inferredGenericTypes: [], inferredProtocolTypes: [], inferredAssociatedTypes: [])12let rawType = rawTypeRepository.rawType(for: String.self, type: String.self, module: "Swift", inferredName: "String", inferredType: "Swift.String", inferredModule: "Swift", inferredGenericTypes: [], inferredProtocolTypes: [], inferredAssociatedTypes: [], inferredSuperclassType: "Swift.String")13let rawType = rawTypeRepository.rawType(for: String.self, type: String.self, module: "Swift", inferredName: "String", inferredType: "Swift.String", inferredModule: "Swift", inferredGenericTypes: [], inferredProtocolTypes: [], inferredAssociatedTypes: [], inferredSuperclassType: "Swift.String", inferredSuperclassModule: "Swift")

Full Screen

Full Screen

RawTypeRepository

Using AI Code Generation

copy

Full Screen

1import Mockingbird2import MockingbirdModule3import Foundation4let rawTypeRepository = RawTypeRepository()5let rawType = rawTypeRepository.type(for: "MockingbirdTests.MockingbirdModule.RawType")6print(rawType)7import MockingbirdModule8import Foundation9let rawTypeRepository = RawTypeRepository()10let rawType = rawTypeRepository.type(for: "MockingbirdTests.MockingbirdModule.RawType")11print(rawType)12import MockingbirdModule13The error is expected, as the MockingbirdModule is not imported in 2.swift file. I am able to fix this by adding the following line to the top of 2.swift file:

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockingbird automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful