Nim icon indicating copy to clipboard operation
Nim copied to clipboard

mixin + block expression: works in Generics, not in "normal" proc

Open mratsim opened this issue 7 years ago • 4 comments
trafficstars

While trying to find an alternative to be able to slice with _ like a[1, _, 0] without having to define my own _ I stumbled upon the following:

History:

  • In procs with generic return type, identifier validity is checked before macro replacement #6387
  • There is a request to disallow the _ identifier except for tuple destructuring #7171

So I tried to inject mixin _ in a block expression before the identifier resolution happen. Unfortunately this works in generic procs but not in normal proc.

Test case:

import macros

type CustomSeq*[T] = object
  data*: seq[T]

macro `[]`*[T](s: CustomSeq[T], args: varargs[untyped]): untyped =
  ## The end goal is to replace the joker "_" by something else
  result = newIntLitNode(10)


proc foo1(): CustomSeq[int] =
  result.data.newSeq(10)
  # Doesn't work
  echo ((block:
            # mixin _ # invalid expression
            result[_]
    ))

echo foo1()

proc foo2[T](): CustomSeq[T] =
  result.data.newSeq(10)
  # works fine with generic return type
  echo ((block:
            mixin _ # Works
            result[_]
    ))

echo foo2[int]()

cc @krux02, @GULPF

mratsim avatar Mar 21 '18 08:03 mratsim

Tested in playground, no longer seems to be an issue.

saem avatar Mar 24 '21 06:03 saem

It still doesn't work when uncomment mixin _ on Nim 1.4.4, gives Error: invalid expression: mixin _

import std/macros

type CustomSeq*[T] = object
  data*: seq[T]

macro `[]`*[T](s: CustomSeq[T], args: varargs[untyped]): untyped =
  ## The end goal is to replace the joker "_" by something else
  result = newIntLitNode(10)


proc foo1(): CustomSeq[int] =
  result.data.newSeq(10)
  # Doesn't work
  echo ((block:
            mixin _ # invalid expression
            result[_]
    ))

echo foo1()

ringabout avatar Mar 24 '21 07:03 ringabout

You're not supposed to be able to use mixin in non-generic procs, no?

metagn avatar Aug 23 '23 01:08 metagn

It still doesn't work when uncomment mixin _ on Nim 1.4.4, gives Error: invalid expression: mixin _

import std/macros

type CustomSeq*[T] = object
  data*: seq[T]

macro `[]`*[T](s: CustomSeq[T], args: varargs[untyped]): untyped =
  ## The end goal is to replace the joker "_" by something else
  result = newIntLitNode(10)


proc foo1(): CustomSeq[int] =
  result.data.newSeq(10)
  # Doesn't work
  echo ((block:
            mixin _ # invalid expression
            result[_]
    ))

echo foo1()

this appears to be fixed in devel but it needs a test case

Graveflo avatar Jul 25 '24 03:07 Graveflo