2 * 2007 Victor Hugo Borja <vic@rubyforge.org>
3 * Copyright 2001-2007 Adrian Thurston <thurston@complang.org>
6 /* This file is part of Ragel.
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.
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.
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
28 #include "rubycodegen.h"
36 #include "rubytable.h"
37 #include "rubyftable.h"
39 #include "rubyfflat.h"
43 using std::ostringstream;
56 /* Target ruby impl */
57 extern RubyImplEnum rubyImpl;
59 /* Target language and output style. */
60 extern CodeStyleEnum codeStyle;
63 extern istream *inStream;
64 extern ostream *outStream;
65 extern output_filter *outFilter;
66 extern const char *outputFileName;
68 /* Graphviz dot file generation. */
69 extern bool graphvizDone;
71 extern int numSplitPartitions;
74 * Callbacks invoked by the XML data parser.
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 )
81 CodeGenData *codeGen = 0;
82 switch ( codeStyle ) {
84 codeGen = new RubyTabCodeGen(out);
87 codeGen = new RubyFTabCodeGen(out);
90 codeGen = new RubyFlatCodeGen(out);
93 codeGen = new RubyFFlatCodeGen(out);
96 if ( rubyImpl == Rubinius ) {
97 codeGen = new RbxGotoCodeGen(out);
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";
107 cout << "Invalid code style\n";
111 codeGen->sourceFileName = sourceFileName;
112 codeGen->fsmName = fsmName;
113 codeGen->wantComplete = wantComplete;
119 void rubyLineDirective( ostream &out, const char *fileName, int line )
121 /* Write a comment containing line info. */
122 out << "# line " << line << " \"";
123 for ( const char *pc = fileName; *pc != 0; pc++ ) {
132 void RubyCodeGen::genLineDirective( ostream &out )
134 std::streambuf *sbuf = out.rdbuf();
135 output_filter *filter = static_cast<output_filter*>(sbuf);
136 rubyLineDirective( out, filter->fileName, filter->line + 1 );
139 string RubyCodeGen::DATA_PREFIX()
142 return FSM_NAME() + "_";
146 std::ostream &RubyCodeGen::STATIC_VAR( string type, string name )
150 " attr_accessor :" << name << "\n"
157 std::ostream &RubyCodeGen::OPEN_ARRAY( string type, string name )
161 " attr_accessor :" << name << "\n"
162 " private :" << name << ", :" << name << "=\n"
164 "self." << name << " = [\n";
168 std::ostream &RubyCodeGen::CLOSE_ARRAY()
175 string RubyCodeGen::ARR_OFF( string ptr, string offset )
177 return ptr + "[" + offset + "]";
180 string RubyCodeGen::NULL_ITEM()
186 string RubyCodeGen::P()
193 INLINE_LIST( ret, pExpr, 0, false );
199 string RubyCodeGen::PE()
206 INLINE_LIST( ret, peExpr, 0, false );
212 string RubyCodeGen::EOFV()
219 INLINE_LIST( ret, eofExpr, 0, false );
225 string RubyCodeGen::CS()
229 ret << ACCESS() << "cs";
232 INLINE_LIST( ret, csExpr, 0, false );
238 string RubyCodeGen::TOP()
242 ret << ACCESS() + "top";
245 INLINE_LIST( ret, topExpr, 0, false );
251 string RubyCodeGen::STACK()
254 if ( stackExpr == 0 )
255 ret << ACCESS() + "stack";
258 INLINE_LIST( ret, stackExpr, 0, false );
264 string RubyCodeGen::ACT()
268 ret << ACCESS() + "act";
271 INLINE_LIST( ret, actExpr, 0, false );
277 string RubyCodeGen::TOKSTART()
280 if ( tokstartExpr == 0 )
281 ret << ACCESS() + "ts";
284 INLINE_LIST( ret, tokstartExpr, 0, false );
290 string RubyCodeGen::TOKEND()
293 if ( tokendExpr == 0 )
294 ret << ACCESS() + "te";
297 INLINE_LIST( ret, tokendExpr, 0, false );
303 string RubyCodeGen::DATA()
307 ret << ACCESS() + "data";
310 INLINE_LIST( ret, dataExpr, 0, false );
316 /* Write out the fsm name. */
317 string RubyCodeGen::FSM_NAME()
323 void RubyCodeGen::ACTION( ostream &ret, GenAction *action, int targState, bool inFinish )
325 /* Write the preprocessor line info for going into the source file. */
326 rubyLineDirective( ret, sourceFileName, action->loc.line );
328 /* Write the block and close it off. */
330 INLINE_LIST( ret, action->inlineList, targState, inFinish );
332 rubyLineDirective( ret, sourceFileName, action->loc.line );
337 string RubyCodeGen::GET_WIDE_KEY()
339 if ( redFsm->anyConditions() )
345 string RubyCodeGen::GET_WIDE_KEY( RedStateAp *state )
347 if ( state->stateCondList.length() > 0 )
353 string RubyCodeGen::GET_KEY()
356 if ( getKeyExpr != 0 ) {
357 /* Emit the user supplied method of retrieving the key. */
359 INLINE_LIST( ret, getKeyExpr, 0, false );
363 /* Expression for retrieving the key, use simple dereference. */
364 ret << DATA() << "[" << P() << "]";
369 string RubyCodeGen::KEY( Key key )
372 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
375 ret << (unsigned long) key.getVal();
380 /* Write out level number of tabs. Makes the nested binary search nice
382 string RubyCodeGen::TABS( int level )
385 while ( level-- > 0 )
390 string RubyCodeGen::INT( int i )
397 void RubyCodeGen::CONDITION( ostream &ret, GenAction *condition )
400 rubyLineDirective( ret, sourceFileName, condition->loc.line );
401 INLINE_LIST( ret, condition->inlineList, 0, false );
404 /* Emit the alphabet data type. */
405 string RubyCodeGen::ALPH_TYPE()
407 string ret = keyOps->alphType->data1;
408 if ( keyOps->alphType->data2 != 0 ) {
410 ret += + keyOps->alphType->data2;
415 /* Emit the alphabet data type. */
416 string RubyCodeGen::WIDE_ALPH_TYPE()
419 if ( redFsm->maxKey <= keyOps->maxKey )
422 long long maxKeyVal = redFsm->maxKey.getLongLong();
423 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
424 assert( wideType != 0 );
426 ret = wideType->data1;
427 if ( wideType->data2 != 0 ) {
429 ret += wideType->data2;
436 string RubyCodeGen::ARRAY_TYPE( unsigned long maxVal )
438 long long maxValLL = (long long) maxVal;
439 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
440 assert( arrayType != 0 );
442 string ret = arrayType->data1;
443 if ( arrayType->data2 != 0 ) {
445 ret += arrayType->data2;
450 /* Write out the array of actions. */
451 std::ostream &RubyCodeGen::ACTIONS_ARRAY()
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 );
460 for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) {
461 ARRAY_ITEM( INT(item->value->actionId), ++totalActions, (act.last() && item.last()) );
468 void RubyCodeGen::STATE_IDS()
470 if ( redFsm->startState != 0 )
471 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
474 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
477 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
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";
490 std::ostream &RubyCodeGen::START_ARRAY_LINE()
496 std::ostream &RubyCodeGen::ARRAY_ITEM( string item, int count, bool last )
502 if ( count % IALL == 0 )
511 std::ostream &RubyCodeGen::END_ARRAY_LINE()
517 /* Emit the offset of the start state as a decimal integer. */
518 string RubyCodeGen::START_STATE_ID()
521 ret << redFsm->startState->id;
525 string RubyCodeGen::ERROR_STATE()
528 if ( redFsm->errState != 0 )
529 ret << redFsm->errState->id;
535 string RubyCodeGen::FIRST_FINAL_STATE()
538 if ( redFsm->firstFinState != 0 )
539 ret << redFsm->firstFinState->id;
541 ret << redFsm->nextStateId;
545 string RubyCodeGen::ACCESS()
548 if ( accessExpr != 0 )
549 INLINE_LIST( ret, accessExpr, 0, false );
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 )
558 for ( GenInlineList::Iter item = *inlineList; item.lte(); item++ ) {
559 switch ( item->type ) {
560 case GenInlineItem::Text:
563 case GenInlineItem::Goto:
564 GOTO( ret, item->targState->id, inFinish );
566 case GenInlineItem::Call:
567 CALL( ret, item->targState->id, targState, inFinish );
569 case GenInlineItem::Next:
570 NEXT( ret, item->targState->id, inFinish );
572 case GenInlineItem::Ret:
573 RET( ret, inFinish );
575 case GenInlineItem::PChar:
578 case GenInlineItem::Char:
581 case GenInlineItem::Hold:
582 ret << P() << " = " << P() << " - 1;";
584 case GenInlineItem::Exec:
585 EXEC( ret, item, targState, inFinish );
587 case GenInlineItem::Curs:
590 case GenInlineItem::Targs:
591 ret << "(" << CS() << ")";
593 case GenInlineItem::Entry:
594 ret << item->targState->id;
596 case GenInlineItem::GotoExpr:
597 GOTO_EXPR( ret, item, inFinish );
599 case GenInlineItem::CallExpr:
600 CALL_EXPR( ret, item, targState, inFinish );
602 case GenInlineItem::NextExpr:
603 NEXT_EXPR( ret, item, inFinish );
605 case GenInlineItem::LmSwitch:
606 LM_SWITCH( ret, item, targState, inFinish );
608 case GenInlineItem::LmSetActId:
609 SET_ACT( ret, item );
611 case GenInlineItem::LmSetTokEnd:
612 SET_TOKEND( ret, item );
614 case GenInlineItem::LmGetTokEnd:
615 GET_TOKEND( ret, item );
617 case GenInlineItem::LmInitTokStart:
618 INIT_TOKSTART( ret, item );
620 case GenInlineItem::LmInitAct:
621 INIT_ACT( ret, item );
623 case GenInlineItem::LmSetTokStart:
624 SET_TOKSTART( ret, item );
626 case GenInlineItem::SubAction:
627 SUB_ACTION( ret, item, targState, inFinish );
629 case GenInlineItem::Break:
630 BREAK( ret, targState );
637 void RubyCodeGen::EXEC( ostream &ret, GenInlineItem *item, int targState, int inFinish )
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";
647 void RubyCodeGen::LM_SWITCH( ostream &ret, GenInlineItem *item,
648 int targState, int inFinish )
651 " case " << ACT() << "\n";
653 for ( GenInlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
654 /* Write the case label, the action and the case break. */
658 ret << " when " << lma->lmId << " then\n";
661 /* Write the block and close it off. */
663 INLINE_LIST( ret, lma->children, targState, inFinish );
670 void RubyCodeGen::SET_ACT( ostream &ret, GenInlineItem *item )
672 ret << ACT() << " = " << item->lmId << ";";
675 void RubyCodeGen::INIT_TOKSTART( ostream &ret, GenInlineItem *item )
677 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
680 void RubyCodeGen::INIT_ACT( ostream &ret, GenInlineItem *item )
682 ret << ACT() << " = 0\n";
685 void RubyCodeGen::SET_TOKSTART( ostream &ret, GenInlineItem *item )
687 ret << TOKSTART() << " = " << P() << "\n";
690 void RubyCodeGen::SET_TOKEND( ostream &ret, GenInlineItem *item )
692 /* The tokend action sets tokend. */
693 ret << TOKEND() << " = " << P();
694 if ( item->offset != 0 )
695 out << "+" << item->offset;
699 void RubyCodeGen::GET_TOKEND( ostream &ret, GenInlineItem *item )
704 void RubyCodeGen::SUB_ACTION( ostream &ret, GenInlineItem *item,
705 int targState, bool inFinish )
707 if ( item->children->length() > 0 ) {
708 /* Write the block and close it off. */
710 INLINE_LIST( ret, item->children, targState, inFinish );
715 int RubyCodeGen::TRANS_ACTION( RedTransAp *trans )
717 /* If there are actions, emit them. Otherwise emit zero. */
719 if ( trans->action != 0 )
720 act = trans->action->location+1;
724 ostream &RubyCodeGen::source_warning( const InputLoc &loc )
726 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
730 ostream &RubyCodeGen::source_error( const InputLoc &loc )
733 assert( sourceFileName != 0 );
734 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
738 void RubyCodeGen::finishRagelDef()
741 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
742 codeStyle == GenIpGoto || codeStyle == GenSplit )
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();
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();
755 /* Choose default transitions and the single transition. */
756 redFsm->chooseDefaultSpan();
758 /* Maybe do flat expand, otherwise choose single. */
759 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
762 redFsm->chooseSingle();
764 /* If any errors have occured in the input file then don't write anything. */
765 if ( gblErrorCount > 0 )
768 if ( codeStyle == GenSplit )
769 redFsm->partitionFsm( numSplitPartitions );
771 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
772 redFsm->setInTrans();
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. */
779 /* Determine if we should use indicies. */
784 /* Determine if we should use indicies or not. */
785 void RubyCodeGen::calcIndexSize()
787 int sizeWithInds = 0, sizeWithoutInds = 0;
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;
795 sizeWithInds += arrayTypeSize(redFsm->maxState) * redFsm->transSet.length();
796 if ( redFsm->anyActions() )
797 sizeWithInds += arrayTypeSize(redFsm->maxActionLoc) * redFsm->transSet.length();
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;
808 /* If using indicies reduces the size, use them. */
809 useIndicies = sizeWithInds < sizeWithoutInds;
812 unsigned int RubyCodeGen::arrayTypeSize( unsigned long maxVal )
814 long long maxValLL = (long long) maxVal;
815 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
816 assert( arrayType != 0 );
817 return arrayType->size;
821 void RubyCodeGen::writeInit()
825 out << " " << P() << " ||= 0\n";
828 out << " " << PE() << " ||= " << DATA() << ".length\n";
831 out << " " << CS() << " = " << START() << "\n";
833 /* If there are any calls, then the stack top needs initialization. */
834 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
835 out << " " << TOP() << " = 0\n";
837 if ( hasLongestMatch ) {
839 " " << TOKSTART() << " = " << NULL_ITEM() << "\n"
840 " " << TOKEND() << " = " << NULL_ITEM() << "\n"
841 " " << ACT() << " = 0\n";
847 void RubyCodeGen::writeExports()
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";
858 void RubyCodeGen::writeStart()
860 out << START_STATE_ID();
863 void RubyCodeGen::writeFirstFinal()
865 out << FIRST_FINAL_STATE();
868 void RubyCodeGen::writeError()
870 out << ERROR_STATE();
877 * indent-tabs-mode: 1
878 * c-file-style: "bsd"