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