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 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
|
//===--- CompletionOverrideLookup.cpp -------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
#include "swift/IDE/CompletionOverrideLookup.h"
#include "CodeCompletionResultBuilder.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/IDE/CodeCompletionString.h"
#include "swift/IDE/CodeCompletionStringPrinter.h"
using namespace swift;
using namespace swift::ide;
bool CompletionOverrideLookup::addAccessControl(
const ValueDecl *VD, CodeCompletionResultBuilder &Builder) {
auto CurrentNominal = CurrDeclContext->getSelfNominalTypeDecl();
assert(CurrentNominal);
auto AccessOfContext = CurrentNominal->getFormalAccess();
if (AccessOfContext < AccessLevel::Public)
return false;
AccessLevel Access = std::min(VD->getFormalAccess(), AccessOfContext);
// Only emit 'public', not needed otherwise.
if (Access < AccessLevel::Public)
return false;
Builder.addAccessControlKeyword(Access);
return true;
}
Type CompletionOverrideLookup::getOpaqueResultType(
const ValueDecl *VD, DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo) {
if (Reason != DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal)
return nullptr;
auto currTy = CurrDeclContext->getDeclaredTypeInContext();
if (!currTy)
return nullptr;
Type ResultT;
if (auto *FD = dyn_cast<FuncDecl>(VD)) {
if (FD->getGenericParams()) {
// Generic function cannot have opaque result type.
return nullptr;
}
ResultT = FD->getResultInterfaceType();
} else if (auto *SD = dyn_cast<SubscriptDecl>(VD)) {
if (SD->getGenericParams()) {
// Generic subscript cannot have opaque result type.
return nullptr;
}
ResultT = SD->getElementInterfaceType();
} else if (auto *VarD = dyn_cast<VarDecl>(VD)) {
ResultT = VarD->getInterfaceType();
} else {
return nullptr;
}
if (!ResultT->is<DependentMemberType>() ||
!ResultT->castTo<DependentMemberType>()->getAssocType())
// The result is not a valid associatedtype.
return nullptr;
// Try substitution to see if the associated type is resolved to concrete
// type.
auto substMap =
currTy->getMemberSubstitutionMap(CurrDeclContext->getParentModule(), VD);
if (!ResultT.subst(substMap)->is<DependentMemberType>())
// If resolved print it.
return nullptr;
auto genericSig = VD->getDeclContext()->getGenericSignatureOfContext();
if (genericSig->isConcreteType(ResultT))
// If it has same type requrement, we will emit the concrete type.
return nullptr;
auto upperBound = genericSig->getUpperBound(
ResultT,
/*forExistentialSelf=*/false,
/*withParameterizedProtocols=*/false);
if (upperBound->isAny())
return nullptr;
return upperBound;
}
void CompletionOverrideLookup::addValueOverride(
const ValueDecl *VD, DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo, CodeCompletionResultBuilder &Builder,
bool hasDeclIntroducer) {
Type opaqueResultType = getOpaqueResultType(VD, Reason, dynamicLookupInfo);
class DeclPrinter : public CodeCompletionStringPrinter {
Type OpaqueBaseTy;
public:
DeclPrinter(CodeCompletionResultBuilder &Builder, Type OpaqueBaseTy)
: CodeCompletionStringPrinter(Builder), OpaqueBaseTy(OpaqueBaseTy) {}
// As for FuncDecl, SubscriptDecl, and VarDecl, substitute the result type
// with 'OpaqueBaseTy' if specified.
void printDeclResultTypePre(ValueDecl *VD, TypeLoc &TL) override {
if (!OpaqueBaseTy.isNull()) {
setNextChunkKind(ChunkKind::Keyword);
printText("some ");
setNextChunkKind(ChunkKind::Text);
TL = TypeLoc::withoutLoc(OpaqueBaseTy);
}
CodeCompletionStringPrinter::printDeclResultTypePre(VD, TL);
}
};
DeclPrinter Printer(Builder, opaqueResultType);
Printer.startPreamble();
bool modifierAdded = false;
// 'public' if needed.
modifierAdded |= !hasAccessModifier && addAccessControl(VD, Builder);
// 'override' if needed
if (missingOverride(Reason)) {
Builder.addOverrideKeyword();
modifierAdded |= true;
}
// Erase existing introducer (e.g. 'func') if any modifiers are added.
if (hasDeclIntroducer && modifierAdded) {
auto dist = Ctx.SourceMgr.getByteDistance(
introducerLoc, Ctx.SourceMgr.getIDEInspectionTargetLoc());
if (dist <= CodeCompletionResult::MaxNumBytesToErase) {
Builder.setNumBytesToErase(dist);
hasDeclIntroducer = false;
}
}
PrintOptions PO;
if (auto transformType = CurrDeclContext->getDeclaredTypeInContext())
PO.setBaseType(transformType);
PO.PrintPropertyAccessors = false;
PO.PrintSubscriptAccessors = false;
PO.SkipUnderscoredKeywords = true;
PO.PrintImplicitAttrs = false;
PO.ExclusiveAttrList.push_back(TypeAttrKind::Escaping);
PO.ExclusiveAttrList.push_back(TypeAttrKind::Autoclosure);
// Print certain modifiers only when the introducer is not written.
// Otherwise, the user can add it after the completion.
if (!hasDeclIntroducer) {
PO.ExclusiveAttrList.push_back(DeclAttrKind::Nonisolated);
}
PO.PrintAccess = false;
PO.PrintOverrideKeyword = false;
PO.PrintSelfAccessKindKeyword = false;
PO.PrintStaticKeyword = !hasStaticOrClass && !hasDeclIntroducer;
PO.SkipIntroducerKeywords = hasDeclIntroducer;
VD->print(Printer, PO);
}
void CompletionOverrideLookup::addMethodOverride(
const FuncDecl *FD, DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo) {
CodeCompletionResultBuilder Builder(Sink,
CodeCompletionResultKind::Declaration,
SemanticContextKind::Super);
Builder.setResultTypeNotApplicable();
Builder.setAssociatedDecl(FD);
addValueOverride(FD, Reason, dynamicLookupInfo, Builder, hasFuncIntroducer);
Builder.addBraceStmtWithCursor();
}
void CompletionOverrideLookup::addVarOverride(
const VarDecl *VD, DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo) {
// Overrides cannot use 'let', but if the 'override' keyword is specified
// then the intention is clear, so provide the results anyway. The compiler
// can then provide an error telling you to use 'var' instead.
// If we don't need override then it's a protocol requirement, so show it.
if (missingOverride(Reason) && hasVarIntroducer && isKeywordSpecified("let"))
return;
CodeCompletionResultBuilder Builder(Sink,
CodeCompletionResultKind::Declaration,
SemanticContextKind::Super);
Builder.setAssociatedDecl(VD);
addValueOverride(VD, Reason, dynamicLookupInfo, Builder, hasVarIntroducer);
}
void CompletionOverrideLookup::addSubscriptOverride(
const SubscriptDecl *SD, DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo) {
CodeCompletionResultBuilder Builder(Sink,
CodeCompletionResultKind::Declaration,
SemanticContextKind::Super);
Builder.setResultTypeNotApplicable();
Builder.setAssociatedDecl(SD);
addValueOverride(SD, Reason, dynamicLookupInfo, Builder, false);
Builder.addBraceStmtWithCursor();
}
void CompletionOverrideLookup::addTypeAlias(
const AssociatedTypeDecl *ATD, DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo) {
CodeCompletionResultBuilder Builder(Sink,
CodeCompletionResultKind::Declaration,
SemanticContextKind::Super);
Builder.setResultTypeNotApplicable();
Builder.setAssociatedDecl(ATD);
if (!hasTypealiasIntroducer && !hasAccessModifier)
(void)addAccessControl(ATD, Builder);
if (!hasTypealiasIntroducer)
Builder.addDeclIntroducer("typealias ");
Builder.addBaseName(ATD->getName().str());
Builder.addTextChunk(" = ");
Builder.addSimpleNamedParameter("Type");
}
void CompletionOverrideLookup::addConstructor(
const ConstructorDecl *CD, DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo) {
CodeCompletionResultBuilder Builder(Sink,
CodeCompletionResultKind::Declaration,
SemanticContextKind::Super);
Builder.setResultTypeNotApplicable();
Builder.setAssociatedDecl(CD);
CodeCompletionStringPrinter printer(Builder);
printer.startPreamble();
if (!hasAccessModifier)
(void)addAccessControl(CD, Builder);
if (missingOverride(Reason) && CD->isDesignatedInit() && !CD->isRequired())
Builder.addOverrideKeyword();
// Emit 'required' if we're in class context, 'required' is not specified,
// and 1) this is a protocol conformance and the class is not final, or 2)
// this is subclass and the initializer is marked as required.
bool needRequired = false;
auto C = CurrDeclContext->getSelfClassDecl();
if (C && !isKeywordSpecified("required")) {
switch (Reason) {
case DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal:
case DeclVisibilityKind::MemberOfProtocolDerivedByCurrentNominal:
if (!C->isSemanticallyFinal())
needRequired = true;
break;
case DeclVisibilityKind::MemberOfSuper:
if (CD->isRequired())
needRequired = true;
break;
default:
break;
}
}
if (needRequired)
Builder.addRequiredKeyword();
{
PrintOptions Options;
if (auto transformType = CurrDeclContext->getDeclaredTypeInContext())
Options.setBaseType(transformType);
Options.PrintImplicitAttrs = false;
Options.SkipAttributes = true;
CD->print(printer, Options);
}
printer.flush();
Builder.addBraceStmtWithCursor();
}
void CompletionOverrideLookup::foundDecl(ValueDecl *D,
DeclVisibilityKind Reason,
DynamicLookupInfo dynamicLookupInfo) {
if (Reason == DeclVisibilityKind::MemberOfCurrentNominal)
return;
if (D->shouldHideFromEditor())
return;
if (D->isSemanticallyFinal())
return;
bool hasIntroducer =
hasFuncIntroducer || hasVarIntroducer || hasTypealiasIntroducer;
if (hasStaticOrClass && !D->isStatic())
return;
// As per the current convention, only instance members are
// suggested if an introducer is not accompanied by a 'static' or
// 'class' modifier.
if (hasIntroducer && !hasStaticOrClass && D->isStatic())
return;
if (auto *FD = dyn_cast<FuncDecl>(D)) {
// We cannot override operators as members.
if (FD->isBinaryOperator() || FD->isUnaryOperator())
return;
// We cannot override individual accessors.
if (isa<AccessorDecl>(FD))
return;
if (hasFuncIntroducer || (!hasIntroducer && !hasInitializerModifier))
addMethodOverride(FD, Reason, dynamicLookupInfo);
return;
}
if (auto *VD = dyn_cast<VarDecl>(D)) {
if (hasVarIntroducer || (!hasIntroducer && !hasInitializerModifier))
addVarOverride(VD, Reason, dynamicLookupInfo);
return;
}
if (auto *SD = dyn_cast<SubscriptDecl>(D)) {
if (!hasIntroducer && !hasInitializerModifier)
addSubscriptOverride(SD, Reason, dynamicLookupInfo);
}
if (auto *CD = dyn_cast<ConstructorDecl>(D)) {
if (!isa<ProtocolDecl>(CD->getDeclContext()))
return;
if (hasIntroducer || hasOverride || hasOverridabilityModifier ||
hasStaticOrClass)
return;
if (CD->isRequired() || CD->isDesignatedInit())
addConstructor(CD, Reason, dynamicLookupInfo);
return;
}
}
void CompletionOverrideLookup::addDesignatedInitializers(NominalTypeDecl *NTD) {
if (hasFuncIntroducer || hasVarIntroducer || hasTypealiasIntroducer ||
hasOverridabilityModifier || hasStaticOrClass)
return;
const auto *CD = dyn_cast<ClassDecl>(NTD);
if (!CD)
return;
if (!CD->hasSuperclass())
return;
CD = CD->getSuperclassDecl();
for (const auto *Member : CD->getMembers()) {
const auto *Constructor = dyn_cast<ConstructorDecl>(Member);
if (!Constructor)
continue;
if (Constructor->hasStubImplementation())
continue;
if (Constructor->isDesignatedInit())
addConstructor(Constructor, DeclVisibilityKind::MemberOfSuper, {});
}
}
void CompletionOverrideLookup::addAssociatedTypes(NominalTypeDecl *NTD) {
if (!hasTypealiasIntroducer &&
(hasFuncIntroducer || hasVarIntroducer || hasInitializerModifier ||
hasOverride || hasOverridabilityModifier || hasStaticOrClass))
return;
if (isa<ProtocolDecl>(NTD))
return;
for (auto Conformance : NTD->getAllConformances()) {
auto Proto = Conformance->getProtocol();
if (!Proto->isAccessibleFrom(CurrDeclContext))
continue;
for (auto *ATD : Proto->getAssociatedTypeMembers()) {
// FIXME: Also exclude the type alias that has already been specified.
if (!Conformance->hasTypeWitness(ATD) || ATD->hasDefaultDefinitionType())
continue;
addTypeAlias(
ATD, DeclVisibilityKind::MemberOfProtocolConformedToByCurrentNominal,
{});
}
}
}
StringRef CompletionOverrideLookup::getResultBuilderDocComment(
ResultBuilderBuildFunction function) {
switch (function) {
case ResultBuilderBuildFunction::BuildArray:
return "Enables support for..in loops in a result builder by "
"combining the results of all iterations into a single result";
case ResultBuilderBuildFunction::BuildBlock:
return "Required by every result builder to build combined results "
"from statement blocks";
case ResultBuilderBuildFunction::BuildEitherFirst:
return "With buildEither(second:), enables support for 'if-else' and "
"'switch' statements by folding conditional results into a single "
"result";
case ResultBuilderBuildFunction::BuildEitherSecond:
return "With buildEither(first:), enables support for 'if-else' and "
"'switch' statements by folding conditional results into a single "
"result";
case ResultBuilderBuildFunction::BuildExpression:
return "If declared, provides contextual type information for statement "
"expressions to translate them into partial results";
case ResultBuilderBuildFunction::BuildFinalResult:
return "If declared, this will be called on the partial result from the "
"outermost block statement to produce the final returned result";
case ResultBuilderBuildFunction::BuildLimitedAvailability:
return "If declared, this will be called on the partial result of "
"an 'if #available' block to allow the result builder to erase "
"type information";
case ResultBuilderBuildFunction::BuildOptional:
return "Enables support for `if` statements that do not have an `else`";
case ResultBuilderBuildFunction::BuildPartialBlockFirst:
return "Builds a partial result component from the first component";
case ResultBuilderBuildFunction::BuildPartialBlockAccumulated:
return "Builds a partial result component by combining an accumulated "
"component and a new component";
}
}
void CompletionOverrideLookup::addResultBuilderBuildCompletion(
NominalTypeDecl *builder, Type componentType,
ResultBuilderBuildFunction function) {
CodeCompletionResultBuilder Builder(Sink, CodeCompletionResultKind::Pattern,
SemanticContextKind::CurrentNominal);
Builder.setResultTypeNotApplicable();
if (!hasFuncIntroducer) {
if (!hasAccessModifier && builder->getFormalAccess() >= AccessLevel::Public)
Builder.addAccessControlKeyword(AccessLevel::Public);
if (!hasStaticOrClass)
Builder.addTextChunk("static ");
Builder.addTextChunk("func ");
}
std::string declStringWithoutFunc;
{
llvm::raw_string_ostream out(declStringWithoutFunc);
printResultBuilderBuildFunction(builder, componentType, function,
std::nullopt, out);
}
Builder.addTextChunk(declStringWithoutFunc);
Builder.addBraceStmtWithCursor();
Builder.setBriefDocComment(getResultBuilderDocComment(function));
}
void CompletionOverrideLookup::addResultBuilderBuildCompletions(
NominalTypeDecl *builder) {
Type componentType = inferResultBuilderComponentType(builder);
addResultBuilderBuildCompletion(builder, componentType,
ResultBuilderBuildFunction::BuildBlock);
addResultBuilderBuildCompletion(builder, componentType,
ResultBuilderBuildFunction::BuildExpression);
addResultBuilderBuildCompletion(builder, componentType,
ResultBuilderBuildFunction::BuildOptional);
addResultBuilderBuildCompletion(builder, componentType,
ResultBuilderBuildFunction::BuildEitherFirst);
addResultBuilderBuildCompletion(
builder, componentType, ResultBuilderBuildFunction::BuildEitherSecond);
addResultBuilderBuildCompletion(builder, componentType,
ResultBuilderBuildFunction::BuildArray);
addResultBuilderBuildCompletion(
builder, componentType,
ResultBuilderBuildFunction::BuildLimitedAvailability);
addResultBuilderBuildCompletion(builder, componentType,
ResultBuilderBuildFunction::BuildFinalResult);
addResultBuilderBuildCompletion(
builder, componentType,
ResultBuilderBuildFunction::BuildPartialBlockFirst);
addResultBuilderBuildCompletion(
builder, componentType,
ResultBuilderBuildFunction::BuildPartialBlockAccumulated);
}
void CompletionOverrideLookup::getOverrideCompletions(SourceLoc Loc) {
if (!CurrDeclContext->isTypeContext())
return;
if (isa<ProtocolDecl>(CurrDeclContext))
return;
Type CurrTy = CurrDeclContext->getSelfTypeInContext();
auto *NTD = CurrDeclContext->getSelfNominalTypeDecl();
if (CurrTy && !CurrTy->is<ErrorType>()) {
// Look for overridable static members too.
Type Meta = MetatypeType::get(CurrTy);
lookupVisibleMemberDecls(*this, Meta, introducerLoc, CurrDeclContext,
/*includeInstanceMembers=*/true,
/*includeDerivedRequirements*/ true,
/*includeProtocolExtensionMembers*/ false);
addDesignatedInitializers(NTD);
addAssociatedTypes(NTD);
}
if (NTD && NTD->getAttrs().hasAttribute<ResultBuilderAttr>()) {
addResultBuilderBuildCompletions(NTD);
}
}
|