Skip to content

Instantly share code, notes, and snippets.

@stefantalpalaru
Created February 26, 2020 20:48
Show Gist options
  • Save stefantalpalaru/82dc71bb547d6f9178b916e3ed5b527d to your computer and use it in GitHub Desktop.
Save stefantalpalaru/82dc71bb547d6f9178b916e3ed5b527d to your computer and use it in GitHub Desktop.
# The object's "Sup" struct member is a struct of its immediate parent and this
# scheme repeats until that parent is RootObj.
#
# Whenever there's a cast (even an implicit one), the Nim compiler generates C
# code that traverses this chain (...Sup.Sup.Sup...).
#
# We use that behaviour in here, by forcing an implicit cast to `RootObj` or
# `ref RootObj`, because we cannot easily traverse that chain of different
# struct types in C, which lacks RTTI.
proc baseType(obj: RootObj): cstring =
when not defined(nimTypeNames):
{.error: "you need to compile this with '-d:nimTypeNames'".}
{.emit: "result = `obj`->m_type->name;".}
proc baseType(obj: ref RootObj): cstring =
obj[].baseType
type
Foo = ref object of RootObj
Bar = ref object of Foo
Baz = object of RootObj
Bob = object of Baz
Bill = ref object of Bob
var
foo = Foo()
bar = Bar()
baz = Baz()
bob = Bob()
bill = Bill()
echo foo.baseType # Foo:ObjectType
echo bar.baseType # Bar:ObjectType
echo baz.baseType # Baz
echo bob.baseType # Bob
echo bill.baseType # Bill:ObjectType
proc f(o: Foo) =
echo o.type # Foo
echo o.baseType # Bar:ObjectType
f(bar)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment