Remainder of warnings fixed.
[external/ragel.git] / ragel / main.cpp
1 /*
2  *  Copyright 2001-2007 Adrian Thurston <thurston@cs.queensu.ca>
3  */
4
5 /*  This file is part of Ragel.
6  *
7  *  Ragel is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  * 
12  *  Ragel is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  * 
17  *  You should have received a copy of the GNU General Public License
18  *  along with Ragel; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
20  */
21
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <iostream>
26 #include <fstream>
27 #include <unistd.h>
28 #include <sstream>
29 #include <unistd.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <errno.h>
34
35 #ifndef WIN32
36 #include <sys/wait.h>
37 #else
38 #include <windows.h>
39 #include <psapi.h>
40 #endif
41
42 /* Parsing. */
43 #include "ragel.h"
44 #include "rlscan.h"
45
46 /* Parameters and output. */
47 #include "pcheck.h"
48 #include "vector.h"
49 #include "version.h"
50 #include "common.h"
51
52 using std::istream;
53 using std::ostream;
54 using std::ifstream;
55 using std::ofstream;
56 using std::cin;
57 using std::cout;
58 using std::cerr;
59 using std::endl;
60 using std::ios;
61 using std::streamsize;
62
63 /* Controls minimization. */
64 MinimizeLevel minimizeLevel = MinimizePartition2;
65 MinimizeOpt minimizeOpt = MinimizeMostOps;
66
67 /* Graphviz dot file generation. */
68 char *machineSpec = 0, *machineName = 0;
69 bool machineSpecFound = false;
70
71 bool printStatistics = false;
72 bool frontendOnly = false;
73 bool generateDot = false;
74
75 typedef Vector<const char *> ArgsVector;
76 ArgsVector frontendArgs;
77 ArgsVector backendArgs;
78
79 /* Print a summary of the options. */
80 void usage()
81 {
82         cout <<
83 "usage: ragel [options] file\n"
84 "general:\n"
85 "   -h, -H, -?, --help   Print this usage and exit\n"
86 "   -v, --version        Print version information and exit\n"
87 "   -o <file>            Write output to <file>\n"
88 "   -s                   Print some statistics on stderr\n"
89 "fsm minimization:\n"
90 "   -n                   Do not perform minimization\n"
91 "   -m                   Minimize at the end of the compilation\n"
92 "   -l                   Minimize after most operations (default)\n"
93 "   -e                   Minimize after every operation\n"
94 "visualization:\n"
95 "   -V                   Generate a dot file for Graphviz\n"
96 "   -p                   Display printable characters on labels\n"
97 "   -S <spec>            FSM specification to output (for rlgen-dot)\n"
98 "   -M <machine>         Machine definition/instantiation to output (for rlgen-dot)\n"
99 "host language:\n"
100 "   -C                   The host language is C, C++, Obj-C or Obj-C++ (default)\n"
101 "   -D                   The host language is D\n"
102 "   -J                   The host language is Java\n"
103 "   -R                   The host language is Ruby\n"
104 "line direcives: (C/D only)\n"
105 "   -L                   Inhibit writing of #line directives\n"
106 "code style: (C/Ruby only)\n"
107 "   -T0                  Table driven FSM (default)\n"
108 "   -T1                  Faster table driven FSM\n"
109 "   -F0                  Flat table driven FSM\n"
110 "   -F1                  Faster flat table-driven FSM\n"
111 "code style: (C only)\n"
112 "   -G0                  Goto-driven FSM\n"
113 "   -G1                  Faster goto-driven FSM\n"
114 "   -G2                  Really fast goto-driven FSM\n"
115 "   -P<N>                N-Way Split really fast goto-driven FSM\n"
116         ;       
117 }
118
119 /* Print version information. */
120 void version()
121 {
122         cout << "Ragel State Machine Compiler version " VERSION << " " PUBDATE << endl <<
123                         "Copyright (c) 2001-2007 by Adrian Thurston" << endl;
124 }
125
126 /* Total error count. */
127 int gblErrorCount = 0;
128
129 /* Print the opening to a warning in the input, then return the error ostream. */
130 ostream &warning( const InputLoc &loc )
131 {
132         assert( loc.fileName != 0 );
133         cerr << loc.fileName << ":" << loc.line << ":" << 
134                         loc.col << ": warning: ";
135         return cerr;
136 }
137
138 /* Print the opening to a program error, then return the error stream. */
139 ostream &error()
140 {
141         gblErrorCount += 1;
142         cerr << PROGNAME ": ";
143         return cerr;
144 }
145
146 ostream &error( const InputLoc &loc )
147 {
148         gblErrorCount += 1;
149         assert( loc.fileName != 0 );
150         cerr << loc.fileName << ":" << loc.line << ": ";
151         return cerr;
152 }
153
154 void escapeLineDirectivePath( std::ostream &out, char *path )
155 {
156         for ( char *pc = path; *pc != 0; pc++ ) {
157                 if ( *pc == '\\' )
158                         out << "\\\\";
159                 else
160                         out << *pc;
161         }
162 }
163
164 void processArgs( int argc, char **argv, char *&inputFileName, char *&outputFileName )
165 {
166         ParamCheck pc("fo:nmleabjkS:M:CDJRvHh?-:sT:F:G:P:LpV", argc, argv);
167
168         while ( pc.check() ) {
169                 switch ( pc.state ) {
170                 case ParamCheck::match:
171                         switch ( pc.parameter ) {
172                         case 'V':
173                                 generateDot = true;
174                                 break;
175
176                         case 'f':
177                                 frontendOnly = true;
178                                 break;
179
180                         /* Output. */
181                         case 'o':
182                                 if ( *pc.parameterArg == 0 )
183                                         error() << "a zero length output file name was given" << endl;
184                                 else if ( outputFileName != 0 )
185                                         error() << "more than one output file name was given" << endl;
186                                 else {
187                                         /* Ok, remember the output file name. */
188                                         outputFileName = pc.parameterArg;
189                                 }
190                                 break;
191
192                         /* Minimization, mostly hidden options. */
193                         case 'n':
194                                 minimizeOpt = MinimizeNone;
195                                 frontendArgs.append( "-n" );
196                                 break;
197                         case 'm':
198                                 minimizeOpt = MinimizeEnd;
199                                 frontendArgs.append( "-m" );
200                                 break;
201                         case 'l':
202                                 minimizeOpt = MinimizeMostOps;
203                                 frontendArgs.append( "-l" );
204                                 break;
205                         case 'e':
206                                 minimizeOpt = MinimizeEveryOp;
207                                 frontendArgs.append( "-e" );
208                                 break;
209                         case 'a':
210                                 minimizeLevel = MinimizeApprox;
211                                 frontendArgs.append( "-a" );
212                                 break;
213                         case 'b':
214                                 minimizeLevel = MinimizeStable;
215                                 frontendArgs.append( "-b" );
216                                 break;
217                         case 'j':
218                                 minimizeLevel = MinimizePartition1;
219                                 frontendArgs.append( "-j" );
220                                 break;
221                         case 'k':
222                                 minimizeLevel = MinimizePartition2;
223                                 frontendArgs.append( "-k" );
224                                 break;
225
226                         /* Machine spec. */
227                         case 'S':
228                                 if ( *pc.parameterArg == 0 )
229                                         error() << "please specify an argument to -S" << endl;
230                                 else if ( machineSpec != 0 )
231                                         error() << "more than one -S argument was given" << endl;
232                                 else {
233                                         /* Ok, remember the path to the machine to generate. */
234                                         machineSpec = pc.parameterArg;
235                                         frontendArgs.append( "-S" );
236                                         frontendArgs.append( pc.parameterArg );
237                                 }
238                                 break;
239
240                         /* Machine path. */
241                         case 'M':
242                                 if ( *pc.parameterArg == 0 )
243                                         error() << "please specify an argument to -M" << endl;
244                                 else if ( machineName != 0 )
245                                         error() << "more than one -M argument was given" << endl;
246                                 else {
247                                         /* Ok, remember the machine name to generate. */
248                                         machineName = pc.parameterArg;
249                                         frontendArgs.append( "-M" );
250                                         frontendArgs.append( pc.parameterArg );
251                                 }
252                                 break;
253
254                         /* Host language types. */
255                         case 'C':
256                                 hostLang = &hostLangC;
257                                 frontendArgs.append( "-C" );
258                                 break;
259                         case 'D':
260                                 hostLang = &hostLangD;
261                                 frontendArgs.append( "-D" );
262                                 break;
263                         case 'J':
264                                 hostLang = &hostLangJava;
265                                 frontendArgs.append( "-J" );
266                                 break;
267                         case 'R':
268                                 hostLang = &hostLangRuby;
269                                 frontendArgs.append( "-R" );
270                                 break;
271
272                         /* Version and help. */
273                         case 'v':
274                                 version();
275                                 exit(0);
276                         case 'H': case 'h': case '?':
277                                 usage();
278                                 exit(0);
279                         case 's':
280                                 printStatistics = true;
281                                 frontendArgs.append( "-s" );
282                                 break;
283                         case '-':
284                                 if ( strcasecmp(pc.parameterArg, "help") == 0 ) {
285                                         usage();
286                                         exit(0);
287                                 }
288                                 else if ( strcasecmp(pc.parameterArg, "version") == 0 ) {
289                                         version();
290                                         exit(0);
291                                 }
292                                 else {
293                                         error() << "--" << pc.parameterArg << 
294                                                         " is an invalid argument" << endl;
295                                 }
296
297                         /* Passthrough args. */
298                         case 'T': 
299                                 backendArgs.append( "-T" );
300                                 backendArgs.append( pc.parameterArg );
301                                 break;
302                         case 'F': 
303                                 backendArgs.append( "-F" );
304                                 backendArgs.append( pc.parameterArg );
305                                 break;
306                         case 'G': 
307                                 backendArgs.append( "-G" );
308                                 backendArgs.append( pc.parameterArg );
309                                 break;
310                         case 'P':
311                                 backendArgs.append( "-P" );
312                                 backendArgs.append( pc.parameterArg );
313                                 break;
314                         case 'p':
315                                 backendArgs.append( "-p" );
316                                 break;
317                         case 'L':
318                                 backendArgs.append( "-L" );
319                                 break;
320                         }
321                         break;
322
323                 case ParamCheck::invalid:
324                         error() << "-" << pc.parameter << " is an invalid argument" << endl;
325                         break;
326
327                 case ParamCheck::noparam:
328                         /* It is interpreted as an input file. */
329                         if ( *pc.curArg == 0 )
330                                 error() << "a zero length input file name was given" << endl;
331                         else if ( inputFileName != 0 )
332                                 error() << "more than one input file name was given" << endl;
333                         else {
334                                 /* OK, Remember the filename. */
335                                 inputFileName = pc.curArg;
336                         }
337                         break;
338                 }
339         }
340 }
341
342 int frontend( char *inputFileName, char *outputFileName )
343 {
344         /* Open the input file for reading. */
345         assert( inputFileName != 0 );
346         ifstream *inFile = new ifstream( inputFileName );
347         istream *inStream = inFile;
348         if ( ! inFile->is_open() )
349                 error() << "could not open " << inputFileName << " for reading" << endp;
350
351         /* Used for just a few things. */
352         std::ostringstream hostData;
353
354         if ( machineSpec == 0 && machineName == 0 )
355                 hostData << "<host line=\"1\" col=\"1\">";
356
357         Scanner scanner( inputFileName, *inStream, hostData, 0, 0, 0, false );
358         scanner.do_scan();
359
360         /* Finished, final check for errors.. */
361         if ( gblErrorCount > 0 )
362                 return 1;
363         
364         /* Now send EOF to all parsers. */
365         terminateAllParsers();
366
367         /* Finished, final check for errors.. */
368         if ( gblErrorCount > 0 )
369                 return 1;
370
371         if ( machineSpec == 0 && machineName == 0 )
372                 hostData << "</host>\n";
373
374         if ( gblErrorCount > 0 )
375                 return 1;
376         
377         ostream *outputFile = 0;
378         if ( outputFileName != 0 )
379                 outputFile = new ofstream( outputFileName );
380         else
381                 outputFile = &cout;
382
383         /* Write the machines, then the surrounding code. */
384         writeMachines( *outputFile, hostData.str(), inputFileName );
385
386         /* Close the intermediate file. */
387         if ( outputFileName != 0 )
388                 delete outputFile;
389
390         return gblErrorCount > 0;
391 }
392
393 char *makeIntermedTemplate( char *baseFileName )
394 {
395         char *result = 0;
396         const char *templ = "ragel-XXXXXX.xml";
397         char *lastSlash = strrchr( baseFileName, '/' );
398         if ( lastSlash == 0 ) {
399                 result = new char[strlen(templ)+1];
400                 strcpy( result, templ );
401         }
402         else {
403                 int baseLen = lastSlash - baseFileName + 1;
404                 result = new char[baseLen + strlen(templ) + 1];
405                 memcpy( result, baseFileName, baseLen );
406                 strcpy( result+baseLen, templ );
407         }
408         return result;
409 };
410
411 char *openIntermed( char *inputFileName, char *outputFileName )
412 {
413         srand(time(0));
414         char *result = 0;
415
416         /* Which filename do we use as the base? */
417         char *baseFileName = outputFileName != 0 ? outputFileName : inputFileName;
418
419         /* The template for the intermediate file name. */
420         char *intermedFileName = makeIntermedTemplate( baseFileName );
421
422         /* Randomize the name and try to open. */
423         char fnChars[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
424         char *firstX = strrchr( intermedFileName, 'X' ) - 5;
425         for ( int tries = 0; tries < 20; tries++ ) {
426                 /* Choose a random name. */
427                 for ( int x = 0; x < 6; x++ )
428                         firstX[x] = fnChars[rand() % 52];
429
430                 /* Try to open the file. */
431                 int fd = ::open( intermedFileName, O_WRONLY|O_EXCL|O_CREAT, S_IRUSR|S_IWUSR );
432
433                 if ( fd > 0 ) {
434                         /* Success. Close the file immediately and return the name for use
435                          * by the child processes. */
436                         ::close( fd );
437                         result = intermedFileName;
438                         break;
439                 }
440
441                 if ( errno == EACCES ) {
442                         error() << "failed to open temp file " << intermedFileName << 
443                                         ", access denied" << endp;
444                 }
445         }
446
447         if ( result == 0 )
448                 error() << "abnormal error: cannot find unique name for temp file" << endp;
449
450         return result;
451 }
452
453
454 void cleanExit( char *intermed, int status )
455 {
456         unlink( intermed );
457         exit( status );
458 }
459
460 #ifndef WIN32
461
462 /* If any forward slash is found in argv0 then it is assumed that the path is
463  * explicit and the path to the backend executable should be derived from
464  * that. Whe check that location and also go up one then inside a directory of
465  * the same name in case we are executing from the source tree. If no forward
466  * slash is found it is assumed the file is being run from the installed
467  * location. The PREFIX supplied during configuration is used. */
468 char **makePathChecksUnix( const char *argv0, const char *progName )
469 {
470         char **result = new char*[3];
471         const char *lastSlash = strrchr( argv0, '/' );
472         int numChecks = 0;
473
474         if ( lastSlash != 0 ) {
475                 char *path = strdup( argv0 );
476                 int givenPathLen = (lastSlash - argv0) + 1;
477                 path[givenPathLen] = 0;
478
479                 int progNameLen = strlen(progName);
480                 int length = givenPathLen + progNameLen + 1;
481                 char *check = new char[length];
482                 sprintf( check, "%s%s", path, progName );
483                 result[numChecks++] = check;
484
485                 length = givenPathLen + 3 + progNameLen + 1 + progNameLen + 1;
486                 check = new char[length];
487                 sprintf( check, "%s../%s/%s", path, progName, progName );
488                 result[numChecks++] = check;
489         }
490         else {
491                 int prefixLen = strlen(PREFIX);
492                 int progNameLen = strlen(progName);
493                 int length = prefixLen + 5 + progNameLen + 1;
494                 char *check = new char[length];
495
496                 sprintf( check, PREFIX "/bin/%s", progName );
497                 result[numChecks++] = check;
498         }
499
500         result[numChecks] = 0;
501         return result;
502 }
503
504
505 void forkAndExec( const char *progName, char **pathChecks, 
506                 ArgsVector &args, char *intermed )
507 {
508         pid_t pid = fork();
509         if ( pid < 0 ) {
510                 /* Error, no child created. */
511                 error() << "failed to fork for " << progName << endl;
512                 cleanExit( intermed, 1 );
513         }
514         else if ( pid == 0 ) {
515                 /* child */
516                 while ( *pathChecks != 0 ) {
517                         /* Execv does not modify argv, it just uses the const form that is
518                          * compatible with the most code. Ours not included. */
519                         execv( *pathChecks, (char *const*) args.data );
520                         pathChecks += 1;
521                 }
522                 error() << "failed to exec " << progName << endl;
523                 cleanExit( intermed, 1 );
524         }
525
526         /* Parent process, wait for the child. */
527         int status;
528         wait( &status );
529
530         /* What happened with the child. */
531         if ( ! WIFEXITED( status ) ) {
532                 error() << progName << " did not exit normally" << endl;
533                 cleanExit( intermed, 1 );
534         }
535         
536         if ( WEXITSTATUS(status) != 0 )
537                 cleanExit( intermed, WEXITSTATUS(status) );
538 }
539
540 #else
541
542 /* GetModuleFileNameEx is used to find out where the the current process's
543  * binary is. That location is searched first. If that fails then we go up one
544  * directory and look for the executable inside a directory of the same name
545  * in case we are executing from the source tree.
546  * */
547 char **makePathChecksWin( const char *progName )
548 {
549         int len = 1024;
550         char *imageFileName = new char[len];
551         HANDLE h = GetCurrentProcess();
552         len = GetModuleFileNameEx( h, NULL, imageFileName, len );
553         imageFileName[len] = 0;
554
555         char **result = new char*[3];
556         const char *lastSlash = strrchr( imageFileName, '\\' );
557         int numChecks = 0;
558
559         assert( lastSlash != 0 );
560         char *path = strdup( imageFileName );
561         int givenPathLen = (lastSlash - imageFileName) + 1;
562         path[givenPathLen] = 0;
563
564         int progNameLen = strlen(progName);
565         int length = givenPathLen + progNameLen + 1;
566         char *check = new char[length];
567         sprintf( check, "%s%s", path, progName );
568         result[numChecks++] = check;
569
570         length = givenPathLen + 3 + progNameLen + 1 + progNameLen + 1;
571         check = new char[length];
572         sprintf( check, "%s..\\%s\\%s", path, progName, progName );
573         result[numChecks++] = check;
574
575         result[numChecks] = 0;
576         return result;
577 }
578
579 void spawn( char *progName, char **pathChecks, 
580                 ArgsVector &args, char *intermed )
581 {
582         int result = 0;
583         while ( *pathChecks != 0 ) {
584                 cerr << "trying to execute " << *pathChecks << endl;
585                 result = _spawnv( _P_WAIT, *pathChecks, args.data );
586                 if ( result >= 0 || errno != ENOENT )
587                         break;
588                 pathChecks += 1;
589         }
590
591         if ( result < 0 ) {
592                 error() << "failed to spawn " << progName << endl;
593                 cleanExit( intermed, 1 );
594         }
595
596         if ( result > 0 )
597                 cleanExit( intermed, 1 );
598 }
599
600 #endif
601
602 void execFrontend( const char *argv0, char *inputFileName, char *intermed )
603 {
604         /* The frontend program name. */
605         const char *progName = "ragel";
606
607         frontendArgs.insert( 0, progName );
608         frontendArgs.insert( 1, "-f" );
609         frontendArgs.append( "-o" );
610         frontendArgs.append( intermed );
611         frontendArgs.append( inputFileName );
612         frontendArgs.append( 0 );
613
614 #ifndef WIN32
615         char **pathChecks = makePathChecksUnix( argv0, progName );
616         forkAndExec( progName, pathChecks, frontendArgs, intermed );
617 #else
618         char **pathChecks = makePathChecksWin( progName );
619         spawn( progName, pathChecks, frontendArgs, intermed );
620 #endif
621 }
622
623 void execBackend( const char *argv0, char *intermed, char *outputFileName )
624 {
625         /* Locate the backend program */
626         const char *progName = 0;
627         if ( generateDot )
628                 progName = "rlgen-dot";
629         else {
630                 switch ( hostLang->lang ) {
631                         case HostLang::C:
632                         case HostLang::D:
633                                 progName = "rlgen-cd";
634                                 break;
635                         case HostLang::Java:
636                                 progName = "rlgen-java";
637                                 break;
638                         case HostLang::Ruby:
639                                 progName = "rlgen-ruby";
640                                 break;
641                 }
642         }
643
644         backendArgs.insert( 0, progName );
645         if ( outputFileName != 0 ) {
646                 backendArgs.append( "-o" );
647                 backendArgs.append( outputFileName );
648         }
649         backendArgs.append( intermed );
650         backendArgs.append( 0 );
651
652 #ifndef WIN32
653         char **pathChecks = makePathChecksUnix( argv0, progName );
654         forkAndExec( progName, pathChecks, backendArgs, intermed );
655 #else
656         char **pathChecks = makePathChecksWin( progName );
657         spawn( progName, pathChecks, backendArgs, intermed );
658 #endif
659 }
660
661 /* Main, process args and call yyparse to start scanning input. */
662 int main(int argc, char **argv)
663 {
664         char *inputFileName = 0;
665         char *outputFileName = 0;
666
667         processArgs( argc, argv, inputFileName, outputFileName );
668
669         /* Require an input file. If we use standard in then we won't have a file
670          * name on which to base the output. */
671         if ( inputFileName == 0 )
672                 error() << "no input file given" << endl;
673
674         /* Bail on argument processing errors. */
675         if ( gblErrorCount > 0 )
676                 exit(1);
677
678         /* Make sure we are not writing to the same file as the input file. */
679         if ( inputFileName != 0 && outputFileName != 0 && 
680                         strcmp( inputFileName, outputFileName  ) == 0 )
681         {
682                 error() << "output file \"" << outputFileName  << 
683                                 "\" is the same as the input file" << endp;
684         }
685
686         if ( frontendOnly )
687                 return frontend( inputFileName, outputFileName );
688
689         char *intermed = openIntermed( inputFileName, outputFileName );
690
691         /* From here on in the cleanExit function should be used to exit. */
692
693         /* Run the frontend, then the backend processes. */
694         execFrontend( argv[0], inputFileName, intermed );
695         execBackend( argv[0], intermed, outputFileName );
696
697         /* Clean up the intermediate. */
698         cleanExit( intermed, 0 );
699
700         return 0;
701 }