e70a7b796970f86ab6915a8384362c82b77b77c3
[external/ragel.git] / rlgen-java / javacodegen.cpp
1 /*
2  *  Copyright 2006-2007 Adrian Thurston <thurston@cs.queensu.ca>
3  *            2007 Colin Fleming <colin.fleming@caverock.com>
4  */
5
6 /*  This file is part of Ragel.
7  *
8  *  Ragel is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  * 
13  *  Ragel is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  * 
18  *  You should have received a copy of the GNU General Public License
19  *  along with Ragel; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
21  */
22
23 #include "rlgen-java.h"
24 #include "javacodegen.h"
25 #include "redfsm.h"
26 #include "gendata.h"
27 #include <iomanip>
28 #include <sstream>
29
30 /* Integer array line length. */
31 #define IALL 12
32
33 /* Static array initialization item count 
34  * (should be multiple of IALL). */
35 #define SAIIC 8184
36
37 #define _resume    1
38 #define _again     2
39 #define _eof_trans 3
40 #define _test_eof  4
41 #define _out       5
42
43 using std::setw;
44 using std::ios;
45 using std::ostringstream;
46 using std::string;
47 using std::cerr;
48
49 void lineDirective( ostream &out, char *fileName, int line )
50 {
51         /* Write the preprocessor line info for to the input file. */
52         out << "// line " << line  << " \"";
53         for ( char *pc = fileName; *pc != 0; pc++ ) {
54                 if ( *pc == '\\' )
55                         out << "\\\\";
56                 else
57                         out << *pc;
58         }
59         out << "\"\n";
60 }
61
62 void genLineDirective( ostream &out )
63 {
64         std::streambuf *sbuf = out.rdbuf();
65         output_filter *filter = static_cast<output_filter*>(sbuf);
66         lineDirective( out, filter->fileName, filter->line + 1 );
67 }
68
69 void JavaTabCodeGen::GOTO( ostream &ret, int gotoDest, bool inFinish )
70 {
71         ret << "{" << CS() << " = " << gotoDest << "; _goto_targ = " << _again << "; " << 
72                         CTRL_FLOW() << "continue _goto;}";
73 }
74
75 void JavaTabCodeGen::GOTO_EXPR( ostream &ret, InlineItem *ilItem, bool inFinish )
76 {
77         ret << "{" << CS() << " = (";
78         INLINE_LIST( ret, ilItem->children, 0, inFinish );
79         ret << "); _goto_targ = " << _again << "; " << CTRL_FLOW() << "continue _goto;}";
80 }
81
82 void JavaTabCodeGen::CALL( ostream &ret, int callDest, int targState, bool inFinish )
83 {
84         if ( prePushExpr != 0 ) {
85                 ret << "{";
86                 INLINE_LIST( ret, prePushExpr, 0, false );
87         }
88
89         ret << "{" << STACK() << "[" << TOP() << "++] = " << CS() << "; " << CS() << " = " << 
90                         callDest << "; _goto_targ = " << _again << "; " << CTRL_FLOW() << "continue _goto;}";
91
92         if ( prePushExpr != 0 )
93                 ret << "}";
94 }
95
96 void JavaTabCodeGen::CALL_EXPR( ostream &ret, InlineItem *ilItem, int targState, bool inFinish )
97 {
98         if ( prePushExpr != 0 ) {
99                 ret << "{";
100                 INLINE_LIST( ret, prePushExpr, 0, false );
101         }
102
103         ret << "{" << STACK() << "[" << TOP() << "++] = " << CS() << "; " << CS() << " = (";
104         INLINE_LIST( ret, ilItem->children, targState, inFinish );
105         ret << "); _goto_targ = " << _again << "; " << CTRL_FLOW() << "continue _goto;}";
106
107         if ( prePushExpr != 0 )
108                 ret << "}";
109 }
110
111 void JavaTabCodeGen::RET( ostream &ret, bool inFinish )
112 {
113         ret << "{" << CS() << " = " << STACK() << "[--" << TOP() << "];";
114
115         if ( postPopExpr != 0 ) {
116                 ret << "{";
117                 INLINE_LIST( ret, postPopExpr, 0, false );
118                 ret << "}";
119         }
120
121         ret << "_goto_targ = " << _again << "; " << CTRL_FLOW() << "continue _goto;}";
122 }
123
124 void JavaTabCodeGen::BREAK( ostream &ret, int targState )
125 {
126         ret << "{ " << P() << " += 1; _goto_targ = " << _out << "; " << 
127                         CTRL_FLOW() << " continue _goto;}";
128 }
129
130 void JavaTabCodeGen::NEXT( ostream &ret, int nextDest, bool inFinish )
131 {
132         ret << CS() << " = " << nextDest << ";";
133 }
134
135 void JavaTabCodeGen::NEXT_EXPR( ostream &ret, InlineItem *ilItem, bool inFinish )
136 {
137         ret << CS() << " = (";
138         INLINE_LIST( ret, ilItem->children, 0, inFinish );
139         ret << ");";
140 }
141
142 void JavaTabCodeGen::EXEC( ostream &ret, InlineItem *item, int targState, int inFinish )
143 {
144         /* The parser gives fexec two children. The double brackets are for D
145          * code. If the inline list is a single word it will get interpreted as a
146          * C-style cast by the D compiler. */
147         ret << "{" << P() << " = ((";
148         INLINE_LIST( ret, item->children, targState, inFinish );
149         ret << "))-1;}";
150 }
151
152 /* Write out an inline tree structure. Walks the list and possibly calls out
153  * to virtual functions than handle language specific items in the tree. */
154 void JavaTabCodeGen::INLINE_LIST( ostream &ret, InlineList *inlineList, 
155                 int targState, bool inFinish )
156 {
157         for ( InlineList::Iter item = *inlineList; item.lte(); item++ ) {
158                 switch ( item->type ) {
159                 case InlineItem::Text:
160                         ret << item->data;
161                         break;
162                 case InlineItem::Goto:
163                         GOTO( ret, item->targState->id, inFinish );
164                         break;
165                 case InlineItem::Call:
166                         CALL( ret, item->targState->id, targState, inFinish );
167                         break;
168                 case InlineItem::Next:
169                         NEXT( ret, item->targState->id, inFinish );
170                         break;
171                 case InlineItem::Ret:
172                         RET( ret, inFinish );
173                         break;
174                 case InlineItem::PChar:
175                         ret << P();
176                         break;
177                 case InlineItem::Char:
178                         ret << GET_KEY();
179                         break;
180                 case InlineItem::Hold:
181                         ret << P() << "--;";
182                         break;
183                 case InlineItem::Exec:
184                         EXEC( ret, item, targState, inFinish );
185                         break;
186                 case InlineItem::Curs:
187                         ret << "(_ps)";
188                         break;
189                 case InlineItem::Targs:
190                         ret << "(" << CS() << ")";
191                         break;
192                 case InlineItem::Entry:
193                         ret << item->targState->id;
194                         break;
195                 case InlineItem::GotoExpr:
196                         GOTO_EXPR( ret, item, inFinish );
197                         break;
198                 case InlineItem::CallExpr:
199                         CALL_EXPR( ret, item, targState, inFinish );
200                         break;
201                 case InlineItem::NextExpr:
202                         NEXT_EXPR( ret, item, inFinish );
203                         break;
204                 case InlineItem::LmSwitch:
205                         LM_SWITCH( ret, item, targState, inFinish );
206                         break;
207                 case InlineItem::LmSetActId:
208                         SET_ACT( ret, item );
209                         break;
210                 case InlineItem::LmSetTokEnd:
211                         SET_TOKEND( ret, item );
212                         break;
213                 case InlineItem::LmGetTokEnd:
214                         GET_TOKEND( ret, item );
215                         break;
216                 case InlineItem::LmInitTokStart:
217                         INIT_TOKSTART( ret, item );
218                         break;
219                 case InlineItem::LmInitAct:
220                         INIT_ACT( ret, item );
221                         break;
222                 case InlineItem::LmSetTokStart:
223                         SET_TOKSTART( ret, item );
224                         break;
225                 case InlineItem::SubAction:
226                         SUB_ACTION( ret, item, targState, inFinish );
227                         break;
228                 case InlineItem::Break:
229                         BREAK( ret, targState );
230                         break;
231                 }
232         }
233 }
234
235 string JavaTabCodeGen::DATA_PREFIX()
236 {
237         if ( dataPrefix )
238                 return FSM_NAME() + "_";
239         return "";
240 }
241
242 /* Emit the alphabet data type. */
243 string JavaTabCodeGen::ALPH_TYPE()
244 {
245         string ret = keyOps->alphType->data1;
246         if ( keyOps->alphType->data2 != 0 ) {
247                 ret += " ";
248                 ret += + keyOps->alphType->data2;
249         }
250         return ret;
251 }
252
253 /* Emit the alphabet data type. */
254 string JavaTabCodeGen::WIDE_ALPH_TYPE()
255 {
256         string ret;
257         if ( redFsm->maxKey <= keyOps->maxKey )
258                 ret = ALPH_TYPE();
259         else {
260                 long long maxKeyVal = redFsm->maxKey.getLongLong();
261                 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
262                 assert( wideType != 0 );
263
264                 ret = wideType->data1;
265                 if ( wideType->data2 != 0 ) {
266                         ret += " ";
267                         ret += wideType->data2;
268                 }
269         }
270         return ret;
271 }
272
273
274
275 void JavaTabCodeGen::COND_TRANSLATE()
276 {
277         out << 
278                 "       _widec = " << GET_KEY() << ";\n"
279                 "       _keys = " << CO() << "[" << CS() << "]*2\n;"
280                 "       _klen = " << CL() << "[" << CS() << "];\n"
281                 "       if ( _klen > 0 ) {\n"
282                 "               int _lower = _keys\n;"
283                 "               int _mid;\n"
284                 "               int _upper = _keys + (_klen<<1) - 2;\n"
285                 "               while (true) {\n"
286                 "                       if ( _upper < _lower )\n"
287                 "                               break;\n"
288                 "\n"
289                 "                       _mid = _lower + (((_upper-_lower) >> 1) & ~1);\n"
290                 "                       if ( " << GET_WIDE_KEY() << " < " << CK() << "[_mid] )\n"
291                 "                               _upper = _mid - 2;\n"
292                 "                       else if ( " << GET_WIDE_KEY() << " > " << CK() << "[_mid+1] )\n"
293                 "                               _lower = _mid + 2;\n"
294                 "                       else {\n"
295                 "                               switch ( " << C() << "[" << CO() << "[" << CS() << "]"
296                                                         " + ((_mid - _keys)>>1)] ) {\n"
297                 ;
298
299         for ( CondSpaceList::Iter csi = condSpaceList; csi.lte(); csi++ ) {
300                 CondSpace *condSpace = csi;
301                 out << "        case " << condSpace->condSpaceId << ": {\n";
302                 out << TABS(2) << "_widec = " << KEY(condSpace->baseKey) << 
303                                 " + (" << GET_KEY() << " - " << KEY(keyOps->minKey) << ");\n";
304
305                 for ( CondSet::Iter csi = condSpace->condSet; csi.lte(); csi++ ) {
306                         out << TABS(2) << "if ( ";
307                         CONDITION( out, *csi );
308                         Size condValOffset = ((1 << csi.pos()) * keyOps->alphSize());
309                         out << " ) _widec += " << condValOffset << ";\n";
310                 }
311
312                 out << 
313                         "               break;\n"
314                         "       }\n";
315         }
316
317         out << 
318                 "                               }\n"
319                 "                               break;\n"
320                 "                       }\n"
321                 "               }\n"
322                 "       }\n"
323                 "\n";
324 }
325
326
327 void JavaTabCodeGen::LOCATE_TRANS()
328 {
329         out <<
330                 "       _match: do {\n"
331                 "       _keys = " << KO() << "[" << CS() << "]" << ";\n"
332                 "       _trans = " << IO() << "[" << CS() << "];\n"
333                 "       _klen = " << SL() << "[" << CS() << "];\n"
334                 "       if ( _klen > 0 ) {\n"
335                 "               int _lower = _keys;\n"
336                 "               int _mid;\n"
337                 "               int _upper = _keys + _klen - 1;\n"
338                 "               while (true) {\n"
339                 "                       if ( _upper < _lower )\n"
340                 "                               break;\n"
341                 "\n"
342                 "                       _mid = _lower + ((_upper-_lower) >> 1);\n"
343                 "                       if ( " << GET_WIDE_KEY() << " < " << K() << "[_mid] )\n"
344                 "                               _upper = _mid - 1;\n"
345                 "                       else if ( " << GET_WIDE_KEY() << " > " << K() << "[_mid] )\n"
346                 "                               _lower = _mid + 1;\n"
347                 "                       else {\n"
348                 "                               _trans += (_mid - _keys);\n"
349                 "                               break _match;\n"
350                 "                       }\n"
351                 "               }\n"
352                 "               _keys += _klen;\n"
353                 "               _trans += _klen;\n"
354                 "       }\n"
355                 "\n"
356                 "       _klen = " << RL() << "[" << CS() << "];\n"
357                 "       if ( _klen > 0 ) {\n"
358                 "               int _lower = _keys;\n"
359                 "               int _mid;\n"
360                 "               int _upper = _keys + (_klen<<1) - 2;\n"
361                 "               while (true) {\n"
362                 "                       if ( _upper < _lower )\n"
363                 "                               break;\n"
364                 "\n"
365                 "                       _mid = _lower + (((_upper-_lower) >> 1) & ~1);\n"
366                 "                       if ( " << GET_WIDE_KEY() << " < " << K() << "[_mid] )\n"
367                 "                               _upper = _mid - 2;\n"
368                 "                       else if ( " << GET_WIDE_KEY() << " > " << K() << "[_mid+1] )\n"
369                 "                               _lower = _mid + 2;\n"
370                 "                       else {\n"
371                 "                               _trans += ((_mid - _keys)>>1);\n"
372                 "                               break _match;\n"
373                 "                       }\n"
374                 "               }\n"
375                 "               _trans += _klen;\n"
376                 "       }\n"
377                 "       } while (false);\n"
378                 "\n";
379 }
380
381 /* Determine if we should use indicies or not. */
382 void JavaTabCodeGen::calcIndexSize()
383 {
384         int sizeWithInds = 0, sizeWithoutInds = 0;
385
386         /* Calculate cost of using with indicies. */
387         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
388                 int totalIndex = st->outSingle.length() + st->outRange.length() + 
389                                 (st->defTrans == 0 ? 0 : 1);
390                 sizeWithInds += arrayTypeSize(redFsm->maxIndex) * totalIndex;
391         }
392         sizeWithInds += arrayTypeSize(redFsm->maxState) * redFsm->transSet.length();
393         if ( redFsm->anyActions() )
394                 sizeWithInds += arrayTypeSize(redFsm->maxActionLoc) * redFsm->transSet.length();
395
396         /* Calculate the cost of not using indicies. */
397         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
398                 int totalIndex = st->outSingle.length() + st->outRange.length() + 
399                                 (st->defTrans == 0 ? 0 : 1);
400                 sizeWithoutInds += arrayTypeSize(redFsm->maxState) * totalIndex;
401                 if ( redFsm->anyActions() )
402                         sizeWithoutInds += arrayTypeSize(redFsm->maxActionLoc) * totalIndex;
403         }
404
405         /* If using indicies reduces the size, use them. */
406         useIndicies = sizeWithInds < sizeWithoutInds;
407 }
408
409 int JavaTabCodeGen::TO_STATE_ACTION( RedStateAp *state )
410 {
411         int act = 0;
412         if ( state->toStateAction != 0 )
413                 act = state->toStateAction->location+1;
414         return act;
415 }
416
417 int JavaTabCodeGen::FROM_STATE_ACTION( RedStateAp *state )
418 {
419         int act = 0;
420         if ( state->fromStateAction != 0 )
421                 act = state->fromStateAction->location+1;
422         return act;
423 }
424
425 int JavaTabCodeGen::EOF_ACTION( RedStateAp *state )
426 {
427         int act = 0;
428         if ( state->eofAction != 0 )
429                 act = state->eofAction->location+1;
430         return act;
431 }
432
433
434 int JavaTabCodeGen::TRANS_ACTION( RedTransAp *trans )
435 {
436         /* If there are actions, emit them. Otherwise emit zero. */
437         int act = 0;
438         if ( trans->action != 0 )
439                 act = trans->action->location+1;
440         return act;
441 }
442
443 std::ostream &JavaTabCodeGen::TO_STATE_ACTION_SWITCH()
444 {
445         /* Walk the list of functions, printing the cases. */
446         for ( ActionList::Iter act = actionList; act.lte(); act++ ) {
447                 /* Write out referenced actions. */
448                 if ( act->numToStateRefs > 0 ) {
449                         /* Write the case label, the action and the case break. */
450                         out << "\tcase " << act->actionId << ":\n";
451                         ACTION( out, act, 0, false );
452                         out << "\tbreak;\n";
453                 }
454         }
455
456         genLineDirective( out );
457         return out;
458 }
459
460 std::ostream &JavaTabCodeGen::FROM_STATE_ACTION_SWITCH()
461 {
462         /* Walk the list of functions, printing the cases. */
463         for ( ActionList::Iter act = actionList; act.lte(); act++ ) {
464                 /* Write out referenced actions. */
465                 if ( act->numFromStateRefs > 0 ) {
466                         /* Write the case label, the action and the case break. */
467                         out << "\tcase " << act->actionId << ":\n";
468                         ACTION( out, act, 0, false );
469                         out << "\tbreak;\n";
470                 }
471         }
472
473         genLineDirective( out );
474         return out;
475 }
476
477 std::ostream &JavaTabCodeGen::EOF_ACTION_SWITCH()
478 {
479         /* Walk the list of functions, printing the cases. */
480         for ( ActionList::Iter act = actionList; act.lte(); act++ ) {
481                 /* Write out referenced actions. */
482                 if ( act->numEofRefs > 0 ) {
483                         /* Write the case label, the action and the case break. */
484                         out << "\tcase " << act->actionId << ":\n";
485                         ACTION( out, act, 0, true );
486                         out << "\tbreak;\n";
487                 }
488         }
489
490         genLineDirective( out );
491         return out;
492 }
493
494
495 std::ostream &JavaTabCodeGen::ACTION_SWITCH()
496 {
497         /* Walk the list of functions, printing the cases. */
498         for ( ActionList::Iter act = actionList; act.lte(); act++ ) {
499                 /* Write out referenced actions. */
500                 if ( act->numTransRefs > 0 ) {
501                         /* Write the case label, the action and the case break. */
502                         out << "\tcase " << act->actionId << ":\n";
503                         ACTION( out, act, 0, false );
504                         out << "\tbreak;\n";
505                 }
506         }
507
508         genLineDirective( out );
509         return out;
510 }
511
512 std::ostream &JavaTabCodeGen::COND_OFFSETS()
513 {
514         int curKeyOffset = 0;
515         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
516                 /* Write the key offset. */
517                 ARRAY_ITEM( INT(curKeyOffset), st.last() );
518
519                 /* Move the key offset ahead. */
520                 curKeyOffset += st->stateCondList.length();
521         }
522         return out;
523 }
524
525 std::ostream &JavaTabCodeGen::KEY_OFFSETS()
526 {
527         int curKeyOffset = 0;
528         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
529                 /* Write the key offset. */
530                 ARRAY_ITEM( INT(curKeyOffset), st.last() );
531
532                 /* Move the key offset ahead. */
533                 curKeyOffset += st->outSingle.length() + st->outRange.length()*2;
534         }
535         return out;
536 }
537
538
539 std::ostream &JavaTabCodeGen::INDEX_OFFSETS()
540 {
541         int curIndOffset = 0;
542         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
543                 /* Write the index offset. */
544                 ARRAY_ITEM( INT(curIndOffset), st.last() );
545
546                 /* Move the index offset ahead. */
547                 curIndOffset += st->outSingle.length() + st->outRange.length();
548                 if ( st->defTrans != 0 )
549                         curIndOffset += 1;
550         }
551         return out;
552 }
553
554 std::ostream &JavaTabCodeGen::COND_LENS()
555 {
556         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
557                 /* Write singles length. */
558                 ARRAY_ITEM( INT(st->stateCondList.length()), st.last() );
559         }
560         return out;
561 }
562
563
564 std::ostream &JavaTabCodeGen::SINGLE_LENS()
565 {
566         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
567                 /* Write singles length. */
568                 ARRAY_ITEM( INT(st->outSingle.length()), st.last() );
569         }
570         return out;
571 }
572
573 std::ostream &JavaTabCodeGen::RANGE_LENS()
574 {
575         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
576                 /* Emit length of range index. */
577                 ARRAY_ITEM( INT(st->outRange.length()), st.last() );
578         }
579         return out;
580 }
581
582 std::ostream &JavaTabCodeGen::TO_STATE_ACTIONS()
583 {
584         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
585                 /* Write any eof action. */
586                 ARRAY_ITEM( INT(TO_STATE_ACTION(st)), st.last() );
587         }
588         return out;
589 }
590
591 std::ostream &JavaTabCodeGen::FROM_STATE_ACTIONS()
592 {
593         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
594                 /* Write any eof action. */
595                 ARRAY_ITEM( INT(FROM_STATE_ACTION(st)), st.last() );
596         }
597         return out;
598 }
599
600 std::ostream &JavaTabCodeGen::EOF_ACTIONS()
601 {
602         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
603                 /* Write any eof action. */
604                 ARRAY_ITEM( INT(EOF_ACTION(st)), st.last() );
605         }
606         return out;
607 }
608
609 std::ostream &JavaTabCodeGen::EOF_TRANS()
610 {
611         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
612                 /* Write any eof action. */
613                 long trans = 0;
614                 if ( st->eofTrans != 0 )
615                         trans = st->eofTrans->id+1;
616
617                 /* Write any eof action. */
618                 ARRAY_ITEM( INT(trans), st.last() );
619         }
620         return out;
621 }
622
623
624 std::ostream &JavaTabCodeGen::COND_KEYS()
625 {
626         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
627                 /* Loop the state's transitions. */
628                 for ( StateCondList::Iter sc = st->stateCondList; sc.lte(); sc++ ) {
629                         /* Lower key. */
630                         ARRAY_ITEM( KEY( sc->lowKey ), false );
631                         ARRAY_ITEM( KEY( sc->highKey ), false );
632                 }
633         }
634
635         /* Output one last number so we don't have to figure out when the last
636          * entry is and avoid writing a comma. */
637         ARRAY_ITEM( INT(0), true );
638         return out;
639 }
640
641 std::ostream &JavaTabCodeGen::COND_SPACES()
642 {
643         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
644                 /* Loop the state's transitions. */
645                 for ( StateCondList::Iter sc = st->stateCondList; sc.lte(); sc++ ) {
646                         /* Cond Space id. */
647                         ARRAY_ITEM( KEY( sc->condSpace->condSpaceId ), false );
648                 }
649         }
650
651         /* Output one last number so we don't have to figure out when the last
652          * entry is and avoid writing a comma. */
653         ARRAY_ITEM( INT(0), true );
654         return out;
655 }
656
657 std::ostream &JavaTabCodeGen::KEYS()
658 {
659         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
660                 /* Loop the singles. */
661                 for ( RedTransList::Iter stel = st->outSingle; stel.lte(); stel++ ) {
662                         ARRAY_ITEM( KEY( stel->lowKey ), false );
663                 }
664
665                 /* Loop the state's transitions. */
666                 for ( RedTransList::Iter rtel = st->outRange; rtel.lte(); rtel++ ) {
667                         /* Lower key. */
668                         ARRAY_ITEM( KEY( rtel->lowKey ), false );
669
670                         /* Upper key. */
671                         ARRAY_ITEM( KEY( rtel->highKey ), false );
672                 }
673         }
674
675         /* Output one last number so we don't have to figure out when the last
676          * entry is and avoid writing a comma. */
677         ARRAY_ITEM( INT(0), true );
678         return out;
679 }
680
681 std::ostream &JavaTabCodeGen::INDICIES()
682 {
683         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
684                 /* Walk the singles. */
685                 for ( RedTransList::Iter stel = st->outSingle; stel.lte(); stel++ ) {
686                         ARRAY_ITEM( KEY( stel->value->id ), false );
687                 }
688
689                 /* Walk the ranges. */
690                 for ( RedTransList::Iter rtel = st->outRange; rtel.lte(); rtel++ ) {
691                         ARRAY_ITEM( KEY( rtel->value->id ), false );
692                 }
693
694                 /* The state's default index goes next. */
695                 if ( st->defTrans != 0 ) {
696                         ARRAY_ITEM( KEY( st->defTrans->id ), false );
697                 }
698         }
699
700         /* Output one last number so we don't have to figure out when the last
701          * entry is and avoid writing a comma. */
702         ARRAY_ITEM( INT(0), true );
703         return out;
704 }
705
706 std::ostream &JavaTabCodeGen::TRANS_TARGS()
707 {
708         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
709                 /* Walk the singles. */
710                 for ( RedTransList::Iter stel = st->outSingle; stel.lte(); stel++ ) {
711                         RedTransAp *trans = stel->value;
712                         ARRAY_ITEM( KEY( trans->targ->id ), false );
713                 }
714
715                 /* Walk the ranges. */
716                 for ( RedTransList::Iter rtel = st->outRange; rtel.lte(); rtel++ ) {
717                         RedTransAp *trans = rtel->value;
718                         ARRAY_ITEM( KEY( trans->targ->id ), false );
719                 }
720
721                 /* The state's default target state. */
722                 if ( st->defTrans != 0 ) {
723                         RedTransAp *trans = st->defTrans;
724                         ARRAY_ITEM( KEY( trans->targ->id ), false );
725                 }
726         }
727
728         /* Output one last number so we don't have to figure out when the last
729          * entry is and avoid writing a comma. */
730         ARRAY_ITEM( INT(0), true );
731         return out;
732 }
733
734
735 std::ostream &JavaTabCodeGen::TRANS_ACTIONS()
736 {
737         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
738                 /* Walk the singles. */
739                 for ( RedTransList::Iter stel = st->outSingle; stel.lte(); stel++ ) {
740                         RedTransAp *trans = stel->value;
741                         ARRAY_ITEM( INT(TRANS_ACTION( trans )), false );
742                 }
743
744                 /* Walk the ranges. */
745                 for ( RedTransList::Iter rtel = st->outRange; rtel.lte(); rtel++ ) {
746                         RedTransAp *trans = rtel->value;
747                         ARRAY_ITEM( INT(TRANS_ACTION( trans )), false );
748                 }
749
750                 /* The state's default index goes next. */
751                 if ( st->defTrans != 0 ) {
752                         RedTransAp *trans = st->defTrans;
753                         ARRAY_ITEM( INT(TRANS_ACTION( trans )), false );
754                 }
755         }
756
757         /* Output one last number so we don't have to figure out when the last
758          * entry is and avoid writing a comma. */
759         ARRAY_ITEM( INT(0), true );
760         return out;
761 }
762
763 std::ostream &JavaTabCodeGen::TRANS_TARGS_WI()
764 {
765         /* Transitions must be written ordered by their id. */
766         RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()];
767         for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ )
768                 transPtrs[trans->id] = trans;
769
770         /* Keep a count of the num of items in the array written. */
771         for ( int t = 0; t < redFsm->transSet.length(); t++ ) {
772                 /* Write out the target state. */
773                 RedTransAp *trans = transPtrs[t];
774                 ARRAY_ITEM( INT(trans->targ->id), ( t >= redFsm->transSet.length()-1 ) );
775         }
776         delete[] transPtrs;
777         return out;
778 }
779
780
781 std::ostream &JavaTabCodeGen::TRANS_ACTIONS_WI()
782 {
783         /* Transitions must be written ordered by their id. */
784         RedTransAp **transPtrs = new RedTransAp*[redFsm->transSet.length()];
785         for ( TransApSet::Iter trans = redFsm->transSet; trans.lte(); trans++ )
786                 transPtrs[trans->id] = trans;
787
788         /* Keep a count of the num of items in the array written. */
789         for ( int t = 0; t < redFsm->transSet.length(); t++ ) {
790                 /* Write the function for the transition. */
791                 RedTransAp *trans = transPtrs[t];
792                 ARRAY_ITEM( INT(TRANS_ACTION( trans )), ( t >= redFsm->transSet.length()-1 ) );
793         }
794         delete[] transPtrs;
795         return out;
796 }
797
798 void JavaTabCodeGen::writeExports()
799 {
800         if ( exportList.length() > 0 ) {
801                 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
802                         STATIC_VAR( ALPH_TYPE(), DATA_PREFIX() + "ex_" + ex->name ) 
803                                         << " = " << KEY(ex->key) << ";\n";
804                 }
805                 out << "\n";
806         }
807 }
808
809 void JavaTabCodeGen::writeData()
810 {
811         /* If there are any transtion functions then output the array. If there
812          * are none, don't bother emitting an empty array that won't be used. */
813         if ( redFsm->anyActions() ) {
814                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActArrItem), A() );
815                 ACTIONS_ARRAY();
816                 CLOSE_ARRAY() <<
817                 "\n";
818         }
819
820         if ( redFsm->anyConditions() ) {
821                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCondOffset), CO() );
822                 COND_OFFSETS();
823                 CLOSE_ARRAY() <<
824                 "\n";
825
826                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCondLen), CL() );
827                 COND_LENS();
828                 CLOSE_ARRAY() <<
829                 "\n";
830
831                 OPEN_ARRAY( WIDE_ALPH_TYPE(), CK() );
832                 COND_KEYS();
833                 CLOSE_ARRAY() <<
834                 "\n";
835
836                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCondSpaceId), C() );
837                 COND_SPACES();
838                 CLOSE_ARRAY() <<
839                 "\n";
840         }
841
842         OPEN_ARRAY( ARRAY_TYPE(redFsm->maxKeyOffset), KO() );
843         KEY_OFFSETS();
844         CLOSE_ARRAY() <<
845         "\n";
846
847         OPEN_ARRAY( WIDE_ALPH_TYPE(), K() );
848         KEYS();
849         CLOSE_ARRAY() <<
850         "\n";
851
852         OPEN_ARRAY( ARRAY_TYPE(redFsm->maxSingleLen), SL() );
853         SINGLE_LENS();
854         CLOSE_ARRAY() <<
855         "\n";
856
857         OPEN_ARRAY( ARRAY_TYPE(redFsm->maxRangeLen), RL() );
858         RANGE_LENS();
859         CLOSE_ARRAY() <<
860         "\n";
861
862         OPEN_ARRAY( ARRAY_TYPE(redFsm->maxIndexOffset), IO() );
863         INDEX_OFFSETS();
864         CLOSE_ARRAY() <<
865         "\n";
866
867         if ( useIndicies ) {
868                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxIndex), I() );
869                 INDICIES();
870                 CLOSE_ARRAY() <<
871                 "\n";
872
873                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxState), TT() );
874                 TRANS_TARGS_WI();
875                 CLOSE_ARRAY() <<
876                 "\n";
877
878                 if ( redFsm->anyActions() ) {
879                         OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), TA() );
880                         TRANS_ACTIONS_WI();
881                         CLOSE_ARRAY() <<
882                         "\n";
883                 }
884         }
885         else {
886                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxState), TT() );
887                 TRANS_TARGS();
888                 CLOSE_ARRAY() <<
889                 "\n";
890
891                 if ( redFsm->anyActions() ) {
892                         OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), TA() );
893                         TRANS_ACTIONS();
894                         CLOSE_ARRAY() <<
895                         "\n";
896                 }
897         }
898
899         if ( redFsm->anyToStateActions() ) {
900                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), TSA() );
901                 TO_STATE_ACTIONS();
902                 CLOSE_ARRAY() <<
903                 "\n";
904         }
905
906         if ( redFsm->anyFromStateActions() ) {
907                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), FSA() );
908                 FROM_STATE_ACTIONS();
909                 CLOSE_ARRAY() <<
910                 "\n";
911         }
912
913         if ( redFsm->anyEofActions() ) {
914                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), EA() );
915                 EOF_ACTIONS();
916                 CLOSE_ARRAY() <<
917                 "\n";
918         }
919
920         if ( redFsm->anyEofTrans() ) {
921                 OPEN_ARRAY( ARRAY_TYPE(redFsm->maxIndex+1), ET() );
922                 EOF_TRANS();
923                 CLOSE_ARRAY() <<
924                 "\n";
925         }
926
927         if ( redFsm->startState != 0 )
928                 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
929
930         if ( writeFirstFinal )
931                 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
932
933         if ( writeErr )
934                 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
935         
936         out << "\n";
937
938         if ( entryPointNames.length() > 0 ) {
939                 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
940                         STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) << 
941                                         " = " << entryPointIds[en.pos()] << ";\n";
942                 }
943                 out << "\n";
944         }
945 }
946
947 void JavaTabCodeGen::writeExec()
948 {
949         out <<
950                 "       {\n"
951                 "       int _klen";
952
953         if ( redFsm->anyRegCurStateRef() )
954                 out << ", _ps";
955
956         out << 
957                 ";\n"
958                 "       int _trans = 0;\n";
959
960         if ( redFsm->anyConditions() )
961                 out << "        int _widec;\n";
962
963         if ( redFsm->anyToStateActions() || redFsm->anyRegActions() || 
964                         redFsm->anyFromStateActions() )
965         {
966                 out << 
967                         "       int _acts;\n"
968                         "       int _nacts;\n";
969         }
970
971         out <<
972                 "       int _keys;\n"
973                 "       int _goto_targ = 0;\n"
974                 "\n";
975         
976         out <<
977                 "       _goto: while (true) {\n"
978                 "       switch ( _goto_targ ) {\n"
979                 "       case 0:\n";
980
981         if ( hasEnd ) {
982                 out << 
983                         "       if ( " << P() << " == " << PE() << " ) {\n"
984                         "               _goto_targ = " << _test_eof << ";\n"
985                         "               continue _goto;\n"
986                         "       }\n";
987         }
988
989         if ( redFsm->errState != 0 ) {
990                 out << 
991                         "       if ( " << CS() << " == " << redFsm->errState->id << " ) {\n"
992                         "               _goto_targ = " << _out << ";\n"
993                         "               continue _goto;\n"
994                         "       }\n";
995         }
996
997         out << "case " << _resume << ":\n"; 
998
999         if ( redFsm->anyFromStateActions() ) {
1000                 out <<
1001                         "       _acts = " << FSA() << "[" << CS() << "]" << ";\n"
1002                         "       _nacts = " << CAST("int") << " " << A() << "[_acts++];\n"
1003                         "       while ( _nacts-- > 0 ) {\n"
1004                         "               switch ( " << A() << "[_acts++] ) {\n";
1005                         FROM_STATE_ACTION_SWITCH() <<
1006                         "               }\n"
1007                         "       }\n"
1008                         "\n";
1009         }
1010
1011         if ( redFsm->anyConditions() )
1012                 COND_TRANSLATE();
1013
1014         LOCATE_TRANS();
1015
1016         if ( useIndicies )
1017                 out << "        _trans = " << I() << "[_trans];\n";
1018         
1019         if ( redFsm->anyEofTrans() )
1020                 out << "case " << _eof_trans << ":\n";
1021
1022         if ( redFsm->anyRegCurStateRef() )
1023                 out << "        _ps = " << CS() << ";\n";
1024
1025         out <<
1026                 "       " << CS() << " = " << TT() << "[_trans];\n"
1027                 "\n";
1028
1029         if ( redFsm->anyRegActions() ) {
1030                 out <<
1031                         "       if ( " << TA() << "[_trans] != 0 ) {\n"
1032                         "               _acts = " <<  TA() << "[_trans]" << ";\n"
1033                         "               _nacts = " << CAST("int") << " " <<  A() << "[_acts++];\n"
1034                         "               while ( _nacts-- > 0 )\n        {\n"
1035                         "                       switch ( " << A() << "[_acts++] )\n"
1036                         "                       {\n";
1037                         ACTION_SWITCH() <<
1038                         "                       }\n"
1039                         "               }\n"
1040                         "       }\n"
1041                         "\n";
1042         }
1043
1044         out << "case " << _again << ":\n";
1045
1046         if ( redFsm->anyToStateActions() ) {
1047                 out <<
1048                         "       _acts = " << TSA() << "[" << CS() << "]" << ";\n"
1049                         "       _nacts = " << CAST("int") << " " << A() << "[_acts++];\n"
1050                         "       while ( _nacts-- > 0 ) {\n"
1051                         "               switch ( " << A() << "[_acts++] ) {\n";
1052                         TO_STATE_ACTION_SWITCH() <<
1053                         "               }\n"
1054                         "       }\n"
1055                         "\n";
1056         }
1057
1058         if ( redFsm->errState != 0 ) {
1059                 out << 
1060                         "       if ( " << CS() << " == " << redFsm->errState->id << " ) {\n"
1061                         "               _goto_targ = " << _out << ";\n"
1062                         "               continue _goto;\n"
1063                         "       }\n";
1064         }
1065
1066         if ( hasEnd ) {
1067                 out << 
1068                         "       if ( ++" << P() << " != " << PE() << " ) {\n"
1069                         "               _goto_targ = " << _resume << ";\n"
1070                         "               continue _goto;\n"
1071                         "       }\n";
1072         }
1073         else {
1074                 out << 
1075                         "       " << P() << " += 1;\n"
1076                         "       _goto_targ = " << _resume << ";\n"
1077                         "       continue _goto;\n";
1078         }
1079
1080         out << "case " << _test_eof << ":\n"; 
1081
1082         if ( redFsm->anyEofTrans() || redFsm->anyEofActions() ) {
1083                 out <<
1084                         "       if ( " << P() << " == " << EOFV() << " )\n"
1085                         "       {\n";
1086
1087                 if ( redFsm->anyEofTrans() ) {
1088                         out <<
1089                                 "       if ( " << ET() << "[" << CS() << "] > 0 ) {\n"
1090                                 "               _trans = " << ET() << "[" << CS() << "] - 1;\n"
1091                                 "               _goto_targ = " << _eof_trans << ";\n"
1092                                 "               continue _goto;\n"
1093                                 "       }\n";
1094                 }
1095
1096                 if ( redFsm->anyEofActions() ) {
1097                         out <<
1098                                 "       int __acts = " << EA() << "[" << CS() << "]" << ";\n"
1099                                 "       int __nacts = " << CAST("int") << " " << A() << "[__acts++];\n"
1100                                 "       while ( __nacts-- > 0 ) {\n"
1101                                 "               switch ( " << A() << "[__acts++] ) {\n";
1102                                 EOF_ACTION_SWITCH() <<
1103                                 "               }\n"
1104                                 "       }\n";
1105                 }
1106
1107                 out <<
1108                         "       }\n"
1109                         "\n";
1110         }
1111
1112         out << "case " << _out << ":\n"; 
1113
1114         /* The switch and goto loop. */
1115         out << "        }\n";
1116         out << "        break; }\n";
1117
1118         /* The execute block. */
1119         out << "        }\n";
1120 }
1121
1122 std::ostream &JavaTabCodeGen::OPEN_ARRAY( string type, string name )
1123 {
1124         array_type = type;
1125         array_name = name;
1126         item_count = 0;
1127         div_count = 1;
1128
1129         out <<  "private static " << type << "[] init_" << name << "_0()\n"
1130                 "{\n\t"
1131                 "return new " << type << " [] {\n\t";
1132         return out;
1133 }
1134
1135 std::ostream &JavaTabCodeGen::ARRAY_ITEM( string item, bool last )
1136 {
1137         item_count++;
1138
1139         out << setw(5) << setiosflags(ios::right) << item;
1140         
1141         if ( !last ) {
1142                 if ( item_count % SAIIC == 0 ) {
1143                         out << "\n\t};\n};\n"
1144                                 "private static "<< array_type << "[] init_" << 
1145                                 array_name << "_" << div_count << "()\n"
1146                                 "{\n\t"
1147                                 "return new " << array_type << " [] {\n\t";
1148                         div_count++;
1149                 } else if (item_count % IALL == 0) { 
1150                         out << ",\n\t";
1151                 } else {
1152                         out << ",";
1153                 }
1154         }
1155         return out;
1156 }
1157
1158 std::ostream &JavaTabCodeGen::CLOSE_ARRAY()
1159 {
1160         out << "\n\t};\n}\n\n";
1161
1162         if (item_count < SAIIC) {
1163                 out << "private static final " << array_type << " " << array_name << 
1164                         "[] = init_" << array_name << "_0();\n\n";
1165         } else {
1166                 out << "private static final " << array_type << " [] combine_" << array_name
1167                         << "() {\n\t"
1168                         << array_type << " [] combined = new " << array_type << 
1169                         " [ " << item_count << " ];\n\t";
1170                 int block = 0;
1171                 int full_blocks = item_count / SAIIC;
1172                 for (;block < full_blocks; ++block) {
1173                         out << "System.arraycopy ( init_" << array_name << "_" << block << 
1174                                 "(), 0, combined, " << SAIIC * block << ", " << SAIIC << " );\n\t";
1175                 }
1176                 if ( (item_count % SAIIC) > 0 ) {
1177                         out << "System.arraycopy ( init_" << array_name << "_" << block << 
1178                                 "(), 0, combined, " << SAIIC * block << ", " << 
1179                                 (item_count % SAIIC) << " );\n\t";
1180                 }
1181                 out << "return combined;\n}\n";
1182                 out << "private static final " << array_type << " [] " << array_name << 
1183                         " = combine_" << array_name << "();";
1184         }
1185         return out;
1186 }
1187
1188
1189 std::ostream &JavaTabCodeGen::STATIC_VAR( string type, string name )
1190 {
1191         out << "static final " << type << " " << name;
1192         return out;
1193 }
1194
1195 string JavaTabCodeGen::ARR_OFF( string ptr, string offset )
1196 {
1197         return ptr + " + " + offset;
1198 }
1199
1200 string JavaTabCodeGen::CAST( string type )
1201 {
1202         return "(" + type + ")";
1203 }
1204
1205 string JavaTabCodeGen::NULL_ITEM()
1206 {
1207         /* In java we use integers instead of pointers. */
1208         return "-1";
1209 }
1210
1211 string JavaTabCodeGen::GET_KEY()
1212 {
1213         ostringstream ret;
1214         if ( getKeyExpr != 0 ) { 
1215                 /* Emit the user supplied method of retrieving the key. */
1216                 ret << "(";
1217                 INLINE_LIST( ret, getKeyExpr, 0, false );
1218                 ret << ")";
1219         }
1220         else {
1221                 /* Expression for retrieving the key, use simple dereference. */
1222                 ret << DATA() << "[" << P() << "]";
1223         }
1224         return ret.str();
1225 }
1226
1227 string JavaTabCodeGen::CTRL_FLOW()
1228 {
1229         return "if (true) ";
1230 }
1231
1232 unsigned int JavaTabCodeGen::arrayTypeSize( unsigned long maxVal )
1233 {
1234         long long maxValLL = (long long) maxVal;
1235         HostType *arrayType = keyOps->typeSubsumes( maxValLL );
1236         assert( arrayType != 0 );
1237         return arrayType->size;
1238 }
1239
1240 string JavaTabCodeGen::ARRAY_TYPE( unsigned long maxVal )
1241 {
1242         long long maxValLL = (long long) maxVal;
1243         HostType *arrayType = keyOps->typeSubsumes( maxValLL );
1244         assert( arrayType != 0 );
1245
1246         string ret = arrayType->data1;
1247         if ( arrayType->data2 != 0 ) {
1248                 ret += " ";
1249                 ret += arrayType->data2;
1250         }
1251         return ret;
1252 }
1253
1254
1255 /* Write out the fsm name. */
1256 string JavaTabCodeGen::FSM_NAME()
1257 {
1258         return fsmName;
1259 }
1260
1261 /* Emit the offset of the start state as a decimal integer. */
1262 string JavaTabCodeGen::START_STATE_ID()
1263 {
1264         ostringstream ret;
1265         ret << redFsm->startState->id;
1266         return ret.str();
1267 };
1268
1269 /* Write out the array of actions. */
1270 std::ostream &JavaTabCodeGen::ACTIONS_ARRAY()
1271 {
1272         ARRAY_ITEM( INT(0), false );
1273         for ( ActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) {
1274                 /* Write out the length, which will never be the last character. */
1275                 ARRAY_ITEM( INT(act->key.length()), false );
1276
1277                 for ( ActionTable::Iter item = act->key; item.lte(); item++ )
1278                         ARRAY_ITEM( INT(item->value->actionId), (act.last() && item.last()) );
1279         }
1280         return out;
1281 }
1282
1283
1284 string JavaTabCodeGen::ACCESS()
1285 {
1286         ostringstream ret;
1287         if ( accessExpr != 0 )
1288                 INLINE_LIST( ret, accessExpr, 0, false );
1289         return ret.str();
1290 }
1291
1292 string JavaTabCodeGen::P()
1293
1294         ostringstream ret;
1295         if ( pExpr == 0 )
1296                 ret << "p";
1297         else {
1298                 ret << "(";
1299                 INLINE_LIST( ret, pExpr, 0, false );
1300                 ret << ")";
1301         }
1302         return ret.str();
1303 }
1304
1305 string JavaTabCodeGen::PE()
1306 {
1307         ostringstream ret;
1308         if ( peExpr == 0 )
1309                 ret << "pe";
1310         else {
1311                 ret << "(";
1312                 INLINE_LIST( ret, peExpr, 0, false );
1313                 ret << ")";
1314         }
1315         return ret.str();
1316 }
1317
1318 string JavaTabCodeGen::EOFV()
1319 {
1320         ostringstream ret;
1321         if ( eofExpr == 0 )
1322                 ret << "eof";
1323         else {
1324                 ret << "(";
1325                 INLINE_LIST( ret, eofExpr, 0, false );
1326                 ret << ")";
1327         }
1328         return ret.str();
1329 }
1330
1331 string JavaTabCodeGen::CS()
1332 {
1333         ostringstream ret;
1334         if ( csExpr == 0 )
1335                 ret << ACCESS() << "cs";
1336         else {
1337                 /* Emit the user supplied method of retrieving the key. */
1338                 ret << "(";
1339                 INLINE_LIST( ret, csExpr, 0, false );
1340                 ret << ")";
1341         }
1342         return ret.str();
1343 }
1344
1345 string JavaTabCodeGen::TOP()
1346 {
1347         ostringstream ret;
1348         if ( topExpr == 0 )
1349                 ret << ACCESS() + "top";
1350         else {
1351                 ret << "(";
1352                 INLINE_LIST( ret, topExpr, 0, false );
1353                 ret << ")";
1354         }
1355         return ret.str();
1356 }
1357
1358 string JavaTabCodeGen::STACK()
1359 {
1360         ostringstream ret;
1361         if ( stackExpr == 0 )
1362                 ret << ACCESS() + "stack";
1363         else {
1364                 ret << "(";
1365                 INLINE_LIST( ret, stackExpr, 0, false );
1366                 ret << ")";
1367         }
1368         return ret.str();
1369 }
1370
1371 string JavaTabCodeGen::ACT()
1372 {
1373         ostringstream ret;
1374         if ( actExpr == 0 )
1375                 ret << ACCESS() + "act";
1376         else {
1377                 ret << "(";
1378                 INLINE_LIST( ret, actExpr, 0, false );
1379                 ret << ")";
1380         }
1381         return ret.str();
1382 }
1383
1384 string JavaTabCodeGen::TOKSTART()
1385 {
1386         ostringstream ret;
1387         if ( tokstartExpr == 0 )
1388                 ret << ACCESS() + "ts";
1389         else {
1390                 ret << "(";
1391                 INLINE_LIST( ret, tokstartExpr, 0, false );
1392                 ret << ")";
1393         }
1394         return ret.str();
1395 }
1396
1397 string JavaTabCodeGen::TOKEND()
1398 {
1399         ostringstream ret;
1400         if ( tokendExpr == 0 )
1401                 ret << ACCESS() + "te";
1402         else {
1403                 ret << "(";
1404                 INLINE_LIST( ret, tokendExpr, 0, false );
1405                 ret << ")";
1406         }
1407         return ret.str();
1408 }
1409
1410 string JavaTabCodeGen::DATA()
1411 {
1412         ostringstream ret;
1413         if ( dataExpr == 0 )
1414                 ret << ACCESS() + "data";
1415         else {
1416                 ret << "(";
1417                 INLINE_LIST( ret, dataExpr, 0, false );
1418                 ret << ")";
1419         }
1420         return ret.str();
1421 }
1422
1423
1424 string JavaTabCodeGen::GET_WIDE_KEY()
1425 {
1426         if ( redFsm->anyConditions() ) 
1427                 return "_widec";
1428         else
1429                 return GET_KEY();
1430 }
1431
1432 string JavaTabCodeGen::GET_WIDE_KEY( RedStateAp *state )
1433 {
1434         if ( state->stateCondList.length() > 0 )
1435                 return "_widec";
1436         else
1437                 return GET_KEY();
1438 }
1439
1440 /* Write out level number of tabs. Makes the nested binary search nice
1441  * looking. */
1442 string JavaTabCodeGen::TABS( int level )
1443 {
1444         string result;
1445         while ( level-- > 0 )
1446                 result += "\t";
1447         return result;
1448 }
1449
1450 string JavaTabCodeGen::KEY( Key key )
1451 {
1452         ostringstream ret;
1453         if ( keyOps->isSigned || !hostLang->explicitUnsigned )
1454                 ret << key.getVal();
1455         else
1456                 ret << (unsigned long) key.getVal();
1457         return ret.str();
1458 }
1459
1460 string JavaTabCodeGen::INT( int i )
1461 {
1462         ostringstream ret;
1463         ret << i;
1464         return ret.str();
1465 }
1466
1467 void JavaTabCodeGen::LM_SWITCH( ostream &ret, InlineItem *item, 
1468                 int targState, int inFinish )
1469 {
1470         ret << 
1471                 "       switch( " << ACT() << " ) {\n";
1472
1473         for ( InlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
1474                 /* Write the case label, the action and the case break. */
1475                 ret << "        case " << lma->lmId << ":\n";
1476
1477                 /* Write the block and close it off. */
1478                 ret << "        {";
1479                 INLINE_LIST( ret, lma->children, targState, inFinish );
1480                 ret << "}\n";
1481
1482                 ret << "        break;\n";
1483         }
1484         /* Default required for D code. */
1485         ret << 
1486                 "       default: break;\n"
1487                 "       }\n"
1488                 "\t";
1489 }
1490
1491 void JavaTabCodeGen::SET_ACT( ostream &ret, InlineItem *item )
1492 {
1493         ret << ACT() << " = " << item->lmId << ";";
1494 }
1495
1496 void JavaTabCodeGen::SET_TOKEND( ostream &ret, InlineItem *item )
1497 {
1498         /* The tokend action sets tokend. */
1499         ret << TOKEND() << " = " << P();
1500         if ( item->offset != 0 ) 
1501                 out << "+" << item->offset;
1502         out << ";";
1503 }
1504
1505 void JavaTabCodeGen::GET_TOKEND( ostream &ret, InlineItem *item )
1506 {
1507         ret << TOKEND();
1508 }
1509
1510 void JavaTabCodeGen::INIT_TOKSTART( ostream &ret, InlineItem *item )
1511 {
1512         ret << TOKSTART() << " = " << NULL_ITEM() << ";";
1513 }
1514
1515 void JavaTabCodeGen::INIT_ACT( ostream &ret, InlineItem *item )
1516 {
1517         ret << ACT() << " = 0;";
1518 }
1519
1520 void JavaTabCodeGen::SET_TOKSTART( ostream &ret, InlineItem *item )
1521 {
1522         ret << TOKSTART() << " = " << P() << ";";
1523 }
1524
1525 void JavaTabCodeGen::SUB_ACTION( ostream &ret, InlineItem *item, 
1526                 int targState, bool inFinish )
1527 {
1528         if ( item->children->length() > 0 ) {
1529                 /* Write the block and close it off. */
1530                 ret << "{";
1531                 INLINE_LIST( ret, item->children, targState, inFinish );
1532                 ret << "}";
1533         }
1534 }
1535
1536 void JavaTabCodeGen::ACTION( ostream &ret, Action *action, int targState, bool inFinish )
1537 {
1538         /* Write the preprocessor line info for going into the source file. */
1539         lineDirective( ret, sourceFileName, action->loc.line );
1540
1541         /* Write the block and close it off. */
1542         ret << "\t{";
1543         INLINE_LIST( ret, action->inlineList, targState, inFinish );
1544         ret << "}\n";
1545 }
1546
1547 void JavaTabCodeGen::CONDITION( ostream &ret, Action *condition )
1548 {
1549         ret << "\n";
1550         lineDirective( ret, sourceFileName, condition->loc.line );
1551         INLINE_LIST( ret, condition->inlineList, 0, false );
1552 }
1553
1554 string JavaTabCodeGen::ERROR_STATE()
1555 {
1556         ostringstream ret;
1557         if ( redFsm->errState != 0 )
1558                 ret << redFsm->errState->id;
1559         else
1560                 ret << "-1";
1561         return ret.str();
1562 }
1563
1564 string JavaTabCodeGen::FIRST_FINAL_STATE()
1565 {
1566         ostringstream ret;
1567         if ( redFsm->firstFinState != 0 )
1568                 ret << redFsm->firstFinState->id;
1569         else
1570                 ret << redFsm->nextStateId;
1571         return ret.str();
1572 }
1573
1574 void JavaTabCodeGen::writeInit()
1575 {
1576         out << "        {\n";
1577
1578         if ( writeCS )
1579                 out << "\t" << CS() << " = " << START() << ";\n";
1580         
1581         /* If there are any calls, then the stack top needs initialization. */
1582         if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
1583                 out << "\t" << TOP() << " = 0;\n";
1584
1585         if ( hasLongestMatch ) {
1586                 out << 
1587                         "       " << TOKSTART() << " = " << NULL_ITEM() << ";\n"
1588                         "       " << TOKEND() << " = " << NULL_ITEM() << ";\n"
1589                         "       " << ACT() << " = 0;\n";
1590         }
1591         out << "        }\n";
1592 }
1593
1594 void JavaTabCodeGen::finishRagelDef()
1595 {
1596         /* The frontend will do this for us, but it may be a good idea to force it
1597          * if the intermediate file is edited. */
1598         redFsm->sortByStateId();
1599
1600         /* Choose default transitions and the single transition. */
1601         redFsm->chooseDefaultSpan();
1602                 
1603         /* Maybe do flat expand, otherwise choose single. */
1604         redFsm->chooseSingle();
1605
1606         /* If any errors have occured in the input file then don't write anything. */
1607         if ( gblErrorCount > 0 )
1608                 return;
1609         
1610         /* Anlayze Machine will find the final action reference counts, among
1611          * other things. We will use these in reporting the usage
1612          * of fsm directives in action code. */
1613         analyzeMachine();
1614
1615         /* Determine if we should use indicies. */
1616         calcIndexSize();
1617 }
1618
1619 ostream &JavaTabCodeGen::source_warning( const InputLoc &loc )
1620 {
1621         cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
1622         return cerr;
1623 }
1624
1625 ostream &JavaTabCodeGen::source_error( const InputLoc &loc )
1626 {
1627         gblErrorCount += 1;
1628         assert( sourceFileName != 0 );
1629         cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
1630         return cerr;
1631 }
1632
1633