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

Macro with typed param can't be used as a pragma attached to a type #15334

Open liquidev opened 4 years ago

liquidev commented 4 years ago

Example

macro entity(entityType: typed) =
  discard

type
  RootEntity = ref object of RootObj
  Player {.entity.} = ref object of RootEntity
    x, y: int

Current Output

/tmp/issue.nim(6, 21) Error: invalid expression: Player {..} = ref object of RootEntity
  x, y: int

Expected Output

Successful compilation. Expected behavior would be similar to procs. You cannot re-emit a procedure's AST after it's been sem-checked, but you are still able to read it with all the idents resolved (which is what I'm trying to do):

import std/macros

# this compiles
macro readAst(p: typed) =
  echo p.treeRepr

proc testRead {.readAst.} =
  echo 1

# this doesn't
macro modifyAst(p: typed): untyped =
  echo p.treeRepr
  result = p

proc testModify {.modifyAst.} =
  echo 1
# /usercode/in.nim(13, 1) Error: redefinition of 'testModify'; previous declaration here: /usercode/in.nim(13, 6)

Additional Information

$ nim -v
Nim Compiler Version 1.3.5 [Linux: amd64]
Compiled at 2020-09-15
Copyright (c) 2006-2020 by Andreas Rumpf

git hash: c38487aa225674f67659c28ce171fd93e2231ad1
active boot switches: -d:release
timotheecour commented 4 years ago

this would be fixed by https://github.com/nim-lang/Nim/issues/13830 as many other things:

note: @liquid600pgm please always reduce your example; here's a reduced one:

when true:
  # macro entity(entityType: untyped) = discard
  macro entity(entityType: typed) = discard
  type Player {.entity.} = object
    x: int

gives:

Error: invalid expression: Player {..} = object

with macro entity(entityType: untyped) = discard it also doesn't work with a different error:

Error: illformed AST:
metagn commented 1 year ago

Related: #18864, workaround outlined in https://github.com/nim-lang/Nim/issues/18864#issuecomment-1695215373