NimYAML/private/lex.nim

470 lines
14 KiB
Nim
Raw Normal View History

2016-09-10 08:30:40 +00:00
# NimYAML - YAML implementation in Nim
# (c) Copyright 2015 Felix Krause
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
import lexbase, streams, strutils
type
StringSource* = object
src: string
pos: int
line, lineStart: int
SourceProvider* = concept c
advance(c) is char
lexCR(c)
lexLF(c)
2016-09-10 10:38:03 +00:00
# YamlLexer*[T: SourceProvider] = ref object # not possible -> compiler bug
YamlLexer*[T] = ref object
2016-09-10 08:30:40 +00:00
source: T
inFlow: bool
literalEndIndent: int
2016-09-10 10:38:03 +00:00
nextImpl, stored: LexerState[T]
2016-09-10 08:30:40 +00:00
buf*: string not nil
indentation*: int
2016-09-10 10:38:03 +00:00
c: char
LexerState[T] = proc(lex: YamlLexer[T], t: var LexerToken): bool
2016-09-10 08:30:40 +00:00
LexerToken* = enum
ltYamlDirective, ltYamlVersion, ltTagDirective, ltTagShorthand,
ltTagUrl, ltUnknownDirective, ltUnknownDirectiveParams,
ltDirectivesEnd, ltDocumentEnd, ltStreamEnd, ltIndentation, ltQuotedScalar,
ltScalarPart, ltEmptyLine, ltSeqItemInd, ltMapKeyInd, ltMapValInd,
ltBraceOpen, ltBraceClose, ltBracketOpen, ltBracketClose, ltComma,
ltLiteralTag, ltTagSuffix, ltAnchor, ltAlias
YamlLexerError* = object of Exception
2016-09-10 10:38:03 +00:00
line, column: int
lineContent: string
2016-09-10 08:30:40 +00:00
# templates
template advance(lex: YamlLexer[BaseLexer], step: int = 1) =
lex.source.bufpos.inc(step)
lex.c = lex.source.buf[lex.source.bufpos]
template advance(lex: YamlLexer[StringSource], step: int = 1) =
lex.source.pos.inc(step)
lex.c = lex.source.src[lex.source.pos]
# lexer states
proc outsideDoc[T](lex: YamlLexer[T], t: var LexerToken): bool
proc yamlVersion[T](lex: YamlLexer[T], t: var LexerToken): bool
proc tagShorthand[T](lex: YamlLexer[T], t: var LexerToken): bool
proc tagUri[T](lex: YamlLexer[T], t: var LexerToken): bool
proc unknownDirParams[T](lex: YamlLexer[T], t: var LexerToken): bool
proc expectLineEnd[T](lex: YamlLexer[T], t: var LexerToken): bool
2016-09-10 10:38:03 +00:00
proc blockStyle[T](lex: YamlLexer[T], t: var LexerToken): bool {.locks:0.}
2016-09-10 08:30:40 +00:00
proc blockStyleInline[T](lex: YamlLexer[T], t: var LexerToken): bool
proc plainScalarPart[T](lex: YamlLexer[T], t: var LexerToken): bool
2016-09-10 10:38:03 +00:00
proc flowStyle[T](lex: YamlLexer[T], t: var LexerToken): bool {.locks:0.}
2016-09-10 08:30:40 +00:00
proc streamEnd[T](lex: YamlLexer[T], t: var LexerToken): bool
# interface
proc newYamlLexer*(source: Stream): YamlLexer[BaseLexer] =
2016-09-10 10:38:03 +00:00
result = YamlLexer[BaseLexer](source: BaseLexer(), inFlow: false, buf: "")
2016-09-10 08:30:40 +00:00
result.source.open(source)
result.c = result.source.buf[result.source.bufpos]
2016-09-10 10:38:03 +00:00
proc newYamlLexer*(source: string, startAt: int = 0):
YamlLexer[StringSource] =
result = YamlLexer[StringSource](buf: "", source:
2016-09-10 08:30:40 +00:00
StringSource(src: source, pos: startAt, lineStart: startAt, line: 1),
inFlow: false, c: source[startAt])
2016-09-10 10:38:03 +00:00
proc init*[T](lex: YamlLexer[T]) =
lex.nextImpl = outsideDoc[T]
2016-09-10 08:30:40 +00:00
proc next*(lex: YamlLexer): LexerToken =
2016-09-10 10:38:03 +00:00
while not lex.nextImpl(lex, result): discard
2016-09-10 08:30:40 +00:00
# implementation
const
space = {' ', '\t'}
lineEnd = {'\l', '\c', EndOfFile}
spaceOrLineEnd = {' ', '\t', '\l', '\c', EndOfFile}
digits = {'0'..'9'}
flowIndicators = {'[', ']', '{', '}', ','}
template debug(message: string) {.dirty.} =
when defined(yamlDebug):
try: styledWriteLine(stdout, fgBlue, message)
except IOError: discard
2016-09-10 10:38:03 +00:00
template lexCR(lex: YamlLexer[BaseLexer]) =
2016-09-10 08:30:40 +00:00
lex.source.bufpos = lex.source.handleCR(lex.source.bufpos)
2016-09-10 10:38:03 +00:00
template lexCR(lex: YamlLexer[StringSource]) =
2016-09-10 08:30:40 +00:00
lex.source.pos.inc()
if lex.source.src[lex.source.pos] == '\l': lex.source.pos.inc()
lex.source.lineStart = lex.source.pos
2016-09-10 10:38:03 +00:00
lex.source.line.inc()
2016-09-10 08:30:40 +00:00
2016-09-10 10:38:03 +00:00
template lexLF(lex: YamlLexer[BaseLexer]) =
2016-09-10 08:30:40 +00:00
lex.source.bufpos = lex.source.handleLF(lex.source.bufpos)
2016-09-10 10:38:03 +00:00
template lexLF(lex: YamlLexer[StringSource]) =
2016-09-10 08:30:40 +00:00
lex.source.pos.inc()
lex.source.lineStart = lex.source.pos
2016-09-10 10:38:03 +00:00
lex.source.line.inc()
template lineNumber(lex: YamlLexer[BaseLexer]): int =
lex.source.lineNumber
template lineNumber(lex: YamlLexer[StringSource]): int =
lex.source.line
template columnNumber(lex: YamlLexer[BaseLexer]): int =
lex.source.getColNumber() + 1
template columnNumber(lex: YamlLexer[StringSource]): int =
lex.source.pos - lex.source.lineStart + 1
template currentLine(lex: YamlLexer[BaseLexer]): string =
lex.source.getCurrentLine(true)
template currentLine(lex: YamlLexer[StringSource]): string =
var result = ""
var i = lex.source.lineStart
while lex.source.src[i] notin lineEnd:
result.add(lex.source.src[i])
inc(i)
result.add("\n" & spaces(lex.columnNumber) & "^\n")
result
proc generateError(lex: YamlLexer, message: string):
ref YamlLexerError {.raises: [].} =
result = newException(YamlLexerError, message)
result.line = lex.lineNumber
result.column = lex.columnNumber
result.lineContent = lex.currentLine
2016-09-10 08:30:40 +00:00
proc directiveName(lex: YamlLexer) =
while lex.c notin spaceOrLineEnd:
lex.buf.add(lex.c)
lex.advance()
proc yamlVersion[T](lex: YamlLexer[T], t: var LexerToken): bool =
debug("lex: yamlVersion")
2016-09-10 10:38:03 +00:00
while lex.c in space: lex.advance()
2016-09-10 08:30:40 +00:00
if lex.c notin digits: raise lex.generateError("Invalid YAML version number")
lex.buf.add(lex.c)
lex.advance()
while lex.c in digits:
lex.buf.add(lex.c)
lex.advance()
if lex.c != '.': raise lex.generateError("Invalid YAML version number")
lex.buf.add('.')
lex.advance()
if lex.c notin digits: raise lex.generateError("Invalid YAML version number")
lex.buf.add(lex.c)
lex.advance()
while lex.c in digits:
lex.buf.add(lex.c)
lex.advance()
if lex.c notin spaceOrLineEnd:
raise lex.generateError("Invalid YAML version number")
t = ltYamlVersion
result = true
lex.stored = outsideDoc[T]
lex.nextImpl = expectLineEnd[T]
template nextIsPlainSafe(lex: YamlLexer[BaseLexer], inFlow: bool): bool =
case lex.source.buf[lex.source.bufpos + 1]
of spaceOrLineEnd: result = false
of flowIndicators: result = not inFlow
else: result = true
template nextIsPlainSafe(lex: YamlLexer[StringSource], inFlow: bool): bool =
2016-09-10 10:38:03 +00:00
var result: bool
2016-09-10 08:30:40 +00:00
case lex.source.src[lex.source.pos + 1]
of spaceOrLineEnd: result = false
of flowIndicators: result = not inFlow
else: result = true
2016-09-10 10:38:03 +00:00
result
2016-09-10 08:30:40 +00:00
proc tagShorthand[T](lex: YamlLexer[T], t: var LexerToken): bool =
debug("lex: tagShorthand")
while lex.c in space: lex.advance()
if lex.c != '!': raise lex.generateError("Tag shorthand must start with a '!'")
lex.buf.add(lex.c)
lex.advance()
if lex.c in spaceOrLineEnd: discard
else:
while lex.c != '!':
case lex.c
of 'a' .. 'z', 'A' .. 'Z', '0' .. '9', '-':
lex.buf.add(lex.c)
lex.advance()
else: raise lex.generateError("Illegal character in tag shorthand")
lex.buf.add(lex.c)
lex.advance()
if lex.c notin spaceOrLineEnd:
raise lex.generateError("Missing space after tag shorthand")
lex.nextImpl = tagUri[T]
proc tagUri[T](lex: YamlLexer[T], t: var LexerToken): bool =
debug("lex: tagUri")
while lex.c in space: lex.advance()
if lex.c == '!':
lex.buf.add(lex.c)
2016-09-10 10:38:03 +00:00
lex.advance()
2016-09-10 08:30:40 +00:00
while true:
case lex.c
of spaceOrLineEnd: break
of 'a' .. 'z', 'A' .. 'Z', '0' .. '9', '#', ';', '/', '?', ':', '@', '&',
'-', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')':
lex.buf.add(lex.c)
lex.advance()
else: raise lex.generateError("Invalid character in tag uri: " &
escape("" & lex.c))
proc unknownDirParams[T](lex: YamlLexer[T], t: var LexerToken): bool =
2016-09-10 10:38:03 +00:00
while lex.c notin lineEnd + {'#'}: lex.advance()
2016-09-10 08:30:40 +00:00
t = ltUnknownDirectiveParams
result = true
lex.stored = outsideDoc[T]
lex.nextImpl = expectLineEnd[T]
proc expectLineEnd[T](lex: YamlLexer[T], t: var LexerToken): bool =
debug("lex: expectLineEnd")
result = false
2016-09-10 10:38:03 +00:00
while lex.c in space: lex.advance()
2016-09-10 08:30:40 +00:00
while true:
case lex.c
of '#':
lex.advance()
while lex.c notin lineEnd: lex.advance()
of EndOfFile:
lex.nextImpl = streamEnd[T]
break
of '\l':
2016-09-10 10:38:03 +00:00
lex.lexLF()
2016-09-10 08:30:40 +00:00
lex.nextImpl = lex.stored
break
of '\c':
2016-09-10 10:38:03 +00:00
lex.lexCR()
2016-09-10 08:30:40 +00:00
lex.nextImpl = lex.stored
break
else:
raise lex.generateError("Unexpected character (expected line end): " &
escape("" & lex.c))
proc possibleDirectivesEnd[T](lex: YamlLexer[T], t: var LexerToken) =
lex.advance()
if lex.c == '-':
lex.advance()
if lex.c == '-':
lex.advance()
if lex.c in spaceOrLineEnd:
t = ltDirectivesEnd
lex.nextImpl = blockStyleInline[T]
return
lex.buf.add('-')
lex.buf.add('-')
elif lex.c in spaceOrLineEnd:
lex.advance()
t = ltSeqItemInd
lex.nextImpl = blockStyleInline[T]
return
lex.buf.add('-')
lex.nextImpl = plainScalarPart[T]
lex.indentation = 0
t = ltIndentation
proc possibleDocumentEnd[T](lex: YamlLexer[T], t: var LexerToken) =
lex.advance()
if lex.c == '.':
lex.advance()
if lex.c == '.':
lex.advance()
if lex.c in spaceOrLineEnd:
t = ltDocumentEnd
lex.nextImpl = expectLineEnd[T]
lex.stored = outsideDoc[T]
return
lex.buf.add('.')
lex.buf.add('.')
lex.buf.add('.')
lex.nextImpl = plainScalarPart[T]
lex.indentation = 0
t = ltIndentation
proc outsideDoc[T](lex: YamlLexer[T], t: var LexerToken): bool =
case lex.c
of '%':
lex.advance()
lex.directiveName()
case lex.buf
2016-09-10 10:38:03 +00:00
of "YAML":
t = ltYamlDirective
lex.nextImpl = yamlVersion[T]
of "TAG":
t = ltTagDirective
lex.nextImpl = tagShorthand[T]
else:
t = ltUnknownDirective
lex.nextImpl = unknownDirParams[T]
return true
2016-09-10 08:30:40 +00:00
of '-':
lex.possibleDirectivesEnd(t)
return true
of '.':
lex.possibleDocumentEnd(t)
return true
of spaceOrLineEnd + {'#'}:
lex.indentation = 0
while lex.c == ' ':
lex.indentation.inc()
lex.advance()
if lex.c in spaceOrLineEnd + {'#'}:
lex.nextImpl = expectLineEnd[T]
lex.stored = outsideDoc[T]
return false
else: lex.indentation = 0
lex.nextImpl = blockStyleInline[T]
t = ltIndentation
result = true
proc blockStyle[T](lex: YamlLexer[T], t: var LexerToken): bool =
case lex.c
of '-':
lex.possibleDirectivesEnd(t)
return true
of '.':
lex.possibleDocumentEnd(t)
return true
of spaceOrLineEnd + {'#'}:
lex.indentation = 0
while lex.c == ' ':
lex.indentation.inc()
lex.advance()
if lex.c in spaceOrLineEnd + {'#'}:
lex.nextImpl = expectLineEnd[T]
lex.stored = blockStyle[T]
t = ltEmptyLine
return true
else: lex.indentation = 0
lex.nextImpl = blockStyleInline[T]
t = ltIndentation
result = true
proc possibleIndicatorChar[T](lex: YamlLexer[T], indicator: LexerToken,
t: var LexerToken): bool =
if lex.nextIsPlainSafe(false):
lex.nextImpl = plainScalarPart[T]
lex.stored = blockStyleInline[T]
result = false
else:
t = indicator
result = true
lex.advance()
while lex.c in space: lex.advance()
if lex.c in lineEnd:
lex.nextImpl = expectLineEnd[T]
lex.stored = blockStyle[T]
proc flowIndicator[T](lex: YamlLexer[T], indicator: LexerToken,
t: var LexerToken, inFlow: static[bool]): bool {.inline.} =
t = indicator
lex.advance()
while lex.c in space: lex.advance()
if lex.c in lineEnd:
lex.nextImpl = expectLineEnd[T]
when inFlow: lex.stored = flowStyle[T]
else: lex.stored = blockStyle[T]
2016-09-10 10:38:03 +00:00
proc singleQuotedScalar[T](lex: YamlLexer[T]) =
discard
proc doubleQuotedScalar[T](lex: YamlLexer[T]) =
discard
2016-09-10 08:30:40 +00:00
proc blockStyleInline[T](lex: YamlLexer[T], t: var LexerToken): bool =
case lex.c
of ':': result = lex.possibleIndicatorChar(ltMapValInd, t)
of '?': result = lex.possibleIndicatorChar(ltMapKeyInd, t)
of '-': result = lex.possibleIndicatorChar(ltSeqItemInd, t)
of lineEnd + {'#'}:
result = false
lex.nextImpl = expectLineEnd[T]
lex.stored = blockStyle[T]
of '\"':
lex.doubleQuotedScalar()
t = ltQuotedScalar
result = true
of '\'':
lex.singleQuotedScalar()
t = ltQuotedScalar
result = true
of '>', '|':
# TODO
result = true
2016-09-10 10:38:03 +00:00
of '{': result = lex.flowIndicator(ltBraceOpen, t, false)
of '}': result = lex.flowIndicator(ltBraceClose, t, false)
of '[': result = lex.flowIndicator(ltBracketOpen, t, false)
of ']': result = lex.flowIndicator(ltBracketClose, t, false)
2016-09-10 08:30:40 +00:00
else:
lex.nextImpl = plainScalarPart[T]
lex.stored = blockStyleInline[T]
result = false
proc plainScalarPart[T](lex: YamlLexer[T], t: var LexerToken): bool =
debug("lex: plainScalar")
block outer:
while true:
lex.buf.add(lex.c)
lex.advance()
case lex.c
of space:
let lenBeforeSpace = lex.buf.len()
while true:
lex.buf.add(lex.c)
lex.advance()
2016-09-10 10:38:03 +00:00
case lex.c
2016-09-10 08:30:40 +00:00
of lineEnd + {'#'}:
lex.buf.setLen(lenBeforeSpace)
lex.nextImpl = expectLineEnd[T]
lex.stored = if lex.inFlow: flowStyle[T] else: blockStyle[T]
break outer
of ':':
2016-09-10 10:38:03 +00:00
if lex.nextIsPlainSafe(lex.inFlow): break
2016-09-10 08:30:40 +00:00
else:
lex.buf.setLen(lenBeforeSpace)
lex.nextImpl = lex.stored
break outer
of flowIndicators:
if lex.inFlow:
lex.buf.setLen(lenBeforeSpace)
lex.nextImpl = lex.stored
break outer
else:
lex.buf.add(lex.c)
lex.advance()
break
of space: discard
else: break
of flowIndicators:
if lex.inFlow:
lex.nextImpl = lex.stored
break
of ':':
2016-09-10 10:38:03 +00:00
if not lex.nextIsPlainSafe(lex.inFlow): break outer
2016-09-10 08:30:40 +00:00
else: discard
t = ltScalarPart
result = true
proc flowStyle[T](lex: YamlLexer[T], t: var LexerToken): bool =
result = false
proc streamEnd[T](lex: YamlLexer[T], t: var LexerToken): bool =
t = ltStreamEnd
result = true