2 * Copyright 2001-2007 Adrian Thurston <thurston@cs.queensu.ca>
5 /* This file is part of Ragel.
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.
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.
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
30 #include <sys/types.h>
40 /* Parameters and output. */
55 using std::streamsize;
57 /* Controls minimization. */
58 MinimizeLevel minimizeLevel = MinimizePartition2;
59 MinimizeOpt minimizeOpt = MinimizeMostOps;
61 /* Graphviz dot file generation. */
62 char *machineSpec = 0, *machineName = 0;
63 bool machineSpecFound = false;
65 bool printStatistics = false;
67 typedef Vector<char*> ArgsVector;
68 ArgsVector backendArgs;
70 /* Print a summary of the options. */
74 "usage: ragel [options] file\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"
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"
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"
96 /* Print version information. */
99 cout << "Ragel State Machine Compiler version " VERSION << " " PUBDATE << endl <<
100 "Copyright (c) 2001-2007 by Adrian Thurston" << endl;
103 /* Total error count. */
104 int gblErrorCount = 0;
106 /* Print the opening to a warning in the input, then return the error ostream. */
107 ostream &warning( const InputLoc &loc )
109 assert( loc.fileName != 0 );
110 cerr << loc.fileName << ":" << loc.line << ":" <<
111 loc.col << ": warning: ";
115 /* Print the opening to a program error, then return the error stream. */
119 cerr << PROGNAME ": ";
123 ostream &error( const InputLoc &loc )
126 assert( loc.fileName != 0 );
127 cerr << loc.fileName << ":" << loc.line << ": ";
131 void escapeLineDirectivePath( std::ostream &out, char *path )
133 for ( char *pc = path; *pc != 0; pc++ ) {
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.
146 char **makePathChecks( const char *argv0, const char *progName )
148 char **result = new char*[3];
149 const char *lastSlash = strrchr( argv0, '/' );
152 if ( lastSlash != 0 ) {
153 char *path = strdup( argv0 );
154 int givenPathLen = (lastSlash - argv0) + 1;
155 path[givenPathLen] = 0;
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;
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;
169 int prefixLen = strlen(PREFIX);
170 int progNameLen = strlen(progName);
171 int length = prefixLen + 5 + progNameLen + 1;
172 char *check = new char[length];
174 sprintf( check, PREFIX "/bin/%s", progName );
175 result[numChecks++] = check;
178 result[numChecks] = 0;
183 void execBackend( const char *argv0, costream *intermed )
185 /* Locate the backend program */
186 const char *progName = 0;
187 switch ( hostLang->lang ) {
190 progName = "rlgen-cd";
193 progName = "rlgen-java";
196 progName = "rlgen-ruby";
200 char **pathChecks = makePathChecks( argv0, progName );
202 backendArgs.insert( 0, "rlgen-ruby" );
203 backendArgs.append( intermed->b->fileName );
204 backendArgs.append( 0 );
208 /* Error, no child created. */
209 error() << "failed to fork backend" << endp;
211 else if ( pid == 0 ) {
213 while ( *pathChecks != 0 ) {
214 execv( *pathChecks, backendArgs.data );
217 error() << "failed to exec backend" << endp;
224 unlink( intermed->b->fileName );
227 char *makeIntermedTemplate( char *baseFileName )
230 char *lastSlash = strrchr( baseFileName, '/' );
231 if ( lastSlash == 0 ) {
232 result = new char[13];
233 strcpy( result, "ragel-XXXXXX.xml" );
236 int baseLen = lastSlash - baseFileName + 1;
237 result = new char[baseLen + 13];
238 memcpy( result, baseFileName, baseLen );
239 strcpy( result+baseLen, "ragel-XXXXXX.xml" );
244 char fnChars[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
246 costream *openIntermed( char *inputFileName, char *outputFileName )
249 costream *result = 0;
251 /* Which filename do we use as the base? */
252 char *baseFileName = outputFileName != 0 ? outputFileName : inputFileName;
254 /* The template for the intermediate file name. */
255 char *intermedFileName = makeIntermedTemplate( baseFileName );
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];
264 /* Try to open the file. */
265 int fd = ::open( intermedFileName, O_WRONLY|O_EXCL|O_CREAT, S_IRUSR|S_IWUSR );
269 FILE *file = fdopen( fd, "wt" );
271 error() << "fdopen(...) on intermediate file failed" << endp;
273 cfilebuf *b = new cfilebuf( intermedFileName, file );
274 result = new costream( b );
278 if ( errno == EACCES ) {
279 error() << "failed to open temp file " << intermedFileName <<
280 ", access denied" << endp;
285 error() << "abnormal error: cannot find unique name for temp file" << endp;
290 /* Main, process args and call yyparse to start scanning input. */
291 int main(int argc, char **argv)
293 ParamCheck pc("o:nmleabjkS:M:CDJRvHh?-:sT:F:G:P:Lp", argc, argv);
294 char *inputFileName = 0;
295 char *outputFileName = 0;
297 while ( pc.check() ) {
298 switch ( pc.state ) {
299 case ParamCheck::match:
300 switch ( pc.parameter ) {
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;
308 /* Ok, remember the output file name. */
309 outputFileName = pc.parameterArg;
310 backendArgs.append( "-o" );
311 backendArgs.append( pc.parameterArg );
315 /* Minimization, mostly hidden options. */
317 minimizeOpt = MinimizeNone;
320 minimizeOpt = MinimizeEnd;
323 minimizeOpt = MinimizeMostOps;
326 minimizeOpt = MinimizeEveryOp;
329 minimizeLevel = MinimizeApprox;
332 minimizeLevel = MinimizeStable;
335 minimizeLevel = MinimizePartition1;
338 minimizeLevel = MinimizePartition2;
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;
348 /* Ok, remember the path to the machine to generate. */
349 machineSpec = pc.parameterArg;
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;
360 /* Ok, remember the machine name to generate. */
361 machineName = pc.parameterArg;
365 /* Host language types. */
367 hostLang = &hostLangC;
370 hostLang = &hostLangD;
373 hostLang = &hostLangJava;
376 hostLang = &hostLangRuby;
379 /* Version and help. */
383 case 'H': case 'h': case '?':
387 printStatistics = true;
390 if ( strcasecmp(pc.parameterArg, "help") == 0 ) {
394 else if ( strcasecmp(pc.parameterArg, "version") == 0 ) {
399 error() << "--" << pc.parameterArg <<
400 " is an invalid argument" << endl;
403 /* Passthrough args. */
405 backendArgs.append( "-T" );
406 backendArgs.append( pc.parameterArg );
409 backendArgs.append( "-F" );
410 backendArgs.append( pc.parameterArg );
413 backendArgs.append( "-G" );
414 backendArgs.append( pc.parameterArg );
417 backendArgs.append( "-P" );
418 backendArgs.append( pc.parameterArg );
421 backendArgs.append( "-p" );
424 backendArgs.append( "-L" );
429 case ParamCheck::invalid:
430 error() << "-" << pc.parameter << " is an invalid argument" << endl;
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;
440 /* OK, Remember the filename. */
441 inputFileName = pc.curArg;
447 /* Bail on above errors. */
448 if ( gblErrorCount > 0 )
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 )
455 error() << "output file \"" << outputFileName <<
456 "\" is the same as the input file" << endp;
459 /* Open the input file for reading. */
461 if ( inputFileName != 0 ) {
462 /* Open the input file for reading. */
463 ifstream *inFile = new ifstream( inputFileName );
465 if ( ! inFile->is_open() )
466 error() << "could not open " << inputFileName << " for reading" << endp;
469 inputFileName = "<stdin>";
473 /* Used for just a few things. */
474 std::ostringstream hostData;
476 if ( machineSpec == 0 && machineName == 0 )
477 hostData << "<host line=\"1\" col=\"1\">";
479 Scanner scanner( inputFileName, *inStream, hostData, 0, 0, 0, false );
482 /* Finished, final check for errors.. */
483 if ( gblErrorCount > 0 )
486 /* Now send EOF to all parsers. */
487 terminateAllParsers();
489 /* Finished, final check for errors.. */
490 if ( gblErrorCount > 0 )
493 if ( machineSpec == 0 && machineName == 0 )
494 hostData << "</host>\n";
496 if ( gblErrorCount > 0 )
499 costream *intermed = openIntermed( inputFileName, outputFileName );
501 /* Write the machines, then the surrounding code. */
502 writeMachines( *intermed, hostData.str(), inputFileName );
504 /* Close the intermediate file. */
507 /* Run the backend process. */
508 execBackend( argv[0], intermed );