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::EOFV()
167 INLINE_LIST( ret, eofExpr, 0, false );
173 string RubyCodeGen::CS()
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, sourceFileName, action->loc.line );
276 /* Write the block and close it off. */
278 INLINE_LIST( ret, action->inlineList, targState, inFinish );
280 rubyLineDirective( ret, sourceFileName, action->loc.line );
285 string RubyCodeGen::GET_WIDE_KEY()
287 if ( redFsm->anyConditions() )
293 string RubyCodeGen::GET_WIDE_KEY( RedStateAp *state )
295 if ( state->stateCondList.length() > 0 )
301 string RubyCodeGen::GET_KEY()
304 if ( getKeyExpr != 0 ) {
305 /* Emit the user supplied method of retrieving the key. */
307 INLINE_LIST( ret, getKeyExpr, 0, false );
311 /* Expression for retrieving the key, use simple dereference. */
312 ret << DATA() << "[" << P() << "]";
317 string RubyCodeGen::KEY( Key key )
320 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
323 ret << (unsigned long) key.getVal();
328 /* Write out level number of tabs. Makes the nested binary search nice
330 string RubyCodeGen::TABS( int level )
333 while ( level-- > 0 )
338 string RubyCodeGen::INT( int i )
345 void RubyCodeGen::CONDITION( ostream &ret, GenAction *condition )
348 rubyLineDirective( ret, sourceFileName, condition->loc.line );
349 INLINE_LIST( ret, condition->inlineList, 0, false );
352 /* Emit the alphabet data type. */
353 string RubyCodeGen::ALPH_TYPE()
355 string ret = keyOps->alphType->data1;
356 if ( keyOps->alphType->data2 != 0 ) {
358 ret += + keyOps->alphType->data2;
363 /* Emit the alphabet data type. */
364 string RubyCodeGen::WIDE_ALPH_TYPE()
367 if ( redFsm->maxKey <= keyOps->maxKey )
370 long long maxKeyVal = redFsm->maxKey.getLongLong();
371 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
372 assert( wideType != 0 );
374 ret = wideType->data1;
375 if ( wideType->data2 != 0 ) {
377 ret += wideType->data2;
384 string RubyCodeGen::ARRAY_TYPE( unsigned long maxVal )
386 long long maxValLL = (long long) maxVal;
387 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
388 assert( arrayType != 0 );
390 string ret = arrayType->data1;
391 if ( arrayType->data2 != 0 ) {
393 ret += arrayType->data2;
398 /* Write out the array of actions. */
399 std::ostream &RubyCodeGen::ACTIONS_ARRAY()
402 int totalActions = 0;
403 ARRAY_ITEM( INT(0), ++totalActions, false );
404 for ( GenActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) {
405 /* Write out the length, which will never be the last character. */
406 ARRAY_ITEM( INT(act->key.length()), ++totalActions, false );
408 for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) {
409 ARRAY_ITEM( INT(item->value->actionId), ++totalActions, (act.last() && item.last()) );
416 void RubyCodeGen::STATE_IDS()
418 if ( redFsm->startState != 0 )
419 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
422 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
425 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
429 if ( entryPointNames.length() > 0 ) {
430 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
431 STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) <<
432 " = " << entryPointIds[en.pos()] << ";\n";
438 std::ostream &RubyCodeGen::START_ARRAY_LINE()
444 std::ostream &RubyCodeGen::ARRAY_ITEM( string item, int count, bool last )
450 if ( count % IALL == 0 )
459 std::ostream &RubyCodeGen::END_ARRAY_LINE()
465 /* Emit the offset of the start state as a decimal integer. */
466 string RubyCodeGen::START_STATE_ID()
469 ret << redFsm->startState->id;
473 string RubyCodeGen::ERROR_STATE()
476 if ( redFsm->errState != 0 )
477 ret << redFsm->errState->id;
483 string RubyCodeGen::FIRST_FINAL_STATE()
486 if ( redFsm->firstFinState != 0 )
487 ret << redFsm->firstFinState->id;
489 ret << redFsm->nextStateId;
493 string RubyCodeGen::ACCESS()
496 if ( accessExpr != 0 )
497 INLINE_LIST( ret, accessExpr, 0, false );
501 /* Write out an inline tree structure. Walks the list and possibly calls out
502 * to virtual functions than handle language specific items in the tree. */
503 void RubyCodeGen::INLINE_LIST( ostream &ret, GenInlineList *inlineList,
504 int targState, bool inFinish )
506 for ( GenInlineList::Iter item = *inlineList; item.lte(); item++ ) {
507 switch ( item->type ) {
508 case GenInlineItem::Text:
511 case GenInlineItem::Goto:
512 GOTO( ret, item->targState->id, inFinish );
514 case GenInlineItem::Call:
515 CALL( ret, item->targState->id, targState, inFinish );
517 case GenInlineItem::Next:
518 NEXT( ret, item->targState->id, inFinish );
520 case GenInlineItem::Ret:
521 RET( ret, inFinish );
523 case GenInlineItem::PChar:
526 case GenInlineItem::Char:
529 case GenInlineItem::Hold:
530 ret << P() << " = " << P() << " - 1;";
532 case GenInlineItem::Exec:
533 EXEC( ret, item, targState, inFinish );
535 case GenInlineItem::Curs:
538 case GenInlineItem::Targs:
539 ret << "(" << CS() << ")";
541 case GenInlineItem::Entry:
542 ret << item->targState->id;
544 case GenInlineItem::GotoExpr:
545 GOTO_EXPR( ret, item, inFinish );
547 case GenInlineItem::CallExpr:
548 CALL_EXPR( ret, item, targState, inFinish );
550 case GenInlineItem::NextExpr:
551 NEXT_EXPR( ret, item, inFinish );
553 case GenInlineItem::LmSwitch:
554 LM_SWITCH( ret, item, targState, inFinish );
556 case GenInlineItem::LmSetActId:
557 SET_ACT( ret, item );
559 case GenInlineItem::LmSetTokEnd:
560 SET_TOKEND( ret, item );
562 case GenInlineItem::LmGetTokEnd:
563 GET_TOKEND( ret, item );
565 case GenInlineItem::LmInitTokStart:
566 INIT_TOKSTART( ret, item );
568 case GenInlineItem::LmInitAct:
569 INIT_ACT( ret, item );
571 case GenInlineItem::LmSetTokStart:
572 SET_TOKSTART( ret, item );
574 case GenInlineItem::SubAction:
575 SUB_ACTION( ret, item, targState, inFinish );
577 case GenInlineItem::Break:
578 BREAK( ret, targState );
585 void RubyCodeGen::EXEC( ostream &ret, GenInlineItem *item, int targState, int inFinish )
587 /* The parser gives fexec two children. The double brackets are for D
588 * code. If the inline list is a single word it will get interpreted as a
589 * C-style cast by the D compiler. */
590 ret << " begin " << P() << " = ((";
591 INLINE_LIST( ret, item->children, targState, inFinish );
592 ret << "))-1; end\n";
595 void RubyCodeGen::LM_SWITCH( ostream &ret, GenInlineItem *item,
596 int targState, int inFinish )
599 " case " << ACT() << "\n";
601 for ( GenInlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
602 /* Write the case label, the action and the case break. */
606 ret << " when " << lma->lmId << " then\n";
609 /* Write the block and close it off. */
611 INLINE_LIST( ret, lma->children, targState, inFinish );
618 void RubyCodeGen::SET_ACT( ostream &ret, GenInlineItem *item )
620 ret << ACT() << " = " << item->lmId << ";";
623 void RubyCodeGen::INIT_TOKSTART( ostream &ret, GenInlineItem *item )
625 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
628 void RubyCodeGen::INIT_ACT( ostream &ret, GenInlineItem *item )
630 ret << ACT() << " = 0\n";
633 void RubyCodeGen::SET_TOKSTART( ostream &ret, GenInlineItem *item )
635 ret << TOKSTART() << " = " << P() << "\n";
638 void RubyCodeGen::SET_TOKEND( ostream &ret, GenInlineItem *item )
640 /* The tokend action sets tokend. */
641 ret << TOKEND() << " = " << P();
642 if ( item->offset != 0 )
643 out << "+" << item->offset;
647 void RubyCodeGen::GET_TOKEND( ostream &ret, GenInlineItem *item )
652 void RubyCodeGen::SUB_ACTION( ostream &ret, GenInlineItem *item,
653 int targState, bool inFinish )
655 if ( item->children->length() > 0 ) {
656 /* Write the block and close it off. */
658 INLINE_LIST( ret, item->children, targState, inFinish );
663 int RubyCodeGen::TRANS_ACTION( RedTransAp *trans )
665 /* If there are actions, emit them. Otherwise emit zero. */
667 if ( trans->action != 0 )
668 act = trans->action->location+1;
672 ostream &RubyCodeGen::source_warning( const InputLoc &loc )
674 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
678 ostream &RubyCodeGen::source_error( const InputLoc &loc )
681 assert( sourceFileName != 0 );
682 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
686 void RubyCodeGen::finishRagelDef()
688 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
689 codeStyle == GenIpGoto || codeStyle == GenSplit )
691 /* For directly executable machines there is no required state
692 * ordering. Choose a depth-first ordering to increase the
693 * potential for fall-throughs. */
694 redFsm->depthFirstOrdering();
697 /* The frontend will do this for us, but it may be a good idea to
698 * force it if the intermediate file is edited. */
699 redFsm->sortByStateId();
702 /* Choose default transitions and the single transition. */
703 redFsm->chooseDefaultSpan();
705 /* Maybe do flat expand, otherwise choose single. */
706 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
709 redFsm->chooseSingle();
711 /* If any errors have occured in the input file then don't write anything. */
712 if ( gblErrorCount > 0 )
715 if ( codeStyle == GenSplit )
716 redFsm->partitionFsm( numSplitPartitions );
718 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
719 redFsm->setInTrans();
721 /* Anlayze Machine will find the final action reference counts, among
722 * other things. We will use these in reporting the usage
723 * of fsm directives in action code. */
726 /* Determine if we should use indicies. */
731 /* Determine if we should use indicies or not. */
732 void RubyCodeGen::calcIndexSize()
734 int sizeWithInds = 0, sizeWithoutInds = 0;
736 /* Calculate cost of using with indicies. */
737 for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
738 int totalIndex = st->outSingle.length() + st->outRange.length() +
739 (st->defTrans == 0 ? 0 : 1);
740 sizeWithInds += arrayTypeSize(redFsm->maxIndex) * totalIndex;
742 sizeWithInds += arrayTypeSize(redFsm->maxState) * redFsm->transSet.length();
743 if ( redFsm->anyActions() )
744 sizeWithInds += arrayTypeSize(redFsm->maxActionLoc) * redFsm->transSet.length();
746 /* Calculate the cost of not using indicies. */
747 for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
748 int totalIndex = st->outSingle.length() + st->outRange.length() +
749 (st->defTrans == 0 ? 0 : 1);
750 sizeWithoutInds += arrayTypeSize(redFsm->maxState) * totalIndex;
751 if ( redFsm->anyActions() )
752 sizeWithoutInds += arrayTypeSize(redFsm->maxActionLoc) * totalIndex;
755 /* If using indicies reduces the size, use them. */
756 useIndicies = sizeWithInds < sizeWithoutInds;
759 unsigned int RubyCodeGen::arrayTypeSize( unsigned long maxVal )
761 long long maxValLL = (long long) maxVal;
762 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
763 assert( arrayType != 0 );
764 return arrayType->size;
768 void RubyCodeGen::writeInit()
772 out << " " << P() << " ||= 0\n";
775 out << " " << PE() << " ||= " << DATA() << ".length\n";
778 out << " " << CS() << " = " << START() << "\n";
780 /* If there are any calls, then the stack top needs initialization. */
781 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
782 out << " " << TOP() << " = 0\n";
784 if ( hasLongestMatch ) {
786 " " << TOKSTART() << " = " << NULL_ITEM() << "\n"
787 " " << TOKEND() << " = " << NULL_ITEM() << "\n"
788 " " << ACT() << " = 0\n";
794 void RubyCodeGen::writeExports()
796 if ( exportList.length() > 0 ) {
797 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
798 STATIC_VAR( ALPH_TYPE(), DATA_PREFIX() + "ex_" + ex->name )
799 << " = " << KEY(ex->key) << "\n";
805 void RubyCodeGen::writeStart()
807 out << START_STATE_ID();
810 void RubyCodeGen::writeFirstFinal()
812 out << FIRST_FINAL_STATE();
815 void RubyCodeGen::writeError()
817 out << ERROR_STATE();
824 * indent-tabs-mode: 1
825 * c-file-style: "bsd"