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
25 #include "cscodegen.h"
33 /* Code generators. */
44 using std::ostringstream;
58 /* Invoked by the parser when the root element is opened. */
59 ostream *csharpOpenOutput( const char *inputFile )
61 if ( hostLang->lang != HostLang::CSharp ) {
62 error() << "this code generator is for C# only" << endl;
66 /* If the output format is code and no output file name is given, then
68 if ( outputFileName == 0 ) {
69 const char *ext = findFileExtension( inputFile );
70 if ( ext != 0 && strcmp( ext, ".rh" ) == 0 )
71 outputFileName = fileNameFromStem( inputFile, ".h" );
73 outputFileName = fileNameFromStem( inputFile, ".cs" );
76 /* Make sure we are not writing to the same file as the input file. */
77 if ( outputFileName != 0 && strcmp( inputFile, outputFileName ) == 0 ) {
78 error() << "output file \"" << outputFileName <<
79 "\" is the same as the input file" << endl;
82 if ( outputFileName != 0 ) {
83 /* Create the filter on the output and open it. */
84 outFilter = new output_filter( outputFileName );
86 /* Open the output stream, attaching it to the filter. */
87 outStream = new ostream( outFilter );
90 /* Writing out ot std out. */
96 /* Invoked by the parser when a ragel definition is opened. */
97 CodeGenData *csharpMakeCodeGen( const char *sourceFileName, const char *fsmName,
98 ostream &out, bool wantComplete )
100 CodeGenData *codeGen = 0;
102 switch ( codeStyle ) {
104 codeGen = new CSharpTabCodeGen(out);
107 codeGen = new CSharpFTabCodeGen(out);
110 codeGen = new CSharpFlatCodeGen(out);
113 codeGen = new CSharpFFlatCodeGen(out);
116 codeGen = new CSharpGotoCodeGen(out);
119 codeGen = new CSharpFGotoCodeGen(out);
122 codeGen = new CSharpIpGotoCodeGen(out);
125 codeGen = new CSharpSplitCodeGen(out);
129 codeGen->sourceFileName = sourceFileName;
130 codeGen->fsmName = fsmName;
131 codeGen->wantComplete = wantComplete;
136 void csharpLineDirective( ostream &out, const char *fileName, int line )
138 if ( noLineDirectives )
141 /* Write the preprocessor line info for to the input file. */
142 out << "#line " << line << " \"";
143 for ( const char *pc = fileName; *pc != 0; pc++ ) {
151 if ( noLineDirectives )
157 void CSharpFsmCodeGen::genLineDirective( ostream &out )
159 std::streambuf *sbuf = out.rdbuf();
160 output_filter *filter = static_cast<output_filter*>(sbuf);
161 csharpLineDirective( out, filter->fileName, filter->line + 1 );
165 /* Init code gen with in parameters. */
166 CSharpFsmCodeGen::CSharpFsmCodeGen( ostream &out )
172 unsigned int CSharpFsmCodeGen::arrayTypeSize( unsigned long maxVal )
174 long long maxValLL = (long long) maxVal;
175 HostType *arrayType = keyOps->typeSubsumes( maxValLL );
176 assert( arrayType != 0 );
177 return arrayType->size;
180 string CSharpFsmCodeGen::ARRAY_TYPE( unsigned long maxVal )
182 return ARRAY_TYPE( maxVal, false );
185 string CSharpFsmCodeGen::ARRAY_TYPE( unsigned long maxVal, bool forceSigned )
187 long long maxValLL = (long long) maxVal;
190 arrayType = keyOps->typeSubsumes(true, maxValLL);
192 arrayType = keyOps->typeSubsumes( maxValLL );
193 assert( arrayType != 0 );
195 string ret = arrayType->data1;
196 if ( arrayType->data2 != 0 ) {
198 ret += arrayType->data2;
203 /* Write out the fsm name. */
204 string CSharpFsmCodeGen::FSM_NAME()
209 /* Emit the offset of the start state as a decimal integer. */
210 string CSharpFsmCodeGen::START_STATE_ID()
213 ret << redFsm->startState->id;
217 /* Write out the array of actions. */
218 std::ostream &CSharpFsmCodeGen::ACTIONS_ARRAY()
221 int totalActions = 1;
222 for ( GenActionTableMap::Iter act = redFsm->actionMap; act.lte(); act++ ) {
223 /* Write out the length, which will never be the last character. */
224 out << act->key.length() << ", ";
225 /* Put in a line break every 8 */
226 if ( totalActions++ % 8 == 7 )
229 for ( GenActionTable::Iter item = act->key; item.lte(); item++ ) {
230 out << item->value->actionId;
231 if ( ! (act.last() && item.last()) )
234 /* Put in a line break every 8 */
235 if ( totalActions++ % 8 == 7 )
244 string CSharpFsmCodeGen::ACCESS()
247 if ( accessExpr != 0 )
248 INLINE_LIST( ret, accessExpr, 0, false );
253 string CSharpFsmCodeGen::P()
260 INLINE_LIST( ret, pExpr, 0, false );
266 string CSharpFsmCodeGen::PE()
273 INLINE_LIST( ret, peExpr, 0, false );
279 string CSharpFsmCodeGen::EOFV()
286 INLINE_LIST( ret, eofExpr, 0, false );
292 string CSharpFsmCodeGen::CS()
296 ret << ACCESS() << "cs";
298 /* Emit the user supplied method of retrieving the key. */
300 INLINE_LIST( ret, csExpr, 0, false );
306 string CSharpFsmCodeGen::TOP()
310 ret << ACCESS() + "top";
313 INLINE_LIST( ret, topExpr, 0, false );
319 string CSharpFsmCodeGen::STACK()
322 if ( stackExpr == 0 )
323 ret << ACCESS() + "stack";
326 INLINE_LIST( ret, stackExpr, 0, false );
332 string CSharpFsmCodeGen::ACT()
336 ret << ACCESS() + "act";
339 INLINE_LIST( ret, actExpr, 0, false );
345 string CSharpFsmCodeGen::TOKSTART()
348 if ( tokstartExpr == 0 )
349 ret << ACCESS() + "ts";
352 INLINE_LIST( ret, tokstartExpr, 0, false );
358 string CSharpFsmCodeGen::TOKEND()
361 if ( tokendExpr == 0 )
362 ret << ACCESS() + "te";
365 INLINE_LIST( ret, tokendExpr, 0, false );
371 string CSharpFsmCodeGen::GET_WIDE_KEY()
373 if ( redFsm->anyConditions() )
379 string CSharpFsmCodeGen::GET_WIDE_KEY( RedStateAp *state )
381 if ( state->stateCondList.length() > 0 )
387 string CSharpFsmCodeGen::GET_KEY()
390 if ( getKeyExpr != 0 ) {
391 /* Emit the user supplied method of retrieving the key. */
393 INLINE_LIST( ret, getKeyExpr, 0, false );
397 /* Expression for retrieving the key, use simple dereference. */
398 ret << "(*" << P() << ")";
403 /* Write out level number of tabs. Makes the nested binary search nice
405 string CSharpFsmCodeGen::TABS( int level )
408 while ( level-- > 0 )
413 /* Write out a key from the fsm code gen. Depends on wether or not the key is
415 string CSharpFsmCodeGen::KEY( Key key )
418 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
421 ret << (unsigned long) key.getVal() << 'u';
425 string CSharpFsmCodeGen::ALPHA_KEY( Key key )
428 if (key.getVal() > 0xFFFF) {
431 ret << "'\\u" << std::hex << std::setw(4) << std::setfill('0') <<
434 //ret << "(char) " << key.getVal();
438 void CSharpFsmCodeGen::EXEC( ostream &ret, GenInlineItem *item, int targState, int inFinish )
440 /* The parser gives fexec two children. The double brackets are for D
441 * code. If the inline list is a single word it will get interpreted as a
442 * C-style cast by the D compiler. */
443 ret << "{" << P() << " = ((";
444 INLINE_LIST( ret, item->children, targState, inFinish );
448 void CSharpFsmCodeGen::LM_SWITCH( ostream &ret, GenInlineItem *item,
449 int targState, int inFinish )
452 " switch( " << ACT() << " ) {\n";
454 for ( GenInlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
455 /* Write the case label, the action and the case break. */
457 ret << " default:\n";
459 ret << " case " << lma->lmId << ":\n";
461 /* Write the block and close it off. */
463 INLINE_LIST( ret, lma->children, targState, inFinish );
474 void CSharpFsmCodeGen::SET_ACT( ostream &ret, GenInlineItem *item )
476 ret << ACT() << " = " << item->lmId << ";";
479 void CSharpFsmCodeGen::SET_TOKEND( ostream &ret, GenInlineItem *item )
481 /* The tokend action sets tokend. */
482 ret << TOKEND() << " = " << P();
483 if ( item->offset != 0 )
484 out << "+" << item->offset;
488 void CSharpFsmCodeGen::GET_TOKEND( ostream &ret, GenInlineItem *item )
493 void CSharpFsmCodeGen::INIT_TOKSTART( ostream &ret, GenInlineItem *item )
495 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
498 void CSharpFsmCodeGen::INIT_ACT( ostream &ret, GenInlineItem *item )
500 ret << ACT() << " = 0;";
503 void CSharpFsmCodeGen::SET_TOKSTART( ostream &ret, GenInlineItem *item )
505 ret << TOKSTART() << " = " << P() << ";";
508 void CSharpFsmCodeGen::SUB_ACTION( ostream &ret, GenInlineItem *item,
509 int targState, bool inFinish )
511 if ( item->children->length() > 0 ) {
512 /* Write the block and close it off. */
514 INLINE_LIST( ret, item->children, targState, inFinish );
520 /* Write out an inline tree structure. Walks the list and possibly calls out
521 * to virtual functions than handle language specific items in the tree. */
522 void CSharpFsmCodeGen::INLINE_LIST( ostream &ret, GenInlineList *inlineList,
523 int targState, bool inFinish )
525 for ( GenInlineList::Iter item = *inlineList; item.lte(); item++ ) {
526 switch ( item->type ) {
527 case GenInlineItem::Text:
530 case GenInlineItem::Goto:
531 GOTO( ret, item->targState->id, inFinish );
533 case GenInlineItem::Call:
534 CALL( ret, item->targState->id, targState, inFinish );
536 case GenInlineItem::Next:
537 NEXT( ret, item->targState->id, inFinish );
539 case GenInlineItem::Ret:
540 RET( ret, inFinish );
542 case GenInlineItem::PChar:
545 case GenInlineItem::Char:
548 case GenInlineItem::Hold:
551 case GenInlineItem::Exec:
552 EXEC( ret, item, targState, inFinish );
554 case GenInlineItem::Curs:
555 CURS( ret, inFinish );
557 case GenInlineItem::Targs:
558 TARGS( ret, inFinish, targState );
560 case GenInlineItem::Entry:
561 ret << item->targState->id;
563 case GenInlineItem::GotoExpr:
564 GOTO_EXPR( ret, item, inFinish );
566 case GenInlineItem::CallExpr:
567 CALL_EXPR( ret, item, targState, inFinish );
569 case GenInlineItem::NextExpr:
570 NEXT_EXPR( ret, item, inFinish );
572 case GenInlineItem::LmSwitch:
573 LM_SWITCH( ret, item, targState, inFinish );
575 case GenInlineItem::LmSetActId:
576 SET_ACT( ret, item );
578 case GenInlineItem::LmSetTokEnd:
579 SET_TOKEND( ret, item );
581 case GenInlineItem::LmGetTokEnd:
582 GET_TOKEND( ret, item );
584 case GenInlineItem::LmInitTokStart:
585 INIT_TOKSTART( ret, item );
587 case GenInlineItem::LmInitAct:
588 INIT_ACT( ret, item );
590 case GenInlineItem::LmSetTokStart:
591 SET_TOKSTART( ret, item );
593 case GenInlineItem::SubAction:
594 SUB_ACTION( ret, item, targState, inFinish );
596 case GenInlineItem::Break:
597 BREAK( ret, targState );
602 /* Write out paths in line directives. Escapes any special characters. */
603 string CSharpFsmCodeGen::LDIR_PATH( char *path )
606 for ( char *pc = path; *pc != 0; pc++ ) {
615 void CSharpFsmCodeGen::ACTION( ostream &ret, GenAction *action, int targState, bool inFinish )
617 /* Write the preprocessor line info for going into the source file. */
618 csharpLineDirective( ret, sourceFileName, action->loc.line );
620 /* Write the block and close it off. */
622 INLINE_LIST( ret, action->inlineList, targState, inFinish );
626 void CSharpFsmCodeGen::CONDITION( ostream &ret, GenAction *condition )
629 csharpLineDirective( ret, sourceFileName, condition->loc.line );
630 INLINE_LIST( ret, condition->inlineList, 0, false );
633 string CSharpFsmCodeGen::ERROR_STATE()
636 if ( redFsm->errState != 0 )
637 ret << redFsm->errState->id;
643 string CSharpFsmCodeGen::FIRST_FINAL_STATE()
646 if ( redFsm->firstFinState != 0 )
647 ret << redFsm->firstFinState->id;
649 ret << redFsm->nextStateId;
653 void CSharpFsmCodeGen::writeInit()
658 out << "\t" << CS() << " = " << START() << ";\n";
660 /* If there are any calls, then the stack top needs initialization. */
661 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
662 out << "\t" << TOP() << " = 0;\n";
664 if ( hasLongestMatch ) {
666 " " << TOKSTART() << " = " << NULL_ITEM() << ";\n"
667 " " << TOKEND() << " = " << NULL_ITEM() << ";\n"
668 " " << ACT() << " = 0;\n";
673 string CSharpFsmCodeGen::DATA_PREFIX()
676 return FSM_NAME() + "_";
680 /* Emit the alphabet data type. */
681 string CSharpFsmCodeGen::ALPH_TYPE()
683 string ret = keyOps->alphType->data1;
684 if ( keyOps->alphType->data2 != 0 ) {
686 ret += + keyOps->alphType->data2;
691 /* Emit the alphabet data type. */
692 string CSharpFsmCodeGen::WIDE_ALPH_TYPE()
695 if ( redFsm->maxKey <= keyOps->maxKey )
698 long long maxKeyVal = redFsm->maxKey.getLongLong();
699 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
700 assert( wideType != 0 );
702 ret = wideType->data1;
703 if ( wideType->data2 != 0 ) {
705 ret += wideType->data2;
711 void CSharpFsmCodeGen::STATE_IDS()
713 if ( redFsm->startState != 0 )
714 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
717 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
720 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
724 if ( entryPointNames.length() > 0 ) {
725 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
726 STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) <<
727 " = " << entryPointIds[en.pos()] << ";\n";
734 void CSharpFsmCodeGen::writeStart()
736 out << START_STATE_ID();
739 void CSharpFsmCodeGen::writeFirstFinal()
741 out << FIRST_FINAL_STATE();
744 void CSharpFsmCodeGen::writeError()
746 out << ERROR_STATE();
752 string CSharpCodeGen::GET_KEY()
755 if ( getKeyExpr != 0 ) {
756 /* Emit the user supplied method of retrieving the key. */
758 INLINE_LIST( ret, getKeyExpr, 0, false );
762 /* Expression for retrieving the key, use simple dereference. */
763 ret << "data[" << P() << "]";
767 string CSharpCodeGen::NULL_ITEM()
772 string CSharpCodeGen::POINTER()
774 // XXX C# has no pointers
775 // multiple items seperated by commas can also be pointer types.
779 string CSharpCodeGen::PTR_CONST()
784 std::ostream &CSharpCodeGen::OPEN_ARRAY( string type, string name )
786 out << "static readonly " << type << "[] " << name << " = ";
789 out << "Encoding.ASCII.Get";
791 out << "new " << type << " [] {\n";
795 std::ostream &CSharpCodeGen::CLOSE_ARRAY()
797 return out << "};\n";
800 std::ostream &CSharpCodeGen::STATIC_VAR( string type, string name )
802 out << "const " << type << " " << name;
806 string CSharpCodeGen::ARR_OFF( string ptr, string offset )
808 // XXX C# can't do pointer arithmetic
809 return "&" + ptr + "[" + offset + "]";
812 string CSharpCodeGen::CAST( string type )
814 return "(" + type + ")";
817 string CSharpCodeGen::UINT( )
822 std::ostream &CSharpCodeGen::SWITCH_DEFAULT()
824 out << " default: break;\n";
828 string CSharpCodeGen::CTRL_FLOW()
833 void CSharpCodeGen::writeExports()
835 if ( exportList.length() > 0 ) {
836 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
837 out << "const " << ALPH_TYPE() << " " << DATA_PREFIX() <<
838 "ex_" << ex->name << " = " << KEY(ex->key) << ";\n";
845 * End C#-specific code.
848 void CSharpFsmCodeGen::finishRagelDef()
850 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
851 codeStyle == GenIpGoto || codeStyle == GenSplit )
853 /* For directly executable machines there is no required state
854 * ordering. Choose a depth-first ordering to increase the
855 * potential for fall-throughs. */
856 redFsm->depthFirstOrdering();
859 /* The frontend will do this for us, but it may be a good idea to
860 * force it if the intermediate file is edited. */
861 redFsm->sortByStateId();
864 /* Choose default transitions and the single transition. */
865 redFsm->chooseDefaultSpan();
867 /* Maybe do flat expand, otherwise choose single. */
868 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
871 redFsm->chooseSingle();
873 /* If any errors have occured in the input file then don't write anything. */
874 if ( gblErrorCount > 0 )
877 if ( codeStyle == GenSplit )
878 redFsm->partitionFsm( numSplitPartitions );
880 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
881 redFsm->setInTrans();
883 /* Anlayze Machine will find the final action reference counts, among
884 * other things. We will use these in reporting the usage
885 * of fsm directives in action code. */
888 /* Determine if we should use indicies. */
892 ostream &CSharpFsmCodeGen::source_warning( const InputLoc &loc )
894 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
898 ostream &CSharpFsmCodeGen::source_error( const InputLoc &loc )
901 assert( sourceFileName != 0 );
902 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";