Can cleanup the xml code generation and remove the holdte and execte tags
[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::ACCESS()
140 {
141         ostringstream ret;
142         if ( accessExpr != 0 )
143                 INLINE_LIST( ret, accessExpr, 0, false );
144         return ret.str();
145 }
146
147
148 string FsmCodeGen::P()
149
150         ostringstream ret;
151         if ( pExpr == 0 )
152                 ret << "p";
153         else {
154                 ret << "(";
155                 INLINE_LIST( ret, pExpr, 0, false );
156                 ret << ")";
157         }
158         return ret.str();
159 }
160
161 string FsmCodeGen::PE()
162 {
163         ostringstream ret;
164         if ( peExpr == 0 )
165                 ret << "pe";
166         else {
167                 ret << "(";
168                 INLINE_LIST( ret, peExpr, 0, false );
169                 ret << ")";
170         }
171         return ret.str();
172 }
173
174 string FsmCodeGen::CS()
175 {
176         ostringstream ret;
177         if ( csExpr == 0 )
178                 ret << ACCESS() << "cs";
179         else {
180                 /* Emit the user supplied method of retrieving the key. */
181                 ret << "(";
182                 INLINE_LIST( ret, csExpr, 0, false );
183                 ret << ")";
184         }
185         return ret.str();
186 }
187
188 string FsmCodeGen::TOP()
189 {
190         ostringstream ret;
191         if ( topExpr == 0 )
192                 ret << ACCESS() + "top";
193         else {
194                 ret << "(";
195                 INLINE_LIST( ret, topExpr, 0, false );
196                 ret << ")";
197         }
198         return ret.str();
199 }
200
201 string FsmCodeGen::STACK()
202 {
203         ostringstream ret;
204         if ( stackExpr == 0 )
205                 ret << ACCESS() + "stack";
206         else {
207                 ret << "(";
208                 INLINE_LIST( ret, stackExpr, 0, false );
209                 ret << ")";
210         }
211         return ret.str();
212 }
213
214 string FsmCodeGen::ACT()
215 {
216         ostringstream ret;
217         if ( actExpr == 0 )
218                 ret << ACCESS() + "act";
219         else {
220                 ret << "(";
221                 INLINE_LIST( ret, actExpr, 0, false );
222                 ret << ")";
223         }
224         return ret.str();
225 }
226
227 string FsmCodeGen::TOKSTART()
228 {
229         ostringstream ret;
230         if ( tokstartExpr == 0 )
231                 ret << ACCESS() + "tokstart";
232         else {
233                 ret << "(";
234                 INLINE_LIST( ret, tokstartExpr, 0, false );
235                 ret << ")";
236         }
237         return ret.str();
238 }
239
240 string FsmCodeGen::TOKEND()
241 {
242         ostringstream ret;
243         if ( tokendExpr == 0 )
244                 ret << ACCESS() + "tokend";
245         else {
246                 ret << "(";
247                 INLINE_LIST( ret, tokendExpr, 0, false );
248                 ret << ")";
249         }
250         return ret.str();
251 }
252
253 string FsmCodeGen::GET_WIDE_KEY()
254 {
255         if ( redFsm->anyConditions() ) 
256                 return "_widec";
257         else
258                 return GET_KEY();
259 }
260
261 string FsmCodeGen::GET_WIDE_KEY( RedStateAp *state )
262 {
263         if ( state->stateCondList.length() > 0 )
264                 return "_widec";
265         else
266                 return GET_KEY();
267 }
268
269 string FsmCodeGen::GET_KEY()
270 {
271         ostringstream ret;
272         if ( getKeyExpr != 0 ) { 
273                 /* Emit the user supplied method of retrieving the key. */
274                 ret << "(";
275                 INLINE_LIST( ret, getKeyExpr, 0, false );
276                 ret << ")";
277         }
278         else {
279                 /* Expression for retrieving the key, use simple dereference. */
280                 ret << "(*" << P() << ")";
281         }
282         return ret.str();
283 }
284
285 /* Write out level number of tabs. Makes the nested binary search nice
286  * looking. */
287 string FsmCodeGen::TABS( int level )
288 {
289         string result;
290         while ( level-- > 0 )
291                 result += "\t";
292         return result;
293 }
294
295 /* Write out a key from the fsm code gen. Depends on wether or not the key is
296  * signed. */
297 string FsmCodeGen::KEY( Key key )
298 {
299         ostringstream ret;
300         if ( keyOps->isSigned || !hostLang->explicitUnsigned )
301                 ret << key.getVal();
302         else
303                 ret << (unsigned long) key.getVal() << 'u';
304         return ret.str();
305 }
306
307 void FsmCodeGen::EXEC( ostream &ret, InlineItem *item, int targState, int inFinish )
308 {
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 );
314         ret << "))-1;}";
315 }
316
317 void FsmCodeGen::LM_SWITCH( ostream &ret, InlineItem *item, 
318                 int targState, int inFinish )
319 {
320         ret << 
321                 "       switch( " << ACT() << " ) {\n";
322
323         for ( InlineList::Iter lma = *item->children; lma.lte(); lma++ ) {
324                 /* Write the case label, the action and the case break. */
325                 ret << "        case " << lma->lmId << ":\n";
326
327                 /* Write the block and close it off. */
328                 ret << "        {";
329                 INLINE_LIST( ret, lma->children, targState, inFinish );
330                 ret << "}\n";
331
332                 ret << "        break;\n";
333         }
334         /* Default required for D code. */
335         ret << 
336                 "       default: break;\n"
337                 "       }\n"
338                 "\t";
339 }
340
341 void FsmCodeGen::SET_ACT( ostream &ret, InlineItem *item )
342 {
343         ret << ACT() << " = " << item->lmId << ";";
344 }
345
346 void FsmCodeGen::SET_TOKEND( ostream &ret, InlineItem *item )
347 {
348         /* The tokend action sets tokend. */
349         ret << TOKEND() << " = " << P();
350         if ( item->offset != 0 ) 
351                 out << "+" << item->offset;
352         out << ";";
353 }
354
355 void FsmCodeGen::GET_TOKEND( ostream &ret, InlineItem *item )
356 {
357         ret << TOKEND();
358 }
359
360 void FsmCodeGen::INIT_TOKSTART( ostream &ret, InlineItem *item )
361 {
362         ret << TOKSTART() << " = " << NULL_ITEM() << ";";
363 }
364
365 void FsmCodeGen::INIT_ACT( ostream &ret, InlineItem *item )
366 {
367         ret << ACT() << " = 0;";
368 }
369
370 void FsmCodeGen::SET_TOKSTART( ostream &ret, InlineItem *item )
371 {
372         ret << TOKSTART() << " = " << P() << ";";
373 }
374
375 void FsmCodeGen::SUB_ACTION( ostream &ret, InlineItem *item, 
376                 int targState, bool inFinish )
377 {
378         if ( item->children->length() > 0 ) {
379                 /* Write the block and close it off. */
380                 ret << "{";
381                 INLINE_LIST( ret, item->children, targState, inFinish );
382                 ret << "}";
383         }
384 }
385
386
387 /* Write out an inline tree structure. Walks the list and possibly calls out
388  * to virtual functions than handle language specific items in the tree. */
389 void FsmCodeGen::INLINE_LIST( ostream &ret, InlineList *inlineList, 
390                 int targState, bool inFinish )
391 {
392         for ( InlineList::Iter item = *inlineList; item.lte(); item++ ) {
393                 switch ( item->type ) {
394                 case InlineItem::Text:
395                         ret << item->data;
396                         break;
397                 case InlineItem::Goto:
398                         GOTO( ret, item->targState->id, inFinish );
399                         break;
400                 case InlineItem::Call:
401                         CALL( ret, item->targState->id, targState, inFinish );
402                         break;
403                 case InlineItem::Next:
404                         NEXT( ret, item->targState->id, inFinish );
405                         break;
406                 case InlineItem::Ret:
407                         RET( ret, inFinish );
408                         break;
409                 case InlineItem::PChar:
410                         ret << P();
411                         break;
412                 case InlineItem::Char:
413                         ret << GET_KEY();
414                         break;
415                 case InlineItem::Hold:
416                         ret << P() << "--;";
417                         break;
418                 case InlineItem::Exec:
419                         EXEC( ret, item, targState, inFinish );
420                         break;
421                 case InlineItem::Curs:
422                         CURS( ret, inFinish );
423                         break;
424                 case InlineItem::Targs:
425                         TARGS( ret, inFinish, targState );
426                         break;
427                 case InlineItem::Entry:
428                         ret << item->targState->id;
429                         break;
430                 case InlineItem::GotoExpr:
431                         GOTO_EXPR( ret, item, inFinish );
432                         break;
433                 case InlineItem::CallExpr:
434                         CALL_EXPR( ret, item, targState, inFinish );
435                         break;
436                 case InlineItem::NextExpr:
437                         NEXT_EXPR( ret, item, inFinish );
438                         break;
439                 case InlineItem::LmSwitch:
440                         LM_SWITCH( ret, item, targState, inFinish );
441                         break;
442                 case InlineItem::LmSetActId:
443                         SET_ACT( ret, item );
444                         break;
445                 case InlineItem::LmSetTokEnd:
446                         SET_TOKEND( ret, item );
447                         break;
448                 case InlineItem::LmGetTokEnd:
449                         GET_TOKEND( ret, item );
450                         break;
451                 case InlineItem::LmInitTokStart:
452                         INIT_TOKSTART( ret, item );
453                         break;
454                 case InlineItem::LmInitAct:
455                         INIT_ACT( ret, item );
456                         break;
457                 case InlineItem::LmSetTokStart:
458                         SET_TOKSTART( ret, item );
459                         break;
460                 case InlineItem::SubAction:
461                         SUB_ACTION( ret, item, targState, inFinish );
462                         break;
463                 case InlineItem::Break:
464                         BREAK( ret, targState );
465                         break;
466                 }
467         }
468 }
469 /* Write out paths in line directives. Escapes any special characters. */
470 string FsmCodeGen::LDIR_PATH( char *path )
471 {
472         ostringstream ret;
473         for ( char *pc = path; *pc != 0; pc++ ) {
474                 if ( *pc == '\\' )
475                         ret << "\\\\";
476                 else
477                         ret << *pc;
478         }
479         return ret.str();
480 }
481
482 void FsmCodeGen::ACTION( ostream &ret, Action *action, int targState, bool inFinish )
483 {
484         /* Write the preprocessor line info for going into the source file. */
485         lineDirective( ret, sourceFileName, action->loc.line );
486
487         /* Write the block and close it off. */
488         ret << "\t{";
489         INLINE_LIST( ret, action->inlineList, targState, inFinish );
490         ret << "}\n";
491 }
492
493 void FsmCodeGen::CONDITION( ostream &ret, Action *condition )
494 {
495         ret << "\n";
496         lineDirective( ret, sourceFileName, condition->loc.line );
497         INLINE_LIST( ret, condition->inlineList, 0, false );
498 }
499
500 string FsmCodeGen::ERROR_STATE()
501 {
502         ostringstream ret;
503         if ( redFsm->errState != 0 )
504                 ret << redFsm->errState->id;
505         else
506                 ret << "-1";
507         return ret.str();
508 }
509
510 string FsmCodeGen::FIRST_FINAL_STATE()
511 {
512         ostringstream ret;
513         if ( redFsm->firstFinState != 0 )
514                 ret << redFsm->firstFinState->id;
515         else
516                 ret << redFsm->nextStateId;
517         return ret.str();
518 }
519
520 void FsmCodeGen::writeInit()
521 {
522         out << "        {\n";
523
524         if ( writeCS )
525                 out << "\t" << CS() << " = " << START() << ";\n";
526         
527         /* If there are any calls, then the stack top needs initialization. */
528         if ( redFsm->anyActionCalls() || redFsm->anyActionRets() )
529                 out << "\t" << TOP() << " = 0;\n";
530
531         if ( hasLongestMatch ) {
532                 out << 
533                         "       " << TOKSTART() << " = " << NULL_ITEM() << ";\n"
534                         "       " << TOKEND() << " = " << NULL_ITEM() << ";\n"
535                         "       " << ACT() << " = 0;\n";
536         }
537         out << "        }\n";
538 }
539
540 string FsmCodeGen::DATA_PREFIX()
541 {
542         if ( dataPrefix )
543                 return FSM_NAME() + "_";
544         return "";
545 }
546
547 /* Emit the alphabet data type. */
548 string FsmCodeGen::ALPH_TYPE()
549 {
550         string ret = keyOps->alphType->data1;
551         if ( keyOps->alphType->data2 != 0 ) {
552                 ret += " ";
553                 ret += + keyOps->alphType->data2;
554         }
555         return ret;
556 }
557
558 /* Emit the alphabet data type. */
559 string FsmCodeGen::WIDE_ALPH_TYPE()
560 {
561         string ret;
562         if ( redFsm->maxKey <= keyOps->maxKey )
563                 ret = ALPH_TYPE();
564         else {
565                 long long maxKeyVal = redFsm->maxKey.getLongLong();
566                 HostType *wideType = keyOps->typeSubsumes( keyOps->isSigned, maxKeyVal );
567                 assert( wideType != 0 );
568
569                 ret = wideType->data1;
570                 if ( wideType->data2 != 0 ) {
571                         ret += " ";
572                         ret += wideType->data2;
573                 }
574         }
575         return ret;
576 }
577
578 void FsmCodeGen::STATE_IDS()
579 {
580         if ( redFsm->startState != 0 )
581                 STATIC_VAR( "int", START() ) << " = " << START_STATE_ID() << ";\n";
582
583         if ( writeFirstFinal )
584                 STATIC_VAR( "int" , FIRST_FINAL() ) << " = " << FIRST_FINAL_STATE() << ";\n";
585
586         if ( writeErr )
587                 STATIC_VAR( "int", ERROR() ) << " = " << ERROR_STATE() << ";\n";
588
589         out << "\n";
590
591         if ( entryPointNames.length() > 0 ) {
592                 for ( EntryNameVect::Iter en = entryPointNames; en.lte(); en++ ) {
593                         STATIC_VAR( "int", DATA_PREFIX() + "en_" + *en ) << 
594                                         " = " << entryPointIds[en.pos()] << ";\n";
595                 }
596                 out << "\n";
597         }
598 }
599
600
601 /*
602  * Language specific, but style independent code generators functions.
603  */
604
605 string CCodeGen::PTR_CONST()
606 {
607         return "const ";
608 }
609
610 std::ostream &CCodeGen::OPEN_ARRAY( string type, string name )
611 {
612         out << "static const " << type << " " << name << "[] = {\n";
613         return out;
614 }
615
616 std::ostream &CCodeGen::CLOSE_ARRAY()
617 {
618         return out << "};\n";
619 }
620
621 std::ostream &CCodeGen::STATIC_VAR( string type, string name )
622 {
623         out << "static const " << type << " " << name;
624         return out;
625 }
626
627 string CCodeGen::UINT( )
628 {
629         return "unsigned int";
630 }
631
632 string CCodeGen::ARR_OFF( string ptr, string offset )
633 {
634         return ptr + " + " + offset;
635 }
636
637 string CCodeGen::CAST( string type )
638 {
639         return "(" + type + ")";
640 }
641
642 string CCodeGen::NULL_ITEM()
643 {
644         return "0";
645 }
646
647 string CCodeGen::POINTER()
648 {
649         return " *";
650 }
651
652 std::ostream &CCodeGen::SWITCH_DEFAULT()
653 {
654         return out;
655 }
656
657 string CCodeGen::CTRL_FLOW()
658 {
659         return "";
660 }
661
662 void CCodeGen::writeExports()
663 {
664         if ( exportList.length() > 0 ) {
665                 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
666                         out << "#define " << DATA_PREFIX() << "ex_" << ex->name << " " << 
667                                         KEY(ex->key) << "\n";
668                 }
669                 out << "\n";
670         }
671 }
672
673 /*
674  * D Specific
675  */
676
677 string DCodeGen::NULL_ITEM()
678 {
679         return "null";
680 }
681
682 string DCodeGen::POINTER()
683 {
684         // multiple items seperated by commas can also be pointer types.
685         return "* ";
686 }
687
688 string DCodeGen::PTR_CONST()
689 {
690         return "";
691 }
692
693 std::ostream &DCodeGen::OPEN_ARRAY( string type, string name )
694 {
695         out << "static const " << type << "[] " << name << " = [\n";
696         return out;
697 }
698
699 std::ostream &DCodeGen::CLOSE_ARRAY()
700 {
701         return out << "];\n";
702 }
703
704 std::ostream &DCodeGen::STATIC_VAR( string type, string name )
705 {
706         out << "static const " << type << " " << name;
707         return out;
708 }
709
710 string DCodeGen::ARR_OFF( string ptr, string offset )
711 {
712         return "&" + ptr + "[" + offset + "]";
713 }
714
715 string DCodeGen::CAST( string type )
716 {
717         return "cast(" + type + ")";
718 }
719
720 string DCodeGen::UINT( )
721 {
722         return "uint";
723 }
724
725 std::ostream &DCodeGen::SWITCH_DEFAULT()
726 {
727         out << "                default: break;\n";
728         return out;
729 }
730
731 string DCodeGen::CTRL_FLOW()
732 {
733         return "if (true) ";
734 }
735
736 void DCodeGen::writeExports()
737 {
738         if ( exportList.length() > 0 ) {
739                 for ( ExportList::Iter ex = exportList; ex.lte(); ex++ ) {
740                         out << "static const " << ALPH_TYPE() << " " << DATA_PREFIX() << 
741                                         "ex_" << ex->name << " = " << KEY(ex->key) << ";\n";
742                 }
743                 out << "\n";
744         }
745 }
746
747 /*
748  * End D-specific code.
749  */
750
751 void FsmCodeGen::finishRagelDef()
752 {
753         if ( codeStyle == GenGoto || codeStyle == GenFGoto || 
754                         codeStyle == GenIpGoto || codeStyle == GenSplit )
755         {
756                 /* For directly executable machines there is no required state
757                  * ordering. Choose a depth-first ordering to increase the
758                  * potential for fall-throughs. */
759                 redFsm->depthFirstOrdering();
760         }
761         else {
762                 /* The frontend will do this for us, but it may be a good idea to
763                  * force it if the intermediate file is edited. */
764                 redFsm->sortByStateId();
765         }
766
767         /* Choose default transitions and the single transition. */
768         redFsm->chooseDefaultSpan();
769                 
770         /* Maybe do flat expand, otherwise choose single. */
771         if ( codeStyle == GenFlat || codeStyle == GenFFlat )
772                 redFsm->makeFlat();
773         else
774                 redFsm->chooseSingle();
775
776         /* If any errors have occured in the input file then don't write anything. */
777         if ( gblErrorCount > 0 )
778                 return;
779         
780         if ( codeStyle == GenSplit )
781                 redFsm->partitionFsm( numSplitPartitions );
782
783         if ( codeStyle == GenIpGoto || codeStyle == GenSplit )
784                 redFsm->setInTrans();
785
786         /* Anlayze Machine will find the final action reference counts, among
787          * other things. We will use these in reporting the usage
788          * of fsm directives in action code. */
789         analyzeMachine();
790
791         /* Determine if we should use indicies. */
792         calcIndexSize();
793 }
794
795 ostream &FsmCodeGen::source_warning( const InputLoc &loc )
796 {
797         cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": warning: ";
798         return cerr;
799 }
800
801 ostream &FsmCodeGen::source_error( const InputLoc &loc )
802 {
803         gblErrorCount += 1;
804         assert( sourceFileName != 0 );
805         cerr << sourceFileName << ":" << loc.line << ":" << loc.col << ": ";
806         return cerr;
807 }
808