Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC] Compile-Time Function Evaluation: static result and {.compileTime.} pragma #8051

Closed
mratsim opened this issue Jun 16, 2018 · 2 comments
Labels

Comments

@mratsim
Copy link
Collaborator

mratsim commented Jun 16, 2018

The {.compileTime.} pragma throws Error: request to generate code for .compileTime proc: foo even in situations where Nim is able to generate a compile time result.

As a workaround we can use a static result.

Test case:

proc foo(x: SomeInteger): int {.compileTime.} =
  result = x.sizeof

proc bar(x: SomeInteger): static[int] =
  result = x.sizeof

var a: int
# echo foo(a) # {.compileTime.} fails
echo bar(a)    # static[result] works

As far as I know, the {.compileTime.} pragma was supposed to be used with NimNode procs.
However in the latest releases, it is automatically done and it does not force compile-time function evaluation either.

So I propose that:

  • either we delete the pragma and document that compile-time function evaluation should use a static result.
  • or we keep it as an alias to static[ResultType] to fix the behaviour highlighted in the test case.
@zah
Copy link
Member

zah commented Jun 16, 2018

The plan is that the compiler will implicitly figure out what can be evaluated at compile time. This will happen when a function doesn't have side effects and all of its parameters are known at compile-time.

I'm surprised that setting a static return type currently has the desired effect. I've never tried to implemented that. The supported way to force static evaluation is by wrapping your proc with a template like this:

func fooImpl(...): SomeType = ...
template foo(...): auto = static(foo(...))

Otherwise, yes, the .compileTime. pragma is rarely needed nowadays.

@krux02
Copy link
Contributor

krux02 commented Nov 12, 2018

of course you can't use a compile time proc in this case, because you can't pass a runtime value a to to a compile time function. The function bar works is in my opition just a bug, if you ever actually want that it is evaluates at compile time the whole thing will blow up in your face. The compiler should refuse to compile it as well. Either use a template as @zah suggested, or pass the typedesc like in this example:

var a: int

proc foo[T](t: typedesc[T]): int {.compileTime.} =
  result = t.sizeof

const x = foo(a.type)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants