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

[SR-4174] Compiler should emit warning when shadowing bound variable during pattern matching #46757

Open
swift-ci opened this issue Mar 7, 2017 · 2 comments
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. compiler The Swift compiler in itself

Comments

@swift-ci
Copy link
Collaborator

swift-ci commented Mar 7, 2017

Previous ID SR-4174
Radar None
Original Reporter erica (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug
Assignee None
Priority Medium

md5: 161deecb8c2d61dc752c8d993c43c08a

relates to:

  • SR-1687 Swift does not warn about shadowing
  • SR-8524 Shadowing in protocols leads to difficult to find bugs

Issue Description:

When pattern matching, it's common to bind a variable or constant. It's uncommon but legal to use a bound value as an argument. Consider the following enumeration and values:

// An enum with one, two, or three associated values
enum Value<T> { case one(T), two(T, T), three(T, T, T) }

// An example with two associated values
let example2: Value<Character> = .two("a", "b")

// A bound symbol
let oldValue = "x"

This code's goal is to conditionally bind newValue and pattern match the value stored in the oldValue symbol. The first example succeeds. The second example compiles and runs but does not match the coder's intent. Using an external let creates a new oldValue shadow instead of pattern matching oldValue's stored value.

// Safe
if case .two(let newValue, oldValue) = example2 { 
    ... 
}

// Syntactically legal but incorrect
if case let .two(newValue, oldValue) = example2 { 
    ... 
}

The compiler should detect same-name shadowing of an already-bound variable during pattern matching and emit a compile-time warning.

References:

@belkadan
Copy link
Contributor

belkadan commented Mar 7, 2017

We don't currently emit any shadowing warnings.

@swift-ci
Copy link
Collaborator Author

swift-ci commented Mar 7, 2017

Comment by erica sadun (JIRA)

So should I take this back to SE? I'm unsure where this applies.

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. compiler The Swift compiler in itself
Projects
None yet
Development

No branches or pull requests

2 participants