summaryrefslogtreecommitdiff
path: root/sources/scalac/transformer/matching/Autom2Scala.java
blob: 4452a38bd8d441e0548be7f68c306e65001c435a (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
package scalac.transformer.matching ;

import scalac.* ;
import scalac.symtab.Symbol ;
import scalac.symtab.Type ;
import scalac.symtab.TermSymbol ;
import scalac.symtab.Definitions ;
import scalac.ast.Tree;
import scalac.ast.TreeGen;
import scalac.util.Name;
import scalac.util.Names;
import Tree.*;

import scalac.transformer.TransMatch.Matcher ;
import java.util.* ;

import ch.epfl.lamp.util.Position;

public class Autom2Scala  {

    protected boolean optimize = true;

      static final Name HASNEXT = Name.fromString("hasnext");
      static final Name CURRENT_ELEM = Name.fromString("cur");

      final int FAIL = -1;

      DetWordAutom dfa;
      protected CodeFactory cf;

    //Vector freeVars;
    //Vector mdefs;

      Definitions defs;
      TreeGen     gen;

      /** owner of the pattern matching expression */
      protected Symbol owner;

      /** symbol of the matcher fun */
      Symbol funSym;

      /** symbol of the iterator ( scala.SequenceIterator ) */
      Symbol iterSym;

      /** symbol of the switching result ( scala.Int ) */
      Symbol resultSym;

      /** symbol of the state variable ( scala.Int ) */
      Symbol stateSym;

      protected Type elementType;

      public int pos;

      String funSymName;

      Symbol newFunSym( String prefix ) {
	  return new TermSymbol( pos,
				 cf.fresh.newName( prefix ),
				 owner,
				 0);
      }

      Symbol newParam( String prefix ) {
	  return new TermSymbol( /*Kinds.VAL, */
                                   pos,
                                   cf.fresh.newName( prefix ),
                                   funSym,
                                   0);
      }

      Type funRetType() {
            switch( funSym.type() ) {
            case MethodType( _, Type retType ):
                  return retType;
            }
            throw new RuntimeException();
      }


      Tree callFun( Tree[] args ) {
            return gen.mkApply_V(gen.Ident(pos, funSym), args);
      }


      /** init funSym, iterSym, stateSym, resultSym + allocate mdefs.
       *  a subclass overriding initializeSyms may change these
       *   (esp. funSym)
       */
      protected void initializeSyms() {
            if( funSymName == null )
                  funSymName = "matcher";
            // the function that does the matching

            this.funSym = newFunSym( funSymName );

            this.iterSym = newParam("iter")
                  .setType( cf._seqIterType( elementType ) ) ;

            this.stateSym = newParam("q")
                  .setType( defs.INT_TYPE() ) ;

            this.resultSym = new TermSymbol( pos,
					     cf.fresh.newName("swRes"),
					     owner,
					     0 )
                  .setType( defs.INT_TYPE() ) ;

            this.funSym
                  .setType( new Type.MethodType( new Symbol[] {
                        iterSym, stateSym },  defs.INT_TYPE() ));

            this.curSym = new TermSymbol( pos,
                                          CURRENT_ELEM,
                                          funSym,
                                          0)
                  .setType( elementType );

            this.hasnSym = new TermSymbol( pos,
					   HASNEXT,
					   funSym,
					   0)
                  .setType( defs.BOOLEAN_TYPE() );

      }


      public Autom2Scala( DetWordAutom dfa,
                          Type elementType,
                          Symbol owner,
                          CodeFactory cf ) {
            this.dfa = dfa;
            this.elementType = elementType;
            this.defs = cf.defs;
            this.gen = cf.gen;
            this.owner = owner;
            this.pos = Position.FIRSTPOS;
            this.cf = cf;
            this.am = new AlgebraicMatcher( cf.unit );
            //this.mdefs = new Vector();

            //this.freeVars = new Vector();
      }

      public Tree theDefDef;

      Symbol curSym;
      Symbol hasnSym;

    // overridden in TracerInScala
    Tree loadCurrentElem( Tree body ) {
	return gen.mkBlock( new Tree[] {
	    cf.gen.ValDef( this.hasnSym,
			   cf._hasNext( _iter() ) ),
	    cf.gen.ValDef( this.curSym,
			   gen.If( gen.Ident( pos, hasnSym ),//cf._hasNext( _iter() ),
				   cf._next( _iter() ),
				   gen.mkDefaultValue(cf.pos,curSym.type()))),
						 //cf.ignoreValue( curSym.type() )

	    body });
    }

    Tree currentElem() {
	return gen.Ident(Position.FIRSTPOS, curSym);
    }

      Tree currentMatches( Label label ) {
            return _cur_eq( _iter(), label );
      }

      //
      // translation of automata to scala code
      //


      /** creates an int variable
       */
      Tree _intvar( Symbol sym, Tree init ) {
	  return gen.ValDef( sym, init );
      }

      /** `<switchResult>'
       */
      public Tree _swres() { return gen.Ident( pos, resultSym );}

      /** `<state>'
       */
      public Tree _state() { return gen.Ident( pos, stateSym ); }

      /** code to reference the iterator
       */
      Tree _iter() {         return gen.Ident( pos, iterSym );  }

      /** body of the matcherDefFun
       */

    public Tree code_body_NEW() {
	int[] tags = new int[dfa.nstates];
	Tree[] bodies = new Tree[dfa.nstates];
	for( int i = 0; i<dfa.nstates; i++ ) {
	    tags[ i ]   = i;
	    if( dfa.isSink( i ))
		bodies[ i ] = run_finished( i ); // state won't change!
	    else
		bodies[ i ] = gen.If( cf.Negate( gen.Ident( pos, hasnSym )),//cf._not_hasNext( _iter() ),
				      run_finished( i ),
				      code_state_NEW( i ));
	}
	if( optimize )
	    return loadCurrentElem( gen.Switch( _state(),
					       tags,
					       bodies,
					       gen.mkIntLit(cf.pos, -1 ),
                                               funRetType()));

	Tree res = code_fail();
	for( int i = dfa.nstates-2; i>= 0; i-- )
	    res = gen.If( cf.Equals( _state(), gen.mkIntLit( cf.pos, i )),
			  bodies[ i ] ,
			  res );

	return loadCurrentElem( res );

    }

      Tree _cur_eq( Tree iter, Label label ) {
            switch( label ) {
            case TreeLabel( Tree pat ):
                  return _cur_match( pat );
            case SimpleLabel( Tree.Literal lit ):
                  return cf.Equals( currentElem(), lit );
            }
            throw new ApplicationError("expected either algebraic or simple label:"+label);
      }

      AlgebraicMatcher am;

    /*
      void handleVars(  ) {
      }
    */
      // calling the /*AlgebraicMatcher*/PatternMatcher here
      Tree _cur_match( Tree pat ) {
            Matcher m = new Matcher( funSym,//this.funSym,
                                     currentElem(),
                                     defs.BOOLEAN_TYPE() );

            am.construct( m, new CaseDef[] {
                cf.gen.CaseDef( pat,
                                gen.mkBooleanLit( pat.pos, true )),
                cf.gen.CaseDef( cf.gen.Ident(pat.pos, defs.PATTERN_WILDCARD),
                                gen.mkBooleanLit( pat.pos, false )) },
                false);
            return am.toTree();
      }

      Tree code_delta( int i, Label label ) {
            throw new RuntimeException();
      }

      Tree code_fail() {
            return gen.mkIntLit(Position.FIRSTPOS, FAIL );
      }

      /** code for the return value of the automaton translation
       */
      Tree run_finished( int state ) {
            if( dfa.isFinal( state )) {
                  return gen.mkIntLit(Position.FIRSTPOS, ((Integer) dfa.finals.get( new Integer( state ) )).intValue() );
            }
            return gen.mkIntLit(Position.FIRSTPOS, FAIL );
      }

    /*
    Tree ifInputHasNext() {
	return cf.If( cf._hasNext( _iter() ),
		      cf.Block( stateBody.pos,
				new Tree[] {
				    loadCurrentElem(),
				    stateBody},
				stateBody.type()) );
    }
    */

    Tree code_state_NEW( int i ) {
	Tree stateBody = code_delta(i, Label.DefaultLabel );
	HashMap trans = ((HashMap[])dfa.deltaq)[ i ];

	for( Iterator labs = dfa.labels.iterator(); labs.hasNext() ; ) {
	    Object label = labs.next();
	    Integer next = (Integer) trans.get( label );


	    Tree action = code_delta( i, (Label) label );

	    if( action != null ) {

		stateBody = gen.If( currentMatches((Label) label ),
				    action,
				    stateBody);
	    }
	}
	return stateBody;
    }
}