summaryrefslogtreecommitdiff
path: root/examples/scala-js/test-suite/src/test/resources/SourceMapTestTemplate.scala
blob: 2b135effbf4589b2eda210df531eb256ab1feab7 (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
package scala.scalajs.testsuite.compiler

import org.scalajs.jasminetest.{JasmineTest, JasmineTestFramework}

/** The test counter */
private[testsuite] object TC {
  var testNum: Int = _

  def is(x: Int): Boolean = testNum == x
}

/** Exception to test source maps. Not a ControlThrowable, because it has
 *  NoStackTrace which would defeat its purpose
 */
case class TestException(lineNo: Int) extends Exception

/**
 * Template to generate source-map tests, verifying that the line numbers
 * reported in the source-mapped stacktraces match up with the line number
 * that the error originated from.
 *
 * /two-star/s in this file are replaced with a code-snippet to throw
 * an exception if `testNum` is set to the /two-star/'s index. The
 * exception is then caught and its stacktrace checked to see
 * that it reports the line number expected (stored in the error
 * message). /three-star/s in are replaced with a dangling else (to
 * allow throwing in expression position).
 * `0/*<testCount>*/` is replaced by the number of /n-star/s in the
 * file.
 */
object SourceMapTest extends JasmineTest {

  val testCount: Int = 0/*<testCount>*/

  if (JasmineTestFramework.hasTag("nodejs")) {
    scalajs.js.Dynamic.global.require("source-map-support").install()
  }

  when("source-maps").
  describe("Source Maps") {

    for (i <- 0 until testCount) {
      it(s"work (test $i)") {
        TC.testNum = i

        try {
          run()
          sys.error("No exception thrown")
        } catch {
          case e @ TestException(lineNo) =>
            val trace0 = e.getStackTrace.toList
            val trace1 = trace0.dropWhile(
              _.getFileName.endsWith("/scala/scalajs/runtime/StackTrace.scala"))
            val trace2 = trace1.dropWhile(
              _.getFileName.endsWith("/java/lang/Throwables.scala"))

            val exSte :: throwSte :: _ = trace2

            expect(exSte.getFileName).toContain("/SourceMapTest.scala")
            // line where `case class TestException is written` above
            expect(exSte.getLineNumber).toBe(15)

            expect(throwSte.getFileName).toContain("/SourceMapTest.scala")
            expect(throwSte.getLineNumber).toBe(lineNo)
        }
      }
    }
  }

  def get(json: JsValue, index: Int) = {
    /**/
    /**/json.asInstanceOf[JsArray].value(index).value
  }

  def get(json: JsValue, index: Int, fieldName: String) = {
    /**/
    /**//***/json.asInstanceOf[JsArray].value(index).asInstanceOf[JsObject].value(fieldName).value
  }
  def run() = {
    /**/
    /**/val ugly =
      """
        |[
        |    "JSON Test Pattern pass1",
        |    {"object with 1 member":["array with 1 element"]},
        |    {},
        |    [],
        |    -42,
        |    true,
        |    false,
        |    null,
        |    {
        |        "integer": 1234567890,
        |        "real": -9876.543210,
        |        "e": 0.123456789e-12,
        |        "E": 1.234567890E+34,
        |        "":  23456789012E66,
        |        "zero": 0,
        |        "one": 1,
        |        "space": " ",
        |        "quote": "\"",
        |        "backslash": "\\",
        |        "controls": "\b\f\n\r\t",
        |        "slash": "/ & \/",
        |        "alpha": "abcdefghijklmnopqrstuvwyz",
        |        "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",
        |        "digit": "0123456789",
        |        "0123456789": "digit",
        |        "special": "`1~!@#$%^&*()_+-={':[,]}|;.</>?",
        |        "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",
        |        "true": true,
        |        "false": false,
        |        "null": null,
        |        "array":[  ],
        |        "object":{  },
        |        "address": "50 St. James Street",
        |        "url": "http://www.JSON.org/",
        |        "comment": "// /* <!-- --",
        |        "# -- --> */": " ",
        |        " s p a c e d " :[1,2 , 3
        |
        |,
        |
        |4 , 5        ,          6           ,7        ],"compact":[1,2,3,4,5,6,7],
        |        "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
        |        "quotes": "&#34; \u005Cu0022 %22 0x22 034 &#x22;",
        |        "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"
        |: "A key can be any string"
        |    },
        |    0.5 ,98.6
        |,
        |99.44
        |,
        |
        |1066,
        |1e1,
        |0.1e1,
        |1e-1,
        |1e00,2e+00,2e-00
        |,"rosebud"]
      """.stripMargin/**/
    /**/val json = new Json()/**/
    /**/val parsed = json.read(ugly)/**/
    /**/
    /**/val unparsed = json.write(parsed)/**/
    /**/val reparsed = json.read(unparsed)/**/

    for (json <- Seq(parsed, reparsed)){/**/
      assert(get(json, 0) == "JSON Test Pattern pass1")
      /**/
      assert(get(json, 5) == true)
      assert(get(json, 6) == false)
      assert(get(json, 8, "real") == "-9876.543210")/**/
      /**/assert(get(json, 8, "comment") == "// /* <!-- --")
      assert(get(json, 8, "jsontext") == "{\"object with 1 member\":[\"array with 1 element\"]}")
      assert(get(json, 19) == "rosebud")/**/
    }
    /**/
  }
}



sealed trait JsValue {
  def value: Any
}

case class JsString(value: java.lang.String) extends JsValue

case class JsObject(value: Map[String, JsValue]) extends JsValue

case class JsArray(value: Seq[JsValue]) extends JsValue

case class JsNumber(value: java.lang.String) extends JsValue

sealed trait JsBoolean extends JsValue {
  def value: Boolean
}

case object JsFalse extends JsBoolean {
  def value = {/**/false}
}

case object JsTrue extends JsBoolean {
  def value = {/**/true}
}

case object JsNull extends JsValue {
  def value = {null}
}

trait Writer{
  /**/
  def writeToBuffer(v: JsValue, sb: StringBuffer): Unit = v match {
    case JsString(s) =>
      /**/sb.append('"')/**/
    /**/var i = 0/**/
      while(i < s.length){/**/
        /**/s.charAt(i) match {
          case '\\' => /**/sb.append("\\\\")/**/
          case '"' => sb.append("\\\"")
          case '/' => /**/sb.append("\\/")/**/
          case '\b' => sb.append("\\b")
          case '\t' => sb.append("\\t")
          case '\n' => /**/sb.append("\\n")/**/
          case '\f' => sb.append("\\f")
          case '\r' => sb.append("\\r")
          case c =>
            if (c < ' '){
              val t = "000" + Integer.toHexString(c)
              sb.append("\\u" + t.takeRight(4))
            }else{
              sb.append(c.toString)
            }
        }
        i += 1
      }
      /**/
      sb.append('"')
    /**/
    case JsObject(kvs) =>
      /**/
      sb.append("{")
      /**/
      var first = true
      kvs.foreach(kv => {
        /**/
        val (k, v) = kv
        if (first)
          first = false
        else
          sb.append(", ")

        /**/
        writeToBuffer(JsString(k), sb)
        sb.append(": ")
        /**/
        writeToBuffer(v, sb)
      })
      sb.append("}")

    case JsArray(vs) => /**/
      sb.append("[")
      if (vs.length > 0) writeToBuffer(vs(0), sb)
      var i = 1
      while(i < vs.length){
        sb.append(", ")
        writeToBuffer(vs(i), sb)
        i += 1
      }
      sb.append("]")
    case JsNumber(d) => sb.append(d)
    case JsFalse => sb.append("false")
    case JsTrue => sb.append("true")
    case JsNull => sb.append("null")
  }
  /**/
}
class Writer2 extends Writer{
  /**/
  def write(v: JsValue): String = {
    /**/
    val sb = new StringBuffer()
    writeToBuffer(v, sb)
    sb.toString
  }
  /**/
}
class Json extends Writer2{

  /**
   * Self-contained JSON parser adapted from
   *
   * https://github.com/nestorpersist/json
   */
  def read(s: String): JsValue = {

    // *** Character Kinds
    /**/
    type CharKind = Int
    val Letter = 0
    val Digit = 1
    val Minus = 2
    val Quote = 3
    val Colon = 4
    val Comma = 5
    val Lbra = 6
    val Rbra = 7
    val Larr = 8
    val Rarr = 9
    val Blank = 10
    val Other = 11
    val Eof = 12
    val Slash = 13

    // *** Token Kinds

    type TokenKind = Int
    val ID = 0
    val STRING = 1
    val NUMBER = 2
    val BIGNUMBER = 3
    val FLOATNUMBER = 4
    val COLON = 5
    val COMMA = 6
    val LOBJ = 7
    val ROBJ = 8
    val LARR = 9
    val RARR = 10
    val BLANK = 11
    val EOF = 12
    /**/
    // *** Character => CharKind Map ***

    val charKind = (0 to 255).toArray.map {
      case c if 'a'.toInt <= c && c <= 'z'.toInt => Letter
      case c if 'A'.toInt <= c && c <= 'Z'.toInt => Letter
      case c if '0'.toInt <= c && c <= '9'.toInt => Digit
      case '-' => /**/Minus
      case ',' => /**/Comma
      case '"' => /**/Quote
      case ':' => /**/Colon
      case '{' => /**/Lbra
      case '}' => Rbra
      case '[' => Larr
      case ']' => Rarr
      case ' ' => Blank
      case '\t' => Blank
      case '\n' => Blank
      case '\r' => Blank
      case '/' => Slash
      case _ => Other
    }

    // *** Character Escapes
    /**/
    val escapeMap = Map[Int, String](
      '\\'.toInt -> "\\",
      '/'.toInt -> "/",
      '\"'.toInt -> "\"",
      'b'.toInt -> "\b",
      'f'.toInt -> "\f",
      'n'.toInt -> "\n",
      'r'.toInt -> "\r",
      't'.toInt -> "\t"
    )
    // *** Import Shared Data ***

    // *** INPUT STRING ***

    // array faster than accessing string directly using charAt
    //final  val s1 = s.toCharArray()
    val size = s.size

    // *** CHARACTERS ***

    var pos = 0

    var ch: Int = 0
    var chKind: CharKind = 0
    var chLinePos: Int = 0
    var chCharPos: Int = 0

    def chNext() = {/**/
      if (pos < size) {/**/
        //ch = s1(pos).toInt
        /**/ch = s.charAt(pos)/**/
        /**/chKind = /***/if (ch < 255) {/**/
          /**//***/charKind(ch)
          } else {/**/
          /**//***/Other
          }/**/
        pos += 1
        if (ch == '\n'.toInt) {
          chLinePos += 1
          chCharPos = 1
        } else {/**/
          chCharPos += 1/**/
        }
      } else {
        ch = -1
        pos = size + 1
        chKind = Eof
      }
    }/**/
    /**/
    /**/
    /**/def chError(msg: String): Nothing = {
      throw new Json.Exception(msg, s, chLinePos, chCharPos)
    }

    def chMark = pos - 1

    def chSubstr(first: Int, delta: Int = 0) = {
      s.substring(first, pos - 1 - delta)
    }

    // *** LEXER ***

    var tokenKind = BLANK
    var tokenValue = ""
    var linePos = 1
    var charPos = 1

    def getDigits() = {
      while (chKind == Digit) chNext()
    }

    def handleDigit() {
      val first = chMark
      getDigits()
      val k1 = if (ch == '.'.toInt) {
        chNext()
        getDigits()
        BIGNUMBER
      } else {
        NUMBER
      }
      val k2 = if (ch == 'E'.toInt || ch == 'e'.toInt) {
        chNext()
        if (ch == '+'.toInt) {
          chNext()
        } else if (ch == '-'.toInt) {
          chNext()
        }
        getDigits()
        FLOATNUMBER
      } else {
        k1
      }
      /**/tokenKind = k2/**/
      /**/tokenValue = chSubstr(first)/**/
      /**/}/**/
    /**/
    def handleRaw() {
      chNext()
      val first = chMark
      var state = 0
      do {
        if (chKind == Eof) chError("EOF encountered in raw string")
        state = (ch, state) match {
          case ('}', _) => 1
          case ('"', 1) => 2
          case ('"', 2) => 3
          case ('"', 3) => 0
          case _ => 0
        }

        chNext()
      } while (state != 3)
      tokenKind = STRING
      tokenValue = chSubstr(first, 3)
    }

    def handle(i: Int) = {
      chNext()
      tokenKind = i
      tokenValue = ""
    }

    def tokenNext() {
      do {
        linePos = chLinePos
        charPos = chCharPos
        val kind: Int = chKind
        kind match {
          case Letter =>
            val first = chMark
            while (chKind == Letter || chKind == Digit) {
              chNext()
            }
            tokenKind = ID
            tokenValue = chSubstr(first)

          case Digit => handleDigit()
          case Minus =>
            chNext()
            handleDigit()
            tokenValue = "-" + tokenValue

          case Quote =>
            val sb = new StringBuilder(50)
            chNext()
            var first = chMark
            while (ch != '"'.toInt && ch >= 32) {
              if (ch == '\\'.toInt) {
                sb.append(chSubstr(first))
                chNext()
                escapeMap.get(ch) match {
                  case Some(s) =>
                    sb.append(s)
                    chNext()

                  case None =>
                    if (ch != 'u'.toInt) chError("Illegal escape")
                    chNext()
                    var code = 0
                    for (i <- 1 to 4) {
                      val ch1 = ch.toChar.toString
                      val i = "0123456789abcdef".indexOf(ch1.toLowerCase)
                      if (i == -1) chError("Illegal hex character")
                      code = code * 16 + i
                      chNext()
                    }
                    sb.append(code.toChar.toString)
                }
                first = chMark
              } else {
                chNext()
              }
            }
            if (ch != '"') chError("Unexpected string character: " + ch.toChar)

            sb.append(chSubstr(first))

            tokenKind = STRING

            tokenValue = sb.toString()
            chNext()
            if (tokenValue.length() == 0 && ch == '{') {
              handleRaw()
            }

          case Colon => handle(COLON)/**/
          case Comma => handle(COMMA)/**/
          case Lbra => handle(LOBJ)/**/
          case Rbra => handle(ROBJ)/**/
          case Larr => handle(LARR)/**/
          case Rarr => handle(RARR)/**/
          case Blank =>
            do chNext() while (chKind == Blank)
            tokenKind = BLANK
            tokenValue = ""

          case Other => chError("Unexpected character: " + ch.toChar + " " + ch)
          case Eof =>
            chNext()
            tokenKind = EOF
            tokenValue = ""

          case Slash =>
            if (chKind != Slash) chError("Expecting Slash")
            do chNext() while (ch != '\n' && chKind != Eof)
            tokenKind = BLANK
            tokenValue = ""

        }
      } while (tokenKind == BLANK)
    }
    /**/
    def tokenError(msg: String): Nothing = {
      throw new Json.Exception(msg, s, linePos, charPos)
    }
    /**/
    // *** PARSER ***

    def handleEof() = tokenError("Unexpected eof")
    def handleUnexpected(i: String) = tokenError(s"Unexpected input: [$i]")

    def handleArray(): JsArray = {
      tokenNext()
      var result = List.empty[JsValue]
      while (tokenKind != RARR) {/**/
        result = getJson() :: result
        /**/tokenKind match{
          case COMMA => /**/tokenNext()
          case RARR => // do nothing
          case _ => tokenError("Expecting , or ]")
        }
      }
      tokenNext()
      JsArray(result.reverse)
    }

    def handleObject(): JsObject = {
      tokenNext()
      var result = List.empty[(String, JsValue)]
      /**/
      while (tokenKind != ROBJ) {
        if (tokenKind != STRING && tokenKind != ID) tokenError("Expecting string or name")
        val name = tokenValue
        tokenNext()
        if (tokenKind != COLON) tokenError("Expecting :")
        tokenNext()
        result = (name -> getJson()) :: result
        tokenKind match{
          case COMMA => tokenNext()
          case ROBJ => // do nothing
          case _ => tokenError("Expecting , or }")
        }
      }
      tokenNext()
      JsObject(result.toMap)
    }
    def handleNumber(name: String, f: String => Unit) = {
      try {
        f(tokenValue)
      } catch {
        case _: Throwable => tokenError("Bad " + name)
      }
      val old = tokenValue
      tokenNext()

      JsNumber(old)
    }
    def getJson(): JsValue = {
      val kind: Int = tokenKind
      val result: JsValue = kind match {
        case ID =>
          val result: JsValue = tokenValue match {
            case "true" => JsTrue
            case "false" => JsFalse
            case "null" => JsNull
            case _ => tokenError("Not true, false, or null")
          }

          tokenNext()
          result

        case STRING =>
          val result = tokenValue
          tokenNext()
          JsString(result)

        case NUMBER => handleNumber("NUMBER", _.toLong)
        case BIGNUMBER => handleNumber("BIGNUMBER", _.toDouble)
        case FLOATNUMBER => handleNumber("FLOATNUMBER", _.toDouble)
        case COLON => handleUnexpected(":")
        case COMMA => handleUnexpected(",")
        case LOBJ => handleObject()
        case ROBJ => handleUnexpected("}")
        case LARR => handleArray()
        case RARR => handleUnexpected("]")
        case EOF => handleEof()
      }
      result
    }
    def parse(): JsValue = {
      chNext()
      tokenNext()
      val result = getJson
      if (tokenKind != EOF) tokenError("Excess input")
      result
    }
    parse()
  }
}

object Json {
  class Exception(val msg: String,
                  val input: String,
                  val line: Int,
                  val char: Int)
    extends scala.Exception(s"JsonParse Error: $msg line $line [$char] in $input")
}