summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/matching/TransMatcher.scala
blob: 23f33ac29f23afeb755a9b6b656abe52b0acea0c (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
/* NSC -- new scala compiler
 * Copyright 2005 LAMP/EPFL
 * @author buraq
 */
// $Id$
package scala.tools.nsc.matching;

/** Translation of pattern matching
 */
abstract class TransMatcher extends transform.Transform
with PatternNodes
with CodeFactory
with PatternMatchers
//with NewMatchers
with SequenceMatchers
with AlgebraicMatchers
with MatcherLabels
with BerrySethis
with DetWordAutoms
with NondetWordAutoms
with Autom2
with WordAutoms
with LeftTracers
with RightTracers {

  import global._;
  import definitions._;
  import posAssigner.atPos;
  import typer.typed;

  val phaseName = "transmatcher";

  protected def newTransformer(unit: global.CompilationUnit): global.Transformer = {
    new TransMatch
  }

  /** container. classes AlgebraicMatcher and SequenceMatcher get input and
   *  store their results in here. resembles the 'Memento' design pattern,
   *  could also be named 'Liaison'
   */
  abstract class PartialMatcher {

    /** owner of the code we create (input)
     */
    val owner: Symbol;

    /** the selector value (input)
     */
    val selector:Tree;

    /** tree representing the matcher (output)
     */
    var tree: Tree  = _ ;

    def pos: int = selector.pos;

    //assert( owner != null ) : "owner is null";
    //assert owner != Symbol.NONE ;
    //this.owner      = owner;

    //assert root != null;
    //assert root.type != null;
    //this.selector   = root;

    //assert this.resultType != Type.NoType;
    //this.resultType = resultType;

    //this.pos        = root.pos; // for convenience only

  }

  var cunit: CompilationUnit = _;

  def fresh = cunit.fresh ;

  var currentOwner: Symbol = _;

  var resultType: Type = _;

  def containsBinding(pat: Tree): Boolean = {
    var generatedVars = false;

    def handleVariableSymbol(sym: Symbol): Unit  =
      if (sym.name.toString().indexOf("$") == -1) {
        generatedVars = true; // .add(sym);
      }

    def isVariableName(name: Name): Boolean =
      ( treeInfo.isVariableName(name) ) && ( name != nme.USCOREkw ) ;

    def isVariableSymbol(sym: Symbol): Boolean =
      ( sym != null )&&( !sym.isPrimaryConstructor );

    def traverse(tree: Tree): Unit = {

      tree match {
        case x @ Ident(name) =>
          if(x.symbol != definitions.PatternWildcard)
            error("shouldn't happen?!");

        case Bind(name, subtree) =>
          var sym: Symbol = null;

        if (isVariableName(name)
            && isVariableSymbol( {sym = tree.symbol; tree.symbol} ))
          handleVariableSymbol(sym);

        traverse( subtree );

        // congruence

        case Apply(fun, args) => args foreach traverse;
        case Sequence(trees)  => trees foreach traverse
        case Star(arg)        => traverse(arg)
        case Typed(expr, tpe) => traverse(expr); // needed??

        case  _ : Select |
               _ : Alternative |
               _ : Select |
               _ : Literal =>  ; // no variables

        case _ =>
          cunit.error(tree.pos, "unknown pattern node:" + tree + " = " + tree.getClass());
      }
    }
    traverse(pat);
    generatedVars;
  }

    /** a casedef with sequence subpatterns like
     *
     *  case ..x @ ().. => body
     *
     * should be replaced straight away with
     *
     *  case    .. () .. => val x = Nil; body
     */

  def isRegularPattern(pat: Tree): Boolean = pat match {
    case Alternative(trees)          =>
      trees exists { isRegularPattern };
    case Star(t)                 => true
    case Ident(_)                => false
    case Bind( n, pat1 )         => isRegularPattern( pat1 );
    case Sequence( trees )       => true // cause there are ArrayValues now
    case ArrayValue( tt, trees ) =>
      trees exists { isRegularPattern };
    case Apply( fn, List(Sequence(List())))      =>
      false
    case Apply( fn, trees )      =>
      trees exists { isRegularPattern };
    case Literal(_)              => false
    case Select(_,_)             => false
    case Typed(_,_)              => false
  }

  protected def isDefault(p: Tree): Boolean = p match {
    case Bind(_,q)            => isDefault(q);
    case Ident(nme.WILDCARD)  => true
    case _                    => false
  };
  protected def isDefaultStar(p: Tree): Boolean = p match {
    case Bind(_,q)                  => isDefaultStar(q);
    case Star(Ident(nme.WILDCARD))  => true
    case _                          => false
  };

  // @todo: this should be isNotRegular :-/ premature opt src of all evil
  // check special case Seq(_,...,_,_*)
  protected def isRightIgnoring(p:ArrayValue): Boolean = p match {
    case ArrayValue(s,trees) =>
      val it = trees.elements;
      var c: Tree = null;
      while(it.hasNext && {c = it.next; //Console.println("isReg?("+c+" = "+isRegularPattern(c)); // DEBUG
!isRegularPattern(c)}) {}
      (!it.hasNext) && isDefaultStar(c)
  }

  class TransMatch extends Transformer {

    override def transformUnit(unit: CompilationUnit) = {
      cunit = unit
      super.transformUnit(unit)
      cunit = null
    }

    /** a casedef with sequence subpatterns like
     *
     *  case ..x @ ().. => body
     *
     * should be replaced straight away with
     *
     *  case    .. () .. => val x = Nil; body
     */
    def isRegular(pats:List[CaseDef]): Pair[List[CaseDef],Boolean] = {
      var existsReg = false;
      var isReg = false;
      var nilVars:List[Symbol] = null;

      def isRegular1(pat: Tree): Tree = pat match {
        case Alternative(trees)          =>
          copy.Alternative(pat, trees map { isRegular1 });

        case Star(t)                 => isReg = true; copy.Star(pat, isRegular1(t) );

        case Ident(_)                => pat;

        case Bind( id, empt @ Sequence(List())) =>
          nilVars = pat.symbol /*id.symbol()*/ :: nilVars;
		  empt;
        case Bind( n, pat1 )         => copy.Bind(pat, n, isRegular1( pat1 ));

      case Sequence( trees )       =>
	    //isReg = isReg || ( trees.length == 0 );
		isReg = true; // cause there are ArrayValues now
		copy.Sequence(pat, trees map { isRegular1 });

      case ArrayValue( tt, List(b @ Bind(id, Star(wc @ Ident(nme.WILDCARD))))) =>
	//Console.println("OPTIMIZING");
	//Console.println(pat);
	//Console.println(pat.tpe);
	//Console.println(b.tpe);
        b.symbol.setInfo(pat.tpe);
		b.setType(pat.tpe);
        val res = copy.Bind(b, id, wc);
	//Console.println("====>");
	//Console.println(res);
	res

      case av @ ArrayValue( s, trees )       =>
        if(isRightIgnoring(av))
          pat
        else
          copy.ArrayValue( pat, s, (trees map { isRegular1 }));

      case Apply( fn, List(Sequence(List())))      =>
        pat;

      case Apply( fn, trees )      =>
	    //Console.println(" IN isRegular, apply node "+pat.toString());
	    //Console.println(" trees are:"+(trees map {x => x.getClass().toString()}));
        copy.Apply( pat, fn, ( trees map { isRegular1 }) )

      case Literal(_)              => pat
      case Select(_,_)             => pat
      case Typed(_,_)              => pat

      //case _   =>
      //  Console.println(pat);
      //  Console.println(pat.getClass());
      //  scala.Predef.error"( what is this ? ")
	  }

	   var res:List[CaseDef] = Nil;
	   val it = pats.elements; while(it.hasNext) {
	     nilVars = Nil;
	     val cdef = it.next;
		 val newt = isRegular1(cdef.pat);
		 existsReg = existsReg || isReg;

         val nbody = if(nilVars.isEmpty) cdef.body else
              atPos(cdef.body.pos)(
                Block(nilVars map {
                  x => ValDef(x, Ident(definitions.NilModule))
                }, cdef.body)
              );

		 res = copy.CaseDef(cdef, newt, cdef.guard, nbody) :: res;
	   }
	   Pair(res.reverse, existsReg);
	}



    /** handles all translation of pattern matching
     */
    def handle(sel:Tree, ocases:List[CaseDef]): Tree = {

      // TEMPORARY
      //new NewMatcher().toIR(sel, ocases)
      //
      // 1. is there a regular pattern?

      val Pair(cases, containsReg) = isRegular(ocases);


      // @todo: remove unused variables

      if(containsReg) {
        // 2. replace nilVariables
        //@todo: bring over AlgebraicMatcher
		/*
        val matcher = new PartialMatcher {
          val global: TransMatcher.this.global.type = TransMatcher.this.global;
          val owner = currentOwner;
          val selector = sel ;
        }
        new AlgebraicMatcher() {
          val tm: TransMatcher.this.type = TransMatcher.this;
        }.construct( matcher, cases );
        matcher.tree
		*/

        System.out.println("" + sel + " match " + ocases);
	cunit.error(sel.pos, "regular expressions not yet implemented");
        sel
      } else {
        val pm = new PatternMatcher();
        pm.initialize(sel, currentOwner, true );
        pm.construct( cases );
        //if (global.log()) {
        //  global.log("internal pattern matching structure");
        //  pm.print();
        //}
        pm.toTree()
      }
    }
    override def transform(tree: Tree): Tree = tree match {
      /* // test code to generate forward jumps
      case Match(selector, CaseDef(Ident(nme.WILDCARD), EmptyTree, exp)::Nil) => // inserting test-code

        val target1 = currentOwner.newLabel(tree.pos, "target1")
        .setInfo(new MethodType(List(definitions.IntClass.tpe), definitions.IntClass.tpe));

        val a = currentOwner.newValue(tree.pos, "a").setInfo(definitions.IntClass.tpe);
        val x = currentOwner.newValueParameter(tree.pos, "x").setInfo(definitions.IntClass.tpe);
        val y = currentOwner.newValueParameter(tree.pos, "y").setInfo(definitions.IntClass.tpe);
        val target2 = currentOwner.newLabel(tree.pos, "target2")
        .setInfo(new MethodType(List(definitions.IntClass.tpe, definitions.IntClass.tpe), definitions.IntClass.tpe));

        val z = currentOwner.newValueParameter(tree.pos, "z").setInfo(definitions.IntClass.tpe);
        typed { atPos(tree.pos) { Block(
          List(
            Apply(Ident(target2), List(Literal(Constant(1)),Literal(Constant(2)))),
            LabelDef(target1, List(x), exp)),
            LabelDef(target2, List(y,z), Apply(Select(Ident(y), nme.PLUS), List(Ident(z))))
        )}};
*/

      case Match(selector, cases) =>
	val nselector = transform(selector).setType(selector.tpe);
        val ncases = cases map { transform };
/*
      Console.println("TransMatch translating cases: ");
      for(val t <- cases) {
	Console.println(t.pat.toString());
	Console.println("BODY "+t.body.toString());
      }
*/
        // @todo: remove from partial matcher
        TransMatcher.this.currentOwner = currentOwner;
        TransMatcher.this.resultType   = tree.tpe;
        //Console.println("TransMatcher currentOwner ="+currentOwner+")");
        //Console.println("TransMatcher selector.tpe ="+selector.tpe+")");
        //Console.println("TransMatcher resultType ="+resultType+")");
        val t_untyped = handle(nselector, ncases.asInstanceOf[List[CaseDef]]);
        //Console.println("t_untyped "+t_untyped.toString());
        val t         = typed { atPos(tree.pos) (t_untyped) };
        //Console.println("t typed "+t.toString());
        t
      case _ =>
        super.transform(tree);
    }
  }
}