2 * Copyright 2001-2006 Adrian Thurston <thurston@cs.queensu.ca>
3 * 2004 Erich Ocean <eric.ocean@ampede.com>
4 * 2005 Alan West <alan@alanz.com>
7 /* This file is part of Ragel.
9 * Ragel is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * Ragel is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with Ragel; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "fsmcodegen.h"
34 using std::ostringstream;
39 void lineDirective( ostream &out, char *fileName, int line )
41 if ( noLineDirectives )
44 /* Write the preprocessor line info for to the input file. */
45 out << "#line " << line << " \"";
46 for ( char *pc = fileName; *pc != 0; pc++ ) {
54 if ( noLineDirectives )
60 void genLineDirective( ostream &out )
62 std::streambuf *sbuf = out.rdbuf();
63 output_filter *filter = static_cast<output_filter*>(sbuf);
64 lineDirective( out, filter->fileName, filter->line + 1 );
68 /* Init code gen with in parameters. */
69 FsmCodeGen::FsmCodeGen( ostream &out )
75 unsigned int FsmCodeGen::arrayTypeSize( unsigned long maxVal )
77 long long maxValLL = (long long) maxVal;
78 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
79 assert( arrayType != 0 );
80 return arrayType->size;
83 string FsmCodeGen::ARRAY_TYPE( unsigned long maxVal )
85 long long maxValLL = (long long) maxVal;
86 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
87 assert( arrayType != 0 );
89 string ret = arrayType->data1;
90 if ( arrayType->data2 != 0 ) {
92 ret += arrayType->data2;
98 /* Write out the fsm name. */
99 string FsmCodeGen::FSM_NAME()
104 /* Emit the offset of the start state as a decimal integer. */
105 string FsmCodeGen::START_STATE_ID()
108 ret << redFsm->startState->id;
112 /* Write out the array of actions. */
113 std::ostream &FsmCodeGen::ACTIONS_ARRAY()
116 int totalActions = 1;
117 for ( ActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) {
118 /* Write out the length, which will never be the last character. */
119 out << act->key.length() << ", ";
120 /* Put in a line break every 8 */
121 if ( totalActions++ % 8 == 7 )
124 for ( ActionTable::Iter item = act->key; item.lte(); item++ ) {
125 out << item->value->actionId;
126 if ( ! (act.last() && item.last()) )
129 /* Put in a line break every 8 */
130 if ( totalActions++ % 8 == 7 )
139 string FsmCodeGen::ACCESS()
142 if ( accessExpr != 0 )
143 INLINE_LIST( ret, accessExpr, 0, false );
148 string FsmCodeGen::P()
155 INLINE_LIST( ret, pExpr, 0, false );
161 string FsmCodeGen::PE()
168 INLINE_LIST( ret, peExpr, 0, false );
174 string FsmCodeGen::CS()
178 ret << ACCESS() << "cs";
180 /* Emit the user supplied method of retrieving the key. */
182 INLINE_LIST( ret, csExpr, 0, false );
188 string FsmCodeGen::TOP()
192 ret << ACCESS() + "top";
195 INLINE_LIST( ret, topExpr, 0, false );
201 string FsmCodeGen::STACK()
204 if ( stackExpr == 0 )
205 ret << ACCESS() + "stack";
208 INLINE_LIST( ret, stackExpr, 0, false );
214 string FsmCodeGen::ACT()
218 ret << ACCESS() + "act";
221 INLINE_LIST( ret, actExpr, 0, false );
227 string FsmCodeGen::TOKSTART()
230 if ( tokstartExpr == 0 )
231 ret << ACCESS() + "tokstart";
234 INLINE_LIST( ret, tokstartExpr, 0, false );
240 string FsmCodeGen::TOKEND()
243 if ( tokendExpr == 0 )
244 ret << ACCESS() + "tokend";
247 INLINE_LIST( ret, tokendExpr, 0, false );
253 string FsmCodeGen::GET_WIDE_KEY()
255 if ( redFsm->anyConditions() )
261 string FsmCodeGen::GET_WIDE_KEY( RedStateAp *state )
263 if ( state->stateCondList.length() > 0 )
269 string FsmCodeGen::GET_KEY()
272 if ( getKeyExpr != 0 ) {
273 /* Emit the user supplied method of retrieving the key. */
275 INLINE_LIST( ret, getKeyExpr, 0, false );
279 /* Expression for retrieving the key, use simple dereference. */
280 ret << "(*" << P() << ")";
285 /* Write out level number of tabs. Makes the nested binary search nice
287 string FsmCodeGen::TABS( int level )
290 while ( level-- > 0 )
295 /* Write out a key from the fsm code gen. Depends on wether or not the key is
297 string FsmCodeGen::KEY( Key key )
300 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
303 ret << (unsigned long) key.getVal() << 'u';
307 void FsmCodeGen::EXEC( ostream &ret, InlineItem *item, int targState, int inFinish )
309 /* The parser gives fexec two children. The double brackets are for D
310 * code. If the inline list is a single word it will get interpreted as a
311 * C-style cast by the D compiler. */
312 ret << "{" << P() << " = ((";
313 INLINE_LIST( ret, item->children, targState, inFinish );
317 void FsmCodeGen::EXECTE( ostream &ret, InlineItem *item, int targState, int inFinish )
319 /* Tokend version of exec. */
321 /* The parser gives fexec two children. The double brackets are for D
322 * code. If the inline list is a single word it will get interpreted as a
323 * C-style cast by the D compiler. */
324 ret << "{" << TOKEND() << " = ((";
325 INLINE_LIST( ret, item->children, targState, inFinish );
330 void FsmCodeGen::LM_SWITCH( ostream &ret, InlineItem *item,
331 int targState, int inFinish )
334 " switch( " << ACT() << " ) {\n";
336 /* If the switch handles error then we also forced the error state. It
338 if ( item->handlesError ) {
339 ret << " case 0: " << TOKEND() << " = " << TOKSTART() << "; ";
340 GOTO( ret, redFsm->errState->id, inFinish );
344 for ( InlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
345 /* Write the case label, the action and the case break. */
346 ret << " case " << lma->lmId << ":\n";
348 /* Write the block and close it off. */
350 INLINE_LIST( ret, lma->children, targState, inFinish );
355 /* Default required for D code. */
362 void FsmCodeGen::SET_ACT( ostream &ret, InlineItem *item )
364 ret << ACT() << " = " << item->lmId << ";";
367 void FsmCodeGen::SET_TOKEND( ostream &ret, InlineItem *item )
369 /* The tokend action sets tokend. */
370 ret << TOKEND() << " = " << P();
371 if ( item->offset != 0 )
372 out << "+" << item->offset;
376 void FsmCodeGen::GET_TOKEND( ostream &ret, InlineItem *item )
381 void FsmCodeGen::INIT_TOKSTART( ostream &ret, InlineItem *item )
383 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
386 void FsmCodeGen::INIT_ACT( ostream &ret, InlineItem *item )
388 ret << ACT() << " = 0;";
391 void FsmCodeGen::SET_TOKSTART( ostream &ret, InlineItem *item )
393 ret << TOKSTART() << " = " << P() << ";";
396 void FsmCodeGen::SUB_ACTION( ostream &ret, InlineItem *item,
397 int targState, bool inFinish )
399 if ( item->children->length() > 0 ) {
400 /* Write the block and close it off. */
402 INLINE_LIST( ret, item->children, targState, inFinish );
408 /* Write out an inline tree structure. Walks the list and possibly calls out
409 * to virtual functions than handle language specific items in the tree. */
410 void FsmCodeGen::INLINE_LIST( ostream &ret, InlineList *inlineList,
411 int targState, bool inFinish )
413 for ( InlineList::Iter item = *inlineList; item.lte(); item++ ) {
414 switch ( item->type ) {
415 case InlineItem::Text:
418 case InlineItem::Goto:
419 GOTO( ret, item->targState->id, inFinish );
421 case InlineItem::Call:
422 CALL( ret, item->targState->id, targState, inFinish );
424 case InlineItem::Next:
425 NEXT( ret, item->targState->id, inFinish );
427 case InlineItem::Ret:
428 RET( ret, inFinish );
430 case InlineItem::PChar:
433 case InlineItem::Char:
436 case InlineItem::Hold:
439 case InlineItem::Exec:
440 EXEC( ret, item, targState, inFinish );
442 case InlineItem::HoldTE:
443 ret << TOKEND() << "--;";
445 case InlineItem::ExecTE:
446 EXECTE( ret, item, targState, inFinish );
448 case InlineItem::Curs:
449 CURS( ret, inFinish );
451 case InlineItem::Targs:
452 TARGS( ret, inFinish, targState );
454 case InlineItem::Entry:
455 ret << item->targState->id;
457 case InlineItem::GotoExpr:
458 GOTO_EXPR( ret, item, inFinish );
460 case InlineItem::CallExpr:
461 CALL_EXPR( ret, item, targState, inFinish );
463 case InlineItem::NextExpr:
464 NEXT_EXPR( ret, item, inFinish );
466 case InlineItem::LmSwitch:
467 LM_SWITCH( ret, item, targState, inFinish );
469 case InlineItem::LmSetActId:
470 SET_ACT( ret, item );
472 case InlineItem::LmSetTokEnd:
473 SET_TOKEND( ret, item );
475 case InlineItem::LmGetTokEnd:
476 GET_TOKEND( ret, item );
478 case InlineItem::LmInitTokStart:
479 INIT_TOKSTART( ret, item );
481 case InlineItem::LmInitAct:
482 INIT_ACT( ret, item );
484 case InlineItem::LmSetTokStart:
485 SET_TOKSTART( ret, item );
487 case InlineItem::SubAction:
488 SUB_ACTION( ret, item, targState, inFinish );
490 case InlineItem::Break:
491 BREAK( ret, targState );
496 /* Write out paths in line directives. Escapes any special characters. */
497 string FsmCodeGen::LDIR_PATH( char *path )
500 for ( char *pc = path; *pc != 0; pc++ ) {
509 void FsmCodeGen::ACTION( ostream &ret, Action *action, int targState, bool inFinish )
511 /* Write the preprocessor line info for going into the source file. */
512 lineDirective( ret, sourceFileName, action->loc.line );
514 /* Write the block and close it off. */
516 INLINE_LIST( ret, action->inlineList, targState, inFinish );
520 void FsmCodeGen::CONDITION( ostream &ret, Action *condition )
523 lineDirective( ret, sourceFileName, condition->loc.line );
524 INLINE_LIST( ret, condition->inlineList, 0, false );
527 string FsmCodeGen::ERROR_STATE()
530 if ( redFsm->errState != 0 )
531 ret << redFsm->errState->id;
537 string FsmCodeGen::FIRST_FINAL_STATE()
540 if ( redFsm->firstFinState != 0 )
541 ret << redFsm->firstFinState->id;
543 ret << redFsm->nextStateId;
547 void FsmCodeGen::writeInit()
552 out << "\t" << CS() << " = " << START() << ";\n";
554 /* If there are any calls, then the stack top needs initialization. */
555 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
556 out << "\t" << TOP() << " = 0;\n";
558 if ( hasLongestMatch ) {
560 " " << TOKSTART() << " = " << NULL_ITEM() << ";\n"
561 " " << TOKEND() << " = " << NULL_ITEM() << ";\n"
562 " " << ACT() << " = 0;\n";
567 string FsmCodeGen::DATA_PREFIX()
570 return FSM_NAME() + "_";
574 /* Emit the alphabet data type. */
575 string FsmCodeGen::ALPH_TYPE()
577 string ret = keyOps->alphType->data1;
578 if ( keyOps->alphType->data2 != 0 ) {
580 ret += + keyOps->alphType->data2;
585 /* Emit the alphabet data type. */
586 string FsmCodeGen::WIDE_ALPH_TYPE()
589 if ( redFsm->maxKey <= keyOps->maxKey )
592 long long maxKeyVal = redFsm->maxKey.getLongLong();
593 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
594 assert( wideType != 0 );
596 ret = wideType->data1;
597 if ( wideType->data2 != 0 ) {
599 ret += wideType->data2;
605 void FsmCodeGen::STATE_IDS()
607 if ( redFsm->startState != 0 )
608 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
610 if ( writeFirstFinal )
611 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
614 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
618 if ( entryPointNames.length() > 0 ) {
619 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
620 STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) <<
621 " = " << entryPointIds[en.pos()] << ";\n";
629 * Language specific, but style independent code generators functions.
632 string CCodeGen::PTR_CONST()
637 std::ostream &CCodeGen::OPEN_ARRAY( string type, string name )
639 out << "static const " << type << " " << name << "[] = {\n";
643 std::ostream &CCodeGen::CLOSE_ARRAY()
645 return out << "};\n";
648 std::ostream &CCodeGen::STATIC_VAR( string type, string name )
650 out << "static const " << type << " " << name;
654 string CCodeGen::UINT( )
656 return "unsigned int";
659 string CCodeGen::ARR_OFF( string ptr, string offset )
661 return ptr + " + " + offset;
664 string CCodeGen::CAST( string type )
666 return "(" + type + ")";
669 string CCodeGen::NULL_ITEM()
674 string CCodeGen::POINTER()
679 std::ostream &CCodeGen::SWITCH_DEFAULT()
684 string CCodeGen::CTRL_FLOW()
689 void CCodeGen::writeExports()
691 if ( exportList.length() > 0 ) {
692 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
693 out << "#define " << DATA_PREFIX() << "ex_" << ex->name << " " <<
694 KEY(ex->key) << "\n";
704 string DCodeGen::NULL_ITEM()
709 string DCodeGen::POINTER()
711 // multiple items seperated by commas can also be pointer types.
715 string DCodeGen::PTR_CONST()
720 std::ostream &DCodeGen::OPEN_ARRAY( string type, string name )
722 out << "static const " << type << "[] " << name << " = [\n";
726 std::ostream &DCodeGen::CLOSE_ARRAY()
728 return out << "];\n";
731 std::ostream &DCodeGen::STATIC_VAR( string type, string name )
733 out << "static const " << type << " " << name;
737 string DCodeGen::ARR_OFF( string ptr, string offset )
739 return "&" + ptr + "[" + offset + "]";
742 string DCodeGen::CAST( string type )
744 return "cast(" + type + ")";
747 string DCodeGen::UINT( )
752 std::ostream &DCodeGen::SWITCH_DEFAULT()
754 out << " default: break;\n";
758 string DCodeGen::CTRL_FLOW()
763 void DCodeGen::writeExports()
765 if ( exportList.length() > 0 ) {
766 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
767 out << "static const " << ALPH_TYPE() << " " << DATA_PREFIX() <<
768 "ex_" << ex->name << " = " << KEY(ex->key) << ";\n";
775 * End D-specific code.
778 void FsmCodeGen::finishRagelDef()
780 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
781 codeStyle == GenIpGoto || codeStyle == GenSplit )
783 /* For directly executable machines there is no required state
784 * ordering. Choose a depth-first ordering to increase the
785 * potential for fall-throughs. */
786 redFsm->depthFirstOrdering();
789 /* The frontend will do this for us, but it may be a good idea to
790 * force it if the intermediate file is edited. */
791 redFsm->sortByStateId();
794 /* Choose default transitions and the single transition. */
795 redFsm->chooseDefaultSpan();
797 /* Maybe do flat expand, otherwise choose single. */
798 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
801 redFsm->chooseSingle();
803 /* If any errors have occured in the input file then don't write anything. */
804 if ( gblErrorCount > 0 )
807 if ( codeStyle == GenSplit )
808 redFsm->partitionFsm( numSplitPartitions );
810 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
811 redFsm->setInTrans();
813 /* Anlayze Machine will find the final action reference counts, among
814 * other things. We will use these in reporting the usage
815 * of fsm directives in action code. */
818 /* Determine if we should use indicies. */
822 ostream &FsmCodeGen::source_warning( const InputLoc &loc )
824 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
828 ostream &FsmCodeGen::source_error( const InputLoc &loc )
831 assert( sourceFileName != 0 );
832 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";