Changed the -l option in rlgen-cd to -L because it is covered in the frontend.
[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/wait.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <errno.h>
35
36 /* Parsing. */
37 #include "ragel.h"
38 #include "rlscan.h"
39
40 /* Parameters and output. */
41 #include "pcheck.h"
42 #include "vector.h"
43 #include "version.h"
44 #include "common.h"
45
46 using std::istream;
47 using std::ostream;
48 using std::ifstream;
49 using std::ofstream;
50 using std::cin;
51 using std::cout;
52 using std::cerr;
53 using std::endl;
54 using std::ios;
55 using std::streamsize;
56
57 /* Controls minimization. */
58 MinimizeLevel minimizeLevel = MinimizePartition2;
59 MinimizeOpt minimizeOpt = MinimizeMostOps;
60
61 /* Graphviz dot file generation. */
62 char *machineSpec = 0, *machineName = 0;
63 bool machineSpecFound = false;
64
65 bool printStatistics = false;
66
67 typedef Vector<char*> ArgsVector;
68 ArgsVector backendArgs;
69
70 /* Print a summary of the options. */
71 void usage()
72 {
73         cout <<
74 "usage: ragel [options] file\n"
75 "general:\n"
76 "   -h, -H, -?, --help   Print this usage and exit\n"
77 "   -v, --version        Print version information and exit\n"
78 "   -o <file>            Write output to <file>\n"
79 "   -s                   Print some statistics on stderr\n"
80 "fsm minimization:\n"
81 "   -n                   Do not perform minimization\n"
82 "   -m                   Minimize at the end of the compilation\n"
83 "   -l                   Minimize after most operations (default)\n"
84 "   -e                   Minimize after every operation\n"
85 "machine selection:\n"
86 "   -S <spec>            FSM specification to output (for rlgen-dot)\n"
87 "   -M <machine>         Machine definition/instantiation to output (for rlgen-dot)\n"
88 "host language:\n"
89 "   -C                   The host language is C, C++, Obj-C or Obj-C++ (default)\n"
90 "   -D                   The host language is D\n"
91 "   -J                   The host language is Java\n"
92 "   -R                   The host language is Ruby\n"
93         ;       
94 }
95
96 /* Print version information. */
97 void version()
98 {
99         cout << "Ragel State Machine Compiler version " VERSION << " " PUBDATE << endl <<
100                         "Copyright (c) 2001-2007 by Adrian Thurston" << endl;
101 }
102
103 /* Total error count. */
104 int gblErrorCount = 0;
105
106 /* Print the opening to a warning in the input, then return the error ostream. */
107 ostream &warning( const InputLoc &loc )
108 {
109         assert( loc.fileName != 0 );
110         cerr << loc.fileName << ":" << loc.line << ":" << 
111                         loc.col << ": warning: ";
112         return cerr;
113 }
114
115 /* Print the opening to a program error, then return the error stream. */
116 ostream &error()
117 {
118         gblErrorCount += 1;
119         cerr << PROGNAME ": ";
120         return cerr;
121 }
122
123 ostream &error( const InputLoc &loc )
124 {
125         gblErrorCount += 1;
126         assert( loc.fileName != 0 );
127         cerr << loc.fileName << ":" << loc.line << ": ";
128         return cerr;
129 }
130
131 void escapeLineDirectivePath( std::ostream &out, char *path )
132 {
133         for ( char *pc = path; *pc != 0; pc++ ) {
134                 if ( *pc == '\\' )
135                         out << "\\\\";
136                 else
137                         out << *pc;
138         }
139 }
140
141 /* If any forward slash is found in argv0 then it is assumed that the path is
142  * explicit and the path to the backend executable should be derived from
143  * that. If no forward slash is found it is assumed the file is being run from
144  * the installed location. The PREFIX supplied during configuration is used.
145  * */
146 char **makePathChecks( const char *argv0, const char *progName )
147 {
148         char **result = new char*[3];
149         const char *lastSlash = strrchr( argv0, '/' );
150         int numChecks = 0;
151
152         if ( lastSlash != 0 ) {
153                 char *path = strdup( argv0 );
154                 int givenPathLen = (lastSlash - argv0) + 1;
155                 path[givenPathLen] = 0;
156
157                 int progNameLen = strlen(progName);
158                 int length = givenPathLen + progNameLen + 1;
159                 char *check = new char[length];
160                 sprintf( check, "%s%s", path, progName );
161                 result[numChecks++] = check;
162
163                 length = givenPathLen + 3 + progNameLen + 1 + progNameLen + 1;
164                 check = new char[length];
165                 sprintf( check, "%s../%s/%s", path, progName, progName );
166                 result[numChecks++] = check;
167         }
168         else {
169                 int prefixLen = strlen(PREFIX);
170                 int progNameLen = strlen(progName);
171                 int length = prefixLen + 5 + progNameLen + 1;
172                 char *check = new char[length];
173
174                 sprintf( check, PREFIX "/bin/%s", progName );
175                 result[numChecks++] = check;
176         }
177
178         result[numChecks] = 0;
179         return result;
180 }
181
182
183 void execBackend( const char *argv0, costream *intermed )
184 {
185         /* Locate the backend program */
186         const char *progName = 0;
187         switch ( hostLang->lang ) {
188                 case HostLang::C:
189                 case HostLang::D:
190                         progName = "rlgen-cd";
191                         break;
192                 case HostLang::Java:
193                         progName = "rlgen-java";
194                         break;
195                 case HostLang::Ruby:
196                         progName = "rlgen-ruby";
197                         break;
198         }
199
200         char **pathChecks = makePathChecks( argv0, progName );
201
202         backendArgs.insert( 0, "rlgen-ruby" );
203         backendArgs.append( intermed->b->fileName );
204         backendArgs.append( 0 );
205
206         pid_t pid = fork();
207         if ( pid < 0 ) {
208                 /* Error, no child created. */
209                 error() << "failed to fork backend" << endp;
210         }
211         else if ( pid == 0 ) {
212                 /* child */
213                 while ( *pathChecks != 0 ) {
214                         execv( *pathChecks, backendArgs.data );
215                         pathChecks += 1;
216                 }
217                 error() << "failed to exec backend" << endp;
218         }
219         else {
220                 /* parent. */
221                 wait( 0 );
222         }
223
224         unlink( intermed->b->fileName );
225 }
226
227 char *makeIntermedTemplate( char *baseFileName )
228 {
229         char *result;
230         char *lastSlash = strrchr( baseFileName, '/' );
231         if ( lastSlash == 0 ) {
232                 result = new char[13];
233                 strcpy( result, "ragel-XXXXXX.xml" );
234         }
235         else {
236                 int baseLen = lastSlash - baseFileName + 1;
237                 result = new char[baseLen + 13];
238                 memcpy( result, baseFileName, baseLen );
239                 strcpy( result+baseLen, "ragel-XXXXXX.xml" );
240         }
241         return result;
242 };
243
244 char fnChars[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
245
246 costream *openIntermed( char *inputFileName, char *outputFileName )
247 {
248         srandom(time(0));
249         costream *result = 0;
250
251         /* Which filename do we use as the base? */
252         char *baseFileName = outputFileName != 0 ? outputFileName : inputFileName;
253
254         /* The template for the intermediate file name. */
255         char *intermedFileName = makeIntermedTemplate( baseFileName );
256
257         /* Randomize the name and try to open. */
258         char *firstX = strrchr( intermedFileName, 'X' ) - 5;
259         for ( int tries = 0; tries < 20; tries++ ) {
260                 /* Choose a random name. */
261                 for ( int x = 0; x < 6; x++ )
262                         firstX[x] = fnChars[random() % 52];
263
264                 /* Try to open the file. */
265                 int fd = ::open( intermedFileName, O_WRONLY|O_EXCL|O_CREAT, S_IRUSR|S_IWUSR );
266
267                 if ( fd > 0 ) {
268                         /* Success. */
269                         FILE *file = fdopen( fd, "wt" );
270                         if ( file == 0 )
271                                 error() << "fdopen(...) on intermediate file failed" << endp;
272
273                         cfilebuf *b = new cfilebuf( intermedFileName, file );
274                         result = new costream( b );
275                         break;
276                 }
277
278                 if ( errno == EACCES ) {
279                         error() << "failed to open temp file " << intermedFileName << 
280                                         ", access denied" << endp;
281                 }
282         }
283
284         if ( result == 0 )
285                 error() << "abnormal error: cannot find unique name for temp file" << endp;
286
287         return result;
288 }
289
290 /* Main, process args and call yyparse to start scanning input. */
291 int main(int argc, char **argv)
292 {
293         ParamCheck pc("o:nmleabjkS:M:CDJRvHh?-:sT:F:G:P:Lp", argc, argv);
294         char *inputFileName = 0;
295         char *outputFileName = 0;
296
297         while ( pc.check() ) {
298                 switch ( pc.state ) {
299                 case ParamCheck::match:
300                         switch ( pc.parameter ) {
301                         /* Output. */
302                         case 'o':
303                                 if ( *pc.parameterArg == 0 )
304                                         error() << "a zero length output file name was given" << endl;
305                                 else if ( outputFileName != 0 )
306                                         error() << "more than one output file name was given" << endl;
307                                 else {
308                                         /* Ok, remember the output file name. */
309                                         outputFileName = pc.parameterArg;
310                                         backendArgs.append( "-o" );
311                                         backendArgs.append( pc.parameterArg );
312                                 }
313                                 break;
314
315                         /* Minimization, mostly hidden options. */
316                         case 'n':
317                                 minimizeOpt = MinimizeNone;
318                                 break;
319                         case 'm':
320                                 minimizeOpt = MinimizeEnd;
321                                 break;
322                         case 'l':
323                                 minimizeOpt = MinimizeMostOps;
324                                 break;
325                         case 'e':
326                                 minimizeOpt = MinimizeEveryOp;
327                                 break;
328                         case 'a':
329                                 minimizeLevel = MinimizeApprox;
330                                 break;
331                         case 'b':
332                                 minimizeLevel = MinimizeStable;
333                                 break;
334                         case 'j':
335                                 minimizeLevel = MinimizePartition1;
336                                 break;
337                         case 'k':
338                                 minimizeLevel = MinimizePartition2;
339                                 break;
340
341                         /* Machine spec. */
342                         case 'S':
343                                 if ( *pc.parameterArg == 0 )
344                                         error() << "please specify an argument to -S" << endl;
345                                 else if ( machineSpec != 0 )
346                                         error() << "more than one -S argument was given" << endl;
347                                 else {
348                                         /* Ok, remember the path to the machine to generate. */
349                                         machineSpec = pc.parameterArg;
350                                 }
351                                 break;
352
353                         /* Machine path. */
354                         case 'M':
355                                 if ( *pc.parameterArg == 0 )
356                                         error() << "please specify an argument to -M" << endl;
357                                 else if ( machineName != 0 )
358                                         error() << "more than one -M argument was given" << endl;
359                                 else {
360                                         /* Ok, remember the machine name to generate. */
361                                         machineName = pc.parameterArg;
362                                 }
363                                 break;
364
365                         /* Host language types. */
366                         case 'C':
367                                 hostLang = &hostLangC;
368                                 break;
369                         case 'D':
370                                 hostLang = &hostLangD;
371                                 break;
372                         case 'J':
373                                 hostLang = &hostLangJava;
374                                 break;
375                         case 'R':
376                                 hostLang = &hostLangRuby;
377                                 break;
378
379                         /* Version and help. */
380                         case 'v':
381                                 version();
382                                 exit(0);
383                         case 'H': case 'h': case '?':
384                                 usage();
385                                 exit(0);
386                         case 's':
387                                 printStatistics = true;
388                                 break;
389                         case '-':
390                                 if ( strcasecmp(pc.parameterArg, "help") == 0 ) {
391                                         usage();
392                                         exit(0);
393                                 }
394                                 else if ( strcasecmp(pc.parameterArg, "version") == 0 ) {
395                                         version();
396                                         exit(0);
397                                 }
398                                 else {
399                                         error() << "--" << pc.parameterArg << 
400                                                         " is an invalid argument" << endl;
401                                 }
402
403                         /* Passthrough args. */
404                         case 'T': 
405                                 backendArgs.append( "-T" );
406                                 backendArgs.append( pc.parameterArg );
407                                 break;
408                         case 'F': 
409                                 backendArgs.append( "-F" );
410                                 backendArgs.append( pc.parameterArg );
411                                 break;
412                         case 'G': 
413                                 backendArgs.append( "-G" );
414                                 backendArgs.append( pc.parameterArg );
415                                 break;
416                         case 'P':
417                                 backendArgs.append( "-P" );
418                                 backendArgs.append( pc.parameterArg );
419                                 break;
420                         case 'p':
421                                 backendArgs.append( "-p" );
422                                 break;
423                         case 'L':
424                                 backendArgs.append( "-L" );
425                                 break;
426                         }
427                         break;
428
429                 case ParamCheck::invalid:
430                         error() << "-" << pc.parameter << " is an invalid argument" << endl;
431                         break;
432
433                 case ParamCheck::noparam:
434                         /* It is interpreted as an input file. */
435                         if ( *pc.curArg == 0 )
436                                 error() << "a zero length input file name was given" << endl;
437                         else if ( inputFileName != 0 )
438                                 error() << "more than one input file name was given" << endl;
439                         else {
440                                 /* OK, Remember the filename. */
441                                 inputFileName = pc.curArg;
442                         }
443                         break;
444                 }
445         }
446
447         /* Bail on above errors. */
448         if ( gblErrorCount > 0 )
449                 exit(1);
450
451         /* Make sure we are not writing to the same file as the input file. */
452         if ( inputFileName != 0 && outputFileName != 0 && 
453                         strcmp( inputFileName, outputFileName  ) == 0 )
454         {
455                 error() << "output file \"" << outputFileName  << 
456                                 "\" is the same as the input file" << endp;
457         }
458
459         /* Open the input file for reading. */
460         istream *inStream;
461         if ( inputFileName != 0 ) {
462                 /* Open the input file for reading. */
463                 ifstream *inFile = new ifstream( inputFileName );
464                 inStream = inFile;
465                 if ( ! inFile->is_open() )
466                         error() << "could not open " << inputFileName << " for reading" << endp;
467         }
468         else {
469                 inputFileName = "<stdin>";
470                 inStream = &cin;
471         }
472
473         /* Used for just a few things. */
474         std::ostringstream hostData;
475
476         if ( machineSpec == 0 && machineName == 0 )
477                 hostData << "<host line=\"1\" col=\"1\">";
478
479         Scanner scanner( inputFileName, *inStream, hostData, 0, 0, 0, false );
480         scanner.do_scan();
481
482         /* Finished, final check for errors.. */
483         if ( gblErrorCount > 0 )
484                 return 1;
485         
486         /* Now send EOF to all parsers. */
487         terminateAllParsers();
488
489         /* Finished, final check for errors.. */
490         if ( gblErrorCount > 0 )
491                 return 1;
492
493         if ( machineSpec == 0 && machineName == 0 )
494                 hostData << "</host>\n";
495
496         if ( gblErrorCount > 0 )
497                 return 1;
498         
499         costream *intermed = openIntermed( inputFileName, outputFileName );
500
501         /* Write the machines, then the surrounding code. */
502         writeMachines( *intermed, hostData.str(), inputFileName );
503
504         /* Close the intermediate file. */
505         intermed->fclose();
506
507         /* Run the backend process. */
508         execBackend( argv[0], intermed );
509
510         return 0;
511 }