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::CS()
142 if ( curStateExpr != 0 ) {
143 /* Emit the user supplied method of retrieving the key. */
145 INLINE_LIST( ret, curStateExpr, 0, false );
149 /* Expression for retrieving the key, use simple dereference. */
150 ret << ACCESS() << "cs";
155 string FsmCodeGen::ACCESS()
158 if ( accessExpr != 0 )
159 INLINE_LIST( ret, accessExpr, 0, false );
163 string FsmCodeGen::GET_WIDE_KEY()
165 if ( redFsm->anyConditions() )
171 string FsmCodeGen::GET_WIDE_KEY( RedStateAp *state )
173 if ( state->stateCondList.length() > 0 )
179 string FsmCodeGen::GET_KEY()
182 if ( getKeyExpr != 0 ) {
183 /* Emit the user supplied method of retrieving the key. */
185 INLINE_LIST( ret, getKeyExpr, 0, false );
189 /* Expression for retrieving the key, use simple dereference. */
190 ret << "(*" << P() << ")";
195 /* Write out level number of tabs. Makes the nested binary search nice
197 string FsmCodeGen::TABS( int level )
200 while ( level-- > 0 )
205 /* Write out a key from the fsm code gen. Depends on wether or not the key is
207 string FsmCodeGen::KEY( Key key )
210 if ( keyOps->isSigned || !hostLang->explicitUnsigned )
213 ret << (unsigned long) key.getVal() << 'u';
217 void FsmCodeGen::EXEC( ostream &ret, InlineItem *item, int targState, int inFinish )
219 /* The parser gives fexec two children. The double brackets are for D
220 * code. If the inline list is a single word it will get interpreted as a
221 * C-style cast by the D compiler. */
222 ret << "{" << P() << " = ((";
223 INLINE_LIST( ret, item->children, targState, inFinish );
227 void FsmCodeGen::EXECTE( ostream &ret, InlineItem *item, int targState, int inFinish )
229 /* Tokend version of exec. */
231 /* The parser gives fexec two children. The double brackets are for D
232 * code. If the inline list is a single word it will get interpreted as a
233 * C-style cast by the D compiler. */
234 ret << "{" << TOKEND() << " = ((";
235 INLINE_LIST( ret, item->children, targState, inFinish );
240 void FsmCodeGen::LM_SWITCH( ostream &ret, InlineItem *item,
241 int targState, int inFinish )
244 " switch( " << ACT() << " ) {\n";
246 /* If the switch handles error then we also forced the error state. It
248 if ( item->handlesError ) {
249 ret << " case 0: " << TOKEND() << " = " << TOKSTART() << "; ";
250 GOTO( ret, redFsm->errState->id, inFinish );
254 for ( InlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
255 /* Write the case label, the action and the case break. */
256 ret << " case " << lma->lmId << ":\n";
258 /* Write the block and close it off. */
260 INLINE_LIST( ret, lma->children, targState, inFinish );
265 /* Default required for D code. */
272 void FsmCodeGen::SET_ACT( ostream &ret, InlineItem *item )
274 ret << ACT() << " = " << item->lmId << ";";
277 void FsmCodeGen::SET_TOKEND( ostream &ret, InlineItem *item )
279 /* The tokend action sets tokend. */
280 ret << TOKEND() << " = " << P();
281 if ( item->offset != 0 )
282 out << "+" << item->offset;
286 void FsmCodeGen::GET_TOKEND( ostream &ret, InlineItem *item )
291 void FsmCodeGen::INIT_TOKSTART( ostream &ret, InlineItem *item )
293 ret << TOKSTART() << " = " << NULL_ITEM() << ";";
296 void FsmCodeGen::INIT_ACT( ostream &ret, InlineItem *item )
298 ret << ACT() << " = 0;";
301 void FsmCodeGen::SET_TOKSTART( ostream &ret, InlineItem *item )
303 ret << TOKSTART() << " = " << P() << ";";
306 void FsmCodeGen::SUB_ACTION( ostream &ret, InlineItem *item,
307 int targState, bool inFinish )
309 if ( item->children->length() > 0 ) {
310 /* Write the block and close it off. */
312 INLINE_LIST( ret, item->children, targState, inFinish );
318 /* Write out an inline tree structure. Walks the list and possibly calls out
319 * to virtual functions than handle language specific items in the tree. */
320 void FsmCodeGen::INLINE_LIST( ostream &ret, InlineList *inlineList,
321 int targState, bool inFinish )
323 for ( InlineList::Iter item = *inlineList; item.lte(); item++ ) {
324 switch ( item->type ) {
325 case InlineItem::Text:
328 case InlineItem::Goto:
329 GOTO( ret, item->targState->id, inFinish );
331 case InlineItem::Call:
332 CALL( ret, item->targState->id, targState, inFinish );
334 case InlineItem::Next:
335 NEXT( ret, item->targState->id, inFinish );
337 case InlineItem::Ret:
338 RET( ret, inFinish );
340 case InlineItem::PChar:
343 case InlineItem::Char:
346 case InlineItem::Hold:
349 case InlineItem::Exec:
350 EXEC( ret, item, targState, inFinish );
352 case InlineItem::HoldTE:
353 ret << TOKEND() << "--;";
355 case InlineItem::ExecTE:
356 EXECTE( ret, item, targState, inFinish );
358 case InlineItem::Curs:
359 CURS( ret, inFinish );
361 case InlineItem::Targs:
362 TARGS( ret, inFinish, targState );
364 case InlineItem::Entry:
365 ret << item->targState->id;
367 case InlineItem::GotoExpr:
368 GOTO_EXPR( ret, item, inFinish );
370 case InlineItem::CallExpr:
371 CALL_EXPR( ret, item, targState, inFinish );
373 case InlineItem::NextExpr:
374 NEXT_EXPR( ret, item, inFinish );
376 case InlineItem::LmSwitch:
377 LM_SWITCH( ret, item, targState, inFinish );
379 case InlineItem::LmSetActId:
380 SET_ACT( ret, item );
382 case InlineItem::LmSetTokEnd:
383 SET_TOKEND( ret, item );
385 case InlineItem::LmGetTokEnd:
386 GET_TOKEND( ret, item );
388 case InlineItem::LmInitTokStart:
389 INIT_TOKSTART( ret, item );
391 case InlineItem::LmInitAct:
392 INIT_ACT( ret, item );
394 case InlineItem::LmSetTokStart:
395 SET_TOKSTART( ret, item );
397 case InlineItem::SubAction:
398 SUB_ACTION( ret, item, targState, inFinish );
400 case InlineItem::Break:
401 BREAK( ret, targState );
406 /* Write out paths in line directives. Escapes any special characters. */
407 string FsmCodeGen::LDIR_PATH( char *path )
410 for ( char *pc = path; *pc != 0; pc++ ) {
419 void FsmCodeGen::ACTION( ostream &ret, Action *action, int targState, bool inFinish )
421 /* Write the preprocessor line info for going into the source file. */
422 lineDirective( ret, sourceFileName, action->loc.line );
424 /* Write the block and close it off. */
426 INLINE_LIST( ret, action->inlineList, targState, inFinish );
430 void FsmCodeGen::CONDITION( ostream &ret, Action *condition )
433 lineDirective( ret, sourceFileName, condition->loc.line );
434 INLINE_LIST( ret, condition->inlineList, 0, false );
437 string FsmCodeGen::ERROR_STATE()
440 if ( redFsm->errState != 0 )
441 ret << redFsm->errState->id;
447 string FsmCodeGen::FIRST_FINAL_STATE()
450 if ( redFsm->firstFinState != 0 )
451 ret << redFsm->firstFinState->id;
453 ret << redFsm->nextStateId;
457 void FsmCodeGen::writeInit()
460 out << "\t" << CS() << " = " << START() << ";\n";
462 /* If there are any calls, then the stack top needs initialization. */
463 if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
464 out << "\t" << TOP() << " = 0;\n";
466 if ( hasLongestMatch ) {
468 " " << TOKSTART() << " = " << NULL_ITEM() << ";\n"
469 " " << TOKEND() << " = " << NULL_ITEM() << ";\n"
470 " " << ACT() << " = 0;\n";
475 string FsmCodeGen::DATA_PREFIX()
478 return FSM_NAME() + "_";
482 /* Emit the alphabet data type. */
483 string FsmCodeGen::ALPH_TYPE()
485 string ret = keyOps->alphType->data1;
486 if ( keyOps->alphType->data2 != 0 ) {
488 ret += + keyOps->alphType->data2;
493 /* Emit the alphabet data type. */
494 string FsmCodeGen::WIDE_ALPH_TYPE()
497 if ( redFsm->maxKey <= keyOps->maxKey )
500 long long maxKeyVal = redFsm->maxKey.getLongLong();
501 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
502 assert( wideType != 0 );
504 ret = wideType->data1;
505 if ( wideType->data2 != 0 ) {
507 ret += wideType->data2;
513 void FsmCodeGen::ENTRY_POINTS()
515 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
516 STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) <<
517 " = " << entryPointIds[en.pos()] << ";\n";
522 void FsmCodeGen::writeExports()
524 if ( exportList.length() > 0 ) {
525 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
526 out << "#define " << DATA_PREFIX() << ex->name << " " <<
527 KEY(ex->key) << "\n";
535 * Language specific, but style independent code generators functions.
538 string CCodeGen::PTR_CONST()
543 std::ostream &CCodeGen::OPEN_ARRAY( string type, string name )
545 out << "static const " << type << " " << name << "[] = {\n";
549 std::ostream &CCodeGen::CLOSE_ARRAY()
551 return out << "};\n";
554 std::ostream &CCodeGen::STATIC_VAR( string type, string name )
556 out << "static const " << type << " " << name;
560 string CCodeGen::UINT( )
562 return "unsigned int";
565 string CCodeGen::ARR_OFF( string ptr, string offset )
567 return ptr + " + " + offset;
570 string CCodeGen::CAST( string type )
572 return "(" + type + ")";
575 string CCodeGen::NULL_ITEM()
580 string CCodeGen::POINTER()
585 std::ostream &CCodeGen::SWITCH_DEFAULT()
590 string CCodeGen::CTRL_FLOW()
599 string DCodeGen::NULL_ITEM()
604 string DCodeGen::POINTER()
606 // multiple items seperated by commas can also be pointer types.
610 string DCodeGen::PTR_CONST()
615 std::ostream &DCodeGen::OPEN_ARRAY( string type, string name )
617 out << "static const " << type << "[] " << name << " = [\n";
621 std::ostream &DCodeGen::CLOSE_ARRAY()
623 return out << "];\n";
626 std::ostream &DCodeGen::STATIC_VAR( string type, string name )
628 out << "static const " << type << " " << name;
632 string DCodeGen::ARR_OFF( string ptr, string offset )
634 return "&" + ptr + "[" + offset + "]";
637 string DCodeGen::CAST( string type )
639 return "cast(" + type + ")";
642 string DCodeGen::UINT( )
647 std::ostream &DCodeGen::SWITCH_DEFAULT()
649 out << " default: break;\n";
653 string DCodeGen::CTRL_FLOW()
658 void FsmCodeGen::finishRagelDef()
660 if ( codeStyle == GenGoto || codeStyle == GenFGoto ||
661 codeStyle == GenIpGoto || codeStyle == GenSplit )
663 /* For directly executable machines there is no required state
664 * ordering. Choose a depth-first ordering to increase the
665 * potential for fall-throughs. */
666 redFsm->depthFirstOrdering();
669 /* The frontend will do this for us, but it may be a good idea to
670 * force it if the intermediate file is edited. */
671 redFsm->sortByStateId();
674 /* Choose default transitions and the single transition. */
675 redFsm->chooseDefaultSpan();
677 /* Maybe do flat expand, otherwise choose single. */
678 if ( codeStyle == GenFlat || codeStyle == GenFFlat )
681 redFsm->chooseSingle();
683 /* If any errors have occured in the input file then don't write anything. */
684 if ( gblErrorCount > 0 )
687 if ( codeStyle == GenSplit )
688 redFsm->partitionFsm( numSplitPartitions );
690 if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
691 redFsm->setInTrans();
693 /* Anlayze Machine will find the final action reference counts, among
694 * other things. We will use these in reporting the usage
695 * of fsm directives in action code. */
698 /* Determine if we should use indicies. */
702 ostream &FsmCodeGen::source_warning( const InputLoc &loc )
704 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
708 ostream &FsmCodeGen::source_error( const InputLoc &loc )
711 assert( sourceFileName != 0 );
712 cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";