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

package scala.tools.nsc.matching

import scala.tools.nsc.util.Position

trait CodeFactory requires transform.ExplicitOuter  {

  import global._

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


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

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

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

  /** returns A for T <: Sequence[ A ]
   */
  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
   */
  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 = If(condition(i), body(i), result)
      i = i - 1
    }
    result
  }

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

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

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

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

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

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

  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 */
  def seqDrop(sel:Tree, i: Int) = if(i == 0) sel else
    Apply(Select(Select(sel, "toList"), "drop"),
          List(Literal(Constant(i))))

  /** for tree of sequence type, returns boolean tree that has length i */
  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
   */
  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 ?

  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*/ 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;
  }
*/
  def Equals(left: Tree, right: Tree): Tree =
    Apply(Select(left, nme.EQEQ), List(right))

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

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

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

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

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

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

  def squeezedBlock(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 == sym =>
          nref = nref + 1
          if(sym.owner == currentOwner)  { // oldOwner should match currentOwner
            nsafeRef = nsafeRef + 1
          } /*else if(nref == 1) {
            Console.println("sym owner: "+sym.owner+" but currentOwner = "+currentOwner)
          }*/
        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))
        rt.nref match {
          case 0 =>
            nremoved = nremoved + 1
            exp1
          case 1 if rt.nsafeRef == 1 =>
            nsubstituted = 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)
        }
    }
  }


}