Support seq indexing

This commit is contained in:
Tomasz Bekas 2023-08-03 11:42:39 +02:00 committed by markspanbroek
parent 08581f5efd
commit 416b6dd566
2 changed files with 15 additions and 0 deletions

View File

@ -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

View File

@ -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