summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/matching/PatternMatchers.scala
blob: 0eee9f85527ca2660c82e13f6f7ca1f30faf3b86 (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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
/* NSC -- new scala compiler
 * Copyright 2005 LAMP/EPFL
 * @author buraq
 */
// $Id$

package scala.tools.nsc.matching ;

import scala.tools.nsc.util.Position;

trait PatternMatchers requires (TransMatcher with PatternNodes) extends AnyRef with PatternNodeCreator {


  import global._;
  import typer.typed ;
  import symtab.Flags;

  // -- begin new data structure for matcher

  abstract class Node{}

  class Test(var tpe: Type, var casted: Symbol) extends Node {
    var thenp: Node  = _
    var vbles = List[Symbol]();
    def bindTo(v: Symbol): this.type = { vbles = v::vbles; this }
    override def toString() = tpe.toString+"?"
  }
  class Load(var expr: Tree) extends Node {
    def tpe = expr.tpe;
    var thenp: PatNodeList = Snil
  }
  case class Return(b:Tree) extends Node {}

  abstract class PatNodeList {};
  case class Snoc(sx:PatNodeList, x:Test) extends PatNodeList;
  case object Snil extends PatNodeList;

    // -- end

 class PatternMatcher  {



  protected var optimize = true;

  /** the owner of the pattern matching expression
   */
  var owner:Symbol = _ ;

  /** the selector expression
   */
  protected var selector: Tree = _;

  /** the root of the pattern node structure
   */
  protected var root: PatternNode = _;

  /** the symbol of the result variable
   */
//  protected var resultVar: Symbol = _;

  def defs = definitions;
  /** init method, also needed in subclass AlgebraicMatcher
   */
  def initialize(selector: Tree, owner: Symbol): Unit = {

    //Konsole.println("pm.initialize selector.tpe = "+selector.tpe);

    /*
    this.mk = new PatternNodeCreator {
      val global = PatternMatcher.this.global;
      val unit = PatternMatcher.this.unit;
      val owner = PatternMatcher.this.owner;
    }
    */
    /*
    this.cf = new CodeFactory {
      val global = PatternMatcher.this.global;
      val unit = PatternMatcher.this.unit;
      val owner = PatternMatcher.this.owner;
    }
    */
    this.root = pConstrPat(selector.pos, selector.tpe.widen);
    //Konsole.println("selector.tpe "+selector.tpe);
    //Konsole.println("selector.tpe.widen "+selector.tpe.widen);
    //Konsole.println("root.symbol "+root.symbol);
    //Konsole.println("root.symbol.tpe "+root.symbol.tpe);
    this.root.and = pHeader(selector.pos,
                              selector.tpe.widen,
                              Ident(root.symbol).setType(root.tpe));
    //Konsole.println("resultType =  "+resultType);
    this.owner = owner;
    this.selector = selector;

    //this.optimize = this.optimize && (settings.target.value == "jvm");
  }

  /** pretty printer
   */
  def print(): Unit = { Console.println (
    root.and.print("", new StringBuffer()).toString()
  )}

  /** enters a sequence of cases into the pattern matcher
   */
  def construct(cases: List[Tree]): Unit = {
    cases foreach enter;
  }

  /** enter a single case into the pattern matcher
   */
  protected def enter(caseDef: Tree): Unit = {
    caseDef match {
      case CaseDef(pat, guard, body) =>
        val env = new CaseEnv;
        // PatternNode matched = match(pat, root);
        val target = enter1(pat, -1, root, root.symbol, env);
        // if (target.and != null)
        //     unit.error(pat.pos, "duplicate case");
      if (null == target.and)
        target.and = pBody(caseDef.pos, env.getBoundVars(), guard, body);
      else if (target.and.isInstanceOf[Body])
        updateBody(target.and.asInstanceOf[Body], env.getBoundVars(), guard, body);
      else
        cunit.error(pat.pos, "duplicate case");
    }
  }

  protected def updateBody(tree: Body, bound: Array[ValDef], guard: Tree , body: Tree): Unit = {
    if (tree.guard(tree.guard.length - 1) == EmptyTree) {
      cunit.error(body.pos, "unreachable code");
    } else {
      val bd = new Array[Array[ValDef]](tree.bound.length + 1);
      val ng = new Array[Tree](tree.guard.length + 1);
      val nb = new Array[Tree](tree.body.length + 1);
      System.arraycopy(tree.bound, 0, bd, 0, tree.bound.length);
      System.arraycopy(tree.guard, 0, ng, 0, tree.guard.length);
      System.arraycopy(tree.body, 0, nb, 0, tree.body.length);
      bd(bd.length - 1) = bound;
      ng(ng.length - 1) = guard;
      nb(nb.length - 1) = body;
      tree.bound = bd ;
      tree.guard = ng ;
      tree.body = nb ;
    }
  }

   /** returns the child patterns of a pattern
    */
  protected def patternArgs(tree: Tree):List[Tree] = {
    //Console.println("patternArgs "+tree.toString());
    val res = tree match {
      case Bind(_, pat) =>
        patternArgs(pat);

      case a @ Apply(_, List(av @ ArrayValue(_, ts))) if isSeqApply(a) && isRightIgnoring(av) =>
	ts.reverse.drop(1).reverse

      case a @ Apply(_, List(av @ ArrayValue(_, ts))) if isSeqApply(a) =>
	ts

      case a @ Apply(_, args) =>
        args;

      case av @ ArrayValue(_, ts) if isRightIgnoring(av) =>
        ts.reverse.drop(1).reverse

      case av @ ArrayValue(_, ts) =>
        ts;

      case _ =>
        List();
    }
    //Console.println("patternArgs returns "+res.toString());
    res
  }

   /* currently no need for extendedSeqApply, ArrayValue in Elem(... _*) style patterns
    * handled in the ArrayValue case
  protected def isExtendedSeqApply( tree: Apply  ): Boolean =  { // NEW
   // Console.print("isSeqApply? "+tree.toString());
   // val res =
	tree match {
	  case Apply(_, list) if list.last.isInstanceOf[ArrayValue] =>
            (tree.tpe.symbol.flags & Flags.CASE) == 0
	  case _ => false;
	}
	//Console.println(res);
	//res;
  }
  */

   //protected var lastSequencePat: PatternNode = null; // hack to optimize sequence matching

  protected def patternNode(tree:Tree , header:Header , env: CaseEnv ): PatternNode  = {
    //if(tree!=null) Console.println("patternNode("+tree+","+header+")");
	//else scala.Predef.error("got null tree in patternNode");
    //Console.println("tree.tpe "+tree.tpe);
    //Console.println("tree.getClass() "+tree.getClass());
    tree match {
      case Bind(name, Typed(Ident( nme.WILDCARD ), tpe)) => // x@_:Type
        if (isSubType(header.getTpe(),tpe.tpe)) {
          //Console.println("U");
          val node = pDefaultPat(tree.pos, tpe.tpe);
          env.newBoundVar( tree.symbol, tree.tpe, header.selector );
          node;
        } else {
          //Console.println("X");
          val node = pConstrPat(tree.pos, tpe.tpe);
          env.newBoundVar( tree.symbol,
                           tpe.tpe, /*scalac: tree.tpe */
                           typed(Ident( node.casted )));
          node;
        }

      case Bind(name, Ident(nme.WILDCARD)) => // x @ _
        val node = pDefaultPat(tree.pos, header.getTpe());
        if ((env != null) && (tree.symbol != defs.PatternWildcard))
          env.newBoundVar( tree.symbol, tree.tpe, header.selector);
        node;

      case Bind(name, pat) =>
        val node = patternNode(pat, header, env);
        if ((env != null) && (tree.symbol != defs.PatternWildcard)) {
          val casted = node.symbol;
          val theValue =  if (casted == NoSymbol) header.selector else Ident( casted).setType(casted.tpe);
          env.newBoundVar(tree.symbol, tree.tpe, theValue);
        }
       node;

      case t @ Apply(fn, args) =>             // pattern with args
        //Console.println("Apply node: "+t);
        //Console.println("isSeqApply "+isSeqApply(t));
        if (isSeqApply(t)) {
          args(0) match {
            //  case Sequence(ts)=>
              case av @ ArrayValue(_, ts)=>
                if(isRightIgnoring(av)) {
                  //Console.println(av.toString()+" IS RIGHTIGNORING");
                  val castedRest = ts.last match {
                    case b:Bind => b.symbol;
                    case _      => null
                  }
                  pRightIgnoringSequencePat(tree.pos, tree.tpe, castedRest, ts.length-1);
                } else
                  //Console.println(av.toString()+" IS  N O T  RIGHTIGNORING");
                  pSequencePat(tree.pos, tree.tpe, ts.length);
          }
	} else if ((fn.symbol != null) &&
                   fn.symbol.isStable &&
                   !(fn.symbol.isModule &&
                     ((fn.symbol.flags & Flags.CASE) != 0))) {
                       pVariablePat(tree.pos, tree);
                     }
          else {
             /*
            Console.println("apply but not seqApply");
            Console.println("tree.tpe="+tree.tpe);
            Console.println("tree.symbol="+tree.symbol);
             */
             pConstrPat(tree.pos, tree.tpe);
          }
      case Typed(Ident( nme.WILDCARD ), tpe) => // x@_:Type
        val doTest = isSubType(header.getTpe(),tpe.tpe); // this is already an optimization
          if(doTest)
            pDefaultPat(tree.pos, tpe.tpe)
          else
            pConstrPat(tree.pos, tpe.tpe);

      case t @ Typed(ident, tpe) =>       // variable pattern
        //Console.println("Z");
        val doTest = isSubType(header.getTpe(),tpe.tpe);
        val node = {
          if(doTest)
            pDefaultPat(tree.pos, tpe.tpe)
          else
            pConstrPat(tree.pos, tpe.tpe);
        }
        if ((null != env) /* && (ident.symbol != defs.PatternWildcard) */)
          node match {
            case ConstrPat(casted) =>
              env.newBoundVar(t.expr.symbol,
                              tpe.tpe,
                              Ident( casted ).setType(casted.tpe));
            case _ =>
              env.newBoundVar(t.expr.symbol,
                              tpe.tpe,
                              {if(doTest)
                                header.selector
                               else
                                 typed(Ident(node
                                             .asInstanceOf[ConstrPat]
                                             .casted))});
          }
      node;

      case Ident(nme.WILDCARD) => pDefaultPat(tree.pos, header.getTpe());

      case Ident(name) => // pattern without args or named constant
        if (tree.symbol.isPrimaryConstructor)
          scala.Predef.error("error may not happen: ident is primary constructor"+tree.symbol); // Burak
        else
          pVariablePat(tree.pos, tree); // named constant (capitalized variable Foo)

      case Select(_, name) => // named constant
        if (tree.symbol.isPrimaryConstructor)
          pConstrPat(tree.pos, tree.tpe);
        else
          pVariablePat(tree.pos, tree);

      case Literal(Constant(value)) =>
        pConstantPat(tree.pos, tree.tpe, value);

      case av @ ArrayValue(_, ts) =>
        if(isRightIgnoring(av)) {
          val castedRest = ts.last match {
            case b:Bind => b.symbol;
            case _      => null
          }
          //Console.println("array value "+av+" is right ignoring!")
          pRightIgnoringSequencePat(tree.pos, tree.tpe, castedRest, ts.length-1);
        } else {
          //Console.println("array value "+av+" is not considered right ignoring")
          //lastSequencePat =
          pSequencePat(tree.pos, tree.tpe, ts.length);
          //lastSequencePat

        }
      case Alternative(ts) =>
        if(ts.length < 2)
          scala.Predef.error("ill-formed Alternative");
        val subroot = pConstrPat(header.pos, header.getTpe());
        subroot.and = pHeader(header.pos, header.getTpe(), header.selector.duplicate);
        val subenv = new CaseEnv;
        var i = 0; while(i < ts.length) {
          val target = enter1(ts(i), -1, subroot, subroot.symbol, subenv);
          target.and = pBody(tree.pos);
          i = i + 1
        }
        pAltPat(tree.pos, subroot.and.asInstanceOf[Header]);
/*
      case Star(Ident(nme.WILDCARD))  =>
        header.selector match {
          case Apply(Select(t, apply), arg @ List(litconst)) =>
            Console.println(t)
            Console.println(apply)
            Console.println(litconst)
            val tree = Apply(Select(Select(t, "toList"), "drop"), arg)
            throw new OptimizeSequencePattern(tree); // ? has to be caught and rethrown by each bind
        }
        // bind the rest /////////////////////////////////////////////////////
*/
      case _ =>
        if(tree == null)
	  scala.Predef.error("unit = " + cunit + "; tree = null");
        else
	  scala.Predef.error("unit = " + cunit + "; tree = "+tree);
    }
  }

  protected def enter(pat: Tree, index: Int, target: PatternNode, casted: Symbol, env: CaseEnv ): PatternNode = {
    target match {
      case ConstrPat(newCasted) =>
        enter1(pat, index, target, newCasted, env);
      case SequencePat(newCasted, len) =>
        enter1(pat, index, target, newCasted, env);
      case _ =>
        enter1(pat, index, target, casted, env);
    }
  }


  private def newHeader(pos: PositionType, casted: Symbol, index: Int): Header = {
    //Console.println("newHeader(pos,"+casted+","+index+")");
    //Console.println("  casted.tpe"+casted.tpe);
    //Console.println("  casted.pos "+casted.pos+"  equals firstpos?"+(casted.pos == Position.FIRSTPOS));
    val ident = typed(Ident(casted));
    if (casted.pos == Position.FIRSTPOS) {
      //Console.println("FIRSTPOS");

      //Console.println("DEBUG");
      //Console.println();

      val t = typed(
        Apply(Select( ident, ident.tpe.member(nme.apply)/* scalac: defs.functionApply( 1 )*/),
              List( Literal( Constant(index) ) )));
      val seqType = t.tpe;
      pHeader( pos, seqType, t );
    } else {
      //Console.println("NOT FIRSTPOS");
     // Console.println("newHeader :: casted="+casted);
     // Console.println("newHeader :: casted.tpe="+casted.tpe);
      //Console.println("newHeader :: ");
      val caseAccs = casted.tpe.symbol.caseFieldAccessors;
      if (caseAccs.length <= index) System.out.println("selecting " + index + " in case fields of " + casted.tpe.symbol + "=" + casted.tpe.symbol.caseFieldAccessors);//debug
      val ts = caseAccs(index);
      //Console.println("newHeader :: ts="+ts);
      //val accType = casted.tpe.memberType(ts); // old scalac
      //val accTree = global.typer.typed(Select(ident, ts)); // !

      val accTree = typed(Apply(Select(ident, ts), List())); // nsc !
      val accType = accTree.tpe;
      //Console.println("newHeader :: accType="+accType);
      //Console.println("newHeader :: accType.resultType ="+accType.resultType);
      //Console.println("accTree.tpe =="+accTree.tpe);

      accType match {
        // scala case accessor
        case MethodType(_, _) =>
          //Console.println("Hello?!");
          pHeader(pos, accType.resultType, Apply(accTree, List()));
        // jaco case accessor
        case _ =>
          //Console.println("Hola?!");
          pHeader(pos, accType, accTree);
      }
    }
  }

  /** main enter function
   *
   *  invariant: ( curHeader == (Header)target.and ) holds
   */
  protected def enter1(pat: Tree, index: Int, target: PatternNode, casted: Symbol,  env: CaseEnv): PatternNode = {
    //System.err.println("enter(" + pat + ", " + index + ", " + target + ", " + casted + ")");
    var bodycond: PatternNode => Body = null; // in case we run into a body (combination of typed pattern and constructor pattern, see bug#644)
    val patArgs = patternArgs(pat);      // get pattern arguments
    //System.err.println("patArgs = "+patArgs);
    var curHeader: Header = target.and match {
      case null => null
      case h: Header => h;    // advance one step in intermediate representation
      case b: Body if b.or != null => b.or.asInstanceOf[Header]
      case b: Body =>
        if(b.guard(b.guard.length - 1) == EmptyTree) {
          cunit.error(pat.pos, "unreachable code")
          null
        }
        else {
          bodycond = {h => b.or = h; b} // depends on the side-effect to curHeader (*)
          null
        }
    }
    if (curHeader == null) {                  // check if we have to add a new header
      //assert index >= 0 : casted;
      if (index < 0) { scala.Predef.error("error entering:" + casted); return null }
      target.and = {curHeader = newHeader(pat.pos, casted, index); curHeader}; // (*)

      if(bodycond != null)
        target.and = bodycond(target.and) // restores body with the guards

      curHeader.or = patternNode(pat, curHeader, env);
      enter(patArgs, curHeader.or, casted, env);
    }
    else {
      // find most recent header
      while (curHeader.next != null)
      curHeader = curHeader.next;
      // create node
      var patNode = patternNode(pat, curHeader, env);
      var next: PatternNode = curHeader;
      // add branch to curHeader, but reuse tests if possible
      while (true) {
        if (next.isSameAs(patNode)) {           // test for patNode already present --> reuse
          // substitute... !!!
          patNode match {
            case ConstrPat(ocasted) =>
              env.substitute(ocasted, typed(Ident(next.asInstanceOf[ConstrPat].casted)));
            case _ =>
          }
          return enter(patArgs, next, casted, env);
        } else if (next.isDefaultPat() ||           // default case reached, or
                   ((next.or == null) &&            //  no more alternatives and
                    (patNode.isDefaultPat() || next.subsumes(patNode)))) {
                      // new node is default or subsumed
                      var header = pHeader(patNode.pos,
                                             curHeader.getTpe(),
                                             curHeader.selector);
                      {curHeader.next = header; header};
                      header.or = patNode;
                      return enter(patArgs,
                                   patNode,
                                   casted,
                                   env);
                    }
          else if (next.or == null) {
            return enter(patArgs, {next.or = patNode; patNode}, casted, env); // add new branch
          } else
            next = next.or;
      }
      error("must not happen");
      null
    }
  }

  /** calls enter for an array of patterns, see enter
   */
  protected def enter(pats:List[Tree], target1: PatternNode , casted1: Symbol  , env: CaseEnv): PatternNode = {
    var target = target1;
    var casted = casted1;
    target match {
      case ConstrPat(newCasted) =>
        casted = newCasted;
      case SequencePat(newCasted, len) =>
        casted = newCasted;
      case RightIgnoringSequencePat(newCasted, _, len) =>
        casted = newCasted;
      case _ =>
    }
    var i = 0; while(i < pats.length) {
      target = enter1(pats(i), i, target, casted, env);
      i = i + 1
    }
    target;
  }

    protected def nCaseComponents(tree: Tree): int = {
        tree match {
          case Apply(fn, _) =>
            val tpe = tree.tpe.symbol.primaryConstructor.tpe;
          //Console.println("~~~ " + tree.type() + ", " + tree.type().symbol.primaryConstructor());
            tpe match {
                // I'm not sure if this is a good idea, but obviously, currently all case classes
                // without constructor arguments have type NoType
            case NoType =>
                error("this cannot happen");
              0
            case MethodType(args, _) =>
                args.length;
            case PolyType(tvars, MethodType(args, _)) =>
                args.length;
            case PolyType(tvars, _) =>
                0;
            case _ =>
              error("not yet implemented;" +
                    "pattern matching for " + tree + ": " + tpe);
            }
        }
      return 0;
    }


    //////////// generator methods

  def toTree(): Tree = {
      if (optimize && isSimpleIntSwitch())
        intSwitchToTree();

      else /* if (false && optimize && isSimpleSwitch())
        switchToTree();
      else */ {
        //print();
        generalSwitchToTree();
      }
    }

  case class Break(res:Boolean) extends java.lang.Throwable;
  case class Break2() extends java.lang.Throwable;

    // TODO disentangle this
    protected def isSimpleSwitch(): Boolean  = {
      print();
      var patNode = root.and;
      while (patNode != null) {
        var node = patNode;
        while (({node = node.or; node}) != null) {
          node match {
                case VariablePat(tree) =>
                  //Console.println(((tree.symbol.flags & Flags.CASE) != 0));
                case ConstrPat(_) =>
                  //Console.println(node.getTpe().toString() + " / " + ((node.getTpe().symbol.flags & Flags.CASE) != 0));
                    var inner = node.and;
                    def funct(inner: PatternNode): Boolean = {
                      //outer: while (true) {
                      inner match {
                        case _h:Header =>
                          if (_h.next != null)
                            throw Break(false);
                          funct(inner.or)

                        case DefaultPat() =>
                          funct(inner.and);

                        case b:Body =>
                          if ((b.guard.length > 1) ||
                              (b.guard(0) != EmptyTree))
                            throw Break(false);

                          throw Break2() // break outer
                        case _ =>
                          //Console.println(inner);
                          throw Break(false);
                      }
                    }
                    var res = false;
                    var set = false;
                    try {
                      funct(inner)
                    } catch {
                      case ex: Break =>
                        res = ex.res;
                        set = true;
                      case ex: Break2 =>
                    }
                    if(set) return res;
            case _ =>
              return false;
          }
        }
        patNode = patNode.nextH();
      }
      return true;
    }

  protected def isSimpleIntSwitch(): Boolean = {
    if (isSameType(selector.tpe.widen, defs.IntClass.tpe)) {
      var patNode = root.and;
      while (patNode != null) {
        var node = patNode;
        while (({node = node.or; node}) != null) {
          node match {
            case ConstantPat(_) => ;
            case _ =>
              return false;
          }
          node.and match {
            case _b:Body =>
              if ((_b.guard.length > 1) ||
                  (_b.guard(0) != EmptyTree) ||
                  (_b.bound(0).length > 0))
                return false;
            case _ =>
              return false;
          }
        }
        patNode = patNode.nextH();
      }
      return true;
    } else
      return false;
  }

  class TagBodyPair(tag1: Int, body1: Tree, next1:TagBodyPair ) {

    var tag: int = tag1;
    var body: Tree = body1;
    var next: TagBodyPair = next1;

    def length(): Int = {
      if (null == next) 1 else (next.length() + 1);
    }
  }

  protected def numCases(patNode1: PatternNode): Int = {
    var patNode = patNode1;
    var n = 0;
    while (({patNode = patNode.or; patNode}) != null)
    patNode match {
      case DefaultPat() => ;
      case _ =>
        n = n + 1;
    }
    n;
  }

  protected def defaultBody(patNode1: PatternNode, otherwise: Tree ): Tree = {
    var patNode = patNode1;
    while (patNode != null) {
      var node = patNode;
      while (({node = node.or; node}) != null)
      node match {
        case DefaultPat() =>
          return node.and.bodyToTree();
        case _ =>
      }
      patNode = patNode.nextH();
    }
    otherwise;
  }

  /** This method translates pattern matching expressions that match
   *  on integers on the top level.
   */
  def intSwitchToTree(): Tree = {
  def insert1(tag: Int, body: Tree, current: TagBodyPair): TagBodyPair = {
    if (current == null)
      return new TagBodyPair(tag, body, null);
    else if (tag > current.tag)
      return new TagBodyPair(current.tag, current.body, insert1(tag, body, current.next));
    else
      return new TagBodyPair(tag, body, current);
  }

    //print();
    val ncases = numCases(root.and);
    val matchError = ThrowMatchError(selector.pos, Ident(root.symbol));
    // without a case, we return a match error if there is no default case
    if (ncases == 0)
      return defaultBody(root.and, matchError);
    // for one case we use a normal if-then-else instruction
    else if (ncases == 1) {
      root.and.or match {
        case ConstantPat(value) =>
          return Block(List(ValDef(root.symbol, selector)),
                            If(Equals(Ident(root.symbol), Literal(value)),
                               (root.and.or.and).bodyToTree(),
                               defaultBody(root.and, matchError)));
        case _ =>
          return generalSwitchToTree();
      }
    }
    //
    // if we have more than 2 cases than use a switch statement
    val _h:Header = root.and.asInstanceOf[Header];

    val next = _h.next;
    var mappings: TagBodyPair = null;
    var defaultBody1: Tree = matchError;
    var patNode = root.and;
    while (patNode != null) {
      var node = patNode.or;
      while (node != null) {
        node match {
          case DefaultPat() =>
            if (defaultBody1 != null)
              scala.Predef.error("not your day today");
            defaultBody1 = node.and.bodyToTree();
            node = node.or;

          case ConstantPat( value: Int )=>
            mappings = insert1(
              value,
              node.and.bodyToTree(),
              mappings);
          node = node.or;
        }
      }
      patNode = patNode.nextH();
    }

    var n = mappings.length();
    var nCases: List[CaseDef] = Nil;
    while (mappings != null) {
      nCases = CaseDef(Literal(mappings.tag),
                       mappings.body) :: nCases;
      mappings = mappings.next;
    }
    /*
    val tags = new Array[Int](n);
    val bodies = new Array[Tree](n);
    n = 0;
    while (mappings != null) {
      tags(n) = mappings.tag;
      bodies(n) = mappings.body;
      n = n + 1;
      mappings = mappings.next;
    }
    return Switch(selector, tags, bodies, defaultBody1, resultType);
    */
    nCases = CaseDef(Ident(nme.WILDCARD), Block(List(ValDef(root.symbol, selector)),defaultBody1)) :: nCases;
    return Match(selector, nCases)
  }


    var exit:Symbol = null;
    /** simple optimization: if the last pattern is `case _' (no guards), we won't generate the ThrowMatchError
     */
  def generalSwitchToTree(): Tree = {
    this.exit = currentOwner.newLabel(root.pos, "exit")
    .setInfo(new MethodType(List(resultType), resultType));
    //Console.println("resultType:"+resultType.toString());
    val result = exit.newValueParameter(root.pos, "result").setInfo( resultType );

    //Console.println("generalSwitchToTree: "+root.or);
    /*
    val ts = List(ValDef(root.symbol, selector));
    val res = If(toTree(root.and),
                 LabelDef(exit, List(result), Ident(result)),
                 ThrowMatchError(selector.pos,  resultType // , Ident(root.symbol)
                               ));
    return Block(ts, res);
    */
    return Block(
      List(
        ValDef(root.symbol, selector),
        toTree(root.and),
        ThrowMatchError(selector.pos,  Ident(root.symbol))),
      LabelDef(exit, List(result), Ident(result)))
  }

  /*protected*/ def toTree(node1: PatternNode): Tree = {
    def optimize1(selType:Type, alternatives1: PatternNode ): Boolean = {
      var alts = alternatives1;
      if (!optimize || !isSubType(selType, defs.ScalaObjectClass.tpe))
        return false;
      var cases = 0;
      while (alts != null) {
        alts match {
          case ConstrPat(_) =>
            if (alts.getTpe().symbol.hasFlag(Flags.CASE))
              cases = cases +1;
            else
              return false;

          case DefaultPat() =>
            ;
          case _ =>
            return false;
        }
        alts = alts.or;
      }
      return cases > 2;
    } // def optimize

    var node = node1;

    var res: Tree = typed(Literal(Constant(false))); //.setInfo(defs.BooleanClass);
    //Console.println("pm.toTree  res.tpe "+res.tpe);
    while (node != null)
    node match {

      case _h:Header =>
        val selector = _h.selector;
        val next = _h.next;
        //res = And(mkNegate(res), toTree(node.or, selector));
        //Console.println("HEADER TYPE = " + selector.type);
        if (optimize1(node.getTpe(), node.or))
          res = Or(res, toOptTree(node.or, selector));
        else
          res = Or(res, toTree(node.or, selector));
        node = next;

      case _b:Body =>
        var bound = _b.bound;
        val guard = _b.guard;
        val body  = _b.body;
        if ((bound.length == 0) &&
            (guard.length == 0) &&
            (body.length == 0)) {
              return Literal(Constant(true));
            }
        var i = guard.length - 1; while(i >= 0) {
        val ts:Seq[Tree] = bound(i).asInstanceOf[Array[Tree]];
        val temp = currentOwner.newValue(body(i).pos, cunit.fresh.newName("r$"))
          .setFlag(Flags.SYNTHETIC).setInfo(resultType);
          var res0: Tree =
            //Block(
            //  List(Assign(Ident(resultVar), body(i))),
            //  Literal(Constant(true)));
            Block(
              List(
                ValDef(temp, body(i)),
                Apply(Ident(exit), List(Ident(temp)))),
              Literal(Constant(true))
            ); // forward jump
          if (guard(i) != EmptyTree)
            res0 = And(guard(i), res0);
          res = Or(Block(ts.toList, res0), res);
          i = i - 1
        }
      if (_b.or != null)
        res = Or(res, toTree(_b.or))
      return res;
        case _ =>
          scala.Predef.error("I am tired");
      }
      return res;
    }


    class TagNodePair(tag1: int, node1: PatternNode, next1: TagNodePair) {
      var tag: int = tag1;
      var node: PatternNode = node1;
      var next: TagNodePair = next1;

      def  length(): Int = {
        return if (null == next)  1 else (next.length() + 1);
      }
    }

    protected def toOptTree(node1: PatternNode, selector: Tree): Tree = {
      def insert2(tag: Int, node: PatternNode, current: TagNodePair): TagNodePair = {
        if (current == null)
          return new TagNodePair(tag, node, null);
        else if (tag > current.tag)
          return new TagNodePair(current.tag, current.node, insert2(tag, node, current.next));
        else if (tag == current.tag) {
          val old = current.node;
          ({current.node = node; node}).or = old;
          return current;
        } else
          return new TagNodePair(tag, node, current);
      }

      def  insertNode(tag:int , node:PatternNode , current:TagNodePair ): TagNodePair = {
        val newnode = node.dup();
        newnode.or = null;
        return insert2(tag, newnode, current);
      }
      var node = node1;
      //System.err.println("pm.toOptTree called"+node);
      var cases: TagNodePair  = null;
      var defaultCase: PatternNode  = null;
      while (node != null)
      node match {
        case ConstrPat(casted) =>
          cases = insertNode(node.getTpe().symbol.tag, node, cases);
          node = node.or;

        case DefaultPat() =>
          defaultCase = node;
          node = node.or;

        case _ =>
          scala.Predef.error("errare humanum est");
      }
      var n = cases.length();
      /*
      val tags = new Array[int](n);
      val bodies = new Array[Tree](n);
      n = 0;
      while (null != cases) {
        tags(n) = cases.tag;
        bodies(n) = toTree(cases.node, selector);
        n = n + 1;
        cases = cases.next;
      }
      */


      /*
      return
      Switch(
        Apply(
          Select(selector.duplicate, defs.ScalaObjectClass_tag),
          List()),
        tags,
        bodies,
        { if (defaultCase == null) Literal(false) else toTree(defaultCase.and) },
                        defs.boolean_TYPE());
                        */
      var nCases: List[CaseDef] = Nil;
      while (cases != null) {
        nCases = CaseDef(Literal(Constant(cases.tag)),
                         toTree(cases.node, selector)) :: nCases;
        cases = cases.next;
      }

      val defBody = if (defaultCase == null)
                      Literal(Constant(false))
                    else
                      toTree(defaultCase.and);

      nCases = CaseDef(Ident(nme.WILDCARD), defBody) :: nCases;
      return Match(Apply(Select(selector.duplicate, defs.ScalaObjectClass_tag),
                         List()),
                   nCases);
    }

   /** why not use plain `if's? the reason is that a failing *guard* must still remain
    *  on the testing path (a kind of backtracking) in order to test subsequent patterns
    *  consider for instance bug#440
    *
    */
   def myIf(cond:Tree,thenp:Tree,elsep:Tree) = {
     Or(And(cond,thenp),elsep);
   }

    protected def toTree(node:PatternNode , selector:Tree ): Tree = {
      //Console.println("pm.toTree("+node+","+selector+")");
      //Console.println("pm.toTree selector.tpe = "+selector.tpe+")");
      if(selector.tpe == null)
        scala.Predef.error("cannot go on");
      if (node == null)
        return Literal(Constant(false));
      else
        node match {
          case DefaultPat() =>
            return toTree(node.and);

          case ConstrPat(casted) =>
            return myIf(gen.mkIsInstanceOf(selector.duplicate, node.getTpe()),
                      Block(
                        List(ValDef(casted,
                                    gen.mkAsInstanceOf(selector.duplicate, node.getTpe(), true))),
                            toTree(node.and)),
                      toTree(node.or, selector.duplicate));
          case SequencePat(casted, len) =>
            return (
          Or(
            And(
              And(gen.mkIsInstanceOf(selector.duplicate, node.getTpe()),
                     Equals(
                       typed(
                         Apply(
                           Select(
                             gen.mkAsInstanceOf(selector.duplicate,
                                                node.getTpe(),
                                                true),
                             node.getTpe().member(nme.length) /*defs.Seq_length*/),
                           List())
                       ),
                       typed(
                         Literal(Constant(len))
                       ))),
              Block(
                List(
                  ValDef(casted,
                         gen.mkAsInstanceOf(selector.duplicate, node.getTpe(), true))),
                  toTree(node.and))),
            toTree(node.or, selector.duplicate)));

          case RightIgnoringSequencePat(casted, castedRest, minlen) =>
          Or(
            And({
              var cond:Tree = gen.mkIsInstanceOf(selector.duplicate, node.getTpe()); // test for sequence

              if(minlen > 0) { // test for minimum length if necessary
                cond = And(cond,
                           GreaterThanOrEquals(
                             typed(
                               Apply(
                                 Select(
                                   gen.mkAsInstanceOf(selector.duplicate,
                                                      node.getTpe(),
                                                      true),
                                   node.getTpe().member(nme.length) /*defs.Seq_length*/),
                                 List())
                             ),
                             typed(
                               Literal(Constant(minlen))
                             )));
              }
              cond
            },
              Block(
                List(
                  ValDef(casted,
                         gen.mkAsInstanceOf(selector.duplicate, node.getTpe(), true)),
                  ValDef(castedRest, {
                    var res:Tree = Ident(casted) // gen.mkAsInstanceOf(selector.duplicate, node.getTpe(), true);
                    if(minlen != 0) {
                      res = Apply(Select(Select(res, "toList"), "drop"),List(Literal(Constant(minlen))))

                    }
                    res
                  })),
                toTree(node.and))),
            toTree(node.or, selector.duplicate));

          case ConstantPat(value) =>
            //Console.println("selector = "+selector);
            //Console.println("selector.tpe = "+selector.tpe);
            return myIf(Equals(selector.duplicate,
                             typed(Literal(Constant(value))).setType(node.tpe)),
                      toTree(node.and),
                      toTree(node.or, selector.duplicate));
          case VariablePat(tree) =>
            val cmp = if(tree.tpe.symbol.isModuleClass && // objects are compared by eq, not == (avoids unnecessary null-magic)
                         selector.tpe <:< definitions.AnyRefClass.tpe) {
                        Eq(selector.duplicate, tree)
                      } else  {
                        Equals(selector.duplicate, tree)
                      }
            return myIf( cmp,
                      toTree(node.and),
                      toTree(node.or, selector.duplicate));

          case AltPat(header) =>
            return myIf(toTree(header),
                      toTree(node.and),
                      toTree(node.or, selector.duplicate));
          case _ =>
            scala.Predef.error("can't plant this tree");
        }
    }
}


}