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<const 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 )
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 );
403 int baseLen = lastSlash - baseFileName + 1;
404 result = new char[baseLen + strlen(templ) + 1];
405 memcpy( result, baseFileName, baseLen );
406 strcpy( result+baseLen, templ );
411 char *openIntermed( char *inputFileName, char *outputFileName )
416 /* Which filename do we use as the base? */
417 char *baseFileName = outputFileName != 0 ? outputFileName : inputFileName;
419 /* The template for the intermediate file name. */
420 char *intermedFileName = makeIntermedTemplate( baseFileName );
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];
430 /* Try to open the file. */
431 int fd = ::open( intermedFileName, O_WRONLY|O_EXCL|O_CREAT, S_IRUSR|S_IWUSR );
434 /* Success. Close the file immediately and return the name for use
435 * by the child processes. */
437 result = intermedFileName;
441 if ( errno == EACCES ) {
442 error() << "failed to open temp file " << intermedFileName <<
443 ", access denied" << endp;
448 error() << "abnormal error: cannot find unique name for temp file" << endp;
454 void cleanExit( char *intermed, int status )
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 )
470 char **result = new char*[3];
471 const char *lastSlash = strrchr( argv0, '/' );
474 if ( lastSlash != 0 ) {
475 char *path = strdup( argv0 );
476 int givenPathLen = (lastSlash - argv0) + 1;
477 path[givenPathLen] = 0;
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;
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;
491 int prefixLen = strlen(PREFIX);
492 int progNameLen = strlen(progName);
493 int length = prefixLen + 5 + progNameLen + 1;
494 char *check = new char[length];
496 sprintf( check, PREFIX "/bin/%s", progName );
497 result[numChecks++] = check;
500 result[numChecks] = 0;
505 void forkAndExec( const char *progName, char **pathChecks,
506 ArgsVector &args, char *intermed )
510 /* Error, no child created. */
511 error() << "failed to fork for " << progName << endl;
512 cleanExit( intermed, 1 );
514 else if ( pid == 0 ) {
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 );
522 error() << "failed to exec " << progName << endl;
523 cleanExit( intermed, 1 );
526 /* Parent process, wait for the child. */
530 /* What happened with the child. */
531 if ( ! WIFEXITED( status ) ) {
532 error() << progName << " did not exit normally" << endl;
533 cleanExit( intermed, 1 );
536 if ( WEXITSTATUS(status) != 0 )
537 cleanExit( intermed, WEXITSTATUS(status) );
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.
547 char **makePathChecksWin( const char *progName )
550 char *imageFileName = new char[len];
551 HANDLE h = GetCurrentProcess();
552 len = GetModuleFileNameEx( h, NULL, imageFileName, len );
553 imageFileName[len] = 0;
555 char **result = new char*[3];
556 const char *lastSlash = strrchr( imageFileName, '\\' );
559 assert( lastSlash != 0 );
560 char *path = strdup( imageFileName );
561 int givenPathLen = (lastSlash - imageFileName) + 1;
562 path[givenPathLen] = 0;
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;
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;
575 result[numChecks] = 0;
579 void spawn( char *progName, char **pathChecks,
580 ArgsVector &args, char *intermed )
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 )
592 error() << "failed to spawn " << progName << endl;
593 cleanExit( intermed, 1 );
597 cleanExit( intermed, 1 );
602 void execFrontend( const char *argv0, char *inputFileName, char *intermed )
604 /* The frontend program name. */
605 const char *progName = "ragel";
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 );
615 char **pathChecks = makePathChecksUnix( argv0, progName );
616 forkAndExec( progName, pathChecks, frontendArgs, intermed );
618 char **pathChecks = makePathChecksWin( progName );
619 spawn( progName, pathChecks, frontendArgs, intermed );
623 void execBackend( const char *argv0, char *intermed, char *outputFileName )
625 /* Locate the backend program */
626 const char *progName = 0;
628 progName = "rlgen-dot";
630 switch ( hostLang->lang ) {
633 progName = "rlgen-cd";
636 progName = "rlgen-java";
639 progName = "rlgen-ruby";
644 backendArgs.insert( 0, progName );
645 if ( outputFileName != 0 ) {
646 backendArgs.append( "-o" );
647 backendArgs.append( outputFileName );
649 backendArgs.append( intermed );
650 backendArgs.append( 0 );
653 char **pathChecks = makePathChecksUnix( argv0, progName );
654 forkAndExec( progName, pathChecks, backendArgs, intermed );
656 char **pathChecks = makePathChecksWin( progName );
657 spawn( progName, pathChecks, backendArgs, intermed );
661 /* Main, process args and call yyparse to start scanning input. */
662 int main(int argc, char **argv)
664 char *inputFileName = 0;
665 char *outputFileName = 0;
667 processArgs( argc, argv, inputFileName, outputFileName );
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;
674 /* Bail on argument processing errors. */
675 if ( gblErrorCount > 0 )
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 )
682 error() << "output file \"" << outputFileName <<
683 "\" is the same as the input file" << endp;
687 return frontend( inputFileName, outputFileName );
689 char *intermed = openIntermed( inputFileName, outputFileName );
691 /* From here on in the cleanExit function should be used to exit. */
693 /* Run the frontend, then the backend processes. */
694 execFrontend( argv[0], inputFileName, intermed );
695 execBackend( argv[0], intermed, outputFileName );
697 /* Clean up the intermediate. */
698 cleanExit( intermed, 0 );