summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala
blob: 3218a7c617593805c61b2f6fb9a5a31556af136d (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
/* NSC -- new Scala compiler
 * Copyright 2005-2007 LAMP/EPFL
 * @author  Martin Odersky
 */
// $Id$

package scala.tools.nsc.ast.parser

import symtab.Flags._
import scala.collection.mutable.ListBuffer
import scala.tools.nsc.util.Position

abstract class TreeBuilder {

  val global: Global
  import global._
  import posAssigner.atPos;
  def freshName(pos : Position, prefix: String): Name
  def freshName(pos : Position): Name = freshName(pos, "x$")

  def scalaDot(name: Name): Tree =
    Select(Ident(nme.scala_) setSymbol definitions.ScalaPackage, name)
  def scalaAnyRefConstr: Tree =
    scalaDot(nme.AnyRef.toTypeName)
  def scalaUnitConstr: Tree =
    scalaDot(nme.Unit.toTypeName)
  def scalaScalaObjectConstr: Tree =
    scalaDot(nme.ScalaObject.toTypeName)
  def productConstr: Tree =
    scalaDot(nme.Product.toTypeName)

  /** Convert all occurrences of (lower-case) variables in a pattern as follows:
   *    x                  becomes      x @ _
   *    x: T               becomes      x @ (_: T)
   */
  private object patvarTransformer extends Transformer {
    override def transform(tree: Tree): Tree = tree match {
      case Ident(name) if (treeInfo.isVarPattern(tree) && name != nme.WILDCARD) =>
        atPos(tree.pos)(Bind(name, Ident(nme.WILDCARD)))
      case Typed(id @ Ident(name), tpt) if (treeInfo.isVarPattern(id) && name != nme.WILDCARD) =>
        Bind(name, atPos(tree.pos)(Typed(Ident(nme.WILDCARD), tpt))) setPos id.pos
      case Apply(fn @ Apply(_, _), args) =>
        copy.Apply(tree, transform(fn), transformTrees(args))
      case Apply(fn, args) =>
        copy.Apply(tree, fn, transformTrees(args))
      case Typed(expr, tpt) =>
        copy.Typed(tree, transform(expr), tpt)
      case Bind(name, body) =>
        copy.Bind(tree, name, transform(body))
      case Sequence(_) | Alternative(_) | Star(_) =>
        super.transform(tree)
      case _ =>
        tree
    }
  }

  /** Traverse pattern and collect all variable names with their types in buffer */
  private object getvarTraverser extends Traverser {
    val buf = new ListBuffer[(Name, Tree, Position)]
    def init: Traverser = { buf.clear; this }
    override def traverse(tree: Tree): Unit = tree match {
      case Bind(name, Typed(tree1, tpt)) =>
        if ((name != nme.WILDCARD) && (buf.elements forall (name !=)))
          buf += ((name, if (treeInfo.mayBeTypePat(tpt)) TypeTree() else tpt, tree.pos))
        traverse(tree1)
      case Bind(name, tree1) =>
        if ((name != nme.WILDCARD) && (buf.elements forall (name !=)))
          buf += ((name, TypeTree(), tree.pos))
        traverse(tree1)
      case _ =>
        super.traverse(tree)
    }
  }

  /** Returns list of all pattern variables, possibly with their types,
   *  without duplicates
   */
  private def getVariables(tree: Tree): List[(Name, Tree,Position)] = {
    getvarTraverser.init.traverse(tree)
    getvarTraverser.buf.toList
  }

  private def makeTuple(trees: List[Tree], isType: Boolean): Tree = {
    val tupString = "Tuple" + trees.length
    Apply(scalaDot(if (isType) newTypeName(tupString) else newTermName(tupString)), trees)
  }

  def makeTupleTerm(trees: List[Tree], flattenUnary: Boolean): Tree = trees match {
    case List() => Literal(())
    case List(tree) if flattenUnary => tree
    case _ => makeTuple(trees, false)
  }

  def makeTupleType(trees: List[Tree], flattenUnary: Boolean): Tree = trees match {
    case List() => scalaUnitConstr
    case List(tree) if flattenUnary => tree
    case _ => AppliedTypeTree(scalaDot(newTypeName("Tuple" + trees.length)), trees)
  }

  def stripParens(t: Tree) = t match {
    case Parens(ts) => atPos(t.pos) { makeTupleTerm(ts, true) }
    case _ => t
  }

  def makeAnnotated(t: Tree, annot: Annotation): Tree = Annotated(annot, t) setPos annot.pos

  def makeSelfDef(name: Name, tpt: Tree): ValDef =
    ValDef(Modifiers(PRIVATE), name, tpt, EmptyTree)

  /** If tree is a variable pattern, return Some("its name and type").
   *  Otherwise return none */
  private def matchVarPattern(tree: Tree): Option[(Name, Tree)] = tree match {
    case Ident(name) => Some((name, TypeTree()))
    case Bind(name, Ident(nme.WILDCARD)) => Some((name, TypeTree()))
    case Typed(Ident(name), tpt) => Some((name, tpt))
    case Bind(name, Typed(Ident(nme.WILDCARD), tpt)) => Some((name, tpt))
    case _ => None
  }

  /** Create tree representing (unencoded) binary operation expression or pattern. */
  def makeBinop(isExpr: Boolean, left: Tree, op: Name, right: Tree): Tree = {
    val arguments = right match {
      case Parens(args) => args
      case _ => List(right)
    }
    if (isExpr) {
      if (treeInfo.isLeftAssoc(op)) {
        Apply(Select(stripParens(left), op.encode), arguments)
      } else {
        val x = freshName(posAssigner.pos);
        Block(
          List(ValDef(Modifiers(SYNTHETIC), x, TypeTree(), stripParens(left))),
          Apply(Select(stripParens(right), op.encode), List(Ident(x))))
      }
    } else {
      Apply(Ident(op.encode), stripParens(left) :: arguments)
    }
  }

  /** Create tree representing an object creation <new parents { stats }> */
  def makeNew(parents: List[Tree], self: ValDef, stats: List[Tree], argss: List[List[Tree]]): Tree =
    if (parents.isEmpty)
      makeNew(List(scalaAnyRefConstr), self, stats, argss)
    else if (parents.tail.isEmpty && stats.isEmpty)
      New(parents.head, argss)
    else {
      val x = nme.ANON_CLASS_NAME.toTypeName
      Block(
        List(ClassDef(
          Modifiers(FINAL), x, List(),
          Template(parents, self, NoMods, List(List()), argss, stats))),
        New(Ident(x), List(List())))
    }

  /** Create a tree represeting an assignment &lt;lhs = rhs&gt; */
  def makeAssign(lhs: Tree, rhs: Tree): Tree = lhs match {
    case Apply(fn, args) => Apply(Select(fn, nme.update), args ::: List(rhs))
    case _ => Assign(lhs, rhs)
  }

  /** A type tree corresponding to (possibly unary) intersection type */
  def makeIntersectionTypeTree(tps: List[Tree]): Tree =
    if (tps.tail.isEmpty) tps.head
    else CompoundTypeTree(Template(tps, emptyValDef, List()))

  /** Create tree representing a while loop */
  def makeWhile(lname: Name, cond: Tree, body: Tree): Tree = {
    val continu = Apply(Ident(lname), List())
    val rhs = If(cond, Block(List(body), continu), Literal(()))
    LabelDef(lname, Nil, rhs)
  }

  /** Create tree representing a do-while loop */
  def makeDoWhile(lname: Name, body: Tree, cond: Tree): Tree = {
    val continu = Apply(Ident(lname), List())
    val rhs = Block(List(body), If(cond, continu, Literal(())))
    LabelDef(lname, Nil, rhs)
  }

  /** Create block of statements `stats'  */
  def makeBlock(stats: List[Tree]): Tree =
    if (stats.isEmpty) Literal(())
    else if (!stats.last.isTerm) Block(stats, Literal(()))
    else if (stats.length == 1) stats.head
    else Block(stats.init, stats.last)

  /** Create tree for for-comprehension generator &lt;val pat0 &lt;- rhs0&gt; */
  def makeGenerator(pos: Position, pat: Tree, valeq: Boolean, rhs: Tree): Enumerator = {
    val pat1 = patvarTransformer.transform(pat);
    val rhs1 =
      if (valeq) rhs
      else matchVarPattern(pat1) match {
        case Some(_) =>
          rhs
        case None =>
          atPos(pos) {
            Apply(
              Select(rhs, nme.filter),
              List(
                makeVisitor(
                  List(
                    CaseDef(pat1.duplicate, EmptyTree, Literal(true)),
                    CaseDef(Ident(nme.WILDCARD), EmptyTree, Literal(false))),
                  false,
                  nme.CHECK_IF_REFUTABLE_STRING
                )))
          }
      }
    if (valeq) ValEq(pos, pat1, rhs1) else ValFrom(pos, pat1, rhs1)
  }

  def makeSyntheticParam(pname: Name) =
    ValDef(Modifiers(PARAM | SYNTHETIC), pname, TypeTree(), EmptyTree)

  def makeSyntheticTypeParam(pname: Name, bounds: Tree) =
    TypeDef(Modifiers(DEFERRED | SYNTHETIC), pname, List(), bounds)

  abstract class Enumerator
  case class ValFrom(pos: Position, pat: Tree, rhs: Tree) extends Enumerator
  case class ValEq(pos: Position, pat: Tree, rhs: Tree) extends Enumerator
  case class Filter(test: Tree) extends Enumerator

  /** Create tree for for-comprehension &lt;for (enums) do body&gt; or
  *   &lt;for (enums) yield body&gt; where mapName and flatMapName are chosen
  *  corresponding to whether this is a for-do or a for-yield.
  *  The creation performs the following rewrite rules:
  *
  *  1.
  *
  *    for (val P <- G) E   ==>   G.foreach (P => E)
  *
  *     Here and in the following (P => E) is interpreted as the function (P => E)
  *     if P is a a variable pattern and as the partial function { case P => E } otherwise.
  *
  *  2.
  *
  *    for (val P <- G) yield E  ==>  G.map (P => E)
  *
  *  3.
  *
  *    for (val P_1 <- G_1; val P_2 <- G_2; ...) ...
  *      ==>
  *    G_1.flatMap (P_1 => for (val P_2 <- G_2; ...) ...)
  *
  *  4.
  *
  *    for (val P <- G; E; ...) ...
  *      =>
  *    for (val P <- G.filter (P => E); ...) ...
  *
  *  5. For N < MaxTupleArity:
  *
  *    for (val P_1 <- G; val P_2 = E_2; val P_N = E_N; ...)
  *      ==>
  *    for (val TupleN(P_1, P_2, ... P_N) <-
  *      for (val x_1 @ P_1 <- G) yield {
  *        val x_2 @ P_2 = E_2
  *        ...
  *        val x_N & P_N = E_N
  *        TupleN(x_1, ..., x_N)
  *      } ...)
  *
  *    If any of the P_i are variable patterns, the corresponding `x_i @ P_i' is not generated
  *    and the variable constituting P_i is used instead of x_i
  *
  */
  private def makeFor(mapName: Name, flatMapName: Name, enums: List[Enumerator], body: Tree): Tree = {

    def makeClosure(pat: Tree, body: Tree): Tree = matchVarPattern(pat) match {
      case Some((name, tpt)) =>
        Function(List(ValDef(Modifiers(PARAM), name, tpt, EmptyTree)), body)
      case None =>
        makeVisitor(List(CaseDef(pat, EmptyTree, body)), false)
    }

    def makeCombination(meth: Name, qual: Tree, pat: Tree, body: Tree): Tree =
      Apply(Select(qual, meth), List(makeClosure(pat, body)));

    def patternVar(pat: Tree): Option[Name] = pat match {
      case Bind(name, _) => Some(name)
      case _ => None
    }

    def makeBind(pat: Tree): Tree = pat match {
      case Bind(_, _) => pat
      case _ => Bind(freshName(pat.pos), pat)
    }

    def makeValue(pat: Tree): Tree = pat match {
      case Bind(name, _) => Ident(name)
    }

    enums match {
      case ValFrom(pos, pat, rhs) :: Nil =>
        atPos(pos) {
          makeCombination(mapName, rhs, pat, body)
        }
      case ValFrom(pos, pat, rhs) :: (rest @ (ValFrom(_,  _, _) :: _)) =>
        atPos(pos) {
          makeCombination(flatMapName, rhs, pat, makeFor(mapName, flatMapName, rest, body))
        }
      case ValFrom(pos, pat, rhs) :: Filter(test) :: rest =>
        makeFor(mapName, flatMapName,
                ValFrom(pos, pat, makeCombination(nme.filter, rhs, pat.duplicate, test)) :: rest,
                body)
      case ValFrom(pos, pat, rhs) :: rest =>
        val valeqs = rest.take(definitions.MaxTupleArity - 1).takeWhile(_.isInstanceOf[ValEq]);
        assert(!valeqs.isEmpty)
        val rest1 = rest.drop(valeqs.length)
        val pats = valeqs map { case ValEq(_, pat, _) => pat }
        val rhss = valeqs map { case ValEq(_, _, rhs) => rhs }
        val defpats = pats map (x => makeBind(x.duplicate))
        val pdefs = List.flatten(List.map2(defpats, rhss)(makePatDef))
        val patX1 = makeBind(pat.duplicate);
        val ids = (patX1 :: defpats) map makeValue
        val rhs1 = makeForYield(
          List(ValFrom(pos, patX1, rhs)),
          Block(pdefs, makeTupleTerm(ids, true)))
        makeFor(mapName, flatMapName, ValFrom(pos, makeTuple(pat :: pats, false), rhs1) :: rest1, body)
      case _ =>
        EmptyTree //may happen for erroneous input
    }
  }

  /** Create tree for for-do comprehension &lt;for (enums) body&gt; */
  def makeFor(enums: List[Enumerator], body: Tree): Tree =
    makeFor(nme.foreach, nme.foreach, enums, body)

  /** Create tree for for-yield comprehension &lt;for (enums) yield body&gt; */
  def makeForYield(enums: List[Enumerator], body: Tree): Tree =
    makeFor(nme.map, nme.flatMap, enums, body)

  /** Create tree for a lifted expression XX-LIFTING
   */
  def makeLifted(gs: List[ValFrom], body: Tree): Tree = {
    def combine(gs: List[ValFrom]): ValFrom = (gs: @unchecked) match {
      case g :: Nil => g
      case ValFrom(pos1, pat1, rhs1) :: gs2 =>
        val ValFrom(pos2, pat2, rhs2) = combine(gs2)
        ValFrom(pos1, makeTuple(List(pat1, pat2), false), Apply(Select(rhs1, nme.zip), List(rhs2)))
    }
    makeForYield(List(combine(gs)), body)
  }

  /** Create tree for a pattern alternative */
  def makeAlternative(ts: List[Tree]): Tree = {
    def alternatives(t: Tree): List[Tree] = t match {
      case Alternative(ts) => ts
      case _ => List(t)
    }
    Alternative(for (val t <- ts; val a <- alternatives(t)) yield a)
  }

  /** Create tree for a pattern sequence */
  def makeSequence(ts: List[Tree]): Tree = {
    def elements(t: Tree): List[Tree] = t match {
      case Sequence(ts) => ts
      case _ => List(t)
    }
    Sequence(for (val t <- ts; val e <- elements(t)) yield e)
  }

  /** Create tree for the p+ regex pattern, becomes p p*  */
  def makePlus(p: Tree): Tree =
    makeSequence(List(p, Star(p.duplicate)))

  /** Create tree for the p? regex pattern, becomes (p| )         */
  def makeOpt(p: Tree): Tree =
    makeAlternative(List(p, Sequence(List())))

  /** Create visitor <x => x match cases> */
  def makeVisitor(cases: List[CaseDef], checkExhaustive: Boolean): Tree =
    makeVisitor(cases, checkExhaustive, "x$")

  private def makeUnchecked(expr: Tree): Tree =
    Annotated(Annotation(New(scalaDot(definitions.UncheckedClass.name), List(List())), List()), expr)

  /** Create visitor <x => x match cases> */
  def makeVisitor(cases: List[CaseDef], checkExhaustive: Boolean, prefix: String): Tree = {
    val x = freshName(posAssigner.pos, prefix)
    val sel = if (checkExhaustive) Ident(x) else makeUnchecked(Ident(x))
    Function(List(makeSyntheticParam(x)), Match(sel, cases))
  }

  /** Create tree for case definition &lt;case pat if guard => rhs&gt; */
  def makeCaseDef(pat: Tree, guard: Tree, rhs: Tree): CaseDef =
    CaseDef(patvarTransformer.transform(pat), guard, rhs)

  /** Create tree for pattern definition &lt;val pat0 = rhs&gt; */
  def makePatDef(pat: Tree, rhs: Tree): List[Tree] =
    makePatDef(Modifiers(0), pat, rhs)

  /** Create tree for pattern definition &lt;mods val pat0 = rhs&gt; */
  def makePatDef(mods: Modifiers, pat: Tree, rhs: Tree): List[Tree] = matchVarPattern(pat) match {
    case Some((name, tpt)) =>
      List(ValDef(mods, name, tpt, rhs).setPos(pat.pos))

    case None =>
      //  in case there is exactly one variable x_1 in pattern
      //  val/var p = e  ==>  val/var x_1 = e.match (case p => (x_1))
      //
      //  in case there are zero or more than one variables in pattern
      //  val/var p = e  ==>  private synthetic val t$ = e.match (case p => (x_1, ..., x_N))
      //                  val/var x_1 = t$._1
      //                  ...
      //                  val/var x_N = t$._N
      val pat1 = patvarTransformer.transform(pat)
      val vars = getVariables(pat1)
      val matchExpr = atPos(pat1.pos){
        Match(
          makeUnchecked(rhs),
          List(CaseDef(pat1, EmptyTree, makeTupleTerm(vars map (_._1) map Ident, true))))
      }
      vars match {
        case List((vname, tpt, pos)) =>
          List(ValDef(mods, vname, tpt, matchExpr).setPos(pos))
        case _ =>
          val tmp = freshName(pat1.pos)
          val firstDef = ValDef(Modifiers(PRIVATE | LOCAL | SYNTHETIC | (mods.flags & LAZY)),
                                tmp, TypeTree(), matchExpr)
          var cnt = 0
          val restDefs = for (val (vname, tpt, pos) <- vars) yield atPos(pos) {
            cnt = cnt + 1
            ValDef(mods, vname, tpt, Select(Ident(tmp), newTermName("_" + cnt)))
          }
          firstDef :: restDefs
      }
  }

  /** Create a tree representing the function type (argtpes) => restpe */
  def makeFunctionTypeTree(argtpes: List[Tree], restpe: Tree): Tree =
    AppliedTypeTree(scalaDot(newTypeName("Function" + argtpes.length)), argtpes ::: List(restpe))

  /** Create a tree representing a the name function type (=> argtpe) => restpe */
  /*
  def makeByNameFunctionTypeTree(argtpe: Tree, restpe: Tree): Tree =
    AppliedTypeTree(scalaDot(newTypeName("ByNameFunction")), List(argtpe, restpe))
  */

  /** Append implicit view section if for `implicitViews' if nonempty */
  def addImplicitViews(owner: Name, vparamss: List[List[ValDef]], implicitViews: List[Tree]): List[List[ValDef]] = {
    val mods = Modifiers(if (owner.isTypeName) PARAMACCESSOR | LOCAL | PRIVATE else PARAM)
    def makeViewParam(tpt: Tree) = ValDef(mods | IMPLICIT, freshName(tpt.pos, "view$"), tpt, EmptyTree)
    if (implicitViews.isEmpty) vparamss
    else vparamss ::: List(implicitViews map makeViewParam)
  }

  /** Create a tree representing a packaging */
  def makePackaging(pkg: Tree, stats: List[Tree]): PackageDef = pkg match {
    case Ident(name) =>
      PackageDef(name, stats).setPos(pkg.pos)
    case Select(qual, name) =>
      makePackaging(qual, List(PackageDef(name, stats).setPos(pkg.pos)))
  }

  case class Parens(args: List[Tree]) extends Tree
}