Skip to content

can't resolve alias when combined with generics. #6900

@krux02

Description

@krux02

I would like to resolve all aliases in getTypeInst, but I can't

import macros

type
  Vec[N: static[int],T] = object
    arr: array[N,T]

  Vec4[T] = Vec[4,T]

  Vec4f = Vec4[float32]

  MyObject = object
    a,b,c: int

  MyObjectAlias = MyObject

  MyObjectSubAlias = MyObjectAlias

proc vec4*[T](x:T): Vec4[T] = Vec4[T](arr: [x,x,x,x])

proc vec4f*(x: float32): Vec4f = Vec4f(arr: [x,x,x,x])

proc resolveAliasTypes(arg: NimNode): NimNode =
  result = arg
  if result.kind == nnkSym:
    if result.typeKind == ntyGenericInst:
      result = arg.getTypeImpl

  while result.typeKind == ntyAlias:
    # this is easy
    result = result.getTypeImpl

  while result.typeKind == ntyGenericInst and result[0].kind == nnkSym:
    # this is not only ugly but also wrong
    let tmp = result[0].getTypeImpl
    if tmp.kind != nnkBracketExpr:
      break
    else:
      result = tmp


macro foobar(arg: typed; note: static[string]): untyped =
  let tmp = arg.getTypeInst.resolveAliasTypes
  echo "--- ", note, " ---"
  echo tmp.typeKind
  echo tmp.lispRepr


var a: Vec4f
var b: Vec4[float32]
var c: Vec[4,float32]
var d: float32
var e: MyObject
var f: MyObjectAlias
var g: MyObjectSubAlias

foobar(a,"It it still has the T Sym, but I need also that to be resolved as Sym(float32)")
foobar(b,"and this is ntyGenericInvocation not ntyGenericInst")
foobar(c,"OK")
foobar(d,"OK")
foobar(e,"OK")
foobar(f,"OK")
foobar(g,"OK")

output:

--- It it still has the T Sym, but I need also that to be resolved as Sym(float32) ---
ntyGenericInvocation
BracketExpr(Sym(Vec), IntLit(4), Sym(T))
--- and this is ntyGenericInvocation not ntyGenericInst ---
ntyGenericInvocation
BracketExpr(Sym(Vec), IntLit(4), Sym(T))
--- OK ---
ntyGenericInst
BracketExpr(Sym(Vec), IntLit(4), Sym(float32))
--- OK ---
ntyFloat32
Sym(float32)
--- OK ---
ntyObject
Sym(MyObject)
--- OK ---
ntyObject
Sym(MyObject)
--- OK ---
ntyObject
Sym(MyObject)

I would like to have this output:

--- OK ---
ntyGenericInst
BracketExpr(Sym(Vec), IntLit(4), Sym(float32))
--- OK ---
ntyGenericInst
BracketExpr(Sym(Vec), IntLit(4), Sym(float32))
--- OK ---
ntyGenericInst
BracketExpr(Sym(Vec), IntLit(4), Sym(float32))
--- OK ---
ntyFloat32
Sym(float32)
--- OK ---
ntyObject
Sym(MyObject)
--- OK ---
ntyObject
Sym(MyObject)
--- OK ---
ntyObject
Sym(MyObject)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions