Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[code-completion] Disable diagnostics during code completion and fix regressions #26888

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion include/swift/AST/DiagnosticEngine.h
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,7 @@ namespace swift {
}

/// Return all \c DiagnosticConsumers.
ArrayRef<DiagnosticConsumer *> getConsumers() {
ArrayRef<DiagnosticConsumer *> getConsumers() const {
return Consumers;
}

Expand Down
1 change: 1 addition & 0 deletions include/swift/AST/DiagnosticSuppression.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class DiagnosticSuppression {
public:
explicit DiagnosticSuppression(DiagnosticEngine &diags);
~DiagnosticSuppression();
static bool isEnabled(const DiagnosticEngine &diags);
};

}
Expand Down
7 changes: 0 additions & 7 deletions include/swift/Basic/SourceManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,6 @@ class SourceManager {
rangeContainsTokenLoc(Enclosing, Inner.End);
}

/// Returns true if range \p R contains the code-completion location, if any.
bool rangeContainsCodeCompletionLoc(SourceRange R) const {
return CodeCompletionBufferID
? rangeContainsTokenLoc(R, getCodeCompletionLoc())
: false;
}

/// Returns the buffer ID for the specified *valid* location.
///
/// Because a valid source location always corresponds to a source buffer,
Expand Down
4 changes: 4 additions & 0 deletions lib/AST/DiagnosticEngine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,10 @@ DiagnosticSuppression::~DiagnosticSuppression() {
diags.addConsumer(*consumer);
}

bool DiagnosticSuppression::isEnabled(const DiagnosticEngine &diags) {
return diags.getConsumers().empty();
}

BufferIndirectlyCausingDiagnosticRAII::BufferIndirectlyCausingDiagnosticRAII(
const SourceFile &SF)
: Diags(SF.getASTContext().Diags) {
Expand Down
5 changes: 5 additions & 0 deletions lib/IDE/ExprContextAnalysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,11 @@ static bool collectPossibleCalleesForApply(
} else if (auto *UDE = dyn_cast<UnresolvedDotExpr>(fnExpr)) {
collectPossibleCalleesByQualifiedLookup(
DC, UDE->getBase(), UDE->getName().getBaseName(), candidates);
} else if (auto *DSCE = dyn_cast<DotSyntaxCallExpr>(fnExpr)) {
if (auto *DRE = dyn_cast<DeclRefExpr>(DSCE->getFn())) {
collectPossibleCalleesByQualifiedLookup(
DC, DSCE->getArg(), DRE->getDecl()->getBaseName(), candidates);
}
}

if (candidates.empty()) {
Expand Down
8 changes: 5 additions & 3 deletions lib/Parse/ParseExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -236,17 +236,19 @@ ParserResult<Expr> Parser::parseExprSequence(Diag<> Message,
// Parse the middle expression of the ternary.
ParserResult<Expr> middle =
parseExprSequence(diag::expected_expr_after_if_question, isExprBasic);
ParserStatus Status = middle;
if (middle.hasCodeCompletion())
return makeParserCodeCompletionResult<Expr>();
HasCodeCompletion = true;
if (middle.isNull())
return nullptr;

// Make sure there's a matching ':' after the middle expr.
if (!Tok.is(tok::colon)) {
diagnose(questionLoc, diag::expected_colon_after_if_question);

return makeParserErrorResult(new (Context) ErrorExpr(
{startLoc, middle.get()->getSourceRange().End}));
Status.setIsParseError();
return makeParserResult(Status, new (Context) ErrorExpr(
{startLoc, middle.get()->getSourceRange().End}));
}

SourceLoc colonLoc = consumeToken();
Expand Down
6 changes: 0 additions & 6 deletions lib/Sema/BuilderTransform.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -566,12 +566,6 @@ ConstraintSystem::TypeMatchResult ConstraintSystem::applyFunctionBuilder(
assert(!builderType->hasTypeParameter());
}

// If we are performing code-completion inside the closure body, supress
// diagnostics to workaround typechecking performance problems.
if (getASTContext().SourceMgr.rangeContainsCodeCompletionLoc(
closure->getSourceRange()))
Options |= ConstraintSystemFlags::SuppressDiagnostics;

BuilderClosureVisitor visitor(getASTContext(), this,
/*wantExpr=*/true, builderType);
Expr *singleExpr = visitor.visit(closure->getBody());
Expand Down
5 changes: 3 additions & 2 deletions lib/Sema/TypeCheckConstraints.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/DiagnosticSuppression.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.h"
Expand Down Expand Up @@ -2141,7 +2142,7 @@ class FallbackDiagnosticListener : public ExprTypeCheckListener {

void maybeProduceFallbackDiagnostic(Expr *expr) const {
if (Options.contains(TypeCheckExprFlags::SubExpressionDiagnostics) ||
Options.contains(TypeCheckExprFlags::SuppressDiagnostics))
DiagnosticSuppression::isEnabled(TC.Diags))
return;

// Before producing fatal error here, let's check if there are any "error"
Expand Down Expand Up @@ -2183,7 +2184,7 @@ Type TypeChecker::typeCheckExpressionImpl(Expr *&expr, DeclContext *dc,
// Construct a constraint system from this expression.
ConstraintSystemOptions csOptions = ConstraintSystemFlags::AllowFixes;

if (options.contains(TypeCheckExprFlags::SuppressDiagnostics))
if (DiagnosticSuppression::isEnabled(Diags))
csOptions |= ConstraintSystemFlags::SuppressDiagnostics;

if (options.contains(TypeCheckExprFlags::AllowUnresolvedTypeVariables))
Expand Down
25 changes: 15 additions & 10 deletions lib/Sema/TypeCheckStmt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/DiagnosticSuppression.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.h"
Expand Down Expand Up @@ -518,20 +519,18 @@ class StmtChecker : public StmtVisitor<StmtChecker, Stmt*> {
}
}

if (EndTypeCheckLoc.isValid()) {
assert(DiagnosticSuppression::isEnabled(TC.Diags) &&
"Diagnosing and AllowUnresolvedTypeVariables don't seem to mix");
options |= TypeCheckExprFlags::AllowUnresolvedTypeVariables;
}

ContextualTypePurpose ctp = CTP_ReturnStmt;
if (auto func =
dyn_cast_or_null<FuncDecl>(TheFunc->getAbstractFunctionDecl())) {
if (func->hasSingleExpressionBody()) {
ctp = CTP_ReturnSingleExpr;
}

// If we are performing code-completion inside a function builder body,
// suppress diagnostics to workaround typechecking performance problems.
if (func->getFunctionBuilderType() &&
TC.Context.SourceMgr.rangeContainsCodeCompletionLoc(
func->getBody()->getSourceRange())) {
options |= TypeCheckExprFlags::SuppressDiagnostics;
}
}

auto exprTy = TC.typeCheckExpression(E, DC, TypeLoc::withoutLoc(ResultTy),
Expand Down Expand Up @@ -1785,6 +1784,12 @@ Stmt *StmtChecker::visitBraceStmt(BraceStmt *BS) {
if (isDiscarded)
options |= TypeCheckExprFlags::IsDiscarded;

if (EndTypeCheckLoc.isValid()) {
assert(DiagnosticSuppression::isEnabled(TC.Diags) &&
"Diagnosing and AllowUnresolvedTypeVariables don't seem to mix");
options |= TypeCheckExprFlags::AllowUnresolvedTypeVariables;
}

auto resultTy =
TC.typeCheckExpression(SubExpr, DC, TypeLoc(), CTP_Unused, options);

Expand Down Expand Up @@ -1942,10 +1947,10 @@ static Expr* constructCallToSuperInit(ConstructorDecl *ctor,
r = new (Context) TryExpr(SourceLoc(), r, Type(), /*implicit=*/true);

TypeChecker &tc = *static_cast<TypeChecker *>(Context.getLazyResolver());
DiagnosticSuppression suppression(tc.Diags);
auto resultTy =
tc.typeCheckExpression(r, ctor, TypeLoc(), CTP_Unused,
TypeCheckExprFlags::IsDiscarded |
TypeCheckExprFlags::SuppressDiagnostics);
TypeCheckExprFlags::IsDiscarded);
if (!resultTy)
return nullptr;

Expand Down
3 changes: 1 addition & 2 deletions lib/Sema/TypeChecker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -705,8 +705,7 @@ bool swift::typeCheckExpression(DeclContext *DC, Expr *&parsedExpr) {
TypeChecker &TC = createTypeChecker(ctx);

auto resultTy = TC.typeCheckExpression(parsedExpr, DC, TypeLoc(),
ContextualTypePurpose::CTP_Unused,
TypeCheckExprFlags::SuppressDiagnostics);
ContextualTypePurpose::CTP_Unused);
return !resultTy;
}

Expand Down
3 changes: 0 additions & 3 deletions lib/Sema/TypeChecker.h
Original file line number Diff line number Diff line change
Expand Up @@ -235,9 +235,6 @@ enum class TypeCheckExprFlags {
/// that we force for style or other reasons.
DisableStructuralChecks = 0x02,

/// Set if the client wants diagnostics suppressed.
SuppressDiagnostics = 0x04,

/// If set, the client wants a best-effort solution to the constraint system,
/// but can tolerate a solution where all of the constraints are solved, but
/// not all type variables have been determined. In this case, the constraint
Expand Down
30 changes: 30 additions & 0 deletions test/IDE/complete_in_closures.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_IIFE_4 | %FileCheck %s -check-prefix=IN_IIFE_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ERROR_IN_CLOSURE_IN_INITIALIZER | %FileCheck %s -check-prefix=ERROR_IN_CLOSURE_IN_INITIALIZER
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DECL_IN_CLOSURE_IN_TOPLEVEL_INIT | %FileCheck %s -check-prefix=DECL_IN_CLOSURE_IN_TOPLEVEL_INIT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SINGLE_EXPR_CLOSURE_CONTEXT | %FileCheck %s -check-prefix=SINGLE_EXPR_CLOSURE_CONTEXT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT | %FileCheck %s -check-prefix=SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT


// ERROR_COMMON: found code completion token
// ERROR_COMMON-NOT: Begin completions
Expand Down Expand Up @@ -401,3 +404,30 @@ var foo = {
// DECL_IN_CLOSURE_IN_TOPLEVEL_INIT-DAG: Decl[InstanceMethod]/Super: dropFirst()[#Substring#]; name=dropFirst()
// DECL_IN_CLOSURE_IN_TOPLEVEL_INIT: End completions
}

func testWithMemoryRebound(_ bar: UnsafePointer<UInt64>) {
_ = bar.withMemoryRebound(to: Int64.self, capacity: 3) { ptr in
return ptr #^SINGLE_EXPR_CLOSURE_CONTEXT^#
// SINGLE_EXPR_CLOSURE_CONTEXT: Begin completions
// SINGLE_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceMethod]/CurrNominal: .deallocate()[#Void#]; name=deallocate()
// SINGLE_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceVar]/CurrNominal: .pointee[#Int64#]; name=pointee
// SINGLE_EXPR_CLOSURE_CONTEXT: End completions
}
}

func testInsideTernaryClosureReturn(test: Bool) -> [String] {
return "hello".map { thing in
test ? String(thing #^SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT^#).uppercased() : String(thing).lowercased()
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT: Begin completions
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceVar]/CurrNominal: .utf8[#Character.UTF8View#]; name=utf8
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceVar]/CurrNominal: .description[#String#]; name=description
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceVar]/CurrNominal: .isWhitespace[#Bool#]; name=isWhitespace
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InstanceMethod]/CurrNominal: .uppercased()[#String#]; name=uppercased()
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: [' ']... {#String.Element#}[#ClosedRange<String.Element>#]; name=... String.Element
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: [' ']< {#Character#}[#Bool#]; name=< Character
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: [' ']>= {#String.Element#}[#Bool#]; name=>= String.Element
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]: [' ']== {#Character#}[#Bool#]; name=== Character
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT-DAG: Keyword[self]/CurrNominal: .self[#String.Element#]; name=self
// SINGLE_TERNARY_EXPR_CLOSURE_CONTEXT: End completions
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ func foo(
// RUN: == -req=complete.update -pos=9:1 -req-opts=filtertext=StructDefinedInSameTarget %s | %FileCheck --check-prefix=INNER_SAMETARGET %s
// INNER_SAMETARGET: key.name: "StructDefinedInSameTarget"
// INNER_SAMETARGET: key.name: "StructDefinedInSameTarget."
// INNER_SAMETARGET: key.name: "StructDefinedInSameTarget("

// RUN: %sourcekitd-test -req=complete.open -pos=9:1 -req-opts=filtertext=StructDefinedInCModule -vfs-files=/target_file2.swift=@%S/../Inputs/vfs/other_file_in_target.swift,/CModule/module.modulemap=%S/../Inputs/vfs/CModule/module.modulemap,/CModule/CModule.h=%S/../Inputs/vfs/CModule/CModule.h,/SwiftModule/SwiftModule.swiftmodule=%t/SwiftModule.swiftmodule %s -pass-as-sourcetext -- %s /target_file2.swift -I /CModule -I /SwiftModule -target %target-triple | %FileCheck --check-prefix=INNER_CMODULE %s
// RUN: %sourcekitd-test -req=complete.open -pos=9:1 -dont-print-response -vfs-files=/target_file2.swift=@%S/../Inputs/vfs/other_file_in_target.swift,/CModule/module.modulemap=%S/../Inputs/vfs/CModule/module.modulemap,/CModule/CModule.h=%S/../Inputs/vfs/CModule/CModule.h,/SwiftModule/SwiftModule.swiftmodule=%t/SwiftModule.swiftmodule %s -pass-as-sourcetext -- %s /target_file2.swift -I /CModule -I /SwiftModule -target %target-triple \
Expand Down