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 the root element is opened. */
78 ostream *rubyOpenOutput( const char *inputFile )
80 if ( hostLang->lang != HostLang::Ruby ) {
81 error() << "this code generator is for Ruby only" << endl;
85 /* If the output format is code and no output file name is given, then
87 if ( outputFileName == 0 ) {
88 const char *ext = findFileExtension( inputFile );
89 if ( ext != 0 && strcmp( ext, ".rh" ) == 0 )
90 outputFileName = fileNameFromStem( inputFile, ".h" );
92 outputFileName = fileNameFromStem( inputFile, ".rb" );
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;
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;
110 /* Open the output stream, attaching it to the filter. */
111 outStream = new ostream( outFilter );
114 /* Writing out ot std out. */
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 )
124 CodeGenData *codeGen = 0;
125 switch ( codeStyle ) {
127 codeGen = new RubyTabCodeGen(out);
130 codeGen = new RubyFTabCodeGen(out);
133 codeGen = new RubyFlatCodeGen(out);
136 codeGen = new RubyFFlatCodeGen(out);
139 if ( rubyImpl == Rubinius ) {
140 codeGen = new RbxGotoCodeGen(out);
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";
150 cout << "Invalid code style\n";
154 codeGen->sourceFileName = sourceFileName;
155 codeGen->fsmName = fsmName;
156 codeGen->wantComplete = wantComplete;
162 void rubyLineDirective( ostream &out, const char *fileName, int line )
164 /* Write a comment containing line info. */
165 out << "# line " << line << " \"";
166 for ( const char *pc = fileName; *pc != 0; pc++ ) {
175 void RubyCodeGen::genLineDirective( ostream &out )
177 std::streambuf *sbuf = out.rdbuf();
178 output_filter *filter = static_cast<output_filter*>(sbuf);
179 rubyLineDirective( out, filter->fileName, filter->line + 1 );
182 string RubyCodeGen::DATA_PREFIX()
185 return FSM_NAME() + "_";
189 std::ostream &RubyCodeGen::STATIC_VAR( string type, string name )
193 " attr_accessor :" << name << "\n"
200 std::ostream &RubyCodeGen::OPEN_ARRAY( string type, string name )
204 " attr_accessor :" << name << "\n"
205 " private :" << name << ", :" << name << "=\n"
207 "self." << name << " = [\n";
211 std::ostream &RubyCodeGen::CLOSE_ARRAY()
218 string RubyCodeGen::ARR_OFF( string ptr, string offset )
220 return ptr + "[" + offset + "]";
223 string RubyCodeGen::NULL_ITEM()
229 string RubyCodeGen::P()
236 INLINE_LIST( ret, pExpr, 0, false );
242 string RubyCodeGen::PE()
249 INLINE_LIST( ret, peExpr, 0, false );
255 string RubyCodeGen::EOFV()
262 INLINE_LIST( ret, eofExpr, 0, false );
268 string RubyCodeGen::CS()
272 ret << ACCESS() << "cs";
275 INLINE_LIST( ret, csExpr, 0, false );
281 string RubyCodeGen::TOP()
285 ret << ACCESS() + "top";
288 INLINE_LIST( ret, topExpr, 0, false );
294 string RubyCodeGen::STACK()
297 if ( stackExpr == 0 )
298 ret << ACCESS() + "stack";
301 INLINE_LIST( ret, stackExpr, 0, false );
307 string RubyCodeGen::ACT()
311 ret << ACCESS() + "act";
314 INLINE_LIST( ret, actExpr, 0, false );
320 string RubyCodeGen::TOKSTART()
323 if ( tokstartExpr == 0 )
324 ret << ACCESS() + "ts";
327 INLINE_LIST( ret, tokstartExpr, 0, false );
333 string RubyCodeGen::TOKEND()
336 if ( tokendExpr == 0 )
337 ret << ACCESS() + "te";
340 INLINE_LIST( ret, tokendExpr, 0, false );
346 string RubyCodeGen::DATA()
350 ret << ACCESS() + "data";
353 INLINE_LIST( ret, dataExpr, 0, false );
359 /* Write out the fsm name. */
360 string RubyCodeGen::FSM_NAME()
366 void RubyCodeGen::ACTION( ostream &ret, GenAction *action, int targState, bool inFinish )
368 /* Write the preprocessor line info for going into the source file. */
369 rubyLineDirective( ret, sourceFileName, action->loc.line );
371 /* Write the block and close it off. */
373 INLINE_LIST( ret, action->inlineList, targState, inFinish );
375 rubyLineDirective( ret, sourceFileName, action->loc.line );
380 string RubyCodeGen::GET_WIDE_KEY()
382 if ( redFsm->anyConditions() )
388 string RubyCodeGen::GET_WIDE_KEY( RedStateAp *state )
390 if ( state->stateCondList.length() > 0 )
396 string RubyCodeGen::GET_KEY()
399 if ( getKeyExpr != 0 ) {
400 /* Emit the user supplied method of retrieving the key. */
402 INLINE_LIST( ret, getKeyExpr, 0, false );
406 /* Expression for retrieving the key, use simple dereference. */
407 ret << DATA() << "[" << P() << "]";
412 string RubyCodeGen::KEY( Key key )
415 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
418 ret << (unsigned long) key.getVal();
423 /* Write out level number of tabs. Makes the nested binary search nice
425 string RubyCodeGen::TABS( int level )
428 while ( level-- > 0 )
433 string RubyCodeGen::INT( int i )
440 void RubyCodeGen::CONDITION( ostream &ret, GenAction *condition )
443 rubyLineDirective( ret, sourceFileName, condition->loc.line );
444 INLINE_LIST( ret, condition->inlineList, 0, false );
447 /* Emit the alphabet data type. */
448 string RubyCodeGen::ALPH_TYPE()
450 string ret = keyOps->alphType->data1;
451 if ( keyOps->alphType->data2 != 0 ) {
453 ret += + keyOps->alphType->data2;
458 /* Emit the alphabet data type. */
459 string RubyCodeGen::WIDE_ALPH_TYPE()
462 if ( redFsm->maxKey <= keyOps->maxKey )
465 long long maxKeyVal = redFsm->maxKey.getLongLong();
466 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
467 assert( wideType != 0 );
469 ret = wideType->data1;
470 if ( wideType->data2 != 0 ) {
472 ret += wideType->data2;
479 string RubyCodeGen::ARRAY_TYPE( unsigned long maxVal )
481 long long maxValLL = (long long) maxVal;
482 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
483 assert( arrayType != 0 );
485 string ret = arrayType->data1;
486 if ( arrayType->data2 != 0 ) {
488 ret += arrayType->data2;
493 /* Write out the array of actions. */
494 std::ostream &RubyCodeGen::ACTIONS_ARRAY()
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 );
503 for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) {
504 ARRAY_ITEM( INT(item->value->actionId), ++totalActions, (act.last() && item.last()) );
511 void RubyCodeGen::STATE_IDS()
513 if ( redFsm->startState != 0 )
514 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
516 if ( writeFirstFinal )
517 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
520 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
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";
533 std::ostream &RubyCodeGen::START_ARRAY_LINE()
539 std::ostream &RubyCodeGen::ARRAY_ITEM( string item, int count, bool last )
545 if ( count % IALL == 0 )
554 std::ostream &RubyCodeGen::END_ARRAY_LINE()
560 /* Emit the offset of the start state as a decimal integer. */
561 string RubyCodeGen::START_STATE_ID()
564 ret << redFsm->startState->id;
568 string RubyCodeGen::ERROR_STATE()
571 if ( redFsm->errState != 0 )
572 ret << redFsm->errState->id;
578 string RubyCodeGen::FIRST_FINAL_STATE()
581 if ( redFsm->firstFinState != 0 )
582 ret << redFsm->firstFinState->id;
584 ret << redFsm->nextStateId;
588 string RubyCodeGen::ACCESS()
591 if ( accessExpr != 0 )
592 INLINE_LIST( ret, accessExpr, 0, false );
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 )
601 for ( GenInlineList::Iter item = *inlineList; item.lte(); item++ ) {
602 switch ( item->type ) {
603 case GenInlineItem::Text:
606 case GenInlineItem::Goto:
607 GOTO( ret, item->targState->id, inFinish );
609 case GenInlineItem::Call:
610 CALL( ret, item->targState->id, targState, inFinish );
612 case GenInlineItem::Next:
613 NEXT( ret, item->targState->id, inFinish );
615 case GenInlineItem::Ret:
616 RET( ret, inFinish );
618 case GenInlineItem::PChar:
621 case GenInlineItem::Char:
624 case GenInlineItem::Hold:
625 ret << P() << " = " << P() << " - 1;";
627 case GenInlineItem::Exec:
628 EXEC( ret, item, targState, inFinish );
630 case GenInlineItem::Curs:
633 case GenInlineItem::Targs:
634 ret << "(" << CS() << ")";
636 case GenInlineItem::Entry:
637 ret << item->targState->id;
639 case GenInlineItem::GotoExpr:
640 GOTO_EXPR( ret, item, inFinish );
642 case GenInlineItem::CallExpr:
643 CALL_EXPR( ret, item, targState, inFinish );
645 case GenInlineItem::NextExpr:
646 NEXT_EXPR( ret, item, inFinish );
648 case GenInlineItem::LmSwitch:
649 LM_SWITCH( ret, item, targState, inFinish );
651 case GenInlineItem::LmSetActId:
652 SET_ACT( ret, item );
654 case GenInlineItem::LmSetTokEnd:
655 SET_TOKEND( ret, item );
657 case GenInlineItem::LmGetTokEnd:
658 GET_TOKEND( ret, item );
660 case GenInlineItem::LmInitTokStart:
661 INIT_TOKSTART( ret, item );
663 case GenInlineItem::LmInitAct:
664 INIT_ACT( ret, item );
666 case GenInlineItem::LmSetTokStart:
667 SET_TOKSTART( ret, item );
669 case GenInlineItem::SubAction:
670 SUB_ACTION( ret, item, targState, inFinish );
672 case GenInlineItem::Break:
673 BREAK( ret, targState );
680 void RubyCodeGen::EXEC( ostream &ret, GenInlineItem *item, int targState, int inFinish )
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";
690 void RubyCodeGen::LM_SWITCH( ostream &ret, GenInlineItem *item,
691 int targState, int inFinish )
694 " case " << ACT() << "\n";
696 for ( GenInlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
697 /* Write the case label, the action and the case break. */
701 ret << " when " << lma->lmId << " then\n";
704 /* Write the block and close it off. */
706 INLINE_LIST( ret, lma->children, targState, inFinish );
713 void RubyCodeGen::SET_ACT( ostream &ret, GenInlineItem *item )
715 ret << ACT() << " = " << item->lmId << ";";
718 void RubyCodeGen::INIT_TOKSTART( ostream &ret, GenInlineItem *item )
720 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
723 void RubyCodeGen::INIT_ACT( ostream &ret, GenInlineItem *item )
725 ret << ACT() << " = 0\n";
728 void RubyCodeGen::SET_TOKSTART( ostream &ret, GenInlineItem *item )
730 ret << TOKSTART() << " = " << P() << "\n";
733 void RubyCodeGen::SET_TOKEND( ostream &ret, GenInlineItem *item )
735 /* The tokend action sets tokend. */
736 ret << TOKEND() << " = " << P();
737 if ( item->offset != 0 )
738 out << "+" << item->offset;
742 void RubyCodeGen::GET_TOKEND( ostream &ret, GenInlineItem *item )
747 void RubyCodeGen::SUB_ACTION( ostream &ret, GenInlineItem *item,
748 int targState, bool inFinish )
750 if ( item->children->length() > 0 ) {
751 /* Write the block and close it off. */
753 INLINE_LIST( ret, item->children, targState, inFinish );
758 int RubyCodeGen::TRANS_ACTION( RedTransAp *trans )
760 /* If there are actions, emit them. Otherwise emit zero. */
762 if ( trans->action != 0 )
763 act = trans->action->location+1;
767 ostream &RubyCodeGen::source_warning( const InputLoc &loc )
769 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
773 ostream &RubyCodeGen::source_error( const InputLoc &loc )
776 assert( sourceFileName != 0 );
777 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
781 void RubyCodeGen::finishRagelDef()
784 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
785 codeStyle == GenIpGoto || codeStyle == GenSplit )
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();
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();
798 /* Choose default transitions and the single transition. */
799 redFsm->chooseDefaultSpan();
801 /* Maybe do flat expand, otherwise choose single. */
802 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
805 redFsm->chooseSingle();
807 /* If any errors have occured in the input file then don't write anything. */
808 if ( gblErrorCount > 0 )
811 if ( codeStyle == GenSplit )
812 redFsm->partitionFsm( numSplitPartitions );
814 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
815 redFsm->setInTrans();
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. */
822 /* Determine if we should use indicies. */
827 /* Determine if we should use indicies or not. */
828 void RubyCodeGen::calcIndexSize()
830 int sizeWithInds = 0, sizeWithoutInds = 0;
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;
838 sizeWithInds += arrayTypeSize(redFsm->maxState) * redFsm->transSet.length();
839 if ( redFsm->anyActions() )
840 sizeWithInds += arrayTypeSize(redFsm->maxActionLoc) * redFsm->transSet.length();
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;
851 /* If using indicies reduces the size, use them. */
852 useIndicies = sizeWithInds < sizeWithoutInds;
855 unsigned int RubyCodeGen::arrayTypeSize( unsigned long maxVal )
857 long long maxValLL = (long long) maxVal;
858 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
859 assert( arrayType != 0 );
860 return arrayType->size;
864 void RubyCodeGen::writeInit()
868 out << " " << P() << " ||= 0\n";
871 out << " " << PE() << " ||= " << DATA() << ".length\n";
874 out << " " << CS() << " = " << START() << "\n";
876 /* If there are any calls, then the stack top needs initialization. */
877 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
878 out << " " << TOP() << " = 0\n";
880 if ( hasLongestMatch ) {
882 " " << TOKSTART() << " = " << NULL_ITEM() << "\n"
883 " " << TOKEND() << " = " << NULL_ITEM() << "\n"
884 " " << ACT() << " = 0\n";
890 void RubyCodeGen::writeExports()
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";
904 * indent-tabs-mode: 1
905 * c-file-style: "bsd"