Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[Macro] cannot pass a distinct type to newLit #13266

Open
nitely opened this issue Jan 27, 2020 · 3 comments
Open

[Macro] cannot pass a distinct type to newLit #13266

nitely opened this issue Jan 27, 2020 · 3 comments
Labels

Comments

@nitely
Copy link
Contributor

nitely commented Jan 27, 2020

Cannot pass a distinct type to newLit. Using the values directly seems to work in my case, but the docs/tutorial say to convert them to NimNode using newLit.

Example

import macros

type
  Rune = distinct int32
  Foo = object
    a: Rune

macro foo*(): untyped =
  result = newStmtList()
  let runeLit = newLit Rune(0)
  let fooLit = newLit Foo(a: Rune(0))
  result.add(quote do:
    echo `runeLit`)
  result.add(quote do:
    echo `fooLit`.a)

proc main() =
  foo()
main()

Current Output

Error: type mismatch: got <Rune>

Expected Output

0
0
$ nim -v
Nim Compiler Version 1.1.1 [Linux: amd64]
Compiled at 2020-01-24
Copyright (c) 2006-2019 by Andreas Rumpf

active boot switches: -d:release
@cooldome
Copy link
Member

cooldome commented Jan 27, 2020

Here is how you do it. You need latest devel nim, because of distinctBase

import macros

type
  Rune = distinct int32
  Foo = object
    a: Rune


proc `$`(r: Rune): string {.borrow.}

import typetraits
proc newLit*(d: distinct): NimNode =
  nnkCall.newTree(typeof(d).getTypeInst, 
            newLit(distinctBase(typeof(d))(d)))

macro foo*(): untyped =
  result = newStmtList()
  let runeLit = newLit Rune(0)
  let fooLit = newLit Foo(a: Rune(0))
  result.add(quote do:
    echo `runeLit`)
  result.add(quote do:
    echo `fooLit`.a)

proc main() =
  foo()
main()

@andreaferretti
Copy link
Collaborator

Wouldn't it be better to have this overload of newLit directly in macros?

@krux02
Copy link
Contributor

krux02 commented Feb 5, 2020

@andreaferretti I did exactly that in my PR (linked above).

@ghost ghost added the Macros label Jul 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants