mirror of
https://github.com/status-im/NimYAML.git
synced 2025-02-09 18:05:18 +00:00
Refactoring: Shorter type names
This commit is contained in:
parent
551c8b0dd1
commit
56d3537920
@ -154,6 +154,6 @@ proc constructJson*(s: YamlStream): seq[JsonNode] =
|
|||||||
|
|
||||||
proc loadToJson*(s: Stream): seq[JsonNode] =
|
proc loadToJson*(s: Stream): seq[JsonNode] =
|
||||||
var
|
var
|
||||||
parser = newParser(coreTagLibrary())
|
parser = newParser(coreTagLibrary)
|
||||||
events = parser.parse(s)
|
events = parser.parse(s)
|
||||||
return constructJson(events)
|
return constructJson(events)
|
@ -52,16 +52,15 @@ proc `$`*(id: TagId): string =
|
|||||||
else:
|
else:
|
||||||
"<" & $cast[int](id) & ">"
|
"<" & $cast[int](id) & ">"
|
||||||
|
|
||||||
proc newParser*(tagLib: YamlTagLibrary): YamlSequentialParser =
|
proc newParser*(tagLib: TagLibrary): YamlParser =
|
||||||
new(result)
|
new(result)
|
||||||
result.tagLib = tagLib
|
result.tagLib = tagLib
|
||||||
result.anchors = initOrderedTable[string, AnchorId]()
|
result.anchors = initOrderedTable[string, AnchorId]()
|
||||||
|
|
||||||
proc setWarningCallback*(parser: YamlSequentialParser,
|
proc setWarningCallback*(parser: YamlParser, callback: WarningCallback) =
|
||||||
callback: YamlWarningCallback) =
|
|
||||||
parser.callback = callback
|
parser.callback = callback
|
||||||
|
|
||||||
proc anchor*(parser: YamlSequentialParser, id: AnchorId): string =
|
proc anchor*(parser: YamlParser, id: AnchorId): string =
|
||||||
for pair in parser.anchors.pairs:
|
for pair in parser.anchors.pairs:
|
||||||
if pair[1] == id:
|
if pair[1] == id:
|
||||||
return pair[0]
|
return pair[0]
|
||||||
@ -85,7 +84,7 @@ template yieldUnexpectedToken(expected: string = "") {.dirty.} =
|
|||||||
msg.add(": " & $token)
|
msg.add(": " & $token)
|
||||||
raiseError(msg)
|
raiseError(msg)
|
||||||
|
|
||||||
proc resolveAnchor(parser: YamlSequentialParser, anchor: var string):
|
proc resolveAnchor(parser: YamlParser, anchor: var string):
|
||||||
AnchorId {.inline.} =
|
AnchorId {.inline.} =
|
||||||
result = yAnchorNone
|
result = yAnchorNone
|
||||||
if anchor.len > 0:
|
if anchor.len > 0:
|
||||||
@ -94,13 +93,13 @@ proc resolveAnchor(parser: YamlSequentialParser, anchor: var string):
|
|||||||
result = parser.anchors[anchor]
|
result = parser.anchors[anchor]
|
||||||
anchor = ""
|
anchor = ""
|
||||||
|
|
||||||
proc resolveAlias(parser: YamlSequentialParser, name: string): AnchorId =
|
proc resolveAlias(parser: YamlParser, name: string): AnchorId =
|
||||||
try:
|
try:
|
||||||
result = parser.anchors[name]
|
result = parser.anchors[name]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
result = yAnchorNone
|
result = yAnchorNone
|
||||||
|
|
||||||
proc resolveTag(parser: YamlSequentialParser, tag: var string,
|
proc resolveTag(parser: YamlParser, tag: var string,
|
||||||
quotedString: bool = false): TagId {.inline.} =
|
quotedString: bool = false): TagId {.inline.} =
|
||||||
if tag.len == 0:
|
if tag.len == 0:
|
||||||
result = if quotedString: parser.tagLib.tags["!"] else:
|
result = if quotedString: parser.tagLib.tags["!"] else:
|
||||||
@ -130,16 +129,12 @@ template yieldScalar(content: string, quoted: bool = false) {.dirty.} =
|
|||||||
template yieldStartMap() {.dirty.} =
|
template yieldStartMap() {.dirty.} =
|
||||||
when defined(yamlDebug):
|
when defined(yamlDebug):
|
||||||
echo "Parser token [mode=", level.mode, ", state=", state, "]: yamlStartMap"
|
echo "Parser token [mode=", level.mode, ", state=", state, "]: yamlStartMap"
|
||||||
yield YamlStreamEvent(kind: yamlStartMap,
|
yield startMapEvent(resolveTag(parser, tag), resolveAnchor(parser, anchor))
|
||||||
mapAnchor: resolveAnchor(parser, anchor),
|
|
||||||
mapTag: resolveTag(parser, tag))
|
|
||||||
|
|
||||||
template yieldStartSequence() {.dirty.} =
|
template yieldStartSequence() {.dirty.} =
|
||||||
when defined(yamlDebug):
|
when defined(yamlDebug):
|
||||||
echo "Parser token [mode=", level.mode, ", state=", state, "]: yamlStartSequence"
|
echo "Parser token [mode=", level.mode, ", state=", state, "]: yamlStartSequence"
|
||||||
yield YamlStreamEvent(kind: yamlStartSequence,
|
yield startSeqEvent(resolveTag(parser, tag), resolveAnchor(parser, anchor))
|
||||||
seqAnchor: resolveAnchor(parser, anchor),
|
|
||||||
seqTag: resolveTag(parser, tag))
|
|
||||||
|
|
||||||
template yieldStart(t: YamlStreamEventKind) {.dirty.} =
|
template yieldStart(t: YamlStreamEventKind) {.dirty.} =
|
||||||
when t == yamlStartMap:
|
when t == yamlStartMap:
|
||||||
@ -148,7 +143,7 @@ template yieldStart(t: YamlStreamEventKind) {.dirty.} =
|
|||||||
yieldStartSequence()
|
yieldStartSequence()
|
||||||
|
|
||||||
template yieldDocumentEnd() {.dirty.} =
|
template yieldDocumentEnd() {.dirty.} =
|
||||||
yield YamlStreamEvent(kind: yamlEndDocument)
|
yield endDocEvent()
|
||||||
tagShorthands = initTable[string, string]()
|
tagShorthands = initTable[string, string]()
|
||||||
tagShorthands["!"] = "!"
|
tagShorthands["!"] = "!"
|
||||||
tagShorthands["!!"] = yamlTagRepositoryPrefix
|
tagShorthands["!!"] = yamlTagRepositoryPrefix
|
||||||
@ -158,11 +153,11 @@ template closeLevel(lvl: DocumentLevel) {.dirty.} =
|
|||||||
case lvl.mode
|
case lvl.mode
|
||||||
of mExplicitBlockMapKey, mFlowMapKey:
|
of mExplicitBlockMapKey, mFlowMapKey:
|
||||||
yieldScalar("")
|
yieldScalar("")
|
||||||
yield YamlStreamEvent(kind: yamlEndMap)
|
yield endMapEvent()
|
||||||
of mImplicitBlockMapKey, mBlockMapValue, mFlowMapValue:
|
of mImplicitBlockMapKey, mBlockMapValue, mFlowMapValue:
|
||||||
yield YamlStreamEvent(kind: yamlEndMap)
|
yield endMapEvent()
|
||||||
of mBlockSequenceItem, mFlowSequenceItem:
|
of mBlockSequenceItem, mFlowSequenceItem:
|
||||||
yield YamlStreamEvent(kind: yamlEndSequence)
|
yield endSeqEvent()
|
||||||
of mScalar:
|
of mScalar:
|
||||||
when defined(yamlDebug):
|
when defined(yamlDebug):
|
||||||
echo "Parser token [mode=", level.mode, ", state=", state, "]: ",
|
echo "Parser token [mode=", level.mode, ", state=", state, "]: ",
|
||||||
@ -272,7 +267,7 @@ template handleTagHandle() {.dirty.} =
|
|||||||
else:
|
else:
|
||||||
raiseError("Unknown tag shorthand: " & handle)
|
raiseError("Unknown tag shorthand: " & handle)
|
||||||
|
|
||||||
proc parse*(parser: YamlSequentialParser, s: Stream): YamlStream =
|
proc parse*(parser: YamlParser, s: Stream): YamlStream =
|
||||||
result = iterator(): YamlStreamEvent =
|
result = iterator(): YamlStreamEvent =
|
||||||
var
|
var
|
||||||
# parsing state
|
# parsing state
|
||||||
|
@ -38,7 +38,7 @@ template safeWrite(s: string or char) {.dirty.} =
|
|||||||
e.cause = getCurrentException()
|
e.cause = getCurrentException()
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
proc startItem(target: Stream, style: YamlPresentationStyle, indentation: int,
|
proc startItem(target: Stream, style: PresentationStyle, indentation: int,
|
||||||
state: var DumperState, isObject: bool)
|
state: var DumperState, isObject: bool)
|
||||||
{.raises: [YamlPresenterOutputError].} =
|
{.raises: [YamlPresenterOutputError].} =
|
||||||
try:
|
try:
|
||||||
@ -46,7 +46,7 @@ proc startItem(target: Stream, style: YamlPresentationStyle, indentation: int,
|
|||||||
of dBlockMapValue:
|
of dBlockMapValue:
|
||||||
target.write('\x0A')
|
target.write('\x0A')
|
||||||
target.write(repeat(' ', indentation))
|
target.write(repeat(' ', indentation))
|
||||||
if isObject or style == ypsCanonical:
|
if isObject or style == psCanonical:
|
||||||
target.write("? ")
|
target.write("? ")
|
||||||
state = dBlockExplicitMapKey
|
state = dBlockExplicitMapKey
|
||||||
else:
|
else:
|
||||||
@ -62,31 +62,31 @@ proc startItem(target: Stream, style: YamlPresentationStyle, indentation: int,
|
|||||||
target.write(": ")
|
target.write(": ")
|
||||||
state = dBlockMapValue
|
state = dBlockMapValue
|
||||||
of dFlowExplicitMapKey:
|
of dFlowExplicitMapKey:
|
||||||
if style != ypsMinimal:
|
if style != psMinimal:
|
||||||
target.write('\x0A')
|
target.write('\x0A')
|
||||||
target.write(repeat(' ', indentation))
|
target.write(repeat(' ', indentation))
|
||||||
target.write(": ")
|
target.write(": ")
|
||||||
state = dFlowMapValue
|
state = dFlowMapValue
|
||||||
of dFlowMapValue:
|
of dFlowMapValue:
|
||||||
if (isObject and style != ypsMinimal) or
|
if (isObject and style != psMinimal) or
|
||||||
style in [ypsJson, ypsCanonical]:
|
style in [psJson, psCanonical]:
|
||||||
target.write(",\x0A" & repeat(' ', indentation))
|
target.write(",\x0A" & repeat(' ', indentation))
|
||||||
if style == ypsJson:
|
if style == psJson:
|
||||||
state = dFlowImplicitMapKey
|
state = dFlowImplicitMapKey
|
||||||
else:
|
else:
|
||||||
target.write("? ")
|
target.write("? ")
|
||||||
state = dFlowExplicitMapKey
|
state = dFlowExplicitMapKey
|
||||||
elif isObject and style == ypsMinimal:
|
elif isObject and style == psMinimal:
|
||||||
target.write(", ? ")
|
target.write(", ? ")
|
||||||
state = dFlowExplicitMapKey
|
state = dFlowExplicitMapKey
|
||||||
else:
|
else:
|
||||||
target.write(", ")
|
target.write(", ")
|
||||||
state = dFlowImplicitMapKey
|
state = dFlowImplicitMapKey
|
||||||
of dFlowMapStart:
|
of dFlowMapStart:
|
||||||
if (isObject and style != ypsMinimal) or
|
if (isObject and style != psMinimal) or
|
||||||
style in [ypsJson, ypsCanonical]:
|
style in [psJson, psCanonical]:
|
||||||
target.write("\x0A" & repeat(' ', indentation))
|
target.write("\x0A" & repeat(' ', indentation))
|
||||||
if style == ypsJson:
|
if style == psJson:
|
||||||
state = dFlowImplicitMapKey
|
state = dFlowImplicitMapKey
|
||||||
else:
|
else:
|
||||||
target.write("? ")
|
target.write("? ")
|
||||||
@ -102,29 +102,29 @@ proc startItem(target: Stream, style: YamlPresentationStyle, indentation: int,
|
|||||||
target.write("- ")
|
target.write("- ")
|
||||||
of dFlowSequenceStart:
|
of dFlowSequenceStart:
|
||||||
case style
|
case style
|
||||||
of ypsMinimal, ypsDefault:
|
of psMinimal, psDefault:
|
||||||
discard
|
discard
|
||||||
of ypsCanonical, ypsJson:
|
of psCanonical, psJson:
|
||||||
target.write('\x0A')
|
target.write('\x0A')
|
||||||
target.write(repeat(' ', indentation))
|
target.write(repeat(' ', indentation))
|
||||||
of ypsBlockOnly:
|
of psBlockOnly:
|
||||||
discard # can never happen
|
discard # can never happen
|
||||||
state = dFlowSequenceItem
|
state = dFlowSequenceItem
|
||||||
of dFlowSequenceItem:
|
of dFlowSequenceItem:
|
||||||
case style
|
case style
|
||||||
of ypsMinimal, ypsDefault:
|
of psMinimal, psDefault:
|
||||||
target.write(", ")
|
target.write(", ")
|
||||||
of ypsCanonical, ypsJson:
|
of psCanonical, psJson:
|
||||||
target.write(",\x0A")
|
target.write(",\x0A")
|
||||||
target.write(repeat(' ', indentation))
|
target.write(repeat(' ', indentation))
|
||||||
of ypsBlockOnly:
|
of psBlockOnly:
|
||||||
discard # can never happen
|
discard # can never happen
|
||||||
except:
|
except:
|
||||||
var e = newException(YamlPresenterOutputError, "")
|
var e = newException(YamlPresenterOutputError, "")
|
||||||
e.cause = getCurrentException()
|
e.cause = getCurrentException()
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
proc writeTagAndAnchor(target: Stream, tag: TagId, tagLib: YamlTagLibrary,
|
proc writeTagAndAnchor(target: Stream, tag: TagId, tagLib: TagLibrary,
|
||||||
anchor: AnchorId) {.raises:[YamlPresenterOutputError].} =
|
anchor: AnchorId) {.raises:[YamlPresenterOutputError].} =
|
||||||
try:
|
try:
|
||||||
if tag notin [yTagQuestionMark, yTagExclamationMark]:
|
if tag notin [yTagQuestionMark, yTagExclamationMark]:
|
||||||
@ -150,8 +150,8 @@ proc writeTagAndAnchor(target: Stream, tag: TagId, tagLib: YamlTagLibrary,
|
|||||||
e.cause = getCurrentException()
|
e.cause = getCurrentException()
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
proc present*(s: YamlStream, target: Stream, tagLib: TagLibrary,
|
||||||
style: YamlPresentationStyle = ypsDefault,
|
style: PresentationStyle = psDefault,
|
||||||
indentationStep: int = 2) =
|
indentationStep: int = 2) =
|
||||||
var
|
var
|
||||||
cached = initQueue[YamlStreamEvent]()
|
cached = initQueue[YamlStreamEvent]()
|
||||||
@ -174,7 +174,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
for item in cacheIterator():
|
for item in cacheIterator():
|
||||||
case item.kind
|
case item.kind
|
||||||
of yamlStartDocument:
|
of yamlStartDocument:
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
# TODO: tag directives
|
# TODO: tag directives
|
||||||
try:
|
try:
|
||||||
target.write("%YAML 1.2\x0A")
|
target.write("%YAML 1.2\x0A")
|
||||||
@ -188,16 +188,16 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
raise e
|
raise e
|
||||||
of yamlScalar:
|
of yamlScalar:
|
||||||
if levels.len == 0:
|
if levels.len == 0:
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
safeWrite('\x0A')
|
safeWrite('\x0A')
|
||||||
else:
|
else:
|
||||||
startItem(target, style, indentation, levels[levels.high],
|
startItem(target, style, indentation, levels[levels.high],
|
||||||
false)
|
false)
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
writeTagAndAnchor(target,
|
writeTagAndAnchor(target,
|
||||||
item.scalarTag, tagLib, item.scalarAnchor)
|
item.scalarTag, tagLib, item.scalarAnchor)
|
||||||
|
|
||||||
if style == ypsJson:
|
if style == psJson:
|
||||||
let hint = guessType(item.scalarContent)
|
let hint = guessType(item.scalarContent)
|
||||||
if item.scalarTag in [yTagQuestionMark, yTagBoolean] and
|
if item.scalarTag in [yTagQuestionMark, yTagBoolean] and
|
||||||
hint in [yTypeBoolTrue, yTypeBoolFalse]:
|
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!")
|
"Infinity and not-a-number values cannot be presented as JSON!")
|
||||||
else:
|
else:
|
||||||
writeDoubleQuoted(item.scalarContent, target)
|
writeDoubleQuoted(item.scalarContent, target)
|
||||||
elif style == ypsCanonical or item.scalarContent.needsEscaping:
|
elif style == psCanonical or item.scalarContent.needsEscaping:
|
||||||
writeDoubleQuoted(item.scalarContent, target)
|
writeDoubleQuoted(item.scalarContent, target)
|
||||||
else:
|
else:
|
||||||
safeWrite(item.scalarContent)
|
safeWrite(item.scalarContent)
|
||||||
of yamlAlias:
|
of yamlAlias:
|
||||||
if style == ypsJson:
|
if style == psJson:
|
||||||
raise newException(YamlPresenterJsonError,
|
raise newException(YamlPresenterJsonError,
|
||||||
"Alias not allowed in JSON output")
|
"Alias not allowed in JSON output")
|
||||||
assert levels.len > 0
|
assert levels.len > 0
|
||||||
@ -234,7 +234,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
of yamlStartSequence:
|
of yamlStartSequence:
|
||||||
var nextState: DumperState
|
var nextState: DumperState
|
||||||
case style
|
case style
|
||||||
of ypsDefault:
|
of psDefault:
|
||||||
var length = 0
|
var length = 0
|
||||||
while true:
|
while true:
|
||||||
try:
|
try:
|
||||||
@ -257,38 +257,38 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
raise e
|
raise e
|
||||||
nextState = if length <= 60: dFlowSequenceStart else:
|
nextState = if length <= 60: dFlowSequenceStart else:
|
||||||
dBlockSequenceItem
|
dBlockSequenceItem
|
||||||
of ypsJson:
|
of psJson:
|
||||||
if levels.len > 0 and levels[levels.high] in
|
if levels.len > 0 and levels[levels.high] in
|
||||||
[dFlowMapStart, dFlowMapValue]:
|
[dFlowMapStart, dFlowMapValue]:
|
||||||
raise newException(YamlPresenterJsonError,
|
raise newException(YamlPresenterJsonError,
|
||||||
"Cannot have sequence as map key in JSON output!")
|
"Cannot have sequence as map key in JSON output!")
|
||||||
nextState = dFlowSequenceStart
|
nextState = dFlowSequenceStart
|
||||||
of ypsMinimal, ypsCanonical:
|
of psMinimal, psCanonical:
|
||||||
nextState = dFlowSequenceStart
|
nextState = dFlowSequenceStart
|
||||||
of ypsBlockOnly:
|
of psBlockOnly:
|
||||||
nextState = dBlockSequenceItem
|
nextState = dBlockSequenceItem
|
||||||
|
|
||||||
if levels.len == 0:
|
if levels.len == 0:
|
||||||
if nextState == dBlockSequenceItem:
|
if nextState == dBlockSequenceItem:
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
writeTagAndAnchor(target,
|
writeTagAndAnchor(target,
|
||||||
item.seqTag, tagLib, item.seqAnchor)
|
item.seqTag, tagLib, item.seqAnchor)
|
||||||
else:
|
else:
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
writeTagAndAnchor(target,
|
writeTagAndAnchor(target,
|
||||||
item.seqTag, tagLib, item.seqAnchor)
|
item.seqTag, tagLib, item.seqAnchor)
|
||||||
safeWrite('\x0A')
|
safeWrite('\x0A')
|
||||||
indentation += indentationStep
|
indentation += indentationStep
|
||||||
else:
|
else:
|
||||||
startItem(target, style, indentation, levels[levels.high], true)
|
startItem(target, style, indentation, levels[levels.high], true)
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
writeTagAndAnchor(target,
|
writeTagAndAnchor(target,
|
||||||
item.seqTag, tagLib, item.seqAnchor)
|
item.seqTag, tagLib, item.seqAnchor)
|
||||||
indentation += indentationStep
|
indentation += indentationStep
|
||||||
|
|
||||||
if nextState == dFlowSequenceStart:
|
if nextState == dFlowSequenceStart:
|
||||||
safeWrite('[')
|
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
|
levels[levels.high] in
|
||||||
[dBlockExplicitMapKey, dBlockMapValue,
|
[dBlockExplicitMapKey, dBlockMapValue,
|
||||||
dBlockImplicitMapKey, dBlockSequenceItem]:
|
dBlockImplicitMapKey, dBlockSequenceItem]:
|
||||||
@ -297,7 +297,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
of yamlStartMap:
|
of yamlStartMap:
|
||||||
var nextState: DumperState
|
var nextState: DumperState
|
||||||
case style
|
case style
|
||||||
of ypsDefault:
|
of psDefault:
|
||||||
type mapParseState = enum
|
type mapParseState = enum
|
||||||
mpInitial, mpKey, mpValue, mpNeedBlock
|
mpInitial, mpKey, mpValue, mpNeedBlock
|
||||||
var mps = mpInitial
|
var mps = mpInitial
|
||||||
@ -322,32 +322,32 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
raise e
|
raise e
|
||||||
nextState = if mps == mpNeedBlock: dBlockMapValue else:
|
nextState = if mps == mpNeedBlock: dBlockMapValue else:
|
||||||
dBlockInlineMap
|
dBlockInlineMap
|
||||||
of ypsMinimal:
|
of psMinimal:
|
||||||
nextState = dFlowMapStart
|
nextState = dFlowMapStart
|
||||||
of ypsCanonical:
|
of psCanonical:
|
||||||
nextState = dFlowMapStart
|
nextState = dFlowMapStart
|
||||||
of ypsJson:
|
of psJson:
|
||||||
if levels.len > 0 and levels[levels.high] in
|
if levels.len > 0 and levels[levels.high] in
|
||||||
[dFlowMapStart, dFlowMapValue]:
|
[dFlowMapStart, dFlowMapValue]:
|
||||||
raise newException(YamlPresenterJsonError,
|
raise newException(YamlPresenterJsonError,
|
||||||
"Cannot have map as map key in JSON output!")
|
"Cannot have map as map key in JSON output!")
|
||||||
nextState = dFlowMapStart
|
nextState = dFlowMapStart
|
||||||
of ypsBlockOnly:
|
of psBlockOnly:
|
||||||
nextState = dBlockMapValue
|
nextState = dBlockMapValue
|
||||||
if levels.len == 0:
|
if levels.len == 0:
|
||||||
if nextState == dBlockMapValue:
|
if nextState == dBlockMapValue:
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
writeTagAndAnchor(target,
|
writeTagAndAnchor(target,
|
||||||
item.mapTag, tagLib, item.mapAnchor)
|
item.mapTag, tagLib, item.mapAnchor)
|
||||||
else:
|
else:
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
safeWrite('\x0A')
|
safeWrite('\x0A')
|
||||||
writeTagAndAnchor(target,
|
writeTagAndAnchor(target,
|
||||||
item.mapTag, tagLib, item.mapAnchor)
|
item.mapTag, tagLib, item.mapAnchor)
|
||||||
indentation += indentationStep
|
indentation += indentationStep
|
||||||
else:
|
else:
|
||||||
if nextState in [dBlockMapValue, dBlockImplicitMapKey]:
|
if nextState in [dBlockMapValue, dBlockImplicitMapKey]:
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
writeTagAndAnchor(target,
|
writeTagAndAnchor(target,
|
||||||
item.mapTag, tagLib, item.mapAnchor)
|
item.mapTag, tagLib, item.mapAnchor)
|
||||||
startItem(target, style, indentation, levels[levels.high],
|
startItem(target, style, indentation, levels[levels.high],
|
||||||
@ -355,14 +355,14 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
else:
|
else:
|
||||||
startItem(target, style, indentation, levels[levels.high],
|
startItem(target, style, indentation, levels[levels.high],
|
||||||
true)
|
true)
|
||||||
if style != ypsJson:
|
if style != psJson:
|
||||||
writeTagAndAnchor(target,
|
writeTagAndAnchor(target,
|
||||||
item.mapTag, tagLib, item.mapAnchor)
|
item.mapTag, tagLib, item.mapAnchor)
|
||||||
indentation += indentationStep
|
indentation += indentationStep
|
||||||
|
|
||||||
if nextState == dFlowMapStart:
|
if nextState == dFlowMapStart:
|
||||||
safeWrite('{')
|
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
|
levels[levels.high] in
|
||||||
[dBlockExplicitMapKey, dBlockMapValue,
|
[dBlockExplicitMapKey, dBlockMapValue,
|
||||||
dBlockImplicitMapKey, dBlockSequenceItem]:
|
dBlockImplicitMapKey, dBlockSequenceItem]:
|
||||||
@ -374,9 +374,9 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
case levels.pop()
|
case levels.pop()
|
||||||
of dFlowSequenceItem:
|
of dFlowSequenceItem:
|
||||||
case style
|
case style
|
||||||
of ypsDefault, ypsMinimal, ypsBlockOnly:
|
of psDefault, psMinimal, psBlockOnly:
|
||||||
safeWrite(']')
|
safeWrite(']')
|
||||||
of ypsJson, ypsCanonical:
|
of psJson, psCanonical:
|
||||||
indentation -= indentationStep
|
indentation -= indentationStep
|
||||||
try:
|
try:
|
||||||
target.write('\x0A')
|
target.write('\x0A')
|
||||||
@ -391,7 +391,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
dBlockImplicitMapKey, dBlockSequenceItem]:
|
dBlockImplicitMapKey, dBlockSequenceItem]:
|
||||||
continue
|
continue
|
||||||
of dFlowSequenceStart:
|
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
|
levels[levels.high] in
|
||||||
[dBlockExplicitMapKey, dBlockMapValue,
|
[dBlockExplicitMapKey, dBlockMapValue,
|
||||||
dBlockImplicitMapKey, dBlockSequenceItem]:
|
dBlockImplicitMapKey, dBlockSequenceItem]:
|
||||||
@ -408,9 +408,9 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
case level
|
case level
|
||||||
of dFlowMapValue:
|
of dFlowMapValue:
|
||||||
case style
|
case style
|
||||||
of ypsDefault, ypsMinimal, ypsBlockOnly:
|
of psDefault, psMinimal, psBlockOnly:
|
||||||
safeWrite('}')
|
safeWrite('}')
|
||||||
of ypsJson, ypsCanonical:
|
of psJson, psCanonical:
|
||||||
indentation -= indentationStep
|
indentation -= indentationStep
|
||||||
try:
|
try:
|
||||||
target.write('\x0A')
|
target.write('\x0A')
|
||||||
@ -425,7 +425,7 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
dBlockImplicitMapKey, dBlockSequenceItem]:
|
dBlockImplicitMapKey, dBlockSequenceItem]:
|
||||||
continue
|
continue
|
||||||
of dFlowMapStart:
|
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
|
levels[levels.high] in
|
||||||
[dBlockExplicitMapKey, dBlockMapValue,
|
[dBlockExplicitMapKey, dBlockMapValue,
|
||||||
dBlockImplicitMapKey, dBlockSequenceItem]:
|
dBlockImplicitMapKey, dBlockSequenceItem]:
|
||||||
@ -448,13 +448,13 @@ proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
|||||||
raise e
|
raise e
|
||||||
safeWrite("...\x0A")
|
safeWrite("...\x0A")
|
||||||
|
|
||||||
proc transform*(input: Stream, output: Stream, style: YamlPresentationStyle,
|
proc transform*(input: Stream, output: Stream, style: PresentationStyle,
|
||||||
indentationStep: int = 2) =
|
indentationStep: int = 2) =
|
||||||
var
|
var
|
||||||
tagLib = extendedTagLibrary()
|
tagLib = extendedTagLibrary
|
||||||
parser = newParser(tagLib)
|
parser = newParser(tagLib)
|
||||||
events = parser.parse(input)
|
events = parser.parse(input)
|
||||||
if style == ypsCanonical:
|
if style == psCanonical:
|
||||||
var specificTagEvents = iterator(): YamlStreamEvent =
|
var specificTagEvents = iterator(): YamlStreamEvent =
|
||||||
for e in events():
|
for e in events():
|
||||||
var event = e
|
var event = e
|
||||||
|
@ -4,23 +4,23 @@
|
|||||||
# See the file "copying.txt", included in this
|
# See the file "copying.txt", included in this
|
||||||
# distribution, for details about the copyright.
|
# distribution, for details about the copyright.
|
||||||
|
|
||||||
proc initTagLibrary*(): YamlTagLibrary =
|
proc initTagLibrary*(): TagLibrary =
|
||||||
result.tags = initTable[string, TagId]()
|
result.tags = initTable[string, TagId]()
|
||||||
result.nextCustomTagId = yFirstCustomTagId
|
result.nextCustomTagId = yFirstCustomTagId
|
||||||
result.secondaryPrefix = yamlTagRepositoryPrefix
|
result.secondaryPrefix = yamlTagRepositoryPrefix
|
||||||
|
|
||||||
proc registerUri*(tagLib: var YamlTagLibrary, uri: string): TagId =
|
proc registerUri*(tagLib: var TagLibrary, uri: string): TagId =
|
||||||
tagLib.tags[uri] = tagLib.nextCustomTagId
|
tagLib.tags[uri] = tagLib.nextCustomTagId
|
||||||
result = tagLib.nextCustomTagId
|
result = tagLib.nextCustomTagId
|
||||||
tagLib.nextCustomTagId = cast[TagId](cast[int](tagLib.nextCustomTagId) + 1)
|
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:
|
for iUri, iId in tagLib.tags.pairs:
|
||||||
if iId == id:
|
if iId == id:
|
||||||
return iUri
|
return iUri
|
||||||
raise newException(KeyError, "Unknown tag id: " & $id)
|
raise newException(KeyError, "Unknown tag id: " & $id)
|
||||||
|
|
||||||
proc failsafeTagLibrary*(): YamlTagLibrary =
|
proc initFailsafeTagLibrary(): TagLibrary =
|
||||||
result = initTagLibrary()
|
result = initTagLibrary()
|
||||||
result.tags["!"] = yTagExclamationMark
|
result.tags["!"] = yTagExclamationMark
|
||||||
result.tags["?"] = yTagQuestionMark
|
result.tags["?"] = yTagQuestionMark
|
||||||
@ -28,15 +28,15 @@ proc failsafeTagLibrary*(): YamlTagLibrary =
|
|||||||
result.tags["tag:yaml.org,2002:seq"] = yTagSequence
|
result.tags["tag:yaml.org,2002:seq"] = yTagSequence
|
||||||
result.tags["tag:yaml.org,2002:map"] = yTagMap
|
result.tags["tag:yaml.org,2002:map"] = yTagMap
|
||||||
|
|
||||||
proc coreTagLibrary*(): YamlTagLibrary =
|
proc initCoreTagLibrary(): TagLibrary =
|
||||||
result = failsafeTagLibrary()
|
result = initFailsafeTagLibrary()
|
||||||
result.tags["tag:yaml.org,2002:null"] = yTagNull
|
result.tags["tag:yaml.org,2002:null"] = yTagNull
|
||||||
result.tags["tag:yaml.org,2002:bool"] = yTagBoolean
|
result.tags["tag:yaml.org,2002:bool"] = yTagBoolean
|
||||||
result.tags["tag:yaml.org,2002:int"] = yTagInteger
|
result.tags["tag:yaml.org,2002:int"] = yTagInteger
|
||||||
result.tags["tag:yaml.org,2002:float"] = yTagFloat
|
result.tags["tag:yaml.org,2002:float"] = yTagFloat
|
||||||
|
|
||||||
proc extendedTagLibrary*(): YamlTagLibrary =
|
proc initExtendedTagLibrary(): TagLibrary =
|
||||||
result = coreTagLibrary()
|
result = initCoreTagLibrary()
|
||||||
result.tags["tag:yaml.org,2002:omap"] = yTagOrderedMap
|
result.tags["tag:yaml.org,2002:omap"] = yTagOrderedMap
|
||||||
result.tags["tag:yaml.org,2002:pairs"] = yTagPairs
|
result.tags["tag:yaml.org,2002:pairs"] = yTagPairs
|
||||||
result.tags["tag:yaml.org,2002:binary"] = yTagBinary
|
result.tags["tag:yaml.org,2002:binary"] = yTagBinary
|
||||||
|
@ -109,7 +109,7 @@ template ensure(input: string, expected: varargs[YamlStreamEvent]) {.dirty.} =
|
|||||||
|
|
||||||
suite "Parsing":
|
suite "Parsing":
|
||||||
setup:
|
setup:
|
||||||
var tagLib = coreTagLibrary()
|
var tagLib = coreTagLibrary
|
||||||
teardown:
|
teardown:
|
||||||
discard
|
discard
|
||||||
|
|
||||||
|
@ -26,7 +26,7 @@ suite "Serialization":
|
|||||||
test "Serialization: Serialize string sequence":
|
test "Serialization: Serialize string sequence":
|
||||||
var input = @["a", "b"]
|
var input = @["a", "b"]
|
||||||
var output = newStringStream()
|
var output = newStringStream()
|
||||||
dump(input, output, ypsBlockOnly, ytsNone)
|
dump(input, output, psBlockOnly, tsNone)
|
||||||
assert output.data == "%YAML 1.2\n--- \n- a\n- b"
|
assert output.data == "%YAML 1.2\n--- \n- a\n- b"
|
||||||
|
|
||||||
test "Serialization: Load Table[int, string]":
|
test "Serialization: Load Table[int, string]":
|
||||||
@ -46,7 +46,7 @@ suite "Serialization":
|
|||||||
input[23] = "dreiundzwanzig"
|
input[23] = "dreiundzwanzig"
|
||||||
input[42] = "zweiundvierzig"
|
input[42] = "zweiundvierzig"
|
||||||
var output = newStringStream()
|
var output = newStringStream()
|
||||||
dump(input, output, ypsBlockOnly, ytsNone)
|
dump(input, output, psBlockOnly, tsNone)
|
||||||
assert output.data == "%YAML 1.2\n--- \n23: dreiundzwanzig\n42: zweiundvierzig"
|
assert output.data == "%YAML 1.2\n--- \n23: dreiundzwanzig\n42: zweiundvierzig"
|
||||||
|
|
||||||
test "Serialization: Load Sequences in Sequence":
|
test "Serialization: Load Sequences in Sequence":
|
||||||
@ -65,7 +65,7 @@ suite "Serialization":
|
|||||||
test "Serialization: Serialize Sequences in Sequence":
|
test "Serialization: Serialize Sequences in Sequence":
|
||||||
let input = @[@[1, 2, 3], @[4, 5], @[6]]
|
let input = @[@[1, 2, 3], @[4, 5], @[6]]
|
||||||
var output = newStringStream()
|
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]"
|
assert output.data == "%YAML 1.2\n--- \n- [1, 2, 3]\n- [4, 5]\n- [6]"
|
||||||
|
|
||||||
test "Serialization: Load custom object":
|
test "Serialization: Load custom object":
|
||||||
@ -83,7 +83,7 @@ suite "Serialization":
|
|||||||
test "Serialization: Serialize custom object":
|
test "Serialization: Serialize custom object":
|
||||||
let input = Person(firstname: "Peter", surname: "Pan", age: 12)
|
let input = Person(firstname: "Peter", surname: "Pan", age: 12)
|
||||||
var output = newStringStream()
|
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"
|
assert output.data == "%YAML 1.2\n--- \nfirstname: Peter\nsurname: Pan\nage: 12"
|
||||||
|
|
||||||
test "Serialization: Load sequence with explicit tags":
|
test "Serialization: Load sequence with explicit tags":
|
||||||
@ -101,7 +101,7 @@ suite "Serialization":
|
|||||||
test "Serialization: Serialize sequence with explicit tags":
|
test "Serialization: Serialize sequence with explicit tags":
|
||||||
let input = @["one", "two"]
|
let input = @["one", "two"]
|
||||||
var output = newStringStream()
|
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"
|
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":
|
test "Serialization: Load custom object with explicit root tag":
|
||||||
@ -120,5 +120,5 @@ suite "Serialization":
|
|||||||
test "Serialization: Serialize custom object with explicit root tag":
|
test "Serialization: Serialize custom object with explicit root tag":
|
||||||
let input = Person(firstname: "Peter", surname: "Pan", age: 12)
|
let input = Person(firstname: "Peter", surname: "Pan", age: 12)
|
||||||
var output = newStringStream()
|
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"
|
assert output.data == "%YAML 1.2\n--- !nim:Person \nfirstname: Peter\nsurname: Pan\nage: 12"
|
90
yaml.nim
90
yaml.nim
@ -110,7 +110,7 @@ type
|
|||||||
## always yield a well-formed ``YamlStream`` and expect it to be
|
## always yield a well-formed ``YamlStream`` and expect it to be
|
||||||
## well-formed if it's an input.
|
## well-formed if it's an input.
|
||||||
|
|
||||||
YamlTagLibrary* = object
|
TagLibrary* = object
|
||||||
## A ``YamlTagLibrary`` maps tag URIs to ``TagId`` s. YAML tag URIs
|
## A ``YamlTagLibrary`` maps tag URIs to ``TagId`` s. YAML tag URIs
|
||||||
## that are defined in the YAML specification or in the
|
## that are defined in the YAML specification or in the
|
||||||
## `YAML tag repository <http://yaml.org/type/>`_ should be mapped to
|
## `YAML tag repository <http://yaml.org/type/>`_ should be mapped to
|
||||||
@ -135,7 +135,7 @@ type
|
|||||||
nextCustomTagId*: TagId
|
nextCustomTagId*: TagId
|
||||||
secondaryPrefix*: string
|
secondaryPrefix*: string
|
||||||
|
|
||||||
YamlWarningCallback* = proc(line, column: int, lineContent: string,
|
WarningCallback* = proc(line, column: int, lineContent: string,
|
||||||
message: string)
|
message: string)
|
||||||
## Callback for parser warnings. Currently, this callback may be called
|
## Callback for parser warnings. Currently, this callback may be called
|
||||||
## on two occasions while parsing a YAML document stream:
|
## on two occasions while parsing a YAML document stream:
|
||||||
@ -144,17 +144,17 @@ type
|
|||||||
## ``1.2``.
|
## ``1.2``.
|
||||||
## - If there is an unknown directive encountered.
|
## - If there is an unknown directive encountered.
|
||||||
|
|
||||||
YamlSequentialParser* = ref object
|
YamlParser* = ref object
|
||||||
## A parser object. Retains its ``YamlTagLibrary`` across calls to
|
## A parser object. Retains its ``YamlTagLibrary`` across calls to
|
||||||
## `parse <#parse,YamlSequentialParser,Stream,YamlStream>`_. Can be used
|
## `parse <#parse,YamlSequentialParser,Stream,YamlStream>`_. Can be used
|
||||||
## to access anchor names while parsing a YAML character stream, but
|
## to access anchor names while parsing a YAML character stream, but
|
||||||
## only until the document goes out of scope (i.e. until
|
## only until the document goes out of scope (i.e. until
|
||||||
## ``yamlEndDocument`` is yielded).
|
## ``yamlEndDocument`` is yielded).
|
||||||
tagLib: YamlTagLibrary
|
tagLib: TagLibrary
|
||||||
anchors: OrderedTable[string, AnchorId]
|
anchors: OrderedTable[string, AnchorId]
|
||||||
callback: YamlWarningCallback
|
callback: WarningCallback
|
||||||
|
|
||||||
YamlPresentationStyle* = enum
|
PresentationStyle* = enum
|
||||||
## Different styles for YAML character stream output.
|
## Different styles for YAML character stream output.
|
||||||
##
|
##
|
||||||
## - ``ypsMinimal``: Single-line flow-only output which tries to
|
## - ``ypsMinimal``: Single-line flow-only output which tries to
|
||||||
@ -172,7 +172,7 @@ type
|
|||||||
## contain one document.
|
## contain one document.
|
||||||
## - ``ypsBlockOnly``: Formats all output in block style, does not use
|
## - ``ypsBlockOnly``: Formats all output in block style, does not use
|
||||||
## flow style at all.
|
## flow style at all.
|
||||||
ypsMinimal, ypsCanonical, ypsDefault, ypsJson, ypsBlockOnly
|
psMinimal, psCanonical, psDefault, psJson, psBlockOnly
|
||||||
|
|
||||||
YamlLoadingError* = object of Exception
|
YamlLoadingError* = object of Exception
|
||||||
## Base class for all exceptions that may be raised during the process
|
## 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 `$`*(id: AnchorId): string {.borrow.}
|
||||||
proc hash*(id: AnchorId): Hash {.borrow.}
|
proc hash*(id: AnchorId): Hash {.borrow.}
|
||||||
|
|
||||||
proc initTagLibrary*(): YamlTagLibrary
|
proc initTagLibrary*(): TagLibrary
|
||||||
## initializes the ``tags`` table and sets ``nextCustomTagId`` to
|
## initializes the ``tags`` table and sets ``nextCustomTagId`` to
|
||||||
## ``yFirstCustomTagId``.
|
## ``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
|
## registers a custom tag URI with a ``YamlTagLibrary``. The URI will get
|
||||||
## the ``TagId`` ``nextCustomTagId``, which will be incremented.
|
## 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.
|
## retrieve the URI a ``TagId`` maps to.
|
||||||
|
|
||||||
# these should be consts, but the Nim VM still has problems handling tables
|
# 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
|
proc initFailsafeTagLibrary(): TagLibrary
|
||||||
## Contains only:
|
proc initCoreTagLibrary(): TagLibrary
|
||||||
## - ``!``
|
proc initExtendedTagLibrary(): TagLibrary
|
||||||
## - ``?``
|
|
||||||
## - ``!!str``
|
let
|
||||||
## - ``!!map``
|
failsafeTagLibrary*: TagLibrary = initFailsafeTagLibrary() ## \
|
||||||
## - ``!!seq``
|
## Contains only:
|
||||||
|
## - ``!``
|
||||||
proc coreTagLibrary*(): YamlTagLibrary
|
## - ``?``
|
||||||
## Contains everything in ``failsafeTagLibrary`` plus:
|
## - ``!!str``
|
||||||
## - ``!!null``
|
## - ``!!map``
|
||||||
## - ``!!bool``
|
## - ``!!seq``
|
||||||
## - ``!!int``
|
coreTagLibrary*: TagLibrary = initCoreTagLibrary() ## \
|
||||||
## - ``!!float``
|
## Contains everything in ``failsafeTagLibrary`` plus:
|
||||||
|
## - ``!!null``
|
||||||
proc extendedTagLibrary*(): YamlTagLibrary
|
## - ``!!bool``
|
||||||
## Contains everything in ``coreTagLibrary`` plus:
|
## - ``!!int``
|
||||||
## - ``!!omap``
|
## - ``!!float``
|
||||||
## - ``!!pairs``
|
extendedTagLibrary*: TagLibrary = initExtendedTagLibrary() ## \
|
||||||
## - ``!!set``
|
## Contains everything in ``coreTagLibrary`` plus:
|
||||||
## - ``!!binary``
|
## - ``!!omap``
|
||||||
## - ``!!merge``
|
## - ``!!pairs``
|
||||||
## - ``!!timestamp``
|
## - ``!!set``
|
||||||
## - ``!!value``
|
## - ``!!binary``
|
||||||
## - ``!!yaml``
|
## - ``!!merge``
|
||||||
|
## - ``!!timestamp``
|
||||||
|
## - ``!!value``
|
||||||
|
## - ``!!yaml``
|
||||||
|
|
||||||
proc guessType*(scalar: string): TypeHint {.raises: [].}
|
proc guessType*(scalar: string): TypeHint {.raises: [].}
|
||||||
|
|
||||||
proc newParser*(tagLib: YamlTagLibrary): YamlSequentialParser
|
proc newParser*(tagLib: TagLibrary): YamlParser
|
||||||
## Instanciates a parser
|
## Instanciates a parser
|
||||||
|
|
||||||
proc setWarningCallback*(parser: YamlSequentialParser,
|
proc setWarningCallback*(parser: YamlParser, callback: WarningCallback)
|
||||||
callback: YamlWarningCallback)
|
|
||||||
|
|
||||||
proc anchor*(parser: YamlSequentialParser, id: AnchorId): string
|
proc anchor*(parser: YamlParser, id: AnchorId): string
|
||||||
## Get the anchor name which an ``AnchorId`` maps to
|
## 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].}
|
YamlStream {.raises: [IOError, YamlParserError].}
|
||||||
## Parse a YAML character stream. ``s`` must be readable.
|
## 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
|
## `constructJson <#constructJson>`_ to construct an in-memory JSON tree
|
||||||
## from a YAML character stream.
|
## from a YAML character stream.
|
||||||
|
|
||||||
proc present*(s: YamlStream, target: Stream, tagLib: YamlTagLibrary,
|
proc present*(s: YamlStream, target: Stream, tagLib: TagLibrary,
|
||||||
style: YamlPresentationStyle = ypsDefault,
|
style: PresentationStyle = psDefault,
|
||||||
indentationStep: int = 2) {.raises: [YamlPresenterJsonError,
|
indentationStep: int = 2) {.raises: [YamlPresenterJsonError,
|
||||||
YamlPresenterOutputError,
|
YamlPresenterOutputError,
|
||||||
YamlPresenterStreamError].}
|
YamlPresenterStreamError].}
|
||||||
## Convert ``s`` to a YAML character stream and write it to ``target``.
|
## 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)
|
indentationStep: int = 2)
|
||||||
## Parser ``input`` as YAML character stream and then dump it to ``output``
|
## Parser ``input`` as YAML character stream and then dump it to ``output``
|
||||||
## without resolving any tags, anchors and aliases.
|
## without resolving any tags, anchors and aliases.
|
||||||
|
@ -3,12 +3,10 @@ import macros, strutils, streams, tables, json, hashes, re
|
|||||||
export yaml, streams, tables, json
|
export yaml, streams, tables, json
|
||||||
|
|
||||||
type
|
type
|
||||||
YamlTagStyle* = enum
|
TagStyle* = enum
|
||||||
ytsNone,
|
tsNone, tsRootOnly, tsAll
|
||||||
ytsRootOnly,
|
|
||||||
ytsAll
|
|
||||||
|
|
||||||
proc initSerializationTagLibrary(): YamlTagLibrary =
|
proc initSerializationTagLibrary(): TagLibrary =
|
||||||
result = initTagLibrary()
|
result = initTagLibrary()
|
||||||
result.tags["!"] = yTagExclamationMark
|
result.tags["!"] = yTagExclamationMark
|
||||||
result.tags["?"] = yTagQuestionMark
|
result.tags["?"] = yTagQuestionMark
|
||||||
@ -41,8 +39,8 @@ static:
|
|||||||
|
|
||||||
var existingTuples = newSeq[NimNode]()
|
var existingTuples = newSeq[NimNode]()
|
||||||
|
|
||||||
template presentTag(t: typedesc, tagStyle: YamlTagStyle): TagId =
|
template presentTag(t: typedesc, tagStyle: TagStyle): TagId =
|
||||||
if tagStyle == ytsNone: yTagQuestionMark else: yamlTag(t)
|
if tagStyle == tsNone: yTagQuestionMark else: yamlTag(t)
|
||||||
|
|
||||||
proc lazyLoadTag*(uri: string): TagId {.inline.} =
|
proc lazyLoadTag*(uri: string): TagId {.inline.} =
|
||||||
try:
|
try:
|
||||||
@ -158,14 +156,14 @@ macro make_serializable*(types: stmt): stmt =
|
|||||||
newIdentNode("YamlStream"),
|
newIdentNode("YamlStream"),
|
||||||
newIdentDefs(newIdentNode("value"), tIdent),
|
newIdentDefs(newIdentNode("value"), tIdent),
|
||||||
newIdentDefs(newIdentNode("tagStyle"),
|
newIdentDefs(newIdentNode("tagStyle"),
|
||||||
newIdentNode("YamlTagStyle"),
|
newIdentNode("TagStyle"),
|
||||||
newIdentNode("ytsNone"))])
|
newIdentNode("tsNone"))])
|
||||||
var iterBody = newStmtList(
|
var iterBody = newStmtList(
|
||||||
newLetStmt(newIdentNode("childTagStyle"), newNimNode(nnkIfExpr).add(
|
newLetStmt(newIdentNode("childTagStyle"), newNimNode(nnkIfExpr).add(
|
||||||
newNimNode(nnkElifExpr).add(
|
newNimNode(nnkElifExpr).add(
|
||||||
newNimNode(nnkInfix).add(newIdentNode("=="),
|
newNimNode(nnkInfix).add(newIdentNode("=="),
|
||||||
newIdentNode("tagStyle"), newIdentNode("ytsRootOnly")),
|
newIdentNode("tagStyle"), newIdentNode("tsRootOnly")),
|
||||||
newIdentNode("ytsNone")
|
newIdentNode("tsNone")
|
||||||
), newNimNode(nnkElseExpr).add(newIdentNode("tagStyle")))),
|
), newNimNode(nnkElseExpr).add(newIdentNode("tagStyle")))),
|
||||||
newNimNode(nnkYieldStmt).add(
|
newNimNode(nnkYieldStmt).add(
|
||||||
newNimNode(nnkObjConstr).add(newIdentNode("YamlStreamEvent"),
|
newNimNode(nnkObjConstr).add(newIdentNode("YamlStreamEvent"),
|
||||||
@ -175,7 +173,7 @@ macro make_serializable*(types: stmt): stmt =
|
|||||||
newNimNode(nnkIfExpr).add(newNimNode(nnkElifExpr).add(
|
newNimNode(nnkIfExpr).add(newNimNode(nnkElifExpr).add(
|
||||||
newNimNode(nnkInfix).add(newIdentNode("=="),
|
newNimNode(nnkInfix).add(newIdentNode("=="),
|
||||||
newIdentNode("tagStyle"),
|
newIdentNode("tagStyle"),
|
||||||
newIdentNode("ytsNone")),
|
newIdentNode("tsNone")),
|
||||||
newIdentNode("yTagQuestionMark")
|
newIdentNode("yTagQuestionMark")
|
||||||
), newNimNode(nnkElseExpr).add(
|
), newNimNode(nnkElseExpr).add(
|
||||||
newCall("yamlTag", newCall("type", tIdent))
|
newCall("yamlTag", newCall("type", tIdent))
|
||||||
@ -239,7 +237,7 @@ proc construct*(s: YamlStream, result: var string) =
|
|||||||
result = item.scalarContent
|
result = item.scalarContent
|
||||||
|
|
||||||
proc serialize*(value: string,
|
proc serialize*(value: string,
|
||||||
tagStyle: YamlTagStyle = ytsNone): YamlStream =
|
tagStyle: TagStyle = tsNone): YamlStream =
|
||||||
result = iterator(): YamlStreamEvent =
|
result = iterator(): YamlStreamEvent =
|
||||||
yield scalarEvent(value, presentTag(string, tagStyle), yAnchorNone)
|
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.")
|
raise newException(ValueError, "Wrong scalar type for int.")
|
||||||
result = parseInt(item.scalarContent)
|
result = parseInt(item.scalarContent)
|
||||||
|
|
||||||
proc serialize*(value: int,
|
proc serialize*(value: int, tagStyle: TagStyle = tsNone): YamlStream =
|
||||||
tagStyle: YamlTagStyle = ytsNone): YamlStream =
|
|
||||||
result = iterator(): YamlStreamEvent =
|
result = iterator(): YamlStreamEvent =
|
||||||
yield scalarEvent($value, presentTag(int, tagStyle), yAnchorNone)
|
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.")
|
raise newException(ValueError, "Wrong scalar type for int64.")
|
||||||
result = parseBiggestInt(item.scalarContent)
|
result = parseBiggestInt(item.scalarContent)
|
||||||
|
|
||||||
proc serialize*(value: int64,
|
proc serialize*(value: int64, tagStyle: TagStyle = tsNone): YamlStream =
|
||||||
tagStyle: YamlTagStyle = ytsNone): YamlStream =
|
|
||||||
result = iterator(): YamlStreamEvent =
|
result = iterator(): YamlStreamEvent =
|
||||||
yield scalarEvent($value, presentTag(int64, tagStyle), yAnchorNone)
|
yield scalarEvent($value, presentTag(int64, tagStyle), yAnchorNone)
|
||||||
|
|
||||||
@ -301,7 +297,7 @@ proc construct*(s: YamlStream, result: var float) =
|
|||||||
else:
|
else:
|
||||||
raise newException(ValueError, "Wrong scalar type for float.")
|
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 =
|
result = iterator(): YamlStreamEvent =
|
||||||
var
|
var
|
||||||
asString: string
|
asString: string
|
||||||
@ -336,8 +332,7 @@ proc construct*(s: YamlStream, result: var bool) =
|
|||||||
else:
|
else:
|
||||||
raise newException(ValueError, "Wrong scalar type for bool")
|
raise newException(ValueError, "Wrong scalar type for bool")
|
||||||
|
|
||||||
proc serialize*(value: bool,
|
proc serialize*(value: bool, tagStyle: TagStyle = tsNone): YamlStream =
|
||||||
tagStyle: YamlTagStyle = ytsNone): YamlStream =
|
|
||||||
result = iterator(): YamlStreamEvent =
|
result = iterator(): YamlStreamEvent =
|
||||||
yield scalarEvent(if value: "y" else: "n", presentTag(bool, tagStyle),
|
yield scalarEvent(if value: "y" else: "n", presentTag(bool, tagStyle),
|
||||||
yAnchorNone)
|
yAnchorNone)
|
||||||
@ -367,10 +362,9 @@ proc construct*[T](s: YamlStream, result: var seq[T]) =
|
|||||||
if finished(s):
|
if finished(s):
|
||||||
raise newException(ValueError, "Construction error!3")
|
raise newException(ValueError, "Construction error!3")
|
||||||
|
|
||||||
proc serialize*[T](value: seq[T],
|
proc serialize*[T](value: seq[T], tagStyle: TagStyle = tsNone): YamlStream =
|
||||||
tagStyle: YamlTagStyle = ytsNone): YamlStream =
|
|
||||||
result = iterator(): YamlStreamEvent =
|
result = iterator(): YamlStreamEvent =
|
||||||
let childTagStyle = if tagStyle == ytsRootOnly: ytsNone else: tagStyle
|
let childTagStyle = if tagStyle == tsRootOnly: tsNone else: tagStyle
|
||||||
yield YamlStreamEvent(kind: yamlStartSequence,
|
yield YamlStreamEvent(kind: yamlStartSequence,
|
||||||
seqTag: presentTag(seq[T], tagStyle),
|
seqTag: presentTag(seq[T], tagStyle),
|
||||||
seqAnchor: yAnchorNone)
|
seqAnchor: yAnchorNone)
|
||||||
@ -414,9 +408,9 @@ proc construct*[K, V](s: YamlStream, result: var Table[K, V]) =
|
|||||||
raise newException(ValueError, "Construction error!")
|
raise newException(ValueError, "Construction error!")
|
||||||
|
|
||||||
proc serialize*[K, V](value: Table[K, V],
|
proc serialize*[K, V](value: Table[K, V],
|
||||||
tagStyle: YamlTagStyle = ytsNone): YamlStream =
|
tagStyle: TagStyle = tsNone): YamlStream =
|
||||||
result = iterator(): YamlStreamEvent =
|
result = iterator(): YamlStreamEvent =
|
||||||
let childTagStyle = if tagStyle == ytsRootOnly: ytsNone else: tagStyle
|
let childTagStyle = if tagStyle == tsRootOnly: tsNone else: tagStyle
|
||||||
yield YamlStreamEvent(kind: yamlStartMap,
|
yield YamlStreamEvent(kind: yamlStartMap,
|
||||||
mapTag: presentTag(Table[K, V], tagStyle),
|
mapTag: presentTag(Table[K, V], tagStyle),
|
||||||
mapAnchor: yAnchorNone)
|
mapAnchor: yAnchorNone)
|
||||||
@ -437,11 +431,10 @@ proc load*[K](input: Stream, target: var K) =
|
|||||||
construct(events, target)
|
construct(events, target)
|
||||||
assert events().kind == yamlEndDocument
|
assert events().kind == yamlEndDocument
|
||||||
|
|
||||||
proc dump*[K](value: K, target: Stream,
|
proc dump*[K](value: K, target: Stream, style: PresentationStyle = psDefault,
|
||||||
style: YamlPresentationStyle = ypsDefault,
|
tagStyle: TagStyle = tsRootOnly, indentationStep: int = 2) =
|
||||||
tagStyle: YamlTagStyle = ytsRootOnly, indentationStep: int = 2) =
|
|
||||||
var serialized = serialize(value,
|
var serialized = serialize(value,
|
||||||
if style == ypsCanonical: ytsAll else: tagStyle)
|
if style == psCanonical: tsAll else: tagStyle)
|
||||||
var events = iterator(): YamlStreamEvent =
|
var events = iterator(): YamlStreamEvent =
|
||||||
yield YamlStreamEvent(kind: yamlStartDocument)
|
yield YamlStreamEvent(kind: yamlStartDocument)
|
||||||
for event in serialized():
|
for event in serialized():
|
||||||
|
Loading…
x
Reference in New Issue
Block a user