You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/docs/reference/experimental/canthrow.md
+28-30Lines changed: 28 additions & 30 deletions
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
---
2
2
layout: doc-page
3
-
title: CanThrow Abilities
3
+
title: CanThrow Capabilities
4
4
author: Martin Odersky
5
5
---
6
6
@@ -42,7 +42,7 @@ So the dilemma is that exceptions are easy to use only as long as we forgo stati
42
42
43
43
However, a programming language is not a framework; it has to cater also for those applications that do not fit the framework's use cases. So there's still a strong motivation for getting exception checking right.
44
44
45
-
## From Effects To Abilities
45
+
## From Effects To Capabilities
46
46
47
47
Why does `map` work so poorly with Java's checked exception model? It's because
48
48
`map`'s signature limits function arguments to not throw checked exceptions. We could try to come up with a more polymorphic formulation of `map`. For instance, it could look like this:
@@ -53,22 +53,20 @@ This assumes a type `A throws E` to indicate computations of type `A` that can t
53
53
54
54
But there is a way to avoid the ceremony. Instead of concentrating on possible _effects_ such as "this code might throw an exception", concentrate on _capabilities_ such as "this code needs the capability to throw an exception". From a standpoint of expressiveness this is quite similar. But capabilities can be expressed as parameters whereas traditionally effects are expressed as some addition to result values. It turns out that this can make a big difference!
55
55
56
-
Going to the root of the word _capability_, it means "being _able_ to do something", so the "cap" prefix is really just a filler. Following Conor McBride, we will use the name _ability_ from now on.
56
+
## The CanThrow Cabability
57
57
58
-
## The CanThrow Ability
59
-
60
-
In the _effects as abilities_ model, an effect is expressed as an (implicit) parameter of a certain type. For exceptions we would expect parameters of type
58
+
In the _effects as capabilities_ model, an effect is expressed as an (implicit) parameter of a certain type. For exceptions we would expect parameters of type
61
59
`CanThrow[E]` where `E` stands for the exception that can be thrown. Here is the definition of `CanThrow`:
62
60
```scala
63
61
erased classCanThrow[-E<:Exception]
64
62
```
65
-
This shows another experimental Scala feature: [erased definitions](./erased-defs). Roughly speaking, values of an erased class do not generate runtime code; they are erased before code generation. This means that all `CanThrow`abilities are compile-time only artifacts; they do not have a runtime footprint.
63
+
This shows another experimental Scala feature: [erased definitions](./erased-defs). Roughly speaking, values of an erased class do not generate runtime code; they are erased before code generation. This means that all `CanThrow`capabilities are compile-time only artifacts; they do not have a runtime footprint.
66
64
67
-
Now, if the compiler sees a `throw Exc()` construct where `Exc` is a checked exception, it will check that there is an ability of type `CanThrow[Exc]` that can be summoned as a given. It's a compile-time error if that's not the case.
65
+
Now, if the compiler sees a `throw Exc()` construct where `Exc` is a checked exception, it will check that there is a capability of type `CanThrow[Exc]` that can be summoned as a given. It's a compile-time error if that's not the case.
68
66
69
-
How can the ability be produced? There are several possibilities:
67
+
How can the capability be produced? There are several possibilities:
70
68
71
-
Most often, the ability is produced by having a using clause `(using CanThrow[Exc])` in some enclosing scope. This roughly corresponds to a `throws` clause
69
+
Most often, the capability is produced by having a using clause `(using CanThrow[Exc])` in some enclosing scope. This roughly corresponds to a `throws` clause
72
70
in Java. The analogy is even stronger since alongside `CanThrow` there is also the following type alias defined in the `scala` package:
@@ -96,7 +94,7 @@ can alternatively be expressed like this:
96
94
```scala
97
95
defm(x: T):U throws E1|E2
98
96
```
99
-
The `CanThrow`/`throws` combo essentially propagates the `CanThrow` requirement outwards. But where are these abilities created in the first place? That's in the `try` expression. Given a `try` like this:
97
+
The `CanThrow`/`throws` combo essentially propagates the `CanThrow` requirement outwards. But where are these capabilities created in the first place? That's in the `try` expression. Given a `try` like this:
100
98
101
99
```scala
102
100
try
@@ -106,7 +104,7 @@ catch
106
104
...
107
105
caseexN: ExN=> handlerN
108
106
```
109
-
the compiler generates abilities for `CanThrow[Ex1]`, ..., `CanThrow[ExN]` that are in scope as givens in `body`. It does this by augmenting the `try` roughly as follows:
107
+
the compiler generates capabilities for `CanThrow[Ex1]`, ..., `CanThrow[ExN]` that are in scope as givens in `body`. It does this by augmenting the `try` roughly as follows:
110
108
```scala
111
109
try
112
110
erased givenCanThrow[Ex1] =???
@@ -136,8 +134,8 @@ You'll get this error message:
136
134
```
137
135
9 | if x < limit then x * x else throw LimitExceeded()
138
136
| ^^^^^^^^^^^^^^^^^^^^^
139
-
|The ability to throw exception LimitExceeded is missing.
140
-
|The ability can be provided by one of the following:
137
+
|The capability to throw exception LimitExceeded is missing.
138
+
|The capability can be provided by one of the following:
141
139
| - A using clause `(using CanThrow[LimitExceeded])`
142
140
| - A `throws` clause in a result type such as `X throws LimitExceeded`
143
141
| - an enclosing `try` that catches LimitExceeded
@@ -146,7 +144,7 @@ You'll get this error message:
146
144
|
147
145
| import unsafeExceptions.canThrowAny
148
146
```
149
-
As the error message implies, you have to declare that `f` needs the ability to throw a `LimitExceeded` exception. The most concise way to do so is to add a `throws` clause:
147
+
As the error message implies, you have to declare that `f` needs the capability to throw a `LimitExceeded` exception. The most concise way to do so is to add a `throws` clause:
150
148
```scala
151
149
deff(x: Double):Double throws LimitExceeded=
152
150
if x < limit then x * x elsethrowLimitExceeded()
@@ -175,26 +173,26 @@ Everything typechecks and works as expected. But wait - we have called `map` wit
175
173
println(xs.map(x => f(x)(using ctl)).sum)
176
174
catchcaseex: LimitExceeded=> println("too large")
177
175
```
178
-
The `CanThrow[LimitExceeded]`ability is passed in a synthesized `using` clause to `f`, since `f` requires it. Then the resulting closure is passed to `map`. The signature of `map` does not have to account for effects. It takes a closure as always, but that
179
-
closure may refer to abilities in its free variables. This means that `map` is
176
+
The `CanThrow[LimitExceeded]`capability is passed in a synthesized `using` clause to `f`, since `f` requires it. Then the resulting closure is passed to `map`. The signature of `map` does not have to account for effects. It takes a closure as always, but that
177
+
closure may refer to capabilities in its free variables. This means that `map` is
180
178
already effect polymorphic even though we did not change its signature at all.
181
-
So the takeaway is that the effects as abilities model naturally provides for effect polymorphism whereas this is something that other approaches struggle with.
179
+
So the takeaway is that the effects as capabilities model naturally provides for effect polymorphism whereas this is something that other approaches struggle with.
182
180
183
181
## Gradual Typing Via Imports
184
182
185
183
Another advantage is that the model allows a gradual migration from current unchecked exceptions to safer exceptions. Imagine for a moment that `experimental.saferExceptions` is turned on everywhere. There would be lots of code that breaks since functions have not yet been properly annotated with `throws`. But it's easy to create an escape hatch that lets us ignore the breakages for a while: simply add the import
186
184
```scala
187
185
importscala.unsafeExceptions.canThrowAny
188
186
```
189
-
This will provide the `CanThrow`ability for any exception, and thereby allow
187
+
This will provide the `CanThrow`capability for any exception, and thereby allow
190
188
all throws and all other calls, no matter what the current state of `throws` declarations is. Here's the
191
189
definition of `canThrowAny`:
192
190
```scala
193
191
packagescala
194
192
objectunsafeExceptions:
195
193
givencanThrowAny:CanThrow[Exception] =???
196
194
```
197
-
Of course, defining a global ability like this amounts to cheating. But the cheating is useful for gradual typing. The import could be used to migrate existing code, or to
195
+
Of course, defining a global capability like this amounts to cheating. But the cheating is useful for gradual typing. The import could be used to migrate existing code, or to
198
196
enable more fluid explorations of code without regard for complete exception safety. At the end of these migrations or explorations the import should be removed.
199
197
200
198
## Scope Of the Extension
@@ -203,24 +201,24 @@ To summarize, the extension for safer exception checking consists of the followi
203
201
204
202
- It adds to the standard library the class `scala.CanThrow`, the type `scala.$throws`, and the `scala.unsafeExceptions` object, as they were described above.
205
203
- It adds some desugaring rules ro rewrite `throws` types to cascaded `$throws` types.
206
-
- It augments the type checking of `throw` by _demanding_ a `CanThrow`ability or the thrown exception.
207
-
- It augments the type checking of `try` by _providing_`CanThrow`abilities for every caught exception.
204
+
- It augments the type checking of `throw` by _demanding_ a `CanThrow`capability or the thrown exception.
205
+
- It augments the type checking of `try` by _providing_`CanThrow`capabilities for every caught exception.
208
206
209
207
That's all. It's quite remarkable that one can do exception checking in this way without any special additions to the type system. We just need regular givens and context functions. Any runtime overhead is eliminated using `erased`.
210
208
211
209
## Caveats
212
210
213
-
Our ability model allows to declare and check the thrown exceptions of first-order code. But as it stands, it does not give us enough mechanism to enforce the _absence_ of
214
-
abilities for arguments to higher-order functions. Consider a variant `pureMap`
211
+
Our capability model allows to declare and check the thrown exceptions of first-order code. But as it stands, it does not give us enough mechanism to enforce the _absence_ of
212
+
capabilities for arguments to higher-order functions. Consider a variant `pureMap`
215
213
of `map` that should enforce that its argument does not throw exceptions or have any other effects (maybe because wants to reorder computations transparently). Right now
216
214
we cannot enforce that since the function argument to `pureMap` can capture arbitrary
217
-
abilities in its free variables without them showing up in its type. One possible way to
218
-
address this would be to introduce a pure function type (maybe written `A -> B`). Pure functions are not allowed to close over abilities. Then `pureMap` could be written
215
+
capabilities in its free variables without them showing up in its type. One possible way to
216
+
address this would be to introduce a pure function type (maybe written `A -> B`). Pure functions are not allowed to close over capabilities. Then `pureMap` could be written
219
217
like this:
220
218
```
221
219
def pureMap(f: A -> B): List[B]
222
220
```
223
-
Another area where the lack of purity requirements shows up is when abilities escape from bounded scopes. Consider the following function
221
+
Another area where the lack of purity requirements shows up is when capabilities escape from bounded scopes. Consider the following function
224
222
```scala
225
223
defescaped(xs: Double*): () =>Int=
226
224
try () => xs.map(f).sum
@@ -240,16 +238,16 @@ But if you try to call `escaped` like this
240
238
valg= escaped(1, 2, 1000000000)
241
239
g()
242
240
```
243
-
the result will be a `LimitExceeded` exception thrown at the second line where `g` is called. What's missing is that `try` should enforce that the abilities it generates do not escape as free variables in the result of its body. It makes sense to describe such scoped effects as _ephemeral abilities_ - they have lifetimes that cannot be extended to delayed code in a lambda.
241
+
the result will be a `LimitExceeded` exception thrown at the second line where `g` is called. What's missing is that `try` should enforce that the capabilities it generates do not escape as free variables in the result of its body. It makes sense to describe such scoped effects as _ephemeral capabilities_ - they have lifetimes that cannot be extended to delayed code in a lambda.
244
242
245
243
246
244
# Outlook
247
245
248
-
We are working on a new class of type system that supports ephemeral abilities by tracking the free variables of values. Once that research matures, it will hopefully be possible to augment the language so that we can enforce the missing properties.
246
+
We are working on a new class of type system that supports ephemeral capabilities by tracking the free variables of values. Once that research matures, it will hopefully be possible to augment the language so that we can enforce the missing properties.
249
247
250
248
And it would have many other applications besides: Exceptions are a special case of _algebraic effects_, which has been a very active research area over the last 20 years and is finding its way into programming languages (e.g. Koka, Eff, Multicore OCaml, Unison). In fact, algebraic effects have been characterized as being equivalent to exceptions with an additional _resume_ operation. The techniques developed here for exceptions can probably be generalized to other classes of algebraic effects.
251
249
252
-
But even without these additional mechanisms, exception checking is already useful as it is. It gives a clear path forward to make code that uses exceptions safer, better documented, and easier to refactor. The only loophole arises for scoped abilities - here we have to verify manually that these abilities do not escape. Specifically, a `try` always has to be placed in the same computation stage as the throws that it enables.
250
+
But even without these additional mechanisms, exception checking is already useful as it is. It gives a clear path forward to make code that uses exceptions safer, better documented, and easier to refactor. The only loophole arises for scoped capabilities - here we have to verify manually that these capabilities do not escape. Specifically, a `try` always has to be placed in the same computation stage as the throws that it enables.
253
251
254
252
Put another way: If the status quo is 0% static checking since 100% is too painful, then an alternative that gives you 95% static checking with great ergonomics looks like a win. And we might still get to 100% in the future.
Copy file name to clipboardExpand all lines: library/src-bootstrapped/scala/CanThrow.scala
+2-2Lines changed: 2 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -2,12 +2,12 @@ package scala
2
2
importlanguage.experimental.erasedDefinitions
3
3
importannotation.{implicitNotFound, experimental}
4
4
5
-
/**An ability class that allows to throw exception `E`. When used with the
5
+
/**A capability class that allows to throw exception `E`. When used with the
6
6
* experimental.saferExceptions feature, a `throw Ex()` expression will require
7
7
* a given of class `CanThrow[Ex]` to be available.
8
8
*/
9
9
@experimental
10
-
@implicitNotFound("The ability to throw exception ${E} is missing.\nThe ability can be provided by one of the following:\n - A using clause `(using CanThrow[${E}])`\n - A `throws` clause in a result type such as `X throws ${E}`\n - an enclosing `try` that catches ${E}")
10
+
@implicitNotFound("The capability to throw exception ${E} is missing.\nThe capability can be provided by one of the following:\n - A using clause `(using CanThrow[${E}])`\n - A `throws` clause in a result type such as `X throws ${E}`\n - an enclosing `try` that catches ${E}")
0 commit comments