# Throwable accessors

**URL:** <https://forums.swift.org/t/throwable-accessors/20509>\
**Category:** Compiler\
**Tags:** compiler, throw\
**Created:** [February 14, 2019, 9:28pm UTC](https://forums.swift.org/t/throwable-accessors/20509 "2019-02-14T21:28:19Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 14, 2019, 9:28pm UTC](https://forums.swift.org/t/throwable-accessors/20509/1 "2019-02-14T21:28:19Z")

</div>

I have spent a bit of time looking into this based on @John_McCall suggestion and encouragement [here](https://forums.swift.org/t/proposal-allow-getters-and-setters-to-throw/191/20).

I think the first thing is to start with the parser and update `parseGetSet()` to consume a `throws` token and then update `createAccessorFunc()` signature to accept a `throws` boolean so when creating an `AccessorDecl`, we can pass it forward.

I have started working on this feature, but I am wondering how much code can be reused since `AccessorDecl` is a subclass of `FuncDecl` which supports `throws` and what other (specific) areas need to be updated to support the new functionality? cc @John_McCall

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [February 14, 2019, 10:05pm UTC](https://forums.swift.org/t/throwable-accessors/20509/2 "2019-02-14T22:05:00Z")

</div>

I think modifying the parser is a fine place to start.

The biggest issue at this stage is probably going to be dealing with all the places that synthesize accessors and making a reasonable decision about whether the synthesized accessor should throw. In most places I hope it'll be obvious how to make that decision, but there might be some nastier exceptions.

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 14, 2019, 11:30pm UTC](https://forums.swift.org/t/throwable-accessors/20509/3 "2019-02-14T23:30:30Z")

</div>

Thanks John, I have got the parser bit working now. At the moment, this parses:

```swift
class Foo {

  enum FooError: Error {
    case bar
  }

  var baz: String {
    get throws {
      throw FooError.bar
    }
  }
}

```

If I try using it:

```swift
let foo = Foo()
let hello = foo.baz

```

then it works! I get a fatal error: `Fatal error: Error raised at top level: test.Foo.FooError.bar`

Sema doesn't quite detect it when I add a `try` (it complains `no calls to throwing functions occur within 'try' expression`) but still leads to a crash as expected. `try?` works though & it doesn't crash.

---

<div class="post-metadata">

**Author:** ![Alejandro](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alejandro/32/46197_2.png) [@Alejandro](https://forums.swift.org/u/Alejandro)\
**Post date:** [February 14, 2019, 11:45pm UTC](https://forums.swift.org/t/throwable-accessors/20509/4 "2019-02-14T23:45:49Z")

</div>

TypeCheckError is where you're going to want to go if you want the type checker to understand that an accessor can throw. Right now it only checks apply expressions if the callee throws.

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 14, 2019, 11:46pm UTC](https://forums.swift.org/t/throwable-accessors/20509/5 "2019-02-14T23:46:03Z")

</div>

Setters don't work at the moment, need some tweaking. Currently crashes in SIL: ` (ThrowDest.isValid() && "calling emitThrow with invalid throw destination!")`

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 14, 2019, 11:46pm UTC](https://forums.swift.org/t/throwable-accessors/20509/6 "2019-02-14T23:46:18Z")

</div>

Yeah, I'll tweak that in a moment!

---

<div class="post-metadata">

**Author:** ![akyrtzi](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/akyrtzi/32/4963_2.png) [@akyrtzi](https://forums.swift.org/u/akyrtzi)\
**Post date:** [February 15, 2019, 1:59am UTC](https://forums.swift.org/t/throwable-accessors/20509/7 "2019-02-15T01:59:38Z")

</div>

It would be great if at some point you could also look into updating the libSyntax part, e.g. [the syntax definition of accessors](https://github.com/apple/swift/blob/376f994159c71217e18388fb1f7f163eefb3d283/utils/gyb_syntax_support/DeclNodes.py#L500) 🙏

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 15, 2019, 2:08am UTC](https://forums.swift.org/t/throwable-accessors/20509/8 "2019-02-15T02:08:31Z")

</div>

Will do 🙂

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [February 15, 2019, 3:47am UTC](https://forums.swift.org/t/throwable-accessors/20509/9 "2019-02-15T03:47:03Z")

</div>

The `TypeCheckError` stuff might be somewhat of a challenge — we used to mark how an l-value expression was being accessed in the AST, but @Slava_Pestov ripped that out, so now you'll have to propagate that information down to the `DeclRefExpr` etc. so that you can know which accessors are being used.

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 15, 2019, 8:21pm UTC](https://forums.swift.org/t/throwable-accessors/20509/10 "2019-02-15T20:21:43Z")

</div>

I think the reason why it's not getting detected for `try` is because the type of the property (`VarDecl`) is ` type='String' interface type='String'` whereas the type for the accessor (get) is `interface type='(Foo) -> () throws -> String'`, so in `TypeCheckError`, when `checkTry` tries walking the subexpression, it encounters a `MemberRefExpr` whose type is `String` and thus produces the `no calls to throwing functions occur within 'try' expression` warning.

So perhaps we also need to update the type of the property to `() throws -> String()`. Is that the correct approach? or should we teach `ErrorHandlingWalker` how to look for accessors as well? @John_McCall

---

<div class="post-metadata">

**Author:** ![Alejandro](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alejandro/32/46197_2.png) [@Alejandro](https://forums.swift.org/u/Alejandro)\
**Post date:** [February 15, 2019, 8:58pm UTC](https://forums.swift.org/t/throwable-accessors/20509/11 "2019-02-15T20:58:53Z")

</div>

It would make more sense (to me) to teach it to walk accessors because new expressions in the future, like await or unsafe, can take advantage of this for async or unsafe accessors.

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 15, 2019, 9:04pm UTC](https://forums.swift.org/t/throwable-accessors/20509/12 "2019-02-15T21:04:45Z")

</div>

Yes, it seems like a reasonable approach. Still trying to understand how it works, because `ErrorHandlingWalker` is a simple class and doesn't seem to be doing much.

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [February 15, 2019, 9:09pm UTC](https://forums.swift.org/t/throwable-accessors/20509/13 "2019-02-15T21:09:04Z")

</div>

Right now, the walker assumes that expressions like `DeclRefExpr` and `MemberRefExpr` don't themselves throw because accessors never throw. That needs to change. Like I said above, this will be somewhat difficult because you can't tell from looking at a `DeclRefExpr` which accessors are going to be used.

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 15, 2019, 9:21pm UTC](https://forums.swift.org/t/throwable-accessors/20509/14 "2019-02-15T21:21:00Z")

</div>

@John_McCall Hmm, in the example I gave above, the `try` expression would look something like:

```swift
(try_expr ...)
  (member_ref_expr ...)
    (declref_expr ...)

```

So, a check like this would work:

```cpp
// in checkTry()
auto throwingAccessor = false;
if (auto MRE = dyn_cast<MemberRefExpr>(E->getValueProvidingExpr())) {
	if (auto VD = dyn_cast_or_null<VarDecl>(MRE->getDecl().getDecl())) {
		if (VD->getAccessor(AccessorKind::Get)->hasThrows()) {
			throwingAccessor = true;
			Flags.set(ContextFlags::HasTryThrowSite);
		}
	}
}
		
if (!throwingAccessor) {
	E->getSubExpr()->walk(*this);
}

```

for

```swift
let bar = try foo.throwingProperty

```

This is just a simple check, but perhaps this could be expanded to check for `DeclRefExpr` and `MemberRefExpr` both and check for getters and setters as well. Maybe this could be extracted into a separate "walker" too.

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 15, 2019, 9:26pm UTC](https://forums.swift.org/t/throwable-accessors/20509/15 "2019-02-15T21:26:31Z")

</div>

But yes, as you said, it's tricky to determine which accessors are going to be used!

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [February 15, 2019, 9:27pm UTC](https://forums.swift.org/t/throwable-accessors/20509/16 "2019-02-15T21:27:35Z")

</div>

That's the right basic idea, except that you should base the decision on which accessor is actually being used, which is context-dependent.

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 15, 2019, 9:39pm UTC](https://forums.swift.org/t/throwable-accessors/20509/17 "2019-02-15T21:39:42Z")

</div>

@John_McCall Yes, that works for getters. For setters, we will have something like this:

```swift
(try_expr ...)
  (assign_expr ...)
    (member_ref_expr ...)
      (declref_expr ...)

```

so maybe check for an assign expression? That could be used to distinguish between a getter and a setter.

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 15, 2019, 9:42pm UTC](https://forums.swift.org/t/throwable-accessors/20509/18 "2019-02-15T21:42:51Z")

</div>

So,

```cpp
auto throwingAccessor = false;
auto setter = dyn_cast<AssignExpr>(E->getValueProvidingExpr());
auto expr = setter ? setter->getDest() : E->getValueProvidingExpr();
if (auto MRE = dyn_cast<MemberRefExpr>(expr)) {
	if (auto VD = dyn_cast_or_null<VarDecl>(MRE->getDecl().getDecl())) {
		if (VD->getAccessor(setter ? AccessorKind::Set : AccessorKind::Get)->hasThrows()) {
			throwingAccessor = true;
			Flags.set(ContextFlags::HasTryThrowSite);
		}
	}
}
		
if (!throwingAccessor) {
    E->getSubExpr()->walk(*this);
}

...

```

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [February 15, 2019, 10:21pm UTC](https://forums.swift.org/t/throwable-accessors/20509/19 "2019-02-15T22:21:18Z")

</div>

That's more like it, but sadly it is much more complicated than that because of `inout` arguments, `mutating` methods, `mutating` accessors, and access semantics.

---

<div class="post-metadata">

**Author:** ![suyashsrijan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/suyashsrijan/32/5292_2.png) [@suyashsrijan](https://forums.swift.org/u/suyashsrijan)\
**Post date:** [February 15, 2019, 10:37pm UTC](https://forums.swift.org/t/throwable-accessors/20509/20 "2019-02-15T22:37:36Z")

</div>

@John_McCall How should I proceed with that? `mutating` getter has the same issue as setters - crash in SILGen: `Assertion failed: (ThrowDest.isValid() && "calling emitThrow with invalid throw destination!")`. I have extremely limited experience with SIL so unsure why this is happening.

```swift
extension String: Error {}

struct Foo {
  var bar: String {
    mutating get throws { 
      throw "Throwing from a getter"
    }
  }
}

func foo(f: inout Foo) {
  let _ = f.bar
}

var instance = Foo()
foo(f: &instance)

```

[Next page](https://forums.swift.org/t/throwable-accessors/20509.md?page=2)
