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