Skip to content

Commit 3815eff

Browse files
authored
Merge pull request #27641 from theblixguy/fix/mutating-fix-it
[AST] emitLetToVarNoteIfSimple should also check if the method/accessor is explicitly non-mutating
2 parents e4504af + 3b5386e commit 3815eff

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

lib/AST/Decl.cpp

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5643,11 +5643,16 @@ void VarDecl::emitLetToVarNoteIfSimple(DeclContext *UseDC) const {
56435643
if (AD->isGetter() && !AD->getAccessorKeywordLoc().isValid())
56445644
return;
56455645
}
5646-
5646+
56475647
auto &d = getASTContext().Diags;
5648-
d.diagnose(FD->getFuncLoc(), diag::change_to_mutating,
5649-
isa<AccessorDecl>(FD))
5650-
.fixItInsert(FD->getFuncLoc(), "mutating ");
5648+
auto diags = d.diagnose(FD->getFuncLoc(), diag::change_to_mutating,
5649+
isa<AccessorDecl>(FD));
5650+
if (auto nonmutatingAttr =
5651+
FD->getAttrs().getAttribute<NonMutatingAttr>()) {
5652+
diags.fixItReplace(nonmutatingAttr->getLocation(), "mutating");
5653+
} else {
5654+
diags.fixItInsert(FD->getFuncLoc(), "mutating ");
5655+
}
56515656
return;
56525657
}
56535658
}

test/Sema/immutability.swift

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ struct SomeStruct {
159159
return 42
160160
}
161161
nonmutating
162-
set { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }}
162+
set { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-16=mutating}}
163163
iv = newValue // expected-error {{cannot assign to property: 'self' is immutable}}
164164
}
165165
}
@@ -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)