From e56cf86c4a089c78a1b7c3005f13343bfbbe3b48 Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Thu, 3 Aug 2023 14:51:31 +0200 Subject: [PATCH] Indexing of strings and sequences should not catch Defect Catching a Defect does not always work, depending on how it's compiled. --- questionable/indexing.nim | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/questionable/indexing.nim b/questionable/indexing.nim index 11892aa..b794b7a 100644 --- a/questionable/indexing.nim +++ b/questionable/indexing.nim @@ -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