summaryrefslogtreecommitdiff
path: root/scalatexApi/src/main/scala/scalatex/stages/Compiler.scala
blob: 618402cbba72a7d7d76533c37132eeedbf12c27f (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
package scalatex.stages
import acyclic.file

import scala.reflect.macros.Context
import scala.reflect.internal.util.{Position, OffsetPosition}

/**
 * Walks the parsed AST, converting it into an un-structured Scala source-blob
 * which when compiled results in a function that can be used to generate the
 * given Frag at runtime.
 */
object Compiler{
  val WN = TwistNodes
  def apply(c: Context)(literalPos: c.Position, template: WN.Template): c.Tree = {

    import c.universe._
    def fragType = tq"scalatags.Text.all.Frag"
    def posFor(offset: Int) = {
      new OffsetPosition(
        literalPos.source,
        offset
      ).asInstanceOf[c.universe.Position]
    }
    def compileTree(frag: WN.TemplateTree): Tree = {
      println(frag)
//      println(frag)
      val fragPos = posFor(literalPos.point + frag.offset)

//      println(s"${frag.offset}\n${literalPos.point}\n${pos.point}\n$frag\n")

      val f: Tree = frag match {
        case WN.Plain(text, offset) => q"$text"
        case WN.Display(exp, offset) => compileTree(exp)
        case WN.Comment(msg, offset) => q""
        case WN.ScalaExp(Seq(WN.Simple(first, _), WN.Block(ws, args, content, _)), offset)
          if first.startsWith("for(") =>
          val fresh = c.fresh()
          val skeleton: Tree = c.parse(first + s"{$fresh}").asInstanceOf[Apply]
//          println("FIRST " + first)
          skeleton.foreach{x =>
            x
            if (x.pos != NoPosition) c.internal.setPos(x, posFor(x.pos.point + fragPos.point + 1))
          }
          val b = content.map(compileTree(_))
          def rec(t: Tree): Tree = t match {
            case a @ Apply(fun, List(f @ Function(vparams, body))) =>
              val f2 = Function(vparams, rec(body))
              val a2 = Apply(fun, List(f2))
              c.internal.setPos(a2, a.pos)
              c.internal.setPos(f2, f.pos)
              a2
            case Ident(x: TermName) if x.decoded == fresh =>
              q"Seq[$fragType](..$b)"
          }

          val out = rec(skeleton)


          out

        case WN.ScalaExp(WN.Simple(first, _) +: WN.Block(_, None, content1, _) +: rest, offset)
          if first.startsWith("if(") =>

          val b1 = content1.map(compileTree(_))
          val tree = c.parse(first + "{}").asInstanceOf[If]
          tree.foreach{x =>
            c.internal.setPos(x, posFor(x.pos.point + fragPos.point + 1))
          }
          val If(cond, _, _) = tree
          val b2 = rest match{
            case Seq(WN.Simple(next, _), WN.Block(_, None, content2, _)) =>
              content2.map(compileTree(_))
            case Seq() => Nil
          }
          q"if($cond){ Seq[$fragType](..$b1): $fragType } else { Seq[$fragType](..$b2): $fragType }"

        case xx @ WN.ScalaExp(WN.Simple(first, _) +: rest, offset) =>
          println("xx " + xx)
          val firstTree = c.parse(first)

          firstTree.foreach{x =>
            c.internal.setPos(x, posFor(x.pos.point + fragPos.point))
          }

          val s = rest.foldLeft[Tree](firstTree) {
            case (l, WN.Simple(code, _)) =>

              val fresh = c.fresh()

              val snippet = s"$fresh$code"
              val skeleton = c.parse(snippet)

              def rec(t: Tree): Tree = {
                val newPos = posFor(fragPos.point + t.pos.point + first.length - fresh.length)
                val res = t match {
                  case Apply(fun, args) =>
                    for(arg <- args; tree <- arg if tree.pos != NoPosition){
                      c.internal.setPos(tree, posFor(tree.pos.point + newPos.point - t.pos.point))
                    }

                    Apply(rec(fun), args)
                  case Select(qualifier, name) => Select(rec(qualifier), name)
                  case Ident(x: TermName) if x.decoded == fresh => l
                }
                c.internal.setPos(res, newPos)
                println("CC " + res)
//                println(Position.formatMessage(newPos.asInstanceOf[scala.reflect.internal.util.Position], "", true))
                res
              }


              val res = rec(skeleton)
              println(";;;")
              println(showCode(res, printPositions = true))
              res

            case (l, b @ WN.Block(ws, None, content, _)) =>
              val contentTrees = content.map( c =>
                atPos(posFor(fragPos.point + c.offset))(compileTree(c))
              )
              val res = atPos(posFor(fragPos.point + b.offset))(q"$l(..$contentTrees)")
              res

            case (l, b @ WN.Block(ws, Some(args), content, _)) =>

              val snippet = s"{$args ()}"
              val skeleton = c.parse(snippet)

              val Function(vparams, body) = skeleton
              println("XXXXX")
              println(snippet)
              println("XXXXX")
              println(vparams.map(showCode(_, printPositions = true)))
              vparams.map(_.foreach { t =>
                println(t + "\t" + t.pos)
                if (t.pos != NoPosition)
                  c.internal.setPos(t, posFor(fragPos.point + t.pos.point))
              })
              println(vparams.map(showCode(_, printPositions = true)))
              println("XXXXX")
              val contentTrees = content.map{t =>
                val tree = compileTree(t)
                c.internal.setPos(tree, posFor(fragPos.point + t.offset))
                tree
              }

              val func = Function(vparams, q"Seq[$fragType](..$contentTrees)")
              c.internal.setPos(func, posFor(fragPos.point + skeleton.pos.point))
              val res = q"$l($func)"
              c.internal.setPos(res, posFor(fragPos.point + b.offset))
              println(showCode(res, printPositions = true))
              println("XXXXX")
              res
          }

          s
      }

//      f.foreach(_.pos = pos)

//      println("XXX " + f.pos)
//      println("F " + f)
      f
    }

    def compileTemplate(tmpl: WN.Template): Tree = {
      val WN.Template(name, comment, params, topImports, imports, subs, content, offset) = tmpl
      val fullName = if (name.toString == "") c.fresh("outer") else name

      val DefDef(mods, realName, tparams, vparamss, tpt, rhs) = {
        val snippet = s"def $fullName$params = {}"
        val z = c.parse(snippet).asInstanceOf[DefDef]
        z
      }

      val innerDefs = subs.map(compileTemplate(_))

      val body = atPos(literalPos)(q"""{
        import scalatags.Text.all._
        ..${topImports.map(i => c.parse(i.code))}
        ..$innerDefs

        Seq[scalatags.Text.all.Frag](..${content.map(compileTree(_))})
      }""")

      if (name.toString == "") body
      else DefDef(mods, realName, tparams, vparamss, tpt, body)
    }

    atPos(literalPos)(q"${compileTemplate(template)}")
  }
}