Index into compound types by Preserve keys

This commit is contained in:
Emery Hemingway 2022-03-08 15:24:14 -06:00
parent db06066e17
commit 8b52e3baf9
1 changed files with 17 additions and 13 deletions

View File

@ -216,15 +216,6 @@ proc `[]=`*(pr: var Preserve; i: Natural; val: Preserve) =
else:
raise newException(ValueError, "`Preserves value is not indexable")
proc `[]`*(pr, key: Preserve): Preserve =
## Select a dictionary value from ``pr``.
if pr.kind == pkDictionary:
for (k, v) in pr.dict:
if key == k: return v
raise newException(KeyError, "Key not in Preserves dictionary")
else:
raise newException(ValueError, "`[]` is not valid for " & $pr.kind)
proc getOrDefault(pr: Preserve; key: Preserve): Preserve =
## Retrieves the value of `pr[key]` if `pr` is a dictionary containing `key`
## or returns the `#f` Preserves value.
@ -249,11 +240,16 @@ proc excl*(pr: var Preserve; key: Preserve) =
delete(pr.set, i, i)
break
proc `[]`*(pr: var Preserve; key: Preserve): var Preserve =
proc `[]`*(pr, key: Preserve): Preserve =
## Select a value by `key` from the Preserves dictionary `pr`.
for (k, v) in pr.dict.items:
if k == key: return v
raise newException(KeyError, "value not in Preserves dictionary")
if pr.isDictionary:
for (k, v) in pr.dict.items:
if k == key: return v
raise newException(KeyError, "value not in Preserves dictionary")
elif (pr.isRecord or pr.isSequence) and key.isInteger:
result = pr[int key.int]
else:
raise newException(ValueError, "invalid Preserves indexing")
proc `[]=`*(pr: var Preserve; key, val: Preserve) =
## Insert `val` by `key` in the Preserves dictionary `pr`.
@ -266,6 +262,14 @@ proc `[]=`*(pr: var Preserve; key, val: Preserve) =
return
pr.dict.add((key, val, ))
proc mget*(pr: var Preserve; key: Preserve): var Preserve =
## Select a value by `key` from the Preserves dictionary `pr`.
if pr.isDictionary:
for (k, v) in pr.dict.items:
if k == key: return v
raise newException(KeyError, "key not in Preserves dictionary")
raise newException(ValueError, "not a Preserves dictionary")
proc toSymbol*(s: sink string; E = void): Preserve[E] {.inline.} =
## Create a Preserves symbol value.
Preserve[E](kind: pkSymbol, symbol: Symbol s)