nim-lang / RFCs

A repository for your Nim proposals.
136 stars 26 forks source link

macros.addPragmas: library alternative to {.pragma: foo, bar1, bar2.} #255

Closed timotheecour closed 8 months ago

timotheecour commented 3 years ago

{.pragma: foo, bar1, bar2.} can't be exported and has other drawbacks.

Here's a library solution that can be used instead:

# in macros.nim
const pragmasPos = 4 # ideally should be exported in std/macros, just like it's in compiler/ast
macro addPragmas*(extra, body): untyped =
  result = body
  result[pragmasPos] = newTree(nnkPragma)
  for ai in extra: result[pragmasPos].add ai

example 1

shows an example where we define something analogous to {.pragma: foo, importc: name, nodecl.} except that foo can be exported

# mylib.nim
import std/macros
const name = "fn"
# complex example with when and capturing `name` in scope
template foo*(body) = 
  when defined(foo):
    addPragmas([importc: name], body)
  else:
    addPragmas([nodecl, importc: name], body)

# main.nim
import mylib
proc fn(a: int) {.exportc.} = discard
proc fn3(a: int) {.foo.}

# or using addPragmas directly:
import macros
proc fn3(a: int) {.addPragmas([nodecl, importc: "fn"]).}
fn3(13)

example 2

turn inclrtl from an include to an import using this approach

proposal

add it to std/macros

note

could also extend it to cover other kinds, such as var and types using the recent-ish pragma macro syntax

timotheecour commented 3 years ago

note: this is an alternative to https://github.com/nim-lang/Nim/pull/13016 ; not yet clear on which is best; if https://github.com/nim-lang/Nim/pull/13016 can be completed than maybe #13016 is better (better syntax)

github-actions[bot] commented 9 months ago

This RFC is stale because it has been open for 1095 days with no activity. Contribute a fix or comment on the issue, or it will be closed in 30 days.