From 416b6dd5669eb26ed375943bfd8b203d5ef02d78 Mon Sep 17 00:00:00 2001 From: Tomasz Bekas Date: Thu, 3 Aug 2023 11:42:39 +0200 Subject: [PATCH] Support seq indexing --- questionable/indexing.nim | 5 +++++ testmodules/options/test.nim | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/questionable/indexing.nim b/questionable/indexing.nim index e265967..11892aa 100644 --- a/questionable/indexing.nim +++ b/questionable/indexing.nim @@ -1,5 +1,8 @@ import std/macros +when (NimMajor, NimMinor) < (1, 4): + type IndexDefect = IndexError + macro `.?`*(expression: typed, brackets: untyped{nkBracket}): untyped = # chain is of shape: expression.?[index] let index = brackets[0] @@ -10,3 +13,5 @@ macro `.?`*(expression: typed, brackets: untyped{nkBracket}): untyped = `expression`[`index`].some except KeyError: T.none + except IndexDefect: + T.none diff --git a/testmodules/options/test.nim b/testmodules/options/test.nim index e79140c..e461543 100644 --- a/testmodules/options/test.nim +++ b/testmodules/options/test.nim @@ -267,6 +267,16 @@ suite "optionals": check table.?["a"] == 1.some check table.?["c"] == int.none + test ".?[] can be used for indexing strings without raising IndexDefect": + let str = "a" + check str.?[0] == 'a'.some + check str.?[1] == char.none + + test ".?[] can be used for indexing sequences without raising IndexDefect": + let sequence = @[1] + check sequence.?[0] == 1.some + check sequence.?[1] == int.none + test ".?[] can be followed by calls, operators and indexing": let table = @{"a": @[41, 42]}.toTable check table.?["a"].isSome