We don't need to create allocate the outpute file stream and open the file at
[external/ragel.git] / ragel / rubycodegen.cpp
1 /*
2  *  2007 Victor Hugo Borja <vic@rubyforge.org>
3  *  Copyright 2001-2007 Adrian Thurston <thurston@complang.org>
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 <iomanip>
24 #include <sstream>
25 #include "redfsm.h"
26 #include "gendata.h"
27 #include "ragel.h"
28 #include "rubycodegen.h"
29 #include "xmlparse.h"
30 #include "pcheck.h"
31 #include "vector.h"
32 #include "version.h"
33 #include "common.h"
34
35 #include "ragel.h"
36 #include "rubytable.h"
37 #include "rubyftable.h"
38 #include "rubyflat.h"
39 #include "rubyfflat.h"
40 #include "rbxgoto.h"
41
42 using std::ostream;
43 using std::ostringstream;
44 using std::string;
45 using std::cerr;
46 using std::endl;
47 using std::istream;
48 using std::ifstream;
49 using std::ostream;
50 using std::ios;
51 using std::cin;
52 using std::cout;
53 using std::cerr;
54 using std::endl;
55
56 /* Target ruby impl */
57 extern RubyImplEnum rubyImpl;
58
59 /* Target language and output style. */
60 extern CodeStyleEnum codeStyle;
61
62 /* Io globals. */
63 extern istream *inStream;
64 extern ostream *outStream;
65 extern output_filter *outFilter;
66 extern const char *outputFileName;
67
68 /* Graphviz dot file generation. */
69 extern bool graphvizDone;
70
71 extern int numSplitPartitions;
72
73 /*
74  * Callbacks invoked by the XML data parser.
75  */
76
77 /* Invoked by the parser when the root element is opened. */
78 ostream *rubyOpenOutput( const char *inputFile )
79 {
80         if ( hostLang->lang != HostLang::Ruby ) {
81                 error() << "this code generator is for Ruby only" << endl;
82                 exit(1);
83         }
84
85         /* If the output format is code and no output file name is given, then
86          * make a default. */
87         if ( outputFileName == 0 ) {
88                 const char *ext = findFileExtension( inputFile );
89                 if ( ext != 0 && strcmp( ext, ".rh" ) == 0 )
90                         outputFileName = fileNameFromStem( inputFile, ".h" );
91                 else
92                         outputFileName = fileNameFromStem( inputFile, ".rb" );
93         }
94
95         /* Make sure we are not writing to the same file as the input file. */
96         if ( outputFileName != 0 && strcmp( inputFile, outputFileName  ) == 0 ) {
97                 error() << "output file \"" << outputFileName  << 
98                                 "\" is the same as the input file" << endl;
99         }
100
101         if ( outputFileName != 0 ) {
102                 /* Create the filter on the output and open it. */
103                 outFilter = new output_filter( outputFileName );
104
105                 /* Open the output stream, attaching it to the filter. */
106                 outStream = new ostream( outFilter );
107         }
108         else {
109                 /* Writing out ot std out. */
110                 outStream = &cout;
111         }
112         return outStream;
113 }
114
115 /* Invoked by the parser when a ragel definition is opened. */
116 CodeGenData *rubyMakeCodeGen( const char *sourceFileName, const char *fsmName, 
117                 ostream &out, bool wantComplete )
118 {
119         CodeGenData *codeGen = 0;
120         switch ( codeStyle ) {
121                 case GenTables: 
122                         codeGen = new RubyTabCodeGen(out);
123                         break;
124                 case GenFTables:
125                         codeGen = new RubyFTabCodeGen(out);
126                         break;
127                 case GenFlat:
128                         codeGen = new RubyFlatCodeGen(out);
129                         break;
130                 case GenFFlat:
131                         codeGen = new RubyFFlatCodeGen(out);
132                         break;
133                 case GenGoto:
134                         if ( rubyImpl == Rubinius ) {
135                                 codeGen = new RbxGotoCodeGen(out);
136                         } else {
137                                 cout << "Goto style is still _very_ experimental " 
138                                         "and only supported using Rubinius.\n"
139                                         "You may want to enable the --rbx flag "
140                                         " to give it a try.\n";
141                                 exit(1);
142                         }
143                         break;
144                 default:
145                         cout << "Invalid code style\n";
146                         exit(1);
147                         break;
148         }
149         codeGen->sourceFileName = sourceFileName;
150         codeGen->fsmName = fsmName;
151         codeGen->wantComplete = wantComplete;
152
153         return codeGen;
154 }
155
156
157 void rubyLineDirective( ostream &out, const char *fileName, int line )
158 {
159         /* Write a comment containing line info. */
160         out << "# line " << line  << " \"";
161         for ( const char *pc = fileName; *pc != 0; pc++ ) {
162                 if ( *pc == '\\' )
163                         out << "\\\\";
164                 else
165                         out << *pc;
166         }
167         out << "\"\n";
168 }
169
170 void RubyCodeGen::genLineDirective( ostream &out )
171 {
172         std::streambuf *sbuf = out.rdbuf();
173         output_filter *filter = static_cast<output_filter*>(sbuf);
174         rubyLineDirective( out, filter->fileName, filter->line + 1 );
175 }
176
177 string RubyCodeGen::DATA_PREFIX()
178 {
179         if ( !noPrefix )
180                 return FSM_NAME() + "_";
181         return "";
182 }
183
184 std::ostream &RubyCodeGen::STATIC_VAR( string type, string name )
185 {
186         out << 
187                 "class << self\n"
188                 "       attr_accessor :" << name << "\n"
189                 "end\n"
190                 "self." << name;
191         return out;
192 }
193
194
195 std::ostream &RubyCodeGen::OPEN_ARRAY( string type, string name )
196 {
197         out << 
198                 "class << self\n"
199                 "       attr_accessor :" << name << "\n"
200                 "       private :" << name << ", :" << name << "=\n"
201                 "end\n"
202                 "self." << name << " = [\n";
203         return out;
204 }
205
206 std::ostream &RubyCodeGen::CLOSE_ARRAY()
207 {
208         out << "]\n";
209         return out;
210 }
211
212
213 string RubyCodeGen::ARR_OFF( string ptr, string offset )
214 {
215         return ptr + "[" + offset + "]";
216 }
217
218 string RubyCodeGen::NULL_ITEM()
219 {
220         return "nil";
221 }
222
223
224 string RubyCodeGen::P()
225
226         ostringstream ret;
227         if ( pExpr == 0 )
228                 ret << "p";
229         else {
230                 //ret << "(";
231                 INLINE_LIST( ret, pExpr, 0, false );
232                 //ret << ")";
233         }
234         return ret.str();
235 }
236
237 string RubyCodeGen::PE()
238 {
239         ostringstream ret;
240         if ( peExpr == 0 )
241                 ret << "pe";
242         else {
243                 //ret << "(";
244                 INLINE_LIST( ret, peExpr, 0, false );
245                 //ret << ")";
246         }
247         return ret.str();
248 }
249
250 string RubyCodeGen::EOFV()
251 {
252         ostringstream ret;
253         if ( eofExpr == 0 )
254                 ret << "eof";
255         else {
256                 //ret << "(";
257                 INLINE_LIST( ret, eofExpr, 0, false );
258                 //ret << ")";
259         }
260         return ret.str();
261 }
262
263 string RubyCodeGen::CS()
264 {
265         ostringstream ret;
266         if ( csExpr == 0 )
267                 ret << ACCESS() << "cs";
268         else {
269                 //ret << "(";
270                 INLINE_LIST( ret, csExpr, 0, false );
271                 //ret << ")";
272         }
273         return ret.str();
274 }
275
276 string RubyCodeGen::TOP()
277 {
278         ostringstream ret;
279         if ( topExpr == 0 )
280                 ret << ACCESS() + "top";
281         else {
282                 //ret << "(";
283                 INLINE_LIST( ret, topExpr, 0, false );
284                 //ret << ")";
285         }
286         return ret.str();
287 }
288
289 string RubyCodeGen::STACK()
290 {
291         ostringstream ret;
292         if ( stackExpr == 0 )
293                 ret << ACCESS() + "stack";
294         else {
295                 //ret << "(";
296                 INLINE_LIST( ret, stackExpr, 0, false );
297                 //ret << ")";
298         }
299         return ret.str();
300 }
301
302 string RubyCodeGen::ACT()
303 {
304         ostringstream ret;
305         if ( actExpr == 0 )
306                 ret << ACCESS() + "act";
307         else {
308                 //ret << "(";
309                 INLINE_LIST( ret, actExpr, 0, false );
310                 //ret << ")";
311         }
312         return ret.str();
313 }
314
315 string RubyCodeGen::TOKSTART()
316 {
317         ostringstream ret;
318         if ( tokstartExpr == 0 )
319                 ret << ACCESS() + "ts";
320         else {
321                 //ret << "(";
322                 INLINE_LIST( ret, tokstartExpr, 0, false );
323                 //ret << ")";
324         }
325         return ret.str();
326 }
327
328 string RubyCodeGen::TOKEND()
329 {
330         ostringstream ret;
331         if ( tokendExpr == 0 )
332                 ret << ACCESS() + "te";
333         else {
334                 //ret << "(";
335                 INLINE_LIST( ret, tokendExpr, 0, false );
336                 //ret << ")";
337         }
338         return ret.str();
339 }
340
341 string RubyCodeGen::DATA()
342 {
343         ostringstream ret;
344         if ( dataExpr == 0 )
345                 ret << ACCESS() + "data";
346         else {
347                 //ret << "(";
348                 INLINE_LIST( ret, dataExpr, 0, false );
349                 //ret << ")";
350         }
351         return ret.str();
352 }
353
354 /* Write out the fsm name. */
355 string RubyCodeGen::FSM_NAME()
356 {
357         return fsmName;
358 }
359
360
361 void RubyCodeGen::ACTION( ostream &ret, GenAction *action, int targState, bool inFinish )
362 {
363         /* Write the preprocessor line info for going into the source file. */
364         rubyLineDirective( ret, sourceFileName, action->loc.line );
365
366         /* Write the block and close it off. */
367         ret << "                begin\n";
368         INLINE_LIST( ret, action->inlineList, targState, inFinish );
369         ret << "                end\n";
370         rubyLineDirective( ret, sourceFileName, action->loc.line );
371 }
372
373
374
375 string RubyCodeGen::GET_WIDE_KEY()
376 {
377         if ( redFsm->anyConditions() ) 
378                 return "_widec";
379         else
380                 return GET_KEY();
381 }
382
383 string RubyCodeGen::GET_WIDE_KEY( RedStateAp *state )
384 {
385         if ( state->stateCondList.length() > 0 )
386                 return "_widec";
387         else
388                 return GET_KEY();
389 }
390
391 string RubyCodeGen::GET_KEY()
392 {
393         ostringstream ret;
394         if ( getKeyExpr != 0 ) { 
395                 /* Emit the user supplied method of retrieving the key. */
396                 ret << "(";
397                 INLINE_LIST( ret, getKeyExpr, 0, false );
398                 ret << ")";
399         }
400         else {
401                 /* Expression for retrieving the key, use simple dereference. */
402                 ret << DATA() << "[" << P() << "]";
403         }
404         return ret.str();
405 }
406
407 string RubyCodeGen::KEY( Key key )
408 {
409         ostringstream ret;
410         if ( keyOps->isSigned || !hostLang->explicitUnsigned )
411                 ret << key.getVal();
412         else
413                 ret << (unsigned long) key.getVal();
414         return ret.str();
415 }
416
417
418 /* Write out level number of tabs. Makes the nested binary search nice
419  * looking. */
420 string RubyCodeGen::TABS( int level )
421 {
422         string result;
423         while ( level-- > 0 )
424                 result += "\t";
425         return result;
426 }
427
428 string RubyCodeGen::INT( int i )
429 {
430         ostringstream ret;
431         ret << i;
432         return ret.str();
433 }
434
435 void RubyCodeGen::CONDITION( ostream &ret, GenAction *condition )
436 {
437         ret << "\n";
438         rubyLineDirective( ret, sourceFileName, condition->loc.line );
439         INLINE_LIST( ret, condition->inlineList, 0, false );
440 }
441
442 /* Emit the alphabet data type. */
443 string RubyCodeGen::ALPH_TYPE()
444 {
445         string ret = keyOps->alphType->data1;
446         if ( keyOps->alphType->data2 != 0 ) {
447                 ret += " ";
448                 ret += + keyOps->alphType->data2;
449         }
450         return ret;
451 }
452
453 /* Emit the alphabet data type. */
454 string RubyCodeGen::WIDE_ALPH_TYPE()
455 {
456         string ret;
457         if ( redFsm->maxKey <= keyOps->maxKey )
458                 ret = ALPH_TYPE();
459         else {
460                 long long maxKeyVal = redFsm->maxKey.getLongLong();
461                 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
462                 assert( wideType != 0 );
463
464                 ret = wideType->data1;
465                 if ( wideType->data2 != 0 ) {
466                         ret += " ";
467                         ret += wideType->data2;
468                 }
469         }
470         return ret;
471 }
472
473
474 string RubyCodeGen::ARRAY_TYPE( unsigned long maxVal )
475 {
476         long long maxValLL = (long long) maxVal;
477         HostType *arrayType = keyOps->typeSubsumes( maxValLL );
478         assert( arrayType != 0 );
479
480         string ret = arrayType->data1;
481         if ( arrayType->data2 != 0 ) {
482                 ret += " ";
483                 ret += arrayType->data2;
484         }
485         return ret;
486 }
487
488 /* Write out the array of actions. */
489 std::ostream &RubyCodeGen::ACTIONS_ARRAY()
490 {
491         START_ARRAY_LINE();
492         int totalActions = 0;
493         ARRAY_ITEM( INT(0), ++totalActions, false );
494         for ( GenActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) {
495                 /* Write out the length, which will never be the last character. */
496                 ARRAY_ITEM( INT(act->key.length()), ++totalActions, false );
497
498                 for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) {
499                         ARRAY_ITEM( INT(item->value->actionId), ++totalActions, (act.last() && item.last()) );
500                 }
501         }
502         END_ARRAY_LINE();
503         return out;
504 }
505
506 void RubyCodeGen::STATE_IDS()
507 {
508         if ( redFsm->startState != 0 )
509                 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
510
511         if ( !noFinal )
512                 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
513
514         if ( !noError )
515                 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
516
517         out << "\n";
518
519         if ( entryPointNames.length() > 0 ) {
520                 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
521                         STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) << 
522                                         " = " << entryPointIds[en.pos()] << ";\n";
523                 }
524                 out << "\n";
525         }
526 }
527
528 std::ostream &RubyCodeGen::START_ARRAY_LINE()
529 {
530         out << "\t";
531         return out;
532 }
533
534 std::ostream &RubyCodeGen::ARRAY_ITEM( string item, int count, bool last )
535 {
536         out << item;
537         if ( !last )
538         {
539                 out << ", ";
540                 if ( count % IALL == 0 )
541                 {
542                         END_ARRAY_LINE();
543                         START_ARRAY_LINE();
544                 }
545         }
546         return out;
547 }
548
549 std::ostream &RubyCodeGen::END_ARRAY_LINE()
550 {
551         out << "\n";
552         return out;
553 }
554
555 /* Emit the offset of the start state as a decimal integer. */
556 string RubyCodeGen::START_STATE_ID()
557 {
558         ostringstream ret;
559         ret << redFsm->startState->id;
560         return ret.str();
561 };
562
563 string RubyCodeGen::ERROR_STATE()
564 {
565         ostringstream ret;
566         if ( redFsm->errState != 0 )
567                 ret << redFsm->errState->id;
568         else
569                 ret << "-1";
570         return ret.str();
571 }
572
573 string RubyCodeGen::FIRST_FINAL_STATE()
574 {
575         ostringstream ret;
576         if ( redFsm->firstFinState != 0 )
577                 ret << redFsm->firstFinState->id;
578         else
579                 ret << redFsm->nextStateId;
580         return ret.str();
581 }
582
583 string RubyCodeGen::ACCESS()
584 {
585         ostringstream ret;
586         if ( accessExpr != 0 )
587                 INLINE_LIST( ret, accessExpr, 0, false );
588         return ret.str();
589 }
590
591 /* Write out an inline tree structure. Walks the list and possibly calls out
592  * to virtual functions than handle language specific items in the tree. */
593 void RubyCodeGen::INLINE_LIST( ostream &ret, GenInlineList *inlineList, 
594                 int targState, bool inFinish )
595 {
596         for ( GenInlineList::Iter item = *inlineList; item.lte(); item++ ) {
597                 switch ( item->type ) {
598                 case GenInlineItem::Text:
599                         ret << item->data;
600                         break;
601                 case GenInlineItem::Goto:
602                         GOTO( ret, item->targState->id, inFinish );
603                         break;
604                 case GenInlineItem::Call:
605                         CALL( ret, item->targState->id, targState, inFinish );
606                         break;
607                 case GenInlineItem::Next:
608                         NEXT( ret, item->targState->id, inFinish );
609                         break;
610                 case GenInlineItem::Ret:
611                         RET( ret, inFinish );
612                         break;
613                 case GenInlineItem::PChar:
614                         ret << P();
615                         break;
616                 case GenInlineItem::Char:
617                         ret << GET_KEY();
618                         break;
619                 case GenInlineItem::Hold:
620                         ret << P() << " = " << P() << " - 1;";
621                         break;
622                 case GenInlineItem::Exec:
623                         EXEC( ret, item, targState, inFinish );
624                         break;
625                 case GenInlineItem::Curs:
626                         ret << "(_ps)";
627                         break;
628                 case GenInlineItem::Targs:
629                         ret << "(" << CS() << ")";
630                         break;
631                 case GenInlineItem::Entry:
632                         ret << item->targState->id;
633                         break;
634                 case GenInlineItem::GotoExpr:
635                         GOTO_EXPR( ret, item, inFinish );
636                         break;
637                 case GenInlineItem::CallExpr:
638                         CALL_EXPR( ret, item, targState, inFinish );
639                         break;
640                 case GenInlineItem::NextExpr:
641                         NEXT_EXPR( ret, item, inFinish );
642                         break;
643                 case GenInlineItem::LmSwitch:
644                         LM_SWITCH( ret, item, targState, inFinish );
645                         break;
646                 case GenInlineItem::LmSetActId:
647                         SET_ACT( ret, item );
648                         break;
649                 case GenInlineItem::LmSetTokEnd:
650                         SET_TOKEND( ret, item );
651                         break;
652                 case GenInlineItem::LmGetTokEnd:
653                         GET_TOKEND( ret, item );
654                         break;
655                 case GenInlineItem::LmInitTokStart:
656                         INIT_TOKSTART( ret, item );
657                         break;
658                 case GenInlineItem::LmInitAct:
659                         INIT_ACT( ret, item );
660                         break;
661                 case GenInlineItem::LmSetTokStart:
662                         SET_TOKSTART( ret, item );
663                         break;
664                 case GenInlineItem::SubAction:
665                         SUB_ACTION( ret, item, targState, inFinish );
666                         break;
667                 case GenInlineItem::Break:
668                         BREAK( ret, targState );
669                         break;
670                 }
671         }
672 }
673
674
675 void RubyCodeGen::EXEC( ostream &ret, GenInlineItem *item, int targState, int inFinish )
676 {
677         /* The parser gives fexec two children. The double brackets are for D
678          * code. If the inline list is a single word it will get interpreted as a
679          * C-style cast by the D compiler. */
680         ret << " begin " << P() << " = ((";
681         INLINE_LIST( ret, item->children, targState, inFinish );
682         ret << "))-1; end\n";
683 }
684
685 void RubyCodeGen::LM_SWITCH( ostream &ret, GenInlineItem *item, 
686                 int targState, int inFinish )
687 {
688         ret << 
689                 "       case " << ACT() << "\n";
690
691         for ( GenInlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
692                 /* Write the case label, the action and the case break. */
693                 if ( lma->lmId < 0 )
694                         ret << "        else\n";
695                 else
696                         ret << "        when " << lma->lmId << " then\n";
697
698
699                 /* Write the block and close it off. */
700                 ret << "        begin";
701                 INLINE_LIST( ret, lma->children, targState, inFinish );
702                 ret << "end\n";
703         }
704
705         ret << "end \n\t";
706 }
707
708 void RubyCodeGen::SET_ACT( ostream &ret, GenInlineItem *item )
709 {
710         ret << ACT() << " = " << item->lmId << ";";
711 }
712
713 void RubyCodeGen::INIT_TOKSTART( ostream &ret, GenInlineItem *item )
714 {
715         ret << TOKSTART() << " = " << NULL_ITEM() << ";";
716 }
717
718 void RubyCodeGen::INIT_ACT( ostream &ret, GenInlineItem *item )
719 {
720         ret << ACT() << " = 0\n";
721 }
722
723 void RubyCodeGen::SET_TOKSTART( ostream &ret, GenInlineItem *item )
724 {
725         ret << TOKSTART() << " = " << P() << "\n";
726 }
727
728 void RubyCodeGen::SET_TOKEND( ostream &ret, GenInlineItem *item )
729 {
730         /* The tokend action sets tokend. */
731         ret << TOKEND() << " = " << P();
732         if ( item->offset != 0 ) 
733                 out << "+" << item->offset;
734         out << "\n";
735 }
736
737 void RubyCodeGen::GET_TOKEND( ostream &ret, GenInlineItem *item )
738 {
739         ret << TOKEND();
740 }
741
742 void RubyCodeGen::SUB_ACTION( ostream &ret, GenInlineItem *item, 
743                 int targState, bool inFinish )
744 {
745         if ( item->children->length() > 0 ) {
746                 /* Write the block and close it off. */
747                 ret << " begin ";
748                 INLINE_LIST( ret, item->children, targState, inFinish );
749                 ret << " end\n";
750         }
751 }
752
753 int RubyCodeGen::TRANS_ACTION( RedTransAp *trans )
754 {
755         /* If there are actions, emit them. Otherwise emit zero. */
756         int act = 0;
757         if ( trans->action != 0 )
758                 act = trans->action->location+1;
759         return act;
760 }
761
762 ostream &RubyCodeGen::source_warning( const InputLoc &loc )
763 {
764         cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
765         return cerr;
766 }
767
768 ostream &RubyCodeGen::source_error( const InputLoc &loc )
769 {
770         gblErrorCount += 1;
771         assert( sourceFileName != 0 );
772         cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
773         return cerr;
774 }
775
776 void RubyCodeGen::finishRagelDef()
777 {
778
779         if ( codeStyle == GenGoto || codeStyle == GenFGoto || 
780                         codeStyle == GenIpGoto || codeStyle == GenSplit )
781         {
782                 /* For directly executable machines there is no required state
783                  * ordering. Choose a depth-first ordering to increase the
784                  * potential for fall-throughs. */
785                 redFsm->depthFirstOrdering();
786         }
787         else {
788                 /* The frontend will do this for us, but it may be a good idea to
789                  * force it if the intermediate file is edited. */
790                 redFsm->sortByStateId();
791         }
792
793         /* Choose default transitions and the single transition. */
794         redFsm->chooseDefaultSpan();
795                 
796         /* Maybe do flat expand, otherwise choose single. */
797         if ( codeStyle == GenFlat || codeStyle == GenFFlat )
798                 redFsm->makeFlat();
799         else
800                 redFsm->chooseSingle();
801
802         /* If any errors have occured in the input file then don't write anything. */
803         if ( gblErrorCount > 0 )
804                 return;
805         
806         if ( codeStyle == GenSplit )
807                 redFsm->partitionFsm( numSplitPartitions );
808
809         if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
810                 redFsm->setInTrans();
811
812         /* Anlayze Machine will find the final action reference counts, among
813          * other things. We will use these in reporting the usage
814          * of fsm directives in action code. */
815         analyzeMachine();
816
817         /* Determine if we should use indicies. */
818         calcIndexSize();
819 }
820
821
822 /* Determine if we should use indicies or not. */
823 void RubyCodeGen::calcIndexSize()
824 {
825         int sizeWithInds = 0, sizeWithoutInds = 0;
826
827         /* Calculate cost of using with indicies. */
828         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
829                 int totalIndex = st->outSingle.length() + st->outRange.length() + 
830                                 (st->defTrans == 0 ? 0 : 1);
831                 sizeWithInds += arrayTypeSize(redFsm->maxIndex) * totalIndex;
832         }
833         sizeWithInds += arrayTypeSize(redFsm->maxState) * redFsm->transSet.length();
834         if ( redFsm->anyActions() )
835                 sizeWithInds += arrayTypeSize(redFsm->maxActionLoc) * redFsm->transSet.length();
836
837         /* Calculate the cost of not using indicies. */
838         for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
839                 int totalIndex = st->outSingle.length() + st->outRange.length() + 
840                                 (st->defTrans == 0 ? 0 : 1);
841                 sizeWithoutInds += arrayTypeSize(redFsm->maxState) * totalIndex;
842                 if ( redFsm->anyActions() )
843                         sizeWithoutInds += arrayTypeSize(redFsm->maxActionLoc) * totalIndex;
844         }
845
846         /* If using indicies reduces the size, use them. */
847         useIndicies = sizeWithInds < sizeWithoutInds;
848 }
849
850 unsigned int RubyCodeGen::arrayTypeSize( unsigned long maxVal )
851 {
852         long long maxValLL = (long long) maxVal;
853         HostType *arrayType = keyOps->typeSubsumes( maxValLL );
854         assert( arrayType != 0 );
855         return arrayType->size;
856 }
857
858
859 void RubyCodeGen::writeInit()
860 {
861         out << "begin\n";
862         
863         out << "        " << P() << " ||= 0\n";
864
865         if ( !noEnd ) 
866                 out << "        " << PE() << " ||= " << DATA() << ".length\n";
867
868         if ( !noCS )
869                 out << "        " << CS() << " = " << START() << "\n";
870
871         /* If there are any calls, then the stack top needs initialization. */
872         if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
873                 out << "        " << TOP() << " = 0\n";
874
875         if ( hasLongestMatch ) {
876                 out <<
877                         "       " << TOKSTART() << " = " << NULL_ITEM() << "\n"
878                         "       " << TOKEND() << " = " << NULL_ITEM() << "\n"
879                         "       " << ACT() << " = 0\n";
880         }
881
882         out << "end\n";
883 }
884
885 void RubyCodeGen::writeExports()
886 {
887         if ( exportList.length() > 0 ) {
888                 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
889                         STATIC_VAR( ALPH_TYPE(), DATA_PREFIX() + "ex_" + ex->name ) 
890                                         << " = " << KEY(ex->key) << "\n";
891                 }
892                 out << "\n";
893         }
894 }
895
896 void RubyCodeGen::writeStart()
897 {
898         out << START_STATE_ID();
899 }
900
901 void RubyCodeGen::writeFirstFinal()
902 {
903         out << FIRST_FINAL_STATE();
904 }
905
906 void RubyCodeGen::writeError()
907 {
908         out << ERROR_STATE();
909 }
910
911
912 /*
913  * Local Variables:
914  * mode: c++
915  * indent-tabs-mode: 1
916  * c-file-style: "bsd"
917  * End:
918  */