-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathDerivedConformanceRingMathProtocols.cpp
456 lines (413 loc) · 19.2 KB
/
DerivedConformanceRingMathProtocols.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//===--- DerivedConformanceRingMathProtocols.cpp --------------------------===//
//
// 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 implements explicit derivation of mathematical ring protocols for
// struct types: AdditiveArithmetic and PointwiseMultiplicative.
//
//===----------------------------------------------------------------------===//
#include "CodeSynthesis.h"
#include "TypeChecker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Types.h"
#include "DerivedConformances.h"
using namespace swift;
// Represents synthesizable math operators.
enum MathOperator {
// `+(Self, Self)`: AdditiveArithmetic
Add,
// `-(Self, Self)`: AdditiveArithmetic
Subtract,
// `.*(Self, Self)`: PointwiseMultiplicative
Multiply
};
static StringRef getMathOperatorName(MathOperator op) {
switch (op) {
case Add:
return "+";
case Subtract:
return "-";
case Multiply:
return ".*";
}
}
static KnownProtocolKind getKnownProtocolKind(MathOperator op) {
switch (op) {
case Add:
case Subtract:
return KnownProtocolKind::AdditiveArithmetic;
case Multiply:
return KnownProtocolKind::PointwiseMultiplicative;
}
}
// Return the protocol requirement with the specified name.
// TODO: Move function to shared place for use with other derived conformances.
static ValueDecl *getProtocolRequirement(ProtocolDecl *proto, Identifier name) {
auto lookup = proto->lookupDirect(name);
// Erase declarations that are not protocol requirements.
// This is important for removing default implementations of the same name.
llvm::erase_if(lookup, [](ValueDecl *v) {
return !isa<ProtocolDecl>(v->getDeclContext()) ||
!v->isProtocolRequirement();
});
assert(lookup.size() == 1 && "Ambiguous protocol requirement");
return lookup.front();
}
// Get the effective memberwise initializer of the given nominal type, or create
// it if it does not exist.
static ConstructorDecl *getOrCreateEffectiveMemberwiseInitializer(
TypeChecker &TC, NominalTypeDecl *nominal) {
auto &C = nominal->getASTContext();
if (auto *initDecl = nominal->getEffectiveMemberwiseInitializer())
return initDecl;
auto *initDecl = createImplicitConstructor(
TC, nominal, ImplicitConstructorKind::Memberwise);
nominal->addMember(initDecl);
C.addSynthesizedDecl(initDecl);
return initDecl;
}
// Return true if given nominal type has a `let` stored with an initial value.
// TODO: Move function to shared place for use with other derived conformances.
static bool hasLetStoredPropertyWithInitialValue(NominalTypeDecl *nominal) {
return llvm::any_of(nominal->getStoredProperties(), [&](VarDecl *v) {
return v->isLet() && v->hasInitialValue();
});
}
static bool canDeriveRingProtocol(KnownProtocolKind knownProtoKind,
NominalTypeDecl *nominal, DeclContext *DC) {
// Nominal type must be a struct. (No stored properties is okay.)
auto *structDecl = dyn_cast<StructDecl>(nominal);
if (!structDecl)
return false;
// Must not have any `let` stored properties with an initial value.
// - This restriction may be lifted later with support for "true" memberwise
// initializers that initialize all stored properties, including initial
// value information.
if (hasLetStoredPropertyWithInitialValue(nominal))
return false;
// All stored properties must conform to `AdditiveArithmetic`.
auto &C = nominal->getASTContext();
auto *proto = C.getProtocol(knownProtoKind);
return llvm::all_of(structDecl->getStoredProperties(), [&](VarDecl *v) {
if (!v->hasInterfaceType())
C.getLazyResolver()->resolveDeclSignature(v);
if (!v->hasInterfaceType())
return false;
auto varType = DC->mapTypeIntoContext(v->getValueInterfaceType());
return (bool)TypeChecker::conformsToProtocol(varType, proto, DC, None);
});
}
bool DerivedConformance::canDeriveAdditiveArithmetic(NominalTypeDecl *nominal,
DeclContext *DC) {
return canDeriveRingProtocol(KnownProtocolKind::AdditiveArithmetic,
nominal, DC);
}
bool DerivedConformance::canDerivePointwiseMultiplicative(NominalTypeDecl *nominal,
DeclContext *DC) {
return canDeriveRingProtocol(KnownProtocolKind::PointwiseMultiplicative,
nominal, DC);
}
// Synthesize body for ring math operator.
static std::pair<BraceStmt *, bool>
deriveBodyMathOperator(AbstractFunctionDecl *funcDecl, MathOperator op) {
auto *parentDC = funcDecl->getParent();
auto *nominal = parentDC->getSelfNominalTypeDecl();
auto &C = nominal->getASTContext();
// Create memberwise initializer: `Nominal.init(...)`.
auto *memberwiseInitDecl = nominal->getEffectiveMemberwiseInitializer();
assert(memberwiseInitDecl && "Memberwise initializer must exist");
auto *initDRE =
new (C) DeclRefExpr(memberwiseInitDecl, DeclNameLoc(), /*Implicit*/ true);
initDRE->setFunctionRefKind(FunctionRefKind::SingleApply);
auto *nominalTypeExpr = TypeExpr::createForDecl(SourceLoc(), nominal,
funcDecl, /*Implicit*/ true);
auto *initExpr = new (C) ConstructorRefCallExpr(initDRE, nominalTypeExpr);
// Get operator protocol requirement.
auto *proto = C.getProtocol(getKnownProtocolKind(op));
auto operatorId = C.getIdentifier(getMathOperatorName(op));
auto *operatorReq = getProtocolRequirement(proto, operatorId);
// Create reference to operator parameters: lhs and rhs.
auto params = funcDecl->getParameters();
auto *lhsDRE =
new (C) DeclRefExpr(params->get(0), DeclNameLoc(), /*Implicit*/ true);
auto *rhsDRE =
new (C) DeclRefExpr(params->get(1), DeclNameLoc(), /*Implicit*/ true);
// Create expression combining lhs and rhs members using member operator.
auto createMemberOpExpr = [&](VarDecl *member) -> Expr * {
auto module = nominal->getModuleContext();
auto memberType =
parentDC->mapTypeIntoContext(member->getValueInterfaceType());
auto confRef = module->lookupConformance(memberType, proto);
assert(confRef && "Member does not conform to math protocol");
// Get member type's math operator, e.g. `Member.+`.
// Use protocol requirement declaration for the operator by default: this
// will be dynamically dispatched.
ValueDecl *memberOpDecl = operatorReq;
// If conformance reference is concrete, then use concrete witness
// declaration for the operator.
if (confRef->isConcrete())
if (auto *concreteMemberMethodDecl =
confRef->getConcrete()->getWitnessDecl(operatorReq))
memberOpDecl = concreteMemberMethodDecl;
assert(memberOpDecl && "Member operator declaration must exist");
auto memberOpDRE =
new (C) DeclRefExpr(memberOpDecl, DeclNameLoc(), /*Implicit*/ true);
auto *memberTypeExpr = TypeExpr::createImplicit(memberType, C);
auto memberOpExpr =
new (C) DotSyntaxCallExpr(memberOpDRE, SourceLoc(), memberTypeExpr);
// Create expression `lhs.member <op> rhs.member`.
Expr *lhsArg = new (C) MemberRefExpr(lhsDRE, SourceLoc(), member,
DeclNameLoc(), /*Implicit*/ true);
auto *rhsArg = new (C) MemberRefExpr(rhsDRE, SourceLoc(), member,
DeclNameLoc(), /*Implicit*/ true);
auto *memberOpArgs =
TupleExpr::create(C, SourceLoc(), {lhsArg, rhsArg}, {}, {}, SourceLoc(),
/*HasTrailingClosure*/ false,
/*Implicit*/ true);
auto *memberOpCallExpr =
new (C) BinaryExpr(memberOpExpr, memberOpArgs, /*Implicit*/ true);
return memberOpCallExpr;
};
// Create array of member operator call expressions.
llvm::SmallVector<Expr *, 2> memberOpExprs;
llvm::SmallVector<Identifier, 2> memberNames;
for (auto member : nominal->getStoredProperties()) {
memberOpExprs.push_back(createMemberOpExpr(member));
memberNames.push_back(member->getName());
}
// Call memberwise initializer with member operator call expressions.
auto *callExpr =
CallExpr::createImplicit(C, initExpr, memberOpExprs, memberNames);
ASTNode returnStmt = new (C) ReturnStmt(SourceLoc(), callExpr, true);
return std::pair<BraceStmt *, bool>(
BraceStmt::create(C, SourceLoc(), returnStmt, SourceLoc(), true), false);
}
// Synthesize function declaration for the given math operator.
static ValueDecl *deriveMathOperator(DerivedConformance &derived,
MathOperator op) {
auto nominal = derived.Nominal;
auto parentDC = derived.getConformanceContext();
auto &C = derived.TC.Context;
auto selfInterfaceType = parentDC->getDeclaredInterfaceType();
// Create parameter declaration with the given name and type.
auto createParamDecl = [&](StringRef name, Type type) -> ParamDecl * {
auto *param = new (C)
ParamDecl(ParamDecl::Specifier::Default, SourceLoc(), SourceLoc(),
Identifier(), SourceLoc(), C.getIdentifier(name), parentDC);
param->setInterfaceType(type);
return param;
};
ParameterList *params =
ParameterList::create(C, {createParamDecl("lhs", selfInterfaceType),
createParamDecl("rhs", selfInterfaceType)});
auto operatorId = C.getIdentifier(getMathOperatorName(op));
DeclName operatorDeclName(C, operatorId, params);
auto operatorDecl =
FuncDecl::create(C, SourceLoc(), StaticSpellingKind::KeywordStatic,
SourceLoc(), operatorDeclName, SourceLoc(),
/*Throws*/ false, SourceLoc(),
/*GenericParams=*/nullptr, params,
TypeLoc::withoutLoc(selfInterfaceType), parentDC);
operatorDecl->setImplicit();
auto bodySynthesizer = [](AbstractFunctionDecl *funcDecl,
void *ctx) -> std::pair<BraceStmt *, bool> {
auto op = (MathOperator) reinterpret_cast<intptr_t>(ctx);
return deriveBodyMathOperator(funcDecl, op);
};
operatorDecl->setBodySynthesizer(bodySynthesizer, (void *) op);
if (auto env = parentDC->getGenericEnvironmentOfContext())
operatorDecl->setGenericEnvironment(env);
operatorDecl->computeType();
operatorDecl->copyFormalAccessFrom(nominal, /*sourceIsParentContext*/ true);
operatorDecl->setValidationToChecked();
derived.addMembersToConformanceContext({operatorDecl});
C.addSynthesizedDecl(operatorDecl);
return operatorDecl;
}
// Synthesize body for a ring property computed property getter.
static std::pair<BraceStmt *, bool>
deriveBodyRingPropertyGetter(AbstractFunctionDecl *funcDecl,
ProtocolDecl *proto, ValueDecl *reqDecl) {
auto *parentDC = funcDecl->getParent();
auto *nominal = parentDC->getSelfNominalTypeDecl();
auto &C = nominal->getASTContext();
auto *memberwiseInitDecl = nominal->getEffectiveMemberwiseInitializer();
assert(memberwiseInitDecl && "Memberwise initializer must exist");
auto *initDRE =
new (C) DeclRefExpr(memberwiseInitDecl, DeclNameLoc(), /*Implicit*/ true);
initDRE->setFunctionRefKind(FunctionRefKind::SingleApply);
auto *nominalTypeExpr = TypeExpr::createForDecl(SourceLoc(), nominal,
funcDecl, /*Implicit*/ true);
auto *initExpr = new (C) ConstructorRefCallExpr(initDRE, nominalTypeExpr);
auto createMemberRingPropertyExpr = [&](VarDecl *member) -> Expr * {
auto memberType =
parentDC->mapTypeIntoContext(member->getValueInterfaceType());
Expr *memberExpr = nullptr;
// If the property is static, create a type expression: `Member`.
if (reqDecl->isStatic()) {
memberExpr = TypeExpr::createImplicit(memberType, C);
}
// If the property is not static, create a member ref expression:
// `self.member`.
else {
auto *selfDecl = funcDecl->getImplicitSelfDecl();
auto *selfDRE =
new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*Implicit*/ true);
memberExpr =
new (C) MemberRefExpr(selfDRE, SourceLoc(), member, DeclNameLoc(),
/*Implicit*/ true);
}
auto module = nominal->getModuleContext();
auto confRef = module->lookupConformance(memberType, proto);
assert(confRef && "Member does not conform to ring protocol");
// If conformance reference is not concrete, then concrete witness
// declaration for ring property cannot be resolved. Return reference to
// protocol requirement: this will be dynamically dispatched.
if (!confRef->isConcrete()) {
return new (C) MemberRefExpr(memberExpr, SourceLoc(), reqDecl,
DeclNameLoc(), /*Implicit*/ true);
}
// Otherwise, return reference to concrete witness declaration.
auto conf = confRef->getConcrete();
auto witnessDecl = conf->getWitnessDecl(reqDecl);
return new (C) MemberRefExpr(memberExpr, SourceLoc(), witnessDecl,
DeclNameLoc(), /*Implicit*/ true);
};
// Create array of `member.<ring property>` expressions.
llvm::SmallVector<Expr *, 2> memberPropExprs;
llvm::SmallVector<Identifier, 2> memberNames;
for (auto member : nominal->getStoredProperties()) {
memberPropExprs.push_back(createMemberRingPropertyExpr(member));
memberNames.push_back(member->getName());
}
// Call memberwise initializer with member ring property expressions.
auto *callExpr =
CallExpr::createImplicit(C, initExpr, memberPropExprs, memberNames);
ASTNode returnStmt = new (C) ReturnStmt(SourceLoc(), callExpr, true);
auto *braceStmt =
BraceStmt::create(C, SourceLoc(), returnStmt, SourceLoc(), true);
return std::pair<BraceStmt *, bool>(braceStmt, false);
}
// Synthesize body for the `AdditiveArithmetic.zero` computed property getter.
static std::pair<BraceStmt *, bool>
deriveBodyAdditiveArithmetic_zero(AbstractFunctionDecl *funcDecl, void *) {
auto &C = funcDecl->getASTContext();
auto *addArithProto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic);
auto *zeroReq = getProtocolRequirement(addArithProto, C.Id_zero);
return deriveBodyRingPropertyGetter(funcDecl, addArithProto, zeroReq);
}
// Synthesize body for the `PointwiseMultiplicative.one` computed property
// getter.
static std::pair<BraceStmt *, bool>
deriveBodyPointwiseMultiplicative_one(AbstractFunctionDecl *funcDecl, void *) {
auto &C = funcDecl->getASTContext();
auto *pointMulProto =
C.getProtocol(KnownProtocolKind::PointwiseMultiplicative);
auto *oneReq = getProtocolRequirement(pointMulProto, C.Id_one);
return deriveBodyRingPropertyGetter(funcDecl, pointMulProto, oneReq);
}
// Synthesize body for the `PointwiseMultiplicative.reciprocal` computed
// property getter.
static std::pair<BraceStmt *, bool>
deriveBodyPointwiseMultiplicative_reciprocal(AbstractFunctionDecl *funcDecl,
void *) {
auto &C = funcDecl->getASTContext();
auto *pointMulProto =
C.getProtocol(KnownProtocolKind::PointwiseMultiplicative);
auto *reciprocalReq = getProtocolRequirement(pointMulProto, C.Id_reciprocal);
return deriveBodyRingPropertyGetter(funcDecl, pointMulProto, reciprocalReq);
}
// Synthesize a ring protocol property declaration.
static ValueDecl *
deriveRingProperty(DerivedConformance &derived, Identifier propertyName,
bool isStatic,
AbstractFunctionDecl::BodySynthesizer bodySynthesizer) {
auto *nominal = derived.Nominal;
auto *parentDC = derived.getConformanceContext();
auto returnInterfaceTy = nominal->getDeclaredInterfaceType();
auto returnTy = parentDC->mapTypeIntoContext(returnInterfaceTy);
// Create ring property declaration.
VarDecl *propDecl;
PatternBindingDecl *pbDecl;
std::tie(propDecl, pbDecl) = derived.declareDerivedProperty(
propertyName, returnInterfaceTy, returnTy, /*isStatic*/ isStatic,
/*isFinal*/ true);
// Create ring property getter.
auto *getterDecl =
derived.addGetterToReadOnlyDerivedProperty(propDecl, returnTy);
getterDecl->setBodySynthesizer(bodySynthesizer.Fn, bodySynthesizer.Context);
derived.addMembersToConformanceContext({getterDecl, propDecl, pbDecl});
return propDecl;
}
// Synthesize the static property declaration for `AdditiveArithmetic.zero`.
static ValueDecl *deriveAdditiveArithmetic_zero(DerivedConformance &derived) {
auto &C = derived.TC.Context;
return deriveRingProperty(derived, C.Id_zero, /*isStatic*/ true,
{deriveBodyAdditiveArithmetic_zero, nullptr});
}
// Synthesize the static property declaration for
// `PointwiseMultiplicative.one`.
static ValueDecl *
derivePointwiseMultiplicative_one(DerivedConformance &derived) {
auto &C = derived.TC.Context;
return deriveRingProperty(derived, C.Id_one, /*isStatic*/ true,
{deriveBodyPointwiseMultiplicative_one, nullptr});
}
// Synthesize the instance property declaration for
// `PointwiseMultiplicative.reciprocal`.
static ValueDecl *
derivePointwiseMultiplicative_reciprocal(DerivedConformance &derived) {
auto &C = derived.TC.Context;
return deriveRingProperty(
derived, C.Id_reciprocal, /*isStatic*/ false,
{deriveBodyPointwiseMultiplicative_reciprocal, nullptr});
}
ValueDecl *
DerivedConformance::deriveAdditiveArithmetic(ValueDecl *requirement) {
// Diagnose conformances in disallowed contexts.
if (checkAndDiagnoseDisallowedContext(requirement))
return nullptr;
// Create memberwise initializer for nominal type if it doesn't already exist.
getOrCreateEffectiveMemberwiseInitializer(TC, Nominal);
if (requirement->getBaseName() == TC.Context.getIdentifier("+"))
return deriveMathOperator(*this, Add);
if (requirement->getBaseName() == TC.Context.getIdentifier("-"))
return deriveMathOperator(*this, Subtract);
if (requirement->getBaseName() == TC.Context.Id_zero)
return deriveAdditiveArithmetic_zero(*this);
TC.diagnose(requirement->getLoc(),
diag::broken_additive_arithmetic_requirement);
return nullptr;
}
ValueDecl *
DerivedConformance::derivePointwiseMultiplicative(ValueDecl *requirement) {
// Diagnose conformances in disallowed contexts.
if (checkAndDiagnoseDisallowedContext(requirement))
return nullptr;
// Create memberwise initializer for nominal type if it doesn't already exist.
getOrCreateEffectiveMemberwiseInitializer(TC, Nominal);
if (requirement->getBaseName() == TC.Context.getIdentifier(".*"))
return deriveMathOperator(*this, Multiply);
if (requirement->getBaseName() == TC.Context.Id_one)
return derivePointwiseMultiplicative_one(*this);
if (requirement->getBaseName() == TC.Context.Id_reciprocal)
return derivePointwiseMultiplicative_reciprocal(*this);
TC.diagnose(requirement->getLoc(),
diag::broken_pointwise_multiplicative_requirement);
return nullptr;
}