made lexer & parser tests compile (not succeed) again

This commit is contained in:
Felix Krause 2020-11-04 16:40:37 +01:00
parent 1d707b184e
commit 4c604b09df
9 changed files with 230 additions and 300 deletions

View File

@ -4,7 +4,7 @@
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
import "../yaml", strutils
import ../yaml, ../yaml/data
proc escapeNewlines(s: string): string =
result = ""
@ -15,46 +15,42 @@ proc escapeNewlines(s: string): string =
of '\\': result.add("\\\\")
else: result.add(c)
proc printDifference*(expected, actual: YamlStreamEvent) =
proc printDifference(expected, actual: Properties): bool =
result = false
if expected.tag != actual.tag:
echo "[scalar.tag] expected", $expected.tag, ", got", $actual.tag
result = true
if expected.anchor != actual.anchor:
echo "[scalar.anchor] expected", $expected.anchor, ", got", $actual.anchor
result = true
proc printDifference*(expected, actual: Event) =
if expected.kind != actual.kind:
echo "expected " & $expected.kind & ", got " & $actual.kind
else:
case expected.kind
of yamlScalar:
if expected.scalarTag != actual.scalarTag:
echo "[", escape(actual.scalarContent), ".tag] expected tag ",
expected.scalarTag, ", got ", actual.scalarTag
elif expected.scalarAnchor != actual.scalarAnchor:
echo "[scalarEvent] expected anchor ", expected.scalarAnchor,
", got ", actual.scalarAnchor
elif expected.scalarContent != actual.scalarContent:
let msg = "[scalarEvent] content mismatch!\nexpected: " &
escapeNewlines(expected.scalarContent) &
"\ngot : " & escapeNewlines(actual.scalarContent)
if expected.scalarContent.len != actual.scalarContent.len:
echo msg, "\n(length does not match)"
else:
for i in 0..expected.scalarContent.high:
if expected.scalarContent[i] != actual.scalarContent[i]:
echo msg, "\n(first different char at pos ", i, ": expected ",
cast[int](expected.scalarContent[i]), ", got ",
cast[int](actual.scalarContent[i]), ")"
break
else: echo "[scalarEvent] Unknown difference"
if not printDifference(expected.scalarProperties, actual.scalarProperties):
if expected.scalarContent != actual.scalarContent:
let msg = "[scalarEvent] content mismatch!\nexpected: " &
escapeNewlines(expected.scalarContent) &
"\ngot : " & escapeNewlines(actual.scalarContent)
if expected.scalarContent.len != actual.scalarContent.len:
echo msg, "\n(length does not match)"
else:
for i in 0..expected.scalarContent.high:
if expected.scalarContent[i] != actual.scalarContent[i]:
echo msg, "\n(first different char at pos ", i, ": expected ",
cast[int](expected.scalarContent[i]), ", got ",
cast[int](actual.scalarContent[i]), ")"
break
else: echo "[scalar] Unknown difference"
of yamlStartMap:
if expected.mapTag != actual.mapTag:
echo "[map.tag] expected ", expected.mapTag, ", got ", actual.mapTag
elif expected.mapAnchor != actual.mapAnchor:
echo "[map.anchor] expected ", expected.mapAnchor, ", got ",
actual.mapAnchor
else: echo "[map.tag] Unknown difference"
if not printDifference(expected.mapProperties, actual.mapProperties):
echo "[map] Unknown difference"
of yamlStartSeq:
if expected.seqTag != actual.seqTag:
echo "[seq.tag] expected ", expected.seqTag, ", got ", actual.seqTag
elif expected.seqAnchor != actual.seqAnchor:
echo "[seq.anchor] expected ", expected.seqAnchor, ", got ",
actual.seqAnchor
else: echo "[seq] Unknown difference"
if not printDifference(expected.seqProperties, actual.seqProperties):
echo "[seq] Unknown difference"
of yamlAlias:
if expected.aliasTarget != actual.aliasTarget:
echo "[alias] expected ", expected.aliasTarget, ", got ",
@ -63,7 +59,7 @@ proc printDifference*(expected, actual: YamlStreamEvent) =
else: echo "Unknown difference in event kind " & $expected.kind
template ensure*(input: var YamlStream,
expected: varargs[YamlStreamEvent]) {.dirty.} =
expected: varargs[Event]) {.dirty.} =
var i = 0
for token in input:
if i >= expected.len:

View File

@ -4,7 +4,7 @@
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
import "../yaml"
import ../yaml, ../yaml/data, ../yaml/private/internal
import lexbase, streams, tables, strutils
type
@ -19,7 +19,7 @@ type
EventLexer = object of BaseLexer
content: string
EventStreamError = object of Exception
EventStreamError = object of ValueError
proc nextToken(lex: var EventLexer): LexerToken =
while true:
@ -116,75 +116,74 @@ template yieldEvent() {.dirty.} =
template setTag(t: TagId) {.dirty.} =
case curEvent.kind
of yamlStartSeq: curEvent.seqTag = t
of yamlStartMap: curEvent.mapTag = t
of yamlScalar: curEvent.scalarTag = t
of yamlStartSeq: curEvent.seqProperties.tag = t
of yamlStartMap: curEvent.mapProperties.tag = t
of yamlScalar: curEvent.scalarProperties.tag = t
else: discard
template setAnchor(a: AnchorId) {.dirty.} =
template setAnchor(a: Anchor) {.dirty.} =
case curEvent.kind
of yamlStartSeq: curEvent.seqAnchor = a
of yamlStartMap: curEvent.mapAnchor = a
of yamlScalar: curEvent.scalarAnchor = a
of yamlStartSeq: curEvent.seqProperties.anchor = a
of yamlStartMap: curEvent.mapProperties.anchor = a
of yamlScalar: curEvent.scalarProperties.anchor = a
of yamlAlias: curEvent.aliasTarget = a
else: discard
template curTag(): TagId =
var foo: TagId
case curEvent.kind
of yamlStartSeq: foo = curEvent.seqTag
of yamlStartMap: foo = curEvent.mapTag
of yamlScalar: foo = curEvent.scalarTag
of yamlStartSeq: foo = curEvent.seqProperties.tag
of yamlStartMap: foo = curEvent.mapProperties.tag
of yamlScalar: foo = curEvent.scalarProperties.tag
else: raise newException(EventStreamError,
$curEvent.kind & " may not have a tag")
foo
template setCurTag(val: TagId) =
case curEvent.kind
of yamlStartSeq: curEvent.seqTag = val
of yamlStartMap: curEvent.mapTag = val
of yamlScalar: curEvent.scalarTag = val
of yamlStartSeq: curEvent.seqProperties.tag = val
of yamlStartMap: curEvent.mapProperties.tag = val
of yamlScalar: curEvent.scalarProperties.tag = val
else: raise newException(EventStreamError,
$curEvent.kind & " may not have a tag")
template curAnchor(): AnchorId =
var foo: AnchorId
template curAnchor(): Anchor =
var foo: Anchor
case curEvent.kind
of yamlStartSeq: foo = curEvent.seqAnchor
of yamlStartMap: foo = curEvent.mapAnchor
of yamlScalar: foo = curEvent.scalarAnchor
of yamlStartSeq: foo = curEvent.seqProperties.anchor
of yamlStartMap: foo = curEvent.mapProperties.anchor
of yamlScalar: foo = curEvent.scalarProperties.anchor
of yamlAlias: foo = curEvent.aliasTarget
else: raise newException(EventStreamError,
$curEvent.kind & "may not have an anchor")
foo
template setCurAnchor(val: AnchorId) =
template setCurAnchor(val: Anchor) =
case curEvent.kind
of yamlStartSeq: curEvent.seqAnchor = val
of yamlStartMap: curEvent.mapAnchor = val
of yamlScalar: curEvent.scalarAnchor = val
of yamlStartSeq: curEvent.seqProperties.anchor = val
of yamlStartMap: curEvent.mapProperties.anchor = val
of yamlScalar: curEvent.scalarProperties.anchor = val
of yamlAlias: curEvent.aliasTarget = val
else: raise newException(EventStreamError,
$curEvent.kind & " may not have an anchor")
template eventStart(k: YamlStreamEventKind) {.dirty.} =
template eventStart(k: EventKind) {.dirty.} =
assertInStream()
yieldEvent()
curEvent = YamlStreamEvent(kind: k)
curEvent = Event(kind: k)
setTag(yTagQuestionMark)
setAnchor(yAnchorNone)
inEvent = true
proc parseEventStream*(input: Stream, tagLib: TagLibrary): YamlStream =
var backend = iterator(): YamlStreamEvent =
var backend = iterator(): Event =
var lex: EventLexer
lex.open(input)
var
inEvent = false
curEvent: YamlStreamEvent
curEvent: Event
streamPos: StreamPos = beforeStream
anchors = initTable[string, AnchorId]()
nextAnchorId = 0.AnchorId
nextAnchorId = "a"
while lex.buf[lex.bufpos] != EndOfFile:
let token = lex.nextToken()
case token
@ -192,12 +191,14 @@ proc parseEventStream*(input: Stream, tagLib: TagLibrary): YamlStream =
if streamPos != beforeStream:
raise newException(EventStreamError, "Illegal +STR")
streamPos = inStream
eventStart(yamlStartStream)
of minusStr:
if streamPos != inStream:
raise newException(EventStreamError, "Illegal -STR")
if inEvent: yield curEvent
inEvent = false
streamPos = afterStream
eventStart(yamlEndStream)
of plusDoc: eventStart(yamlStartDoc)
of minusDoc: eventStart(yamlEndDoc)
of plusMap: eventStart(yamlStartMap)
@ -219,9 +220,8 @@ proc parseEventStream*(input: Stream, tagLib: TagLibrary): YamlStream =
if curAnchor() != yAnchorNone:
raise newException(EventStreamError,
"Duplicate anchor in " & $curEvent.kind)
anchors[lex.content] = nextAnchorId
setCurAnchor(nextAnchorId)
nextAnchorId = (AnchorId)(((int)nextAnchorId) + 1)
setCurAnchor(nextAnchorId.Anchor)
nextAnchor(nextAnchorId, len(nextAnchorId))
of starAnchor:
assertInEvent("alias")
if curEvent.kind != yamlAlias:
@ -231,7 +231,7 @@ proc parseEventStream*(input: Stream, tagLib: TagLibrary): YamlStream =
raise newException(EventStreamError, "Duplicate alias target: " &
escape(lex.content))
else:
curEvent.aliasTarget = anchors[lex.content]
curEvent.aliasTarget = lex.content.Anchor
of quotContent:
assertInEvent("scalar content")
if curTag() == yTagQuestionMark: setCurTag(yTagExclamationMark)

View File

@ -3,36 +3,34 @@ import ../yaml/private/lex
import unittest, strutils
const tokensWithValue =
{ltScalarPart, ltQuotedScalar, ltYamlVersion, ltTagShorthand, ltTagUri,
ltUnknownDirective, ltUnknownDirectiveParams, ltLiteralTag, ltAnchor,
ltAlias, ltBlockScalar}
{Token.Plain, Token.SingleQuoted, Token.DoubleQuoted, Token.Literal,
Token.Folded, Token.DirectiveParam,
Token.TagHandle, Token.Suffix, Token.VerbatimTag,
Token.UnknownDirective, Token.Anchor, Token.Alias}
type
TokenWithValue = object
case kind: LexerToken
case kind: Token
of tokensWithValue:
value: string
of ltIndentation:
of Indentation:
indentation: int
of ltTagHandle:
handle, suffix: string
else: discard
proc actualRepr(lex: YamlLexer, t: LexerToken): string =
proc actualRepr(lex: Lexer, t: Token): string =
result = $t
case t
of tokensWithValue + {ltTagHandle}:
result.add("(" & escape(lex.buf) & ")")
of ltIndentation:
of tokensWithValue + {Token.TagHandle}:
result.add("(" & escape(lex.evaluated) & ")")
of Indentation:
result.add("(" & $lex.indentation & ")")
else: discard
proc assertEquals(input: string, expected: varargs[TokenWithValue]) =
let lex = newYamlLexer(input)
var
lex: Lexer
i = 0
blockScalarEnd = -1
flowDepth = 0
lex.init(input)
for expectedToken in expected:
inc(i)
try:
@ -42,176 +40,135 @@ proc assertEquals(input: string, expected: varargs[TokenWithValue]) =
lex.actualRepr(lex.cur)
case expectedToken.kind
of tokensWithValue:
doAssert lex.buf == expectedToken.value, "Wrong token content at #" &
doAssert lex.evaluated == expectedToken.value, "Wrong token content at #" &
$i & ": Expected " & escape(expectedToken.value) &
", got " & escape(lex.buf)
lex.buf = ""
of ltIndentation:
", got " & escape(lex.evaluated)
of Indentation:
doAssert lex.indentation == expectedToken.indentation,
"Wrong indentation length at #" & $i & ": Expected " &
$expectedToken.indentation & ", got " & $lex.indentation
if lex.indentation <= blockScalarEnd:
lex.endBlockScalar()
blockScalarEnd = -1
of ltBraceOpen, ltBracketOpen:
inc(flowDepth)
if flowDepth == 1: lex.setFlow(true)
of ltBraceClose, ltBracketClose:
dec(flowDepth)
if flowDepth == 0: lex.setFlow(false)
of ltTagHandle:
let
handle = lex.buf.substr(0, lex.shorthandEnd)
suffix = lex.buf.substr(lex.shorthandEnd + 1)
doAssert handle == expectedToken.handle,
"Wrong handle at #" & $i & ": Expected " & expectedToken.handle &
", got " & handle
doAssert suffix == expectedToken.suffix,
"Wrong suffix at #" & $i & ": Expected " & expectedToken.suffix &
", got " & suffix
lex.buf = ""
else: discard
except YamlLexerError:
let e = (ref YamlLexerError)(getCurrentException())
except LexerError:
let e = (ref LexerError)(getCurrentException())
echo "Error at line " & $e.line & ", column " & $e.column & ":"
echo e.lineContent
assert false
proc assertLookahead(input: string, expected: bool, tokensBefore: int = 1) =
let lex = newYamlLexer(input)
var flowDepth = 0
for i in 0..tokensBefore:
lex.next()
case lex.cur
of ltBraceOpen, ltBracketOpen:
inc(flowDepth)
if flowDepth == 1: lex.setFlow(true)
of ltBraceClose, ltBracketClose:
dec(flowDepth)
if flowDepth == 0: lex.setFlow(false)
else: discard
doAssert lex.isImplicitKeyStart() == expected
proc i(indent: int): TokenWithValue =
TokenWithValue(kind: ltIndentation, indentation: indent)
proc sp(v: string): TokenWithValue =
TokenWithValue(kind: ltScalarPart, value: v)
proc qs(v: string): TokenWithValue =
TokenWithValue(kind: ltQuotedScalar, value: v)
proc se(): TokenWithValue = TokenWithValue(kind: ltStreamEnd)
proc mk(): TokenWithValue = TokenWithValue(kind: ltMapKeyInd)
proc mv(): TokenWithValue = TokenWithValue(kind: ltMapValInd)
proc si(): TokenWithValue = TokenWithValue(kind: ltSeqItemInd)
proc dy(): TokenWithValue = TokenWithValue(kind: ltYamlDirective)
proc dt(): TokenWithValue = TokenWithValue(kind: ltTagDirective)
TokenWithValue(kind: Token.Indentation, indentation: indent)
proc pl(v: string): TokenWithValue =
TokenWithValue(kind: Token.Plain, value: v)
proc sq(v: string): TokenWithValue =
TokenWithValue(kind: Token.SingleQuoted, value: v)
proc dq(v: string): TokenWithValue =
TokenWithValue(kind: Token.DoubleQuoted, value: v)
proc e(): TokenWithValue = TokenWithValue(kind: Token.StreamEnd)
proc mk(): TokenWithValue = TokenWithValue(kind: Token.MapKeyInd)
proc mv(): TokenWithValue = TokenWithValue(kind: Token.MapValueInd)
proc si(): TokenWithValue = TokenWithValue(kind: Token.SeqItemInd)
proc dy(): TokenWithValue = TokenWithValue(kind: Token.YamlDirective)
proc dt(): TokenWithValue = TokenWithValue(kind: Token.TagDirective)
proc du(v: string): TokenWithValue =
TokenWithValue(kind: ltUnknownDirective, value: v)
TokenWithValue(kind: Token.UnknownDirective, value: v)
proc dp(v: string): TokenWithValue =
TokenWithValue(kind: ltUnknownDirectiveParams, value: v)
proc yv(v: string): TokenWithValue =
TokenWithValue(kind: ltYamlVersion, value: v)
TokenWithValue(kind: Token.DirectiveParam, value: v)
proc th(v: string): TokenWithValue =
TokenWithValue(kind: Token.TagHandle, value: v)
proc ts(v: string): TokenWithValue =
TokenWithValue(kind: ltTagShorthand, value: v)
proc tu(v: string): TokenWithValue =
TokenWithValue(kind: ltTagUri, value: v)
proc dirE(): TokenWithValue = TokenWithValue(kind: ltDirectivesEnd)
proc docE(): TokenWithValue = TokenWithValue(kind: ltDocumentEnd)
proc bsh(): TokenWithValue = TokenWithValue(kind: ltBlockScalarHeader)
proc bs(v: string): TokenWithValue =
TokenWithValue(kind: ltBlockScalar, value: v)
proc el(): TokenWithValue = TokenWithValue(kind: ltEmptyLine)
proc ao(): TokenWithValue = TokenWithValue(kind: ltBracketOpen)
proc ac(): TokenWithValue = TokenWithValue(kind: ltBracketClose)
proc oo(): TokenWithValue = TokenWithValue(kind: ltBraceOpen)
proc oc(): TokenWithValue = TokenWithValue(kind: ltBraceClose)
proc c(): TokenWithValue = TokenWithValue(kind: ltComma)
proc th(handle, suffix: string): TokenWithValue =
TokenWithValue(kind: ltTagHandle, handle: handle, suffix: suffix)
proc lt(v: string): TokenWithValue =
TokenWithValue(kind: ltLiteralTag, value: v)
proc an(v: string): TokenWithValue = TokenWithValue(kind: ltAnchor, value: v)
proc al(v: string): TokenWithValue = TokenWithValue(kind: ltAlias, value: v)
TokenWithValue(kind: Token.Suffix, value: v)
proc tv(v: string): TokenWithValue =
TokenWithValue(kind: Token.VerbatimTag, value: v)
proc dirE(): TokenWithValue = TokenWithValue(kind: Token.DirectivesEnd)
proc docE(): TokenWithValue = TokenWithValue(kind: Token.DocumentEnd)
proc ls(v: string): TokenWithValue = TokenWithValue(kind: Token.Literal, value: v)
proc fs(v: string): TokenWithValue = TokenWithValue(kind: Token.Folded, value: v)
proc ss(): TokenWithValue = TokenWithValue(kind: Token.SeqStart)
proc se(): TokenWithValue = TokenWithValue(kind: Token.SeqEnd)
proc ms(): TokenWithValue = TokenWithValue(kind: Token.MapStart)
proc me(): TokenWithValue = TokenWithValue(kind: Token.MapEnd)
proc sep(): TokenWithValue = TokenWithValue(kind: Token.SeqSep)
proc an(v: string): TokenWithValue = TokenWithValue(kind: Token.Anchor, value: v)
proc al(v: string): TokenWithValue = TokenWithValue(kind: Token.Alias, value: v)
suite "Lexer":
test "Empty document":
assertEquals("", se())
assertEquals("", e())
test "Single-line scalar":
assertEquals("scalar", i(0), sp("scalar"), se())
assertEquals("scalar", i(0), pl("scalar"), e())
test "Multiline scalar":
assertEquals("scalar\l line two", i(0), sp("scalar"), i(2),
sp("line two"), se())
assertEquals("scalar\l line two", i(0), pl("scalar line two"), e())
test "Single-line mapping":
assertEquals("key: value", i(0), sp("key"), mv(), sp("value"), se())
assertEquals("key: value", i(0), pl("key"), mv(), pl("value"), e())
test "Multiline mapping":
assertEquals("key:\n value", i(0), sp("key"), mv(), i(2), sp("value"),
se())
assertEquals("key:\n value", i(0), pl("key"), mv(), i(2), pl("value"),
e())
test "Explicit mapping":
assertEquals("? key\n: value", i(0), mk(), sp("key"), i(0), mv(),
sp("value"), se())
assertEquals("? key\n: value", i(0), mk(), pl("key"), i(0), mv(),
pl("value"), e())
test "Sequence":
assertEquals("- a\n- b", i(0), si(), sp("a"), i(0), si(), sp("b"), se())
assertEquals("- a\n- b", i(0), si(), pl("a"), i(0), si(), pl("b"), e())
test "Single-line single-quoted scalar":
assertEquals("'quoted scalar'", i(0), qs("quoted scalar"), se())
assertEquals("'quoted scalar'", i(0), sq("quoted scalar"), e())
test "Multiline single-quoted scalar":
assertEquals("'quoted\l multi line \l\lscalar'", i(0),
qs("quoted multi line\lscalar"), se())
sq("quoted multi line\lscalar"), e())
test "Single-line double-quoted scalar":
assertEquals("\"quoted scalar\"", i(0), qs("quoted scalar"), se())
assertEquals("\"quoted scalar\"", i(0), dq("quoted scalar"), e())
test "Multiline double-quoted scalar":
assertEquals("\"quoted\l multi line \l\lscalar\"", i(0),
qs("quoted multi line\lscalar"), se())
dq("quoted multi line\lscalar"), e())
test "Escape sequences":
assertEquals(""""\n\x31\u0032\U00000033"""", i(0), qs("\l123"), se())
assertEquals(""""\n\x31\u0032\U00000033"""", i(0), dq("\l123"), e())
test "Directives":
assertEquals("%YAML 1.2\n---\n%TAG\n...\n\n%TAG ! example.html",
dy(), yv("1.2"), dirE(), i(0), sp("%TAG"), i(0), docE(), dt(),
ts("!"), tu("example.html"), se())
dy(), dp("1.2"), dirE(), i(0), pl("%TAG"), i(0), docE(), dt(),
th("!"), ts("example.html"), e())
test "Markers and Unknown Directive":
assertEquals("---\n---\n...\n%UNKNOWN warbl", dirE(), dirE(), i(0),
docE(), du("UNKNOWN"), dp("warbl"), se())
docE(), du("UNKNOWN"), dp("warbl"), e())
test "Block scalar":
assertEquals("|\l a\l\l b\l # comment", i(0), bsh(), bs("a\l\lb\l"), se())
assertEquals("|\l a\l\l b\l # comment", i(0), ls("a\l\lb\l"), e())
test "Block Scalars":
assertEquals("one : >2-\l foo\l bar\ltwo: |+\l bar\l baz", i(0),
sp("one"), mv(), bsh(), bs(" foo\lbar"), i(0), sp("two"), mv(), bsh(),
bs("bar\l baz"), se())
pl("one"), mv(), fs(" foo\lbar"), i(0), pl("two"), mv(),
ls("bar\l baz"), e())
test "Flow indicators":
assertEquals("bla]: {c: d, [e]: f}", i(0), sp("bla]"), mv(), oo(), sp("c"),
mv(), sp("d"), c(), ao(), sp("e"), ac(), mv(), sp("f"), oc(), se())
assertEquals("bla]: {c: d, [e]: f}", i(0), pl("bla]"), mv(), ms(), pl("c"),
mv(), pl("d"), sep(), ss(), pl("e"), se(), mv(), pl("f"), me(), e())
test "Adjacent map values in flow style":
assertEquals("{\"foo\":bar, [1]\l:egg}", i(0), oo(), qs("foo"), mv(),
sp("bar"), c(), ao(), sp("1"), ac(), mv(), sp("egg"), oc(), se())
assertEquals("{\"foo\":bar, [1]\l:egg}", i(0), ms(), dq("foo"), mv(),
pl("bar"), sep(), ss(), pl("1"), se(), mv(), pl("egg"), me(), e())
test "Tag handles":
assertEquals("- !!str string\l- !local local\l- !e! e", i(0), si(),
th("!!", "str"), sp("string"), i(0), si(), th("!", "local"),
sp("local"), i(0), si(), th("!e!", ""), sp("e"), se())
th("!!"), ts("str"), pl("string"), i(0), si(), th("!"), ts("local"),
pl("local"), i(0), si(), th("!e!"), ts(""), pl("e"), e())
test "Literal tag handle":
assertEquals("!<tag:yaml.org,2002:str> string", i(0),
lt("tag:yaml.org,2002:str"), sp("string"), se())
tv("tag:yaml.org,2002:str"), pl("string"), e())
test "Anchors and aliases":
assertEquals("&a foo: {&b b: *a, *b : c}", i(0), an("a"), sp("foo"), mv(),
oo(), an("b"), sp("b"), mv(), al("a"), c(), al("b"), mv(), sp("c"),
oc(), se())
assertEquals("&a foo: {&b b: *a, *b : c}", i(0), an("a"), pl("foo"), mv(),
ms(), an("b"), pl("b"), mv(), al("a"), sep(), al("b"), mv(), pl("c"),
me(), e())
test "Empty lines":
assertEquals("""block: foo
@ -226,37 +183,6 @@ flow: {
mi
}""", i(0), sp("block"), mv(), sp("foo"), el(), i(2), sp("bar"), el(), i(4),
sp("baz"), i(0), sp("flow"), mv(), oo(), sp("foo"), el(), sp("bar"), mv(),
sp("baz"), el(), el(), sp("mi"), oc(), se())
suite "Lookahead":
test "Simple Scalar":
assertLookahead("abcde", false)
test "Simple Mapping":
assertLookahead("a: b", true)
test "Colon inside plain scalar":
assertLookahead("abc:de", false)
test "Colon inside quoted scalar":
assertLookahead("'abc: de'", false)
test "Quotes inside plain scalar":
assertLookahead("abc\'\"de: foo", true)
test "Flow indicator inside plain scalar":
assertLookahead("abc}]: de", true)
test "Complex key":
assertLookahead("[1, 2, \"3\"]: foo", true)
test "Flow value":
assertLookahead("{a: b}", false)
test "In flow context":
assertLookahead("[ abcde]: foo", false, 2)
test "Adjacent value":
assertLookahead("[\"abc\":de]", true, 2)
}""", i(0), pl("block"), mv(), pl("foo\nbar\nbaz"),
i(0), pl("flow"), mv(), ms(), pl("foo\nbar"), mv(),
pl("baz\n\nmi"), me(), e())

View File

@ -4,9 +4,9 @@
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
import os, osproc, terminal, strutils, streams, macros, unittest, sets
import os, terminal, strutils, streams, macros, unittest, sets
import testEventParser, commonTestUtils
import "../yaml"
import ../yaml, ../yaml/data
const
testSuiteFolder = "yaml-test-suite"
@ -18,7 +18,9 @@ proc echoError(msg: string) =
proc parserTest(path: string, errorExpected : bool): bool =
var
tagLib = initExtendedTagLibrary()
parser = newYamlParser(tagLib)
parser: YamlParser
parser.init(tagLib)
var
actualIn = newFileStream(path / "in.yaml")
actual = parser.parse(actualIn)
expectedIn = newFileStream(path / "test.event")
@ -28,14 +30,8 @@ proc parserTest(path: string, errorExpected : bool): bool =
expectedIn.close()
var i = 1
try:
while not actual.finished():
while true:
let actualEvent = actual.next()
if expected.finished():
result = errorExpected
if not result:
echoError("At token #" & $i & ": Expected stream end, got " &
$actualEvent.kind)
return
let expectedEvent = expected.next()
if expectedEvent != actualEvent:
result = errorExpected
@ -45,12 +41,8 @@ proc parserTest(path: string, errorExpected : bool): bool =
": Actual tokens do not match expected tokens")
return
i.inc()
if not expected.finished():
result = errorExpected
if not result:
echoError("Got fewer tokens than expected, first missing " &
"token: " & $expected.next().kind)
return
if actualEvent.kind == yamlEndStream:
break
result = not errorExpected
if not result:
echo "Expected error, but parsed without error."
@ -60,7 +52,7 @@ proc parserTest(path: string, errorExpected : bool): bool =
let e = getCurrentException()
if e.parent of YamlParserError:
let pe = (ref YamlParserError)(e.parent)
echo "line ", pe.line, ", column ", pe.column, ": ", pe.msg
echo "line ", pe.mark.line, ", column ", pe.mark.column, ": ", pe.msg
echo pe.lineContent
else: echo e.msg
echoError("Catched an exception at token #" & $i &

View File

@ -198,8 +198,9 @@ proc loadDom*(s: Stream | string): YamlDocument
{.raises: [IOError, YamlParserError, YamlConstructionError].} =
var
tagLib = initExtendedTagLibrary()
parser = newYamlParser(tagLib)
events = parser.parse(s)
parser: YamlParser
parser.init(tagLib)
var events = parser.parse(s)
try: result = compose(events, tagLib)
except YamlStreamError:
let e = getCurrentException()

View File

@ -11,14 +11,14 @@
## This is the low-level parser API. A ``YamlParser`` enables you to parse any
## non-nil string or Stream object as YAML character stream.
import tables, strutils, macros
import tables, strutils, macros, streams
import taglib, stream, private/lex, private/internal, data
when defined(nimNoNil):
{.experimental: "notnil".}
type
YamlParser* = ref object
YamlParser* = object
## A parser object. Retains its ``TagLibrary`` across calls to
## `parse <#parse,YamlParser,Stream>`_. Can be used
## to access anchor names while parsing a YAML character stream, but
@ -26,7 +26,6 @@ type
## ``yamlEndDocument`` is yielded).
tagLib: TagLibrary
issueWarnings: bool
anchors: Table[string, Anchor]
State = proc(c: Context, e: var Event): bool {.locks: 0, gcSafe.}
@ -83,28 +82,9 @@ type
## Some elements in this list are vague. For a detailed description of a
## valid YAML character stream, see the YAML specification.
# interface
proc newYamlParser*(tagLib: TagLibrary = initExtendedTagLibrary(),
issueWarnings: bool = false): YamlParser =
## Creates a YAML parser. if ``callback`` is not ``nil``, it will be called
## whenever the parser yields a warning.
new(result)
result.tagLib = tagLib
result.issueWarnings = issueWarnings
# implementation
template debug(message: string) {.dirty.} =
when defined(yamlDebug):
try: styledWriteLine(stdout, fgBlue, message)
except IOError: discard
const defaultProperties = (yAnchorNone, yTagQuestionMark)
proc isEmpty(props: Properties): bool =
result = props.anchor == yAnchorNone and
props.tag == yTagQuestionMark
# parser states
{.push gcSafe, locks: 0.}
proc atStreamStart(c: Context, e: var Event): bool
@ -139,11 +119,44 @@ proc afterFlowSeqItem(c: Context, e: var Event): bool
proc afterPairValue(c: Context, e: var Event): bool
{.pop.}
proc init[T](pc: Context, source: T) {.inline.} =
pc.levels.add(Level(state: atStreamStart, indentation: -2))
pc.headerProps = defaultProperties
pc.inlineProps = defaultProperties
pc.lex.init(source)
proc init[T](c: Context, source: T) {.inline.} =
c.levels.add(Level(state: atStreamStart, indentation: -2))
c.nextImpl = proc(s: YamlStream, e: var Event): bool =
let c = Context(s)
return c.levels[^1].state(c, e)
c.headerProps = defaultProperties
c.inlineProps = defaultProperties
c.lex.init(source)
# interface
proc init*(p: var YamlParser, tagLib: TagLibrary = initExtendedTagLibrary(),
issueWarnings: bool = false) =
## Creates a YAML parser. if ``callback`` is not ``nil``, it will be called
## whenever the parser yields a warning.
p.tagLib = tagLib
p.issueWarnings = issueWarnings
proc parse*(p: YamlParser, s: Stream): YamlStream =
let c = new(Context)
c.init(s)
return c
proc parse*(p: YamlParser, s: string): YamlStream =
let c = new(Context)
c.init(s)
return c
# implementation
template debug(message: string) {.dirty.} =
when defined(yamlDebug):
try: styledWriteLine(stdout, fgBlue, message)
except IOError: discard
proc isEmpty(props: Properties): bool =
result = props.anchor == yAnchorNone and
props.tag == yTagQuestionMark
proc generateError(c: Context, message: string):
ref YamlParserError {.raises: [].} =
@ -706,7 +719,7 @@ proc beforeBlockMapValue(c: Context, e: var Event): bool =
raise c.generateError("Unexpected token (expected mapping value): " & $c.lex.cur)
proc beforeBlockIndentation(c: Context, e: var Event): bool =
proc endBlockNode() =
proc endBlockNode(e: var Event) =
if c.levels[^1].state == beforeBlockMapKey:
e = endMapEvent(c.lex.curStartPos, c.lex.curEndPos)
elif c.levels[^1].state == beforeBlockMapValue:
@ -729,7 +742,7 @@ proc beforeBlockIndentation(c: Context, e: var Event): bool =
of Indentation:
c.blockIndentation = c.lex.indentation
if c.blockIndentation < c.levels[^1].indentation:
endBlockNode()
endBlockNode(e)
return true
else:
c.lex.next()
@ -737,7 +750,7 @@ proc beforeBlockIndentation(c: Context, e: var Event): bool =
of StreamEnd, DocumentEnd, DirectivesEnd:
c.blockIndentation = 0
if c.levels[^1].state != beforeDocEnd:
endBlockNode()
endBlockNode(e)
return true
else:
return false

View File

@ -730,8 +730,9 @@ proc doTransform(input: Stream | string, output: PresenterTarget,
options: PresentationOptions, resolveToCoreYamlTags: bool) =
var
taglib = initExtendedTagLibrary()
parser = newYamlParser(tagLib)
events = parser.parse(input)
parser: YamlParser
parser.init(tagLib)
var events = parser.parse(input)
try:
if options.style == psCanonical:
var bys: YamlStream = newBufferYamlStream()

View File

@ -1380,9 +1380,9 @@ proc construct*[T](s: var YamlStream, target: var T)
proc load*[K](input: Stream | string, target: var K)
{.raises: [YamlConstructionError, IOError, YamlParserError].} =
## Loads a Nim value from a YAML character stream.
var
parser = newYamlParser(serializationTagLibrary)
events = parser.parse(input)
var parser: YamlParser
parser.init(serializationTagLibrary)
var events = parser.parse(input)
try: construct(events, target)
except YamlStreamError:
let e = (ref YamlStreamError)(getCurrentException())
@ -1391,9 +1391,9 @@ proc load*[K](input: Stream | string, target: var K)
else: internalError("Unexpected exception: " & $e.parent.name)
proc loadMultiDoc*[K](input: Stream | string, target: var seq[K]) =
var
parser = newYamlParser(serializationTagLibrary)
events = parser.parse(input)
var parser: YamlParser
parser.init(serializationTagLibrary)
var events = parser.parse(input)
try:
while not events.finished():
var item: K

View File

@ -90,9 +90,10 @@ proc constructJson*(s: var YamlStream): seq[JsonNode]
var
levels = newSeq[Level]()
anchors = initTable[AnchorId, JsonNode]()
anchors = initTable[Anchor, JsonNode]()
for event in s:
case event.kind
of yamlStartStream, yamlEndStream: discard
of yamlStartDoc:
# we don't need to do anything here; root node will be created
# by first scalar, sequence or map event
@ -106,13 +107,13 @@ proc constructJson*(s: var YamlStream): seq[JsonNode]
anchors[event.seqProperties.anchor] = levels[levels.high].node
of yamlStartMap:
levels.add(initLevel(newJObject()))
if event.mapAnchor != yAnchorNone:
anchors[event.mapAnchor] = levels[levels.high].node
if event.mapProperties.anchor != yAnchorNone:
anchors[event.mapProperties.anchor] = levels[levels.high].node
of yamlScalar:
if levels.len == 0:
# parser ensures that next event will be yamlEndDocument
levels.add((node: jsonFromScalar(event.scalarContent,
event.scalarTag),
event.scalarProperties.tag),
key: "",
expKey: true))
continue
@ -120,25 +121,25 @@ proc constructJson*(s: var YamlStream): seq[JsonNode]
case levels[levels.high].node.kind
of JArray:
let jsonScalar = jsonFromScalar(event.scalarContent,
event.scalarTag)
event.scalarProperties.tag)
levels[levels.high].node.elems.add(jsonScalar)
if event.scalarAnchor != yAnchorNone:
anchors[event.scalarAnchor] = jsonScalar
if event.scalarProperties.anchor != yAnchorNone:
anchors[event.scalarProperties.anchor] = jsonScalar
of JObject:
if levels[levels.high].expKey:
levels[levels.high].expKey = false
# JSON only allows strings as keys
levels[levels.high].key = event.scalarContent
if event.scalarAnchor != yAnchorNone:
if event.scalarProperties.anchor != yAnchorNone:
raise newException(YamlConstructionError,
"scalar keys may not have anchors in JSON")
else:
let jsonScalar = jsonFromScalar(event.scalarContent,
event.scalarTag)
event.scalarProperties.tag)
levels[levels.high].node[levels[levels.high].key] = jsonScalar
levels[levels.high].expKey = true
if event.scalarAnchor != yAnchorNone:
anchors[event.scalarAnchor] = jsonScalar
if event.scalarProperties.anchor != yAnchorNone:
anchors[event.scalarProperties.anchor] = jsonScalar
else:
internalError("Unexpected node kind: " & $levels[levels.high].node.kind)
of yamlEndSeq, yamlEndMap:
@ -177,13 +178,13 @@ proc constructJson*(s: var YamlStream): seq[JsonNode]
when not defined(JS):
proc loadToJson*(s: Stream): seq[JsonNode]
{.raises: [YamlParserError, YamlConstructionError, IOError].} =
{.raises: [YamlParserError, YamlConstructionError, IOError, OSError].} =
## Uses `YamlParser <#YamlParser>`_ and
## `constructJson <#constructJson>`_ to construct an in-memory JSON tree
## from a YAML character stream.
var
parser = newYamlParser(initCoreTagLibrary())
events = parser.parse(s)
var parser: YamlParser
parser.init(initCoreTagLibrary())
var events = parser.parse(s)
try:
return constructJson(events)
except YamlStreamError:
@ -199,9 +200,9 @@ proc loadToJson*(str: string): seq[JsonNode]
## Uses `YamlParser <#YamlParser>`_ and
## `constructJson <#constructJson>`_ to construct an in-memory JSON tree
## from a YAML character stream.
var
parser = newYamlParser(initCoreTagLibrary())
events = parser.parse(str)
var parser: YamlParser
parser.init(initCoreTagLibrary())
var events = parser.parse(str)
try: return constructJson(events)
except YamlStreamError:
let e = getCurrentException()