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

import scalac.*;
import scalac.ast.*;
import scalac.symtab.*;
import Tree.*;
import scalac.util.Name;
import scalac.util.Names;

import scalac.transformer.TransMatch.Matcher ;

import java.util.* ;

import ch.epfl.lamp.util.Position;

public class LeftTracerInScala extends TracerInScala {

      Tree selector;

      /** symbol of the accumulator ( scala.SequenceList )
       */
      Symbol accumSym;

      Type _accumType( Type elemType ) {
            return cf.SeqTraceType( elemType );
      }


      Matcher _m ;
      public LeftTracerInScala( DetWordAutom dfa,
                                Type elementType,
                                Matcher m,
                                CodeFactory cf ) {

	  super( dfa, elementType, m.owner, cf );
	  this._m = m;
	  this.selector = m.selector;
	  //helpMap = new HashMap(); moved up
	  helpVarDefs = new Vector();

      }

    Vector  helpVarDefs;

    Symbol makeHelpVar( Symbol realVar ) {
	Symbol helpVar = new TermSymbol( pos,
					 cf.fresh.newName( realVar.name
							   .toString() ),
					 owner,
					 0)
	    .setType( cf.SeqListType( elementType ) ) ;

	helpMap.put( realVar, helpVar );

	Tree varDef = gen.ValDef(helpVar, gen.Nil(cf.pos /*cf.newSeqNil elementType*/ ));
	// set mutable flag of symbol helpVar ??
	helpVarDefs.add( varDef );
	return helpVar;
    }

    Symbol makeHelpVarSEQ( Tree pat ) {
	String  helpName = String.valueOf( pat.hashCode() ); //wicked, in'it ?
	Symbol helpVar =
	    new TermSymbol( pos,
			    cf.fresh.newName(Name.fromString( helpName )),
			    owner,
			    0)
	    .setType( cf.SeqListType( pat.type() )) ;

	ValDef varDef = (ValDef) gen.ValDef( helpVar,
					     gen.mkDefaultValue(cf.pos,
								cf.SeqListType( pat.type() ))
					     //cf.ignoreValue( )
					     );
	helpVarDefs.add( varDef );
	return helpVar;
    }

    protected void initializeSyms() {
	funSymName = "leftTracer";

	nestedMap = new HashMap();

	super.initializeSyms();

	this.accumSym = newParam("accum")                    // accumulator
	    .setType( _accumType( elementType ));

	this.funSym
	    .setType( new Type.MethodType( new Symbol[] {
		accumSym, iterSym, stateSym},
					   _accumType( elementType )));

	// 2 do: rename switchresultsym to something else...

	this.resultSym = new TermSymbol( //Kinds.VAR,
					pos,
					cf.fresh.newName("trace"),
					owner,
					0 )
	    .setType( _accumType( elementType ) ) ;
    }

    // should throw an exception here really, e.g. MatchError
    Tree code_fail() {
	return gen.Ident( accumSym.pos, accumSym );

    }

    /** returns translation of transition with label from i.
     *  returns null if there is no such transition(no translation needed)
     */
    Tree code_delta( int i, Label label ) {
	Integer target = dfa.delta( i, label );
	/*
	  System.out.println("LeftTracer:calling dfa.delta("+i+","+label+")");
	  System.out.println("result: "+target);
	*/
	if( target == null )
	    return null;

	// (optimization) that one is a dead state (does not make sense for tracer)
	/*
	  if( target == dfa.nstates - 1 )
	  return code_fail();
	*/

	/*
	Tree newAcc = cf.newSeqTraceCons(new Integer(i),
					 currentElem(),
					 _ref( accumSym ));
	*/
	Tree hd = cf.newPair( gen.mkIntLit(cf.pos, i), currentElem() );
	Tree newAcc = gen.Cons(cf.pos,
			       hd.type,
			       hd,
			       _ref( accumSym ));

	return callFun( new Tree[] { newAcc , _iter(), gen.mkIntLit( cf.pos, target )} );
    }


    public Tree code_body() {

	Tree body = code_fail(); // never reached at runtime.

	// state [ nstates-1 ] is the dead state, so we skip it

	//`if( state == q ) <code_state> else {...}'
	for( int i = dfa.nstates-2; i >= 0; i-- ) {
	    body = code_state( i, body );
	}

	return loadCurrentElem( body );

    }

    /** return code for state i of the dfa SAME AS IN SUPER, ONLY SINK IS GONE
     */
    Tree code_state( int i, Tree elseBody ) {

	Tree runFinished; // holds result of the run
	int  finalSwRes;

	runFinished = run_finished( i );

	Tree stateBody ; // action(delta) for one particular label/test

	// default action (fail if there is none)

	stateBody = code_delta( i, Label.DefaultLabel);

	if( stateBody == null )
	    stateBody = code_fail();
	// transitions of state i

	HashMap trans = ((HashMap[])dfa.deltaq)[ i ];

	for( Iterator labs = ((HashMap)dfa.deltaq( i )).keySet().iterator();
	     labs.hasNext() ; ) {
	    Object label = labs.next();
	    Integer next = (Integer) trans.get( label );

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

	    if( action != null ) {
		stateBody = cf.If( _cur_eq( _iter(), (Label) label ),
				   action,
				   stateBody);
	    }
	}
	stateBody = cf.If( cf.Negate( _ref( hasnSym )),
			   runFinished,
			   stateBody );
	return cf.If( cf.Equals( _state(), gen.mkIntLit(cf.pos, i )),
		      stateBody ,
		      elseBody );
    }

    Tree[] getTrace() {

	initializeSyms();
	Tree tb = code_body();
	theDefDef = gen.DefDef( this.funSym,
				tb );

	Vector v = new Vector();

	v.addAll( helpVarDefs );

	//
	// `def leftTracer(...) = ...'                 the function definition
	v.add( theDefDef );

	Tree emptyAcc    = gen.Nil( cf.pos ); //cf._seqTraceNil( elementType );

	// the valdef is needed, because passing emptyAcc as a parameter
	//   results in a ClassCastException at runtime (?!)

	Symbol emptyAccSym = new TermSymbol( pos,
					     cf.fresh.newName("acc"),
					     owner,
					     0 )
	    .setType( _accumType( elementType ) ) ;

	// `val acc = SeqNil[ elementType ]'                 init accumulator
	v.add( gen.ValDef( emptyAccSym, emptyAcc) );

	Tree run = callFun( new Tree[] {
	    gen.Ident( pos, emptyAccSym ),
	    cf.newIterator( selector, selector.type() ),
	    gen.mkIntLit( cf.pos, 0 )  });

	run = gen.ValDef( resultSym, run );

	v.add( run );

	// vars...
	for( Iterator it = helpMap.keySet().iterator(); it.hasNext(); ) {
	    v.add( bindVar( (Symbol) it.next()) );
	}

	/* IF YOU NEED DEBUG OUTPUT AT RUNTIME
	   v.add( cf.debugPrintRuntime( "the trace is" ) );
	   v.add( cf.debugPrintRuntime( gen.Ident( pos, resultSym ) ) );
	   v.add( cf.debugPrintNewlineRuntime( "" ) );
	*/

	Tree res[] = new Tree[ v.size() ];
	int j = 0;
	for( Iterator it = v.iterator(); it.hasNext(); )
	    res[ j++ ] = (Tree) it.next();

	_m.varMap = nestedMap;

	return res;

    }

    public HashMap nestedMap;

    // calling the AlgebraicMatcher here
    Tree _cur_match( Tree pat ) {
	//System.out.println("calling algebraic matcher on type:"+pat.type);

	Matcher m = new Matcher( funSym,
				 currentElem(),
				 defs.BOOLEAN_TYPE );

	if( CollectVariableTraverser.containsBinding( pat )) {
	    switch( pat ) {
	    case Sequence(Tree[] pats):
		//System.out.println("ouch! v Left");
		Symbol hv = makeHelpVarSEQ( pat );
		nestedMap.put( pat, hv );
		Tree stm  = gen.Assign( gen.Ident(Position.FIRSTPOS, hv), currentElem() );
		m.stms = new Tree[2];
		m.stms[0] = stm;
		m.stms[1] = gen.mkBooleanLit(Position.FIRSTPOS, true);
		return gen.mkBlock(m.stms);
	    }
	}

	HashMap helpMap = FreshVariableTraverser.getVars( pat, owner, cf.fresh );
	//System.out.println("varMap: "+helpMap );

	m.varMap = helpMap;

	//replaceVars( pat );

	am.construct( m, new CaseDef[] {
	    (CaseDef) cf.make.CaseDef( pat.pos,
				       pat,
				       Tree.Empty,
				       gen.mkBooleanLit( cf.pos, true )),
	    (CaseDef) cf.make.CaseDef( pat.pos,
				       cf.make.Ident(pat.pos, Names.WILDCARD)
				       //DON'T .setSymbol( Symbol.NONE ) !
				       .setType(pat.type()),
				       Tree.Empty,
				       gen.mkBooleanLit( cf.pos, false)) },
		      false
		      );
	Tree res = am.toTree().setType( defs.BOOLEAN_TYPE );
	return res;
    }


    /** return the accumulator + last state
     */
    Tree run_finished( int state ) {
	Tree hd = cf.newPair( gen.mkIntLit( cf.pos, state ),
			      gen.mkDefaultValue(cf.pos,
						 elementType)
			      /*cf.ignoreValue( elementType )*/);
	//System.err.println(hd.type);
	return gen.Cons(  cf.pos,
			  hd.type(),
			  hd,
			  _ref( accumSym ));
    }

}