Skip to content

[AST] emitLetToVarNoteIfSimple should also check if the method/accessor is explicitly non-mutating #27641

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

Merged
merged 3 commits into from
Oct 14, 2019
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
13 changes: 9 additions & 4 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5683,11 +5683,16 @@ void VarDecl::emitLetToVarNoteIfSimple(DeclContext *UseDC) const {
if (AD->isGetter() && !AD->getAccessorKeywordLoc().isValid())
return;
}

auto &d = getASTContext().Diags;
d.diagnose(FD->getFuncLoc(), diag::change_to_mutating,
isa<AccessorDecl>(FD))
.fixItInsert(FD->getFuncLoc(), "mutating ");
auto diags = d.diagnose(FD->getFuncLoc(), diag::change_to_mutating,
isa<AccessorDecl>(FD));
if (auto nonmutatingAttr =
FD->getAttrs().getAttribute<NonMutatingAttr>()) {
diags.fixItReplace(nonmutatingAttr->getLocation(), "mutating");
} else {
diags.fixItInsert(FD->getFuncLoc(), "mutating ");
}
return;
}
}
Expand Down
22 changes: 21 additions & 1 deletion test/Sema/immutability.swift
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ struct SomeStruct {
return 42
}
nonmutating
set { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }}
set { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-16=mutating}}
iv = newValue // expected-error {{cannot assign to property: 'self' is immutable}}
}
}
Expand Down Expand Up @@ -681,3 +681,23 @@ struct SS {
j = j // expected-error {{cannot assign to value: 'j' is a 'let' constant}}
}
}

protocol JustAProtocol {
var name: String { get set }
}

extension JustAProtocol {
var foo: String {
get { return name }
nonmutating set { name = newValue } // expected-error {{cannot assign to property: 'self' is immutable}}
// expected-note@-1 {{mark accessor 'mutating' to make 'self' mutable}}{{5-16=mutating}}
}

nonmutating func bar() { // expected-note {{mark method 'mutating' to make 'self' mutable}}{{3-14=mutating}}
name = "Hello" // expected-error {{cannot assign to property: 'self' is immutable}}
}

func baz() { // expected-note {{mark method 'mutating' to make 'self' mutable}}{{3-3=mutating }}
name = "World" // expected-error {{cannot assign to property: 'self' is immutable}}
}
}