|
| 1 | +package org.glavo.dotty { |
| 2 | + |
| 3 | +import scala.collection.mutable |
| 4 | + |
| 5 | +sealed trait Node { |
| 6 | + def mkString(n: Int): String |
| 7 | +} |
| 8 | + |
| 9 | +class Tag(val name: String, |
| 10 | + val attributes: mutable.LinkedHashMap[Symbol, String] = mutable.LinkedHashMap(), |
| 11 | + val children: mutable.Buffer[Node] = mutable.Buffer()) extends Node { |
| 12 | + |
| 13 | + override def mkString(n: Int): String = { |
| 14 | + Tag.spaces(n) + s"<$name ${attributes.map(_.name + "=" + Tag.unescape(_)).mkString(" ")}>" + |
| 15 | + (if(children.isEmpty) "\n" |
| 16 | + else children.map(_.mkString(n + 4)).mkString("\n", "\n", "\n")) + |
| 17 | + Tag.spaces(n) + s"</$name>" |
| 18 | + } |
| 19 | + |
| 20 | + def apply(attrs: (Symbol, String)*): this.type = { |
| 21 | + attributes ++= attrs |
| 22 | + this |
| 23 | + } |
| 24 | + |
| 25 | + def apply[U](f: implicit Tag => U)(implicit t: Tag = null): this.type = { |
| 26 | + if(t != null) t.children += this |
| 27 | + f(this) |
| 28 | + this |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +object Tag { |
| 33 | + def spaces(n: Int = 0): String = { |
| 34 | + if(n == 0) "" |
| 35 | + else { |
| 36 | + val cs = new Array[Char](n) |
| 37 | + for (i <- 0 until n) |
| 38 | + cs(i) = 0 |
| 39 | + |
| 40 | + new String(cs) |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + def unescape(str: String): String = { |
| 45 | + "\"" + str + "\"" |
| 46 | + } |
| 47 | + |
| 48 | + implicit def symbolToTag(symbol: Symbol): Tag = |
| 49 | + new Tag(symbol.name) |
| 50 | + |
| 51 | + implicit class PairMaker(val tag: Symbol) extends AnyVal { |
| 52 | + def :=(value: String): (Symbol, String) = (tag, value) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +class Text(val value: String) extends Node { |
| 57 | + override def mkString(n: Int): String = { |
| 58 | + Tag.spaces(n) + value |
| 59 | + } |
| 60 | +} |
| 61 | +} |
| 62 | + |
| 63 | +object Test { |
| 64 | +import org.glavo.dotty._ |
| 65 | +import org.glavo.dotty.Tag._ |
| 66 | +'html{} // error |
| 67 | +} |
0 commit comments