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>
45 #define S_IRUSR _S_IREAD
46 #define S_IWUSR _S_IWRITE
54 /* Parameters and output. */
69 using std::streamsize;
71 /* Controls minimization. */
72 MinimizeLevel minimizeLevel = MinimizePartition2;
73 MinimizeOpt minimizeOpt = MinimizeMostOps;
75 /* Graphviz dot file generation. */
76 char *machineSpec = 0, *machineName = 0;
77 bool machineSpecFound = false;
78 bool wantDupsRemoved = true;
80 bool printStatistics = false;
81 bool frontendOnly = false;
82 bool generateDot = false;
84 ArgsVector frontendArgs;
85 ArgsVector backendArgs;
86 ArgsVector includePaths;
88 /* Print a summary of the options. */
92 "usage: ragel [options] file\n"
94 " -h, -H, -?, --help Print this usage and exit\n"
95 " -v, --version Print version information and exit\n"
96 " -o <file> Write output to <file>\n"
97 " -s Print some statistics on stderr\n"
98 " -d Do not remove duplicates from action lists\n"
99 " -I <dir> Add <dir> to the list of directories to search\n"
100 " for included an imported files\n"
101 "error reporting format:\n"
102 " --error-format=gnu file:line:column: message (default)\n"
103 " --error-format=msvc file(line,column): message\n"
104 "fsm minimization:\n"
105 " -n Do not perform minimization\n"
106 " -m Minimize at the end of the compilation\n"
107 " -l Minimize after most operations (default)\n"
108 " -e Minimize after every operation\n"
110 " -x Run the frontend only: emit XML intermediate format\n"
111 " -V Generate a dot file for Graphviz\n"
112 " -p Display printable characters on labels\n"
113 " -S <spec> FSM specification to output (for rlgen-dot)\n"
114 " -M <machine> Machine definition/instantiation to output (for rlgen-dot)\n"
116 " -C The host language is C, C++, Obj-C or Obj-C++ (default)\n"
117 " -D The host language is D\n"
118 " -J The host language is Java\n"
119 " -R The host language is Ruby\n"
120 " -A The host language is C#\n"
121 "line direcives: (C/D/C# only)\n"
122 " -L Inhibit writing of #line directives\n"
123 "code style: (C/Ruby/C# only)\n"
124 " -T0 Table driven FSM (default)\n"
125 " -T1 Faster table driven FSM\n"
126 " -F0 Flat table driven FSM\n"
127 " -F1 Faster flat table-driven FSM\n"
128 "code style: (C/C# only)\n"
129 " -G0 Goto-driven FSM\n"
130 " -G1 Faster goto-driven FSM\n"
131 "code style: (C only)\n"
132 " -G2 Really fast goto-driven FSM\n"
133 " -P<N> N-Way Split really fast goto-driven FSM\n"
139 /* Print version information and exit. */
142 cout << "Ragel State Machine Compiler version " VERSION << " " PUBDATE << endl <<
143 "Copyright (c) 2001-2007 by Adrian Thurston" << endl;
147 /* Error reporting format. */
148 ErrorFormat errorFormat = ErrorFormatGNU;
150 InputLoc makeInputLoc( const char *fileName, int line, int col)
152 InputLoc loc = { fileName, line, col };
156 ostream &operator<<( ostream &out, const InputLoc &loc )
158 assert( loc.fileName != 0 );
159 switch ( errorFormat ) {
160 case ErrorFormatMSVC:
161 out << loc.fileName << "(" << loc.line;
163 out << "," << loc.col;
168 out << loc.fileName << ":" << loc.line;
170 out << ":" << loc.col;
176 /* Total error count. */
177 int gblErrorCount = 0;
179 /* Print the opening to a warning in the input, then return the error ostream. */
180 ostream &warning( const InputLoc &loc )
182 cerr << loc << ": warning: ";
186 /* Print the opening to a program error, then return the error stream. */
190 cerr << PROGNAME ": ";
194 ostream &error( const InputLoc &loc )
201 void escapeLineDirectivePath( std::ostream &out, char *path )
203 for ( char *pc = path; *pc != 0; pc++ ) {
211 void processArgs( int argc, char **argv, char *&inputFileName, char *&outputFileName )
213 ParamCheck pc("xo:dnmleabjkS:M:I:CDJRAvHh?-:sT:F:G:P:LpV", argc, argv);
215 while ( pc.check() ) {
216 switch ( pc.state ) {
217 case ParamCheck::match:
218 switch ( pc.parameter ) {
229 if ( *pc.paramArg == 0 )
230 error() << "a zero length output file name was given" << endl;
231 else if ( outputFileName != 0 )
232 error() << "more than one output file name was given" << endl;
234 /* Ok, remember the output file name. */
235 outputFileName = pc.paramArg;
239 /* Minimization, mostly hidden options. */
241 wantDupsRemoved = false;
242 frontendArgs.append( "-d" );
245 /* Minimization, mostly hidden options. */
247 minimizeOpt = MinimizeNone;
248 frontendArgs.append( "-n" );
251 minimizeOpt = MinimizeEnd;
252 frontendArgs.append( "-m" );
255 minimizeOpt = MinimizeMostOps;
256 frontendArgs.append( "-l" );
259 minimizeOpt = MinimizeEveryOp;
260 frontendArgs.append( "-e" );
263 minimizeLevel = MinimizeApprox;
264 frontendArgs.append( "-a" );
267 minimizeLevel = MinimizeStable;
268 frontendArgs.append( "-b" );
271 minimizeLevel = MinimizePartition1;
272 frontendArgs.append( "-j" );
275 minimizeLevel = MinimizePartition2;
276 frontendArgs.append( "-k" );
281 if ( *pc.paramArg == 0 )
282 error() << "please specify an argument to -S" << endl;
283 else if ( machineSpec != 0 )
284 error() << "more than one -S argument was given" << endl;
286 /* Ok, remember the path to the machine to generate. */
287 machineSpec = pc.paramArg;
288 frontendArgs.append( "-S" );
289 frontendArgs.append( pc.paramArg );
295 if ( *pc.paramArg == 0 )
296 error() << "please specify an argument to -M" << endl;
297 else if ( machineName != 0 )
298 error() << "more than one -M argument was given" << endl;
300 /* Ok, remember the machine name to generate. */
301 machineName = pc.paramArg;
302 frontendArgs.append( "-M" );
303 frontendArgs.append( pc.paramArg );
308 if ( *pc.paramArg == 0 )
309 error() << "please specify an argument to -I" << endl;
311 includePaths.append( pc.paramArg );
312 frontendArgs.append( "-I" );
313 frontendArgs.append( pc.paramArg );
317 /* Error reporting format. */
319 if ( pc.paramArg[0] == '0' )
320 errorFormat = ErrorFormatGNU;
321 else if ( pc.paramArg[0] == '1' )
322 errorFormat = ErrorFormatMSVC;
324 error() << "-E" << pc.paramArg[0] <<
325 " is an invalid argument" << endl;
327 frontendArgs.append( "-E" );
328 frontendArgs.append( pc.paramArg );
331 /* Host language types. */
333 hostLang = &hostLangC;
334 frontendArgs.append( "-C" );
337 hostLang = &hostLangD;
338 frontendArgs.append( "-D" );
341 hostLang = &hostLangJava;
342 frontendArgs.append( "-J" );
345 hostLang = &hostLangRuby;
346 frontendArgs.append( "-R" );
349 hostLang = &hostLangCSharp;
350 frontendArgs.append( "-A" );
353 /* Version and help. */
357 case 'H': case 'h': case '?':
361 printStatistics = true;
362 frontendArgs.append( "-s" );
365 char *eq = strchr( pc.paramArg, '=' );
370 if ( strcmp( pc.paramArg, "help" ) == 0 )
372 else if ( strcmp( pc.paramArg, "version" ) == 0 )
374 else if ( strcmp( pc.paramArg, "error-format" ) == 0 ) {
376 error() << "expecting '=value' for error-format" << endl;
377 else if ( strcmp( eq, "gnu" ) == 0 ) {
378 errorFormat = ErrorFormatGNU;
379 frontendArgs.append( "--error-format=gnu" );
381 else if ( strcmp( eq, "msvc" ) == 0 ) {
382 errorFormat = ErrorFormatMSVC;
383 frontendArgs.append( "--error-format=msvc" );
386 error() << "invalid value for error-format" << endl;
390 error() << "--" << pc.paramArg <<
391 " is an invalid argument" << endl;
396 /* Passthrough args. */
398 backendArgs.append( "-T" );
399 backendArgs.append( pc.paramArg );
402 backendArgs.append( "-F" );
403 backendArgs.append( pc.paramArg );
406 backendArgs.append( "-G" );
407 backendArgs.append( pc.paramArg );
410 backendArgs.append( "-P" );
411 backendArgs.append( pc.paramArg );
414 backendArgs.append( "-p" );
417 backendArgs.append( "-L" );
422 case ParamCheck::invalid:
423 error() << "-" << pc.parameter << " is an invalid argument" << endl;
426 case ParamCheck::noparam:
427 /* It is interpreted as an input file. */
428 if ( *pc.curArg == 0 )
429 error() << "a zero length input file name was given" << endl;
430 else if ( inputFileName != 0 )
431 error() << "more than one input file name was given" << endl;
433 /* OK, Remember the filename. */
434 inputFileName = pc.curArg;
441 int frontend( char *inputFileName, char *outputFileName )
443 /* Open the input file for reading. */
444 assert( inputFileName != 0 );
445 ifstream *inFile = new ifstream( inputFileName );
446 istream *inStream = inFile;
447 if ( ! inFile->is_open() )
448 error() << "could not open " << inputFileName << " for reading" << endp;
450 /* Used for just a few things. */
451 std::ostringstream hostData;
453 if ( machineSpec == 0 && machineName == 0 )
454 hostData << "<host line=\"1\" col=\"1\">";
456 Scanner scanner( inputFileName, *inStream, hostData, 0, 0, 0, false );
459 /* Finished, final check for errors.. */
460 if ( gblErrorCount > 0 )
463 /* Now send EOF to all parsers. */
464 terminateAllParsers();
466 /* Finished, final check for errors.. */
467 if ( gblErrorCount > 0 )
470 if ( machineSpec == 0 && machineName == 0 )
471 hostData << "</host>\n";
473 if ( gblErrorCount > 0 )
476 ostream *outputFile = 0;
477 if ( outputFileName != 0 )
478 outputFile = new ofstream( outputFileName );
482 /* Write the machines, then the surrounding code. */
483 writeMachines( *outputFile, hostData.str(), inputFileName );
485 /* Close the intermediate file. */
486 if ( outputFileName != 0 )
489 return gblErrorCount > 0;
492 char *makeIntermedTemplate( char *baseFileName )
495 const char *templ = "ragel-XXXXXX.xml";
496 char *lastSlash = strrchr( baseFileName, '/' );
497 if ( lastSlash == 0 ) {
498 result = new char[strlen(templ)+1];
499 strcpy( result, templ );
502 int baseLen = lastSlash - baseFileName + 1;
503 result = new char[baseLen + strlen(templ) + 1];
504 memcpy( result, baseFileName, baseLen );
505 strcpy( result+baseLen, templ );
510 char *openIntermed( char *inputFileName, char *outputFileName )
515 /* Which filename do we use as the base? */
516 char *baseFileName = outputFileName != 0 ? outputFileName : inputFileName;
518 /* The template for the intermediate file name. */
519 char *intermedFileName = makeIntermedTemplate( baseFileName );
521 /* Randomize the name and try to open. */
522 char fnChars[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
523 char *firstX = strrchr( intermedFileName, 'X' ) - 5;
524 for ( int tries = 0; tries < 20; tries++ ) {
525 /* Choose a random name. */
526 for ( int x = 0; x < 6; x++ )
527 firstX[x] = fnChars[rand() % 52];
529 /* Try to open the file. */
530 int fd = ::open( intermedFileName, O_WRONLY|O_EXCL|O_CREAT, S_IRUSR|S_IWUSR );
533 /* Success. Close the file immediately and return the name for use
534 * by the child processes. */
536 result = intermedFileName;
540 if ( errno == EACCES ) {
541 error() << "failed to open temp file " << intermedFileName <<
542 ", access denied" << endp;
547 error() << "abnormal error: cannot find unique name for temp file" << endp;
553 void cleanExit( char *intermed, int status )
561 /* If any forward slash is found in argv0 then it is assumed that the path is
562 * explicit and the path to the backend executable should be derived from
563 * that. Whe check that location and also go up one then inside a directory of
564 * the same name in case we are executing from the source tree. If no forward
565 * slash is found it is assumed the file is being run from the installed
566 * location. The PREFIX supplied during configuration is used. */
567 char **makePathChecksUnix( const char *argv0, const char *progName )
569 char **result = new char*[3];
570 const char *lastSlash = strrchr( argv0, '/' );
573 if ( lastSlash != 0 ) {
574 char *path = strdup( argv0 );
575 int givenPathLen = (lastSlash - argv0) + 1;
576 path[givenPathLen] = 0;
578 int progNameLen = strlen(progName);
579 int length = givenPathLen + progNameLen + 1;
580 char *check = new char[length];
581 sprintf( check, "%s%s", path, progName );
582 result[numChecks++] = check;
584 length = givenPathLen + 3 + progNameLen + 1 + progNameLen + 1;
585 check = new char[length];
586 sprintf( check, "%s../%s/%s", path, progName, progName );
587 result[numChecks++] = check;
590 int prefixLen = strlen(PREFIX);
591 int progNameLen = strlen(progName);
592 int length = prefixLen + 5 + progNameLen + 1;
593 char *check = new char[length];
595 sprintf( check, PREFIX "/bin/%s", progName );
596 result[numChecks++] = check;
599 result[numChecks] = 0;
604 void forkAndExec( const char *progName, char **pathChecks,
605 ArgsVector &args, char *intermed )
609 /* Error, no child created. */
610 error() << "failed to fork for " << progName << endl;
611 cleanExit( intermed, 1 );
613 else if ( pid == 0 ) {
615 while ( *pathChecks != 0 ) {
616 /* Execv does not modify argv, it just uses the const form that is
617 * compatible with the most code. Ours not included. */
618 execv( *pathChecks, (char *const*) args.data );
621 error() << "failed to exec " << progName << endl;
622 cleanExit( intermed, 1 );
625 /* Parent process, wait for the child. */
629 /* What happened with the child. */
630 if ( ! WIFEXITED( status ) ) {
631 error() << progName << " did not exit normally" << endl;
632 cleanExit( intermed, 1 );
635 if ( WEXITSTATUS(status) != 0 )
636 cleanExit( intermed, WEXITSTATUS(status) );
641 /* GetModuleFileNameEx is used to find out where the the current process's
642 * binary is. That location is searched first. If that fails then we go up one
643 * directory and look for the executable inside a directory of the same name
644 * in case we are executing from the source tree.
646 char **makePathChecksWin( const char *progName )
649 char *imageFileName = new char[len];
650 HANDLE h = GetCurrentProcess();
651 len = GetModuleFileNameEx( h, NULL, imageFileName, len );
652 imageFileName[len] = 0;
654 char **result = new char*[3];
655 const char *lastSlash = strrchr( imageFileName, '\\' );
658 assert( lastSlash != 0 );
659 char *path = strdup( imageFileName );
660 int givenPathLen = (lastSlash - imageFileName) + 1;
661 path[givenPathLen] = 0;
663 int progNameLen = strlen(progName);
664 int length = givenPathLen + progNameLen + 1;
665 char *check = new char[length];
666 sprintf( check, "%s%s", path, progName );
667 result[numChecks++] = check;
669 length = givenPathLen + 3 + progNameLen + 1 + progNameLen + 1;
670 check = new char[length];
671 sprintf( check, "%s..\\%s\\%s", path, progName, progName );
672 result[numChecks++] = check;
674 result[numChecks] = 0;
678 void spawn( const char *progName, char **pathChecks,
679 ArgsVector &args, char *intermed )
682 while ( *pathChecks != 0 ) {
683 //cerr << "trying to execute " << *pathChecks << endl;
684 result = _spawnv( _P_WAIT, *pathChecks, args.data );
685 if ( result >= 0 || errno != ENOENT )
691 error() << "failed to spawn " << progName << endl;
692 cleanExit( intermed, 1 );
696 cleanExit( intermed, 1 );
701 void execFrontend( const char *argv0, char *inputFileName, char *intermed )
703 /* The frontend program name. */
704 const char *progName = "ragel";
706 frontendArgs.insert( 0, progName );
707 frontendArgs.insert( 1, "-x" );
708 frontendArgs.append( "-o" );
709 frontendArgs.append( intermed );
710 frontendArgs.append( inputFileName );
711 frontendArgs.append( 0 );
714 char **pathChecks = makePathChecksUnix( argv0, progName );
715 forkAndExec( progName, pathChecks, frontendArgs, intermed );
717 char **pathChecks = makePathChecksWin( progName );
718 spawn( progName, pathChecks, frontendArgs, intermed );
722 void execBackend( const char *argv0, char *intermed, char *outputFileName )
724 /* Locate the backend program */
725 const char *progName = 0;
727 progName = "rlgen-dot";
729 switch ( hostLang->lang ) {
732 progName = "rlgen-cd";
735 progName = "rlgen-java";
738 progName = "rlgen-ruby";
740 case HostLang::CSharp:
741 progName = "rlgen-csharp";
745 backendArgs.insert( 0, progName );
746 if ( outputFileName != 0 ) {
747 backendArgs.append( "-o" );
748 backendArgs.append( outputFileName );
750 backendArgs.append( intermed );
751 backendArgs.append( 0 );
754 char **pathChecks = makePathChecksUnix( argv0, progName );
755 forkAndExec( progName, pathChecks, backendArgs, intermed );
757 char **pathChecks = makePathChecksWin( progName );
758 spawn( progName, pathChecks, backendArgs, intermed );
762 /* Main, process args and call yyparse to start scanning input. */
763 int main(int argc, char **argv)
765 char *inputFileName = 0;
766 char *outputFileName = 0;
768 processArgs( argc, argv, inputFileName, outputFileName );
770 /* If -M or -S are given and we're not generating a dot file then invoke
771 * the frontend. These options are not useful with code generators. */
772 if ( machineName != 0 || machineSpec != 0 ) {
777 /* Require an input file. If we use standard in then we won't have a file
778 * name on which to base the output. */
779 if ( inputFileName == 0 )
780 error() << "no input file given" << endl;
782 /* Bail on argument processing errors. */
783 if ( gblErrorCount > 0 )
786 /* Make sure we are not writing to the same file as the input file. */
787 if ( inputFileName != 0 && outputFileName != 0 &&
788 strcmp( inputFileName, outputFileName ) == 0 )
790 error() << "output file \"" << outputFileName <<
791 "\" is the same as the input file" << endp;
795 return frontend( inputFileName, outputFileName );
797 char *intermed = openIntermed( inputFileName, outputFileName );
799 /* From here on in the cleanExit function should be used to exit. */
801 /* Run the frontend, then the backend processes. */
802 execFrontend( argv[0], inputFileName, intermed );
803 execBackend( argv[0], intermed, outputFileName );
805 /* Clean up the intermediate. */
806 cleanExit( intermed, 0 );