Skip to content

Commit 185d3bc

Browse files
committed
[AST] emitLetToVarNoteIfSimple should also check if the function or accessor is explicitly 'nonmutating'
Otherwise, we will simply insert the 'mutating' fix-it after 'nonmutating', leading to another error that says both cannot be used at the same time
1 parent 5e1f790 commit 185d3bc

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

lib/AST/Decl.cpp

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5683,11 +5683,16 @@ void VarDecl::emitLetToVarNoteIfSimple(DeclContext *UseDC) const {
56835683
if (AD->isGetter() && !AD->getAccessorKeywordLoc().isValid())
56845684
return;
56855685
}
5686-
5686+
56875687
auto &d = getASTContext().Diags;
5688-
d.diagnose(FD->getFuncLoc(), diag::change_to_mutating,
5689-
isa<AccessorDecl>(FD))
5690-
.fixItInsert(FD->getFuncLoc(), "mutating ");
5688+
auto diags = d.diagnose(FD->getFuncLoc(), diag::change_to_mutating,
5689+
isa<AccessorDecl>(FD));
5690+
if (auto nonmutatingAttr =
5691+
FD->getAttrs().getAttribute<NonMutatingAttr>()) {
5692+
diags.fixItReplace(nonmutatingAttr->getLocation(), "mutating ");
5693+
} else {
5694+
diags.fixItInsert(FD->getFuncLoc(), "mutating ");
5695+
}
56915696
return;
56925697
}
56935698
}

test/Sema/immutability.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,3 +681,23 @@ struct SS {
681681
j = j // expected-error {{cannot assign to value: 'j' is a 'let' constant}}
682682
}
683683
}
684+
685+
protocol JustAProtocol {
686+
var name: String { get set }
687+
}
688+
689+
extension JustAProtocol {
690+
var foo: String {
691+
get { return name }
692+
nonmutating set { name = newValue } // expected-error {{cannot assign to property: 'self' is immutable}}
693+
// expected-note@-1 {{mark accessor 'mutating' to make 'self' mutable}}{{5-16=mutating}}
694+
}
695+
696+
nonmutating func bar() { // expected-note {{mark method 'mutating' to make 'self' mutable}}{{3-14=mutating}}
697+
name = "Hello" // expected-error {{cannot assign to property: 'self' is immutable}}
698+
}
699+
700+
func baz() { // expected-note {{mark method 'mutating' to make 'self' mutable}}{{3-3=mutating }}
701+
name = "World" // expected-error {{cannot assign to property: 'self' is immutable}}
702+
}
703+
}

0 commit comments

Comments
 (0)