nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.22k stars 1.46k forks source link

Warn on repeated non-trivial evaluations in templates #23754

Open arnetheduck opened 4 days ago

arnetheduck commented 4 days ago

Summary

When passing parameters to templates, subsitution may cause the parameter to be evaluated multiple times - warn when this happens

Description

proc f(): int =
  echo "hello"
  42

template test(a: int): int =
  a + a

echo test(f())

In the above template, a is evaluated twice which may be expensive - in the example, "hello" is printed twice which in most cases is both undesirable and inefficient.

In most cases, it's problem with the template declaration: it should probably have captured a in a local variable.

However, this is only a problem when a evaluates to something non-trivial - ie test(425) is not a problem and should not cause an evaluation warning.

Similarly, sometimes the multi-eval is desired, thus there should be a way to disable the warning locally - test(a{.dirty.}: int) would be one option (or some other keyword) - another option would be a call-site annotation.

Alternatives

No response

Examples

No response

Backwards Compatibility

No response

Links

No response