Hello Everyone,
Nim Noob here. I am having a blast learning Nim and my effort to do so has centered around trying to port something similar to Python's Parsy to Nim.
You can find my implementation here: https://github.com/CircArgs/parsnim
Everything is functional, however I'm having some difficulties with a couple of examples I am putting together:
The first attempt inheritance and the second tries an object variant from the Nim tutorials.
For 1, despite Operator and Number both being Nodes, I cannot combine them (I have naively attempted to convert things to methods but this did not work either) The error is
parsnim/examples/expressions_variant.nim(43, 47) Error: type mismatch: got <Parser[expressions_variant.NodeKind, expressions_variant.Operator], Parser[expressions_variant.NodeKind, expressions_variant.Number]>
but expected one of:
proc `or`[T, R](parser, other: Parser[T, R]): Parser[T, R]
first type mismatch at position: 2
required type for other: Parser[or.T, or.R]
but expression 'number_expr' is of type: Parser[expressions_variant.NodeKind, expressions_variant.Number]
For 2, I get
parsnim/examples/expressions.nim(39, 49) Error: cannot prove that it's safe to initialize 'leftOp', 'rightOp' with the runtime value for the discriminator 'kind'
I understand the first error but cannot figure how to get around it while maintaining the inheritance.
The second error does not make sense to me at all.
Would someone be willing to point me in the right direction for these two issues?
Thank You!
In the example with variants, Node(kind: op, leftOp: left.value[0], rightOp: right.value[0])], "") is valid only if op is nkAdd or nkSub. However, Nim doesn't know if that's the case. You can solve it by using a case statement/expression:
case op
of nkAdd, nkSub:
# here you can safely construct the object
else:
# do something else