syndicate-nim/src/syndicate/patterns.nim

59 lines
1.7 KiB
Nim
Raw Normal View History

2021-10-28 17:43:20 +00:00
# SPDX-FileCopyrightText: ☭ 2021 Emery Hemingway
# SPDX-License-Identifier: Unlicense
2021-10-29 12:06:00 +00:00
import std/[macros, tables]
2021-10-28 17:43:20 +00:00
import preserves
import ./protocols/dataspacePatterns
2021-10-28 17:43:20 +00:00
from ./actors import Ref
2021-10-29 12:06:00 +00:00
export dataspacePatterns.`$`
2021-10-28 17:43:20 +00:00
type
2021-10-29 12:06:00 +00:00
CRec = dataspacePatterns.CRec[Ref]
DCompoundRec = dataspacePatterns.DCompoundRec[Ref]
DBind* = dataspacePatterns.DBind[Ref]
DLit* = dataspacePatterns.DLit[Ref]
DCompound* = dataspacePatterns.DCompound[Ref]
2021-10-28 17:43:20 +00:00
Pattern* = dataspacePatterns.Pattern[Ref]
2021-10-29 12:06:00 +00:00
proc `?`*(d: DBind): Pattern =
Pattern(orKind: PatternKind.DBind, dbind: d)
proc `?`*(d: DLit): Pattern =
Pattern(orKind: PatternKind.DLit, dlit: d)
proc `?`*(d: DCompound): Pattern =
Pattern(orKind: PatternKind.DCompound, dcompound: d)
proc `?`*(s: string): Pattern =
?DLit(value: toPreserve(s, Ref))
2021-10-29 12:06:00 +00:00
proc arity(T: typedesc): int =
var t: T # a hack to iterate the fields of a non-existent instance
for _ in fields(t): inc result
proc `?_`*(): Pattern = Pattern(orKind: PatternKind.DDiscard)
proc `?*`*(): Pattern = ?DBind(pattern: `?_`())
2021-10-29 12:06:00 +00:00
proc `?`*(T: typedesc; bindings: openArray[(int, Pattern)]): Pattern =
## Pattern constructor operator.
when T.hasCustomPragma(preservesRecord):
var label = tosymbol(T.getCustomPragmaVal(preservesRecord), Ref)
2021-10-29 12:06:00 +00:00
result = ?DCompound(
orKind: DCompoundKind.rec,
rec: DCompoundRec(
ctor: CRec(label: label, arity: T.arity),
members: toTable bindings))
else:
{.error: "no custom pragma on " & $T.}
proc observe*(pat: Pattern): Pattern =
# TODO: why doesn't Observe from ./protocols/dataspace.nim work?
?DCompound(
orKind: DCompoundKind.rec,
rec: DCompoundRec(
ctor: CRec(label: toSymbol("Observe", Ref), arity: 2),
2021-11-03 18:22:33 +00:00
members: toTable {0 : pat, 1: `?_`()}))