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"
35 #include "rubytable.h"
36 #include "rubyftable.h"
38 #include "rubyfflat.h"
42 using std::ostringstream;
55 /* Target ruby impl */
57 /* Target language and output style. */
58 extern CodeStyle codeStyle;
60 extern int numSplitPartitions;
63 * Callbacks invoked by the XML data parser.
67 void rubyLineDirective( ostream &out, const char *fileName, int line )
69 /* Write a comment containing line info. */
70 out << "# line " << line << " \"";
71 for ( const char *pc = fileName; *pc != 0; pc++ ) {
80 void RubyCodeGen::genLineDirective( ostream &out )
82 std::streambuf *sbuf = out.rdbuf();
83 output_filter *filter = static_cast<output_filter*>(sbuf);
84 rubyLineDirective( out, filter->fileName, filter->line + 1 );
87 string RubyCodeGen::DATA_PREFIX()
90 return FSM_NAME() + "_";
94 std::ostream &RubyCodeGen::STATIC_VAR( string type, string name )
98 " attr_accessor :" << name << "\n"
105 std::ostream &RubyCodeGen::OPEN_ARRAY( string type, string name )
109 " attr_accessor :" << name << "\n"
110 " private :" << name << ", :" << name << "=\n"
112 "self." << name << " = [\n";
116 std::ostream &RubyCodeGen::CLOSE_ARRAY()
123 string RubyCodeGen::ARR_OFF( string ptr, string offset )
125 return ptr + "[" + offset + "]";
128 string RubyCodeGen::NULL_ITEM()
134 string RubyCodeGen::P()
141 INLINE_LIST( ret, pExpr, 0, false );
147 string RubyCodeGen::PE()
154 INLINE_LIST( ret, peExpr, 0, false );
160 string RubyCodeGen::vEOF()
167 INLINE_LIST( ret, eofExpr, 0, false );
173 string RubyCodeGen::vCS()
177 ret << ACCESS() << "cs";
180 INLINE_LIST( ret, csExpr, 0, false );
186 string RubyCodeGen::TOP()
190 ret << ACCESS() + "top";
193 INLINE_LIST( ret, topExpr, 0, false );
199 string RubyCodeGen::STACK()
202 if ( stackExpr == 0 )
203 ret << ACCESS() + "stack";
206 INLINE_LIST( ret, stackExpr, 0, false );
212 string RubyCodeGen::ACT()
216 ret << ACCESS() + "act";
219 INLINE_LIST( ret, actExpr, 0, false );
225 string RubyCodeGen::TOKSTART()
228 if ( tokstartExpr == 0 )
229 ret << ACCESS() + "ts";
232 INLINE_LIST( ret, tokstartExpr, 0, false );
238 string RubyCodeGen::TOKEND()
241 if ( tokendExpr == 0 )
242 ret << ACCESS() + "te";
245 INLINE_LIST( ret, tokendExpr, 0, false );
251 string RubyCodeGen::DATA()
255 ret << ACCESS() + "data";
258 INLINE_LIST( ret, dataExpr, 0, false );
264 /* Write out the fsm name. */
265 string RubyCodeGen::FSM_NAME()
271 void RubyCodeGen::ACTION( ostream &ret, GenAction *action, int targState, bool inFinish )
273 /* Write the preprocessor line info for going into the source file. */
274 rubyLineDirective( ret, action->loc.fileName, action->loc.line );
276 /* Write the block and close it off. */
278 INLINE_LIST( ret, action->inlineList, targState, inFinish );
284 string RubyCodeGen::GET_WIDE_KEY()
286 if ( redFsm->anyConditions() )
292 string RubyCodeGen::GET_WIDE_KEY( RedStateAp *state )
294 if ( state->stateCondList.length() > 0 )
300 string RubyCodeGen::GET_KEY()
303 if ( getKeyExpr != 0 ) {
304 /* Emit the user supplied method of retrieving the key. */
306 INLINE_LIST( ret, getKeyExpr, 0, false );
310 /* Expression for retrieving the key, use simple dereference. */
311 ret << DATA() << "[" << P() << "]";
316 string RubyCodeGen::KEY( Key key )
319 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
322 ret << (unsigned long) key.getVal();
327 /* Write out level number of tabs. Makes the nested binary search nice
329 string RubyCodeGen::TABS( int level )
332 while ( level-- > 0 )
337 string RubyCodeGen::INT( int i )
344 void RubyCodeGen::CONDITION( ostream &ret, GenAction *condition )
347 rubyLineDirective( ret, condition->loc.fileName, condition->loc.line );
348 INLINE_LIST( ret, condition->inlineList, 0, false );
351 /* Emit the alphabet data type. */
352 string RubyCodeGen::ALPH_TYPE()
354 string ret = keyOps->alphType->data1;
355 if ( keyOps->alphType->data2 != 0 ) {
357 ret += + keyOps->alphType->data2;
362 /* Emit the alphabet data type. */
363 string RubyCodeGen::WIDE_ALPH_TYPE()
366 if ( redFsm->maxKey <= keyOps->maxKey )
369 long long maxKeyVal = redFsm->maxKey.getLongLong();
370 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
371 assert( wideType != 0 );
373 ret = wideType->data1;
374 if ( wideType->data2 != 0 ) {
376 ret += wideType->data2;
383 string RubyCodeGen::ARRAY_TYPE( unsigned long maxVal )
385 long long maxValLL = (long long) maxVal;
386 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
387 assert( arrayType != 0 );
389 string ret = arrayType->data1;
390 if ( arrayType->data2 != 0 ) {
392 ret += arrayType->data2;
397 /* Write out the array of actions. */
398 std::ostream &RubyCodeGen::ACTIONS_ARRAY()
401 int totalActions = 0;
402 ARRAY_ITEM( INT(0), ++totalActions, false );
403 for ( GenActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) {
404 /* Write out the length, which will never be the last character. */
405 ARRAY_ITEM( INT(act->key.length()), ++totalActions, false );
407 for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) {
408 ARRAY_ITEM( INT(item->value->actionId), ++totalActions, (act.last() && item.last()) );
415 void RubyCodeGen::STATE_IDS()
417 if ( redFsm->startState != 0 )
418 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
421 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
424 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
428 if ( entryPointNames.length() > 0 ) {
429 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
430 STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) <<
431 " = " << entryPointIds[en.pos()] << ";\n";
437 std::ostream &RubyCodeGen::START_ARRAY_LINE()
443 std::ostream &RubyCodeGen::ARRAY_ITEM( string item, int count, bool last )
449 if ( count % IALL == 0 )
458 std::ostream &RubyCodeGen::END_ARRAY_LINE()
464 /* Emit the offset of the start state as a decimal integer. */
465 string RubyCodeGen::START_STATE_ID()
468 ret << redFsm->startState->id;
472 string RubyCodeGen::ERROR_STATE()
475 if ( redFsm->errState != 0 )
476 ret << redFsm->errState->id;
482 string RubyCodeGen::FIRST_FINAL_STATE()
485 if ( redFsm->firstFinState != 0 )
486 ret << redFsm->firstFinState->id;
488 ret << redFsm->nextStateId;
492 string RubyCodeGen::ACCESS()
495 if ( accessExpr != 0 )
496 INLINE_LIST( ret, accessExpr, 0, false );
500 /* Write out an inline tree structure. Walks the list and possibly calls out
501 * to virtual functions than handle language specific items in the tree. */
502 void RubyCodeGen::INLINE_LIST( ostream &ret, GenInlineList *inlineList,
503 int targState, bool inFinish )
505 for ( GenInlineList::Iter item = *inlineList; item.lte(); item++ ) {
506 switch ( item->type ) {
507 case GenInlineItem::Text:
510 case GenInlineItem::Goto:
511 GOTO( ret, item->targState->id, inFinish );
513 case GenInlineItem::Call:
514 CALL( ret, item->targState->id, targState, inFinish );
516 case GenInlineItem::Next:
517 NEXT( ret, item->targState->id, inFinish );
519 case GenInlineItem::Ret:
520 RET( ret, inFinish );
522 case GenInlineItem::PChar:
525 case GenInlineItem::Char:
528 case GenInlineItem::Hold:
529 ret << P() << " = " << P() << " - 1;";
531 case GenInlineItem::Exec:
532 EXEC( ret, item, targState, inFinish );
534 case GenInlineItem::Curs:
537 case GenInlineItem::Targs:
538 ret << "(" << vCS() << ")";
540 case GenInlineItem::Entry:
541 ret << item->targState->id;
543 case GenInlineItem::GotoExpr:
544 GOTO_EXPR( ret, item, inFinish );
546 case GenInlineItem::CallExpr:
547 CALL_EXPR( ret, item, targState, inFinish );
549 case GenInlineItem::NextExpr:
550 NEXT_EXPR( ret, item, inFinish );
552 case GenInlineItem::LmSwitch:
553 LM_SWITCH( ret, item, targState, inFinish );
555 case GenInlineItem::LmSetActId:
556 SET_ACT( ret, item );
558 case GenInlineItem::LmSetTokEnd:
559 SET_TOKEND( ret, item );
561 case GenInlineItem::LmGetTokEnd:
562 GET_TOKEND( ret, item );
564 case GenInlineItem::LmInitTokStart:
565 INIT_TOKSTART( ret, item );
567 case GenInlineItem::LmInitAct:
568 INIT_ACT( ret, item );
570 case GenInlineItem::LmSetTokStart:
571 SET_TOKSTART( ret, item );
573 case GenInlineItem::SubAction:
574 SUB_ACTION( ret, item, targState, inFinish );
576 case GenInlineItem::Break:
577 BREAK( ret, targState );
584 void RubyCodeGen::EXEC( ostream &ret, GenInlineItem *item, int targState, int inFinish )
586 /* The parser gives fexec two children. The double brackets are for D
587 * code. If the inline list is a single word it will get interpreted as a
588 * C-style cast by the D compiler. */
589 ret << " begin " << P() << " = ((";
590 INLINE_LIST( ret, item->children, targState, inFinish );
591 ret << "))-1; end\n";
594 void RubyCodeGen::LM_SWITCH( ostream &ret, GenInlineItem *item,
595 int targState, int inFinish )
598 " case " << ACT() << "\n";
600 for ( GenInlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
601 /* Write the case label, the action and the case break. */
605 ret << " when " << lma->lmId << " then\n";
608 /* Write the block and close it off. */
610 INLINE_LIST( ret, lma->children, targState, inFinish );
617 void RubyCodeGen::SET_ACT( ostream &ret, GenInlineItem *item )
619 ret << ACT() << " = " << item->lmId << ";";
622 void RubyCodeGen::INIT_TOKSTART( ostream &ret, GenInlineItem *item )
624 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
627 void RubyCodeGen::INIT_ACT( ostream &ret, GenInlineItem *item )
629 ret << ACT() << " = 0\n";
632 void RubyCodeGen::SET_TOKSTART( ostream &ret, GenInlineItem *item )
634 ret << TOKSTART() << " = " << P() << "\n";
637 void RubyCodeGen::SET_TOKEND( ostream &ret, GenInlineItem *item )
639 /* The tokend action sets tokend. */
640 ret << TOKEND() << " = " << P();
641 if ( item->offset != 0 )
642 out << "+" << item->offset;
646 void RubyCodeGen::GET_TOKEND( ostream &ret, GenInlineItem *item )
651 void RubyCodeGen::SUB_ACTION( ostream &ret, GenInlineItem *item,
652 int targState, bool inFinish )
654 if ( item->children->length() > 0 ) {
655 /* Write the block and close it off. */
657 INLINE_LIST( ret, item->children, targState, inFinish );
662 int RubyCodeGen::TRANS_ACTION( RedTransAp *trans )
664 /* If there are actions, emit them. Otherwise emit zero. */
666 if ( trans->action != 0 )
667 act = trans->action->location+1;
671 ostream &RubyCodeGen::source_warning( const InputLoc &loc )
673 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
677 ostream &RubyCodeGen::source_error( const InputLoc &loc )
680 assert( sourceFileName != 0 );
681 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
685 void RubyCodeGen::finishRagelDef()
687 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
688 codeStyle == GenIpGoto || codeStyle == GenSplit )
690 /* For directly executable machines there is no required state
691 * ordering. Choose a depth-first ordering to increase the
692 * potential for fall-throughs. */
693 redFsm->depthFirstOrdering();
696 /* The frontend will do this for us, but it may be a good idea to
697 * force it if the intermediate file is edited. */
698 redFsm->sortByStateId();
701 /* Choose default transitions and the single transition. */
702 redFsm->chooseDefaultSpan();
704 /* Maybe do flat expand, otherwise choose single. */
705 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
708 redFsm->chooseSingle();
710 /* If any errors have occured in the input file then don't write anything. */
711 if ( gblErrorCount > 0 )
714 if ( codeStyle == GenSplit )
715 redFsm->partitionFsm( numSplitPartitions );
717 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
718 redFsm->setInTrans();
720 /* Anlayze Machine will find the final action reference counts, among
721 * other things. We will use these in reporting the usage
722 * of fsm directives in action code. */
725 /* Determine if we should use indicies. */
730 /* Determine if we should use indicies or not. */
731 void RubyCodeGen::calcIndexSize()
733 int sizeWithInds = 0, sizeWithoutInds = 0;
735 /* Calculate cost of using with indicies. */
736 for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
737 int totalIndex = st->outSingle.length() + st->outRange.length() +
738 (st->defTrans == 0 ? 0 : 1);
739 sizeWithInds += arrayTypeSize(redFsm->maxIndex) * totalIndex;
741 sizeWithInds += arrayTypeSize(redFsm->maxState) * redFsm->transSet.length();
742 if ( redFsm->anyActions() )
743 sizeWithInds += arrayTypeSize(redFsm->maxActionLoc) * redFsm->transSet.length();
745 /* Calculate the cost of not using indicies. */
746 for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
747 int totalIndex = st->outSingle.length() + st->outRange.length() +
748 (st->defTrans == 0 ? 0 : 1);
749 sizeWithoutInds += arrayTypeSize(redFsm->maxState) * totalIndex;
750 if ( redFsm->anyActions() )
751 sizeWithoutInds += arrayTypeSize(redFsm->maxActionLoc) * totalIndex;
754 /* If using indicies reduces the size, use them. */
755 useIndicies = sizeWithInds < sizeWithoutInds;
758 unsigned int RubyCodeGen::arrayTypeSize( unsigned long maxVal )
760 long long maxValLL = (long long) maxVal;
761 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
762 assert( arrayType != 0 );
763 return arrayType->size;
767 void RubyCodeGen::writeInit()
771 out << " " << P() << " ||= 0\n";
774 out << " " << PE() << " ||= " << DATA() << ".length\n";
777 out << " " << vCS() << " = " << START() << "\n";
779 /* If there are any calls, then the stack top needs initialization. */
780 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
781 out << " " << TOP() << " = 0\n";
783 if ( hasLongestMatch ) {
785 " " << TOKSTART() << " = " << NULL_ITEM() << "\n"
786 " " << TOKEND() << " = " << NULL_ITEM() << "\n"
787 " " << ACT() << " = 0\n";
793 void RubyCodeGen::writeExports()
795 if ( exportList.length() > 0 ) {
796 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
797 STATIC_VAR( ALPH_TYPE(), DATA_PREFIX() + "ex_" + ex->name )
798 << " = " << KEY(ex->key) << "\n";
804 void RubyCodeGen::writeStart()
806 out << START_STATE_ID();
809 void RubyCodeGen::writeFirstFinal()
811 out << FIRST_FINAL_STATE();
814 void RubyCodeGen::writeError()
816 out << ERROR_STATE();
823 * indent-tabs-mode: 1
824 * c-file-style: "bsd"