I want macro used as pragma who makes proc hash(x: UserDefinedObject): Hash.
example:
(hashable is the name of the macro)
```example1.nim
import hashes
type
MyObject {.hashable.} = object
foo: int
bar: string
is converted to
```converted1.nim
import hashes
type
MyObject = object
foo: int
bar: string
proc hash(x: MyObject): Hash =
## Computes a Hash from `x`.
var h: Hash = 0
h = h !& hash(x.foo)
h = h !& hash(x.bar)
result = !$h
another example:
```example2.nim
import hashes
type
MyKind = enum
A, B
MyObject {.hashable.} = object
case kind: MyKind
of A:
foo: int
of B:
bar: string
is converted to
```converted2.nim
import hashes
type
MyKind = enum
A, B
MyObject = object
case kind: MyKind
of A:
foo: int
of B:
bar: string
proc hash(x: MyObject): Hash =
## Computes a Hash from `x`.
var h: Hash = 0
h = h !& hash(x.kind)
case x.kind
of A:
h = h !& hash(x.foo)
of B:
h = h !& hash(x.bar)
result = !$h
And...?
I hope a new feature like the examples' hashable macro will be implemented.
Sorry for my poor English ;(
Somewhat duplicate of #6696
Why is it won't fix @data-man ? I could see that in sugar.nim
@mratsim
Sorry for my poor English!
I don't think this is possible. Your hashable macro generates code that is outside the scope of the type block. You can already do something like this, which I think makes more sense:
import hashes
hashable:
type
MyObject = object
foo: int
bar: string
@dom96 and on the next day you will need to generate hashable+comparable :)
Until the language itself solved the problem, it may be better to provide meta-macro:
derive hashable, comparable, serializable("BE"):
type
MyObject = object
foo: int
bar: string
where each submacro only generates extra procedures and derive collects their results + type itself.
@Bulat-Ziganshin sugar.derive seems entirely possible with today's Nim. No new feature required.
Useful feature, but not scheduled for 2020 and the existing workarounds are perfectly acceptable.
Most helpful comment
I don't think this is possible. Your
hashablemacro generates code that is outside the scope of thetypeblock. You can already do something like this, which I think makes more sense: