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