2 * Copyright 2001-2006 Adrian Thurston <thurston@complang.org>
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
24 #include "cdcodegen.h"
32 /* Code generators. */
43 using std::ostringstream;
56 /* Target language and output style. */
57 extern CodeStyleEnum codeStyle;
60 extern istream *inStream;
61 extern ostream *outStream;
62 extern output_filter *outFilter;
63 extern const char *outputFileName;
65 /* Graphviz dot file generation. */
66 extern bool graphvizDone;
68 extern int numSplitPartitions;
69 extern bool noLineDirectives;
71 /* Invoked by the parser when the root element is opened. */
72 ostream *cdOpenOutput( const char *inputFile )
74 if ( hostLang->lang != HostLang::C && hostLang->lang != HostLang::D ) {
75 error() << "this code generator is for C and D only" << endl;
79 /* If the output format is code and no output file name is given, then
81 if ( outputFileName == 0 ) {
82 const char *ext = findFileExtension( inputFile );
83 if ( ext != 0 && strcmp( ext, ".rh" ) == 0 )
84 outputFileName = fileNameFromStem( inputFile, ".h" );
86 const char *defExtension = 0;
87 switch ( hostLang->lang ) {
88 case HostLang::C: defExtension = ".c"; break;
89 case HostLang::D: defExtension = ".d"; break;
92 outputFileName = fileNameFromStem( inputFile, defExtension );
96 /* Make sure we are not writing to the same file as the input file. */
97 if ( outputFileName != 0 && strcmp( inputFile, outputFileName ) == 0 ) {
98 error() << "output file \"" << outputFileName <<
99 "\" is the same as the input file" << endl;
102 if ( outputFileName != 0 ) {
103 /* Create the filter on the output and open it. */
104 outFilter = new output_filter( outputFileName );
106 /* Open the output stream, attaching it to the filter. */
107 outStream = new ostream( outFilter );
110 /* Writing out ot std out. */
116 /* Invoked by the parser when a ragel definition is opened. */
117 CodeGenData *cdMakeCodeGen( const char *sourceFileName, const char *fsmName,
118 ostream &out, bool wantComplete )
120 CodeGenData *codeGen = 0;
121 switch ( hostLang->lang ) {
123 switch ( codeStyle ) {
125 codeGen = new CTabCodeGen(out);
128 codeGen = new CFTabCodeGen(out);
131 codeGen = new CFlatCodeGen(out);
134 codeGen = new CFFlatCodeGen(out);
137 codeGen = new CGotoCodeGen(out);
140 codeGen = new CFGotoCodeGen(out);
143 codeGen = new CIpGotoCodeGen(out);
146 codeGen = new CSplitCodeGen(out);
152 switch ( codeStyle ) {
154 codeGen = new DTabCodeGen(out);
157 codeGen = new DFTabCodeGen(out);
160 codeGen = new DFlatCodeGen(out);
163 codeGen = new DFFlatCodeGen(out);
166 codeGen = new DGotoCodeGen(out);
169 codeGen = new DFGotoCodeGen(out);
172 codeGen = new DIpGotoCodeGen(out);
175 codeGen = new DSplitCodeGen(out);
183 codeGen->sourceFileName = sourceFileName;
184 codeGen->fsmName = fsmName;
185 codeGen->wantComplete = wantComplete;
191 void cdLineDirective( ostream &out, const char *fileName, int line )
193 if ( noLineDirectives )
196 /* Write the preprocessor line info for to the input file. */
197 out << "#line " << line << " \"";
198 for ( const char *pc = fileName; *pc != 0; pc++ ) {
206 if ( noLineDirectives )
212 void FsmCodeGen::genLineDirective( ostream &out )
214 std::streambuf *sbuf = out.rdbuf();
215 output_filter *filter = static_cast<output_filter*>(sbuf);
216 cdLineDirective( out, filter->fileName, filter->line + 1 );
220 /* Init code gen with in parameters. */
221 FsmCodeGen::FsmCodeGen( ostream &out )
227 unsigned int FsmCodeGen::arrayTypeSize( unsigned long maxVal )
229 long long maxValLL = (long long) maxVal;
230 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
231 assert( arrayType != 0 );
232 return arrayType->size;
235 string FsmCodeGen::ARRAY_TYPE( unsigned long maxVal )
237 long long maxValLL = (long long) maxVal;
238 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
239 assert( arrayType != 0 );
241 string ret = arrayType->data1;
242 if ( arrayType->data2 != 0 ) {
244 ret += arrayType->data2;
250 /* Write out the fsm name. */
251 string FsmCodeGen::FSM_NAME()
256 /* Emit the offset of the start state as a decimal integer. */
257 string FsmCodeGen::START_STATE_ID()
260 ret << redFsm->startState->id;
264 /* Write out the array of actions. */
265 std::ostream &FsmCodeGen::ACTIONS_ARRAY()
268 int totalActions = 1;
269 for ( GenActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) {
270 /* Write out the length, which will never be the last character. */
271 out << act->key.length() << ", ";
272 /* Put in a line break every 8 */
273 if ( totalActions++ % 8 == 7 )
276 for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) {
277 out << item->value->actionId;
278 if ( ! (act.last() && item.last()) )
281 /* Put in a line break every 8 */
282 if ( totalActions++ % 8 == 7 )
291 string FsmCodeGen::ACCESS()
294 if ( accessExpr != 0 )
295 INLINE_LIST( ret, accessExpr, 0, false, false );
300 string FsmCodeGen::P()
307 INLINE_LIST( ret, pExpr, 0, false, false );
313 string FsmCodeGen::PE()
320 INLINE_LIST( ret, peExpr, 0, false, false );
326 string FsmCodeGen::EOFV()
333 INLINE_LIST( ret, eofExpr, 0, false, false );
339 string FsmCodeGen::CS()
343 ret << ACCESS() << "cs";
345 /* Emit the user supplied method of retrieving the key. */
347 INLINE_LIST( ret, csExpr, 0, false, false );
353 string FsmCodeGen::TOP()
357 ret << ACCESS() + "top";
360 INLINE_LIST( ret, topExpr, 0, false, false );
366 string FsmCodeGen::STACK()
369 if ( stackExpr == 0 )
370 ret << ACCESS() + "stack";
373 INLINE_LIST( ret, stackExpr, 0, false, false );
379 string FsmCodeGen::ACT()
383 ret << ACCESS() + "act";
386 INLINE_LIST( ret, actExpr, 0, false, false );
392 string FsmCodeGen::TOKSTART()
395 if ( tokstartExpr == 0 )
396 ret << ACCESS() + "ts";
399 INLINE_LIST( ret, tokstartExpr, 0, false, false );
405 string FsmCodeGen::TOKEND()
408 if ( tokendExpr == 0 )
409 ret << ACCESS() + "te";
412 INLINE_LIST( ret, tokendExpr, 0, false, false );
418 string FsmCodeGen::GET_WIDE_KEY()
420 if ( redFsm->anyConditions() )
426 string FsmCodeGen::GET_WIDE_KEY( RedStateAp *state )
428 if ( state->stateCondList.length() > 0 )
434 string FsmCodeGen::GET_KEY()
437 if ( getKeyExpr != 0 ) {
438 /* Emit the user supplied method of retrieving the key. */
440 INLINE_LIST( ret, getKeyExpr, 0, false, false );
444 /* Expression for retrieving the key, use simple dereference. */
445 ret << "(*" << P() << ")";
450 /* Write out level number of tabs. Makes the nested binary search nice
452 string FsmCodeGen::TABS( int level )
455 while ( level-- > 0 )
460 /* Write out a key from the fsm code gen. Depends on wether or not the key is
462 string FsmCodeGen::KEY( Key key )
465 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
468 ret << (unsigned long) key.getVal() << 'u';
472 void FsmCodeGen::EXEC( ostream &ret, GenInlineItem *item, int targState, int inFinish )
474 /* The parser gives fexec two children. The double brackets are for D
475 * code. If the inline list is a single word it will get interpreted as a
476 * C-style cast by the D compiler. */
477 ret << "{" << P() << " = ((";
478 INLINE_LIST( ret, item->children, targState, inFinish, false );
482 void FsmCodeGen::LM_SWITCH( ostream &ret, GenInlineItem *item,
483 int targState, int inFinish, bool csForced )
486 " switch( " << ACT() << " ) {\n";
488 bool haveDefault = false;
489 for ( GenInlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
490 /* Write the case label, the action and the case break. */
491 if ( lma->lmId < 0 ) {
492 ret << " default:\n";
496 ret << " case " << lma->lmId << ":\n";
498 /* Write the block and close it off. */
500 INLINE_LIST( ret, lma->children, targState, inFinish, csForced );
506 if ( hostLang->lang == HostLang::D && !haveDefault )
507 ret << " default: break;";
514 void FsmCodeGen::SET_ACT( ostream &ret, GenInlineItem *item )
516 ret << ACT() << " = " << item->lmId << ";";
519 void FsmCodeGen::SET_TOKEND( ostream &ret, GenInlineItem *item )
521 /* The tokend action sets tokend. */
522 ret << TOKEND() << " = " << P();
523 if ( item->offset != 0 )
524 out << "+" << item->offset;
528 void FsmCodeGen::GET_TOKEND( ostream &ret, GenInlineItem *item )
533 void FsmCodeGen::INIT_TOKSTART( ostream &ret, GenInlineItem *item )
535 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
538 void FsmCodeGen::INIT_ACT( ostream &ret, GenInlineItem *item )
540 ret << ACT() << " = 0;";
543 void FsmCodeGen::SET_TOKSTART( ostream &ret, GenInlineItem *item )
545 ret << TOKSTART() << " = " << P() << ";";
548 void FsmCodeGen::SUB_ACTION( ostream &ret, GenInlineItem *item,
549 int targState, bool inFinish, bool csForced )
551 if ( item->children->length() > 0 ) {
552 /* Write the block and close it off. */
554 INLINE_LIST( ret, item->children, targState, inFinish, csForced );
560 /* Write out an inline tree structure. Walks the list and possibly calls out
561 * to virtual functions than handle language specific items in the tree. */
562 void FsmCodeGen::INLINE_LIST( ostream &ret, GenInlineList *inlineList,
563 int targState, bool inFinish, bool csForced )
565 for ( GenInlineList::Iter item = *inlineList; item.lte(); item++ ) {
566 switch ( item->type ) {
567 case GenInlineItem::Text:
570 case GenInlineItem::Goto:
571 GOTO( ret, item->targState->id, inFinish );
573 case GenInlineItem::Call:
574 CALL( ret, item->targState->id, targState, inFinish );
576 case GenInlineItem::Next:
577 NEXT( ret, item->targState->id, inFinish );
579 case GenInlineItem::Ret:
580 RET( ret, inFinish );
582 case GenInlineItem::PChar:
585 case GenInlineItem::Char:
588 case GenInlineItem::Hold:
591 case GenInlineItem::Exec:
592 EXEC( ret, item, targState, inFinish );
594 case GenInlineItem::Curs:
595 CURS( ret, inFinish );
597 case GenInlineItem::Targs:
598 TARGS( ret, inFinish, targState );
600 case GenInlineItem::Entry:
601 ret << item->targState->id;
603 case GenInlineItem::GotoExpr:
604 GOTO_EXPR( ret, item, inFinish );
606 case GenInlineItem::CallExpr:
607 CALL_EXPR( ret, item, targState, inFinish );
609 case GenInlineItem::NextExpr:
610 NEXT_EXPR( ret, item, inFinish );
612 case GenInlineItem::LmSwitch:
613 LM_SWITCH( ret, item, targState, inFinish, csForced );
615 case GenInlineItem::LmSetActId:
616 SET_ACT( ret, item );
618 case GenInlineItem::LmSetTokEnd:
619 SET_TOKEND( ret, item );
621 case GenInlineItem::LmGetTokEnd:
622 GET_TOKEND( ret, item );
624 case GenInlineItem::LmInitTokStart:
625 INIT_TOKSTART( ret, item );
627 case GenInlineItem::LmInitAct:
628 INIT_ACT( ret, item );
630 case GenInlineItem::LmSetTokStart:
631 SET_TOKSTART( ret, item );
633 case GenInlineItem::SubAction:
634 SUB_ACTION( ret, item, targState, inFinish, csForced );
636 case GenInlineItem::Break:
637 BREAK( ret, targState, csForced );
642 /* Write out paths in line directives. Escapes any special characters. */
643 string FsmCodeGen::LDIR_PATH( char *path )
646 for ( char *pc = path; *pc != 0; pc++ ) {
655 void FsmCodeGen::ACTION( ostream &ret, GenAction *action, int targState,
656 bool inFinish, bool csForced )
658 /* Write the preprocessor line info for going into the source file. */
659 cdLineDirective( ret, sourceFileName, action->loc.line );
661 /* Write the block and close it off. */
663 INLINE_LIST( ret, action->inlineList, targState, inFinish, csForced );
667 void FsmCodeGen::CONDITION( ostream &ret, GenAction *condition )
670 cdLineDirective( ret, sourceFileName, condition->loc.line );
671 INLINE_LIST( ret, condition->inlineList, 0, false, false );
674 string FsmCodeGen::ERROR_STATE()
677 if ( redFsm->errState != 0 )
678 ret << redFsm->errState->id;
684 string FsmCodeGen::FIRST_FINAL_STATE()
687 if ( redFsm->firstFinState != 0 )
688 ret << redFsm->firstFinState->id;
690 ret << redFsm->nextStateId;
694 void FsmCodeGen::writeInit()
699 out << "\t" << CS() << " = " << START() << ";\n";
701 /* If there are any calls, then the stack top needs initialization. */
702 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
703 out << "\t" << TOP() << " = 0;\n";
705 if ( hasLongestMatch ) {
707 " " << TOKSTART() << " = " << NULL_ITEM() << ";\n"
708 " " << TOKEND() << " = " << NULL_ITEM() << ";\n"
709 " " << ACT() << " = 0;\n";
714 string FsmCodeGen::DATA_PREFIX()
717 return FSM_NAME() + "_";
721 /* Emit the alphabet data type. */
722 string FsmCodeGen::ALPH_TYPE()
724 string ret = keyOps->alphType->data1;
725 if ( keyOps->alphType->data2 != 0 ) {
727 ret += + keyOps->alphType->data2;
732 /* Emit the alphabet data type. */
733 string FsmCodeGen::WIDE_ALPH_TYPE()
736 if ( redFsm->maxKey <= keyOps->maxKey )
739 long long maxKeyVal = redFsm->maxKey.getLongLong();
740 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
741 assert( wideType != 0 );
743 ret = wideType->data1;
744 if ( wideType->data2 != 0 ) {
746 ret += wideType->data2;
752 void FsmCodeGen::STATE_IDS()
754 if ( redFsm->startState != 0 )
755 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
758 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
761 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
765 if ( entryPointNames.length() > 0 ) {
766 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
767 STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) <<
768 " = " << entryPointIds[en.pos()] << ";\n";
774 void FsmCodeGen::writeStart()
776 out << START_STATE_ID();
779 void FsmCodeGen::writeFirstFinal()
781 out << FIRST_FINAL_STATE();
784 void FsmCodeGen::writeError()
786 out << ERROR_STATE();
790 * Language specific, but style independent code generators functions.
793 string CCodeGen::PTR_CONST()
798 std::ostream &CCodeGen::OPEN_ARRAY( string type, string name )
800 out << "static const " << type << " " << name << "[] = {\n";
804 std::ostream &CCodeGen::CLOSE_ARRAY()
806 return out << "};\n";
809 std::ostream &CCodeGen::STATIC_VAR( string type, string name )
811 out << "static const " << type << " " << name;
815 string CCodeGen::UINT( )
817 return "unsigned int";
820 string CCodeGen::ARR_OFF( string ptr, string offset )
822 return ptr + " + " + offset;
825 string CCodeGen::CAST( string type )
827 return "(" + type + ")";
830 string CCodeGen::NULL_ITEM()
835 string CCodeGen::POINTER()
840 std::ostream &CCodeGen::SWITCH_DEFAULT()
845 string CCodeGen::CTRL_FLOW()
850 void CCodeGen::writeExports()
852 if ( exportList.length() > 0 ) {
853 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
854 out << "#define " << DATA_PREFIX() << "ex_" << ex->name << " " <<
855 KEY(ex->key) << "\n";
865 string DCodeGen::NULL_ITEM()
870 string DCodeGen::POINTER()
872 // multiple items seperated by commas can also be pointer types.
876 string DCodeGen::PTR_CONST()
881 std::ostream &DCodeGen::OPEN_ARRAY( string type, string name )
883 out << "static const " << type << "[] " << name << " = [\n";
887 std::ostream &DCodeGen::CLOSE_ARRAY()
889 return out << "];\n";
892 std::ostream &DCodeGen::STATIC_VAR( string type, string name )
894 out << "static const " << type << " " << name;
898 string DCodeGen::ARR_OFF( string ptr, string offset )
900 return "&" + ptr + "[" + offset + "]";
903 string DCodeGen::CAST( string type )
905 return "cast(" + type + ")";
908 string DCodeGen::UINT( )
913 std::ostream &DCodeGen::SWITCH_DEFAULT()
915 out << " default: break;\n";
919 string DCodeGen::CTRL_FLOW()
924 void DCodeGen::writeExports()
926 if ( exportList.length() > 0 ) {
927 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
928 out << "static const " << ALPH_TYPE() << " " << DATA_PREFIX() <<
929 "ex_" << ex->name << " = " << KEY(ex->key) << ";\n";
936 * End D-specific code.
939 void FsmCodeGen::finishRagelDef()
941 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
942 codeStyle == GenIpGoto || codeStyle == GenSplit )
944 /* For directly executable machines there is no required state
945 * ordering. Choose a depth-first ordering to increase the
946 * potential for fall-throughs. */
947 redFsm->depthFirstOrdering();
950 /* The frontend will do this for us, but it may be a good idea to
951 * force it if the intermediate file is edited. */
952 redFsm->sortByStateId();
955 /* Choose default transitions and the single transition. */
956 redFsm->chooseDefaultSpan();
958 /* Maybe do flat expand, otherwise choose single. */
959 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
962 redFsm->chooseSingle();
964 /* If any errors have occured in the input file then don't write anything. */
965 if ( gblErrorCount > 0 )
968 if ( codeStyle == GenSplit )
969 redFsm->partitionFsm( numSplitPartitions );
971 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
972 redFsm->setInTrans();
974 /* Anlayze Machine will find the final action reference counts, among
975 * other things. We will use these in reporting the usage
976 * of fsm directives in action code. */
979 /* Determine if we should use indicies. */
983 ostream &FsmCodeGen::source_warning( const InputLoc &loc )
985 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
989 ostream &FsmCodeGen::source_error( const InputLoc &loc )
992 assert( sourceFileName != 0 );
993 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";