# Compile-Time Constant Expressions for Swift

**URL:** <https://forums.swift.org/t/compile-time-constant-expressions-for-swift/12879>\
**Category:** Pitches\
**Created:** [May 21, 2018, 8:14pm UTC](https://forums.swift.org/t/compile-time-constant-expressions-for-swift/12879 "2018-05-21T20:14:26Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![marcrasi](https://avatars.discourse-cdn.com/v4/letter/m/ec9cab/32.png) [@marcrasi](https://forums.swift.org/u/marcrasi)\
**Post date:** [May 21, 2018, 11:42pm UTC](https://forums.swift.org/t/compile-time-constant-expressions-for-swift/12879/4 "2018-05-21T23:42:42Z")

</div>

Thanks for the feedback!

> [@felix91gr](#):
>
> When you say:
> 
> > We will add a recursion depth limit (e.g. 16). This prevents infinite compile time for cases of infinite recursion.
> 
> Isn't that too coarse? I mean, it's better than not having recursion, of course! But I'd like to know why it can't be one of these:
> 
> 1. Checking for infinite recursion (is it undecidable for these semantics? If so, well, 🤷🏼‍♂️ gg).
> 2. Accepting a hard-coded UInt as a parameter of recursion.
> 3. Accepting a pure function that, based on some parameter `n` in the `@compilerEvaluated` function, gives you an upper bound (UInt) on the recursion depth. _If possible, the value of this bound should he polynomial. Exponential bounds would raise an error. Since it would be a pure function, you can decide whether it is exponential or not, right?_
> 
> (3) would be the best explicitly parametrized compromise, I think.

I didn't think about this tradeoff between simplicity and power for max recursion depth. So there's no reason to think that the proposal currently chooses the best compromise! And indeed, a completely hardcoded limit is probably bad because users who really need more depth will be stuck.

Not sure if you meant #2 to be a global limit, or per-function, but a configurable global limit sounds like a pretty good point in the tradeoff space to me. Looking to other languages for precedent, I find that a few C++ compilers (clang and gcc) have a default limit of 512 for constexpr max recusion depth, and a compiler flag that allows you to change the limit if you really need to.

Something dynamic like #3 sounds a bit too powerful to me. It would add a totally new concept to the language (polynomial bounds), and I expect that most practical compile-time evaluated functions will be small and simple enough to not need it. Users can easily deal with the few large and variable-depth functions by occasionally bumping up a global limit.

(And I strongly suspect that the proposed programming model is turing complete, so #1 is indeed undecidable.)

---

_[View the full topic](https://forums.swift.org/t/compile-time-constant-expressions-for-swift/12879)._
