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 " -x Run the frontend only: emit XML intermediate format\n"
96 " -V Generate a dot file for Graphviz\n"
97 " -p Display printable characters on labels\n"
98 " -S <spec> FSM specification to output (for rlgen-dot)\n"
99 " -M <machine> Machine definition/instantiation to output (for rlgen-dot)\n"
101 " -C The host language is C, C++, Obj-C or Obj-C++ (default)\n"
102 " -D The host language is D\n"
103 " -J The host language is Java\n"
104 " -R The host language is Ruby\n"
105 "line direcives: (C/D only)\n"
106 " -L Inhibit writing of #line directives\n"
107 "code style: (C/Ruby only)\n"
108 " -T0 Table driven FSM (default)\n"
109 " -T1 Faster table driven FSM\n"
110 " -F0 Flat table driven FSM\n"
111 " -F1 Faster flat table-driven FSM\n"
112 "code style: (C only)\n"
113 " -G0 Goto-driven FSM\n"
114 " -G1 Faster goto-driven FSM\n"
115 " -G2 Really fast goto-driven FSM\n"
116 " -P<N> N-Way Split really fast goto-driven FSM\n"
120 /* Print version information. */
123 cout << "Ragel State Machine Compiler version " VERSION << " " PUBDATE << endl <<
124 "Copyright (c) 2001-2007 by Adrian Thurston" << endl;
127 /* Total error count. */
128 int gblErrorCount = 0;
130 /* Print the opening to a warning in the input, then return the error ostream. */
131 ostream &warning( const InputLoc &loc )
133 assert( loc.fileName != 0 );
134 cerr << loc.fileName << ":" << loc.line << ":" <<
135 loc.col << ": warning: ";
139 /* Print the opening to a program error, then return the error stream. */
143 cerr << PROGNAME ": ";
147 ostream &error( const InputLoc &loc )
150 assert( loc.fileName != 0 );
151 cerr << loc.fileName << ":" << loc.line << ": ";
155 void escapeLineDirectivePath( std::ostream &out, char *path )
157 for ( char *pc = path; *pc != 0; pc++ ) {
165 void processArgs( int argc, char **argv, char *&inputFileName, char *&outputFileName )
167 ParamCheck pc("xo:nmleabjkS:M:CDJRvHh?-:sT:F:G:P:LpV", argc, argv);
169 while ( pc.check() ) {
170 switch ( pc.state ) {
171 case ParamCheck::match:
172 switch ( pc.parameter ) {
183 if ( *pc.parameterArg == 0 )
184 error() << "a zero length output file name was given" << endl;
185 else if ( outputFileName != 0 )
186 error() << "more than one output file name was given" << endl;
188 /* Ok, remember the output file name. */
189 outputFileName = pc.parameterArg;
193 /* Minimization, mostly hidden options. */
195 minimizeOpt = MinimizeNone;
196 frontendArgs.append( "-n" );
199 minimizeOpt = MinimizeEnd;
200 frontendArgs.append( "-m" );
203 minimizeOpt = MinimizeMostOps;
204 frontendArgs.append( "-l" );
207 minimizeOpt = MinimizeEveryOp;
208 frontendArgs.append( "-e" );
211 minimizeLevel = MinimizeApprox;
212 frontendArgs.append( "-a" );
215 minimizeLevel = MinimizeStable;
216 frontendArgs.append( "-b" );
219 minimizeLevel = MinimizePartition1;
220 frontendArgs.append( "-j" );
223 minimizeLevel = MinimizePartition2;
224 frontendArgs.append( "-k" );
229 if ( *pc.parameterArg == 0 )
230 error() << "please specify an argument to -S" << endl;
231 else if ( machineSpec != 0 )
232 error() << "more than one -S argument was given" << endl;
234 /* Ok, remember the path to the machine to generate. */
235 machineSpec = pc.parameterArg;
236 frontendArgs.append( "-S" );
237 frontendArgs.append( pc.parameterArg );
243 if ( *pc.parameterArg == 0 )
244 error() << "please specify an argument to -M" << endl;
245 else if ( machineName != 0 )
246 error() << "more than one -M argument was given" << endl;
248 /* Ok, remember the machine name to generate. */
249 machineName = pc.parameterArg;
250 frontendArgs.append( "-M" );
251 frontendArgs.append( pc.parameterArg );
255 /* Host language types. */
257 hostLang = &hostLangC;
258 frontendArgs.append( "-C" );
261 hostLang = &hostLangD;
262 frontendArgs.append( "-D" );
265 hostLang = &hostLangJava;
266 frontendArgs.append( "-J" );
269 hostLang = &hostLangRuby;
270 frontendArgs.append( "-R" );
273 /* Version and help. */
277 case 'H': case 'h': case '?':
281 printStatistics = true;
282 frontendArgs.append( "-s" );
285 if ( strcasecmp(pc.parameterArg, "help") == 0 ) {
289 else if ( strcasecmp(pc.parameterArg, "version") == 0 ) {
294 error() << "--" << pc.parameterArg <<
295 " is an invalid argument" << endl;
298 /* Passthrough args. */
300 backendArgs.append( "-T" );
301 backendArgs.append( pc.parameterArg );
304 backendArgs.append( "-F" );
305 backendArgs.append( pc.parameterArg );
308 backendArgs.append( "-G" );
309 backendArgs.append( pc.parameterArg );
312 backendArgs.append( "-P" );
313 backendArgs.append( pc.parameterArg );
316 backendArgs.append( "-p" );
319 backendArgs.append( "-L" );
324 case ParamCheck::invalid:
325 error() << "-" << pc.parameter << " is an invalid argument" << endl;
328 case ParamCheck::noparam:
329 /* It is interpreted as an input file. */
330 if ( *pc.curArg == 0 )
331 error() << "a zero length input file name was given" << endl;
332 else if ( inputFileName != 0 )
333 error() << "more than one input file name was given" << endl;
335 /* OK, Remember the filename. */
336 inputFileName = pc.curArg;
343 int frontend( char *inputFileName, char *outputFileName )
345 /* Open the input file for reading. */
346 assert( inputFileName != 0 );
347 ifstream *inFile = new ifstream( inputFileName );
348 istream *inStream = inFile;
349 if ( ! inFile->is_open() )
350 error() << "could not open " << inputFileName << " for reading" << endp;
352 /* Used for just a few things. */
353 std::ostringstream hostData;
355 if ( machineSpec == 0 && machineName == 0 )
356 hostData << "<host line=\"1\" col=\"1\">";
358 Scanner scanner( inputFileName, *inStream, hostData, 0, 0, 0, false );
361 /* Finished, final check for errors.. */
362 if ( gblErrorCount > 0 )
365 /* Now send EOF to all parsers. */
366 terminateAllParsers();
368 /* Finished, final check for errors.. */
369 if ( gblErrorCount > 0 )
372 if ( machineSpec == 0 && machineName == 0 )
373 hostData << "</host>\n";
375 if ( gblErrorCount > 0 )
378 ostream *outputFile = 0;
379 if ( outputFileName != 0 )
380 outputFile = new ofstream( outputFileName );
384 /* Write the machines, then the surrounding code. */
385 writeMachines( *outputFile, hostData.str(), inputFileName );
387 /* Close the intermediate file. */
388 if ( outputFileName != 0 )
391 return gblErrorCount > 0;
394 char *makeIntermedTemplate( char *baseFileName )
397 const char *templ = "ragel-XXXXXX.xml";
398 char *lastSlash = strrchr( baseFileName, '/' );
399 if ( lastSlash == 0 ) {
400 result = new char[strlen(templ)+1];
401 strcpy( result, templ );
404 int baseLen = lastSlash - baseFileName + 1;
405 result = new char[baseLen + strlen(templ) + 1];
406 memcpy( result, baseFileName, baseLen );
407 strcpy( result+baseLen, templ );
412 char *openIntermed( char *inputFileName, char *outputFileName )
417 /* Which filename do we use as the base? */
418 char *baseFileName = outputFileName != 0 ? outputFileName : inputFileName;
420 /* The template for the intermediate file name. */
421 char *intermedFileName = makeIntermedTemplate( baseFileName );
423 /* Randomize the name and try to open. */
424 char fnChars[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
425 char *firstX = strrchr( intermedFileName, 'X' ) - 5;
426 for ( int tries = 0; tries < 20; tries++ ) {
427 /* Choose a random name. */
428 for ( int x = 0; x < 6; x++ )
429 firstX[x] = fnChars[rand() % 52];
431 /* Try to open the file. */
432 int fd = ::open( intermedFileName, O_WRONLY|O_EXCL|O_CREAT, S_IRUSR|S_IWUSR );
435 /* Success. Close the file immediately and return the name for use
436 * by the child processes. */
438 result = intermedFileName;
442 if ( errno == EACCES ) {
443 error() << "failed to open temp file " << intermedFileName <<
444 ", access denied" << endp;
449 error() << "abnormal error: cannot find unique name for temp file" << endp;
455 void cleanExit( char *intermed, int status )
463 /* If any forward slash is found in argv0 then it is assumed that the path is
464 * explicit and the path to the backend executable should be derived from
465 * that. Whe check that location and also go up one then inside a directory of
466 * the same name in case we are executing from the source tree. If no forward
467 * slash is found it is assumed the file is being run from the installed
468 * location. The PREFIX supplied during configuration is used. */
469 char **makePathChecksUnix( const char *argv0, const char *progName )
471 char **result = new char*[3];
472 const char *lastSlash = strrchr( argv0, '/' );
475 if ( lastSlash != 0 ) {
476 char *path = strdup( argv0 );
477 int givenPathLen = (lastSlash - argv0) + 1;
478 path[givenPathLen] = 0;
480 int progNameLen = strlen(progName);
481 int length = givenPathLen + progNameLen + 1;
482 char *check = new char[length];
483 sprintf( check, "%s%s", path, progName );
484 result[numChecks++] = check;
486 length = givenPathLen + 3 + progNameLen + 1 + progNameLen + 1;
487 check = new char[length];
488 sprintf( check, "%s../%s/%s", path, progName, progName );
489 result[numChecks++] = check;
492 int prefixLen = strlen(PREFIX);
493 int progNameLen = strlen(progName);
494 int length = prefixLen + 5 + progNameLen + 1;
495 char *check = new char[length];
497 sprintf( check, PREFIX "/bin/%s", progName );
498 result[numChecks++] = check;
501 result[numChecks] = 0;
506 void forkAndExec( const char *progName, char **pathChecks,
507 ArgsVector &args, char *intermed )
511 /* Error, no child created. */
512 error() << "failed to fork for " << progName << endl;
513 cleanExit( intermed, 1 );
515 else if ( pid == 0 ) {
517 while ( *pathChecks != 0 ) {
518 /* Execv does not modify argv, it just uses the const form that is
519 * compatible with the most code. Ours not included. */
520 execv( *pathChecks, (char *const*) args.data );
523 error() << "failed to exec " << progName << endl;
524 cleanExit( intermed, 1 );
527 /* Parent process, wait for the child. */
531 /* What happened with the child. */
532 if ( ! WIFEXITED( status ) ) {
533 error() << progName << " did not exit normally" << endl;
534 cleanExit( intermed, 1 );
537 if ( WEXITSTATUS(status) != 0 )
538 cleanExit( intermed, WEXITSTATUS(status) );
543 /* GetModuleFileNameEx is used to find out where the the current process's
544 * binary is. That location is searched first. If that fails then we go up one
545 * directory and look for the executable inside a directory of the same name
546 * in case we are executing from the source tree.
548 char **makePathChecksWin( const char *progName )
551 char *imageFileName = new char[len];
552 HANDLE h = GetCurrentProcess();
553 len = GetModuleFileNameEx( h, NULL, imageFileName, len );
554 imageFileName[len] = 0;
556 char **result = new char*[3];
557 const char *lastSlash = strrchr( imageFileName, '\\' );
560 assert( lastSlash != 0 );
561 char *path = strdup( imageFileName );
562 int givenPathLen = (lastSlash - imageFileName) + 1;
563 path[givenPathLen] = 0;
565 int progNameLen = strlen(progName);
566 int length = givenPathLen + progNameLen + 1;
567 char *check = new char[length];
568 sprintf( check, "%s%s", path, progName );
569 result[numChecks++] = check;
571 length = givenPathLen + 3 + progNameLen + 1 + progNameLen + 1;
572 check = new char[length];
573 sprintf( check, "%s..\\%s\\%s", path, progName, progName );
574 result[numChecks++] = check;
576 result[numChecks] = 0;
580 void spawn( const char *progName, char **pathChecks,
581 ArgsVector &args, char *intermed )
584 while ( *pathChecks != 0 ) {
585 //cerr << "trying to execute " << *pathChecks << endl;
586 result = _spawnv( _P_WAIT, *pathChecks, args.data );
587 if ( result >= 0 || errno != ENOENT )
593 error() << "failed to spawn " << progName << endl;
594 cleanExit( intermed, 1 );
598 cleanExit( intermed, 1 );
603 void execFrontend( const char *argv0, char *inputFileName, char *intermed )
605 /* The frontend program name. */
606 const char *progName = "ragel";
608 frontendArgs.insert( 0, progName );
609 frontendArgs.insert( 1, "-x" );
610 frontendArgs.append( "-o" );
611 frontendArgs.append( intermed );
612 frontendArgs.append( inputFileName );
613 frontendArgs.append( 0 );
616 char **pathChecks = makePathChecksUnix( argv0, progName );
617 forkAndExec( progName, pathChecks, frontendArgs, intermed );
619 char **pathChecks = makePathChecksWin( progName );
620 spawn( progName, pathChecks, frontendArgs, intermed );
624 void execBackend( const char *argv0, char *intermed, char *outputFileName )
626 /* Locate the backend program */
627 const char *progName = 0;
629 progName = "rlgen-dot";
631 switch ( hostLang->lang ) {
634 progName = "rlgen-cd";
637 progName = "rlgen-java";
640 progName = "rlgen-ruby";
645 backendArgs.insert( 0, progName );
646 if ( outputFileName != 0 ) {
647 backendArgs.append( "-o" );
648 backendArgs.append( outputFileName );
650 backendArgs.append( intermed );
651 backendArgs.append( 0 );
654 char **pathChecks = makePathChecksUnix( argv0, progName );
655 forkAndExec( progName, pathChecks, backendArgs, intermed );
657 char **pathChecks = makePathChecksWin( progName );
658 spawn( progName, pathChecks, backendArgs, intermed );
662 /* Main, process args and call yyparse to start scanning input. */
663 int main(int argc, char **argv)
665 char *inputFileName = 0;
666 char *outputFileName = 0;
668 processArgs( argc, argv, inputFileName, outputFileName );
670 /* If -M or -S are given and we're not generating a dot file then invoke
671 * the frontend. These options are not useful with code generators. */
672 if ( machineName != 0 || machineSpec != 0 ) {
677 /* Require an input file. If we use standard in then we won't have a file
678 * name on which to base the output. */
679 if ( inputFileName == 0 )
680 error() << "no input file given" << endl;
682 /* Bail on argument processing errors. */
683 if ( gblErrorCount > 0 )
686 /* Make sure we are not writing to the same file as the input file. */
687 if ( inputFileName != 0 && outputFileName != 0 &&
688 strcmp( inputFileName, outputFileName ) == 0 )
690 error() << "output file \"" << outputFileName <<
691 "\" is the same as the input file" << endp;
695 return frontend( inputFileName, outputFileName );
697 char *intermed = openIntermed( inputFileName, outputFileName );
699 /* From here on in the cleanExit function should be used to exit. */
701 /* Run the frontend, then the backend processes. */
702 execFrontend( argv[0], inputFileName, intermed );
703 execBackend( argv[0], intermed, outputFileName );
705 /* Clean up the intermediate. */
706 cleanExit( intermed, 0 );