summaryrefslogtreecommitdiff
path: root/api/src/main/scala/twist/stages/Parser.scala
blob: 925cbccd2834066c0beee790b1cda98f3536a963 (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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
package twist.stages

import acyclic.file
import scala.annotation.elidable
import scala.annotation.elidable._
import scala.Some

import scala.collection.mutable.{ArrayBuffer, Buffer, ListBuffer}

object TwistNodes{
  trait Positioned{
    def offset: Int
  }
  abstract class TemplateTree extends Positioned
  abstract class ScalaExpPart extends Positioned

  case class Params(code: String, offset: Int) extends Positioned
  case class Template(name: PosString, comment: Option[Comment], params: PosString, topImports: Seq[Simple], imports: Seq[Simple], sub: Seq[Template], content: Seq[TemplateTree], offset: Int) extends Positioned
  case class PosString(str: String, offset: Int) extends Positioned {
    override def toString = str
  }
  case class Plain(text: String, offset: Int) extends TemplateTree with Positioned
  case class Display(exp: ScalaExp, offset: Int) extends TemplateTree with Positioned
  case class Comment(msg: String, offset: Int) extends TemplateTree with Positioned
  case class ScalaExp(parts: Seq[ScalaExpPart], offset: Int) extends TemplateTree with Positioned
  case class Simple(code: String, offset: Int) extends ScalaExpPart with Positioned
  case class Block(whitespace: String, args: Option[PosString], content: Seq[TemplateTree], offset: Int) extends ScalaExpPart with Positioned
}

import TwistNodes._

object Parser extends (String => Template){
  def apply(source: String) = {
    Parser.parse(source, _.template()) match{
      case Parser.Success(tmpl: Template, input) => tmpl
      case Parser.Error(input, errors) => throw new Exception("Parsing Failed " + errors.mkString("\n"))
    }
  }

  def parse[T](source: String, f: Parser => T): ParseResult[T] = {
    val p = new Parser

    // Initialize mutable state

    p.input.reset(source)
    p.errorStack.clear()
    val res = f(p)

    if (p.errorStack.length == 0 && res != null) Success(res, p.input)
    else Error(p.input, p.errorStack.toList)
  }

  sealed abstract class ParseResult[+T]{
    def toOption: Option[T]
  }
  case class Success[+T](t: T, input: Input) extends ParseResult[T]{
    def toOption = Some(t)
  }
  case class Error(input: Input, errors: List[PosString]) extends ParseResult[Nothing]{
    def toOption = None
  }

  case class Input() {
    private var offset_ = 0
    private var source_ = ""
    private var length_ = 1
    val regressionStatistics = new collection.mutable.HashMap[String, (Int, Int)]

    /** Peek at the current input. Does not check for EOF. */
    def apply(): Char = source_.charAt(offset_)

    /**
     * Peek `length` characters ahead. Does not check for EOF.
     * @return string from current offset upto current offset + `length`
     */
    def apply(length: Int): String = source_.substring(offset_, (offset_ + length))

    /** Equivalent to `input(str.length) == str`. Does not check for EOF. */
    def matches(str: String): Boolean = {
      var i = 0;
      val l = str.length
      while (i < l) {
        if (source_.charAt(offset_ + i) != str.charAt(i))
          return false
        i += 1
      }
      true
    }

    /** Advance input by one character */
    def advance(): Unit = offset_ += 1

    /** Advance input by `increment` number of characters */
    def advance(increment: Int): Unit = offset_ += increment

    /** Backtrack by `decrement` numner of characters */
    def regress(decrement: Int): Unit = offset_ -= decrement

    /** Backtrack to a known offset */
    def regressTo(offset: Int): Unit = {
      @noinline @elidable(INFO)
      def updateRegressionStatistics() = {
        val distance = offset_ - offset
        val methodName = Thread.currentThread().getStackTrace()(2).getMethodName()
        val (count, charAccum) = regressionStatistics.get(methodName) getOrElse ((0, 0))
        regressionStatistics(methodName) = (count + 1, charAccum + distance)
      }

      offset_ = offset
    }

    def isPastEOF(len: Int): Boolean = (offset_ + len-1) >= length_

    def isEOF() = isPastEOF(1)

    def atEnd() = isEOF()

    def offset() = offset_

    def source() = source_

    /** Reset the input to have the given contents */
    def reset(source: String) {
      offset_ = 0
      source_ = source
      length_ = source.length()
      regressionStatistics.clear()
    }
  }
}
class Parser{
  import Parser._

  val input: Input = new Input
  val errorStack: ListBuffer[PosString] = ListBuffer()

  /**
   *  Try to match `str` and advance `str.length` characters.
   *
   *  Reports an error if the input does not match `str` or if `str.length` goes past the EOF.
   */
  def accept(str: String): Unit = {
    val len = str.length
    if (!input.isPastEOF(len) && input.matches(str))
      input.advance(len)
    else
      error("Expected '" + str + "' but found '" + (if (input.isPastEOF(len)) "EOF" else input(len)) + "'")
  }

  /**
   *  Does `f` applied to the current peek return true or false? If true, advance one character.
   *
   *  Will not advance if at EOF.
   *
   *  @return true if advancing, false otherwise.
   */
  def check(f: Char => Boolean): Boolean = {
    if (!input.isEOF() && f(input())) {
      input.advance()
      true
    } else false
  }

  /**
   *  Does the current input match `str`? If so, advance `str.length`.
   *
   *  Will not advance if `str.length` surpasses EOF
   *
   *  @return true if advancing, false otherwise.
   */
  def check(str: String): Boolean = {
    val len = str.length
    if (!input.isPastEOF(len) && input.matches(str)){
      input.advance(len)
      true
    } else false
  }

  def error(message: String, offset: Int = input.offset): Unit = {
    errorStack += PosString(message, offset)
  }

  /** Consume/Advance `length` characters, and return the consumed characters. Returns "" if at EOF. */
  def any(length: Int = 1): String = {
    if (input.isEOF()) {
      error("Expected more input but found 'EOF'")
      ""
    } else {
      val s = input(length)
      input.advance(length)
      s
    }
  }

  /**
   *  Consume characters until input matches `stop`
   *
   *  @param inclusive - should stop be included in the consumed characters?
   *  @return the consumed characters
   */
  def anyUntil(stop: String, inclusive: Boolean): String = {
    var sb = new StringBuilder
    while (!input.isPastEOF(stop.length) && !input.matches(stop))
      sb.append(any())
    if (inclusive && !input.isPastEOF(stop.length))
      sb.append(any(stop.length))
    sb.toString()
  }

  /**
   *  Consume characters until `f` returns false on the peek of input.
   *
   *  @param inclusive - should the stopped character be included in the consumed characters?
   *  @return the consumed characters
   */
  def anyUntil(f: Char => Boolean, inclusive: Boolean): String = {
    var sb = new StringBuilder
    while (!input.isEOF() && f(input()) == false)
      sb.append(any())
    if (inclusive && !input.isEOF())
      sb.append(any())
    sb.toString
  }

  /** Recursively match pairs of prefixes and suffixes and return the consumed characters
    *
    *  Terminates at EOF.
    */
  def recursiveTag(prefix: String, suffix: String, allowStringLiterals: Boolean = false): String = {
    if (check(prefix)) {
      var stack = 1
      val sb = new StringBuffer
      sb.append(prefix)
      while (stack > 0) {
        if (check(prefix)) {
          stack += 1
          sb.append(prefix)
        } else if (check(suffix)) {
          stack -= 1
          sb.append(suffix)
        } else if (input.isEOF()) {
          error("Expected '" + suffix + "' but found 'EOF'")
          stack = 0
        } else if (allowStringLiterals) {
          stringLiteral("\"", "\\") match {
            case null => sb.append(any())
            case s => sb.append(s)
          }
        } else {
          sb.append(any())
        }
      }
      sb.toString()
    } else null
  }

  /**
   * Match a string literal, allowing for escaped quotes.
   * Terminates at EOF.
   */
  def stringLiteral(quote: String, escape: String): String = {
    if (check(quote)) {
      var within = true
      val sb = new StringBuffer
      sb.append(quote)
      while (within) {
        if (check(quote)) { // end of string literal
          sb.append(quote)
          within = false
        } else if (check(escape)) {
          sb.append(escape)
          if (check(quote)) { // escaped quote
            sb.append(quote)
          } else if (check(escape)) { // escaped escape
            sb.append(escape)
          }
        } else if (input.isEOF()) {
          error("Expected '" + quote + "' but found 'EOF'")
          within = false
        } else {
          sb.append(any())
        }
      }
      sb.toString()
    } else null
  }

  /** Match zero or more `parser` */
  def several[T, BufferType <: Buffer[T]](parser: () => T, provided: BufferType = null)(implicit manifest: Manifest[BufferType]): BufferType = {

    val ab = if (provided != null) provided else manifest.runtimeClass.newInstance().asInstanceOf[BufferType]
    var parsed = parser()
    while (parsed != null) {
      ab += parsed
      parsed = parser()
    }
    ab
  }

  def parentheses(): String = recursiveTag("(", ")", allowStringLiterals = true)

  def squareBrackets(): String = recursiveTag("[", "]")

  def whitespace(): String = anyUntil(_ > '\u0020', inclusive = false)

  // not completely faithful to original because it allows for zero whitespace
  def whitespaceNoBreak(): String = anyUntil(c => c != ' ' && c != '\t', inclusive = false)

  def identifier(): String = {
    var result: String = null
    // TODO: should I be checking for EOF here?
    if (!input.isEOF() && Character.isJavaIdentifierStart(input())) {
      result = anyUntil(Character.isJavaIdentifierPart(_) == false, false)
    }
    result
  }

  def comment(): Comment = {
    val pos = input.offset
    if (check("@*")) {
      val text = anyUntil("*@", inclusive = false)
      accept("*@")
      Comment(text, pos)
    } else null
  }

  def startArgs(): String = {
    val result = several[String, ArrayBuffer[String]](parentheses)
    if (result.length > 0)
      result.mkString
    else
      null
  }

  def importExpression(): Simple = {
    val p = input.offset
    if (check("@import "))
      Simple("import " + anyUntil("\n", inclusive = true).trim, p+1) // don't include position of @
    else null
  }

  def scalaBlock(): Simple = {
    if (check("@{")) {
      input.regress(1); // we need to parse the '{' via 'brackets()'
      val p = input.offset
      brackets() match {
        case null => null
        case b => Simple(b, p)
      }
    } else null
  }

  def brackets(): String = {
    var result = recursiveTag("{", "}")
    // mimicking how the original parser handled EOF for this rule
    if (result != null && result.last != '}')
      result = null
    result
  }

  def mixed(): ListBuffer[TemplateTree] = {
    // parses: comment | scalaBlockDisplayed | forExpression | matchExpOrSafeExprOrExpr | caseExpression | plain
    def opt1(): ListBuffer[TemplateTree] = {
      val t =
        comment() match {
          case null => scalaBlockDisplayed() match {
            case null => forExpression match {
              case null => matchExpOrSafeExpOrExpr() match {
                case null => caseExpression() match {
                  case null => plain()
                  case x => x
                }
                case x => x
              }
              case x => x
            }
            case x => x
          }
          case x => x
        }
      if (t != null) ListBuffer(t)
      else null
    }

    // parses: '{' mixed* '}'
    def opt2(): ListBuffer[TemplateTree] = {
      val lbracepos = input.offset()
      if (check("{")) {
        var buffer = new ListBuffer[TemplateTree]
        buffer += Plain("{", lbracepos)
        for (m <- several[ListBuffer[TemplateTree], ListBuffer[ListBuffer[TemplateTree]]](mixed))
          buffer = buffer ++ m // creates a new object, but is constant in time, as opposed to buffer ++= m which is linear (proportional to size of m)
        val rbracepos = input.offset
        if (check("}"))
          buffer += Plain("}", rbracepos)
        else
          error("Expected ending '}'")
        buffer
      } else null
    }

    opt1() match {
      case null => opt2()
      case x => x
    }
  }

  def scalaBlockDisplayed(): Display = {
    val sb = scalaBlock()

    if (sb != null)
      Display(ScalaExp(sb :: Nil, sb.offset), sb.offset)
    else
      null
  }

  def blockArgs(): PosString = {
    val p = input.offset
    val result = anyUntil("=>", true)
    if (result.endsWith("=>") && !result.contains("\n"))
      PosString(result, p)
    else {
      input.regress(result.length())
      null
    }
  }

  def block(): Block = {
    var result: Block = null
    val p = input.offset
    val ws = whitespaceNoBreak()
    if (check("{")) {
      val blkArgs = Option(blockArgs())
      val mixeds = several[ListBuffer[TemplateTree], ListBuffer[ListBuffer[TemplateTree]]](mixed)
      accept("}")
      // TODO - not use flatten here (if it's a performance problem)
      result = Block(ws, blkArgs, mixeds.flatten, p)
    } else {
      input.regressTo(p)
    }

    result
  }

  def caseExpression(): TemplateTree = {
    var result: TemplateTree = null

    val wspos = input.offset
    val ws = whitespace()
    val p = input.offset()
    if (check("case ")) {
      val pattern = Simple("case " + anyUntil("=>", inclusive = true), p)
      val blk = block()
      if (blk != null) {
        result = ScalaExp(ListBuffer(pattern, blk), blk.offset)
        whitespace()
      } else {
        //error("Expected block after 'case'")
        input.regressTo(wspos)
      }
    } else if (ws.length > 0) {
      // We could regress here and not return something for the ws, because the plain production rule
      // would parse this, but this would actually be a hotspot for backtracking, so let's return it
      // here seeing as it's been parsed all ready.
      result = Plain(ws, wspos)
    }

    result
  }

  def matchExpOrSafeExpOrExpr(): Display = {
    val resetPosition = input.offset
    val result =
      expression() match {
        case null => safeExpression()
        case x => x
      }

    if (result != null) {
      val exprs = result.exp.parts.asInstanceOf[ListBuffer[ScalaExpPart]]
      val mpos = input.offset
      val ws = whitespaceNoBreak()
      if (check("match")) {
        val m = Simple(ws + "match", mpos)
        val blk = block()
        if (blk != null) {
          exprs.append(m)
          exprs.append(blk)
        } else {
          // error("expected block after match")
          input.regressTo(mpos)
        }
      } else {
        input.regressTo(mpos)
      }
    }

    result
  }

  def forExpression(): Display = {
    var result: Display = null
    val p = input.offset
    if (check("@for")) {
      val parens = parentheses()
      if (parens != null) {
        val blk = block()
        if (blk != null) {
          result = Display(ScalaExp(ListBuffer(Simple("for" + parens + " yield ", p+1), blk), p+1), p+1) // don't include pos of @
        }
      }
    }

    if (result == null)
      input.regressTo(p)

    result
  }

  def safeExpression(): Display = {
    if (check("@(")) {
      input.regress(1)
      val p = input.offset
      Display(ScalaExp(ListBuffer(Simple(parentheses(), p)), p), p)
    } else null
  }

  def plain(): Plain = {
    def single(): String = {
      if (check("@@")) "@"
      else if (!input.isEOF() && input() != '@' && input() != '}' && input() != '{') any()
      else null
    }
    val p = input.offset
    var result: Plain = null
    var part = single()
    if (part != null) {
      val sb = new StringBuffer
      while (part != null) {
        sb.append(part)
        part = single()
      }
      result = Plain(sb.toString(), p)
    }

    result
  }

  def expression(): Display = {
    var result: Display = null
    if (check("@")) {
      val pos = input.offset
      val code = methodCall()
      if (code != null) {
        val parts = several[ScalaExpPart, ListBuffer[ScalaExpPart]](expressionPart)
        parts.prepend(Simple(code, pos))
        result = Display(ScalaExp(parts, pos-1), pos-1)
      } else {
        input.regressTo(pos - 1) // don't consume the @ if we fail
      }
    }

    result
  }

  def methodCall(): String = {
    val name = identifier()
    if (name != null) {
      val sb = new StringBuffer(name)
      sb.append(Option(squareBrackets) getOrElse "")
      sb.append(Option(parentheses) getOrElse "")
      sb.toString()
    } else null
  }

  def expressionPart(): ScalaExpPart = {
    def simpleParens() = {
      val p = input.offset
      val parens = parentheses()
      if (parens != null) Simple(parens, p)
      else null
    }

    def wsThenScalaBlockChained() = {
      val reset = input.offset
      val ws = whitespaceNoBreak()
      val chained = scalaBlockChained()
      if (chained eq null) input.regressTo(reset)
      chained
    }

    chainedMethods() match {
      case null => block() match {
        case null => wsThenScalaBlockChained() match {
          case null => elseCall() match {
            case null => simpleParens()
            case x => x
          }
          case x => x
        }
        case x => x
      }
      case x => x
    }
  }

  def scalaBlockChained(): Block = {
    val blk = scalaBlock()
    if (blk != null)
      Block("", None, ListBuffer(ScalaExp(ListBuffer(blk), blk.offset)), blk.offset)
    else null
  }

  def chainedMethods(): Simple = {
    val p = input.offset
    var result: Simple = null
    if (check(".")) {
      val firstMethodCall = methodCall()
      if (firstMethodCall != null) {
        val sb = new StringBuffer("." + firstMethodCall)
        var done = false
        while (!done) {
          val reset = input.offset
          var nextLink: String = null
          if (check(".")) {
            methodCall() match {
              case m: String => nextLink = m
              case _ =>
            }
          }

          nextLink match {
            case null => {
              done = true
              input.regressTo(reset)
            }
            case _ => {
              sb.append(".")
              sb.append(nextLink)
            }
          }
        }

        result = Simple(sb.toString(), p)
      } else input.regressTo(p)
    }

    result
  }

  def elseCall(): Simple = {
    val reset = input.offset
    whitespaceNoBreak()
    val p = input.offset
    if (check("else")) {
      whitespaceNoBreak()
      Simple("else", p)
    } else {
      input.regressTo(reset)
      null
    }
  }

  def template(): Template = {
    val topImports = extraImports()
    whitespace()
    val commentpos = input.offset
    val cm = Option(comment()).map(_.copy(offset = commentpos))
    whitespace()
    val args =
      if (check("@(")) {
        input.regress(1)
        val p = input.offset
        val args = startArgs()
        if (args != null) Some(PosString(args, p))
        else None
      } else None
    val (imports, templates, mixeds) = templateContent()

    Template(PosString("", 0), cm, args.getOrElse(PosString("()", 0)), topImports, imports, templates, mixeds, 0)
  }
  def subTemplate(): Template = {
    var result: Template = null
    val resetPosition = input.offset
    val templDecl = templateDeclaration()
    if (templDecl != null) {
      anyUntil(c => c != ' ' && c != '\t', inclusive = false)
      if (check("{")) {
        val (imports, templates, mixeds) = templateContent()
        if (check("}"))
          result = Template(templDecl._1, None, templDecl._2, Nil, imports, templates, mixeds, templDecl._1.offset)
      }
    }

    if (result == null)
      input.regressTo(resetPosition)
    result
  }

  def templateDeclaration(): (PosString, PosString) = {
    if (check("@")) {
      val namepos = input.offset
      val name = identifier() match {
        case null => null
        case id => PosString(id, namepos)
      }

      if (name != null) {
        val paramspos = input.offset
        val types = Option(squareBrackets) getOrElse ""
        val args = several[String, ArrayBuffer[String]](parentheses)
        val params = PosString(types + args.mkString, paramspos)
        if (params != null)

          anyUntil(c => c != ' ' && c != '\t', inclusive = false)
          if (check("=")) {
            return (name, params)
          }
      } else input.regress(1) // don't consume @
    }

    null
  }

  def templateContent(): (Seq[Simple], Seq[Template], Seq[TemplateTree]) = {
    val imports = new ArrayBuffer[Simple]

    val templates = new ArrayBuffer[Template]
    val mixeds = new ArrayBuffer[TemplateTree]

    var done = false
    while (!done) {
      val impExp = importExpression()
      if (impExp != null) imports += impExp
      else {

        val templ = subTemplate()
        if (templ != null) templates += templ
        else {
          val mix = mixed()
          if (mix != null) mixeds ++= mix
          else {
            // check for an invalid '@' symbol, and just skip it so we can continue the parse
            val pos = input.offset
            if (check("@")) error("Invalid '@' symbol", pos)
            else done = true
          }
        }
      }
    }

    (imports, templates, mixeds)
  }

  def extraImports(): Seq[Simple] = {
    val resetPosition = input.offset
    val imports = new ArrayBuffer[Simple]

    while (whitespace().nonEmpty || (comment() ne null)) {} // ignore

    var done = false
    while (!done) {
      val importExp = importExpression()
      if (importExp ne null) {
        imports += importExp
        whitespace()
      } else {
        done = true
      }
    }

    if (imports.isEmpty) {
      input.regressTo(resetPosition)
    }

    imports
  }



  def mkRegressionStatisticsString() {
    val a = input.regressionStatistics.toArray.sortBy { case (m, (c, a)) => c }
    a.mkString("\n")
  }

  // TODO - only for debugging purposes, remove before release
  def setSource(source: String) {
    input.reset(source)
  }
}