Refactoring: Shorter type names

This commit is contained in:
Felix Krause 2016-01-14 22:51:30 +01:00
parent 551c8b0dd1
commit 56d3537920
8 changed files with 149 additions and 159 deletions

View File

@ -154,6 +154,6 @@ proc constructJson*(s: YamlStream): seq[JsonNode] =
proc loadToJson*(s: Stream): seq[JsonNode] =
var
parser = newParser(coreTagLibrary())
parser = newParser(coreTagLibrary)
events = parser.parse(s)
return constructJson(events)

View File

@ -52,16 +52,15 @@ proc `$`*(id: TagId): string =
else:
"<" & $cast[int](id) & ">"
proc newParser*(tagLib: YamlTagLibrary): YamlSequentialParser =
proc newParser*(tagLib: TagLibrary): YamlParser =
new(result)
result.tagLib = tagLib
result.anchors = initOrderedTable[string, AnchorId]()
proc setWarningCallback*(parser: YamlSequentialParser,
callback: YamlWarningCallback) =
proc setWarningCallback*(parser: YamlParser, callback: WarningCallback) =
parser.callback = callback
proc anchor*(parser: YamlSequentialParser, id: AnchorId): string =
proc anchor*(parser: YamlParser, id: AnchorId): string =
for pair in parser.anchors.pairs:
if pair[1] == id:
return pair[0]
@ -85,7 +84,7 @@ template yieldUnexpectedToken(expected: string = "") {.dirty.} =
msg.add(": " & $token)
raiseError(msg)
proc resolveAnchor(parser: YamlSequentialParser, anchor: var string):
proc resolveAnchor(parser: YamlParser, anchor: var string):
AnchorId {.inline.} =
result = yAnchorNone
if anchor.len > 0:
@ -94,13 +93,13 @@ proc resolveAnchor(parser: YamlSequentialParser, anchor: var string):
result = parser.anchors[anchor]
anchor = ""
proc resolveAlias(parser: YamlSequentialParser, name: string): AnchorId =
proc resolveAlias(parser: YamlParser, name: string): AnchorId =
try:
result = parser.anchors[name]
except KeyError:
result = yAnchorNone
proc resolveTag(parser: YamlSequentialParser, tag: var string,
proc resolveTag(parser: YamlParser, tag: var string,
quotedString: bool = false): TagId {.inline.} =
if tag.len == 0:
result = if quotedString: parser.tagLib.tags["!"] else:
@ -130,16 +129,12 @@ template yieldScalar(content: string, quoted: bool = false) {.dirty.} =
template yieldStartMap() {.dirty.} =
when defined(yamlDebug):
echo "Parser token [mode=", level.mode, ", state=", state, "]: yamlStartMap"
yield YamlStreamEvent(kind: yamlStartMap,
mapAnchor: resolveAnchor(parser, anchor),
mapTag: resolveTag(parser, tag))
yield startMapEvent(resolveTag(parser, tag), resolveAnchor(parser, anchor))
template yieldStartSequence() {.dirty.} =
when defined(yamlDebug):
echo "Parser token [mode=", level.mode, ", state=", state, "]: yamlStartSequence"
yield YamlStreamEvent(kind: yamlStartSequence,
seqAnchor: resolveAnchor(parser, anchor),
seqTag: resolveTag(parser, tag))
yield startSeqEvent(resolveTag(parser, tag), resolveAnchor(parser, anchor))
template yieldStart(t: YamlStreamEventKind) {.dirty.} =
when t == yamlStartMap:
@ -148,7 +143,7 @@ template yieldStart(t: YamlStreamEventKind) {.dirty.} =
yieldStartSequence()
template yieldDocumentEnd() {.dirty.} =
yield YamlStreamEvent(kind: yamlEndDocument)
yield endDocEvent()
tagShorthands = initTable[string, string]()
tagShorthands["!"] = "!"
tagShorthands["!!"] = yamlTagRepositoryPrefix
@ -158,11 +153,11 @@ template closeLevel(lvl: DocumentLevel) {.dirty.} =
case lvl.mode
of mExplicitBlockMapKey, mFlowMapKey:
yieldScalar("")
yield YamlStreamEvent(kind: yamlEndMap)
yield endMapEvent()
of mImplicitBlockMapKey, mBlockMapValue, mFlowMapValue:
yield YamlStreamEvent(kind: yamlEndMap)
yield endMapEvent()
of mBlockSequenceItem, mFlowSequenceItem:
yield YamlStreamEvent(kind: yamlEndSequence)
yield endSeqEvent()
of mScalar:
when defined(yamlDebug):
echo "Parser token [mode=", level.mode, ", state=", state, "]: ",
@ -272,7 +267,7 @@ template handleTagHandle() {.dirty.} =
else:
raiseError("Unknown tag shorthand: " & handle)
proc parse*(parser: YamlSequentialParser, s: Stream): YamlStream =
proc parse*(parser: YamlParser, s: Stream): YamlStream =
result = iterator(): YamlStreamEvent =
var
# parsing state

View File

@ -38,7 +38,7 @@ template safeWrite(s: string or char) {.dirty.} =
e.cause = getCurrentException()
raise e
proc startItem(target: Stream, style: YamlPresentationStyle, indentation: int,
proc startItem(target: Stream, style: PresentationStyle, indentation: int,
state: var DumperState, isObject: bool)
{.raises: [YamlPresenterOutputError].} =
try:
@ -46,7 +46,7 @@ proc startItem(target: Stream, style: YamlPresentationStyle, indentation: int,
of dBlockMapValue:
target.write('\x0A')
target.write(repeat(' ', indentation))
if isObject or style == ypsCanonical:
if isObject or style == psCanonical:
target.write("? ")
state = dBlockExplicitMapKey
else:
@ -62,31 +62,31 @@ proc startItem(target: Stream, style: YamlPresentationStyle, indentation: int,
target.write(": ")
state = dBlockMapValue
of dFlowExplicitMapKey:
if style != ypsMinimal:
if style != psMinimal:
target.write('\x0A')
target.write(repeat(' ', indentation))
target.write(": ")
state = dFlowMapValue
of dFlowMapValue:
if (isObject and style != ypsMinimal) or
style in [ypsJson, ypsCanonical]:
if (isObject and style != psMinimal) or
style in [psJson, psCanonical]:
target.write(",\x0A" & repeat(' ', indentation))
if style == ypsJson:
if style == psJson:
state = dFlowImplicitMapKey
else:
target.write("? ")
state = dFlowExplicitMapKey
elif isObject and style == ypsMinimal:
elif isObject and style == psMinimal:
target.write(", ? ")
state = dFlowExplicitMapKey
else:
target.write(", ")
state = dFlowImplicitMapKey
of dFlowMapStart:
if (isObject and style != ypsMinimal) or
style in [ypsJson, ypsCanonical]:
if (isObject and style != psMinimal) or
style in [psJson, psCanonical]:
target.write("\x0A" & repeat(' ', indentation))
if style == ypsJson:
if style == psJson:
state = dFlowImplicitMapKey
else:
target.write("? ")
@ -102,29 +102,29 @@ proc startItem(target: Stream, style: YamlPresentationStyle, indentation: int,
target.write("- ")
of dFlowSequenceStart:
case style
of ypsMinimal, ypsDefault:
of psMinimal, psDefault:
discard
of ypsCanonical, ypsJson:
of psCanonical, psJson:
target.write('\x0A')
target.write(repeat(' ', indentation))
of ypsBlockOnly:
of psBlockOnly:
discard # can never happen
state = dFlowSequenceItem
of dFlowSequenceItem:
case style
of ypsMinimal, ypsDefault:
of psMinimal, psDefault:
target.write(", ")
of ypsCanonical, ypsJson:
of psCanonical, psJson:
target.write(",\x0A")
target.write(repeat(' ', indentation))
of ypsBlockOnly:
of psBlockOnly:
discard # can never happen
except:
var e = newException(YamlPresenterOutputError, "")
e.cause = getCurrentException()
raise e
proc writeTagAndAnchor(target: Stream, tag: TagId, tagLib: YamlTagLibrary,
proc writeTagAndAnchor(target: Stream, tag: TagId, tagLib: TagLibrary,
anchor: AnchorId) {.raises:[YamlPresenterOutputError].} =
try:
if tag notin [yTagQuestionMark, yTagExclamationMark]:
@ -150,8 +150,8 @@ proc writeTagAndAnchor(target: Stream, tag: TagId, tagLib: YamlTagLibrary,
e.cause = getCurrentException()
raise e
proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
style: YamlPresentationStyle = ypsDefault,
proc present*(s: YamlStream, target: Stream, tagLib: TagLibrary,
style: PresentationStyle = psDefault,
indentationStep: int = 2) =
var
cached = initQueue[YamlStreamEvent]()
@ -174,7 +174,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
for item in cacheIterator():
case item.kind
of yamlStartDocument:
if style != ypsJson:
if style != psJson:
# TODO: tag directives
try:
target.write("%YAML 1.2\x0A")
@ -188,16 +188,16 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
raise e
of yamlScalar:
if levels.len == 0:
if style != ypsJson:
if style != psJson:
safeWrite('\x0A')
else:
startItem(target, style, indentation, levels[levels.high],
false)
if style != ypsJson:
if style != psJson:
writeTagAndAnchor(target,
item.scalarTag, tagLib, item.scalarAnchor)
if style == ypsJson:
if style == psJson:
let hint = guessType(item.scalarContent)
if item.scalarTag in [yTagQuestionMark, yTagBoolean] and
hint in [yTypeBoolTrue, yTypeBoolFalse]:
@ -214,12 +214,12 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
"Infinity and not-a-number values cannot be presented as JSON!")
else:
writeDoubleQuoted(item.scalarContent, target)
elif style == ypsCanonical or item.scalarContent.needsEscaping:
elif style == psCanonical or item.scalarContent.needsEscaping:
writeDoubleQuoted(item.scalarContent, target)
else:
safeWrite(item.scalarContent)
of yamlAlias:
if style == ypsJson:
if style == psJson:
raise newException(YamlPresenterJsonError,
"Alias not allowed in JSON output")
assert levels.len > 0
@ -234,7 +234,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
of yamlStartSequence:
var nextState: DumperState
case style
of ypsDefault:
of psDefault:
var length = 0
while true:
try:
@ -257,38 +257,38 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
raise e
nextState = if length <= 60: dFlowSequenceStart else:
dBlockSequenceItem
of ypsJson:
of psJson:
if levels.len > 0 and levels[levels.high] in
[dFlowMapStart, dFlowMapValue]:
raise newException(YamlPresenterJsonError,
"Cannot have sequence as map key in JSON output!")
nextState = dFlowSequenceStart
of ypsMinimal, ypsCanonical:
of psMinimal, psCanonical:
nextState = dFlowSequenceStart
of ypsBlockOnly:
of psBlockOnly:
nextState = dBlockSequenceItem
if levels.len == 0:
if nextState == dBlockSequenceItem:
if style != ypsJson:
if style != psJson:
writeTagAndAnchor(target,
item.seqTag, tagLib, item.seqAnchor)
else:
if style != ypsJson:
if style != psJson:
writeTagAndAnchor(target,
item.seqTag, tagLib, item.seqAnchor)
safeWrite('\x0A')
indentation += indentationStep
else:
startItem(target, style, indentation, levels[levels.high], true)
if style != ypsJson:
if style != psJson:
writeTagAndAnchor(target,
item.seqTag, tagLib, item.seqAnchor)
indentation += indentationStep
if nextState == dFlowSequenceStart:
safeWrite('[')
if levels.len > 0 and style in [ypsJson, ypsCanonical] and
if levels.len > 0 and style in [psJson, psCanonical] and
levels[levels.high] in
[dBlockExplicitMapKey, dBlockMapValue,
dBlockImplicitMapKey, dBlockSequenceItem]:
@ -297,7 +297,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
of yamlStartMap:
var nextState: DumperState
case style
of ypsDefault:
of psDefault:
type mapParseState = enum
mpInitial, mpKey, mpValue, mpNeedBlock
var mps = mpInitial
@ -322,32 +322,32 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
raise e
nextState = if mps == mpNeedBlock: dBlockMapValue else:
dBlockInlineMap
of ypsMinimal:
of psMinimal:
nextState = dFlowMapStart
of ypsCanonical:
of psCanonical:
nextState = dFlowMapStart
of ypsJson:
of psJson:
if levels.len > 0 and levels[levels.high] in
[dFlowMapStart, dFlowMapValue]:
raise newException(YamlPresenterJsonError,
"Cannot have map as map key in JSON output!")
nextState = dFlowMapStart
of ypsBlockOnly:
of psBlockOnly:
nextState = dBlockMapValue
if levels.len == 0:
if nextState == dBlockMapValue:
if style != ypsJson:
if style != psJson:
writeTagAndAnchor(target,
item.mapTag, tagLib, item.mapAnchor)
else:
if style != ypsJson:
if style != psJson:
safeWrite('\x0A')
writeTagAndAnchor(target,
item.mapTag, tagLib, item.mapAnchor)
indentation += indentationStep
else:
if nextState in [dBlockMapValue, dBlockImplicitMapKey]:
if style != ypsJson:
if style != psJson:
writeTagAndAnchor(target,
item.mapTag, tagLib, item.mapAnchor)
startItem(target, style, indentation, levels[levels.high],
@ -355,14 +355,14 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
else:
startItem(target, style, indentation, levels[levels.high],
true)
if style != ypsJson:
if style != psJson:
writeTagAndAnchor(target,
item.mapTag, tagLib, item.mapAnchor)
indentation += indentationStep
if nextState == dFlowMapStart:
safeWrite('{')
if levels.len > 0 and style in [ypsJson, ypsCanonical] and
if levels.len > 0 and style in [psJson, psCanonical] and
levels[levels.high] in
[dBlockExplicitMapKey, dBlockMapValue,
dBlockImplicitMapKey, dBlockSequenceItem]:
@ -374,9 +374,9 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
case levels.pop()
of dFlowSequenceItem:
case style
of ypsDefault, ypsMinimal, ypsBlockOnly:
of psDefault, psMinimal, psBlockOnly:
safeWrite(']')
of ypsJson, ypsCanonical:
of psJson, psCanonical:
indentation -= indentationStep
try:
target.write('\x0A')
@ -391,7 +391,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
dBlockImplicitMapKey, dBlockSequenceItem]:
continue
of dFlowSequenceStart:
if levels.len > 0 and style in [ypsJson, ypsCanonical] and
if levels.len > 0 and style in [psJson, psCanonical] and
levels[levels.high] in
[dBlockExplicitMapKey, dBlockMapValue,
dBlockImplicitMapKey, dBlockSequenceItem]:
@ -408,9 +408,9 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
case level
of dFlowMapValue:
case style
of ypsDefault, ypsMinimal, ypsBlockOnly:
of psDefault, psMinimal, psBlockOnly:
safeWrite('}')
of ypsJson, ypsCanonical:
of psJson, psCanonical:
indentation -= indentationStep
try:
target.write('\x0A')
@ -425,7 +425,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
dBlockImplicitMapKey, dBlockSequenceItem]:
continue
of dFlowMapStart:
if levels.len > 0 and style in [ypsJson, ypsCanonical] and
if levels.len > 0 and style in [psJson, psCanonical] and
levels[levels.high] in
[dBlockExplicitMapKey, dBlockMapValue,
dBlockImplicitMapKey, dBlockSequenceItem]:
@ -448,13 +448,13 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
raise e
safeWrite("...\x0A")
proc transform*(input: Stream, output: Stream, style: YamlPresentationStyle,
proc transform*(input: Stream, output: Stream, style: PresentationStyle,
indentationStep: int = 2) =
var
tagLib = extendedTagLibrary()
tagLib = extendedTagLibrary
parser = newParser(tagLib)
events = parser.parse(input)
if style == ypsCanonical:
if style == psCanonical:
var specificTagEvents = iterator(): YamlStreamEvent =
for e in events():
var event = e

View File

@ -4,23 +4,23 @@
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
proc initTagLibrary*(): YamlTagLibrary =
proc initTagLibrary*(): TagLibrary =
result.tags = initTable[string, TagId]()
result.nextCustomTagId = yFirstCustomTagId
result.secondaryPrefix = yamlTagRepositoryPrefix
proc registerUri*(tagLib: var YamlTagLibrary, uri: string): TagId =
proc registerUri*(tagLib: var TagLibrary, uri: string): TagId =
tagLib.tags[uri] = tagLib.nextCustomTagId
result = tagLib.nextCustomTagId
tagLib.nextCustomTagId = cast[TagId](cast[int](tagLib.nextCustomTagId) + 1)
proc uri*(tagLib: YamlTagLibrary, id: TagId): string =
proc uri*(tagLib: TagLibrary, id: TagId): string =
for iUri, iId in tagLib.tags.pairs:
if iId == id:
return iUri
raise newException(KeyError, "Unknown tag id: " & $id)
proc failsafeTagLibrary*(): YamlTagLibrary =
proc initFailsafeTagLibrary(): TagLibrary =
result = initTagLibrary()
result.tags["!"] = yTagExclamationMark
result.tags["?"] = yTagQuestionMark
@ -28,15 +28,15 @@ proc failsafeTagLibrary*(): YamlTagLibrary =
result.tags["tag:yaml.org,2002:seq"] = yTagSequence
result.tags["tag:yaml.org,2002:map"] = yTagMap
proc coreTagLibrary*(): YamlTagLibrary =
result = failsafeTagLibrary()
proc initCoreTagLibrary(): TagLibrary =
result = initFailsafeTagLibrary()
result.tags["tag:yaml.org,2002:null"] = yTagNull
result.tags["tag:yaml.org,2002:bool"] = yTagBoolean
result.tags["tag:yaml.org,2002:int"] = yTagInteger
result.tags["tag:yaml.org,2002:float"] = yTagFloat
proc extendedTagLibrary*(): YamlTagLibrary =
result = coreTagLibrary()
proc initExtendedTagLibrary(): TagLibrary =
result = initCoreTagLibrary()
result.tags["tag:yaml.org,2002:omap"] = yTagOrderedMap
result.tags["tag:yaml.org,2002:pairs"] = yTagPairs
result.tags["tag:yaml.org,2002:binary"] = yTagBinary

View File

@ -109,7 +109,7 @@ template ensure(input: string, expected: varargs[YamlStreamEvent]) {.dirty.} =
suite "Parsing":
setup:
var tagLib = coreTagLibrary()
var tagLib = coreTagLibrary
teardown:
discard

View File

@ -26,7 +26,7 @@ suite "Serialization":
test "Serialization: Serialize string sequence":
var input = @["a", "b"]
var output = newStringStream()
dump(input, output, ypsBlockOnly, ytsNone)
dump(input, output, psBlockOnly, tsNone)
assert output.data == "%YAML 1.2\n--- \n- a\n- b"
test "Serialization: Load Table[int, string]":
@ -46,7 +46,7 @@ suite "Serialization":
input[23] = "dreiundzwanzig"
input[42] = "zweiundvierzig"
var output = newStringStream()
dump(input, output, ypsBlockOnly, ytsNone)
dump(input, output, psBlockOnly, tsNone)
assert output.data == "%YAML 1.2\n--- \n23: dreiundzwanzig\n42: zweiundvierzig"
test "Serialization: Load Sequences in Sequence":
@ -65,7 +65,7 @@ suite "Serialization":
test "Serialization: Serialize Sequences in Sequence":
let input = @[@[1, 2, 3], @[4, 5], @[6]]
var output = newStringStream()
dump(input, output, ypsDefault, ytsNone)
dump(input, output, psDefault, tsNone)
assert output.data == "%YAML 1.2\n--- \n- [1, 2, 3]\n- [4, 5]\n- [6]"
test "Serialization: Load custom object":
@ -83,7 +83,7 @@ suite "Serialization":
test "Serialization: Serialize custom object":
let input = Person(firstname: "Peter", surname: "Pan", age: 12)
var output = newStringStream()
dump(input, output, ypsBlockOnly, ytsNone)
dump(input, output, psBlockOnly, tsNone)
assert output.data == "%YAML 1.2\n--- \nfirstname: Peter\nsurname: Pan\nage: 12"
test "Serialization: Load sequence with explicit tags":
@ -101,7 +101,7 @@ suite "Serialization":
test "Serialization: Serialize sequence with explicit tags":
let input = @["one", "two"]
var output = newStringStream()
dump(input, output, ypsBlockOnly, ytsAll)
dump(input, output, psBlockOnly, tsAll)
assert output.data == "%YAML 1.2\n--- !nim:seq(tag:yaml.org,2002:str) \n- !!str one\n- !!str two"
test "Serialization: Load custom object with explicit root tag":
@ -120,5 +120,5 @@ suite "Serialization":
test "Serialization: Serialize custom object with explicit root tag":
let input = Person(firstname: "Peter", surname: "Pan", age: 12)
var output = newStringStream()
dump(input, output, ypsBlockOnly, ytsRootOnly)
dump(input, output, psBlockOnly, tsRootOnly)
assert output.data == "%YAML 1.2\n--- !nim:Person \nfirstname: Peter\nsurname: Pan\nage: 12"

View File

@ -110,7 +110,7 @@ type
## always yield a well-formed ``YamlStream`` and expect it to be
## well-formed if it's an input.
YamlTagLibrary* = object
TagLibrary* = object
## A ``YamlTagLibrary`` maps tag URIs to ``TagId`` s. YAML tag URIs
## that are defined in the YAML specification or in the
## `YAML tag repository <http://yaml.org/type/>`_ should be mapped to
@ -135,7 +135,7 @@ type
nextCustomTagId*: TagId
secondaryPrefix*: string
YamlWarningCallback* = proc(line, column: int, lineContent: string,
WarningCallback* = proc(line, column: int, lineContent: string,
message: string)
## Callback for parser warnings. Currently, this callback may be called
## on two occasions while parsing a YAML document stream:
@ -144,17 +144,17 @@ type
## ``1.2``.
## - If there is an unknown directive encountered.
YamlSequentialParser* = ref object
YamlParser* = ref object
## A parser object. Retains its ``YamlTagLibrary`` across calls to
## `parse <#parse,YamlSequentialParser,Stream,YamlStream>`_. Can be used
## to access anchor names while parsing a YAML character stream, but
## only until the document goes out of scope (i.e. until
## ``yamlEndDocument`` is yielded).
tagLib: YamlTagLibrary
tagLib: TagLibrary
anchors: OrderedTable[string, AnchorId]
callback: YamlWarningCallback
callback: WarningCallback
YamlPresentationStyle* = enum
PresentationStyle* = enum
## Different styles for YAML character stream output.
##
## - ``ypsMinimal``: Single-line flow-only output which tries to
@ -172,7 +172,7 @@ type
## contain one document.
## - ``ypsBlockOnly``: Formats all output in block style, does not use
## flow style at all.
ypsMinimal, ypsCanonical, ypsDefault, ypsJson, ypsBlockOnly
psMinimal, psCanonical, psDefault, psJson, psBlockOnly
YamlLoadingError* = object of Exception
## Base class for all exceptions that may be raised during the process
@ -318,58 +318,60 @@ proc `==`*(left, right: AnchorId): bool {.borrow.}
proc `$`*(id: AnchorId): string {.borrow.}
proc hash*(id: AnchorId): Hash {.borrow.}
proc initTagLibrary*(): YamlTagLibrary
proc initTagLibrary*(): TagLibrary
## initializes the ``tags`` table and sets ``nextCustomTagId`` to
## ``yFirstCustomTagId``.
proc registerUri*(tagLib: var YamlTagLibrary, uri: string): TagId
proc registerUri*(tagLib: var TagLibrary, uri: string): TagId
## registers a custom tag URI with a ``YamlTagLibrary``. The URI will get
## the ``TagId`` ``nextCustomTagId``, which will be incremented.
proc uri*(tagLib: YamlTagLibrary, id: TagId): string
proc uri*(tagLib: TagLibrary, id: TagId): string
## retrieve the URI a ``TagId`` maps to.
# these should be consts, but the Nim VM still has problems handling tables
# properly, so we use constructor procs instead.
# properly, so we use let instead.
proc failsafeTagLibrary*(): YamlTagLibrary
## Contains only:
## - ``!``
## - ``?``
## - ``!!str``
## - ``!!map``
## - ``!!seq``
proc coreTagLibrary*(): YamlTagLibrary
## Contains everything in ``failsafeTagLibrary`` plus:
## - ``!!null``
## - ``!!bool``
## - ``!!int``
## - ``!!float``
proc extendedTagLibrary*(): YamlTagLibrary
## Contains everything in ``coreTagLibrary`` plus:
## - ``!!omap``
## - ``!!pairs``
## - ``!!set``
## - ``!!binary``
## - ``!!merge``
## - ``!!timestamp``
## - ``!!value``
## - ``!!yaml``
proc initFailsafeTagLibrary(): TagLibrary
proc initCoreTagLibrary(): TagLibrary
proc initExtendedTagLibrary(): TagLibrary
let
failsafeTagLibrary*: TagLibrary = initFailsafeTagLibrary() ## \
## Contains only:
## - ``!``
## - ``?``
## - ``!!str``
## - ``!!map``
## - ``!!seq``
coreTagLibrary*: TagLibrary = initCoreTagLibrary() ## \
## Contains everything in ``failsafeTagLibrary`` plus:
## - ``!!null``
## - ``!!bool``
## - ``!!int``
## - ``!!float``
extendedTagLibrary*: TagLibrary = initExtendedTagLibrary() ## \
## Contains everything in ``coreTagLibrary`` plus:
## - ``!!omap``
## - ``!!pairs``
## - ``!!set``
## - ``!!binary``
## - ``!!merge``
## - ``!!timestamp``
## - ``!!value``
## - ``!!yaml``
proc guessType*(scalar: string): TypeHint {.raises: [].}
proc newParser*(tagLib: YamlTagLibrary): YamlSequentialParser
proc newParser*(tagLib: TagLibrary): YamlParser
## Instanciates a parser
proc setWarningCallback*(parser: YamlSequentialParser,
callback: YamlWarningCallback)
proc setWarningCallback*(parser: YamlParser, callback: WarningCallback)
proc anchor*(parser: YamlSequentialParser, id: AnchorId): string
proc anchor*(parser: YamlParser, id: AnchorId): string
## Get the anchor name which an ``AnchorId`` maps to
proc parse*(parser: YamlSequentialParser, s: Stream):
proc parse*(parser: YamlParser, s: Stream):
YamlStream {.raises: [IOError, YamlParserError].}
## Parse a YAML character stream. ``s`` must be readable.
@ -392,14 +394,14 @@ proc loadToJson*(s: Stream): seq[JsonNode]
## `constructJson <#constructJson>`_ to construct an in-memory JSON tree
## from a YAML character stream.
proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
style: YamlPresentationStyle = ypsDefault,
proc present*(s: YamlStream, target: Stream, tagLib: TagLibrary,
style: PresentationStyle = psDefault,
indentationStep: int = 2) {.raises: [YamlPresenterJsonError,
YamlPresenterOutputError,
YamlPresenterStreamError].}
## Convert ``s`` to a YAML character stream and write it to ``target``.
proc transform*(input: Stream, output: Stream, style: YamlPresentationStyle,
proc transform*(input: Stream, output: Stream, style: PresentationStyle,
indentationStep: int = 2)
## Parser ``input`` as YAML character stream and then dump it to ``output``
## without resolving any tags, anchors and aliases.

View File

@ -3,12 +3,10 @@ import macros, strutils, streams, tables, json, hashes, re
export yaml, streams, tables, json
type
YamlTagStyle* = enum
ytsNone,
ytsRootOnly,
ytsAll
TagStyle* = enum
tsNone, tsRootOnly, tsAll
proc initSerializationTagLibrary(): YamlTagLibrary =
proc initSerializationTagLibrary(): TagLibrary =
result = initTagLibrary()
result.tags["!"] = yTagExclamationMark
result.tags["?"] = yTagQuestionMark
@ -41,8 +39,8 @@ static:
var existingTuples = newSeq[NimNode]()
template presentTag(t: typedesc, tagStyle: YamlTagStyle): TagId =
if tagStyle == ytsNone: yTagQuestionMark else: yamlTag(t)
template presentTag(t: typedesc, tagStyle: TagStyle): TagId =
if tagStyle == tsNone: yTagQuestionMark else: yamlTag(t)
proc lazyLoadTag*(uri: string): TagId {.inline.} =
try:
@ -158,14 +156,14 @@ macro make_serializable*(types: stmt): stmt =
newIdentNode("YamlStream"),
newIdentDefs(newIdentNode("value"), tIdent),
newIdentDefs(newIdentNode("tagStyle"),
newIdentNode("YamlTagStyle"),
newIdentNode("ytsNone"))])
newIdentNode("TagStyle"),
newIdentNode("tsNone"))])
var iterBody = newStmtList(
newLetStmt(newIdentNode("childTagStyle"), newNimNode(nnkIfExpr).add(
newNimNode(nnkElifExpr).add(
newNimNode(nnkInfix).add(newIdentNode("=="),
newIdentNode("tagStyle"), newIdentNode("ytsRootOnly")),
newIdentNode("ytsNone")
newIdentNode("tagStyle"), newIdentNode("tsRootOnly")),
newIdentNode("tsNone")
), newNimNode(nnkElseExpr).add(newIdentNode("tagStyle")))),
newNimNode(nnkYieldStmt).add(
newNimNode(nnkObjConstr).add(newIdentNode("YamlStreamEvent"),
@ -175,7 +173,7 @@ macro make_serializable*(types: stmt): stmt =
newNimNode(nnkIfExpr).add(newNimNode(nnkElifExpr).add(
newNimNode(nnkInfix).add(newIdentNode("=="),
newIdentNode("tagStyle"),
newIdentNode("ytsNone")),
newIdentNode("tsNone")),
newIdentNode("yTagQuestionMark")
), newNimNode(nnkElseExpr).add(
newCall("yamlTag", newCall("type", tIdent))
@ -239,7 +237,7 @@ proc construct*(s: YamlStream, result: var string) =
result = item.scalarContent
proc serialize*(value: string,
tagStyle: YamlTagStyle = ytsNone): YamlStream =
tagStyle: TagStyle = tsNone): YamlStream =
result = iterator(): YamlStreamEvent =
yield scalarEvent(value, presentTag(string, tagStyle), yAnchorNone)
@ -255,8 +253,7 @@ proc construct*(s: YamlStream, result: var int) =
raise newException(ValueError, "Wrong scalar type for int.")
result = parseInt(item.scalarContent)
proc serialize*(value: int,
tagStyle: YamlTagStyle = ytsNone): YamlStream =
proc serialize*(value: int, tagStyle: TagStyle = tsNone): YamlStream =
result = iterator(): YamlStreamEvent =
yield scalarEvent($value, presentTag(int, tagStyle), yAnchorNone)
@ -272,8 +269,7 @@ proc contruct*(s: YamlStream, result: var int64) =
raise newException(ValueError, "Wrong scalar type for int64.")
result = parseBiggestInt(item.scalarContent)
proc serialize*(value: int64,
tagStyle: YamlTagStyle = ytsNone): YamlStream =
proc serialize*(value: int64, tagStyle: TagStyle = tsNone): YamlStream =
result = iterator(): YamlStreamEvent =
yield scalarEvent($value, presentTag(int64, tagStyle), yAnchorNone)
@ -301,7 +297,7 @@ proc construct*(s: YamlStream, result: var float) =
else:
raise newException(ValueError, "Wrong scalar type for float.")
proc serialize*(value: float, tagStyle: YamlTagStyle = ytsNone): YamlStream =
proc serialize*(value: float, tagStyle: TagStyle = tsNone): YamlStream =
result = iterator(): YamlStreamEvent =
var
asString: string
@ -336,8 +332,7 @@ proc construct*(s: YamlStream, result: var bool) =
else:
raise newException(ValueError, "Wrong scalar type for bool")
proc serialize*(value: bool,
tagStyle: YamlTagStyle = ytsNone): YamlStream =
proc serialize*(value: bool, tagStyle: TagStyle = tsNone): YamlStream =
result = iterator(): YamlStreamEvent =
yield scalarEvent(if value: "y" else: "n", presentTag(bool, tagStyle),
yAnchorNone)
@ -367,10 +362,9 @@ proc construct*[T](s: YamlStream, result: var seq[T]) =
if finished(s):
raise newException(ValueError, "Construction error!3")
proc serialize*[T](value: seq[T],
tagStyle: YamlTagStyle = ytsNone): YamlStream =
proc serialize*[T](value: seq[T], tagStyle: TagStyle = tsNone): YamlStream =
result = iterator(): YamlStreamEvent =
let childTagStyle = if tagStyle == ytsRootOnly: ytsNone else: tagStyle
let childTagStyle = if tagStyle == tsRootOnly: tsNone else: tagStyle
yield YamlStreamEvent(kind: yamlStartSequence,
seqTag: presentTag(seq[T], tagStyle),
seqAnchor: yAnchorNone)
@ -414,9 +408,9 @@ proc construct*[K, V](s: YamlStream, result: var Table[K, V]) =
raise newException(ValueError, "Construction error!")
proc serialize*[K, V](value: Table[K, V],
tagStyle: YamlTagStyle = ytsNone): YamlStream =
tagStyle: TagStyle = tsNone): YamlStream =
result = iterator(): YamlStreamEvent =
let childTagStyle = if tagStyle == ytsRootOnly: ytsNone else: tagStyle
let childTagStyle = if tagStyle == tsRootOnly: tsNone else: tagStyle
yield YamlStreamEvent(kind: yamlStartMap,
mapTag: presentTag(Table[K, V], tagStyle),
mapAnchor: yAnchorNone)
@ -437,11 +431,10 @@ proc load*[K](input: Stream, target: var K) =
construct(events, target)
assert events().kind == yamlEndDocument
proc dump*[K](value: K, target: Stream,
style: YamlPresentationStyle = ypsDefault,
tagStyle: YamlTagStyle = ytsRootOnly, indentationStep: int = 2) =
proc dump*[K](value: K, target: Stream, style: PresentationStyle = psDefault,
tagStyle: TagStyle = tsRootOnly, indentationStep: int = 2) =
var serialized = serialize(value,
if style == ypsCanonical: ytsAll else: tagStyle)
if style == psCanonical: tsAll else: tagStyle)
var events = iterator(): YamlStreamEvent =
yield YamlStreamEvent(kind: yamlStartDocument)
for event in serialized():