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.55k stars 1.47k forks source link

`nim dump` and other information obtaining commands execute top-level `exec` statements in nims files #8219

Closed zah closed 2 years ago

zah commented 6 years ago

Any top level exec statement appearing in a nims file will be executed when the file is subjected to nim dump, nim check and probably nimsuggest.

The issue was originally raised by a nim.vim user here: https://github.com/zah/nim.vim/issues/87

A similar problem was reported previously here: https://github.com/nim-lang/Nim/issues/3858

Araq commented 6 years ago

Well anything that needs to process the configuration needs to ... process the configuration. What do you suggest?

andreaferretti commented 6 years ago

My suggestion is to point out this issue very clearly in the documentation and strongly encourage the use of nimscript tasks over top level statements

Araq commented 6 years ago

I don't understand what these top level statements were supposed to accomplish. If you tell nim to exec something on every recompile, why should "nim check" and nimsuggest not do the same? The semantics are "I need to do this on every recompile" and nim check and nimsuggest need to know the same as "nim c" does.

Note that nim check foo.nims should not run the Nimscript file, but that's a different issue.

zah commented 6 years ago

I should clarify that this issue is not about side-effects appearing in configuration files. It's about using nims files for simple scripting or project automation tasks.

The issue can be solved if we treat the top-level code as a body of a function that only gets compiled (without being implicitly executed). This would entail that only side-effects from macros would be present when calling nim check or nimsuggest. Another simple work-around would be to introduce a special define (i.e. with defineSymbol) that is present only when a nimscript file is being evaluated. Then if would be possible to guard the execution like this:

proc run = 
   ...

when defined(EvaluatingNimScript):
  run()
zah commented 6 years ago

Another hacky work-around usable right now is the following:

import
  strutils

proc run =
  ...

if paramCount() == 1 and currentSourcePath.endsWith(paramStr(1)):
  run()
Araq commented 6 years ago

when defined(nimscript) is a thing.

zah commented 6 years ago

@Araq, the problem is that nimscript is always defined in nims files (even under nim check and nimsuggest), so it cannot be used right now to discriminate between the different cases.

mratsim commented 4 years ago

Seems like another instance of https://github.com/nim-lang/Nim/issues/12125 (but at "runtime")