I am trying to follow this LLVM guide in Nim.
The first obstacle I have found to how to encode algebraic data types to represent the various types of tokens. If I understand correctly, algebraic data types are represented in Nim via an enum plus a variant object, for instance
type
Token = enum
IdentifierToken, NumberToken, CharacterToken
TokenObject = object
case kind: Token
of IdentifierToken:
name: string
of NumberToken:
value: float
of CharacterToken:
ch: char
The problem I have with this approach is how to encode the case where the token does not have any fields, such as EOFToken.
A workaround would be to encode these other tokens as a separate enum and then use a union type, like
type
Token2 = enum
EOFToken, DefToken, ExternToken
ActualToken = Token2 or TokenObject
but it seems rather inconvenient.
Is there a more natural way to handle this case?
Use nil for an empty branch, e.g.:
type
Token = enum
IdentifierToken, NumberToken, CharacterToken, EOFToken
TokenObject = object
case kind: Token
of IdentifierToken:
name: string
of NumberToken:
value: float
of CharacterToken:
ch: char
of EOFToken:
nil