# Allow referencing outer functions when inner functions share base name

**URL:** <https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800>\
**Category:** Discussion\
**Created:** [July 27, 2020, 9:28pm UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800 "2020-07-27T21:28:53Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jumhyn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jumhyn/32/3891_2.png) [@Jumhyn](https://forums.swift.org/u/Jumhyn)\
**Post date:** [July 27, 2020, 9:28pm UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/1 "2020-07-27T21:28:53Z")

</div>

Consider the following snippet:

```swift
func foo(x1: Int) {}

struct S {
    func foo(x2: Int) {}
    func method() {
        func foo(x3: Int) {}
        let closure = {
            func foo(x4: Int) {}
            foo(x1: 0)
            foo(x2: 0)
            foo(x3: 0)
            foo(x4: 0)
        }
    }
}

```

In Swift today, the first three calls to `foo` fail to compile with a complaint about the wrong argument label ("`expected 'x4:'`"). I found [SR-7018](https://bugs.swift.org/browse/SR-7018) wherein @jrose confirms that this is the intended behavior.

As I've worked on an implementation for [compound variable names](https://forums.swift.org/t/compound-variable-names/37963), I came across this behavior. Given the relatively sparse usage of nested functions, it's not surprising that this behavior has not caused much trouble.

However, I do worry about it's consequence in the midst of compound variable names, since it would potentially make compound names behave subtly differently from simple names. E.g.,

```swift
func fetchImage(from url: URL, then completion(image:): (UIImage) -> Void) -> {
  let completion(data:): (Data) -> Void = {
    completion(image: makeImage(from: $0)) // Error: incorrect argument label
  }
  fetchData(from: url, completion: completion(data:))
}

```

I'm interested in the community's feedback on whether this behavior is more confusing in the context of compound names, or if it seems unlikely to be an issue in practice.

---

<div class="post-metadata">

**Author:** ![beccadax](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/beccadax/32/34217_2.png) [@beccadax](https://forums.swift.org/u/beccadax)\
**Post date:** [July 27, 2020, 9:32pm UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/2 "2020-07-27T21:32:43Z")

</div>

Does using `ModuleName.foo` instead get you to `foo(x1:)`?

---

<div class="post-metadata">

**Author:** ![Jumhyn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jumhyn/32/3891_2.png) [@Jumhyn](https://forums.swift.org/u/Jumhyn)\
**Post date:** [July 27, 2020, 9:37pm UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/3 "2020-07-27T21:37:42Z")

</div>

Yeah, you can reference `Module.foo(x1:)`, and `self.foo(x2:)` works as well. AFAIK there's no way to get at `foo(x3:)` within `closure`, but the double-nested functions are unusual enough that I'm not particularly troubled by being unable to access shadowed base names. With compound variable names, though, the points at which compound names can be introduced increases drastically (such as function parameters in the example above), so this sort of shadowing may be more problematic.

---

<div class="post-metadata">

**Author:** ![typesanitizer](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/typesanitizer/32/8661_2.png) [@typesanitizer](https://forums.swift.org/u/typesanitizer)\
**Post date:** [July 27, 2020, 10:05pm UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/4 "2020-07-27T22:05:53Z")

</div>

> [@Jumhyn](#):
>
> In Swift today, all of the calls to `foo` fail to compile with a complaint about the wrong argument label

Typo? The first three calls give an error, the fourth call to `foo(x4:)` is fine.

* * *

```swift
  let completion(data:): (Data) -> Void = {
    completion(image: makeImage(from: $0)) // Error: incorrect argument label
  }

```

I don't get why should this be an error...? Swift's `let` is not recursive from what I can tell:

```swift
let f : () -> () = { f() } // error: variable used within its own initial value

```

---

<div class="post-metadata">

**Author:** ![Jumhyn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jumhyn/32/3891_2.png) [@Jumhyn](https://forums.swift.org/u/Jumhyn)\
**Post date:** [July 27, 2020, 10:33pm UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/5 "2020-07-27T22:33:20Z")

</div>

> [@typesanitizer](#):
>
> Typo? The first three calls give an error, the fourth call to `foo(x4:)` is fine.

Yes, thank you, updated appropriately! 🤦‍♂️

> [@typesanitizer](#):
>
> I don't get why should this be an error...? Swift's `let` is not recursive from what I can tell:
> 
> ```swift
> let f : () -> () = { f() } // error: variable used within its own initial value
> 
> ```

Yeah, we could probably massage the parser and lookup so that this example makes sense to the compiler, with the caveat that we'd have to give up on this ([7 year old!](https://github.com/rintaro/swift/commit/736c6d2db64ff426622079bffb1fe1fb8ca13af4#diff-3f6a161822412eea4b0e705487dd88c1R1324)) FIXME 😅

```swift
// FIXME: We want this to work: "var x = { x() }", but for now it's better 
// to disallow it than to crash.

```

But the issue still arises even if we allow recursive closures, in ways that seem much more natural than the double-nested function:

```swift
func fetchImage(
  from url: URL, 
  then completion(image:): (UIImage) -> Void, 
  onError completion(error:): (Error) -> Void
) -> {
  let completion(data:): (Data) -> Void = {
    completion(image: makeImage(from: $0))
  }
  fetchData(from: url) { error, data in
    if let error = error {
      completion(error: error) // Incorrect argument label!
    } else if let data = data {
      completion(data: data)
    } else {
      assertionFailure("No error and no data!")
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![typesanitizer](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/typesanitizer/32/8661_2.png) [@typesanitizer](https://forums.swift.org/u/typesanitizer)\
**Post date:** [July 27, 2020, 11:07pm UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/6 "2020-07-27T23:07:04Z")

</div>

> [@Jumhyn](#):
>
> Yeah, we could probably massage the parser and lookup so that this example makes sense to the compiler, with the caveat that we'd have to give up on this ([7 year old!](https://github.com/rintaro/swift/commit/736c6d2db64ff426622079bffb1fe1fb8ca13af4#diff-3f6a161822412eea4b0e705487dd88c1R1324)) FIXME 😅

I suspect that changing that behavior will break some code relying on the interaction of shadowing and closures. I don't think fixing the FIXME is worth that breakage. Since local functions are easily written, you can tie the knot yourself. 🤷‍♂️

> [@Jumhyn](#):
>
> But the issue still arises even if we allow recursive closures, in ways that seem much more natural than the double-nested function:

Is this meaningfully different from [SR-7018](https://bugs.swift.org/browse/SR-7018)? IMO it is the same problem, but in a slightly different setting. I think `completion(image:)` should not behave as if it is in the same scope as `completion(data:)` because there is an unbalanced opening brace between them, and braces indicate scopes. "Braces indicate scopes" is a simpler mental rule than "braces indicate scopes except when they are the main braces for a function declaration". And different scopes implies shadowing, not addition to overload set (as per SR-7018).

That said here's the behavior for slightly similar code that you can write today:

```swift
func g(_ f: () -> ()) {
    func f(x: Int) {}
    f() // okay
    f(x: 10) // error: argument passed to call that takes no arguments
}

```

which has me somewhat shook. 😮 (EDIT: Confirmed that this is a bug with Doug. Filed [[SR-13306] Incorrect shadowing behavior for local functions and outer function parameters · Issue #55746 · apple/swift · GitHub](https://bugs.swift.org/browse/SR-13306))

---

<div class="post-metadata">

**Author:** ![Jumhyn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jumhyn/32/3891_2.png) [@Jumhyn](https://forums.swift.org/u/Jumhyn)\
**Post date:** [July 28, 2020, 12:20am UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/7 "2020-07-28T00:20:54Z")

</div>

> [@typesanitizer](#):
>
> I suspect that changing that behavior will break some code relying on the interaction of shadowing and closures. I don't think fixing the FIXME is worth that breakage. Since local functions are easily written, you can tie the knot yourself. 🤷‍♂️

Agreed.

> [@typesanitizer](#):
>
> Is this meaningfully different from [SR-7018](https://bugs.swift.org/browse/SR-7018)? IMO it is the same problem, but in a slightly different setting. [...] And different scopes implies shadowing, not addition to overload set (as per SR-7018).

Depends on your definition of "meaningful." My concern arises from two (perhaps unfounded) concerns:

1. Local functions/closures with the same base name and different argument names will become more common if compound variable names become part of the language.
2. The 'inline' spelling of compound-named variables implies that

```swift
var base(arg1:arg2:): (Int, String) -> Void
var base(arg3:arg4:): (Int, String) -> Void

```

should behave more like

```swift
var baseWithArg1Arg2: (Int, String) -> Void
var baseWithArg3Arg4: (Int, String) -> Void

```

than

```swift
func base(arg1: Int, arg2: String) {}
func base(arg3: Int, arg4: String) {}

```

I'm hoping this thread will shed some light on whether others think (1) and (2) are true in a world with compound-named variables.

> [@typesanitizer](#):
>
> (EDIT: Confirmed that this is a bug with Doug.)

Phew—I didn't know how to respond to that other than "oh, dear"!

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [July 28, 2020, 12:54am UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/8 "2020-07-28T00:54:57Z")

</div>

This is essentially the same as:

[SR–0456](https://bugs.swift.org/browse/SR-456) Confusing build error when calling 'max' function within 'extension Int'  
[SR–1772](https://bugs.swift.org/browse/SR-1772) File-level function with the same name as instance function not picked up by compiler  
[SR–2450](https://bugs.swift.org/browse/SR-2450) Wrong min() function is selected for call  
[SR–4466](https://bugs.swift.org/browse/SR-4466) Extra arguments error for valid call to max  
[SR–4660](https://bugs.swift.org/browse/SR-4660) Methods on self should not block unambiguous calls to free functions  
[SR–7018](https://bugs.swift.org/browse/SR-7018) Overload resolution fails for nested function  
[SR–7143](https://bugs.swift.org/browse/SR-7143) Compiler chooses custom function over foundation function

…and probably more that I didn’t find at a quick search.

I’ve been meaning to start a thread about fixing this. As I see it, the correct solution is to change how the compiler matches candidates for a call-site.

Specifically, when expanding its search scope, the compiler should look at the full compound name including all argument labels, not just the base name, and it should not stop until it finds a candidate which could plausibly match the full name.

Declarations with the same base name but non-matching argument labels can still be identified for the purpose of generating diagnostics, but they should not be considered potential matches, and thus the search scope should continue past them.

Only a declaration which, using Swift’s rules for matching call-site arguments to function parameters by argument label, could potentially be a match based on its full compound name, should be considered a candidate.

When such a candidate matching the full compound name is found, then the search scope can stop expanding and any such candidates found there can be processed for type resolution as usual.

---

<div class="post-metadata">

**Author:** ![Jumhyn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jumhyn/32/3891_2.png) [@Jumhyn](https://forums.swift.org/u/Jumhyn)\
**Post date:** [July 28, 2020, 1:14am UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/9 "2020-07-28T01:14:42Z")

</div>

Thank you for pulling up all those examples!

> [@Nevin](#):
>
> Specifically, when expanding its search scope, the compiler should look at the full compound name including all argument labels, not just the base name, and it should not stop until it finds a candidate which could plausibly match the full name.

Right, this would bring us in line with the "argument labels are part of the name" model that SE-0111 laid the groundwork for. I'm hoping this change can be made in a source-compatible way—I haven't thought of any situation in which this extension of the lookup rules would break existing code.

> [@Jumhyn](#):
>
> AFAIK there's no way to get at `foo(x3:)` within `closure`

FWIW, I was wrong about this. Writing `f(x3:)(0)` compiles just fine. If `f(x3:)` were instead defined as `func foo() {}`, though, I can't think of a way around the current shadowing rules.

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [July 28, 2020, 1:32am UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/10 "2020-07-28T01:32:45Z")

</div>

> [@Jumhyn](#):
>
> I'm hoping this change can be made in a source-compatible way—I haven't thought of any situation in which this extension of the lookup rules would break existing code.

I concur. Any existing code which compiles today, must necessarily already have a valid candidate that matches the call-site successfully, and no smaller scopes do.

Tightening the rules to account for argument labels cannot introduce any new candidates at or below the same scope, and it can only rule out incompatible candidates. So the existing valid candidate will not be eliminated, and no new candidates will be added.

Code that works today will continue to work the same way with this improvement.

---

<div class="post-metadata">

**Author:** ![phoneyDev](https://avatars.discourse-cdn.com/v4/letter/p/49beb7/32.png) [@phoneyDev](https://forums.swift.org/u/phoneyDev)\
**Post date:** [July 29, 2020, 9:59pm UTC](https://forums.swift.org/t/allow-referencing-outer-functions-when-inner-functions-share-base-name/38800/11 "2020-07-29T21:59:28Z")

</div>

This seems also related to

```swift
let max = max(1, 2) // Variable used within its own initial value

```

```swift
let max = 1
let max1 = max(1, 2) // Cannot call value of non-function type 'Int'

```

> <https://github.com/apple/swift/issues/44455>
>
> | | |
> |------------------|-----------------|…
> |Previous ID | SR-1846 |
> |Radar | rdar://problem/22374793 |
> |Original Reporter | ayaka (JIRA User) |
> |Type | Bug |
> 
> 
> Attachment: \[Download\](https://user-images.githubusercontent.com/2727770/164961438-f285049b-00ce-4668-be64-e5ab5eb194c7.gz)
> 
>       
> \<details\>
> \<summary\>Environment\</summary\>
> 
> Xcode Version 7.3.1 (7D1014)  
> Xcode Version 8.0 beta (8S128d)
> 
> Xcode Version 10.2
> 
> 
> \</details\>
> 
> \<details\>
> \<summary\>Additional Detail from JIRA\</summary\>
> 
> | | |
> |------------------|-----------------|
> |Votes | 14 |
> |Component/s | Compiler |
> |Labels | Bug, LanguageFeatureRequest |
> |Assignee | None |
> |Priority | Medium |
> 
>    
> 
> md5: 6bf3d6604bae951be26a31a7e1d23712
> 
> \</details\>
> 
> 
> 
> 
> \*\*is duplicated by\*\*:  
> \* \[SR-3040\](https://bugs.swift.org/browse/SR-3040) Variable used within its own initial value error for functions with labels  
> \* \[SR-5916\](https://bugs.swift.org/browse/SR-5916) Assigning to var from func of same prefix throws compiler error  
> \* \[SR-10233\](https://bugs.swift.org/browse/SR-10233) Can't initialize var with function call whose stem is the same as the var name  
> \* \[SR-13404\](https://bugs.swift.org/browse/SR-13404) Swift 5 Compiler Fails to Distinguish Variable from Function  
> 
> \*\*relates to\*\*:  
> \* \[SR-10295\](https://bugs.swift.org/browse/SR-10295) Unexpected ambiguity error when trying to use variable with the same name as an instance member  
> 
> 
> \*\*Issue Description:\*\*
> 
> 
> For example:
> 
> func length(of string: String) -\\\> Int {  
> return string.characters.count  
> }
> 
> let length = length(of: "Hello world")
> 
> emits an error \\\`Variable used in its own initial value\\\`.
> 
> I often find myself wanting to use the pattern, like:  
> \`let localizedString = localizedString(from: "someKey")\`  
> but because of the error, I end up artificially changing the name of the function to something like \`getLocalizedString\` or the variable to a slightly different name, which doesn’t feel very Swift-y or in line with the new API design guidelines.
> 
> I’m sure there’s a good reason why it’s an error, but it would be reallllly nice if there is a workaround for this for the sake of writing nicer code. 🙂
> 
> Thanks!
