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 */
58 /* Target language and output style. */
59 extern CodeStyle codeStyle;
61 extern int numSplitPartitions;
64 * Callbacks invoked by the XML data parser.
68 void rubyLineDirective( ostream &out, const char *fileName, int line )
70 /* Write a comment containing line info. */
71 out << "# line " << line << " \"";
72 for ( const char *pc = fileName; *pc != 0; pc++ ) {
81 void RubyCodeGen::genLineDirective( ostream &out )
83 std::streambuf *sbuf = out.rdbuf();
84 output_filter *filter = static_cast<output_filter*>(sbuf);
85 rubyLineDirective( out, filter->fileName, filter->line + 1 );
88 string RubyCodeGen::DATA_PREFIX()
91 return FSM_NAME() + "_";
95 std::ostream &RubyCodeGen::STATIC_VAR( string type, string name )
99 " attr_accessor :" << name << "\n"
106 std::ostream &RubyCodeGen::OPEN_ARRAY( string type, string name )
110 " attr_accessor :" << name << "\n"
111 " private :" << name << ", :" << name << "=\n"
113 "self." << name << " = [\n";
117 std::ostream &RubyCodeGen::CLOSE_ARRAY()
124 string RubyCodeGen::ARR_OFF( string ptr, string offset )
126 return ptr + "[" + offset + "]";
129 string RubyCodeGen::NULL_ITEM()
135 string RubyCodeGen::P()
142 INLINE_LIST( ret, pExpr, 0, false );
148 string RubyCodeGen::PE()
155 INLINE_LIST( ret, peExpr, 0, false );
161 string RubyCodeGen::EOFV()
168 INLINE_LIST( ret, eofExpr, 0, false );
174 string RubyCodeGen::CS()
178 ret << ACCESS() << "cs";
181 INLINE_LIST( ret, csExpr, 0, false );
187 string RubyCodeGen::TOP()
191 ret << ACCESS() + "top";
194 INLINE_LIST( ret, topExpr, 0, false );
200 string RubyCodeGen::STACK()
203 if ( stackExpr == 0 )
204 ret << ACCESS() + "stack";
207 INLINE_LIST( ret, stackExpr, 0, false );
213 string RubyCodeGen::ACT()
217 ret << ACCESS() + "act";
220 INLINE_LIST( ret, actExpr, 0, false );
226 string RubyCodeGen::TOKSTART()
229 if ( tokstartExpr == 0 )
230 ret << ACCESS() + "ts";
233 INLINE_LIST( ret, tokstartExpr, 0, false );
239 string RubyCodeGen::TOKEND()
242 if ( tokendExpr == 0 )
243 ret << ACCESS() + "te";
246 INLINE_LIST( ret, tokendExpr, 0, false );
252 string RubyCodeGen::DATA()
256 ret << ACCESS() + "data";
259 INLINE_LIST( ret, dataExpr, 0, false );
265 /* Write out the fsm name. */
266 string RubyCodeGen::FSM_NAME()
272 void RubyCodeGen::ACTION( ostream &ret, GenAction *action, int targState, bool inFinish )
274 /* Write the preprocessor line info for going into the source file. */
275 rubyLineDirective( ret, sourceFileName, action->loc.line );
277 /* Write the block and close it off. */
279 INLINE_LIST( ret, action->inlineList, targState, inFinish );
281 rubyLineDirective( ret, sourceFileName, action->loc.line );
286 string RubyCodeGen::GET_WIDE_KEY()
288 if ( redFsm->anyConditions() )
294 string RubyCodeGen::GET_WIDE_KEY( RedStateAp *state )
296 if ( state->stateCondList.length() > 0 )
302 string RubyCodeGen::GET_KEY()
305 if ( getKeyExpr != 0 ) {
306 /* Emit the user supplied method of retrieving the key. */
308 INLINE_LIST( ret, getKeyExpr, 0, false );
312 /* Expression for retrieving the key, use simple dereference. */
313 ret << DATA() << "[" << P() << "]";
318 string RubyCodeGen::KEY( Key key )
321 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
324 ret << (unsigned long) key.getVal();
329 /* Write out level number of tabs. Makes the nested binary search nice
331 string RubyCodeGen::TABS( int level )
334 while ( level-- > 0 )
339 string RubyCodeGen::INT( int i )
346 void RubyCodeGen::CONDITION( ostream &ret, GenAction *condition )
349 rubyLineDirective( ret, sourceFileName, condition->loc.line );
350 INLINE_LIST( ret, condition->inlineList, 0, false );
353 /* Emit the alphabet data type. */
354 string RubyCodeGen::ALPH_TYPE()
356 string ret = keyOps->alphType->data1;
357 if ( keyOps->alphType->data2 != 0 ) {
359 ret += + keyOps->alphType->data2;
364 /* Emit the alphabet data type. */
365 string RubyCodeGen::WIDE_ALPH_TYPE()
368 if ( redFsm->maxKey <= keyOps->maxKey )
371 long long maxKeyVal = redFsm->maxKey.getLongLong();
372 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
373 assert( wideType != 0 );
375 ret = wideType->data1;
376 if ( wideType->data2 != 0 ) {
378 ret += wideType->data2;
385 string RubyCodeGen::ARRAY_TYPE( unsigned long maxVal )
387 long long maxValLL = (long long) maxVal;
388 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
389 assert( arrayType != 0 );
391 string ret = arrayType->data1;
392 if ( arrayType->data2 != 0 ) {
394 ret += arrayType->data2;
399 /* Write out the array of actions. */
400 std::ostream &RubyCodeGen::ACTIONS_ARRAY()
403 int totalActions = 0;
404 ARRAY_ITEM( INT(0), ++totalActions, false );
405 for ( GenActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) {
406 /* Write out the length, which will never be the last character. */
407 ARRAY_ITEM( INT(act->key.length()), ++totalActions, false );
409 for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) {
410 ARRAY_ITEM( INT(item->value->actionId), ++totalActions, (act.last() && item.last()) );
417 void RubyCodeGen::STATE_IDS()
419 if ( redFsm->startState != 0 )
420 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
423 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
426 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
430 if ( entryPointNames.length() > 0 ) {
431 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
432 STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) <<
433 " = " << entryPointIds[en.pos()] << ";\n";
439 std::ostream &RubyCodeGen::START_ARRAY_LINE()
445 std::ostream &RubyCodeGen::ARRAY_ITEM( string item, int count, bool last )
451 if ( count % IALL == 0 )
460 std::ostream &RubyCodeGen::END_ARRAY_LINE()
466 /* Emit the offset of the start state as a decimal integer. */
467 string RubyCodeGen::START_STATE_ID()
470 ret << redFsm->startState->id;
474 string RubyCodeGen::ERROR_STATE()
477 if ( redFsm->errState != 0 )
478 ret << redFsm->errState->id;
484 string RubyCodeGen::FIRST_FINAL_STATE()
487 if ( redFsm->firstFinState != 0 )
488 ret << redFsm->firstFinState->id;
490 ret << redFsm->nextStateId;
494 string RubyCodeGen::ACCESS()
497 if ( accessExpr != 0 )
498 INLINE_LIST( ret, accessExpr, 0, false );
502 /* Write out an inline tree structure. Walks the list and possibly calls out
503 * to virtual functions than handle language specific items in the tree. */
504 void RubyCodeGen::INLINE_LIST( ostream &ret, GenInlineList *inlineList,
505 int targState, bool inFinish )
507 for ( GenInlineList::Iter item = *inlineList; item.lte(); item++ ) {
508 switch ( item->type ) {
509 case GenInlineItem::Text:
512 case GenInlineItem::Goto:
513 GOTO( ret, item->targState->id, inFinish );
515 case GenInlineItem::Call:
516 CALL( ret, item->targState->id, targState, inFinish );
518 case GenInlineItem::Next:
519 NEXT( ret, item->targState->id, inFinish );
521 case GenInlineItem::Ret:
522 RET( ret, inFinish );
524 case GenInlineItem::PChar:
527 case GenInlineItem::Char:
530 case GenInlineItem::Hold:
531 ret << P() << " = " << P() << " - 1;";
533 case GenInlineItem::Exec:
534 EXEC( ret, item, targState, inFinish );
536 case GenInlineItem::Curs:
539 case GenInlineItem::Targs:
540 ret << "(" << CS() << ")";
542 case GenInlineItem::Entry:
543 ret << item->targState->id;
545 case GenInlineItem::GotoExpr:
546 GOTO_EXPR( ret, item, inFinish );
548 case GenInlineItem::CallExpr:
549 CALL_EXPR( ret, item, targState, inFinish );
551 case GenInlineItem::NextExpr:
552 NEXT_EXPR( ret, item, inFinish );
554 case GenInlineItem::LmSwitch:
555 LM_SWITCH( ret, item, targState, inFinish );
557 case GenInlineItem::LmSetActId:
558 SET_ACT( ret, item );
560 case GenInlineItem::LmSetTokEnd:
561 SET_TOKEND( ret, item );
563 case GenInlineItem::LmGetTokEnd:
564 GET_TOKEND( ret, item );
566 case GenInlineItem::LmInitTokStart:
567 INIT_TOKSTART( ret, item );
569 case GenInlineItem::LmInitAct:
570 INIT_ACT( ret, item );
572 case GenInlineItem::LmSetTokStart:
573 SET_TOKSTART( ret, item );
575 case GenInlineItem::SubAction:
576 SUB_ACTION( ret, item, targState, inFinish );
578 case GenInlineItem::Break:
579 BREAK( ret, targState );
586 void RubyCodeGen::EXEC( ostream &ret, GenInlineItem *item, int targState, int inFinish )
588 /* The parser gives fexec two children. The double brackets are for D
589 * code. If the inline list is a single word it will get interpreted as a
590 * C-style cast by the D compiler. */
591 ret << " begin " << P() << " = ((";
592 INLINE_LIST( ret, item->children, targState, inFinish );
593 ret << "))-1; end\n";
596 void RubyCodeGen::LM_SWITCH( ostream &ret, GenInlineItem *item,
597 int targState, int inFinish )
600 " case " << ACT() << "\n";
602 for ( GenInlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
603 /* Write the case label, the action and the case break. */
607 ret << " when " << lma->lmId << " then\n";
610 /* Write the block and close it off. */
612 INLINE_LIST( ret, lma->children, targState, inFinish );
619 void RubyCodeGen::SET_ACT( ostream &ret, GenInlineItem *item )
621 ret << ACT() << " = " << item->lmId << ";";
624 void RubyCodeGen::INIT_TOKSTART( ostream &ret, GenInlineItem *item )
626 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
629 void RubyCodeGen::INIT_ACT( ostream &ret, GenInlineItem *item )
631 ret << ACT() << " = 0\n";
634 void RubyCodeGen::SET_TOKSTART( ostream &ret, GenInlineItem *item )
636 ret << TOKSTART() << " = " << P() << "\n";
639 void RubyCodeGen::SET_TOKEND( ostream &ret, GenInlineItem *item )
641 /* The tokend action sets tokend. */
642 ret << TOKEND() << " = " << P();
643 if ( item->offset != 0 )
644 out << "+" << item->offset;
648 void RubyCodeGen::GET_TOKEND( ostream &ret, GenInlineItem *item )
653 void RubyCodeGen::SUB_ACTION( ostream &ret, GenInlineItem *item,
654 int targState, bool inFinish )
656 if ( item->children->length() > 0 ) {
657 /* Write the block and close it off. */
659 INLINE_LIST( ret, item->children, targState, inFinish );
664 int RubyCodeGen::TRANS_ACTION( RedTransAp *trans )
666 /* If there are actions, emit them. Otherwise emit zero. */
668 if ( trans->action != 0 )
669 act = trans->action->location+1;
673 ostream &RubyCodeGen::source_warning( const InputLoc &loc )
675 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
679 ostream &RubyCodeGen::source_error( const InputLoc &loc )
682 assert( sourceFileName != 0 );
683 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
687 void RubyCodeGen::finishRagelDef()
689 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
690 codeStyle == GenIpGoto || codeStyle == GenSplit )
692 /* For directly executable machines there is no required state
693 * ordering. Choose a depth-first ordering to increase the
694 * potential for fall-throughs. */
695 redFsm->depthFirstOrdering();
698 /* The frontend will do this for us, but it may be a good idea to
699 * force it if the intermediate file is edited. */
700 redFsm->sortByStateId();
703 /* Choose default transitions and the single transition. */
704 redFsm->chooseDefaultSpan();
706 /* Maybe do flat expand, otherwise choose single. */
707 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
710 redFsm->chooseSingle();
712 /* If any errors have occured in the input file then don't write anything. */
713 if ( gblErrorCount > 0 )
716 if ( codeStyle == GenSplit )
717 redFsm->partitionFsm( numSplitPartitions );
719 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
720 redFsm->setInTrans();
722 /* Anlayze Machine will find the final action reference counts, among
723 * other things. We will use these in reporting the usage
724 * of fsm directives in action code. */
727 /* Determine if we should use indicies. */
732 /* Determine if we should use indicies or not. */
733 void RubyCodeGen::calcIndexSize()
735 int sizeWithInds = 0, sizeWithoutInds = 0;
737 /* Calculate cost of using with indicies. */
738 for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
739 int totalIndex = st->outSingle.length() + st->outRange.length() +
740 (st->defTrans == 0 ? 0 : 1);
741 sizeWithInds += arrayTypeSize(redFsm->maxIndex) * totalIndex;
743 sizeWithInds += arrayTypeSize(redFsm->maxState) * redFsm->transSet.length();
744 if ( redFsm->anyActions() )
745 sizeWithInds += arrayTypeSize(redFsm->maxActionLoc) * redFsm->transSet.length();
747 /* Calculate the cost of not using indicies. */
748 for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
749 int totalIndex = st->outSingle.length() + st->outRange.length() +
750 (st->defTrans == 0 ? 0 : 1);
751 sizeWithoutInds += arrayTypeSize(redFsm->maxState) * totalIndex;
752 if ( redFsm->anyActions() )
753 sizeWithoutInds += arrayTypeSize(redFsm->maxActionLoc) * totalIndex;
756 /* If using indicies reduces the size, use them. */
757 useIndicies = sizeWithInds < sizeWithoutInds;
760 unsigned int RubyCodeGen::arrayTypeSize( unsigned long maxVal )
762 long long maxValLL = (long long) maxVal;
763 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
764 assert( arrayType != 0 );
765 return arrayType->size;
769 void RubyCodeGen::writeInit()
773 out << " " << P() << " ||= 0\n";
776 out << " " << PE() << " ||= " << DATA() << ".length\n";
779 out << " " << CS() << " = " << START() << "\n";
781 /* If there are any calls, then the stack top needs initialization. */
782 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
783 out << " " << TOP() << " = 0\n";
785 if ( hasLongestMatch ) {
787 " " << TOKSTART() << " = " << NULL_ITEM() << "\n"
788 " " << TOKEND() << " = " << NULL_ITEM() << "\n"
789 " " << ACT() << " = 0\n";
795 void RubyCodeGen::writeExports()
797 if ( exportList.length() > 0 ) {
798 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
799 STATIC_VAR( ALPH_TYPE(), DATA_PREFIX() + "ex_" + ex->name )
800 << " = " << KEY(ex->key) << "\n";
806 void RubyCodeGen::writeStart()
808 out << START_STATE_ID();
811 void RubyCodeGen::writeFirstFinal()
813 out << FIRST_FINAL_STATE();
816 void RubyCodeGen::writeError()
818 out << ERROR_STATE();
825 * indent-tabs-mode: 1
826 * c-file-style: "bsd"