Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Rewriting an if expression into a statement while copying the IfStmt/IfExpr node will cause unused type error #18351

Open
alaviss opened this issue Jun 25, 2021 · 2 comments
Labels
CPS bugs/pulls related to the cps project Macros

Comments

@alaviss
Copy link
Collaborator

alaviss commented Jun 25, 2021

Example

import macros

func flatty(dst, src: NimNode): NimNode =
  case src.kind
  of AtomicNodes:
    result = newAssignment(copy(dst), copy(src))
  of nnkStmtList, nnkStmtListExpr:
    result = copyNimNode(src)
    
    for idx in 0 ..< src.len - 1:
      result.add copy(src[idx])
    
    result.add flatty(dst, src.last)
  of nnkElifExpr, nnkElifBranch:
    result = copyNimNode(src).add(copy src[0]):
      flatty(dst, src[1])
  of nnkElse, nnkElseExpr:
    result = copyNimNode(src).add(flatty(dst, src[0]))
  of nnkIfExpr, nnkIfStmt:
    result = copyNimNode(src)
    # if you instead build a new node, the issue doesn't happen
    # result = newNimNode(src.kind, src)
    
    for child in src.items:
      result.add flatty(dst, child)
  else:
    error "unsupported node " & repr(src), src

macro rewriter(dst, src: typed): untyped =
  result = flatty(dst, src)
  echo repr result
 
var x: int
rewriter(x):
  if true: 1 else: 0

Current Output

if true: x = 1
else:
  x = 0
test.nim(35, 20) Error: expression 'x = 0' is of type 'int literal(1)' and has to be used (or discarded); start of expression here: test.nim(33, 1)

Additional Information

$ nim -v
Nim Compiler Version 1.5.1 [Linux: amd64]
Compiled at 2021-06-24
Copyright (c) 2006-2021 by Andreas Rumpf

git hash: 0f91b67f5c15328330f74a8769aed9961940aab2
active boot switches: -d:release -d:nimUseLinenoise
@alaviss alaviss added Macros CPS bugs/pulls related to the cps project labels Jun 25, 2021
@Araq
Copy link
Member

Araq commented Jun 25, 2021

There is macros.newTree these days, copyNimNode(src).add(flatty(dst, src[0])) is not recommended. (Not that it has anything to do with this bug.)

@alaviss
Copy link
Collaborator Author

alaviss commented Jun 25, 2021

Copying retain all line information, so it's a bit more convenient that way.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
CPS bugs/pulls related to the cps project Macros
Projects
None yet
Development

No branches or pull requests

2 participants