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