summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/matching/CodeFactory.scala
blob: f7b892d3570252f7a413efab1a26ecd16e911c43 (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
/* NSC -- new Scala compiler
 * Copyright 2005-2007 LAMP/EPFL
 * @author Burak Emir
 */
// $Id$

package scala.tools.nsc.matching

import scala.tools.nsc.util.Position

/** contains many helper methods that build trees...some of these currently
 *  unused, since were for regexp matching.
 *
 *  @author Burak Emir
 */
trait CodeFactory {
  self: transform.ExplicitOuter with PatternNodes =>

  import global._

  import definitions._             // standard classes and methods
  import typer.typed               // methods to type trees
  import posAssigner.atPos         // for filling in tree positions


  final def typedValDef(x:Symbol, rhs:Tree) = {
    //Console.println("1"+x.tpe)
    x.tpe match {
      case WildcardType => rhs.setType(null); val rhs1 = typed(rhs); x setInfo rhs1.tpe; typed{ValDef(x, rhs)}
      case _ => typed{ValDef(x, typed(rhs, x.tpe))}
    }
  }

  final def mk_(tpe:Type) = Ident(nme.WILDCARD) setType tpe

  final def targetLabel(owner: Symbol, pos: Position, name:String, argtpes:List[Type], resultTpe: Type) =
    owner.newLabel(pos, name).setInfo(new MethodType(argtpes, resultTpe))

  final def targetParams(subst:Binding):List[ValDef] = if(subst eq NoBinding) Nil else subst match {
    case Binding(v,t,n) => ValDef(v, {
      //v.setFlag(symtab.Flags.TRANS_FLAG);
      if(t.tpe <:< v.tpe) typed{Ident(t)}
      else if(v.tpe <:< t.tpe) typed{gen.mkAsInstanceOf(Ident(t),v.tpe)} // refinement
      else {
        //Console.println("internal error, types don't match: pattern variable "+v+":"+v.tpe+" temp "+t+":"+t.tpe)
        error("internal error, types don't match: pattern variable "+v+":"+v.tpe+" temp "+t+":"+t.tpe)
        typed{gen.mkAsInstanceOf(Ident(t),v.tpe)} // refinement
      }
    })::targetParams(n)
  }

  /** returns  `List[ Tuple2[ scala.Int, <elemType> ] ]' */
  final def SeqTraceType(elemType: Type): Type =
    appliedType(definitions.ListClass.typeConstructor,
                List(pairType(definitions.IntClass.info,
                              elemType)))

  final def pairType(left: Type, right: Type) =
    appliedType(definitions.TupleClass(2).typeConstructor,
                List(left,right))

  /**  returns `Iterator[ elemType ]' */
  final def _seqIterType(elemType: Type): Type =
    appliedType(definitions.IteratorClass.typeConstructor,
                List(elemType))

  /** returns A for T <: Sequence[ A ]
   */
  final def getElemType_Sequence(tpe: Type): Type = {
    //System.err.println("getElemType_Sequence("+tpe.widen()+")")
    val tpe1 = tpe.widen.baseType(definitions.SeqClass)

    if (tpe1 == NoType)
      Predef.error("arg " + tpe + " not subtype of Seq[A]")

    tpe1.typeArgs(0)
  }

  // --------- these are new

  /** a faked switch statement
   */
  final def Switch(condition: Array[Tree], body: Array[Tree], defaultBody: Tree): Tree = {
    //assert condition != null:"cond is null";
    //assert body != null:"body is null";
    //assert defaultBody != null:"defaultBody is null";
    var result = defaultBody
    var i = condition.length - 1
    while (i >= 0) {
      result = makeIf(condition(i), body(i), result)
      i -= 1
    }
    result
  }

  final def renamingBind(defaultv: Set[Symbol], scrut: Symbol, ndefault: Tree) = {
    if (!defaultv.isEmpty) {
      var dv: List[Symbol] = Nil
      var to: List[Symbol] = Nil
      val it = defaultv.elements; while(it.hasNext) {
        dv = it.next :: dv
        to = scrut   :: to
      }
      val tss = new TreeSymSubstituter(dv, to)
      tss.traverse(ndefault)
    }
  }

  final def emptynessCheck(vsym: Symbol) = {
    if (vsym.tpe.typeSymbol == definitions.SomeClass)  // is Some[_]
      Literal(Constant(true))
    else                                          // is Option[_]
      Not(Select(Ident(vsym), nme.isEmpty))
  }

  final def makeIf(cond: Tree, thenp: Tree, elsep: Tree) = (cond,thenp,elsep) match {
    case (Literal(Constant(true)),  _, _) => thenp
    case (Literal(Constant(false)), _, _) => elsep
    case (_, Literal(Constant(true)), Literal(Constant(false))) => cond
    case _ => If(cond, thenp, elsep)
  }

  /** returns code `<seqObj>.elements' */
  final def newIterator(seqObj: Tree): Tree =
    Apply(Select(seqObj, newTermName("elements")), List())

  /** `it.next()'     */
  final def _next(iter: Tree) =
    Apply(Select(iter, definitions.Iterator_next), List())

  /** `it.hasNext()'  */
  final def _hasNext(iter: Tree) =
    Apply(Select(iter, definitions.Iterator_hasNext), List())

  /** `!it.hasCur()'  */
  final def _not_hasNext(iter: Tree) =
    Apply(Select(_hasNext(iter), definitions.Boolean_not), List())

  /** `trace.isEmpty' */
  final def isEmpty( iter: Tree  ):  Tree =
    Apply(Select(iter, definitions.List_isEmpty), List())

  /** `arg.head' */
  final def SeqList_head(arg: Tree) =
    Apply(Select(arg, definitions.List_head), List())

  final def Negate(tree: Tree) = tree match {
    case Literal(Constant(value:Boolean))=>
      Literal(Constant(!value))
    case _ =>
      Apply(Select(tree, definitions.Boolean_not), List());
  }

  /** for tree of sequence type, returns tree that drops first i elements */
  final def seqDrop(sel:Tree, ix: Int) = if (ix == 0) sel else
    Apply(Select(Select(sel, nme.toList), nme.drop),
          List(Literal(Constant(ix))))

  /** for tree of sequence type, returns tree that drops first i elements */
  final def seqElement(sel:Tree, ix: Int) = if (ix == 0) sel else
    Apply(Select(sel, sel.tpe.member(nme.apply)), List(Literal(Constant(ix))))

  /** for tree of sequence type, returns boolean tree that has length i */
  final def seqHasLength(sel: Tree, ntpe: Type, i: Int) =
    typed(
      Equals(
        Apply(Select(sel, ntpe.member(nme.length)), List()),
        Literal(Constant(i))
      )
    )/*defs.Seq_length ?*/

  /** for tree of sequence type sel, returns boolean tree testing that length >= i
   */
  final def seqLongerThan(sel:Tree, tpe:Type, i:Int) =
    GreaterThanOrEquals(
      typed(Apply(Select(sel, tpe.member(nme.length)), List())),
      typed(Literal(Constant(i))))
      //defs.Seq_length instead of tpe.member ?

  final def Not(arg:Tree) = arg match {
    case Literal(Constant(true))  => Literal(Constant(false))
    case Literal(Constant(false)) => Literal(Constant(true))
    case t                        => Select(arg, definitions.Boolean_not)
  }
  /*protected*/ def And(left: Tree, right: Tree): Tree = left match {
    case Literal(Constant(value: Boolean)) =>
      if (value) right else left
    case _ =>
      right match {
        case Literal(Constant(true)) =>
	  left
        case _ =>
          Apply(Select(left, definitions.Boolean_and), List(right))
      }
  }

  /*protected*/final def Or(left: Tree, right: Tree): Tree = {
    left match {
/*
      case If(cond: Tree, thenp: Tree, Literal(Constant(false))) =>  // little opt, frequent special case
        If(cond, thenp, right)
*/
      case Literal(Constant(value: Boolean))=>
	if(value) left else right
      case _ =>
        right match {
          case Literal(Constant(false)) =>
	    left
          case _ =>
            Apply(Select(left, definitions.Boolean_or), List(right));
        }
    }
  }

  // used by Equals
  /*
  private def getCoerceToInt(left: Type): Symbol = {
    val sym = left.nonPrivateMember( nme.coerce );
    //assert sym != Symbol.NONE : Debug.show(left);

    sym.alternatives.find {
      x => x.info match {
        case MethodType(vparams, restpe) =>
          vparams.length == 0 && isSameType(restpe,definitions.IntClass.info)
      }
    }.get
  }
  */
  // used by Equals
/*
  private def getEqEq(left: Type, right: Type): Symbol = {
    //Console.println("getEqeq of left  ==  "+left);
    val sym = left.nonPrivateMember( nme.EQEQ );


    //if (sym == NoSymbol)
    //  error("no eqeq for "+left);
    //    : Debug.show(left) + "::" + Debug.show(left.members());

    var fun: Symbol  = null;
    var ftype:Type  = null; // faster than `definitions.AnyClass.tpe'
    sym.alternatives.foreach {
      x =>
        //Console.println("getEqEq: "+x);
        val vparams = x.info.paramTypes;
        //Console.println("vparams.length ==  "+vparams.length);

        if (vparams.length == 1) {
          val vptype = vparams(0);
          //Console.println("vptype ==  "+vptype);
          //Console.println("   ftype ==  "+ftype);
          //Console.println("   cond1 ==  "+isSubType(right, vptype));
          //Console.println("   cond2("+vptype+","+ftype+") ==  "+(ftype == null || isSubType(vptype, ftype)));
          //Console.println("vptype.getClass "+vptype.getClass());
          if (isSubType(right, vptype) && (ftype == null || isSubType(vptype, ftype)) ) {
            fun = x;
            ftype = vptype;
            //Console.println("fun now: "+fun+"  ftype now "+ftype);
          }
        }
    }
    //if (fun == null) scala.Predef.error("couldn't find eqeq for left"+left);
    fun;
  }
*/
  final def Equals(left: Tree, right: Tree): Tree =
    Apply(Select(left, nme.EQEQ), List(right))

  final def Eq(left: Tree, right: Tree): Tree =
    Apply(Select(left, nme.eq), List(right))

  final def GreaterThanOrEquals(left: Tree, right: Tree): Tree =
    Apply(Select(left, nme.GE), List(right))

  final def ThrowMatchError(pos: Position, obj: Tree) =
    atPos(pos) {
      Throw(
        New(
          TypeTree(definitions.MatchErrorClass.tpe),
          List(List(
            obj
          ))))
    }

  final def NotNull(tree:Tree) =
    typed {
      Apply(Select(tree, nme.ne), List(Literal(Constant(null))))
    }

  final def IsNull(tree:Tree) =
    typed {
      Apply(Select(tree, nme.eq), List(Literal(Constant(null))))
    }

    // statistics
    var nremoved = 0
    var nsubstituted = 0
    var nstatic = 0

  final def squeezedBlock(vds: List[Tree], exp: Tree)(implicit theOwner: Symbol): Tree =
    if (settings_squeeze)
      squeezedBlock1(vds, exp)
    else
      Block(vds,exp)

  final def squeezedBlock1(vds: List[Tree], exp: Tree)(implicit theOwner: Symbol): Tree = {
    val tpe = exp.tpe

    class RefTraverser(sym: Symbol) extends Traverser {
      var nref = 0
      var nsafeRef = 0
      override def traverse(tree: Tree) = tree match {
        case t:Ident if t.symbol eq sym =>
          nref += 1
          if(sym.owner == currentOwner)  { // oldOwner should match currentOwner
            nsafeRef += 1
          } /*else if(nref == 1) {
            Console.println("sym owner: "+sym.owner+" but currentOwner = "+currentOwner)
          }*/
        case LabelDef(_,args,rhs) =>
          var args1 = args; while(args1 ne Nil) {
            if(args1.head.symbol eq sym) {
              nref += 2   // will abort traversal, cannot substitute this one
              args1 = Nil // break
            } else {
              args1 = args1.tail
            }
          }
          traverse(rhs)
        case t if nref > 1 =>
          // abort, no story to tell
        case t =>
          super.traverse(t)
      }
    }

    class Subst(sym: Symbol, rhs: Tree) extends Transformer {
      var stop = false
      override def transform(tree: Tree) = tree match {
        case t:Ident if t.symbol == sym =>
          stop = true
          rhs
        case t if stop =>
          t
        case t =>
          super.transform(t)
      }
    }
    vds match {
      case Nil =>
        exp
      case (vd:ValDef) :: rest =>
        // recurse
        val exp1 = squeezedBlock(rest, exp)

        //Console.println("squeezedBlock for valdef "+vd)
        val sym = vd.symbol
        val rt = new RefTraverser(sym)
        rt.atOwner (theOwner) (rt.traverse(exp1))
      //Console.println("hello, ref count = "+rt.nref+"/"+rt.nsafeRef)
        rt.nref match {
          case 0 =>
            nremoved = nremoved + 1
            exp1
          case 1 if rt.nsafeRef == 1 =>
            nsubstituted += 1
            new Subst(sym, vd.rhs).transform(exp1)
          case _ =>
            exp1 match {
              case Block(vds2, exp2) => Block(vd::vds2, exp2)
              case exp2              => Block(vd::Nil,  exp2)
            }
        }
      case x::xs =>
        squeezedBlock(xs, exp) match {
          case Block(vds2, exp2) => Block(x::vds2, exp2)
          case exp2              => Block(x::Nil,  exp2)
        }
    }
  }


}