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
27 #include "rlgen-ruby.h"
28 #include "ruby-codegen.h"
31 using std::ostringstream;
37 void rubyLineDirective( ostream &out, const char *fileName, int line )
39 /* Write a comment containing line info. */
40 out << "# line " << line << " \"";
41 for ( const char *pc = fileName; *pc != 0; pc++ ) {
50 void RubyCodeGen::genLineDirective( ostream &out )
52 std::streambuf *sbuf = out.rdbuf();
53 output_filter *filter = static_cast<output_filter*>(sbuf);
54 rubyLineDirective( out, filter->fileName, filter->line + 1 );
57 string RubyCodeGen::DATA_PREFIX()
60 return FSM_NAME() + "_";
64 std::ostream &RubyCodeGen::STATIC_VAR( string type, string name )
68 " attr_accessor :" << name << "\n"
75 std::ostream &RubyCodeGen::OPEN_ARRAY( string type, string name )
79 " attr_accessor :" << name << "\n"
80 " private :" << name << ", :" << name << "=\n"
82 "self." << name << " = [\n";
86 std::ostream &RubyCodeGen::CLOSE_ARRAY()
93 string RubyCodeGen::ARR_OFF( string ptr, string offset )
95 return ptr + "[" + offset + "]";
98 string RubyCodeGen::NULL_ITEM()
104 string RubyCodeGen::P()
111 INLINE_LIST( ret, pExpr, 0, false );
117 string RubyCodeGen::PE()
124 INLINE_LIST( ret, peExpr, 0, false );
130 string RubyCodeGen::EOFV()
137 INLINE_LIST( ret, eofExpr, 0, false );
143 string RubyCodeGen::CS()
147 ret << ACCESS() << "cs";
150 INLINE_LIST( ret, csExpr, 0, false );
156 string RubyCodeGen::TOP()
160 ret << ACCESS() + "top";
163 INLINE_LIST( ret, topExpr, 0, false );
169 string RubyCodeGen::STACK()
172 if ( stackExpr == 0 )
173 ret << ACCESS() + "stack";
176 INLINE_LIST( ret, stackExpr, 0, false );
182 string RubyCodeGen::ACT()
186 ret << ACCESS() + "act";
189 INLINE_LIST( ret, actExpr, 0, false );
195 string RubyCodeGen::TOKSTART()
198 if ( tokstartExpr == 0 )
199 ret << ACCESS() + "ts";
202 INLINE_LIST( ret, tokstartExpr, 0, false );
208 string RubyCodeGen::TOKEND()
211 if ( tokendExpr == 0 )
212 ret << ACCESS() + "te";
215 INLINE_LIST( ret, tokendExpr, 0, false );
221 string RubyCodeGen::DATA()
225 ret << ACCESS() + "data";
228 INLINE_LIST( ret, dataExpr, 0, false );
234 /* Write out the fsm name. */
235 string RubyCodeGen::FSM_NAME()
241 void RubyCodeGen::ACTION( ostream &ret, GenAction *action, int targState, bool inFinish )
243 /* Write the preprocessor line info for going into the source file. */
244 rubyLineDirective( ret, sourceFileName, action->loc.line );
246 /* Write the block and close it off. */
248 INLINE_LIST( ret, action->inlineList, targState, inFinish );
250 rubyLineDirective( ret, sourceFileName, action->loc.line );
255 string RubyCodeGen::GET_WIDE_KEY()
257 if ( redFsm->anyConditions() )
263 string RubyCodeGen::GET_WIDE_KEY( RedStateAp *state )
265 if ( state->stateCondList.length() > 0 )
271 string RubyCodeGen::GET_KEY()
274 if ( getKeyExpr != 0 ) {
275 /* Emit the user supplied method of retrieving the key. */
277 INLINE_LIST( ret, getKeyExpr, 0, false );
281 /* Expression for retrieving the key, use simple dereference. */
282 ret << DATA() << "[" << P() << "]";
287 string RubyCodeGen::KEY( Key key )
290 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
293 ret << (unsigned long) key.getVal();
298 /* Write out level number of tabs. Makes the nested binary search nice
300 string RubyCodeGen::TABS( int level )
303 while ( level-- > 0 )
308 string RubyCodeGen::INT( int i )
315 void RubyCodeGen::CONDITION( ostream &ret, GenAction *condition )
318 rubyLineDirective( ret, sourceFileName, condition->loc.line );
319 INLINE_LIST( ret, condition->inlineList, 0, false );
322 /* Emit the alphabet data type. */
323 string RubyCodeGen::ALPH_TYPE()
325 string ret = keyOps->alphType->data1;
326 if ( keyOps->alphType->data2 != 0 ) {
328 ret += + keyOps->alphType->data2;
333 /* Emit the alphabet data type. */
334 string RubyCodeGen::WIDE_ALPH_TYPE()
337 if ( redFsm->maxKey <= keyOps->maxKey )
340 long long maxKeyVal = redFsm->maxKey.getLongLong();
341 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
342 assert( wideType != 0 );
344 ret = wideType->data1;
345 if ( wideType->data2 != 0 ) {
347 ret += wideType->data2;
354 string RubyCodeGen::ARRAY_TYPE( unsigned long maxVal )
356 long long maxValLL = (long long) maxVal;
357 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
358 assert( arrayType != 0 );
360 string ret = arrayType->data1;
361 if ( arrayType->data2 != 0 ) {
363 ret += arrayType->data2;
368 /* Write out the array of actions. */
369 std::ostream &RubyCodeGen::ACTIONS_ARRAY()
372 int totalActions = 0;
373 ARRAY_ITEM( INT(0), ++totalActions, false );
374 for ( ActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) {
375 /* Write out the length, which will never be the last character. */
376 ARRAY_ITEM( INT(act->key.length()), ++totalActions, false );
378 for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) {
379 ARRAY_ITEM( INT(item->value->actionId), ++totalActions, (act.last() && item.last()) );
386 void RubyCodeGen::STATE_IDS()
388 if ( redFsm->startState != 0 )
389 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
391 if ( writeFirstFinal )
392 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
395 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
399 if ( entryPointNames.length() > 0 ) {
400 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
401 STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) <<
402 " = " << entryPointIds[en.pos()] << ";\n";
408 std::ostream &RubyCodeGen::START_ARRAY_LINE()
414 std::ostream &RubyCodeGen::ARRAY_ITEM( string item, int count, bool last )
420 if ( count % IALL == 0 )
429 std::ostream &RubyCodeGen::END_ARRAY_LINE()
435 /* Emit the offset of the start state as a decimal integer. */
436 string RubyCodeGen::START_STATE_ID()
439 ret << redFsm->startState->id;
443 string RubyCodeGen::ERROR_STATE()
446 if ( redFsm->errState != 0 )
447 ret << redFsm->errState->id;
453 string RubyCodeGen::FIRST_FINAL_STATE()
456 if ( redFsm->firstFinState != 0 )
457 ret << redFsm->firstFinState->id;
459 ret << redFsm->nextStateId;
463 string RubyCodeGen::ACCESS()
466 if ( accessExpr != 0 )
467 INLINE_LIST( ret, accessExpr, 0, false );
471 /* Write out an inline tree structure. Walks the list and possibly calls out
472 * to virtual functions than handle language specific items in the tree. */
473 void RubyCodeGen::INLINE_LIST( ostream &ret, GenInlineList *inlineList,
474 int targState, bool inFinish )
476 for ( GenInlineList::Iter item = *inlineList; item.lte(); item++ ) {
477 switch ( item->type ) {
478 case GenInlineItem::Text:
481 case GenInlineItem::Goto:
482 GOTO( ret, item->targState->id, inFinish );
484 case GenInlineItem::Call:
485 CALL( ret, item->targState->id, targState, inFinish );
487 case GenInlineItem::Next:
488 NEXT( ret, item->targState->id, inFinish );
490 case GenInlineItem::Ret:
491 RET( ret, inFinish );
493 case GenInlineItem::PChar:
496 case GenInlineItem::Char:
499 case GenInlineItem::Hold:
500 ret << P() << " = " << P() << " - 1;";
502 case GenInlineItem::Exec:
503 EXEC( ret, item, targState, inFinish );
505 case GenInlineItem::Curs:
508 case GenInlineItem::Targs:
509 ret << "(" << CS() << ")";
511 case GenInlineItem::Entry:
512 ret << item->targState->id;
514 case GenInlineItem::GotoExpr:
515 GOTO_EXPR( ret, item, inFinish );
517 case GenInlineItem::CallExpr:
518 CALL_EXPR( ret, item, targState, inFinish );
520 case GenInlineItem::NextExpr:
521 NEXT_EXPR( ret, item, inFinish );
523 case GenInlineItem::LmSwitch:
524 LM_SWITCH( ret, item, targState, inFinish );
526 case GenInlineItem::LmSetActId:
527 SET_ACT( ret, item );
529 case GenInlineItem::LmSetTokEnd:
530 SET_TOKEND( ret, item );
532 case GenInlineItem::LmGetTokEnd:
533 GET_TOKEND( ret, item );
535 case GenInlineItem::LmInitTokStart:
536 INIT_TOKSTART( ret, item );
538 case GenInlineItem::LmInitAct:
539 INIT_ACT( ret, item );
541 case GenInlineItem::LmSetTokStart:
542 SET_TOKSTART( ret, item );
544 case GenInlineItem::SubAction:
545 SUB_ACTION( ret, item, targState, inFinish );
547 case GenInlineItem::Break:
548 BREAK( ret, targState );
555 void RubyCodeGen::EXEC( ostream &ret, GenInlineItem *item, int targState, int inFinish )
557 /* The parser gives fexec two children. The double brackets are for D
558 * code. If the inline list is a single word it will get interpreted as a
559 * C-style cast by the D compiler. */
560 ret << " begin " << P() << " = ((";
561 INLINE_LIST( ret, item->children, targState, inFinish );
562 ret << "))-1; end\n";
565 void RubyCodeGen::LM_SWITCH( ostream &ret, GenInlineItem *item,
566 int targState, int inFinish )
569 " case " << ACT() << "\n";
571 for ( GenInlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
572 /* Write the case label, the action and the case break. */
576 ret << " when " << lma->lmId << " then\n";
579 /* Write the block and close it off. */
581 INLINE_LIST( ret, lma->children, targState, inFinish );
588 void RubyCodeGen::SET_ACT( ostream &ret, GenInlineItem *item )
590 ret << ACT() << " = " << item->lmId << ";";
593 void RubyCodeGen::INIT_TOKSTART( ostream &ret, GenInlineItem *item )
595 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
598 void RubyCodeGen::INIT_ACT( ostream &ret, GenInlineItem *item )
600 ret << ACT() << " = 0\n";
603 void RubyCodeGen::SET_TOKSTART( ostream &ret, GenInlineItem *item )
605 ret << TOKSTART() << " = " << P() << "\n";
608 void RubyCodeGen::SET_TOKEND( ostream &ret, GenInlineItem *item )
610 /* The tokend action sets tokend. */
611 ret << TOKEND() << " = " << P();
612 if ( item->offset != 0 )
613 out << "+" << item->offset;
617 void RubyCodeGen::GET_TOKEND( ostream &ret, GenInlineItem *item )
622 void RubyCodeGen::SUB_ACTION( ostream &ret, GenInlineItem *item,
623 int targState, bool inFinish )
625 if ( item->children->length() > 0 ) {
626 /* Write the block and close it off. */
628 INLINE_LIST( ret, item->children, targState, inFinish );
633 int RubyCodeGen::TRANS_ACTION( RedTransAp *trans )
635 /* If there are actions, emit them. Otherwise emit zero. */
637 if ( trans->action != 0 )
638 act = trans->action->location+1;
642 ostream &RubyCodeGen::source_warning( const GenInputLoc &loc )
644 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
648 ostream &RubyCodeGen::source_error( const GenInputLoc &loc )
651 assert( sourceFileName != 0 );
652 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
656 void RubyCodeGen::finishRagelDef()
659 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
660 codeStyle == GenIpGoto || codeStyle == GenSplit )
662 /* For directly executable machines there is no required state
663 * ordering. Choose a depth-first ordering to increase the
664 * potential for fall-throughs. */
665 redFsm->depthFirstOrdering();
668 /* The frontend will do this for us, but it may be a good idea to
669 * force it if the intermediate file is edited. */
670 redFsm->sortByStateId();
673 /* Choose default transitions and the single transition. */
674 redFsm->chooseDefaultSpan();
676 /* Maybe do flat expand, otherwise choose single. */
677 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
680 redFsm->chooseSingle();
682 /* If any errors have occured in the input file then don't write anything. */
683 if ( gblErrorCount > 0 )
686 if ( codeStyle == GenSplit )
687 redFsm->partitionFsm( numSplitPartitions );
689 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
690 redFsm->setInTrans();
692 /* Anlayze Machine will find the final action reference counts, among
693 * other things. We will use these in reporting the usage
694 * of fsm directives in action code. */
697 /* Determine if we should use indicies. */
702 /* Determine if we should use indicies or not. */
703 void RubyCodeGen::calcIndexSize()
705 int sizeWithInds = 0, sizeWithoutInds = 0;
707 /* Calculate cost of using with indicies. */
708 for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
709 int totalIndex = st->outSingle.length() + st->outRange.length() +
710 (st->defTrans == 0 ? 0 : 1);
711 sizeWithInds += arrayTypeSize(redFsm->maxIndex) * totalIndex;
713 sizeWithInds += arrayTypeSize(redFsm->maxState) * redFsm->transSet.length();
714 if ( redFsm->anyActions() )
715 sizeWithInds += arrayTypeSize(redFsm->maxActionLoc) * redFsm->transSet.length();
717 /* Calculate the cost of not using indicies. */
718 for ( RedStateList::Iter st = redFsm->stateList; st.lte(); st++ ) {
719 int totalIndex = st->outSingle.length() + st->outRange.length() +
720 (st->defTrans == 0 ? 0 : 1);
721 sizeWithoutInds += arrayTypeSize(redFsm->maxState) * totalIndex;
722 if ( redFsm->anyActions() )
723 sizeWithoutInds += arrayTypeSize(redFsm->maxActionLoc) * totalIndex;
726 /* If using indicies reduces the size, use them. */
727 useIndicies = sizeWithInds < sizeWithoutInds;
730 unsigned int RubyCodeGen::arrayTypeSize( unsigned long maxVal )
732 long long maxValLL = (long long) maxVal;
733 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
734 assert( arrayType != 0 );
735 return arrayType->size;
739 void RubyCodeGen::writeInit()
743 out << " " << P() << " ||= 0\n";
746 out << " " << PE() << " ||= " << DATA() << ".length\n";
749 out << " " << CS() << " = " << START() << "\n";
751 /* If there are any calls, then the stack top needs initialization. */
752 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
753 out << " " << TOP() << " = 0\n";
755 if ( hasLongestMatch ) {
757 " " << TOKSTART() << " = " << NULL_ITEM() << "\n"
758 " " << TOKEND() << " = " << NULL_ITEM() << "\n"
759 " " << ACT() << " = 0\n";
765 void RubyCodeGen::writeExports()
767 if ( exportList.length() > 0 ) {
768 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
769 STATIC_VAR( ALPH_TYPE(), DATA_PREFIX() + "ex_" + ex->name )
770 << " = " << KEY(ex->key) << "\n";
779 * indent-tabs-mode: 1
780 * c-file-style: "bsd"