Support seq indexing

This commit is contained in:
Tomasz Bekas 2023-08-03 11:42:39 +02:00
parent 08581f5efd
commit 8402ac1db4
No known key found for this signature in database
GPG Key ID: 4854E04C98824959
2 changed files with 15 additions and 0 deletions

View File

@ -1,5 +1,8 @@
import std/macros import std/macros
when (NimMajor, NimMinor) < (1, 4):
type IndexDefect = IndexError
macro `.?`*(expression: typed, brackets: untyped{nkBracket}): untyped = macro `.?`*(expression: typed, brackets: untyped{nkBracket}): untyped =
# chain is of shape: expression.?[index] # chain is of shape: expression.?[index]
let index = brackets[0] let index = brackets[0]
@ -10,3 +13,5 @@ macro `.?`*(expression: typed, brackets: untyped{nkBracket}): untyped =
`expression`[`index`].some `expression`[`index`].some
except KeyError: except KeyError:
T.none T.none
except IndexDefect:
T.none

View File

@ -267,6 +267,16 @@ suite "optionals":
check table.?["a"] == 1.some check table.?["a"] == 1.some
check table.?["c"] == int.none 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": test ".?[] can be followed by calls, operators and indexing":
let table = @{"a": @[41, 42]}.toTable let table = @{"a": @[41, 42]}.toTable
check table.?["a"].isSome check table.?["a"].isSome