aboutsummaryrefslogtreecommitdiff
path: root/yamlesque/src/main/scala/YamlParser.scala
blob: 71849f12aea71678d4a6412c6c1dfc98a9f5180f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package yamlesque

import annotation.{switch, tailrec}
import scala.collection.mutable.ListBuffer

object YamlParser extends (Iterator[Char] => YamlValue) {

  sealed trait TokenKind
  object TokenKind {
    case object EOF extends TokenKind
    case object BAD extends TokenKind
    case object DOCSTART extends TokenKind
    case object DOCEND extends TokenKind
    case object MAPPING extends TokenKind
    case object ITEM extends TokenKind
    case object IDENTIFIER extends TokenKind
    case object COMMENT extends TokenKind
  }
  import TokenKind._

  case class Token(val kind: TokenKind, value: String = "") {
    var line: Int = 0
    var col: Int = 0
    def setPos(line: Int, col: Int): this.type = {
      this.col = col
      this.line = line
      this
    }
    override def toString() = {
      s"($line, $col): " + super.toString
    }
  }

  object Chars {
    final val LF = '\u000A'
    final val CR = '\u000D'
    final val SU = '\u001A'

    @inline def isSpace(ch: Char): Boolean = ch match {
      case ' ' | '\t' => true
      case _          => false
    }

    @inline def isBlank(ch: Char): Boolean = ch match {
      case ' ' | '\t' | CR | LF | SU => true
      case _                         => false
    }
  }

  class Scanner(chars: Iterator[Char]) extends Iterator[Token] {
    import Chars._

    private var ch0: Char = 0
    private var ch1: Char = 0
    private var ch2: Char = 0
    private var pos: Long = 0
    private var line: Int = 0
    private var col: Int = 0

    private def skipChar(): Unit = {
      val ch: Char = if (chars.hasNext) {
        chars.next()
      } else {
        SU
      }
      pos += 1
      col += 1
      ch0 = ch1
      ch1 = ch2
      ch2 = ch
    }
    private def skipChars(n: Int): Unit = {
      var i = 0
      while (i < n) { skipChar(); i += 1 }
    }
    def init() = {
      skipChars(3)
      pos = 0
      col = 0
      line = 0
    }

    private var buffer = new StringBuilder()
    private def putChar(): Unit = {
      buffer.append(ch0)
      skipChars(1)
    }
    private def tokenValue(): String = {
      val str = buffer.result()
      buffer.clear()
      str
    }

    private var token: Token = Token(BAD, "not yet initialized")

    @tailrec private def fetchToken(): Unit = {
      ch0 match {
        case ':' if isBlank(ch1) =>
          token = Token(MAPPING).setPos(line, col)
          skipChars(1)
        case '-' if isBlank(ch1) =>
          token = Token(ITEM).setPos(line, col)
          skipChars(1)
        case '-' if ch1 == '-' && ch2 == '-' =>
          token = Token(DOCSTART).setPos(line, col)
          skipChars(3)
        case '.' if ch1 == '.' && ch2 == '.' =>
          token = Token(DOCEND).setPos(line, col)
          skipChars(3)
        case '#' =>
          val l = line
          val c = col
          skipChars(1)
          while (ch0 != LF && ch0 != SU) {
            putChar()
          }
          token = Token(COMMENT, tokenValue()).setPos(l, c)
          buffer.clear()
        case c if isSpace(c) =>
          skipChars(1)
          fetchToken()
        case LF =>
          skipChars(1)
          col = 0
          line += 1
          fetchToken()
        case CR =>
          skipChars(1)
          if (ch0 == LF) {
            skipChars(1)
          }
          col = 0
          line += 1
          fetchToken()
        case SU =>
          token = Token(EOF).setPos(line, col)
          skipChars(1)
        case _ => fetchScalar()
      }
    }

    private def fetchScalar(): Unit = {
      def finishScalar() = token = Token(IDENTIFIER, tokenValue())
      @tailrec def fetchRest(): Unit = ch0 match {
        case ':' if isBlank(ch1) =>
          finishScalar()
        case LF =>
          finishScalar()
        case SU =>
          finishScalar()
        case c =>
          putChar()
          fetchRest()
      }
      val l = line
      val c = col
      fetchRest()
      token.setPos(l, c)
    }

    override def hasNext: Boolean = true
    override def next(): Token = {
      fetchToken()
      token
    }
    init()
  }

  def parse(tokens: Iterator[Token]): YamlValue = {
    var token0 = tokens.next()
    var token1 = tokens.next()

    def readNext(): Unit = {
      token0 = token1
      token1 = tokens.next()
    }

    def fatal(message: String, token: Token) = {
      val completeMessage =
        s"parse error at line ${token.line}, column ${token.col}: $message"
      throw new ParseException(completeMessage)
    }

    def wrongKind(found: Token, required: TokenKind*) = {
      fatal(
        s"token kind not allowed at this position\n" +
          s"  found: ${found.kind}\n" +
          s"  required: ${required.mkString(" or ")}\n" +
          " " * found.col + found.value + "\n" +
          " " * found.col + "^",
        found
      )
    }

    def nextSequence() = {
      val startCol = token0.col
      val items = new ListBuffer[YamlValue]
      while (startCol <= token0.col && token0.kind != EOF) {
        token0.kind match {
          case ITEM =>
            readNext()
            items += nextBlock(startCol)
          case _ => wrongKind(token0, ITEM)
        }
      }
      YamlSequence(items.toVector)
    }

    def nextMapping() = {
      val startCol = token0.col
      val fields = new ListBuffer[(String, YamlValue)]
      while (startCol <= token0.col && token0.kind != EOF) {
        token0.kind match {
          case IDENTIFIER =>
            val key = token0.value
            readNext()
            token0.kind match {
              case MAPPING =>
                readNext()
                val value = nextBlock(startCol)
                fields += key -> value
              case _ => wrongKind(token0, MAPPING)
            }

          case _ => wrongKind(token0, IDENTIFIER)
        }
      }
      YamlMapping(fields.toMap)
    }

    def nextBlock(startCol: Int): YamlValue = {
      if (token0.col < startCol) {
        YamlScalar.Empty
      } else {
        token0.kind match {
          case IDENTIFIER =>
            if (token1.kind == MAPPING && token0.line == token1.line) {
              nextMapping()
            } else {
              val y = YamlScalar(token0.value)
              readNext()
              y
            }
          case ITEM =>
            nextSequence()
          case EOF => YamlScalar.Empty
          case _   => wrongKind(token0, IDENTIFIER, ITEM)
        }
      }
    }

    nextBlock(0)
  }

  def apply(data: Iterator[Char]): YamlValue = parse(new Scanner(data))

}

class ParseException(val message: String) extends Exception(message)