Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calling std/parseEnum with a range type doesn't work #24562

Open
dawdmaow opened this issue Dec 23, 2024 · 3 comments
Open

Calling std/parseEnum with a range type doesn't work #24562

dawdmaow opened this issue Dec 23, 2024 · 3 comments

Comments

@dawdmaow
Copy link

Description

Error: Expected a node of kind nnkEnumTy, got nnkInfix

main.nim

import std/[strutils]

type
  Enum = enum a, b, c
  EnumRange = b..c

discard parseEnum[EnumRange]("")

Nim Version

2.2.0

Current Output

PS /Users/dawid/Desktop/unfun/netchess/tmp> nim c main
Hint: used config file '/Users/dawid/.choosenim/toolchains/nim-2.2.0/config/nim.cfg' [Conf]
Hint: used config file '/Users/dawid/.choosenim/toolchains/nim-2.2.0/config/config.nims' [Conf]
.......................................................................................
stack trace: (most recent call last)
/Users/dawid/.choosenim/toolchains/nim-2.2.0/lib/std/enumutils.nim(27, 3) genEnumCaseStmt
/Users/dawid/.choosenim/toolchains/nim-2.2.0/lib/core/macros.nim(691, 24) expectKind
/Users/dawid/Desktop/unfun/netchess/tmp/main.nim(7, 29) template/generic instantiation of `parseEnum` from here
/Users/dawid/.choosenim/toolchains/nim-2.2.0/lib/pure/strutils.nim(1323, 18) template/generic instantiation of `genEnumCaseStmt` from here
/Users/dawid/Desktop/unfun/netchess/tmp/main.nim(5, 16) Error: Expected a node of kind nnkEnumTy, got nnkInfix


### Expected Output

_No response_

### Known Workarounds

_No response_

### Additional Information

_No response_
@metagn
Copy link
Collaborator

metagn commented Dec 24, 2024

Implementing it so it only parses the fields in the range would be a new feature, however we could skip the range type or at least give a proper error and restrict to enum and not range.

@beef331
Copy link
Collaborator

beef331 commented Dec 24, 2024

For a general solution

import std/[strutils, typetraits]

proc parseEnum[T: range and enum](val: string): T =
  let val = parseEnum[T.rangeBase](val)
  if val notin T.low..T.high:
    raise (ref ValueError)(msg: "Expected a value inside " & $T & " but got " & $val)
  T(val)


type
  Enum = enum a, b, c
  EnumRange = b..c

echo parseEnum[EnumRange]("b")
try:
  discard parseEnum[EnumRange]("a")
except:
  discard parseEnum[EnumRange]("")

No clue if a PR would be accepted for this.

@Araq
Copy link
Member

Araq commented Dec 24, 2024

No clue if a PR would be accepted for this.

Sure, why not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants