r/nim • • Sep 04 '21

How to import module without creating constant with same name

When you import something in nim, a constant created with same name, that's the reason why Nim modules have such strange names like std/times or std/tables instead of nice and plain std/table.

This makes hardest problem of programming - giving a good names to things (including modules) much more harder, as you can't give modules plain names, because if you do module name would conflict with variable names.

But thankfully, there's a way to solve this problem.

  1. Create some-shared-folder-or-package/requires.nim with the following content
import std/[strutils, macros]

macro require*(modules: varargs[untyped]) =
  var moduless: seq[string]

  # Normalizing module names, converging `namespace/[a, b]` into `namespace/a, namespace/b`
  for m in modules:
    let ms = m.repr().replace(" ")
    if "[" in ms:
      let parts = ms.split("/")
      if parts.len > 2: raise Exception.new_exception("invalid module name " & ms)
      let nspace = parts[0]
      let names = parts[1].replace("[").replace("]").split(",")
      for name in names:
        moduless.add nspace & "/" & name
    else:
      moduless.add ms

  # Importing modules with added postfix _m
  result = nnk_stmt_list.new_tree()
  for m in moduless:
    let mname = new_ident_node(($m).split("/")[^1] & "_m")
    result.add quote do:
      import `m` as `mname`
  1. Add nim.cfg to your project with this line

import:some-shared-folder-or-package/requires.nim

  1. All done, now you can give clean and nice names to your modules, and don't worry about module name and variable name conflicts, just use require instead of import.
0 Upvotes

2 comments sorted by

4

u/SultanOfSodomy Sep 04 '21

I stumbled on this naming problem more than once but I wont recommend this solution. The import section should be clear of unnecessary metaprogramming hacks imho.

0

u/h234sd Sep 04 '21

I would agreed in ordinary situation. But clear module names are far more important than clean imports.