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>
46 /* Parameters and output. */
61 using std::streamsize;
63 /* Controls minimization. */
64 MinimizeLevel minimizeLevel = MinimizePartition2;
65 MinimizeOpt minimizeOpt = MinimizeMostOps;
67 /* Graphviz dot file generation. */
68 char *machineSpec = 0, *machineName = 0;
69 bool machineSpecFound = false;
71 bool printStatistics = false;
72 bool frontendOnly = false;
73 bool generateDot = false;
75 typedef Vector<char*> ArgsVector;
76 ArgsVector frontendArgs;
77 ArgsVector backendArgs;
79 /* Print a summary of the options. */
83 "usage: ragel [options] file\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"
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"
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"
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"
119 /* Print version information. */
122 cout << "Ragel State Machine Compiler version " VERSION << " " PUBDATE << endl <<
123 "Copyright (c) 2001-2007 by Adrian Thurston" << endl;
126 /* Total error count. */
127 int gblErrorCount = 0;
129 /* Print the opening to a warning in the input, then return the error ostream. */
130 ostream &warning( const InputLoc &loc )
132 assert( loc.fileName != 0 );
133 cerr << loc.fileName << ":" << loc.line << ":" <<
134 loc.col << ": warning: ";
138 /* Print the opening to a program error, then return the error stream. */
142 cerr << PROGNAME ": ";
146 ostream &error( const InputLoc &loc )
149 assert( loc.fileName != 0 );
150 cerr << loc.fileName << ":" << loc.line << ": ";
154 void escapeLineDirectivePath( std::ostream &out, char *path )
156 for ( char *pc = path; *pc != 0; pc++ ) {
164 void processArgs( int argc, char **argv, char *&inputFileName, char *&outputFileName )
166 ParamCheck pc("fo:nmleabjkS:M:CDJRvHh?-:sT:F:G:P:LpV", argc, argv);
168 while ( pc.check() ) {
169 switch ( pc.state ) {
170 case ParamCheck::match:
171 switch ( pc.parameter ) {
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;
187 /* Ok, remember the output file name. */
188 outputFileName = pc.parameterArg;
192 /* Minimization, mostly hidden options. */
194 minimizeOpt = MinimizeNone;
195 frontendArgs.append( "-n" );
198 minimizeOpt = MinimizeEnd;
199 frontendArgs.append( "-m" );
202 minimizeOpt = MinimizeMostOps;
203 frontendArgs.append( "-l" );
206 minimizeOpt = MinimizeEveryOp;
207 frontendArgs.append( "-e" );
210 minimizeLevel = MinimizeApprox;
211 frontendArgs.append( "-a" );
214 minimizeLevel = MinimizeStable;
215 frontendArgs.append( "-b" );
218 minimizeLevel = MinimizePartition1;
219 frontendArgs.append( "-j" );
222 minimizeLevel = MinimizePartition2;
223 frontendArgs.append( "-k" );
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;
233 /* Ok, remember the path to the machine to generate. */
234 machineSpec = pc.parameterArg;
235 frontendArgs.append( "-S" );
236 frontendArgs.append( pc.parameterArg );
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;
247 /* Ok, remember the machine name to generate. */
248 machineName = pc.parameterArg;
249 frontendArgs.append( "-M" );
250 frontendArgs.append( pc.parameterArg );
254 /* Host language types. */
256 hostLang = &hostLangC;
257 frontendArgs.append( "-C" );
260 hostLang = &hostLangD;
261 frontendArgs.append( "-D" );
264 hostLang = &hostLangJava;
265 frontendArgs.append( "-J" );
268 hostLang = &hostLangRuby;
269 frontendArgs.append( "-R" );
272 /* Version and help. */
276 case 'H': case 'h': case '?':
280 printStatistics = true;
281 frontendArgs.append( "-s" );
284 if ( strcasecmp(pc.parameterArg, "help") == 0 ) {
288 else if ( strcasecmp(pc.parameterArg, "version") == 0 ) {
293 error() << "--" << pc.parameterArg <<
294 " is an invalid argument" << endl;
297 /* Passthrough args. */
299 backendArgs.append( "-T" );
300 backendArgs.append( pc.parameterArg );
303 backendArgs.append( "-F" );
304 backendArgs.append( pc.parameterArg );
307 backendArgs.append( "-G" );
308 backendArgs.append( pc.parameterArg );
311 backendArgs.append( "-P" );
312 backendArgs.append( pc.parameterArg );
315 backendArgs.append( "-p" );
318 backendArgs.append( "-L" );
323 case ParamCheck::invalid:
324 error() << "-" << pc.parameter << " is an invalid argument" << endl;
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;
334 /* OK, Remember the filename. */
335 inputFileName = pc.curArg;
342 int frontend( char *inputFileName, char *outputFileName )
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;
351 /* Used for just a few things. */
352 std::ostringstream hostData;
354 if ( machineSpec == 0 && machineName == 0 )
355 hostData << "<host line=\"1\" col=\"1\">";
357 Scanner scanner( inputFileName, *inStream, hostData, 0, 0, 0, false );
360 /* Finished, final check for errors.. */
361 if ( gblErrorCount > 0 )
364 /* Now send EOF to all parsers. */
365 terminateAllParsers();
367 /* Finished, final check for errors.. */
368 if ( gblErrorCount > 0 )
371 if ( machineSpec == 0 && machineName == 0 )
372 hostData << "</host>\n";
374 if ( gblErrorCount > 0 )
377 ostream *outputFile = 0;
378 if ( outputFileName != 0 )
379 outputFile = new ofstream( outputFileName );
383 /* Write the machines, then the surrounding code. */
384 writeMachines( *outputFile, hostData.str(), inputFileName );
386 /* Close the intermediate file. */
387 if ( outputFileName != 0 )
390 return gblErrorCount > 0;
393 char *makeIntermedTemplate( char *baseFileName )
395 char *result = 0, *templ = "ragel-XXXXXX.xml";
396 char *lastSlash = strrchr( baseFileName, '/' );
397 if ( lastSlash == 0 ) {
398 result = new char[strlen(templ)+1];
399 strcpy( result, templ );
402 int baseLen = lastSlash - baseFileName + 1;
403 result = new char[baseLen + strlen(templ) + 1];
404 memcpy( result, baseFileName, baseLen );
405 strcpy( result+baseLen, templ );
410 char *openIntermed( char *inputFileName, char *outputFileName )
415 /* Which filename do we use as the base? */
416 char *baseFileName = outputFileName != 0 ? outputFileName : inputFileName;
418 /* The template for the intermediate file name. */
419 char *intermedFileName = makeIntermedTemplate( baseFileName );
421 /* Randomize the name and try to open. */
422 char fnChars[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
423 char *firstX = strrchr( intermedFileName, 'X' ) - 5;
424 for ( int tries = 0; tries < 20; tries++ ) {
425 /* Choose a random name. */
426 for ( int x = 0; x < 6; x++ )
427 firstX[x] = fnChars[rand() % 52];
429 /* Try to open the file. */
430 int fd = ::open( intermedFileName, O_WRONLY|O_EXCL|O_CREAT, S_IRUSR|S_IWUSR );
433 /* Success. Close the file immediately and return the name for use
434 * by the child processes. */
436 result = intermedFileName;
440 if ( errno == EACCES ) {
441 error() << "failed to open temp file " << intermedFileName <<
442 ", access denied" << endp;
447 error() << "abnormal error: cannot find unique name for temp file" << endp;
453 void cleanExit( char *intermed, int status )
461 /* If any forward slash is found in argv0 then it is assumed that the path is
462 * explicit and the path to the backend executable should be derived from
463 * that. Whe check that location and also go up one then inside a directory of
464 * the same name in case we are executing from the source tree. If no forward
465 * slash is found it is assumed the file is being run from the installed
466 * location. The PREFIX supplied during configuration is used. */
467 char **makePathChecksUnix( const char *argv0, const char *progName )
469 char **result = new char*[3];
470 const char *lastSlash = strrchr( argv0, '/' );
473 if ( lastSlash != 0 ) {
474 char *path = strdup( argv0 );
475 int givenPathLen = (lastSlash - argv0) + 1;
476 path[givenPathLen] = 0;
478 int progNameLen = strlen(progName);
479 int length = givenPathLen + progNameLen + 1;
480 char *check = new char[length];
481 sprintf( check, "%s%s", path, progName );
482 result[numChecks++] = check;
484 length = givenPathLen + 3 + progNameLen + 1 + progNameLen + 1;
485 check = new char[length];
486 sprintf( check, "%s../%s/%s", path, progName, progName );
487 result[numChecks++] = check;
490 int prefixLen = strlen(PREFIX);
491 int progNameLen = strlen(progName);
492 int length = prefixLen + 5 + progNameLen + 1;
493 char *check = new char[length];
495 sprintf( check, PREFIX "/bin/%s", progName );
496 result[numChecks++] = check;
499 result[numChecks] = 0;
504 void forkAndExec( char *progName, char **pathChecks,
505 ArgsVector &args, char *intermed )
509 /* Error, no child created. */
510 error() << "failed to fork for " << progName << endl;
511 cleanExit( intermed, 1 );
513 else if ( pid == 0 ) {
515 while ( *pathChecks != 0 ) {
516 execv( *pathChecks, args.data );
519 error() << "failed to exec " << progName << endl;
520 cleanExit( intermed, 1 );
523 /* Parent process, wait for the child. */
527 /* What happened with the child. */
528 if ( ! WIFEXITED( status ) ) {
529 error() << progName << " did not exit normally" << endl;
530 cleanExit( intermed, 1 );
533 if ( WEXITSTATUS(status) != 0 )
534 cleanExit( intermed, WEXITSTATUS(status) );
539 /* GetModuleFileNameEx is used to find out where the the current process's
540 * binary is. That location is searched first. If that fails then we go up one
541 * directory and look for the executable inside a directory of the same name
542 * in case we are executing from the source tree.
544 char **makePathChecksWin( const char *progName )
547 char *imageFileName = new char[len];
548 HANDLE h = GetCurrentProcess();
549 len = GetModuleFileNameEx( h, NULL, imageFileName, len );
550 imageFileName[len] = 0;
552 char **result = new char*[3];
553 const char *lastSlash = strrchr( imageFileName, '\\' );
556 assert( lastSlash != 0 );
557 char *path = strdup( imageFileName );
558 int givenPathLen = (lastSlash - imageFileName) + 1;
559 path[givenPathLen] = 0;
561 int progNameLen = strlen(progName);
562 int length = givenPathLen + progNameLen + 1;
563 char *check = new char[length];
564 sprintf( check, "%s%s", path, progName );
565 result[numChecks++] = check;
567 length = givenPathLen + 3 + progNameLen + 1 + progNameLen + 1;
568 check = new char[length];
569 sprintf( check, "%s..\\%s\\%s", path, progName, progName );
570 result[numChecks++] = check;
572 result[numChecks] = 0;
576 void spawn( char *progName, char **pathChecks,
577 ArgsVector &args, char *intermed )
580 while ( *pathChecks != 0 ) {
581 cerr << "trying to execute " << *pathChecks << endl;
582 result = _spawnv( _P_WAIT, *pathChecks, args.data );
583 if ( result >= 0 || errno != ENOENT )
589 error() << "failed to spawn " << progName << endl;
590 cleanExit( intermed, 1 );
594 cleanExit( intermed, 1 );
599 void execFrontend( const char *argv0, char *inputFileName, char *intermed )
601 /* The frontend program name. */
602 char *progName = "ragel";
604 frontendArgs.insert( 0, progName );
605 frontendArgs.insert( 1, "-f" );
606 frontendArgs.append( "-o" );
607 frontendArgs.append( intermed );
608 frontendArgs.append( inputFileName );
609 frontendArgs.append( 0 );
612 char **pathChecks = makePathChecksUnix( argv0, progName );
613 forkAndExec( progName, pathChecks, frontendArgs, intermed );
615 char **pathChecks = makePathChecksWin( progName );
616 spawn( progName, pathChecks, frontendArgs, intermed );
620 void execBackend( const char *argv0, char *intermed, char *outputFileName )
622 /* Locate the backend program */
625 progName = "rlgen-dot";
627 switch ( hostLang->lang ) {
630 progName = "rlgen-cd";
633 progName = "rlgen-java";
636 progName = "rlgen-ruby";
641 backendArgs.insert( 0, progName );
642 if ( outputFileName != 0 ) {
643 backendArgs.append( "-o" );
644 backendArgs.append( outputFileName );
646 backendArgs.append( intermed );
647 backendArgs.append( 0 );
650 char **pathChecks = makePathChecksUnix( argv0, progName );
651 forkAndExec( progName, pathChecks, backendArgs, intermed );
653 char **pathChecks = makePathChecksWin( progName );
654 spawn( progName, pathChecks, backendArgs, intermed );
658 /* Main, process args and call yyparse to start scanning input. */
659 int main(int argc, char **argv)
661 char *inputFileName = 0;
662 char *outputFileName = 0;
664 processArgs( argc, argv, inputFileName, outputFileName );
666 /* Require an input file. If we use standard in then we won't have a file
667 * name on which to base the output. */
668 if ( inputFileName == 0 )
669 error() << "no input file given" << endl;
671 /* Bail on argument processing errors. */
672 if ( gblErrorCount > 0 )
675 /* Make sure we are not writing to the same file as the input file. */
676 if ( inputFileName != 0 && outputFileName != 0 &&
677 strcmp( inputFileName, outputFileName ) == 0 )
679 error() << "output file \"" << outputFileName <<
680 "\" is the same as the input file" << endp;
684 return frontend( inputFileName, outputFileName );
686 char *intermed = openIntermed( inputFileName, outputFileName );
688 /* From here on in the cleanExit function should be used to exit. */
690 /* Run the frontend, then the backend processes. */
691 execFrontend( argv[0], inputFileName, intermed );
692 execBackend( argv[0], intermed, outputFileName );
694 /* Clean up the intermediate. */
695 cleanExit( intermed, 0 );