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