# What is GHC.Stack.Types.HasCallStack

**URL:** <https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402>\
**Category:** Learn\
**Created:** [December 27, 2023, 5:38pm UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402 "2023-12-27T17:38:08Z")\
**Posts on this page:** 16\
**Page:** 2

<div class="post-metadata">

**Author:** ![tomjaguarpaw](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/tomjaguarpaw/32/1230_2.png) [@tomjaguarpaw](https://discourse.haskell.org/u/tomjaguarpaw)\
**Post date:** [December 29, 2023, 9:39am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/21 "2023-12-29T09:39:56Z")

</div>

Perhaps it would be illustrative to examine the difference between `unsafePartial` and `unsafePerformIO`.

If we want to use `IO` in Haskell we have a “proper” way of doing so, which is just to plumb it all the way to `main :: IO ()`. There is such corresponding way of using `Partial`, because the type of main is not `Partial => Effect Unit`. That means users using `Partial` are _forced_ to use `unsafePartial` at some point in their program. If Haskell forced users to use `unsafePerformIO` in order to do `IO` that would also be very bad (actually, worse).

Would the situation be better if instead of `unsafePartial` the way of interpreting `Partial =>` was `partialToException :: (Partial => a) -> Effect a`? The equivalent in Haskell would be `partialToException :: (Partial => a) -> IO a`. We still wouldn’t have the property that `evaluate <=< partialToException` removes the partiality, but at least the partiality _is_ stuck in `IO`. On the other hand, this wouldn’t allow us to “mark” safe usages of, e.g., `head` and return to the pure world.

---

<div class="post-metadata">

**Author:** ![atravers](https://avatars.discourse-cdn.com/v4/letter/a/45deac/32.png) [@atravers](https://discourse.haskell.org/u/atravers)\
**Post date:** [December 29, 2023, 11:17am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/22 "2023-12-29T11:17:10Z")

</div>

From looking at the PureScript documentation, it appears `unsafePartial` works by throwing an exception. For Haskell, that suggests:

```haskell
partialToException :: (Partial => a) -> b
partialToException x = throw (PartiallyDefined (fromPartial x))

```

with a suitable invocation of `catch` in `IO` to deal with the exception accordingly. Now compare that to the [current definition of](https://hackage.haskell.org/package/base-4.19.0.0/docs/src/GHC.Err.html#error) `Prelude.error` :

```haskell
error :: ... HasCallStack => [Char] -> a
error s = raise# (errorCallWithCallStackException s ?callStack)

```

…let’s just rename `HasCallStack` to `Partial` - problem [solved!](https://www.interaction-design.org/literature/article/kiss-keep-it-simple-stupid-a-design-principle)

---

<div class="post-metadata">

**Author:** ![brandonchinn178](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/brandonchinn178/32/5103_2.png) [@brandonchinn178](https://discourse.haskell.org/u/brandonchinn178)\
**Post date:** [December 29, 2023, 6:23pm UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/23 "2023-12-29T18:23:09Z")

</div>

RE: partialToException

I don’t see the purpose of this. If the only way to invoke a partial function is via IO, why not just force partial functions to be IO and use throwIO?

The whole point of partial functions is the developer knowing that a certain branch is unreachable, but can’t prove it via the type system. So me writing

```haskell
newtype NonEmptySet a = NonEmptySet (Set a)

toList :: NonEmptySet a -> NonEmpty a
toList (NonEmptySet s) =
  case nonEmpty (Set.toList s) of
    Nothing -> error "unreachable"
    Just l -> l

```

is morally correct, provided I don’t export the constructor for NonEmptySet. It would be quite sad if the only way to call toList is via IO, because it would leak the implementation (that I’m reusing Set instead of creating a NonEmpty version of the Set ADT that makes illegal states unrepresentable)

---

<div class="post-metadata">

**Author:** ![rhendric](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/rhendric/32/2689_2.png) [@rhendric](https://discourse.haskell.org/u/rhendric)\
**Post date:** [December 30, 2023, 12:33am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/24 "2023-12-30T00:33:20Z")

</div>

> [@tomjaguarpaw](#):
>
> Would the situation be better if instead of `unsafePartial` the way of interpreting `Partial =>` was `partialToException :: (Partial => a) -> Effect a`? The equivalent in Haskell would be `partialToException :: (Partial => a) -> IO a`. We still wouldn’t have the property that `evaluate <=< partialToException` removes the partiality, but at least the partiality _is_ stuck in `IO`. On the other hand, this wouldn’t allow us to “mark” safe usages of, e.g., `head` and return to the pure world.

I don’t think that’s the correct model. Partiality isn’t a property of a term; it’s a property of a function. A term either reduces to bottom or does not. A function may return a bottom on some inputs and be defined on others.

If I have a term that produces `IO ([a] -> a)`, I understand that type as telling me that in order to get to the function within, I must suffer any sort of side effect. But from inside the lambda to which that term is `>>=`'d, the term of type `[a] -> a` is pure—regardless of how many times I call it, or on which inputs I call it, it will not create any _more_ side effects. If I want to express that the inner function might cause more side effects, I need to Kleisli it: `IO ([a] -> IO a)`.

With `head :: Partial => [a] -> a` and your proposed `partialToException`, I’d have `partialToException head :: IO ([a] -> a)`. But the term `head` isn’t the thing that can cause problems; it’s the application of `head` to an empty list. So for the reasons I stated above, this doesn’t capture the correct property, that the term of type `[a] -> a` that gets bound in a lambda is still partial and needs to be handled with care.

The correct thing, using existing tools, is a Kleisli: `headIO :: [a] -> IO a`, or much more conventionally, `headMay :: [a] -> Maybe a`. But for someone who is willing to invest language complexity to get better ergonomics than that, I would want partiality to be expressed similarly to how Linear Haskell expresses linearity, as a [modifier](https://github.com/ghc-proposals/ghc-proposals/pull/370) on the function type itself. With a few new language rules such as ‘the inferred type of a lambda that directly encloses an application of a partial function is partial’, totality-polymorphic function composition, and _both_ a Kleisli-producing `applyOrThrowIO :: Exception e => e -> (a %Partial -> b) -> a -> IO b` _and_ an `unsafeTotal :: (a %Partial -> b) -> a -> b` for when you can’t prove totality to the type checker but you know you have it, this would have… well, exactly as many problems as Linear Haskell currently has. But presumably those are being worked on.

(The Linear Haskell connection is supported in my mind by the idea that the affine/linear distinction is ‘dual’—and I use the scare quotes only because I’m not enough of an expert to assert this confidently—to the partial/total distinction. A linear function must use its argument once, while an affine function might not use it at all. Dually, a total function must use its _continuation_ once, while a partial function might not use it at all, considering throwing an error as escaping to some other continuation.)

---

<div class="post-metadata">

**Author:** ![tomjaguarpaw](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/tomjaguarpaw/32/1230_2.png) [@tomjaguarpaw](https://discourse.haskell.org/u/tomjaguarpaw)\
**Post date:** [December 30, 2023, 8:40am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/25 "2023-12-30T08:40:14Z")

</div>

Very interesting! You’ve convinced me that `Partial` is not a good solution to this problem.

---

<div class="post-metadata">

**Author:** ![atravers](https://avatars.discourse-cdn.com/v4/letter/a/45deac/32.png) [@atravers](https://discourse.haskell.org/u/atravers)\
**Post date:** [December 30, 2023, 9:16am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/26 "2023-12-30T09:16:53Z")

</div>

> [@rhendric](#):
>
> The correct thing, using existing tools, is a Kleisli: `headIO :: [a] -> IO a`

- 

```haskell
headIO :: [a] -> IO a
headIO (x:_) = return x
headIO [] = throwIO (errorCallWithoutCallStackException "empty list!" )

```

- 

```haskell
import Control.Exception(evaluate) -- :: a -> IO a

head :: [a] -> a
head (x:_) = x
head [] = throw (errorCallWithoutCallStackException "empty list!")

headIO :: [a] -> IO a
headIO = evaluate . head

```

…what’s the difference in behaviour?

---

<div class="post-metadata">

**Author:** ![rhendric](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/rhendric/32/2689_2.png) [@rhendric](https://discourse.haskell.org/u/rhendric)\
**Post date:** [December 30, 2023, 9:44am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/27 "2023-12-30T09:44:09Z")

</div>

Is there one? I don’t feel fully confident in the distinction between precise and imprecise exceptions, but my understanding of `evaluate` is that it’ll turn an error in the reduction of its argument into an exception in `IO`, and `throwIO` simply starts with an exception in `IO`, so my guess is that they would do the same thing.

---

<div class="post-metadata">

**Author:** ![Bodigrim](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/bodigrim/32/1457_2.png) [@Bodigrim](https://discourse.haskell.org/u/Bodigrim)\
**Post date:** [December 30, 2023, 2:13pm UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/28 "2023-12-30T14:13:37Z")

</div>

> [@rhendric](#):
>
> The problem with encoding partiality as a constraint is that `unsafePartial head` (where `unsafePartial :: (Partial => a) -> a`) resolves the constraint to the compiler’s satisfaction without actually reducing the thing that is partial (the intent is that you’d always call `unsafePartial (head foo)` instead, but mistakes happen and type checkers are for catching them). You’re left with something having the type of a pure function, and you can pass that pure function anywhere else and it may blow up on you there.

That’s very interesting, thanks for the insight.

> [@rhendric](#):
>
> The correct thing, using existing tools, is a Kleisli: `headIO :: [a] -> IO a`, or much more conventionally, `headMay :: [a] -> Maybe a`. But for someone who is willing to invest language complexity to get better ergonomics than that, I would want partiality to be expressed similarly to how Linear Haskell expresses linearity, as a [modifier](https://github.com/ghc-proposals/ghc-proposals/pull/370) on the function type itself. With a few new language rules such as ‘the inferred type of a lambda that directly encloses an application of a partial function is partial’, totality-polymorphic function composition, and _both_ a Kleisli-producing `applyOrThrowIO :: Exception e => e -> (a %Partial -> b) -> a -> IO b` _and_ an `unsafeTotal :: (a %Partial -> b) -> a -> b` for when you can’t prove totality to the type checker but you know you have it, this would have… well, exactly as many problems as Linear Haskell currently has. But presumably those are being worked on.

Well, this is very close to what a Kleisli arrow in `MonadError` monad already does. The only thing it cannot model is totality-polymorphic composition, which is a very challenging notion (at least for linear types).

---

<div class="post-metadata">

**Author:** ![rhendric](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/rhendric/32/2689_2.png) [@rhendric](https://discourse.haskell.org/u/rhendric)\
**Post date:** [December 31, 2023, 10:26pm UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/29 "2023-12-31T22:26:00Z")

</div>

> [@Bodigrim](#):
>
> Well, this is very close to what a Kleisli arrow in `MonadError` monad already does.

Oh, absolutely! The only difference between using Kleisli arrows or function arrows to model this is ergonomic. Ergonomics is what drove the decision to make the `Partial` class, though, so if we’re solving the ergonomic problem with Kleisli composition by adding something for the particular case of Kleisli arrows in the partiality monad, the above proposal is what I’d recommend over a `Partial` class.

Explanation for those unfamiliar with PureScript: the language’s integration with `Partial` is such that an incomplete case expression requires a `Partial` ‘instance’ in scope (there are no such instances in fact, but having the constraint in an outer scope discharges the requirement, and `unsafePartial` ultimately tells the lie that there is one). So instead of

```haskell
foo :: MonadError e m => [a] -> m a
foo xs = case xs of
  h:_ -> pure h
  _ -> throwError ... 

```

one writes

```haskell
foo :: Partial => [a] -> a
foo xs = case xs of
  h:_ -> h

```

For larger functions, this is a big deal; the `Partial` constraint can be requested once and then regular function composition suffices for everything inside.

It’s a neat thought, but again, the difficulty is that the `Partial` constraint isn’t specific enough about which function arrows have the partiality attached to them, and that ultimately leads to the problem I was highlighting. The challenge is to solve the problem with a similar lack of intrusiveness (which is the problem with Kleisli-ing everything). Modified arrows are the only idea I have that seems like it could do that.

---

<div class="post-metadata">

**Author:** ![lukemccartney](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/lukemccartney/32/3958_2.png) [@lukemccartney](https://discourse.haskell.org/u/lukemccartney)\
**Post date:** [December 31, 2023, 11:02pm UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/30 "2023-12-31T23:02:15Z")

</div>

Okay. Bringing it back to simple terms for myself. Why is ‘GHC.Stack.Types.HasCallStack’ mentioned, it doesn’t provide any type information.

How would one write functions that use this syntax? Why would one write a function with that syntax?

It’s not like a function definition;  
‘’’  
mult :: Num a =\> a → a → a  
‘’’  
So I guess the question is, what _is_ it?

---

<div class="post-metadata">

**Author:** ![atravers](https://avatars.discourse-cdn.com/v4/letter/a/45deac/32.png) [@atravers](https://discourse.haskell.org/u/atravers)\
**Post date:** [January 1, 2024, 12:17am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/31 "2024-01-01T00:17:30Z")

</div>

[`GHC.Stack.Types.HasCallStack`](https://hackage.haskell.org/package/docs/src/GHC.Stack.Types.html#HasCallStack) provides an implicit parameter `callStack` used by [`error`](https://hackage.haskell.org/package/base/docs/Prelude.html#v:error):

```haskell
error :: HasCallStack => [Char] -> a
error s = raise# (errorCallWithCallStackException s ?callStack)

```

The definition [`errorEmptyList`](https://hackage.haskell.org/package/base/docs/src/GHC.List.html#errorEmptyList) then uses `error`:

```haskell
errorEmptyList :: HasCallStack => String -> a
errorEmptyList fun =
  error (prel_list_str ++ fun ++ ": empty list")

```

The [`badHead`](https://hackage.haskell.org/package/base/docs/src/GHC.List.html#badHead) definition then uses `errorEmptyList`:

```haskell
badHead :: HasCallStack => a
badHead = errorEmptyList "head"

```

Finally, [`GHC.List.head`](https://hackage.haskell.org/package/base-4.19.0.0/docs/src/GHC.List.html#head), uses `badHead` in the case of `[]`

```haskell
head :: HasCallStack => [a] -> a
head (x:_) = x
head [] = badHead

```

So anything that ultimately relies on `error` will acquire the `HasCallStack` context because `error` uses `callStack`, and:

> [@chreekat](#):
>
> `HasCallstack` was introduced as a mechanism to allow authors to precisely control the generation of callstacks when an exception happens.
> 
> As you can see, it’s a bit finicky and not everyone is happy with the current design. But at least we get callstacks now!

---

<div class="post-metadata">

**Author:** ![rhendric](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/rhendric/32/2689_2.png) [@rhendric](https://discourse.haskell.org/u/rhendric)\
**Post date:** [January 1, 2024, 2:04am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/32 "2024-01-01T02:04:37Z")

</div>

> [@lukemccartney](#):
>
> How would one write functions that use this syntax? Why would one write a function with that syntax?

How: simply add the constraint, and GHC does the rest. You largely don’t need to think about it.

Why: using it means the function in question will appear in stack traces; [see this example](https://play.haskell.org/saved/oYGZtb7b). You may or may not want that.

---

<div class="post-metadata">

**Author:** ![Ambrose](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/ambrose/32/5672_2.png) [@Ambrose](https://discourse.haskell.org/u/Ambrose)\
**Post date:** [January 1, 2024, 2:07am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/33 "2024-01-01T02:07:38Z")

</div>

Plugging require-callstack, which helps with one wart of the vanilla implementation (it’s easy to truncate callstacks due to negligence)

> **[require-callstack](https://hackage.haskell.org/package/require-callstack)**
>
> Propagate HasCallStack with constraints

---

<div class="post-metadata">

**Author:** ![atravers](https://avatars.discourse-cdn.com/v4/letter/a/45deac/32.png) [@atravers](https://discourse.haskell.org/u/atravers)\
**Post date:** [January 1, 2024, 9:02am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/34 "2024-01-01T09:02:41Z")

</div>

[Hrm:](https://hackage.haskell.org/package/require-callstack/docs/RequireCallStack.html)

> [@](#):
>
> [`provideCallStack`](https://hackage.haskell.org/package/require-callstack/docs/RequireCallStack.html#provideCallStack)` :: (RequireCallStackImpl => r) -> r`
> 
> - Satisfy a `RequireCallStack` constraint for the given block. Can be used instead of propagating a `RequireCallStack` up the call graph.

…how is that any safer than `unsafePartial :: (Partial => a) -> a` in PureScript?

---

<div class="post-metadata">

**Author:** ![atravers](https://avatars.discourse-cdn.com/v4/letter/a/45deac/32.png) [@atravers](https://discourse.haskell.org/u/atravers)\
**Post date:** [January 1, 2024, 11:38am UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/36 "2024-01-01T11:38:05Z")

</div>

> [@maxigit](#):
>
> My initial though was instead of a constraint have an implicit parameter […]

You mean like how [`GHC.Stack.Types.HasCallStack`](https://hackage.haskell.org/package/docs/src/GHC.Stack.Types.html#HasCallStack) is defined?

> [@](#):
>
> `type HasCallStack = ?callStack :: CallStack`

* * *

> [@maxigit](#):
>
> […] it probably doesn’t work either.

And a better solution is also being sought for `HasCallStack`:

> [@](#):
>
> NOTE: The implicit parameter `?callStack :: CallStack` is an implementation detail and **should not** be considered part of the `CallStack` API, we may decide to change the implementation in the future.

---

<div class="post-metadata">

**Author:** ![atravers](https://avatars.discourse-cdn.com/v4/letter/a/45deac/32.png) [@atravers](https://discourse.haskell.org/u/atravers)\
**Post date:** [January 1, 2024, 12:21pm UTC](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402/38 "2024-01-01T12:21:05Z")

</div>

> [@maxigit](#):
>
> ```haskell
> twoHeads xs ys = (head xs, head ys)
> 
> ```
> 
> will have automatically type `?partialHead a => [a] -> [a] -> (a,a)`

…which will already annoy people wanting to use it with lists of differently-typed values:

```haskell
twoHeads (... :: [Bool]) (... :: [Char]) -- ?!?

```

Suggested reading:

- [Law of Excluded Middle - ProofWiki](https://proofwiki.org/wiki/Law_of_Excluded_Middle)

- [“Mostly functional” programming does not work](https://queue.acm.org/detail.cfm?id=2611829) (2014)

[Previous page](https://discourse.haskell.org/t/what-is-ghc-stack-types-hascallstack/8402.md?page=1)
