nim-lang / RFCs

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

Minor mitigating changes to typedef macro pragmas for now #427

Closed metagn closed 2 years ago

metagn commented 2 years ago

This currently fails with "illformed AST":

import macros

macro test(s): untyped =
  newTree(nnkTypeSection, s)

type Foo {.test.} = object

You are supposed to return another nnkTypeDef. Before this is changed in favor of some new system, if ever, a small change in the meantime for convenience could be to accept a typesection from the macro and inject all the typedefs inside it into the original typesection where the typedef was (or behave as such).

import macros

macro test(s): untyped =
  let name = $s[0].basename
  result = newTree(nnkTypeSection,
    newTree(nnkTypeDef, ident(name & "1"), s[1], s[2]),
    newTree(nnkTypeDef, ident(name & "2"), s[1], s[2]))

type
  Foo = object
  Bar {.test.} = object
    x, y, z: int
  Baz = object

# becomes

type
  Foo = object
  Bar1 = object
    x, y, z: int
  Bar2 = object
    x, y, z: int
  Baz = object

Also maybe accept any expression from the macro if the typedef is the only one in its typesection (so cyclic references can be respected) and replace the entire typesection with that expression, but this might not be as easy.

import macros

macro test(s): untyped =
  let name = $s[0].basename
  result = newCall("echo", newLit("type name is " & name))

type Bar {.test.} = object
  x, y, z: int

# becomes

echo("type name is Bar")

# invalid:
type
  Foo = object
  Bar {.test.} = object
    x, y, z: int
type
  Bar {.test.} = object
    x, y, z: int
  Foo = object

Bonus: Maybe accept statement lists where the first statement is a typesection, inject that typesection, then add the remaining statements after the FULL original typesection. Not sure if this makes sense.

This should be completely non breaking, I don't think anyone relies on "illformed AST" errors.

Extras (not part of proposal):

juancarlospaco commented 2 years ago

That kind of error messages need to be improved into something more useful and descriptive.