Indexing of strings and sequences should not catch Defect

Catching a Defect does not always work, depending on how
it's compiled.
This commit is contained in:
Mark Spanbroek 2023-08-03 14:51:31 +02:00 committed by markspanbroek
parent 416b6dd566
commit e56cf86c4a

View File

@ -1,7 +1,16 @@
import std/macros
when (NimMajor, NimMinor) < (1, 4):
type IndexDefect = IndexError
macro `.?`*(expression: seq | string, brackets: untyped{nkBracket}): untyped =
# chain is of shape: (seq or string).?[index]
let index = brackets[0]
quote do:
block:
type T = typeof(`expression`[`index`])
let evaluated = `expression`
if `index` < evaluated.len:
evaluated[`index`].some
else:
T.none
macro `.?`*(expression: typed, brackets: untyped{nkBracket}): untyped =
# chain is of shape: expression.?[index]
@ -13,5 +22,3 @@ macro `.?`*(expression: typed, brackets: untyped{nkBracket}): untyped =
`expression`[`index`].some
except KeyError:
T.none
except IndexDefect:
T.none