The startstate, first final and error state writing can be moved to FsmCodeGen.
[external/ragel.git] / rlgen-cd / fsmcodegen.cpp
1 /*
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>
5  */
6
7 /*  This file is part of Ragel.
8  *
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.
13  * 
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.
18  * 
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 
22  */
23
24 #include "rlgen-cd.h"
25 #include "fsmcodegen.h"
26 #include "redfsm.h"
27 #include "gendata.h"
28 #include <sstream>
29 #include <string>
30 #include <assert.h>
31
32
33 using std::ostream;
34 using std::ostringstream;
35 using std::string;
36 using std::cerr;
37 using std::endl;
38
39 void lineDirective( ostream &out, char *fileName, int line )
40 {
41         if ( noLineDirectives )
42                 out << "/* ";
43
44         /* Write the preprocessor line info for to the input file. */
45         out << "#line " << line  << " \"";
46         for ( char *pc = fileName; *pc != 0; pc++ ) {
47                 if ( *pc == '\\' )
48                         out << "\\\\";
49                 else
50                         out << *pc;
51         }
52         out << '"';
53
54         if ( noLineDirectives )
55                 out << " */";
56
57         out << '\n';
58 }
59
60 void genLineDirective( ostream &out )
61 {
62         std::streambuf *sbuf = out.rdbuf();
63         output_filter *filter = static_cast<output_filter*>(sbuf);
64         lineDirective( out, filter->fileName, filter->line + 1 );
65 }
66
67
68 /* Init code gen with in parameters. */
69 FsmCodeGen::FsmCodeGen( ostream &out )
70 :
71         CodeGenData(out)
72 {
73 }
74
75 unsigned int FsmCodeGen::arrayTypeSize( unsigned long maxVal )
76 {
77         long long maxValLL = (long long) maxVal;
78         HostType *arrayType = keyOps->typeSubsumes( maxValLL );
79         assert( arrayType != 0 );
80         return arrayType->size;
81 }
82
83 string FsmCodeGen::ARRAY_TYPE( unsigned long maxVal )
84 {
85         long long maxValLL = (long long) maxVal;
86         HostType *arrayType = keyOps->typeSubsumes( maxValLL );
87         assert( arrayType != 0 );
88
89         string ret = arrayType->data1;
90         if ( arrayType->data2 != 0 ) {
91                 ret += " ";
92                 ret += arrayType->data2;
93         }
94         return ret;
95 }
96
97
98 /* Write out the fsm name. */
99 string FsmCodeGen::FSM_NAME()
100 {
101         return fsmName;
102 }
103
104 /* Emit the offset of the start state as a decimal integer. */
105 string FsmCodeGen::START_STATE_ID()
106 {
107         ostringstream ret;
108         ret << redFsm->startState->id;
109         return ret.str();
110 };
111
112 /* Write out the array of actions. */
113 std::ostream &FsmCodeGen::ACTIONS_ARRAY()
114 {
115         out << "\t0, ";
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 )
122                         out << "\n\t";
123
124                 for ( ActionTable::Iter item = act->key; item.lte(); item++ ) {
125                         out << item->value->actionId;
126                         if ( ! (act.last() && item.last()) )
127                                 out << ", ";
128
129                         /* Put in a line break every 8 */
130                         if ( totalActions++ % 8 == 7 )
131                                 out << "\n\t";
132                 }
133         }
134         out << "\n";
135         return out;
136 }
137
138
139 string FsmCodeGen::CS()
140 {
141         ostringstream ret;
142         if ( curStateExpr != 0 ) { 
143                 /* Emit the user supplied method of retrieving the key. */
144                 ret << "(";
145                 INLINE_LIST( ret, curStateExpr, 0, false );
146                 ret << ")";
147         }
148         else {
149                 /* Expression for retrieving the key, use simple dereference. */
150                 ret << ACCESS() << "cs";
151         }
152         return ret.str();
153 }
154
155 string FsmCodeGen::ACCESS()
156 {
157         ostringstream ret;
158         if ( accessExpr != 0 )
159                 INLINE_LIST( ret, accessExpr, 0, false );
160         return ret.str();
161 }
162
163 string FsmCodeGen::GET_WIDE_KEY()
164 {
165         if ( redFsm->anyConditions() ) 
166                 return "_widec";
167         else
168                 return GET_KEY();
169 }
170
171 string FsmCodeGen::GET_WIDE_KEY( RedStateAp *state )
172 {
173         if ( state->stateCondList.length() > 0 )
174                 return "_widec";
175         else
176                 return GET_KEY();
177 }
178
179 string FsmCodeGen::GET_KEY()
180 {
181         ostringstream ret;
182         if ( getKeyExpr != 0 ) { 
183                 /* Emit the user supplied method of retrieving the key. */
184                 ret << "(";
185                 INLINE_LIST( ret, getKeyExpr, 0, false );
186                 ret << ")";
187         }
188         else {
189                 /* Expression for retrieving the key, use simple dereference. */
190                 ret << "(*" << P() << ")";
191         }
192         return ret.str();
193 }
194
195 /* Write out level number of tabs. Makes the nested binary search nice
196  * looking. */
197 string FsmCodeGen::TABS( int level )
198 {
199         string result;
200         while ( level-- > 0 )
201                 result += "\t";
202         return result;
203 }
204
205 /* Write out a key from the fsm code gen. Depends on wether or not the key is
206  * signed. */
207 string FsmCodeGen::KEY( Key key )
208 {
209         ostringstream ret;
210         if ( keyOps->isSigned || !hostLang->explicitUnsigned )
211                 ret << key.getVal();
212         else
213                 ret << (unsigned long) key.getVal() << 'u';
214         return ret.str();
215 }
216
217 void FsmCodeGen::EXEC( ostream &ret, InlineItem *item, int targState, int inFinish )
218 {
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 );
224         ret << "))-1;}";
225 }
226
227 void FsmCodeGen::EXECTE( ostream &ret, InlineItem *item, int targState, int inFinish )
228 {
229         /* Tokend version of exec. */
230
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 );
236         ret << "));}";
237 }
238
239
240 void FsmCodeGen::LM_SWITCH( ostream &ret, InlineItem *item, 
241                 int targState, int inFinish )
242 {
243         ret << 
244                 "       switch( " << ACT() << " ) {\n";
245
246         /* If the switch handles error then we also forced the error state. It
247          * will exist. */
248         if ( item->handlesError ) {
249                 ret << "        case 0: " << TOKEND() << " = " << TOKSTART() << "; ";
250                 GOTO( ret, redFsm->errState->id, inFinish );
251                 ret << "\n";
252         }
253
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";
257
258                 /* Write the block and close it off. */
259                 ret << "        {";
260                 INLINE_LIST( ret, lma->children, targState, inFinish );
261                 ret << "}\n";
262
263                 ret << "        break;\n";
264         }
265         /* Default required for D code. */
266         ret << 
267                 "       default: break;\n"
268                 "       }\n"
269                 "\t";
270 }
271
272 void FsmCodeGen::SET_ACT( ostream &ret, InlineItem *item )
273 {
274         ret << ACT() << " = " << item->lmId << ";";
275 }
276
277 void FsmCodeGen::SET_TOKEND( ostream &ret, InlineItem *item )
278 {
279         /* The tokend action sets tokend. */
280         ret << TOKEND() << " = " << P();
281         if ( item->offset != 0 ) 
282                 out << "+" << item->offset;
283         out << ";";
284 }
285
286 void FsmCodeGen::GET_TOKEND( ostream &ret, InlineItem *item )
287 {
288         ret << TOKEND();
289 }
290
291 void FsmCodeGen::INIT_TOKSTART( ostream &ret, InlineItem *item )
292 {
293         ret << TOKSTART() << " = " << NULL_ITEM() << ";";
294 }
295
296 void FsmCodeGen::INIT_ACT( ostream &ret, InlineItem *item )
297 {
298         ret << ACT() << " = 0;";
299 }
300
301 void FsmCodeGen::SET_TOKSTART( ostream &ret, InlineItem *item )
302 {
303         ret << TOKSTART() << " = " << P() << ";";
304 }
305
306 void FsmCodeGen::SUB_ACTION( ostream &ret, InlineItem *item, 
307                 int targState, bool inFinish )
308 {
309         if ( item->children->length() > 0 ) {
310                 /* Write the block and close it off. */
311                 ret << "{";
312                 INLINE_LIST( ret, item->children, targState, inFinish );
313                 ret << "}";
314         }
315 }
316
317
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 )
322 {
323         for ( InlineList::Iter item = *inlineList; item.lte(); item++ ) {
324                 switch ( item->type ) {
325                 case InlineItem::Text:
326                         ret << item->data;
327                         break;
328                 case InlineItem::Goto:
329                         GOTO( ret, item->targState->id, inFinish );
330                         break;
331                 case InlineItem::Call:
332                         CALL( ret, item->targState->id, targState, inFinish );
333                         break;
334                 case InlineItem::Next:
335                         NEXT( ret, item->targState->id, inFinish );
336                         break;
337                 case InlineItem::Ret:
338                         RET( ret, inFinish );
339                         break;
340                 case InlineItem::PChar:
341                         ret << P();
342                         break;
343                 case InlineItem::Char:
344                         ret << GET_KEY();
345                         break;
346                 case InlineItem::Hold:
347                         ret << P() << "--;";
348                         break;
349                 case InlineItem::Exec:
350                         EXEC( ret, item, targState, inFinish );
351                         break;
352                 case InlineItem::HoldTE:
353                         ret << TOKEND() << "--;";
354                         break;
355                 case InlineItem::ExecTE:
356                         EXECTE( ret, item, targState, inFinish );
357                         break;
358                 case InlineItem::Curs:
359                         CURS( ret, inFinish );
360                         break;
361                 case InlineItem::Targs:
362                         TARGS( ret, inFinish, targState );
363                         break;
364                 case InlineItem::Entry:
365                         ret << item->targState->id;
366                         break;
367                 case InlineItem::GotoExpr:
368                         GOTO_EXPR( ret, item, inFinish );
369                         break;
370                 case InlineItem::CallExpr:
371                         CALL_EXPR( ret, item, targState, inFinish );
372                         break;
373                 case InlineItem::NextExpr:
374                         NEXT_EXPR( ret, item, inFinish );
375                         break;
376                 case InlineItem::LmSwitch:
377                         LM_SWITCH( ret, item, targState, inFinish );
378                         break;
379                 case InlineItem::LmSetActId:
380                         SET_ACT( ret, item );
381                         break;
382                 case InlineItem::LmSetTokEnd:
383                         SET_TOKEND( ret, item );
384                         break;
385                 case InlineItem::LmGetTokEnd:
386                         GET_TOKEND( ret, item );
387                         break;
388                 case InlineItem::LmInitTokStart:
389                         INIT_TOKSTART( ret, item );
390                         break;
391                 case InlineItem::LmInitAct:
392                         INIT_ACT( ret, item );
393                         break;
394                 case InlineItem::LmSetTokStart:
395                         SET_TOKSTART( ret, item );
396                         break;
397                 case InlineItem::SubAction:
398                         SUB_ACTION( ret, item, targState, inFinish );
399                         break;
400                 case InlineItem::Break:
401                         BREAK( ret, targState );
402                         break;
403                 }
404         }
405 }
406 /* Write out paths in line directives. Escapes any special characters. */
407 string FsmCodeGen::LDIR_PATH( char *path )
408 {
409         ostringstream ret;
410         for ( char *pc = path; *pc != 0; pc++ ) {
411                 if ( *pc == '\\' )
412                         ret << "\\\\";
413                 else
414                         ret << *pc;
415         }
416         return ret.str();
417 }
418
419 void FsmCodeGen::ACTION( ostream &ret, Action *action, int targState, bool inFinish )
420 {
421         /* Write the preprocessor line info for going into the source file. */
422         lineDirective( ret, sourceFileName, action->loc.line );
423
424         /* Write the block and close it off. */
425         ret << "\t{";
426         INLINE_LIST( ret, action->inlineList, targState, inFinish );
427         ret << "}\n";
428 }
429
430 void FsmCodeGen::CONDITION( ostream &ret, Action *condition )
431 {
432         ret << "\n";
433         lineDirective( ret, sourceFileName, condition->loc.line );
434         INLINE_LIST( ret, condition->inlineList, 0, false );
435 }
436
437 string FsmCodeGen::ERROR_STATE()
438 {
439         ostringstream ret;
440         if ( redFsm->errState != 0 )
441                 ret << redFsm->errState->id;
442         else
443                 ret << "-1";
444         return ret.str();
445 }
446
447 string FsmCodeGen::FIRST_FINAL_STATE()
448 {
449         ostringstream ret;
450         if ( redFsm->firstFinState != 0 )
451                 ret << redFsm->firstFinState->id;
452         else
453                 ret << redFsm->nextStateId;
454         return ret.str();
455 }
456
457 void FsmCodeGen::writeInit()
458 {
459         out << "        {\n";
460         out << "\t" << CS() << " = " << START() << ";\n";
461         
462         /* If there are any calls, then the stack top needs initialization. */
463         if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
464                 out << "\t" << TOP() << " = 0;\n";
465
466         if ( hasLongestMatch ) {
467                 out << 
468                         "       " << TOKSTART() << " = " << NULL_ITEM() << ";\n"
469                         "       " << TOKEND() << " = " << NULL_ITEM() << ";\n"
470                         "       " << ACT() << " = 0;\n";
471         }
472         out << "        }\n";
473 }
474
475 string FsmCodeGen::DATA_PREFIX()
476 {
477         if ( dataPrefix )
478                 return FSM_NAME() + "_";
479         return "";
480 }
481
482 /* Emit the alphabet data type. */
483 string FsmCodeGen::ALPH_TYPE()
484 {
485         string ret = keyOps->alphType->data1;
486         if ( keyOps->alphType->data2 != 0 ) {
487                 ret += " ";
488                 ret += + keyOps->alphType->data2;
489         }
490         return ret;
491 }
492
493 /* Emit the alphabet data type. */
494 string FsmCodeGen::WIDE_ALPH_TYPE()
495 {
496         string ret;
497         if ( redFsm->maxKey <= keyOps->maxKey )
498                 ret = ALPH_TYPE();
499         else {
500                 long long maxKeyVal = redFsm->maxKey.getLongLong();
501                 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
502                 assert( wideType != 0 );
503
504                 ret = wideType->data1;
505                 if ( wideType->data2 != 0 ) {
506                         ret += " ";
507                         ret += wideType->data2;
508                 }
509         }
510         return ret;
511 }
512
513 void FsmCodeGen::STATE_IDS()
514 {
515         STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
516
517         if ( writeFirstFinal )
518                 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
519
520         if ( writeErr )
521                 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
522
523         out << "\n";
524
525         if ( entryPointNames.length() > 0 ) {
526                 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
527                         STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) << 
528                                         " = " << entryPointIds[en.pos()] << ";\n";
529                 }
530                 out << "\n";
531         }
532 }
533
534 void FsmCodeGen::writeExports()
535 {
536         if ( exportList.length() > 0 ) {
537                 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
538                         out << "#define " << DATA_PREFIX() << ex->name << " " << 
539                                         KEY(ex->key) << "\n";
540                 }
541                 out << "\n";
542         }
543 }
544
545
546 /*
547  * Language specific, but style independent code generators functions.
548  */
549
550 string CCodeGen::PTR_CONST()
551 {
552         return "const ";
553 }
554
555 std::ostream &CCodeGen::OPEN_ARRAY( string type, string name )
556 {
557         out << "static const " << type << " " << name << "[] = {\n";
558         return out;
559 }
560
561 std::ostream &CCodeGen::CLOSE_ARRAY()
562 {
563         return out << "};\n";
564 }
565
566 std::ostream &CCodeGen::STATIC_VAR( string type, string name )
567 {
568         out << "static const " << type << " " << name;
569         return out;
570 }
571
572 string CCodeGen::UINT( )
573 {
574         return "unsigned int";
575 }
576
577 string CCodeGen::ARR_OFF( string ptr, string offset )
578 {
579         return ptr + " + " + offset;
580 }
581
582 string CCodeGen::CAST( string type )
583 {
584         return "(" + type + ")";
585 }
586
587 string CCodeGen::NULL_ITEM()
588 {
589         return "0";
590 }
591
592 string CCodeGen::POINTER()
593 {
594         return " *";
595 }
596
597 std::ostream &CCodeGen::SWITCH_DEFAULT()
598 {
599         return out;
600 }
601
602 string CCodeGen::CTRL_FLOW()
603 {
604         return "";
605 }
606
607 /*
608  * D Specific
609  */
610
611 string DCodeGen::NULL_ITEM()
612 {
613         return "null";
614 }
615
616 string DCodeGen::POINTER()
617 {
618         // multiple items seperated by commas can also be pointer types.
619         return "* ";
620 }
621
622 string DCodeGen::PTR_CONST()
623 {
624         return "";
625 }
626
627 std::ostream &DCodeGen::OPEN_ARRAY( string type, string name )
628 {
629         out << "static const " << type << "[] " << name << " = [\n";
630         return out;
631 }
632
633 std::ostream &DCodeGen::CLOSE_ARRAY()
634 {
635         return out << "];\n";
636 }
637
638 std::ostream &DCodeGen::STATIC_VAR( string type, string name )
639 {
640         out << "static const " << type << " " << name;
641         return out;
642 }
643
644 string DCodeGen::ARR_OFF( string ptr, string offset )
645 {
646         return "&" + ptr + "[" + offset + "]";
647 }
648
649 string DCodeGen::CAST( string type )
650 {
651         return "cast(" + type + ")";
652 }
653
654 string DCodeGen::UINT( )
655 {
656         return "uint";
657 }
658
659 std::ostream &DCodeGen::SWITCH_DEFAULT()
660 {
661         out << "                default: break;\n";
662         return out;
663 }
664
665 string DCodeGen::CTRL_FLOW()
666 {
667         return "if (true) ";
668 }
669
670 void FsmCodeGen::finishRagelDef()
671 {
672         if ( codeStyle == GenGoto || codeStyle == GenFGoto || 
673                         codeStyle == GenIpGoto || codeStyle == GenSplit )
674         {
675                 /* For directly executable machines there is no required state
676                  * ordering. Choose a depth-first ordering to increase the
677                  * potential for fall-throughs. */
678                 redFsm->depthFirstOrdering();
679         }
680         else {
681                 /* The frontend will do this for us, but it may be a good idea to
682                  * force it if the intermediate file is edited. */
683                 redFsm->sortByStateId();
684         }
685
686         /* Choose default transitions and the single transition. */
687         redFsm->chooseDefaultSpan();
688                 
689         /* Maybe do flat expand, otherwise choose single. */
690         if ( codeStyle == GenFlat || codeStyle == GenFFlat )
691                 redFsm->makeFlat();
692         else
693                 redFsm->chooseSingle();
694
695         /* If any errors have occured in the input file then don't write anything. */
696         if ( gblErrorCount > 0 )
697                 return;
698         
699         if ( codeStyle == GenSplit )
700                 redFsm->partitionFsm( numSplitPartitions );
701
702         if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
703                 redFsm->setInTrans();
704
705         /* Anlayze Machine will find the final action reference counts, among
706          * other things. We will use these in reporting the usage
707          * of fsm directives in action code. */
708         analyzeMachine();
709
710         /* Determine if we should use indicies. */
711         calcIndexSize();
712 }
713
714 ostream &FsmCodeGen::source_warning( const InputLoc &loc )
715 {
716         cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
717         return cerr;
718 }
719
720 ostream &FsmCodeGen::source_error( const InputLoc &loc )
721 {
722         gblErrorCount += 1;
723         assert( sourceFileName != 0 );
724         cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
725         return cerr;
726 }
727